Example #1
0
        private static double FindMinimalCost(HashSet<ISet<int>> allTrees)
        {
            // Kruskal -> Sorting edges by their weight
            Array.Sort(paths, (a, b) => a.Item3.CompareTo(b.Item3));

            double result = 0;

            foreach (var path in paths)
            {
                var tree1 = allTrees.Where(tree => tree.Contains(path.Item1)).First();
                var tree2 = allTrees.Where(tree => tree.Contains(path.Item2)).First();

                // Elements are in same tree
                if (tree1.Equals(tree2)) continue;

                result += path.Item3;

                tree1.UnionWith(tree2);
                allTrees.Remove(tree2);

                // Small optimization
                if (allTrees.Count == 1) break;
            }

            return result;
        }
Example #2
0
 public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
 {
     object actionName, subactionName;
     var hasActionName = controllerContext.RouteData.Values.TryGetValue("action", out actionName);
     var hasSubActionName = controllerContext.RouteData.Values.TryGetValue("subaction", out subactionName);
     var method = controllerContext.Request.Method;
     var allMethods =
         controllerContext.ControllerDescriptor.ControllerType.GetMethods(
             BindingFlags.Instance | BindingFlags.Public);
     var validMethods = Array.FindAll(allMethods, IsValidActionMethod);
     var actionDescriptors = new HashSet<ReflectedHttpActionDescriptor>();
     foreach (
         var actionDescriptor in
             validMethods.Select(m => new ReflectedHttpActionDescriptor(controllerContext.ControllerDescriptor, m)))
     {
         actionDescriptors.Add(actionDescriptor);
         this.actionParams.Add(
             actionDescriptor,
             actionDescriptor.ActionBinding.ParameterBindings.Where(
                 b => !b.Descriptor.IsOptional && b.Descriptor.ParameterType.UnderlyingSystemType.IsPrimitive)
                             .Select(b => b.Descriptor.Prefix ?? b.Descriptor.ParameterName)
                             .ToArray());
     }
     IEnumerable<ReflectedHttpActionDescriptor> actionsFoundSoFar;
     if (hasSubActionName)
     {
         actionsFoundSoFar =
             actionDescriptors.Where(
                 i =>
                 i.ActionName.ToLowerInvariant() == subactionName.ToString().ToLowerInvariant()
                 && i.SupportedHttpMethods.Contains(method)).ToArray();
     }
     else if (hasActionName)
     {
         actionsFoundSoFar =
             actionDescriptors.Where(
                 i =>
                 i.ActionName.ToLowerInvariant() == actionName.ToString().ToLowerInvariant()
                 && i.SupportedHttpMethods.Contains(method)).ToArray();
     }
     else
     {
         actionsFoundSoFar =
             actionDescriptors.Where(
                 i =>
                 i.ActionName.ToLowerInvariant().Contains(method.ToString().ToLowerInvariant())
                 && i.SupportedHttpMethods.Contains(method)).ToArray();
     }
     var actionsFound = FindActionUsingRouteAndQueryParameters(controllerContext, actionsFoundSoFar);
     if (actionsFound == null || !actionsFound.Any())
         throw new HttpResponseException(
             controllerContext.Request.CreateErrorResponse(HttpStatusCode.NotFound, "Cannot find a matching action."));
     if (actionsFound.Count() > 1)
         throw new HttpResponseException(
             controllerContext.Request.CreateErrorResponse(HttpStatusCode.Ambiguous, "Multiple matches found."));
     return actionsFound.FirstOrDefault();
 }
        public void ArrangeGameObjects(string[] warriorCharacters)
        {
            InitGrid();

            Warrior[] warriors = GetWarriors(warriorCharacters);
            _warriorSquares = new Square<Warrior>[warriors.Length];

            HashSet<Square<GameObject>> squaresTried = new HashSet<Square<GameObject>>();
            Square<GameObject> squareToTry;
            for (int i = 0; i < warriors.Length; i++)
            {
                do
                {
                    squareToTry = _grid[
                        _randomGenerator.Next(0, GridSize),
                        _randomGenerator.Next(0, GridSize)];
                } while (
                    squaresTried.Contains(squareToTry) ||
                    IsWithin(2, squareToTry, squaresTried.Where(s => s.GameObject is Warrior)));

                squareToTry.GameObject = warriors[i];
                _warriorSquares[i] = new Square<Warrior>(squareToTry.Row, squareToTry.Col, warriors[i]);
                squaresTried.Add(squareToTry);
            }

            for (int i = 0; i < ApplesCount; i++)
            {
                do
                {
                    squareToTry = _grid[
                        _randomGenerator.Next(0, GridSize),
                        _randomGenerator.Next(0, GridSize)];
                } while (
                    squaresTried.Contains(squareToTry) ||
                    IsWithin(1, squareToTry, squaresTried.Where(s => s.GameObject is Fruit)));

                squareToTry.GameObject = new Apple();
                squaresTried.Add(squareToTry);
            }

            for (int i = 0; i < PearsCount; i++)
            {
                do
                {
                    squareToTry = _grid[
                        _randomGenerator.Next(0, GridSize),
                        _randomGenerator.Next(0, GridSize)];
                } while (
                    squaresTried.Contains(squareToTry) ||
                    IsWithin(1, squareToTry, squaresTried.Where(s => s.GameObject is Fruit)));

                squareToTry.GameObject = new Pear();
                squaresTried.Add(squareToTry);
            }
        }
Example #4
0
        /// <summary>
        /// Creates a <see cref="RoutingTablesAdaptersList"/>
        /// </summary>
        /// <param name="previousAdapterList">A complete list of all the adapters that existed before.</param>
        /// <param name="currentAdapterList">A complete list of all the adapters that exist now</param>
        public RoutingTablesAdaptersList(HashSet<IAdapter> previousAdapterList, HashSet<IAdapter> currentAdapterList)
        {
            NewAdapter = new List<IAdapter>();
            ExistingAdapter = new List<IAdapter>();
            OldAdapter = new List<IAdapter>();
            NewAndExistingAdapters = new List<IAdapter>();

            NewAndExistingAdapters.AddRange(currentAdapterList);
            NewAdapter.AddRange(currentAdapterList.Where(x => !previousAdapterList.Contains(x)));
            OldAdapter.AddRange(previousAdapterList.Where(x => !currentAdapterList.Contains(x)));
            ExistingAdapter.AddRange(currentAdapterList.Where(x => previousAdapterList.Contains(x)));
        }
    static void Main()
    {
        int N = int.Parse(Console.ReadLine());
        var edges = new Tuple<int, int, int>[N];
        var nodes = new HashSet<int>();

        for (int i = 0; i < N; i++)
        {
            var input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

            edges[i] = new Tuple<int, int, int>(input[0], input[1], input[2]);
            nodes.Add(input[0]);
            nodes.Add(input[1]);
        }

        var allTrees = new HashSet<HashSet<int>>();

        // Represend each node as tree
        foreach (var node in nodes)
        {
            var tree = new HashSet<int>();
            tree.Add(node);

            allTrees.Add(tree);
        }

        // Sorting edges by their weight
        Array.Sort(edges, (a, b) => a.Item3.CompareTo(b.Item3));

        double result = 0;

        foreach (var edge in edges)
        {
            var tree1 = allTrees.Where(tree => tree.Contains(edge.Item1)).First();
            var tree2 = allTrees.Where(tree => tree.Contains(edge.Item2)).First();

            // Elements are in same tree
            if (tree1.Equals(tree2)) continue;

            result += edge.Item3;

            tree1.UnionWith(tree2);
            allTrees.Remove(tree2);

            // Small optimization
            if (allTrees.Count == 1) break;
        }

        Console.WriteLine(result);
    }
        public void CaseInsensitiveComparison()
        {
            List<GitInstallation> list = new List<GitInstallation>
            {
                new GitInstallation(@"C:\Program Files (x86)\Git", KnownGitDistribution.GitForWindows32v1),
                new GitInstallation(@"C:\Program Files (x86)\Git", KnownGitDistribution.GitForWindows32v2),
                new GitInstallation(@"C:\Program Files\Git", KnownGitDistribution.GitForWindows32v1),
                new GitInstallation(@"C:\Program Files\Git", KnownGitDistribution.GitForWindows32v2),
                new GitInstallation(@"C:\Program Files\Git", KnownGitDistribution.GitForWindows64v2),
                // ToLower versions
                new GitInstallation(@"C:\Program Files (x86)\Git".ToLower(), KnownGitDistribution.GitForWindows32v1),
                new GitInstallation(@"C:\Program Files (x86)\Git".ToLower(), KnownGitDistribution.GitForWindows32v2),
                new GitInstallation(@"C:\Program Files\Git".ToLower(), KnownGitDistribution.GitForWindows32v1),
                new GitInstallation(@"C:\Program Files\Git".ToLower(), KnownGitDistribution.GitForWindows32v2),
                new GitInstallation(@"C:\Program Files\Git".ToLower(), KnownGitDistribution.GitForWindows64v2),
                // ToUpper versions
                new GitInstallation(@"C:\Program Files (x86)\Git".ToUpper(), KnownGitDistribution.GitForWindows32v1),
                new GitInstallation(@"C:\Program Files (x86)\Git".ToUpper(), KnownGitDistribution.GitForWindows32v2),
                new GitInstallation(@"C:\Program Files\Git".ToUpper(), KnownGitDistribution.GitForWindows32v1),
                new GitInstallation(@"C:\Program Files\Git".ToUpper(), KnownGitDistribution.GitForWindows32v2),
                new GitInstallation(@"C:\Program Files\Git".ToUpper(), KnownGitDistribution.GitForWindows64v2),
            };

            HashSet<GitInstallation> set = new HashSet<GitInstallation>(list);

            Assert.AreEqual(15, list.Count);
            Assert.AreEqual(5, set.Count);

            Assert.AreEqual(6, list.Where(x => x.Version == KnownGitDistribution.GitForWindows32v1).Count());
            Assert.AreEqual(6, list.Where(x => x.Version == KnownGitDistribution.GitForWindows32v2).Count());
            Assert.AreEqual(3, list.Where(x => x.Version == KnownGitDistribution.GitForWindows64v2).Count());

            Assert.AreEqual(2, set.Where(x => x.Version == KnownGitDistribution.GitForWindows32v1).Count());
            Assert.AreEqual(2, set.Where(x => x.Version == KnownGitDistribution.GitForWindows32v2).Count());
            Assert.AreEqual(1, set.Where(x => x.Version == KnownGitDistribution.GitForWindows64v2).Count());

            foreach (var v in Enum.GetValues(typeof(KnownGitDistribution)))
            {
                KnownGitDistribution kgd = (KnownGitDistribution)v;

                var a = list.Where(x => x.Version == kgd);
                Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Cmd, a.First().Cmd)));
                Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Config, a.First().Config)));
                Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Git, a.First().Git)));
                Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Libexec, a.First().Libexec)));
                Assert.IsTrue(a.All(x => x != a.First() || GitInstallation.PathComparer.Equals(x.Sh, a.First().Sh)));
            }
        }
Example #7
0
 private void UpdateCategory(ISession session, CategoryData categoryData, Webpage parent, HashSet<CategoryData> allData, NopImportContext nopImportContext)
 {
     CategoryData data = categoryData;
     var suggestParams = new SuggestParams
     {
         DocumentType = typeof(Category).FullName,
         PageName = data.Name,
         UseHierarchy = true
     };
     var category = new Category
     {
         Name = data.Name,
         UrlSegment = string.IsNullOrWhiteSpace(data.Url) ? _webpageUrlService.Suggest(parent, suggestParams) : data.Url,
         Parent = parent,
         CategoryAbstract = data.Abstract.LimitCharacters(500),
         PublishOn = data.Published ? CurrentRequestData.Now.Date : (DateTime?)null,
         RevealInNavigation = true
     };
     var mediaFile = nopImportContext.FindNew<MediaFile>(data.PictureId);
     if (mediaFile != null)
     {
         category.FeatureImage = mediaFile.FileUrl;
     }
     session.Save(category);
     nopImportContext.AddEntry(data.Id, category);
     List<CategoryData> children = allData.Where(d => d.ParentId == data.Id).ToList();
     foreach (CategoryData child in children)
     {
         UpdateCategory(session, child, category, allData, nopImportContext);
     }
 }
 private void UpdatePrefix(HashSet<string> items, string oldPrefix, string newPrefix) {
     var itemsToUpdate = items.Where(a => a.StartsWithIgnoreCase(oldPrefix)).ToList();
     foreach (var item in itemsToUpdate) {
         items.Remove(item);
         items.Add(newPrefix + item.Substring(oldPrefix.Length));
     }
 }
Example #9
0
    public static void Main(string[] args)
    {
        // setup test data
        var PlatformSet = new HashSet<Platform>();
        Platform Platform0;
        PlatformSet.Add(Platform0 = new Platform());
        var ManSet = new HashSet<Man>();
        Man Man0;
        ManSet.Add(Man0 = new Man());
        Man Man1;
        ManSet.Add(Man1 = new Man());
        Man0.ceiling = Platform0;
        Man1.ceiling = Platform0;
        Man0.floor = Platform0;
        Man1.floor = Platform0;
        var DateSet = new HashSet<Date>();
        var PersonSet = new HashSet<Person>();
        Eve Eve0;
        PersonSet.Add(Eve0 = Eve.Instance);
        var WomanSet = new HashSet<Woman>();
        WomanSet.Add(Eve0);
        var EveSet = new HashSet<Eve>();
        EveSet.Add(Eve0);

        // check test data
        Contract.Assert(Contract.ForAll(ManSet, m => ManSet.Where(n => FuncClass.Above(m, n)).Count() == 1), "BelowToo");
    }
Example #10
0
        public IEnumerable<IReceipt> Receive(int maximumCount)
        {
            if (Directory.Exists(_directoryName))
            {
                HashSet<string> fileNames = new HashSet<string>(Directory.GetFiles(_directoryName));
                string[] notReceivedFileNames = fileNames.Where((n) =>
                    Path.HasExtension(n) && !fileNames.Contains(Path.Combine(Path.GetDirectoryName(n), Path.GetFileNameWithoutExtension(n)))).ToArray();

                for (int i = 0; i < Math.Min(maximumCount, notReceivedFileNames.Length); i++)
                {
                    TimeSpan span = DateTime.UtcNow.Subtract(File.GetLastWriteTimeUtc(notReceivedFileNames[i]));

                    if (span.TotalMilliseconds > _visibilityDelayMilliseconds)
                    {
                        string message;

                        using (Stream stream = new FileStream(notReceivedFileNames[i], FileMode.Open, FileAccess.Read))
                        {
                            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                            {
                                message = reader.ReadToEnd();
                            }
                        }

                        yield return new Receipt(message, notReceivedFileNames[i]);
                    }
                }
            }
        }
        public void hash() {
            decimal beløb1 = 11.5M;

            decimal beløb2 = beløb1 / 3M;

            beløb2 *= 3M;

            /*
            True
            40270000
            BFD9000F
            True
            False
            False
            True*/

            Console.WriteLine(beløb1 == beløb2); // (A)

            Console.WriteLine(beløb1.GetHashCode().ToString("X8")); // (B)

            Console.WriteLine(beløb2.GetHashCode().ToString("X8")); // (C)

            var list = new List<decimal> { beløb1, };

            Console.WriteLine(list.Contains(beløb2)); // (D)

            var mgd = new HashSet<decimal> { beløb1, };

            Console.WriteLine(mgd.Contains(beløb2)); // (E)

            Console.WriteLine(mgd.AsEnumerable().Contains(beløb2)); // (F)

            Console.WriteLine(mgd.Where(d => true).Contains(beløb2)); // (G)

        }
Example #12
0
 public IEnumerable<string> GetNames(SyntaxNode node)
 {
     _leftSideOfNames = new HashSet<string>();
     _fullNames = new HashSet<string>();
     Visit(node);
     return _leftSideOfNames.Where(each => _fullNames.Contains(each)).ToArray();
 }
        /// <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 #14
0
        /// <summary>
        /// - Removes empty xmlns attributes
        /// - Change unclear namespaces: qXX -> _preNamespace
        /// </summary>
        /// <param name="rootElement"></param>
        public static void RemoveEmptyNamespaces(XElement rootElement)
        {
            var nsAttributes = new List<Tuple<XAttribute, XAttribute>>();
            var localNames = new HashSet<string>();
            var allAttributes = rootElement.Descendants().SelectMany(x => x.Attributes());

            allAttributes.Where(x => x.Name.LocalName == "xmlns" && string.IsNullOrEmpty(x.Value)).Remove();

            foreach (var attribute in allAttributes.Where(y => y.IsNamespaceDeclaration && !string.IsNullOrEmpty(y.Value)))
            {
                if (attribute.Name.Namespace != "http://www.w3.org/2000/xmlns/" || !attribute.Name.LocalName.StartsWith("q")) continue;

                localNames.Add(attribute.Name.LocalName);
                nsAttributes.Add(new Tuple<XAttribute, XAttribute>(attribute, new XAttribute("_preNamespace", attribute.Value)));
            }

            foreach (var nsAttribute in nsAttributes)
            {
                var parent = nsAttribute.Item1.Parent;

                if (parent == null) continue;

                nsAttribute.Item1.Remove();
                parent.Add(nsAttribute.Item2);
            }

            foreach (var attribute in allAttributes.Where(x => x.Value.Contains(":")))
            {
                foreach (var localName in localNames.Where(x => attribute.Value.Contains(x)))
                {
                    attribute.Value = attribute.Value.Replace(localName + ":", "");
                    break;
                }
            }
        }
Example #15
0
        public override ValueType Solve()
        {
            var numbers = new HashSet<ulong>(new ulong[] {1});
            const int ROWS = 51;

            ulong[] prev;
            ulong[] next = { 1 };

            for(int size=2;size<=ROWS;size++)
            {
                prev = next;

                next = new ulong[size];
                next[0] = next[size - 1] = 1;

                for(int i=1;i<size-1;i++)
                {
                    next[i] = prev[i-1] + prev[i];
                    numbers.Add(next[i]);
                }
            }

            var candidates = numbers.Where(n => n%4 != 0).OrderBy(n => n).ToList();

            foreach(ulong prime in PrimeExtensions.Primes((int)Math.Floor(Math.Sqrt(candidates.Last()))))
            {
                candidates = candidates.Where(n => n%(prime*prime) != 0).ToList();
            }

            return candidates.Sum(n=>(long)n);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="BootstrapConventions" /> class.
        /// </summary>
        public BootstrapConventions()
        {
            this.IsConcreteType = t => !t.IsInterface && !t.IsAbstract && !t.IsGenericType && t.Namespace != null;

            this.IsService = t => this.IsConcreteType( t ) && Topics.Radical.StringExtensions.IsLike( t.Namespace, "*.Services" );

            this.SelectServiceContracts = type =>
            {
                var interfaces = type.GetInterfaces();
                var types = new HashSet<Type>( interfaces )
                {
                    type
                };

                var contracts = types.Where( t => t.IsAttributeDefined<ContractAttribute>() );
                if ( contracts.Any() )
                {
                    return contracts;
                }

                if ( interfaces.Any() )
                {
                    return interfaces;
                }

                return types;
            };

            this.IsFactory = t => this.IsConcreteType( t ) && t.IsNested && t.Name.EndsWith( "Factory" );

            this.SelectFactoryContracts = type => new[] { type };

            this.IsValidator = t => this.IsConcreteType( t ) && t.Namespace.EndsWith( ".Validators" ) && t.Is( typeof( IValidator<> ) );

            this.SelectValidatorContracts = t =>
            {
                var contracts = t.GetInterfaces()
                            .Where( i => i.IsAttributeDefined<ContractAttribute>() )
                            .ToArray();
                return contracts;
            };

            this.IsExcluded = t =>
            {
                return t.IsAttributeDefined<DisableAutomaticRegistrationAttribute>();
            };

            //this.AssemblyFileScanPatterns = entryAssembly =>
            //{
            //    var name = entryAssembly.GetName().Name;

            //    var dllPattern = String.Format( "{0}*.dll", name );
            //    var radical = "Radical.*.dll";

            //    return new[] { dllPattern, radical };
            //};

            //this.IncludeAssemblyInContainerScan = assembly => true;
        }
Example #17
0
        public static IFeedResult AppendError(this IFeedResult self, TransportMessage message, FeedError error)
        {
            var errorItems = new HashSet<TransportMessage>(self.FailedMessages);
            var errorMessage = errorItems.Where(x => x == message).SingleOrDefault() ?? message;
            errorItems.Add(new TransportMessage(errorMessage, error));

            return new MessageProcessor.FeedResult(self.SuccessfulMessages, errorItems);
        }
Example #18
0
        public static IUnityContainer CreateAndRegisterAllDependencies()
        {
            //Referencing data so dll will be copied.  Not really ideal.
            var container = new UnityContainer();
            var dsTypes = new HashSet<Type>(AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.StartsWith("Foodies"))
                                 .SelectMany(s => s.GetTypes()));

            foreach (var dsInterfaces in dsTypes.Where(t => t.IsInterface))
            {
                var assignableType = dsTypes.Where(t => dsInterfaces.IsAssignableFrom(t) && t != dsInterfaces);
                foreach (var type in assignableType)
                {
                    container.RegisterType(dsInterfaces, type);
                }
            }
            return container;
        }
		public static string[] GetProgramFilesPaths()
		{
			var paths = new HashSet<string>();
			paths.Add(Environment.GetEnvironmentVariable("ProgramFiles(x86)"));
			paths.Add(Environment.GetEnvironmentVariable("ProgramFiles"));
			paths.Add(Environment.GetEnvironmentVariable("ProgramW6432"));
			return paths.Where(p => p != null).ToArray();
		}
Example #20
0
        private static HashSet<string> CreateIndex(HashSet<string> left, HashSet<string> right)
        {
            var idx = new HashSet<string>();

            foreach (var item in left.Where(right.Contains))
                idx.Add(item);

            return idx;
        }
 public IEnumerable<IStylingRule> GetUnusedRules()
 {
     lock (_sync)
     {
         var unusedRules = new HashSet<IStylingRule>(GetAllRules());
         unusedRules.ExceptWith(_ruleUsages.Select(x => x.Rule).Distinct());
         return unusedRules.Where(x => !UsageRegistry.IsAProtectedClass(x)).ToList();
     }
 }
    static void Main()
    {
        int N = // ...

        var allTrees = new HashSet<HashSet<int>>();
        var edges = new Tuple<int, int, int>[N];
        var nodes = new HashSet<int>();

        // Initialization -> edges / nodes
        
        // Represend each node as tree
        foreach (var node in nodes)
        {
            var tree = new HashSet<int>();
            tree.Add(node);

            allTrees.Add(tree);
        }

        // Sorting edges by their weight
        Array.Sort(edges, (a, b) => a.Item3.CompareTo(b.Item3));

        double result = 0; // Minimal spanning tree distance

        foreach (var edge in edges)
        {
            var tree1 = allTrees.Where(tree => tree.Contains(edge.Item1)).First();
            var tree2 = allTrees.Where(tree => tree.Contains(edge.Item2)).First();

            // Elements are in same tree
            if (tree1.Equals(tree2)) continue;

            result += edge.Item3;

            // Combine trees
            tree1.UnionWith(tree2);
            allTrees.Remove(tree2);

            // Small optimization
            if (allTrees.Count == 1) break;
        }

        Console.WriteLine(result);
    }
        /// <summary>
        /// Determines whether the interpreter factory contains the specified
        /// modules.
        /// </summary>
        /// <returns>The names of the modules that were found.</returns>
        public static async Task<HashSet<string>> FindModulesAsync(this IPythonInterpreterFactory factory, params string[] moduleNames) {
            var finding = new HashSet<string>(moduleNames);
            var found = new HashSet<string>();
            var withPackages = factory.PackageManager;
            if (withPackages != null) {
                foreach (var m in finding) {
                    if ((await withPackages.GetInstalledPackageAsync(new PackageSpec(m), CancellationToken.None)).IsValid) {
                        found.Add(m);
                    }
                }
                finding.ExceptWith(found);
                if (!finding.Any()) {
                    // Found all of them, so stop searching
                    return found;
                }
            }

            var withDb = factory as PythonInterpreterFactoryWithDatabase;
            if (withDb != null && withDb.IsCurrent) {
                var db = withDb.GetCurrentDatabase();
                found.UnionWith(finding.Where(m => db.GetModule(m) != null));

                // Always stop searching after this step
                return found;
            }

            if (withDb != null) {
                try {
                    var paths = await PythonTypeDatabase.GetDatabaseSearchPathsAsync(withDb);
                    found.UnionWith(PythonTypeDatabase.GetDatabaseExpectedModules(withDb.Configuration.Version, paths)
                        .SelectMany()
                        .Select(g => g.ModuleName)
                        .Where(m => finding.Contains(m)));
                } catch (InvalidOperationException) {
                }

                finding.ExceptWith(found);
                if (!finding.Any()) {
                    // Found all of them, so stop searching
                    return found;
                }
            }

            return await Task.Run(() => {
                foreach (var mp in ModulePath.GetModulesInLib(factory.Configuration)) {
                    if (finding.Remove(mp.ModuleName)) {
                        found.Add(mp.ModuleName);
                    }

                    if (!finding.Any()) {
                        break;
                    }
                }
                return found;
            });
        }
Example #24
0
 public static IFeedResult AppendError(this IFeedResult self, IEnumerable<TransportMessage> messages, FeedError error)
 {
     var errorItems = new HashSet<TransportMessage>(self.FailedMessages);
     foreach (var failedMessage in messages)
     {
         var errorMessage = errorItems.Where(x => x == failedMessage).SingleOrDefault() ?? failedMessage;
         errorItems.Add(new TransportMessage(errorMessage, error));
     }
     return new MessageProcessor.FeedResult(self.SuccessfulMessages, errorItems);
 }
Example #25
0
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        var edges = new Tuple<int, int, int>[n];
        var nodes = new HashSet<int>();

        for (int i = 0; i < n; i++)
        {
            var input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

            edges[i] = new Tuple<int, int, int>(input[0], input[1], input[2]);
            nodes.Add(input[0]);
            nodes.Add(input[1]);
        }

        var allTrees = new HashSet<HashSet<int>>();
        foreach (var node in nodes)
        {
            var tree = new HashSet<int>();
            tree.Add(node);
            allTrees.Add(tree);
        }

        Array.Sort(edges, (a, b) => a.Item3.CompareTo(b.Item3));

        long result = 0;
        foreach (var edge in edges)
        {
            var tree1 = allTrees.Where(tree => tree.Contains(edge.Item1)).First();
            var tree2 = allTrees.Where(tree => tree.Contains(edge.Item2)).First();

            if (tree1.Equals(tree2)) continue;

            result += edge.Item3;

            tree1.UnionWith(tree2);
            allTrees.Remove(tree2);

            if (allTrees.Count == 1) break;
        }

        Console.WriteLine(result);
    }
Example #26
0
        string Main()
        {
            // We don't necessarily need to look at every permutation
            // Just need to be find every cube that contains the exact same characters
            // There is still ways to improve the speed of this by keeping track of permutations?";

            HashSet<long> cubes = new HashSet<long>();
            int max = 20000;
            int maxCount = 0;
            long finalCube = 0;

            for (long i = 1; i < max; i++)
                cubes.Add(i * i * i);

            foreach (long cube in cubes)
            {
                int validPermutations = 1;
                var currentCubeLength = cube.ToString().Length;
                var currentCubeChars = cube.ToString().ToCharArray().OrderBy(c => c).ToList();

                var cubesOfSameLength = cubes.Where(c => c.ToString().Length == currentCubeLength && c != cube).ToList();
                foreach (long similarCube in cubesOfSameLength)
                {
                    var similarCubeChars = similarCube.ToString().ToCharArray().OrderBy(c => c).ToList();

                    bool isMatch = true;
                    for (int i = 0; i < currentCubeLength; i++)
                    {
                        if (currentCubeChars[i] != similarCubeChars[i])
                        {
                            isMatch = false;
                            break;
                        }
                    }

                    if (isMatch)
                        validPermutations++;
                }

                if (validPermutations > maxCount)
                {
                    maxCount = validPermutations;
                    finalCube = cube;
                    Console.WriteLine(cube + ", " + validPermutations);
                }

                if (maxCount == 5)
                    break;
            }

            Console.WriteLine("Cube permutations: " + maxCount);
            Console.WriteLine("Cube: " + finalCube);
            Console.WriteLine("Cubic: " + Math.Pow(finalCube, (1.0 / 3.0)));
            return "";
        }
        /// <summary>
        /// Gives all packages for an Id, and all dependencies recursively.
        /// </summary>
        public override async Task<IEnumerable<PackageDependencyInfo>> ResolvePackages(IEnumerable<string> packageIds, NuGetFramework projectFramework, bool includePrerelease, CancellationToken token)
        {
            HashSet<PackageDependencyInfo> result = new HashSet<PackageDependencyInfo>(PackageIdentityComparer.Default);

            foreach (string packageId in packageIds)
            {
                result.UnionWith(await GetPackagesFromRegistration(packageId, AllVersions, projectFramework, token));
            }

            return result.Where(e => includePrerelease || !e.Version.IsPrerelease);
        }
Example #28
0
		public IEnumerable<Actor> UnitsInRange(CPos xy)
		{
			var range = ((ChronoshiftPowerInfo)Info).Range;
			var tiles = Self.World.Map.FindTilesInCircle(xy, range);
			var units = new HashSet<Actor>();
			foreach (var t in tiles)
				units.UnionWith(Self.World.ActorMap.GetActorsAt(t));

			return units.Where(a => a.Info.HasTraitInfo<ChronoshiftableInfo>() &&
				!a.TraitsImplementing<IPreventsTeleport>().Any(condition => condition.PreventsTeleport(a)));
		}
        public static SPEvolutionPlan BuildMigrationPlan(long target, IEnumerable<long> applied, IEnumerable<long> availableEvos)
        {
            long startVersion = applied.Count() < 1 ? 0 : applied.Max();
            HashSet<long> set = new HashSet<long>(applied);

            // проверки
            var list = availableEvos.Where(x => x < startVersion && !set.Contains(x));
            if (list.Count() > 1)
            {
                throw new ArgumentException
                    ("Current Evolution Schema Version Error: There is not applied evolutions step");//, list);
            }

            set.UnionWith(availableEvos);

            var versions = target < startVersion
                            ? set.Where(n => n <= startVersion && n > target).OrderByDescending(x => x).ToList()
                            : set.Where(n => n > startVersion && n <= target).OrderBy(x => x).ToList();

            return new SPEvolutionPlan(versions, startVersion);
        }
        public IEnumerable<PhonebookEntry> Find(string name, string town)
        {
            HashSet<PhonebookEntry> matchedByName = new HashSet<PhonebookEntry>();
            matchedByName.UnionWith(this.byFirstName[name]);
            matchedByName.UnionWith(this.byMiddleName[name]);
            matchedByName.UnionWith(this.byLastName[name]);
            matchedByName.UnionWith(this.byNickname[name]);

            IEnumerable<PhonebookEntry> matchedByNameAndTown =
                matchedByName.Where(entry => entry.Town == town);
            return matchedByNameAndTown;
        }