private static IEnumerable<Type> FilterTypesInAssemblies(IBuildManager buildManager, Predicate<Type> predicate)
        {
            // Go through all assemblies referenced by the application and search for types matching a predicate
            IEnumerable<Type> typesSoFar = Type.EmptyTypes;

            ICollection assemblies = buildManager.GetReferencedAssemblies();
            foreach (Assembly assembly in assemblies)
            {
                Type[] typesInAsm;
                try
                {
                    try
                    {
                        typesInAsm = assembly.GetExportedTypes();
                    }
                    catch (NotImplementedException)
                    {
                        typesInAsm = assembly.GetTypes();
                    }
                }
                catch (ReflectionTypeLoadException ex)
                {
                    typesInAsm = ex.Types;
                }
                typesSoFar = typesSoFar.Concat(typesInAsm);
            }
            return typesSoFar.Where(type => TypeIsPublicClass(type) && predicate(type));
        }
        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null) throw new ArgumentNullException("execute");

            _execute = execute;
            _canExecute = canExecute;
        }
Exemple #3
0
 public void InitializeButtonState(Mubox.Configuration.KeySettingCollection keySettings, Predicate<Mubox.Configuration.KeySetting> filterCallback, Action<Mubox.Configuration.KeySetting> enableCallback, Action<Mubox.Configuration.KeySetting> disableCallback)
 {
     this.KeySettings = keySettings;
     this.FilterCallback = filterCallback;
     this.EnableCallback = enableCallback;
     this.DisableCallback = disableCallback;
     ProcessFrameworkElementTree(this, (Action<FrameworkElement>)delegate(FrameworkElement frameworkElement)
     {
         try
         {
             System.Windows.Controls.Primitives.ToggleButton toggleButton = frameworkElement as System.Windows.Controls.Primitives.ToggleButton;
             if (toggleButton != null)
             {
                 Mubox.Configuration.KeySetting keySetting;
                 toggleButton.IsChecked =
                     KeySettings.TryGetKeySetting((WinAPI.VK)Enum.Parse(typeof(WinAPI.VK), toggleButton.Tag as string, true), out keySetting)
                     && FilterCallback(keySetting);
             }
         }
         catch (Exception ex)
         {
             ex.Log();
         }
     });
 }
        internal static AssemblyLoaderPathNameCriterion NewCriterion(Predicate predicate)
        {
            if (predicate == null)
                throw new ArgumentNullException("predicate");

            return new AssemblyLoaderPathNameCriterion(predicate);
        }
		public AddNewConfigurationDialog(bool solution, bool editPlatforms,
		                                 IEnumerable<string> availableSourceItems,
		                                 Predicate<string> checkNameValid)
		{
			this.checkNameValid = checkNameValid;
			
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			foreach (Control ctl in this.Controls) {
				ctl.Text = StringParser.Parse(ctl.Text);
			}
			
			createInAllCheckBox.Visible = solution;
			nameTextBox.TextChanged += delegate {
				okButton.Enabled = nameTextBox.TextLength > 0;
			};
			copyFromComboBox.Items.Add(StringParser.Parse("${res:Dialog.EditAvailableConfigurationsDialog.EmptyItem}"));
			copyFromComboBox.Items.AddRange(availableSourceItems.ToArray());
			copyFromComboBox.SelectedIndex = 0;
			
			if (solution) {
				if (editPlatforms)
					this.Text = StringParser.Parse("${res:Dialog.EditAvailableConfigurationsDialog.AddSolutionPlatform}");
				else
					this.Text = StringParser.Parse("${res:Dialog.EditAvailableConfigurationsDialog.AddSolutionConfiguration}");
			} else {
				if (editPlatforms)
					this.Text = StringParser.Parse("${res:Dialog.EditAvailableConfigurationsDialog.AddProjectPlatform}");
				else
					this.Text = StringParser.Parse("${res:Dialog.EditAvailableConfigurationsDialog.AddProjectConfiguration}");
			}
		}
        public ActionCommand(Action<Object> execute, Predicate<Object> canExecute = null)
        {
            if (execute == null) throw new ArgumentNullException(nameof(execute));

            this.execute = execute;
            this.canExecute = canExecute ?? (parameter => true);
        }
Exemple #7
0
        /// <summary>
        /// Gets the replacement for the specified placeholder for the specified object.
        /// </summary>
        /// <param name="placeholder">The placeholder to be replaced.</param>
        /// <param name="objs">The objects that the placeholder replacements are for.</param>
        /// <param name="match">A predicate indicating whether the specified placeholder should be replaced.</param>
        /// <returns>The replacement for the specified placeholder.</returns>
        private static string GetPlaceholderReplacement(string placeholder, IList<IXenObject> objs, Predicate<string> match)
        {
            if (match(placeholder))
            {
                if (objs == null || objs.Count == 0)
                    return NULL_PLACEHOLDER_KEY;

                if (objs.Count > 1)
                    return MULTI_TARGET_PLACEHOLDER_KEY;

                if (placeholder == "session_id")
                {
                    if (objs[0].Connection == null || objs[0].Connection.Session == null)
                    {
                        return NULL_PLACEHOLDER_KEY;
                    }
                    return objs[0].Connection.Session.uuid;
                }
                else
                {
                    // otherwise update url with the latest info
                    PropertyNames property = (PropertyNames)Enum.Parse(typeof(PropertyNames), placeholder);

                    object val = PropertyAccessors.Get(property)(objs[0]);
                    return val != null ? val.ToString() : NULL_PLACEHOLDER_KEY;
                }
            }

            return null;
        }
        /// <summary>
        /// Branches the request pipeline based on the result of the given predicate.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="predicate">Invoked with the request environment to determine if the branch should be taken</param>
        /// <param name="configuration">Configures a branch to take</param>
        /// <returns></returns>
        public static IApplicationBuilder MapWhen(this IApplicationBuilder app, Predicate predicate, Action<IApplicationBuilder> configuration)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (predicate == null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            // create branch
            var branchBuilder = app.New();
            configuration(branchBuilder);
            var branch = branchBuilder.Build();

            // put middleware in pipeline
            var options = new MapWhenOptions
            {
                Predicate = predicate,
                Branch = branch,
            };
            return app.Use(next => new MapWhenMiddleware(next, options).Invoke);
        }
        public void LoadsRequestedFilteredRecords()
        {
            this.logSource
                .Setup(x => x.ReadRecordAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
                .Returns(
                    (int index, CancellationToken cancellationToken) => Task.FromResult(new Record {Index = index}));

            this.filter = record => record.Message == "B";

            this.records.OnNext(new Record {Index = 3, Message = "A"});
            this.records.OnNext(new Record {Index = 4, Message = "B"});
            this.records.OnNext(new Record {Index = 5, Message = "B"});

            this.testScheduler.AdvanceBy(TimeSpan.FromMinutes(5).Ticks);

            var record1 = this.collection[0];
            var record2 = this.collection[1];

            var loaded = this.collection.LoadingRecordCount.Where(x => x == 0).FirstAsync().ToTask();

            this.testScheduler.AdvanceBy(TimeSpan.FromMinutes(5).Ticks);

            loaded.Wait();

            Assert.True(record1.IsLoaded);
            Assert.True(record2.IsLoaded);
        }
        private void LoadingWork(Predicate<IDataReader> readWhile = null)
        {
            if (readWhile == null)
            {
                readWhile = r => true;
            }

            var index = 0;
            if (_Reader.Read())
            {
                var columns = _Reader.GetColumnNames();

                do
                {
                    if (!readWhile(_Reader))
                    {
                        break;
                    }

                    _LoadedRows.Add(new DataRow(index++)
                    {
                        ColumnNames = columns,
                        Values = _Reader.GetValues()
                    });

                } while (_Reader.Read());

            }

            _LoadedRows.CompleteAdding();
            _Reader.Close();
        }
		private SqlExpressionFinder(Predicate<Expression> isMatch, bool findFirst)
		{
			this.isMatch = isMatch;
			this.findFirst = findFirst;

			this.results = new List<Expression>();
		}
Exemple #12
0
        /// <summary>
        /// Constructs a new Response with the specified properties.
        /// </summary>
        /// <param name="rule">The rule used to decide if the response should be returned.</param>
        /// <param name="message">A function that builds the HttpResponseMessage to be returned.</param>
        public Response(Predicate<Request> rule, Func<HttpResponseMessage> message)
        {
            if (message == null) throw new ArgumentNullException("message");

            Rule = rule;
            Message = message;
        }
        public static SyntaxToken GetTouchingToken(
            this SyntaxTree syntaxTree,
            int position,
            Predicate<SyntaxToken> predicate,
            CancellationToken cancellationToken,
            bool findInsideTrivia = false)
        {
            // Contract.ThrowIfNull(syntaxTree);

            if (position >= syntaxTree.Length)
            {
                return default(SyntaxToken);
            }

            var token = syntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia);

            if ((token.Span.Contains(position) || token.Span.End == position) && predicate(token))
            {
                return token;
            }

            token = token.GetPreviousToken();

            if (token.Span.End == position && predicate(token))
            {
                return token;
            }

            // SyntaxKind = None
            return default(SyntaxToken);
        }
 /// <summary>
 /// Initializes a new instance of <see cref="ViewsCollection"/>.
 /// </summary>
 /// <param name="list">The list to wrap and filter.</param>
 /// <param name="filter">A predicate to filter the <paramref name="list"/> collection.</param>
 public ViewsCollection(ObservableCollection<ItemMetadata> list, Predicate<ItemMetadata> filter)
 {
     this.subjectCollection = list;
     this.filter = filter;
     Initialize();
     subjectCollection.CollectionChanged += UnderlyingCollection_CollectionChanged;
 }
Exemple #15
0
        public static ComPtr<IDiaSymbol> GetSymbol(this IDiaSymbol symbol, SymTagEnum symTag, string name, Predicate<IDiaSymbol> filter = null) {
            var result = new ComPtr<IDiaSymbol>();

            IDiaEnumSymbols enumSymbols;
            symbol.findChildren(symTag, name, 1, out enumSymbols);
            using (ComPtr.Create(enumSymbols)) {
                int n = enumSymbols.count;
                if (n == 0) {
                    Debug.Fail("Symbol '" + name + "' was not found.");
                    throw new ArgumentException();
                }

                try {
                    for (int i = 0; i < n; ++i) {
                        using (var item = ComPtr.Create(enumSymbols.Item((uint)i))) {
                            if (filter == null || filter(item.Object)) {
                                if (result.Object == null) {
                                    result = item.Detach();
                                } else {
                                    Debug.Fail("Found more than one symbol named '" + name + "' and matching the filter.");
                                    throw new ArgumentException();
                                }
                            }
                        }
                    }
                } catch {
                    result.Dispose();
                    throw;
                }
            }

            return result;
        }
        public virtual IEnumerable<InstrumentationTarget> GetInstrumentationSet(string assemblyPath, InstrumentAttribute context, Predicate<ITypeDetails> typeFilter)
        {
            var toReturn = new List<InstrumentationTarget>();

            _logger.InfoFormat("Processing assembly {0}", assemblyPath);

            if (typeFilter == null)
            {
                typeFilter = x => true;
            }

            var allTypes = this.GetTypes(assemblyPath).Where(x => x.IsClass && !x.IsNested && typeFilter(x));
            _logger.DebugFormat("Found {0} types", allTypes.Count());

            InstrumentAttribute assyContext = null;

            if (allTypes.Any())
            {
                assyContext = allTypes.First().Assembly.InstrumentationContext;
            }

            foreach (var t in allTypes)
            {
                toReturn.AddRange(GetInstrumentationSet(t, InstrumentAttribute.GetEffectiveInstrumentationContext(assyContext, context)));
            }

            return toReturn;
        }
Exemple #17
0
 /// <summary>
 /// Finds a mobile using the predicate passed.
 /// </summary>
 /// <param name="predicate">The predicate to match.</param>
 /// <returns>The IMobile found.</returns>
 public Thing FindMobile(Predicate<Thing> predicate)
 {
     lock (this.lockObject)
     {
         return this.mobiles.Find(predicate);
     }
 }
Exemple #18
0
 public static void ReadInMemory(FileInfo zipFileName, Predicate<ZipEntry> filter, Action<MemoryStream> action)
 {
     using (ZipInputStream inputStream = new ZipInputStream(zipFileName.OpenRead()))
     {
         ZipEntry entry;
         while ((entry = inputStream.GetNextEntry()) != null)
         {
             if (filter(entry))
             {
                 using (MemoryStream stream = new MemoryStream())
                 {
                     int count = 0x800;
                     byte[] buffer = new byte[0x800];
                     if (entry.Size <= 0L)
                     {
                         goto Label_0138;
                     }
                 Label_0116:
                     count = inputStream.Read(buffer, 0, buffer.Length);
                     if (count > 0)
                     {
                         stream.Write(buffer, 0, count);
                         goto Label_0116;
                     }
                 Label_0138:
                     stream.Position = 0;
                     action(stream);
                 }
             }
         }
     }
 }
 public DelegateCommand(Action<object> execute,
     Predicate<object> canExecute)
 {
     _execute = execute;
     _canExecute = canExecute;
     _isRunning = false;
 }
Exemple #20
0
        internal void AddMatch(string s, Location ml, bool offsetPos, Predicate<ChangeType> changeTypeSelector)
        {
            Location mlDup = ml.Clone() as Location;
            int charsToGoBack = s.Length - 1 ;
            if (offsetPos)
            {
                mlDup.CharOffset--;
                mlDup.RedlineCharPos--;
            }

            if (mlDup.CharOffset == -1)
            {
                mlDup.CharOffset = 0;
                charsToGoBack++;
            }

            // we are looking at the last char in the string when we get called, so offset back to the first
            WorkBackwards(mlDup, charsToGoBack, changeTypeSelector);

#if DEBUG
            TextRun tr = mlDup.TargetObject as TextRun;
            Debug.Assert(tr != null);
            if (mlDup.CharOffset + mlDup.Length <= tr.Content.Length)
            {
                string sCheck = tr.Content.Substring(mlDup.CharOffset, mlDup.Length);
                Debug.Assert(sCheck.ToUpper() == s.ToUpper());
            }
            else
            {
                Debug.Assert(s.ToUpper().StartsWith(tr.Content.ToUpper().Substring(mlDup.CharOffset)));
            }
#endif

            MatchLocations.Add(mlDup);
        }
Exemple #21
0
		public SnapshotPoint? GetPoint(Predicate<ITextBuffer> match, PositionAffinity affinity) {
			if (match == null)
				throw new ArgumentNullException(nameof(match));
			if (match(AnchorBuffer))
				return GetPoint(AnchorBuffer.CurrentSnapshot, affinity);
			return null;
		}
        /// <summary>
        /// 获取当前项目中满足指定条件的类型集合
        /// 首先从缓存文件中查询,若无缓存则遍历所有引用的程序集,并最后保存到缓存文件中
        /// </summary>
        /// <param name="cacheName">缓存文件名</param>
        /// <param name="predicate">类型匹配的规则(一个委托)</param>
        /// <param name="buildManager">操作类型缓存的组件</param>
        /// <returns>匹配的类型集合</returns>
        public static List<Type> GetFilteredTypesFromAssemblies(string cacheName, Predicate<Type> predicate, IBuildManager buildManager)
        {
            //类型缓存序列化器
            TypeCacheSerializer serializer = new TypeCacheSerializer();

            //首先从本地磁盘读取缓存路由的缓存文件,获取缓存的区域路由的类型集合
            // first, try reading from the cache on disk
            List<Type> matchingTypes = ReadTypesFromCache(cacheName, predicate, buildManager, serializer);
            if (matchingTypes != null)
            {
                return matchingTypes;
            }

            //如果没有读取到路由的缓存信息,则枚举每一个程序集寻找匹配的类型
            //即寻找继承了AreaRegistration的类,并且包含无参构造函数
            // if reading from the cache failed, enumerate over every assembly looking for a matching type
            matchingTypes = FilterTypesInAssemblies(buildManager, predicate).ToList();


            // 将类型信息保存到XML文件中作为缓存
            // C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\985b57d0\89016edd\UserCache\MVC-AreaRegistrationTypeCache.xml
            // finally, save the cache back to disk
            SaveTypesToCache(cacheName, matchingTypes, buildManager, serializer);

            return matchingTypes;
        }
Exemple #23
0
		public static void PurifySpellVars()
		{
			VarFilter = delegate(string var)
			{
				Console.Write("Change {0}? (y/n): ", var);
				bool change = Console.ReadKey().KeyChar == 'y';
				if (change)
				{
					Console.WriteLine(" - Changing...");
				}
				else
				{
					Console.WriteLine(" - Skipping...");
				}
				return change;
			};

			PurifyFiles(
				"./WCell.RealmServer/Spells",
				CsFileFilter,
				false,
				"./backups",
				new[]
					{
						"TODO",
						"DBC",
						"IO"
					});
		}
    /// <summary>
    /// Initializes a new instance of the command.
    /// </summary>
    /// <param name="canExecuteDelegate">Checks whether the command can be executed
    /// or not. This delegate is being invoked if <see cref="CanExecute"/> is being
    /// called. Might be null in order to always enable the command.</param>
    /// <param name="executeDelegate">An action that is being invoked if the command
    /// executes (<see cref="Execute"/> is being invoked).</param>
    /// <exception cref="ArgumentNullException">If <paramref name="executeDelegate"/>
    /// is a null reference.</exception>
    public DelegateCommand(Predicate<object> canExecuteDelegate, Action<object> executeDelegate)
    {
      if (executeDelegate == null) throw new ArgumentNullException("executeDelegate");
      ExecuteAction = executeDelegate;

      CanExecutePredicate = canExecuteDelegate;
    }
        // TODO -- this is so common here and in FubuMVC, just get something into FubuCore
        public static IEnumerable<Assembly> AssembliesFromPath(string path, Predicate<Assembly> assemblyFilter)
        {
            var assemblyPaths = Directory.GetFiles(path)
                .Where(file =>
                       Path.GetExtension(file).Equals(
                           ".exe",
                           StringComparison.OrdinalIgnoreCase)
                       ||
                       Path.GetExtension(file).Equals(
                           ".dll",
                           StringComparison.OrdinalIgnoreCase));

            foreach (string assemblyPath in assemblyPaths)
            {
                Assembly assembly =
                    AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(
                        x => x.GetName().Name == Path.GetFileNameWithoutExtension(assemblyPath));

                if (assembly == null)
                {
                    try
                    {
                        assembly = Assembly.LoadFrom(assemblyPath);
                    }
                    catch
                    {
                    }
                }

                if (assembly != null && assemblyFilter(assembly))
                {
                    yield return assembly;
                }
            }
        }
        public static FrameworkElement Find(this DependencyObject parent, Predicate<FrameworkElement> predicate)
        {
            if (parent is FrameworkElement)
                if (predicate((FrameworkElement)parent))
                    return (FrameworkElement)parent;

            foreach (var child in GetChildren(parent))
            {
                try
                {
                    var childElement = child as FrameworkElement;
                    if (childElement != null)
                        if (predicate(childElement))
                            return childElement;
                        else
                        {
                            var result = childElement.Find(predicate);
                            if (result != null)
                                return result;
                        }
                }
                catch { }
            }

            return null;
        }
Exemple #27
0
 public Rule(Parser parser, RuleType ruleType, Predicate<Parser> lookAhead, RuleDelegate evaluate)
 {
     _parser = parser;
     _ruleType = ruleType;
     _lookAhead = lookAhead;
     _evaluate = evaluate;
 }
Exemple #28
0
 public FlvParser(Stream stream, Predicate<FlvTag> exec)
 {
     FLVHeader header = FLVHeader.ReadHeader(stream);
     if (!header.IsFlv) {
         this.IsFlv = false;
         return;
     }
     this.IsFlv = true;
     stream.Seek(header.Length, SeekOrigin.Begin);
     Tags = new List<FlvTag>();
     FlvTag tag;
     while ((tag = FlvTag.ReadTag(stream)) != null) {
         if (tag is ScriptTag) {
             this.MetaTag = tag as ScriptTag;
         }
         Tags.Add(tag);
         if (Duration < tag.TimeStamp)
             Duration = tag.TimeStamp;
         if (exec != null) {
             if (!exec(tag)) {
                 break;
             }
         }
     }
     if (Tags.Count > 1) {
         this.Length = stream.Length - Tags[1].Offset + 11; //+ FlvMain.c_HeaderSize;
         this.Rate = (this.Duration == 0 ? 0 : this.Length * 8 / this.Duration);
     }
 }
 public CremationTarget(string label, Predicate<Thing> p, int naturalPriority, Droid c)
 {
     this.label = label;
     this.naturalPriority = naturalPriority;
     this.Accepts = p;
     this.crematorius = c;
 }
Exemple #30
0
 public int FindIndex(int startIndex, Predicate <T> match)
 {
     Contract.Ensures(Contract.Result <int>() >= -1);
     Contract.Ensures(Contract.Result <int>() < startIndex + Count);
     return(FindIndex(startIndex, _size - startIndex, match));
 }
Exemple #31
0
 public void Subscribe <T>(Predicate <T> condition)
 {
     throw new NotImplementedException();
 }
Exemple #32
0
        public static void FindChildren <T>(this DependencyObject obj, IList <T> accumulator, Predicate <T> predicate) where T : DependencyObject
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj), "DependencyObject reference mustn't be null.");
            }
            if (accumulator == null)
            {
                throw new ArgumentNullException(nameof(accumulator), "List reference mustn't be null.");
            }
            if (predicate == null)
            {
                throw new ArgumentNullException(nameof(predicate), "Predicate reference mustn't be null.");
            }
            for (var i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);
                if (child is T && predicate((T)child))
                {
                    accumulator.Add((T)child);
                }
                FindChildren <T>(child, accumulator, predicate);
            }
            var contentControl = obj as ContentControl;

            if (contentControl?.Content is T && predicate((T)contentControl.Content))
            {
                accumulator.Add((T)contentControl.Content);
            }
            if (contentControl?.Content is DependencyObject)
            {
                FindChildren <T>((DependencyObject)contentControl.Content, accumulator, predicate);
            }
        }
 public static string GetAnyOrThrow<Key>(this Dictionary<Key, string> dict, Key[] keys, string exMessage, Predicate<string> validator = null)
 {
     foreach (var key in keys)
     {
         if (dict.TryGetValue(key, out var ret))
         {
             if (validator != null && !validator(ret))
                 continue;
             return ret;
         }
     }
     
     throw new KeyNotFoundException(exMessage);
 }
        public static string GetOrThrow<Key>(this Dictionary<Key, string> dict, Key key, string exMessage, Predicate<string> validator = null)
        {
            if (dict.TryGetValue(key, out var ret))
            {
                if (validator != null && !validator(ret))
                    throw new ArgumentException(exMessage);
                return ret;
            }

            throw new KeyNotFoundException(exMessage);
        }
Exemple #35
0
 public FilteredEnumerator(IndexedEnumerable indexedEnumerable, IEnumerable enumerable, Predicate <object> filterCallback)
 {
     _enumerable        = enumerable;
     _enumerator        = _enumerable.GetEnumerator();
     _filterCallback    = filterCallback;
     _indexedEnumerable = indexedEnumerable;
 }
Exemple #36
0
        string GenerateTransitionsFor(int i)
        {
            StringBuilder transitions = new StringBuilder();
            var stack = new SimpleStack<int>();
            var set = new HashSet<int>();
            var automaton = automata[i];
            stack.Push(automaton.InitialState);
            set.Add(automaton.InitialState);

            Predicate<int> IsFinalSink = (q =>
                (automaton.GetMovesCountFrom(q) == 1 && automaton.IsLoopState(q)
                && automaton.IsFinalState(q) && automaton.GetMoveFrom(q).Label.IsFull));

            Predicate<int> IsNonfinalSink = (q =>
                (!automaton.IsFinalState(q) &&
                  (automaton.GetMovesCountFrom(q) == 0 ||
                    (automaton.GetMovesCountFrom(q) == 1 && automaton.IsLoopState(q)))));

            while (stack.IsNonempty)
            {
                int q = stack.Pop();
                bool q_is_complete = false;
                if (IsFinalSink(q))
                    transitions.Append(String.Format(@"
        State{0}:
            return true;", q));
                else if (IsNonfinalSink(q))
                {
                    transitions.Append(String.Format(@"
        State{0}:
            return false;", q));
                }
                else
                {
                    transitions.Append(String.Format(@"
        State{0}:
            if (i == k)
                return {1};", q, (automaton.IsFinalState(q) ? "true" : "false")));
                    if (automaton.GetMovesCountFrom(q) > 0) //q is a sink
                    {
                        transitions.Append(String.Format(@"
            if (!UTF8toUTF16(&r, &i, &x, k, str))
                return false;"));
                        //---------------------------------------------------------------------
                        //many potential optimizations can be made in generating the conditions
                        //---------------------------------------------------------------------
                        var path = solver.True;
                        foreach (var move in automaton.GetMovesFrom(q))
                        {
                            path = solver.MkDiff(path, move.Label);
                            if (path == solver.False) //this is the last else case
                            {
                                transitions.Append(String.Format(@"
            goto State{0};", move.TargetState));
                                q_is_complete = true;
                            }
                            else
                                transitions.Append(String.Format(@" 
            if ({0})
                goto State{1};", helper_predicates.GeneratePredicate(move.Label), move.TargetState));
                            if (set.Add(move.TargetState))
                                stack.Push(move.TargetState);
                        }
                    }
                    if (!q_is_complete)
                        //reject the input, this corresponds to q being a partial state 
                        //the implicit transition is to a deadend sink state
                        transitions.Append(@"
            return false;");
                }
            }
            return transitions.ToString();
        }
Exemple #37
0
        // private readonly Func<bool, object> canExecute;


        public RelayCommand(Action <object> execute, Predicate <object> canExecute = null)
        {
            this.execute    = execute ?? throw new ArgumentNullException("execute");
            this.canExecute = canExecute;
        }
Exemple #38
0
 public int Count(Predicate <T> predicate)
 {
     return(m_storedObjects.FindAll(predicate).Count);
 }
Exemple #39
0
 public void Subscribe(Type messageType, Predicate <object> condition)
 {
     throw new NotImplementedException();
 }
Exemple #40
0
 public T Find(Predicate <T> predicate)
 {
     return(m_storedObjects.Find(predicate));
 }
        public static SnapshotSpan?MapUpOrDownToFirstMatch(this IBufferGraph bufferGraph, SnapshotSpan span, Predicate <ITextSnapshot> match)
        {
            var spans = bufferGraph.MapDownToFirstMatch(span, SpanTrackingMode.EdgeExclusive, match);

            if (!spans.Any())
            {
                spans = bufferGraph.MapUpToFirstMatch(span, SpanTrackingMode.EdgeExclusive, match);
            }

            return(spans.Select(s => (SnapshotSpan?)s).FirstOrDefault());
        }
Exemple #42
0
 /// <summary></summary>
 public Expression <Func <T, bool> > Update(Expression body, IEnumerable <ParameterExpression> parameters)
 {
     return(Predicate.Update(body, parameters));
 }
Exemple #43
0
 public List <T> FindAll(Predicate <T> predicate)
 {
     return(m_storedObjects.FindAll(predicate));
 }
Exemple #44
0
 /// <summary></summary>
 public Func <T, bool> Compile()
 {
     return(Predicate.Compile());
 }
Exemple #45
0
 IEnumerable <IType> IType.GetNestedTypes(IReadOnlyList <IType> typeArguments, Predicate <ITypeDefinition> filter, GetMemberOptions options)
 {
     return(EmptyList <IType> .Instance);
 }
Exemple #46
0
 /// <summary>And</summary>
 public Expression <Func <T, bool> > And([NotNull] Expression <Func <T, bool> > expr2)
 {
     return((IsStarted) ? _predicate = Predicate.And(expr2) : Start(expr2));
 }
Exemple #47
0
 /// <summary></summary>
 public Func <T, bool> Compile(DebugInfoGenerator debugInfoGenerator)
 {
     return(Predicate.Compile(debugInfoGenerator));
 }
Exemple #48
0
 /// <summary>
 /// Find the first parent of this object that matches a predicate.
 /// </summary>
 /// <param name="matcher">The predicate to match</param>
 /// <returns>The matching parent if it was found, null otherwise</returns>
 public MapObject FindClosestParent(Predicate <MapObject> matcher)
 {
     return(FindParents(matcher).FirstOrDefault());
 }
Exemple #49
0
 /// <summary> Show predicate string </summary>
 public override string ToString()
 {
     return(Predicate == null ? null : Predicate.ToString());
 }
Exemple #50
0
 public virtual void RemoveWhere(Predicate whereClause)
 {
     _storage.RemoveWhere(whereClause);
 }
Exemple #51
0
 /// <summary>
 /// Find the last parent of this object that matches a predicate.
 /// </summary>
 /// <param name="matcher">The predicate to match</param>
 /// <returns>The matching parent if it was found, null otherwise</returns>
 public MapObject FindTopmostParent(Predicate <MapObject> matcher)
 {
     return(FindParents(matcher).LastOrDefault());
 }
Exemple #52
0
 public int FindLastIndex(int startIndex, Predicate <T> match)
 {
     Contract.Ensures(Contract.Result <int>() >= -1);
     Contract.Ensures(Contract.Result <int>() <= startIndex);
     return(FindLastIndex(startIndex, startIndex + 1, match));
 }
Exemple #53
0
 public object FindLast(Predicate whereClause)
 {
     Ring.IndexedLink indexedLink = _storage.FindLast(whereClause);
     return((indexedLink == null) ? null : indexedLink.Value);
 }
Exemple #54
0
 /// <summary>
 /// Filter the rows
 /// </summary>
 /// <param name="observed">observed operation</param>
 /// <param name="filterexpr">callback method for filtering</param>
 /// <returns>resulting operation</returns>
 public static FilterOperation Filter(this IObservableOperation observed, Predicate<Row> filterexpr)
 {
     FilterOperation op = new FilterOperation(filterexpr);
     observed.Subscribe(op);
     return op;
 } 
Exemple #55
0
        static void LogMouseEvent(Object obj, MouseEventArgs e)
        {
            Console.WriteLine("LogMouse");

            ThreadStart ts  = new ThreadStart(MyMethod);
            ThreadStart ts2 = MyMethod;
            Thread      t   = new Thread(ts2);

            t.Start();

            StreamFactory factory = GenerateSampleData;

            using (Stream stream = factory())
            {
                int data;
                while ((data = stream.ReadByte()) != -1)
                {
                    Console.WriteLine(data);
                }
            }

            //=======================
            EventHandler         handler    = new EventHandler(LogPlainEvent);
            KeyPressEventHandler keyHandler = new KeyPressEventHandler(handler);

            //==============
            Dervied        x   = new Dervied();
            SampleDelegate fac = new SampleDelegate(x.CandidateAction);

            fac("TEST!!");

            ActionMethod();
            //===============================
            List <int> intList = new List <int>();

            intList.Add(5);
            intList.Add(10);
            intList.Add(15);
            intList.Add(25);

            intList.ForEach(delegate(int n) {
                Console.WriteLine(Math.Sqrt(n));
            });

            //================
            Predicate <int> isEven = delegate(int xx) { return(xx % 2 == 0); };

            Console.WriteLine(isEven(10));

            //SortAndShowFiles("Sort by name:",delegate(FileInfo f1,FileInfo f2) { return f1.Name.CompareTo(f2.Name); });

            EnclosingMethod();
            CaptureVariable();

            Console.WriteLine("//=======================");
            MethodInvoker xxx = CreateDelegateInstace();

            xxx();
            xxx();

            InitCapturedVariable();
        }
Exemple #56
0
        static void Main(string[] args)
        {
            EnumSample es = new EnumSample();

            es.Test();
            System.Console.WriteLine(new structSample(12, 22).Diagnoal);

            structSample ss = new structSample(1, 2);

            //  ss.Length = 11;
            //ss.Width = 22;
            System.Console.WriteLine(ss.Diagnoal);

            System.Console.WriteLine(StaticClass.cc);

            Person jon = new Person("Jon");

            StringProcessor jonsVoice, tomsVoice, background;

            jonsVoice = new StringProcessor(jon.Say);
            {
                Person tom = new Person("Tom");
                tomsVoice = new StringProcessor(tom.Say);
            }
            background = new StringProcessor(Background.Note);

            jonsVoice("Hello, son.");

            tomsVoice("hello, Daddy");
            background("An airplane flies past");
            jon.Name   = "Jon Snow";
            jonsVoice += tomsVoice;

            foreach (Delegate dele in jonsVoice.GetInvocationList())
            {
                dele.DynamicInvoke("Iknow nothing yegret");
            }

            jonsVoice("I know nothing");
            background.Invoke("Another airplane files past");
            ClassSizeof szof = new ClassSizeof(name: "zhouwei", age: 33, gender: "male");

            // Program pro = new Program();
            //class
            Console.WriteLine("{0}-{1}-{2}", szof.Name, szof.Age, szof.Gender);
            Console.WriteLine(Marshal.SizeOf(szof /*new ClassSizeof(name: "zhouwei", age: 33, gender: "male")*/));

            List <ClassSizeof> list = new List <ClassSizeof> {
                new ClassSizeof(name: "zhouwei", age: 33, gender: "male"),
                new ClassSizeof(name: "zhouchao", age: 30, gender: "male"),
                new ClassSizeof(name: "zhoujiazu", age: 230, gender: "male"),
                new ClassSizeof(name: "dengmin", age: 32, gender: "female")
            };

            list.Sort(new Comparer());
            list.Sort(delegate(ClassSizeof s1, ClassSizeof s2) { return(s2.Age

                                                                        - s1.Age); });

            list.Sort(comparison: (a, b) => { return(a.Age - b.Age); });

            foreach (ClassSizeof szof2 in list.OrderBy(z => z.Name))
            {
                Console.WriteLine("{0}-{1}-{2}", szof2.Name, szof2.Age, szof2.Gender);
            }

            foreach (ClassSizeof szof1 in list)
            {
                Console.WriteLine("{0}-{1}-{2}", szof1.Name, szof1.Age, szof1.Gender);
            }

            Predicate <ClassSizeof> gr30 = delegate(ClassSizeof sz) { return(sz.Age > 30); };

            List <ClassSizeof>   qualified = list.FindAll(gr30);
            Action <ClassSizeof> print     = Console.WriteLine;

            Console.WriteLine("action print");
            qualified.ForEach(print);
            var qua = from ClassSizeof sz in list where sz.Age > 30 select sz;

            Console.WriteLine("LINQ");
            foreach (ClassSizeof sz in qua.OrderBy(p => p.Age))
            {
                Console.WriteLine(sz);
            }


            DelegateEventsTest det = new DelegateEventsTest();

            det.Test();

            GenericDictionary td = new GenericDictionary();

            td.Test();
            PartialClassSampleInvoker pcsi = new PartialClassSampleInvoker();

            pcsi.Test();

            ExtensionClass ec = new ExtensionClass();

            ec.Test();

            OverrideAndHiddenSample oahs = new OverrideAndHiddenSample();

            oahs.Test();

            AsAndIsSample aais = new AsAndIsSample();

            aais.Test();

            WeakReferenceSample srs = new WeakReferenceSample();

            srs.Test();

            LinkedListSample lls = new LinkedListSample();

            lls.Test();

            CoContraVarianceIsMakeSureConvertFromDerivedToBase iovs = new CoContraVarianceIsMakeSureConvertFromDerivedToBase();

            iovs.Test();

            Console.Read();
        }
Exemple #57
0
 public int FindLastIndex(Predicate <T> match)
 {
     Contract.Ensures(Contract.Result <int>() >= -1);
     Contract.Ensures(Contract.Result <int>() < Count);
     return(FindLastIndex(_size - 1, _size, match));
 }
Exemple #58
0
        protected XunitProject Parse(Predicate <string> fileExists)
        {
            var assemblies = new List <Tuple <string, string> >();

            while (arguments.Count > 0)
            {
                if (arguments.Peek().StartsWith("-", StringComparison.Ordinal))
                {
                    break;
                }

                var assemblyFile = arguments.Pop();
                if (IsConfigFile(assemblyFile))
                {
                    throw new ArgumentException($"expecting assembly, got config file: {assemblyFile}");
                }
                if (!fileExists(assemblyFile))
                {
                    throw new ArgumentException($"file not found: {assemblyFile}");
                }

                string configFile = null;
                if (arguments.Count > 0)
                {
                    var value = arguments.Peek();
                    if (!value.StartsWith("-", StringComparison.Ordinal) && IsConfigFile(value))
                    {
                        configFile = arguments.Pop();
                        if (!fileExists(configFile))
                        {
                            throw new ArgumentException($"config file not found: {configFile}");
                        }
                    }
                }

                assemblies.Add(Tuple.Create(assemblyFile, configFile));
            }

            var project = GetProjectFile(assemblies);

            while (arguments.Count > 0)
            {
                var option     = PopOption(arguments);
                var optionName = option.Key.ToLowerInvariant();

                if (!optionName.StartsWith("-", StringComparison.Ordinal))
                {
                    throw new ArgumentException($"unknown command line option: {option.Key}");
                }

                optionName = optionName.Substring(1);

                if (optionName == "nologo")
                {
                    GuardNoOptionValue(option);
                    NoLogo = true;
                }
                else if (optionName == "failskips")
                {
                    GuardNoOptionValue(option);
                    FailSkips = true;
                }
                else if (optionName == "stoponfail")
                {
                    GuardNoOptionValue(option);
                    StopOnFail = true;
                }
                else if (optionName == "nocolor")
                {
                    GuardNoOptionValue(option);
                    NoColor = true;
                }
                else if (optionName == "noappdomain")
                {
                    GuardNoOptionValue(option);
                    NoAppDomain = true;
                }
                else if (optionName == "noautoreporters")
                {
                    GuardNoOptionValue(option);
                    NoAutoReporters = true;
                }
#if DEBUG
                else if (optionName == "pause")
                {
                    GuardNoOptionValue(option);
                    Pause = true;
                }
#endif
                else if (optionName == "debug")
                {
                    GuardNoOptionValue(option);
                    Debug = true;
                }
                else if (optionName == "serialize")
                {
                    GuardNoOptionValue(option);
                    Serialize = true;
                }
                else if (optionName == "wait")
                {
                    GuardNoOptionValue(option);
                    Wait = true;
                }
                else if (optionName == "diagnostics")
                {
                    GuardNoOptionValue(option);
                    DiagnosticMessages = true;
                }
                else if (optionName == "internaldiagnostics")
                {
                    GuardNoOptionValue(option);
                    InternalDiagnosticMessages = true;
                }
                else if (optionName == "maxthreads")
                {
                    if (option.Value == null)
                    {
                        throw new ArgumentException("missing argument for -maxthreads");
                    }

                    switch (option.Value)
                    {
                    case "default":
                        MaxParallelThreads = 0;
                        break;

                    case "unlimited":
                        MaxParallelThreads = -1;
                        break;

                    default:
                        int threadValue;
                        if (!int.TryParse(option.Value, out threadValue) || threadValue < 1)
                        {
                            throw new ArgumentException("incorrect argument value for -maxthreads (must be 'default', 'unlimited', or a positive number)");
                        }

                        MaxParallelThreads = threadValue;
                        break;
                    }
                }
                else if (optionName == "parallel")
                {
                    if (option.Value == null)
                    {
                        throw new ArgumentException("missing argument for -parallel");
                    }

                    if (!Enum.TryParse(option.Value, out ParallelismOption parallelismOption))
                    {
                        throw new ArgumentException("incorrect argument value for -parallel");
                    }

                    switch (parallelismOption)
                    {
                    case ParallelismOption.all:
                        ParallelizeAssemblies      = true;
                        ParallelizeTestCollections = true;
                        break;

                    case ParallelismOption.assemblies:
                        ParallelizeAssemblies      = true;
                        ParallelizeTestCollections = false;
                        break;

                    case ParallelismOption.collections:
                        ParallelizeAssemblies      = false;
                        ParallelizeTestCollections = true;
                        break;

                    default:
                        ParallelizeAssemblies      = false;
                        ParallelizeTestCollections = false;
                        break;
                    }
                }
                else if (optionName == "noshadow")
                {
                    GuardNoOptionValue(option);
                    foreach (var assembly in project.Assemblies)
                    {
                        assembly.Configuration.ShadowCopy = false;
                    }
                }
                else if (optionName == "trait")
                {
                    if (option.Value == null)
                    {
                        throw new ArgumentException("missing argument for -trait");
                    }

                    var pieces = option.Value.Split('=');
                    if (pieces.Length != 2 || string.IsNullOrEmpty(pieces[0]) || string.IsNullOrEmpty(pieces[1]))
                    {
                        throw new ArgumentException("incorrect argument format for -trait (should be \"name=value\")");
                    }

                    var name  = pieces[0];
                    var value = pieces[1];
                    project.Filters.IncludedTraits.Add(name, value);
                }
                else if (optionName == "notrait")
                {
                    if (option.Value == null)
                    {
                        throw new ArgumentException("missing argument for -notrait");
                    }

                    var pieces = option.Value.Split('=');
                    if (pieces.Length != 2 || string.IsNullOrEmpty(pieces[0]) || string.IsNullOrEmpty(pieces[1]))
                    {
                        throw new ArgumentException("incorrect argument format for -notrait (should be \"name=value\")");
                    }

                    var name  = pieces[0];
                    var value = pieces[1];
                    project.Filters.ExcludedTraits.Add(name, value);
                }
                else if (optionName == "class")
                {
                    if (option.Value == null)
                    {
                        throw new ArgumentException("missing argument for -class");
                    }

                    project.Filters.IncludedClasses.Add(option.Value);
                }
                else if (optionName == "method")
                {
                    if (option.Value == null)
                    {
                        throw new ArgumentException("missing argument for -method");
                    }

                    project.Filters.IncludedMethods.Add(option.Value);
                }
                else if (optionName == "namespace")
                {
                    if (option.Value == null)
                    {
                        throw new ArgumentException("missing argument for -namespace");
                    }

                    project.Filters.IncludedNameSpaces.Add(option.Value);
                }
                else
                {
                    // Might be a result output file...
                    if (TransformFactory.AvailableTransforms.Any(t => t.CommandLine.Equals(optionName, StringComparison.OrdinalIgnoreCase)))
                    {
                        if (option.Value == null)
                        {
                            throw new ArgumentException($"missing filename for {option.Key}");
                        }

                        EnsurePathExists(option.Value);

                        project.Output.Add(optionName, option.Value);
                    }
                    // ...or it might be a reporter (we won't know until later)
                    else
                    {
                        GuardNoOptionValue(option);
                        unknownOptions.Add(optionName);
                    }
                }
            }

            return(project);
        }
Exemple #59
0
 public bool Exists(Predicate <T> match)
 {
     return(FindIndex(match) != -1);
 }
 void PopulateListView(ListView lv, List<KeyValuePair<string, Type>> map, Predicate<KeyValuePair<string, Type>> match)
 {
     lv.Visible = false;
     lv.BeginUpdate();
     lv.Items.Clear();
     string fmt = "{0:D" + (map.Count.ToString().Length) + "}";
     int order = 0;
     foreach (var kvp in map)
     {
         order++;
         if (!match(kvp)) continue;
         string tag = getTag(kvp.Key);
         string wrapper = kvp.Value.Name;
         string file = System.IO.Path.GetFileName(kvp.Value.Assembly.Location);
         string title = GetAttrValue(kvp.Value.Assembly, typeof(System.Reflection.AssemblyTitleAttribute), "Title");
         string description = GetAttrValue(kvp.Value.Assembly, typeof(System.Reflection.AssemblyDescriptionAttribute), "Description");
         string company = GetAttrValue(kvp.Value.Assembly, typeof(System.Reflection.AssemblyCompanyAttribute), "Company");
         string product = GetAttrValue(kvp.Value.Assembly, typeof(System.Reflection.AssemblyProductAttribute), "Product");
         ListViewItem lvi = new ListViewItem(new string[] { String.Format(fmt, order), tag, kvp.Key, wrapper, file, title, description, company, product, });
         lvi.Tag = kvp;
         lv.Items.Add(lvi);
     }
     if (lv.Items.Count > 0)
         lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
     lv.EndUpdate();
     lv.Visible = true;
 }