Example #1
1
        public static void Write(TextWriter writer, IEnumerable<Dictionary<string, string>> records)
        {
            if (records == null) return; //AOT

            var allKeys = new HashSet<string>();
            var cachedRecords = new List<IDictionary<string, string>>();

            foreach (var record in records)
            {
                foreach (var key in record.Keys)
                {
                    if (!allKeys.Contains(key))
                    {
                        allKeys.Add(key);
                    }
                }
                cachedRecords.Add(record);
            }

            var headers = allKeys.OrderBy(key => key).ToList();
            if (!CsvConfig<Dictionary<string, string>>.OmitHeaders)
            {
                WriteRow(writer, headers);
            }
            foreach (var cachedRecord in cachedRecords)
            {
                var fullRecord = headers.ConvertAll(header => 
                    cachedRecord.ContainsKey(header) ? cachedRecord[header] : null);
                WriteRow(writer, fullRecord);
            }
        }
Example #2
1
        public static int Solution2(Stopwatch timer)
        {
            timer.Restart();

            var a = new HashSet<int>();
            int maxlcm = 1;
            int t = 0;
            var results = new List<int>();

            for (int i = 2; i <= 20; i++)
            {
                int k = i%2 == 0 ? 1 : 2;
                for (int j = k; j < i; j+=2)
                {
                    if (gcd(i, j) == 1)
                    {
                        a.Add(2*i*(i + j));
                    }
                }
            }

            var sortedA = a.OrderBy(v => v).ToArray();

            while (maxlcm < 1000)
            {
                maxlcm = lcm(maxlcm, sortedA[t]);
                results.Add(maxlcm);
                t++;
            }

            int res = results[results.Count - 2];
            timer.Stop();
            return res;
        }
Example #3
0
        public void UpdateInfo()
        {
            if (Application.Session == null)
            {
                this.fileList.Items.Clear();
            }
            else
            {
                HashSet<string> files = new HashSet<string>(PathComparer.OSIndependentPath);

                // Search for source files
                foreach (ObjectCodeFile obj in Application.Session.LoadedImages)
                {
                    foreach (string path in obj.SourceFiles)
                    {
                        files.Add(path);
                    }
                }

                // Add each file item
                foreach (string file in files.OrderBy(x=>x, PathComparer.OSIndependentFilename))
                {
                    // Ignore empty entries
                    if (!string.IsNullOrWhiteSpace(file))
                    {
                        var newItem = new SourceFileItem(file);
                        newItem.MouseDoubleClick += OnFileDoubleClick;

                        this.fileList.Items.Add(newItem);
                    }
                }
            }
        }
Example #4
0
        //private static void ProcessNode(HtmlNode node, Stack<HtmlNode> stack)
        //{
        //    var depth = stack.Count;
        //    var padding = String.Empty.PadLeft(depth, ' ');
        //    stack.Push(node);
        //    try
        //    {
        //        Debug.WriteLine(padding + "Node: " + node.Name);
        //        foreach (var child in node.ChildNodes)
        //        {
        //            ProcessNode(child, stack);
        //        }
        //    }
        //    finally
        //    {
        //        stack.Pop();
        //    }
        //}

        private void button_Click(object sender, RoutedEventArgs e)
        {
            using (var stream = File.OpenRead(@"C:\Documents\bookmarks_7_27_15.html"))
            {
                var doc = new HtmlDocument();
                doc.Load(stream);

                var rootFolder = new Folder { Name = "<root>" };

                ProcessNode(doc.DocumentNode, rootFolder);
                if (rootFolder.Folders.Count == 1)
                    rootFolder = rootFolder.Folders.Single();

                treeView.Items.Add(GetTree(rootFolder));

                var bookmarks = rootFolder.AllBookmarks.ToList();
                bookmarks.Sort(
                    (l, r) => StringComparer.OrdinalIgnoreCase.Compare(l.Href.ToString(), r.Href.ToString()));
                var lookupItem = new TreeViewItem { Header = "Lookup" };
                var lookup = rootFolder.AllBookmarks.ToLookup(b => b.Href.ToString(), b => b.Folder, StringComparer.OrdinalIgnoreCase);
                foreach (var key in lookup)
                {
                    var folders = new HashSet<string>(key.Select(k => k.FullName), StringComparer.OrdinalIgnoreCase);
                    if (folders.Count > 1)
                    {
                        //folders.Sort((l, r) => StringComparer.OrdinalIgnoreCase.Compare(l.FullName, r.FullName));
                        var keyItem = new TreeViewItem { Header = key.Key + " (" + folders.Count + ")" };
                        foreach (var folder in folders.OrderBy(f => f, StringComparer.OrdinalIgnoreCase))
                            keyItem.Items.Add(new TreeViewItem { Header = folder });
                        lookupItem.Items.Add(keyItem);
                    }
                }
                lookupItem.ExpandSubtree();
                treeView.Items.Add(lookupItem);
                var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                foreach (var bookmark in rootFolder.AllBookmarks)
                    set.Add(bookmark.ToString());
                foreach (var txt in set)
                    Debug.WriteLine(txt);

                using (var output = File.OpenWrite(@"C:\Documents\output.html"))
                {
                    output.SetLength(0);
                    using (var writer = new StreamWriter(output))
                    {

                        writer.WriteLine(@"<!DOCTYPE NETSCAPE-Bookmark-file-1>");
                        writer.WriteLine(@"<!-- This is an automatically generated file.");
                        writer.WriteLine(@"     It will be read and overwritten.");
                        writer.WriteLine(@"     DO NOT EDIT! -->");
                        writer.WriteLine(
                            "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html;charset=UTF-8\">");
                        writer.WriteLine(@"<TITLE>Bookmarks</TITLE>");
                        WriteFolder(rootFolder, writer, new HashSet<string>(StringComparer.OrdinalIgnoreCase), "");
                    }
                }

                //Debugger.Break();
            }
        }
Example #5
0
        /// <summary>
        /// 获取一次Tcp端口快照信息
        /// </summary>
        /// <param name="ipVersion">ip版本</param>
        /// <returns></returns>
        public static unsafe PortOwnerPid[] Snapshot(AddressFamily ipVersion)
        {
            var size = 0;
            var TCP_TABLE_OWNER_PID_ALL = 5;
            TcpSnapshot.GetExtendedTcpTable(null, &size, false, ipVersion, TCP_TABLE_OWNER_PID_ALL, 0);

            var pTable = stackalloc byte[size];
            var state = TcpSnapshot.GetExtendedTcpTable(pTable, &size, false, ipVersion, TCP_TABLE_OWNER_PID_ALL, 0);
            if (state != 0)
            {
                return new PortOwnerPid[0];
            }

            var hashSet = new HashSet<PortOwnerPid>();
            var rowLength = *(int*)(pTable);
            var pRow = pTable + Marshal.SizeOf(rowLength);

            for (int i = 0; i < rowLength; i++)
            {
                var row = *(MIB_TCPROW_OWNER_PID*)pRow;
                var port = ByteConverter.ToBytes(row.LocalPort, Endians.Little);

                var portOwner = new PortOwnerPid
                {
                    Port = ByteConverter.ToUInt16(port, 0, Endians.Big),
                    OwerPid = (int)row.OwningPid
                };
                hashSet.Add(portOwner);
                pRow = pRow + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID));
            }

            return hashSet.OrderBy(item => item.Port).ToArray();
        }
Example #6
0
        public FeatureInteraction(HashSet<XgbTreeNode> interaction, double gain, double cover, double pathProbability, double depth, double treeIndex, double fScore = 1)
        {
            SplitValueHistogram = new SplitValueHistogram();
            List<string> features = interaction.OrderBy(x => x.Feature).Select(y => y.Feature).ToList();

            Name = string.Join("|", features);
            Depth = interaction.Count - 1;
            Gain = gain;
            Cover = cover;
            FScore = fScore;
            FScoreWeighted = pathProbability;
            AverageFScoreWeighted = FScoreWeighted / FScore;
            AverageGain = Gain / FScore;
            ExpectedGain = Gain * pathProbability;
            TreeIndex = treeIndex;
            TreeDepth = depth;
            AverageTreeIndex = TreeIndex / FScore;
            AverageTreeDepth = TreeDepth / FScore;
            HasLeafStatistics = false;

            if (Depth == 0)
            {
                SplitValueHistogram.AddValue(interaction.First().SplitValue);
            }
        }
        public static IReadOnlyList <RazorDiagnostic> GetAllDiagnostics(this IntermediateNode node)
        {
            if (node == null)
            {
                throw new ArgumentNullException(nameof(node));
            }

            HashSet <RazorDiagnostic> diagnostics = null;

            AddAllDiagnostics(node);

            var allOrderedDiagnostics = diagnostics?.OrderBy(diagnostic => diagnostic.Span.AbsoluteIndex);

            return(allOrderedDiagnostics?.ToList() ?? EmptyDiagnostics);

            void AddAllDiagnostics(IntermediateNode n)
            {
                if (n.HasDiagnostics)
                {
                    if (diagnostics == null)
                    {
                        diagnostics = new HashSet <RazorDiagnostic>();
                    }

                    diagnostics.UnionWith(n.Diagnostics);
                }

                for (var i = 0; i < n.Children.Count; i++)
                {
                    AddAllDiagnostics(n.Children[i]);
                }
            }
        }
    static void Main(string[] args)
    {
        int N = int.Parse(Console.ReadLine());
        HashSet<House> Houses = new HashSet<House>();
        long amountOfCable = 0;
        for (int i = 0; i < N; i++)
        {
            string[] inputs = Console.ReadLine().Split(' ');
            Houses.Add(new House { X = int.Parse(inputs[0]), Y = int.Parse(inputs[1]) });
        }

        //Core: Calculate Average House Y index
        double Avg = Houses.Sum(x => x.Y) / N;

        //Core:find the house closest to the Avg Y and use its Y coordinate
        int closest = Houses.OrderBy(x => Math.Abs(x.Y - Avg)).First().Y;

        //lay the mainline
        amountOfCable += (Houses.Max(x => x.X) - Houses.Min(x => x.X));

        //per other House calculate distance from location to mainline
        foreach (var i in Houses)
        {
            amountOfCable += i.Y > closest ? i.Y - closest : closest - i.Y;
        }

        // Write an action using Console.WriteLine()
        // To debug: Console.Error.WriteLine("Debug messages...");

        Console.WriteLine(amountOfCable);
    }
Example #9
0
        public static void Main()
        {
            var generator = new TextGenerator(WordTypes.Name);

            var names = generator.GenerateText(1000);
            var trie = new Trie();
            var words = new HashSet<string>();
            names.Split(' ').ToList().ForEach(
                x =>
                    {
                        words.Add(x);
                        trie.AddWord(x);
                    });

            var result = new StringBuilder();

            foreach (var word in words.OrderBy(x => x))
            {
                int occurenceCount;
                trie.TryFindWord(word, out occurenceCount);
                result.AppendFormat("{0} -> {1} times", word, occurenceCount).AppendLine();
            }

            Console.WriteLine(result);
        }
        /// <summary>
        /// Reduce a list of References to the smallest set of references that
        /// covers the same set as the original.
        /// </summary>
        /// <param name="source">the list of references</param>
        /// <returns>a reduced set of references</returns>
        public static ICollection<Reference> Reduce(this IEnumerable<Reference> source)
        {
            Reference lastReference = null;
            List<Reference> destination = new List<Reference>();

            foreach (Reference check in source.OrderBy(r => r))
            {
                if (lastReference != null)
                {
                    if (lastReference.Book.Equals(check.Book) && lastReference.Chapter == check.Chapter)
                    {
                        HashSet<int> uniqueVerses = new HashSet<int>(lastReference.Verses.Union(check.Verses));
                        lastReference.Verses = uniqueVerses.OrderBy(v => v).ToArray();
                    }
                    else
                    {
                        destination.Add(lastReference);
                        lastReference = null;
                    }
                }

                lastReference = check;
            }

            if (lastReference != null)
            {
                destination.Add(lastReference);
            }

            return destination;
        }
        /// <summary>
        /// Retrieves all events across all aggregates that are related to the specified aggregate ids, in the order in which they were recorded.
        /// </summary>
        /// <param name="events">The events.</param>
        /// <param name="relatedToAggregateIds">The aggregate ids to which the events relate.</param>
        public static async Task<IEnumerable<StorableEvent>> RelatedEvents(
            this IQueryable<StorableEvent> events,
            params Guid[] relatedToAggregateIds)
        {
            var ids = new HashSet<Guid>(relatedToAggregateIds);

            var relatedEvents = new HashSet<StorableEvent>();

            int currentCount;

            do
            {
                currentCount = relatedEvents.Count;

                var unqueriedIds = ids.Where(id => ! relatedEvents.Select(e => e.AggregateId).Contains(id));

                var newEvents = await events.Where(e => unqueriedIds.Any(id => id == e.AggregateId)).ToArrayAsync();

                relatedEvents.UnionWith(newEvents);

                var moreIds = newEvents
                    .SelectMany(e => e.Body.ExtractGuids())
                    .Distinct()
                    .ToArray();

                if (!moreIds.Any())
                {
                    break;
                }

                ids.UnionWith(moreIds);
            } while (currentCount != relatedEvents.Count);

            return relatedEvents.OrderBy(e => e.Id);
        }
Example #12
0
 private List<int> Combinations(int num)
 {
     _digits = num.ToString().Select(c => Convert.ToInt32(c.ToString())).ToArray();
     _combos = new HashSet<int>();
     Helper(0);
     return _combos.OrderBy(o => o).ToList();
 }
        static Version[] CalculateKnownVersions(ReportRepository repository)
        {
            const int blocks = 4;
            const int versionsPerBlock = 2;

            HashSet<Version> popularVersions = new HashSet<Version>();
            DateTime startDate = repository.Sessions.Min(s => s.StartTime);
            DateTime endDate = repository.Sessions.Max(s => s.StartTime);

            TimeSpan span = endDate - startDate;
            // last week has its own block, other 3 blocks are distributed evenly over the remaining timespan
            if (span > new TimeSpan(30, 0, 0, 0))
                span -= new TimeSpan(7, 0, 0, 0);

            foreach (var groupByBlock in repository.Sessions.AsEnumerable().GroupBy(s => (s.StartTime.Ticks-startDate.Ticks)*(blocks-1)/span.Ticks).OrderBy(g => g.Key)) {
                int versionsAddedThisBlock = 0;
                foreach (var version in groupByBlock.GroupBy(s => s.AppVersion).OrderByDescending(g => g.Count())) {
                    if (popularVersions.Add(version.Key)) {
                        if (++versionsAddedThisBlock >= versionsPerBlock)
                            break;
                    }
                }
            }
            return popularVersions.OrderBy(v => v).ToArray();
        }
 private void RenderMismatches(string format, HashSet<Tuple<string, string, string>> results)
 {
     foreach (var row in results.OrderBy(r => r.Item1))
     {
         _options.Reports.WriteInformation(string.Format(format, row.Item1, row.Item2, row.Item3));
     }
 }
Example #15
0
        public void Walk(IGraphNode<LibraryDescription> root)
        {
            _assemblyFilePaths = new HashSet<string>(StringComparer.Ordinal);
            _dependencyAssemblySources = new Dictionary<string, HashSet<string>>(StringComparer.Ordinal);
            _dependencyPackageSources = new Dictionary<string, HashSet<string>>(StringComparer.Ordinal);

            var libraries = new HashSet<LibraryDescription>();
            root.DepthFirstPreOrderWalk(visitNode: (node, _) => VisitLibrary(node, _, libraries));

            _reports.Information.WriteLine("\n[Target framework {0} ({1})]\n",
                _framework.ToString(), VersionUtility.GetShortFrameworkName(_framework));

            foreach (var assemblyFilePath in _assemblyFilePaths.OrderBy(assemblyName => assemblyName))
            {
                _reports.Information.WriteLine(assemblyFilePath);
                if (_showDetails)
                {
                    var assemblyName = Path.GetFileNameWithoutExtension(assemblyFilePath);

                    HashSet<string> packagesSources;
                    if (_dependencyPackageSources.TryGetValue(assemblyName, out packagesSources) && packagesSources.Any())
                    {
                        _reports.Information.WriteLine("    by package:  {0}", string.Join(", ", packagesSources));
                    }

                    HashSet<string> assemblySources;
                    if (_dependencyAssemblySources.TryGetValue(assemblyName, out assemblySources) && assemblySources.Any())
                    {
                        _reports.Information.WriteLine("    by assembly: {0}", string.Join(", ", assemblySources));
                    }
                }
            }
        }
 protected void WriteClaimSignatureSet( HashSet<string> claimSignatures)
 {
     Debug.WriteLine("Claim Signatures: ");
     foreach (var claimSignature in claimSignatures.OrderBy(n => n))
     {
         Debug.WriteLine("\t" + claimSignature);
     }
 }
 /// <summary>
 ///  对可行点进行排序。排序的依据为每个点的评分。
 /// </summary>
 /// <param name="set"></param>
 /// <returns></returns>
 public List<Point> SortPossiblePoint(HashSet<Point> set)
 {
     List<Point >list=new List<Point> ();
        IEnumerable<Point> ie = set.OrderBy(p => p.Evaluate);
        foreach (Point p in ie)
        list.Add(p);
        return list;
 }
Example #18
0
        private IEnumerable<UnityObject> Targets(IEnumerable<fiSerializedObject> backups) {
            var targets = new HashSet<UnityObject>();

            foreach (var backup in backups) {
                targets.Add(backup.Target.Target);
            }

            return targets.OrderBy(obj => obj.name);
        }
        /// <summary>
        /// Find all listener interfaces in the given assembly that are not somehow used in an event.
        /// </summary>
        internal static void Find(AssemblyDefinition assembly)
        {
            var usedInterfaces = new HashSet<string>();
            var foundInterfaces = new HashSet<string>();


            foreach (var type in assembly.MainModule.GetTypes())
            {
                if (type.IsInterface && type.Name.EndsWith("Listener"))
                {
                    // Found possible listener interface
                    var fullName = GetFullName(type);
                    if (fullName == null)
                        continue;
                    if (!usedInterfaces.Contains(fullName))
                    {
                        foundInterfaces.Add(fullName);
                    }
                }
                else if (!type.IsInterface && type.HasEvents)
                {
                    // Scan for events
                    foreach (var evt in type.Events.Where(x => x.HasCustomAttributes))
                    {
                        var attr = evt.CustomAttributes.FirstOrDefault(x => (x.AttributeType.Namespace == AttributeConstants.Dot42AttributeNamespace) &&
                                     (x.AttributeType.Name == AttributeConstants.ListenerInterfaceAttributeName));
                        if (attr != null)
                        {
                            // Ctor argument can be string or type
                            var fullName = attr.ConstructorArguments[0].Value as string;
                            if (fullName == null)
                            {
                                var typeRef = (TypeReference)attr.ConstructorArguments[0].Value;
                                var intfType = typeRef.Resolve();
                                fullName = GetFullName(intfType);
                            }
                            if (fullName != null)
                            {
                                // Found event with ListenerInterfaceAttribute
                                usedInterfaces.Add(fullName);
                                foundInterfaces.Remove(fullName);
                            }
                        }
                    }
                }
            }

            if (foundInterfaces.Count == 0)
                return;

            Console.WriteLine("Found {0} listener interfaces", foundInterfaces.Count);
            foreach (var name in foundInterfaces.OrderBy(x => x))
            {
                Console.WriteLine(name);
            }
            Console.WriteLine();
        }
 private IEnumerable<HgBundleFile> BuildBundleFiles(HgRepository hgRepository, HgRevset hgRevset, HashSet<string> paths)
 {
     var orderedPaths = paths.OrderBy(p => p).ToList();
     foreach(var path in orderedPaths)
     {
         var bundleFile = BuildBundleFile(hgRepository, hgRevset, path);
         if(bundleFile != null)
             yield return bundleFile;
     } // foreach
 }
        public static Vector3 GetClosestWardSpot(this Vector3 wallPosition)
        {
            // If the position is not a wall then return the input position
            var flags = wallPosition.ToNavMeshCell().CollFlags;
            if (!flags.HasFlag(CollisionFlags.Wall) && !flags.HasFlag(CollisionFlags.Building))
            {
                return wallPosition;
            }

            const int maxRange = 10;
            const double step = 2 * Math.PI / 20;

            var start = new Vector2(wallPosition.ToNavMeshCell().GridX, wallPosition.ToNavMeshCell().GridY);
            var checkedCells = new HashSet<Vector2>();

            // Get all directions
            var directions = new List<Vector2>();
            for (var theta = 0d; theta <= 2 * Math.PI + step; theta += step)
            {
                directions.Add((new Vector2((short) (start.X + Math.Cos(theta)), (short) (start.Y - Math.Sin(theta))) - start).Normalized());
            }

            var validPositions = new HashSet<Vector3>();
            for (var range = 1; range < maxRange; range++)
            {
                foreach (var direction in directions)
                {
                    // Get the position to check
                    var end = start + range * direction;
                    var testPoint = new Vector2((short) end.X, (short) end.Y);
                    if (checkedCells.Contains(testPoint))
                    {
                        continue;
                    }
                    checkedCells.Add(testPoint);

                    // Check the position for wall flags
                    flags = new NavMeshCell((short) testPoint.X, (short) testPoint.Y).CollFlags;
                    if (!flags.HasFlag(CollisionFlags.Wall) && !flags.HasFlag(CollisionFlags.Building))
                    {
                        // Add the position to the valid positions set
                        validPositions.Add(NavMesh.GridToWorld((short) testPoint.X, (short) testPoint.Y));
                    }
                }

                if (validPositions.Count > 0)
                {
                    // Return the closest position to the initial wall position
                    return validPositions.OrderBy(o => o.Distance(start, true)).First();
                }
            }

            // Nothing found return input
            return wallPosition;
        }
Example #22
0
        public void Should_visit_all_vertices_reachable_from_one()
        {
            var found = new HashSet<int>();

            var algorithm = new DepthFirstSearchAlgorithm<int, SEdge<int>>(_adjacencyGraph);
            algorithm.DiscoverVertex += v => found.Add(v);
            algorithm.ExamineEdge += e => { if (algorithm.GetVertexColor(e.Target) != GraphColor.White) throw new Exception("cycle!"); };
            algorithm.Compute(1);

            Assert.That(found.OrderBy(i => i).ToArray(), Is.EquivalentTo(new[] {1, 2, 3, 4} ));
        }
        public IEnumerable<Student> OrderedByParticipation()
        {
            if (!this.students.Any())
            {
                throw new InvalidOperationException("There are no students to sort");
            }

            var copiedStudents = new HashSet<Student>(this.students);
            var result = copiedStudents.OrderBy(st => st.Participations);
            return result;
        }
Example #24
0
        public TDPNode JumpPointSearch(int mStartX, int mStartY, int mTargetX, int mTargetY)
        {
            var startNode = GetNode(mStartX, mStartY);
            var targetNode = GetNode(mTargetX, mTargetY);

            var openContainer = new HashSet<TDPNode> {startNode};
            var nodesToRefresh = new List<TDPNode> {startNode, targetNode};

            while (openContainer.Count > 0)
            {
                var currentNode = openContainer.OrderBy(x => x.F).First();

                openContainer.Remove(currentNode);
                currentNode.IsClosed = true;

                if (currentNode == targetNode)
                {
                    var finalNode = targetNode;
                    while (finalNode.Parent != startNode) finalNode = finalNode.Parent;

                    foreach (var node in nodesToRefresh) node.Refresh();
                    return finalNode;
                }

                foreach (var neighbor in JPSFindNeighbors(currentNode))
                {
                    var jumpPoint = JPSJump(neighbor, currentNode, targetNode);
                    if (jumpPoint == null) continue;

                    var x = currentNode.X;
                    var y = currentNode.Y;
                    var jx = jumpPoint.X;
                    var jy = jumpPoint.Y;
                    var jumpNode = GetNode(jx, jy);

                    if (jumpNode.IsClosed) continue;

                    var d = Math.Sqrt(TDLDistances.EuclideanDistanceSquared(jx, jy, x, y));
                    var ng = currentNode.G + d; // next `g` value

                    if (openContainer.Contains(jumpNode) && !(ng < jumpNode.G)) continue;

                    jumpNode.G = ng;
                    if (jumpNode.H == 0) jumpNode.H = Math.Sqrt(TDLDistances.EuclideanDistanceSquared(jx, jy, targetNode.X, targetNode.Y));
                    jumpNode.Parent = currentNode;

                    openContainer.Add(jumpNode);
                    nodesToRefresh.Add(jumpNode);
                }
            }

            foreach (var node in nodesToRefresh) node.Refresh();
            return null;
        }
Example #25
0
 public override UInt160[] GetScriptHashesForVerifying()
 {
     HashSet<UInt160> hashes = new HashSet<UInt160>(base.GetScriptHashesForVerifying());
     foreach (TransactionResult result in GetTransactionResults().Where(p => p.Amount < Fixed8.Zero))
     {
         RegisterTransaction tx = Blockchain.Default.GetTransaction(result.AssetId) as RegisterTransaction;
         if (tx == null) throw new InvalidOperationException();
         hashes.Add(tx.Admin);
     }
     return hashes.OrderBy(p => p).ToArray();
 }
Example #26
0
        public static Dictionary<Target, int> GetTargetToInt(HashSet<Target> targets)
        {
            var mapping = new Dictionary<Target, int>();
            int count = 0;
            foreach (var target in targets.OrderBy(t => (int)t))
            {
                mapping[target] = count;
                ++count;
            }

            return mapping;
        }
Example #27
0
 static List<int> Primes(int max)
 {
     HashSet<int> p = new HashSet<int>(Enumerable.Range(2, max - 1));
     for (int i = 2; i <= max; i++) {
         if (p.Contains(i)) {
             for (int j = 2 * i; j <= max; j += i) {
                 p.Remove(j);
             }
         }
     }
     return p.OrderBy(i => i).ToList();
 }
Example #28
0
        public static void CopyDirectory(string sourceDir, string destDir) {
            sourceDir = sourceDir.TrimEnd('\\');
            destDir = destDir.TrimEnd('\\');
            try {
                Directory.CreateDirectory(destDir);
            } catch (IOException) {
            }

            var newDirectories = new HashSet<string>(from d in Directory.EnumerateDirectories(sourceDir, "*", SearchOption.AllDirectories)
                                                     where d.StartsWith(sourceDir)
                                                     select d.Substring(sourceDir.Length + 1), StringComparer.OrdinalIgnoreCase);
            newDirectories.ExceptWith(from d in Directory.EnumerateDirectories(destDir, "*", SearchOption.AllDirectories)
                                      where d.StartsWith(destDir)
                                      select d.Substring(destDir.Length + 1));

            foreach (var newDir in newDirectories.OrderBy(i => i.Length).Select(i => Path.Combine(destDir, i))) {
                try {
                    if (newDir.Length < NativeMethods.MAX_FOLDER_PATH) {
                        Directory.CreateDirectory(newDir);
                    }
                } catch {
                    Debug.WriteLine("Failed to create directory " + newDir);
                }
            }

            var newFiles = new HashSet<string>(from f in Directory.EnumerateFiles(sourceDir, "*", SearchOption.AllDirectories)
                                               where f.StartsWith(sourceDir)
                                               select f.Substring(sourceDir.Length + 1), StringComparer.OrdinalIgnoreCase);
            newFiles.ExceptWith(from f in Directory.EnumerateFiles(destDir, "*", SearchOption.AllDirectories)
                                where f.StartsWith(destDir)
                                select f.Substring(destDir.Length + 1));

            foreach (var newFile in newFiles) {
                var copyFrom = Path.Combine(sourceDir, newFile);
                var copyTo = Path.Combine(destDir, newFile);
                try {
                    if (copyTo.Length < NativeMethods.MAX_PATH && copyFrom.Length < NativeMethods.MAX_PATH) {
                        var copyToDir = Path.GetDirectoryName(copyTo);
                        if (copyToDir.Length < NativeMethods.MAX_FOLDER_PATH) {
                            File.Copy(copyFrom, copyTo);
                            File.SetAttributes(copyTo, FileAttributes.Normal);
                        } else {
                            Debug.WriteLine("Failed to copy " + copyFrom + " to " + copyTo + " due to max path limit");
                        }
                    } else {
                        Debug.WriteLine("Failed to copy " + copyFrom + " to " + copyTo + " due to max path limit");
                    }
                } catch {
                    Debug.WriteLine("Failed to copy " + copyFrom + " to " + copyTo + " for unknown reason");
                }
            }
        }
        public void ConcurrentEmitsReachForEach()
        {
            var count = 100;
            var howOften = 1000;

            var source = AsyncEnumerable.Source<int>();
            var evt = new ManualResetEventSlim();
            var sem = new SemaphoreSlim(0);

            var derived = source.Select(i => i).Where(i => true);

            var values = new HashSet<int>();
            var subscription = source.ForEach(i =>
            {
                lock (values)
                {
                    values.Add(i);
                }
            });


            for (int i = 0; i < count; i++)
            {
                var id = i;
                var t = new Thread(() =>
                {
                    evt.Wait();
                    for(int x = 0; x < howOften; x++)
                        source.Yield(id).Wait();
                    sem.Release();
                });
                t.IsBackground = true;
                t.Start();
            }

            evt.Set();

            for (int i = 0; i < count; i++)
                sem.Wait();

            var arr = values.OrderBy(a => a).ToArray();

            Assert.AreEqual(count, arr.Length, "not all inputs processed");

            for (int i = 0; i < count; i++)
            {
                Assert.AreEqual(i, arr[i]);
            }



        }
Example #30
0
        private List<string> BuildWords()
        {
            if (bible == null)
                throw new InvalidOperationException();

            var uniqueWords = new HashSet<string>(
                bible.GetService<ITokenToVerseMap>().TokenFrequency()
                    .Where(tf => tf.Token.IsWord)
                    .Select(tf => (string) tf.Token),
                comparer);
            var sortedWords = uniqueWords.OrderBy(word => word, comparer);
            return sortedWords.ToList();
        }
 private static IEnumerable<string> GetAllFactIds(IDictionary<string, IEnumerable<Fact>> parentChildDictionary)
 {
     var factList = new HashSet<string>();
     foreach (var keyValuePair in parentChildDictionary)
     {
         factList.Add(keyValuePair.Key);
         foreach (var fact in keyValuePair.Value)
         {
             factList.Add(fact.FactId);
         }
     }
     return factList.OrderBy(Convert.ToInt32);
 }
Example #32
0
        //----------------------------------------------

        public override string ToString()
        {
            var authors      = _authorsLink?.OrderBy(x => x.Order).Select(x => x.Author.Name);
            var authorString = authors == null
                ? "(Cached) " + AuthorsOrdered
                : string.Join(", ", authors);
            var reviewsString = _reviews == null
                ? $"(Cached) {ReviewsCount} reviews"
                : $"{_reviews.Count()} reviews";
            var tagsString = _tags == null || !_tags.Any()
                ? ""
                : $" Tags: " + string.Join(", ", _tags.Select(x => x.TagId));

            return($"{Title}: by {authorString}. Price {ActualPrice}, {reviewsString}. Published {PublishedOn:d}{tagsString}");
        }
Example #33
0
        public void Run()
        {
            using (var ch = _host.Start("Run"))
            {
                var conv        = Conversions.Instance;
                var comp        = new SetOfKindsComparer();
                var dstToSrcMap = new Dictionary <HashSet <DataKind>, HashSet <DataKind> >(comp);
                var srcToDstMap = new Dictionary <DataKind, HashSet <DataKind> >();

                var kinds = Enum.GetValues(typeof(DataKind)).Cast <DataKind>().Distinct().OrderBy(k => k).ToArray();
                var types = kinds.Select(kind => PrimitiveType.FromKind(kind)).ToArray();

                HashSet <DataKind> nonIdentity = null;
                // For each kind and its associated type.
                for (int i = 0; i < types.Length; ++i)
                {
                    ch.AssertValue(types[i]);
                    var info = Utils.MarshalInvoke(KindReport <int>, types[i].RawType, ch, types[i]);

                    var      dstKinds = new HashSet <DataKind>();
                    Delegate del;
                    bool     isIdentity;
                    for (int j = 0; j < types.Length; ++j)
                    {
                        if (conv.TryGetStandardConversion(types[i], types[j], out del, out isIdentity))
                        {
                            dstKinds.Add(types[j].RawKind);
                        }
                    }
                    if (!conv.TryGetStandardConversion(types[i], types[i], out del, out isIdentity))
                    {
                        Utils.Add(ref nonIdentity, types[i].RawKind);
                    }
                    else
                    {
                        ch.Assert(isIdentity);
                    }

                    srcToDstMap[types[i].RawKind] = dstKinds;
                    HashSet <DataKind> srcKinds;
                    if (!dstToSrcMap.TryGetValue(dstKinds, out srcKinds))
                    {
                        dstToSrcMap[dstKinds] = srcKinds = new HashSet <DataKind>();
                    }
                    srcKinds.Add(types[i].RawKind);
                }

                // Now perform the final outputs.
                for (int i = 0; i < kinds.Length; ++i)
                {
                    var dsts = srcToDstMap[kinds[i]];
                    HashSet <DataKind> srcs;
                    if (!dstToSrcMap.TryGetValue(dsts, out srcs))
                    {
                        continue;
                    }
                    ch.Assert(Utils.Size(dsts) >= 1);
                    ch.Assert(Utils.Size(srcs) >= 1);
                    string srcStrings = string.Join(", ", srcs.OrderBy(k => k).Select(k => '`' + k.GetString() + '`'));
                    string dstStrings = string.Join(", ", dsts.OrderBy(k => k).Select(k => '`' + k.GetString() + '`'));
                    dstToSrcMap.Remove(dsts);
                    ch.Info(srcStrings + " | " + dstStrings);
                }

                if (Utils.Size(nonIdentity) > 0)
                {
                    ch.Warning("The following kinds did not have an identity conversion: {0}",
                               string.Join(", ", nonIdentity.OrderBy(k => k).Select(DataKindExtensions.GetString)));
                }
            }
        }
Example #34
0
 public int[] GetAllowedThumbnailSizes()
 {
     EnsureThumbSizeWhitelist();
     return(_allowedThumbSizes.OrderBy(x => x).ToArray());
 }
    public static Stack <Node_script> GetPath(GridPosition_script startPosition, GridPosition_script goalPosition)
    {
        if (_nodes == null)
        {
            CreateNodes();
        }

        int                   gCost;
        Node_script           neighbor;
        GridPosition_script   neighborPosition;
        Node_script           currentNode = _nodes[startPosition];
        Node_script           goalNode    = _nodes[goalPosition];
        HashSet <Node_script> openList    = new HashSet <Node_script>();
        HashSet <Node_script> closedList  = new HashSet <Node_script>();
        Stack <Node_script>   path        = new Stack <Node_script>();

        openList.Add(currentNode);

        while (openList.Count > 0)
        {
            // GET THE NODE WITH THE LOWEST F COST
            currentNode = openList.OrderBy(n => n.F).First();

            // GOAL REACHED
            if (currentNode == goalNode)
            {
                // RECONSTRUCT PATH BY BACKTRACING PARENTS
                path.Push(currentNode);

                while (currentNode.Parent != null)
                {
                    currentNode = currentNode.Parent;
                    path.Push(currentNode);
                }

                break;
            }

            // COSE CURRENT
            openList.Remove(currentNode);
            closedList.Add(currentNode);

            // OPEN NEIGHBORS
            for (int row = -1; row <= 1; row++)
            {
                for (int column = -1; column <= 1; column++)
                {
                    neighborPosition = new GridPosition_script(currentNode.Position.Row - row, currentNode.Position.Column - column);

                    // SKIP OUT-OF-BOUNDS, UNWALKABLES AND CURRENT NODE
                    if (TileMap_script.Instance.IsWithinBounds(neighborPosition) &&
                        (TileMap_script.Instance.Tiles[neighborPosition].IsWalkable) && (neighborPosition != currentNode.Position))
                    {
                        neighbor = _nodes[neighborPosition];

                        // SKIP CLOSED NODE
                        if (closedList.Contains(neighbor))
                        {
                            continue;
                        }

                        // HORIZONTAL/VERTICAL
                        if (Mathf.Abs(column - row) == 1)
                        {
                            gCost = 10;
                            // DIAGONAL
                        }
                        else
                        {
                            if (!IsMoveAllowed(currentNode, neighbor))
                            {
                                continue;
                            }
                            gCost = 14;
                        }

                        // NEW/UNVISITED
                        if (!openList.Contains(neighbor))
                        {
                            openList.Add(neighbor);
                            // SKIP IF NOT BETTER
                        }
                        else if ((currentNode.G + gCost) >= neighbor.G)
                        {
                            continue;
                        }

                        // UPDATE COST
                        neighbor.CalculateCost(currentNode, goalNode, gCost);
                    }
                }
            }
        }

        _nodes.Clear();
        _nodes = null;

        //// VIZUALIZE OPEN LIST
        //GameObject.Find("AstarTest_object").GetComponent<AstarTest_script>().Visualize(openList,   Color.yellow);
        //GameObject.Find("AstarTest_object").GetComponent<AstarTest_script>().Visualize(closedList, Color.cyan);
        //GameObject.Find("AstarTest_object").GetComponent<AstarTest_script>().Visualize(path,       Color.blue);

        return(path);
    }
Example #36
0
        public IActionResult Search(string query)
        {
            if (query != null && query != "")
            {
                var model = new SearchViewModel();
                model.subservmod  = new SubjectSearchViewModel();
                model.profservmod = new ProfessorSearchViewModel();
                try
                {
                    // subject part
                    model.subservmod.tags = _context.SubjectTag.Where(o => o.Name.ToLower().Contains(query.ToLower())).ToList();
                    var tmp      = new HashSet <Models.Subject>();
                    var subjects = _context.Subject.Include(s => s.Faculty).ToList();
                    model.query = query;
                    foreach (var tag in model.subservmod.tags)
                    {
                        model.subservmod.subtagset = _context.SubjectTagSet.Include(s => s.Subject).ThenInclude(s => s.Faculty).Where(o => o.SubjectTagID == tag.ID).ToList();


                        foreach (var sts in model.subservmod.subtagset)
                        {
                            if (sts.Subject.Validated)
                            {
                                tmp.Add(sts.Subject);
                            }
                        }
                    }
                    //var tmp = _context.Subject.FirstOrDefault();
                    subjects = subjects.Where(s => s.Name.ToLower().Contains(query.ToLower()) && s.Validated).ToList();
                    foreach (var subject in subjects)
                    {
                        if (!tmp.Contains(subject))
                        {
                            tmp.Add(subject);
                        }
                    }
                    model.subservmod.subjects = tmp.OrderBy(s => s.Name);


                    // professor part
                    var profs = _context.Professor.Where(o => o.Validated && o.FullName.ToLower().Contains(query.ToLower())).ToList();
                    var x     = _context.Subject.Where(s => tmp.Contains(s)).SelectMany(s => s.Professors).Select(s => s.Professor).Where(p => p.Validated).ToList();
                    foreach (var y in x)
                    {
                        if (!profs.Contains(y))
                        {
                            profs.Add(y);
                        }
                    }

                    model.profservmod.professors = profs.OrderBy(p => p.FullName);
                }
                //model.subjects = _context.Subject.ToList();
                catch {
                    model.query = query;
                }
                return(View(model));
            }
            var model2 = new SearchViewModel();

            model2.subservmod             = new SubjectSearchViewModel();
            model2.profservmod            = new ProfessorSearchViewModel();
            model2.profservmod.professors = _context.Professor.Where(o => o.Validated).OrderBy(p => p.FullName).ToList();
            model2.subservmod.subjects    = _context.Subject.Include(s => s.Faculty).Where(o => o.Validated).OrderBy(s => s.Name).ToList();
            //model2.subtagset = _context.SubjectTagSet.ToList();
            model2.query = query;
            return(View(model2));
        }
Example #37
0
        /// <summary>
        /// For framework use only.
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="context"></param>
        /// <param name="candidates"></param>
        /// <returns></returns>
        public Task ApplyAsync(HttpContext httpContext, EndpointSelectorContext context, CandidateSet candidates)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            if (candidates == null)
            {
                throw new ArgumentNullException(nameof(candidates));
            }

            // Returning a 405 here requires us to return keep track of all 'seen' HTTP methods. We allocate to
            // keep track of this beause we either need to keep track of the HTTP methods or keep track of the
            // endpoints - both allocate.
            //
            // Those code only runs in the presence of dynamic endpoints anyway.
            //
            // We want to return a 405 iff we eliminated ALL of the currently valid endpoints due to HTTP method
            // mismatch.
            bool?            needs405Endpoint = null;
            HashSet <string> methods          = null;

            for (var i = 0; i < candidates.Count; i++)
            {
                // We do this check first for consistency with how 405 is implemented for the graph version
                // of this code. We still want to know if any endpoints in this set require an HTTP method
                // even if those endpoints are already invalid.
                var metadata = candidates[i].Endpoint.Metadata.GetMetadata <IHttpMethodMetadata>();
                if (metadata == null || metadata.HttpMethods.Count == 0)
                {
                    // Can match any method.
                    needs405Endpoint = false;
                    continue;
                }

                // Saw a valid endpoint.
                needs405Endpoint = needs405Endpoint ?? true;

                if (!candidates.IsValidCandidate(i))
                {
                    continue;
                }

                var httpMethod = httpContext.Request.Method;
                var headers    = httpContext.Request.Headers;
                if (metadata.AcceptCorsPreflight &&
                    string.Equals(httpMethod, PreflightHttpMethod, StringComparison.OrdinalIgnoreCase) &&
                    headers.ContainsKey(HeaderNames.Origin) &&
                    headers.TryGetValue(HeaderNames.AccessControlRequestMethod, out var accessControlRequestMethod) &&
                    !StringValues.IsNullOrEmpty(accessControlRequestMethod))
                {
                    needs405Endpoint = false; // We don't return a 405 for a CORS preflight request when the endpoints accept CORS preflight.
                    httpMethod       = accessControlRequestMethod;
                }

                var matched = false;
                for (var j = 0; j < metadata.HttpMethods.Count; j++)
                {
                    var candidateMethod = metadata.HttpMethods[j];
                    if (!string.Equals(httpMethod, candidateMethod, StringComparison.OrdinalIgnoreCase))
                    {
                        methods = methods ?? new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                        methods.Add(candidateMethod);
                        continue;
                    }

                    matched          = true;
                    needs405Endpoint = false;
                    break;
                }

                if (!matched)
                {
                    candidates.SetValidity(i, false);
                }
            }

            if (needs405Endpoint == true)
            {
                // We saw some endpoints coming in, and we eliminated them all.
                context.Endpoint = CreateRejectionEndpoint(methods.OrderBy(m => m, StringComparer.OrdinalIgnoreCase));
            }

            return(Task.CompletedTask);
        }
Example #38
0
        /// <summary>
        /// Guesses all inputs in a pipeline.
        /// If empty, the function looks into every view with no predecessor.
        /// </summary>
        public static void GuessInputs(IDataTransform trans, ref string[] inputs, IDataView[] begin = null)
        {
            var vars = EnumerateVariables(trans, begin).Where(c => c.position == TagHelper.GraphPositionEnum.first).ToArray();

            if (inputs == null)
            {
                inputs = vars.Select(c => c.variableName).ToArray();
                var has = new HashSet <string>(inputs);
                if (has.Count != inputs.Length)
                {
                    throw Contracts.Except($"One column is duplicated.");
                }
            }
            else
            {
                var has = new HashSet <string>(inputs);
                if (has.Count != inputs.Length)
                {
                    throw Contracts.Except($"One column is duplicated.");
                }
                has = new HashSet <string>(vars.Select(c => c.variableName));
                foreach (var inp in inputs)
                {
                    if (!has.Contains(inp))
                    {
                        throw Contracts.Except($"Unable to find column '{inp}' in {string.Join(", ", has.OrderBy(c => c))}.");
                    }
                }
            }
        }
Example #39
0
 protected override string GetKey()
 {
     return(_currentCity + "-" + string.Join("-", _visited.OrderBy(i => i)));
 }
Example #40
0
        static void InHousrTest(string[] args)
        {
            args = new string[]
            {
                "Vector",
                "-1",
                //"langprofiles-char-1_5-nfc-all.bin.gz",
                "langprofiles-word-1_5-nfc-10k.bin.gz",
                "wiki",
                //"parsed-files.txt"
                "test_lst.txt"
            };
            if (args.Length != 5 && args.Length != 7)
            {
                Console.Error.WriteLine("Usage: TestLanguageIdentifier liSpec cap distros.bin.gz [wiki|twit|none] tests.txt [nfolds fold]");
                Console.Error.WriteLine("where liSpec: Vector     -- cosine similarity of gram vectors");
                Console.Error.WriteLine("              Likely     -- probability of last char of trigram conditioned on prefix");
                Console.Error.WriteLine("              LikelySp   -- probability of last char of trigram conditioned on prefix, smart prior");
                Console.Error.WriteLine("              LikelyAp   -- probability of last char of trigram conditioned on prefix, additive prior");
                Console.Error.WriteLine("              Rank,rs    -- rank corr; rs = sf|sr|kt");
                Console.Error.WriteLine("      cap indicates how many grams per language to load (-1 means use all)");
                Console.Error.WriteLine("      distros.bin.gz is the file containing language profiles procuded by CompileDistros");
                Console.Error.WriteLine("      tests.txt contains a list of test file names, one per language, each file name of the form xx_*,");
                Console.Error.WriteLine("           where xx is the ISO 639-1 language code");
                Console.Error.WriteLine("      nfolds (optionally) indicates the number of folds for n-fold cross validation");
                Console.Error.WriteLine("      fold (optionally) indicates the number of the fold to test on");
            }
            else
            {
                var sw      = Stopwatch.StartNew();
                var li      = LanguageIdentifier.New(args[2], args[0], int.Parse(args[1]));
                var cleaner = Cleaning.MakeCleaner(args[3]);
                var nfolds  = args.Length == 5 ? -1 : int.Parse(args[5]);
                var fold    = args.Length == 5 ? -1 : int.Parse(args[6]);

                var confusionMatrix = new Dictionary <string, long>();
                var set             = new HashSet <string>();
                foreach (var pair in LabeledData.Read(args[4], nfolds, fold, false))
                {
                    var lang = li.Identify(cleaner(pair.text));  // Calling the language identifier -- it all happens here!
                    if (pair.lang == "")
                    {
                        continue;
                    }
                    var key = lang + "\t" + pair.lang;
                    set.Add(lang);
                    set.Add(pair.lang);
                    if (!confusionMatrix.ContainsKey(key))
                    {
                        confusionMatrix[key] = 0;
                    }
                    confusionMatrix[key]++;
                }
                var langs = set.OrderBy(x => x).ToArray();
                for (int i = 0; i < langs.Length; i++)
                {
                    Console.Write("\t{0}", langs[i]);
                }
                Console.WriteLine();
                for (int j = 0; j < langs.Length; j++)
                {
                    Console.Write(langs[j]);
                    for (int i = 0; i < langs.Length; i++)
                    {
                        Console.Write("\t{0}", Lookup(confusionMatrix, langs[j] + "\t" + langs[i]));
                    }
                    Console.WriteLine();
                }
                Console.Error.WriteLine("Done. Job took {0} seconds", sw.ElapsedMilliseconds * 0.001);
                Console.ReadKey();
            }
        }
        private static void WriteCommonClass(Type type, CSharpCodeProvider compiler)
        {
            string name      = type.Name.Replace(DESCRIPTOR, PARAMETERS);
            string subFolder = GetSubfolder();

            List <string> propertiesList = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanRead && p.CanWrite)
                                           .Aggregate(new List <string>(), (list, p) =>
            {
                if (p.GetMethod.IsAbstract)
                {
                    list.Add(string.Format("\t\tabstract public {0} {1} {{ get; set; }}", p.PropertyType.GetNewPropertyClassName(compiler, replaceCommonTypeName), p.Name));
                }
                else if (p.GetMethod.IsVirtual && !p.GetMethod.IsFinal && p.GetMethod.GetBaseDefinition() == p.GetMethod)
                {
                    list.Add(string.Format("\t\tvirtual public {0} {1} {{ get; set; }}", p.PropertyType.GetNewPropertyClassName(compiler, replaceCommonTypeName), p.Name));
                }
                else if (p.GetMethod.GetBaseDefinition() != p.GetMethod)
                {
                    list.Add(string.Format("\t\tpublic override {0} {1} {{ get; set; }}", p.PropertyType.GetNewPropertyClassName(compiler, replaceCommonTypeName), p.Name));
                }
                else
                {
                    list.Add(string.Format("\t\tpublic {0} {1} {{ get; set; }}", p.PropertyType.GetNewPropertyClassName(compiler, replaceCommonTypeName), p.Name));
                }

                return(list);
            });

            List <string> propertyNameList = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanRead && p.CanWrite)
                                             .Aggregate(new List <string>(), (list, p) =>
            {
                list.Add(p.Name);

                return(list);
            });

            HashSet <string> nameSpaces = new HashSet <string>(new List <string> {
                "using LogicBuilder.Attributes;"
            });
            Type currentType = type;

            while (currentType != typeof(object))
            {
                nameSpaces  = GetNamespaces(nameSpaces);
                currentType = currentType.BaseType;
            }

            string constructorString = GetConstructor(type, compiler, propertyNameList);

            string baseClassString = type.BaseType != typeof(object) ? $" : {type.BaseType.GetNewPropertyClassName(compiler, replaceCommonTypeName)}" : "";

            string nameSpacesString = nameSpaces.Any()
                ? $"{string.Join(Environment.NewLine, nameSpaces.OrderBy(n => n))}{Environment.NewLine}{Environment.NewLine}"
                : "";

            string propertiestring = propertiesList.Any()
                ? $"{Environment.NewLine}{Environment.NewLine}{string.Join(Environment.NewLine, propertiesList)}"
                : "";

            string text = File.ReadAllText($"{Directory.GetCurrentDirectory()}\\ParameterClassTemplate.txt")
                          .Replace("#Name#", name)
                          .Replace(PROPERTIES, propertiestring)
                          .Replace(NAMESPACES, nameSpacesString)
                          .Replace(CONSTRUCTORS, constructorString)
                          .Replace("#Base#", baseClassString.Replace(DESCRIPTOR, PARAMETERS));

            text = text.Replace("#Modifier#", type.IsAbstract ? "abstract " : "");

            text = text.Replace("#Folder#", string.IsNullOrEmpty(subFolder) ? "" : $@".{subFolder}");

            string savePath = string.IsNullOrEmpty(subFolder) ? Constants.BASEPATH : $@"{Constants.BASEPATH}\{subFolder}";

            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            using (StreamWriter sr = new StreamWriter($"{savePath}\\{name}.cs", false, Encoding.UTF8))
            {
                sr.Write(text);
            }

            string GetSubfolder()
            {
                if (type.Namespace == "Contoso.Forms.Configuration")
                {
                    return("");
                }

                return(type.Namespace.Replace("Contoso.Forms.Configuration.", ""));
            }

            HashSet <string> GetNamespaces(HashSet <string> namesapces)
            {
                return(currentType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanRead && p.CanWrite)
                       .Select(p => p.PropertyType)
                       .Aggregate(namesapces, (list, next) =>
                {
                    if (next == typeof(object) ||
                        next == typeof(string) ||
                        (next.IsLiteralType() && !typeof(Enum).IsAssignableFrom(next) && !(next.IsGenericType && next.GetGenericTypeDefinition() == typeof(Nullable <>))))
                    {
                        return list;
                    }

                    if (!next.Namespace.Equals("Contoso.Forms.Configuration") &&
                        !next.Namespace.Equals($"Contoso.Forms.Configuration.{subFolder}") &&
                        next.Namespace.StartsWith("Contoso.Forms.Configuration"))
                    {
                        list.Add($"using {next.Namespace.Replace("Contoso.Forms.Configuration", "Contoso.Forms.Parameters")};");
                    }
                    else if (next.Namespace.StartsWith("Contoso.Common.Configuration.ExpressionDescriptors"))
                    {
                        list.Add($"using {next.Namespace.Replace("Contoso.Common.Configuration.ExpressionDescriptors", "Contoso.Parameters.Expressions")};");
                    }
                    else if (next.Namespace.StartsWith("Contoso.Common.Configuration.ExpansionDescriptors"))
                    {
                        list.Add($"using {next.Namespace.Replace("Contoso.Common.Configuration.ExpansionDescriptors", "Contoso.Parameters.Expansions")};");
                    }
                    else if (!next.Namespace.StartsWith("Contoso.Forms.Configuration"))
                    {
                        list.Add($"using {next.Namespace};");
                    }

                    return list;
                }));
            }
        }
Example #42
0
        public static async Task <List <CompletionItem> > Handle(CSharpContext context, string code, int line, int column)
        {
            var _document = context.WithText(code);
            var position  = context.GetPosition(line, column);


            var service        = Microsoft.CodeAnalysis.Completion.CompletionService.GetService(_document);
            var completionList = service.GetCompletionsAsync(_document, position).Result;

            var completions = new HashSet <AutoCompleteResponse>();

            if (completionList != null)
            {
                // Only trigger on space if Roslyn has object creation items
                //if (request.TriggerCharacter == " " && !completionList.Items.Any(i => i.IsObjectCreationCompletionItem()))
                //{
                //    return completions;
                //}

                // get recommended symbols to match them up later with SymbolCompletionProvider
                var semanticModel = await _document.GetSemanticModelAsync();

                var recommendedSymbols = await Microsoft.CodeAnalysis.Recommendations.Recommender.GetRecommendedSymbolsAtPositionAsync(semanticModel, position, context.Workspace);

                var isSuggestionMode = completionList.SuggestionModeItem != null;

                foreach (var item in completionList.Items)
                {
                    var completionText = item.DisplayText;
                    //if (completionText.IsValidCompletionFor(wordToComplete))
                    {
                        var symbols = await item.GetCompletionSymbolsAsync(recommendedSymbols, _document);

                        if (symbols.Any())
                        {
                            foreach (var symbol in symbols)
                            {
                                if (context.Types != null && symbol.Kind != SymbolKind.Namespace)
                                {
                                    var name = symbol.ContainingType != null
                                        ? symbol.ContainingType.ToDisplayString()
                                        : symbol.ToString();

                                    var allowed = context.Types.Any(y => name.Like(y));

                                    if (!allowed)
                                    {
                                        continue;
                                    }
                                }
                                if (item.UseDisplayTextAsCompletionText())
                                {
                                    completionText = item.DisplayText;
                                }
                                else if (item.TryGetInsertionText(out var insertionText))
                                {
                                    completionText = insertionText;
                                }
                                else
                                {
                                    completionText = symbol.Name;
                                }

                                if (symbol != null)
                                {
                                    //if (request.WantSnippet)
                                    //{
                                    //    foreach (var completion in MakeSnippetedResponses(request, symbol, completionText, isSuggestionMode))
                                    //    {
                                    //        completions.Add(completion);
                                    //    }
                                    //}
                                    //else
                                    {
                                        completions.Add(MakeAutoCompleteResponse(symbol, completionText, isSuggestionMode));
                                    }
                                }
                            }

                            // if we had any symbols from the completion, we can continue, otherwise it means
                            // the completion didn't have an associated symbol so we'll add it manually
                            continue;
                        }

                        // for other completions, i.e. keywords, create a simple AutoCompleteResponse
                        // we'll just assume that the completion text is the same
                        // as the display text.
                        var response = new AutoCompleteResponse()
                        {
                            CompletionText   = item.DisplayText,
                            DisplayText      = item.DisplayText,
                            Snippet          = item.DisplayText,
                            Kind             = item.Tags.First(),
                            IsSuggestionMode = isSuggestionMode
                        };

                        completions.Add(response);
                    }
                }
            }

            var osr = completions
                      // .OrderByDescending(c => c.CompletionText.IsValidCompletionStartsWithExactCase(wordToComplete))
                      // .ThenByDescending(c => c.CompletionText.IsValidCompletionStartsWithIgnoreCase(wordToComplete))
                      // .ThenByDescending(c => c.CompletionText.IsCamelCaseMatch(wordToComplete))
                      // .ThenByDescending(c => c.CompletionText.IsSubsequenceMatch(wordToComplete))
                      .OrderBy(c => c.DisplayText, StringComparer.OrdinalIgnoreCase)
                      .ThenBy(c => c.CompletionText, StringComparer.OrdinalIgnoreCase);


            var completions2 = new Dictionary <string, List <CompletionItem> >();

            foreach (var response in osr)
            {
                var completionItem = new CompletionItem
                {
                    label  = response.CompletionText,
                    detail = !string.IsNullOrEmpty(response.ReturnType) ?
                             response.DisplayText :
                             $"{response.ReturnType} {response.DisplayText}",
                    documentation = response.Description,
                    kind          = (int)GetCompletionItemKind(response.Kind),
                    insertText    = response.CompletionText,
                };

                if (!completions2.ContainsKey(completionItem.label))
                {
                    completions2[completionItem.label] = new List <CompletionItem>();
                }
                completions2[completionItem.label].Add(completionItem);
            }

            var result = new List <CompletionItem>();

            foreach (var key in completions2.Keys)
            {
                var suggestion    = completions2[key][0];
                var overloadCount = completions2[key].Count - 1;

                if (overloadCount > 0)
                {
                    // indicate that there is more
                    suggestion.detail = $"{suggestion.detail} (+ {overloadCount} overload(s))";
                }

                result.Add(suggestion);
            }

            return(result);
        }
Example #43
0
        /*
         * http://theory.stanford.edu/~amitp/GameProgramming/ImplementationNotes.html
         * OPEN = priority queue containing START
         * CLOSED = empty set
         * while lowest rank in OPEN is not the GOAL:
         *  current = remove lowest rank item from OPEN
         *  add current to CLOSED
         *  for neighbors of current:
         *  cost = g(current) + movementcost(current, neighbor)
         *  if neighbor in OPEN and cost less than g(neighbor):
         *      remove neighbor from OPEN, because new path is better
         *  if neighbor in CLOSED and cost less than g(neighbor): ⁽²⁾
         *      remove neighbor from CLOSED
         *  if neighbor not in OPEN and neighbor not in CLOSED:
         *      set g(neighbor) to cost
         *      add neighbor to OPEN
         *      set priority queue rank to g(neighbor) + h(neighbor)
         *      set neighbor's parent to current
         */
        public static List <Point> GetPath(GameState state, Point startPoint, Point endPoint)
        {
            Dictionary <Point, Point> Froms     = new Dictionary <Point, Point>();
            Dictionary <Point, int>   Steps     = new Dictionary <Point, int>();
            Dictionary <Point, int>   Distances = new Dictionary <Point, int>();
            //
            HashSet <Point> OPEN = new HashSet <Point>()
            {
                startPoint
            };
            HashSet <Point> CLOSED = new HashSet <Point>();

            //
            int Step = 0;

            Froms[startPoint]     = startPoint;
            Steps[startPoint]     = Step;
            Distances[startPoint] = 0;
            //while lowest rank in OPEN is not the GOAL
            while ((OPEN.Count() > 0) && (OPEN.OrderBy(x => Distances[x]).First() != endPoint))
            {
                //current = remove lowest rank item from OPEN
                //add current to CLOSED
                Point current = OPEN.OrderBy(x => Distances[x]).First();
                OPEN.Remove(current);
                CLOSED.Add(current);
                //for neighbors of current
                List <Point> neighbors = new List <Point>();
                neighbors.Add(new Point(current.X + 1, current.Y));
                neighbors.Add(new Point(current.X - 1, current.Y));
                neighbors.Add(new Point(current.X, current.Y + 1));
                neighbors.Add(new Point(current.X, current.Y - 1));
                foreach (Point neighbor in neighbors)
                {
                    //Is valid neighbor?
                    if (neighbor.X >= GameState.W || neighbor.X < 0 || neighbor.Y >= GameState.H || neighbor.Y < 0)
                    {
                        continue;
                    }
                    if (state.Board[neighbor.X, neighbor.Y] != '.')
                    {
                        continue;
                    }
                    if (state.Entities.Exists(e => e.Position.Equals(neighbor) && e.Type == GameState.EntityType.Bomb))
                    {
                        continue;
                    }
                    //cost = g(current) + movementcost(current, neighbor)
                    int cost = Distances[current] + 1;
                    //if neighbor in OPEN and cost less than g(neighbor)
                    if (OPEN.Contains(neighbor) && (cost < Distances[neighbor]))
                    {
                        //remove neighbor from OPEN, because new path is better
                        OPEN.Remove(neighbor);
                    }
                    //if neighbor in CLOSED and cost less than g(neighbor)
                    if (CLOSED.Contains(neighbor) && (cost < Distances[neighbor]))
                    {
                        //remove neighbor from CLOSED
                        CLOSED.Remove(neighbor);
                    }
                    //if neighbor not in OPEN and neighbor not in CLOSED:
                    if (!OPEN.Contains(neighbor) && !CLOSED.Contains(neighbor))
                    {
                        //set g(neighbor) to cost
                        Distances[neighbor] = cost;
                        //add neighbor to OPEN
                        OPEN.Add(neighbor);
                        //set neighbor's parent to current
                        Froms[neighbor] = current;
                        Steps[neighbor] = Steps[current] + 1;
                    }
                }
            }

            //
            List <Point> Result = new List <Point>();

            //Impossible
            if (!Froms.ContainsKey(endPoint))
            {
                return(Result);
            }
            //
            Point currNode = endPoint;

            while (currNode != startPoint)
            {
                Result.Add(currNode);
                currNode = Froms[currNode];
            }
            //
            return(Result);
        }
Example #44
0
        public static void GenerateLibraryFileFromXML(string file_path)
        {
            XmlTextReader reader = new XmlTextReader(file_path);

            List <string> library_file_lines = new List <string> ();

            string extra_method_string = Properties.Resources.ExtraMethods;
            string extra_call_string   = Properties.Resources.ExtraCalls;

            // Read extra files
            Dictionary <string, string> extra_calls = new Dictionary <string, string> ();

            foreach (string s in extra_call_string.Split('\n'))
            {
                if (s == "")
                {
                    continue;
                }

                string line = s.Substring(0, s.Length - 1);

                int i = line.IndexOf('|');

                extra_calls.Add(line.Substring(0, i), line.Substring(i + 1));
            }

            string method_title          = null;
            string method_name           = null;
            string method_place_notation = null;
            string method_classification = null;
            bool   is_little             = false;
            bool   is_differential       = false;

            int number_of_stupid_methods = 0;

            HashSet <char> chars = new HashSet <char> ();

            while (!reader.EOF)
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.Name == "classification")
                    {
                        if (reader.IsEmptyElement)
                        {
                            method_classification = Utils.ClassificationToString(Classification.Principle);

                            is_little       = false;
                            is_differential = false;

                            reader.Read();
                        }
                        else
                        {
                            is_little       = reader.GetAttribute("little") != null;
                            is_differential = reader.GetAttribute("differential") != null;

                            method_classification = reader.ReadInnerXml();
                        }
                    }
                    else if (reader.Name == "name")
                    {
                        if (reader.IsEmptyElement)
                        {
                            method_name = "";

                            reader.Read();
                        }
                        else
                        {
                            method_name = reader.ReadInnerXml();
                        }
                    }
                    else if (reader.Name == "title")
                    {
                        method_title = reader.ReadInnerXml();
                    }
                    else if (reader.Name == "notation")
                    {
                        method_place_notation = reader.ReadInnerXml();
                    }
                    else
                    {
                        reader.Read();
                    }
                }
                else if (reader.NodeType == XmlNodeType.EndElement)
                {
                    if (reader.Name == "method")
                    {
                        Stage stage = Utils.GetStageOfMethodFromMethodTitle(method_title);

                        method_place_notation = PlaceNotation.CompressPlaceNotation(method_place_notation, stage);

                        Method method = new Method(method_place_notation, method_name, stage, null, false);

                        foreach (char c in method_title)
                        {
                            chars.Add(c);
                        }

                        bool should_overwrite_title;

                        if (method.title == method_title)
                        {
                            should_overwrite_title = false;
                        }
                        else
                        {
                            number_of_stupid_methods += 1;
                            Console.WriteLine(method_title + " != " + method.title);
                            should_overwrite_title = true;
                        }

                        string tag_string = "";
                        if (is_differential)
                        {
                            if (is_little)
                            {
                                tag_string = "b";                                 // b = both
                            }
                            else
                            {
                                tag_string = "d";                                 // d = differential
                            }
                        }
                        else
                        {
                            if (is_little)
                            {
                                tag_string = "l";                                 // l = little
                            }
                        }

                        library_file_lines.Add(
                            method_name + "|" +
                            method_place_notation + "|" +
                            Constants.int_value_lookup [(int)stage] +
                            Constants.int_value_lookup [(int)Utils.StringToClassification(method_classification)] +
                            tag_string +
                            (should_overwrite_title ? "|" + method_title : "") +
                            (extra_calls.ContainsKey(method_title) ? "\\" + extra_calls [method_title] : "")
                            );
                    }

                    reader.Read();
                }
                else
                {
                    reader.Read();
                }
            }

            foreach (char c in chars.OrderBy(x => (int)x))
            {
                Console.Write(true ? c.ToString() : (int)c + " ");
            }

            Console.Write("\n");

            Console.WriteLine(library_file_lines.Count.ToString() + " methods copied.  " + number_of_stupid_methods + " of them are stupid.");

            System.IO.File.WriteAllLines("../../../../Bob/methods.txt", library_file_lines.ToArray());
        }
        public static void TestTaskContinuation()
        {
            // Relay race in the olympics
            string[] countries = { "Russia", "France", "England", "United States", "India", "Germany", "China" };
            Task <RelayRunner>[,] teams = new Task <RelayRunner> [countries.Length, 4];
            List <Task <RelayRunner> > runners         = new List <Task <RelayRunner> >();
            List <Task <RelayRunner> > firstLegRunners = new List <Task <RelayRunner> >();

            for (int i = 0; i < countries.Length; i++)
            {
                for (int r = 0; r < 4; r++)
                {
                    var runner = new RelayRunner()
                    {
                        Country   = countries[i],
                        Leg       = r + 1,
                        HasBaton  = r == 0 ? true : false,
                        TotalLegs = 4
                    };

                    if (r == 0) // add starting leg for country
                    {
                        Func <RelayRunner> funcRunner = runner.Sprint;
                        teams[i, r] = new Task <RelayRunner>(funcRunner);
                        firstLegRunners.Add(teams[i, r]);
                    }
                    else // add other legs for country
                    {
                        teams[i, r] = teams[i, r - 1].ContinueWith((lastRunnerRunning) =>
                        {
                            var lastRunner = lastRunnerRunning.Result;
                            // Handoff the baton
                            Console.WriteLine($"{lastRunner.Country} hands off from " +
                                              $"{lastRunner.Leg} to {runner.Leg}!");
                            Random rnd       = new Random();
                            int fumbleChance = rnd.Next(0, 10);
                            if (fumbleChance > 8)
                            {
                                Console.WriteLine($"Oh no! {lastRunner.Country} for Leg {runner.Leg}" +
                                                  $" fumbled the hand off from Leg {lastRunner.Leg}!");
                                Thread.Sleep(1000);
                                Console.WriteLine($"{lastRunner.Country} for Leg {runner.Leg}" +
                                                  " recovered the baton and is running again!");
                            }
                            lastRunner.HasBaton = false;
                            runner.HasBaton     = true;
                            return(runner.Sprint());
                        });
                    }
                    // add to our list of runners
                    runners.Add(teams[i, r]);
                }
            }

            //Fire the gun to start the race!
            Parallel.ForEach(firstLegRunners, r =>
            {
                r.Start();
            });

            // Wait for everyone to finish
            Task.WaitAll(runners.ToArray());

            Console.WriteLine("\r\nRace standings:");

            var standings = from r in runners
                            group r by r.Result.Country into countryTeams
                            select countryTeams;

            string winningCountry = string.Empty;
            int    bestTime       = int.MaxValue;

            HashSet <Tuple <int, string> > place = new HashSet <Tuple <int, string> >();

            foreach (var team in standings)
            {
                var time = team.Sum(r => r.Result.LegTime.Milliseconds);
                if (time < bestTime)
                {
                    bestTime       = time;
                    winningCountry = team.Key;
                }
                place.Add(new Tuple <int, string>(time, $"{team.Key} with a time of {time}ms"));
            }
            int p = 1;

            foreach (var item in place.OrderBy(t => t.Item1))
            {
                Console.WriteLine($"{p}: {item.Item2}");
                p++;
            }
            Console.WriteLine($"\n\nThe winning team is from {winningCountry}");
        }
        public FsmModel CreateModel(PlayMakerFSM fsm)
        {
            var model = new FsmModel {
                description = fsm.FsmDescription,
                states      = new List <FsmStateModel>(),
            };

            GetPrefabData(fsm, model);

            // Pre-populate state models.
            var stateLookup = new Dictionary <string, FsmStateModel>();

            foreach (var state in fsm.FsmStates)
            {
                // Cannot support duplicate state names, and PlayMaker's GUI does not allow this but gotta check.
                if (stateLookup.ContainsKey(state.Name))
                {
                    throw new System.Exception("Duplicate state name: " + state.Name);
                }

                if (state.Name.Contains("\""))
                {
                    throw new System.Exception("Illegal characters in state name '" + state.Name + "'");
                }

                var stateModel = new FsmStateModel {
                    name        = state.Name,
                    transitions = new List <FsmTransitionModel>(),
                    isStart     = fsm.Fsm.StartState == state.Name,
                };

                model.states.Add(stateModel);

                stateLookup[state.Name] = stateModel;
            }

            // All events
            var fsmEvents = new HashSet <string>(fsm.FsmEvents.Select(e => e.Name));

            // Now populate transitions
            foreach (var state in fsm.FsmStates)
            {
                var stateModel = stateLookup[state.Name];

                // Gather transition events
                var evts = new HashSet <string>();
                foreach (var transition in state.Transitions)
                {
                    if (evts.Contains(transition.FsmEvent.Name))
                    {
                        throw new System.Exception("Duplicate transition event: " + transition.FsmEvent.Name + " in state: " + state.Name);
                    }

                    FsmStateModel toState;
                    if (!stateLookup.TryGetValue(transition.ToState, out toState))
                    {
                        throw new System.Exception("Missing to state in transition: " + transition.FsmEvent.Name + " in state: " + state.Name);
                    }

                    if (toState == stateModel)
                    {
                        throw new System.Exception("Detected self transition in state: " + state.Name + " for event: " + transition.FsmEvent.Name);
                    }

                    evts.Add(transition.FsmEvent.Name);
                }

                // Gather internal actions
                stateModel.internalActions = new List <FsmInternalActionModel>();
                foreach (var action in state.Actions)
                {
                    if (action is Actions.InternalAction)
                    {
                        var i = action as Actions.InternalAction;
                        if (i._event == null || string.IsNullOrEmpty(i._event.Value))
                        {
                            throw new System.Exception(string.Format("Internal action in '{0}' has no event defined", state.Name));
                        }
                        else if (!fsmEvents.Contains(i._event.Value))
                        {
                            throw new System.Exception(string.Format("Internal action in '{0}' has event '{1}' but no event by that name is defined", state.Name, i._event.Value));
                        }

                        var actionModel = new FsmInternalActionModel {
                            evt = new FsmEventModel {
                                name = i._event.Value,
                            },
                            _delegate = new FsmDelegateMethod(),
                        };

                        FillInMethodInfo(stateModel, action as Actions.BaseDelegateAction, i._event.Value + " (internal action)", actionModel._delegate);

                        stateModel.internalActions.Add(actionModel);
                    }
                }

                // Gather transitions
                foreach (var transition in state.Transitions)
                {
                    FsmStateModel toState = stateLookup[transition.ToState];

                    var transitionModel = new FsmTransitionModel {
                        evt = new FsmEventModel {
                            name = transition.FsmEvent.Name,
                        },
                        from = stateModel,
                        to   = toState,
                    };

                    stateModel.transitions.Add(transitionModel);
                }

                // Gather on enter/exit
                stateModel.onEnter = new List <FsmOnEnterExitModel>();
                stateModel.onExit  = new List <FsmOnEnterExitModel>();

                foreach (var action in state.Actions)
                {
                    AddEnterExitEvent(action as Actions.BaseDelegateAction, stateModel);
                }

                // Gather ignore events
                var toIgnore = new HashSet <string>();
                stateModel.ignoreEvents = new List <FsmEventModel>();
                foreach (var action in state.Actions)
                {
                    var ignore = action as Actions.IgnoreEventAction;
                    if (ignore == null || ignore._event == null || string.IsNullOrEmpty(ignore._event.Value) || toIgnore.Contains(ignore._event.Value))
                    {
                        continue;
                    }

                    // Sanity check, this event should not be used in a transition or an internal action
                    var evt = ignore._event.Value;
                    foreach (var internalAction in stateModel.internalActions)
                    {
                        if (internalAction.evt.name == evt)
                        {
                            throw new System.Exception(string.Format("Ignore action event in '{0}' has event '{1}' that is used by an internal action", state.Name, evt));
                        }
                    }
                    foreach (var transition in stateModel.transitions)
                    {
                        if (transition.evt.name == evt)
                        {
                            throw new System.Exception(string.Format("Ignore action event in '{0}' has event '{1}' that is used by a transition", state.Name, evt));
                        }
                    }

                    stateModel.ignoreEvents.Add(new FsmEventModel {
                        name = ignore._event.Value
                    });
                }
            }

            // Now gather all required interfaces
            var interfaces = new HashSet <Type>();

            foreach (var state in model.states)
            {
                foreach (var m in state.onEnter)
                {
                    interfaces.Add(m._delegate._interface);
                }
                foreach (var m in state.internalActions)
                {
                    interfaces.Add(m._delegate._interface);
                }
                foreach (var m in state.onExit)
                {
                    interfaces.Add(m._delegate._interface);
                }
            }

            model.context = new FsmContextModel {
                requiredInterfaces = interfaces.OrderBy(t => t.FullName).ToList(),
            };

            // Gather all used events
            var events = new HashSet <string>();

            foreach (var state in model.states)
            {
                foreach (var transition in state.transitions)
                {
                    events.Add(transition.evt.name);
                }
                foreach (var action in state.internalActions)
                {
                    events.Add(action.evt.name);
                }
            }

            model.events = events.OrderBy(e => e).Select(e => new FsmEventModel {
                name = e
            }).ToList();

            return(model);
        }
Example #47
0
 public override string ToString()
 {
     return(string.Join(",", _severities.OrderBy(s => s).Select(s => SeverityPrefix + s).Concat(_codes.OrderBy(c => c))));
 }
Example #48
0
        /// <summary>
        /// Returns the ordered file set for dynamically registered assets and ensures that all pre-processor pipelines are applied correctly
        /// </summary>
        /// <param name="files"></param>
        /// <param name="pipeline"></param>
        /// <returns></returns>
        public IEnumerable <IWebFile> GetOrderedFileSet(IEnumerable <IWebFile> files, PreProcessPipeline pipeline)
        {
            var customOrdered  = new HashSet <IWebFile>(WebFilePairEqualityComparer.Instance);
            var defaultOrdered = new HashSet <IWebFile>(WebFilePairEqualityComparer.Instance);

            foreach (var file in files)
            {
                ValidateFile(file);
                if (file.Pipeline == null)
                {
                    file.Pipeline = pipeline.Copy();
                }
                file.FilePath = _requestHelper.Content(file.FilePath);

                //We need to check if this path is a folder, then iterate the files
                if (_fileSystemHelper.IsFolder(file.FilePath))
                {
                    var filePaths = _fileSystemHelper.GetPathsForFilesInFolder(file.FilePath);
                    foreach (var f in filePaths)
                    {
                        if (file.Order > 0)
                        {
                            customOrdered.Add(new WebFile
                            {
                                FilePath       = _requestHelper.Content(f),
                                DependencyType = file.DependencyType,
                                Pipeline       = file.Pipeline,
                                Order          = file.Order
                            });
                        }
                        else
                        {
                            defaultOrdered.Add(new WebFile
                            {
                                FilePath       = _requestHelper.Content(f),
                                DependencyType = file.DependencyType,
                                Pipeline       = file.Pipeline,
                                Order          = file.Order
                            });
                        }
                    }
                }
                else
                {
                    if (file.Order > 0)
                    {
                        customOrdered.Add(file);
                    }
                    else
                    {
                        defaultOrdered.Add(file);
                    }
                }
            }

            //add the custom ordered to the end of the list
            foreach (var f in customOrdered.OrderBy(x => x.Order))
            {
                defaultOrdered.Add(f);
            }

            //apply conventions
            return(defaultOrdered.Select(ApplyConventions).Where(x => x != null));
        }
        public StringBuilder Export(string pipeLineAbbreviation, HashSet <Element> elements, Document document)
        {
            Document doc   = document;
            string   key   = pipeLineAbbreviation;
            plst     pList = new plst();
            //paramList = new plst();
            //The list of fittings, sorted by TYPE then SKEY
            IList <Element> accessoriesList = elements.
                                              OrderBy(e => e.get_Parameter(pList.PCF_ELEM_TYPE.Guid).AsString()).
                                              ThenBy(e => e.get_Parameter(pList.PCF_ELEM_SKEY.Guid).AsString()).ToList();

            StringBuilder sbAccessories = new StringBuilder();

            //This is a workaround to try to determine what element caused an exception
            Element element = null;

            try
            {
                foreach (Element Element in accessoriesList)
                {
                    //This is a workaround to try to determine what element caused an exception
                    element = Element;
                    //If the Element Type field is empty -> ignore the component
                    if (string.IsNullOrEmpty(element.get_Parameter(pList.PCF_ELEM_TYPE.Guid).AsString()))
                    {
                        continue;
                    }

                    sbAccessories.AppendLine(element.get_Parameter(new plst().PCF_ELEM_TYPE.Guid).AsString());
                    sbAccessories.AppendLine("    COMPONENT-IDENTIFIER " + element.get_Parameter(new plst().PCF_ELEM_COMPID.Guid).AsInteger());

                    //Write Plant3DIso entries if turned on
                    if (InputVars.ExportToPlant3DIso)
                    {
                        sbAccessories.Append(Composer.Plant3DIsoWriter(element, doc));
                    }

                    //Cast the elements gathered by the collector to FamilyInstances
                    FamilyInstance familyInstance = (FamilyInstance)element;
                    Options        options        = new Options();
                    //MEPModel of the elements is accessed
                    MEPModel mepmodel = familyInstance.MEPModel;
                    //Get connector set for the element
                    ConnectorSet connectorSet = mepmodel.ConnectorManager.Connectors;

                    //Switch to different element type configurations
                    switch (element.get_Parameter(pList.PCF_ELEM_TYPE.Guid).AsString())
                    {
                    case ("FILTER"):
                        //Process endpoints of the component
                        Connector primaryConnector = null; Connector secondaryConnector = null;

                        foreach (Connector connector in connectorSet)
                        {
                            if (connector.GetMEPConnectorInfo().IsPrimary)
                            {
                                primaryConnector = connector;
                            }
                            if (connector.GetMEPConnectorInfo().IsSecondary)
                            {
                                secondaryConnector = connector;
                            }
                        }

                        //Process endpoints of the component
                        sbAccessories.Append(EndWriter.WriteEP1(element, primaryConnector));
                        sbAccessories.Append(EndWriter.WriteEP2(element, secondaryConnector));

                        break;

                    case ("INSTRUMENT"):
                        //Process endpoints of the component
                        primaryConnector = null; secondaryConnector = null;

                        foreach (Connector connector in connectorSet)
                        {
                            if (connector.GetMEPConnectorInfo().IsPrimary)
                            {
                                primaryConnector = connector;
                            }
                            if (connector.GetMEPConnectorInfo().IsSecondary)
                            {
                                secondaryConnector = connector;
                            }
                        }

                        //Process endpoints of the component
                        sbAccessories.Append(EndWriter.WriteEP1(element, primaryConnector));
                        sbAccessories.Append(EndWriter.WriteEP2(element, secondaryConnector));
                        sbAccessories.Append(EndWriter.WriteCP(familyInstance));

                        break;

                    case ("VALVE"):
                        goto case ("INSTRUMENT");

                    case ("VALVE-ANGLE"):
                        //Process endpoints of the component
                        primaryConnector = null; secondaryConnector = null;

                        foreach (Connector connector in connectorSet)
                        {
                            if (connector.GetMEPConnectorInfo().IsPrimary)
                            {
                                primaryConnector = connector;
                            }
                            if (connector.GetMEPConnectorInfo().IsSecondary)
                            {
                                secondaryConnector = connector;
                            }
                        }

                        //Process endpoints of the component
                        sbAccessories.Append(EndWriter.WriteEP1(element, primaryConnector));
                        sbAccessories.Append(EndWriter.WriteEP2(element, secondaryConnector));

                        //The centre point is obtained by creating an unbound line from primary connector and projecting the secondary point on the line.
                        XYZ  reverseConnectorVector = -primaryConnector.CoordinateSystem.BasisZ;
                        Line primaryLine            = Line.CreateUnbound(primaryConnector.Origin, reverseConnectorVector);
                        XYZ  centrePoint            = primaryLine.Project(secondaryConnector.Origin).XYZPoint;

                        sbAccessories.Append(EndWriter.WriteCP(centrePoint));

                        break;

                    case ("INSTRUMENT-DIAL"):
                        ////Process endpoints of the component
                        //primaryConnector = null;

                        //foreach (Connector connector in connectorSet) primaryConnector = connector;

                        ////Process endpoints of the component
                        //sbAccessories.Append(EndWriter.WriteEP1(element, primaryConnector));

                        ////The co-ords point is obtained by creating an unbound line from primary connector and taking an arbitrary point a long the line.
                        //reverseConnectorVector = -primaryConnector.CoordinateSystem.BasisZ.Multiply(0.656167979);
                        //XYZ coOrdsPoint = primaryConnector.Origin;
                        //Transform pointTranslation;
                        //pointTranslation = Transform.CreateTranslation(reverseConnectorVector);
                        //coOrdsPoint = pointTranslation.OfPoint(coOrdsPoint);

                        primaryConnector = null;
                        foreach (Connector connector in connectorSet)
                        {
                            primaryConnector = connector;
                        }
                        //Connector information extraction

                        sbAccessories.Append(EndWriter.WriteEP1(element, primaryConnector));

                        XYZ primConOrigin = primaryConnector.Origin;

                        //Analyses the geometry to obtain a point opposite the main connector.
                        //Extraction of the direction of the connector and reversing it
                        reverseConnectorVector = -primaryConnector.CoordinateSystem.BasisZ;
                        Line detectorLine = Line.CreateUnbound(primConOrigin, reverseConnectorVector);
                        //Begin geometry analysis
                        GeometryElement geometryElement = familyInstance.get_Geometry(options);

                        //Prepare resulting point
                        XYZ endPointAnalyzed = null;

                        foreach (GeometryObject geometry in geometryElement)
                        {
                            GeometryInstance instance = geometry as GeometryInstance;
                            if (null == instance)
                            {
                                continue;
                            }
                            foreach (GeometryObject instObj in instance.GetInstanceGeometry())
                            {
                                Solid solid = instObj as Solid;
                                if (null == solid || 0 == solid.Faces.Size || 0 == solid.Edges.Size)
                                {
                                    continue;
                                }
                                foreach (Face face in solid.Faces)
                                {
                                    IntersectionResultArray results = null;
                                    XYZ intersection           = null;
                                    SetComparisonResult result = face.Intersect(detectorLine, out results);
                                    if (result != SetComparisonResult.Overlap)
                                    {
                                        continue;
                                    }
                                    intersection = results.get_Item(0).XYZPoint;
                                    if (intersection.IsAlmostEqualTo(primConOrigin) == false)
                                    {
                                        endPointAnalyzed = intersection;
                                    }
                                }
                            }
                        }

                        sbAccessories.Append(EndWriter.WriteCO(endPointAnalyzed));

                        break;

                    case "SUPPORT":
                        primaryConnector = (from Connector c in connectorSet where c.GetMEPConnectorInfo().IsPrimary select c).FirstOrDefault();
                        sbAccessories.Append(EndWriter.WriteCO(familyInstance, primaryConnector));
                        break;

                    case "INSTRUMENT-3WAY":
                        //Sort connectors to primary, secondary and none
                        primaryConnector = null; secondaryConnector = null; Connector tertiaryConnector = null;

                        foreach (Connector connector in connectorSet)
                        {
                            if (connector.GetMEPConnectorInfo().IsPrimary)
                            {
                                primaryConnector = connector;
                            }
                            if (connector.GetMEPConnectorInfo().IsSecondary)
                            {
                                secondaryConnector = connector;
                            }
                            if ((connector.GetMEPConnectorInfo().IsPrimary == false) && (connector.GetMEPConnectorInfo().IsSecondary == false))
                            {
                                tertiaryConnector = connector;
                            }
                        }

                        //Process endpoints of the component
                        sbAccessories.Append(EndWriter.WriteEP1(element, primaryConnector));
                        sbAccessories.Append(EndWriter.WriteEP2(element, secondaryConnector));
                        sbAccessories.Append(EndWriter.WriteEP3(element, tertiaryConnector));
                        sbAccessories.Append(EndWriter.WriteCP(familyInstance));
                        break;
                    }

                    Composer elemParameterComposer = new Composer();
                    sbAccessories.Append(elemParameterComposer.ElemParameterWriter(element));

                    #region CII export
                    if (InputVars.ExportToCII && !string.Equals(element.get_Parameter(pList.PCF_ELEM_TYPE.Guid).AsString(), "SUPPORT"))
                    {
                        sbAccessories.Append(Composer.CIIWriter(doc, key));
                    }
                    #endregion

                    sbAccessories.Append("    UNIQUE-COMPONENT-IDENTIFIER ");
                    sbAccessories.Append(element.UniqueId);
                    sbAccessories.AppendLine();

                    //Process tap entries of the element if any
                    //Diameter Limit nullifies the tapsWriter output if the tap diameter is less than the limit so it doesn't get exported
                    if (string.IsNullOrEmpty(element.LookupParameter("PCF_ELEM_TAP1").AsString()) == false)
                    {
                        TapsWriter tapsWriter = new TapsWriter(element, "PCF_ELEM_TAP1", doc);
                        sbAccessories.Append(tapsWriter.tapsWriter);
                    }
                    if (string.IsNullOrEmpty(element.LookupParameter("PCF_ELEM_TAP2").AsString()) == false)
                    {
                        TapsWriter tapsWriter = new TapsWriter(element, "PCF_ELEM_TAP2", doc);
                        sbAccessories.Append(tapsWriter.tapsWriter);
                    }
                    if (string.IsNullOrEmpty(element.LookupParameter("PCF_ELEM_TAP3").AsString()) == false)
                    {
                        TapsWriter tapsWriter = new TapsWriter(element, "PCF_ELEM_TAP3", doc);
                        sbAccessories.Append(tapsWriter.tapsWriter);
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception("Element " + element.Id.IntegerValue.ToString() + " caused an exception: " + e.Message);
            }

            //// Clear the output file
            //System.IO.File.WriteAllBytes(InputVars.OutputDirectoryFilePath + "Accessories.pcf", new byte[0]);

            //// Write to output file
            //using (StreamWriter w = File.AppendText(InputVars.OutputDirectoryFilePath + "Accessories.pcf"))
            //{
            //    w.Write(sbAccessories);
            //    w.Close();
            //}
            return(sbAccessories);
        }
Example #50
0
        /// <summary>
        /// Writes a protein database in mzLibProteinDb format, with additional modifications from the AdditionalModsToAddToProteins list.
        /// </summary>
        /// <param name="AdditionalModsToAddToProteins"></param>
        /// <param name="proteinList"></param>
        /// <param name="outputFileName"></param>
        /// <returns>The new "modified residue" entries that are added due to being in the Mods dictionary</returns>
        public static Dictionary <string, int> WriteXmlDatabase(Dictionary <string, HashSet <Tuple <int, Modification> > > AdditionalModsToAddToProteins, List <Protein> proteinList, string outputFileName)
        {
            var xmlWriterSettings = new XmlWriterSettings
            {
                Indent      = true,
                IndentChars = "  "
            };

            Dictionary <string, int> newModResEntries = new Dictionary <string, int>();

            using (XmlWriter writer = XmlWriter.Create(outputFileName, xmlWriterSettings))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("mzLibProteinDb");

                HashSet <Modification> all_relevant_modifications = new HashSet <Modification>(proteinList.SelectMany(p => p.OneBasedPossibleLocalizedModifications.Values.SelectMany(list => list))
                                                                                               .Concat(AdditionalModsToAddToProteins.Where(kv => proteinList.Select(p => p.Accession).Contains(kv.Key)).SelectMany(kv => kv.Value.Select(v => v.Item2))));

                foreach (Modification mod in all_relevant_modifications.OrderBy(m => m.id))
                {
                    writer.WriteStartElement("modification");
                    writer.WriteString(mod.ToString() + Environment.NewLine + "//");
                    writer.WriteEndElement();
                }
                foreach (Protein protein in proteinList)
                {
                    writer.WriteStartElement("entry");
                    writer.WriteStartElement("accession");
                    writer.WriteString(protein.Accession);
                    writer.WriteEndElement();

                    if (protein.Name != null)
                    {
                        writer.WriteStartElement("name");
                        writer.WriteString(protein.Name);
                        writer.WriteEndElement();
                    }

                    if (protein.FullName != null)
                    {
                        writer.WriteStartElement("protein");
                        writer.WriteStartElement("recommendedName");
                        writer.WriteStartElement("fullName");
                        writer.WriteString(protein.FullName);
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                    }

                    writer.WriteStartElement("gene");
                    foreach (var gene_name in protein.GeneNames)
                    {
                        writer.WriteStartElement("name");
                        writer.WriteAttributeString("type", gene_name.Item1);
                        writer.WriteString(gene_name.Item2);
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();

                    foreach (var dbRef in protein.DatabaseReferences)
                    {
                        writer.WriteStartElement("dbReference");
                        writer.WriteAttributeString("type", dbRef.Type);
                        writer.WriteAttributeString("id", dbRef.Id);
                        foreach (Tuple <string, string> property in dbRef.Properties)
                        {
                            writer.WriteStartElement("property");
                            writer.WriteAttributeString("type", property.Item1);
                            writer.WriteAttributeString("value", property.Item2);
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement();
                    }
                    foreach (var proteolysisProduct in protein.ProteolysisProducts)
                    {
                        writer.WriteStartElement("feature");
                        writer.WriteAttributeString("type", proteolysisProduct.Type);
                        writer.WriteStartElement("location");
                        writer.WriteStartElement("begin");
                        writer.WriteAttributeString("position", proteolysisProduct.OneBasedBeginPosition.ToString());
                        writer.WriteEndElement();
                        writer.WriteStartElement("end");
                        writer.WriteAttributeString("position", proteolysisProduct.OneBasedEndPosition.ToString());
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                    }

                    Dictionary <int, HashSet <string> > modsToWriteForThisSpecificProtein = new Dictionary <int, HashSet <string> >();

                    foreach (var ye in protein.OneBasedPossibleLocalizedModifications)
                    {
                        foreach (var nice in ye.Value)
                        {
                            if (modsToWriteForThisSpecificProtein.TryGetValue(ye.Key, out HashSet <string> val))
                            {
                                val.Add(nice.id);
                            }
                            else
                            {
                                modsToWriteForThisSpecificProtein.Add(ye.Key, new HashSet <string> {
                                    nice.id
                                });
                            }
                        }
                    }

                    if (AdditionalModsToAddToProteins.ContainsKey(protein.Accession))
                    {
                        foreach (var ye in AdditionalModsToAddToProteins[protein.Accession])
                        {
                            int    additionalModResidueIndex = ye.Item1;
                            string additionalModId           = ye.Item2.id;
                            bool   modAdded = false;

                            // If we already have modifications that need to be written to the specific residue, get the hash set of those mods
                            if (modsToWriteForThisSpecificProtein.TryGetValue(additionalModResidueIndex, out HashSet <string> val))
                            {
                                // Try to add the new mod to that hash set. If it's not there, modAdded=true, and it is added.
                                modAdded = val.Add(additionalModId);
                            }

                            // Otherwise, no modifications currently need to be written to the residue at residueIndex, so need to create new hash set for that residue
                            else
                            {
                                modsToWriteForThisSpecificProtein.Add(additionalModResidueIndex, new HashSet <string> {
                                    additionalModId
                                });
                                modAdded = true;
                            }

                            // Finally, if a new modification has in fact been deemed worthy of being added to the database, mark that in the output dictionary
                            if (modAdded)
                            {
                                if (newModResEntries.ContainsKey(additionalModId))
                                {
                                    newModResEntries[additionalModId]++;
                                }
                                else
                                {
                                    newModResEntries.Add(additionalModId, 1);
                                }
                            }
                        }
                    }

                    foreach (var hm in modsToWriteForThisSpecificProtein.OrderBy(b => b.Key))
                    {
                        foreach (var modId in hm.Value)
                        {
                            writer.WriteStartElement("feature");
                            writer.WriteAttributeString("type", "modified residue");
                            writer.WriteAttributeString("description", modId);
                            writer.WriteStartElement("location");
                            writer.WriteStartElement("position");
                            writer.WriteAttributeString("position", hm.Key.ToString(CultureInfo.InvariantCulture));
                            writer.WriteEndElement();
                            writer.WriteEndElement();
                            writer.WriteEndElement();
                        }
                    }

                    foreach (var hm in protein.SequenceVariations)
                    {
                        writer.WriteStartElement("feature");
                        writer.WriteAttributeString("type", "sequence variant");
                        writer.WriteAttributeString("description", hm.Description);
                        writer.WriteStartElement("original");
                        writer.WriteString(hm.OriginalSequence);
                        writer.WriteEndElement(); // original
                        writer.WriteStartElement("variation");
                        writer.WriteString(hm.VariantSequence);
                        writer.WriteEndElement(); // variation
                        writer.WriteStartElement("location");
                        if (hm.OneBasedBeginPosition == hm.OneBasedEndPosition)
                        {
                            writer.WriteStartElement("position");
                            writer.WriteAttributeString("position", hm.OneBasedBeginPosition.ToString());
                            writer.WriteEndElement();
                        }
                        else
                        {
                            writer.WriteStartElement("begin");
                            writer.WriteAttributeString("position", hm.OneBasedBeginPosition.ToString());
                            writer.WriteEndElement();
                            writer.WriteStartElement("end");
                            writer.WriteAttributeString("position", hm.OneBasedEndPosition.ToString());
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement(); // location
                        writer.WriteEndElement(); // feature
                    }

                    foreach (var hm in protein.DisulfideBonds)
                    {
                        writer.WriteStartElement("feature");
                        writer.WriteAttributeString("type", "disulfide bond");
                        writer.WriteAttributeString("description", hm.Description);
                        writer.WriteStartElement("location");
                        if (hm.OneBasedBeginPosition == hm.OneBasedEndPosition)
                        {
                            writer.WriteStartElement("position");
                            writer.WriteAttributeString("position", hm.OneBasedBeginPosition.ToString());
                            writer.WriteEndElement();
                        }
                        else
                        {
                            writer.WriteStartElement("begin");
                            writer.WriteAttributeString("position", hm.OneBasedBeginPosition.ToString());
                            writer.WriteEndElement();
                            writer.WriteStartElement("end");
                            writer.WriteAttributeString("position", hm.OneBasedEndPosition.ToString());
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement(); // location
                        writer.WriteEndElement(); // feature
                    }

                    writer.WriteStartElement("sequence");
                    writer.WriteAttributeString("length", protein.Length.ToString(CultureInfo.InvariantCulture));
                    writer.WriteString(protein.BaseSequence);
                    writer.WriteEndElement(); // sequence
                    writer.WriteEndElement(); // entry
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
            return(newModResEntries);
        }
Example #51
0
        private void ProcessAdvancedFactorItems(Component leaf, List <FactorItem> factorItems, bool folderlevel, string simulationPath)
        {
            List <string> variableTypes = new List <string>();

            LoadVariableTypes(Types.Instance.MetaDataNode("Factor", "FactorVariables"), variableTypes);

            //add any childnodes that are factors
            var result = (from c in leaf.ChildNodes
                          where c.Type == "factor" && c.ContentsAsXML.SelectSingleNode("targets") != null
                          select c);

            foreach (var factor in result)
            {
                List <string> targets = new List <string>();
                string        spath   = simulationPath + "/";
                foreach (XmlNode node in factor.ContentsAsXML.SelectSingleNode("//targets").ChildNodes)
                {
                    if (node.InnerText.Contains(spath))
                    {
                        targets.Add(node.InnerText);
                    }
                }
                if (targets.Count > 0)
                {
                    //manager factor or normal
                    if (factor.ChildNodes.Count == 1 && variableTypes.Contains(factor.ChildNodes[0].Type.ToLower()))
                    {
                        XmlNodeList varNodes = factor.ContentsAsXML.SelectNodes("//vars/*");
                        foreach (XmlNode node in varNodes)
                        {
                            ManagerFactorItem item = new ManagerFactorItem(this);
                            item.Targets         = targets;
                            item.FactorComponent = factor;
                            item.Variable        = node;
                            string[] pars        = node.InnerText.Split(new char[] { ',' });
                            var      unique_pars = new HashSet <string>(pars.Select(x => x.Trim(new char[] { '\"', ' ' })));
                            item.Parameters = unique_pars.OrderBy(a => a).ToList <string>();
                            if ((from f in factorItems
                                 where f.getDesc() == item.getDesc()
                                 select f).Count() == 0)
                            {
                                if (factorItems.Count > 0)
                                {
                                    item.NextItem = factorItems[0];
                                }
                                factorItems.Insert(0, item);
                            }
                        }
                    }
                    else
                    {
                        FactorItem item = new FactorItem(this);
                        item.Targets         = targets;
                        item.FactorComponent = factor;
                        if ((from f in factorItems
                             where f.getDesc() == item.getDesc()
                             select f).Count() == 0)
                        {
                            if (factorItems.Count > 0)
                            {
                                item.NextItem = factorItems[0];
                            }
                            factorItems.Insert(0, item);
                        }
                    }
                }
            }
            if (leaf.Parent != null && leaf.Parent.Parent != null)
            {//PArent.Parent is to check against the root node
                if (leaf.Parent.Type == "folder" && folderlevel)
                {
                    //parent is a factorfolder
                    FactorItem item = new FactorItem(this);
                    //item.Targets = targets;
                    item.FactorComponent = leaf.Parent;
                    item.FolderLevel     = leaf.Name;
                    if ((from f in factorItems
                         where f.getDesc() == item.getDesc()
                         select f).Count() == 0)
                    {
                        if (factorItems.Count > 0)
                        {
                            item.NextItem = factorItems[0];
                        }
                        factorItems.Insert(0, item);
                    }
                }
                ProcessAdvancedFactorItems(leaf.Parent, factorItems, !folderlevel, simulationPath);
            }
        }
Example #52
0
        public static void VerifyMarkup(
            string markdown,
            string html,
            string[] errors       = null,
            string[] dependencies = null,
            bool lineNumber       = false,
            string filePath       = "test.md",
            Dictionary <string, string> tokens = null,
            Dictionary <string, string> files  = null,
            Action <MarkdownObject> verifyAST  = null)
        {
            errors = errors ?? Array.Empty <string>();
            tokens = tokens ?? new Dictionary <string, string>();
            files  = files ?? new Dictionary <string, string>();

            var actualErrors       = new List <string>();
            var actualDependencies = new HashSet <string>();

            var markdownContext = new MarkdownContext(
                getToken: key => tokens.TryGetValue(key, out var value) ? value : null,
                logInfo: (a, b, c, d) => { },
                logSuggestion: Log("suggestion"),
                logWarning: Log("warning"),
                logError: Log("error"),
                readFile: ReadFile);

            var pipelineBuilder = new MarkdownPipelineBuilder()
                                  .UseDocfxExtensions(markdownContext)
                                  .UseYamlFrontMatter();

            if (lineNumber)
            {
                pipelineBuilder.UseLineNumber();
            }

            var pipeline = pipelineBuilder.Build();

            using (InclusionContext.PushFile(filePath))
            {
                var actualHtml = Markdown.ToHtml(markdown, pipeline);

                if (html != null)
                {
                    Assert.Equal(
                        html.Replace("\r", "").Replace("\n", ""),
                        actualHtml.Replace("\r", "").Replace("\n", ""));
                }

                Assert.Equal(errors.OrderBy(_ => _), actualErrors.OrderBy(_ => _));

                if (dependencies != null)
                {
                    Assert.Equal(dependencies.OrderBy(_ => _), actualDependencies.OrderBy(_ => _));
                }
            }

            MarkdownContext.LogActionDelegate Log(string level)
            {
                return((code, message, origin, line) => actualErrors.Add(code));
            }

            (string content, object file) ReadFile(string path, object relativeTo, MarkdownObject origin)
            {
                var key = Path.Combine(Path.GetDirectoryName(relativeTo.ToString()), path).Replace('\\', '/');

                if (path.StartsWith("~/"))
                {
                    path = path.Substring(2);
                    key  = path;
                }

                actualDependencies.Add(path);
                return(files.TryGetValue(key, out var value) ? (value, key) : default);
Example #53
0
    public static PathInfo GetShortestPath(Unit unit, PathSquare start, PathSquare end)
    {
        HashSet <PathSquare> closedSet = new HashSet <PathSquare>();
        HashSet <PathSquare> openSet   = new HashSet <PathSquare>();

        PathSquare closestSquare   = null;
        double     closestDistance = 9999;

        openSet.Add(start);

        ResetPathSquare();

        start.gScore = 0;
        start.fScore = start.Distance(end);

        double bestRouteDist = start.Distance(end);

        while (openSet.Count > 0)
        {
            var current = openSet.OrderBy(n => n.fScore).FirstOrDefault();

            if (current == end)
            {
                return(PathInfo.GenerateWaypoints(start, current));
            }

            openSet.Remove(current);
            closedSet.Add(current);

            foreach (var pair in current.neighbours)
            {
                var neighbourInfo = pair.Value;
                var neighbour     = neighbourInfo.neighbour;
                var distance      = neighbourInfo.distance;


                if (closedSet.Contains(neighbour))
                {
                    continue;
                }

                if (!CanWalkToSquare(unit, neighbourInfo))
                {
                    continue;
                }

                var alternativeDistance = current.gScore + distance;

                /*if(alternativeDistance > bestRouteDist * 2)
                 * {
                 *  continue; //stop searching for route that's longer than 2x the optimal path
                 * }*/

                if (!openSet.Contains(neighbour))
                {
                    openSet.Add(neighbour);
                }
                else if (alternativeDistance >= neighbour.gScore)
                {
                    continue;
                }

                var estimatedDistance = neighbour.Distance(end);

                neighbour.parent = current;
                neighbour.gScore = alternativeDistance;
                neighbour.fScore = alternativeDistance + estimatedDistance;

                if (closestDistance > estimatedDistance)
                {
                    closestSquare   = neighbour;
                    closestDistance = estimatedDistance;
                }
            }
        }

        if (closestSquare == null)
        {
            return(null);
        }

        if (closestSquare.Distance(end) < start.Distance(end))
        {
            var path = PathInfo.GenerateWaypoints(start, closestSquare);
            path.reachable = false;

            return(path);
        }
        else
        {
            return(null);
        }
    }
Example #54
0
 private IEnumerable <string> GetFoundWords()
 {
     // Not horribly performant but only called once on exit to alphabetically order the found words
     return(m_foundWords.OrderBy(x => x));
 }
Example #55
0
        public void Save(IEnumerable <string> removeMasters)
        {
            Log.Info("Saving plugin " + fileName);

            byte thisPluginNumber = context.Plugins.GetPluginNumber(this);

            // Collect all masters (Always add the main plugin as master)
            HashSet <byte> collectedMasters = new HashSet <byte>()
            {
                0
            };

            // Collect all referenced form IDs
            HashSet <uint> referencedFormIds = GetReferencedFormIds();

            foreach (var id in referencedFormIds)
            {
                if (!context.Forms.Contains(id))
                {
                    //Log.Warning("Unable to determine the master of unresolved reference [0x{0:X8}].", id);
                    // Skip unresolved references, a warning will be issued while writing

                    // Handle unresolved references as best as possible, derive plugin number from formId and add it as a master
                    byte assumedPluginNumber = (byte)(id >> 24);
                    if (assumedPluginNumber != thisPluginNumber)
                    {
                        if (!collectedMasters.Contains(assumedPluginNumber))
                        {
                            collectedMasters.Add(assumedPluginNumber);
                        }
                    }

                    Log.Warning("Assumed unresolved form {0:X8} plugin {1}.", id, context.Plugins[assumedPluginNumber].FileName);
                }
                else
                {
                    var form = context.Forms[id];

                    // Find the original form
                    // to add the original plugin which adds it as the master and not the last plugin which edits the referenced form
                    while (form.OverridesForm != null)
                    {
                        form = form.OverridesForm;
                    }

                    // Add if not of the current plugin
                    if (form.PluginNumber != thisPluginNumber)
                    {
                        if (!collectedMasters.Contains(form.PluginNumber))
                        {
                            collectedMasters.Add(form.PluginNumber);
                        }
                    }
                }
            }

            // Form IDs this plugin is overriding
            var overridenForms = Forms.Where(f => f.IsOverriding);

            foreach (var form in overridenForms)
            {
                // Go through all overriden forms until the original form
                var overridenForm = form.OverridesForm;
                while (overridenForm != null)
                {
                    if (!collectedMasters.Contains(overridenForm.PluginNumber))
                    {
                        collectedMasters.Add(overridenForm.PluginNumber);
                    }

                    // Next overriden form by this form
                    overridenForm = overridenForm.OverridesForm;
                }
            }

            // Add masters (will be sorted by pluginNumber)
            foreach (var number in collectedMasters.OrderBy(i => i))
            {
                var masterFileName = context.Plugins[number].FileName;

                // Force remove masters
                if (removeMasters != null && removeMasters.Contains(masterFileName))
                {
                    continue;
                }

                // Already added (when appending)
                if (header.GetMasterFiles().Contains(masterFileName))
                {
                    continue;
                }

                header.AddMasterFile(masterFileName);
                Log.Fine("Added master: {0}", masterFileName);
            }

            //// Make a backup of existing file
            //string backupPath = null;
            //if (File.Exists(path))
            //{
            //    backupPath = path + "-" + (ulong)DateTime.Now.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
            //    File.Move(path, backupPath);
            //}

            if (!Forms.Any())
            {
                Log.Warning("No forms to write. Empty plugin will be generated.");
            }

            int  count = 0;
            long total = Forms.Count();

            using (var progress = Display.StartProgress("Saving plugin"))
            {
                // Save plugin to memory stream
                using (var stream = new MemoryStream())
                {
                    using (var writer = context.CreateWriter(stream))
                    {
                        // Prepare reference mapper
                        writer.ReferenceMapper = new PluginReferenceMapper(this);

                        // Write header
                        header.PluginVersion = context.GetLatestPluginVersion();
                        writer.WriteHeader(header);
                        Log.Fine("Written header record");

                        // Write forms by type
                        foreach (var type in context.Forms.GetFormKinds())
                        {
                            var formOfType = Forms.Where(f => f.FormKind == type);
                            if (formOfType.Any())
                            {
                                Log.Fine("Writting {0}", type);
                            }

                            foreach (var form in formOfType)
                            {
                                writer.WriteRecord(form.Record, form.FormId);
                                count++;

                                progress.Update(count, total, "{0}:{1}", FileName, type);
                            }
                        }

                        Log.Fine("Written {0} form(s)", count);

                        writer.Close();

                        // Write memory stream to file
                        // only if changed
                        stream.Position = 0;
                        var file = context.DataFileProvider.GetDataFile(FileMode.Create, fileName);
                        if (!file.CopyFrom(stream, true))
                        {
                            Log.Info("New plugin content is the same as that of the existing plugin.");
                        }
                    }
                }
            }

            Log.Info("Plugin saved");
        }
Example #56
0
        /// <summary>
        /// Executes the specified pipelines and pipelines with <see cref="ExecutionPolicy.Always"/> policies.
        /// </summary>
        /// <param name="pipelines">
        /// The pipelines to execute or <c>null</c>/empty to only execute pipelines with the <see cref="ExecutionPolicy.Always"/> policy.
        /// </param>
        /// <param name="defaultPipelines">
        /// <c>true</c> to run the default pipelines in addition to the pipelines specified
        /// or <c>false</c> to only run the specified pipelines.
        /// </param>
        /// <param name="cancellationTokenSource">
        /// A cancellation token source that can be used to cancel the execution.
        /// </param>
        /// <returns>The output documents from each executed pipeline.</returns>
        public async Task <IPipelineOutputs> ExecuteAsync(string[] pipelines, bool defaultPipelines, CancellationTokenSource cancellationTokenSource)
        {
            // Setup
            await default(SynchronizationContextRemover);
            CheckDisposed();
            Guid executionId = Guid.NewGuid();
            ConcurrentDictionary <string, PhaseResult[]> phaseResults =
                new ConcurrentDictionary <string, PhaseResult[]>(StringComparer.OrdinalIgnoreCase);
            PipelineOutputs outputs = new PipelineOutputs(phaseResults);

            // Create the pipeline phases (this also validates the pipeline graph)
            // Also add the service-based pipelines as late as possible so other services have been configured
            if (_phases == null)
            {
                AddServicePipelines();
                _phases = GetPipelinePhases(_pipelines, _logger);
            }

            // Verify pipelines
            HashSet <string> executingPipelines = GetExecutingPipelines(pipelines, defaultPipelines);

            if (executingPipelines.Count == 0)
            {
                _logger.LogWarning("No pipelines are configured or specified for execution.");
                return(outputs);
            }

            // Log
            _logger.LogInformation($"Executing {executingPipelines.Count} pipelines ({string.Join(", ", executingPipelines.OrderBy(x => x))})");
            _logger.LogDebug($"Execution ID {executionId}");
            System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();

            // Raise before event
            await Events.RaiseAsync(new BeforeEngineExecution(this, executionId));

            // Do a check for the same input/output path
            if (FileSystem.InputPaths.Any(x => x.Equals(FileSystem.OutputPath)))
            {
                _logger.LogWarning("The output path is also one of the input paths which can cause unexpected behavior and is usually not advised");
            }

            // Clean paths
            CleanTempPath();
            if (Settings.GetBool(Keys.CleanOutputPath))
            {
                CleanOutputPath();
            }

            // Get phase tasks
            Task[] phaseTasks = null;
            try
            {
                // Get and execute all phases
                phaseTasks = GetPhaseTasks(executionId, executingPipelines, phaseResults, cancellationTokenSource);
                await Task.WhenAll(phaseTasks);
            }
            catch (Exception ex)
            {
                if (!(ex is OperationCanceledException))
                {
                    _logger.LogCritical("Error during execution");
                }
                throw;
            }
            finally
            {
                stopwatch.Stop();
            }

            // Raise after event
            await Events.RaiseAsync(new AfterEngineExecution(this, executionId, outputs, stopwatch.ElapsedMilliseconds));

            // Log execution summary table
            _logger.LogInformation(
                "Execution summary: (number of output documents per pipeline and phase)"
                + Environment.NewLine
                + Environment.NewLine
                + phaseResults
                .OrderBy(x => x.Key)
                .ToStringTable(
                    new[]
            {
                "Pipeline",
                nameof(Phase.Input),
                nameof(Phase.Process),
                nameof(Phase.Transform),
                nameof(Phase.Output),
                "Total Time"
            },
                    x => x.Key,
                    x => GetPhaseResultTableString(x.Value[(int)Phase.Input]),
                    x => GetPhaseResultTableString(x.Value[(int)Phase.Process]),
                    x => GetPhaseResultTableString(x.Value[(int)Phase.Transform]),
                    x => GetPhaseResultTableString(x.Value[(int)Phase.Output]),
                    x =>
                    ((x.Value[(int)Phase.Input]?.ElapsedMilliseconds ?? 0)
                     + (x.Value[(int)Phase.Process]?.ElapsedMilliseconds ?? 0)
                     + (x.Value[(int)Phase.Transform]?.ElapsedMilliseconds ?? 0)
                     + (x.Value[(int)Phase.Output]?.ElapsedMilliseconds ?? 0)).ToString()
                    + " ms"));
    public static Stack <Node> GetPath(Point start, Point goal)
    {
        if (nodes == null)
        {
            CreateNodes();
        }

        HashSet <Node> openList = new HashSet <Node>();

        HashSet <Node> closedList = new HashSet <Node>();

        Stack <Node> finalPath   = new Stack <Node>();
        Node         currentNode = nodes[start];

        openList.Add(currentNode);

        while (openList.Count > 0)
        {
            for (int x = -1; x <= 1; x++)
            {
                for (int y = -1; y <= 1; y++)
                {
                    Point neighbourPos = new Point(currentNode.GridPosition.X - x, currentNode.GridPosition.Y - y);

                    if (LevelManager.Instance.InBounds(neighbourPos) && LevelManager.Instance.Tiles[neighbourPos].CanBeMovedThrough() && neighbourPos != currentNode.GridPosition)
                    {
                        int gCost = 0;
                        if (Math.Abs(x - y) == 1)
                        {
                            gCost = 10;
                        }
                        else
                        {
                            if (!ConnectedDiagonally(currentNode, nodes[neighbourPos]))
                            {
                                continue;
                            }
                            gCost = 14;
                        }

                        Node neighbour = nodes[neighbourPos];



                        if (openList.Contains(neighbour))
                        {
                            if (currentNode.G + gCost < neighbour.G)
                            {
                                neighbour.CalcValues(currentNode, nodes[goal], gCost);
                            }
                        }

                        else if (!closedList.Contains(neighbour))
                        {
                            openList.Add(neighbour);
                            neighbour.CalcValues(currentNode, nodes[goal], gCost);
                        }
                    }
                }
            }

            openList.Remove(currentNode);
            closedList.Add(currentNode);

            if (openList.Count > 0)
            {
                // Sort the list by F values, then select the first from the list
                currentNode = openList.OrderBy(n => n.F).First();
            }

            if (currentNode == nodes[goal])
            {
                while (currentNode.GridPosition != start)
                {
                    finalPath.Push(currentNode);
                    currentNode = currentNode.Parent;
                }
                break;
            }
        }

        return(finalPath);

        //**** THIS IS FOR DEBUGGING ONLY, REMOVE LATER

        //GameObject.Find("AStarDebugger").GetComponent<AStarDebugger>().DebugPath(openList, closedList, finalPath);
    }
Example #58
0
        /// <summary>
        /// Create an error message to describe the primary issue in an invalid solution.
        /// </summary>
        /// <param name="solution">A partial solution from the resolver</param>
        /// <param name="availablePackages">all packages that were available for the solution</param>
        /// <param name="packagesConfig">packages already installed in the project</param>
        /// <param name="newPackageIds">new packages that are not already installed</param>
        /// <returns>A user friendly diagonstic message</returns>
        public static string GetDiagnosticMessage(IEnumerable <ResolverPackage> solution,
                                                  IEnumerable <PackageDependencyInfo> availablePackages,
                                                  IEnumerable <PackageReference> packagesConfig,
                                                  IEnumerable <string> newPackageIds)
        {
            // remove empty and absent packages, absent packages cannot have error messages
            solution = solution.Where(package => package != null && !package.Absent);

            var allPackageIds       = new HashSet <string>(solution.Select(package => package.Id), StringComparer.OrdinalIgnoreCase);
            var newPackageIdSet     = new HashSet <string>(newPackageIds, StringComparer.OrdinalIgnoreCase);
            var installedPackageIds = new HashSet <string>(packagesConfig.Select(package => package.PackageIdentity.Id), StringComparer.OrdinalIgnoreCase);

            var requiredPackageIds = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            requiredPackageIds.UnionWith(newPackageIdSet);
            requiredPackageIds.UnionWith(installedPackageIds);
            var requiredPackages = solution.Where(package => requiredPackageIds.Contains(package.Id)).ToList();

            // all new packages that are not already installed, and that aren't the primary target
            var newDependencyPackageIds = new HashSet <string>(allPackageIds.Except(requiredPackageIds), StringComparer.OrdinalIgnoreCase);

            // 1. find cases where the target package does not satisfy the dependency constraints
            foreach (var targetId in newPackageIdSet.OrderBy(id => id, StringComparer.OrdinalIgnoreCase))
            {
                var brokenPackage = GetPackagesWithBrokenDependenciesOnId(targetId, requiredPackages)
                                    .OrderBy(package => package.Id, StringComparer.OrdinalIgnoreCase)
                                    .FirstOrDefault();

                if (brokenPackage != null)
                {
                    return(GetErrorMessage(targetId, solution, availablePackages, packagesConfig));
                }
            }

            // 2. find cases where the target package is missing dependencies
            foreach (var targetPackage in solution.Where(package => newPackageIdSet.Contains(package.Id))
                     .OrderBy(package => package.Id, StringComparer.OrdinalIgnoreCase))
            {
                var brokenDependency = GetBrokenDependencies(targetPackage, solution)
                                       .OrderBy(package => package.Id, StringComparer.OrdinalIgnoreCase)
                                       .FirstOrDefault();

                if (brokenDependency != null)
                {
                    return(GetErrorMessage(brokenDependency.Id, solution, availablePackages, packagesConfig));
                }
            }

            // 3. find cases where an already installed package is missing a dependency
            // this may happen if an installed package was upgraded by the resolver
            foreach (var targetPackage in solution.Where(package => installedPackageIds.Contains(package.Id))
                     .OrderBy(package => package.Id, StringComparer.OrdinalIgnoreCase))
            {
                var brokenDependency = GetBrokenDependencies(targetPackage, solution)
                                       .OrderBy(package => package.Id, StringComparer.OrdinalIgnoreCase)
                                       .FirstOrDefault();

                if (brokenDependency != null)
                {
                    return(GetErrorMessage(brokenDependency.Id, solution, availablePackages, packagesConfig));
                }
            }

            // 4. find cases where a new dependency has a missing dependency
            // to get the most useful error here, sort the packages by their distance from a required package
            foreach (var targetPackage in solution.Where(package => newDependencyPackageIds.Contains(package.Id))
                     .OrderBy(package => GetLowestDistanceFromTarget(package.Id, requiredPackageIds, solution))
                     .ThenBy(package => package.Id, StringComparer.OrdinalIgnoreCase))
            {
                var brokenDependency = GetBrokenDependencies(targetPackage, solution)
                                       .OrderBy(package => package.Id, StringComparer.OrdinalIgnoreCase)
                                       .FirstOrDefault();

                if (brokenDependency != null)
                {
                    return(GetErrorMessage(brokenDependency.Id, solution, availablePackages, packagesConfig));
                }
            }

            // this should only get hit if the inputs are invalid, or the solution has no problems
            return(Strings.NoSolution);
        }
Example #59
0
        public override bool Verify()
        {
            if (!Blockchain.Default.Ability.HasFlag(BlockchainAbility.TransactionIndexes) || !Blockchain.Default.Ability.HasFlag(BlockchainAbility.UnspentIndexes))
            {
                return(false);
            }
            if (PrevHash != Blockchain.Default.CurrentBlockHash)
            {
                return(false);
            }
            HashSet <ECPoint> miners = new HashSet <ECPoint>(Blockchain.Default.GetMiners());

            if (!miners.Contains(Miner))
            {
                return(false);
            }
            if (NoncePieces.Count != miners.Count - 1)
            {
                return(false);
            }
            if (!NoncePieces.Keys.Concat(new[] { Miner }).OrderBy(p => p).SequenceEqual(miners.OrderBy(p => p)))
            {
                return(false);
            }
            return(this.VerifySignature());
        }
Example #60
0
 private static void WriteSet(string caption, HashSet <TreeNode> set, TextWriter sb)
 {
     sb.Write(caption);
     sb.WriteLine(string.Join(",", set.OrderBy(n => n.Number).Select(n => n.Number.ToString())));
 }