public bool IsScopeSatisfied(HashSet<string> requiredScope, HashSet<string> grantedScope) { if (requiredScope.IsSubsetOf(grantedScope)) { return true; } return false; }
public void Parsing_Of_Sc_Query_Output() { string output = Resources.ScQueryOutput; HashSet<ServiceItem> expected = new HashSet<ServiceItem> { new ServiceItem { ServiceName = "TermService", DisplayName = "Terminal Services" }, new ServiceItem { ServiceName = "Themes", DisplayName = "Themes" }, new ServiceItem { ServiceName = "UNS", DisplayName = "Intel(R) Management and Security Application User Notification Service" } }; HashSet<ServiceItem> actual = ServiceHelper_Accessor.ParseServicesOutput(output); Assert.IsTrue(expected.IsSubsetOf(actual)); Assert.IsTrue(expected.IsSupersetOf(actual)); }
protected Expression Compare(BinaryExpression bop) { var e1 = this.SkipConvert(bop.Left); var e2 = this.SkipConvert(bop.Right); EntityExpression entity1 = e1 as EntityExpression; EntityExpression entity2 = e2 as EntityExpression; if (entity1 == null && e1 is OuterJoinedExpression) { entity1 = ((OuterJoinedExpression)e1).Expression as EntityExpression; } if (entity2 == null && e2 is OuterJoinedExpression) { entity2 = ((OuterJoinedExpression)e2).Expression as EntityExpression; } bool negate = bop.NodeType == ExpressionType.NotEqual; if (entity1 != null) { return this.MakePredicate(e1, e2, entity1.Entity.PrimaryKeys.Select(p => p.Member), negate); } else if (entity2 != null) { return this.MakePredicate(e1, e2, entity2.Entity.PrimaryKeys.Select(p => p.Member), negate); } var dm1 = this.GetDefinedMembers(e1); var dm2 = this.GetDefinedMembers(e2); if (dm1 == null && dm2 == null) { // neither are constructed types return bop; } if (dm1 != null && dm2 != null) { // both are constructed types, so they'd better have the same members declared HashSet<string> names1 = new HashSet<string>(dm1.Select(m => m.Name), StringComparer.Ordinal); HashSet<string> names2 = new HashSet<string>(dm2.Select(m => m.Name), StringComparer.Ordinal); if (names1.IsSubsetOf(names2) && names2.IsSubsetOf(names1)) { return MakePredicate(e1, e2, dm1, negate); } } else if (dm1 != null) { return MakePredicate(e1, e2, dm1, negate); } else if (dm2 != null) { return MakePredicate(e1, e2, dm2, negate); } throw new InvalidOperationException(Res.InvalidOperationCompareException); }
public void DispatchPreservesAllRouteValues( DefaultRouteDispatcher sut, MethodCallExpression method, IDictionary<string, object> routeValues) { var actual = sut.Dispatch(method, routeValues); var expected = new HashSet<KeyValuePair<string, object>>(routeValues); Assert.True(expected.IsSubsetOf(actual.RouteValues)); }
static bool IsGroupTagsUnique(List<CityPack> cities, HashSet<string> tags) { foreach (CityPack pack in cities) { if (tags.IsSubsetOf(pack.cities) && !tags.IsProperSubsetOf(pack.cities)) { return false; } } return true; }
/// <summary> /// Determines whether one given scope is a subset of another scope. /// </summary> /// <param name="requestedScope">The requested scope, which may be a subset of <paramref name="grantedScope"/>.</param> /// <param name="grantedScope">The granted scope, the suspected superset.</param> /// <returns> /// <c>true</c> if all the elements that appear in <paramref name="requestedScope"/> also appear in <paramref name="grantedScope"/>; /// <c>false</c> otherwise. /// </returns> public static bool IsScopeSubset(string requestedScope, string grantedScope) { if (string.IsNullOrEmpty(requestedScope)) { return true; } if (string.IsNullOrEmpty(grantedScope)) { return false; } var requestedScopes = new HashSet<string>(requestedScope.Split(scopeDelimiter, StringSplitOptions.RemoveEmptyEntries)); var grantedScopes = new HashSet<string>(grantedScope.Split(scopeDelimiter, StringSplitOptions.RemoveEmptyEntries)); return requestedScopes.IsSubsetOf(grantedScopes); }
static void Main() { var companyTeams = new HashSet<string>(){ "Ferrari", "McLaren", "Mersedes" }; var traditionalTeams = new HashSet<string>() { "Ferrari", "McLaren" }; var privateTeams = new HashSet<string>() { "Red Bull", "Lotus", "Toro Rosso", "Force India", "Sauber" }; if (traditionalTeams.IsSubsetOf(companyTeams)) { Console.WriteLine("tradTeam is subset of company Teams"); } }
/// <summary> /// Gets the instance of the created command object. /// </summary> /// <param name="tokens">Command line arguments to initialize command with.</param> /// <exception cref="Exception{OptionsValidationExceptionArgs}"> /// Indicates that at least one required option was not specified. /// </exception> internal object CreateInstance(IDictionary<string, OptionValue> tokens) { HashSet<string> availableOptions = new HashSet<string>(tokens.Select(t => t.Key.ToLowerInvariant())); OptionMetadata[] targetMetadata = null; // Find options set that matches our tokens collection. foreach (var usage in _metadata.Options) { HashSet<string> requiredOptions = new HashSet<string>(usage.Where(o => o.Required).Select(o => o.Name.ToLowerInvariant())); HashSet<string> allOptions = new HashSet<string>(usage.Select(o => o.Name.ToLowerInvariant())); if (requiredOptions.IsSubsetOf(availableOptions) && allOptions.IsSupersetOf(availableOptions)) { targetMetadata = usage; break; } } if (null == targetMetadata) { var args = new OptionsValidationExceptionArgs("Invalid command arguments provided."); throw new Exception<OptionsValidationExceptionArgs>(args); } try { return CreateInstanceInternal(targetMetadata, tokens); } catch (TargetInvocationException ex) { var argumentError = ex.InnerException as ArgumentException; if (null == argumentError) throw; string msg = string.Format("Invalid value for option '{0}'. {1}", argumentError.ParamName, argumentError.Message); var args = new OptionsValidationExceptionArgs(msg); throw new Exception<OptionsValidationExceptionArgs>(args); } catch (MissingMethodException) { var args = new OptionsValidationExceptionArgs("Invalid command arguments provided."); throw new Exception<OptionsValidationExceptionArgs>(args); } }
static void Main() { var companyTeams = new HashSet<string>() { "Ferrari", "McLaren", "Mercedes" }; var traditionalTeams = new HashSet<string>() { "Ferrari", "McLaren" }; var privateTeams = new HashSet<string>() { "Red Bull", "Lotus", "Toro Rosso", "Force India", "Sauber" }; if (privateTeams.Add("Williams")) WriteLine("Williams added"); if (!companyTeams.Add("McLaren")) WriteLine("McLaren was already in this set"); if (traditionalTeams.IsSubsetOf(companyTeams)) { WriteLine("traditionalTeams is subset of companyTeams"); } if (companyTeams.IsSupersetOf(traditionalTeams)) { WriteLine("companyTeams is a superset of traditionalTeams"); } traditionalTeams.Add("Williams"); if (privateTeams.Overlaps(traditionalTeams)) { WriteLine("At least one team is the same with traditional and private teams"); } var allTeams = new SortedSet<string>(companyTeams); allTeams.UnionWith(privateTeams); allTeams.UnionWith(traditionalTeams); WriteLine(); WriteLine("all teams"); foreach (var team in allTeams) { WriteLine(team); } allTeams.ExceptWith(privateTeams); WriteLine(); WriteLine("no private team left"); foreach (var team in allTeams) { WriteLine(team); } }
public void TestSubSetSuperSet () { var aSet = new HashSet<int> { 1, 2 }; var bSet = new HashSet<int> { 1 }; Assert.IsTrue (aSet.IsSubsetOf (aSet)); Assert.IsTrue (bSet.IsSubsetOf (aSet)); Assert.IsTrue (bSet.IsProperSubsetOf (aSet)); Assert.IsFalse (aSet.IsProperSubsetOf (aSet)); Assert.IsTrue (aSet.IsSupersetOf (aSet)); Assert.IsTrue (aSet.IsSupersetOf (bSet)); Assert.IsTrue (aSet.IsProperSupersetOf (bSet)); Assert.IsFalse (aSet.IsProperSupersetOf (aSet)); }
protected Expression Compare(BinaryExpression bop) { var e1 = this.SkipConvert(bop.Left); var e2 = this.SkipConvert(bop.Right); EntityExpression entity1 = e1 as EntityExpression; EntityExpression entity2 = e2 as EntityExpression; bool negate = bop.NodeType == ExpressionType.NotEqual; if (entity1 != null) { return this.MakePredicate(e1, e2, this.mapping.GetPrimaryKeyMembers(entity1.Entity), negate); } else if (entity2 != null) { return this.MakePredicate(e1, e2, this.mapping.GetPrimaryKeyMembers(entity2.Entity), negate); } var dm1 = this.GetDefinedMembers(e1); var dm2 = this.GetDefinedMembers(e2); if (dm1 == null && dm2 == null) { // neither are constructed types return bop; } if (dm1 != null && dm2 != null) { // both are constructed types, so they'd better have the same members declared HashSet<string> names1 = new HashSet<string>(dm1.Select(m => m.Name)); HashSet<string> names2 = new HashSet<string>(dm2.Select(m => m.Name)); if (names1.IsSubsetOf(names2) && names2.IsSubsetOf(names1)) { return MakePredicate(e1, e2, dm1, negate); } } else if (dm1 != null) { return MakePredicate(e1, e2, dm1, negate); } else if (dm2 != null) { return MakePredicate(e1, e2, dm2, negate); } throw new InvalidOperationException("Cannot compare two constructed types with different sets of members assigned."); }
public bool Equals(AlternationRegExp alternationRegExp) { if (!base.Equals(alternationRegExp)) return false; if (alternationRegExp.ChildExpressions.Length != ChildExpressions.Length) return false; // The easiest way to check whether two arrays has same regular axpressions is to construct HaashSets and check // if the sets are equal. Remember, the order is not important! var hashSetForThis = new HashSet<RegExp>(ChildExpressions); var hashSetForOther = new HashSet<RegExp>(alternationRegExp.ChildExpressions); if (hashSetForOther.IsSubsetOf(hashSetForThis) && hashSetForThis.IsSubsetOf(hashSetForOther)) { return true; } return false; }
public bool PreconditionVerification(QsCompilation compilation) { var requiredNamespace = compilation.Namespaces .FirstOrDefault(ns => ns.Name.Equals(BuiltIn.CoreNamespace)); if (requiredNamespace == null) { return(false); } var providedOperations = new QsNamespace[] { requiredNamespace } .Callables() .Select(c => c.FullName) .ToHashSet(); var requiredBuiltIns = new HashSet <QsQualifiedName>() { BuiltIn.Length.FullName, BuiltIn.RangeReverse.FullName }; return(requiredBuiltIns.IsSubsetOf(providedOperations)); }
internal static bool DoesEndKeySubsumeAssociationSetKey(AssociationSet assocSet, AssociationEndMember thisEnd, HashSet <Pair <EdmMember, EntityType> > associationkeys) { AssociationType assocType = assocSet.ElementType; EntityType thisEndsEntityType = (EntityType)((RefType)thisEnd.TypeUsage.EdmType).ElementType; HashSet <Pair <EdmMember, EntityType> > thisEndKeys = new HashSet <Pair <EdmMember, EntityType> >( thisEndsEntityType.KeyMembers.Select(edmMember => new Pair <EdmMember, EntityType>(edmMember, thisEndsEntityType))); foreach (ReferentialConstraint constraint in assocType.ReferentialConstraints) { IEnumerable <EdmMember> otherEndProperties; EntityType otherEndType; if (thisEnd.Equals((AssociationEndMember)constraint.ToRole)) { otherEndProperties = Helpers.AsSuperTypeList <EdmProperty, EdmMember>(constraint.FromProperties); otherEndType = (EntityType)((RefType)((AssociationEndMember)constraint.FromRole).TypeUsage.EdmType).ElementType; } else if (thisEnd.Equals((AssociationEndMember)constraint.FromRole)) { otherEndProperties = Helpers.AsSuperTypeList <EdmProperty, EdmMember>(constraint.ToProperties); otherEndType = (EntityType)((RefType)((AssociationEndMember)constraint.ToRole).TypeUsage.EdmType).ElementType; } else { //this end not part of the referential constraint continue; } //Essentially ref constraints is an equality condition, so remove redundant members from entity set key foreach (EdmMember member in otherEndProperties) { associationkeys.Remove(new Pair <EdmMember, EntityType>(member, otherEndType)); } } //Now that all redundant members have been removed, is thisEnd the key of the entity set? return(associationkeys.IsSubsetOf(thisEndKeys)); }
/// <summary> /// return true if and only if the pair can be skipped. If not true, add the new set. /// </summary> /// <param name="implStateID"> </param> /// <param name="specState"> </param> /// <returns></returns> public bool Add(string implStateID, HashSet <FAState> specState) { List <HashSet <FAState> > items; if (Pairs.TryGetValue(implStateID, out items)) { foreach (HashSet <FAState> item in items) { if (item.IsSubsetOf(specState)) { return(true); } } //the following adds the set List <HashSet <FAState> > newList = new List <HashSet <FAState> >(); newList.Add(specState); foreach (HashSet <FAState> item in items) { if (!specState.IsSubsetOf(item)) { newList.Add(item); } } Pairs[implStateID] = newList; return(false); //the above adds the set } else { List <HashSet <FAState> > newList = new List <HashSet <FAState> >(); newList.Add(specState); Pairs.Add(implStateID, newList); return(false); } }
public static void Cozy() { Console.WriteLine("\n-----------------------------------------------"); Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName); Console.WriteLine("-----------------------------------------------"); //HashSet<T>和List<T>差不多的,但HashSet<T>只能包含不重复的元素 var hashSet = new HashSet <int>(); //Add()会返回一个bool值,添加成功返回true,集合内有相同的元素,则添加失败返回false Console.WriteLine(hashSet.Add(1)); //output True Console.WriteLine(hashSet.Add(1)); //output False Console.WriteLine(hashSet.Add(2)); Console.WriteLine(hashSet.Add(3)); var array = new[] { 1, 2, 3, 4, 5 }; Console.WriteLine(hashSet.IsSubsetOf(array)); //output True Console.WriteLine(hashSet.IsSupersetOf(array)); //output False //增加array集合的元素 hashSet.UnionWith(array); foreach (var i in hashSet) { Console.WriteLine(i); } //移除array集合的元素 hashSet.ExceptWith(array); foreach (var i in hashSet) { Console.WriteLine(i); } }
protected override IEnumerable <StateMachineResult> Next(Value Input) { var Expected = new HashSet <KeyCode>(Chord.Keys); var SequentialTriggers = 0; while (true) { var Down = new HashSet <KeyCode>(); //Each time that we get an input that is a KeyDown while (Input.Current is { } Current) { System.Diagnostics.Debug.WriteLine(Input.Current); if (Current.KeyDown is { } V1) { var Key = PotentiallyNormalize(V1.Key, Expected); Down.Add(Key); if (Expected.IsSubsetOf(Down)) { SequentialTriggers += 1; if (SequentialTriggers <= MaxSequentialTriggers) { yield return(StateMachineResult.Complete); } else { yield return(StateMachineResult.Rejected); } } else { SequentialTriggers = 0; yield return(StateMachineResult.Rejected); } }
public void Start() { var primes = PrimeNumbers.GetPrimeSet(1000000); var truncatablePrimes = new List <int>(); foreach (var prime in primes.Skip(4)) { var digits = Numbers.ToDigits(prime); var lefts = new HashSet <int>(); var rights = new HashSet <int>(); for (int i = 1; i < digits.Length; i++) { lefts.Add(Numbers.ToNumber(digits, i, digits.Length)); rights.Add(Numbers.ToNumber(digits, 0, digits.Length - i)); } if (lefts.IsSubsetOf(primes) && rights.IsSubsetOf(primes)) { truncatablePrimes.Add(prime); } if (truncatablePrimes.Count == Max) { break; } } //Console.WriteLine($"Truncatable primes:"); foreach (var truncatablePrime in truncatablePrimes) { //Console.WriteLine($"{truncatablePrime}"); } Console.WriteLine($"Sum of eleven truncs: {truncatablePrimes.Sum()}"); }
static void Main(string[] args) { var citiesInUK = new HashSet <string>() { "Sheffield", "Ripon", "Truro", "Manchester" }; var bigUkCities = new HashSet <string>() { "Manchester", "Sheffield" }; var bigCitiesset = new HashSet <string>() { "New York", "Manchester", "Sheffield", "Paris" }; var ukIsSubset = citiesInUK.IsSubsetOf(bigCitiesset); Console.WriteLine($"Uk cities subset of big cities list?: {ukIsSubset}"); var bigUkIsSubset = bigUkCities.IsSubsetOf(bigCitiesset); Console.WriteLine($"big Uk cities subset of big cities list?: {bigUkIsSubset}"); Console.WriteLine(); var superSetOfUkCities = bigCitiesset.IsSupersetOf(citiesInUK); Console.WriteLine($"big cities list is superset of UK cities?: {superSetOfUkCities}"); var superSetOfBigUkCities = bigCitiesset.IsSupersetOf(bigUkCities); Console.WriteLine($"big cities list is superset of big UK cities?: {superSetOfBigUkCities}"); //yra dar IsProperSupersetOf() ir IsProperSubsetOf() //neskaito jei tur vienodus elementus???? //netru linq ekvivalentu visi metodai menti anksciau }
public static void Cozy() { Console.WriteLine("\n-----------------------------------------------"); Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName); Console.WriteLine("-----------------------------------------------"); //HashSet<T>和List<T>差不多的,但HashSet<T>只能包含不重复的元素 var hashSet = new HashSet<int>(); //Add()会返回一个bool值,添加成功返回true,集合内有相同的元素,则添加失败返回false Console.WriteLine(hashSet.Add(1)); //output True Console.WriteLine(hashSet.Add(1)); //output False Console.WriteLine(hashSet.Add(2)); Console.WriteLine(hashSet.Add(3)); var array = new[] {1, 2, 3, 4, 5}; Console.WriteLine(hashSet.IsSubsetOf(array)); //output True Console.WriteLine(hashSet.IsSupersetOf(array)); //output False //增加array集合的元素 hashSet.UnionWith(array); foreach (var i in hashSet) { Console.WriteLine(i); } //移除array集合的元素 hashSet.ExceptWith(array); foreach (var i in hashSet) { Console.WriteLine(i); } }
SubjectComparisonOutcome CompareSubjectDimensions <T>(HashSet <T> set1, HashSet <T> set2) { if (set1.Count == set2.Count && set1.IsSubsetOf(set2)) { return(SubjectComparisonOutcome.Equal); } else if (set1.Count < set2.Count && set1.IsProperSubsetOf(set2)) { return(SubjectComparisonOutcome.Parent); } else if (set1.Count > set2.Count && set1.IsProperSupersetOf(set2)) { return(SubjectComparisonOutcome.Child); } else if (set1.Overlaps(set2)) { return(SubjectComparisonOutcome.Overlap); } else { return(SubjectComparisonOutcome.Disjoint); } }
public int CompareSetsEasyWay(HashSet <int> a, HashSet <int> b) { if (a.IsSubsetOf(b)) { return(-1); } else if (a.IsSupersetOf(b)) { return(1); } else if (a.SetEquals(b)) { return(0); } else if (!a.IsSubsetOf(b) && !b.IsSubsetOf(a)) { return(-2); } else { return(2); } }
public SubjectCompareOutcome CompareTwoExpTypes(HashSet <ExposureType> list1, HashSet <ExposureType> list2) { if (list1.Count == list2.Count && list1.IsSubsetOf(list2)) { return(SubjectCompareOutcome.Equal); } else if (list1.Count < list2.Count && list1.IsProperSubsetOf(list2)) { return(SubjectCompareOutcome.Parent); } else if (list1.Count > list2.Count && list1.IsProperSupersetOf(list2)) { return(SubjectCompareOutcome.Child); } else if (list1.Overlaps(list2)) { return(SubjectCompareOutcome.Overlap); } else { return(SubjectCompareOutcome.Disjoin); } }
private static void CheckAssociatedMetadataType(Type mainType, Type associatedMetadataType) { // Only properties from main type HashSet <string> mainTypeMemberNames = new HashSet <string>(mainType.GetProperties().Select(p => p.Name)); // Properties and fields from buddy type var buddyFields = associatedMetadataType.GetFields().Select(f => f.Name); var buddyProperties = associatedMetadataType.GetProperties().Select(p => p.Name); HashSet <string> buddyTypeMembers = new HashSet <string>(buddyFields.Concat(buddyProperties), StringComparer.Ordinal); // Buddy members should be a subset of the main type's members if (!buddyTypeMembers.IsSubsetOf(mainTypeMemberNames)) { // Reduce the buddy members to the set not contained in the main members buddyTypeMembers.ExceptWith(mainTypeMemberNames); throw new InvalidOperationException(String.Format( CultureInfo.CurrentCulture, DataAnnotationsResources.AssociatedMetadataTypeTypeDescriptor_MetadataTypeContainsUnknownProperties, mainType.FullName, String.Join(", ", buddyTypeMembers.ToArray()))); } }
public SubsetCategories( HashSet <T> set, HashSet <T> subset, HashSet <HashSet <T> > topology) { // assert that the topology is a valid topology on the set if (!subset.IsSubsetOf(set)) { throw new Exception( "The given subset is not a valid subset of the set."); } // assert that the topology is a valid topology on the set if (!IsTopology(topology, set)) { throw new Exception( "The given topology is not a valid topology on the set."); } Set = set; Subset = subset; Topology = topology; }
/// <summary> /// Check if the user is authorized. /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="requestedScopes">The scopes the user has requested.</param> /// <returns><c>true</c>, if the user is authorized for the specified scopes; otherwise, <c>false</c>.</returns> private static bool UserIsAuthorizedForRequestedScopes(string userName, HashSet <string> requestedScopes) { // We define the scopes the user is authorized for. Once again, you would expect these scopes to be retrieved from // a persistent store. Note: the scopes a user is authorized for can very well differ between users. Think of an // admin user being authorized for more scopes than a regular user // Get the scopes the user is authorized for from the database. IOAuth2AuthorizationStoreAgent agent = DependencyInjection.Get <IOAuth2AuthorizationStoreAgent>(); IList <OAuth2Scope> scopes = agent.GetUserScopes(userName); HashSet <string> scopesUserIsAuthorizedFor = new HashSet <string>(OAuthUtilities.ScopeStringComparer); scopes.Select(x => x.Code).ToList().ForEach(x => { scopesUserIsAuthorizedFor.Add(x); }); // Check if the scopes that are being requested are a subset of the scopes the user is authorized for. // If not, that means that the user has requested at least one scope it is not authorized for bool userIsAuthorizedForRequestedScopes = requestedScopes.IsSubsetOf(scopesUserIsAuthorizedFor); return(userIsAuthorizedForRequestedScopes); }
public ScheduleCompareOutcome CompareTwoSchedules(IScheduleInput s1, IScheduleInput s2) { HashSet <RITE> list1 = s1.GetScheduleRITEList(); HashSet <RITE> list2 = s2.GetScheduleRITEList(); if (list1.Count == list2.Count && list1.IsSubsetOf(list2)) { if (s1.IsPerRisk == s2.IsPerRisk) { return(ScheduleCompareOutcome.Equal); } else if (s1.IsPerRisk && !s2.IsPerRisk) { return(ScheduleCompareOutcome.Parent); } else { return(ScheduleCompareOutcome.Child); } } else if (list1.Count < list2.Count && list1.IsProperSubsetOf(list2)) { return(ScheduleCompareOutcome.Parent); } else if (list1.Count > list2.Count && list1.IsProperSupersetOf(list2)) { return(ScheduleCompareOutcome.Child); } else if (list1.Overlaps(list2)) { return(ScheduleCompareOutcome.Overlap); } else { return(ScheduleCompareOutcome.Disjoin); } }
private void MaxFrequentSet(List <int[]> output, HashSet <int> available, SinglyLinkedList <int> build) { available.RemoveWhere(p => !IsFrequent(new SinglyLinkedList <int>(p, build))); if (available.Count == 0) { int[] addIn; try { addIn = build.ToArray(); } catch (ArgumentNullException) { addIn = new int[] { }; } // check that build is not a subset of any element in output HashSet <int> buildSet = new HashSet <int>(addIn); if (!output.Exists(p => buildSet.IsSubsetOf(p))) { output.Add(addIn); //Console.Write("{"); //for (int i = 0; i < addIn.Length; i++) // Console.Write("{0}{1}", addIn[i], (i == addIn.Length - 1) ? "" : ", "); //Console.WriteLine("}"); } } else if (!output.Exists(p => new HashSet <int>(build.Union(available)).IsSubsetOf(p))) { foreach (var i in available.ToArray()) { available.Remove(i); MaxFrequentSet(output, new HashSet <int>(available), new SinglyLinkedList <int>(i, build)); } } }
private List <SCPSet> Fitness(List <SCPSet> sets, List <SCPSet> union) { if (IsFeasible(sets)) { return(sets); } HashSet <int> attributes = new HashSet <int>(); double price = 0.0; sets.ForEach(s => { price += s.Cost; s.Attributes.ForEach(a => attributes.Add(a.Tag)); }); union.ForEach(set => { int frequency = set.Attributes.Select(a => a.Tag).Except(attributes).Count() + attributes.Count; set.Overhead = (set.Cost + price) / frequency; }); union = union.OrderBy(u => u.Overhead).ToList(); SCPSet best = union.First(); best.Visit = true; HashSet <int> additional = new HashSet <int>(); best.Attributes.ForEach(a => additional.Add(a.Tag)); if (additional.IsSubsetOf(attributes) == false) { sets.Add(best); } union = union.Where(set => set.Visit == false).ToList(); return(Fitness(sets, union)); }
public bool PreconditionVerification(QsCompilation compilation) { var controlNs = compilation.Namespaces .FirstOrDefault(ns => ns.Name.Equals(BuiltIn.ClassicallyControlledNamespace)); if (controlNs == null) { return(false); } var providedOperations = new QsNamespace[] { controlNs } .Callables() .Select(c => c.FullName) .ToHashSet(); var requiredBuiltIns = new HashSet <QsQualifiedName>() { BuiltIn.NoOp.FullName, BuiltIn.ApplyIfZero.FullName, BuiltIn.ApplyIfZeroA.FullName, BuiltIn.ApplyIfZeroC.FullName, BuiltIn.ApplyIfZeroCA.FullName, BuiltIn.ApplyIfOne.FullName, BuiltIn.ApplyIfOneA.FullName, BuiltIn.ApplyIfOneC.FullName, BuiltIn.ApplyIfOneCA.FullName, BuiltIn.ApplyIfElseR.FullName, BuiltIn.ApplyIfElseRA.FullName, BuiltIn.ApplyIfElseRC.FullName, BuiltIn.ApplyIfElseRCA.FullName }; return(requiredBuiltIns.IsSubsetOf(providedOperations)); }
private static bool MealContainsAllIngredients(Meal meal, int[] userIngredientIds) { var targetIngredients = new List <int>(); // Create list of ids found in meal foreach (var mealIngredient in meal.MealIngredients) { var ingredientId = mealIngredient.Ingredient.IngredientId; targetIngredients.Add(ingredientId); } // Convert to hash sets and compare meal ingredients with user ingredients var targetIngredientsHashSet = new HashSet <int>(targetIngredients); var userIngredientsHashSet = new HashSet <int>(userIngredientIds); if (userIngredientsHashSet.IsSubsetOf(targetIngredientsHashSet)) { return(true); } else { return(false); } }
/// <summary> /// Determines RFC2849 safe string compliance. /// </summary> /// <param name="value">The dn or attribute value.</param> /// <returns>Whether or not the string is ASCII safe.</returns> public static bool IsSafeString(this string value) { if (value == null) { throw new ArgumentNullException(nameof(value), "The attribute value can not be null."); } // RFC2849 note 5. if (string.IsNullOrEmpty(value)) { return(true); } // RFC2849 note 8. if (value[value.Length - 1] == 32) { return(false); } // RFC2849 note 4. HashSet <int> chars = new HashSet <int>(value.Select(x => (int)x)); return(chars.IsSubsetOf(Constants.SafeAsciiChars)); }
public bool Equals(Schedule s) { if (s == null) { return(false); } if (ScheduleSymbols == null && s.ScheduleSymbols == null) { return(true); } else if (ScheduleSymbols == null || s.ScheduleSymbols == null) { return(false); } else if (ScheduleSymbols.Count != s.ScheduleSymbols.Count) { return(false); } else { return(ScheduleSymbols.IsSubsetOf(s.ScheduleSymbols)); } }
private IndexMergeResults ExcludePartialResults(IndexMergeResults originalIndexes) { var resultingIndexMerge = new IndexMergeResults(); foreach (var suggestion in originalIndexes.Suggestions) { suggestion.CanMerge.Sort(); } bool hasMatch = false; for (int i = 0; i < originalIndexes.Suggestions.Count; i++) { var sug1 = originalIndexes.Suggestions[i]; for (int j = i + 1; j < originalIndexes.Suggestions.Count; j++) { var sug2 = originalIndexes.Suggestions[j]; if ((sug1 != sug2) && (sug1.CanMerge.Count <= sug2.CanMerge.Count)) { var sugCanMergeSet = new HashSet <string>(sug1.CanMerge); hasMatch = sugCanMergeSet.IsSubsetOf(sug2.CanMerge); if (hasMatch) { break; } } } if (!hasMatch) { resultingIndexMerge.Suggestions.Add(sug1); } hasMatch = false; } resultingIndexMerge.Unmergables = originalIndexes.Unmergables; return(resultingIndexMerge); }
public void IsSubsetOfTest() { var s1 = new HashSet <string>(NumGen(4, 2, 10)); Assert.That(() => s1.IsSubsetOf(null), Throws.Exception); var s2 = new HashSet <string>(NumGen(0, 2, 20)); Assert.That(s1.IsSubsetOf(s2), Is.True); var s3 = new HashSet <string>(NumGen(4, 2, 10)); Assert.That(s1.IsSubsetOf(s3), Is.True); var s4 = new HashSet <string>(NumGen(1, 2, 10)); Assert.That(s1.IsSubsetOf(s4), Is.False); s1.Clear(); Assert.That(s1.IsSubsetOf(s2), Is.True); s2.Clear(); Assert.That(s1.IsSubsetOf(s2), Is.True); }
/// <inheritdoc/> public bool IsSubsetOf(IEnumerable <TKey> other) { lock (_syncLock) return(_hashSet.IsSubsetOf(other)); }
private bool IsAuthorizationValid(HashSet<string> requestedScopes, string clientIdentifier, DateTime issuedUtc, string username) { var grantedScopeStrings = from auth in Database.DataContext.ClientAuthorizations where auth.Client.ClientIdentifier == clientIdentifier && auth.CreatedOnUtc <= issuedUtc && (!auth.ExpirationDateUtc.HasValue || auth.ExpirationDateUtc.Value >= DateTime.UtcNow) && auth.User.AuthenticationTokens.Any(token => token.ClaimedIdentifier == username) select auth.Scope; if (!grantedScopeStrings.Any()) { // No granted authorizations prior to the issuance of this token, so it must have been revoked. // Even if later authorizations restore this client's ability to call in, we can't allow // access tokens issued before the re-authorization because the revoked authorization should // effectively and permanently revoke all access and refresh tokens. return false; } var grantedScopes = new HashSet<string>(OAuthUtilities.ScopeStringComparer); foreach (string scope in grantedScopeStrings) { grantedScopes.UnionWith(OAuthUtilities.SplitScopes(scope)); } return requestedScopes.IsSubsetOf(grantedScopes); }
public override bool IsRelationshipSource(MappingEntity entity, MemberInfo member) { if (IsAssociationRelationship(entity, member)) { if (typeof(IEnumerable).IsAssignableFrom(TypeHelper.GetMemberType(member))) { return false; } // is source of relationship if relatedKeyMembers are the related entity's primary keys MappingEntity entity2 = GetRelatedEntity(entity, member); var relatedPKs = new HashSet<string>(this.GetPrimaryKeyMembers(entity2).Select(m => m.Name)); var relatedKeyMembers = new HashSet<string>( this.GetAssociationRelatedKeyMembers(entity, member).Select(m => m.Name)); return relatedPKs.IsSubsetOf(relatedKeyMembers) && relatedKeyMembers.IsSubsetOf(relatedPKs); } return false; }
// insert new join closest to the aliases it depends on private bool IsOuterDependent(bool isOuterDependent, SqlSource location, HashSet<SqlAlias> consumed, out HashSet<SqlAlias> produced) { if (location.NodeType == SqlNodeType.Join) { // walk down join tree looking for best location for join SqlJoin join = (SqlJoin)location; if (this.IsOuterDependent(isOuterDependent, join.Left, consumed, out produced)) return true; HashSet<SqlAlias> rightProduced; bool rightIsOuterDependent = join.JoinType == SqlJoinType.LeftOuter || join.JoinType == SqlJoinType.OuterApply; if (this.IsOuterDependent(rightIsOuterDependent, join.Right, consumed, out rightProduced)) return true; produced.UnionWith(rightProduced); } else { SqlAlias a = location as SqlAlias; if (a != null) { SqlSelect s = a.Node as SqlSelect; if (s != null && !isOuterDependent && s.From != null) { if (this.IsOuterDependent(false, s.From, consumed, out produced)) return true; } } produced = SqlGatherProducedAliases.Gather(location); } // look to see if this subtree fully satisfies join condition if (consumed.IsSubsetOf(produced)) { return isOuterDependent; } return false; }
public bool IsSubsetOf(IEnumerable <string> other) { return(_hashset.IsSubsetOf(other)); }
public bool IsSubsetOf(IEnumerable <T> other) { return(_set.IsSubsetOf(other)); }
public bool HasPermissions(params string[] permissions) { if (this.Permissions.Contains("*") || (permissions.Length == 1 && permissions[0] == "*")) { return true; } if (permissions.Length == 0 || (permissions.Length == 1 && string.IsNullOrEmpty(permissions[0]))) { return false; } HashSet<string> perms = new HashSet<string>(permissions); return perms.IsSubsetOf(this.Permissions); }
//-------------------------------------------------------------------------------------------------------------------------------- public bool IsSubsetOf(EnumHashSet <T> other) { return(Raw.IsSubsetOf(other.Raw)); }
void TestRetrieval(int offset, int length) { HashSet<TestTextSegment> actual = new HashSet<TestTextSegment>(tree.FindOverlappingSegments(offset, length)); HashSet<TestTextSegment> expected = new HashSet<TestTextSegment>(); foreach (TestTextSegment e in expectedSegments) { if (e.ExpectedOffset + e.ExpectedLength < offset) continue; if (e.ExpectedOffset > offset + length) continue; expected.Add(e); } Assert.IsTrue(actual.IsSubsetOf(expected)); Assert.IsTrue(expected.IsSubsetOf(actual)); }
public void AddNewFolder() { using (var app = new VisualStudioApp()) { var project = app.OpenProject(@"TestData\NodejsProjectData\HelloWorld.sln"); using (new NodejsOptionHolder(NodejsPackage.Instance.GeneralOptionsPage, "ShowBrowserAndNodeLabels", false)) { var window = app.OpenSolutionExplorer(); // find server.js, send copy & paste, verify copy of file is there var projectNode = window.WaitForItem("Solution 'HelloWorld' (1 project)", "HelloWorld"); AutomationWrapper.Select(projectNode); var startingDirs = new HashSet<string>(Directory.GetDirectories(@"TestData\NodejsProjectData\HelloWorld"), StringComparer.OrdinalIgnoreCase); Keyboard.PressAndRelease(Key.F10, Key.LeftCtrl, Key.LeftShift); Keyboard.PressAndRelease(Key.D); Keyboard.PressAndRelease(Key.Right); Keyboard.PressAndRelease(Key.D); Keyboard.Type("MyNewFolder"); var curDirs = new HashSet<string>(Directory.GetDirectories(@"TestData\NodejsProjectData\HelloWorld"), StringComparer.OrdinalIgnoreCase); Assert.IsTrue(curDirs.IsSubsetOf(startingDirs) && startingDirs.IsSubsetOf(curDirs), "new directory created" + String.Join(", ", curDirs) + " vs. " + String.Join(", ", startingDirs)); Keyboard.PressAndRelease(Key.Enter); Assert.AreNotEqual(null, window.WaitForItem("Solution 'HelloWorld' (1 project)", "HelloWorld", "MyNewFolder")); Assert.IsTrue(Directory.Exists(@"TestData\NodejsProjectData\HelloWorld\MyNewFolder")); } } }
protected void ShouldContain(ISet<ISet<Fault>> sets, params Fault[] faults) { foreach (var set in sets) { var faultSet = new HashSet<Fault>(faults); if (set.IsSubsetOf(faultSet) && faultSet.IsSubsetOf(set)) return; } throw new TestException("Fault set is not contained in set."); }
private void ComputeFollow() { StartNonterminal.Follow.Add(StopTerminal); // Continue adding elements until no more changes to FOLLOW are made. // bool change = true; while (change) { change = false; // Iterate over all nonterminals and their rules. // foreach (NonterminalType x in m_nonterminals.Values) { foreach (RuleType rule in x.Rules) { // For rules of the form X -> ... Y B1 B2 ... Bn, add FIRST(Bi) (excluding e) // to FOLLOW(Y) if FIRST(Bj) contains e for all j < i. Add FOLLOW(X) to // FOLLOW(Y) if FIRST(Bi) contains e for all i. // for (int idx = 0; idx < rule.Rhs.Length; ++idx) { if (rule.Rhs[idx].ElementType == LanguageElementTypes.Nonterminal) { NonterminalType y = (NonterminalType)rule.Rhs[idx]; bool epsilonInAllB = true; for (int j = idx + 1; j < rule.Rhs.Length; ++j) { LanguageElementType b = rule.Rhs[j]; HashSet <TerminalType> bFirst = b.First.GetSetExcludingEpsilon(); if (bFirst.Count > 0 && !bFirst.IsSubsetOf(y.Follow)) { y.Follow.UnionWith(bFirst); change = true; } if (!b.First.ContainsEpsilon) { epsilonInAllB = false; break; } } if (epsilonInAllB) { if (x.Follow.Count > 0 && !x.Follow.IsSubsetOf(y.Follow)) { y.Follow.UnionWith(x.Follow); change = true; } } } } } } } }
private bool IsAuthorizationValid(HashSet<string> requestedScopes, string clientIdentifier, DateTime issuedUtc, string username) { // If db precision exceeds token time precision (which is common), the following query would // often disregard a token that is minted immediately after the authorization record is stored in the db. // To compensate for this, we'll increase the timestamp on the token's issue date by 1 second. issuedUtc += TimeSpan.FromSeconds(1); var grantedScopeStrings = from auth in MvcApplication.DataContext.ClientAuthorizations where auth.Client.ClientIdentifier == clientIdentifier && auth.CreatedOnUtc <= issuedUtc && (!auth.ExpirationDateUtc.HasValue || auth.ExpirationDateUtc.Value >= DateTime.UtcNow) && auth.User.OpenIDClaimedIdentifier == username select auth.Scope; if (!grantedScopeStrings.Any()) { // No granted authorizations prior to the issuance of this token, so it must have been revoked. // Even if later authorizations restore this client's ability to call in, we can't allow // access tokens issued before the re-authorization because the revoked authorization should // effectively and permanently revoke all access and refresh tokens. return false; } var grantedScopes = new HashSet<string>(OAuthUtilities.ScopeStringComparer); foreach (string scope in grantedScopeStrings) { grantedScopes.UnionWith(OAuthUtilities.SplitScopes(scope)); } return requestedScopes.IsSubsetOf(grantedScopes); }
protected Expression Compare(BinaryExpression bop) { var e1 = this.SkipConvert(bop.Left); var e2 = this.SkipConvert(bop.Right); OuterJoinedExpression oj1 = e1 as OuterJoinedExpression; OuterJoinedExpression oj2 = e2 as OuterJoinedExpression; EntityExpression entity1 = oj1 != null ? oj1.Expression as EntityExpression : e1 as EntityExpression; EntityExpression entity2 = oj2 != null ? oj2.Expression as EntityExpression : e2 as EntityExpression; bool negate = bop.NodeType == ExpressionType.NotEqual; // check for outer-joined entity comparing against null. These are special because outer joins have // a test expression specifically desgined to be tested against null to determine if the joined side exists. if (oj1 != null && e2.NodeType == ExpressionType.Constant && ((ConstantExpression)e2).Value == null) { return MakeIsNull(oj1.Test, negate); } else if (oj2 != null && e1.NodeType == ExpressionType.Constant && ((ConstantExpression)e1).Value == null) { return MakeIsNull(oj2.Test, negate); } // if either side is an entity construction expression then compare using its primary key members if (entity1 != null) { return this.MakePredicate(e1, e2, this.mapping.GetPrimaryKeyMembers(entity1.Entity), negate); } else if (entity2 != null) { return this.MakePredicate(e1, e2, this.mapping.GetPrimaryKeyMembers(entity2.Entity), negate); } // check for comparison of user constructed type projections var dm1 = this.GetDefinedMembers(e1); var dm2 = this.GetDefinedMembers(e2); if (dm1 == null && dm2 == null) { // neither are constructed types return bop; } if (dm1 != null && dm2 != null) { // both are constructed types, so they'd better have the same members declared HashSet<string> names1 = new HashSet<string>(dm1.Select(m => m.Name)); HashSet<string> names2 = new HashSet<string>(dm2.Select(m => m.Name)); if (names1.IsSubsetOf(names2) && names2.IsSubsetOf(names1)) { return MakePredicate(e1, e2, dm1, negate); } } else if (dm1 != null) { return MakePredicate(e1, e2, dm1, negate); } else if (dm2 != null) { return MakePredicate(e1, e2, dm2, negate); } throw new InvalidOperationException("Cannot compare two constructed types with different sets of members assigned."); }
public static bool IsQualifiedSubset(QualifiedSubset subsetToTest, AccessStructure miniamlAccess) { foreach (var qualifiedSet in miniamlAccess.Accesses) { if (!(qualifiedSet is QualifiedSubset)) continue; HashSet<int> a = new HashSet<int>(subsetToTest.Parties.Select(x => x.GetPartyId())); var qs = (QualifiedSubset)qualifiedSet; HashSet<int> b = new HashSet<int>(qs.Parties.Select(x => x.GetPartyId())); if (b.IsProperSubsetOf(a) || b.IsSubsetOf(a)) return true; } return false; }
/// <summary> /// Checks the supplied Commandline Arguments for valid switches /// </summary> /// <param name="CommandArgs">String Array of arguments</param> public static bool ValidArgs(string[] CommandArgs) { HashSet<string> possibleArgs = new HashSet<string> { "-D", "-W", "-A", "-Q" }; HashSet<string> passedArgs = new HashSet<string>(); foreach (string str in CommandArgs) { passedArgs.Add(str); } bool isSubset = !passedArgs.IsSubsetOf(possibleArgs); return true; }
private void ComputeClosure(IGrammar grammar, HashSet<GeneratorStateItem> items) { // Continue to loop until new more elements are added to the state. // bool stateModified = true; while (stateModified) { HashSet<GeneratorStateItem> newItems = new HashSet<GeneratorStateItem>(); // Iterate over the current elements in the state and determine (possible) new // elements to be added. // foreach (GeneratorStateItem item in items) { LanguageElementType languageElement = item.RuleItem.DotElement; if (languageElement != null && languageElement.ElementType == LanguageElementTypes.Nonterminal) { NonterminalType nonterminal = (NonterminalType)languageElement; foreach (RuleType rule in nonterminal.Rules) { GeneratorStateItem newItem = new GeneratorStateItem(new GeneratorRuleItem(rule, 0)); newItems.Add(newItem); } } } // Exit loop if all potential new elements already exist in state. Otherwise, add new elements // and repeat process. // if (newItems.IsSubsetOf(items)) { stateModified = false; } else { items.UnionWith(newItems); } } }
/// <summary> /// 尝试从路由值创建虚拟路径 /// </summary> /// <param name="requestContext">当前请求上下文</param> /// <param name="values">路由值</param> /// <returns>虚拟路径信息</returns> public override VirtualPathData GetVirtualPath( RequestContext requestContext, RouteValueDictionary values ) { var cache = requestContext.HttpContext.Cache; var _values = values.ToDictionary( pair => pair.Key, pair => pair.Value == null ? null : pair.Value.ToString(), StringComparer.OrdinalIgnoreCase ); var cacheKey = CreateCacheKey( _values ); var virtualPath = cache.Get( cacheKey ) as string; if ( virtualPath != null ) return new VirtualPathData( this, virtualPath ); var keySet = new HashSet<string>( _values.Keys, StringComparer.OrdinalIgnoreCase ); var candidateRules = _rules .Where( r => !r.Oneway ) //不是单向路由规则 .Where( r => keySet.IsSupersetOf( r.RouteKeys ) ) //所有路由键都必须匹配 .Where( r => keySet.IsSubsetOf( r.AllKeys ) || !r.LimitedQueries ) //所有路由键和查询字符串键必须能涵盖要设置的键。 .Where( r => r.IsMatch( _values ) ) //必须满足路由规则所定义的路由数据。 .ToArray(); if ( !candidateRules.Any() ) return null; var bestRule = BestRule( candidateRules ); virtualPath = bestRule.CreateVirtualPath( _values ); if ( MvcCompatible ) virtualPath = virtualPath.Substring( 2 ); cache.Insert( cacheKey, virtualPath, CacheItemPriority.AboveNormal ); var data = new VirtualPathData( this, virtualPath ); foreach ( var pair in bestRule.DataTokens ) data.DataTokens.Add( pair.Key, pair.Value ); data.DataTokens["RoutingRuleName"] = bestRule.Name; return data; }
public bool IsSubsetOf(IEnumerable <string> other) => Flags.IsSubsetOf(other);
/// <summary> /// Check if the requested scope is valid. /// </summary> /// <param name="requestedScope">The scope the user has requested.</param> /// <param name="authorizedScope">The scope the user is authorized for.</param> /// <returns><c>true</c>, if the user is authorized for the specified scope; otherwise, <c>false</c>.</returns> private static bool RequestedScopeIsValid(HashSet<string> requestedScope, HashSet<string> authorizedScope) { // Check if the requested scope is a subset of the authorized scope. // If not, that means that the user has requested at least one scope it is not authorized for return requestedScope.IsSubsetOf(authorizedScope); }
/// <summary> /// Determines whether the hash set is a subset of the specified collection. /// </summary> /// <param name="other">The collection to compare to the current hash set.</param> /// <returns> /// <see langword="true" /> if the hash set is a subset of other; otherwise, <see langword="false" />. /// </returns> public virtual bool IsSubsetOf(IEnumerable <T> other) => _set.IsSubsetOf(other);
private void ComputeFirst() { // All terminals contains themselves in FIRST. // foreach (TerminalType terminalType in m_terminals.Values) { terminalType.First.Add(terminalType); } // For nonterminals, continue adding elements until no more changes to FIRST are made. // bool change = true; while (change) { change = false; // Iterate over all nonterminals and their rules. // foreach (NonterminalType x in m_nonterminals.Values) { foreach (RuleType rule in x.Rules) { if (rule.Rhs.Length == 0) { // If the rule X -> e exists, add e to FIRST(X). // if (!x.First.Contains(null)) { x.First.Add(null); change = true; } } else { // For rules of the form X -> Y1 Y2 Y3 ... Yn, add FIRST(Yi) to FIRST(X) // when e is in FIRST(Yj) for j < i. Add e to FIRST(X) if e is in // FIRST(Yi) for all i. // bool epsilonInAllY = true; foreach (LanguageElementType y in rule.Rhs) { HashSet <TerminalType> yFirst = y.First.GetSetExcludingEpsilon(); if (yFirst.Count > 0 && !yFirst.IsSubsetOf(x.First)) { x.First.UnionWith(yFirst); change = true; } if (!y.First.ContainsEpsilon) { epsilonInAllY = false; break; } } if (epsilonInAllY && !x.First.ContainsEpsilon) { x.First.Add(null); change = true; } } } } } }
public override bool IsRelationshipTarget(MappingEntity entity, MemberInfo member) { if (IsAssociationRelationship(entity, member)) { if (typeof(IEnumerable).IsAssignableFrom(TypeHelper.GetMemberType(member))) { return true; } // is target of relationship if the assoctions keys are the same as this entities primary key var pks = new HashSet<string>(this.GetPrimaryKeyMembers(entity).Select(m => m.Name)); var keys = new HashSet<string>(this.GetAssociationKeyMembers(entity, member).Select(m => m.Name)); return keys.IsSubsetOf(pks) && pks.IsSubsetOf(keys); } return false; }
public Episode[] GetShowEpisode(string originalShowName, int season, int episode, CancellationToken token) { var episodes = new List<Episode>(); var list = GetShows(token); var showWords = FileData.GetWordset(originalShowName).ToList(); var showName = string.Join(" ", showWords); Show exactShow = null; if (this.CustomMappings.Contains(showName)) { var custom = this.CustomMappings[showName]; exactShow = list.FirstOrDefault(s => s.Title.Equals(custom.ShowName, StringComparison.CurrentCultureIgnoreCase)); } if (exactShow == null) { exactShow = list.FirstOrDefault(s => s.NormalizedTitle.Equals(showName)) ?? list.FirstOrDefault( s => s.Directory.Equals(showName, StringComparison.CurrentCultureIgnoreCase)) ?? list.FirstOrDefault( s => s.Title.Equals(showName, StringComparison.CurrentCultureIgnoreCase)); } if (exactShow == null) { var ss = new HashSet<string>(showWords); foreach (var sh in list.Where(s => ss.IsSubsetOf(s.ExtendedWordset))) { Episode ep; if (!sh.TryGetEpisode(token, season, episode, out ep)) { ep = new Episode(sh.Title, season.ToString(CultureInfo.InvariantCulture), episode.ToString(CultureInfo.InvariantCulture), "", false); } episodes.Add(ep); } } else { Episode episodeItem; if (exactShow.TryGetEpisode(token, season, episode, out episodeItem)) { episodes.Add(episodeItem); } } return episodes.ToArray(); }
public bool CheckIsRefinement(ModuleDecl derived, ModuleFacadeDecl original) { // Check explicit refinement // TODO syntactic analysis of export sets is not quite right var derivedPointer = derived.Signature.ModuleDef; while (derivedPointer != null) { if (derivedPointer == original.OriginalSignature.ModuleDef) { HashSet<string> exports; if (derived is AliasModuleDecl) { exports = new HashSet<string>(((AliasModuleDecl)derived).Exports.ConvertAll(t => t.val)); } else if (derived is ModuleFacadeDecl) { exports = new HashSet<string>(((ModuleFacadeDecl)derived).Exports.ConvertAll(t => t.val)); } else { reporter.Error(MessageSource.RefinementTransformer, derived, "a module ({0}) can only be refined by an alias module or a module facade", original.Name); return false; } var oexports = new HashSet<string>(original.Exports.ConvertAll(t => t.val)); return oexports.IsSubsetOf(exports); } derivedPointer = derivedPointer.RefinementBase; } return false; }