示例#1
0
        static void Main(string[] args)
        {
            /* The words of the dictionary this evil hangman example works with are supplied in the linear array below.
             * For a more sophisticated implementation loading from an external file is obviously possible, but the idea here
             * was to provide a simple solution to the problem, so beginner programmers could understand how they could solve
             * it themselves.
             */
            string[] dict = {"bakalava", "balamata", "balerina", "balirina", "baniceta", "kalotina", "kolibata", "korubata"};
            HashSet<string> words = new HashSet<string>(dict);
            char[] seq = {'l', 'r', 'i', 'o', 'e', 'n', 'm', 'k', 'v', 't', 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'p', 'r', 's', 'u', 'w', 'x', 'y', 'z'};
            HashSet<char> toGuess = new HashSet<char>(seq);
            Random rand = new Random();
            Console.WriteLine("Pick a word: (1-" + words.Count + ")");
            int ind = int.Parse(Console.ReadLine());

            Console.WriteLine("The word you chose is " + answer + ". Let's see whether the computer can guess it...");
            answer = dict[ind - 1];

            guessed.Add(answer[0]);
            guessed.Add(answer[answer.Length - 1]);

            while (words.Count != 1)
            {
                words.RemoveWhere(Remover);
                PrintGuessed(guessed);
                Console.WriteLine(string.Join(", ", words));
                guessed.Add(toGuess.First());
                toGuess.Remove(toGuess.First());
            }
            Console.WriteLine("The word is: " + words.First());
            Console.ReadLine();
        }
示例#2
0
        private static HashSet<Point> GetFreePointsInRange(Point pivotPoint)
        {
            // The 8 points below are the 8 possible moves of a horse if is not near the end of a board
            Point topRight = new Point(pivotPoint.Row + 2, pivotPoint.Col + 1);
            Point topLeft = new Point(pivotPoint.Row + 2, pivotPoint.Col - 1);
            Point rightUpper = new Point(pivotPoint.Row + 1, pivotPoint.Col + 2);
            Point rightLower = new Point(pivotPoint.Row - 1, pivotPoint.Col + 2);
            Point leftUpper = new Point(pivotPoint.Row + 1, pivotPoint.Col - 2);
            Point leftLower = new Point(pivotPoint.Row - 1, pivotPoint.Col - 2);
            Point bottomRight = new Point(pivotPoint.Row - 2, pivotPoint.Col + 1);
            Point bottomLeft = new Point(pivotPoint.Row - 2, pivotPoint.Col - 1);

            HashSet<Point> freePointsInRange = new HashSet<Point>()
            {
                topRight, topLeft,
                rightUpper, rightLower,
                leftUpper, leftLower,
                bottomRight, bottomLeft
            };

            // Removes each point that is out of the board or that has been visited
            freePointsInRange.RemoveWhere(x => x.Col < 0 ||
                                      x.Row < 0 ||
                                      x.Row >= matrix.GetLength(0) ||
                                      x.Col >= matrix.GetLength(1) ||
                                      matrix[x.Row, x.Col] != 0);

            return freePointsInRange;
        }
示例#3
0
 public void FilterEntities(BattleEntity sourceEntity, HashSet<BattleEntity> entities)
 {
     switch(mTargetParam) {
     case AISkillRule.ConditionTarget.ENEMY:
         entities.RemoveWhere(FilterEnemy);
         break;
     case AISkillRule.ConditionTarget.PC:
         entities.RemoveWhere(FilterPC);
         break;
     case AISkillRule.ConditionTarget.SELF:
         entities.RemoveWhere(delegate(BattleEntity obj) {
             return sourceEntity != obj;
         });
         break;
     }
 }
 public int LadderLength(string start, string end, string[] dict)
 {
     HashSet<string> hset = new HashSet<string>(dict);
     HashSet<string> currentStarts = new HashSet<string>() { start };
     int answer = 1;
     while (true)
     {
         hset.RemoveWhere(v => currentStarts.Contains(v));
         HashSet<string> nextStarts = new HashSet<string>();
         foreach (var starting in currentStarts)
         {
             if (starting == end)
             {
                 return answer;
             }
             GetValidMoves(starting, hset).ToList().ForEach(n => nextStarts.Add(n));
         }
         if (nextStarts.Count > 0)
         {
             answer++;
             currentStarts = nextStarts;
         }
         else
         {
             return 0;
         }
     }
 }
        public static int Circulars(int range)
        {
            int count = 0;
            HashSet<int> primes = new HashSet<int>();
            primes.UnionWith(Primes.primeRange(range));
            HashSet<string> stringprimes = new HashSet<string>();
            stringprimes.UnionWith(primes.Select<int, string>(x => x.ToString()));

            stringprimes.RemoveWhere(x => x.Contains('2') || x.Contains('4') || x.Contains('6') || x.Contains('8') || x.Contains('0'));

            foreach (string number in stringprimes) {
                string varnumber = number.Substring(0);
                bool allPrime = true;
                for (int i = 0; i < number.Length; i++) {
                    char c = varnumber.First<char>();
                    varnumber += c;
                    varnumber = varnumber.Remove(0, 1);
                    if (!primes.Contains(int.Parse(varnumber))) {
                        //Console.WriteLine(number);
                        allPrime = false;
                        break;
                    }
                }
                if (allPrime == true) {
                    count++;
                }
                allPrime = true;
            }
            return count + 1;
        }
        public void Execute()
        {
            var mask = new NodeMask();
            mask.Label = "Cycles";
            mask.IsShowMask = true;

            try
            {
                if (!myPresentation.Graph.Nodes.Any())
                {
                    return;
                }

                var unvisited = new HashSet<Node>(myPresentation.Graph.Nodes);
                unvisited.RemoveWhere(n => n.In.Count == 0 || n.Out.Count == 0);

                while (unvisited.Count > 0)
                {
                    var current = unvisited.First();
                    unvisited.Remove(current);

                    foreach (var node in FindCycles(unvisited, current, new HashSet<Node> { current }))
                    {
                        mask.Set(node);
                    }
                }
            }
            finally
            {
                var module = myPresentation.GetModule<INodeMaskModule>();
                module.Push(mask);
            }
        }
示例#7
0
        public static HashSet<Triangle> Shrink(HashSet<Triangle> set)
        {
            HashSet<Triangle> Shrunk = new HashSet<Triangle>(set);
            Shrunk.RemoveWhere(t => t.Neighbors.Any(i => !set.Contains(i)));

            return Shrunk;
        }
        public override string ToString()
        {
            if (OperationTypes == null || OperationTypes.Count == 0) return null;

            var uniqueTypes = new HashSet<Type>();
            var uniqueTypeNames = new List<string>();
            foreach (var type in OperationTypes)
            {
                foreach (var assemblyType in type.Assembly.GetTypes())
                {
                    if (assemblyType.GetCustomAttributes(typeof(DataContractAttribute), false).Length > 0)
                    {
                        var baseTypeWithSameName = XsdMetadata.GetBaseTypeWithTheSameName(assemblyType);
                        if (uniqueTypeNames.Contains(baseTypeWithSameName.GetOperationName()))
                        {
                            log.WarnFormat("Skipping duplicate type with existing name '{0}'", baseTypeWithSameName.GetOperationName());
                        }
                        uniqueTypes.Add(baseTypeWithSameName);
                    }
                }
            }

            uniqueTypes.RemoveWhere(x => x.IsGenericTypeDefinition());

            this.OperationTypes = uniqueTypes;

            var schemaSet = XsdUtils.GetXmlSchemaSet(OperationTypes);
            var xsd = XsdUtils.GetXsd(schemaSet);
            var filteredXsd = Filter(xsd);
            return filteredXsd;
        }
		/// <summary>
		///   Removes all methods from the set that are not compatible to the signature of the <pramref name="signature" />.
		/// </summary>
		/// <param name="methods">The set of methods that should be filtered.</param>
		/// <param name="delegateType">The signature the methods must be compatible to.</param>
		public static void Filter(HashSet<IMethodSymbol> methods, INamedTypeSymbol delegateType)
		{
			Requires.NotNull(methods, nameof(methods));
			Requires.NotNull(delegateType, nameof(delegateType));
			Requires.That(delegateType.TypeKind == TypeKind.Delegate, "Expected a delegate type.");

			methods.RemoveWhere(port => !port.IsSignatureCompatibleTo(delegateType.DelegateInvokeMethod));
		}
        /// <inheritdoc />
        public IEnumerable<TagHelperDescriptor> Resolve([NotNull] TagHelperDescriptorResolutionContext context)
        {
            var resolvedDescriptors = new HashSet<TagHelperDescriptor>(TagHelperDescriptorComparer.Default);

            // tagHelperPrefix directives do not affect which TagHelperDescriptors are added or removed from the final
            // list, need to remove them.
            var actionableDirectiveDescriptors = context.DirectiveDescriptors.Where(
                directive => directive.DirectiveType != TagHelperDirectiveType.TagHelperPrefix);

            foreach (var directiveDescriptor in actionableDirectiveDescriptors)
            {
                try
                {
                    var lookupInfo = GetLookupInfo(directiveDescriptor, context.ErrorSink);

                    // Could not resolve the lookup info.
                    if (lookupInfo == null)
                    {
                        return Enumerable.Empty<TagHelperDescriptor>();
                    }

                    if (directiveDescriptor.DirectiveType == TagHelperDirectiveType.RemoveTagHelper)
                    {
                        resolvedDescriptors.RemoveWhere(descriptor => MatchesLookupInfo(descriptor, lookupInfo));
                    }
                    else if (directiveDescriptor.DirectiveType == TagHelperDirectiveType.AddTagHelper)
                    {
                        var descriptors = ResolveDescriptorsInAssembly(
                            lookupInfo.AssemblyName,
                            directiveDescriptor.Location,
                            context.ErrorSink);

                        // Only use descriptors that match our lookup info
                        descriptors = descriptors.Where(descriptor => MatchesLookupInfo(descriptor, lookupInfo));

                        resolvedDescriptors.UnionWith(descriptors);
                    }
                }
                catch (Exception ex)
                {
                    string directiveName;
                    _directiveNames.TryGetValue(directiveDescriptor.DirectiveType, out directiveName);
                    Debug.Assert(!string.IsNullOrEmpty(directiveName));

                    context.ErrorSink.OnError(
                        directiveDescriptor.Location,
                        Resources.FormatTagHelperDescriptorResolver_EncounteredUnexpectedError(
                            "@" + directiveName,
                            directiveDescriptor.DirectiveText,
                            ex.Message));
                }
            }

            var prefixedDescriptors = PrefixDescriptors(context, resolvedDescriptors);

            return prefixedDescriptors;
        }
示例#11
0
        public override void Run(string[] args)
        {
            var filenames = string.Empty;
            var options = new OptionSet() { { "f=|files=", "Merges the specified split files.", f => filenames = f } };
            options.Parse(args);
            if (string.IsNullOrWhiteSpace(filenames))
            {
                throw new OptionSetException(options);
            }

            var splitFiles = new HashSet<string>(Directory.EnumerateFiles(@".\", filenames));
            var workFiles = new List<string>(splitFiles.Take(splitFiles.Count - Take >= Take ? Take : splitFiles.Count));
            splitFiles.RemoveWhere(s => workFiles.Contains(s));
            int splitId = 0;
            bool firstRun = true;
            var createdFiles = new HashSet<string>();

            while (workFiles.Count > 1 || firstRun)
            {
                int written = 0;
                var multiQueue = new MultiQueue(workFiles);
                using (var stream = Utils.FindFirstSplitFile("merge", ref splitId))
                {
                    createdFiles.Add(stream.Name);
                    Console.WriteLine("Merging {0} into {1}", string.Join(",", from f in workFiles
                                                                               select Path.GetFileName(f)),
                                                                               Path.GetFileName(stream.Name));
                    foreach (var item in multiQueue.Merge())
                    {
                        stream.Write(item.ToGuid().ToByteArray(), 0, 16);
                        if (++written % 1000000 == 0)
                        {
                            Console.WriteLine("Written {0} lines", written);
                        }
                    }
                }

                Console.WriteLine("Written {0} lines", written);
                Console.WriteLine("Excluded {0} duplicates.", multiQueue.Duplicates);
                if (!firstRun)
                {
                    workFiles.ForEach(f => File.Delete(f));
                }

                workFiles = new List<string>(splitFiles.Take(splitFiles.Count - Take >= Take ? Take : splitFiles.Count));
                splitFiles.RemoveWhere(s => workFiles.Contains(s));
                if (workFiles.Count < Take)
                {
                    splitFiles = createdFiles;
                    createdFiles = new HashSet<string>();
                    workFiles = new List<string>(splitFiles.Take(Take));
                    splitFiles.RemoveWhere(s => workFiles.Contains(s));
                    firstRun = false;
                }
            }
        }
示例#12
0
        HashSet<int> GenerateFourDigitTriangleNumbers()
        {
            var triangleNumbers = new HashSet<int>();

              for (int i = 1; i < 1000; i++) {
            triangleNumbers.Add(i * (i + 1) / 2);
              }
              triangleNumbers.RemoveWhere(tn => tn / 1000 >= 1 && tn / 1000 < 10);
              return triangleNumbers;
        }
示例#13
0
        HashSet<int> GenerateFourDigitSquareNumbers()
        {
            var squareNumbers = new HashSet<int>();

              for (int i = 1; i < 100; i++) {
            squareNumbers.Add(i * i);
              }
              squareNumbers.RemoveWhere(sn => sn / 1000 >= 1 && sn / 1000 < 10);
              return squareNumbers;
        }
 public void FilterEntities(BattleEntity sourceEntity, HashSet<BattleEntity> entities)
 {
     switch(mHpCondition) {
     case AISkillRule.HitPointCondition.HP_DEAD:
         entities.RemoveWhere(delegate(BattleEntity obj) {
             return obj.character.curHP > 0;
         });
         break;
     case AISkillRule.HitPointCondition.HP_GT:
         entities.RemoveWhere(delegate(BattleEntity obj) {
             return obj.character.curHP / obj.character.maxHP <= mHpPercValue;
         });
         break;
     case AISkillRule.HitPointCondition.HP_LT:
         entities.RemoveWhere(delegate(BattleEntity obj) {
             return obj.character.curHP / obj.character.maxHP >= mHpPercValue;
         });
         break;
         // highest, just find the max
     case AISkillRule.HitPointCondition.HP_HIGHEST:
         float maxHP = -1;
         foreach(BattleEntity entity in entities) {
             maxHP = Mathf.Max(maxHP, entity.character.curHP);
         }
         entities.RemoveWhere(delegate(BattleEntity obj) {
             return obj.character.curHP != maxHP;
         });
         break;
     case AISkillRule.HitPointCondition.HP_LOWEST:
         float minHP = 9999999;
         foreach(BattleEntity entity in entities) {
             // we want to make sure we dont count dead people
             minHP = Mathf.Max(1, Mathf.Min(minHP, entity.character.curHP));
         }
         entities.RemoveWhere(delegate(BattleEntity obj) {
             return obj.character.curHP != minHP;
         });
         break;
     }
 }
 public void FilterEntities(BattleEntity sourceEntity, HashSet<BattleEntity> entities)
 {
     switch(mHpCondition) {
     case AISkillRule.ResourceCondition.RES_EMPTY:
         entities.RemoveWhere(delegate(BattleEntity obj) {
             return obj.character.curResource > 0;
         });
         break;
     case AISkillRule.ResourceCondition.RES_GT:
         entities.RemoveWhere(delegate(BattleEntity obj) {
             return obj.character.curResource / obj.character.maxResource <= mHpPercValue;
         });
         break;
     case AISkillRule.ResourceCondition.RES_LT:
         entities.RemoveWhere(delegate(BattleEntity obj) {
             return obj.character.curResource / obj.character.maxResource >= mHpPercValue;
         });
         break;
         // highest, just find the max
     case AISkillRule.ResourceCondition.RES_HIGHEST:
         float maxResource = -1;
         foreach(BattleEntity entity in entities) {
             maxResource = Mathf.Max(maxResource, entity.character.curResource);
         }
         entities.RemoveWhere(delegate(BattleEntity obj) {
             return obj.character.curResource != maxResource;
         });
         break;
     case AISkillRule.ResourceCondition.RES_LOWEST:
         float minResource = 9999999;
         foreach(BattleEntity entity in entities) {
             // we want to make sure we dont count dead people
             minResource = Mathf.Min(minResource, entity.character.curResource);
         }
         entities.RemoveWhere(delegate(BattleEntity obj) {
             return obj.character.curResource != minResource;
         });
         break;
     }
 }
        public virtual InternalModelBuilder Apply(InternalModelBuilder modelBuilder)
        {
            Check.NotNull(modelBuilder, nameof(modelBuilder));

            foreach (var entityType in modelBuilder.Metadata.GetEntityTypes())
            {
                var unmappedProperty = entityType.GetProperties().FirstOrDefault(p => !IsMappedPrimitiveProperty(((IProperty)p).ClrType));
                if (unmappedProperty != null)
                {
                    throw new InvalidOperationException(CoreStrings.PropertyNotMapped(unmappedProperty.Name, entityType.Name));
                }

                if (entityType.HasClrType())
                {
                    var clrProperties = new HashSet<string>();
                    clrProperties.UnionWith(entityType.ClrType.GetRuntimeProperties()
                        .Where(pi => pi.IsCandidateProperty())
                        .Select(pi => pi.Name));

                    clrProperties.ExceptWith(entityType.GetProperties().Select(p => p.Name));

                    clrProperties.ExceptWith(entityType.GetNavigations().Select(p => p.Name));

                    var entityTypeBuilder = modelBuilder.Entity(entityType.ClrType, ConfigurationSource.Convention);

                    clrProperties.RemoveWhere(p => entityTypeBuilder.IsIgnored(p, ConfigurationSource.Convention));

                    if (clrProperties.Count > 0)
                    {
                        foreach (var clrProperty in clrProperties)
                        {
                            var actualProperty = entityType.ClrType.GetRuntimeProperty(clrProperty);
                            var targetType = FindCandidateNavigationPropertyType(actualProperty);
                            if (targetType != null)
                            {
                                if (!modelBuilder.IsIgnored(targetType.DisplayName(), ConfigurationSource.Convention))
                                {
                                    throw new InvalidOperationException(CoreStrings.NavigationNotAdded(actualProperty.Name, entityType.Name));
                                }
                            }
                            else
                            {
                                throw new InvalidOperationException(CoreStrings.PropertyNotAdded(actualProperty.Name, entityType.Name));
                            }
                        }
                    }
                }
            }

            return modelBuilder;
        }
示例#17
0
    // filter out by if targets are within range
    public void FilterEntities(BattleEntity sourceEntity, HashSet<BattleEntity> entities)
    {
        // first row filter
        PCCharacter.RowPosition rowPosition = PCCharacter.RowPosition.FRONT;
        switch(mRowCondition) {
        case AISkillRule.RowCondition.BACK_COUNT_GT:
        case AISkillRule.RowCondition.BACK_COUNT_LT:
            rowPosition = PCCharacter.RowPosition.BACK;
            break;
        case AISkillRule.RowCondition.FRONT_COUNT_GT:
        case AISkillRule.RowCondition.FRONT_COUNT_LT:
            rowPosition = PCCharacter.RowPosition.FRONT;
            break;
        case AISkillRule.RowCondition.MIDDLE_COUNT_GT:
        case AISkillRule.RowCondition.MIDDLE_COUNT_LT:
            rowPosition = PCCharacter.RowPosition.MIDDLE;
            break;
        }

        // then remove all entries are not that row
        entities.RemoveWhere(delegate(BattleEntity obj) {
            if(obj is PCBattleEntity && ((PCBattleEntity)obj).pcCharacter.rowPosition == rowPosition) {
                return false;
            }
            return true;
        });

        // finally see if it meets the condition, if it does, leave them, if it doesnt, remove all
        switch(mRowCondition) {
        case AISkillRule.RowCondition.BACK_COUNT_GT:
        case AISkillRule.RowCondition.FRONT_COUNT_GT:
        case AISkillRule.RowCondition.MIDDLE_COUNT_GT:
            if(entities.Count > mFilterCount) {
                // ok
            }
            else {
                entities.Clear();
            }
            break;
        case AISkillRule.RowCondition.BACK_COUNT_LT:
        case AISkillRule.RowCondition.FRONT_COUNT_LT:
        case AISkillRule.RowCondition.MIDDLE_COUNT_LT:
            if(entities.Count < mFilterCount) {
                // ok
            }
            else {
                entities.Clear();
            }
            break;
        }
    }
示例#18
0
文件: Tag.cs 项目: obscuredesign/web
        /// <summary>
        /// Creates all tags in supplied collection that don't already exist and returns the newly created tags.
        /// </summary>
        public static IEnumerable<Tag> CreateAllIfNotExists(this DbSet<Tag> source, IEnumerable<string> tags)
        {
            var tagSet = new HashSet<string>(tags);
            
            var existingTags = source
                .Where(t => tagSet.Contains(t.Name))
                .Select(t => t.Name)
                .ToList(); // consume to get result out of DB

            tagSet.RemoveWhere(tag => existingTags.Contains(tag));

            var newTags = tagSet.Select(t => new Tag { Name = t });

            source.AddRange(newTags);
            return newTags;
        }
示例#19
0
        public Algoritmo( string path, string pred_obj)
        {
            predicados = new HashSet<Literal>();
            dominio = new HashSet<string>();
            baseConocimiento = new List<Literal>();
            conocimientoPos = new List<Literal>();
            conocimientoNeg = new List<Literal>();
            objetivo = pred_obj;
            var file = (from lines in File.ReadAllLines(@path)
                        let line = lines.Split(new[] { "(" }, StringSplitOptions.RemoveEmptyEntries)
                        select new
                        {
                            predicado = line[0],
                            atributos = line[1].Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries)
                        }
                        );
            foreach (var lit in file)
            {
                int natt = lit.atributos.Count();
                Literal nuevo = new Literal(lit.predicado, natt);
                predicados.Add(nuevo.Clone()); //para tener la cardinalidad tb
                string[] att = lit.atributos;
                att[natt - 1] = att[natt - 1].Remove(att[natt - 1].Count() - 1);
                nuevo.Atributos = att;

                dominio.UnionWith(att);

                if (lit.predicado == pred_obj)
                    conocimientoPos.Add(nuevo);
                else
                {
                    baseConocimiento.Add(nuevo);
                    //predicados.Add(lit.predicado); //Para recursivo poner fuera del else
                }
            }
            predicados.RemoveWhere(T => T.Nombre == objetivo);
            int n_att = conocimientoPos[0].nAtt;
            foreach (var litNeg in dominio.Repetitions(n_att))
            {
                Literal nuevo = new Literal(pred_obj, n_att);
                nuevo.Atributos = litNeg;
                conocimientoNeg.Add(nuevo);
            }
            conocimientoNeg.RemoveAll(T => conocimientoPos.Contains(T));
        }
示例#20
0
        double IClassifier.Classify(string sample)
        {
            if (!isTrained)
                throw new NotTrainedException();
            var tokens = new HashSet<string>(Utils.ExtractWords(sample));
            tokens.RemoveWhere(e => this.stopWords.Contains(e));

            double logProb1 = CalculateSampleLogProbability(tokens, this.logProbabilities1);
            double logProb2 = CalculateSampleLogProbability(tokens, this.logProbabilities2);

            // numerically safer calculation for (-1*p1 + 1*p2)/(p1 + p2)
            double logDiff = logProb1 - logProb2;
            double diff = Math.Exp(-Math.Abs(logDiff));
            double result = -Math.Sign(logDiff) * (1 - diff) / (1 + diff);
            // Console.WriteLine("Actual result: " + result);

            return result;
        }
示例#21
0
        public IEnumerable<string> GetItems(string fullPath, ItemType itemType)
        {
            // REVIEW: We should pass the filter to this method so it happens on the server
            // REVIEW: Can we do some smart caching so we don't hit the server every time this is called?
            var itemSet = _workspace.VersionControlServer.GetItems(fullPath, TFS.VersionSpec.Latest, RecursionType.OneLevel, DeletedState.NonDeleted, itemType);

            // Get the local files for the server files
            var items = new HashSet<string>(from item in itemSet.Items
                                            select GetLocalItemForServerItem(item.ServerItem),
                                            StringComparer.OrdinalIgnoreCase);

            // Remove the path from the list if we're looking for folders
            if (itemType == ItemType.Folder)
            {
                items.Remove(fullPath);

                if (Directory.Exists(fullPath))
                {
                    // Files might have pending adds, but directories might not
                    // (even though they get added as a result of checking in those files).
                    foreach (var directory in Directory.EnumerateDirectories(fullPath))
                    {
                        items.Add(directory);
                    }
                }
            }

            // Remove pending deletes from the items collection
            foreach (var change in GetPendingChanges(fullPath, RecursionType.OneLevel))
            {
                if (change.IsDelete)
                {
                    // Remove all children of this path
                    items.RemoveWhere(item => item.StartsWith(change.LocalItem, StringComparison.OrdinalIgnoreCase));
                }
                else
                {
                    items.Add(change.LocalItem);
                }
            }

            return items;
        }
示例#22
0
        static int Main(string[] args)
        {
            object obj = new object();
            HashSet<object> hashset;
            Object[] oa = new Object[2];

            hashset = new HashSet<object>();
            hashset.Add(obj);
            hashset.Remove(obj);

            //Regression test: make sure these don't throw.
            foreach (object o in hashset)
            {
            }
            hashset.CopyTo(oa, 0, 2);
            hashset.RemoveWhere(MyPredicate);

            return 100;
        }
示例#23
0
    /// <summary>
    /// Finds the path using Iterative Deepening method
    /// </summary>
    public override void FindPath()
    {
        grid.ResetNodes(meshCopy);

        HashSet<Node> visitedHash = new HashSet<Node>();
        Node startNode = grid.NodeFromWorldPoint(meshCopy, startPos);
        Node targetNode = grid.NodeFromWorldPoint(meshCopy, targetPos);
        visitedHash.Add(startNode);

        int depth = 0;
        path.pathSuccess = false;

        try
        {
            //Starts the stopwatch for timing the algorithm
            stopWatch = System.Diagnostics.Stopwatch.StartNew();
            while(!path.pathSuccess && visitedHash.Count < grid.MaxSize)
            {
                path.pathSuccess = Deepening(startNode, depth, visitedHash, targetNode);

                visitedHash.RemoveWhere(n => n.parent != null && n != startNode);

                depth++;
            }

            if(path.pathSuccess)
                path.waypoints = RetracePath(startNode, targetNode);
        }
        catch(Exception ex)
        {
            Debug.Log("Error in find path method of IDeepening path");
            path.pathSuccess = false;
        }

        stopWatch.Stop();

        path.totalMs = totalMs + stopWatch.ElapsedMilliseconds;
        path.pathTime = stopWatch.ElapsedMilliseconds;
        path.totalNodes = visitedHash.Count;

        //This must be set to let the Pathfinding object know that thread has completed its job
        doneEvent.Set();
    }
示例#24
0
        public static void Regression_Dev10_624201()
        {
            Predicate<object> predicate = (Object o) => { return false; };

            object obj = new object();
            HashSet<object> hashset;
            Object[] oa = new Object[2];

            hashset = new HashSet<object>();
            hashset.Add(obj);
            hashset.Remove(obj);

            //Regression test: make sure these don't throw.
            foreach (object o in hashset)
            { }
            hashset.CopyTo(oa, 0, 2);
            hashset.RemoveWhere(predicate);

            // we just want to make sure it doesn't throw.
        }
        public static void Main()
        {
            var numbers = new HashSet<int>();

            Console.WriteLine("Generating numbers...");
            for (int i = 0; i < NumbersCount; i++)
            {
                numbers.Add(-i);
            }

            Console.WriteLine("Removing negative numbers...");
            var sw = new Stopwatch();

            sw.Start();
            numbers.RemoveWhere(x => x < 0);
            sw.Stop();

            Console.WriteLine($"Removal elapsed time: {(int)sw.Elapsed.TotalMilliseconds}ms");
            Console.WriteLine(value: "Much faster than a list");
        }
示例#26
0
        private void StartReaper()
        {
            Task.Factory.StartNew(async () =>
            {
                await Task.Delay(1000).ConfigureAwait(false);
                Logger.Information("Reaper: started..");

                var c = _consulPort > 0 ? new ConsulRestClient(_consulPort) : new ConsulRestClient();

                var lookup = new HashSet<string>();
                while (true)
                {
                    try
                    {
                        var res = await c.GetCriticalServicesAsync().ConfigureAwait(false);
                        foreach (var criticalServiceId in res)
                        {
                            if (lookup.Contains(criticalServiceId))
                            {
                                await c.DeregisterServiceAsync(criticalServiceId).ConfigureAwait(false);
                                Logger.Information("Reaper: Removing {ServiceId}", criticalServiceId);
                            }
                            else
                            {
                                lookup.Add(criticalServiceId);
                                Logger.Information("Reaper: Marking {ServiceId}", criticalServiceId);
                            }
                        }
                        //remove entries that are no longer critical
                        lookup.RemoveWhere(i => !res.Contains(i));
                    }
                    catch (Exception x)
                    {
                        Logger.Error(x, "Crashed");
                    }

                    await Task.Delay(5000).ConfigureAwait(false);
                }
            });
        }
示例#27
0
        public IList<AxisConstraint> GetAvailableSplits()
        {
            HashSet<AxisConstraint> availableSplits = new HashSet<AxisConstraint>();

            AxisConstraint? minX = null, minY = null, minZ = null, maxX = null, maxY = null, maxZ = null;

            foreach(RotateableRegion region in _rotateableRegions)
            {
                IntBlockBounds rotatedBounds = region.RotatedBounds();
                if (HasPivot(AxisConstraint.AxisType.X))
                {
                    availableSplits.Add(UpdateMinMax(ref minX, ref maxX, AxisConstraint.X(rotatedBounds.MinX)));
                    availableSplits.Add(UpdateMinMax(ref minX, ref maxX, AxisConstraint.X(rotatedBounds.MaxX)));
                }
                if (HasPivot(AxisConstraint.AxisType.Y))
                {
                    availableSplits.Add(UpdateMinMax(ref minY, ref maxY, AxisConstraint.Y(rotatedBounds.MinY)));
                    availableSplits.Add(UpdateMinMax(ref minY, ref maxY, AxisConstraint.Y(rotatedBounds.MaxY)));
                }
                if (HasPivot(AxisConstraint.AxisType.Z))
                {
                    availableSplits.Add(UpdateMinMax(ref minZ, ref maxZ, AxisConstraint.Z(rotatedBounds.MinZ)));
                    availableSplits.Add(UpdateMinMax(ref minZ, ref maxZ, AxisConstraint.Z(rotatedBounds.MaxZ)));
                }
            }

            availableSplits.RemoveWhere(axisConstraint =>
                axisConstraint.Equals(minX) ||
                axisConstraint.Equals(maxX) ||
                axisConstraint.Equals(minY) ||
                axisConstraint.Equals(maxY) ||
                axisConstraint.Equals(minZ) ||
                axisConstraint.Equals(maxZ) ||
                _rotateableRegions.Any(region => axisConstraint.IntersectedByBlockBounds(region.RotatedBounds()))
            );

            return availableSplits.ToList();
        }
 public static HashSet<BuildingInfo> GetPillars(this NetInfo prefab)
 {
     HashSet<BuildingInfo> pillars = new HashSet<BuildingInfo>();
     var roadAi = prefab.m_netAI as RoadBridgeAI;
     if (roadAi != null)
     {
         pillars.Add(roadAi.m_bridgePillarInfo);
         pillars.Add(roadAi.m_middlePillarInfo);
     }
     var trainTrackAi = prefab.m_netAI as TrainTrackBridgeAI;
     if (trainTrackAi != null)
     {
         pillars.Add(trainTrackAi.m_bridgePillarInfo);
         pillars.Add(trainTrackAi.m_middlePillarInfo);
     }
     var pedestrianPathAi = prefab.m_netAI as PedestrianBridgeAI;
     if (pedestrianPathAi != null)
     {
         pillars.Add(pedestrianPathAi.m_bridgePillarInfo);
     }
     pillars.RemoveWhere(bi => bi == null);
     return pillars;
 }
示例#29
0
        /// <summary>
        /// Generates a syntax tree for the provided assemblies.
        /// </summary>
        /// <param name="assemblies">The assemblies to generate code for.</param>
        /// <param name="runtime">Whether or not runtime code generation is being performed.</param>
        /// <returns>The generated syntax tree.</returns>
        private static GeneratedSyntax GenerateForAssemblies(List<Assembly> assemblies, bool runtime)
        {
            if (Logger.IsVerbose)
            {
                Logger.Verbose(
                    "Generating code for assemblies: {0}",
                    string.Join(", ", assemblies.Select(_ => _.FullName)));
            }

            Assembly targetAssembly;
            HashSet<Type> ignoredTypes;
            if (runtime)
            {
                // Ignore types which have already been accounted for.
                ignoredTypes = GetTypesWithGeneratedSupportClasses();
                targetAssembly = null;
            }
            else
            {
                ignoredTypes = new HashSet<Type>();
                targetAssembly = assemblies.FirstOrDefault();
            }

            var members = new List<MemberDeclarationSyntax>();

            // If any KnownAssemblies have been specified, include them during code generation.
            var knownAssemblies =
                assemblies.SelectMany(_ => _.GetCustomAttributes<KnownAssemblyAttribute>())
                    .Select(_ => _.Assembly)
                    .Distinct()
                    .ToSet();
            if (knownAssemblies.Count > 0)
            {
                knownAssemblies.UnionWith(assemblies);
                assemblies = knownAssemblies.ToList();
            }

            // Get types from assemblies which reference Orleans and are not generated assemblies.
            var includedTypes = new HashSet<Type>();
            for (var i = 0; i < assemblies.Count; i++)
            {
                var assembly = assemblies[i];
                foreach (var attribute in assembly.GetCustomAttributes<KnownTypeAttribute>())
                {
                    ConsiderType(attribute.Type, runtime, targetAssembly, includedTypes);
                }

                foreach (var type in assembly.DefinedTypes)
                {
                    ConsiderType(type, runtime, targetAssembly, includedTypes);
                }
            }

            includedTypes.RemoveWhere(_ => ignoredTypes.Contains(_));

            // Group the types by namespace and generate the required code in each namespace.
            foreach (var group in includedTypes.GroupBy(_ => CodeGeneratorCommon.GetGeneratedNamespace(_)))
            {
                var namespaceMembers = new List<MemberDeclarationSyntax>();
                foreach (var type in group)
                {
                    // The module containing the serializer.
                    var module = runtime ? null : type.Module;

                    // Every type which is encountered must be considered for serialization.
                    Action<Type> onEncounteredType = encounteredType =>
                    {
                        // If a type was encountered which can be accessed, process it for serialization.
                        SerializerGenerationManager.RecordTypeToGenerate(encounteredType, module, targetAssembly);
                    };

                    if (Logger.IsVerbose2)
                    {
                        Logger.Verbose2("Generating code for: {0}", type.GetParseableName());
                    }

                    if (GrainInterfaceData.IsGrainInterface(type))
                    {
                        if (Logger.IsVerbose2)
                        {
                            Logger.Verbose2(
                                "Generating GrainReference and MethodInvoker for {0}",
                                type.GetParseableName());
                        }

                        GrainInterfaceData.ValidateInterfaceRules(type);

                        namespaceMembers.Add(GrainReferenceGenerator.GenerateClass(type, onEncounteredType));
                        namespaceMembers.Add(GrainMethodInvokerGenerator.GenerateClass(type));
                    }

                    // Generate serializers.
                    var first = true;
                    Type toGen;
                    while (SerializerGenerationManager.GetNextTypeToProcess(out toGen))
                    {
                        if (!runtime)
                        {
                            if (first)
                            {
                                ConsoleText.WriteStatus("ClientGenerator - Generating serializer classes for types:");
                                first = false;
                            }

                            ConsoleText.WriteStatus(
                                "\ttype " + toGen.FullName + " in namespace " + toGen.Namespace
                                + " defined in Assembly " + toGen.Assembly.GetName());
                        }

                        if (Logger.IsVerbose2)
                        {
                            Logger.Verbose2(
                                "Generating & Registering Serializer for Type {0}",
                                toGen.GetParseableName());
                        }

                        namespaceMembers.AddRange(SerializerGenerator.GenerateClass(toGen, onEncounteredType));
                    }
                }

                if (namespaceMembers.Count == 0)
                {
                    if (Logger.IsVerbose)
                    {
                        Logger.Verbose2("Skipping namespace: {0}", group.Key);
                    }

                    continue;
                }

                members.Add(
                    SF.NamespaceDeclaration(SF.ParseName(group.Key))
                        .AddUsings(
                            TypeUtils.GetNamespaces(typeof(TaskUtility), typeof(GrainExtensions))
                                .Select(_ => SF.UsingDirective(SF.ParseName(_)))
                                .ToArray())
                        .AddMembers(namespaceMembers.ToArray()));
            }

            return new GeneratedSyntax
            {
                SourceAssemblies = assemblies,
                Syntax = members.Count > 0 ? SF.CompilationUnit().AddMembers(members.ToArray()) : null
            };
        }
示例#30
0
        internal static void WriteProjectXml(
            XmlWriter writer,
            string projectPath,
            string sourcePath,
            string filters,
            string startupFile,
            bool excludeNodeModules,
            out Guid projectGuid
        ) {
            var projectHome = CommonUtils.GetRelativeDirectoryPath(Path.GetDirectoryName(projectPath), sourcePath);
            projectGuid = Guid.NewGuid();

            writer.WriteStartDocument();
            writer.WriteStartElement("Project", "http://schemas.microsoft.com/developer/msbuild/2003");
            writer.WriteAttributeString("DefaultTargets", "Build");

            writer.WriteStartElement("PropertyGroup");

            writer.WriteStartElement("Configuration");
            writer.WriteAttributeString("Condition", " '$(Configuration)' == '' ");
            writer.WriteString("Debug");
            writer.WriteEndElement();

            writer.WriteElementString("SchemaVersion", "2.0");
            writer.WriteElementString("ProjectGuid", projectGuid.ToString("B"));
            writer.WriteElementString("ProjectHome", projectHome);
            writer.WriteElementString("ProjectView", "ShowAllFiles");

            if (CommonUtils.IsValidPath(startupFile)) {
                writer.WriteElementString("StartupFile", Path.GetFileName(startupFile));
            } else {
                writer.WriteElementString("StartupFile", String.Empty);
            }
            writer.WriteElementString("WorkingDirectory", ".");
            writer.WriteElementString("OutputPath", ".");
            writer.WriteElementString("ProjectTypeGuids", "{3AF33F2E-1136-4D97-BBB7-1795711AC8B8};{349c5851-65df-11da-9384-00065b846f21};{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}");
            bool typeScriptSupport = EnumerateAllFiles(sourcePath, filters, excludeNodeModules)
                .Any(filename => NodejsConstants.TypeScriptExtension.Equals(Path.GetExtension(filename), StringComparison.OrdinalIgnoreCase));

            if (typeScriptSupport) {
                writer.WriteElementString("TypeScriptSourceMap", "true");
                writer.WriteElementString("TypeScriptModuleKind", "CommonJS");
                writer.WriteElementString("EnableTypeScript", "true");
            }

            writer.WriteStartElement("VisualStudioVersion");
            writer.WriteAttributeString("Condition", "'$(VisualStudioVersion)' == ''");
            writer.WriteString("14.0");
            writer.WriteEndElement();

            writer.WriteStartElement("VSToolsPath");
            writer.WriteAttributeString("Condition", "'$(VSToolsPath)' == ''");
            writer.WriteString(@"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)");
            writer.WriteEndElement();

            writer.WriteEndElement(); // </PropertyGroup>

            // VS requires property groups with conditions for Debug
            // and Release configurations or many COMExceptions are
            // thrown.
            writer.WriteStartElement("PropertyGroup");
            writer.WriteAttributeString("Condition", "'$(Configuration)' == 'Debug'");
            writer.WriteEndElement();
            writer.WriteStartElement("PropertyGroup");
            writer.WriteAttributeString("Condition", "'$(Configuration)' == 'Release'");
            writer.WriteEndElement();

            var folders = new HashSet<string>(
                Directory.EnumerateDirectories(sourcePath, "*", SearchOption.AllDirectories)
                    .Select(dirName => 
                        CommonUtils.TrimEndSeparator(
                            CommonUtils.GetRelativeDirectoryPath(sourcePath, dirName)
                        )
                    )
                    .Where(ShouldIncludeDirectory)
            );

            // Exclude node_modules and bower_components folders.
            if (excludeNodeModules) {
                folders.RemoveWhere(NodejsConstants.ContainsNodeModulesOrBowerComponentsFolder);
            }

            writer.WriteStartElement("ItemGroup");
            foreach (var file in EnumerateAllFiles(sourcePath, filters, excludeNodeModules)) {
                var ext = Path.GetExtension(file);
                if (NodejsConstants.JavaScriptExtension.Equals(ext, StringComparison.OrdinalIgnoreCase)) {
                    writer.WriteStartElement("Compile");
                } else if (NodejsConstants.TypeScriptExtension.Equals(ext, StringComparison.OrdinalIgnoreCase)) {
                    writer.WriteStartElement("TypeScriptCompile");
                } else {
                    writer.WriteStartElement("Content");
                }
                writer.WriteAttributeString("Include", file);
                writer.WriteEndElement();
            }
            writer.WriteEndElement();

            writer.WriteStartElement("ItemGroup");
            foreach (var folder in folders.Where(s => !string.IsNullOrWhiteSpace(s)).OrderBy(s => s)) {
                writer.WriteStartElement("Folder");
                writer.WriteAttributeString("Include", folder);
                writer.WriteEndElement();
            }
            writer.WriteEndElement();

            writer.WriteStartElement("Import");
            writer.WriteAttributeString("Project", @"$(MSBuildToolsPath)\Microsoft.Common.targets");
            writer.WriteAttributeString("Condition", @"Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')");
            writer.WriteEndElement();

            writer.WriteComment("Do not delete the following Import Project.  While this appears to do nothing it is a marker for setting TypeScript properties before our import that depends on them.");
            writer.WriteStartElement("Import");
            writer.WriteAttributeString("Project", @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets");
            writer.WriteAttributeString("Condition", @"False");
            writer.WriteEndElement();

            writer.WriteStartElement("Import");
            writer.WriteAttributeString("Project", @"$(VSToolsPath)\Node.js Tools\Microsoft.NodejsTools.targets");
            writer.WriteEndElement();

            writer.WriteRaw(@"
    <ProjectExtensions>
        <VisualStudio>
          <FlavorProperties GUID=""{349c5851-65df-11da-9384-00065b846f21}"">
            <WebProjectProperties>
              <UseIIS>False</UseIIS>
              <AutoAssignPort>True</AutoAssignPort>
              <DevelopmentServerPort>0</DevelopmentServerPort>
              <DevelopmentServerVPath>/</DevelopmentServerVPath>
              <IISUrl>http://localhost:48022/</IISUrl>
              <NTLMAuthentication>False</NTLMAuthentication>
              <UseCustomServer>True</UseCustomServer>
              <CustomServerUrl>http://localhost:1337</CustomServerUrl>
              <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
            </WebProjectProperties>
          </FlavorProperties>
          <FlavorProperties GUID=""{349c5851-65df-11da-9384-00065b846f21}"" User="""">
            <WebProjectProperties>
              <StartPageUrl>
              </StartPageUrl>
              <StartAction>CurrentPage</StartAction>
              <AspNetDebugging>True</AspNetDebugging>
              <SilverlightDebugging>False</SilverlightDebugging>
              <NativeDebugging>False</NativeDebugging>
              <SQLDebugging>False</SQLDebugging>
              <ExternalProgram>
              </ExternalProgram>
              <StartExternalURL>
              </StartExternalURL>
              <StartCmdLineArguments>
              </StartCmdLineArguments>
              <StartWorkingDirectory>
              </StartWorkingDirectory>
              <EnableENC>False</EnableENC>
              <AlwaysStartWebServerOnDebug>False</AlwaysStartWebServerOnDebug>
            </WebProjectProperties>
          </FlavorProperties>
        </VisualStudio>
    </ProjectExtensions>
");

            writer.WriteEndElement(); // </Project>

            writer.WriteEndDocument();
        }