Esempio n. 1
0
 public static Task <string> ReadContent(this IFileSystemOperator @operator, string filePath)
 {
     return(EnumerableHelper.ProcessSingular(@operator.ReadContentsByFilePath, filePath));
 }
Esempio n. 2
0
        public override void Run(ExecutionSettings executionSettings, bool printRules)
        {
            builder = new MsDataBuilder();
            var data = builder.BuildInstance(executionSettings);

            var frequentSets = data.Elements.Keys.Select(element => new List <int> {
                element
            }).ToList();

            frequentSets = frequentSets.Where(set => set.IsFrequent(data.Transactions, executionSettings.MinSup)).ToList();
            var frequentItemSets = frequentSets.ToDictionary(set => new FrequentItemSet <int>(set),
                                                             set => set.GetSupport(data.Transactions));
            List <List <int> > candidates;

            while ((candidates = GenerateCandidates(frequentSets)).Count > 0)
            {
                //! sprawdź czy któryś podzbiór k-1 elementowy kadydatów nie jest w frequentSets => wywal go!

                // leave only these sets which are frequent
                candidates =
                    candidates.Where(set => set.IsFrequent(data.Transactions, executionSettings.MinSup)).ToList();

                if (candidates.Count > 0)
                {
                    frequentSets = candidates;
                    foreach (var candidate in candidates)
                    {
                        var fItemSet = new FrequentItemSet <int>(candidate);

                        if (!frequentItemSets.ContainsKey(fItemSet))
                        {
                            frequentItemSets.Add(fItemSet, candidate.GetSupport(data.Transactions));
                        }
                    }
                }
                else
                {
                    // we don't have any more candidates
                    break;
                }
            }

            //here we should do something with the candidates
            var decisionRules = new List <DecisionRule <int> >();

            foreach (var frequentSet in frequentSets)
            {
                var subSets = EnumerableHelper.GetSubsets(frequentSet);

                foreach (var t in subSets)
                {
                    var leftSide = new FrequentItemSet <int>(t);
                    for (var j = 0; j < subSets.Count; j++)
                    {
                        var rightSide = new FrequentItemSet <int>(subSets[j]);
                        if (rightSide.ItemSet.Count != 1 || !FrequentItemSet <int> .SetsSeparated(rightSide, leftSide))
                        {
                            continue;
                        }

                        if (frequentItemSets.ContainsKey(leftSide))
                        {
                            var confidence = (double)frequentItemSets[new FrequentItemSet <int>(frequentSet)] / frequentItemSets[leftSide];
                            if (confidence >= executionSettings.MinConf)
                            {
                                var rule = new DecisionRule <int>(leftSide.ItemSet, rightSide.ItemSet, frequentItemSets[new FrequentItemSet <int>(frequentSet)], confidence);
                                decisionRules.Add(rule);
                            }
                        }
                    }
                }
            }

            if (!printRules)
            {
                return;
            }

            var result = PrintRules(decisionRules, executionSettings.DataSourcePath, executionSettings.MinSup,
                                    executionSettings.MinConf, data.Transactions.Keys.Count, data.Elements);

            Console.WriteLine(result);
        }
Esempio n. 3
0
 public static Task <bool> ExistsFile(this IFileSystemOperator @operator, string filePath)
 {
     return(EnumerableHelper.ProcessSingular(@operator.ExistsFiles, filePath));
 }
Esempio n. 4
0
 private Task <IDictionary <int, ImageAssetRenderDetails> > GetMainImages(PagedQueryResult <CustomEntityRenderSummary> customEntityResult)
 {
     return(_imageAssetRepository.GetImageAssetRenderDetailsByIdRangeAsync(customEntityResult
                                                                           .Items
                                                                           .Select(i => (PlayerDataModel)i.Model)
                                                                           .Where(m => !EnumerableHelper.IsNullOrEmpty(m.ImageAssetIds))
                                                                           .Select(m => m.ImageAssetIds.First())
                                                                           .Distinct()));
 }
Esempio n. 5
0
 public IEnumerable <IDiagnoser> GetDiagnosers() => EnumerableHelper.Empty <IDiagnoser>();
Esempio n. 6
0
 public KeyFrame()
 {
     FrameReference = -1;
     Scripts        = EnumerableHelper.Array(4, string.Empty);
 }
Esempio n. 7
0
        public void ImportFromModel(object model, params object[] context)
        {
            IEnumerable   input = model as IEnumerable;
            List <TValue> inputList;

            if (input == null)
            {
                inputList = new List <TValue>();
            }
            else
            {
                inputList = EnumerableHelper.CreateFrom <TValue>(typeof(List <TValue>), input, 0) as List <TValue>;

                inputList.Sort();

                ChoiceList <TChoiceItem, TValue, TDisplay> choiceList = context[0] as ChoiceList <TChoiceItem, TValue, TDisplay>;

                List <CheckBoxListItem <TValue> > items   = new List <CheckBoxListItem <TValue> >();
                List <OrderItem <TValue> >        orderer = new List <OrderItem <TValue> >();

                int index = 0;

                foreach (TChoiceItem item in choiceList.Items)
                {
                    CheckBoxListItem <TValue> checkBoxListItem = new CheckBoxListItem <TValue>();
                    OrderItem <TValue>        orderItem        = new OrderItem <TValue>();
                    checkBoxListItem.Code  = choiceList.ValueSelector(item);
                    checkBoxListItem.Label = choiceList.DisplaySelector(item).ToString();

                    if (choiceList.LabelAttributesSelector != null)
                    {
                        checkBoxListItem.LabelAttributes = choiceList.LabelAttributesSelector(item);
                    }
                    else
                    {
                        checkBoxListItem.LabelAttributes = new { }
                    };
                    if (choiceList.DisplayAttributesSelector != null)
                    {
                        checkBoxListItem.DisplayAttributes = choiceList.DisplayAttributesSelector(item);
                    }
                    else
                    {
                        checkBoxListItem.DisplayAttributes = new { }
                    };
                    items.Add(checkBoxListItem);

                    orderItem.Value = checkBoxListItem.Code;
                    orderItem.Place = index;
                    orderer.Add(orderItem);
                    index++;
                }
                Items = items.ToArray();
                orderer.Sort();
                IEnumerator <OrderItem <TValue> > ordererIterator = (orderer as IEnumerable <OrderItem <TValue> >).GetEnumerator();
                ordererIterator.Reset();
                ordererIterator.MoveNext();
                foreach (TValue selectedValue in inputList)
                {
                    while (((IComparable)selectedValue).CompareTo(ordererIterator.Current.Value) > 0)
                    {
                        ordererIterator.MoveNext();
                    }
                    if (((IComparable)selectedValue).CompareTo(ordererIterator.Current.Value) == 0)
                    {
                        Items[ordererIterator.Current.Place].Selected = true;
                    }
                }
            }
        }
    }
Esempio n. 8
0
 public void For()
 {
     Assert.Equal("0,1,2", EnumerableHelper.For(3).JoinStr(","));
 }
Esempio n. 9
0
        private async Task <BulkCopyRowsCopied> ProviderSpecificCopyInternal <T>(
            ProviderConnections providerConnections,
            ITable <T> table,
            BulkCopyOptions options,
            IAsyncEnumerable <T> source,
            CancellationToken cancellationToken)
            where T : notnull
        {
            var dataConnection = providerConnections.DataConnection;
            var connection     = providerConnections.ProviderConnection;
            var transaction    = providerConnections.ProviderTransaction;
            var ed             = dataConnection.MappingSchema.GetEntityDescriptor(typeof(T));
            var columns        = ed.Columns.Where(c => !c.SkipOnInsert || options.KeepIdentity == true && c.IsIdentity).ToList();
            var sb             = _provider.CreateSqlBuilder(dataConnection.MappingSchema);
            var rc             = new BulkCopyRowsCopied();

            var bc = _provider.Adapter.BulkCopy !.Create(connection, transaction);

            if (options.NotifyAfter != 0 && options.RowsCopiedCallback != null)
            {
                bc.NotifyAfter = options.NotifyAfter;

                bc.MySqlRowsCopied += (sender, args) =>
                {
                    rc.RowsCopied += args.RowsCopied;
                    options.RowsCopiedCallback(rc);
                    if (rc.Abort)
                    {
                        args.Abort = true;
                    }
                };
            }

            if (options.BulkCopyTimeout.HasValue)
            {
                bc.BulkCopyTimeout = options.BulkCopyTimeout.Value;
            }

            var tableName = GetTableName(sb, options, table);

            bc.DestinationTableName = GetTableName(sb, options, table);

            for (var i = 0; i < columns.Count; i++)
            {
                bc.AddColumnMapping(_provider.Adapter.BulkCopy.CreateColumnMapping(i, columns[i].ColumnName));
            }

            // emulate missing BatchSize property
            // this is needed, because MySql fails on big batches, so users should be able to limit batch size
            var batches = EnumerableHelper.Batch(source, options.MaxBatchSize ?? int.MaxValue);

            await foreach (var batch in batches.WithCancellation(cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext))
            {
                var rd = new BulkCopyReader <T>(dataConnection, columns, batch, cancellationToken);

                await TraceActionAsync(
                    dataConnection,
                    () => (bc.CanWriteToServerAsync2 || bc.CanWriteToServerAsync ? "INSERT ASYNC BULK " : "INSERT BULK ") + tableName + "(" + string.Join(", ", columns.Select(x => x.ColumnName)) + Environment.NewLine,
                    async() => {
                    if (bc.CanWriteToServerAsync2)
                    {
                        await bc.WriteToServerAsync2(rd, cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext);
                    }
                    else
                    if (bc.CanWriteToServerAsync)
                    {
                        await bc.WriteToServerAsync(rd, cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext);
                    }
                    else
                    {
                        bc.WriteToServer(rd);
                    }
                    return(rd.Count);
                }, true).ConfigureAwait(Configuration.ContinueOnCapturedContext);

                rc.RowsCopied += rd.Count;
            }

            if (options.NotifyAfter != 0 && options.RowsCopiedCallback != null)
            {
                options.RowsCopiedCallback(rc);
            }

            return(rc);
        }
 public static T Random <T>(this IEnumerable <T> input)
 {
     return(EnumerableHelper.Random(input));
 }
Esempio n. 11
0
        /// <summary>
        /// Creates the <see cref="PagedSource"/>.
        /// </summary>
        /// <param name="sourceCollection">The source collection</param>
        public PagedSource(IEnumerable sourceCollection)
        {
            var pageSize = EnumerableHelper.Count(sourceCollection);

            Initialize(sourceCollection, pageSize);
        }
Esempio n. 12
0
        protected override BulkCopyRowsCopied ProviderSpecificCopy <T>(
            ITable <T> table,
            BulkCopyOptions options,
            IEnumerable <T> source)
        {
            if (_provider.Adapter.BulkCopy != null && table.DataContext is DataConnection dataConnection)
            {
                var connection = _provider.TryGetProviderConnection(dataConnection.Connection, dataConnection.MappingSchema);

                var transaction = dataConnection.Transaction;
                if (connection != null && transaction != null)
                {
                    transaction = _provider.TryGetProviderTransaction(transaction, dataConnection.MappingSchema);
                }

                if (connection != null && (dataConnection.Transaction == null || transaction != null))
                {
                    var ed      = dataConnection.MappingSchema.GetEntityDescriptor(typeof(T));
                    var columns = ed.Columns.Where(c => !c.SkipOnInsert || options.KeepIdentity == true && c.IsIdentity).ToList();
                    var sb      = _provider.CreateSqlBuilder(dataConnection.MappingSchema);
                    var rc      = new BulkCopyRowsCopied();

                    var bc = _provider.Adapter.BulkCopy.Create(connection, transaction);
                    if (options.NotifyAfter != 0 && options.RowsCopiedCallback != null)
                    {
                        bc.NotifyAfter = options.NotifyAfter;

                        bc.MySqlRowsCopied += (sender, args) =>
                        {
                            rc.RowsCopied += args.RowsCopied;
                            options.RowsCopiedCallback(rc);
                            if (rc.Abort)
                            {
                                args.Abort = true;
                            }
                        };
                    }

                    if (options.BulkCopyTimeout.HasValue)
                    {
                        bc.BulkCopyTimeout = options.BulkCopyTimeout.Value;
                    }

                    var tableName = GetTableName(sb, options, table);

                    bc.DestinationTableName = GetTableName(sb, options, table);

                    for (var i = 0; i < columns.Count; i++)
                    {
                        bc.AddColumnMapping(_provider.Adapter.BulkCopy.CreateColumnMapping(i, columns[i].ColumnName));
                    }

                    // emulate missing BatchSize property
                    // this is needed, because MySql fails on big batches, so users should be able to limit batch size
                    foreach (var batch in EnumerableHelper.Batch(source, options.MaxBatchSize ?? int.MaxValue))
                    {
                        var rd = new BulkCopyReader(dataConnection, columns, batch);

                        TraceAction(
                            dataConnection,
                            () => "INSERT BULK " + tableName + "(" + string.Join(", ", columns.Select(x => x.ColumnName)) + Environment.NewLine,
                            () => { bc.WriteToServer(rd); return(rd.Count); });

                        rc.RowsCopied += rd.Count;
                    }

                    if (options.NotifyAfter != 0 && options.RowsCopiedCallback != null)
                    {
                        options.RowsCopiedCallback(rc);
                    }

                    return(rc);
                }
            }

            return(MultipleRowsCopy(table, options, source));
        }
Esempio n. 13
0
 public void GetRecursivelyTest_Files()
 {
     EnumerableHelper.GetRecursively(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), Directory.GetDirectories, Directory.GetFiles)
     .ForEachExecute(Console.WriteLine);
 }
Esempio n. 14
0
        /// <summary>
        /// Rounds the frame to the nearest level of specified tolerance.
        /// </summary>
        /// <param name="origional">the frame to round</param>
        /// <param name="tolerance">the timespan to round on.</param>
        /// <returns>A new frame that is rounded.</returns>
        public static SortedList <DateTime, FrameData> RoundToTolerance(this SortedList <DateTime, FrameData> origional, TimeSpan tolerance)
        {
            SortedList <DateTime, FrameData> results = new SortedList <DateTime, FrameData>();

            SortedList <DateTime, List <FrameData> > buckets = new SortedList <DateTime, List <FrameData> >();

            foreach (KeyValuePair <DateTime, FrameData> items in origional)
            {
                DateTime roundedDate = items.Key.Round(tolerance);
                if (!buckets.TryGetValue(roundedDate, out List <FrameData> frames))
                {
                    frames = new List <FrameData>();
                    buckets.Add(roundedDate, frames);
                }
                frames.Add(items.Value);
            }

            foreach (KeyValuePair <DateTime, List <FrameData> > bucket in buckets)
            {
                if (bucket.Value.Count == 1)
                {
                    results.Add(bucket.Key, bucket.Value[0]);
                }
                else
                {
                    int          count = bucket.Value.Sum(x => x.Points.Count);
                    List <ulong> keys  = new List <ulong>(count);
                    List <HistorianValueStruct> values = new List <HistorianValueStruct>(count);

                    FrameData tempFrame = new FrameData();
                    tempFrame.Points = new SortedList <ulong, HistorianValueStruct>();

                    List <EnumerableHelper> allFrames = new List <EnumerableHelper>();

                    foreach (FrameData frame in bucket.Value)
                    {
                        allFrames.Add(new EnumerableHelper(frame));
                    }

                    while (true)
                    {
                        EnumerableHelper lowestKey = null;

                        foreach (EnumerableHelper item in allFrames)
                        {
                            lowestKey = Min(lowestKey, item);
                        }

                        if (lowestKey is null)
                        {
                            break;
                        }

                        keys.Add(lowestKey.PointId);
                        values.Add(lowestKey.Value);

                        //tempFrame.Points.Add(lowestKey.PointId, lowestKey.Value);
                        lowestKey.Read();
                    }
                    tempFrame.Points = SortedListConstructor.Create(keys, values);
                    results.Add(bucket.Key, tempFrame);
                }
            }
            return(results);
        }
Esempio n. 15
0
        private async Task <BulkCopyRowsCopied> ProviderSpecificCopyImplAsync <T>(DataConnection dataConnection, ITable <T> table, BulkCopyOptions options, IAsyncEnumerable <T> source, CancellationToken cancellationToken)
        {
            var connection = _provider.TryGetProviderConnection(dataConnection.Connection, dataConnection.MappingSchema);

            if (connection == null)
            {
                return(await MultipleRowsCopyAsync(table, options, source, cancellationToken).ConfigureAwait(Common.Configuration.ContinueOnCapturedContext));
            }

            var sqlBuilder = (BasicSqlBuilder)_provider.CreateSqlBuilder(dataConnection.MappingSchema);
            var ed         = dataConnection.MappingSchema.GetEntityDescriptor(typeof(T));
            var tableName  = GetTableName(sqlBuilder, options, table);
            var columns    = ed.Columns.Where(c => !c.SkipOnInsert || options.KeepIdentity == true && c.IsIdentity).ToArray();

            var fields      = string.Join(", ", columns.Select(column => sqlBuilder.ConvertInline(column.ColumnName, ConvertType.NameToQueryField)));
            var copyCommand = $"COPY {tableName} ({fields}) FROM STDIN (FORMAT BINARY)";

            // batch size numbers not based on any strong grounds as I didn't found any recommendations for it
            var batchSize = Math.Max(10, options.MaxBatchSize ?? 10000);

            var npgsqlTypes = new NpgsqlProviderAdapter.NpgsqlDbType[columns.Length];

            for (var i = 0; i < columns.Length; i++)
            {
                var npgsqlType = _provider.GetNativeType(columns[i].DbType, true);
                if (npgsqlType == null)
                {
                    var columnType = columns[i].DataType != DataType.Undefined ? new SqlQuery.SqlDataType(columns[i]) : null;

                    if (columnType == null || columnType.Type.DataType == DataType.Undefined)
                    {
                        columnType = columns[i].MappingSchema.GetDataType(columns[i].StorageType);
                    }

                    var sb = new System.Text.StringBuilder();
                    sqlBuilder.BuildTypeName(sb, columnType);
                    npgsqlType = _provider.GetNativeType(sb.ToString(), true);
                }

                if (npgsqlType == null)
                {
                    throw new LinqToDBException($"Cannot guess PostgreSQL type for column {columns[i].ColumnName}. Specify type explicitly in column mapping.");
                }

                npgsqlTypes[i] = npgsqlType.Value;
            }

            var writer = _provider.Adapter.BeginBinaryImport(connection, copyCommand);

            if (!writer.SupportsAsync)
            {
                // seems to be missing one of the required async methods; fallback to sync importer
                var enumerator = source.GetAsyncEnumerator(cancellationToken);
                await using (enumerator.ConfigureAwait(Common.Configuration.ContinueOnCapturedContext))
                {
                    return(ProviderSpecificCopySyncImpl(dataConnection, options, EnumerableHelper.AsyncToSyncEnumerable(enumerator), connection, tableName, columns, npgsqlTypes, copyCommand, batchSize, writer));
                }
            }

            var rowsCopied   = new BulkCopyRowsCopied();
            var currentCount = 0;

            try
            {
                await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(Common.Configuration.ContinueOnCapturedContext))
                {
                    await writer.StartRowAsync(cancellationToken).ConfigureAwait(Common.Configuration.ContinueOnCapturedContext);

                    for (var i = 0; i < columns.Length; i++)
                    {
                        await writer.WriteAsync(columns[i].GetValue(item !), npgsqlTypes[i], cancellationToken)
                        .ConfigureAwait(Common.Configuration.ContinueOnCapturedContext);
                    }

                    currentCount++;
                    rowsCopied.RowsCopied++;

                    if (options.NotifyAfter != 0 && options.RowsCopiedCallback != null && rowsCopied.RowsCopied % options.NotifyAfter == 0)
                    {
                        options.RowsCopiedCallback(rowsCopied);

                        if (rowsCopied.Abort)
                        {
                            break;
                        }
                    }

                    if (currentCount >= batchSize)
                    {
                        await writer.CompleteAsync(cancellationToken)
                        .ConfigureAwait(Common.Configuration.ContinueOnCapturedContext);

                        await writer.DisposeAsync()
                        .ConfigureAwait(Common.Configuration.ContinueOnCapturedContext);

                        writer       = _provider.Adapter.BeginBinaryImport(connection, copyCommand);
                        currentCount = 0;
                    }
                }

                if (!rowsCopied.Abort)
                {
                    await TraceActionAsync(
                        dataConnection,
                        () => "INSERT ASYNC BULK " + tableName + "(" + string.Join(", ", columns.Select(x => x.ColumnName)) + Environment.NewLine,
                        async() => {
                        var ret = await writer.CompleteAsync(cancellationToken)
                                  .ConfigureAwait(Common.Configuration.ContinueOnCapturedContext);
                        return((int)rowsCopied.RowsCopied);
                    }).ConfigureAwait(Common.Configuration.ContinueOnCapturedContext);
                }

                if (options.NotifyAfter != 0 && options.RowsCopiedCallback != null)
                {
                    options.RowsCopiedCallback(rowsCopied);
                }
            }
            finally
            {
                await writer.DisposeAsync()
                .ConfigureAwait(Common.Configuration.ContinueOnCapturedContext);
            }

            return(rowsCopied);
        }
 static EnumerableHelper Min(EnumerableHelper left, EnumerableHelper right)
 {
     if (left == null)
         return right;
     if (right == null)
         return left;
     if (!left.IsValid && !right.IsValid)
         return null;
     if (!left.IsValid)
         return right;
     if (!right.IsValid)
         return left;
     if (left.PointId < right.PointId)
         return left;
     return right;
 }
        public static void ReWrite(QueryModel queryModel, ISessionFactory sessionFactory)
        {
            var nsqmv = new NestedSelectDetector();

            nsqmv.VisitExpression(queryModel.SelectClause.Selector);
            if (!nsqmv.HasSubquery)
            {
                return;
            }

            var subQueryModel = nsqmv.Expression.QueryModel;

            var mainFromClause = subQueryModel.MainFromClause;

            var restrictions = subQueryModel.BodyClauses
                               .OfType <WhereClause>()
                               .Select(w => new NhWithClause(w.Predicate));

            var join = new NhJoinClause(mainFromClause.ItemName,
                                        mainFromClause.ItemType,
                                        mainFromClause.FromExpression,
                                        restrictions);

            queryModel.BodyClauses.Add(join);

            var visitor = new SwapQuerySourceVisitor(subQueryModel.MainFromClause, join);

            queryModel.TransformExpressions(visitor.Swap);

            var ctor = Tuple.Type.GetConstructor(System.Type.EmptyTypes);

            var key = Expression.Parameter(Tuple.Type, "key");

            var values = Expression.Parameter(typeof(IEnumerable <Tuple>), "values");

            var expressions = new List <ExpressionHolder>();

            var rewriter = new SelectClauseRewriter(key, values, expressions);

            var resultSelector = rewriter.VisitExpression(queryModel.SelectClause.Selector);

            var field = Tuple.Type.GetField("Items");

            var keySelector = CreateSelector(ctor, field, expressions, 0);

            var elementSelector = CreateSelector(ctor, field, expressions, 1);

            var cast = EnumerableHelper.GetMethod("Cast", new[] { typeof(IEnumerable) }, new[] { typeof(object[]) });

            var groupBy = EnumerableHelper.GetMethod("GroupBy",
                                                     new[] { typeof(IEnumerable <>), typeof(Func <,>), typeof(Func <,>), typeof(Func <, ,>) },
                                                     new[] { typeof(object[]), Tuple.Type, Tuple.Type, queryModel.SelectClause.Selector.Type });

            var toList = EnumerableHelper.GetMethod("ToList", new[] { typeof(IEnumerable <>) }, new[] { queryModel.SelectClause.Selector.Type });

            var input = Expression.Parameter(typeof(IEnumerable <object>), "input");

            var call = Expression.Call(toList,
                                       Expression.Call(groupBy,
                                                       Expression.Call(cast, input),
                                                       keySelector,
                                                       elementSelector,
                                                       Expression.Lambda(resultSelector, key, values)));

            var lambda = Expression.Lambda(call, input);

            queryModel.ResultOperators.Add(new ClientSideSelect2(lambda));

            var initializers = expressions.Select(e => e.Expression == null
                                                                                                                   ? GetIdentifier(sessionFactory, expressions, e)
                                                                                                                   : ConvertToObject(e.Expression));

            queryModel.SelectClause.Selector = Expression.NewArrayInit(typeof(object), initializers);
        }
Esempio n. 18
0
 protected override bool IsMatch(T value)
 {
     return(!EnumerableHelper.IsNullOrEmpty(value));
 }
Esempio n. 19
0
        public static MvcHtmlString CheckBoxListFor <TModel, TChoiceItem, TValue, TDisplay>
        (
            this HtmlHelper <TModel> htmlHelper,
            Expression <Func <TModel, IEnumerable <TValue> > > expression,
            ChoiceList <TChoiceItem, TValue, TDisplay> choiceList,
            bool useTemplate    = false,
            object template     = null,
            object itemTemplate = null)
            where TValue : IComparable
        {
            IEnumerable <TValue> values = default(IEnumerable <TValue>);

            if (expression == null)
            {
                throw (new ArgumentNullException("expression"));
            }
            try
            {
                values = expression.Compile().Invoke(htmlHelper.ViewData.Model);
            }
            catch {}
            if (values == null)
            {
                values = new List <TValue>();
            }
            if (choiceList == null)
            {
                throw (new ArgumentNullException("choiceList"));
            }

            var fullPropertyPath =
                htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(
                    ExpressionHelper.GetExpressionText(expression));
            var propertyPath =

                ExpressionHelper.GetExpressionText(expression);
            CheckBoxList <IEnumerable <TValue>, TChoiceItem, TValue, TDisplay> displayModel =
                new CheckBoxList <IEnumerable <TValue>, TChoiceItem, TValue, TDisplay>();

            displayModel.ImportFromModel(values, new object[] { choiceList });

            StringBuilder sb = new StringBuilder();

            sb.Append(BasicHtmlHelper.RenderDisplayInfo(htmlHelper,
                                                        typeof(CheckBoxList <IEnumerable <TValue>, TChoiceItem, TValue, TDisplay>),
                                                        propertyPath));

            int index = 0;

            foreach (CheckBoxListItem <TValue> item in displayModel.Items)
            {
                sb.Append(htmlHelper.Hidden
                              (EnumerableHelper.CreateSubIndexName(BasicHtmlHelper.AddField(propertyPath, "$.Items"), index) + ".Code",
                              item.Code));
                index++;
            }
            if (useTemplate)
            {
                if (template == null && itemTemplate == null)
                {
                    template = typeof(CheckBoxList <IEnumerable <TValue>, TChoiceItem, TValue, TDisplay>).Name;
                }
                if (template != null)
                {
                    ViewDataDictionary <CheckBoxList <IEnumerable <TValue>, TChoiceItem, TValue, TDisplay> > dataDictionary =
                        new ViewDataDictionary <CheckBoxList <IEnumerable <TValue>, TChoiceItem, TValue, TDisplay> >(displayModel);
                    dataDictionary.TemplateInfo.HtmlFieldPrefix = (BasicHtmlHelper.AddField(fullPropertyPath, "$"));

                    sb.Append(new TemplateInvoker <CheckBoxList <IEnumerable <TValue>, TChoiceItem, TValue, TDisplay> >(template).Invoke <TModel>(htmlHelper, dataDictionary));
                }
                else
                {
                    int itemIndex = 0;
                    foreach (CheckBoxListItem <TValue> item in displayModel.Items)
                    {
                        ViewDataDictionary <CheckBoxListItem <TValue> > dataDictionary =
                            new ViewDataDictionary <CheckBoxListItem <TValue> >(item);
                        dataDictionary.TemplateInfo.HtmlFieldPrefix = (BasicHtmlHelper.AddField(fullPropertyPath, string.Format("$.Items[{0}]", itemIndex)));
                        sb.Append(new TemplateInvoker <CheckBoxListItem <TValue> >(itemTemplate)
                                  .Invoke(htmlHelper, dataDictionary));
                        itemIndex++;
                    }
                }
            }
            else
            {
                index = 0;
                foreach (CheckBoxListItem <TValue> item in displayModel.Items)
                {
                    sb.Append("<div>");
                    sb.Append(htmlHelper.CheckBox(
                                  EnumerableHelper.CreateSubIndexName(BasicHtmlHelper.AddField(propertyPath, "$.Items"), index) + ".Selected",
                                  item.Selected,
                                  item.DisplayAttributes));
                    sb.Append("&nbsp;");
                    sb.Append(string.Format(CultureInfo.InvariantCulture,
                                            "<span {0}>{1}</span>",
                                            BasicHtmlHelper.GetAttributesString(item.LabelAttributes),
                                            item.Label));
                    sb.Append("</div>");
                    index++;
                }
            }
            return(MvcHtmlString.Create(sb.ToString()));
        }
Esempio n. 20
0
 /// <summary>
 /// Indicates if this contains one-off versioned updates. This basically
 /// ignores "always update commands" when checking to see if an exception
 /// should be thrown if the db is locked for updates and updates are required.
 /// </summary>
 public bool ContainsVersionUpdates()
 {
     return(!EnumerableHelper.IsNullOrEmpty(VersionedCommands));
 }
Esempio n. 21
0
        public void EncodeErr()
        {
            var pdus = EnumerableHelper.ToArray(PduEncoder.Encode(new Sms.Sms("+123456789123", "From its origin in southwestern Tibet as the Yarlung Tsangpo River, it flows across southern Tibet to break through the Himalayas in great gorges and into Arunachal Pradesh (India) where it is known as Dihang.[3] It flows southwest through the Assam Valley as Brahmaputra and south through Bangladesh as the Jamuna (not to be mistaken with Yamuna of India). In the vast Ganges Delta it merges with the Padma, the main distributary of the Ganges, then the Meghna, before emptying into the Bay of Bengal.")));

            Assert.Equal(4, pdus.Length);
        }
        public static void Main(string[] args)
        {
            if (args != null)
            {
                if (args.Length > 0)
                {
                    if (args[0] == "/wait")
                    {
                        Console.WriteLine("Waiting ... ...");
                        Console.WriteLine("Press any key to continue ...");
                        Console.ReadLine();
                        Console.WriteLine("Continue ... ...");
                    }
                }
            }
            Console.WriteLine($"{nameof(Environment.Version)}: {Environment.Version}");
            Console.WriteLine($"{nameof(RuntimeInformation.FrameworkDescription)}: {RuntimeInformation.FrameworkDescription}");

            OSPlatform OSPlatform
                = EnumerableHelper
                  .Range
                  (
                      OSPlatform.Linux
                      , OSPlatform.OSX
                      , OSPlatform.Windows
                  )
                  .First
                  (
                      (x) =>
            {
                return
                (RuntimeInformation
                 .IsOSPlatform(x));
            }
                  );
            var s = $"{nameof(RuntimeInformation.FrameworkDescription)}:{RuntimeInformation.FrameworkDescription}";

            s += "\n";
            s += $"{nameof(RuntimeInformation.OSArchitecture)}:{RuntimeInformation.OSArchitecture.ToString()}";
            s += "\n";
            s += $"{nameof(RuntimeInformation.OSDescription)}:{RuntimeInformation.OSDescription}";
            s += "\n";
            s += $"{nameof(RuntimeInformation.ProcessArchitecture)}:{RuntimeInformation.ProcessArchitecture.ToString()}";
            s += "\n";
            s += $"{nameof(OSPlatform)}:{OSPlatform}";

            Console.WriteLine(s);

            var os = Environment.OSVersion;

            Console.WriteLine("Current OS Information:\n");
            Console.WriteLine("Platform: {0:G}", os.Platform);
            Console.WriteLine("Version String: {0}", os.VersionString);
            Console.WriteLine("Version Information:");
            Console.WriteLine("   Major: {0}", os.Version.Major);
            Console.WriteLine("   Minor: {0}", os.Version.Minor);
            Console.WriteLine("Service Pack: '{0}'", os.ServicePack);

            CreateWebHostBuilder
                (args)
            //.UseKestrel()
            //.UseContentRoot(Directory.GetCurrentDirectory())
            //.UseIISIntegration()
            .Build()
            .Run();
        }
Esempio n. 23
0
 public IEnumerable <IJob> GetJobs() => EnumerableHelper.Empty <IJob>();
Esempio n. 24
0
        public static async Task <IDistinctEnumerable <string> > EnumerateFilePaths(this IFileSystemOperator @operator, string directoryPath)
        {
            var output = await EnumerableHelper.ProcessSingular(@operator.EnumerateFilePaths, directoryPath);

            return(output.AsDistinct());
        }
Esempio n. 25
0
        /// <summary>
        /// J. Shi et al. / Computer Vision and Image Understanding 102 (2006) 117–133
        /// Section 4.2
        /// </summary>
        /// <param name="benchmarkFeatures">Needs to have just two values</param>
        /// <param name="landmarkFeatures"></param>
        /// <param name="allDatabaseIndividuals"></param>
        public static RatioComparison ComputeInitialEigenRatios(
            List <FeaturePointType> benchmarkFeatures,
            List <FeaturePointType> landmarkFeatures,
            int numberOfDesiredRatios,
            List <DatabaseFin> allDatabaseIndividuals,
            List <IEnumerable <FeaturePointType> > suppliedRatioPermutations = null)
        {
            List <IEnumerable <FeaturePointType> > ratioPermutations;

            if (suppliedRatioPermutations != null)
            {
                ratioPermutations = suppliedRatioPermutations;
            }
            else
            {
                ratioPermutations = EnumerableHelper.GetUniquePermutations(landmarkFeatures, 2).ToList();
            }

            // Desired number of ratios needs to be <= the number of permutations.  We're going to set
            // it at that max if it's too large
            if (numberOfDesiredRatios > ratioPermutations.Count - 1)
            {
                numberOfDesiredRatios = ratioPermutations.Count - 1;
            }

            List <Vector <double> > ratioList = new List <Vector <double> >();
            var totalRatios = CreateVector.Dense <double>(ratioPermutations.Count - 1);

            foreach (var individual in allDatabaseIndividuals)
            {
                var ratios = CalculateRatios(individual, benchmarkFeatures, landmarkFeatures, ratioPermutations);
                totalRatios += ratios;
                ratioList.Add(ratios);
            }

            Vector <double> averageRatios = totalRatios / allDatabaseIndividuals.Count;

            var galleryMatrix = CreateMatrix.Dense <double>(ratioPermutations.Count - 1, allDatabaseIndividuals.Count);

            int j = 0;

            foreach (var ratioVector in ratioList)
            {
                Vector <double> translatedRatios = ratioVector - averageRatios;

                for (var i = 0; i < translatedRatios.Count; i++)
                {
                    galleryMatrix[i, j] = translatedRatios[i];
                }

                j += 1;
            }

            var covarianceMatrix = galleryMatrix * galleryMatrix.Transpose();

            // Perform the Eigenvalue Decomposition
            var evd = covarianceMatrix.Evd(Symmetricity.Unknown);

            // Find all the EigenValues with only real components (no imaginary)
            // and store their original index, and sort them descending so we
            // can then find the numberOfDesiredFeatures most significant values
            var sorted = evd.EigenValues
                         .Where(ev => ev.Imaginary == 0.0)
                         .Select((x, i) => new KeyValuePair <double, int>(x.Real, i))
                         .OrderByDescending(x => x.Key)
                         .ToList();

            var eigenValues       = sorted.Select(x => x.Key).ToList();
            var eigenValueIndices = sorted.Select(x => x.Value).ToList();

            // Now we want to build our projection matrix with the numberOfDesiredRatios
            // EigenVectors we want to keep (these will end up yielding the
            // numberOfDesiredRatios number of principal components)
            var projectionMatrix = CreateMatrix.Dense <double>(ratioPermutations.Count - 1, numberOfDesiredRatios);

            var result = new RatioComparison
            {
                RatioPermutations = ratioPermutations,
                AverageRatios     = averageRatios,
                BenchmarkFeatures = benchmarkFeatures,
                LandmarkFeatures  = landmarkFeatures,
                IndividualRatios  = new List <RatioItem>()
            };

            result.EigenValues = CreateVector.Dense <double>(numberOfDesiredRatios);

            for (int r = 0; r < numberOfDesiredRatios; r++)
            {
                result.EigenValues[r] = eigenValues[r];

                for (int k = 0; k < ratioPermutations.Count - 1; k++)
                {
                    // The EigenVectors are stored such that each column is an EigenVector
                    // with the Math.NET implementation
                    projectionMatrix[k, r] = evd.EigenVectors[k, eigenValueIndices[r]];
                }
            }

            result.ProjectionMatrix = projectionMatrix;

            var principalComponents = galleryMatrix.Transpose() * projectionMatrix;

            // Our principal components are now such that each database individual is a row
            var rHats = new List <Vector <double> >();

            for (int i = 0; i < allDatabaseIndividuals.Count; i++)
            {
                var item = new RatioItem
                {
                    DatabaseFin = allDatabaseIndividuals[i],
                    RHat        = CreateVector.Dense <double>(numberOfDesiredRatios),
                    RawRatios   = ratioList[i]
                };

                for (int k = 0; k < numberOfDesiredRatios; k++)
                {
                    item.RHat[k] = principalComponents[i, k];
                }

                result.IndividualRatios.Add(item);
            }

            return(result);
        }
Esempio n. 26
0
 public IEnumerable <T> Create <T>(int count) where T : class => EnumerableHelper.Create(count, Create <T>);