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));
		}
Example #2
0
 public bool IsScopeSatisfied(HashSet<string> requiredScope, HashSet<string> grantedScope)
 {
     if (requiredScope.IsSubsetOf(grantedScope))
     {
         return true;
     }
     return false;
 }
Example #3
0
        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;
 }
 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>
		/// 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);
		}
Example #8
0
        /// <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.");
        }
Example #12
0
        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;
        }
Example #13
0
        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 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.");
		}
Example #15
0
        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 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;
 }
        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;
        }
		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;
		}
Example #19
0
 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));
 }
 /// <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);
 }
Example #21
0
            // 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;
            }
Example #22
0
        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"));
                }
            }
        }
		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);
		}
Example #24
0
        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();
        }
Example #25
0
 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);
 }
		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);
		}
Example #27
0
        /// <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;
        }
		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;
		}
Example #29
0
        /// <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;
        }
Example #30
0
        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);
                }
            }
        }