Example #1
1
        /// <summary>
        /// Locates the changes between the prior and post state of the modules..
        /// </summary>
        /// <param name="modules_prior">List of the available modules prior to the update.</param>
        /// <param name="modules_post">List of the available modules after the update.</param>
        private void PrintChanges(List<CkanModule> modules_prior, List<CkanModule> modules_post)
        {
            var prior = new HashSet<CkanModule>(modules_prior, new NameComparer());
            var post = new HashSet<CkanModule>(modules_post, new NameComparer());


            var added = new HashSet<CkanModule>(post.Except(prior, new NameComparer()));
            var removed = new HashSet<CkanModule>(prior.Except(post, new NameComparer()));


            var unchanged = post.Intersect(prior);//Default compare includes versions
            var updated = post.Except(unchanged).Except(added).Except(removed).ToList();

            // Print the changes.
            user.RaiseMessage("Found {0} new modules, {1} removed modules and {2} updated modules.", added.Count(), removed.Count(), updated.Count());

            if (added.Count > 0)
            {
                PrintModules("New modules [Name (CKAN identifier)]:", added);
            }

            if (removed.Count > 0)
            {
                PrintModules("Removed modules [Name (CKAN identifier)]:", removed);
            }

            if (updated.Count > 0)
            {
                PrintModules("Updated modules [Name (CKAN identifier)]:", updated);
            }
        }
Example #2
1
		public override void OnUpdateList ()
		{
			base.OnUpdateList ();
			StackFrame frame = DebuggingService.CurrentFrame;
			
			if (frame == null || !FrameEquals (frame, lastFrame)) {
				tree.ClearExpressions ();
				lastExpressions = null;
			}
			lastFrame = frame;
			
			if (frame == null)
				return;
			
			//FIXME: tree should use the local refs rather than expressions. ATM we exclude items without names
			var expr = new HashSet<string> (frame.GetAllLocals ().Select (i => i.Name)
				.Where (n => !string.IsNullOrEmpty (n) && n != "?"));
			
			//add expressions not in tree already, remove expressions that are longer valid
			if (lastExpressions != null) {
				foreach (string rem in lastExpressions.Except (expr))
					tree.RemoveExpression (rem);
				foreach (string rem in expr.Except (lastExpressions))
					tree.AddExpression (rem);
			} else {
				tree.AddExpressions (expr);
			}
			
			lastExpressions = expr;
		}
         public static List<DateTime> GetBusinessDays(DateTime dateFrom, DateTime dateTo)

        {
            HashSet<DateTime> holidays = new HashSet<DateTime>();
            HashSet<DateTime> businessDaysSet = new HashSet<DateTime>();

            for (int year=dateFrom.Year; year<=dateTo.Year; year++)
            {
                HashSet<DateTime> holidayList = GetHolidays(year);
                holidays.UnionWith(holidayList);
            }

            for (var dt = dateFrom; dt <= dateTo; dt = dt.AddDays(1))

            {if ((dt.DayOfWeek == DayOfWeek.Saturday) || (dt.DayOfWeek == DayOfWeek.Sunday))
                continue;
            else
                businessDaysSet.Add(dt);
            }
            
 
            List<DateTime> businessDays = businessDaysSet.Except(holidays).ToList();
            businessDays.Sort((a,b)=>a.CompareTo(b));
            return businessDays;

        }
    IEnumerator LoadTagCoroutine(string id, string sceneName, string tagName)
    {
        var before = new HashSet<GameObject>((GameObject[])GameObject.FindObjectsOfType(typeof(GameObject)));
        Application.LoadLevelAdditive(sceneName);

        yield return new WaitForEndOfFrame();

        var after = new HashSet<GameObject>((GameObject[])GameObject.FindObjectsOfType(typeof(GameObject)));
        var newObjects = after.Except(before).ToList();
        var destroy = newObjects.Where (arg => arg.tag != tagName).ToArray();

        foreach(var i in destroy)
        {
            var parent = i.transform.parent;
            while(parent && parent.tag != tagName)
            {
                parent = parent.transform.parent;
            }

            if(parent)
                continue;

            GameObject.DestroyImmediate(i);
        }
        newObjects.RemoveAll((obj) => !obj);

        Group.AddToGroup(id, newObjects);
    }
Example #5
0
        public void AllValuesInArrayAreIndexed()
        {
            var coll = GetCollection();

            // Make sure property Tags is indexed
            coll.Indices.EnsureIndex("Tags");

            // Insert something where Tags is list of values
            const string key = "a key of some sort";
            var values = new HashSet<object> {"A", "B", DateTime.Now, null, Math.PI};
            coll.Update(key, new {Tags = values});

            // Now, extract what the index really contains
            var indexContent = new List<KeyValuePair<IndexValue, string>>();
            coll.Indices.VisitIndex("Tags", indexContent.Add);

            // First of all, each index entry must point to our key
            foreach (var kv in indexContent)
            {
                Assert.AreEqual(key, kv.Value);
            }

            // Second, the index should contain the array values
            var indexValues = new HashSet<object>(indexContent.Select(kv => kv.Key.Value));

            Assert.AreEqual(0, indexValues.Except(values).Count(), "Index values are too many");
            Assert.AreEqual(0, values.Except(indexValues).Count(), "Index values are too feew");
        }
Example #6
0
        public DiffResult DiffInputs(CompilerIO other)
        {
            var myInputSet = new HashSet<string>(Inputs);
            var otherInputSet = new HashSet<string>(other.Inputs);

            var additions = myInputSet.Except(otherInputSet);
            var deletions = otherInputSet.Except(myInputSet);

            return new DiffResult(additions, deletions);
        }
    IEnumerator LoadCoroutine(string id, string sceneName)
    {
        var before = new HashSet<GameObject>((GameObject[])GameObject.FindObjectsOfType(typeof(GameObject)));
        Application.LoadLevelAdditive(sceneName);

        yield return 0;

        var after = new HashSet<GameObject>((GameObject[])GameObject.FindObjectsOfType(typeof(GameObject)));
        var newObjects = after.Except(before).ToList();
        Group.AddToGroup(id, newObjects);
    }
Example #8
0
    /// <summary>
    /// 检查要设置的值是否存在于候选值列表中
    /// </summary>
    /// <param name="values">所要设置的值</param>
    /// <param name="message">若不能设置,获取错误信息</param>
    /// <returns>是否可以设置</returns>
    protected virtual bool CanSetValues( HashSet<string> values, out string message )
    {
      var invalidValue = values.Except( CandidateValues ).FirstOrDefault();

      if ( invalidValue != null && !Form.Configuration.IgnoreInvailidValuesInGroupControl )//如果有一个设置的值不在候选值列表
      {
        message = string.Format( "不能对控件设置值 \"{0}\"", invalidValue.First() );
        return false;
      }

      message = null;
      return true;
    }
Example #9
0
        public void Run(Action<string> emitError, Action<string> emitWarning, Ruleset rules)
        {
            foreach (var actorInfo in rules.Actors)
            {
                if (actorInfo.Key.StartsWith("^", StringComparison.Ordinal))
                    continue;

                var granted = new HashSet<string>();
                var consumed = new HashSet<string>();

                foreach (var trait in actorInfo.Value.TraitInfos<ITraitInfo>())
                {
                    var fieldConsumed = trait.GetType().GetFields()
                        .Where(x => x.HasAttribute<ConsumedConditionReferenceAttribute>())
                        .SelectMany(f => LintExts.GetFieldValues(trait, f, emitError));

                    var propertyConsumed = trait.GetType().GetProperties()
                        .Where(x => x.HasAttribute<ConsumedConditionReferenceAttribute>())
                        .SelectMany(p => LintExts.GetPropertyValues(trait, p, emitError));

                    var fieldGranted = trait.GetType().GetFields()
                        .Where(x => x.HasAttribute<GrantedConditionReferenceAttribute>())
              					.SelectMany(f => LintExts.GetFieldValues(trait, f, emitError));

                    var propertyGranted = trait.GetType().GetProperties()
                        .Where(x => x.HasAttribute<GrantedConditionReferenceAttribute>())
              					.SelectMany(f => LintExts.GetPropertyValues(trait, f, emitError));

                    foreach (var c in fieldConsumed.Concat(propertyConsumed))
                        if (!string.IsNullOrEmpty(c))
                            consumed.Add(c);

                    foreach (var g in fieldGranted.Concat(propertyGranted))
                        if (!string.IsNullOrEmpty(g))
                            granted.Add(g);
                }

                var unconsumed = granted.Except(consumed);
                if (unconsumed.Any())
                    emitWarning("Actor type `{0}` grants conditions that are not consumed: {1}".F(actorInfo.Key, unconsumed.JoinWith(", ")));

                var ungranted = consumed.Except(granted);
                if (ungranted.Any())
                    emitError("Actor type `{0}` consumes conditions that are not granted: {1}".F(actorInfo.Key, ungranted.JoinWith(", ")));

                if ((consumed.Any() || granted.Any()) && actorInfo.Value.TraitInfoOrDefault<UpgradeManagerInfo>() == null)
                    emitError("Actor type `{0}` defines conditions but does not include an UpgradeManager".F(actorInfo.Key));
            }
        }
Example #10
0
        public ActionResult Refresh()
        {
            var directory = HostingEnvironment.VirtualPathProvider.GetDirectory( VirtualPathUtility.ToAbsolute( templatePath ) );

              var data = new HashSet<string>( dbUtility.Data( "SELECT virtualPath FROM Templates " ).Column<string>(), StringComparer.OrdinalIgnoreCase );

              var local = new HashSet<string>( SearchFiles( directory ).Select( f => VirtualPathUtility.ToAppRelative( f.VirtualPath ) ) );

              foreach ( var virtualPath in local.Except( data ) )
            dbUtility.NonQuery( "INSERT INTO Templates ( virtualPath ) VALUES ( {0} )", virtualPath );

              foreach ( var virtualPath in data.Except( local ) )
            dbUtility.NonQuery( "DELETE Templates WHERE virtualPath = {0}", virtualPath );

              return RedirectToAction( "List" );
        }
Example #11
0
        public static void Update()
        {
            currentState = Keyboard.GetState();

            HashSet <Keys> currentKeySet = new HashSet <Keys> (currentState.GetPressedKeys());
            IEnumerable <Keys> pressedKeys = currentKeySet.Except(previousKeySet);
            IEnumerable <Keys> releasedKeys = previousKeySet.Except(currentKeySet);

            if (pressedKeys.Count() > 0) {
                FireKeyPressed(new KeyEvent(pressedKeys));
            }

            if (releasedKeys.Count() > 0) {
                FireKeyReleased(new KeyEvent(releasedKeys));
            }

            previousKeySet = currentKeySet;
            previousState = currentState;
        }
Example #12
0
        public static void AllStatesCanBeReached(IEnumerable<State> states)
        {
            var allStates = new HashSet<State>(states);

            var visitedStates = new HashSet<State>();
            TraverseStateGraph(states.First(), visitedStates);

            var unreachableStates = allStates.Except(visitedStates).ToList();

            if (unreachableStates.Count != 0)
            {
                Console.WriteLine("Unreachable states:");
                foreach (var unreachableState in unreachableStates)
                {
                    Console.WriteLine(unreachableState.Name);
                }
            }

            Assert.Equal(allStates.Count, visitedStates.Count);
        }
    // cross check /Resources/Prefabs and Levels.xml if there are any item prefabs that exist only in one but not the other
    public void crossCheck()
    {
        // create a two sets of prefabs
        HashSet<string> resPrefabSet = new HashSet<string>();
        HashSet<string> xmlPrefabSet = new HashSet<string>();

        // Get prefabs from Levels.xml
        getLevelPrefabs(xmlPrefabSet);

        // Get prefabs from the /Resources/Prefabs folder
        getResPrefabs(resPrefabSet);

        // Cross checks
        foreach (string prefab in xmlPrefabSet.Except(resPrefabSet).ToList())
            Debug.LogError(prefab + " is missing in the /Resorces/Prefabs folder but used in Levels.xml");

        foreach (string prefab in resPrefabSet.Except(xmlPrefabSet).ToList())
            Debug.Log(prefab + " exists in the /Resorces/Prefabs folder but not used in Levels.xml");

        Debug.Log("Cross Check Done");
    }
 public void AssertNumberOfResultsIsConsistentOnRecompile(IEnumerable<IViewComputationResultModel> results)
 {
     HashSet<Tuple<string, ValueSpecification>> values = null;
     foreach (var result in results)
     {
         Assert.NotNull(result);
         var newValues = new HashSet<Tuple<string, ValueSpecification>>(result.AllResults.Select(r => Tuple.Create(r.CalculationConfiguration, r.ComputedValue.Specification)));
         if (values != null)
         {
             if (!values.SetEquals(newValues))
             {
                 var missing = values.Except(newValues).ToList();
                 var added = newValues.Except(values).ToList();
                 throw new Exception(string.Format("Previously missing {0} results, now {1}. Missing {2}. Added {3}", values.Count, newValues.Count, String.Join(",", missing), String.Join(",", added)));
             }
         }
         else
         {
             values = newValues;
         }
     }
 }
        public void Should_Return_All_Metadata_From_Metadata_Repository_OnGet()
        {
            // Arrange
            var queryableList = this.ConstructQueryableList();
            MetadataController controller = new MetadataController();
            var metadataRepositoryMock = new Mock<IMetadataRepository>();
            metadataRepositoryMock.Setup(x => x.GetAll()).Returns(queryableList).Verifiable();
            controller.MetadataRepository = metadataRepositoryMock.Object;

            // Act
            var actionResult = controller.Get();

            // Assert
            GenericValueResult<IEnumerable<Models.MetadataInfo>> results = actionResult as GenericValueResult<IEnumerable<Models.MetadataInfo>>;
            results.Should().NotBeNull("Wrong data type was returned from the controller");
            results.Value.Count().Should().Be(queryableList.Count());

            HashSet<int> receivedIds = new HashSet<int>(results.Value.Select(x => x.Id.Value).AsEnumerable());
            HashSet<int> expectedIds = new HashSet<int>(queryableList.Select(x => x.Id).AsEnumerable());
            expectedIds.Except(receivedIds).Count().Should().Be(0, "Result list should contain all the same IDs as the list in Repository");

            metadataRepositoryMock.VerifyAll();
        }
Example #16
0
        public ActionResult _RegisterPushTargets(int topicID, Dictionary<int, bool> users)
        {
            var topic = db.Topics.Find(topicID);
            if (topic.IsReadOnly)
                return HTTPStatus(HttpStatusCode.Forbidden, "Das Thema ist schreibgeschützt.");

            var desired = new HashSet<int>(users.Where(kvp => kvp.Value).Select(kvp => kvp.Key));
            var actual = new HashSet<int>(db.PushNotifications.Where(pn => pn.TopicID == topicID).Select(pn => pn.UserID));

            foreach (var userID in desired.Except(actual))
                db.PushNotifications.Add(new PushNotification
                {
                    TopicID = topicID,
                    UserID = userID
                });

            foreach (var userID in actual.Except(desired))
                db.PushNotifications.RemoveRange(db.PushNotifications.Where(pn => pn.TopicID == topicID && pn.UserID == userID));

            db.SaveChanges();

            return _EditListTopic(topic);
        }
		private string GetNewClonedDirectoryOrNulIfNoneCloned(IEnumerable<string> directoriesThatExistedBeforeCloning)
		{
			var dirs = new HashSet<string>(Directory.GetDirectories(_repoHoldingFolder));
			return dirs.Except(directoriesThatExistedBeforeCloning).FirstOrDefault();
		}
        private void GetReferences(JObject lockFile)
        {
            var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: false);
            var frameworkReferences = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            var fileNamesOfRegularReferences = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (var package in GetPackagesFromTarget(lockFile, target))
            {
                foreach (var referenceItem in CreateItems(package, NuGetAssetTypeCompile, includePdbs: false))
                {
                    _references.Add(referenceItem);

                    fileNamesOfRegularReferences.Add(Path.GetFileNameWithoutExtension(referenceItem.ItemSpec));
                }

                if (IncludeFrameworkReferences)
                {
                    var frameworkAssembliesArray = package.TargetObject["frameworkAssemblies"] as JArray;
                    if (frameworkAssembliesArray != null)
                    {
                        foreach (var frameworkAssembly in frameworkAssembliesArray.OfType<JToken>())
                        {
                            frameworkReferences.Add((string)frameworkAssembly);
                        }
                    }
                }
            }

            foreach (var frameworkReference in frameworkReferences.Except(fileNamesOfRegularReferences, StringComparer.OrdinalIgnoreCase))
            {
                var item = new TaskItem(frameworkReference);
                item.SetMetadata(NuGetIsFrameworkReference, "true");
                item.SetMetadata(NuGetSourceType, NuGetSourceType_Package);
                _references.Add(item);
            }
        }
        void TestFindReferences(IEntity entity)
        {
            if (IgnoreEntity(entity))
                return;
            FindReferences fr = new FindReferences();
            fr.FindTypeReferencesEvenIfAliased = true;

            Stopwatch w = new Stopwatch();
            var searchScopes = fr.GetSearchScopes(entity);
            foreach (var project in solution.Projects) {
                w.Restart();
                HashSet<AstNode> foundReferences = new HashSet<AstNode>();
                var interestingFiles = new HashSet<CSharpFile>();
                foreach (var searchScope in searchScopes) {
                    foreach (var unresolvedFile in fr.GetInterestingFiles(searchScope, project.Compilation)) {
                        var file = project.Files.Single(f => f.FileName == unresolvedFile.FileName);
                        Debug.Assert(file.UnresolvedTypeSystemForFile == unresolvedFile);

                        // Skip file if it doesn't contain the search term
                        if (searchScope.SearchTerm != null && file.OriginalText.IndexOf(searchScope.SearchTerm, StringComparison.Ordinal) < 0)
                            continue;

                        interestingFiles.Add(file);
                    }
                }
                foreach (var file in interestingFiles) {
                    fr.FindReferencesInFile(searchScopes, file.UnresolvedTypeSystemForFile, file.SyntaxTree, project.Compilation,
                                            delegate(AstNode node, ResolveResult result) {
                                                foundReferences.Add(node);
                                            }, CancellationToken.None);
                }
                w.Stop();
                if (timings.ContainsKey(entity.EntityType)) {
                    timings[entity.EntityType] += w.Elapsed;
                } else {
                    timings[entity.EntityType] = w.Elapsed;
                }

                IEntity importedEntity = project.Compilation.Import(entity);

                HashSet<AstNode> expectedReferences;
                if (importedEntity == null || !referenceDict.TryGetValue(importedEntity, out expectedReferences)) {
                    if (foundReferences.Any()) {
                        // There aren't any expected references stored, but we found some references anyways:
                        Console.WriteLine();
                        Console.WriteLine("Entity not in reference dictionary: " + entity);
                    }
                    return;
                }
                if (foundReferences.Except(expectedReferences).Any()) {
                    Console.WriteLine();
                    Console.WriteLine("Reference mismatch for " + entity + ":");
                    var n = foundReferences.Except(expectedReferences).First();
                    Console.WriteLine("Found unexpected reference " + n + " (" + n.GetRegion() + ")");
                }
                if (expectedReferences.Except(foundReferences).Any()) {
                    Console.WriteLine();
                    Console.WriteLine("Reference mismatch for " + entity + ":");
                    var n = expectedReferences.Except(foundReferences).First();
                    Console.WriteLine("Did not find expected reference " + n + " (" + n.GetRegion() + ")");
                }
            }

            if (entityCount.ContainsKey(entity.EntityType)) {
                entityCount[entity.EntityType]++;
            } else {
                entityCount[entity.EntityType] = 1;
            }
        }
		List<ILNode> FindLoops(HashSet<ControlFlowNode> scope, ControlFlowNode entryPoint, bool excludeEntryPoint)
		{
			List<ILNode> result = new List<ILNode>();
			
			// Do not modify entry data
			scope = new HashSet<ControlFlowNode>(scope);
			
			Queue<ControlFlowNode> agenda  = new Queue<ControlFlowNode>();
			agenda.Enqueue(entryPoint);
			while(agenda.Count > 0) {
				ControlFlowNode node = agenda.Dequeue();
				
				// If the node is a loop header
				if (scope.Contains(node)
				    && node.DominanceFrontier.Contains(node)
				    && (node != entryPoint || !excludeEntryPoint))
				{
					HashSet<ControlFlowNode> loopContents = FindLoopContent(scope, node);
					
					// If the first expression is a loop condition
					ILBasicBlock basicBlock = (ILBasicBlock)node.UserData;
					ILExpression condExpr;
					ILLabel trueLabel;
					ILLabel falseLabel;
					// It has to be just brtrue - any preceding code would introduce goto
					if(basicBlock.MatchSingleAndBr(ILCode.Brtrue, out trueLabel, out condExpr, out falseLabel))
					{
						ControlFlowNode trueTarget;
						labelToCfNode.TryGetValue(trueLabel, out trueTarget);
						ControlFlowNode falseTarget;
						labelToCfNode.TryGetValue(falseLabel, out falseTarget);
						
						// If one point inside the loop and the other outside
						if ((!loopContents.Contains(trueTarget) && loopContents.Contains(falseTarget)) ||
						    (loopContents.Contains(trueTarget) && !loopContents.Contains(falseTarget)) )
						{
							loopContents.RemoveOrThrow(node);
							scope.RemoveOrThrow(node);
							
							// If false means enter the loop
							if (loopContents.Contains(falseTarget) || falseTarget == node)
							{
								// Negate the condition
								condExpr = new ILExpression(ILCode.LogicNot, null, condExpr);
								ILLabel tmp = trueLabel;
								trueLabel = falseLabel;
								falseLabel = tmp;
							}
							
							ControlFlowNode postLoopTarget;
							labelToCfNode.TryGetValue(falseLabel, out postLoopTarget);
							if (postLoopTarget != null) {
								// Pull more nodes into the loop
								HashSet<ControlFlowNode> postLoopContents = FindDominatedNodes(scope, postLoopTarget);
								var pullIn = scope.Except(postLoopContents).Where(n => node.Dominates(n));
								loopContents.UnionWith(pullIn);
							}
							
							// Use loop to implement the brtrue
							basicBlock.Body.RemoveTail(ILCode.Brtrue, ILCode.Br);
							basicBlock.Body.Add(new ILWhileLoop() {
								Condition = condExpr,
								BodyBlock = new ILBlock() {
									EntryGoto = new ILExpression(ILCode.Br, trueLabel),
									Body = FindLoops(loopContents, node, false)
								}
							});
							basicBlock.Body.Add(new ILExpression(ILCode.Br, falseLabel));
							result.Add(basicBlock);
							
							scope.ExceptWith(loopContents);
						}
					}
					
					// Fallback method: while(true)
					if (scope.Contains(node)) {
						result.Add(new ILBasicBlock() {
							Body = new List<ILNode>() {
								new ILLabel() { Name = "Loop_" + (nextLabelIndex++) },
								new ILWhileLoop() {
									BodyBlock = new ILBlock() {
										EntryGoto = new ILExpression(ILCode.Br, (ILLabel)basicBlock.Body.First()),
										Body = FindLoops(loopContents, node, true)
									}
								},
							},
						});
						
						scope.ExceptWith(loopContents);
					}
				}

				// Using the dominator tree should ensure we find the the widest loop first
				foreach(var child in node.DominatorTreeChildren) {
					agenda.Enqueue(child);
				}
			}
			
			// Add whatever is left
			foreach(var node in scope) {
				result.Add((ILNode)node.UserData);
			}
			scope.Clear();
			
			return result;
		}
        /// <summary>
        /// Given a list of symbols, determine which are not recommended at the same position in linked documents.
        /// </summary>
        /// <param name="expectedSymbols">The symbols recommended in the active context.</param>
        /// <param name="linkedContextSymbolLists">The symbols recommended in linked documents</param>
        /// <returns>The list of projects each recommended symbol did NOT appear in.</returns>
        protected Dictionary<ISymbol, List<ProjectId>> FindSymbolsMissingInLinkedContexts(HashSet<ISymbol> expectedSymbols, IEnumerable<Tuple<DocumentId, AbstractSyntaxContext, IEnumerable<ISymbol>>> linkedContextSymbolLists)
        {
            var missingSymbols = new Dictionary<ISymbol, List<ProjectId>>(LinkedFilesSymbolEquivalenceComparer.IgnoreAssembliesInstance);

            foreach (var linkedContextSymbolList in linkedContextSymbolLists)
            {
                var symbolsMissingInLinkedContext = expectedSymbols.Except(linkedContextSymbolList.Item3, LinkedFilesSymbolEquivalenceComparer.IgnoreAssembliesInstance);
                foreach (var missingSymbol in symbolsMissingInLinkedContext)
                {
                    missingSymbols.GetOrAdd(missingSymbol, (m) => new List<ProjectId>()).Add(linkedContextSymbolList.Item1.ProjectId);
                }
            }

            return missingSymbols;
        }
Example #22
0
        void HandleNewTerrainsAndObjects()
        {
            m_oldKnownLocations = m_newKnownLocations;
            m_newKnownLocations = CollectLocations();

            m_oldKnownObjects = m_newKnownObjects;
            m_newKnownObjects = CollectObjects(m_newKnownLocations);

            var revealedLocations = m_newKnownLocations.Except(m_oldKnownLocations);
            var revealedObjects = m_newKnownObjects.Except(m_oldKnownObjects);

            SendNewTerrains(revealedLocations);
            SendNewObjects(revealedObjects);
        }
Example #23
0
 private static void TraceToSource(Bus FromBus, Bus BusThatStartedItAll, HashSet<Bus> busesInThisTrace, HashSet<Bus> busesOnPath)
 {
     //start at FromBus, take a step away from FromBus.
     //If we're at the source, add the path that we took to BusesOnRouteToSource.
     //If we're at a dead-end, then stop tracing this branch.
     //If we hit a bus that's already on the route, then terminate and add the branch.
     var connectedBuses = FromBus.ConnectedTo.OfType<Line>().Select(line => line.ConnectedTo.OfType<Bus>().Except(FromBus.Yield()).Single()) //all the buses neighbouring this one
         .Except(busesInThisTrace) //exclude any buses we've already touched in this trace
         ;
     foreach (var bus in connectedBuses)
     {
         if (busesOnPath.Contains(bus)) //we're connected to the target bus. no further processing required on this branch.
         {
             busesOnPath.UnionWith(busesInThisTrace.Except(BusThatStartedItAll.Yield()));
             continue;
         }
         else
         {
             //keep searching!
             HashSet<Bus> NextStepTraceList;
             if (connectedBuses.Count() == 1) //if this is the only possible way forward, then just keep using the same thingy.
             {
                 NextStepTraceList = busesInThisTrace;
             }
             else
             {
                 NextStepTraceList = new HashSet<Bus>(busesInThisTrace);
             }
             NextStepTraceList.Add(bus);
             TraceToSource(bus, BusThatStartedItAll, NextStepTraceList, busesOnPath);
         }
     }
 }
        private string[] GetMissingModules(HashSet<string> existingDatabase) {
            var searchPaths = PythonTypeDatabase.GetCachedDatabaseSearchPaths(DatabasePath);

            if (searchPaths == null) {
                // No cached search paths means our database is out of date.
                return existingDatabase
                    .Except(RequiredBuiltinModules)
                    .OrderBy(name => name, StringComparer.InvariantCultureIgnoreCase)
                    .ToArray();
            }
            
            return PythonTypeDatabase.GetDatabaseExpectedModules(_config.Version, searchPaths)
                .SelectMany()
                .Select(mp => mp.ModuleName)
                .Concat(RequiredBuiltinModules)
                .Where(m => !existingDatabase.Contains(m))
                .OrderBy(name => name, StringComparer.InvariantCultureIgnoreCase)
                .ToArray();
        }
Example #25
0
        /// <summary>
        /// Resyncs the user with our view of the neighbors
        /// </summary>
        /// <param name="newDrawDistance">The new DD for the user</param>
        /// <param name="resyncDelay">Delay before executing the resync. We  delay on a region crossing because the viewer locks up sometimes when freeing memory</param>
        /// <returns></returns>
        private async Task CalculateAndResyncNeighbors(uint newDrawDistance, int resyncDelay)
        {
            uint xmin, xmax, ymin, ymax;

            Util.GetDrawDistanceBasedRegionRectangle((uint)newDrawDistance, _scene.RegionInfo.RegionLocX,
                _scene.RegionInfo.RegionLocY, out xmin, out xmax, out ymin, out ymax);

            //get our current neighbor list
            List<SimpleRegionInfo> knownNeighborsList = _scene.SurroundingRegions.GetKnownNeighborsWithinClientDD(newDrawDistance);
            Dictionary<ulong, SimpleRegionInfo> knownNeighborsDict = new Dictionary<ulong, SimpleRegionInfo>();
            foreach (var neighbor in knownNeighborsList)
            {
                knownNeighborsDict.Add(neighbor.RegionHandle, neighbor);
            }

            HashSet<ulong> knownNeighbors = new HashSet<ulong>(knownNeighborsList.Select(x => x.RegionHandle));

            List<ulong> deadRegions;
            List<ulong> newRegions;

            lock (_remotePresences)
            {
                //check the list of what we have vs what we should have
                HashSet<ulong> usersRegions = new HashSet<ulong>();

                //add all regions from the presence
                foreach (var presence in _remotePresences.Values)
                {
                    knownNeighborsDict[presence.PresenceInfo.RegionInfo.RegionHandle] = presence.PresenceInfo.RegionInfo;

                    //dont put far regions into this update, they shouldnt be dropped by DD changes
                    if (!presence.IsFarPresence)
                    {
                        usersRegions.Add(presence.PresenceInfo.RegionInfo.RegionHandle);
                    }
                }

                // regions that we have but that we shouldnt have anymore
                deadRegions = new List<ulong>(usersRegions.Except(knownNeighbors));
                // regions that we don't have that we need to add
                newRegions = new List<ulong>(knownNeighbors.Except(usersRegions));
            }

            try
            {
                await _operationSemaphore.WaitAsync();
                if (resyncDelay > 0) await Task.Delay(resyncDelay);
                await this.ResyncRegions(knownNeighborsDict, deadRegions, newRegions);
            }
            finally
            {
                _operationSemaphore.Release();
            }
        }
Example #26
0
		void VerifyChanges(ICmObject[] expectedNewbies, ICmObject[] expectedDirtballs,
			ICmObjectId[] expectedGoners, IUnitOfWorkService m_uowService)
		{
			var newbies = new HashSet<ICmObjectId>();
			var dirtballs = new HashSet<ICmObjectOrSurrogate>(new ObjectSurrogateEquater());
			var goners = new HashSet<ICmObjectId>();
			m_uowService.GatherChanges(newbies, dirtballs, goners);
			var setNewbies = new HashSet<ICmObjectId>(from obj in expectedNewbies select obj.Id);
			Assert.That(newbies.Except(setNewbies), Is.Empty, "some unexpected newbies were found");
			Assert.That(setNewbies.Except(newbies), Is.Empty, "some expected newbies were not found");
			var setDirtballs = new HashSet<ICmObjectOrSurrogate>(expectedDirtballs.Cast<ICmObjectOrSurrogate>());
			Assert.That(dirtballs.Except(setDirtballs), Is.Empty, "some unexpected dirtballs were found");
			Assert.That(setDirtballs.Except(dirtballs), Is.Empty, "some expected dirtballs were not found");
			var setGoners = new HashSet<ICmObjectId>(expectedGoners);
			Assert.That(goners.Except(setGoners), Is.Empty, "some unexpected goners were found");
			Assert.That(setGoners.Except(goners), Is.Empty, "some expected goners were not found");
		}
Example #27
0
 /// <summary>
 /// 求两个Hash集合的差集(不改变原集合)
 /// 将返回其不在 second 中的元素
 /// 注释:Except方法是IEnumrable的方法,也可用于List等
 /// </summary>
 /// <param name="first"></param>
 /// <param name="compararSet"></param>
 /// <returns></returns>
 public static IList<int> setExcept(HashSet<int> first, HashSet<int> second)
 {
     return first.Except<int>(second).ToList<int>();
 }
        private void GetReferences(JObject lockFile)
        {
            var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: false);
            var frameworkReferences = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            var fileNamesOfRegularReferences = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (var package in target)
            {
                var packageNameParts = package.Key.Split('/');
                var packageName = packageNameParts[0];
                var packageVersion = packageNameParts[1];


                Log.LogMessageFromResources(MessageImportance.Low, "ResolvedReferencesFromPackage", packageName);

                foreach (var referenceItem in CreateItems(packageName, packageVersion, package.Value, NuGetAssetTypeCompile))
                {
                    _references.Add(referenceItem);

                    fileNamesOfRegularReferences.Add(Path.GetFileNameWithoutExtension(referenceItem.ItemSpec));
                }

                if (IncludeFrameworkReferences)
                {
                    var frameworkAssembliesArray = package.Value["frameworkAssemblies"] as JArray;
                    if (frameworkAssembliesArray != null)
                    {
                        foreach (var frameworkAssembly in frameworkAssembliesArray.OfType<JToken>())
                        {
                            frameworkReferences.Add((string)frameworkAssembly);
                        }
                    }
                }
            }

            foreach (var frameworkReference in frameworkReferences.Except(fileNamesOfRegularReferences, StringComparer.OrdinalIgnoreCase))
            {
                _references.Add(new TaskItem(frameworkReference));
            }
        }
Example #29
0
		public void Compare(TextWriter writer)
		{
			var newFiles = new HashSet<string>(Directory.GetFiles(newDir, "*.dbc").Select((file) => new FileInfo(file).Name), 
			                                   StringComparer.InvariantCultureIgnoreCase);

			var oldFiles = new HashSet<string>(Directory.GetFiles(oldDir, "*.dbc").Select((file) => new FileInfo(file).Name),
			                                   StringComparer.InvariantCultureIgnoreCase);

			var addedFiles = newFiles.Except(oldFiles);

			var removedFiles = oldFiles.Except(newFiles);

			var existingFiles = newFiles.Except(addedFiles);

			if (addedFiles.Count() > 0)
			{
				writer.WriteLine("{0} files have been added:", addedFiles.Count());
				foreach (var file in addedFiles)
				{
					writer.WriteLine("\t" + new FileInfo(file).Name);
					var reader = new DBCReader(Path.Combine(newDir, file));
					writer.WriteLine("\t\tColumn Count: " + reader.ColumnCount);
					writer.WriteLine("\t\tRow Count: " + reader.RecordCount);
					writer.WriteLine("\t\tHas Strings: " + reader.HasStrings);
					if (reader.IrregularColumnSize)
					{
						writer.WriteLine("\t\tColumn Size IRREGULAR!");
					}
				}
			}

			if (removedFiles.Count() > 0)
			{
				writer.WriteLine("{0} files have been deprecated (not present anymore):", removedFiles.Count());
				foreach (var file in addedFiles)
				{
					writer.WriteLine("\t" + new FileInfo(file).Name);
				}
			}

			writer.WriteLine();
			writer.WriteLine("#######################################");
			writer.WriteLine("Changes in files{0}:", maxTestAmount != int.MaxValue ? " - Testing with first " + maxTestAmount + " rows" : "");
			writer.WriteLine();

			foreach (var file in existingFiles)
			{
				var comparer = new DBCFileComparer(Path.Combine(oldDir, file), Path.Combine(newDir, file), maxTestAmount, null);
				if (comparer.NewReader.IrregularColumnSize)
				{
					writer.WriteLine("Skipping {0} (IRREGULAR Column Size)", file);
				}
				else if (comparer.NewReader.ColumnCount != comparer.OldReader.ColumnCount &&
				         (comparer.NewReader.ColumnCount < 2 || comparer.OldReader.ColumnCount < 2))
				{
					writer.WriteLine("Skipping {0} (Only 1 column or less)", file);
				}
				else
				{
					comparer.Compare(writer);
				}
			}
		}
            public void UpdateNotifications(Domain.Entity.Mill.Pipe pipeSavingState)
            {
                if (isProperlyCreated)
                {
                    //* What can happen at Save Pipe: (NRO - non required inspection operation)
                    //* - pipe is new and have no previous state (to update: NROs from current size type(new))
                    if (initialPipeSizeTypeId == Guid.Empty)
                    {
                        ProcessPipeTestResults(pipeSavingState.PipeTestResult);
                        ProcessNROForPipeSizeType(pipeSavingState.Type.Id, pipeSavingState, NROWhatToDo.Add);
                    }

                    //* - pipe is existing and pipe size type changed (to update: NROs from previous size type(remove), NROs from current size type(new))
                    else if(pipeSavingState.Type == null || initialPipeSizeTypeId != pipeSavingState.Type.Id)
                    {
                        //update notification for old size type
                        IList<Guid> removeId = new List<Guid>();

                        foreach (TestResultInfo t in initialTestResultList)
                        {
                            removeId.Add(t.OperationId);
                        }
                        removeId.Distinct();
                        foreach (Guid id in removeId)
                        {
                            manager.UpdateUnits(id);
                        }

                        foreach (Guid id in manager.cache.EnumerateOperationsForSizeType(initialPipeSizeTypeId))
                        {
                            manager.cache.RemoveUnits(id, ChooseUnit(manager.cache.GetMeasure(id)));
                            UpdateNotification(id);
                        }

                        //update notification for new size type
                        ProcessPipeTestResults(pipeSavingState.PipeTestResult);
                        foreach (Guid id in manager.cache.EnumerateOperationsForSizeType(pipeSavingState.Type.Id))
                        {
                            manager.cache.AddUnits(id, ChooseUnit(manager.cache.GetMeasure(id), pipeSavingState));
                            UpdateNotification(id);
                        }
                    }

                    //* - pipe is existing and operations were edited (to update: NROs from current size type(track changes))
                    else if (initialPipeSizeTypeId == pipeSavingState.Type.Id)
                    {
                        HashSet<NROInfo> initialState = new HashSet<NROInfo>();
                        initialState.UnionWith(initialNROList);
                        HashSet<NROInfo> savingState = new HashSet<NROInfo>();
                        savingState.UnionWith(GetNROInfoListFromPipeTestResultList(pipeSavingState.PipeTestResult));

                        var resultList = savingState.Except(initialState);
                        foreach (NROInfo result in resultList.Distinct())
                        {
                            if (result.IsCompleted)
                            {
                                manager.UpdateUnits(result.OperationId); 
                            }
                        }

                        ProcessNROForPipeSizeType(pipeSavingState.Type.Id, pipeSavingState, NROWhatToDo.EditOperations);
                    }

                    //* - pipe deactivation (to update: NRO (remove))
                    else if (!pipeSavingState.IsActive)
                    {
                        ProcessPipeTestResults(pipeSavingState.PipeTestResult);
                        ProcessNROForPipeSizeType(pipeSavingState.Type.Id, pipeSavingState, NROWhatToDo.Remove);
                    }
                }
                NotificationService.Instance.NotifyInterested();
                SavePipeState(pipeSavingState);
            }