示例#1
0
        private void TraceStartEndJob(ICollection <long> queryIdList, IEnumerable <string> languages, bool isStart)
        {
            string ids   = queryIdList.Aggregate(string.Empty, (current, id) => current + id + ", ");
            string names = queryIdList.Aggregate(string.Empty, (current, id) => current + AvrDbHelper.GetQueryNameForLog(id) + ", ");
            string langs = languages.Aggregate(string.Empty, (current, lang) => current + lang + ", ");

            string msg = isStart
                ? "Start refresh queries with ids '{0}'{3} and with names '{1}'{3} for languages '{2}'"
                : "End refresh queries with ids '{0}'{3} and with names '{1}'{3} for languages '{2}'";

            m_Trace.TraceInfo(m_TraceTitle, msg, ids, names, langs, Environment.NewLine);
        }
示例#2
0
 public void Optimize(
     BigInteger allFeatureBitMask, BigInteger rejectingFeatureBitMask,
     ICollection <BigInteger> rejectedFeatures)
 {
     Accepting &= allFeatureBitMask
                  ^ rejectedFeatures.Aggregate(rejectingFeatureBitMask, (a, b) => a | b);
 }
        public virtual async Task <ICollection <T> > GetAsync(Expression <Func <T, bool> > filter = null,
                                                              Func <IQueryable <T>, IQueryable <T> > queryableFunc = null,
                                                              ICollection <Func <IQueryable <T>, IIncludableQueryable <T, object> > > includeProperties = null,
                                                              ICollection <FilteredIncludeExpression> filteredIncludes = null)
        {
            IQueryable <T> query = this.dbSet;

            if (filter != null)
            {
                query = query.Where(filter);
            }

            if (includeProperties != null)
            {
                query = includeProperties.Aggregate(query, (list, next) => query = next(query));
            }

            return(LoadFilteredIncludes(queryableFunc != null ? await queryableFunc(query).ToListAsync() : await query.ToListAsync()));

            ICollection <T> LoadFilteredIncludes(List <T> list)
            {
                if (filteredIncludes == null)
                {
                    return(list);
                }

                FilteredIncludesHelper.DoExplicitLoading(this.context, list, filteredIncludes);
                return(list);
            }
        }
        public static T Aggregate <T>(this ICollection <IAggregate <T> > aggregates) where T : class, IAggregate <T>, new()
        {
            var aggr = new T();

            return(aggregates
                   .Aggregate(aggr, (now, next) => next.Commit(now)));
        }
示例#5
0
        string GetAllTypesAsString(ICollection <string> types)
        {
            // This causes a conflict with the vim keyword 'contains'
            types.Remove("Contains");

            return(types.Aggregate("", (current, type) => current + type + " "));
        }
        private static List <MemberDetails> GetMemberDetails <TSource>(ICollection <string> propertyFullNames, ParameterExpression selectorParameter)
        => propertyFullNames.Aggregate(new List <MemberDetails>(), (list, next) =>
        {
            Type t = typeof(TSource);
            List <string> fullNameList = next.Split('.').Aggregate(new List <string>(), (lst, n) =>
            {
                MemberInfo p = t.GetMemberInfo(n);
                t            = p.GetMemberType();
                lst.Add(p.Name);
                return(lst);
            });

            list.Add(new MemberDetails
            {
                Selector = fullNameList.Aggregate
                           (
                    (Expression)selectorParameter, (param, n) => Expression.MakeMemberAccess
                    (
                        param,
                        param.Type.GetMemberInfo(n)
                    )
                           ),
                MemberName = string.Join("", fullNameList),
                Type       = t
            });
            return(list);
        });
        /// <summary>
        /// Creates an include method call expression to be invoked on an expression e.g. (parameter, member, method call) of type IQueryable<T>.
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="expression"></param>
        /// <param name="includes"></param>
        /// <param name="parameterName"></param>
        /// <returns></returns>
        public static MethodCallExpression GetInclude <TSource>(this Expression expression, string include)
        {
            if (string.IsNullOrEmpty(include))
            {
                return(null);
            }
            ICollection <string> includes = include.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            Type parentType = typeof(TSource);

            return(includes.Aggregate(null, (MethodCallExpression mce, string next) =>
            {
                LambdaExpression selectorExpression = next.GetTypedSelector(parentType);
                MemberInfo mInfo = parentType.GetMemberInfo(next);

                mce = mce == null
                      //The Include espression takes two arguments.  The parameter (object being extended by the helper method) and the lambda expression for the property selector
                        ? Expression.Call(typeof(EntityFrameworkQueryableExtensions), "Include", new Type[] { parentType, mInfo.GetMemberType() }, expression, selectorExpression)
                      //The ThenInclude espression takes two arguments.  The resulting method call expression from Include and the lambda expression for the property selector
                        : Expression.Call(typeof(EntityFrameworkQueryableExtensions), "ThenInclude", new Type[] { typeof(TSource), parentType, mInfo.GetMemberType() }, mce, selectorExpression);

                parentType = mInfo.GetMemberType().GetCurrentType();//new previous property to include members from.

                return mce;
            }));
        }
示例#8
0
        public async Task <RulesCache> LoadRulesOnStartUp()
        {
            try
            {
                ICollection <RulesModuleModel> modules = (await this._repository.GetItemsAsync <RulesModuleModel, RulesModule>(t => t.Application == this._applicationOptions.ApplicationName));

                return(modules.Aggregate(new RulesCache(new Dictionary <string, RuleEngine>(), new Dictionary <string, string>()), (cache, module) =>
                {
                    string moduleName = module.Name.ToLowerInvariant();
                    RuleSet ruleSet = module.DeserializeRuleSetFile();
                    if (ruleSet == null)
                    {
                        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.invalidRulesetFormat, moduleName));
                    }

                    cache.RuleEngines.Add(moduleName, new RuleEngine(ruleSet, RulesSerializer.GetValidation(ruleSet)));

                    using (IResourceReader reader = new ResourceReader(new MemoryStream(module.ResourceSetFile)))
                    {
                        reader.OfType <DictionaryEntry>()
                        .ToList()
                        .ForEach(entry => cache.ResourceStrings.Add((string)entry.Key, (string)entry.Value));
                    }

                    return cache;
                }));
            }
            catch (Exception ex)
            {
                this._logger.LogError(ex, ex.Message);
                return(new RulesCache(new Dictionary <string, RuleEngine>(), new Dictionary <string, string>()));
            }
        }
示例#9
0
        long OffsetFromMessages(ICollection <IMessage> successful, ICollection <IMessage> remaining)
        {
            long offset;

            // If there are no outstanding children, checkpoint the messages given.
            // This can happen in two cases:
            //   1. One endpoint is being written to and we need to keep up with its checkpointer.
            //   2. No endpoints are being written to and we should advance the checkpoint.
            if (remaining.Count == 0)
            {
                // Find the largest offset in the successful messages
                offset = successful.Aggregate(this.Offset, (acc, m) => Math.Max(acc, m.Offset));
            }
            else
            {
                // 1. Find the minimum offset in the remaining messages
                // 2. Find all of the successful messages with a smaller offset than the minimum offset from above
                // 3. Find the maximum offset in the filtered messages and use this as the checkpoint offset
                // This checkpoints up to but not including the minimum offset of the remaining messages
                // so that the remaining messages can be retried.
                long minOffsetRemaining = remaining.Min(m => m.Offset);
                offset = successful
                         .Where(m => m.Offset < minOffsetRemaining)
                         .Aggregate(this.Offset, (acc, m) => Math.Max(acc, m.Offset));
            }
            return(offset);
        }
        private static void ClearOriginalAddressesAndAppendToBody(MailMessage realMailMessage, string addressType, ICollection <MailAddress> addresses)
        {
            var newline   = realMailMessage.IsBodyHtml ? "<br />" : Environment.NewLine;
            var separator = newline + "\t";

            var toExpected = addresses.Aggregate(String.Empty, (s, mailAddress) => s + Environment.NewLine + "\t" + mailAddress.ToString());

            if (!GeneralUtility.IsNullOrEmptyOrOnlyWhitespace(toExpected))
            {
                var toAppend = String.Format("{0}{1}Actual {2}:{3}", newline, separator, addressType, realMailMessage.IsBodyHtml ? toExpected.HtmlEncodeWithBreaks() : toExpected);
                realMailMessage.Body += toAppend;

                for (var i = 0; i < realMailMessage.AlternateViews.Count; i++)
                {
                    var stream = realMailMessage.AlternateViews[i].ContentStream;
                    using (var reader = new StreamReader(stream))
                    {
                        var alternateBody = reader.ReadToEnd();
                        alternateBody += toAppend;
                        var newAlternateView = AlternateView.CreateAlternateViewFromString(alternateBody, null, realMailMessage.AlternateViews[i].ContentType.MediaType);
                        realMailMessage.AlternateViews[i].LinkedResources.ToList().ForEach(x => newAlternateView.LinkedResources.Add(x));
                        realMailMessage.AlternateViews[i] = newAlternateView;
                    }
                }
            }
            addresses.Clear();
        }
        public async Task <IReadOnlyList <T> > GetAsync(Expression <Func <T, bool> >?predicate, Func <IQueryable <T>, IOrderedQueryable <T> >?orderBy, ICollection <Expression <Func <T, object> > > includes, bool disableTracking = true)
        {
            IQueryable <T> query = _context.Set <T>();

            if (disableTracking)
            {
                query = query.AsNoTracking();
            }

            if (includes != default)
            {
                query = includes.Aggregate(query, (current, next) => current.Include(next));
            }

            if (predicate != default)
            {
                query = query.Where(predicate);
            }

            if (orderBy != default)
            {
                return(await orderBy(query).ToListAsync());
            }

            return(await query.ToListAsync());
        }
示例#12
0
        public async Task ProcessAsync(TRequest request)
        {
            var firstHandler = _handlers.FirstOrDefault();

            if (_handlers.Count == 1)
            {
                // ReSharper disable once PossibleNullReferenceException
                firstHandler.DependencyResolver = _dependencyResolver;
                await firstHandler.HandleAsync(request);

                return;
            }

            _handlers.Aggregate((prev, next) =>
            {
                prev.Next = next;
                prev.DependencyResolver = _dependencyResolver;
                next.DependencyResolver = _dependencyResolver;

                return(next);
            });

            if (firstHandler != null)
            {
                await firstHandler.HandleAsync(request);
            }
        }
示例#13
0
        public YahooGatherer(int updatePeriod, IEnumerable <string> enumerable, params string[] args)
        {
            this.timer = new Timer(updatePeriod);

            logger.Info("Creating a new YahooGatherer");

            stocks = new List <string>();
            if (enumerable != null)
            {
                foreach (string s in enumerable)
                {
                    stocks.Add(s);
                }
            }

            foreach (string s in args)
            {
                stocks.Add(s);
            }

            logger.Info("Gatherers stocks are: " + stocks.Aggregate((string start, string next) => start + " " + next));

            timer.Elapsed += UpdateStocksData;
            timer.Start();
        }
示例#14
0
        /// <inheritdoc />
        public void Execute(IFileSource fileSource)
        {
            Log.InfoFormat("Executing pipeline with {0} {1}", fileSource?.GetType().Name, fileSource);

            IFileSource prev = null;

            DataProcessors.Aggregate(fileSource, (current, processor) =>
            {
                if (current != prev)
                {
                    current?.Init();
                    prev = current;
                }

                current?.BeginExecute();

                var newSource = processor.Execute(current);

                current?.EndExecute();

                return(newSource);
            });

            Log.InfoFormat("Executed pipeline with {0} {1}", fileSource?.GetType().Name, fileSource);
        }
示例#15
0
        string GetAllTypesAsString(ICollection<string> types)
        {
            // This causes a conflict with the vim keyword 'contains'
            types.Remove("Contains");

            return types.Aggregate("", (current, type) => current + type + " ");
        }
        /// <summary>
        /// GetAsync
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <typeparam name="TData"></typeparam>
        /// <param name="query"></param>
        /// <param name="mapper"></param>
        /// <param name="filter"></param>
        /// <param name="queryFunc"></param>
        /// <param name="includeProperties"></param>
        /// <returns></returns>
        public static async Task <ICollection <TModel> > GetAsync <TModel, TData>(this IQueryable <TData> query, IMapper mapper,
                                                                                  Expression <Func <TModel, bool> > filter = null,
                                                                                  Expression <Func <IQueryable <TModel>, IQueryable <TModel> > > queryFunc = null,
                                                                                  IEnumerable <Expression <Func <TModel, object> > > includeProperties     = null)
        {
            //Map the expressions
            Expression <Func <TData, bool> > f = mapper.MapExpression <Expression <Func <TData, bool> > >(filter);
            Func <IQueryable <TData>, IQueryable <TData> >    mappedQueryFunc = mapper.MapExpression <Expression <Func <IQueryable <TData>, IQueryable <TData> > > >(queryFunc)?.Compile();
            ICollection <Expression <Func <TData, object> > > includes        = mapper.MapIncludesList <Expression <Func <TData, object> > >(includeProperties);

            if (filter != null)
            {
                query = query.Where(f);
            }

            if (includes != null)
            {
                query = includes.Aggregate(query, (q, next) => q.Include(next));
            }

            //Call the store
            ICollection <TData> result = mappedQueryFunc != null ? await mappedQueryFunc(query).ToListAsync() : await query.ToListAsync();

            //Map and return the data
            return(mapper.Map <IEnumerable <TData>, IEnumerable <TModel> >(result).ToList());
        }
        public T Compile <T>(Expression <T> expression) where T : class
        {
            expression = (Expression <T>)_expressionMiddleware.Aggregate((Expression)expression, (e, m) => m.Invoke(e));

            if (_closureFeature == null)
            {
                return(expression.CompileFast());
            }

            expression = (Expression <T>)_closureFeature.ExpressionMiddleware.Invoke(expression);

            var parameters = new[] { _closure }.Concat(expression.Parameters).ToArray();
            var lambda               = Expression.Lambda(expression.Body, parameters);
            var compiledDelegateType = Expression.GetDelegateType(parameters.Select(o => o.Type).Concat(new[] { lambda.ReturnType }).ToArray());

            var method = typeof(FastExpressionCompiler)
                         .GetMethod(nameof(CompileGeneric), BindingFlags.Static | BindingFlags.NonPublic)
                         ?.MakeGenericMethod(compiledDelegateType);

            var compiledLambda = method?.Invoke(null, new object[] { lambda }) ?? throw new InvalidOperationException("lambda cannot be compiled");

            var outerParameters = expression.Parameters.Select(o => Expression.Parameter(o.Type, o.Name)).ToArray();

            var store       = ExpressionShortcuts.Arg(_templateClosure).Property(o => o.Store);
            var outerLambda = Expression.Lambda <T>(
                Expression.Invoke(Expression.Constant(compiledLambda), new[] { store.Expression }.Concat(outerParameters)),
                outerParameters);

            return(outerLambda.CompileFast());
        }
            public T Compile <T>(Expression <T> expression) where T : class
            {
                expression = (Expression <T>)_expressionMiddleware.Aggregate((Expression)expression, (e, m) => m.Invoke(e));

                var closureFeature = _closureFeature;

                if (closureFeature.TemplateClosure.CurrentIndex == -1)
                {
                    closureFeature = new ClosureFeature();
                    _closureFeature.Children.AddLast(closureFeature);
                }

                var templateClosure = closureFeature.TemplateClosure;
                var closure         = closureFeature.ClosureInternal;

                expression = (Expression <T>)closureFeature.ExpressionMiddleware.Invoke(expression);

                var parameters = new[] { (ParameterExpression)closure }.Concat(expression.Parameters);
                var lambda         = Expression.Lambda(expression.Body, parameters);
                var compiledLambda = lambda.Compile();

                var outerParameters = expression.Parameters.Select(o => Expression.Parameter(o.Type, o.Name)).ToArray();
                var store = Arg(templateClosure).Member(o => o.Store);
                var parameterExpressions = new[] { store.Expression }.Concat(outerParameters);
                var invocationExpression = Expression.Invoke(Expression.Constant(compiledLambda), parameterExpressions);
                var outerLambda          = Expression.Lambda <T>(invocationExpression, outerParameters);

                return(outerLambda.Compile());
            }
示例#19
0
        /// <summary>
        /// GetQueryAsync
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <typeparam name="TData"></typeparam>
        /// <param name="query"></param>
        /// <param name="mapper"></param>
        /// <param name="filter"></param>
        /// <param name="queryFunc"></param>
        /// <param name="includeProperties"></param>
        /// <returns></returns>
        public static async Task <IQueryable <TModel> > GetQueryAsync <TModel, TData>(this IQueryable <TData> query, IMapper mapper,
                                                                                      Expression <Func <TModel, bool> > filter = null,
                                                                                      Expression <Func <IQueryable <TModel>, IQueryable <TModel> > > queryFunc = null,
                                                                                      IEnumerable <Expression <Func <TModel, object> > > includeProperties     = null)
        {
            //Map the expressions
            Expression <Func <TData, bool> > f = mapper.MapExpression <Expression <Func <TData, bool> > >(filter);
            Func <IQueryable <TData>, IQueryable <TData> >    mappedQueryFunc = mapper.MapExpression <Expression <Func <IQueryable <TData>, IQueryable <TData> > > >(queryFunc)?.Compile();
            ICollection <Expression <Func <TData, object> > > includes        = mapper.MapIncludesList <Expression <Func <TData, object> > >(includeProperties);

            if (filter != null)
            {
                query = query.Where(f);
            }

            if (includes != null)
            {
                query = includes.Aggregate(query, (q, next) => q.Include(next));
            }

            return(await Task.Run
                   (
                       () => mappedQueryFunc != null
                       ?mapper.ProjectTo <TModel>(mappedQueryFunc(query))
                       : mapper.ProjectTo <TModel>(query)
                   ));
        }
示例#20
0
        public NHibernateQueryBuilder <T> BuildQuery(ICollection <Expression <Func <T, bool> > > whereExpressions, ICollection <OrderExpressionContainer> orderExpressions)
        {
            InitializeBuilder();


            if (whereExpressions.Count == 0)
            {
                return(this);
            }


            const string whereExpressionsConcatinationElement = " " + "AND" + " ";

            var whereElement = whereExpressions.Aggregate(string.Empty, (current, expression) => current + TransformWhereExpressionToHQL(expression) + whereExpressionsConcatinationElement);

            QueryString += " " + "WHERE" + " " + whereElement.Substring(0, whereElement.Length - (whereExpressionsConcatinationElement).Length);



            if (orderExpressions.Count == 0)
            {
                return(this);
            }


            const string orderExpressionsConcatinationElement = "," + " ";

            var orderElement = orderExpressions.Aggregate(string.Empty, (current, orderExpression) => current + TransformOrderExpressionToHQL(orderExpression.Expression, orderExpression.IsDescending) + orderExpressionsConcatinationElement);

            QueryString += " " + "ORDER BY" + " " + orderElement.Substring(0, orderElement.Length - (orderExpressionsConcatinationElement).Length);


            return(this);
        }
示例#21
0
        public override string ToString()
        {
            string sort    = sortOrder.Count > 0 ? " Sort[{0}]" : "";
            string page    = " Page[Number:{0}, Size:{1}]";
            string include = includePaths.Count > 0 ? " Include[{0}]" : "";

            string where = Predicate != null ? " Where[{0}]" : "";

            string sortValue = sortOrder.Select(x => x.SortPropertyName + " " + x.SortOrder.ToString())
                               .Aggregate((current, next) => current + ", " + next);

            StringBuilder sb = new StringBuilder();

            if (string.IsNullOrEmpty(sort) == false)
            {
                sb.AppendFormat(sort, sortValue);
            }

            if (string.IsNullOrEmpty(page) == false)
            {
                sb.AppendFormat(page, PageNumber, PageSize);
            }

            if (string.IsNullOrEmpty(include) == false)
            {
                sb.AppendFormat(include, includePaths.Aggregate((current, next) => current + ", " + next));
            }

            if (string.IsNullOrEmpty(where) == false)
            {
                sb.AppendFormat(where, Predicate.ToString());
            }

            return(sb.ToString());
        }
示例#22
0
 public void BeginTransaction(TAggregateId streamId, ICollection <IDomainEvent <TAggregateId> > evts)
 {
     if (!evts.Aggregate(true, (res, evt) => res && (evt.StreamId.Equals(streamId))))
     {
         throw new TransactionCannotBeginException($"Try to start trasaction for StreamId {streamId} but not all events into collection belong to this stream.");
     }
     _idRange = _idProvider.PrepareIdRange(streamId, evts.Count);
 }
示例#23
0
 public Permission?ResolveInstancePermission(TContext context, T instance)
 {
     if (!InstancePermissionResolvers.Any())
     {
         return(null);
     }
     return(InstancePermissionResolvers.Aggregate(Permission.Admin, (permission, resolver) => permission & resolver(context, instance)));
 }
示例#24
0
        public IQueryable <TEntity> Find(Expression <Func <TEntity, bool> > predicate, ICollection <string> includes)
        {
            IQueryable <TEntity> query = Entities;

            query = query.Where(predicate);
            query = includes.Aggregate(query, (current, include) => current.Include(include));
            return(query);
        }
 static float mass_flow(ICollection <ResourceLine> resources)
 {
     if (resources == null || resources.Count == 0)
     {
         return(0);
     }
     return(resources.Aggregate(0f, (f, r) => f + r.Rate));
 }
 public string Convert(ICollection <string> sourceMember, ResolutionContext context)
 {
     if (sourceMember == null || !sourceMember.Any())
     {
         return(null);
     }
     return(sourceMember.Aggregate((x, y) => $"{x},{y}"));
 }
示例#27
0
        void AnnotationEvent(string eventSource, ICollection <IAnnotation> annotations)
        {
            var eventMessage = $"{annotations.Count} annotations were {eventSource}";

            eventMessage = annotations.Aggregate(eventMessage, (current, annotation) =>
                                                 current + $"\r\n{annotation.AnnotationType.ToString ()} on page {annotation.PageIndex}");
            Events.Add(eventMessage);
        }
示例#28
0
        public async Task LoadSelectedModules(List <string> modules)
        {
            if (this._rulesCache == null)
            {
                throw new InvalidOperationException(Properties.Resources.rulesCacheCannotBeNull);
            }

            if (modules.Count < 1)
            {
                return;
            }

            List <string> queryItems = modules.Select(item => string.Concat(item, PIPE, this._applicationOptions.ApplicationName)).ToList();
            ICollection <RulesModuleModel> rulesModules = (await this._repository.GetItemsAsync <RulesModuleModel, RulesModule>(item => queryItems.Contains(item.NamePlusApplication)));

            this._rulesCache = rulesModules.Aggregate(this._rulesCache, (cache, next) =>
            {
                string moduleName = next.Name.ToLowerInvariant();
                lock (cache)
                {
                    RuleSet ruleSet = next.DeserializeRuleSetFile();
                    if (ruleSet == null)
                    {
                        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.invalidRulesetFormat, moduleName));
                    }

                    if (cache.RuleEngines.ContainsKey(moduleName))
                    {
                        cache.RuleEngines[moduleName] = new RuleEngine(ruleSet, RulesSerializer.GetValidation(ruleSet));
                    }
                    else
                    {
                        cache.RuleEngines.Add(moduleName, new RuleEngine(ruleSet, RulesSerializer.GetValidation(ruleSet)));
                    }

                    using (IResourceReader reader = new ResourceReader(new MemoryStream(next.ResourceSetFile)))
                    {
                        reader.OfType <DictionaryEntry>()
                        .ToList()
                        .ForEach(entry =>
                        {
                            string resourceKey = (string)entry.Key;
                            if (cache.ResourceStrings.ContainsKey(resourceKey))
                            {
                                cache.ResourceStrings[resourceKey] = (string)entry.Value;
                            }
                            else
                            {
                                cache.ResourceStrings.Add(resourceKey, (string)entry.Value);
                            }
                        });
                    }
                }

                return(cache);
            });
        }
示例#29
0
        /// <inheritdoc />
        public SkinFlags Convert(ICollection <string> value, object state)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value", "Precondition: value != null");
            }

            return(value.Aggregate(default(SkinFlags), (current, s) => current | this.converterForSkinFlags.Convert(s, state)));
        }
示例#30
0
        /// <inheritdoc />
        public ItemRestrictions Convert(ICollection <string> value, object state)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value", "Precondition: value != null");
            }

            return(value.Aggregate(default(ItemRestrictions), (current, s) => current | this.itemRestrictionConverter.Convert(s, state)));
        }
示例#31
0
        public static int ElementwiseHash <T>(this ICollection <T> collection)
        {
            if (collection == null)
            {
                return(0);
            }

            return(collection.Aggregate(collection.Count, (current, element) => unchecked ((current * 397) ^ element.GetHashCode())));
        }
示例#32
0
        public static string EvaluateList(ICollection<Object> collection, Object lowerNumber, Object higherNumber)
        {
            DivisionOutput result = collection.Aggregate(
                new DivisionOutput() { Operations = String.Empty, Log = String.Empty },
                (currentOutput, value) =>
                    currentOutput += EvaluateItem(value, lowerNumber, higherNumber));

            return result.Operations + "\r\n" + result.Log;
        }
 public static string Setup(BackgroundWorker worker, ICollection<Row> rows, ICollection<Row> excludeRows, IEnumerable<string> list, IEnumerable<string> exclude)
 {
     foreach (var i in list)
     {
         if (worker.CancellationPending) return null;
         if (exclude.Any(j => i.EndsWith(j, StringComparison.CurrentCultureIgnoreCase)))
         {
             excludeRows.Add(new Row(i, false));
         }
         else if (System.IO.Directory.Exists(i))
         {
             worker.ReportProgress(0, string.Format("{0:#,0}ファイル {1:#,0}行 {2:#,0}バイト 除外 {3:#,0}", rows.Count, rows.Aggregate(0L, (s, r) => s += r.Count ?? 0L), rows.Aggregate(0L, (s, r) => s += r.Size ?? 0L), excludeRows.Count));
             if (Setup(worker, rows, excludeRows, System.IO.Directory.EnumerateFileSystemEntries(i), exclude) == null) return null;
         }
         else if (!rows.Any(j => j.Path == i))
         {
             rows.Add(new Row(i, true));
         }
     }
     return string.Format("全 {0:#,0}ファイル {1:#,0}行 {2:#,0}バイト 除外 {3:#,0}", rows.Count, rows.Aggregate(0L, (s, r) => s += r.Count ?? 0L), rows.Aggregate(0L, (s, r) => s += r.Size ?? 0L), excludeRows.Count);
 }
示例#34
0
        internal static string Parse(string content, List<string> matches, ICollection<PgType> types)
        {
            foreach (string match in matches)
            {
                string comment = HtmlHelper.RemoveComment(match);

                if (!comment.StartsWith("Types"))
                {
                    continue;
                }

                comment = comment.Replace("Types", "");
                string items = "";
                items = types.Aggregate(items, (current, type) => current + Parse(comment, type));

                content = content.Replace(match, items);
            }
            return content;
        }
示例#35
0
        public TextureAtlas(Device device, ICollection<string> filenames) {
            NumCells = filenames.Count;

            // Note: all textures need to be the same size
            var tex = Texture2D.FromFile(device, filenames.First());
            var w = tex.Description.Width;
            var h = tex.Description.Height;
            tex.Dispose();

            Columns = Math.Min(8192 / w, (int)Math.Ceiling(Math.Sqrt(NumCells)));
            Rows = Math.Min(8192 / h, (int)Math.Ceiling((float)NumCells/Columns));

            System.Diagnostics.Debug.Assert(Columns * Rows >= NumCells);

            var bitmap = new Bitmap(Columns * w, Rows * h);
            _texTransforms = new Matrix[NumCells];

            using (var g = Graphics.FromImage(bitmap)) {
                g.Clear(Color.Black);
                var r = 0;
                var c = 0;
                foreach (var filename in filenames) {
                    g.DrawImage(new Bitmap(filename), new Point(c*w, r*h) );

                    _texTransforms[r * Columns + c] =
                        Matrix.Scaling(1.0f/(Columns*2), 1.0f / (2*Rows), 0) * 
                        Matrix.Translation(c * w / (float)bitmap.Width, r * h / (float)bitmap.Width, 0);

                    c++;
                    if (c >= Columns) {
                        c = 0;
                        r++;
                    }

                }
            }
            var tmpFile = Path.GetTempFileName() + ".bmp";
            bitmap.Save(tmpFile);

            TextureView = ShaderResourceView.FromFile(device, tmpFile);
            TextureView.Resource.DebugName = "texture atlas: " +filenames.Aggregate((i, j) => i + ", " + j);
        }
示例#36
0
        /// <summary>
        ///     导出到CSV文件
        /// </summary>
        /// <param name="titles">文件标题</param>
        /// <param name="datas">数据</param>
        /// <param name="fileName">要保存的文件名</param>
        public static void DataTableToCSV(ICollection<string> titles, IEnumerable<object[]> datas, string fileName,
            char split = ',', Encoding encoding = null)
        {
            if (encoding == null)
                encoding = Encoding.UTF8;
            var fs = new FileStream(fileName, FileMode.OpenOrCreate);

            var sw = new StreamWriter(new BufferedStream(fs), encoding);

            var title = titles.Aggregate("", (current, title1) => current + (title1 + split));

            title = title.Substring(0, title.Length - 1) + "\n";

            sw.Write(title);

            foreach (var rows in datas)
            {
                var line = new StringBuilder();
                foreach (var row in rows)
                {
                    if (row != null)
                    {
                        line.Append(row.ToString().Trim());
                    }
                    else
                    {
                        line.Append(" ");
                    }
                    line.Append(split);
                }
                var result = line.ToString().Substring(0, line.Length - 1) + "\n";

                sw.Write(result);
            }

            sw.Close();

            fs.Close();
        }
 /// <summary>
 /// this method will acquire the website name from a given command which has been identified
 /// as a go to website command.
 /// </summary>
 /// <param name="commandSegments">command segments as a list (to remove problems that may occur when there are spaces)</param>
 /// <returns>identified website name</returns>
 public static string GetWebsiteNameForGoCommand(ICollection<string> commandSegments)
 {
     try
     {
         var fileContent = FileManager.GetContentOfAFile("fnc_brwsr_go"); // get the contents of the respective file as a list
         // the file content above do not comprise of the website names
         // thus the underneath foreach loop will iterate through the file content
         // and if the any of the content is available in the command segments, it will remove them
         // so that the website name will be remaining at the end
         foreach (var content in fileContent.Where(commandSegments.Contains))
         {
             commandSegments.Remove(content);
         }
         // from the remaining command segment, if the user has provided the command as
         // for instance google dot com, the "dot" will be replaced by a "." and finally the command
         // segments will be concatenated and returned to the user
         return commandSegments.Aggregate("", (current, segment) => current + (segment == "dot" ? "." : segment));
     }
     catch (Exception ex)
     {
         Log.ErrorLog(ex);
         throw;
     }
 }
示例#38
0
        public void Start(ICollection<string> titles)
        {
            fileStream = new FileStream(FileName, FileMode.OpenOrCreate);
            streamWriter = new StreamWriter(new BufferedStream(fileStream), AttributeHelper.GetEncoding(EncodingType));
            var title = titles.Aggregate("", (current, title1) => current + (title1 + SplitChar));

            title = title.Substring(0, title.Length - 1) + "\n";

            streamWriter.Write(title);
        }
示例#39
0
 public void Optimize(
         BigInteger allFeatureBitMask, BigInteger rejectingFeatureBitMask,
         ICollection<BigInteger> rejectedFeatures) {
     Accepting &= allFeatureBitMask
                  ^ rejectedFeatures.Aggregate(rejectingFeatureBitMask, (a, b) => a | b);
 }
示例#40
0
        private static double AppendLine(PageRenderData context, ICollection<TextElement> inlines, TextAlignment align, 
                                         ParagraphInfo p, double width, double top, double defaultFontSize, 
                                         int paragraphID, bool firstLine)
        {
            if (inlines.Count == 0)
                return top;

            double height = inlines.Max((t => t.Height));
            double inlinesWidth = inlines.Sum((t => t.Width));
            double leftMargin = 0.0;
            double wordSpacing = 0.0;
            double textIndent = !firstLine || align != TextAlignment.Justify && align != TextAlignment.Left
                              ? 0.0
                              : p.TextIndent;
            width -= p.MarginRight + p.MarginLeft + textIndent;

            switch (align)
            {
                case TextAlignment.Center:
                    leftMargin = (width - inlinesWidth)/2.0;
                    break;
                case TextAlignment.Right:
                    leftMargin = width - inlinesWidth;
                    break;
                case TextAlignment.Justify:
                    wordSpacing = (width - inlinesWidth)/(inlines.Count - 1);
                    break;
            }

            double tempLeftMargin = leftMargin + (p.MarginLeft + textIndent);

            inlines.Aggregate(tempLeftMargin, (current, inlineItem) => 
                BuildInlineItem(context, top, defaultFontSize, paragraphID, inlineItem, height, current, wordSpacing));

            return top + height * AppSettings.Default.FontSettings.FontInterval;
        }
示例#41
0
        /// <summary>
        /// An overload for MirrorDir that specifies both the excludePdbs and useMultipleRobocopyInstances options.
        /// </summary>
        /// <param name="srcdir">The source to be mirrored.</param>
        /// <param name="destdir">The destination to be mirrored.</param>
        /// <param name="files">The specific files or search patterns to be mirrored.  If null, *.* is used.</param>
        /// <param name="logfile">The logfile to which to be written.</param>
        /// <param name="recurseSubdirs">A bool indicating if subdirectories should be copied or not.</param>
        /// <param name="excludePdbs">A bool indicating if pdb files should be excluded.</param>
        /// <param name="useMultipleRobocopyInstances">A bool indicating if multiple instances of robocopy should be used.
        /// If true, a maximum of ThreadPool.GetMaxThreads() robocopy instances will be spawned.</param>
        /// <returns>If useMultipleRobocopyInstances is true, a RobocopyData object is returned, and its signal field will be signaled
        /// when the robocopy completes.  Otherwise, null is returned.</returns>
        public static RobocopyData MirrorDir(string srcdir, string destdir, ICollection<string> files, string logfile, bool recurseSubdirs,
            bool excludePdbs, bool useMultipleRobocopyInstances)
        {
            if (useMultipleRobocopyInstances)
            {
                // multiple robocopy instances were requested, so queue up some background threads
                // that will each spawn a robocopy process and signal a wait handle when done
                // return the wait handle so that the caller can monitor the robocopy progress
                //
                var data = new RobocopyData
                {
                    srcDir = srcdir,
                    destDir = destdir
                };
                if (files != null)
                {
                    data.files = files;
                }
                data.logFile = logfile;
                data.recurseSubdirs = recurseSubdirs;
                data.excludePdbs = excludePdbs;
                data.signal = new ManualResetEvent(false);

                ThreadPool.QueueUserWorkItem(ThreadedMirrorDir, data);
                return data;
            }
            // make sure we didn't get any null arguments
            // 
            if (srcdir == null)
            {
                srcdir = string.Empty;
            }
            if (destdir == null)
            {
                destdir = string.Empty;
            }

            // call robocopy directly and allow it to block the current thread
            // first build up the robocopy command to be run
            //

            var robocopyCmd = string.Format(recurseSubdirs ? "robocopy /mir /np /nfl /r:5 /w:5 \"{0}\" \"{1}\"" : "robocopy /copy:dat /purge /np /r:5 /w:5 \"{0}\" \"{1}\"", srcdir.TrimEnd('\\'), destdir.TrimEnd('\\'));

            // iterate through the files to be copied and add each to the command line
            //
            if (files != null)
            {
                robocopyCmd = files.Aggregate(robocopyCmd, (current, f) => current + $" \"{f}\" ");
            }

            // if excludepdbs is true then add this as a command line param to robocopy
            //
            if (excludePdbs)
            {
                robocopyCmd += " /XF *.pdb";
            }

            // run robocopy
            //
            RunRobocopyCommand(robocopyCmd, logfile);
            return null;
        }
 private Location GetClosestLocation(ICollection<Location> locations, Location location)
 {
     return locations.Aggregate((loc1, loc2) => location.ComputeEuclidicDistance(loc1) < location.ComputeEuclidicDistance(loc2) ? loc1 : loc2);
 }
        private static void RecursiveResolveProperty(ICollection<DataProperty> properties, int level)
        {
            if (level < 0)
            {
                throw new ArgumentException("Level can't be negative", "level");
            }
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }

            var continueSearch = false;

            foreach (var entry in properties.Where(entry => !string.IsNullOrEmpty(entry.Value)).Where(entry => entry.Value.Contains("[") && entry.Value.Contains("]")))
            {
                foreach (var entry2 in properties)
                {
                    entry.Value = entry.Value.Replace("[" + entry2.Id + "]", entry2.Value);
                }

                if (entry.Value.Contains("[") && entry.Value.Contains("]"))
                {
                    continueSearch = true;
                }
            }

            if (!continueSearch)
            {
                return;
            }

            if (level > 20)
            {
                var exceptionString = properties.Aggregate(string.Empty, (current, entry3) => current + (entry3.Id + "->" + entry3.Value + "**"));

                Log.WriteError("Could not resolve all properties" + exceptionString, "RecursiveResolveProperty");
                throw new InstallerVerificationLibraryException("Could not resolve all properties" + exceptionString);
            }
            RecursiveResolveProperty(properties, ++level);
        }
示例#44
0
        static string GetTags(ICollection<string> tags)
        {
            if (tags == null || tags.Count == 0)
                return string.Empty;

            var html = tags.Aggregate("", (current, tag) => current + string.Format("<a href='#' onclick=\"ChangePostFilter('Tag','{0}','')\">{0}</a>, ", tag));
            return html.Trim().Substring(0, html.Trim().Length - 1);
        }
示例#45
0
        static string GetCategories(ICollection<Category> categories)
        {
            if (categories == null || categories.Count == 0)
                return string.Empty;

            var html = categories.Aggregate("", (current, cat) => current + string.Format("<a href='#' onclick=\"ChangePostFilter('Category','{0}','{1}')\">{1}</a>, ", cat.Id, cat.Title));
            return html.Trim().Substring(0, html.Trim().Length - 1);
        }
        /// <summary>
        /// Updates information in summary page.
        /// </summary>
        /// <param name="remappingList">List of remappings</param>
        private void UpdateSummaryInformation(ICollection<RemappingResult> remappingList)
        {
            TimeSpan baseDuration = m_plan.GetTotalTime(m_character.After(m_plan.ChosenImplantSet), false);
            lvPoints.Items.Clear();

            // Add global informations
            ListViewGroup globalGroup = new ListViewGroup("Global informations");
            lvPoints.Groups.Add(globalGroup);

            TimeSpan savedTime = remappingList.Aggregate(TimeSpan.Zero,
                                                         (current, remap) =>
                                                         current.Add(remap.BaseDuration.Subtract(remap.BestDuration)));

            lvPoints.Items.Add(new ListViewItem(
                $"Current time : {baseDuration.ToDescriptiveText(DescriptiveTextOptions.IncludeCommas)}", globalGroup));

            if (savedTime != TimeSpan.Zero)
            {
                lvPoints.Items.Add(
                    new ListViewItem(
                        $"Optimized time : {baseDuration.Subtract(savedTime).ToDescriptiveText(DescriptiveTextOptions.IncludeCommas)}",
                        globalGroup));

                if (savedTime < TimeSpan.Zero)
                {
                    ListViewItem savedTimeItem = lvPoints.Items.Add(
                        new ListViewItem(
                            $"{(-savedTime).ToDescriptiveText(DescriptiveTextOptions.IncludeCommas)} slower than current.",
                                         globalGroup));
                    savedTimeItem.ForeColor = Color.DarkRed;
                }
                else
                {
                    ListViewItem savedTimeItem = lvPoints.Items.Add(
                        new ListViewItem(
                            $"{savedTime.ToDescriptiveText(DescriptiveTextOptions.IncludeCommas)} better than current.",
                                         globalGroup));
                    savedTimeItem.ForeColor = Color.DarkGreen;
                }
            }
            else
                lvPoints.Items.Add(new ListViewItem("Your attributes are already optimal.", globalGroup));

            // Notify plan updated
            ListViewItem lvi = new ListViewItem("Your plan has been updated.", globalGroup)
                                   { Font = FontFactory.GetFont(lvPoints.Font, FontStyle.Bold) };
            lvPoints.Items.Add(lvi);

            // Add pages and summary informations
            TimeSpan lastRemap = TimeSpan.Zero;
            foreach (RemappingResult remap in remappingList)
            {
                AddSummaryForRemapping(remap, ref lastRemap);
            }

            columnHeader.Width = lvPoints.ClientSize.Width;
        }
示例#47
0
 static float mass_flow(ICollection<ResourceLine> resources)
 {
     if(resources == null || resources.Count == 0) return 0;
     return resources.Aggregate(0f, (f, r) => f+r.Rate);
 }
示例#48
0
        internal static string ParseTriggers(string content, List<string> matches, ICollection<PgFunction> functions)
        {
            foreach (string match in matches)
            {
                string comment = HtmlHelper.RemoveComment(match);

                string items = "";

                if (!comment.StartsWith("TriggerFunctions"))
                {
                    continue;
                }

                comment = comment.Replace("TriggerFunctions", "");

                items = functions.Aggregate(items, (current, procedure) => current + Parse(comment, procedure));

                content = content.Replace(match, items);
            }

            return content;
        }
        private static string RecursiveResolvePropertiesInString(ICollection<DataProperty> properties, string value,
            int level)
        {
            if (level < 0)
            {
                throw new ArgumentException("Level can't be negative", "level");
            }
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException("value");
            }

            var continueSearch = false;
            if (value.Contains("[") && value.Contains("]"))
            {
                value = properties.Aggregate(value, (current, entry) => current.Replace("[" + entry.Id + "]", entry.Value));

                if (value.Contains("[") && value.Contains("]"))
                {
                    if (value.IndexOf("[", StringComparison.OrdinalIgnoreCase) !=
                        value.LastIndexOf("[", StringComparison.OrdinalIgnoreCase) && !value.Contains("[!]"))
                    {
                        continueSearch = true;
                    }
                }
            }

            if (!continueSearch)
            {
                return value;
            }

            if (level > 20)
            {
                Log.WriteError("Could not resolve all properties for '" + value + "'",
                    "RecursiveResolvePropertiesInString");
                return value;
            }

            value = RecursiveResolvePropertiesInString(properties, value, ++level);

            return value;
        }
示例#50
0
        private static string HttpBuildQuery(ICollection<KeyValuePair<string, string>> param)
        {
            var strRetVal = "";

            if (param.Count > 0) {
                strRetVal = param.Aggregate(strRetVal, (current, s) => current + (s.Key + "=" + s.Value + "&"));
                strRetVal = strRetVal.Substring(0, strRetVal.Length - 1);
            }

            return strRetVal;
        }
示例#51
0
        /// <summary>
        /// Partitioning evenly ensures that each processor used by PLinq will deal
        /// with a partition of equal "weight". In this case, we make sure each
        /// partition contains not only the same amount of files, but also (as close
        /// to as possible) the same amount of "bytes". For example, if we have 100
        /// files totaling 32MB and 4 processors, we will end up with 4 partitions
        /// of (exactly) 25 files totalling (approximately) 8MB each.
        /// 
        /// Note: This code inside this method is not the cleanest, but it is
        /// written in a way that tries to minimiz the # of large array allocations.
        /// </summary>
        private static IList<IFileContentsPiece> CreateFilePieces(ICollection<FileData> filesWithContents)
        {
            // Factory for file identifiers
              int currentFileId = 0;
              Func<int> fileIdFactory = () => currentFileId++;

              // Predicate to figure out if a file is "small"
              Func<FileData, bool> isSmallFile = x => x.Contents.ByteLength <= ChunkSize;

              // Count the total # of small and large files, while splitting large files
              // into their fragments.
              var smallFilesCount = 0;
              var largeFiles = new List<FileContentsPiece>(filesWithContents.Count / 100);
              foreach (var fileData in filesWithContents) {
            if (isSmallFile(fileData)) {
              smallFilesCount++;
            } else {
              var splitFileContents = SplitFileContents(fileData, fileIdFactory());
              largeFiles.AddRange(splitFileContents);
            }
              }
              var totalFileCount = smallFilesCount + largeFiles.Count;

              // Store elements in their partitions
              // # of partitions = # of logical processors
              var fileContents = new FileContentsPiece[totalFileCount];
              var partitionCount = Environment.ProcessorCount;
              var generator = new PartitionIndicesGenerator(
            totalFileCount,
            partitionCount);

              // Store large files
              foreach (var item in largeFiles) {
            fileContents[generator.Next()] = item;
              }
              // Store small files
              foreach (var fileData in filesWithContents) {
            if (isSmallFile(fileData)) {
              var item = fileData.Contents.CreatePiece(
            fileData.FileName,
            fileIdFactory(),
            fileData.Contents.TextRange);
              fileContents[generator.Next()] = item;
            }
              }

              if (LogPiecesStats) {
            Debug.Assert(fileContents.All(x => x != null));
            Debug.Assert(fileContents.Aggregate(0L, (c, x) => c + x.ByteLength) ==
              filesWithContents.Aggregate(0L, (c, x) => c + x.Contents.ByteLength));
            fileContents.GetPartitionRanges(partitionCount).ForAll(
              (index, range) => {
            Logger.LogInfo("Partition {0} has a weight of {1:n0}",
              index,
              fileContents
                .Skip(range.Key)
                .Take(range.Value)
                .Aggregate(0L, (c, x) => c + x.ByteLength));
              });
              }
              return fileContents;
        }
示例#52
0
        public static string GetSummaryReport(ICollection<SessionEx> sessions)
        {
            var res = new StringBuilder(DefaultBufferSize);

            res.AppendLine("Name\tValue");

            if (sessions.Count > 0)
            {
                var minDate = sessions.Min(session => session.LastUpdateTime);
                res.AppendLine("MinDate\t{0}", minDate.ToString("yyyy-MM-dd HH:mm:ss"));

                var maxDate = sessions.Max(session => session.LastUpdateTime);
                res.AppendLine("MaxDate\t{0}", maxDate.ToString("yyyy-MM-dd HH:mm:ss"));
            }

            // append leading space as a workaround for the PowerPivot quirk
            // http://social.msdn.microsoft.com/Forums/en-US/sqlkjpowerpivotforexcel/thread/456699ec-b5a2-4ae9-bc9f-b7ed2d637959
            res.AppendLine("SessionsCount\t {0}", sessions.Count);

            var latencyRecordsCount = sessions.Aggregate(0,
                (val, session) => val + session.Records.Where(Util.IsLatency).Count());
            res.AppendLine("LatencyRecordsCount\t {0}", latencyRecordsCount);

            var jitterRecordsCount = sessions.Aggregate(0,
                (val, session) => val + session.Records.Where(Util.IsJitter).Count());
            res.AppendLine("JitterRecordsCount\t {0}", jitterRecordsCount);

            return res.ToString();
        }
        public static Type DeduceType(ICollection<object> values)
        {
            // Try to find a common type among the elements.
            var result = values.Aggregate(null as Type,
                (current, next) => GetCommonType(current, next != null ? next.GetType() : typeof(object)));

            if (result == typeof(object))
            {
                // Try again with interfaces.
                var interfaceSets = values.Select(item => item != null ? item.GetType().GetInterfaces() : null);
                foreach (var commonInterface in CommonInterfaces)
                {
                    if (interfaceSets.All(interfaceSet =>
                        interfaceSet == null || interfaceSet.Contains(commonInterface)))
                    {
                        result = commonInterface;
                        break;
                    }
                }
            }

            return result ?? typeof(object);
        }