public async Task<IEnumerable<Album>> AlbumsFromCommaSeparatedValuesAndUserId(string albumsAsCommaSeparatedValues, string userId) { if (string.IsNullOrWhiteSpace(albumsAsCommaSeparatedValues)) { return Enumerable.Empty<Album>(); } var albumsValues = new HashSet<string>(); albumsAsCommaSeparatedValues.Split(new[] { GlobalConstants.CommaSeparatedCollectionSeparator }, StringSplitOptions.RemoveEmptyEntries) .ToList() .ForEach(val => { albumsValues.Add(val.Trim()); }); var resultAlbum = await this.albums .All() .Where(a => (albumsValues.Contains(a.Name.ToLower()) || albumsValues.Contains(a.Id.ToString())) && a.Creator.Id == userId) .ToListAsync(); (await this.albums .All() .Where(a => (albumsValues.Contains(a.Name.ToLower()) || albumsValues.Contains(a.Id.ToString())) && a.Creator.Id == userId) .Select(a => a.Name.ToLower()) .ToListAsync()) .ForEach(a => albumsValues.Remove(a)); var idValues = new List<string>(); albumsValues.ForEach(v => { int id; var isId = int.TryParse(v, out id); if (isId) { idValues.Add(v); } }); idValues.ForEach(a => albumsValues.Remove(a)); albumsValues.ForEach(tagName => resultAlbum.Add(new Album() { Name = tagName })); return resultAlbum; }
/// <summary> /// 正しく読み込めた棋譜のリストを保存します。 /// </summary> public static void SavePathList(string filepath, HashSet<string> pathList) { using (var writer = new StreamWriter(filepath, false, Encoding.UTF8)) { pathList.ForEach(_ => writer.WriteLine(_)); } }
public async Task<IEnumerable<Tag>> TagsFromCommaSeparatedValues(string tagsAsCommaSeparatedValues) { if (string.IsNullOrWhiteSpace(tagsAsCommaSeparatedValues)) { return Enumerable.Empty<Tag>(); } var tagNames = new HashSet<string>(); tagsAsCommaSeparatedValues.Split(new[] { GlobalConstants.CommaSeparatedCollectionSeparator }, StringSplitOptions.RemoveEmptyEntries) .ToList() .ForEach(tag => { tagNames.Add(tag.ToLower().Trim()); }); var resultTags = await this.tags .All() .Where(t => tagNames.Contains(t.Name)) .ToListAsync(); (await this.tags .All() .Where(t => tagNames.Contains(t.Name.ToLower())) .Select(t => t.Name.ToLower()) .ToListAsync()) .ForEach(t => tagNames.Remove(t)); tagNames.ForEach(tagName => resultTags.Add(new Tag { Name = tagName })); return resultTags; }
private void OnServerTestingFinished(object sender, EventArgs e) { var hashset = new HashSet<MissingProduct>(); this.manager.Cache.MissingProductsPerServer.Values.ForEach(hashset.UnionWith); this.MissingProducts.Clear(); hashset.ForEach(this.MissingProducts.Add); }
/** * RelationshipDiscoverer Constructor */ public RelationshipDiscoverer(HashSet<Type> Models) { this.Discovered = new List<Relation>(); // Loop through all models in the context. Models.ForEach(model => { // Loop through all mapped props of the model Model.Dynamic(model).MappedProps.ForEach(prop => { // Ignore primative types. if (TypeMapper.IsClrType(prop.PropertyType)) { return; } // Get the relationship discriptor. Relation? relation; if (TypeMapper.IsListOfEntities(prop)) { if ((relation = this.IsManyToMany(prop)) == null) { if ((relation = this.IsManyToOne(prop)) == null) { throw new UnknownRelationshipException(prop); } } } else { // Make sure the type is a Graceful Model. // If this exception throws, it probably means the // TypeMapper has failed us. if (!prop.PropertyType.IsSubclassOf(typeof(Model))) { throw new UnknownRelationshipException(prop); } if ((relation = this.IsOneToMany(prop)) == null) { if ((relation = this.IsOneToOne(prop)) == null) { throw new UnknownRelationshipException(prop); } } } // Add it to our discovered list. this.Discovered.Add((Relation)relation); }); }); }
void InitializeCategories(ISession session) { var categories = new HashSet<Category> { new Category {Name = "Backpacks", Description = "Backpacks"}, new Category {Name = "Bikes", Description = "Bikes"}, new Category {Name = "Boots", Description = "Boots"}, new Category {Name = "Hats & Helmets", Description = "Hats & Helmets"}, new Category {Name = "Hiking Gear", Description = "Hiking Gear"}, new Category {Name = "Sunglasses", Description = "Sunglasses"} }; categories.ForEach(category => session.Save(category)); _categories = categories; }
/// <summary> /// Publishes the mod to the workshop /// </summary> /// <returns></returns> public bool Publish() { bool newMod = false; if (!Steamworks.SteamAPI.IsSteamRunning()) { MySandboxGame.Log.WriteLineAndConsole("Cannot publish, Steam not detected!"); return(false); } if (!Directory.Exists(m_modPath)) { MySandboxGame.Log.WriteLineAndConsole(string.Format("Directory does not exist {0}. Wrong option?", m_modPath ?? string.Empty)); return(false); } // Upload/Publish if (m_modId == 0) { MySandboxGame.Log.WriteLineAndConsole(string.Format("Uploading new {0}: {1}", m_type.ToString(), m_title)); newMod = true; } else { MySandboxGame.Log.WriteLineAndConsole(string.Format("Updating {0}: {1}; {2}", m_type.ToString(), m_modId, m_title)); } // Add the global game filter for file extensions _globalIgnoredExtensions?.ForEach(s => m_ignoredExtensions.Add(s)); // Process Tags ProcessTags(); PrintItemDetails(); if (m_dryrun) { MySandboxGame.Log.WriteLineAndConsole("DRY-RUN; Publish skipped"); } else { if (_publishMethod != null) { m_modId = _publishMethod(m_modPath, m_title, null, m_modId, (MyPublishedFileVisibility)(m_visibility ?? PublishedFileVisibility.Private), m_tags, m_ignoredExtensions, m_ignoredPaths #if SE , m_dlcs).Id;
private void AddHighlightings() { var variables = new HashSet<IVariableDeclaration>(); Graf.ReachableExits.ForEach(exit => { var data = _elementDataStorage[exit.Source]; if (data != null) { data.Status.ForEach(kvp => { if (kvp.Value == VariableDisposeStatus.NotDisposed || kvp.Value == VariableDisposeStatus.Both) variables.Add(kvp.Key); }); } }); variables.ForEach( variableDeclaration => _highlightings.Add(new HighlightingInfo(variableDeclaration.GetNameDocumentRange(), new LocalVariableNotDisposed(variableDeclaration.DeclaredName)))); }
public async Task<IEnumerable<Tag>> TagsFromCommaSeparatedValues(string tagsAsCommaSeparatedValues) { if (string.IsNullOrWhiteSpace(tagsAsCommaSeparatedValues)) { return Enumerable.Empty<Tag>(); } var existingTagIds = new HashSet<int>(); var tagNames = new HashSet<string>(); tagsAsCommaSeparatedValues.Split(new[] { TagSeparator }, StringSplitOptions.RemoveEmptyEntries) .ToList() .ForEach(tag => { int tagId; if (int.TryParse(tag, out tagId)) { existingTagIds.Add(tagId); } else { tagNames.Add(tag.ToLower()); } }); var resultTags = await this.tags .All() .Where(t => existingTagIds.Contains(t.Id) || tagNames.Contains(t.Name)) .ToListAsync(); (await this.tags .All() .Where(t => tagNames.Contains(t.Name.ToLower())) .Select(t => t.Name.ToLower()) .ToListAsync()) .ForEach(t => tagNames.Remove(t)); tagNames.ForEach(tagName => resultTags.Add(new Tag { Name = tagName, Type = TagType.UserSubmitted })); return resultTags; }
static void Main(string[] args) { var inputs = new List<CryptoHashInput>(); var algorithms = new HashSet<CryptoHashAlgorithm>(); var optionSet = new OptionSet { { "h|?|help", s => PrintUsageAndExit() }, { "V|verbose", s => _verbose = true }, { "json", s => _json = true }, { "map", s => _map = true }, { "lower", s => _upper = false }, { "md5", s => algorithms.Add(new MD5Algorithm()) }, { "sha1", s => algorithms.Add(new SHA1Algorithm()) }, { "sha256", s => algorithms.Add(new SHA256Algorithm()) }, { "sha512", s => algorithms.Add(new SHA512Algorithm()) }, }; var paths = optionSet.Parse(args); if (!algorithms.Any()) { algorithms.Add(new MD5Algorithm()); algorithms.Add(new SHA1Algorithm()); algorithms.Add(new SHA256Algorithm()); algorithms.Add(new SHA512Algorithm()); } algorithms.ForEach(algorithm => algorithm.UpperCase = _upper); var stdin = StdIn; if (stdin != null) { inputs.Add(new CryptoHashInput("stdin", stdin, algorithms)); } inputs.AddRange(paths.Select(path => new CryptoHashInput(path, algorithms))); Print(inputs); }
void InitializeProducts(ISession session) { var products = new HashSet<Product> { new Product{Name = "Hiking Backpack", ProductCode = "Backpack1_1", Category = _categories.First(x => x.Name == "Backpacks"), Price = 50}, new Product{Name = "Wide-base Backpack", ProductCode = "Backpack2_1", Category = _categories.First(x => x.Name == "Backpacks"), Price = 50}, new Product{Name = "Short Backpack", ProductCode = "Backpack3_1", Category = _categories.First(x => x.Name == "Backpacks"), Price = 40}, new Product{Name = "Mountaineering Backpack", ProductCode = "Backpack4_1", Category = _categories.First(x => x.Name == "Backpacks"), Price = 130}, new Product{Name = "Sprint 500 Bike", ProductCode = "Bike1_1", Category = _categories.First(x => x.Name == "Bikes"), Price = 460}, new Product{Name = "Escape 3.0 Bike", ProductCode = "Bike2_1", Category = _categories.First(x => x.Name == "Bikes"), Price = 680}, new Product{Name = "Scoop Cruiser", ProductCode = "Bike3_1", Category = _categories.First(x => x.Name == "Bikes"), Price = 380}, new Product{Name = "Sierra Leather Hiking Boots", ProductCode = "Boots1_1", Category = _categories.First(x => x.Name == "Boots"), Price = 90}, new Product{Name = "Rainier Leather Hiking Boots", ProductCode = "Boots2_1", Category = _categories.First(x => x.Name == "Boots"), Price = 110}, new Product{Name = "Cascade Fur-Lined Hiking Boots", ProductCode = "Boots3_1", Category = _categories.First(x => x.Name == "Boots"), Price = 130}, new Product{Name = "Adirondak Fur-Lined Hiking Boots", ProductCode = "Boots4_1", Category = _categories.First(x => x.Name == "Boots"), Price = 60}, new Product{Name = "Olympic Hiking Boots", ProductCode = "Boots5_1", Category = _categories.First(x => x.Name == "Boots"), Price = 90}, new Product{Name = "Weathered Lether Baseball Cap", ProductCode = "Hat1_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 13}, new Product{Name = "Colorful Straw hat", ProductCode = "Hat2_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 10}, new Product{Name = "Summertime Straw Hat", ProductCode = "Hat3_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 23}, new Product{Name = "Bicycle Safety Helmet", ProductCode = "Helmet1_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 80}, new Product{Name = "Fusion Helmet", ProductCode = "Helmet2_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 150}, new Product{Name = "Fire Helmet", ProductCode = "Helmet3_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 125}, new Product{Name = "Bicycle Safety Helmet", ProductCode = "Helmet1_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 80}, new Product{Name = "Sentinel Locking Carbiner", ProductCode = "Carbiner1_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 16}, new Product{Name = "Guardian Locking Carbiner", ProductCode = "Carbiner2_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 6}, new Product{Name = "Trailhead Locking Carbiner", ProductCode = "Carbiner3_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 80}, new Product{Name = "Traiguide Compass", ProductCode = "Compass1_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 30}, new Product{Name = "Northstar Compass", ProductCode = "Compass2_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 18}, new Product{Name = "Sundial Compass", ProductCode = "Compass3_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 12}, new Product{Name = "Polar Start Compass", ProductCode = "Compass4_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 15}, new Product{Name = "Compass Necklace", ProductCode = "Compass5_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 16}, new Product{Name = "Battery Operated Flashlight", ProductCode = "Flashlight1_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 8}, new Product{Name = "Heavy-Duty Flashlight", ProductCode = "Flashlight2_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 13}, new Product{Name = "Retro Flashlight", ProductCode = "Flashlight3_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 24}, new Product{Name = "Northwind Traders Arizona Sunglasses", ProductCode = "Sunglasses1_1", Category = _categories.First(x => x.Name == "Sunglasses"), Price = 35}, new Product{Name = "Northwind Traders Eclipse Sunglasses", ProductCode = "Sunglasses2_1", Category = _categories.First(x => x.Name == "Sunglasses"), Price = 55}, }; products.ForEach(product => session.Save(product)); }
/// <summary> /// Convert calls to methods marked with InlineAttribute. /// </summary> public void Convert(ReachableContext reachableContext) { this.reachableContext = reachableContext; // Collect all names var methodsWithBody = reachableContext.ReachableTypes.SelectMany(x => x.Methods).Where(m => m.HasBody).ToList(); if (methodsWithBody.Count == 0) return; // Find all methods marked with InlineAttribute var inlineMethods = new HashSet<MethodDefinition>(methodsWithBody.Where(x =>x.HasCustomAttributes && x.CustomAttributes.Any(c => (c.AttributeType.Name == AttributeConstants.InlineAttributeName) && (c.AttributeType.Namespace == AttributeConstants.Dot42AttributeNamespace)))); if (inlineMethods.Count == 0) return; // Prepare inline methods inlineMethods.ForEach(x => x.Body.SimplifyMacros()); // Now inline all applicable calls var notAlwaysConverted = new HashSet<MethodDefinition>(); foreach (var method in methodsWithBody) { if (!inlineMethods.Contains(method)) { Convert(method.Body, inlineMethods, notAlwaysConverted); } } // Mark all methods that have been inlined in all calls not reachable. /*foreach (var method in inlineMethods) { if (!notAlwaysConverted.Contains(method)) { //method.SetNotReachable(); } }*/ }
public static void Consume <T>(this HashSet <T> s, Action <T> f) { s.ForEach(f); s.Clear(); }
protected override async Task <HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { var resourceKey = GetResourceKey(request.RequestUri, _varyHeaders, request); CacheableEntity cacheableEntity = null; var cacheControlHeader = new CacheControlHeaderValue { Private = true, MustRevalidate = true, MaxAge = TimeSpan.FromSeconds(0) }; if (request.Method == HttpMethod.Get) { var eTags = request.Headers.IfNoneMatch; var modifiedSince = request.Headers.IfModifiedSince; var anyEtagsFromTheClientExist = eTags.Any(); var doWeHaveAnyCacheableEntityForTheRequest = _eTagCacheDictionary.TryGetValue(resourceKey, out cacheableEntity); if (anyEtagsFromTheClientExist) { if (doWeHaveAnyCacheableEntityForTheRequest) { if (eTags.Any(x => x.Tag == cacheableEntity.EntityTag.Tag)) { var tempResp = new HttpResponseMessage(HttpStatusCode.NotModified); tempResp.Headers.CacheControl = cacheControlHeader; return(tempResp); } } } else if (modifiedSince.HasValue) { if (doWeHaveAnyCacheableEntityForTheRequest) { if (cacheableEntity.IsValid(modifiedSince.Value)) { var tempResp = new HttpResponseMessage(HttpStatusCode.NotModified); tempResp.Headers.CacheControl = cacheControlHeader; return(tempResp); } } } } HttpResponseMessage response; try { response = await base.SendAsync(request, cancellationToken); } catch (Exception ex) { response = request.CreateErrorResponse( HttpStatusCode.InternalServerError, ex); } if (response.IsSuccessStatusCode) { if (request.Method == HttpMethod.Get && !_eTagCacheDictionary.TryGetValue(resourceKey, out cacheableEntity)) { cacheableEntity = new CacheableEntity(resourceKey); cacheableEntity.EntityTag = GenerateETag(); cacheableEntity.LastModified = DateTimeOffset.Now; _eTagCacheDictionary.AddOrUpdate( resourceKey, cacheableEntity, (k, e) => cacheableEntity); } if (request.Method == HttpMethod.Put || request.Method == HttpMethod.Post || request.Method == HttpMethod.Delete) { HashSet <string> invalidCaches = new HashSet <string>(); invalidCaches.Add(GetRequestUri(request.RequestUri)); CacheInvalidationStore.ForEach( func => func(GetRequestUri(request.RequestUri)) .ForEach(uri => invalidCaches.Add(uri))); invalidCaches.ForEach(invalidCacheUri => { var cacheEntityKeys = _eTagCacheDictionary.Keys.Where( x => x.StartsWith( string.Format("{0}:", invalidCacheUri), StringComparison.InvariantCultureIgnoreCase)); cacheEntityKeys.ForEach(key => { if (!string.IsNullOrEmpty(key)) { CacheableEntity outVal = null; _eTagCacheDictionary.TryRemove(key, out outVal); } }); }); } else { response.Headers.CacheControl = cacheControlHeader; response.Headers.ETag = cacheableEntity.EntityTag; response.Content.Headers.LastModified = cacheableEntity.LastModified; _varyHeaders.ForEach( varyHeader => response.Headers.Vary.Add(varyHeader)); } } return(response); }
public static List<Node> LayOutSiblingNodes(ISet<Node> toBeGrouped) { if (toBeGrouped.Count <= 1) return toBeGrouped.ToList(); var groupedNodes = new List<Node>(); var hasBeenAdded = new HashSet<Node>(); var nextGroupTarget = toBeGrouped; //Remove nodes that does not depend on anything and is never referenced var unreferenced = toBeGrouped.Where(x => !x.SiblingDependencies.Any() && !toBeGrouped.SiblingDependencies().Contains(x)).ToHashSet(); nextGroupTarget.ExceptWith(unreferenced); while (toBeGrouped.Any()) { if (!nextGroupTarget.Any()) { nextGroupTarget = toBeGrouped; } while (nextGroupTarget.Any()) { var currentLayer = GetFacadeNodes(nextGroupTarget); nextGroupTarget = currentLayer.SiblingDependencies().ToHashSet(); if (nextGroupTarget.Any()) { //Get the next layer to check if any of the dependencies are unique to a node of the current layer var nextLayer = GetFacadeNodes(nextGroupTarget); //Check if any nodes that have not been added yet has dependencies on the unique ones, in this case they arent really unique var leftForNextBatch = toBeGrouped.Except(currentLayer.Union(nextLayer)); nextLayer.RemoveAll(x => leftForNextBatch.SiblingDependencies().Contains(x)); var uniqueDependencies = nextLayer.Where(x => !currentLayer.All(n => n.SiblingDependencies.Contains(x))) .Distinct() .ToList(); //If there are unique dependencies, vertical layers are created to separate the unique dependency from layers that dont depend on it if (uniqueDependencies.Any()) { while (true) { //Check if any nodes that have not been added yet has dependencies on the unique ones, in this case they arent really unique leftForNextBatch = toBeGrouped.Except(currentLayer.Union(nextLayer)); nextLayer.RemoveAll(x => leftForNextBatch.Any(y => y.IndirectlyDependsOn(x))); var groupsToCreate = FindDependencyPatterns(currentLayer, nextLayer); var toBeShared = new HashSet<Node>(); toBeGrouped.ExceptWith(currentLayer); foreach (var dependencyGroup in groupsToCreate) { var referencers = dependencyGroup.Referencers; currentLayer.RemoveRange(referencers.ToList()); var dependants = dependencyGroup.Dependants.ToList(); nextGroupTarget.ExceptWith(dependants); toBeGrouped.ExceptWith(dependants); hasBeenAdded.UnionWith(dependants); hasBeenAdded.UnionWith(referencers); // Add dependant to the vertical layer var depNode = CreateHorizontalLayer(dependants); // Add references to the vertical layer var referenceNode = CreateHorizontalLayer(referencers); var newList = new List<Node> {depNode, referenceNode}; //Get ALL the possible candidates for the vertical layer var verticalCandidates = referencers.SelectMany(x => x.IndirectSiblingDependencies()) .Except(dependants) .Union( dependants.SelectMany(x => x.IndirectSiblingDependencies())) .Distinct() .Except(hasBeenAdded).Intersect(toBeGrouped) .ToHashSet(); //Get all the nodes in this current call depth var otherGroups = groupsToCreate.Except(dependencyGroup); var nodesInOtherGroups = otherGroups. SelectMany(x => x.Dependants.Union(x.Referencers)).ToHashSet(); var otherNodes = toBeGrouped.Union(currentLayer) .Union(nodesInOtherGroups) .Except(verticalCandidates) .ToHashSet(); var siblingDepsRelevantForNewNode = new HashSet<Node>(); //If any of the other nodes depends on the vertical candidate the candidate is removed and will be placed in a later iteration of this call (it is still left in toBeGrouped) foreach (var candidate in verticalCandidates.ToList()) { var otherNodesDependantOnCandidate = otherNodes.Where(x => x.IndirectlyDependsOn(candidate)).ToHashSet(); if (toBeShared.Contains(candidate) || otherNodesDependantOnCandidate.Any()) { verticalCandidates.Remove(candidate); toBeShared.Add(candidate); } } if (verticalCandidates.Any()) { toBeGrouped.ExceptWith(verticalCandidates); nextGroupTarget.ExceptWith(verticalCandidates); hasBeenAdded.UnionWith(verticalCandidates); var allDepsOfVerticalCandidates = verticalCandidates.SiblingDependencies().ToHashSet(); siblingDepsRelevantForNewNode = allDepsOfVerticalCandidates; var dependenciesOfNestedNodes = allDepsOfVerticalCandidates.Intersect(verticalCandidates).ToHashSet(); //Remove dependencies of nodes that are outside the new group that will be layouted foreach (var candidate in verticalCandidates) candidate.SiblingDependencies.RemoveWhere( x => !verticalCandidates.Contains(x)); //Remove all nodes from this levels stack that should be added by the recursive call // If they dont at all depend on each other!! List<Node> newNodes; if (!dependenciesOfNestedNodes.Any()) newNodes = new List<Node> {CreateHorizontalLayer(verticalCandidates)}; else newNodes = GroupNodes(verticalCandidates); newList.InsertRange(0, newNodes); } siblingDepsRelevantForNewNode.UnionWith( referencers.Union(dependants).SiblingDependencies()); siblingDepsRelevantForNewNode.ExceptWith( verticalCandidates.Union(referencers).Union(dependants)); var verticalNode = new VerticalSiblingHolderNode(newList); siblingDepsRelevantForNewNode.ForEach(x => verticalNode.SiblingDependencies.Add(x)); currentLayer.Add(verticalNode); } if (toBeShared.Any()) nextLayer = GetFacadeNodes(nextGroupTarget); else break; } nextGroupTarget = toBeGrouped; } else { toBeGrouped.ExceptWith(currentLayer); } } else toBeGrouped.ExceptWith(currentLayer); groupedNodes.Add(CreateHorizontalLayer(currentLayer)); } } //TODO: Add if only one layer //if (unreferenced.Any()) // newChildOrder.Add(CreateHorizontalLayer(unreferenced)); groupedNodes.Reverse(); return groupedNodes; }
public static void Applications( string appDisplayName, string appId, HashSet <string> permissionsSet, HashSet <string> userIdSet, string principalId, string homePage, string appOwnerOrganizationId) { try { var gremlinVertices = new List <GremlinVertex>(); var gremlinEdges = new List <GremlinEdge>(); var vertex = new GremlinVertex(appId, nameof(Models.BloodHound.Application)); vertex.AddProperty(CosmosDbHelper.CollectionPartitionKey, appId.GetHashCode()); vertex.AddProperty(nameof(Application.DisplayName), appDisplayName?.ToUpper() ?? string.Empty); vertex.AddProperty(nameof(permissionsSet), permissionsSet.ToDelimitedString(",") ?? string.Empty); vertex.AddProperty(nameof(principalId), principalId ?? string.Empty); vertex.AddProperty(nameof(homePage), homePage ?? string.Empty); vertex.AddProperty(nameof(appOwnerOrganizationId), appOwnerOrganizationId ?? string.Empty); gremlinVertices.Add(vertex); if (appOwnerOrganizationId != null) { var vertexDomain = new GremlinVertex(appOwnerOrganizationId, nameof(Models.BloodHound.Domain)); vertexDomain.AddProperty(CosmosDbHelper.CollectionPartitionKey, appOwnerOrganizationId.GetHashCode()); vertexDomain.AddProperty(nameof(Application.DisplayName), appOwnerOrganizationId.ToUpper()); gremlinVertices.Add(vertexDomain); gremlinEdges.Add( new GremlinEdge( appOwnerOrganizationId + appId, "Owner", appOwnerOrganizationId, appId, nameof(Models.BloodHound.Domain), nameof(Application), appOwnerOrganizationId.GetHashCode(), appId.GetHashCode() )); } if (permissionsSet.Any(_ => string.Equals(_, "Directory.AccessAsUser.All", StringComparison.OrdinalIgnoreCase))) { userIdSet.ForEach(userId => gremlinEdges.Add( new GremlinEdge( appId + userId, "AccessAsUser", appId, userId, nameof(Models.BloodHound.Application), nameof(User), appId.GetHashCode(), userId.GetHashCode() )) ); } CosmosDbHelper.RunImportVerticesBlock.Post(gremlinVertices); CosmosDbHelper.RunImportEdgesBlock.Post(gremlinEdges); } catch (Exception e) { Console.WriteLine(e); throw; } }
private void UpdateAddActors() { actorsToAdd.ForEach(AddActorNow); actorsToAdd.Clear(); }
public void Dispose() { _createdFiles.ForEach(File.Delete); }
private void UpdateInstructorCourses(string[] selectedCourses, Instructor instructor) { if (selectedCourses == null) { var condition = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; condition.Predicates.Add(Predicates.Field<CourseInstructor>(s => s.InstructorId, Operator.Eq, instructor.InstructorId)); instructor.Courses.ForEach(c => { condition.Predicates.Add(Predicates.Field<CourseInstructor>(s => s.CourseId, Operator.Eq, c.CourseId)); }); _connection.Delete<CourseInstructor>(condition); } else { var selectedCourseHs = new HashSet<string>(selectedCourses); var instructorCourses = new HashSet<int>( instructor.Courses.Select(s => s.CourseId)); var courseLst = new List<int>(); selectedCourses.ToList().ForEach(s => { courseLst.Add(Convert.ToInt32(s)); }); instructorCourses.ForEach(s => { courseLst.Add(s); }); foreach (var course in courseLst) { if (selectedCourseHs.Contains(course.ToString())) { if (!instructorCourses.Contains(course)) { var courseInstructor = new CourseInstructor { InstructorId = instructor.InstructorId, CourseId = course }; _connection.Insert(courseInstructor); } } else { if (instructorCourses.Contains(course)) { var condition = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; condition.Predicates.Add(Predicates.Field<CourseInstructor>(f => f.InstructorId, Operator.Eq, instructor.InstructorId)); condition.Predicates.Add(Predicates.Field<CourseInstructor>(f => f.CourseId, Operator.Eq, course)); _connection.Delete<CourseInstructor>(condition); } } } } }
public void RemoteRouter_must_deploy_dynamic_resizable_number_of_children_on_remote_host_driven_by_configuration() { var probe = CreateTestProbe(masterSystem); var router = masterSystem.ActorOf(FromConfig.Instance.Props(EchoActorProps), "elastic-blub"); var replies = CollectRouteePaths(probe, router, 5); var childred = new HashSet<ActorPath>(replies); childred.Should().HaveCount(2); childred.Select(x => x.Parent).Distinct().Should().HaveCount(1); childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress)); masterSystem.Stop(router); }
public void RemoteRouter_must_deploy_its_children_on_remote_host_driven_by_programmatic_definition() { var probe = CreateTestProbe(masterSystem); var router = masterSystem.ActorOf(new RemoteRouterConfig( new RoundRobinPool(2), new[] { new Address("akka.tcp", sysName, "127.0.0.1", port) }) .Props(EchoActorProps), "blub2"); var replies = CollectRouteePaths(probe, router, 5); var childred = new HashSet<ActorPath>(replies); childred.Should().HaveCount(2); childred.Select(x => x.Parent).Distinct().Should().HaveCount(1); childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress)); masterSystem.Stop(router); }
public void RemoteRouter_must_deploy_its_children_on_remote_host_driven_by_configuration() { var probe = CreateTestProbe(masterSystem); var router = masterSystem.ActorOf(new RoundRobinPool(2).Props(EchoActorProps), "blub"); var replies = CollectRouteePaths(probe, router, 5); var childred = new HashSet<ActorPath>(replies); childred.Should().HaveCount(2); childred.Select(x => x.Parent).Distinct().Should().HaveCount(1); childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress)); masterSystem.Stop(router); }
protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { var resourceKey = GetResourceKey(request.RequestUri, _varyHeaders, request); CacheableEntity cacheableEntity = null; var cacheControlHeader = new CacheControlHeaderValue { Private = true, MustRevalidate = true, MaxAge = TimeSpan.FromSeconds(0) }; if (request.Method == HttpMethod.Get) { var eTags = request.Headers.IfNoneMatch; var modifiedSince = request.Headers.IfModifiedSince; var anyEtagsFromTheClientExist = eTags.Any(); var doWeHaveAnyCacheableEntityForTheRequest = _eTagCacheDictionary.TryGetValue(resourceKey, out cacheableEntity); if (anyEtagsFromTheClientExist) { if (doWeHaveAnyCacheableEntityForTheRequest) { if (eTags.Any(x => x.Tag == cacheableEntity.EntityTag.Tag)) { var tempResp = new HttpResponseMessage(HttpStatusCode.NotModified); tempResp.Headers.CacheControl = cacheControlHeader; return tempResp; } } } else if (modifiedSince.HasValue) { if (doWeHaveAnyCacheableEntityForTheRequest) { if (cacheableEntity.IsValid(modifiedSince.Value)) { var tempResp = new HttpResponseMessage(HttpStatusCode.NotModified); tempResp.Headers.CacheControl = cacheControlHeader; return tempResp; } } } } HttpResponseMessage response; try { response = await base.SendAsync(request, cancellationToken); } catch (Exception ex) { response = request.CreateErrorResponse( HttpStatusCode.InternalServerError, ex); } if (response.IsSuccessStatusCode) { if (request.Method == HttpMethod.Get && !_eTagCacheDictionary.TryGetValue(resourceKey, out cacheableEntity)) { cacheableEntity = new CacheableEntity(resourceKey); cacheableEntity.EntityTag = GenerateETag(); cacheableEntity.LastModified = DateTimeOffset.Now; _eTagCacheDictionary.AddOrUpdate( resourceKey, cacheableEntity, (k, e) => cacheableEntity); } if (request.Method == HttpMethod.Put || request.Method == HttpMethod.Post || request.Method == HttpMethod.Delete) { HashSet<string> invalidCaches = new HashSet<string>(); invalidCaches.Add(GetRequestUri(request.RequestUri)); CacheInvalidationStore.ForEach( func => func(GetRequestUri(request.RequestUri)) .ForEach(uri => invalidCaches.Add(uri))); invalidCaches.ForEach(invalidCacheUri => { var cacheEntityKeys = _eTagCacheDictionary.Keys.Where( x => x.StartsWith( string.Format("{0}:", invalidCacheUri), StringComparison.InvariantCultureIgnoreCase)); cacheEntityKeys.ForEach(key => { if (!string.IsNullOrEmpty(key)) { CacheableEntity outVal = null; _eTagCacheDictionary.TryRemove(key, out outVal); } }); }); } else { response.Headers.CacheControl = cacheControlHeader; response.Headers.ETag = cacheableEntity.EntityTag; response.Content.Headers.LastModified = cacheableEntity.LastModified; _varyHeaders.ForEach( varyHeader => response.Headers.Vary.Add(varyHeader)); } } return response; }
public static IHasCustomProperties AddCustomProperties(this IHasCustomProperties obj, HashSet <CustomProperty> customProperties) { customProperties.ForEach(cp => obj.CustomProperties.Add(cp)); return(obj); }
private void LoadSprites() { loadedSprites.ForEach(s => s.Remove()); loadedSprites.Clear(); var contentPackages = GameMain.Config.SelectedContentPackages.ToList(); #if !DEBUG var vanilla = GameMain.VanillaContent; if (vanilla != null) { contentPackages.Remove(vanilla); } #endif foreach (var contentPackage in contentPackages) { foreach (var file in contentPackage.Files) { if (file.Path.EndsWith(".xml")) { XDocument doc = XMLExtensions.TryLoadXml(file.Path); if (doc != null && doc.Root != null) { LoadSprites(doc.Root); } } } } void LoadSprites(XElement element) { element.Elements("sprite").ForEach(s => CreateSprite(s)); element.Elements("Sprite").ForEach(s => CreateSprite(s)); element.Elements("backgroundsprite").ForEach(s => CreateSprite(s)); element.Elements("BackgroundSprite").ForEach(s => CreateSprite(s)); element.Elements("brokensprite").ForEach(s => CreateSprite(s)); element.Elements("BrokenSprite").ForEach(s => CreateSprite(s)); element.Elements("containedsprite").ForEach(s => CreateSprite(s)); element.Elements("ContainedSprite").ForEach(s => CreateSprite(s)); element.Elements("inventoryicon").ForEach(s => CreateSprite(s)); element.Elements("InventoryIcon").ForEach(s => CreateSprite(s)); //decorativesprites don't necessarily have textures (can be used to hide/disable other sprites) element.Elements("decorativesprite").ForEach(s => { if (s.Attribute("texture") != null) { CreateSprite(s); } }); element.Elements("DecorativeSprite").ForEach(s => { if (s.Attribute("texture") != null) { CreateSprite(s); } }); element.Elements().ForEach(e => LoadSprites(e)); } void CreateSprite(XElement element) { string spriteFolder = ""; string textureElement = element.GetAttributeString("texture", ""); // TODO: parse and create? if (textureElement.Contains("[GENDER]") || textureElement.Contains("[HEADID]") || textureElement.Contains("[RACE]")) { return; } if (!textureElement.Contains("/")) { var parsedPath = element.ParseContentPathFromUri(); spriteFolder = Path.GetDirectoryName(parsedPath); } // Uncomment if we do multiple passes -> there can be duplicates //string identifier = Sprite.GetID(element); //if (loadedSprites.None(s => s.ID == identifier)) //{ // loadedSprites.Add(new Sprite(element, spriteFolder)); //} loadedSprites.Add(new Sprite(element, spriteFolder)); } }
public void RemoteRouter_must_deploy_remote_routers_based_on_configuration() { var probe = CreateTestProbe(masterSystem); var router = masterSystem.ActorOf(FromConfig.Instance.Props(EchoActorProps), "remote-blub"); router.Path.Address.Should().Be(intendedRemoteAddress); var replies = CollectRouteePaths(probe, router, 5); var childred = new HashSet<ActorPath>(replies); childred.Should().HaveCount(2); var parents = childred.Select(x => x.Parent).Distinct().ToList(); parents.Should().HaveCount(1); parents.Head().Should().Be(router.Path); childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress)); masterSystem.Stop(router); }
public static bool Invoke(Message message) { var split = message.Content.Split(' '); var root = split[0]; foreach (var info in AllCommands) { if (info.ValidateStrings?.Any(s => s == root) == true || info.Regex?.IsMatch(root) == true || info.MethodInfo.Name == root) { if (info.RequireAdmin && !Config.Instance.GetPlayerConfig(message.Sender).Admin) { throw new DoudizhuCommandParseException("你不是管理"); } var reqParameters = info.MethodInfo.GetParameters().SkipInject().ToArray(); var parameters = split.Skip(1).ToArray(); if (parameters.Length > reqParameters.Length) { throw new DoudizhuCommandParseException("参数数量过多"); } if (parameters.Length < reqParameters.Length - reqParameters.Count(p => p.IsOptional)) { throw new DoudizhuCommandParseException("参数不全"); } // input check for (var index = 0; index < parameters.Length; index++) { var param = parameters[index]; var reqparam = reqParameters[index]; if (string.IsNullOrWhiteSpace(param)) { throw new DoudizhuCommandParseException($"参数{index}为空, 需求为{GetParamHelp(reqparam)}"); } if (reqparam.ParameterType == typeof(Number) && !Number.TryParse(param, out _)) { throw new DoudizhuCommandParseException($"参数{index}不是数字, 需求为{GetParamHelp(reqparam)}"); } } var game = new Lazy <Game>(() => GamesManager.Games[message.Group]); var currentPlayer = new Lazy <Player>(() => game.Value.CurrentPlayer); var senderPlayer = new Lazy <Player>(() => game.Value.GetPlayer(message.Sender)); // attrib check var stateOnly = info.MethodInfo.GetCustomAttribute <StateOnlyAttribute>(); if (stateOnly != null) { if (!GamesManager.Games.ContainsKey(message.Group)) { throw new DoudizhuCommandParseException("该群没有游戏."); } if (stateOnly.GameState != game.Value.State) { throw new DoudizhuCommandParseException($"该命令需求游戏在以下状态{stateOnly.GameState}."); //TODO } } var playerOnly = info.MethodInfo.GetCustomAttribute <PlayerOnlyAttribute>(); if (playerOnly != null) { if (!GamesManager.Games.ContainsKey(message.Group)) { throw new DoudizhuCommandParseException("该群没有游戏."); } switch (playerOnly.PlayerState) { case PlayerState.InGame: if (senderPlayer.Value == null) { throw new DoudizhuCommandParseException("该命令需求你在游戏中."); } break; case PlayerState.CurrentPlayer: if (senderPlayer.Value == null || currentPlayer.Value != senderPlayer.Value) { throw new DoudizhuCommandParseException("该命令需求你是当前玩家."); } break; case PlayerState.ChooseLandlordPlayer: if (senderPlayer.Value != game.Value.GetPlayerByIndex(((ChooseLandlordData)game.Value.StateData).LandlordIndex)) { throw new DoudizhuCommandParseException("该命令需求你是当前玩家."); } break; default: throw new ArgumentOutOfRangeException(); } } // build params var iReqParams = info.MethodInfo.GetParameters(); Debug.Assert(iReqParams.Count(obj => obj.IsAttributeDefined <InjectAttribute>()) == 0 || iReqParams.Length == 0 || (iReqParams.First().IsAttributeDefined <InjectAttribute>() && iReqParams.Select((param, index) => new { param, index }) .Where(obj => obj.param.IsAttributeDefined <InjectAttribute>()) .Select(obj => obj.index) .ToArray().IsSequential(i => i))); var list = new List <object>(); var callbacks = new HashSet <Action>(); foreach (var pinfo in iReqParams.Where(p => p.IsAttributeDefined <InjectAttribute>())) { if (pinfo.ParameterType == typeof(Config)) { list.Add(Config.Instance); callbacks.Add(Config.Save); continue; } if (pinfo.ParameterType == typeof(Game)) { if (!GamesManager.Games.ContainsKey(message.Group)) { throw new DoudizhuCommandParseException("该群没有游戏, 请先使用[创建游戏]."); } list.Add(game.Value); continue; } if (pinfo.ParameterType == typeof(PlayerConfig)) { list.Add(Config.Instance.GetPlayerConfig(message.Sender)); callbacks.Add(Config.Save); continue; } if (pinfo.ParameterType.IsSubclassOf(typeof(StateData))) { list.Add(game.Value.StateData); continue; } if (pinfo.ParameterType == typeof(TargetSender)) { list.Add(message.Group.GetGroupSender()); continue; } if (pinfo.ParameterType == typeof(Player)) { list.Add(senderPlayer.Value); continue; } var attrib = pinfo.GetCustomAttribute <InjectAttribute>(); switch (attrib.Injectwhat) { case Injects.PlayerID: list.Add(message.Sender); continue; case Injects.GameID: list.Add(message.Group); continue; } Debug.Assert(1 + 1 != 2); } for (var index = 0; index < reqParameters.Length; index++) { var param = parameters.SafeGet(index); var reqparam = reqParameters[index]; if (reqparam.IsOptional && param == null) { list.Add(Type.Missing); continue; } if (reqparam.ParameterType == typeof(Number)) { list.Add(Number.Parse(param)); continue; } if (reqparam.ParameterType == typeof(string)) { list.Add(param); continue; } throw new NotSupportedException("Fork 您"); } var result = info.MethodInfo.Invoke(Activator.CreateInstance(info.MethodInfo.DeclaringType), list.ToArray()); if (result == null) { return(true); } switch (result) { case string s: message.Group.GetGroupSender().Send(s); break; default: throw new NotSupportedException("Fork 您"); } callbacks.ForEach(c => c()); // TODO return(true); } } return(false); }
void InitializeProducts(ISession session) { var products = new HashSet <Product> { new Product { Name = "Hiking Backpack", ProductCode = "Backpack1_1", Category = _categories.First(x => x.Name == "Backpacks"), Price = 50 }, new Product { Name = "Wide-base Backpack", ProductCode = "Backpack2_1", Category = _categories.First(x => x.Name == "Backpacks"), Price = 50 }, new Product { Name = "Short Backpack", ProductCode = "Backpack3_1", Category = _categories.First(x => x.Name == "Backpacks"), Price = 40 }, new Product { Name = "Mountaineering Backpack", ProductCode = "Backpack4_1", Category = _categories.First(x => x.Name == "Backpacks"), Price = 130 }, new Product { Name = "Sprint 500 Bike", ProductCode = "Bike1_1", Category = _categories.First(x => x.Name == "Bikes"), Price = 460 }, new Product { Name = "Escape 3.0 Bike", ProductCode = "Bike2_1", Category = _categories.First(x => x.Name == "Bikes"), Price = 680 }, new Product { Name = "Scoop Cruiser", ProductCode = "Bike3_1", Category = _categories.First(x => x.Name == "Bikes"), Price = 380 }, new Product { Name = "Sierra Leather Hiking Boots", ProductCode = "Boots1_1", Category = _categories.First(x => x.Name == "Boots"), Price = 90 }, new Product { Name = "Rainier Leather Hiking Boots", ProductCode = "Boots2_1", Category = _categories.First(x => x.Name == "Boots"), Price = 110 }, new Product { Name = "Cascade Fur-Lined Hiking Boots", ProductCode = "Boots3_1", Category = _categories.First(x => x.Name == "Boots"), Price = 130 }, new Product { Name = "Adirondak Fur-Lined Hiking Boots", ProductCode = "Boots4_1", Category = _categories.First(x => x.Name == "Boots"), Price = 60 }, new Product { Name = "Olympic Hiking Boots", ProductCode = "Boots5_1", Category = _categories.First(x => x.Name == "Boots"), Price = 90 }, new Product { Name = "Weathered Lether Baseball Cap", ProductCode = "Hat1_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 13 }, new Product { Name = "Colorful Straw hat", ProductCode = "Hat2_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 10 }, new Product { Name = "Summertime Straw Hat", ProductCode = "Hat3_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 23 }, new Product { Name = "Bicycle Safety Helmet", ProductCode = "Helmet1_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 80 }, new Product { Name = "Fusion Helmet", ProductCode = "Helmet2_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 150 }, new Product { Name = "Fire Helmet", ProductCode = "Helmet3_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 125 }, new Product { Name = "Bicycle Safety Helmet", ProductCode = "Helmet1_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 80 }, new Product { Name = "Sentinel Locking Carbiner", ProductCode = "Carbiner1_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 16 }, new Product { Name = "Guardian Locking Carbiner", ProductCode = "Carbiner2_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 6 }, new Product { Name = "Trailhead Locking Carbiner", ProductCode = "Carbiner3_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 80 }, new Product { Name = "Traiguide Compass", ProductCode = "Compass1_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 30 }, new Product { Name = "Northstar Compass", ProductCode = "Compass2_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 18 }, new Product { Name = "Sundial Compass", ProductCode = "Compass3_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 12 }, new Product { Name = "Polar Start Compass", ProductCode = "Compass4_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 15 }, new Product { Name = "Compass Necklace", ProductCode = "Compass5_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 16 }, new Product { Name = "Battery Operated Flashlight", ProductCode = "Flashlight1_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 8 }, new Product { Name = "Heavy-Duty Flashlight", ProductCode = "Flashlight2_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 13 }, new Product { Name = "Retro Flashlight", ProductCode = "Flashlight3_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 24 }, new Product { Name = "Northwind Traders Arizona Sunglasses", ProductCode = "Sunglasses1_1", Category = _categories.First(x => x.Name == "Sunglasses"), Price = 35 }, new Product { Name = "Northwind Traders Eclipse Sunglasses", ProductCode = "Sunglasses2_1", Category = _categories.First(x => x.Name == "Sunglasses"), Price = 55 }, }; products.ForEach(product => session.Save(product)); }
public override void LoadModelParameters(string parameters) { var urlParser = new UrlParser(parameters); UpdateAvailableIndexes(); ClearCurrentQuery(); if (urlParser.GetQueryParam("mode") == "dynamic") { var collection = urlParser.GetQueryParam("collection"); IsDynamicQuery = true; DatabaseCommands.GetTermsAsync("Raven/DocumentsByEntityName", "Tag", "", 100) .ContinueOnSuccessInTheUIThread(collections => { DynamicOptions.Match(new[] { "AllDocs" }.Concat(collections).ToArray()); string selectedOption = null; if (!string.IsNullOrEmpty(collection)) { selectedOption = DynamicOptions.FirstOrDefault(s => s.Equals(collection)); } if (selectedOption == null) { selectedOption = DynamicOptions[0]; } DynamicSelectedOption = selectedOption; DocumentsResult.SetChangesObservable(null); }); return; } IsDynamicQuery = false; var newIndexName = urlParser.Path.Trim('/'); if (string.IsNullOrEmpty(newIndexName)) { if (AvailableIndexes.Any()) { NavigateToIndexQuery(AvailableIndexes.FirstOrDefault()); return; } } IndexName = newIndexName; DatabaseCommands.GetIndexAsync(IndexName) .ContinueOnUIThread(task => { if (task.IsFaulted || task.Result == null) { if (AvailableIndexes.Any()) { NavigateToIndexQuery(AvailableIndexes.FirstOrDefault()); } else { NavigateToIndexesList(); } return; } var fields = task.Result.Fields; QueryIndexAutoComplete = new QueryIndexAutoComplete(fields, IndexName, QueryDocument); var regex1 = new Regex(@"(?:SpatialIndex\.Generate|SpatialGenerate)"); var regex2 = new Regex(@"(?:SpatialIndex\.Generate|SpatialGenerate)\(@?\""([^\""]+)\"""); var strs = task.Result.Maps.ToList(); if (task.Result.Reduce != null) { strs.Add(task.Result.Reduce); } var legacyFields = new HashSet <string>(); foreach (var map in task.Result.Maps) { var count = regex1.Matches(map).Count; var matches = regex2.Matches(map).Cast <Match>().Select(x => x.Groups[1].Value).ToList(); if (matches.Count < count) { legacyFields.Add(Constants.DefaultSpatialFieldName); } matches.ForEach(x => legacyFields.Add(x)); } var spatialFields = task.Result.SpatialIndexes .Select(x => new SpatialQueryField { Name = x.Key, IsGeographical = x.Value.Type == SpatialFieldType.Geography, Units = x.Value.Units }) .ToList(); legacyFields.ForEach(x => spatialFields.Add(new SpatialQueryField { Name = x, IsGeographical = true, Units = SpatialUnits.Kilometers })); UpdateSpatialFields(spatialFields); HasTransform = !string.IsNullOrEmpty(task.Result.TransformResults); DocumentsResult.SetChangesObservable( d => d.IndexChanges .Where(n => n.Name.Equals(indexName, StringComparison.InvariantCulture)) .Select(m => Unit.Default)); SetSortByOptions(fields); RestoreHistory(); }).Catch(); }
/// <summary> /// Удаляет все возможное столбцы /// </summary> public void RemoveAll() { AllAlorColumn.ForEach(Remove); }
private void UpdateRemoveActors() { actorsToRemove.ForEach(RemoveActorNow); actorsToRemove.Clear(); }
private void LoadSprites() { loadedSprites.ForEach(s => s.Remove()); loadedSprites.Clear(); //foreach (string filePath in ContentPackage.GetAllContentFiles(GameMain.SelectedPackages)) //{ // XDocument doc = XMLExtensions.TryLoadXml(filePath); // if (doc != null && doc.Root != null) // { // LoadSprites(doc.Root); // } //} foreach (string filePath in Directory.GetFiles("Content/", "*.xml", SearchOption.AllDirectories)) { XDocument doc = XMLExtensions.TryLoadXml(filePath); if (doc != null && doc.Root != null) { LoadSprites(doc.Root); } } void LoadSprites(XElement element) { element.Elements("sprite").ForEach(s => CreateSprite(s)); element.Elements("Sprite").ForEach(s => CreateSprite(s)); element.Elements("backgroundsprite").ForEach(s => CreateSprite(s)); element.Elements("BackgroundSprite").ForEach(s => CreateSprite(s)); element.Elements("brokensprite").ForEach(s => CreateSprite(s)); element.Elements("BrokenSprite").ForEach(s => CreateSprite(s)); element.Elements("containedsprite").ForEach(s => CreateSprite(s)); element.Elements("ContainedSprite").ForEach(s => CreateSprite(s)); element.Elements("inventoryicon").ForEach(s => CreateSprite(s)); element.Elements("InventoryIcon").ForEach(s => CreateSprite(s)); //decorativesprites don't necessarily have textures (can be used to hide/disable other sprites) element.Elements("decorativesprite").ForEach(s => { if (s.Attribute("texture") != null) { CreateSprite(s); } }); element.Elements("DecorativeSprite").ForEach(s => { if (s.Attribute("texture") != null) { CreateSprite(s); } }); element.Elements().ForEach(e => LoadSprites(e)); } void CreateSprite(XElement element) { string spriteFolder = ""; string textureElement = element.GetAttributeString("texture", ""); // TODO: parse and create if (textureElement.Contains("[GENDER]") || textureElement.Contains("[HEADID]") || textureElement.Contains("[RACE]")) { return; } if (!textureElement.Contains("/")) { spriteFolder = Path.GetDirectoryName(element.ParseContentPathFromUri()); } // Uncomment if we do multiple passes -> there can be duplicates //string identifier = Sprite.GetID(element); //if (loadedSprites.None(s => s.ID == identifier)) //{ // loadedSprites.Add(new Sprite(element, spriteFolder)); //} loadedSprites.Add(new Sprite(element, spriteFolder)); } }
private void visitCore() { var now = App.TimeSource.UTCNow; var toDelete = new HashSet <T>(m_Comparer); var ttlSec = TimeLimitSec; var maxCount = SizeLimit; var overage = 0; if (maxCount > 0) { overage = m_Data.Sum(d => d.m_ApproximateCount) - maxCount; } var overagePerBucket = overage / m_Data.Length; //equal distribution is assumed per getBucket() for (var i = 0; i < m_Data.Length; i++) { var dict = m_Data[i]; var mustLock = (now - dict.m_LastLock).TotalMinutes > 5; if (!mustLock) { if (!Monitor.TryEnter(dict)) { continue; } } else { Monitor.Enter(dict); } try { dict.m_LastLock = now;//lock taken now toDelete.Clear(); if (ttlSec > 0) //impose time limit { dict.Where(kvp => ((now - kvp.Value).TotalSeconds > ttlSec)) .ForEach(kvp => toDelete.Add(kvp.Key)); } //impose count limit if (overagePerBucket > toDelete.Count) { var timeSorted = dict.OrderBy(kvp => kvp.Value);//ascending = older first foreach (var item in timeSorted) { if (overagePerBucket > toDelete.Count) { toDelete.Add(item.Key); } else { break; } } } toDelete.ForEach(k => dict.Remove(k)); dict.m_ApproximateCount = dict.Count; } finally { Monitor.Exit(dict); } } }
public static void UpdateGui(HashSet <CardInstance> cards, bool sendRed) { cards.ForEach(c => c.SendCardUpdated(sendRed)); }
/// <summary> /// Process the remainder of the beams /// </summary> /// <param name="Beams">The full list of beams to process</param> /// <param name="Members">The empty list of members</param> private void ProcessBeams(HashSet<Beam> Beams, HashSet<Member> Members) { int memberCount = Members.Count; double totalBeams = Beams.Count; // Process the remaining beams while (Beams.Any()) { Beam currentBeam = Beams.First(); Member newMember; List<Beam> beams; beams = GatherMemberBeams(currentBeam, false); beams.AddRange(GatherMemberBeams(currentBeam, true)); beams = new HashSet<Beam>(beams).ToList(); // Generate new member. This needs to be generated with the model beams and not with the cloned list! newMember = this.GenerateNewMember(++memberCount, this.StaadModel.Beams.Where(o => beams.Contains(o)).ToList()); Members.Add(newMember); // Remove processed beam and node. This needs to be removed from the cloned list and not the model! beams.ForEach(b => Beams.Remove(b)); // Fire status update event this.OnStatusUpdate(new MemberGeneratorStatusUpdateEventArgs("Generating members...", 1 - (Beams.Count / totalBeams), newMember)); // Select the latest member if required if (SelectIndividualMembersDuringCreation) this.StaadModel.Staad.Geometry.SelectMultipleBeams(newMember.Beams.Select(o => o.ID).ToArray()); } }
public void RemoveUnusedNodes() { _statsWithoutModifiers.ForEach(RemoveUnusedStatGraphNodes); SelectRemovableStats() .ToList().ForEach(Remove); }
//private DependencyGraph Sample(DependencyGraph aGraph, List<OutputEntry> aWarnings, int percent) //{ // var rand = new Random(); // var selected = new HashSet<Library>(aWarnings.SelectMany(w => w.Projects) // .Concat(aGraph.Vertices.Where(v => rand.Next(100) < percent))); // var result = new DependencyGraph(); // result.AddVertexRange(selected); // result.AddEdgeRange(aGraph.Edges.Where(e => selected.Contains(e.Source) && selected.Contains(e.Target))); // return result; //} private string GenerateDot() { var result = new DotStringBuilder("Dependencies"); result.AppendConfig("concentrate", "true"); int clusterIndex = 1; foreach (var group in graph.Vertices.Where(a => a.GroupElement != null) .GroupBy(a => a.GroupElement.Name)) { var groupName = @group.Key; var clusterName = "cluster" + clusterIndex++; var groupInfo = new GroupInfo(clusterName + "_top", clusterName + "_bottom"); groupInfos.Add(groupName, groupInfo); result.StartSubgraph(clusterName); result.AppendConfig("label", groupName); result.AppendConfig("color", "lightgray"); result.AppendConfig("style", "filled"); result.AppendConfig("fontsize", "20"); result.AppendSpace(); AppendGroupNode(result, "min", groupInfo.TopNode); result.AppendSpace(); var projs = new HashSet<Library>(group); projs.ForEach(a => AppendProject(result, a)); result.AppendSpace(); graph.Edges.Where(e => projs.Contains(e.Source) && projs.Contains(e.Target)) .ForEach(d => AppendDependency(result, d)); result.AppendSpace(); AppendGroupNode(result, "max", groupInfo.BottomNode); result.EndSubgraph(); result.AppendSpace(); } graph.Vertices.Where(a => a.GroupElement == null) .ForEach(a => AppendProject(result, a)); result.AppendSpace(); graph.Edges.Where(e => AreFromDifferentGroups(e.Source, e.Target)) .ForEach(d => AppendDependency(result, d)); result.AppendSpace(); AddDependenciesBetweenGroups(result); return result.ToString(); }
private void RunCustomTool() { _projectItems.ForEach(projectItem => projectItem.RunCustomTool()); _projectItems = new HashSet <EnvDTE.ProjectItem>(); }
public void RemoteRouter_must_let_remote_deployment_be_overridden_by_local_configuration() { var probe = CreateTestProbe(masterSystem); var router = masterSystem.ActorOf( new RoundRobinPool(2) .Props(EchoActorProps) .WithDeploy(new Deploy(new RemoteScope(intendedRemoteAddress))), "local-blub"); router.Path.Address.ToString().Should().Be(string.Format("akka://{0}", masterSystem.Name)); var replies = CollectRouteePaths(probe, router, 5); var childred = new HashSet<ActorPath>(replies); childred.Should().HaveCount(2); var parents = childred.Select(x => x.Parent).Distinct().ToList(); parents.Should().HaveCount(1); parents.Head().Address.Should().Be(new Address("akka.tcp", sysName, "127.0.0.1", port)); childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress)); masterSystem.Stop(router); }
internal void PostConfigureServices(ConfigureServicesContext context) { _postConfigureServiceActions.ForEach(a => a(context)); }
protected override void OnHandle(TCommand command) { string title = command.Title; var authorIdentity = command.UserName; using (var uow = UowFactory.Create()) { Validate(command, uow); var revisor = uow.Context .Query <Entities.Security.User>() .SingleOrDefault(u => u.UserName == authorIdentity); var revisorName = revisor.Person != null?revisor.Person.GetFullName() : revisor.UserName; var postStatus = Entities.Posts.PostStatus.Saved; // TODO: figure out the next status, based on user and workflow config var postFormat = Entities.Posts.ContentFormats.Html; var postTags = (command.TagsCommaSeparated ?? "").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(t => t.Trim()) .ToList(); var site = uow.Context.FindById <Entities.Sites.Site>(command.SiteId); var tagEntities = new HashSet <Tag>(); foreach (var tagName in postTags) { var tagEntity = uow.Context.Query <Tag>().FirstOrDefault(t => t.Name == tagName); if (tagEntity == null) { // TODO: send AddTag command instead tagEntity = new Tag { Name = tagName, Site = site }; uow.Context.Add(tagEntity); } tagEntities.Add(tagEntity); } var post = uow.Context.FindById <Entities.Posts.Post>(command.PostId); if (post == null) { throw new EntityNotFoundException(string.Format("Post with Id: {0} not found", command.PostId)); } if (post.Site.Id != command.SiteId || post.Zone.Id != command.ZoneId) { throw new Exception("Site/Zone are not valid"); } DateTime?nowDate = DateTime.Now; post.Name = command.Title; post.Title = command.Title; post.MetaTitle = command.MetaTitle ?? title; post.MetaDescription = command.MetaDescription; post.PublishDate = postStatus == PostStatus.Published ? nowDate : null; post.EffectiveDate = postStatus == PostStatus.Published ? nowDate : null; post.Status = postStatus; post.Format = postFormat; post.IsPrivate = command.IsPrivate; post.IsDiscussionEnabled = command.IsRatingEnabled; post.IsAnonymousCommentAllowed = command.IsAnonymousCommentAllowed; post.IsRatingEnabled = command.IsRatingEnabled; post.Tags.Clear(); tagEntities .ForEach(tag => post.Tags.Add(tag)); var newRevisionRequired = true; // TODO: if (newRevisionRequired) { var postRevision = post.Revise(); command.Links .ForEach(l => postRevision.Post.Links.Add(new PostLink { Type = l.Key, Ref = l.Value, Post = postRevision.Post })); } else { post.Links.Clear(); command.Links .ForEach(l => post.Links.Add(new PostLink { Type = l.Key, Ref = l.Value, Post = post })); } post.LatestRevision.Summary = command.ContentSummary; post.LatestRevision.Body = command.Content; post.LatestRevision.Reviser = revisor; post.LatestRevision.Author = revisorName; uow.Context.Update(post); uow.Complete(); } }
public void RemoteRouter_must_let_remote_deployment_be_overridden_by_remote_configuration() { var probe = CreateTestProbe(masterSystem); var router = masterSystem.ActorOf( new RoundRobinPool(2) .Props(EchoActorProps) .WithDeploy(new Deploy(new RemoteScope(intendedRemoteAddress))), "remote-override"); router.Path.Address.Should().Be(intendedRemoteAddress); var replies = CollectRouteePaths(probe, router, 5); var childred = new HashSet<ActorPath>(replies); childred.Should().HaveCount(4); var parents = childred.Select(x => x.Parent).Distinct().ToList(); parents.Should().HaveCount(1); parents.Head().Address.Should().Be(router.Path.Address); childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress)); masterSystem.Stop(router); }
public static void Main(string[] args) { StringReader reader = new StringReader(File.ReadAllText("input.txt")); HashSet <Point> points = new HashSet <Point>(); int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; while (reader.Peek() != -1) { var match = Regex.Match(reader.ReadLine(), POINT_REGEX); Point p = new Point(int.Parse(match.Groups[1].Value), int.Parse(match.Groups[2].Value), int.Parse(match.Groups[3].Value), int.Parse(match.Groups[4].Value)); points.Add(p); } int time; for (time = 1; true; time += 1) { points.ForEach(p => p.move()); int maxDistance = -1; foreach (Point p1 in points) { int curMinDis = int.MaxValue; foreach (Point p2 in points) { if (p1 != p2) { if (curMinDis > p1.distanceTo(p2)) { curMinDis = p1.distanceTo(p2); } } } if (maxDistance < curMinDis) { maxDistance = curMinDis; } } if (maxDistance <= 2) { break; } } foreach (Point p in points) { if (p.x < minX) { minX = p.x; } else if (p.x > maxX) { maxX = p.x; } if (p.y < minY) { minY = p.y; } else if (p.y > maxY) { maxY = p.y; } } char[,] display = new char[Math.Abs(maxY - minY) + 1, Math.Abs(maxX - minX) + 1]; for (int i = minX; i <= maxX; i += 1) { for (int j = minY; j <= maxY; j += 1) { display[j - minY, i - minX] = ' '; } } foreach (Point p in points) { display[p.y - minY, p.x - minX] = '#'; } for (int i = 0; i < display.GetLength(0); i += 1) { for (int j = 0; j < display.GetLength(1); j += 1) { Console.Write(display[i, j]); } Console.WriteLine(); } Console.WriteLine("The points are closest at time: {0}.", time); Console.WriteLine("Min X: {0}, Max X: {1}, Min Y: {2}, Max Y: {3}", minX, maxX, minY, maxY); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); }
/// <summary> /// Creates a minimum spanning tree from a set of weighted edges. /// The input are edges ((TVertex, TVertex), TWeight) of a graph. /// The output are a subset of these edges which form a minimum spanning tree. /// The type of the weight (TWeight) needs to be IComparable. /// </summary> public static IEnumerable <Tup <Pair <TVertex>, TWeight> > Create <TVertex, TWeight>( IEnumerable <Tup <Pair <TVertex>, TWeight> > edges ) where TWeight : IComparable <TWeight> { Requires.NotNull(edges); Report.BeginTimed("create vertex set"); var vertexSet = new HashSet <TVertex>(edges.SelectMany(e => e.E0)); Report.End(); if (vertexSet.Count < 2) { yield break; } //compare function Func <KeyValuePair <TWeight, TVertex>, KeyValuePair <TWeight, TVertex>, int> compare = (kvp0, kvp1) => kvp0.Key.CompareTo(kvp1.Key); // init per-vertex edge priority queues Report.BeginTimed("init per-vertex edge priority queues"); //var v2es = new Dictionary<TVertex, PriorityQueue<TWeight, TVertex>>(); //vertexSet.ForEach(v => v2es[v] = new PriorityQueue<TWeight, TVertex>()); var v2es = new Dictionary <TVertex, List <KeyValuePair <TWeight, TVertex> > >(); vertexSet.ForEach(v => v2es[v] = new List <KeyValuePair <TWeight, TVertex> >()); foreach (var e in edges) { //v2es[e.E0.E0].Enqueue(e.E1, e.E0.E1); //v2es[e.E0.E1].Enqueue(e.E1, e.E0.E0); v2es[e.E0.E0].HeapEnqueue(compare, new KeyValuePair <TWeight, TVertex>(e.E1, e.E0.E1)); v2es[e.E0.E1].HeapEnqueue(compare, new KeyValuePair <TWeight, TVertex>(e.E1, e.E0.E0)); } Report.End(); // mst var mst = new HashSet <TVertex>(); Action <TVertex> move = v => { vertexSet.Remove(v); mst.Add(v); }; // build minimum spanning tree using Prim's algorithm Report.BeginTimed("build mst"); move(vertexSet.First()); while (vertexSet.Count > 0) { var candidateQueues = mst .Where(v => v2es.ContainsKey(v)) .Select(v => Tup.Create(v, v2es[v])).Where(q => !q.E1.IsEmptyOrNull()) ; foreach (var q in candidateQueues) { //while (!q.E1.IsEmptyOrNull() && mst.Contains(q.E1.Peek())) while (!q.E1.IsEmptyOrNull() && mst.Contains(q.E1[0].Value)) { //q.E1.Dequeue(); q.E1.HeapDequeue(compare); } if (q.E1.IsEmptyOrNull()) { v2es.Remove(q.E0); } } var best = candidateQueues //.Select(q => Tup.Create(q.E0, q.E1.PeekKeyAndValue())) .Select(q => Tup.Create(q.E0, q.E1[0])) .Min((a, b) => a.E1.Key.CompareTo(b.E1.Key) < 0) ; //v2es[best.E0].Dequeue(); v2es[best.E0].HeapDequeue(compare); move(best.E1.Value); yield return(Tup.Create(Pair.Create(best.E0, best.E1.Value), best.E1.Key)); } Report.End(); }
void IStoreListener.OnInitializeFailed(InitializationFailureReason error) { _list.ForEach(l => l.OnInitializeFailed(error)); }
public void Dispose() { _target._suspendedNotifications = null; _properties.ForEach(x => _target.OnPropertyChanged(x)); }
/// <summary> /// Publishes the mod to the workshop /// </summary> /// <returns></returns> public bool Publish() { bool newMod = false; if (!Directory.Exists(m_modPath)) { MySandboxGame.Log.WriteLineAndConsole(string.Format("Directory does not exist {0}. Wrong option?", m_modPath ?? string.Empty)); return(false); } // Upload/Publish #if SE if (((IMod)this).ModId == 0) #else if (m_modId == 0) #endif { MySandboxGame.Log.WriteLineAndConsole(string.Format("Uploading new {0}: {1}", m_type.ToString(), m_title)); newMod = true; #if SE if (m_modId.Length == 0) { m_modId = new WorkshopId[1] { new WorkshopId(0, MyGameService.GetDefaultUGC().ServiceName) } } ; #endif } else { MySandboxGame.Log.WriteLineAndConsole(string.Format("Updating {0}: {1}; {2}", m_type.ToString(), m_modId.AsString(), m_title)); } // Add the global game filter for file extensions _globalIgnoredExtensions?.ForEach(s => m_ignoredExtensions.Add(s)); // Process Tags ProcessTags(); PrintItemDetails(); MyWorkshopItem[] items = null; if (m_dryrun) { MySandboxGame.Log.WriteLineAndConsole("DRY-RUN; Publish skipped"); return(true); } else { if (_publishMethod != null) { InjectedMethod.ChangeLog = m_changelog; #if SE var result = _publishMethod(m_modPath, m_title, m_description, m_modId, (MyPublishedFileVisibility)(m_visibility ?? PublishedFileVisibility.Private), m_tags, m_ignoredExtensions, m_ignoredPaths, m_dlcs, out items); PublishSuccess = result.Item1 == MyGameServiceCallResult.OK; if (PublishSuccess) { m_modId = items.Select(i => new WorkshopId(i.Id, i.ServiceName)).ToArray(); } #else m_modId = _publishMethod(m_modPath, m_title, m_description, m_modId, (MyPublishedFileVisibility)(m_visibility ?? PublishedFileVisibility.Private), m_tags, m_ignoredExtensions, m_ignoredPaths); #endif } else { MySandboxGame.Log.WriteLineAndConsole(string.Format(Constants.ERROR_Reflection, "PublishItemBlocking")); } // SE libraries don't support updating dependencies, so we have to do that separately WorkshopHelper.PublishDependencies(m_modId, m_deps, m_depsToRemove); } if (((IMod)this).ModId == 0 || !PublishSuccess) { MySandboxGame.Log.WriteLineAndConsole("Upload/Publish FAILED!"); return(false); } else { MySandboxGame.Log.WriteLineAndConsole(string.Format("Upload/Publish success: {0}", m_modId.AsString())); if (newMod) { #if SE if (MyWorkshop.GenerateModInfo(m_modPath, items, MyGameService.UserId)) #else if (MyWorkshop.UpdateModMetadata(m_modPath, m_modId, MySteam.UserId)) #endif { MySandboxGame.Log.WriteLineAndConsole(string.Format("Create modinfo.sbmi success: {0}", m_modId.AsString())); } else { MySandboxGame.Log.WriteLineAndConsole(string.Format("Create modinfo.sbmi FAILED: {0}", m_modId.AsString())); return(false); } } } return(true); } bool FillPropertiesFromPublished() { var results = new List <MyWorkshopItem>(); #if SE if (MyWorkshop.GetItemsBlockingUGC(m_modId.ToList(), results)) #else if (MyWorkshop.GetItemsBlocking(new List <ulong>() { m_modId }, results)) #endif { System.Threading.Thread.Sleep(1000); // Fix for DLC not being filled in if (results.Count > 0) { #if SE m_workshopItems[m_modId[0]] = results[0]; if (m_modId.Length > 1 && results.Count > 1) { m_workshopItems[m_modId[1]] = results[1]; } #else if (results.Count > 1) { m_modId = results[0].Id; } #endif m_title = results[0].Title; // Check if the mod owner in the sbmi matches steam owner var owner = results[0].OwnerId; if (m_visibility == null) { m_visibility = (PublishedFileVisibility)(int)results[0].Visibility; } #if SE m_dlcs = results[0].DLCs.ToArray(); #endif m_deps = results[0].Dependencies.ToArray(); MyDebug.AssertDebug(owner == MyGameService.UserId); if (owner != MyGameService.UserId) { MySandboxGame.Log.WriteLineAndConsole(string.Format("Owner mismatch! Mod owner: {0}; Current user: {1}", owner, MyGameService.UserId)); MySandboxGame.Log.WriteLineAndConsole("Upload/Publish FAILED!"); return(false); } return(true); } return(false); } return(true); } void ProcessTags() { // TODO: This code could be better. // Get the list of existing tags, if there are any var existingTags = GetTags(); var length = m_tags.Length; // Order or tag processing matters // 1) Copy mod type into tags var modtype = m_type.ToString(); // 2) Verify the modtype matches what was listed in the workshop // TODO If type doesn't match, process as workshop type if (existingTags != null && existingTags.Length > 0) { MyDebug.AssertRelease(existingTags.Contains(modtype, StringComparer.InvariantCultureIgnoreCase), string.Format("Mod type '{0}' does not match workshop '{1}'", modtype, existingTags[0])); } #if SE // 3a) check if user passed in the 'development' tag // If so, remove it, and mark the mod as 'dev' so it doesn't get flagged later if (m_tags.Contains(MyWorkshop.WORKSHOP_DEVELOPMENT_TAG)) { m_tags = (from tag in m_tags where tag != MyWorkshop.WORKSHOP_DEVELOPMENT_TAG select tag).ToArray(); m_isDev = true; } #endif // 3b If tags contain mod type, remove it if (m_tags.Contains(modtype, StringComparer.InvariantCultureIgnoreCase)) { m_tags = (from tag in m_tags where string.Compare(tag, modtype, true) != 0 select tag).ToArray(); } // 4) if (m_tags.Length == 1 && m_tags[0] == null && existingTags != null && existingTags.Length > 0) { // 4a) If user passed no tags, use existing ones Array.Resize(ref m_tags, existingTags.Length); Array.Copy(existingTags, m_tags, existingTags.Length); } else { // 4b) Verify passed in tags are valid for this mod type var validTags = new List <MyWorkshop.Category>() { #if SE // 'obsolete' tag is always available, as is 'No Mods' and 'experimental' new MyWorkshop.Category() { Id = "obsolete" }, new MyWorkshop.Category() { Id = "no mods" }, new MyWorkshop.Category() { Id = "experimental" }, #endif }; switch (m_type) { case WorkshopType.Mod: MyWorkshop.ModCategories.ForEach(c => validTags.Add(c)); // Mods have extra tags not in this list #if SE validTags.Add(new MyWorkshop.Category() { Id = "campaign" }); validTags.Add(new MyWorkshop.Category() { Id = "font" }); validTags.Add(new MyWorkshop.Category() { Id = "noscripts" }); #endif break; case WorkshopType.Blueprint: MyWorkshop.BlueprintCategories.ForEach(c => validTags.Add(c)); #if SE // Blueprints have extra tags not in this list validTags.Add(new MyWorkshop.Category() { Id = "large_grid" }); validTags.Add(new MyWorkshop.Category() { Id = "small_grid" }); validTags.Add(new MyWorkshop.Category() { Id = "safe" }); // Mod.io only? #endif break; case WorkshopType.Scenario: MyWorkshop.ScenarioCategories.ForEach(c => validTags.Add(c)); break; case WorkshopType.World: MyWorkshop.WorldCategories.ForEach(c => validTags.Add(c)); break; case WorkshopType.IngameScript: //tags = new MyWorkshop.Category[0]; // There are none currently break; default: MyDebug.FailRelease("Invalid category."); break; } // This query gets all the items in 'm_tags' that do *not* exist in 'validTags' // This is for detecting invalid tags passed in var invalidItems = from utag in m_tags where !( from tag in validTags select tag.Id ).Contains(utag, StringComparer.InvariantCultureIgnoreCase) select utag; if (invalidItems.Count() > 0) { MySandboxGame.Log.WriteLineAndConsole(string.Format("{0} invalid tags: {1}", (m_force ? "Forced" : "Removing"), string.Join(", ", invalidItems))); if (!m_force) { m_tags = (from tag in m_tags where !invalidItems.Contains(tag) select tag).ToArray(); } } // Now prepend the 'Type' tag string[] newTags = new string[m_tags.Length + 1]; newTags[0] = m_type.ToString(); var tags = from tag in validTags select tag.Id; // Convert all tags to proper-case for (var x = 0; x < m_tags.Length; x++) { var tag = m_tags[x]; var newtag = (from vtag in tags where (string.Compare(vtag, tag, true) == 0) select vtag).FirstOrDefault(); if (!string.IsNullOrEmpty(newtag)) { newTags[x + 1] = newtag; } else { newTags[x + 1] = m_tags[x]; } } m_tags = newTags; } #if SE // 5) Set or clear development tag if (m_isDev) { // If user selected dev, add dev tag if (!m_tags.Contains(MyWorkshop.WORKSHOP_DEVELOPMENT_TAG)) { Array.Resize(ref m_tags, m_tags.Length + 1); m_tags[m_tags.Length - 1] = MyWorkshop.WORKSHOP_DEVELOPMENT_TAG; } } else { // If not, remove tag if (m_tags.Contains(MyWorkshop.WORKSHOP_DEVELOPMENT_TAG)) { m_tags = (from tag in m_tags where tag != MyWorkshop.WORKSHOP_DEVELOPMENT_TAG select tag).ToArray(); } } #endif // 6) Strip empty values m_tags = m_tags.Where(x => !string.IsNullOrEmpty(x)).ToArray(); // Done } string[] GetTags() { var results = new List <MyWorkshopItem>(); #if SE if (MyWorkshop.GetItemsBlockingUGC(m_modId.ToList(), results)) #else if (MyWorkshop.GetItemsBlocking(new List <ulong>() { m_modId }, results)) #endif { if (results.Count > 0) { return(results[0].Tags.ToArray()); } else { return(null); } } return(null); } uint[] GetDLC() { #if SE var results = new List <MyWorkshopItem>(); if (MyWorkshop.GetItemsBlockingUGC(m_modId.ToList(), results)) { if (results.Count > 0) { return(results[0].DLCs.ToArray()); } else { return(null); } } #endif return(null); } PublishedFileVisibility GetVisibility() { var results = new List <MyWorkshopItem>(); #if SE if (MyWorkshop.GetItemsBlockingUGC(m_modId.ToList(), results)) #else if (MyWorkshop.GetItemsBlocking(new List <ulong>() { m_modId }, results)) #endif { if (results.Count > 0) { return((PublishedFileVisibility)(int)results[0].Visibility); } else { return(PublishedFileVisibility.Private); } } return(PublishedFileVisibility.Private); }
public ActionResult Edit(CourseInputModel model) { if (model != null && ModelState.IsValid) { var currentUserId = this.UserProfile.Id; var updatedArticle = this.Mapper.Map<Course>(model); var imageUploader = new ImageUplouder(); var images = new HashSet<Image>(); string folderPath = Server.MapPath(WebConstants.ImagesMainPathMap + currentUserId); if (model.Files != null && model.Files.Count() > 0) { foreach (var file in model.Files) { if (file != null && (file.ContentType == WebConstants.ContentTypeJpg || file.ContentType == WebConstants.ContentTypePng) && file.ContentLength < WebConstants.MaxImageFileSize) { images.Add(imageUploader.UploadImage(file, folderPath, currentUserId)); } } } images.ForEach(x => updatedArticle.Images.Add(x)); this.courses.Update(model.Id, updatedArticle); return this.RedirectToAction("Course", "School", new { area = "", id = model.Id }); } return this.View(model); }
/// <summary> /// Disposes the bus /// </summary> public void Dispose() { _disposables.ForEach(d => d.Dispose()); _disposables.Clear(); }
private void btnSave_Click(object sender, EventArgs e) { try { if (ModelDescription.Properties != null) { ModelDescription.Properties.Clear(); } if (_editors != null) { _editors.ForEach(ctrl => { if (ctrl is DataMart.Client.Controls.DataSourceEditor) { ModelDescription.Properties.AddRange(((DataMart.Client.Controls.DataSourceEditor)ctrl).GetSettings()); } else { string value = string.Empty; if (ctrl is TextBox) { value = ((TextBox)ctrl).Text.Trim(); } if (ctrl is ComboBox) { ComboBox combo = (ComboBox)ctrl; if (combo.SelectedIndex >= 0) { value = ((PropertyData)combo.SelectedItem).Value; } } if (ctrl is CheckBox) { value = ((CheckBox)ctrl).Checked.ToString(); } if (ctrl is SelectFileButton) { SelectFileButton btn = (SelectFileButton)ctrl; if (btn.Multiselect) { value = string.Join(",", btn.FileNames); } else { value = btn.FileName; } } if (ctrl is SelectFolderButton) { value = ((SelectFolderButton)ctrl).FolderPath; } if (!string.IsNullOrEmpty(ctrl.Tag.ToString())) { ModelDescription.Properties.Add(new PropertyData(ctrl.Tag.ToString(), value)); } } }); _editors.Clear(); } DialogResult = DialogResult.OK; this.Close(); } catch (Exception ex) { log.Error(ex); } finally { this.Cursor = Cursors.Default; } }
private async Task StressVm(SimpleFatherTestViewModel root, IHtmlBinding mb, SimpleReadOnlyTestViewModel bigVm) { var js = mb.JsRootObject; IJavascriptObject other; using (var perf = GetPerformanceCounter("Perf to bind Vm")) { await DoSafeAsyncUI(() => root.Other = bigVm); await WaitAnotherUiCycleAsync(); await Task.Delay(DelayForTimeOut); perf.DiscountTime = DelayForTimeOut; other = await _WebView.EvaluateAsync(() => GetAttribute(js, "Other")); } other.IsObject.Should().BeTrue(); var rootJs = mb.JsBrideRootObject; ISet <IJsCsGlue> allChildren = new HashSet <IJsCsGlue>(); using (GetPerformanceCounter("Perf to VisitAllChildren")) { await DoSafeAsyncUI(() => rootJs.VisitDescendantsSafe(glue => true)); } using (GetPerformanceCounter("Perf to VisitAllChildren Collect")) { await DoSafeAsyncUI(() => rootJs.VisitDescendantsSafe(glue => allChildren.Add(glue))); } _TestOutputHelper.WriteLine($"Objects created {allChildren.Count}"); using (GetPerformanceCounter("Perf Foreach GetAllChildren")) { await DoSafeAsyncUI(() => allChildren.ForEach(_ => { })); } List <object> basics = null; using (GetPerformanceCounter("Perf Collecting basics")) { basics = allChildren.Where(g => g.Type == JsCsGlueType.Basic && g.CValue != null).Select(g => g.CValue).ToList(); } string string1, string2, string3, string4; using (GetPerformanceCounter("Creating string")) { string1 = $"[{string.Join(",", basics.Select(JavascriptNamer.GetCreateExpression))}]"; } using (GetPerformanceCounter("Creating string parralel")) { var builder = new StringBuilder("["); var first = true; Parallel.ForEach(basics, () => new Builder(), (basic, _, sb) => { if (!sb.First) { sb.String.Append(","); } sb.String.Append(basic); sb.First = false; return(sb); }, (sb) => { lock (builder) { if (!first) { builder.Append(","); } first = false; builder.Append(sb.String); } }); builder.Append("]"); string2 = builder.ToString(); } var array = basics.ToArray(); using (GetPerformanceCounter("Creating JSON string")) { string3 = JsonConvert.SerializeObject(array); } using (GetPerformanceCounter("Creating JSON string bigVm")) { string4 = JsonConvert.SerializeObject(bigVm); } }
public override void PostStop() => _sources.ForEach(s => s.Cancel());
public override void LoadModelParameters(string parameters) { var urlParser = new UrlParser(parameters); UpdateAvailableIndexes(); ClearCurrentQuery(); if (urlParser.GetQueryParam("mode") == "dynamic") { var collection = urlParser.GetQueryParam("collection"); IsDynamicQuery = true; DatabaseCommands.GetTermsAsync("Raven/DocumentsByEntityName", "Tag", "", 100) .ContinueOnSuccessInTheUIThread(collections => { DynamicOptions.Match(new[] { "AllDocs" }.Concat(collections).ToArray()); string selectedOption = null; if (!string.IsNullOrEmpty(collection)) selectedOption = DynamicOptions.FirstOrDefault(s => s.Equals(collection)); if (selectedOption == null) selectedOption = DynamicOptions[0]; DynamicSelectedOption = selectedOption; DocumentsResult.SetChangesObservable(null); }); return; } IsDynamicQuery = false; var newIndexName = urlParser.Path.Trim('/'); if (string.IsNullOrEmpty(newIndexName)) { if (AvailableIndexes.Any()) { NavigateToIndexQuery(AvailableIndexes.FirstOrDefault()); return; } } IndexName = newIndexName; if (Database.Value.Statistics.Value.Errors.Any(error => error.Index == IndexName)) { QueryErrorMessage.Value = "The index " + IndexName + " has errors"; IsErrorVisible.Value = true; } DatabaseCommands.GetIndexAsync(IndexName) .ContinueOnUIThread(task => { if (task.IsFaulted || task.Result == null) { if (AvailableIndexes.Any()) { NavigateToIndexQuery(AvailableIndexes.FirstOrDefault()); } else { NavigateToIndexesList(); } return; } var fields = task.Result.Fields; QueryIndexAutoComplete = new QueryIndexAutoComplete(fields, IndexName, QueryDocument); var regex1 = new Regex(@"(?:SpatialIndex\.Generate|SpatialGenerate)"); var regex2 = new Regex(@"(?:SpatialIndex\.Generate|SpatialGenerate)\(@?\""([^\""]+)\"""); var strs = task.Result.Maps.ToList(); if (task.Result.Reduce != null) strs.Add(task.Result.Reduce); var legacyFields = new HashSet<string>(); foreach (var map in task.Result.Maps) { var count = regex1.Matches(map).Count; var matches = regex2.Matches(map).Cast<Match>().Select(x => x.Groups[1].Value).ToList(); if (matches.Count < count) legacyFields.Add(Constants.DefaultSpatialFieldName); matches.ForEach(x => legacyFields.Add(x)); } var spatialFields = task.Result.SpatialIndexes .Select(x => new SpatialQueryField { Name = x.Key, IsGeographical = x.Value.Type == SpatialFieldType.Geography, Units = x.Value.Units }) .ToList(); legacyFields.ForEach(x => spatialFields.Add(new SpatialQueryField { Name = x, IsGeographical = true, Units = SpatialUnits.Kilometers })); UpdateSpatialFields(spatialFields); HasTransform = !string.IsNullOrEmpty(task.Result.TransformResults); DocumentsResult.SetChangesObservable( d => d.IndexChanges .Where(n =>n.Name.Equals(indexName,StringComparison.InvariantCulture)) .Select(m => Unit.Default)); SetSortByOptions(fields); RestoreHistory(); }).Catch(); }
public async Task UpdateAsync(float currentTimeMS) { if (currentTimeMS - _lastTimeStamp > _config.TimestampPeriodMS) { //Check to make sure there aren't two master servers var data = await _redisServer.GetValueAsync <MasterServerTimestamp>(RedisDBKeyTypes.MasterServerTimestamp); if (data != null) { int receivedID = int.Parse(data.MasterServerID); if (receivedID != Id) { throw new InvalidOperationException("Error: the ID associated with the current Master Server timestamp does not match this master server's Id. Are there two master servers running?"); } } else { ConsoleManager.WriteLine("MasterServerTimestamp was null in redis db. Possible cause: MasterServer update was late.", ConsoleMessageType.Warning); //If data is null, I'm assuming the master server was late in updating (which shouldn't happen in production, but was happening occasionally in debug.) Log just in case. } var msg = new MasterServerTimestamp() { MasterServerID = Id.ToString() }; await _redisServer.SetValueAsync(RedisDBKeyTypes.MasterServerTimestamp, msg, new TimeSpan(0, 0, 0, 0, _config.TimestampTimeoutMS)); _lastTimeStamp = currentTimeMS; } HashSet <int> slaveIDsToRemove = new HashSet <int>(); //Check for disconnected slaves foreach (var s in _slaveServers) { var heartbeat = await _redisServer.GetRawValueAsync(RedisDBKeyTypes.SlaveHeartbeat, s.Value.ID.ToString()); if (heartbeat == null && TimeKeeper.MsSinceInitialization - _initTimeMs > _config.InitializationTimestampTimeoutMS && TimeKeeper.MsSinceInitialization - s.Value.InitializationTime > _config.SlaveInitializationGracePeriod) { _redisServer.ClearHashValue(RedisDBKeyTypes.SlaveIDHashSet, s.Value.ID); //ConsoleManager.WriteLine("Slave server timed out. Removing from slave list...", ConsoleMessageType.Warning); slaveIDsToRemove.Add(s.Key); _redisServer.PublishObjectAsync(ChannelTypes.MasterSlave, s.Value.ID, new NetworkMessageContainer(new MessageSlaveDisconnection(), MessageTypes.Redis_SlaveDisconnectionDetected)); _pendingRebalance = true;//TODO: implement more graceful rebalance on slave disconnect, as of this writing the server basically just resets entirely _rebalanceWaitStartTime = TimeKeeper.MsSinceInitialization; } } slaveIDsToRemove.ForEach(key => { RemoveSlave(key); }); if (_pendingRebalance && TimeKeeper.MsSinceInitialization - _rebalanceWaitStartTime > _config.RebalanceDelayMS) { _rebalanceServers(); } }