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
0
        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
        /// <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 #5
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));
                    }
                }
            }
        }
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);
            }
        }
Example #7
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);
        }
Example #8
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();
            }
        }
        /// <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;
        }
    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);
    }
        /// <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));
     }
 }
 /// <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;
 }
 protected void WriteClaimSignatureSet( HashSet<string> claimSignatures)
 {
     Debug.WriteLine("Claim Signatures: ");
     foreach (var claimSignature in claimSignatures.OrderBy(n => n))
     {
         Debug.WriteLine("\t" + claimSignature);
     }
 }
        /// <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();
        }
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);
        }
 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 #21
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;
        }
        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 #23
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} ));
        }
Example #24
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 #25
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 #26
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 #27
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 #29
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);
 }