System.Collections.Generic.HashSet.UnionWith(System.Collections.Generic.IEnumerable)

Here are the examples of the csharp api System.Collections.Generic.HashSet.UnionWith(System.Collections.Generic.IEnumerable) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

668 Examples 7

19 View Source File : SolutionPort.cs
License : Apache License 2.0
Project Creator : aws

private void InitRules(List<PortCoreConfiguration> solutionConfiguration, List<replacedyzerResult> replacedyzerResults)
        {
            using var projectTypeFeatureDetector = new FeatureDetector();

            // sync up preplaceded in configuration with replacedyze results
            solutionConfiguration = solutionConfiguration.Where(s => replacedyzerResults.Select(a => a.ProjectResult?.ProjectFilePath).Contains(s.ProjectPath)).ToList();
            replacedyzerResults = replacedyzerResults.Where(a => solutionConfiguration.Select(s => s.ProjectPath).Contains(a.ProjectResult?.ProjectFilePath)).ToList();
            _projectTypeFeatureResults = projectTypeFeatureDetector.DetectFeaturesInProjects(replacedyzerResults);

            var allReferences = new HashSet<string>();
            foreach (var projectConfiguration in solutionConfiguration)
            {
                var projectTypeFeatureResult = _projectTypeFeatureResults[projectConfiguration.ProjectPath];
                projectConfiguration.ProjectType = GetProjectType(projectTypeFeatureResult);
                if (projectConfiguration.UseDefaultRules)
                {
                    //If a rules dir was provided, copy files from that dir into the rules folder
                    if (!string.IsNullOrEmpty(projectConfiguration.RulesDir))
                    {
                        CopyOverrideRules(projectConfiguration.RulesDir);
                    }
                    projectConfiguration.RulesDir = Constants.RulesDefaultPath;
                    var projectResult = replacedyzerResults
                        .FirstOrDefault(a => a.ProjectResult?.ProjectFilePath == projectConfiguration.ProjectPath)
                        .ProjectResult;

                    projectResult?.SourceFileResults?.SelectMany(s => s.References)?.Select(r => r.Namespace).Distinct().ToList().ForEach(currentReference=> { 
                        if (currentReference != null && !allReferences.Contains(currentReference))
                        {
                            allReferences.Add(currentReference);
                        }
                    });

                    projectResult?.SourceFileResults?.SelectMany(s => s.Children.OfType<UsingDirective>())?.Select(u=>u.Identifier).Distinct().ToList().ForEach(currentReference => {
                        if (currentReference != null && !allReferences.Contains(currentReference))
                        {
                            allReferences.Add(currentReference);
                        }
                    });
                }
                AddWCFReferences(projectConfiguration);
                
                projectConfiguration.AdditionalReferences.Add(Constants.ProjectRecommendationFile);

                allReferences.UnionWith(projectConfiguration.AdditionalReferences);
            }

            _portSolutionResult.References = allReferences.ToHashSet<string>();

            DownloadRecommendationFiles(allReferences);

        }

19 View Source File : QueryPartitionRangePageEnumeratorTests.cs
License : MIT License
Project Creator : Azure

[TestMethod]
            public async Task TestSplitAsync()
            {
                int numItems = 100;
                IDoreplacedentContainer doreplacedentContainer = await this.CreateDoreplacedentContainerAsync(numItems);
                IAsyncEnumerator<TryCatch<QueryPage>> enumerator = this.CreateEnumerator(doreplacedentContainer);

                (HashSet<string> parentIdentifiers, QueryState state) = await this.PartialDrainAsync(enumerator, numIterations: 3);

                // Split the parreplacedion
                await doreplacedentContainer.SplitAsync(new FeedRangeParreplacedionKeyRange("0"), cancellationToken: default);

                // Try To read from the parreplacedion that is gone.
                await enumerator.MoveNextAsync();
                replacedert.IsTrue(enumerator.Current.Failed);

                // Resume on the children using the parent continuaiton token
                HashSet<string> childIdentifiers = new HashSet<string>();

                await doreplacedentContainer.RefreshProviderAsync(NoOpTrace.Singleton, cancellationToken: default);
                List<FeedRangeEpk> ranges = await doreplacedentContainer.GetFeedRangesAsync(
                    trace: NoOpTrace.Singleton, 
                    cancellationToken: default);
                foreach (FeedRangeEpk range in ranges)
                {
                    IAsyncEnumerable<TryCatch<QueryPage>> enumerable = new ParreplacedionRangePageAsyncEnumerable<QueryPage, QueryState>(
                        feedRangeState: new FeedRangeState<QueryState>(range, state),
                        (feedRangeState) => new QueryParreplacedionRangePageAsyncEnumerator(
                            queryDataSource: doreplacedentContainer,
                            sqlQuerySpec: new Cosmos.Query.Core.SqlQuerySpec("SELECT * FROM c"),
                            feedRangeState: feedRangeState,
                            parreplacedionKey: null,
                            queryPaginationOptions: new QueryPaginationOptions(pageSizeHint: 10),
                            cancellationToken: default),
                        trace: NoOpTrace.Singleton);
                    HashSet<string> resourceIdentifiers = await this.DrainFullyAsync(enumerable);

                    childIdentifiers.UnionWith(resourceIdentifiers);
                }

                replacedert.AreEqual(numItems, parentIdentifiers.Count + childIdentifiers.Count);
            }

19 View Source File : MethodTable.cs
License : GNU General Public License v3.0
Project Creator : anydream

private void MergeInterfaces(string metNameKey, HashSet<TableMethodPair> entrySet)
		{
			if (!SlotMap.TryGetValue(metNameKey, out var vslot))
			{
				vslot = new VirtualSlot(null);
				SlotMap.Add(metNameKey, vslot);
			}
			vslot.Entries.UnionWith(entrySet);
		}

19 View Source File : HexGridTilesProvider.cs
License : MIT License
Project Creator : AurelWu

public static List<Vector3Int> Cone(Vector3Int origin, Vector3Int targetDirection, float coneWidthHalfAngle, int coneLength)
            {
                Vector3 originCartesian = HexConverter.TileCoordToCartesianCoord(origin);
                IEnumerable<Vector3Int> ring = GetTiles.Ring(origin, coneLength, 1);
                HashSet<Vector3Int> cone = new HashSet<Vector3Int>();
                foreach (Vector3Int target in ring)
                {
                    Vector3 targetWorldPos = HexConverter.TileCoordToCartesianCoord(target);
                    Vector3 lookWorldPos = HexConverter.TileCoordToCartesianCoord((origin + targetDirection));
                    float angle = Vector3.Angle(targetWorldPos - originCartesian, lookWorldPos - originCartesian);
                    if (Mathf.Abs(angle) > coneWidthHalfAngle + 0.001) continue;

                    List<Vector3Int> linePointsL = GetTiles.Line(origin, target, false, -0.00001f); //for more consistent results we use 2 lines, one slightly left of center
                    List<Vector3Int> linePointsR = GetTiles.Line(origin, target, false, +0.00001f); //and this her slightly right of center
                    cone.UnionWith(linePointsL);
                    cone.UnionWith(linePointsR);
                }
                return cone.ToList();

            }

19 View Source File : IPDMeshCreator.cs
License : GNU General Public License v3.0
Project Creator : artembakhanov

private int? FindActivePoint(Edge e_ij, Dictionary<Edge, Edge> edges, List<Triangle> triangles, HashSet<Edge> fixedEdges, HashSet<int> fixedVertices)
    {
        findAPCounter++;
        int ap1, ap2;

        List<int> innerPoints;
        ConvexPolyhedron p = BuildPolyhedron(e_ij, edges, out ap1, out ap2, out innerPoints);
        List<Vector3> allowedPoints = new List<Vector3>
        {
            PointCloud[e_ij.vertex1].Position,
            PointCloud[e_ij.vertex2].Position
        };
        if (ap1 != -1 && !fixedVertices.Contains(ap1)) allowedPoints.Add(PointCloud[ap1].Position);
        if (ap2 != -1 && !fixedVertices.Contains(ap2)) allowedPoints.Add(PointCloud[ap2].Position);

        //var points = VoxelSet.GetInnerPoints(p, (PointCloud[e_ij.vertex1].Position + PointCloud[e_ij.vertex2].Position) / 2);
        var points = GetInnerPoints(p, innerPoints);
        float sum = float.PositiveInfinity;
        int? activePoint = null;
        HashSet<Triangle> tr = new HashSet<Triangle>();
        foreach (var m in points)
        {
            tr.UnionWith(PointCloud[m].triangles);
        }
        foreach (var m in points)
        {
            float currentSum = CalculateEnergy(e_ij.vertex1, e_ij.vertex2, e_ij.vertex3, m);
            if (PointCloud[m].status == PointStatus.ACTIVE 
                && currentSum < sum 
                && (!checkLengths || Distance(m, e_ij.vertex1) <= maxEdgeLength && Distance(m, e_ij.vertex2) <= maxEdgeLength)
                && GeomIntegrity(e_ij, m, tr, allowedPoints.ToArray(), fixedEdges, fixedVertices)) // if do not intersect other triangles
            {
                activePoint = m;
                sum = currentSum;
            }
        }

        return activePoint;
    }

19 View Source File : TypeGenerator.cs
License : GNU General Public License v3.0
Project Creator : anydream

private void ProcessType(TypeX currType)
		{
			// 生成类型结构体代码
			TypeCppCode cppCode = GenDeclCode(currType);

			// 生成方法代码
			foreach (var metX in currType.Methods)
			{
				MethodGen.Process(metX);

				cppCode.DeclCode.Append(MethodGen.DeclCode);
				cppCode.ImplCode.Append(MethodGen.ImplCode);

				cppCode.DeclDependNames.UnionWith(MethodGen.DeclDependNames);
				cppCode.ImplDependNames.UnionWith(MethodGen.ImplDependNames);

				cppCode.DependStrings.UnionWith(MethodGen.DependStrings);
			}

			GenIsinstCode(currType, out var declCode, out var implCode);
			cppCode.DeclCode.Append(declCode);
			cppCode.ImplCode.Append(implCode);
		}

19 View Source File : LASets.cs
License : MIT License
Project Creator : Azure

private HashSet<ATNState> closure(ATNState start)
        {
            if (start == null)
            {
                throw new Exception();
            }

            HashSet<ATNState> visited = new HashSet<ATNState>();
            Stack<ATNState> stack = new Stack<ATNState>();
            stack.Push(start);
            while (stack.Any())
            {
                ATNState state = stack.Pop();
                if (visited.Contains(state))
                {
                    continue;
                }

                visited.Add(state);
                foreach (Transition transition in state.TransitionsArray)
                {
                    switch (transition.TransitionType)
                    {
                        case TransitionType.RULE:
                            {
                                RuleTransition rule = (RuleTransition)transition;
                                ATNState sub_state = rule.target;
                                HashSet<ATNState> cl = this.closure(sub_state);
                                if (cl.Where(s => this.stopStates.Contains(s) && s.atn == sub_state.atn).Any())
                                {
                                    HashSet<ATNState> cl2 = this.closure(rule.followState);
                                    cl.UnionWith(cl2);
                                }
                                foreach (ATNState c in cl)
                                {
                                    visited.Add(c);
                                }
                            }
                            break;

                        case TransitionType.PREDICATE:
                            if (this.CheckPredicate((PredicateTransition)transition))
                            {
                                if (transition.target == null)
                                {
                                    throw new Exception();
                                }

                                stack.Push(transition.target);
                            }
                            break;

                        case TransitionType.WILDCARD:
                            break;

                        default:
                            if (transition.IsEpsilon)
                            {
                                if (transition.target == null)
                                {
                                    throw new Exception();
                                }

                                stack.Push(transition.target);
                            }
                            break;
                    }
                }
            }
            return visited;
        }

19 View Source File : UpdateSubscriptionsUseCase.cs
License : Apache License 2.0
Project Creator : Anapher

public async Task<Unit> Handle(UpdateSubscriptionsRequest request, CancellationToken cancellationToken)
        {
            var participant = request.Participant;

            _logger.LogDebug("Update subscriptions for {participant}", participant);

            var subscriptions = new HashSet<SynchronizedObjectId>();
            foreach (var provider in _providers)
            {
                var availableSubscriptions = await provider.GetAvailableObjects(participant);
                subscriptions.UnionWith(availableSubscriptions);
            }

            _logger.LogDebug("Add {count} subscriptions", subscriptions.Count);

            var oldSubscriptions =
                await _subscriptionsRepository.GetSet(participant, subscriptions.Select(x => x.ToString()).ToList()) ??
                ImmutableList<string>.Empty;

            if (!await _joinedParticipantsRepository.IsParticipantJoined(participant))
            {
                _logger.LogWarning("The participant does not seem to be joined, remove all subscriptions");
                await _subscriptionsRepository.Remove(participant);
                return Unit.Value;
            }

            var added = subscriptions.Where(x => !oldSubscriptions.Contains(x.ToString())).ToList();
            await SendCurrentSynchronizedObjectValues(participant, added);

            var removed = oldSubscriptions.Except(subscriptions.Select(x => x.ToString()))
                .Select(SynchronizedObjectId.Parse).ToList();

            if (removed.Any() || added.Any())
                await _mediator.Publish(new ParticipantSubscriptionsUpdatedNotification(participant, removed, added));

            return Unit.Value;
        }

19 View Source File : ITypedDurableOrchestrationStarterGenerator.cs
License : MIT License
Project Creator : Azure

private CompilationUnitSyntax Generate()
        {
            var modifiers = AsModifierList(SyntaxKind.PublicKeyword, SyntaxKind.PartialKeyword);

            var requiredNamespaces = new HashSet<string>(requiredUsings);
            var memberList = new List<MemberDeclarationSyntax>();

            foreach (var function in functions)
            {
                if (function.Kind != DurableFunctionKind.Orchestration)
                    continue;

                memberList.Add(GenerateStartMethod(function));

                requiredNamespaces.UnionWith(function.RequiredNamespaces);
            }

            var members = SyntaxFactory.List(memberList);

            var @interface = SyntaxFactory.InterfaceDeclaration(Names.ITypedDurableOrchestrationStarter)
                .WithModifiers(modifiers)
                .WithMembers(members);

            var @namespace = GenerateNamespace().AddMembers(@interface);

            var usings = AsUsings(requiredNamespaces);

            return SyntaxFactory.CompilationUnit().AddUsings(usings).AddMembers(@namespace).NormalizeWhitespace();
        }

19 View Source File : ConsulDependencies.cs
License : MIT License
Project Creator : andyalm

public void CopyTo(ConsulDependencies other)
        {
            other.Keys.UnionWith(Keys);
            other.KeyPrefixes.UnionWith(KeyPrefixes);
            other.Services.UnionWith(Services);
        }

19 View Source File : StarboardModule.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

private async Task ProcessRemovedStar(Starboard board, ITextChannel channel, Cacheable<IUserMessage, ulong> cachedMessage, SocketReaction reaction)
        {
            if (!board.Emojis.Contains(reaction.Emote.GetFullName()))
                return;

            var message = await cachedMessage.GetOrDownloadAsync();
            if (message == null)
                return;

            var logger = _logger.WithScope(message);

            if ((!board.AllowSelfStars && message.Author.Id == reaction.UserId) || message.Author.IsBot)
                return;

            if (string.IsNullOrEmpty(message.Content) && message.Attachments.Count <= 0)
                return;

            var starrers = new HashSet<ulong>();
            foreach (var emoji in message.Reactions.Where(x => board.Emojis.Contains(x.Key.GetFullName())).Select(x => x.Key))
                starrers.UnionWith((await message.GetReactionUsersAsync(emoji, int.MaxValue).FlattenAsync()).Select(x => x.Id));

            if (!board.AllowSelfStars)
                starrers.Remove(message.Author.Id);

            var entry = await _settings.Modify(channel.GuildId, (StarboardSettings s) =>
            {
                var b = s.Starboards.FirstOrDefault(x => x.Id == board.Id);
                if (b == null)
                    return null;

                b.StarredMessages.TryGetValue(message.Id, out var e);

                if (starrers.Count <= 0 && !board.KeepUnstarred)
                    b.StarredMessages.Remove(message.Id);

                return e;
            });

            if (entry == null)
                return;

            if (entry.StarboardMessage == default)
                return;

            var starChannel = await channel.Guild.GetTextChannelAsync(board.Channel);
            if (starChannel == null)
                return;

            var starMessage = await starChannel.GetMessageAsync(entry.StarboardMessage) as IUserMessage;
            if (starMessage == null)
                return; // Probably got deleted from starboard

            if (starrers.Count <= 0 && !board.KeepUnstarred)
            {
                try
                {
                    await starMessage.DeleteAsync();
                    logger.LogInformation("Removed unstarred message in board {StarboardId}", board.Id);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Failed to delete unstarred message in board {StarboardId}", board.Id);
                }
            }
            else
            {
                var built = await BuildStarMessage(message, channel, starrers.Count, board.Emojis.First(), entry.Attachments, board.Style);
                await starMessage.ModifyAsync(x =>
                {
                    x.Content = built.Text;
                    x.Embed = built.Embed;
                });
            }
        }

19 View Source File : FrameworkConfigurationBuilder.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public FrameworkConfigurationBuilder AddModulesFromreplacedembly(replacedembly replacedembly)
        {
            _modules.UnionWith(replacedembly.GetTypes().Where(x => x.GetCustomAttribute<ModuleAttribute>() != null));
            return this;
        }

19 View Source File : tileMapScript.cs
License : MIT License
Project Creator : Angus-Fan

public HashSet<Node> getUnitAttackOptionsFromPosition()
    {
        HashSet<Node> tempNeighbourHash = new HashSet<Node>();
        HashSet<Node> neighbourHash = new HashSet<Node>();
        HashSet<Node> seenNodes = new HashSet<Node>();
        Node initialNode = graph[selectedUnit.GetComponent<UnitScript>().x, selectedUnit.GetComponent<UnitScript>().y];
        int attRange = selectedUnit.GetComponent<UnitScript>().attackRange;


        neighbourHash = new HashSet<Node>();
        neighbourHash.Add(initialNode);
        for (int i = 0; i < attRange; i++)
        {
            foreach (Node t in neighbourHash)
            {
                foreach (Node tn in t.neighbours)
                {
                    tempNeighbourHash.Add(tn);
                }
            }
            neighbourHash = tempNeighbourHash;
            tempNeighbourHash = new HashSet<Node>();
            if (i < attRange - 1)
            {
                seenNodes.UnionWith(neighbourHash);
            }
        }
        neighbourHash.ExceptWith(seenNodes);
        neighbourHash.Remove(initialNode);
        return neighbourHash;
    }

19 View Source File : FeatureLoader.cs
License : Apache License 2.0
Project Creator : aws

private static HashSet<CompiledFeature> LoadCompiledFeaturesFromreplacedembly(FeatureScope featureScope, CompiledFeaturereplacedembly compiledFeaturereplacedembly)
        {
            var loadedFeatures = new HashSet<CompiledFeature>();

            var loadedreplacedembly = replacedembly.LoadFile(Path.Combine(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location), compiledFeaturereplacedembly.replacedemblyPath));
            foreach (var featureNamespace in compiledFeaturereplacedembly.CompiledFeatureNamespaces)
            {
                var compiledFeatures = LoadCompiledFeaturesByNamespace(featureScope, loadedreplacedembly, featureNamespace);
                loadedFeatures.UnionWith(compiledFeatures);
            }

            return loadedFeatures;
        }

19 View Source File : Selector.cs
License : MIT License
Project Creator : AmigoCap

public void Select(bool erase = false) {
            if (!isActiveAndEnabled)
                return;

            Tools.StartClock();

            List<SelectorPart> parts = new List<SelectorPart>(GetComponents<SelectorPart>());
            parts.RemoveAll(p => !p.enabled);

            if (parts.Count == 0)
                return;

            Visualization viz = Visualization.Instance;
            HashSet<Atom> selectedRibbons = SelectorManager.Instance.selectedRibbons[(int)Color];

            foreach (SelectorPart p in parts) {
                if (needsCheckedHighlightCleanup) {
                    needsCheckedHighlightCleanup = false;
                    foreach (Atom a in p.RibbonsToCheck)
                        a.ShouldHighlightBecauseChecked((int)Color, false);
                }

                Tools.AddClockStop("Removed old c_highlights");

                p.FindTouchedRibbons();

                Tools.AddClockStop("Found touched ribbons");

                if (SelectorManager.Instance.HighlightChecked && !Persistent) {
                    foreach (Atom a in p.RibbonsToCheck)
                        a.ShouldHighlightBecauseChecked((int)Color, true);
                }

                Tools.AddClockStop("Added new c_highlights");
                Tools.EndClock();
            }

            IEnumerable<Atom> handledRibbons;

            if (parts.Count > 1) {
                HashSet<Atom> handledRibbonsSet = new HashSet<Atom>();

                foreach (SelectorPart p in GetComponents<SelectorPart>()) {
                    if (!p.enabled)
                        continue;
                    if (p.Positive) {
                        handledRibbonsSet.UnionWith(p.TouchedRibbons);
                    }
                    else {
                        handledRibbonsSet.ExceptWith(p.TouchedRibbons);
                    }
                }

                handledRibbons = handledRibbonsSet;
            }
            else {
                handledRibbons = parts[0].TouchedRibbons;
            }

            if (erase) {
                selectedRibbons.ExceptWith(handledRibbons);

                foreach (Atom a in handledRibbons) {
                    a.ShouldHighlightBecauseSelected((int)Color, false);
                }
            }
            else {
                selectedRibbons.UnionWith(handledRibbons);

                if (SelectorManager.Instance.HighlightSelected) {
                    foreach (Atom a in handledRibbons) {
                        a.ShouldHighlightBecauseSelected((int)Color, true);
                    }
                }
            }

            Tools.AddClockStop("Added new s_highlights");

            if (SelectorManager.Instance.HighlightChecked && !Persistent)
                needsCheckedHighlightCleanup = true;
        }

19 View Source File : AnalysisHandler.cs
License : Apache License 2.0
Project Creator : aws

public async Task<List<SourceFilereplacedysisResult>> replacedyzeFileIncremental(string filePath, string fileContent, string projectFile, string solutionFilePath, List<string> preportReferences
            , List<string> currentReferences, RootNodes projectRules, ExternalReferences externalReferences, bool actionsOnly = false, bool compatibleOnly = false, string targetFramework = DEFAULT_TARGET)
        {
            try
            {
                List<SourceFilereplacedysisResult> sourceFilereplacedysisResults = new List<SourceFilereplacedysisResult>();

                var filereplacedysis = await replacedyzeProjectFiles(projectFile, fileContent, filePath, preportReferences, currentReferences);
                var fileActions = replacedyzeFileActionsIncremental(projectFile, projectRules, targetFramework, solutionFilePath, filePath, filereplacedysis);

                var sourceFileResult = filereplacedysis.RootNodes.FirstOrDefault();

                Dictionary<string, List<CodeEnreplacedyDetails>> sourceFileToCodeEnreplacedyDetails = new Dictionary<string, List<CodeEnreplacedyDetails>>();
                Dictionary<string, Task<RecommendationDetails>> recommendationResults = new Dictionary<string, Task<RecommendationDetails>>();
                Dictionary<PackageVersionPair, Task<PackageDetails>> packageResults = new Dictionary<PackageVersionPair, Task<PackageDetails>>();

                if (!actionsOnly)
                {
                    var sourceFileToInvocations = new[] { SourceFileToCodeTokens(sourceFileResult) }.ToDictionary(result => result.Key, result => result.Value);

                    sourceFileToCodeEnreplacedyDetails = CodeEnreplacedyModelToCodeEnreplacedies.Convert(sourceFileToInvocations, externalReferences);

                    var namespaces = sourceFileToCodeEnreplacedyDetails.Aggregate(new HashSet<string>(), (agg, cur) =>
                    {
                        agg.UnionWith(cur.Value.Select(i => i.Namespace).Where(i => i != null));
                        return agg;
                    });

                    var nugetPackages = externalReferences?.NugetReferences?
                            .Select(r => CodeEnreplacedyModelToCodeEnreplacedies.ReferenceToPackageVersionPair(r))?
                            .ToHashSet();

                    var subDependencies = externalReferences?.NugetDependencies?
                        .Select(r => CodeEnreplacedyModelToCodeEnreplacedies.ReferenceToPackageVersionPair(r))
                        .ToHashSet();

                    var sdkPackages = namespaces.Select(n => new PackageVersionPair { PackageId = n, Version = "0.0.0", PackageSourceType = PackageSourceType.SDK });

                    var allPackages = nugetPackages
                        .Union(subDependencies)
                        .Union(sdkPackages)
                        .ToList();

                    packageResults = _handler.GetNugetPackages(allPackages, solutionFilePath, isIncremental: true, incrementalRefresh: false);

                    recommendationResults = _recommendationHandler.GetApiRecommendation(namespaces.ToList());
                }

                var portingActionResults = new Dictionary<string, List<RecommendedAction>>();

                var recommendedActions = fileActions.Select(f => new RecommendedAction()
                {
                    Description = f.Description,
                    RecommendedActionType = RecommendedActionType.ReplaceApi,
                    TextSpan = new Model.TextSpan()
                    {
                        StartCharPosition = f.TextSpan.StartCharPosition,
                        EndCharPosition = f.TextSpan.EndCharPosition,
                        StartLinePosition = f.TextSpan.StartLinePosition,
                        EndLinePosition = f.TextSpan.EndLinePosition
                    },
                    TextChanges = f.TextChanges
                }).ToHashSet().ToList();

                portingActionResults.Add(filePath, recommendedActions);

                var sourceFilereplacedysisResult = CodeEnreplacedyModelToCodeEnreplacedies.replacedyzeResults(
                    sourceFileToCodeEnreplacedyDetails, packageResults, recommendationResults, portingActionResults, targetFramework, compatibleOnly);

                //In case actions only, result will be empty, so we populate with actions
                if (actionsOnly)
                {
                    sourceFilereplacedysisResult.Add(new SourceFilereplacedysisResult()
                    {
                        SourceFileName = Path.GetFileName(filePath),
                        SourceFilePath = filePath,
                        RecommendedActions = recommendedActions,
                        ApireplacedysisResults = new List<ApireplacedysisResult>()
                    });
                }

                sourceFilereplacedysisResults.AddRange(sourceFilereplacedysisResult);


                return sourceFilereplacedysisResults;
            }
            finally
            {
                CommonUtils.RunGarbageCollection(_logger, "PortingreplacedistantreplacedysisHandler.replacedyzeFileIncremental");
            }
        }

19 View Source File : GeneratorContext.cs
License : GNU General Public License v3.0
Project Creator : anydream

public Dictionary<string, string> Merge()
		{
			// 排序编译单元
			var sortedUnits = UnitMap.Values.ToList();
			sortedUnits.Sort((lhs, rhs) => GetDependOrder(lhs).CompareTo(GetDependOrder(rhs)));

			// 合并编译单元
			UnitMap.Clear();
			var transMap = new Dictionary<string, string>();

			// 收集桥接代码的所有依赖项
			var bridgeUnitNames = new HashSet<string>();
			var bridgeUnits = new List<CompileUnit>();
			var remainUnits = new List<CompileUnit>();
			for (; ; )
			{
				bool changed = false;
				foreach (var unit in sortedUnits)
				{
					string unitName = unit.Name;
					if (BridgeTypes.Contains(unitName) ||
						bridgeUnitNames.Contains(unitName))
					{
						bridgeUnits.Add(unit);
						bridgeUnitNames.Add(unitName);
						bridgeUnitNames.UnionWith(unit.DeclDepends);
						changed = true;
					}
					else
						remainUnits.Add(unit);
				}

				if (changed)
				{
					sortedUnits = remainUnits;
					remainUnits = new List<CompileUnit>();
				}
				else
					break;
			}
			bridgeUnits.Sort((lhs, rhs) => GetDependOrder(lhs).CompareTo(GetDependOrder(rhs)));

			// 生成桥接单元
			CompileUnit bridgeUnit = new CompileUnit();
			bridgeUnit.Name = "il2cppBridge";
			UnitMap.Add(bridgeUnit.Name, bridgeUnit);

			foreach (var unit in bridgeUnits)
			{
				bridgeUnit.DeclCode += "#define IL2CPP_BRIDGE_HAS_" + unit.Name + '\n';
				bridgeUnit.Append(unit);
				transMap[unit.Name] = bridgeUnit.Name;
			}

			// 划分其他编译单元
			CompileUnit currUnit = NewUnit();
			foreach (var unit in sortedUnits)
			{
				Debug.replacedert(!bridgeUnit.DeclDepends.Contains(unit.Name));
				currUnit.Append(unit);
				transMap[unit.Name] = currUnit.Name;
				if (IsUnitFull(currUnit))
					currUnit = NewUnit();
			}

			if (currUnit.IsEmpty())
				UnitMap.Remove(currUnit.Name);

			foreach (var unit in UnitMap.Values)
			{
				var declDeps = new HashSet<string>();
				foreach (string dep in unit.DeclDepends)
					declDeps.Add(transMap[dep]);
				unit.DeclDepends = declDeps;

				var implDeps = new HashSet<string>();
				foreach (string dep in unit.ImplDepends)
					implDeps.Add(transMap[dep]);
				unit.ImplDepends = implDeps;

				unit.Optimize(UnitMap);
			}

			return transMap;
		}

19 View Source File : BufferedPartitionRangeEnumeratorTests.cs
License : MIT License
Project Creator : Azure

[TestMethod]
            public async Task TestSplitAsync()
            {
                int numItems = 100;
                IDoreplacedentContainer inMemoryCollection = await this.CreateDoreplacedentContainerAsync(numItems);
                IAsyncEnumerator<TryCatch<ReadFeedPage>> enumerator = this.CreateEnumerator(inMemoryCollection);

                (HashSet<string> parentIdentifiers, ReadFeedState state) = await this.PartialDrainAsync(enumerator, numIterations: 3);

                // Split the parreplacedion
                await inMemoryCollection.SplitAsync(new FeedRangeParreplacedionKeyRange(parreplacedionKeyRangeId: "0"), cancellationToken: default);

                // Try To read from the parreplacedion that is gone.
                await enumerator.MoveNextAsync();
                replacedert.IsTrue(enumerator.Current.Failed);

                // Resume on the children using the parent continuaiton token
                HashSet<string> childIdentifiers = new HashSet<string>();
                foreach (int parreplacedionKeyRangeId in new int[] { 1, 2 })
                {
                    ParreplacedionRangePageAsyncEnumerable<ReadFeedPage, ReadFeedState> enumerable = new ParreplacedionRangePageAsyncEnumerable<ReadFeedPage, ReadFeedState>(
                        feedRangeState: new FeedRangeState<ReadFeedState>(
                            new FeedRangeParreplacedionKeyRange(parreplacedionKeyRangeId: parreplacedionKeyRangeId.ToString()),
                            state),
                        (feedRangeState) => new ReadFeedParreplacedionRangeEnumerator(
                            inMemoryCollection,
                            feedRangeState: feedRangeState,
                            readFeedPaginationOptions: new ReadFeedPaginationOptions(pageSizeHint: 10),
                            cancellationToken: default),
                        trace: NoOpTrace.Singleton);
                    HashSet<string> resourceIdentifiers = await this.DrainFullyAsync(enumerable);

                    childIdentifiers.UnionWith(resourceIdentifiers);
                }

                replacedert.AreEqual(numItems, parentIdentifiers.Count + childIdentifiers.Count);
            }

19 View Source File : RegisterAllocator.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public void Initialize()
        {
            var blocks = transformer.RootScope.GetBasicBlocks().Cast<BasicBlock<IRInstrList>>().ToList();
            liveness = Livenessreplacedysis.ComputeLiveness(blocks);

            var stackVars = new HashSet<IRVariable>();
            foreach(var blockLiveness in liveness)
            {
                foreach(var instr in blockLiveness.Key.Content)
                {
                    if(instr.OpCode != IROpCode.__LEA)
                        continue;

                    var variable = (IRVariable) instr.Operand2;
                    if(variable.VariableType != IRVariableType.Argument)
                        stackVars.Add(variable);
                }
                stackVars.UnionWith(blockLiveness.Value.OutLive);
            }

            // [BP - 2] = last argument
            // [BP - 1] = return address
            // [BP    ] = old BP
            // [BP + 1] = first local

            var offset = 1;
            globalVars = stackVars.ToDictionary(var => var, var => new StackSlot(offset++, var));
            baseOffset = offset;
            LocalSize = baseOffset - 1;

            offset = -2;
            var parameters = transformer.Context.GetParameters();
            for(var i = parameters.Length - 1; i >= 0; i--)
            {
                var paramVar = parameters[i];
                globalVars[paramVar] = new StackSlot(offset--, paramVar);
            }

            allocation = globalVars.ToDictionary(pair => pair.Key, pair => (object) pair.Value);
        }

19 View Source File : ITypedDurableOrchestrationCallerGenerator.cs
License : MIT License
Project Creator : Azure

private CompilationUnitSyntax Generate()
        {
            var modifiers = AsModifierList(SyntaxKind.PublicKeyword, SyntaxKind.PartialKeyword);

            var requiredNamespaces = new HashSet<string>(requiredUsings);
            var memberList = new List<MemberDeclarationSyntax>();

            foreach (var function in functions)
            {
                if (function.Kind != DurableFunctionKind.Orchestration)
                    continue;

                memberList.Add(GenerateCallMethodWithRetry(function));
                memberList.Add(GenerateCallMethodWithoutRetry(function));
                memberList.Add(GenerateStartMethod(function));

                requiredNamespaces.UnionWith(function.RequiredNamespaces);
            }

            var members = SyntaxFactory.List(memberList);

            var @interface = SyntaxFactory.InterfaceDeclaration(Names.ITypedDurableOrchestrationCaller)
                .WithModifiers(modifiers)
                .WithMembers(members);

            var @namespace = GenerateNamespace().AddMembers(@interface);

            var usings = AsUsings(requiredNamespaces);

            return SyntaxFactory.CompilationUnit().AddUsings(usings).AddMembers(@namespace).NormalizeWhitespace();
        }

19 View Source File : AssDocument.cs
License : MIT License
Project Creator : arcusmaximus

private replacedStyle GetStyleMatchingStructure(replacedSection section)
        {
            HashSet<ShadowType> sectionShadowTypes = new HashSet<ShadowType>(section.ShadowColors.Keys);

            foreach (replacedStyle style in _styles.Values)
            {
                replacedStyleOptions options = GetStyleOptions(style);

                if (style.HasOutlineBox != (section.BackColor.A > 0))
                    continue;

                HashSet<ShadowType> styleShadowTypes = new HashSet<ShadowType>();
                if (style.HasOutline && !style.OutlineIsBox)
                    styleShadowTypes.Add(ShadowType.Glow);

                if (options != null)
                    styleShadowTypes.UnionWith(options.ShadowTypes);

                if (!styleShadowTypes.SetEquals(sectionShadowTypes))
                    continue;

                return style;
            }
            return null;
        }

19 View Source File : Auth0IdTokenJwtEvents.cs
License : MIT License
Project Creator : ARKlab

void _convertUserToClaims(ClaimsIdenreplacedy idenreplacedy, User profile)
        {
            var id = profile.Idenreplacedies.Single(i => i.Provider + "|" + i.UserId == profile.UserId);

            if (!string.IsNullOrWhiteSpace(profile.Email))
            {
                idenreplacedy.AddClaim(new Claim(ClaimTypes.Email, profile.Email, ClaimValueTypes.String, id.Connection));
                idenreplacedy.AddClaim(new Claim("email", profile.Email, ClaimValueTypes.String, id.Connection));
            }

            if (!string.IsNullOrWhiteSpace(profile.FullName))
            {
                idenreplacedy.AddClaim(new Claim(ClaimTypes.Name, profile.FullName, ClaimValueTypes.String, id.Connection));
                idenreplacedy.AddClaim(new Claim("name", profile.FullName, ClaimValueTypes.String, id.Connection));
            }

            if (!string.IsNullOrWhiteSpace(profile.NickName))
                idenreplacedy.AddClaim(new Claim("nickname", profile.NickName, ClaimValueTypes.String, id.Connection));
            if (!string.IsNullOrWhiteSpace(profile.FirstName))
                idenreplacedy.AddClaim(new Claim("given_name", profile.FirstName, ClaimValueTypes.String, id.Connection));
            if (!string.IsNullOrWhiteSpace(profile.LastName))
                idenreplacedy.AddClaim(new Claim("family_name", profile.LastName, ClaimValueTypes.String, id.Connection));
            if (!string.IsNullOrWhiteSpace(id.Connection))
                idenreplacedy.AddClaim(new Claim("connection", id.Connection, ClaimValueTypes.String, id.Connection));
            if (!string.IsNullOrWhiteSpace(profile.Picture))
                idenreplacedy.AddClaim(new Claim("picture", profile.Picture, ClaimValueTypes.String, id.Connection));
            if (!string.IsNullOrWhiteSpace(id.Provider))
                idenreplacedy.AddClaim(new Claim("provider", id.Provider, ClaimValueTypes.String, id.Connection));

            var roles = new HashSet<string>();
            if (profile.AppMetadata?.authorization?.roles != null)
                roles.UnionWith((profile.AppMetadata?.authorization?.roles as IEnumerable<dynamic>).Select(r => r.ToString() as string));
            if (profile.ProviderAttributes.ContainsKey("authorization"))
                roles.UnionWith((profile.ProviderAttributes["authorization"]["roles"] as IEnumerable<dynamic>).Select(r => r.ToString() as string));
            if (profile.ProviderAttributes.ContainsKey("roles"))
                roles.UnionWith((profile.ProviderAttributes["roles"] as IEnumerable<dynamic>).Select(r => r.ToString() as string));
            roles.UnionWith(idenreplacedy.FindAll("roles").Select(x => x.Value));
            idenreplacedy.AddClaims(roles.Select(r => new Claim(idenreplacedy.RoleClaimType, r, ClaimValueTypes.String, "Auth0")));

            var groups = new HashSet<string>();
            if (profile.AppMetadata?.authorization?.groups != null)
                groups.UnionWith((profile.AppMetadata?.authorization?.groups as IEnumerable<dynamic>).Select(r => r.ToString() as string));
            if (profile.ProviderAttributes.ContainsKey("authorization"))
                groups.UnionWith((profile.ProviderAttributes["authorization"]["groups"] as IEnumerable<dynamic>).Select(r => r.ToString() as string));
            if (profile.ProviderAttributes.ContainsKey("groups"))
                groups.UnionWith((profile.ProviderAttributes["groups"] as IEnumerable<dynamic>).Select(r => r.ToString() as string));
            groups.UnionWith(idenreplacedy.FindAll("groups").Select(x => x.Value));
            idenreplacedy.AddClaims(groups.Select(r => new Claim(Auth0ClaimTypes.Group, r, ClaimValueTypes.String, "Auth0")));

            var permissions = new HashSet<string>();
            if (profile.AppMetadata?.authorization?.permissions != null)
                permissions.UnionWith((profile.AppMetadata?.authorization?.permissions as IEnumerable<dynamic>).Select(r => r.ToString() as string));
            if (profile.ProviderAttributes.ContainsKey("authorization"))
                permissions.UnionWith((profile.ProviderAttributes["authorization"]["permissions"] as IEnumerable<dynamic>).Select(r => r.ToString() as string));
            if (profile.ProviderAttributes.ContainsKey("permissions"))
                permissions.UnionWith((profile.ProviderAttributes["permissions"] as IEnumerable<dynamic>).Select(r => r.ToString() as string));
            permissions.UnionWith(idenreplacedy.FindAll("permissions").Select(x => x.Value));
            idenreplacedy.AddClaims(permissions.Select(r => new Claim(Auth0ClaimTypes.Permission, r, ClaimValueTypes.String, "Auth0")));

        }

19 View Source File : Planet.cs
License : The Unlicense
Project Creator : aeroson

private void UpdateChunkRenderers(Stopwatch frameStart, TimeSpan timeBudget)
	{
		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers");

		if (subdivisonCalculationLast == null) return;

		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers / UnionWith");
		toRenderChunks.Clear();
		toRenderChunks.UnionWith(subdivisonCalculationLast.GetChunksToRender());
		MyProfiler.EndSample();

		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers / calculate toStartRendering");
		toStartRendering.Clear();
		foreach (var chunk in toRenderChunks)
		{
			if (!chunk.HasFullyGeneratedData) continue;
			if (!chunksCurrentlyRendered.ContainsKey(chunk)) toStartRendering.Add(chunk);
			//if (toStartRendering.Count > 10) break;
		}
		MyProfiler.EndSample();

		// if chunks are regenerated, refresh their rendering
		foreach (var chunk in chunkGenerationJustFinished)
		{
			if (chunksCurrentlyRendered.ContainsKey(chunk))
			{
				chunksCurrentlyRendered[chunk].RenderChunk(chunk);
				considerChunkForCleanup.Remove(chunk);
			}
		}

		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers / toStopRendering / calculate");
		toStopRendering.Clear();
		foreach (var kvp in chunksCurrentlyRendered)
		{
			if (!toRenderChunks.Contains(kvp.Key)) toStopRendering.Add(kvp.Key);
		}
		MyProfiler.EndSample();

		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers / toStopRendering / execute");
		foreach (var chunk in toStopRendering)
		{
			bool bIsAnyParentRendered = false;
			{
				ChunkData parent = chunk.parent;
				while (parent != null)
				{
					if (!toStopRendering.Contains(parent) && chunksCurrentlyRendered.ContainsKey(parent))
					{
						bIsAnyParentRendered = true;
						break;
					}

					parent = parent.parent;
				}
			}

			bool bAllChildrenRendered = chunk.AreAllChildrenRendered;

			if (bIsAnyParentRendered || bAllChildrenRendered) // make sure we hide chunk only if there is some other chunk rendering mesh in its place
			{
				freeRenderers.Push(chunksCurrentlyRendered[chunk]);
				chunksCurrentlyRendered.Remove(chunk);
				considerChunkForCleanup.Add(chunk);
			}
		}
		MyProfiler.EndSample();

		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers / toStartRendering / get free renderers");
		while (freeRenderers.Count < toStartRendering.Count)
		{
			var renderer = ProceduralPlanets.main.GetFreeChunkRendererFromPool();
			freeRenderers.Push(renderer);
		}
		MyProfiler.EndSample();

		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers / toStartRendering / execute");
		foreach (var chunk in toStartRendering)
		{
			var renderer = freeRenderers.Pop();
			renderer.RenderChunk(chunk);
			chunksCurrentlyRendered.Add(chunk, renderer);
			considerChunkForCleanup.Remove(chunk);
		}
		MyProfiler.EndSample();

		MyProfiler.BeginSample("Procedural Planet / Update ChunkRenderers / Return to pool");
		while (freeRenderers.Count > 0)
		{
			ProceduralPlanets.main.ReturnChunkRendererToPool(freeRenderers.Pop());
		}
		MyProfiler.EndSample();


		MyProfiler.AddNumberSample("Procedural Planet / Update ChunkRenderers / to start rendering", toStartRendering.Count);
		MyProfiler.AddNumberSample("Procedural Planet / Update ChunkRenderers / to stop rendering", toStopRendering.Count);
		MyProfiler.AddNumberSample("Procedural Planet / Update ChunkRenderers / to render", toRenderChunks.Count);
		MyProfiler.AddNumberSample("Procedural Planet / chunksCurrentlyRendered", chunksCurrentlyRendered.Count);

		MyProfiler.EndSample();
	}

19 View Source File : IniFile.cs
License : GNU General Public License v3.0
Project Creator : Artentus

private static Dictionary<string, Dictionary<string, string>> MergeData(IEnumerable<Dictionary<string, Dictionary<string, string>>> dataList)
        {
            var sections = new HashSet<string>();
            foreach (var data in dataList)
            {
                var set = new HashSet<string>(data.Keys);
                sections.UnionWith(set);
            }

            var result = new Dictionary<string, Dictionary<string, string>>();
            foreach (var section in sections)
                result.Add(section, new Dictionary<string, string>());

            foreach (var data in dataList)
            {
                foreach (var kvp in data)
                    result[kvp.Key].UnionWith(kvp.Value);
            }

            return result;
        }

19 View Source File : tileMapScript.cs
License : MIT License
Project Creator : Angus-Fan

public HashSet<Node> getUnitMovementOptions()
    {
        float[,] cost = new float[mapSizeX, mapSizeY];
        HashSet<Node> UIHighlight = new HashSet<Node>();
        HashSet<Node> tempUIHighlight = new HashSet<Node>();
        HashSet<Node> finalMovementHighlight = new HashSet<Node>();      
        int moveSpeed = selectedUnit.GetComponent<UnitScript>().moveSpeed;
        Node unitInitialNode = graph[selectedUnit.GetComponent<UnitScript>().x, selectedUnit.GetComponent<UnitScript>().y];

        ///Set-up the initial costs for the neighbouring nodes
        finalMovementHighlight.Add(unitInitialNode);
        foreach (Node n in unitInitialNode.neighbours)
        {
            cost[n.x, n.y] = costToEnterTile(n.x, n.y);
            //Debug.Log(cost[n.x, n.y]);
            if (moveSpeed - cost[n.x, n.y] >= 0)
            {
                UIHighlight.Add(n);
            }
        }

        finalMovementHighlight.UnionWith(UIHighlight);

        while (UIHighlight.Count != 0)
        {
            foreach (Node n in UIHighlight)
            {
                foreach (Node neighbour in n.neighbours)
                {
                    if (!finalMovementHighlight.Contains(neighbour))
                    {
                        cost[neighbour.x, neighbour.y] = costToEnterTile(neighbour.x, neighbour.y) + cost[n.x, n.y];
                        //Debug.Log(cost[neighbour.x, neighbour.y]);
                        if (moveSpeed - cost[neighbour.x, neighbour.y] >= 0)
                        {
                            //Debug.Log(cost[neighbour.x, neighbour.y]);
                            tempUIHighlight.Add(neighbour);
                        }
                    }
                }

            }

            UIHighlight = tempUIHighlight;
            finalMovementHighlight.UnionWith(UIHighlight);
            tempUIHighlight = new HashSet<Node>();
           
        }
        Debug.Log("The total amount of movable spaces for this unit is: " + finalMovementHighlight.Count);
        Debug.Log("We have used the function to calculate it this time");
        return finalMovementHighlight;
    }

19 View Source File : FrameworkConfigurationBuilder.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public FrameworkConfigurationBuilder AddModulesFromServices(IServiceCollection services)
        {
            _modules.UnionWith(services.Where(x => x.ServiceType.GetCustomAttribute<ModuleAttribute>() != null).Select(x => x.ServiceType));
            return this;
        }

19 View Source File : FrameworkConfigurationBuilder.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

public FrameworkConfigurationBuilder AddOwners(IEnumerable<ulong> ids)
        {
            _ownerIDs.UnionWith(ids);
            return this;
        }

19 View Source File : tileMapScript.cs
License : MIT License
Project Creator : Angus-Fan

public HashSet<Node> getUnitTotalAttackableTiles(HashSet<Node> finalMovementHighlight, int attRange, Node unitInitialNode)
    {
        HashSet<Node> tempNeighbourHash = new HashSet<Node>();
        HashSet<Node> neighbourHash = new HashSet<Node>();
        HashSet<Node> seenNodes = new HashSet<Node>();
        HashSet<Node> totalAttackableTiles = new HashSet<Node>();
        foreach (Node n in finalMovementHighlight)
        {
            neighbourHash = new HashSet<Node>();
            neighbourHash.Add(n);
            for (int i = 0; i < attRange; i++)
            {
                foreach (Node t in neighbourHash)
                {
                    foreach (Node tn in t.neighbours)
                    {
                        tempNeighbourHash.Add(tn);
                    }
                }

                neighbourHash = tempNeighbourHash;
                tempNeighbourHash = new HashSet<Node>();
                if (i < attRange - 1)
                {
                    seenNodes.UnionWith(neighbourHash);
                }

            }
            neighbourHash.ExceptWith(seenNodes);
            seenNodes = new HashSet<Node>();
            totalAttackableTiles.UnionWith(neighbourHash);
        }
        totalAttackableTiles.Remove(unitInitialNode);
        
        //Debug.Log("The unit node has this many attack options" + totalAttackableTiles.Count);
        return (totalAttackableTiles);
    }

19 View Source File : QuadTree.cs
License : MIT License
Project Creator : Auios

public T[] FindObjects(QuadTreeRect rect)
        {
            List<T> foundObjects = new List<T>();
            if(_hasChildren)
            {
                foundObjects.AddRange(quad_TL.FindObjects(rect));
                foundObjects.AddRange(quad_TR.FindObjects(rect));
                foundObjects.AddRange(quad_BL.FindObjects(rect));
                foundObjects.AddRange(quad_BR.FindObjects(rect));
            }
            else
            {
                if(IsOverlapping(rect))
                {
                    foundObjects.AddRange(_objects);
                }
            }

            HashSet<T> result = new HashSet<T>();
            result.UnionWith(foundObjects);

            return result.ToArray();
        }

19 View Source File : IEnumerableExtensions.cs
License : MIT License
Project Creator : AlphaYu

public static HashSet<TResult> ToHashSet<T, TResult>(this IEnumerable<T> source, Func<T, TResult> selector)
        {
            var set = new HashSet<TResult>();
            set.UnionWith(source.Select(selector));
            return set;
        }

19 View Source File : HelpGeneratorBase.cs
License : Apache License 2.0
Project Creator : aws

public HashSet<string> ParameterNamesForSet(string setName, bool appendAllSets)
        {
            if (!ParameterSets.ContainsKey(setName))
                throw new ArgumentException("Parameter set is unknown: " + setName, setName);

            var parameters = new HashSet<string>(ParameterSets[setName]);
            if (appendAllSets && !setName.Equals(AllSetsKey, StringComparison.Ordinal))
            {
                var allSets = ParameterSets[AllSetsKey];
                parameters.UnionWith(allSets);
            }

            return parameters;
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : anydream

protected override void ExpandDepends()
		{
			HashSet<string> depSet = new HashSet<string>();
			foreach (string dep in DependFiles)
			{
				string dfile = Path.Combine(OutDir, Path.GetFileName(dep) + ".d");

				if (Helper.GetDependFiles(dfile, out var depFiles))
					depSet.UnionWith(depFiles);
			}
			foreach (string dep in depSet)
				DependFiles.Add(Path.GetFullPath(dep));
		}

19 View Source File : FeatureSetLoader.cs
License : Apache License 2.0
Project Creator : aws

public static FeatureSet LoadFeatureSetFromFeatureConfig(FeatureConfig featureConfig)
        {
            var compiledFeatures = new HashSet<CompiledFeature>();
            var configuredFeatures = new HashSet<ConfiguredFeature>();
            foreach (var featureGroup in featureConfig.FeatureGroups)
            {
                var featureScope = featureGroup.FeatureScope;
                var newCompiledFeatures = FeatureLoader.LoadCompiledFeaturesFromreplacedemblies(featureScope, featureGroup.CompiledFeaturereplacedemblies);
                var newConfiguredFeatures = FeatureLoader.LoadConfiguredFeatures(featureScope, featureGroup.ConfiguredFeatures);

                compiledFeatures.UnionWith(newCompiledFeatures);
                configuredFeatures.UnionWith(newConfiguredFeatures);
            }

            return new FeatureSet(compiledFeatures, configuredFeatures);
        }

19 View Source File : HierarchicalResolver.cs
License : MIT License
Project Creator : Abc-Arbitrage

public IEnumerable<IAppender> GetAllAppenders()
        {
            var appenders = new HashSet<IAppender>();
            AddAppenders(_root);
            return appenders;

            void AddAppenders(Node? node)
            {
                if (node == null)
                    return;

                appenders.UnionWith(node.Appenders);
                foreach (var childNode in node.Children.Values)
                    AddAppenders(childNode);
            }
        }

19 View Source File : FeatureLoader.cs
License : Apache License 2.0
Project Creator : aws

public static HashSet<CompiledFeature> LoadCompiledFeaturesFromreplacedemblies(
            FeatureScope featureScope,
            CompiledFeaturereplacedembly[] compiledFeaturereplacedemblies)
        {
            var loadedFeatures = new HashSet<CompiledFeature>();
            foreach (var compiledFeaturereplacedembly in compiledFeaturereplacedemblies)
            {
                try
                {
                    var compiledFeatures = LoadCompiledFeaturesFromreplacedembly(featureScope, compiledFeaturereplacedembly);
                    loadedFeatures.UnionWith(compiledFeatures);
                }
                catch (FileNotFoundException ex)
                {
                    Logger.LogError(ex, $"Could not find replacedembly {compiledFeaturereplacedembly.replacedemblyPath}");
                }
            }

            return loadedFeatures;
        }

19 View Source File : GeneratorContext.cs
License : GNU General Public License v3.0
Project Creator : anydream

public void Append(CompileUnit unit)
		{
			DeclCode += unit.DeclCode;
			DeclDepends.UnionWith(unit.DeclDepends);
			ImplCode += unit.ImplCode;
			ImplDepends.UnionWith(unit.ImplDepends);
			StringDepends.UnionWith(unit.StringDepends);
		}

19 View Source File : CosmosTraceDiagnostics.cs
License : MIT License
Project Creator : Azure

private void WalkTraceTreeForRegionsContated(ITrace currentTrace, HashSet<(string, Uri)> regionsContacted)
        {
            foreach (object datums in currentTrace.Data.Values)
            {
                if (datums is ClientSideRequestStatisticsTraceDatum clientSideRequestStatisticsTraceDatum)
                {
                    regionsContacted.UnionWith(clientSideRequestStatisticsTraceDatum.RegionsContacted);
                    return;
                }
            }

            foreach (ITrace childTrace in currentTrace.Children)
            {
                this.WalkTraceTreeForRegionsContated(childTrace, regionsContacted);
            }
        }

19 View Source File : Selector.cs
License : MIT License
Project Creator : AmigoCap

public void Select(bool erase = false) {
            if (!isActiveAndEnabled)
                return;

            Tools.StartClock();

            List<SelectorPart> parts = new List<SelectorPart>(GetComponents<SelectorPart>());
            parts.RemoveAll(p => !p.enabled);

            if (parts.Count == 0)
                return;

            Visualization viz = Visualization.Instance;
            HashSet<Atom> selectedRibbons = SelectorManager.Instance.selectedRibbons[(int)Color];

            foreach (SelectorPart p in parts) {
                if (needsCheckedHighlightCleanup) {
                    needsCheckedHighlightCleanup = false;
                    foreach (Atom a in p.RibbonsToCheck)
                        a.ShouldHighlightBecauseChecked((int)Color, false);
                }

                Tools.AddClockStop("Removed old c_highlights");

                p.FindTouchedRibbons();

                Tools.AddClockStop("Found touched ribbons");

                if (SelectorManager.Instance.HighlightChecked && !Persistent) {
                    foreach (Atom a in p.RibbonsToCheck)
                        a.ShouldHighlightBecauseChecked((int)Color, true);
                }

                Tools.AddClockStop("Added new c_highlights");
                Tools.EndClock();
            }

            IEnumerable<Atom> handledRibbons;

            if (parts.Count > 1) {
                HashSet<Atom> handledRibbonsSet = new HashSet<Atom>();

                foreach (SelectorPart p in GetComponents<SelectorPart>()) {
                    if (!p.enabled)
                        continue;
                    if (p.Positive) {
                        handledRibbonsSet.UnionWith(p.TouchedRibbons);
                    }
                    else {
                        handledRibbonsSet.ExceptWith(p.TouchedRibbons);
                    }
                }

                handledRibbons = handledRibbonsSet;
            }
            else {
                handledRibbons = parts[0].TouchedRibbons;
            }

            if (erase) {
                selectedRibbons.ExceptWith(handledRibbons);

                foreach (Atom a in handledRibbons) {
                    a.ShouldHighlightBecauseSelected((int)Color, false);
                }
            }
            else {
                selectedRibbons.UnionWith(handledRibbons);

                if (SelectorManager.Instance.HighlightSelected) {
                    foreach (Atom a in handledRibbons) {
                        a.ShouldHighlightBecauseSelected((int)Color, true);
                    }
                }
            }

            Tools.AddClockStop("Added new s_highlights");

            if (SelectorManager.Instance.HighlightChecked && !Persistent)
                needsCheckedHighlightCleanup = true;
        }

19 View Source File : CollectionRoutingMap.cs
License : MIT License
Project Creator : Azure

public CollectionRoutingMap TryCombine(
            IEnumerable<Tuple<ParreplacedionKeyRange, ServiceIdenreplacedy>> ranges,
            string changeFeedNextIfNoneMatch)
        {
            HashSet<string> newGoneRanges = new HashSet<string>(ranges.SelectMany(tuple => tuple.Item1.Parents ?? Enumerable.Empty<string>()));
            newGoneRanges.UnionWith(this.goneRanges);

            Dictionary<string, Tuple<ParreplacedionKeyRange, ServiceIdenreplacedy>> newRangeById =
                this.rangeById.Values.Where(tuple => !newGoneRanges.Contains(tuple.Item1.Id)).ToDictionary(tuple => tuple.Item1.Id, StringComparer.Ordinal);

            foreach (Tuple<ParreplacedionKeyRange, ServiceIdenreplacedy> tuple in ranges.Where(tuple => !newGoneRanges.Contains(tuple.Item1.Id)))
            {
                newRangeById[tuple.Item1.Id] = tuple;

                DefaultTrace.TraceInformation(
                    "CollectionRoutingMap.TryCombine newRangeById[{0}] = {1}",
                    tuple.Item1.Id, tuple);
            }

            List<Tuple<ParreplacedionKeyRange, ServiceIdenreplacedy>> sortedRanges = newRangeById.Values.ToList();

            sortedRanges.Sort(new MinParreplacedionKeyTupleComparer());
            List<ParreplacedionKeyRange> newOrderedRanges = sortedRanges.Select(range => range.Item1).ToList();

            if (!IsCompleteSetOfRanges(newOrderedRanges))
            {
                return null;
            }

            return new CollectionRoutingMap(newRangeById, newOrderedRanges, this.CollectionUniqueId, changeFeedNextIfNoneMatch);
        }

19 View Source File : MethodTable.cs
License : GNU General Public License v3.0
Project Creator : anydream

public void ResolveTable()
		{
			Debug.replacedert(InstGenArgs == null);

			var metDefList = new List<Tuple<string, MethodDef>>();
			var conflictMap = new Dictionary<string, ConflictPair>();
			var nameSet = new HashSet<string>();

			bool thisIsInterface = Def.IsInterface;
			bool thisIsAbstract = Def.IsAbstract;

			StringBuilder sb = new StringBuilder();

			uint lastRid = 0;
			foreach (MethodDef metDef in Def.Methods)
			{
				// 跳过非虚方法
				if (!metDef.IsVirtual)
				{
					// 非虚方法如果存在显式重写则视为错误
					if (metDef.HasOverrides)
					{
						throw new TypeLoadException(
							string.Format("Explicit overridden method must be virtual in type {0}: {1}",
								GetNameKey(),
								metDef.FullName));
					}

					continue;
				}

				if (metDef.Rid != 0)
				{
					Debug.replacedert(lastRid == 0 || lastRid < metDef.Rid);
					lastRid = metDef.Rid;
				}

				// 获得方法签名
				Helper.MethodDefNameKey(sb, metDef, null);
				string metNameKey = sb.ToString();
				sb.Clear();
				nameSet.Add(metNameKey);

				if (thisIsInterface)
				{
					Debug.replacedert(metDef.IsAbstract && metDef.IsNewSlot);
					metDefList.Add(new Tuple<string, MethodDef>(metNameKey, metDef));
				}
				else
				{
					// 特殊处理签名冲突的方法
					if (!conflictMap.TryGetValue(metNameKey, out var confPair))
					{
						confPair = new ConflictPair();
						conflictMap.Add(metNameKey, confPair);
						metDefList.Add(new Tuple<string, MethodDef>(metNameKey, metDef));
					}

					if (metDef.IsNewSlot)
						confPair.NewSlots.Add(metDef);
					else
						confPair.ReuseSlots.Add(metDef);
				}
			}

			if (!thisIsInterface)
			{
				foreach (var item in conflictMap.Where(kvp => !kvp.Value.ContainsConflicts()).ToList())
				{
					conflictMap.Remove(item.Key);
				}
			}

			// 解析基类方法表
			MethodTable baseTable = null;
			if (Def.BaseType != null)
			{
				baseTable = TypeMgr.ResolveMethodTable(Def.BaseType);

				// 继承基类数据
				DerivedTable(baseTable);
			}

			var expOverrides = new List<Tuple<string, MethodDef>>();
			// 解析隐式重写
			foreach (var mereplacedem in metDefList)
			{
				string metNameKey = mereplacedem.Item1;

				if (thisIsInterface)
				{
					// 接口需要合并相同签名的方法
					MethodDef metDef = mereplacedem.Item2;
					var entry = new TableMethodPair(this, metDef);
					MergeInterface(metNameKey, entry);
				}
				else if (conflictMap.TryGetValue(metNameKey, out var confPair))
				{
					Debug.replacedert(confPair.ContainsConflicts());

					// 冲突签名的方法需要先处理重写槽方法, 再处理新建槽方法
					VirtualSlot lastVSlot = null;
					foreach (var metDef in confPair.ReuseSlots)
						lastVSlot = ProcessMethod(metNameKey, metDef, baseTable, expOverrides);

					// 应用重写信息到入口映射
					ApplyVirtualSlot(lastVSlot);

					foreach (var metDef in confPair.NewSlots)
						ProcessMethod(metNameKey, metDef, baseTable, expOverrides);
				}
				else
				{
					MethodDef metDef = mereplacedem.Item2;
					ProcessMethod(metNameKey, metDef, baseTable, expOverrides);
				}
			}
			metDefList = null;
			conflictMap = null;
			baseTable = null;

			// 关联抽象基类未实现的接口
			if (NotImplInterfaces.IsCollectionValid())
			{
				List<string> removedKeys = new List<string>();
				foreach (var kv in NotImplInterfaces)
				{
					string metNameKey = kv.Key;
					var notImplEntries = kv.Value;
					if (SlotMap.TryGetValue(metNameKey, out var vslot))
					{
						vslot.Entries.UnionWith(notImplEntries);
						removedKeys.Add(metNameKey);
						ApplyVirtualSlot(vslot);
					}
				}
				foreach (var key in removedKeys)
					NotImplInterfaces.Remove(key);
			}

			// 关联接口
			if (Def.HasInterfaces)
			{
				foreach (var inf in Def.Interfaces)
				{
					MethodTable infTable = TypeMgr.ResolveMethodTable(inf.Interface);
					foreach (var kv in infTable.SlotMap)
					{
						string metNameKey = kv.Key;
						var infEntries = kv.Value.Entries;

						if (thisIsInterface)
						{
							MergeInterfaces(metNameKey, infEntries);
						}
						else if (nameSet.Contains(metNameKey) &&
								 SlotMap.TryGetValue(metNameKey, out var vslot))
						{
							// 关联当前类型内签名相同的方法
							vslot.Entries.UnionWith(infEntries);
							ApplyVirtualSlot(vslot);
						}
						else
						{
							foreach (var entry in infEntries)
							{
								if (!EntryMap.ContainsKey(entry))
								{
									if (SlotMap.TryGetValue(metNameKey, out vslot))
									{
										// 关联继承链上签名相同的方法
										vslot.Entries.Add(entry);
										ApplyVirtualSlot(vslot);
									}
									else if (thisIsAbstract)
									{
										AddNotImplInterface(metNameKey, entry);
									}
									else
									{
										// 暂时未实现的接口入口
										SetEntryMap(entry, null);
									}
								}
							}
						}
					}
				}
			}

			// 记录显式重写目标以便查重
			var expOverTargets = new HashSet<TableMethodPair>();

			// 解析显式重写
			foreach (var expItem in expOverrides)
			{
				string metNameKey = expItem.Item1;
				MethodDef metDef = expItem.Item2;

				foreach (MethodOverride metOver in metDef.Overrides)
				{
					var overTarget = metOver.MethodDeclaration;
					var overImpl = metOver.MethodBody;

					MethodTable targetTable = TypeMgr.ResolveMethodTable(overTarget.DeclaringType);
					MethodDef targetDef = overTarget.ResolveMethodDef();

					// 验证显式重写目标的正确性
					if (targetDef == null || targetDef.DeclaringType != targetTable.Def)
					{
						throw new TypeLoadException(
							string.Format("Illegal explicit overriding target in type {0}: {1}",
								GetNameKey(),
								overTarget.FullName));
					}
					if (!targetDef.IsVirtual)
					{
						throw new TypeLoadException(
							string.Format("Explicit overriding target must be virtual in type {0}: {1}",
								GetNameKey(),
								overTarget.FullName));
					}

					var targetEntry = new TableMethodPair(targetTable, targetDef);

					MethodDef implDef = overImpl.ResolveMethodDef();
					Debug.replacedert(metDef == implDef);

					// 同一个类内重复的显式重写, 以及重写存在重写的方法, 视为错误
					if ((targetTable == this && targetDef.HasOverrides) ||
						expOverTargets.Contains(targetEntry))
					{
						throw new TypeLoadException(
							string.Format("Explicit overriding target has been overridden in type {0}: {1}",
								GetNameKey(),
								overTarget.FullName));
					}
					expOverTargets.Add(targetEntry);

					if (targetTable.Def.IsInterface)
					{
						// 接口方法显式重写
						ExplicitOverride(targetEntry, metNameKey);
					}
					else
					{
						// 相同类型的需要添加到替换映射, 以便非虚调用时处理替换
						if (targetTable == this)
							SameTypeReplaceMap[targetDef] = new TableMethodPair(this, implDef);
						else
						{
							var vslot = SlotMap[metNameKey];
							Debug.replacedert(vslot != null);
							SetEntryMap(targetEntry, vslot.Implemented);
						}
					}
				}
			}
			expOverTargets = null;

			// 接口不需要展开入口
			if (thisIsInterface)
				return;

			// 展开新建槽位映射
			foreach (var kv in SlotMap)
			{
				var entries = kv.Value.Entries;
				var newSlotEntry = kv.Value.NewSlotEntry;
				Debug.replacedert(newSlotEntry.Item2.IsNewSlot);

				foreach (TableMethodPair entry in entries)
				{
					var entryDef = entry.Item2;
					if (entryDef.IsReuseSlot && entryDef != newSlotEntry.Item2)
						NewSlotEntryMap[entryDef] = newSlotEntry;
				}
			}

			// 对于非抽象类需要检查是否存在实现
			if (!thisIsAbstract)
			{
				foreach (var kv in EntryMap)
				{
					if (kv.Value == null)
					{
						throw new TypeLoadException(
							string.Format("Interface/abstract method not implemented in type {0}: {1} -> {2}",
								GetNameKey(),
								kv.Key.Item1.GetNameKey(),
								kv.Key.Item2.FullName));
					}
				}
			}
		}

19 View Source File : SinglePartitionPartitionRangeEnumeratorTests.cs
License : MIT License
Project Creator : Azure

[TestMethod]
            public async Task TestSplitAsync()
            {
                int numItems = 100;
                IDoreplacedentContainer inMemoryCollection = await this.CreateDoreplacedentContainerAsync(numItems);
                IReadOnlyList<FeedRangeInternal> ranges = await inMemoryCollection.GetFeedRangesAsync(trace: NoOpTrace.Singleton, cancellationToken: default);
                replacedert.AreEqual(1, ranges.Count);

                TracingAsyncEnumerator<TryCatch<ReadFeedPage>> enumerator = new(
                    new ReadFeedParreplacedionRangeEnumerator(
                        inMemoryCollection,
                        feedRangeState: new FeedRangeState<ReadFeedState>(ranges[0], ReadFeedState.Beginning()),
                        readFeedPaginationOptions: new ReadFeedPaginationOptions(pageSizeHint: 10),
                        cancellationToken: default),
                    NoOpTrace.Singleton);


                (HashSet<string> parentIdentifiers, ReadFeedState state) = await this.PartialDrainAsync(enumerator, numIterations: 3);

                // Split the parreplacedion
                await inMemoryCollection.SplitAsync(ranges[0], cancellationToken: default);

                // Try To read from the parreplacedion that is gone.
                await enumerator.MoveNextAsync();
                replacedert.IsTrue(enumerator.Current.Failed);

                // Resume on the children using the parent continuaiton token
                HashSet<string> childIdentifiers = new HashSet<string>();

                await inMemoryCollection.RefreshProviderAsync(NoOpTrace.Singleton, cancellationToken: default);
                IReadOnlyList<FeedRangeInternal> childRanges = await inMemoryCollection.GetFeedRangesAsync(trace: NoOpTrace.Singleton, cancellationToken: default);
                foreach (FeedRangeInternal childRange in childRanges)
                {
                    ParreplacedionRangePageAsyncEnumerable<ReadFeedPage, ReadFeedState> enumerable = new ParreplacedionRangePageAsyncEnumerable<ReadFeedPage, ReadFeedState>(
                        feedRangeState: new FeedRangeState<ReadFeedState>(childRange, state),
                        (feedRangeState) => new ReadFeedParreplacedionRangeEnumerator(
                                inMemoryCollection,
                                feedRangeState: feedRangeState,
                                readFeedPaginationOptions: new ReadFeedPaginationOptions(pageSizeHint: 10),
                                cancellationToken: default),
                        trace: NoOpTrace.Singleton);
                    HashSet<string> resourceIdentifiers = await this.DrainFullyAsync(enumerable);

                    childIdentifiers.UnionWith(resourceIdentifiers);
                }

                replacedert.AreEqual(numItems, parentIdentifiers.Count + childIdentifiers.Count);
            }

19 View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever

public async Task FindDiscKeyAsync(string discKeyCachePath)
        {
            // reload disc keys
            try
            {
                foreach (var keyProvider in DiscKeyProviders)
                {
                    Log.Trace($"Getting keys from {keyProvider.GetType().Name}...");
                    var newKeys = await keyProvider.EnumerateAsync(discKeyCachePath, ProductCode, Cts.Token).ConfigureAwait(false);
                    Log.Trace($"Got {newKeys.Count} keys");
                    lock (AllKnownDiscKeys)
                    {
                        foreach (var keyInfo in newKeys)
                        {
                            try
                            {
                                if (!AllKnownDiscKeys.TryGetValue(keyInfo.DecryptedKeyId, out var duplicates))
                                    AllKnownDiscKeys[keyInfo.DecryptedKeyId] = duplicates = new HashSet<DiscKeyInfo>();
                                duplicates.Add(keyInfo);
                            }
                            catch (Exception e)
                            {
                                Log.Error(e);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to load disc keys");
            }
            // check if user provided something new since the last attempt
            var untestedKeys = new HashSet<string>();
            lock (AllKnownDiscKeys)
                untestedKeys.UnionWith(AllKnownDiscKeys.Keys);
            untestedKeys.ExceptWith(TestedDiscKeys);
            if (untestedKeys.Count == 0)
                throw new KeyNotFoundException("No valid disc decryption key was found");

            // select physical device
            string physicalDevice = null;
            List<string> physicalDrives = new List<string>();
            Log.Trace("Trying to enumerate physical drives...");
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    physicalDrives = EnumeratePhysicalDrivesWindows();
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    physicalDrives = EnumeratePhysicalDrivesLinux();
                else
                    throw new NotImplementedException("Current OS is not supported");
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw;
            }
            Log.Debug($"Found {physicalDrives.Count} physical drives");

            if (physicalDrives.Count == 0)
                throw new InvalidOperationException("No optical drives were found");

            foreach (var drive in physicalDrives)
            {
                try
                {
                    Log.Trace($"Checking physical drive {drive}...");
                    using var discStream = File.Open(drive, FileMode.Open, FileAccess.Read, FileShare.Read);
                    var tmpDiscReader = new CDReader(discStream, true, true);
                    if (tmpDiscReader.FileExists("PS3_DISC.SFB"))
                    {
                        Log.Trace("Found PS3_DISC.SFB, getting sector data...");
                        var discSfbInfo = tmpDiscReader.GetFileInfo("PS3_DISC.SFB");
                        if (discSfbInfo.Length == discSfbData.Length)
                        {
                            var buf = new byte[discSfbData.Length];
                            var sector = tmpDiscReader.PathToClusters(discSfbInfo.FullName).First().Offset;
                            Log.Trace($"PS3_DISC.SFB sector number is {sector}, reading content...");
                            discStream.Seek(sector * tmpDiscReader.ClusterSize, SeekOrigin.Begin);
                            discStream.ReadExact(buf, 0, buf.Length);
                            if (buf.SequenceEqual(discSfbData))
                            {
                                physicalDevice = drive;
                                break;
                            }
                            Log.Trace("SFB content check failed, skipping the drive");
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Debug($"Skipping drive {drive}: {e.Message}");
                }
            }
            if (physicalDevice == null)
                throw new AccessViolationException("Couldn't get physical access to the drive");

            Log.Debug($"Selected physical drive {physicalDevice}");
            driveStream = File.Open(physicalDevice, FileMode.Open, FileAccess.Read, FileShare.Read);

            // find disc license file
            discReader = new CDReader(driveStream, true, true);
            FileRecord detectionRecord = null;
            byte[] expectedBytes = null;
            try
            {
                foreach (var path in Detectors.Keys)
                    if (discReader.FileExists(path))
                    {
                        var clusterRange = discReader.PathToClusters(path);
                        detectionRecord = new FileRecord(path, clusterRange.Min(r => r.Offset), discReader.GetFileLength(path));
                        expectedBytes = Detectors[path];
                        if (detectionRecord.Length == 0)
                            continue;
                        
                        Log.Debug($"Using {path} for disc key detection");
                        break;
                    }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            if (detectionRecord == null)
                throw new FileNotFoundException("Couldn't find a single disc key detection file, please report");

            if (Cts.IsCancellationRequested)
                return;

            SectorSize = discReader.ClusterSize;

            // select decryption key
            driveStream.Seek(detectionRecord.StartSector * discReader.ClusterSize, SeekOrigin.Begin);
            detectionSector = new byte[discReader.ClusterSize];
            detectionBytesExpected = expectedBytes;
            sectorIV = Decrypter.GetSectorIV(detectionRecord.StartSector);
            Log.Debug($"Initialized {nameof(sectorIV)} ({sectorIV?.Length * 8} bit) for sector {detectionRecord.StartSector}: {sectorIV?.ToHexString()}");
            driveStream.ReadExact(detectionSector, 0, detectionSector.Length);
            string discKey = null;
            try
            {
                discKey = untestedKeys.AsParallel().FirstOrDefault(k => !Cts.IsCancellationRequested && IsValidDiscKey(k));
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            if (discKey == null)
                throw new KeyNotFoundException("No valid disc decryption key was found");

            if (Cts.IsCancellationRequested)
                return;

            lock (AllKnownDiscKeys)
                AllKnownDiscKeys.TryGetValue(discKey, out allMatchingKeys);
            var discKeyInfo = allMatchingKeys?.First();
            DiscKeyFilename = Path.GetFileName(discKeyInfo?.FullPath);
            DiscKeyType = discKeyInfo?.KeyType ?? default;
        }

19 View Source File : ITypedDurableActivityCallerGenerator.cs
License : MIT License
Project Creator : Azure

private CompilationUnitSyntax Generate()
        {
            var modifiers = AsModifierList(SyntaxKind.PublicKeyword, SyntaxKind.PartialKeyword);

            var requiredNamespaces = new HashSet<string>(requiredUsings);
            var memberList = new List<MemberDeclarationSyntax>();

            foreach (var function in functions)
            {
                if (function.Kind != DurableFunctionKind.Activity)
                    continue;

                memberList.Add(GenerateCallMethodWithRetry(function));
                memberList.Add(GenerateCallMethodWithoutRetry(function));

                requiredNamespaces.UnionWith(function.RequiredNamespaces);
            }

            var members = SyntaxFactory.List(memberList);

            var @interface = SyntaxFactory.InterfaceDeclaration(Names.ITypedDurableActivityCaller)
                .WithModifiers(modifiers)
                .WithMembers(members);

            var @namespace = GenerateNamespace().AddMembers(@interface);

            var usings = AsUsings(requiredNamespaces);

            return SyntaxFactory.CompilationUnit().AddUsings(usings).AddMembers(@namespace).NormalizeWhitespace();
        }

19 View Source File : TypeX.cs
License : GNU General Public License v3.0
Project Creator : anydream

private void AddDerivedTypeRecursive(HashSet<TypeX> tySet)
		{
			DerivedTypes.UnionWith(tySet);

			// 递归添加
			BaseType?.AddDerivedTypeRecursive(tySet);
			foreach (var inf in Interfaces)
				inf.AddDerivedTypeRecursive(tySet);

			if (HasVarianceBaseTypes)
			{
				foreach (var va in VarianceBaseTypes)
					va.AddDerivedTypeRecursive(tySet);
			}
		}

19 View Source File : ObjectPatchTypeHandler.cs
License : Apache License 2.0
Project Creator : Anapher

private static void AddProperties(HashSet<string> hashSet, JObject jObject)
        {
            hashSet.UnionWith(jObject.Properties().Select(x => x.Name));
        }

19 View Source File : KeyboardEvents.cs
License : zlib License
Project Creator : 0x0ade

public static void Update() {
            Keys[] keys = Keyboard.GetState().GetPressedKeys();
            Down.Clear();
            for (int i = 0; i < keys.Length; i++) {
                Keys key = keys[i];
                if (!LastDown.Contains(key))
                    KeyDown(key);
                Down.Add(key);
            }
            foreach (Keys key in LastDown) {
                if (!Down.Contains(key))
                    KeyUp(key);
            }
            LastDown.Clear();
            LastDown.UnionWith(Down);
        }

19 View Source File : Reanimator.cs
License : MIT License
Project Creator : aarthificial

public void AddTemporaryDriver(params string[] driverName)
        {
            _temporaryDrivers.UnionWith(driverName);
        }

19 View Source File : CachingAsyncInterceptor.cs
License : MIT License
Project Creator : AlphaYu

private (List<string> cacheKeys, DateTime expireDt) ProcessEvictBefore(IInvocation invocation, CachingEvictAttribute attribute)
        {
            var serviceMethod = invocation.Method ?? invocation.MethodInvocationTarget;
            var needRemovedKeys = new HashSet<string>();

            if (!string.IsNullOrEmpty(attribute.CacheKey))
            {
                needRemovedKeys.Add(attribute.CacheKey);
            }

            if (attribute.CacheKeys?.Length > 0)
            {
                needRemovedKeys.UnionWith(attribute.CacheKeys);
            }

            if (!string.IsNullOrWhiteSpace(attribute.CacheKeyPrefix))
            {
                var cacheKeys = _keyGenerator.GetCacheKeys(serviceMethod, invocation.Arguments, attribute.CacheKeyPrefix);
                needRemovedKeys.UnionWith(cacheKeys);
            }

            var keyExpireSeconds = _cacheProvider.CacheOptions.PollyTimeoutSeconds + 1;
            _cacheProvider.KeyExpireAsync(needRemovedKeys, keyExpireSeconds).GetAwaiter().GetResult();

            return (needRemovedKeys.ToList(), DateTime.Now.AddSeconds(keyExpireSeconds));
        }

19 View Source File : tileMapScript.cs
License : MIT License
Project Creator : Angus-Fan

public HashSet<Node> getUnitTotalRange(HashSet<Node> finalMovementHighlight, HashSet<Node> totalAttackableTiles)
    {
        HashSet<Node> unionTiles = new HashSet<Node>();
        unionTiles.UnionWith(finalMovementHighlight);
        //unionTiles.UnionWith(finalEnemyUnitsInMovementRange);
        unionTiles.UnionWith(totalAttackableTiles);
        return unionTiles;
    }

19 View Source File : StarboardModule.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

private async Task ProcessNewStar(Starboard board, ITextChannel channel, Cacheable<IUserMessage, ulong> cachedMessage, SocketReaction reaction)
        {
            if (!board.Emojis.Contains(reaction.Emote.GetFullName()))
                return;

            if (board.ChannelsWhitelist.Count > 0 && !board.ChannelsWhitelist.Contains(channel.Id))
                return;

            var message = await cachedMessage.GetOrDownloadAsync();
            if (message == null)
                return;

            var logger = _logger.WithScope(message);

            if ((!board.AllowSelfStars && message.Author.Id == reaction.UserId) || message.Author.IsBot)
                return;

            if (string.IsNullOrEmpty(message.Content) && message.Attachments.Count <= 0)
                return;

            var starrers = new HashSet<ulong>();
            foreach (var emoji in message.Reactions.Where(x => board.Emojis.Contains(x.Key.GetFullName())).Select(x => x.Key))
            {
                try
                {
                    starrers.UnionWith((await message.GetReactionUsersAsync(emoji, int.MaxValue).FlattenAsync()).Select(x => x.Id));
                }
                catch (Discord.Net.HttpException ex) when (ex.DiscordCode == 50001)
                {
                    logger.LogInformation("Missing access to read reactions in channel");
                }
            }

            if (!board.AllowSelfStars)
                starrers.Remove(message.Author.Id);

            var entry = await _settings.Modify(channel.GuildId, (StarboardSettings s) =>
            {
                var b = s.Starboards.FirstOrDefault(x => x.Id == board.Id);
                if (b == null)
                    return null;

                var e = b.StarredMessages.GetOrCreate(message.Id);
                e.Author = message.Author.Id;
                e.StarCount = starrers.Count;
                
                return e;
            });

            if (entry == null)
                return;

            if (starrers.Count < board.Threshold)
                return;

            var starChannel = await channel.Guild.GetTextChannelAsync(board.Channel);
            if (starChannel == null)
                return;

            if (entry.StarboardMessage == default)
            {
                // Post new
                if (!(await channel.Guild.GetCurrentUserAsync()).GetPermissions(channel).SendMessages)
                {
                    logger.LogInformation("Can't post starred message because of missing permissions in {TargetChannelName} ({TargetChannelId})", starChannel.Name, starChannel.Id);
                    return;
                }

                var attachments = await ProcessAttachments(message.Attachments);
                var built = await BuildStarMessage(message, channel, starrers.Count, board.Emojis.First(), attachments, board.Style);
                var starMessage = await _communicator.SendMessage(starChannel, built.Text, built.Embed);

                await _settings.Modify(channel.GuildId, (StarboardSettings s) =>
                {
                    var b = s.Starboards.FirstOrDefault(x => x.Id == board.Id);
                    if (b != null && b.StarredMessages.TryGetValue(message.Id, out var e))
                    {
                        e.StarboardMessage = starMessage.Single().Id;
                        e.Attachments = attachments;
                    }
                });

                logger.LogInformation("New starred message in board {StarboardId}", board.Id);
            }
            else
            {
                // Update
                var starMessage = await starChannel.GetMessageAsync(entry.StarboardMessage) as IUserMessage;
                if (starMessage == null)
                    return; // Probably got deleted from starboard

                var built = await BuildStarMessage(message, channel, starrers.Count, board.Emojis.First(), entry.Attachments, board.Style);
                await starMessage.ModifyAsync(x => 
                {
                    x.Content = built.Text;
                    x.Embed = built.Embed;
                });
            }
        }

See More Examples