示例#1
0
        public void Ordinal_should_result_in_four_claims()
        {
            var hashSet = new HashSet <Claim>(_claims, new ClaimComparer(new ClaimComparer.Options {
                IgnoreValueCase = false
            }));

            hashSet.Count.Should().Be(4);

            var item = hashSet.First();

            item.Type.Should().Be("claim_type1");
            item.Value.Should().Be("value");
            item.Issuer.Should().Be("issuer1");

            item = hashSet.Skip(1).First();
            item.Type.Should().Be("claim_type1");
            item.Value.Should().Be("Value");
            item.Issuer.Should().Be("issuer1");

            item = hashSet.Skip(2).First();
            item.Type.Should().Be("claim_type1");
            item.Value.Should().Be("value");
            item.Issuer.Should().Be("issuer2");

            item = hashSet.Skip(3).First();
            item.Type.Should().Be("claim_type1");
            item.Value.Should().Be("Value");
            item.Issuer.Should().Be("issuer2");
        }
示例#2
0
        public void Default_options_should_result_in_four_claims()
        {
            var hashSet = new HashSet <Claim>(_claims, new ClaimComparer());

            hashSet.Count.Should().Be(4);

            var item = hashSet.First();

            item.Type.Should().Be("claim_type1");
            item.Value.Should().Be("value");
            item.Issuer.Should().Be("issuer1");

            item = hashSet.Skip(1).First();
            item.Type.Should().Be("claim_type1");
            item.Value.Should().Be("Value");
            item.Issuer.Should().Be("issuer1");

            item = hashSet.Skip(2).First();
            item.Type.Should().Be("claim_type1");
            item.Value.Should().Be("value");
            item.Issuer.Should().Be("issuer2");

            item = hashSet.Skip(3).First();
            item.Type.Should().Be("claim_type1");
            item.Value.Should().Be("Value");
            item.Issuer.Should().Be("issuer2");
        }
示例#3
0
        static void Main(string[] args)
        {
            const int limit  = 1000000;
            var       primes = new HashSet <int>();

            for (mpz_t p = 2; p <= limit; p = p.NextPrimeGMP())
            {
                primes.Add((int)p);
            }
            var indexes   = Enumerable.Range(0, primes.Count + 1).ToArray();
            int max       = 0;
            int bestprime = 0;

            for (int i = 0; i < primes.Count &&
                 primes.Skip(i).Take(max).Sum() <= limit /* is it possible to generate a longer string? */
                 ; i++)
            {
                for (int c = max; c <= primes.Count - i; c++)
                {
                    var sum = primes.Skip(i).Take(c).Sum();
                    if (sum >= limit)
                    {
                        break;
                    }
                    if (c > max && primes.Contains(sum))
                    {
                        bestprime = sum;
                        max       = c;
                    }
                }
            }
            Console.WriteLine($"\n{bestprime}, max = {max}");
        }
示例#4
0
    public static bool IsEventAvailable()
    {
        var possibleActions = new HashSet <int>(ActionsParser.Events.Keys);

        possibleActions.ExceptWith(PreviouslyUsedIndexes.Skip(System.Math.Max(0, PreviouslyUsedIndexes.Count - 5)));

        return(possibleActions.Any());
    }
        public void BinarySeachTreeTestCase1()
        {
            var rnd = new Random();

            var set = new HashSet <int>();

            do
            {
                var value = rnd.Next(100, 1000);
                set.Add(value);
                Console.WriteLine($"Choosing value: {value}");
            } while (set.Count < 10);

            BinarySeachTree <int> searchTree = null;

            foreach (var item in set)
            {
                searchTree = BinarySeachTree <int> .Insert(searchTree, item);
            }

            var expectedOutput = set.Skip(4).First();

            var actualOutput = BinarySeachTree <int> .Search(searchTree, expectedOutput);

            Assert.AreEqual(expectedOutput, actualOutput.Value, "Value does not match");
        }
    static void Main()
    {
        var listOfLists = new HashSet <int>[]
        {
            new HashSet <int> {
                1, 2, 3
            },
            new HashSet <int> {
                0, 2, 4
            },
            new HashSet <int> {
                0, 1, 2
            }
        };
        var r = listOfLists[0]; foreach (var rc in listOfLists.Skip(1))

        {
            r.IntersectWith(rc);
        }

        foreach (var item in r)
        {
            System.Console.WriteLine(item);
        }
    }
        private async Task RunAsync(CancellationToken token)
        {
            try
            {
                while (!token.IsCancellationRequested)
                {
                    await Task.Delay(_random.Next(1024, 8192), token);

                    if (Update == null || _prices.Count == 0)
                    {
                        continue;
                    }

                    var price = _prices.Skip(_random.Next(_prices.Count)).First();

                    var newPrice = price.Price + _random.Next(-99, 99) / 10m;
                    if (newPrice < 0)
                    {
                        newPrice = 0m;
                    }
                    price.Price = newPrice;

                    Update?.Invoke(this, new StockPriceUpdateEventArgs(price.Symbol, price.Price));
                }
            }
            catch (OperationCanceledException)
            {
                // Ignored
            }
        }
示例#8
0
        public async Task <Dictionary <string, EmailVerificationStatus> > GetStatusAsync(HashSet <string> emailAddresses, CancellationToken ct = default)
        {
            var result = new Dictionary <string, EmailVerificationStatus>();

            var buckets = (int)Math.Ceiling((double)emailAddresses.Count / MaxEmailAddressesPerRequest);

            for (var i = 0; i < buckets; i++)
            {
                ct.ThrowIfCancellationRequested();

                var bucketAddresses = emailAddresses.Skip(i * MaxEmailAddressesPerRequest).Take(MaxEmailAddressesPerRequest);

                var request = new GetIdentityVerificationAttributesRequest
                {
                    Identities = bucketAddresses.ToList()
                };

                var response = await amazonSES.GetIdentityVerificationAttributesAsync(request, ct);

                foreach (var(key, attr) in response.VerificationAttributes)
                {
                    result[key] = MapStatus(attr.VerificationStatus);
                }
            }

            return(result);
        }
示例#9
0
        private async Task <Dictionary <int, string> > GetProjectNamesForUserMapping(HashSet <int> projectIds, int?userId)
        {
            var projectNameIdDictionary = (await _artifactRepository.GetProjectNameByIdsAsync(projectIds)).ToDictionary(x => x.ItemId, x => x.Name);

            if (!userId.HasValue)
            {
                return(projectNameIdDictionary);
            }

            var projectIdPermissions = new List <KeyValuePair <int, RolePermissions> >();

            int iterations = (int)Math.Ceiling((double)projectIds.Count / 50);

            for (int i = 0; i < iterations; i++)
            {
                var chunkProjectIds = projectIds.Skip(i * 50).Take(50);
                var newDictionary   = await _artifactPermissionsRepository.GetArtifactPermissions(chunkProjectIds, userId.Value);

                projectIdPermissions.AddRange(newDictionary.ToList());
            }

            var projectIdPermissionsDictionary = projectIdPermissions.ToDictionary(x => x.Key, x => x.Value);

            foreach (int projectId in projectIds)
            {
                if (!projectIdPermissionsDictionary.ContainsKey(projectId) || !projectIdPermissionsDictionary[projectId].HasFlag(RolePermissions.Read))
                {
                    projectNameIdDictionary[projectId] = ServiceConstants.NoPermissions;
                }
            }

            return(projectNameIdDictionary);
        }
示例#10
0
        private void LoadDirectoryHistory()
        {
            var fn = GetHistoryFileName();

            if (File.Exists(fn))
            {
                var strs = new HashSet <string>();
                using (var stream = File.OpenRead(fn))
                    using (var tr = new StreamReader(stream))
                    {
                        while (true)
                        {
                            var line = tr.ReadLine();
                            if (string.IsNullOrWhiteSpace(line))
                            {
                                break;
                            }
                            var s = line.Trim();
                            if (Directory.Exists(s))
                            {
                                strs.Add(s);
                            }
                        }
                    }
                if (5 < strs.Count)
                {
                    strs = new HashSet <string>(strs.Skip(strs.Count - 5));
                }
                DirectoryHistory = new ObservableCollection <string>(strs);
            }
            else
            {
                DirectoryHistory = new ObservableCollection <string>();
            }
        }
示例#11
0
        public IGenome <TSimulation> PickRandomGenome()
        {
            var random = evolutionSettings.RandomnessProvider;

            return(genomes
                   .Skip(random.Next(0, genomes.Count))
                   .First());
        }
示例#12
0
        private HashSet <NotifyEntry> TrimSet(HashSet <NotifyEntry> entries)
        {
            if (entries.Count <= 20)
            {
                return(entries);
            }

            return(new HashSet <NotifyEntry>(entries.Skip(entries.Count - 20)));
        }
        public static T RandomElement <T>(this HashSet <T> source, Random r)
        {
            if (source.Count <= 0)
            {
                throw new IndexOutOfRangeException();
            }
            int randomIndex = r.Next(source.Count);

            return(source.Skip(randomIndex).First());
        }
示例#14
0
            public long QuantumEntanglement()
            {
                long quantumEntanglement = _packages.First();

                foreach (var pack in _packages.Skip(1))
                {
                    quantumEntanglement *= pack;
                }
                return(quantumEntanglement);
            }
示例#15
0
 HashSet <string> GetTempResults(HashSet <int> tempIds, Dictionary <int, HashSet <string> > tempFullOddResults)
 {
     return(tempIds.Skip(1)
            .Aggregate(
                new HashSet <string>(tempFullOddResults[tempIds.First()]),
                (h, e) =>
     {
         h.IntersectWith(tempFullOddResults[e]); return h;
     }
                ));
 }
示例#16
0
        public static ushort GetFreePort()
        {
            var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            var tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

            var usedPorts = new HashSet<ushort>(tcpConnInfoArray.Select(x => (ushort)x.LocalEndPoint.Port));
            var availablePorts = new HashSet<ushort>(Enumerable.Range(1024, 65535 - 1024).Select(x => (ushort)x));
            availablePorts.ExceptWith(usedPorts);

            return availablePorts.Skip(new Random().Next(availablePorts.Count - 1)).First();
        }
示例#17
0
        public static ushort GetFreePort()
        {
            var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            var tcpConnInfoArray   = ipGlobalProperties.GetActiveTcpConnections();

            var usedPorts      = new HashSet <ushort>(tcpConnInfoArray.Select(x => (ushort)x.LocalEndPoint.Port));
            var availablePorts = new HashSet <ushort>(Enumerable.Range(1024, 65535 - 1024).Select(x => (ushort)x));

            availablePorts.ExceptWith(usedPorts);

            return(availablePorts.Skip(new Random().Next(availablePorts.Count - 1)).First());
        }
示例#18
0
        /// <summary>
        /// Returns all nodes that in its input ports' scope. A node is in its
        /// scope if that node is one of its upstream nodes.
        /// </summary>
        /// <param name="portIndex">Inport index</param>
        /// <param name="checkEscape">
        /// If need to exclude nodes that one of their downstream nodes are not
        /// in the scope
        /// </param>
        /// <param name="isInclusive">
        /// If a upstream node is ScopedNodeModel, need to include all upstream
        /// nodes of that node.
        /// </param>
        /// <param name="forceToGetNodeForInport"></param>
        /// <returns></returns>
        public IEnumerable <NodeModel> GetInScopeNodesForInport(
            int portIndex,
            bool checkEscape             = true,
            bool isInclusive             = true,
            bool forceToGetNodeForInport = false)
        {
            // The related test cases are in DynmoTest.ScopedNodeTest.
            var scopedNodes = new HashSet <NodeModel>();

            Tuple <int, NodeModel> inputTuple = null;

            if ((!forceToGetNodeForInport && !IsScopedInport(portIndex)) ||
                !this.TryGetInput(portIndex, out inputTuple))
            {
                return(scopedNodes);
            }

            scopedNodes.Add(this);
            var inputNode   = inputTuple.Item2;
            var workingList = new Queue <NodeModel>();

            if (!checkEscape || (checkEscape && IsNodeInScope(inputNode, scopedNodes)))
            {
                workingList.Enqueue(inputNode);
                scopedNodes.Add(inputNode);
            }

            // Collect all upstream nodes in BFS order
            while (workingList.Any())
            {
                var currentNode = workingList.Dequeue();
                if (!isInclusive && currentNode is ScopedNodeModel)
                {
                    continue;
                }

                foreach (int index in Enumerable.Range(0, currentNode.InPortData.Count))
                {
                    if (currentNode.TryGetInput(index, out inputTuple))
                    {
                        inputNode = inputTuple.Item2;
                        if (!checkEscape || (checkEscape && IsNodeInScope(inputNode, scopedNodes)))
                        {
                            workingList.Enqueue(inputNode);
                            scopedNodes.Add(inputNode);
                        }
                    }
                }
            }

            return(scopedNodes.Skip(1));
        }
示例#19
0
        static char[][] getPFMatrix(string key)
        {
            var set = new HashSet <char>(key.ToUpper() + pfAlphabet);

            var matrix = new char[5][];

            for (int i = 0; i < 5; i++)
            {
                matrix[i] = set.Skip(5 * i).Take(5).ToArray();
            }

            return(matrix);
        }
示例#20
0
 /// <summary>Evicts entries from the strongly-referenced cache until the <see cref="MaximumSize"/> is satisfied.</summary>
 private void evictStrong()
 {
     while (CurrentSize > MaximumSize && _strong.Count > 0)
     {
         // Pick two random entries and evict the one that's been used the least.
         var item1 = _strong.Skip(Rnd.Next(_strong.Count)).First();
         var item2 = _strong.Skip(Rnd.Next(_strong.Count)).First();
         if (item1.UseCount < item2.UseCount)
         {
             _strong.Remove(item1);
             CurrentSize -= item1.Strong.Size;
             item1.Strong = null;
         }
         else
         {
             _strong.Remove(item2);
             CurrentSize -= item2.Strong.Size;
             item2.Strong = null;
         }
         Evictions++;
     }
 }
示例#21
0
        private HashSet <KeySet> GetDestinationKeySets(
            HashSet <KeySet> immutableKeySets,
            TableMapping tableMapping,
            Dictionary <string, DbColumnType> destColumnNameTypeMappings,
            IEnumerable <string> keyColumnNames)
        {
            var keySets = new HashSet <KeySet>();

            var chunkIndex = 0;
            var chunkSize  = 1000;

            while (chunkIndex * chunkSize < immutableKeySets.Count)
            {
                var chunkedImmutableKeySets = immutableKeySets.Skip(chunkIndex++ *chunkSize).Take(chunkSize);

                using (IDbCommand cmd = GetDbCommand(
                           BuildSqlCmdTextForLoadDestinationKeySets(
                               chunkedImmutableKeySets,
                               tableMapping,
                               keyColumnNames), _conn, _trans))
                {
                    cmd.CommandTimeout = _sqlCommandTimeout;

                    using (IDataReader dataReader = cmd.ExecuteReader())
                    {
                        while (dataReader.Read())
                        {
                            var keySet = new KeySet();
                            foreach (var keyColumnName in keyColumnNames)
                            {
                                keySet.Add(keyColumnName, destColumnNameTypeMappings[keyColumnName], dataReader[keyColumnName]);
                            }

                            if (keySets.Contains(keySet))
                            {
                                throw new Exception(
                                          string.Format(
                                              "The destination table ({0}) contains data with duplicated keys ({1})",
                                              tableMapping.Destination,
                                              keySet.ToString()));
                            }

                            keySets.Add(keySet);
                        }
                    }
                }
            }

            return(keySets);
        }
示例#22
0
        public static async Task <int> Task1(string file)
        {
            var rules = await ParseRules(file);

            var lookup = rules
                         .SelectMany(kvp => kvp.Value, (kvp, c) => (from: kvp.Key, bag: c.Item1))
                         .ToLookup(x => x.bag, x => x.from);

            var bags = new HashSet <string>();

            BagsThatContain("shiny gold", lookup, bags);

            return(bags.Skip(1).Count());
        }
示例#23
0
        /// <summary>
        /// Helper method for the SetCellContents methods.
        /// Creates and adds valid cells to the object dictionary.
        /// Creates, adds and removes dependecies as needed.
        /// Invariant that the cell name is valid as it was checked in SetContentsOfCell
        ///
        ///
        /// Throws an InvalidNameException if the name is invalid or null
        /// Throws an ArgumentNullException if the contents are null
        /// </summary>
        /// <param name="name"></param>
        /// <param name="contents"></param>
        /// <returns></returns>
        private HashSet <String> HandleSetCell(string name, Object contents)
        {
            HashSet <string> allDependentsForCell;
            Cell             oldCell = null;

            //Checks if the cell already exists
            if (cells.ContainsKey(name))
            {
                oldCell = cells[name];
                cells.Remove(name); //Remove the cell if it exists already
            }
            HashSet <String> oldDependees = RecalculateDependecies(name, contents);

            //Makes a new HashSet of all of the cells that will be affected by changing this cell
            // plus this cell.
            //Throws a CircularException if there is a circular dependency.
            try
            {
                allDependentsForCell = new HashSet <string>(GetCellsToRecalculate(name).ToArray <string>());
            }
            catch (CircularException)
            {
                //If an exception is found, revert the dependency graph and contents then throw the exception
                dependencies.ReplaceDependees(name, oldDependees);
                if (oldCell != null)
                {
                    cells.Add(name, oldCell);
                }
                throw;
            }

            //If the cell doesn't contain an empty string, add the new cell to the set
            // (otherwise it stays removed from the dictionary)
            if (!contents.Equals(""))
            {
                Cell cell = new Cell(contents, Lookup);
                cells.Add(name, cell);
            }

            //Recalculates all of the values that depend on this cell, except for the current cell
            //This is important if the cell is an empty string and doesn't exist in the dictionary
            foreach (String dependent in allDependentsForCell.Skip(1))
            {
                cells[dependent].CalculateValue(Lookup);
            }

            return(allDependentsForCell);
        }
        public ActionResult <ResourceModel> Save(ResourceModel model)
        {
            if (_resourceModification.GetAllResources <IResource>(r => r.Id == model.Id).Count() > 0)
            {
                return(Conflict($"The resource '{model.Id}' already exists."));
            }

            var id = _resourceModification.Create(_resourceTypeTree[model.Type].ResourceType, r => {
                var resourcesToSave = new HashSet <long>();
                var resourceCache   = new Dictionary <long, Resource>();
                FromModel(model, resourcesToSave, resourceCache, r);
                resourcesToSave.Skip(1).ForEach(id => _resourceModification.Modify(id, r => true));
            });

            return(GetDetails(id));
        }
        protected void ReevaluateSelected()
        {
            if (!Children.Any())
            {
                return;
            }
            // The state of this needs to be indeterminate if
            // - at least one child is indeterminate, OR
            // - at least two children differ in state
            // Otherwise, the state of this needs to be the same as all the children, which is the same as the state of the first child.
            var state = Children.First().Selected;

            state = state == null ? null : (Children.Skip(1).Any(c => c.Selected != state) ? null : state);
            if (Selected == state)
            {
                return;
            }
            SelectedChanged(state);
        }
示例#26
0
        /// <summary>
        /// bring out each combination given a set.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="set"></param>
        /// <returns></returns>
        static public HashSet <HashSet <T> > Eval <T>(HashSet <T> set)
        {
            if (set.Count == 0)
            {
                return(new HashSet <HashSet <T> >(
                           new HashSet <T>[] { new HashSet <T>(set.Comparer) }
                           ,

                           HashSet <T> .CreateSetComparer()
                           ));
            }
            else
            {
                ///take the first element
                ///

                //HashSet<T> head= new HashSet<T>();

                //head.Add(set.First());



                HashSet <T> beheadedSet = new HashSet <T>(set.Skip(1), set.Comparer);

                var beheadedSetCombination = Eval(beheadedSet);


                var withFirstCombination = new HashSet <HashSet <T> >(HashSet <T> .CreateSetComparer());

                foreach (var item in beheadedSetCombination)
                {
                    var t = new HashSet <T>(item, set.Comparer);

                    t.Add(set.First());

                    withFirstCombination.Add(t);
                }

                beheadedSetCombination.UnionWith(withFirstCombination);

                return(beheadedSetCombination);
            }
        }
示例#27
0
        /// <summary>
        /// Автоматический шаг дальше
        /// </summary>
        /// <param name="milliseconds"></param>
        protected override void AutoNextCore()
        {
            if (CanSelectQuestion)
            {
                var index = new Random().Next(_questionsTable.Count);
                var pair  = _questionsTable.Skip(index).First();

                SelectQuestion(pair.Item1, pair.Item2);
                return;
            }

            if (CanSelectTheme)
            {
                var themeIndex = new Random().Next(_themesTable.Count);
                themeIndex = _themesTable.Skip(themeIndex).First();

                SelectTheme(themeIndex);
            }
        }
示例#28
0
        public static int CountAcresLongTime(IEnumerable <string> input)
        {
            var area   = GetArea(input);
            var values = new HashSet <int>();

            for (int minute = 0; minute < 1000000000; minute++)
            {
                area = area.Select((s, i) => s.Select((s2, j) => Transform(s2, i, j, area)).ToList()).ToList();
                if ((minute + 1) % 1000 == 0)
                {
                    if (!values.Add(area.Sum(s => s.Count(c => c == '|')) * area.Sum(s => s.Count(c => c == '#'))))
                    {
                        return(values.Skip(1000000 % (minute + 1) - 1).First());
                    }
                }
            }

            return(area.Sum(s => s.Count(c => c == '|')) * area.Sum(s => s.Count(c => c == '#')));
        }
示例#29
0
        public void Ignoring_issuer_should_result_in_one_claim()
        {
            var hashSet = new HashSet <Claim>(_claims, new ClaimComparer(new ClaimComparer.Options {
                IgnoreIssuer = true
            }));

            hashSet.Count.Should().Be(2);

            var item = hashSet.First();

            item.Type.Should().Be("claim_type1");
            item.Value.Should().Be("value");
            item.Issuer.Should().Be("issuer1");

            item = hashSet.Skip(1).First();
            item.Type.Should().Be("claim_type1");
            item.Value.Should().Be("Value");
            item.Issuer.Should().Be("issuer1");
        }
示例#30
0
        static string PlayFair(string input, string key, int dir)
        {
            var set = new HashSet <char>(key.ToUpper() + pfAlphabet);

            var matrix = new char[5][];

            for (int i = 0; i < 5; i++)
            {
                matrix[i] = set.Skip(5 * i).Take(5).ToArray();
            }
            var text = input.ToUpper().Replace('J', 'I').Replace(" ", string.Empty);

            if (text.Length % 2 != 0)
            {
                text += 'X';
            }
            var pairs = Regex.Matches(text, "..").Cast <Match>().Select(x => DuplicatesPlayFair(x.Value.ToCharArray())).ToArray();

            return(string.Join("", pairs.Select(x => new string(PairEncryption(matrix, x, dir))).ToArray()));
        }
示例#31
0
 /// <summary>
 /// 在指定函数调用过程中,从指定的索引分割当前操作为指定长度的集合。
 /// </summary>
 /// <param name="index">开始索引。</param>
 /// <param name="length">操作长度。</param>
 /// <param name="action">执行的操作。</param>
 public void Split(int index, int length, Action action)
 {
     if (length > 0 && index >= 0 && length + index <= Count)
     {
         try
         {
             _SubItems = _Items.Skip(index).Take(length);
             _SubCount = length;
             action();
         }
         finally
         {
             _SubItems = null;
         }
     }
     else
     {
         action();
     }
 }
示例#32
0
        /// <summary>
        /// Get all nodes that in its input ports's scope. A node is in its 
        /// scope if that node is one of its upstream nodes. 
        /// </summary>
        /// <param name="portIndex">Inport index</param>
        /// <param name="checkEscape">
        /// If need to exclude nodes that one of their downstream nodes are not 
        /// in the scope
        /// </param>
        /// <param name="isInclusive">
        /// If a upstream node is ScopedNodeModel, need to include all upstream 
        /// nodes of that node.
        /// </param>
        /// <returns></returns>
        public IEnumerable<NodeModel> GetInScopeNodesForInport(
            int portIndex, 
            bool checkEscape = true, 
            bool isInclusive = true, 
            bool forceToGetNodeForInport = false)
        {
            // The related test cases are in DynmoTest.ScopedNodeTest.
            var scopedNodes = new HashSet<NodeModel>();

            Tuple<int, NodeModel> inputTuple = null;
            if ((!forceToGetNodeForInport && !IsScopedInport(portIndex)) || 
                !this.TryGetInput(portIndex, out inputTuple))
            {
                return scopedNodes;
            }

            scopedNodes.Add(this);
            var inputNode = inputTuple.Item2;
            var workingList = new Queue<NodeModel>();
            if (!checkEscape || (checkEscape && IsNodeInScope(inputNode, scopedNodes)))
            {
                workingList.Enqueue(inputNode);
                scopedNodes.Add(inputNode);
            }

            // Collect all upstream nodes in BFS order
            while (workingList.Any())
            {
                var currentNode = workingList.Dequeue();
                if (!isInclusive && currentNode is ScopedNodeModel)
                {
                    continue;
                }

                foreach (int index in Enumerable.Range(0, currentNode.InPortData.Count))
                {
                    if (currentNode.TryGetInput(index, out inputTuple))
                    {
                        inputNode = inputTuple.Item2;
                        if (!checkEscape || (checkEscape && IsNodeInScope(inputNode, scopedNodes)))
                        {
                            workingList.Enqueue(inputNode);
                            scopedNodes.Add(inputNode);
                        }
                    }
                }
            }

            return scopedNodes.Skip(1);
        }
示例#33
0
        public virtual void GenerateVMTCode(HashSet<Type> aTypesSet, HashSet<MethodBase> aMethodsSet, Func<Type, uint> aGetTypeID, Func<MethodBase, uint> aGetMethodUID)
        {
            new Comment("---------------------------------------------------------");
            new Cosmos.Assembler.Label(InitVMTCodeLabel);
            new Push { DestinationReg = Registers.EBP };
            new Mov { DestinationReg = Registers.EBP, SourceReg = Registers.ESP };
            mSequences = new DebugInfo.SequencePoint[0];

            var xSetTypeInfoRef = VTablesImplRefs.SetTypeInfoRef;
            var xSetMethodInfoRef = VTablesImplRefs.SetMethodInfoRef;
            var xTypesFieldRef = VTablesImplRefs.VTablesImplDef.GetField("mTypes",
                                                                               BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
            string xTheName = DataMember.GetStaticFieldName(xTypesFieldRef);
            DataMember xDataMember = (from item in Cosmos.Assembler.Assembler.CurrentInstance.DataMembers
                                      where item.Name == xTheName
                                      select item).FirstOrDefault();
            if (xDataMember != null)
            {
                Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Remove((from item in Cosmos.Assembler.Assembler.CurrentInstance.DataMembers
                                                                               where item == xDataMember
                                                                               select item).First());
            }
            var xData = new byte[16 + (aTypesSet.Count * GetVTableEntrySize())];
            var xTemp = BitConverter.GetBytes(aGetTypeID(typeof(Array)));
            xTemp = BitConverter.GetBytes(0x80000002);
            Array.Copy(xTemp, 0, xData, 4, 4);
            xTemp = BitConverter.GetBytes(aTypesSet.Count);
            Array.Copy(xTemp, 0, xData, 8, 4);
            xTemp = BitConverter.GetBytes(GetVTableEntrySize());
            Array.Copy(xTemp, 0, xData, 12, 4);
            Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xTheName + "__Contents", xData));
            Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xTheName + "__Handle", ElementReference.New(xTheName + "__Contents")));
            Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xTheName, Cosmos.Assembler.ElementReference.New(xTheName + "__Handle")));
#if VMT_DEBUG
        using (var xVmtDebugOutput = XmlWriter.Create(@"c:\data\vmt_debug.xml"))
        {
            xVmtDebugOutput.WriteStartDocument();
            xVmtDebugOutput.WriteStartElement("VMT");
#endif
            //Push((uint)aTypesSet.Count);
            foreach (var xType in aTypesSet)
            {
#if VMT_DEBUG
                xVmtDebugOutput.WriteStartElement("Type");
                xVmtDebugOutput.WriteAttributeString("TypeId", aGetTypeID(xType).ToString());
                if (xType.BaseType != null)
                {
                    xVmtDebugOutput.WriteAttributeString("BaseTypeId", aGetTypeID(xType.BaseType).ToString());
                }
                xVmtDebugOutput.WriteAttributeString("Name", xType.FullName);
#endif
                // value contains true if the method is an interface method definition
                SortedList<MethodBase, bool> xEmittedMethods = new SortedList<MethodBase, bool>(new MethodBaseComparer());
                foreach (MethodBase xMethod in xType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    if (aMethodsSet.Contains(xMethod))
                    { //) && !xMethod.IsAbstract) {
                        if (!xEmittedMethods.ContainsKey(xMethod))
                        {
                            xEmittedMethods.Add(xMethod, false);
                        }
                    }
                }
                foreach (MethodBase xCtor in xType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    if (aMethodsSet.Contains(xCtor))
                    { // && !xCtor.IsAbstract) {
                        if (!xEmittedMethods.ContainsKey(xCtor))
                        {
                            xEmittedMethods.Add(xCtor, false);
                        }
                    }
                }
                foreach (var xIntf in xType.GetInterfaces())
                {
                    foreach (var xMethodIntf in xIntf.GetMethods())
                    {
                        var xActualMethod = xType.GetMethod(xIntf.FullName + "." + xMethodIntf.Name,
                                                            (from xParam in xMethodIntf.GetParameters()
                                                             select xParam.ParameterType).ToArray());

                        if (xActualMethod == null)
                        {
                            // get private implemenation
                            xActualMethod = xType.GetMethod(xMethodIntf.Name,
                                                            (from xParam in xMethodIntf.GetParameters()
                                                             select xParam.ParameterType).ToArray());
                        }
                        if (xActualMethod == null)
                        {
                            try
                            {
                                if (!xIntf.IsGenericType)
                                {
                                    var xMap = xType.GetInterfaceMap(xIntf);
                                    for (int k = 0; k < xMap.InterfaceMethods.Length; k++)
                                    {
                                        if (xMap.InterfaceMethods[k] == xMethodIntf)
                                        {
                                            xActualMethod = xMap.TargetMethods[k];
                                            break;
                                        }
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                        if (aMethodsSet.Contains(xMethodIntf))
                        {
                            if (!xEmittedMethods.ContainsKey(xMethodIntf))
                            {
                                xEmittedMethods.Add(xMethodIntf, true);
                            }
                        }

                    }
                }
                int? xBaseIndex = null;
                if (xType.BaseType == null)
                {
                    xBaseIndex = (int)aGetTypeID(xType);
                }
                else
                {
                    for (int t = 0; t < aTypesSet.Count; t++)
                    {
                        // todo: optimize check
                        var xItem = aTypesSet.Skip(t).First();
                        if (xItem.ToString() == xType.BaseType.ToString())
                        {
                            xBaseIndex = (int)aGetTypeID(xItem);
                            break;
                        }
                    }
                }
                if (xBaseIndex == null)
                {
                    throw new Exception("Base type not found!");
                }
                for (int x = xEmittedMethods.Count - 1; x >= 0; x--)
                {
                    if (!aMethodsSet.Contains(xEmittedMethods.Keys[x]))
                    {
                        xEmittedMethods.RemoveAt(x);
                    }
                }
                if (!xType.IsInterface)
                {
                    Push(aGetTypeID(xType));
                    Move("VMT__TYPE_ID_HOLDER__" + DataMember.FilterStringForIncorrectChars(LabelName.GetFullName(xType) + " ASM_IS__" + xType.Assembly.GetName().Name), (int)aGetTypeID(xType));
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(
                        new DataMember("VMT__TYPE_ID_HOLDER__" + DataMember.FilterStringForIncorrectChars(LabelName.GetFullName(xType) + " ASM_IS__" + xType.Assembly.GetName().Name), new int[] { (int)aGetTypeID(xType) }));
                    Push((uint)xBaseIndex.Value);
                    xData = new byte[16 + (xEmittedMethods.Count * 4)];
                    xTemp = BitConverter.GetBytes(aGetTypeID(typeof(Array)));
                    Array.Copy(xTemp, 0, xData, 0, 4);
                    xTemp = BitConverter.GetBytes(0x80000002); // embedded array
                    Array.Copy(xTemp, 0, xData, 4, 4);
                    xTemp = BitConverter.GetBytes(xEmittedMethods.Count); // embedded array
                    Array.Copy(xTemp, 0, xData, 8, 4);
                    xTemp = BitConverter.GetBytes(4); // embedded array
                    Array.Copy(xTemp, 0, xData, 12, 4);
                    string xDataName = "____SYSTEM____TYPE___" + DataMember.FilterStringForIncorrectChars(LabelName.GetFullName(xType) + " ASM_IS__" + xType.Assembly.GetName().Name) + "__MethodIndexesArray";
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, xData));
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName + "_Handle", ElementReference.New(xDataName)));
                    Push(xDataName + "_Handle");
                    xDataName = "____SYSTEM____TYPE___" + DataMember.FilterStringForIncorrectChars(LabelName.GetFullName(xType) + " ASM_IS__" + xType.Assembly.GetName().Name) + "__MethodAddressesArray";
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, xData));
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName + "_Handle", ElementReference.New(xDataName)));
                    Push(xDataName + "_Handle");
                    xData = new byte[16 + Encoding.Unicode.GetByteCount(xType.FullName + ", " + xType.Module.Assembly.GetName().FullName)];
                    xTemp = BitConverter.GetBytes(aGetTypeID(typeof(Array)));
                    Array.Copy(xTemp, 0, xData, 0, 4);
                    xTemp = BitConverter.GetBytes(0x80000002); // embedded array
                    Array.Copy(xTemp, 0, xData, 4, 4);
                    xTemp = BitConverter.GetBytes((xType.FullName + ", " + xType.Module.Assembly.GetName().FullName).Length);
                    Array.Copy(xTemp, 0, xData, 8, 4);
                    xTemp = BitConverter.GetBytes(2); // embedded array
                    Array.Copy(xTemp, 0, xData, 12, 4);
                    xDataName = "____SYSTEM____TYPE___" + DataMember.FilterStringForIncorrectChars(LabelName.GetFullName(xType) + " ASM_IS__" + xType.Assembly.GetName().Name);
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, xData));
                    Cosmos.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName + "_Handle", ElementReference.New(xDataName)));
                    Push("0" + xEmittedMethods.Count.ToString("X") + "h");
                    Call(xSetTypeInfoRef);
                }
                for (int j = 0; j < xEmittedMethods.Count; j++)
                {
                    MethodBase xMethod = xEmittedMethods.Keys[j];
#if VMT_DEBUG
                    xVmtDebugOutput.WriteStartElement("Method");
                    xVmtDebugOutput.WriteAttributeString("Id", aGetMethodUID(xMethod).ToString());
                    xVmtDebugOutput.WriteAttributeString("Name", xMethod.GetFullName());
                    xVmtDebugOutput.WriteEndElement();
#endif
                    var xMethodId = aGetMethodUID(xMethod);
                    if (!xType.IsInterface)
                    {
                        if (xEmittedMethods.Values[j])
                        {
                            var xNewMethod = xType.GetMethod(xMethod.DeclaringType.FullName + "." + xMethod.Name,
                                                                (from xParam in xMethod.GetParameters()
                                                                 select xParam.ParameterType).ToArray());

                            if (xNewMethod == null)
                            {
                                // get private implementation
                                xNewMethod = xType.GetMethod(xMethod.Name,
                                                                (from xParam in xMethod.GetParameters()
                                                                 select xParam.ParameterType).ToArray());
                            }
                            if (xNewMethod == null)
                            {
                                try
                                {
                                    var xMap = xType.GetInterfaceMap(xMethod.DeclaringType);
                                    for (int k = 0; k < xMap.InterfaceMethods.Length; k++)
                                    {
                                        if (xMap.InterfaceMethods[k] == xMethod)
                                        {
                                            xNewMethod = xMap.TargetMethods[k];
                                            break;
                                        }
                                    }
                                }
                                catch
                                {
                                }
                            }
                            xMethod = xNewMethod;
                        }

                        Push((uint)aGetTypeID(xType));
                        Push((uint)j);

                        Push((uint)xMethodId);
                        if (xMethod.IsAbstract)
                        {
                            // abstract methods dont have bodies, oiw, are not emitted
                            Push(0);
                        }
                        else
                        {
                            Push(ILOp.GetMethodLabel(xMethod));
                        }
                        Push(0);
                        Call(VTablesImplRefs.SetMethodInfoRef);
                    }
                }
#if VMT_DEBUG
                xVmtDebugOutput.WriteEndElement(); // type
#endif
            }
#if VMT_DEBUG
                    xVmtDebugOutput.WriteEndElement(); // types
                    xVmtDebugOutput.WriteEndDocument();
        }
#endif

            new Cosmos.Assembler.Label("_END_OF_" + InitVMTCodeLabel);
            new Pop { DestinationReg = Registers.EBP };
            new Return();
        }
示例#34
0
        protected async Task FetchUrlInfos(Status[] ses)
        {
            if (ses == null || ses.Length == 0)
                return;
            var mem = MemoryCache.Default;

            var urls = new HashSet<string>();
            foreach (var s in ses)
            {
                var us = Utils.ExtractUrlFromWeibo(s.text);
                foreach(var url in us)
                {
                    if (mem.Get("http://t.cn/" + url) == null)
                        urls.Add(url);
                }
                //urls.Add(us);
                if (s.retweeted_status != null)
                {
                    var rus = Utils.ExtractUrlFromWeibo(s.retweeted_status.text);
                    foreach (var url in rus)
                    {
                        if (mem.Get("http://t.cn/" + url) == null)
                            urls.Add(url);
                    }
                }
            }
            if(urls.Count >= 20)
            {
                var tasks = new Task[2];
                var u1 = urls.Take(20);
                tasks[0] = FetchUrlInfosImp(u1);
                var u2 = urls.Skip(20);
                tasks[1] = FetchUrlInfosImp(u2);
                await Task.WhenAll(tasks);
            }else
            {
                await FetchUrlInfosImp(urls);
            }

        }
        //added by gremlin aggruthmanager
        private void DoAggRuthAgentManager()
        {
            string Names;

            float income = this.spyBudget;

            this.DesiredAgentsPerHostile = (int)(income * .08f) + 1;
            this.DesiredAgentsPerNeutral = (int)(income * .03f) + 1;

            //this.DesiredAgentsPerHostile = 5;
            //this.DesiredAgentsPerNeutral = 2;
            this.BaseAgents = empire.GetPlanets().Count / 2;
            this.DesiredAgentCount = 0;
            foreach (KeyValuePair<Empire, Ship_Game.Gameplay.Relationship> Relationship in this.empire.GetRelations())
            {
                if (!Relationship.Value.Known || Relationship.Key.isFaction || Relationship.Key.data.Defeated)
                {
                    continue;
                }
                if (Relationship.Value.Posture == Posture.Hostile)
                {
                    GSAI desiredAgentCount = this;
                    desiredAgentCount.DesiredAgentCount = desiredAgentCount.DesiredAgentCount + this.DesiredAgentsPerHostile;
                }
                if (Relationship.Value.Posture != Posture.Neutral)
                {
                    continue;
                }
                GSAI gSAI = this;
                gSAI.DesiredAgentCount = gSAI.DesiredAgentCount + this.DesiredAgentsPerNeutral;
            }
            GSAI desiredAgentCount1 = this;
            desiredAgentCount1.DesiredAgentCount = desiredAgentCount1.DesiredAgentCount + this.BaseAgents;

            int empirePlanetSpys = this.empire.GetPlanets().Count() / 3 + 3;// (int)(this.spyBudget / (this.empire.GrossTaxes * 3));
            int currentSpies = this.empire.data.AgentList.Count;
            if (this.spyBudget >= 250f && currentSpies < empirePlanetSpys)
            {
                Names = (!File.Exists(string.Concat("Content/NameGenerators/spynames_", this.empire.data.Traits.ShipType, ".txt")) ? File.ReadAllText("Content/NameGenerators/spynames_Humans.txt") : File.ReadAllText(string.Concat("Content/NameGenerators/spynames_", this.empire.data.Traits.ShipType, ".txt")));
                string[] Tokens = Names.Split(new char[] { ',' });
                Agent a = new Agent();
                a.Name = AgentComponent.GetName(Tokens);
                this.empire.data.AgentList.Add(a);
                this.spyBudget -= 250f;
            }
            int Defenders = 0;
            int Offense = 0;
            foreach (Agent a in this.empire.data.AgentList)
            {
                if (a.Mission == AgentMission.Defending)
                {
                    Defenders++;
                }
                else if (a.Mission != AgentMission.Undercover)
                {
                    Offense++;
                }
                if (a.Mission != AgentMission.Defending || a.Level >= 2 || this.spyBudget <= 50f)
                {
                    continue;
                }
                a.AssignMission(AgentMission.Training, this.empire, "");
            }
            int DesiredOffense = (int)(this.empire.data.AgentList.Count  * .3f);
            //int DesiredOffense = (int)(this.empire.data.AgentList.Count - empire.GetPlanets().Count * .33f); // (int)(0.33f * (float)this.empire.data.AgentList.Count);
            //int DesiredOffense = this.empire.data.AgentList.Count / 2;
            foreach (Agent agent in this.empire.data.AgentList)
            {
                if (agent.Mission != AgentMission.Defending && agent.Mission != AgentMission.Undercover || Offense >= DesiredOffense )
                {
                    continue;
                }
                List<Empire> PotentialTargets = new List<Empire>();
                foreach (KeyValuePair<Empire, Ship_Game.Gameplay.Relationship> Relation in this.empire.GetRelations())
                {
                    if (!Relation.Value.Known || Relation.Key.isFaction || Relation.Key.data.Defeated || Relation.Value.Posture != Posture.Neutral && Relation.Value.Posture != Posture.Hostile)
                    {
                        continue;
                    }
                    PotentialTargets.Add(Relation.Key);
                }
                if (PotentialTargets.Count <= 0)
                {
                    continue;
                }
                HashSet<AgentMission> PotentialMissions = new HashSet<AgentMission>();
                Empire Target = PotentialTargets[HelperFunctions.GetRandomIndex(PotentialTargets.Count)];
                if (this.empire.GetRelations()[Target].AtWar)
                {
                    if (agent.Level >= 8)
                    {
                        PotentialMissions.Add(AgentMission.InciteRebellion);
                        PotentialMissions.Add(AgentMission.Assassinate);

                        PotentialMissions.Add(AgentMission.StealTech);
                    }
                    if (agent.Level >= 4)
                    {
                        PotentialMissions.Add(AgentMission.StealTech);
                        PotentialMissions.Add(AgentMission.Robbery);
                        PotentialMissions.Add(AgentMission.Sabotage);
                    }
                    if (agent.Level < 4)
                    {
                        PotentialMissions.Add(AgentMission.Sabotage);
                        PotentialMissions.Add(AgentMission.StealTech);
                        PotentialMissions.Add(AgentMission.Robbery);
                        //PotentialMissions.Add(AgentMission.Infiltrate);
                    }
                }
                if (this.empire.GetRelations()[Target].Posture == Posture.Hostile)
                {
                    if (agent.Level >= 8)
                    {
                        PotentialMissions.Add(AgentMission.StealTech);
                        PotentialMissions.Add(AgentMission.Assassinate);
                    }
                    if (agent.Level >= 4)
                    {
                        PotentialMissions.Add(AgentMission.Robbery);
                        PotentialMissions.Add(AgentMission.Sabotage);

                    }
                    if (agent.Level < 4)
                    {
                        PotentialMissions.Add(AgentMission.Sabotage);

                    }
                }

                if (this.empire.GetRelations()[Target].SpiesDetected > 0)
                {
                    if (agent.Level >= 4) PotentialMissions.Add(AgentMission.Assassinate);
                }
                HashSet<AgentMission> remove = new HashSet<AgentMission>();
                foreach(AgentMission mission in PotentialMissions)
                {
                    switch (mission)
                    {
                        case AgentMission.Defending:
                        case AgentMission.Training:
                            break;
                        case AgentMission.Infiltrate:
                            if (ResourceManager.AgentMissionData.InfiltrateCost > this.spyBudget)
                            {
                                remove.Add(mission);
                            }
                            break;
                        case AgentMission.Assassinate:
                            if (ResourceManager.AgentMissionData.AssassinateCost > this.spyBudget)
                            {
                                remove.Add(mission);
                            }
                            break;
                        case AgentMission.Sabotage:
                            if (ResourceManager.AgentMissionData.SabotageCost > this.spyBudget)
                            {
                                remove.Add(mission);
                            }
                            break;
                        case AgentMission.StealTech:
                            if (ResourceManager.AgentMissionData.StealTechCost > this.spyBudget)
                            {
                                remove.Add(mission);
                            }
                            break;
                        case AgentMission.Robbery:
                            if (ResourceManager.AgentMissionData.RobberyCost > this.spyBudget)
                            {
                                remove.Add(mission);
                            }
                            break;
                        case AgentMission.InciteRebellion:
                            if (ResourceManager.AgentMissionData.RebellionCost > this.spyBudget)
                            {
                                remove.Add(mission);
                            }
                            break;
                        case AgentMission.Undercover:
                            if (ResourceManager.AgentMissionData.InfiltrateCost > this.spyBudget)
                            {
                                remove.Add(mission);
                            }
                            break;
                        case AgentMission.Recovering:
                            break;
                        default:
                            break;
                    }
                }
                foreach(AgentMission removeMission in remove)
                {
                    PotentialMissions.Remove(removeMission);
                }
                if (PotentialMissions.Count <= 0)
                {
                    continue;
                }
                AgentMission am = PotentialMissions.Skip(HelperFunctions.GetRandomIndex(PotentialMissions.Count)).FirstOrDefault();
                if(am !=null)
                agent.AssignMission(am, this.empire, Target.data.Traits.Name);
                Offense++;

            }
        }