Example #1
0
        /// <summary>
        /// Gets the application assemblies.
        /// </summary>
        /// <param name="assemblyFilter">(Optional) A filter for the assemblies.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A promise of an enumeration of application assemblies.
        /// </returns>
        public virtual async Task<IEnumerable<Assembly>> GetAppAssembliesAsync(Func<AssemblyName, bool> assemblyFilter = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // TODO The assemblies from the current domain do not consider the not loaded
            // but required referenced assemblies. Therefore load all the references recursively.
            // This could be optimized somehow.
            var assemblies = this.GetLoadedAssemblies();

            assemblyFilter = assemblyFilter ?? this.AssemblyFilter;
            var loadedAssemblyRefs = new HashSet<string>(assemblies.Select(a => a.GetName().FullName));
            var assembliesToCheck = assemblies.Where(a => assemblyFilter(a.GetName())).ToList();

            while (assembliesToCheck.Count > 0)
            {
                var assemblyRefsToLoad = new HashSet<AssemblyName>();
                foreach (var assembly in assembliesToCheck)
                {
                    var referencesToLoad = this.GetReferencedAssemblies(assembly).Where(a => !loadedAssemblyRefs.Contains(a.FullName) && assemblyFilter(a));
                    assemblyRefsToLoad.AddRange(referencesToLoad);
                }

                loadedAssemblyRefs.AddRange(assemblyRefsToLoad.Select(an => an.FullName));
                assembliesToCheck = assemblyRefsToLoad.Select(this.AssemblyLoader.LoadAssembly).ToList();
                assemblies.AddRange(assembliesToCheck);
            }

            await this.AddAdditionalAssembliesAsync(assemblies, assemblyFilter, cancellationToken).PreserveThreadContext();
            return assemblies;
        }
 public static void SomeFunction()
 {
     Dictionary<int, int> dict = new Dictionary<int, int>();
     dict.Add(4, 3);
     Console.WriteLine(dict[4]);
     Console.WriteLine(dict.ContainsKey(8));
     dict.Remove(4);
     foreach(int key in dict.Keys)
         Console.WriteLine(key);
     foreach(int val in dict.Values)
         Console.WriteLine(val);
     foreach(var kv in dict)
         Console.WriteLine(kv.Key + " " + kv.Value);
     var dict2 = dict.ToDictionary(o => o.Key, o => o.Value);
     var vals = dict.Values;
     
     HashSet<int> hash = new HashSet<int>();
     hash.Add(999);
     Console.WriteLine(hash.Contains(999));
     hash.Remove(999);
     Console.WriteLine(hash.Contains(999));
     foreach(int hashItem in hash)
         Console.WriteLine(hashItem);
     var z = hash.Select(o => 3).ToArray();
     var g = hash.GroupBy(o => o).Select(o => o.Count()).Min();
 }
Example #3
0
        public static ClaimsIdentity CreateUserIdentity(string emailAddress, string id, string[] organizationIds, string[] roles, string defaultProjectId = null) {
            var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name, emailAddress),
                    new Claim(ClaimTypes.NameIdentifier, id),
                    new Claim(OrganizationIdsClaim, String.Join(",", organizationIds))
                };

            if (!String.IsNullOrEmpty(defaultProjectId))
                claims.Add(new Claim(DefaultProjectIdClaim, defaultProjectId));

            var userRoles = new HashSet<string>(roles);
            if (userRoles.Any()) {
                // add implied scopes
                if (userRoles.Contains(AuthorizationRoles.GlobalAdmin))
                    userRoles.Add(AuthorizationRoles.User);

                if (userRoles.Contains(AuthorizationRoles.User))
                    userRoles.Add(AuthorizationRoles.Client);

                claims.AddRange(userRoles.Select(scope => new Claim(ClaimTypes.Role, scope)));
            } else {
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.Client));
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.User));
            }

            return new ClaimsIdentity(claims, UserAuthenticationType);
        }
Example #4
0
        public void onProductListReceived (string productListString) {
            if (productListString.Length == 0) {
                biller.logError (UnibillError.STOREKIT_RETURNED_NO_PRODUCTS);
                biller.onSetupComplete (false);
                return;
            }

            Dictionary<string, object> response = (Dictionary<string, object>)Unibill.Impl.MiniJSON.jsonDecode(productListString);
            HashSet<PurchasableItem> productsReceived = new HashSet<PurchasableItem>();
            foreach (var identifier in response.Keys) {
                var item = remapper.getPurchasableItemFromPlatformSpecificId(identifier.ToString());
                Dictionary<string, object> details = (Dictionary<string, object>)response[identifier];

                PurchasableItem.Writer.setLocalizedPrice(item, details["price"].ToString());
                PurchasableItem.Writer.setLocalizedTitle(item, details["localizedTitle"].ToString());
                PurchasableItem.Writer.setLocalizedDescription(item, details["localizedDescription"].ToString());
                productsReceived.Add(item);
            }

            HashSet<PurchasableItem> productsNotReceived = new HashSet<PurchasableItem> (products);
            productsNotReceived.ExceptWith (productsReceived);
            if (productsNotReceived.Count > 0) {
                foreach (PurchasableItem product in productsNotReceived) {
                    biller.logError(UnibillError.STOREKIT_REQUESTPRODUCTS_MISSING_PRODUCT, product.Id, remapper.mapItemIdToPlatformSpecificId(product));
                }
            }

            this.productsNotReturnedByStorekit = new HashSet<string>(productsNotReceived.Select(x => remapper.mapItemIdToPlatformSpecificId(x)));

            // We should complete so long as we have at least one purchasable product.
            biller.onSetupComplete(true);
        }
        ///<summary>Gets all files that indirectly depend on the specified file.</summary>
        public async Task<IEnumerable<string>> GetRecursiveDependentsAsync(string fileName)
        {
            HashSet<GraphNode> visited;
            fileName = Path.GetFullPath(fileName);
            using (await rwLock.ReadLockAsync())
            {
                GraphNode rootNode;
                if (!nodes.TryGetValue(fileName, out rootNode))
                    return Enumerable.Empty<string>();

                var stack = new Stack<GraphNode>();
                stack.Push(rootNode);
                visited = new HashSet<GraphNode> { rootNode };
                while (stack.Count > 0)
                {
                    foreach (var child in stack.Pop().Dependents)
                    {
                        if (!visited.Add(child)) continue;
                        stack.Push(child);
                    }
                }
                // Don't return the original file.
                visited.Remove(rootNode);
            }
            return visited.Select(n => n.FileName);
        }
        public static int Circulars(int range)
        {
            int count = 0;
            HashSet<int> primes = new HashSet<int>();
            primes.UnionWith(Primes.primeRange(range));
            HashSet<string> stringprimes = new HashSet<string>();
            stringprimes.UnionWith(primes.Select<int, string>(x => x.ToString()));

            stringprimes.RemoveWhere(x => x.Contains('2') || x.Contains('4') || x.Contains('6') || x.Contains('8') || x.Contains('0'));

            foreach (string number in stringprimes) {
                string varnumber = number.Substring(0);
                bool allPrime = true;
                for (int i = 0; i < number.Length; i++) {
                    char c = varnumber.First<char>();
                    varnumber += c;
                    varnumber = varnumber.Remove(0, 1);
                    if (!primes.Contains(int.Parse(varnumber))) {
                        //Console.WriteLine(number);
                        allPrime = false;
                        break;
                    }
                }
                if (allPrime == true) {
                    count++;
                }
                allPrime = true;
            }
            return count + 1;
        }
Example #7
0
        private static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            string[] k = new string[t];
            for (int i = 0; i < k.Length; i++)
            {
                k[i] = Console.ReadLine();
            }

            string temp = @"<[ ]{0,}[a-z]{1,}[\d]{0,}";
            var regex = new Regex(temp);
            HashSet<string> rez = new HashSet<string>();
            for (int i = 0; i < k.Length; i++)
            {
                var matchs = regex.Matches(k[i]);
                foreach (var r in matchs)
                {
                    var match = (Match)r;

                        rez.Add(match.Value);

                }
            }
            var s = rez
                .Select(f=>f.Substring(1))
                .ToArray();
            Array.Sort(s);
            string mimimi = string.Join(";", s);

            Console.Write(mimimi);
        }
Example #8
0
        private SyntaxNode AddNamespaceImports(
            Document document,
            SemanticModel model,
            OptionSet options,
            IEnumerable<INamespaceSymbol> namespaces)
        {
            var existingNamespaces = new HashSet<INamespaceSymbol>();
            this.GetExistingImportedNamespaces(document, model, existingNamespaces);

            var namespacesToAdd = new HashSet<INamespaceSymbol>(namespaces);
            namespacesToAdd.RemoveAll(existingNamespaces);

            var root = model.SyntaxTree.GetRoot();
            if (namespacesToAdd.Count == 0)
            {
                return root;
            }

            var gen = SyntaxGenerator.GetGenerator(document);

            var newRoot = root;
            foreach (var import in namespacesToAdd.Select(ns => gen.NamespaceImportDeclaration(ns.ToDisplayString()).WithAdditionalAnnotations(Simplifier.Annotation)))
            {
                newRoot = this.InsertNamespaceImport(newRoot, gen, import, options);
            }

            return newRoot;
        }
        public void Install(RunningDeployment deployment)
        {
            var transformDefinitions = GetTransformDefinitions(deployment.Variables.Get(SpecialVariables.Package.AdditionalXmlConfigurationTransforms));

            var sourceExtensions = new HashSet<string>(
                  transformDefinitions
                    .Where(transform => transform.Advanced)
                    .Select(transform => "*" + Path.GetExtension(transform.SourcePattern))
                    .Distinct()
                );

            if (deployment.Variables.GetFlag(SpecialVariables.Package.AutomaticallyRunConfigurationTransformationFiles))
            {
                sourceExtensions.Add("*.config");
                transformDefinitions.Add(new XmlConfigTransformDefinition("Release"));

                var environment = deployment.Variables.Get(SpecialVariables.Environment.Name);
                if (!string.IsNullOrWhiteSpace(environment))
                {
                    transformDefinitions.Add(new XmlConfigTransformDefinition(environment));
                }
            }

            var transformsRun = new HashSet<Tuple<string, string>>();
            foreach (var configFile in fileSystem.EnumerateFilesRecursively(deployment.CurrentDirectory, sourceExtensions.ToArray()))
            {
                ApplyTransformations(configFile, transformDefinitions, transformsRun);
            }

            deployment.Variables.SetStrings(SpecialVariables.AppliedXmlConfigTransforms, transformsRun.Select(t => t.Item1), "|");
        }
        /// <summary>
        /// Returns a list of assemblies that need binding redirects.
        /// </summary>
        /// <param name="assemblies">List assemblies to analyze for binding redirects</param>
        public static IEnumerable<AssemblyBinding> GetBindingRedirects(IEnumerable<IAssembly> assemblies)
        {
            if (assemblies == null) {
                throw new ArgumentNullException("assemblies");
            }

            // Evaluate the list eagerly
            var assemblyList = assemblies.ToList();

            var assemblyNameLookup = assemblyList.ToDictionary(GetUniqueKey);

            // Output set of assemblies we need redirects for
            var redirectAssemblies = new HashSet<IAssembly>();

            // For each available assembly
            foreach (IAssembly assembly in assemblyList) {
                foreach (IAssembly referenceAssembly in assembly.ReferencedAssemblies) {
                    Tuple<string, string> key = GetUniqueKey(referenceAssembly);
                    IAssembly targetAssembly;
                    // If we have an assembly with the same unique key in our list of a different version then we want to use that version
                    // then we want to add a redirect for that assembly
                    if (assemblyNameLookup.TryGetValue(key, out targetAssembly) && targetAssembly.Version != referenceAssembly.Version) {
                        redirectAssemblies.Add(targetAssembly);
                    }
                }
            }

            return redirectAssemblies.Select(a => new AssemblyBinding(a));
        }
        private async Task<SyntaxNode> AddNamespaceImportsAsync(
            Document document,
            SemanticModel model,
            OptionSet options,
            IEnumerable<INamespaceSymbol> namespaces,
            CancellationToken cancellationToken)
        {
            var existingNamespaces = new HashSet<INamespaceSymbol>();
            await this.GetExistingImportedNamespacesAsync(document, model, existingNamespaces, cancellationToken).ConfigureAwait(false);

            var namespacesToAdd = new HashSet<INamespaceSymbol>(namespaces);
            namespacesToAdd.RemoveAll(existingNamespaces);

            var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
            if (namespacesToAdd.Count == 0)
            {
                return root;
            }

            var gen = SyntaxGenerator.GetGenerator(document);

            var newRoot = root;
            foreach (var import in namespacesToAdd.Select(ns => gen.NamespaceImportDeclaration(ns.ToDisplayString()).WithAdditionalAnnotations(Simplifier.Annotation)))
            {
                newRoot = this.InsertNamespaceImport(newRoot, gen, import, options);
            }

            return newRoot;
        }
Example #12
0
 public ReplayViewModel Get([FromUri]string[] ids)
 {
     var heads = new[]
     {
         new Directed {X = 1, Y = 13, Direction = Direction.East},
         new Directed {X = 25, Y = 13, Direction = Direction.West},
         new Directed {X = 13, Y = 1, Direction = Direction.North},
         new Directed {X = 13, Y = 25, Direction = Direction.South}
     };
     var n = 0;
     var unique = new HashSet<string>(ids);
     var fighters = unique
         .Select(id => snakeStore.GetById(id))
         .Where(s => s != null)
         .Take(4)
         .Select(snake => new Fighter(snake.Id, snake.Chips, heads[n++]))
         .ToList();
     var tickCount = Environment.TickCount;
     var replay = new Replay(tickCount) { BattleField = new BattleField() };
     if (fighters.Count > 0)
     {
         var battleField = new BattleField();
         var battleManager = new BattleManager(fighters, replay, new FieldComparer(battleField), battleField, tickCount);
         battleManager.Fight(550); //original 550    
     }
     var model = Mapper.Map<Replay, ReplayViewModel>(replay);
     return model;
 }
Example #13
0
        public void MatchIndex()
        {
            string tournamentName = "ChallongeNet" + Utilities.RandomName();
            Debug.WriteLine(string.Format("Initializing with name {0}", tournamentName));

            var tournamentUnderTest = this.target.TournamentCreate(tournamentName, TournamentType.SingleElimination, tournamentName);

            var participantNames = new HashSet<string>();
            const int NumberOfParticipants = 8;
            while (participantNames.Count < NumberOfParticipants)
            {
                string name = "ChallongeNet" + Utilities.RandomName();
                participantNames.Add(name);
            }

            var participants = participantNames.Select(name => this.target.ParticipantCreate(tournamentUnderTest, new ParticipantCreateParameters { Name = name })).ToList();

            tournamentUnderTest = this.target.TournamentStart(tournamentUnderTest);

            var participant = participants.First();
            var parameters = new MatchIndexParameters { ParticipantId = participant.Id };
            var matches = this.target.MatchIndex(tournamentUnderTest, parameters);
            var m = matches.Where(match => match.Player1Id == participant.Id || match.Player2Id == participant.Id);
            Assert.AreEqual(1, m.Count());

            parameters = new MatchIndexParameters { State = MatchIndexParameters.MatchIndexState.complete };
            matches = this.target.MatchIndex(tournamentUnderTest, parameters);
            Assert.AreEqual(0, matches.Count);

            this.target.TournamentDestroy(tournamentUnderTest);
        }
        /// <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 #15
0
        /// <summary> Converts a console file args into actual files. </summary>
        /// <remarks> Sequences like "test.vsdx *.vsdx .\test.vsdx" will be correctly recognized,
        /// no file duplicates will be created. </remarks>
        /// <param name="passedFileArgs">File arguments in the console input.</param>
        /// <returns>Sequence of files recognized in the console input.</returns>
        public static IEnumerable<FileInfo> GatherFiles(IList<string> passedFileArgs)
        {
            // Expand passed console input with possible wildcards and duplications into real unique file names:
            var expandedPaths = new HashSet<string>();
            foreach (var inputItem in passedFileArgs) {
                if (string.IsNullOrWhiteSpace(inputItem)) { continue; }

                string[] files;
                if (Directory.Exists(inputItem)) {
                    files = GetFiles(inputItem);
                } else {
                    string path = Path.GetDirectoryName(inputItem);
                    string filename = Path.GetFileName(inputItem);
                    if (filename == "*") {
                        filename = "*.*";
                    }

                    files = GetFiles(path, filename);
                }

                foreach (var file in files) {
                    expandedPaths.Add(file);
                }
            }
            // Expanded file names can be safely turned into FileInfos, since GetFiles()
            // only return real files which can be accessed.
            return expandedPaths.Select(expandedPath => new FileInfo(expandedPath));
        }
Example #16
0
        public static ClaimsIdentity ToIdentity(this User user, string defaultProjectId = null) {
            if (user == null)
                return WindowsIdentity.GetAnonymous();
            
            var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name, user.EmailAddress),
                    new Claim(ClaimTypes.NameIdentifier, user.Id),
                    new Claim(OrganizationIdsClaim, String.Join(",", user.OrganizationIds.ToArray()))
                };

            if (!String.IsNullOrEmpty(defaultProjectId))
                claims.Add(new Claim(DefaultProjectIdClaim, defaultProjectId));

            var userRoles = new HashSet<string>(user.Roles.ToArray());
            if (userRoles.Any()) {
                // add implied scopes
                if (userRoles.Contains(AuthorizationRoles.GlobalAdmin))
                    userRoles.Add(AuthorizationRoles.User);

                if (userRoles.Contains(AuthorizationRoles.User))
                    userRoles.Add(AuthorizationRoles.Client);

                claims.AddRange(userRoles.Select(scope => new Claim(ClaimTypes.Role, scope)));
            } else {
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.Client));
                claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.User));
            }

            return new ClaimsIdentity(claims, UserAuthenticationType);
        }
 protected ApprovalProcess(Guid promotionId, HashSet<Editor> editors)
 {
     Id = Guid.NewGuid();
     PromotionId = promotionId;
     Status = ApprovalStatus.Pending;
     ApprovalRequests = editors.Select(e => new ApprovalRequest(e)).ToList();
 }
        public static UnifiedBubbleGroup CreateUnified(List<BubbleGroup> groups, BubbleGroup primaryGroup)
        {
            lock (BubbleGroupDatabase.OperationLock)
            {
                var unifiedGroupsToKill = new HashSet<UnifiedBubbleGroup>();
                foreach (var group in groups)
                {
                    if (group.IsUnified)
                    {
                        unifiedGroupsToKill.Add(group.Unified);
                        @group.DeregisterUnified();
                    }
                }
                foreach (var unifiedGroup in unifiedGroupsToKill)
                {
                    BubbleGroupManager.BubbleGroupsRemove(unifiedGroup);
                }
                BubbleGroupIndex.RemoveUnified(unifiedGroupsToKill.Select(x => x.ID).ToArray());

                var unified = CreateUnifiedInternal(groups, primaryGroup);
                BubbleGroupIndex.AddUnified(unified);
                BubbleGroupManager.BubbleGroupsAdd(unified);
                return unified;
            }
        }
Example #19
0
        public bool MapCanBeSolved()
        {
            var cluesFound = new HashSet<Clue>();
            var doorManager = model.DoorAndClueManager;
            //Door & Clue manager works on the reduced map, so we use this here
            //Potentially could be problematic if something is wrong with map reduction
            var totalVerticesReducedMap = model.GraphNoCycles.mapNoCycles.VertexCount;

            int lastTimeAccessibleVertices = 0;
            int noAccessibleVertices = 0;
            do
            {
                lastTimeAccessibleVertices = noAccessibleVertices;

                var accessibleVertices = doorManager.GetAccessibleVerticesWithClues(cluesFound.Select(c => c.OpenLockIndex));

                //Add any clues in these vertices to the clues we have (hashset ensures we don't add twice)
                var cluesAtVertices = accessibleVertices.SelectMany(v => doorManager.ClueMap.ContainsKey(v) ? doorManager.ClueMap[v] : new List<Clue> ());
                foreach (var clue in cluesAtVertices) { cluesFound.Add(clue); }

                noAccessibleVertices = accessibleVertices.Count();
            } while (noAccessibleVertices != lastTimeAccessibleVertices);

            //Couldn't touch all vertices - map is not solvable
            if (noAccessibleVertices < totalVerticesReducedMap)
                return false;

            return true;
        }
		internal Assembly CompileAndLoadClassDefinition(string code, string className, HashSet<string> assemblies)
		{
			using (var ms = new MemoryStream())
			{
				string assemblyFileName = className + Guid.NewGuid().ToString().Replace("-", "") + ".dll";

				assemblies.Add(typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly.Location);
				var references = assemblies.Select(a => MetadataReference.CreateFromFile(a));
				var compilation = CSharpCompilation.Create(assemblyFileName,
					new[] { CSharpSyntaxTree.ParseText(code) }, references,
					new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary
//#if !DEBUG
//, optimizationLevel: OptimizationLevel.Release
//#endif
));

				var result = compilation.Emit(ms);
				if (!result.Success)
				{
					var errors = string.Join(Environment.NewLine, result.Diagnostics);
					throw new Exception("Unable to compile. Errors:" + Environment.NewLine + errors);
				}

				var assembly = Assembly.Load(ms.GetBuffer());
				return assembly;
			}
		}
        public IList<HtmlCompletion> GetEntries(HtmlCompletionContext context)
        {
            var list = new HashSet<string>();

            context.Document.HtmlEditorTree.RootNode.Accept(this, list);

            return new List<HtmlCompletion>(list.Select(s => new SimpleHtmlCompletion(s, context.Session)));
        }
        public string[] GetAllProjectReferences(string projectName)
        {
            var project = Solution.Projects.First(x => x.Name == projectName);
            var allReferences = new HashSet<MetadataReference>();

            PopulateWithReferences(allReferences, project);

            return allReferences.Select(x => x.Display).ToArray();
        }
        public IList<HtmlCompletion> GetEntries(HtmlCompletionContext context)
        {
            var list = new HashSet<string>();
            var glyph = GlyphService.GetGlyph(StandardGlyphGroup.GlyphGroupVariable, StandardGlyphItem.GlyphItemPublic);

            context.Document.HtmlEditorTree.RootNode.Accept(this, list);

            return list.Select(s => new HtmlCompletion(s, s, s, glyph, HtmlIconAutomationText.AttributeIconText)).ToList();
        }
Example #24
0
        /// <summary>
        /// Calculate a path from the start location to the destination location
        /// </summary>
        /// <remarks>
        /// Based on the A* pathfinding algorithm described on Wikipedia
        /// </remarks>
        /// <see href="https://en.wikipedia.org/wiki/A*_search_algorithm#Pseudocode"/>
        /// <param name="start">Start location</param>
        /// <param name="goal">Destination location</param>
        /// <param name="allowUnsafe">Allow possible but unsafe locations</param>
        /// <returns>A list of locations, or null if calculation failed</returns>
        public static Queue<Location> CalculatePath(World world, Location start, Location goal, bool allowUnsafe = false)
        {
            Queue<Location> result = null;

            AutoTimeout.Perform(() =>
            {
                HashSet<Location> ClosedSet = new HashSet<Location>(); // The set of locations already evaluated.
                HashSet<Location> OpenSet = new HashSet<Location>(new[] { start });  // The set of tentative nodes to be evaluated, initially containing the start node
                Dictionary<Location, Location> Came_From = new Dictionary<Location, Location>(); // The map of navigated nodes.

                Dictionary<Location, int> g_score = new Dictionary<Location, int>(); //:= map with default value of Infinity
                g_score[start] = 0; // Cost from start along best known path.
                // Estimated total cost from start to goal through y.
                Dictionary<Location, int> f_score = new Dictionary<Location, int>(); //:= map with default value of Infinity
                f_score[start] = (int)start.DistanceSquared(goal); //heuristic_cost_estimate(start, goal)

                while (OpenSet.Count > 0)
                {
                    Location current = //the node in OpenSet having the lowest f_score[] value
                        OpenSet.Select(location => f_score.ContainsKey(location)
                        ? new KeyValuePair<Location, int>(location, f_score[location])
                        : new KeyValuePair<Location, int>(location, int.MaxValue))
                        .OrderBy(pair => pair.Value).First().Key;
                    if (current == goal)
                    { //reconstruct_path(Came_From, goal)
                        List<Location> total_path = new List<Location>(new[] { current });
                        while (Came_From.ContainsKey(current))
                        {
                            current = Came_From[current];
                            total_path.Add(current);
                        }
                        total_path.Reverse();
                        result = new Queue<Location>(total_path);
                    }
                    OpenSet.Remove(current);
                    ClosedSet.Add(current);
                    foreach (Location neighbor in GetAvailableMoves(world, current, allowUnsafe))
                    {
                        if (ClosedSet.Contains(neighbor))
                            continue;		// Ignore the neighbor which is already evaluated.
                        int tentative_g_score = g_score[current] + (int)current.DistanceSquared(neighbor); //dist_between(current,neighbor) // length of this path.
                        if (!OpenSet.Contains(neighbor))	// Discover a new node
                            OpenSet.Add(neighbor);
                        else if (tentative_g_score >= g_score[neighbor])
                            continue;		// This is not a better path.

                        // This path is the best until now. Record it!
                        Came_From[neighbor] = current;
                        g_score[neighbor] = tentative_g_score;
                        f_score[neighbor] = g_score[neighbor] + (int)neighbor.DistanceSquared(goal); //heuristic_cost_estimate(neighbor, goal)
                    }
                }
            }, TimeSpan.FromSeconds(5));

            return result;
        }
 public IMapa Przetwarzaj(HashSet<VoronoiEdge> krawedzieWoronoja)
 {
     _komorkiZVectorami = new Dictionary<Vector, IKomorka>();
      _rogiZVectorami = new Dictionary<Vector, IRog>();
      Mapa.Dwukrawedzie = krawedzieWoronoja.Select(woro => UtworzDwukrawedz(woro)).ToList();
      UstawKomorkomPrzylegle();
      UstawRogomBliskich();
      Mapa.ZakonczonoTworzenie = true;
      return Mapa;
 }
Example #26
0
 private Entry PickOtherMethod(HashSet<Entry> except)
 {
     var except2 = new HashSet<string>(except.Select(e => e.OptUnitID));
     var randomUnit = Units[RandomGenerator.Random.Next(Units.Count)];
     while (except2.Contains(randomUnit.ID))
     {
         randomUnit = Units[RandomGenerator.Random.Next(Units.Count)];
     }
     return new Entry(randomUnit.ID, randomUnit.CreateContext());
 }
        protected override bool TickCore(RealmTime time)
        {
            var entities = GetNearestEntities(28, 0x0d5e)
                .Concat(GetNearestEntities(28, 0x0d60))
                .ToArray();
            if (entities.Length != 5)
                return true;

            var packets = new List<Packet>();
            var owner = Host.Self.Owner;
            if (entities.All(_ => _.ObjectType != 0x0d5e))
            {
                var players = new HashSet<Entity>();
                foreach (var i in entities.SelectMany(_ => (_ as Enemy).DamageCounter.GetPlayerData()).Where(i => i.Item1.Quest == Host))
                    players.Add(i.Item1);
                packets.AddRange(players.Select(i => new NotificationPacket
                {
                    ObjectId = i.Id, Color = new ARGB(0xFF00FF00), Text = "Quest Complete!"
                }));

                if (Host.Self.Owner is GameWorld)
                    (Host.Self.Owner as GameWorld).EnemyKilled(Host as Enemy,
                        (entities.Last() as Enemy).DamageCounter.Parent.LastHitter);
                Despawn.Instance.Tick(Host, time);
                foreach (var i in entities)
                    Die.Instance.Tick(i, time);
            }
            else
            {
                var hasCorpse = entities.Any(_ => _.ObjectType == 0x0d60);
                for (var i = 0; i < entities.Length; i++)
                    for (var j = i + 1; j < entities.Length; j++)
                    {
                        packets.Add(new ShowEffectPacket
                        {
                            TargetId = entities[i].Id,
                            EffectType = EffectType.Stream,
                            Color = new ARGB(hasCorpse ? 0xffffff00 : 0xffff0000),
                            PosA = new Position
                            {
                                X = entities[j].X,
                                Y = entities[j].Y
                            },
                            PosB = new Position
                            {
                                X = entities[i].X,
                                Y = entities[i].Y
                            }
                        });
                    }
            }
            owner.BroadcastPackets(packets, null);

            return true;
        }
        public IList<HtmlCompletion> GetEntries(HtmlCompletionContext context)
        {
            var list = new HashSet<string>();

            if (context.Element != null && _inputTypes.Contains(context.Element.Name))
            {
                context.Document.HtmlEditorTree.RootNode.Accept(this, list);
            }

            return new List<HtmlCompletion>(list.Select(s => new SimpleHtmlCompletion(s, context.Session)));
        }
Example #29
0
        public static string GetUsersString(HashSet<Guid> users)
        {
            var usersString = users.Select(GetUser)
                                   .Aggregate(string.Empty, (current, user) => current + (user.DisplayName + ", "));
            if (!string.IsNullOrEmpty(usersString))
            {
                usersString = usersString.Remove(usersString.Length - 2);
            }

            return usersString;
        }
        public static IEnumerable<VocabularyItem> GenerateVocabulary(InputSettings settings)
        {
            var words = new HashSet<string>();
            while (words.Count < settings.VocabularySize)
                words.Add(GenerateOneWord(settings.WordMaxLength));

            Func<int> genOccurrence = () => _st_random.Next(settings.WordMaxOccurrences + 1);
            return words
                   .Select(word => new VocabularyItem(word, genOccurrence()))
                   .ToArray();
        }