예제 #1
0
        static void Main(string[] args)
        {
            SortedSet <int> n = new SortedSet <int>();
            SortedSet <int> m = new SortedSet <int>();

            int[] lengths = Console.ReadLine().Split().Select(s => Int32.Parse(s)).ToArray();

            for (int i = 0; i < lengths[0]; i++)
            {
                int temp = Int32.Parse(Console.ReadLine());
                if (!n.Any(k => k == temp))
                {
                    n.Add(temp);
                }
            }
            for (int i = 0; i < lengths[1]; i++)
            {
                int temp = Int32.Parse(Console.ReadLine());
                if (!m.Any(k => k == temp))
                {
                    m.Add(temp);
                }
            }
            StringBuilder sb = new StringBuilder();

            foreach (var el in n)
            {
                if (m.Any(e => e == el))
                {
                    sb.Append(el + " ");
                }
            }
            Console.WriteLine(sb.ToString().Trim());
            Console.ReadLine();
        }
예제 #2
0
        public void TestSortedSet()
        {
            var set     = new SortedSet <int>();
            var r1      = set.Add(1);
            var r1Again = set.Add(1);

            set.Add(2);
            set.Add(3);
            set.Add(4);
            set.Add(6);
            set.Add(7);
            set.Add(8);

            //重复加返回false
            Assert.IsTrue(r1);
            Assert.IsFalse(r1Again);

            //where 后toList还是保持本来的顺序
            var where = set.Where(a => a < 6).ToList();
            Assert.AreEqual(where[0], 1);

            if (set.Any(s => s < -1))
            {
                //不会执行到
                var small = set.Where(s => s < -1).Max();
            }


            if (set.Any(s => s < 6))
            {
                //where后取max min还能取到的
                var small = set.Where(s => s < 6).Max();
                Assert.AreEqual(small, 4);
            }
        }
        public void DataIntegrity_AllCharacterIdsAndDefaultCharactersHaveCharacterDetail()
        {
            CharacterDetailData.TabDelimitedCharacterDetailData = Resources.CharacterDetail;             //resets cache

            var           charactersHavingDetail   = CharacterDetailData.Singleton.GetAll().Select(d => d.CharacterId).ToList();
            ISet <string> missingCharacters        = new SortedSet <string>();
            ISet <string> missingDefaultCharacters = new SortedSet <string>();

            foreach (CharacterVerse cv in ControlCharacterVerseData.Singleton.GetAllQuoteInfo())
            {
                if (!charactersHavingDetail.Contains(cv.Character))
                {
                    if (CharacterVerseData.IsCharacterStandard(cv.Character) || cv.Character == CharacterVerseData.kNeedsReview)
                    {
                        continue;
                    }
                    // For interruptions, we actually never pay any attention to the character ID. They are always narrator.
                    // But in some verses we have both a normal narrator Quotation and an interruption, so to avoid a problem
                    // in other data integrity checks, we just use the dummy character id "interruption-XXX" (where XXX is the
                    // 3-letter book code.
                    if (cv.QuoteType == QuoteType.Interruption || cv.Character.StartsWith("interruption-"))
                    {
                        continue;
                    }

                    var characters = cv.Character.Split('/');
                    if (characters.Length > 1)
                    {
                        foreach (var character in characters.Where(character => !charactersHavingDetail.Contains(character)))
                        {
                            missingCharacters.Add(character);
                        }
                    }
                    else
                    {
                        missingCharacters.Add(cv.Character);
                    }
                }

                if (!(string.IsNullOrEmpty(cv.DefaultCharacter) || charactersHavingDetail.Contains(cv.DefaultCharacter)))
                {
                    if (CharacterVerseData.IsCharacterStandard(cv.DefaultCharacter) || cv.DefaultCharacter == CharacterVerseData.kNeedsReview)
                    {
                        continue;
                    }

                    missingDefaultCharacters.Add(cv.DefaultCharacter);
                }
            }

            Assert.False(missingCharacters.Any() || missingDefaultCharacters.Any(),
                         (missingCharacters.Any() ? "Characters in Character-Verse data but not in Character-Detail:" +
                          Environment.NewLine +
                          missingCharacters.OnePerLineWithIndent() : "") +
                         (missingDefaultCharacters.Any() ? Environment.NewLine +
                          "Default characters in Character-Verse data but not in Character-Detail:" +
                          Environment.NewLine +
                          missingDefaultCharacters.OnePerLineWithIndent() : ""));
        }
예제 #4
0
        public void ComputePreconditions()
        {
            var NameToImpl = new Func <string, Implementation>(name =>
                                                               BoogieUtil.findProcedureImpl(program.TopLevelDeclarations, name));
            var main = id2Graph[program.mainProcName];

            main.UpdatePrecondition(main.precondition.Top(NameToImpl(main.Id)));

            IntraGraph.TopDown = true;
            var worklist = new SortedSet <IntraGraph>(main);

            worklist.Add(main);

            var SetPrecondition = new Action <string, IWeight>((name, weight) =>
            {
                var g       = id2Graph[name];
                var changed = g.UpdatePrecondition(weight);
                if (changed)
                {
                    worklist.Add(g);
                }
            });

            while (worklist.Any())
            {
                var proc = worklist.First();
                worklist.Remove(proc);
                proc.PropagatePrecondition(NameToImpl, SetPrecondition);
            }

            IntraGraph.TopDown = false;
        }
예제 #5
0
        private static bool promoRights()
        {
            bool ret = false; // assume failure

            try
            {
                foreach (AcUser user in _users.OrderBy(n => n))
                {
                    SortedSet <string>   groups = user.Principal.Members;                      // the list of groups this user is a member of
                    IEnumerable <string> query  = from ef in _locks.Select(lk => lk.ExceptFor) // locks applied to all except this group
                                                  where groups.Any(g => g == ef)               // any group in groups list that matches an ExceptFor group
                                                  select ef;
                    string found = query.FirstOrDefault();                                     // not null indicates the user has promote privileges somewhere
                    Console.WriteLine($"{user}\t{((found == null) ? "None" : "ExceptFor")}");
                }

                ret = true;
            }

            catch (Exception ecx)
            {
                AcDebug.Log($"Exception caught and logged in Program.promoRights{Environment.NewLine}{ecx.Message}");
            }

            return(ret);
        }
예제 #6
0
        public IList <int[]> KSmallestPairs(int[] nums1, int[] nums2, int k)
        {
            var ans = new List <int[]>();

            if (nums1.Length == 0 || nums2.Length == 0 || k == 0)
            {
                return(ans);
            }
            var heap = new SortedSet <int[]>(Comparer <int[]> .Create((a, b) =>
            {
                var result = a[0] + a[1] - b[0] - b[1];
                if (result == 0)
                {
                    return(a[3] - b[3]);
                }
                return(result);
            }));

            for (int i = 0; i < nums1.Length && i < k; i++)
            {
                heap.Add(new int[] { nums1[i], nums2[0], 0, i });
            }
            while (k-- > 0 && heap.Any())
            {
                int[] cur = heap.Min;
                ans.Add(new int[] { cur[0], cur[1] });
                heap.Remove(cur);
                if (cur[2] == nums2.Length - 1)
                {
                    continue;
                }
                heap.Add(new int[] { cur[0], nums2[cur[2] + 1], cur[2] + 1, cur[3] });
            }
            return(ans);
        }
        private static void Main()
        {
            var start = new Position(Console.ReadLine()
                                     .Split(' ')
                                     .Select(int.Parse)
                                     .ToArray());

            var size = new Position(Console.ReadLine()
                                    .Split(' ')
                                    .Select(int.Parse)
                                    .ToArray());

            matrix = new int[size.Row, size.Col];
            Position.RowsLenght = size.Row;
            Position.ColsLenght = size.Col;

            visited.Add(start);

            FillMattrix();
            GetTotalTeleportationPower(start, 0);

            if (powers.Any())
            {
                Console.WriteLine(powers.Max());
            }
            else
            {
                Console.WriteLine(0);
            }
        }
예제 #8
0
        public static void Main()
        {
            var reservationsList = new SortedSet <string>();

            var input = Console.ReadLine();

            while (input != "PARTY")
            {
                reservationsList.Add(input);
                input = Console.ReadLine();
            }

            while (input != "END")
            {
                reservationsList.Remove(input);
                input = Console.ReadLine();
            }

            if (reservationsList.Any())
            {
                Console.WriteLine(reservationsList.Count);

                foreach (var guestNumber in reservationsList)
                {
                    Console.WriteLine(guestNumber);
                }
            }
            else
            {
                Console.WriteLine(reservationsList.Count);
            }
        }
예제 #9
0
        public static void Main()
        {
            var input   = Console.ReadLine();
            var parking = new SortedSet <string>();

            while (input != "END")
            {
                var inputParams = Regex.Split(input, ", ");
                if (inputParams[0] == "IN")
                {
                    parking.Add(inputParams[1]);
                }
                else if (inputParams[0] == "OUT")
                {
                    parking.Remove(inputParams[1]);
                }
                input = Console.ReadLine();
            }
            if (parking.Any())
            {
                foreach (var car in parking)
                {
                    Console.WriteLine(car);
                }
            }
            else
            {
                Console.WriteLine("Parking Lot is Empty");
            }
        }
예제 #10
0
 static void Minimization()
 {
     _minimizedFinalStates    = new SortedSet <string>();
     _minimizedNonFinalStates = new SortedSet <string>();
     foreach (string state in _reachableStates)
     {
         if (_finalStates.Contains(state))
         {
             _minimizedFinalStates.Add(state);
         }
         else
         {
             _minimizedNonFinalStates.Add(state);
         }
     }
     if (_minimizedNonFinalStates.Any())
     {
         _statePartitions.Add(_minimizedNonFinalStates);
     }
     if (_minimizedFinalStates.Any())
     {
         _statePartitions.Add(_minimizedFinalStates);
     }
     PartitionRefinement(ref _statePartitions);
     UpdateData();
 }
예제 #11
0
        public static int LastStoneWeight(int[] stones)
        {
            var len = stones.Length;
            var set = new SortedSet <Tuple <int, int> >(new WeightComparer());

            for (var i = 0; i < stones.Length; i++)
            {
                set.Add(new Tuple <int, int>(stones[i], i));
            }

            while (set.Count > 1)
            {
                var y = set.First();
                set.Remove(y);
                var x = set.First();
                set.Remove(x);

                if (x.Item1 != y.Item1)
                {
                    len++;
                    set.Add(new Tuple <int, int>(y.Item1 - x.Item1, len));
                }
            }

            return(set.Any() ? set.First().Item1 : 0);
        }
예제 #12
0
파일: Regex.cs 프로젝트: Porges/Fastre
 private Or(SortedSet <Regex <T> > regexes)
     : base(
         regexes.Any(r => r.AcceptsEmptyString),
         regexes.Aggregate(RegexType.Or.GetHashCode(), (hash, rex) => hash * 7 + rex.GetHashCode()))
 {
     _regexes = regexes;
 }
예제 #13
0
 private void SetMedianDay()
 {
     if (visibleDays.Any())
     {
         MedianDay = visibleDays.First() + (visibleDays.Last() - visibleDays.First()).Divide(2);
     }
 }
예제 #14
0
        public LookupResult LookupWord(string word)
        {
            if (word.Length <= 2)
            {
                return(LookupResult.PartialMatch);
            }

            string prefix = word.Substring(0, 2);

            if (!_words.ContainsKey(prefix))
            {
                return(LookupResult.NoMatch);
            }

            SortedSet <String> bucket = _words[prefix];

            if (!bucket.Any(a => a.StartsWith(word)))
            {
                return(LookupResult.NoMatch);
            }

            if (bucket.Contains(word))
            {
                return(LookupResult.Match);
            }

            return(LookupResult.PartialMatch);
        }
        private string AssertAllBaseTextCharacters(HuffmanNode root)
        {
            bool[] characters = new bool[char.MaxValue];

            foreach (char character in baseText)
            {
                characters[character] = true;
            }

            var huffmanTreeCharacters = new SortedSet <char>();
            var baseTextCharacters    = new SortedSet <char>(characters
                                                             .Select((wasEncountered, index) => new { WasEncountered = wasEncountered, Character = (char)index })
                                                             .Where(x => x.WasEncountered)
                                                             .Select(x => x.Character));

            NodeVisitor(root, node =>
            {
                if (node.Character > 0)
                {
                    huffmanTreeCharacters.Add(node.Character);
                }
                return(null);
            });

            baseTextCharacters.ExceptWith(huffmanTreeCharacters);

            return(baseTextCharacters.Any()
            ? $"Huffman tree does not contain '{baseTextCharacters.First()}' that was in base text"
            : null);
        }
예제 #16
0
        public void PropagatePrecondition(Func <string, Implementation> NameToImpl, Action <string, IWeight> SetPrecondition)
        {
            foreach (var node in Nodes)
            {
                node.weight = iw.Zero(impl);
            }
            entryNode.weight = precondition;

            var worklist = new SortedSet <Node>(entryNode);

            worklist.Add(entryNode);

            while (worklist.Any())
            {
                var node = worklist.First();
                worklist.Remove(node);

                foreach (var edge in node.Successors)
                {
                    var c = edge.PropagatePrecondition(ProcSummary, NameToImpl, SetPrecondition);
                    if (c)
                    {
                        worklist.Add(edge.tgt);
                    }
                }
            }
        }
        /// <summary>
        /// Finds the related table names of the current query.
        /// </summary>
        public SortedSet <string> GetCacheDependencies(EFCachePolicy cachePolicy, SortedSet <string> tableNames, string commandText)
        {
            if (cachePolicy == null)
            {
                throw new ArgumentNullException(nameof(cachePolicy));
            }

            var textsInsideSquareBrackets = _sqlCommandsProcessor.GetSqlCommandTableNames(commandText);
            var cacheDependencies         = new SortedSet <string>(
                tableNames.Intersect(textsInsideSquareBrackets, StringComparer.OrdinalIgnoreCase),
                StringComparer.OrdinalIgnoreCase);

            if (cacheDependencies.Any())
            {
                logProcess(tableNames, textsInsideSquareBrackets, cacheDependencies);
                return(cacheDependencies);
            }

            cacheDependencies = cachePolicy.CacheItemsDependencies as SortedSet <string>;
            if (cacheDependencies?.Any() != true)
            {
                _logger.LogDebug($"It's not possible to calculate the related table names of the current query[{commandText}]. Please use EFCachePolicy.Configure(options => options.CacheDependencies(\"real_table_name_1\", \"real_table_name_2\")) to specify them explicitly.");
                cacheDependencies = new SortedSet <string>(StringComparer.OrdinalIgnoreCase)
                {
                    EFCachePolicy.EFUnknownsCacheDependency
                };
            }
            logProcess(tableNames, textsInsideSquareBrackets, cacheDependencies);
            return(cacheDependencies);
        }
예제 #18
0
        public Dictionary <string, SortedSet <string> > CalculateDependencies()
        {
            // for each node list nodes it depends on (i.e. reverse traverse)
            var processors   = Nodes.ToDictionary(n => n.ID, n => RFGraphDefinition.GetFullName(n.GraphName, n.Label));
            var dependencies = new Dictionary <string, SortedSet <string> >();

            foreach (var node in Nodes)
            {
                var visited = new SortedSet <int>();
                var toVisit = new SortedSet <int>(Edges.Where(e => e.DestinationNode == node.ID).Select(e => e.SourceNode));
                while (toVisit.Any())
                {
                    var next = toVisit.First();
                    toVisit.Remove(next);
                    if (!visited.Contains(next))
                    {
                        visited.Add(next);
                        foreach (var source in Edges.Where(e => e.DestinationNode == next).Select(e => e.SourceNode))
                        {
                            if (!visited.Contains(source))
                            {
                                toVisit.Add(source);
                            }
                        }
                    }
                }
                dependencies.Add(processors[node.ID], new SortedSet <string>(visited.Where(v => processors.ContainsKey(v)).Select(v => processors[v])));
            }
            return(dependencies);
        }
예제 #19
0
    static void Main()
    {
        var findedAreas = new SortedSet<Area>();
        for (int row = 0; row < matrix.GetLength(0); row++)
        {
            for (int col = 0; col < matrix.GetLength(1); col++)
            {
                if (matrix[row, col] == ' ')
                {
                    GetConnectedAreaSize(row, col);
                    var area = new Area(row, col, areaSize);
                    findedAreas.Add(area);
                    areaSize = 0;
                }
            }
        }

        if (findedAreas.Any())
        {
            Console.WriteLine("Total areas found: {0}", findedAreas.Count);
            int number = 0;
            foreach (var area in findedAreas)
            {
                ++number;
                Console.WriteLine("Area #{0} at {1}", number, area.ToString());
            }
        }
    }
예제 #20
0
        static void Main(string[] args)
        {
            SortedSet <string> uniqueElements = new SortedSet <string>();

            int numberOfLines = int.Parse(Console.ReadLine());

            for (int i = 0; i < numberOfLines; i++)
            {
                string[] elements = Console.ReadLine()
                                    .Split(" ", StringSplitOptions.RemoveEmptyEntries)
                                    .ToArray();

                foreach (string element in elements)
                {
                    uniqueElements.Add(element);
                }
            }

            bool areAny = uniqueElements.Any();

            if (areAny)
            {
                Console.WriteLine(string.Join(" ", uniqueElements));
            }
        }
예제 #21
0
        static void Main(string[] args)
        {
            SortedSet <string> invited = new SortedSet <string>();

            string input = Console.ReadLine();

            while (input != "PARTY")
            {
                invited.Add(input);
                input = Console.ReadLine();
            }
            input = Console.ReadLine();
            while (input != "END")
            {
                if (invited.Any(i => i == input))
                {
                    invited.Remove(input);
                }
                input = Console.ReadLine();
            }
            Console.WriteLine(invited.Count);
            foreach (var person in invited)
            {
                Console.WriteLine(person);
            }
            Console.ReadLine();
        }
        protected override List <TestResult> GetTestResults()
        {
            var testResults = new List <TestResult>();

            testResults.Add(new TestResult(ResultType.Success, new Location(""),
                                           string.Format(Noark5Messages.DatesFirstAndLastRegistrationMessage_NumberOfRegistrations, _registrationCount)));

            if (_registrationCreationDates.Any())
            {
                testResults.Add(new TestResult(ResultType.Success, new Location(""),
                                               string.Format(Noark5Messages.DatesFirstAndLastRegistrationMessage_CreationDateFirstRegistration, _registrationCreationDates.First().ToShortDateString())));
                testResults.Add(new TestResult(ResultType.Success, new Location(""),
                                               string.Format(Noark5Messages.DatesFirstAndLastRegistrationMessage_CreationDateLastRegistration, _registrationCreationDates.Last().ToShortDateString())));
            }
            else
            {
                testResults.Add(new TestResult(ResultType.Error, new Location(""),
                                               Noark5Messages.DatesFirstAndLastRegistrationMessage_NoValidRegistrationCreationDates));
            }

            if (_invalidRegistrationCreationDateCount > 0)
            {
                testResults.Add(new TestResult(ResultType.Error, new Location(""),
                                               string.Format(Noark5Messages.DatesFirstAndLastRegistrationMessage_NumberOfInvalidRegistrationCreationDates, _invalidRegistrationCreationDateCount)));
            }

            return(testResults);
        }
예제 #23
0
        /// <summary>
        /// my solution
        /// </summary>
        /// <param name="lists"></param>
        /// <returns></returns>
        public static ListNode MergeKLists(ListNode[] lists)
        {
            var dummy = new ListNode(0);       //dummy head;
            var tail  = dummy;
            var heap  = new SortedSet <int>(); //  SortedSet +Dictionary 来模拟 PQ
            var dict  = new Dictionary <int, List <ListNode> >();

            foreach (var node in lists)   // 将节点装入 PQ
            {
                if (node == null)
                {
                    continue;
                }
                AddToPQ(heap, node, dict);
            }
            while (heap.Any())
            {
                var node = RemoveMin(heap, dict); //取出,并删除最小的
                tail.next = node;
                tail      = tail.next;            // my bug 需要移动
                if (node.next != null)
                {
                    AddToPQ(heap, node.next, dict);  // 如果最小的 的 next不空,则装入PQ
                }
            }
            return(dummy.next);
        }
예제 #24
0
        /// <summary>
        /// Writes the paths to the output files to a text file.
        /// </summary>
        /// <param name="path">Path to write file.</param>
        /// <param name="fileTransfers">Collection of files that were transferred to the output directory.</param>
        private void CreateOutputsFile(string path, IEnumerable <ITrackedFile> trackedFiles)
        {
            var uniqueOutputPaths = new SortedSet <string>(trackedFiles.Where(t => t.Clean).Select(t => t.Path), StringComparer.OrdinalIgnoreCase);

            if (!uniqueOutputPaths.Any())
            {
                return;
            }

            var directory = Path.GetDirectoryName(path);

            Directory.CreateDirectory(directory);

            using (var outputs = new StreamWriter(path, false))
            {
                //// Don't list files where the source is the same as the destination since
                //// that might be the only place the file exists. The outputs file is often
                //// used to delete stuff and losing the original source would be bad.
                //var uniqueOutputPaths = new SortedSet<string>(fileTransfers.Where(ft => !ft.Redundant).Select(ft => ft.Destination), StringComparer.OrdinalIgnoreCase);

                foreach (var outputPath in uniqueOutputPaths)
                {
                    outputs.WriteLine(outputPath);
                }
            }
        }
예제 #25
0
    public ListNode MergeKLists(ListNode[] lists)
    {
        var heap = new SortedSet <Tuple <ListNode, int> >(new Comparer());

        for (var i = 0; i < lists.Length; ++i)
        {
            if (lists[i] != null)
            {
                heap.Add(Tuple.Create(lists[i], i));
            }
        }
        ListNode head    = null;
        ListNode current = null;

        while (heap.Any())
        {
            var min = heap.Min;
            heap.Remove(min);
            if (min.Item1.next != null)
            {
                heap.Add(Tuple.Create(min.Item1.next, min.Item2));
            }
            if (head == null)
            {
                head    = min.Item1;
                current = head;
            }
            else
            {
                current.next = min.Item1;
                current      = current.next;
            }
        }
        return(head);
    }
예제 #26
0
        private static int[] ClimbingLeaderboard(int[] scores, int[] alice)
        {
            int[] ret       = new int[alice.Length];
            var   sortedSet = new SortedSet <int>(scores);
            int   last      = alice[0];
            bool  inserted  = false;

            for (int i = 0; i < alice.Length; i++)
            {
                if (inserted)
                {
                    sortedSet.Remove(last);
                    inserted = false;
                }
                if (!sortedSet.Any(x => x == last))
                {
                    sortedSet.Add(alice[i]);
                    last     = alice[i];
                    inserted = true;
                }
                ret[i] = sortedSet.Count(x => x > alice[i]) + 1;
            }

            return(ret);
        }
예제 #27
0
파일: Ledger.cs 프로젝트: nofuture-git/31g
        public virtual bool IsBalanced()
        {
            if (!_dataStore.Any())
            {
                return(true);
            }
            var assetAccounts     = new List <IAccount <Identifier> >();
            var liabilityAccounts = new List <IAccount <Identifier> >();
            var equityAccounts    = new List <IAccount <Identifier> >();

            foreach (var acct in _dataStore)
            {
                switch (acct.AccountType)
                {
                case KindsOfAccounts.Asset:
                    assetAccounts.Add(acct);
                    continue;

                case KindsOfAccounts.Liability:
                    liabilityAccounts.Add(acct);
                    continue;

                case KindsOfAccounts.Equity:
                    equityAccounts.Add(acct);
                    continue;
                }
            }

            return(assetAccounts.Sum().GetRounded().GetAbs() ==
                   (liabilityAccounts.Sum() + equityAccounts.Sum()).GetRounded().GetAbs());
        }
예제 #28
0
            public bool SubSearch(SortedSet <int> nums, int k, int currentSum, int targetSum)
            {
                if (k == 0)
                {
                    return(!nums.Any());
                }

                if (currentSum > targetSum)
                {
                    return(false);
                }
                if (currentSum == targetSum)
                {
                    return(SubSearch(nums, k - 1, 0, targetSum));
                }
                tempList.Clear();
                tempList.AddRange(nums);
                foreach (var elem in tempList)
                {
                    nums.Remove(elem);
                    if (SubSearch(nums, k, currentSum + elem, targetSum))
                    {
                        return(true);
                    }
                    nums.Add(elem);
                }

                return(false);
            }
예제 #29
0
        static EventQueue()
        {
            var worker = new Thread(() =>
            {
                for (; ;)
                {
                    EventQueueEvent minEvent;
                    lock (events)
                        minEvent = events.Any() ? events.Min : null;
                    if (minEvent != null && minEvent.CallTime <= DateTime.Now)
                    {
                        lock (events)
                            if (!events.Remove(minEvent))
                            {
                                logger.Fatal("EventQueue failed removing element");
                            }
                        eventById.TryRemove(minEvent.Guid, out var _);
                        minEvent.Action.BeginInvoke(minEvent.State, ActionInvokeCallback, new InvokeStateObject
                        {
                            TimerCallback = minEvent.Action
                        });
                    }
                    Thread.Sleep(1);
                }
                // ReSharper disable once FunctionNeverReturns
            });

            worker.Start();
        }
예제 #30
0
        // topologically sort the graph to work out calculation order
        public Dictionary <string, int> CalculateWeights()
        {
            var remainingNodes = new SortedSet <int>(Nodes.Select(n => n.ID).Union(KeyNodes.Select(k => k.Value.ID)));
            var markedNodes    = new SortedSet <int>();
            var processors     = Nodes.ToDictionary(n => n.ID, n => RFGraphDefinition.GetFullName(n.GraphName, n.Label));
            var visitOrder     = new List <int>();

            while (remainingNodes.Any())
            {
                var remainingNode = remainingNodes.First();
                Visit(remainingNode, markedNodes, remainingNodes, visitOrder);
            }

            var weights = new Dictionary <string, int>();
            int idx     = 1;

            visitOrder.Reverse();
            foreach (var node in visitOrder)
            {
                if (processors.ContainsKey(node))
                {
                    weights.Add(processors[node], idx++);
                }
            }
            return(weights);
        }
예제 #31
0
            private IEnumerable <DateTime> OccurenceGeneratorMethod()
            {
                DateTime init   = DateTime.Now;
                int      year   = init.Year;
                DateTime output = init;

                while (true)
                {
                    foreach (int month in Months)
                    {
                        // Initial test
                        if (year == init.Year && month < init.Month)
                        {
                            continue;
                        }

                        int maxDays = DateTime.DaysInMonth(year, month);
                        foreach (int day in Days)
                        {
                            if (year == init.Year && month == init.Month && day < init.Day)
                            {
                                continue;
                            }

                            if (day > maxDays)
                            {
                                continue;
                            }

                            output = new DateTime(year, month, day);
                            if (DaysOfWeek.Any(dow => dow - 1 == (int)output.DayOfWeek))
                            {
                                foreach (int hour in Hours)
                                {
                                    if (year == init.Year && month == init.Month && day == init.Day && hour < init.Hour)
                                    {
                                        continue;
                                    }

                                    foreach (int minute in Minutes)
                                    {
                                        if (year == init.Year && month == init.Month && day == init.Day && hour == init.Hour && minute < init.Minute)
                                        {
                                            continue;
                                        }

                                        yield return(new DateTime(year, month, day, hour, minute, 0));;
                                    }
                                }
                            }
                        }
                    }
                    year += 1;

                    if (year > init.Year + 10)
                    {
                        yield break;
                    }
                }
            }
예제 #32
0
파일: PathFinder.cs 프로젝트: ndech/Alpha
 private static List<Step> CalculatePath(IMovable movable, Zone destination)
 {
     List<Step> steps = new List<Step>();
     if (movable.Location == destination || !movable.CanCross(destination))
         return steps;
     //Calculate path using A* algorithm
     SortedSet<PathfindingNode> openList = new SortedSet<PathfindingNode>(
         Comparer<PathfindingNode>.Create((a, b) => a.CompareTo(b)));
     HashSet<Zone> closedList = new HashSet<Zone>();
     openList.Add(new PathfindingNode(movable.Location, destination.DistanceWith(movable.Location)));
     bool pathFound = destination == movable.Location;
     while (!pathFound)
     {
         if (openList.Count == 0)
             break;
         PathfindingNode currentNode = openList.First();
         foreach (Zone neighbourg in currentNode.Zone.Adjacencies.Select(a => a.Neighbourg).Where(s => movable.CanCross(s)))
         {
             if (closedList.Contains(neighbourg) || openList.Any(n => n.Zone == neighbourg))
                 continue;
             openList.Add(new PathfindingNode(neighbourg, destination.DistanceWith(neighbourg), currentNode));
             if (neighbourg == destination) // Path found !
             {
                 pathFound = true;
                 steps.Add(new Step(currentNode.Zone, destination));
                 while (currentNode.Parent != null)
                 {
                     steps.Add(new Step(currentNode.Parent.Zone, currentNode.Zone));
                     currentNode = currentNode.Parent;
                 }
                 steps.Reverse();
                 break;
             }
         }
         openList.Remove(currentNode);
         closedList.Add(currentNode.Zone);
     }
     if (steps.Count == 0)
         return steps;
     return steps;
 }
예제 #33
0
        private ICEOutcome LearnInvFromTemplate(Dictionary<string, int> impl2Priority, Template t, int range, out VCGenOutcome overallOutcome)
        {
            overallOutcome = null;

            // create a new z3 context
            if (z3Context != null)
            {
                z3Context.context.Dispose();
                z3Context.config.Dispose();
            }
            z3Context = new Z3Context();

            foreach (var func in existentialFunctions.Values)
            {
                // initialize function to an "Octagons" instance with the given template "t".
                function2Value[func.Name] = ICEDomainFactory.GetInstance("Octagons", t, ref z3Context, func.Name, range);
            }

            // add counterexamples into the z3Context. These are obtained from the earlier iterations of the template.
            foreach (var cex in counterExamples)
            {
                AddCounterExampleToZ3Context(cex);
            }

            var worklist = new SortedSet<Tuple<int, string>>();
            name2Impl.Keys.Iter(k => worklist.Add(Tuple.Create(impl2Priority[k], k)));

            while (worklist.Any())
            {
                var impl = worklist.First().Item2;
                worklist.Remove(worklist.First());

                #region vcgen

                var gen = prover.VCExprGen;
                var terms = new List<Expr>();
                foreach (var tup in impl2FuncCalls[impl])
                {
                    var controlVar = tup.Item2;
                    var exprVars = tup.Item3;
                    var varList = new List<Expr>();
                    exprVars.Args.OfType<Expr>().Iter(v => varList.Add(v));

                    var args = new List<Expr>();
                    controlVar.InParams.Iter(v => args.Add(Expr.Ident(v)));
                    Expr term = Expr.Eq(new NAryExpr(Token.NoToken, new FunctionCall(controlVar), args),
                                 function2Value[tup.Item1].Gamma(varList));

                    if (controlVar.InParams.Count != 0)
                    {
                        term = new ForallExpr(Token.NoToken, new List<Variable>(controlVar.InParams.ToArray()),
                            new Trigger(Token.NoToken, true, new List<Expr> { new NAryExpr(Token.NoToken, new FunctionCall(controlVar), args) }),
                            term);
                    }
                    terms.Add(term);
                }
                var env = BinaryTreeAnd(terms, 0, terms.Count - 1);

                env.Typecheck(new TypecheckingContext((IErrorSink)null));
                var envVC = prover.Context.BoogieExprTranslator.Translate(env);

                var vc = gen.Implies(envVC, impl2VC[impl]);

                if (CommandLineOptions.Clo.Trace)
                {
                    Console.WriteLine("Verifying {0}: ", impl);
                    //Console.WriteLine("env: {0}", envVC);
                    var envFuncs = new HashSet<string>();
                    impl2FuncCalls[impl].Iter(tup => envFuncs.Add(tup.Item1));
                    envFuncs.Iter(f => PrintFunction(existentialFunctions[f]));
                }

                #endregion vcgen

                VCExpr finalVC;

                #region bound_value_of_cexs
            #if false
                finalVC = vc;

            #else
                int bound = 1000000;
                terms.Clear();
                foreach (var tup in impl2FuncCalls[impl])
                {
                    var exprVars = tup.Item3;
                    var varList = new List<Expr>();
                    exprVars.Args.OfType<Expr>().Where(v => v.Type.IsInt).Iter(v => varList.Add(v));
                    foreach (var variable in varList)
                    {
                        terms.Add(Expr.Le(variable, Expr.Literal(bound)));
                        terms.Add(Expr.Ge(variable, Expr.Literal(-1 * bound)));
                        //terms.Add(Expr.Ge(variable, Expr.Literal(0)));
                    }
                }
                var boundcex = BinaryTreeAnd(terms, 0, terms.Count - 1);
                boundcex.Typecheck(new TypecheckingContext((IErrorSink)null));
                var boundcexVC = prover.Context.BoogieExprTranslator.Translate(boundcex);

                finalVC = gen.Implies(boundcexVC, vc);
            #endif
                #endregion bound_value_of_cexs

                var handler = impl2ErrorHandler[impl].Item1;
                var collector = impl2ErrorHandler[impl].Item2;
                collector.Reset(impl);
                VCisValid = true;   // set to false if control reaches HandleCounterExample
                realErrorEncountered = false;
                newSamplesAdded = false;

                var start = DateTime.Now;

                prover.Push();
                prover.Assert(gen.Not(finalVC), true);
                prover.FlushAxiomsToTheoremProver();
                prover.Check();
                ProverInterface.Outcome proverOutcome = prover.CheckOutcomeCore(handler);

                //prover.BeginCheck(impl, vc, handler);
                //ProverInterface.Outcome proverOutcome = prover.CheckOutcomeCore(handler);

                var inc = (DateTime.Now - start);
                proverTime += inc;
                numProverQueries++;

                if (CommandLineOptions.Clo.Trace)
                    Console.WriteLine("Prover Time taken = " + inc.TotalSeconds.ToString());

                if (proverOutcome == ProverInterface.Outcome.TimeOut || proverOutcome == ProverInterface.Outcome.OutOfMemory)
                {
                    Console.WriteLine("Z3 Prover for implementation {0} times out or runs out of memory !", impl);
                    z3Context.context.Dispose();
                    z3Context.config.Dispose();

                    overallOutcome = new VCGenOutcome(proverOutcome, new List<Counterexample>());
                    return ICEOutcome.Timeout;
                }

                if (CommandLineOptions.Clo.Trace)
                    Console.WriteLine(!VCisValid ? "SAT" : "UNSAT");

                if (!VCisValid)
                {
                    if (realErrorEncountered)
                    {
                        overallOutcome = new VCGenOutcome(ProverInterface.Outcome.Invalid, collector.real_errors);
                        return ICEOutcome.ErrorFound;
                    }

                    Debug.Assert(newSamplesAdded);
                    HashSet<string> funcsChanged;
                    if (!learn(out funcsChanged))
                    {
                        // learner timed out or there is no valid conjecture in the current given template
                        overallOutcome = new VCGenOutcome(ProverInterface.Outcome.Invalid, collector.conjecture_errors);
                        prover.Pop();
                        return ICEOutcome.InvariantNotFound;
                    }
                    // propagate dependent guys back into the worklist, including self
                    var deps = new HashSet<string>();
                    deps.Add(impl);
                    funcsChanged.Iter(f => deps.UnionWith(function2implAssumed[f]));
                    funcsChanged.Iter(f => deps.UnionWith(function2implAsserted[f]));

                    deps.Iter(s => worklist.Add(Tuple.Create(impl2Priority[s], s)));
                }

                prover.Pop();
            }
            // The program was verified with the current template!
            overallOutcome = new VCGenOutcome(ProverInterface.Outcome.Valid, new List<Counterexample>());
            return ICEOutcome.InvariantFound;
        }
예제 #34
0
 /// <summary>
 /// Sprawdza czy potrafimy wyświetlić dany tym MIME
 /// </summary>
 /// <returns></returns>
 private bool CheckMimeToDisplay()
 {
     if (!headers.ContainsKey("Content-Type"))
         return true;
     var mime = headers["Content-Type"];
     var allowedMimes = new SortedSet<string> { "text/html", "text/plain" };
     return allowedMimes.Any(allowedMime => mime.StartsWith(allowedMime));
 }
예제 #35
0
        private VCGenOutcome LearnInv(Dictionary<string, int> impl2Priority)
        {
            var worklist = new SortedSet<Tuple<int, string>>();
            name2Impl.Keys.Iter(k => worklist.Add(Tuple.Create(impl2Priority[k], k)));
            
            while (worklist.Any())
            {
                var impl = worklist.First().Item2;
                worklist.Remove(worklist.First());

                #region vcgen

                var gen = prover.VCExprGen;
                var terms = new List<Expr>();
                foreach (var tup in impl2FuncCalls[impl])
                {
                    var controlVar = tup.Item2;
                    var exprVars = tup.Item3;
                    var varList = new List<Expr>();
                    exprVars.Args.OfType<Expr>().Iter(v => varList.Add(v));

                    var args = new List<Expr>();
                    controlVar.InParams.Iter(v => args.Add(Expr.Ident(v)));
                    Expr term = Expr.Eq(new NAryExpr(Token.NoToken, new FunctionCall(controlVar), args),
                                 function2Value[tup.Item1].Gamma(varList));

                    if (controlVar.InParams.Count != 0)
                    {
                        term = new ForallExpr(Token.NoToken, new List<Variable>(controlVar.InParams.ToArray()),
                            new Trigger(Token.NoToken, true, new List<Expr> { new NAryExpr(Token.NoToken, new FunctionCall(controlVar), args) }),
                            term);
                    }
                    terms.Add(term);

                    /*
                    foreach (var variable in varList)
                    {
                        terms.Add(Expr.Le(variable, Expr.Literal(10)));
                        terms.Add(Expr.Ge(variable, Expr.Literal(-10)));
                    }
                    */
                }
                var env = BinaryTreeAnd(terms, 0, terms.Count - 1);

                env.Typecheck(new TypecheckingContext((IErrorSink)null));
                var envVC = prover.Context.BoogieExprTranslator.Translate(env);
                var vc = gen.Implies(envVC, impl2VC[impl]);

                if (CommandLineOptions.Clo.Trace)
                {
                    Console.WriteLine("Verifying {0}: ", impl);
                    //Console.WriteLine("env: {0}", envVC);
                    var envFuncs = new HashSet<string>();
                    impl2FuncCalls[impl].Iter(tup => envFuncs.Add(tup.Item1));
                    envFuncs.Iter(f => PrintFunction(existentialFunctions[f]));
                }

                #endregion vcgen

                VCExpr finalVC;
                for (int i = 0; i <= bounds4cex.Count(); i++)
                {
#region boundcexvalues
                    /* Last iteration is when there are enforced no bounds on the cex values. */
                    if (i < bounds4cex.Count())
                    {
                        int bound = bounds4cex.ElementAt(i);
                        terms.Clear();
                        foreach (var tup in impl2FuncCalls[impl])
                        {
                            var exprVars = tup.Item3;
                            var varList = new List<Expr>();
                            exprVars.Args.OfType<Expr>().Where(v => v.Type.IsInt).Iter(v => varList.Add(v));
                            foreach (var variable in varList)
                            {
                                terms.Add(Expr.Le(variable, Expr.Literal(bound)));
                                terms.Add(Expr.Ge(variable, Expr.Literal(-1 * bound)));
                                //terms.Add(Expr.Ge(variable, Expr.Literal(0)));
                            }
                        }
                        var boundcex = BinaryTreeAnd(terms, 0, terms.Count - 1);
                        boundcex.Typecheck(new TypecheckingContext((IErrorSink)null));
                        var boundcexVC = prover.Context.BoogieExprTranslator.Translate(boundcex);

                        finalVC = gen.Implies(boundcexVC, vc);
                    }
                    else
                    {
                        //finalVC = vc;
                        
                        
                        int bound = 1000000;
                        terms.Clear();
                        foreach (var tup in impl2FuncCalls[impl])
                        {
                            var exprVars = tup.Item3;
                            var varList = new List<Expr>();
                            exprVars.Args.OfType<Expr>().Where(v => v.Type.IsInt).Iter(v => varList.Add(v));
                            foreach (var variable in varList)
                            {
                                terms.Add(Expr.Le(variable, Expr.Literal(bound)));
                                terms.Add(Expr.Ge(variable, Expr.Literal(-1 * bound)));
                                //terms.Add(Expr.Ge(variable, Expr.Literal(0)));
                            }
                        }
                        var boundcex = BinaryTreeAnd(terms, 0, terms.Count - 1);
                        boundcex.Typecheck(new TypecheckingContext((IErrorSink)null));
                        var boundcexVC = prover.Context.BoogieExprTranslator.Translate(boundcex);

                        finalVC = gen.Implies(boundcexVC, vc);
                         
                    }
#endregion boundcexvalues

                    var handler = impl2ErrorHandler[impl].Item1;
                    var collector = impl2ErrorHandler[impl].Item2;
                    collector.Reset(impl);
                    implicationCounterExamples.Clear();
                    VCisValid = true;   // set to false if control reaches HandleCounterExample
                    //realErrorEncountered = false;
                    //newSamplesAdded = false;
                    //this.posNegCexAdded = false;

                    var start = DateTime.Now;

                    prover.Push();
                    prover.Assert(gen.Not(finalVC), true);
                    prover.FlushAxiomsToTheoremProver();
                    prover.Check();
                    ProverInterface.Outcome proverOutcome = prover.CheckOutcomeCore(handler);

                    var inc = (DateTime.Now - start);
                    proverTime += inc;
                    numProverQueries++;

                    if (CommandLineOptions.Clo.Trace)
                        Console.WriteLine("Prover Time taken = " + inc.TotalSeconds.ToString());

                    if (proverOutcome == ProverInterface.Outcome.TimeOut || proverOutcome == ProverInterface.Outcome.OutOfMemory)
                    {
                        Console.WriteLine("Z3 Prover for implementation {0} times out or runs out of memory !", impl);
                        return new VCGenOutcome(proverOutcome, new List<Counterexample>());
                    }

                    if (!VCisValid)
                    {
                        /* There was a counterexample found and acted upon while proving the method. */
                        if (collector.real_errors.Count > 0)
                        {
                            return new VCGenOutcome(ProverInterface.Outcome.Invalid, collector.real_errors);
                        }

                        if (collector.conjecture_errors.Count == 0)
                        {
                            // No positive or negative counter-example added. Need to add implication counter-examples
                            Debug.Assert(collector.implication_errors.Count > 0);
                            foreach (var cex in implicationCounterExamples)
                            {
                                AddCounterExample(cex);
                            }
                        }

                        //Debug.Assert(newSamplesAdded);
                        HashSet<string> funcsChanged;

                        if (!learn(out funcsChanged))
                        {
                            // learner timed out, ran into some errors, or if there is no consistent conjecture
                            prover.Pop();
                            if(collector.conjecture_errors.Count > 0)
                                return new VCGenOutcome(ProverInterface.Outcome.Invalid, collector.conjecture_errors);
                            else
                                return new VCGenOutcome(ProverInterface.Outcome.Invalid, collector.implication_errors);
                        }
                        // propagate dependent guys back into the worklist, including self
                        var deps = new HashSet<string>();
                        deps.Add(impl);
                        funcsChanged.Iter(f => deps.UnionWith(function2implAssumed[f]));
                        funcsChanged.Iter(f => deps.UnionWith(function2implAsserted[f]));

                        deps.Iter(s => worklist.Add(Tuple.Create(impl2Priority[s], s)));

                        // break out of the loop that iterates over various bounds.
                        prover.Pop();
                        break;
                    }
                    else
                    {
                        prover.Pop();
                    }
                }
            }
            // The program was verified
            return new VCGenOutcome(ProverInterface.Outcome.Valid, new List<Counterexample>());            
        }
예제 #36
0
        private CTerm WithAttr(CTerm type, IDiaSymbol sym)
        {
            SortedSet<TypeAttr> attrs = new SortedSet<TypeAttr>();
            if (sym.constType == 1) { attrs.Add(TypeAttrs.Const); }
            if (sym.volatileType == 1) { attrs.Add(TypeAttrs.Volatile); }
            if (sym.unalignedType == 1) { attrs.Add(TypeAttrs.Unaligned); }

            return attrs.Any() ? new CAttrTerm(type, attrs) : type;
        }