private static IEnumerable<Type> getTypes(Type sourceType) { Queue<Type> pending = new Queue<Type>(); HashSet<Type> visited = new HashSet<Type>(); pending.Enqueue(sourceType); while (pending.Count != 0) { Type type = pending.Dequeue(); visited.Add(type); yield return type; if (type.BaseType != null) { if (!visited.Contains(type.BaseType)) { pending.Enqueue(type.BaseType); } } foreach (Type interfaceType in type.GetInterfaces()) { if (!visited.Contains(interfaceType)) { pending.Enqueue(interfaceType); } } } }
/// <summary> /// Writes index files into the specified directory. /// </summary> /// <param name="indexDirectory">The directory into which the index files should be written.</param> /// <param name="recordMapper">The mapper for the records.</param> /// <param param name="records">The records which should be written.</param> public void WriteDirectory(DirectoryInfo indexDirectory, IRecordMapper<string> recordMapper, IEnumerable<IReferenceRecord> records) { if (!indexDirectory.Exists) { indexDirectory.Create(); } var directoryNames = new HashSet<string>(); foreach (var directory in indexDirectory.GetDirectories()) { if (!directoryNames.Contains(directory.Name)) { directoryNames.Add(directory.Name); } } foreach (var record in records) { var directoryName = recordMapper.Map(record); if (!directoryNames.Contains(directoryName)) { indexDirectory.CreateSubdirectory(directoryName); directoryNames.Add(directoryName); } // Write index files into the index directory } }
public bool run() { var triangleNumbers = new HashSet<long>(); var pentagonalNumbers = new HashSet<long>(); var hexagonalNumbers = new HashSet<long>(); for (var n = 1L; ; n++) { long v1 = n * (n + 1) / 2; long v2 = n * (3 * n - 1) / 2; long v3 = n * (2 * n - 1); triangleNumbers.Add(v1); pentagonalNumbers.Add(v2); hexagonalNumbers.Add(v3); if ((pentagonalNumbers.Contains(v1) && hexagonalNumbers.Contains(v1)) || (triangleNumbers.Contains(v2) && hexagonalNumbers.Contains(v2)) || (triangleNumbers.Contains(v3) && pentagonalNumbers.Contains(v3))) { { if (triangleNumbers.Intersect(pentagonalNumbers) .Intersect(hexagonalNumbers).Count() == 3) { break; } } } } var result = triangleNumbers.Intersect(pentagonalNumbers) .Intersect(hexagonalNumbers).OrderBy(v => v).Last(); return result == 1533776805; }
public Task<PermissionSet> GetPermissions(IReadOnlyList<SignatureEvidence> authentication, LedgerPath path, bool recursiveOnly, string recordName) { HashSet<string> identities = new HashSet<string>(authentication.Select(evidence => keyEncoder.GetPubKeyHash(evidence.PublicKey)), StringComparer.Ordinal); LedgerPath pathRecordName; // If the path is root and the record name is a tird-party asset owned by the current identity, // arbitrary modification of the balance is allowed if (LedgerPath.TryParse(recordName, out pathRecordName) && thirdPartyAssetPath.IsStrictParentOf(pathRecordName) && path.Segments.Count == 0 && identities.Contains(pathRecordName.Segments[thirdPartyAssetPath.Segments.Count])) { return Task.FromResult(new PermissionSet(accountNegative: Access.Permit)); } // Account /asset/p2pkh/[addr]/ if (thirdPartyAssetPath.IsStrictParentOf(path) && path.Segments.Count == thirdPartyAssetPath.Segments.Count + 1 && keyEncoder.IsP2pkh(path.Segments[path.Segments.Count - 1])) { Access ownAccount = identities.Contains(path.Segments[path.Segments.Count - 1]) && recordName != DynamicPermissionLayout.AclResourceName ? Access.Permit : Access.Unset; return Task.FromResult(new PermissionSet( accountModify: Access.Permit, accountCreate: Access.Permit, accountSpend: ownAccount, dataModify: ownAccount)); } else { return Task.FromResult(new PermissionSet()); } }
static void Main(string[] args) { int n = ushort.Parse(Console.ReadLine()); HashSet<int> noPrime = new HashSet<int> { }; for (int x = 2; x < n; x++) { for (int y = x * 2; y < n; y = y + x) { if (!noPrime.Contains(y)) { noPrime.Add(y); } } } Console.Write("2"); for (int z = 3; z <= n; z++) { if (z != n) { if (!noPrime.Contains(z)) { Console.Write(", " + z); } } } Console.WriteLine(); }
private List<KeyValuePair<BinaryExpressionSyntax, BinaryExpressionSyntax>> FindReoccuringOperations( IEnumerable<BinaryExpressionSyntax> operations, SemanticModel semanticModel) { var originalList = operations.ToList(); var copiedList = originalList.ToList(); var duplicates = new List<KeyValuePair<BinaryExpressionSyntax, BinaryExpressionSyntax>>(); var alreadyFound = new HashSet<BinaryExpressionSyntax>(); foreach (var oItem in originalList) { foreach (var cItem in copiedList) { if (alreadyFound.Contains(oItem) && alreadyFound.Contains(cItem)) continue; if (IsEqualButNotTheSame(oItem, cItem, semanticModel)) { alreadyFound.Add(oItem); alreadyFound.Add(cItem); duplicates.Add(new KeyValuePair<BinaryExpressionSyntax, BinaryExpressionSyntax>(oItem, cItem)); break; } } } return duplicates; }
public void Create() { var collection = new HashSet<string> { "A", "B", "A" }.AsReadOnly(); Assert.AreEqual(2, collection.Count); Assert.IsTrue(collection.Contains("A")); Assert.IsTrue(collection.Contains("B")); }
/// <summary> /// Determines which methods can be proxied from /// the given <paramref name="baseType"/> and <paramref name="baseInterfaces"/>. /// </summary> /// <remarks>By default, only public virtual methods will be proxied.</remarks> /// <param name="baseType">The base class of the proxy type currently being generated.</param> /// <param name="baseInterfaces">The list of interfaces that the proxy must implement.</param> /// <returns>A list of <see cref="MethodInfo"/> objects that can be proxied.</returns> public IEnumerable<MethodInfo> ChooseProxyMethodsFrom(Type baseType, IEnumerable<Type> baseInterfaces) { var results = new HashSet<MethodInfo>(); var baseMethods = from method in baseType.GetMethods() where method.IsVirtual && !method.IsFinal && !method.IsPrivate select method; // Add the virtual methods defined // in the base type foreach (var method in baseMethods) { if (!results.Contains(method)) results.Add(method); } var interfaceMethods = from currentInterface in baseInterfaces from method in currentInterface.GetMethods() where method.IsPublic && method.IsVirtual && !method.IsFinal && !results.Contains(method) select method; // Add the virtual methods defined // in the interface types foreach (var method in interfaceMethods) { results.Add(method); } return results; }
static void Main(string[] args) { var letters = new HashSet<char>("the quick brown fox"); Console.WriteLine(letters.Contains('t')); // true Console.WriteLine(letters.Contains('j')); // false foreach (char c in letters) { Console.Write(c); // the quickbrownfx } letters.IntersectWith("aeiou"); foreach (char c in letters) { Console.Write(c); // euio } var letters2 = new HashSet<char>("the quick brown fox"); letters2.ExceptWith("aeiou"); foreach (char c in letters2) { Console.Write(c); // th qckbrwnfx } var letters3 = new HashSet<char>("the quick brown fox"); letters3.SymmetricExceptWith("the lazy brown fox"); foreach (char c in letters3) { Console.Write(c); // quicklazy } }
private TestType GetTestType(MethodInfo testMethod) { var uniqueAttributeTypes = new HashSet<string>(); var allAttributes = testMethod.GetCustomAttributes(); foreach (var attr in allAttributes) { uniqueAttributeTypes.Add(attr.GetType().Name); } if (uniqueAttributeTypes.Contains(typeof (TestCaseAttribute).Name)) { if (uniqueAttributeTypes.Contains(typeof (ShouldThrowAttribute).Name)) { return TestType.TestCasesShouldThrow; } return TestType.TestCasesNormal; } if (uniqueAttributeTypes.Contains(typeof (ShouldThrowAttribute).Name)) { return TestType.ShouldThrow; } return TestType.Normal; }
public int LongestConsecutiveSolution(int[] nums) { int length = nums.Length; HashSet<int> set = new HashSet<int>(); int max=0; foreach(int cur in nums) set.Add(cur); foreach (int cur in nums) { int len=1; int left = cur - 1; int right = cur + 1; while (set.Contains(left)) { len++; set.Remove(left); left--; } while (set.Contains(right)) { len++; set.Remove(left); right++; } max = max > len ? max : len; } return max; }
static void Main(string[] args) { int number = int.Parse(Console.ReadLine()); HashSet<int> NoPrime = new HashSet<int>(); for (int x = 2; x < number; x++) { for (int y = x * 2; y < number; y = y + x) { if (!NoPrime.Contains(y)) { NoPrime.Add(y); } } } Console.Write("2"); for (int z = 3; z <= number ; z++) { if (z != number) { if (!NoPrime.Contains(z)) { Console.Write(", " + z); } } } Console.WriteLine(); }
public virtual void move(double deltaT, HashSet<Keys> keyPressed) { base.move(); if (keyPressed.Contains(Keys.Left)) { this.positionX += (deltaT) * playerSpeed; } if (keyPressed.Contains(Keys.Right)) { this.positionX -= (deltaT) * playerSpeed; } this.munitionStock.move(deltaT, keyPressed, this); foreach(Missile m in Missile.misileList) if (!BasicShip.colitionTest(this,m)) { int old = this.live; this.live -= m.live; m.live -= old; } }
public List<Graph> ConnectedComponents() { List<Graph> ret = new List<Graph>(); HashSet<int> visited = new HashSet<int>(); Queue<int> queue = new Queue<int>(); ForEachVertex((v) => { if (!visited.Contains(v)) { Graph g = new Graph(); queue.Enqueue(v); visited.Add(v); while (queue.Count != 0) { int u = queue.Dequeue(); g.storage[u] = storage[u]; ForEachNeighbor(u, (w) => { if (!visited.Contains(w)) { queue.Enqueue(w); visited.Add(w); } }); } ret.Add(g); } }); return ret; }
public override string Solve() { var denominators = new List<BigInteger>(); var numbersToSkip = new HashSet<decimal> { 10, 20, 30, 40, 50, 60, 70, 80, 90 }; for (decimal numerator = 10; numerator < 100; numerator++) { for (decimal denominator = 10; denominator < 100; denominator++) { if (numbersToSkip.Contains(numerator) && numbersToSkip.Contains(denominator)) { continue; } if (numerator == denominator) { continue; } decimal? numberInBoth = GetNumberInboth(numerator, denominator); if (numberInBoth != null) { var one = numerator / denominator; if (one > 1) continue; var newDenominator = RemoveNumber(numberInBoth.Value, denominator); if (newDenominator == 0) { continue; } var newNumerator = RemoveNumber(numberInBoth.Value, numerator); var two = newNumerator / newDenominator; if (one == two) { denominators.Add(BigInteger.Parse(newDenominator.ToString())); } } } } var product = denominators[0] * denominators[1] * denominators[2]; return product.ToString(); }
public void SimpleMergeSucceeds() { var lengths = new[] { 1, 3, 4, 6 }; var words = new[] { "car", "dog", "free", "sixpack" }; var uniqueLengths = new HashSet<int>(); var uniqueWords = new HashSet<string>(); var pairs = new HashSet<Tuple<int, string>>(); lengths.Merge( words, l => l, w => w.Length, l => uniqueLengths.Add(l), w => uniqueWords.Add(w), (l, w) => pairs.Add(Tuple.Create(l, w)) ); Assert.AreEqual(2, uniqueLengths.Count); Assert.IsTrue(uniqueLengths.Contains(1)); Assert.IsTrue(uniqueLengths.Contains(6)); Assert.AreEqual(1, uniqueWords.Count); Assert.IsTrue(uniqueWords.Contains("sixpack")); Assert.AreEqual(3, pairs.Count); Assert.IsTrue(pairs.Contains(Tuple.Create(3, "car"))); Assert.IsTrue(pairs.Contains(Tuple.Create(3, "dog"))); Assert.IsTrue(pairs.Contains(Tuple.Create(4, "free"))); }
public HashSet<string> FindSynonymAttribute(string attribute, string category) { HashSet<string> answer = new HashSet<string>(); answer.Add(attribute); if (categoryToAttributeset.ContainsKey(category) == false) return answer; if (attribute == "postal code" && category == "address") { attribute = "postal code"; } List<string> synonymList = GetSynonymsByInstance(attribute); foreach (string synonym in synonymList) if (categoryToAttributeset[category].Contains(synonym)&&synonym.Length>=3) { if (answer.Contains(synonym) == false) answer.Add(synonym); } string[] tokens = attribute.Split(' '); if (tokens.Count() != 1) { HashSet<string> subAnswer = FindSynonymAttribute(tokens[tokens.Count() - 1], category); foreach (string item in subAnswer) if (answer.Contains(item) == false) { answer.Add(item); } } return answer; }
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); }
/// <summary> /// This method removes duplicates from tile connections. This includes connections /// which are a subset of another connection. /// </summary> /// <param name="tileConnections"></param> /// <returns></returns> public static List<TileConnection> CleanDuplicatesFromTileCollectionList(List<TileConnection> tileConnections) { var dupes = new HashSet<TileConnection>(); //compare every tile connection against every other to find the duplicates. This is slow. for (var tci = 0; tci < tileConnections.Count; tci++) { var tc = tileConnections[tci]; for (var tci2 = tci + 1; tci2 < tileConnections.Count; tci2++) { var tc2 = tileConnections[tci2]; if (!dupes.Contains(tc2) && tc2.IsDuplicateOrSubsetOf(tc)) { dupes.Add(tc2); } else if (!dupes.Contains(tc) && tc.IsDuplicateOrSubsetOf(tc2)) { //By using else if we ensure that we don't add both tileconnections //if they are exact duplicates dupes.Add(tc); } } } //remove all the duplicates dupes.ToList().ForEach( dup => { tileConnections.Remove(dup); }); return tileConnections; }
public int CalculateBudgetUsed() { this.edges.Sort(); var graph = BuildGraph(); var spanningTreeNodes = new HashSet<int>(); var connectedEdges = this.edges .Where(e => e.IsConnected); foreach (var connectedEdge in connectedEdges) { spanningTreeNodes.Add(connectedEdge.StartNode); spanningTreeNodes.Add(connectedEdge.EndNode); } foreach (var edge in edges) { if (!spanningTreeNodes.Contains(edge.StartNode)) { Prim(graph, spanningTreeNodes, edge.StartNode); } if (!spanningTreeNodes.Contains(edge.EndNode)) { Prim(graph, spanningTreeNodes, edge.EndNode); } } var budgetUsed = this.startBudget - this.leftBudget; return budgetUsed; }
protected override void RunFilterImpl() { IEnumerable<Entity> relatedObjects = entity.EntitySet.GetRelatedEntities(entity, DegreeOfRelationshipsToShow); var hashSet = new HashSet<IEntity>(relatedObjects.Cast<IEntity>()); schemaController.SetEntitiesAndRelationshipsToVisible(hashSet); // Add Parents foreach(var ent in relatedObjects) { if (ent.Parent == null) continue; if(hashSet.Contains(ent) && hashSet.Contains(ent.Parent)) { schemaController.SetVisibilityOfVirtualRelationship(ent.Parent, ent, Visibility.Visible); } } if (!ShowTables) return; // Get the mapped tables for the primary entity we are showing. var mappings = mappingSet.GetMappingsContaining(entity); HashSet<IEntity> tables = new HashSet<IEntity>(mappings.Select(m => m.FromTable).Cast<IEntity>()); schemaController.SetEntitiesAndRelationshipsToVisible(tables); foreach(var m in mappings) { schemaController.SetVisibility(m, Visibility.Visible); } }
public static LinearLinkage Apply(IRandom random, LinearLinkage p1, LinearLinkage p2) { var length = p1.Length; var child = new LinearLinkage(length); var endNodes = new HashSet<int>(); for (var i = 0; i < length; i++) { if ((p1[i] == i && p2[i] == i) || ((p1[i] == i || p2[i] == i) && random.NextDouble() < 0.5)) { child[i] = i; endNodes.Add(i); } } for (var i = 0; i < length; i++) { if (endNodes.Contains(i)) continue; var p1End = endNodes.Contains(p1[i]); var p2End = endNodes.Contains(p2[i]); if ((p1End && p2End) || (!p1End && !p2End)) { child[i] = random.NextDouble() < 0.5 ? p1[i] : p2[i]; } else if (p1End) { child[i] = p1[i]; } else { child[i] = p2[i]; } } child.LinearizeTreeStructures(); return child; }
internal IEnumerable<SortingInfo> GetFullSort() { var memo = new HashSet<string>(); var result = new List<SortingInfo>(); if(HasGroups) { foreach(var g in Group) { if(memo.Contains(g.Selector)) continue; memo.Add(g.Selector); result.Add(g); } } if(HasSort) { foreach(var s in Sort) { if(memo.Contains(s.Selector)) continue; memo.Add(s.Selector); result.Add(s); } } IEnumerable<string> requiredSort = new string[0]; if(HasDefaultSort) requiredSort = requiredSort.Concat(new[] { DefaultSort }); if(HasPrimaryKey) requiredSort = requiredSort.Concat(PrimaryKey); return Utils.AddRequiredSort(result, requiredSort); }
protected IEnumerable<Bundle> CreateExternalBundlesFromReferences(IEnumerable<Bundle> bundlesArray, CassetteSettings settings) { var referencesAlreadyCreated = new HashSet<string>(); foreach (var bundle in bundlesArray) { foreach (var reference in bundle.References) { if (reference.IsUrl() == false) continue; if (referencesAlreadyCreated.Contains(reference)) continue; var externalBundle = CreateExternalBundle(reference, bundle, settings); referencesAlreadyCreated.Add(externalBundle.Path); yield return externalBundle; } foreach (var asset in bundle.Assets) { foreach (var assetReference in asset.References) { if (assetReference.Type != AssetReferenceType.Url || referencesAlreadyCreated.Contains(assetReference.Path)) continue; var externalBundle = CreateExternalBundle(assetReference.Path, bundle, settings); referencesAlreadyCreated.Add(externalBundle.Path); yield return externalBundle; } } } }
private static MvcHtmlString[] RadioButtonListInternal(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, bool usedViewData, IDictionary<string, object> htmlAttributes) { if (String.IsNullOrEmpty(name)) { throw new ArgumentException(MvcResources.Common_NullOrEmpty, "name"); } if (selectList == null) { throw new ArgumentNullException("selectList"); } // If we haven't already used ViewData to get the entire list of items then we need to // use the ViewData-supplied value before using the parameter-supplied value. if (!usedViewData) { object defaultValue = htmlHelper.ViewData.Eval(name); if (defaultValue != null) { IEnumerable defaultValues = new[] { defaultValue }; IEnumerable<string> values = from object value in defaultValues select Convert.ToString(value, CultureInfo.CurrentCulture); HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase); List<SelectListItem> newSelectList = new List<SelectListItem>(); foreach (SelectListItem item in selectList) { item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text); newSelectList.Add(item); } selectList = newSelectList; } } IEnumerable<MvcHtmlString> radioButtons = selectList.Select<SelectListItem, MvcHtmlString>(item => htmlHelper.RadioButton(name, item.Value, item.Selected, htmlAttributes)); return radioButtons.ToArray(); }
long Solve(int N, List<int> A, int I, HashSet<int> used, int need) { long result = 0; for (int i = 1; i <= N; i++) { if (used.Contains(i)) { continue; } var n = i - A[I] > 0 ? need - (i - A[I]) : need; if (n <= 0) { int c = 0; for (int j = 1; j <= N; j++) { if (!used.Contains(j) && j != i) { c++; } } result += Prod(Enumerable.Range(1, c).ToList()); } else { used.Add(i); result += Solve(N, A, I + 1, used, n); used.Remove(i); } } return result; }
public void MergeWithNullKeysSucceeds() { var wordsA = new[] { "car", "dog", "free", null }; var wordsB = new[] { "car", "dog", "free", "sixpack" }; var uniqueA = new HashSet<string>(); var uniqueB = new HashSet<string>(); var pairs = new HashSet<string>(); wordsA.Merge( wordsB, a => a, b => b, a => uniqueA.Add(a), b => uniqueB.Add(b), (a, b) => pairs.Add(a) ); Assert.AreEqual(1, uniqueA.Count); Assert.IsTrue(uniqueA.Contains(null)); Assert.AreEqual(1, uniqueB.Count); Assert.IsTrue(uniqueB.Contains("sixpack")); Assert.AreEqual(3, pairs.Count); Assert.IsTrue(pairs.Contains("car")); Assert.IsTrue(pairs.Contains("dog")); Assert.IsTrue(pairs.Contains("free")); }
public void Reset(IEnumerable<ItemReference> refsToKeep) { if (refsToKeep.Any()) { var refsToKeepHash = new HashSet<ItemReference>(refsToKeep); // Clean up the definitions as necessary var defnsToRemove = (from p in _allDefinitions where !refsToKeepHash.Contains(p.Value) select p.Key).ToList(); foreach (var defnToRemove in defnsToRemove) { _allDefinitions.Remove(defnToRemove); } // Clean up the dependencies as necessary foreach (var depend in _allDependencies) { depend.Value.RemoveAllButMasterList(refsToKeepHash); } // Remove dependency information var itemsToRemove = (from p in _allItemDependencies where !refsToKeepHash.Contains(p.Key) select p.Key).ToList(); foreach (var itemToRemove in itemsToRemove) { _allItemDependencies.Remove(itemToRemove); } } else { this.Reset(); } }
internal override ThreeValuedLogic Evaluate(Strategy strategy) { var containing = new HashSet<IObject>(this.containingEnumerable); if (this.associationType.IsMany) { var associations = strategy.GetCompositeAssociations(this.associationType); foreach (var assoc in associations) { if (containing.Contains((IObject)assoc)) { return ThreeValuedLogic.True; } } return ThreeValuedLogic.False; } var association = strategy.GetCompositeAssociation(this.associationType); if (association != null) { return containing.Contains(association) ? ThreeValuedLogic.True : ThreeValuedLogic.False; } return ThreeValuedLogic.False; }
/// <summary> /// Returns the lightest set of edges that would divide the graph in two components should they be removed. /// </summary> /// <param name="graph">The flow graph to calculate the minimum cut of.</param> /// <param name="source">The source of the flow.</param> /// <param name="sink">The sink of the flow.</param> /// <returns>A list containing the edges that make up the minimum cut.</returns> public static List<IFlowGraphEdge> MinCut(IGraph<IFlowGraphEdge> graph, uint source, uint sink) { Dictionary<uint, Dictionary<uint, FlowEdge>> flowGraph = BuildFlowGraph(graph); MaxFlow(flowGraph, source, sink); List<IFlowGraphEdge> cut = new List<IFlowGraphEdge>(); HashSet<uint> reachable = new HashSet<uint>(); Queue<uint> open = new Queue<uint>(); open.Enqueue(source); reachable.Add(source); while (open.Count > 0) { uint i = open.Dequeue(); foreach (uint j in flowGraph[i].Keys) if (!reachable.Contains(j) && flowGraph[i][j].Residual > 0) { open.Enqueue(j); reachable.Add(j); } } foreach (uint i in reachable) { foreach (uint j in flowGraph[i].Keys) if (!reachable.Contains(j)) cut.Add(flowGraph[i][j].Original); } return cut; }
internal bool HavePermissions(IEnumerable <string> permissionsToCheck) { using (tokenChangeLock.ReaderLock()) { if (!CheckIsLoggedIsLoggedIn()) { throw new AuthenticationContextException("not logged in"); } return(permissionsToCheck.All(p => permissions?.Contains(p) == true)); } }
/* * protected static double[] ReadDoubles(BigEndianBinaryReader reader, int count) * { * var result = new double[count]; * for (var i = 0; i < count; i++) * result[i] = reader.ReadDouble(); * return result; * } */ /// <summary> /// Get the z values and populate each one of them in Coordinate.Z /// If there are M values, return an array with those. /// </summary> /// <param name="file">The reader</param> /// <param name="totalRecordLength">Total number of bytes in this record</param> /// <param name="currentlyReadBytes">How many bytes are read from this record</param> /// <param name="buffer">The coordinate buffer</param> /// <param name="skippedList">A list of indices which have not been added to the buffer</param> protected void GetZMValues(BigEndianBinaryReader file, int totalRecordLength, ref int currentlyReadBytes, CoordinateBuffer buffer, HashSet <int> skippedList = null) { int numPoints = buffer.Capacity; if (HasZValue()) { boundingBox[boundingBoxIndex++] = ReadDouble(file, totalRecordLength, ref currentlyReadBytes); boundingBox[boundingBoxIndex++] = ReadDouble(file, totalRecordLength, ref currentlyReadBytes); int numSkipped = 0; for (int i = 0; i < numPoints; i++) { double z = ReadDouble(file, totalRecordLength, ref currentlyReadBytes); if (skippedList?.Contains(i) != true) { buffer.SetZ(i - numSkipped, z); } else { numSkipped++; } } } // Trond: Note that M value is always optional per the shapefile spec. So we need to test total read record bytes // v.s. read bytes to see if we have them or not // Also: If we have Z we might have M. Per shapefile defn. if ((HasMValue() || HasZValue()) && currentlyReadBytes < totalRecordLength) { boundingBox[boundingBoxIndex++] = ReadDouble(file, totalRecordLength, ref currentlyReadBytes); boundingBox[boundingBoxIndex++] = ReadDouble(file, totalRecordLength, ref currentlyReadBytes); int numSkipped = 0; for (int i = 0; i < numPoints; i++) { double m = ReadDouble(file, totalRecordLength, ref currentlyReadBytes); if (skippedList?.Contains(i) != true) { buffer.SetM(i - numSkipped, m); } else { numSkipped++; } } } if (currentlyReadBytes < totalRecordLength) { int remaining = totalRecordLength - currentlyReadBytes; file.ReadBytes(remaining * 2); } }
private BestVersionMatch GetBestVersionMatch( VersionRange versionRange, IReadOnlyList <NuGetVersion> inputVersions, HashSet <NuGetVersion> listed, bool showUnlisted) { var outputVersions = new List <VersionCompatibility>(); var output = new BestVersionMatch { VersionRange = versionRange, Versions = outputVersions, }; var remainingVersions = new List <NuGetVersion>(inputVersions); while (remainingVersions.Any()) { var version = versionRange.FindBestMatch(remainingVersions); if (version == null) { break; } var compatibility = new VersionCompatibility( version, isCompatible: true, isListed: listed?.Contains(version)); if (output.BestMatch == null) { output.BestMatch = compatibility; outputVersions.Add(compatibility); } else if (showUnlisted || compatibility.IsListed != false) { outputVersions.Add(compatibility); } remainingVersions.Remove(version); } outputVersions.AddRange(remainingVersions .OrderBy(version => version) .Select(version => new VersionCompatibility( version, isCompatible: false, isListed: listed?.Contains(version))) .Where(version => showUnlisted || version.IsListed != false)); return(output); }
protected override void ProcessAssembly(AssemblyDefinition assembly) { if (!Context.IsOptimizationEnabled(CodeOptimizations.ClearInitLocals, assembly) && _assemblies?.Contains(assembly.Name.Name) != true) { return; } bool changed = false; foreach (ModuleDefinition module in assembly.Modules) { foreach (TypeDefinition type in EnumerateTypesAndNestedTypes(module.Types)) { foreach (MethodDefinition method in type.Methods) { if (method.Body != null) { if (method.Body.InitLocals) { method.Body.InitLocals = false; changed = true; } } } } } if (changed && (Annotations.GetAction(assembly) == AssemblyAction.Copy)) { Annotations.SetAction(assembly, AssemblyAction.Save); } }
private bool ShouldGenerateItemIdCollection(object collection) { // Do not generate for value types (collections that are struct) or null if (collection?.GetType().IsValueType != false) { return(false); } // Do not generate if within a type that doesn't use identifiable collections if (inNonIdentifiableType > 0) { return(false); } // Do not generate if item id collection already exists if (CollectionItemIdHelper.HasCollectionItemIds(collection)) { return(false); } // Do not generate if the collection has been flagged to not be identifiable if (nonIdentifiableCollection?.Contains(collection) == true) { return(false); } return(true); }
private const string newLine = "\r\n"; //Environment.NewLine public string Create(DateTime date, IEnumerable <Department> departments, Dictionary <string, IList <Employee> > departmentEmployees, HashSet <string> employeeErrors) { var totalSum = 0; AddLine(date.ToString("MMMM yyyy", CultureInfo.CreateSpecificCulture("ru-RU"))) .AddDelimeter(); if (departments != null) { foreach (var department in departments) { AddLine(department.Name); var sum = 0; if (departmentEmployees != null && departmentEmployees.TryGetValue(department.Id, out var employees)) { foreach (var employee in employees) { AddEmployee(employee, employeeErrors?.Contains(employee.Id) == true); sum += employee.Salary; } } AddLine($"Всего по отделу {sum}"); AddDelimeter(); totalSum += sum; } } AddLine($"Всего по предприятию {totalSum}"); return(ToString()); }
void CreateTypeNodes(List <TypeDef> types) { TypeNode parentNode = null; foreach (var type in types) { bool wasLoaded = loadedClassTokens?.Contains(type.MDToken.Raw) ?? false; TypeNode typeNode; if (type.DeclaringType == null) { typeNode = GetOrCreateNonNestedTypeTreeNode(modNode, type); } else { if (parentNode == null) { parentNode = documentTabService.DocumentTreeView.FindNode(type.DeclaringType); } if (parentNode == null || parentNode.TreeNode.LazyLoading) { break; } typeNode = GetOrCreateNestedTypeTreeNode(parentNode, type); } Debug.Assert(typeNode != null); if (wasLoaded || modifiedTypes.Contains(type.MDToken.Raw)) { UpdateMemberNodes(typeNode); } parentNode = typeNode; } }
protected TValue Compose <TInput1, TInput2, TValue>( TInput1 firstInput, string firstInputName, TInput2 secondInput, string secondInputName, Func <TInput1, TInput2, TValue> selector, [CallerMemberName] string?name = null ) { if (name is null) { throw new ArgumentNullException(nameof(name)); } if (!(_registeredComposedProperties?.Contains(name) ?? false)) { (_registeredComposedProperties ??= new()).Add(name); RegisterPropertyCallback(firstInputName, Callback); RegisterPropertyCallback(secondInputName, Callback); void Callback() => OnPropertyChanged(name); } return(selector(firstInput, secondInput)); }
public virtual string GetUnique(string desiredName, IIdentifier whoIsAsking, IEnumerable <IIdentifier> reservedNames, IEnumerable <IIdentifier> siblingNames, HashSet <string> locallyReservedNames = null) { // can't disambiguate on an empty name. if (string.IsNullOrEmpty(desiredName)) { return(desiredName); } var names = new HashSet <IIdentifier>(reservedNames.Where(each => !IsSpecialCase(whoIsAsking, each))); // is this a legal name? -- add a Qualifier Suffix (ie, Method/Model/Property/etc) string conflict; while ((conflict = IsNameLegal(desiredName, whoIsAsking)) != null) { desiredName += whoIsAsking.Qualifier; // todo: gws: log the name change because it conflicted with a reserved word. // Singleton<Log>.Instance?.Add(new Message {Text = $"todo:{conflict}"}); } // does it conflict with a type name locally? (add a Qualifier Suffix) IIdentifier confl; while (null != (confl = IsNameAvailable(desiredName, names))) { desiredName += whoIsAsking.Qualifier; } // special case (corolary): a compositeType can actually have the same name as a property if (whoIsAsking is CompositeType) { siblingNames = siblingNames.Where(each => !(each is Property)); } if (whoIsAsking is Property) { siblingNames = siblingNames.Where(each => !(each is CompositeType)); } // does it have a sibling collision? names = new HashSet <IIdentifier>(siblingNames); var baseName = desiredName; var suffix = 0; while (IsNameAvailable(desiredName, names) != null) { desiredName = baseName + ++suffix; } // is there a collision with any local name we care about? while (true == locallyReservedNames?.Contains(desiredName)) { desiredName = baseName + ++suffix; } return(desiredName); }
protected void BuildDomainModel <D, O>(D domain, O dataObj, HashSet <string> map, bool alreadyEncrypted, HashSet <string> notEncList = null) where D : Domain where O : Data.Data { var domainType = domain.GetType(); var dataObjType = dataObj.GetType(); foreach (var prop in map) { var dataObjPropInfo = dataObjType.GetProperty(prop); var dataObjProp = dataObjPropInfo.GetValue(dataObj); var domainPropInfo = domainType.GetProperty(prop); if (alreadyEncrypted || (notEncList?.Contains(prop) ?? false)) { domainPropInfo.SetValue(domain, dataObjProp, null); } else { domainPropInfo.SetValue( domain, dataObjProp != null && !string.IsNullOrWhiteSpace(dataObjProp as string) ? new CipherString(dataObjProp as string) : null, null ); } } }
public void Validate(Type type, HashSet <string>?paramSkip = null) { if (ShouldSkip.ShouldSkip(type)) { return; } var constr = type.GetConstructors(); if (constr.Length > 1) { throw new AutofacValidationException( $"'{type.FullName}' has more than one constructor"); } if (constr.Length == 0) { return; } foreach (var param in constr[0].GetParameters()) { if (param.IsOptional) { continue; } if (param.Name != null && (paramSkip?.Contains(param.Name) ?? false)) { continue; } ValidateType.Validate(param.ParameterType); } }
protected void FindSplitIdx(string s, int startIdx, out int splitIdx, out int numDiscardedSeparators) { if (startIdx >= s.Length) { startIdx = s.Length - 1; } numDiscardedSeparators = 0; for (int tentativeIdx = startIdx; true; --tentativeIdx) //at each step, we check tentativeIdx and tentativeIdx-1. { if (tentativeIdx <= 0) //if 0 is reached, there are no separators in this string. { splitIdx = startIdx; return; } if (retainedSeparators?.Contains(s[tentativeIdx - 1]) == true) //a retained separator on the left of the tentativeIdx is always a valid split. { splitIdx = tentativeIdx; return; } // Note that idx-1 is checked for retained separators, while idx is checked for discarded ones: if (discardedSeparators?.Contains(s[tentativeIdx]) == true) { splitIdx = tentativeIdx; numDiscardedSeparators = 1; // Could extend this later to look for multiple discarded separators. return; } } }
/// <summary> /// Perform the necessary operations for a move, check liberties, capture, etc. Also /// updates the Move and IsLegal properties. /// </summary> /// <param name="x">The X coordinate of the move.</param> /// <param name="y">The Y coordinate of the move.</param> /// <returns>True if the move was legal.</returns> protected bool InternalMakeMove(int x, int y) { var legal = true; var oturn = Turn.Opposite(); if (Board[x, y] != Content.Empty) { legal = false; // Overwrite move } Board[x, y] = oturn; Move = new Point(x, y); var capturedGroups = Board.GetCapturedGroups(x, y); if (capturedGroups.Count == 0 && Board.GetLiberties(x, y) == 0) // Suicide move { _captures[Turn] += Board.Capture(Board.GetGroupAt(x, y)); legal = false; } else { _captures[oturn] += Board.Capture(capturedGroups.Where(p => p.Content == oturn.Opposite())); } if (_superKoSet?.Contains(Board) == true) // Violates super-ko { legal = false; } _superKoSet?.Add(Board); IsLegal = legal; return(legal); }
/// <inheritdoc/> public IPropertyBag CreateModified( IPropertyBag input, IEnumerable <KeyValuePair <string, object> >?propertiesToSetOrAdd, IEnumerable <string>?propertiesToRemove) { IReadOnlyDictionary <string, object> existingProperties = input.AsDictionary(); Dictionary <string, object> newProperties = propertiesToSetOrAdd?.ToDictionary(kv => kv.Key, kv => kv.Value) ?? new Dictionary <string, object>(); HashSet <string>?remove = propertiesToRemove == null ? null : new HashSet <string>(propertiesToRemove); foreach (KeyValuePair <string, object> existingKv in existingProperties) { string key = existingKv.Key; bool newPropertyWithThisNameExists = newProperties.ContainsKey(key); bool existingPropertyIsToBeRemoved = remove?.Contains(key) == true; if (newPropertyWithThisNameExists && existingPropertyIsToBeRemoved) { throw new ArgumentException($"Property {key} appears in both {nameof(propertiesToSetOrAdd)} and {nameof(propertiesToRemove)}"); } if (!newPropertyWithThisNameExists && !existingPropertyIsToBeRemoved) { newProperties.Add(key, existingKv.Value); } } return(new JsonNetPropertyBag(newProperties, this.serializerSettings)); }
public List <PositionKey> VisibleTiles(int dx, int dy, int width, int height, ref HashSet <PositionKey> exclude) { var tlLoc = ScreenToCanvas(dx, dy); var brLoc = ScreenToCanvas(dx + width, dy + height); if (double.IsNaN(tlLoc.X) || double.IsNaN(brLoc.X)) { throw new Exception("ScreenToCanvas gave an invalid result"); } var result = new List <PositionKey>(); var tlPos = tlLoc.TilePosition ?? throw new Exception("TL tile position lookup failed"); var brPos = brLoc.TilePosition ?? throw new Exception("BR tile position lookup failed"); for (int y = tlPos.Y; y <= brPos.Y; y++) { for (int x = tlPos.X; x <= brPos.X; x++) { var pk = new PositionKey(x, y); if (exclude?.Contains(pk) == true) { exclude.Remove(pk); continue; } result.Add(new PositionKey(x, y)); } } return(result); }
public override bool Match(ITest test) { // If filter was created with null tests collection, we assume we want to run all tests if (_testNames?.Contains(test.FullName) ?? true) { // We don't want to run explicit tests if (!_force) { var parent = test; while (parent != null) { if (parent.RunState != RunState.Runnable) { return(false); } parent = parent.Parent; } } return(true); } return(false); }
public override ValueProviderResult GetValue(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (key.Length == 0) { // Top level parameters will fall back to an empty prefix when the parameter name does not // appear in any value provider. This would result in the parameter binding to a form parameter // with a empty key (e.g. Request body looks like "=test") which isn't a scenario we want to support. // Return a "None" result in this event. return(ValueProviderResult.None); } var values = _values[key]; if (values.Count == 0) { return(ValueProviderResult.None); } else { var culture = _invariantValueKeys?.Contains(key) == true ? CultureInfo.InvariantCulture : Culture; return(new ValueProviderResult(values, culture)); } }
/// <summary> /// Checks if the command requires the given <see cref="Subsystem"/>. /// </summary> /// <param name="system">The system</param> /// <returns>Whether or not the subsystem is required, or false if given null.</returns> public bool DoesRequire(Subsystem system) { lock (m_syncRoot) { return(m_requirements?.Contains(system) ?? false); } }
private void CheckNodeInOriginalTreeOrTracked(SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (OriginalRoot.Contains(node)) { // Node is contained in the original tree. return; } if (_allowEditsOnLazilyCreatedTrackedNewNodes) { // This could be a node that is handed to us lazily from one of the prior edits // which support lazy replacement nodes, we conservatively avoid throwing here. // If this was indeed an unsupported node, syntax editor will throw an exception later // when attempting to compute changed root. return; } if (_lazyTrackedNewNodesOpt?.Contains(node) == true) { // Node is one of the new nodes, which is already tracked and supported. return; } throw new ArgumentException(WorkspacesResources.The_node_is_not_part_of_the_tree, nameof(node)); }
public async Task <(IReadOnlyCollection <(VariableDeclarationSyntax Decl, ITypeSymbol Type)> Variables, IReadOnlyCollection <CSharpSyntaxNode> Methods)> SplitVariableDeclarationsAsync( VariableDeclaratorSyntax declarator, HashSet <ILocalSymbol> symbolsToSkip = null, bool preferExplicitType = false) { var vbInitValue = GetInitializerToConvert(declarator); var initializerOrMethodDecl = await vbInitValue.AcceptAsync(TriviaConvertingExpressionVisitor); var vbInitializerTypeInfo = vbInitValue != null?_semanticModel.GetTypeInfo(vbInitValue) : default(TypeInfo?); var vbInitializerType = vbInitValue != null ? vbInitializerTypeInfo.Value.Type : default(ITypeSymbol); bool requireExplicitTypeForAll = declarator.Names.Count > 1; IMethodSymbol initSymbol = null; if (vbInitValue != null) { TypeInfo expType = vbInitializerTypeInfo.Value; preferExplicitType |= ShouldPreferExplicitType(vbInitValue, expType.ConvertedType, out bool vbInitIsNothingLiteral); initSymbol = _semanticModel.GetSymbolInfo(vbInitValue).Symbol as IMethodSymbol; bool isAnonymousFunction = initSymbol?.IsAnonymousFunction() == true; requireExplicitTypeForAll |= vbInitIsNothingLiteral || isAnonymousFunction; } var csVars = new Dictionary <string, (VariableDeclarationSyntax Decl, ITypeSymbol Type)>(); var csMethods = new List <CSharpSyntaxNode>(); foreach (var name in declarator.Names) { var declaredSymbol = _semanticModel.GetDeclaredSymbol(name); if (symbolsToSkip?.Contains(declaredSymbol) == true) { continue; } var declaredSymbolType = declaredSymbol.GetSymbolType(); var equalsValueClauseSyntax = await ConvertEqualsValueClauseSyntaxAsync(declarator, name, vbInitValue, declaredSymbolType, declaredSymbol, initializerOrMethodDecl); var v = SyntaxFactory.VariableDeclarator(ConvertIdentifier(name.Identifier), null, equalsValueClauseSyntax); string k = declaredSymbolType?.GetFullMetadataName() ?? name.ToString();//Use likely unique key if the type symbol isn't available if (csVars.TryGetValue(k, out var decl)) { csVars[k] = (decl.Decl.AddVariables(v), decl.Type); continue; } if (initializerOrMethodDecl == null || initializerOrMethodDecl is ExpressionSyntax) { var variableDeclaration = CreateVariableDeclaration(declarator, preferExplicitType, requireExplicitTypeForAll, vbInitializerType, declaredSymbolType, equalsValueClauseSyntax, initSymbol, v); csVars[k] = (variableDeclaration, declaredSymbolType); } else { csMethods.Add(initializerOrMethodDecl); } } return(csVars.Values, csMethods); }
public override bool Walk(NameExpression node) { if (_localNames?.Contains(node.Name) == true) { return(false); } if (_localNameExpressions?.Contains(node) == true) { return(false); } var analysis = _walker.Analysis; var m = analysis.ExpressionEvaluator.LookupNameInScopes(node.Name, out var variableDefinitionScope, out var v, LookupOptions.All); if (m == null) { _walker.ReportUndefinedVariable(node); } v?.AddReference(new Location(analysis.Document, node.IndexSpan)); // Make sure we have definition and the document matches if (v?.Definition == null || v.Definition.DocumentUri != analysis.Document.Uri) { return(false); } // Do not complain about functions and classes that appear later in the file if (v.Value is IPythonFunctionType || v.Value is IPythonClassType) { return(false); } // Take into account where variable is defined so we do detect // undefined x in // y = x // x = 1 var variableDefinitionSpan = v.Definition.Span; var nameUseLocation = node.GetLocation(analysis); // Make sure we are in the same scope in order to avoid // def func(): // y = x // // x = 1 var nameUseScope = analysis.ExpressionEvaluator.GlobalScope.FindScope(analysis.Document, nameUseLocation.Span.Start); if (nameUseScope.IsNestedInScope(variableDefinitionScope)) { return(false); } // Exclude same-name variables declared within the same statement // like 'e' that appears before its declaration in '[e in for e in {}]' if (variableDefinitionSpan.IsAfter(nameUseLocation.Span) && !IsSpanInComprehension(nameUseLocation.Span)) { _walker.ReportUndefinedVariable(node); } return(false); }
public static Job FindSwapJobs(Pawn pawn) { List <Apparel> wornApparel = pawn.apparel.WornApparel; Outfit currentOutfit = pawn.outfits.CurrentOutfit; //Looping all apparel is a bit redundant because the caller is already in apparel loop, but the order might not work for this for (int i = wornApparel.Count - 1; i >= 0; i--) { Apparel takeOff = wornApparel[i]; if (!currentOutfit.filter.Allows(takeOff) && pawn.outfits.forcedHandler.AllowedToAutomaticallyDrop(takeOff)) { Log.Message("Finding swaps for " + pawn + ", could take off " + takeOff); HashSet <Thing> haulingThings = null; Log.Message("Mods: " + ModsConfig.ActiveModsInLoadOrder.ToStringSafeEnumerable()); try { ((Action)(() => { haulingThings = pawn.TryGetComp <CompHauledToInventory>()?.GetHashSet(); }))(); } catch (TypeLoadException) { } foreach (Thing t in pawn.inventory.innerContainer) { Log.Message("could wear " + t + "?"); if ((haulingThings == null || !haulingThings.Contains(t)) && t is Apparel swapTo && currentOutfit.filter.Allows(swapTo) && ApparelUtility.HasPartsToWear(pawn, swapTo.def)) { Log.Message("does " + t + " match?"); if (ApparelUtility.CanWearTogether(takeOff.def, swapTo.def, pawn.RaceProps.body)) { continue; } Log.Message("does " + t + " fit?"); if (FitsAfterSwap(swapTo, pawn, takeOff)) { Log.Message("yes totally I'm swapping " + takeOff + " for " + swapTo); return(new Job(GearUpAndGoJobDefOf.SwapApparelWithInventory, takeOff, swapTo)); } } } Log.Message("Nothing to swap to: should I return it to inventory?"); HashSet <Thing> wornThings = pawn.TryGetComp <CompWornFromInventory>()?.GetHashSet(); if (wornThings?.Contains(takeOff) ?? false) { Log.Message("yes totally I'm removing " + takeOff + " back into inventory"); return(new Job(GearUpAndGoJobDefOf.SwapApparelWithInventory, takeOff)); } } } return(null); }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public string GenerateCommandLine(Rule rule, Dictionary <string, object> propertyValues, HashSet <string> propertiesToIgnore = null) { // // Generate a command line with arguments in the same order as those in rule.Properties. // (We might need to add support for sorting by an explicit order.) // var builder = new CommandLineBuilder(); foreach (var property in rule.Properties) { if (property == null) { continue; } else if (!property.IncludeInCommandLine) { continue; // Property explicitly excluded. } else if (propertiesToIgnore?.Contains(property.Name) ?? false) { continue; // Property explicitly ignored. } if (!propertyValues.TryGetValue(property.Name, out object value)) { continue; // No associated value found for this property. } if (property.GetType().Equals(typeof(StringListProperty))) { GenerateArgumentStringList(ref builder, rule, property as StringListProperty, value); } else if (property.GetType().Equals(typeof(StringProperty))) { GenerateArgumentString(ref builder, rule, property as StringProperty, value); } else if (property.GetType().Equals(typeof(EnumProperty))) { GenerateArgumentEnum(ref builder, rule, property as EnumProperty, value); } else if (property.GetType().Equals(typeof(BoolProperty))) { GenerateArgumentBool(ref builder, rule, property as BoolProperty, value); } else if (property.GetType().Equals(typeof(IntProperty))) { GenerateArgumentInt(ref builder, rule, property as IntProperty, value); } else { throw new NotImplementedException(); } } return(builder.ToString()); }
/// <summary> /// Populate the Martial Arts Techniques list. /// </summary> private async ValueTask RefreshTechniquesList() { string strFilter = '(' + _objCharacter.Settings.BookXPath() + ')'; string strSearch = await txtSearch.DoThreadSafeFuncAsync(x => x.Text); if (!string.IsNullOrEmpty(strSearch)) { strFilter += " and " + CommonFunctions.GenerateSearchXPath(strSearch); } XPathNodeIterator objTechniquesList = _xmlBaseChummerNode.Select("techniques/technique[" + strFilter + ']'); using (new FetchSafelyFromPool <List <ListItem> >(Utils.ListItemListPool, out List <ListItem> lstTechniqueItems)) { foreach (XPathNavigator xmlTechnique in objTechniquesList) { string strId = (await xmlTechnique.SelectSingleNodeAndCacheExpressionAsync("id"))?.Value; if (!string.IsNullOrEmpty(strId)) { string strTechniqueName = (await xmlTechnique.SelectSingleNodeAndCacheExpressionAsync("name"))?.Value ?? await LanguageManager.GetStringAsync("String_Unknown"); if (_setAllowedTechniques?.Contains(strTechniqueName) == false) { continue; } if (xmlTechnique.RequirementsMet(_objCharacter, _objMartialArt)) { lstTechniqueItems.Add(new ListItem( strId, (await xmlTechnique.SelectSingleNodeAndCacheExpressionAsync("translate")) ?.Value ?? strTechniqueName)); } } } lstTechniqueItems.Sort(CompareListItems.CompareNames); string strOldSelected = await lstTechniques.DoThreadSafeFuncAsync(x => x.SelectedValue?.ToString()); _blnLoading = true; await lstTechniques.PopulateWithListItemsAsync(lstTechniqueItems); _blnLoading = false; await lstTechniques.DoThreadSafeAsync(x => { if (!string.IsNullOrEmpty(strOldSelected)) { x.SelectedValue = strOldSelected; } else { x.SelectedIndex = -1; } }); } }
protected CommentResponse BuildCommentResponse( Comment comment, bool canUserSeeNotApprovedComments, DefaultDictionary <int, List <Comment> > replies, DefaultDictionary <int, int> commentLikesCount, HashSet <int> likedByUserCommentsIds, [CanBeNull] Dictionary <string, List <Group> > authorId2Groups, [CanBeNull] HashSet <string> authorsWithPassed, [CanBeNull] HashSet <int> userAvailableGroups, bool canViewAllGroupMembers, bool addCourseIdAndSlideId, bool addParentCommentId, bool addReplies ) { var commentInfo = new CommentResponse { Id = comment.Id, Text = comment.Text, RenderedText = CommentTextHelper.RenderCommentTextToHtml(comment.Text), Author = BuildShortUserInfo(comment.Author), PublishTime = comment.PublishTime, IsApproved = comment.IsApproved, IsLiked = likedByUserCommentsIds.Contains(comment.Id), LikesCount = commentLikesCount[comment.Id], IsPassed = authorsWithPassed?.Contains(comment.AuthorId) ?? false, Replies = new List <CommentResponse>() }; if (authorId2Groups != null && userAvailableGroups != null && authorId2Groups.ContainsKey(comment.Author.Id)) { commentInfo.AuthorGroups = authorId2Groups[comment.AuthorId] .Where(g => canViewAllGroupMembers || userAvailableGroups.Contains(g.Id)) .Select(BuildShortGroupInfo) .ToList().NullIfEmpty(); } if (addCourseIdAndSlideId) { commentInfo.CourseId = comment.CourseId; commentInfo.SlideId = comment.SlideId; } if (addParentCommentId && !comment.IsTopLevel) { commentInfo.ParentCommentId = comment.ParentCommentId; } if (!comment.IsTopLevel) { commentInfo.IsCorrectAnswer = comment.IsCorrectAnswer; return(commentInfo); } commentInfo.IsPinnedToTop = comment.IsPinnedToTop; if (addReplies) { var commentReplies = FilterVisibleComments(replies[comment.Id], canUserSeeNotApprovedComments); commentInfo.Replies = BuildCommentsListResponse(commentReplies, canUserSeeNotApprovedComments, null, commentLikesCount, likedByUserCommentsIds, authorId2Groups, authorsWithPassed, userAvailableGroups, canViewAllGroupMembers, addCourseIdAndSlideId, addParentCommentId, addReplies); } return(commentInfo); }
public void Unapply(HashSet <object> appliedSetters) { foreach (var setter in actor) { if (!appliedSetters?.Contains(setter.Key) ?? true) { setter.Unset(); } } }
protected override JsonDictionaryContract CreateDictionaryContract(Type objectType) { var contract = base.CreateDictionaryContract(objectType); if (_types?.Contains(objectType) == true) { contract.DictionaryKeyResolver = propertyName => propertyName; } return(contract); }
public static string FilePath(this InstallItem line, HashSet <string> existingPaths, string extension = ".xml") { var folder = line.Type == InstallType.Script ? "_Scripts" : line.Reference.Type; var newPath = folder + "\\" + Utils.CleanFileName(line.Reference.KeyedName ?? line.Reference.Unique) + extension; if (existingPaths?.Contains(newPath) == true) { newPath = folder + "\\" + Utils.CleanFileName((line.Reference.KeyedName ?? "") + "_" + line.Reference.Unique) + extension; } return(newPath); }
public override ValueProviderResult GetValue(string key) { var result = base.GetValue(key); if (result.Length > 0 && _invariantValueKeys?.Contains(key) == true) { return(new(result.Values, CultureInfo.InvariantCulture)); } return(result); }
public IEnumerable <(string Key, object Value, bool IsGroupByField)> GetPropertiesInOrder(object target) { if (!(target is ObjectInstance oi)) { throw new ArgumentException($"JintPropertyAccessor.GetPropertiesInOrder is expecting a target of type ObjectInstance but got one of type {target.GetType().Name}."); } foreach (var property in oi.GetOwnProperties()) { yield return(property.Key, GetValue(property.Value.Value), _groupByFields?.Contains(property.Key) ?? false); } }