Example #1
1
        private static IList<int> Merge(IList<int> left, IList<int> right)
        {
            var result = new List<int>();

            while (left.Any() && right.Any())
            {
                if (left[0] < right[0])
                {
                    result.Add(left[0]);
                    left.Remove(left[0]);
                }
                result.Add(right[0]);
                right.Remove(right[0]);
            }

            while (left.Any())
            {
                result.Add(left[0]);
                left.Remove(left[0]);
            }
            while (right.Any())
            {
                result.Add(right[0]);
                right.Remove(right[0]);
            }

            return result;
        }
Example #2
1
        public MultilayerPerceptron(int numInputs, int numOutputs, IList<int> hiddenLayerSizes)
        {
            if (numInputs <= 0)
                throw new NeuralNetworkException($"Argument {nameof(numInputs)} must be positive; was {numInputs}.");

            if (numOutputs <= 0)
                throw new NeuralNetworkException($"Argument {nameof(numOutputs)} must be positive; was {numOutputs}.");

            if (hiddenLayerSizes == null || !hiddenLayerSizes.Any())
                throw new NeuralNetworkException($"Argument {nameof(hiddenLayerSizes)} cannot be null or empty.");

            if (hiddenLayerSizes.Any(h => h <= 0))
            {
                var badSize = hiddenLayerSizes.First(h => h <= 0);
                var index = hiddenLayerSizes.IndexOf(badSize);
                throw new NeuralNetworkException($"Argument {nameof(hiddenLayerSizes)} must contain only positive " +
                                                $"values; was {badSize} at index {index}.");
            }

            NumInputs = numInputs;
            NumOutputs = numOutputs;
            HiddenLayerSizes = hiddenLayerSizes.ToArray();

            Weights = new double[hiddenLayerSizes.Count + 1][];

            for (var i = 0; i < hiddenLayerSizes.Count + 1; i++)
            {
                if (i == 0)
                    Weights[i] = new double[(numInputs + 1) * hiddenLayerSizes[0]];
                else if (i < hiddenLayerSizes.Count)
                    Weights[i] = new double[(hiddenLayerSizes[i-1] + 1) * hiddenLayerSizes[i]];
                else
                    Weights[i] = new double[(hiddenLayerSizes[hiddenLayerSizes.Count - 1] + 1) * numOutputs];
            }
        }
        /// <summary>
        /// Sort the items by their priority and their index they currently exist in the collection
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public static IList<IClientDependencyFile> SortItems(IList<IClientDependencyFile> files)
        {
            //first check if each item's order is the same, if this is the case we'll make sure that we order them 
            //by the way they were defined
            if (!files.Any()) return files;

            var firstPriority = files.First().Priority;

            if (files.Any(x => x.Priority != firstPriority))
            {
                var sortedOutput = new List<IClientDependencyFile>();
                //ok they are not the same so we'll need to sort them by priority and by how they've been entered
                var groups = files.GroupBy(x => x.Priority).OrderBy(x => x.Key);
                foreach (var currentPriority in groups)
                {
                    //for this priority group, we'll need to prioritize them by how they are found in the files array
                    sortedOutput.AddRange(currentPriority.OrderBy(files.IndexOf));
                }
                return sortedOutput;
            }

            //they are all the same so we can really just return the original list since it will already be in the 
            //order that they were added.
            return files;
        } 
Example #4
1
 /// <summary>
 /// 初始化降生点
 /// </summary>
 /// <param name="points">可行走区域</param>
 /// <param name="pins">排除传送阵区域</param>
 public void InitBron(IList<Point> points, IList<Rectangle> pins)
 {
     m_bornPlace = new List<Point>();
     if (m_box.Range != Rectangle.Empty)
     {
         foreach (var p in points)
         {
             if (m_box.Range.Contains(p))
             {
                 if (!pins.Any(x => x.Contains(p)))
                 {
                     m_bornPlace.Add(p);
                 }
             }
         }
     }
     if (m_bornPlace.Count == 0)
     {
         foreach (var p in points)
         {
             if (!pins.Any(x => x.Contains(p)))
             {
                 m_bornPlace.Add(p);
             }
         }
     }
     int index = NumberRandom.Next(m_bornPlace.Count);
     this.m_point = m_bornPlace[index];
 }
Example #5
1
        public static IList<int> Merge(IList<int> left, IList<int> right)
        {
            IList<int> result = new List<int>();

            while (left.Any() && right.Any())
            {
                if (left[0] < right[0])
                {
                    result.Add(left[0]);
                    left.Remove(left[0]);
                }
                else
                {
                    result.Add(right[0]);
                    right.Remove(right[0]);
                }
            }

            while (left.Any())
            {
                result.Add(left[0]);
                left.RemoveAt(0);
            }
            while (right.Any())
            {
                result.Add(right[0]);
                right.RemoveAt(0);
            }

            return result;
        }
        public IList<CounterDescriptor> UpdateCounterItems(IList<CounterDescriptor> counterItems)
        {
            //get sites from IIS
            ServerManager iisManager = new ServerManager();
            var sites = iisManager.Sites;

            //build list of names no longer used
            var countersToRemove = new List<string>();
            foreach (var counterItem in counterItems)
            {
                if (!sites.Any(rd => rd.Name==counterItem.Name))
                    countersToRemove.Add(counterItem.Name);
            }
            //remove all contained in removal list
            counterItems = counterItems.Where(item => !countersToRemove.Contains(item.Name)).ToList();

            //add new
            foreach (var iisSite in sites)
            {
                //if we don't have an item with the same name in our list, add it
                if (!counterItems.Any(rd => rd.Name==iisSite.Name))
                {
                    counterItems.Add(CreateDescriptor(iisSite));
                }
            }

            //total
            if (!counterItems.Any(rd => rd.Name == "Total"))
            {
                counterItems.Add(CreateAllMethodRequestsDescriptor());
            }

            //return
            return counterItems;
        }
        private string FormatDeletePatterns(IList<ITriple> deletePatterns, string updateGraphUri)
        {
            var deleteCmds = new StringBuilder();
            int propId = 0;
            if (deletePatterns.Any(p => IsGraphTargeted(p) && IsGrounded(p)))
            {
                deleteCmds.AppendLine("DELETE DATA {");
                foreach (var patternGroup in deletePatterns.Where(p => IsGraphTargeted(p) && IsGrounded(p)).GroupBy(p=>p.Graph))
                {
                    deleteCmds.AppendFormat("GRAPH <{0}> {{", patternGroup.Key);
                    deleteCmds.AppendLine();
                    foreach (var deletePattern in patternGroup)
                    {
                        AppendTriplePattern(deletePattern, deleteCmds);
                    }
                    deleteCmds.AppendLine("}");
                }
                deleteCmds.AppendLine("};");
            }
            foreach (var deletePattern in deletePatterns.Where(p=>IsGraphTargeted(p) && !IsGrounded(p)))
            {
                deleteCmds.AppendFormat("WITH <{0}> DELETE {{ {1} }} WHERE {{ {1} }};",
                                        deletePattern.Graph, FormatDeletePattern(deletePattern, ref propId));
            }
            if (deletePatterns.Any(p => !IsGraphTargeted(p) && IsGrounded(p)))
            {
                // Delete from default graph
                deleteCmds.AppendLine("DELETE DATA {");
                foreach (var p in deletePatterns.Where(p => !IsGraphTargeted(p) && IsGrounded(p)))
                {
                    AppendTriplePattern(p, deleteCmds);
                }
                // If an update graph is specified delete from that too
                if (updateGraphUri != null)
                {
                    deleteCmds.AppendFormat("GRAPH <{0}> {{", updateGraphUri);
                    deleteCmds.AppendLine();
                    foreach (var p in deletePatterns.Where(p => !IsGraphTargeted(p) && IsGrounded(p)))
                    {
                        AppendTriplePattern(p, deleteCmds);
                    }
                    deleteCmds.AppendLine("}");
                }
                deleteCmds.AppendLine("};");

            }
            foreach (var deletePattern in deletePatterns.Where(p => !IsGraphTargeted(p) && !IsGrounded(p)))
            {
                var cmd = String.Format("DELETE {{ {0} }} WHERE {{ {0} }};",
                                        FormatDeletePattern(deletePattern, ref propId));
                deleteCmds.AppendLine(cmd);
                if (updateGraphUri != null)
                {
                    deleteCmds.AppendFormat("WITH <{0}> ", updateGraphUri);
                    deleteCmds.AppendLine(cmd);
                }
            }
            return deleteCmds.ToString();
        }
Example #8
1
        public EntityDeleteModel(IList<PropertyDeleteOption> deleteOptions)
        {
            DisplayRecordHierarchy = deleteOptions.Any();
            AssumableDeleteHierarchyWarning = deleteOptions.Any(x => x.ShowOptions);

            if (deleteOptions.Any(x => x.DeleteOption == CascadeOption.AskUser))
                PropertiesDeleteOptions = deleteOptions.Where(x => x.Visible).ToList();
            else
                PropertiesDeleteOptions = new List<PropertyDeleteOption>();
        }
        /// <summary>
        /// Returns the submission status for an entire assignment.
        /// </summary>
        public static SubmissionStatus ForAssignment(
            IList<SubmissionStatus> questionStatus)
        {
            var completion = questionStatus.All(q => q.Completion == Completion.Completed)
                ? Completion.Completed
                : questionStatus.Any(q => q.Completion != Completion.NotStarted)
                    ? Completion.InProgress
                    : Completion.NotStarted;

            var late = questionStatus.Any(q => q.Late);

            return new SubmissionStatus(completion, late);
        }
        private IEnumerable<FieldDeclarationSyntax> GetRuleViolations(IList<dynamic> fieldsInfo)
        {
            if (fieldsInfo.Any(f => !f.IsCollection))
            {
                return fieldsInfo.Where(f => f.IsCollection).Select(f => f.Syntax as FieldDeclarationSyntax);
            }

            if (fieldsInfo.Any(f => f.IsCollection))
            {
                return fieldsInfo.Where(f => f.IsCollection).Skip(1).Select(f => f.Syntax as FieldDeclarationSyntax);
            }

            return new List<FieldDeclarationSyntax>();
        }
        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            if (IsHtmlFile && completionSets.Any())
            {
                var bottomSpan = completionSets.First().ApplicableTo;
                if (!JScriptEditorUtil.IsInJScriptLanguageBlock(_lbm, bottomSpan.GetStartPoint(bottomSpan.TextBuffer.CurrentSnapshot)))
                {
                    // This is an HTML statement completion session, so do nothing
                    return;
                }
            }

            // TODO: Reflect over the ShimCompletionSet to see where the Description value comes from
            //       as setting the property does not actually change the value.
            var newCompletionSets = completionSets
                .Select(cs => cs == null ? cs : new ScriptCompletionSet(
                    cs.Moniker,
                    cs.DisplayName,
                    cs.ApplicableTo,
                    cs.Completions
                        .Select(c => c == null ? c : new Completion(
                            c.DisplayText,
                            c.InsertionText,
                            DocCommentHelper.ProcessParaTags(c.Description),
                            c.IconSource,
                            c.IconAutomationText))
                        .ToList(),
                    cs.CompletionBuilders))
                .ToList();
            
            completionSets.Clear();

            newCompletionSets.ForEach(cs => completionSets.Add(cs));
        }
        public static Movement Analyze(IList<Movement> movements)
        {
            Movement movement;

            if (movements.Any(x => x > Movement.Higher))
                movement = Movement.Highest;
            else if (movements.Any(x => x > Movement.High))
                movement = Movement.High;
            else if (movements.Any(x => x > Movement.Med))
                movement = Movement.Med;
            else if (movements.Average(x => (double)x) > (double)Movement.Lowest)
                movement = Movement.Low;
            else
                movement = Movement.Lowest;
            return movement;
        }
Example #13
0
        public void Execute(IList<IAggregateCommand> commands, int expectedVersion)
        {
            if (!commands.Any())
            {
                return;
            }

            var rootId = commands.First().AggregateId;

            if (commands.Any(x => x.AggregateId != rootId))
            {
                throw new InvalidOperationException("Can only execute commands for a single aggregate at a time");
            }

            var root = this.repository.GetById(rootId);
            if (root == null)
            {
                root = this.repository.New();
                root.Identity = rootId;
            }

            if (expectedVersion != 0)
            {
                // if we using this command executor multiple times for the same aggregate, when we invoke it we will often have the 
                // verion of the roor prior to the first invocation. Consequently when we check the expected version the second time, 
                // we have a different version and we get an exception. This is supposed to handle that case by remembering what the 
                // version of the root was when we first saw it.
                var rootVersion = root.Version;
                if (this.versions.ContainsKey(root.Identity))
                {
                    rootVersion = this.versions[root.Identity];
                }

                if (rootVersion != expectedVersion)
                {
                    throw new InvalidOperationException(string.Format("Not Expected Version {0}, {1}", expectedVersion, root.Version));
                }
            }

            var exec = new ExecutingCommandExecutor(root);
            exec.Execute(commands, expectedVersion);

            this.repository.Save(root);

            if (expectedVersion != 0 && !this.versions.ContainsKey(root.Identity))
            {
                this.versions[root.Identity] = expectedVersion;
            }
        }
Example #14
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public static IList<string> Upload(IList<FileItem> files)
        {
            if (files == null || !files.Any())
            {
                return null;
            }

            //远程
            if (_fileUploadType.Equals("REMOTE", StringComparison.CurrentCultureIgnoreCase))
            {
                var req = YunClient.Instance.Execute(new FileUploadRequest { Images = files });
                if (!req.IsError && req.Files != null && req.Files.Any())
                {
                    return req.Files;
                }

                return null;
            }

            //本地
            return
                files.Select(file => new PictureCore(file.GetContent(), file.GetFileName()))
                    .Select(instance => instance.Create())
                    .Where(result => !string.IsNullOrWhiteSpace(result))
                    .ToList();
        }
Example #15
0
        /// <summary>
        /// Retrives the width columns.
        /// </summary>
        /// <param name="columns">The columns.</param>
        /// <returns>Dictionary{System.StringSystem.Int32}.</returns>
        private static Dictionary<string, int> RetriveWidthColumns(IList<string> columns)
        {
            var columnWidthList = new Dictionary<string, int>();

            if (columns != null && columns.Any())
            {
                if (columns[0].Contains(Constants.SplitVerticalBar))
                {
                    for (var i = 0; i < columns.Count(); i++)
                    {
                        var column = columns[i].Split(Constants.SplitVerticalBar);

                        var columnUniqName = !string.IsNullOrEmpty(column[0]) ? column[0] : string.Empty;

                        var columnWidth = 0;
                        try
                        {
                            columnWidth = !string.IsNullOrEmpty(column[1]) && column[1].Length > 1 ? Convert.ToInt32(column[1], CultureInfo.InvariantCulture) : 0;
                        }
                        catch
                        {
                        }

                        columnWidthList[columnUniqName.Trim()] = columnWidth;
                    }
                }
            }

            return columnWidthList;
        }
Example #16
0
        public bool Prepare(wnd.IDataObject ido)
        {
            currentDishes = SelectDishes(ido);
            PrepareDishes(currentDishes);

            return currentDishes.Any();
        }
Example #17
0
        public bool Prepare(string url, string format)
        {
            currentDishes = SelectDishes(url, format);
            PrepareDishes(currentDishes);

            return currentDishes.Any();
        }
Example #18
0
 private static IEnumerable<object[]> GetFilesPerTest(IList<string> tests, IList<string> skips = null)
 {
     var files = TestDocuments;
     if (tests == null)
     {
         yield return new object[0];
         yield break;
     }
     if (skips == null)
         skips = new string[0];
     foreach (var file in files)
     {
         var filenames = new List<string>();
         var ok = false;
         foreach (var ext in tests)
         {
             if (!file.Value.Contains(ext))
             {
                 ok = false;
                 break;
             }
             filenames.Add(Path.Combine("Data", file.Key + ext));
             ok = true;
         }
         if (ok && !skips.Any(skip => file.Value.Contains(skip)))
             yield return filenames.Cast<object>().ToArray();
     }
 }
        public void SetNotificationTypeActions(IList<NotificationTypeAction> actions, int notificationTypeId)
        {
            Requires.NotNull("actions", actions);

            if (!actions.Any())
            {
                throw new ArgumentException("Actions must contain at least one item.");
            }

            if (actions.Any(x => string.IsNullOrEmpty(x.APICall)))
            {
                throw new ArgumentException("All actions must specify an APICall");
            }

            if (actions.Any(x => string.IsNullOrEmpty(x.NameResourceKey)))
            {
                throw new ArgumentException("All actions must specify a NameResourceKey");
            }

            foreach (var action in actions)
            {
                action.NotificationTypeActionId = _dataService.AddNotificationTypeAction(notificationTypeId,
                                                                                         action.NameResourceKey,
                                                                                         action.DescriptionResourceKey,
                                                                                         action.ConfirmResourceKey,
                                                                                         action.APICall,
                                                                                         GetCurrentUserId());
                action.NotificationTypeId = notificationTypeId;
            }
        }
        public ProgramConstruct ProcessTokens(IList<ResolvedToken> tokens) {
            Contract.Requires(tokens != null);

            _tokens = tokens;
            var functions = new List<FunctionConstruct>();
            ExectuableBlockConstruct block = null;

            while (_tokens.Any() && PeekNextToken() != Token.EOF) {
                switch (PeekNextToken()) {

                    case Token.KW_FUNC:
                        functions.Add(ProcessAsFunction());
                        break;

                    case Token.EOL:
                        GetNextToken();
                        break;

                    default:
                        block = ProcessAsBlock(true);
                        break;

                }
            }


            return new ProgramConstruct(functions, block);
        }
        /// <summary>
        /// Exports the specified entry.
        /// </summary>
        /// <param name="entries">The entry.</param>
        internal void Export(IList<Entry> entries)
        {
            if (entries.Any() == false) return;

            // setup variable to group all error messages together
            var errorBuilder = new StringBuilder();

            // Build a batch based update to avoid memory overhead
            var bulkCommand = new BulkCommand(GetIndex(), LOG_TYPE);
            var bulkJsons = new BulkBuilder(serializer)
                .PipelineCollection(entries, (builder, entity) => builder.Index(entity, id: entity.Id.ToString()))
                .JoinInBatches(batchSize: 1000);

            foreach (var bulk in bulkJsons)
            {
                string result = connection.Put(bulkCommand, bulk);

                var bulkResult = serializer.ToBulkResult(result);

                // Check for errors
                foreach (var operation in bulkResult.items.Where(a => a.Result.ok == false))
                {
                    errorBuilder.AppendFormat("Id: {0} Error: {1} {2}", operation.Result._id, operation.Result.error, Environment.NewLine);
                }
            }

            // Check for any errors that are reported by the ElasticSearch
            var error = errorBuilder.ToString();
            if (string.IsNullOrWhiteSpace(error) == false) throw new ApplicationException(error);
        }
        /// <summary>
        /// Gets a read-only cached <see cref="CultureInfo"/> for the specified name. Only names that exist in
        /// <paramref name="supportedCultures"/> will be used.
        /// </summary>
        /// <param name="name">The culture name.</param>
        /// <param name="supportedCultures">The cultures supported by the application.</param>
        /// <returns>
        /// A read-only cached <see cref="CultureInfo"/> or <c>null</c> a match wasn't found in
        /// <paramref name="supportedCultures"/>.
        /// </returns>
        public static CultureInfo GetCultureInfo(string name, IList<CultureInfo> supportedCultures)
        {
            // Allow only known culture names as this API is called with input from users (HTTP requests) and
            // creating CultureInfo objects is expensive and we don't want it to throw either.
            if (name == null || supportedCultures == null ||
                !supportedCultures.Any(supportedCulture => string.Equals(supportedCulture.Name, name, StringComparison.OrdinalIgnoreCase)))
            {
                return null;
            }

            var entry = _cache.GetOrAdd(name, n =>
            {
                try
                {
                    return new CacheEntry(CultureInfo.ReadOnly(new CultureInfo(n)));
                }
                catch (CultureNotFoundException)
                {
                    // This can still throw as the list of culture names we have is generated from latest .NET Framework
                    // on latest Windows and thus contains names that won't be supported on lower framework or OS versions.
                    // We can just cache the null result in these cases as it's ultimately bound by the list anyway.
                    return new CacheEntry(cultureInfo: null);
                }
            });

            return entry.CultureInfo;
        }
        public static NamespaceDeclarationSyntax AddUsingDirectives(
            this NamespaceDeclarationSyntax namespaceDeclaration,
            IList<UsingDirectiveSyntax> usingDirectives,
            bool placeSystemNamespaceFirst,
            params SyntaxAnnotation[] annotations)
        {
            if (!usingDirectives.Any())
            {
                return namespaceDeclaration;
            }

            var specialCaseSystem = placeSystemNamespaceFirst;
            var comparer = specialCaseSystem
                ? UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance
                : UsingsAndExternAliasesDirectiveComparer.NormalInstance;

            var usings = new List<UsingDirectiveSyntax>();
            usings.AddRange(namespaceDeclaration.Usings);
            usings.AddRange(usingDirectives);

            if (namespaceDeclaration.Usings.IsSorted(comparer))
            {
                usings.Sort(comparer);
            }

            usings = usings.Select(u => u.WithAdditionalAnnotations(annotations)).ToList();
            var newNamespace = namespaceDeclaration.WithUsings(SyntaxFactory.List(usings));

            return newNamespace;
        }
Example #24
0
        private static void SeedEnemies(IList<IGameObject> entities)
        {
            int saturation = Rand.Next(MinEnemySaturationRate, MaxEnemySaturationPercentage + 1);

            int numberOfEnemies = saturation * Constants.MapHeight * Constants.MapWidth / 100;

            var enemies = Assembly.GetExecutingAssembly().GetTypes()
                .Where(t => t.IsClass)
                .Where(t => t.CustomAttributes.Any(a => a.AttributeType == typeof(EnemyAttribute)))
                .ToArray();

            for (int i = 0; i < numberOfEnemies; i++)
            {
                int currentX = Rand.Next(1, Constants.MapWidth);
                int currentY = Rand.Next(1, Constants.MapHeight);

                while (entities.Any(e => e.Position.X == currentX && e.Position.Y == currentY))
                {
                    currentX = Rand.Next(1, Constants.MapWidth);
                    currentY = Rand.Next(1, Constants.MapHeight);
                }

                int entityIndex = Rand.Next(0, enemies.Length);

                var entity = Activator.CreateInstance(enemies[entityIndex], new Position(currentX, currentY)) as IGameObject;

                entities.Add(entity);
            }
        }
 private bool IsWinner(IList<NoughtsAndCrossesButton> buttons)
 {
     if (buttons.Any(x => x.Value == null)) { return false; }
     return (from b in buttons
            group b by b.Value into g
            select new {g.Key}).Count() == 1;
 }
Example #26
0
        public InterlockDataAdapter(OleDbDataReader dr ,IList<string> dynamicList, int startColumn)
        {
            ControlSystemName = string.Empty;
            InterlockTypeName =
            Number = string.Empty;
            Cause = string.Empty;
            Description = string.Empty;

            ControlSystemName = dr.SafeString((int)InterlockColumn.ControlSystemName).Trim();
            InterlockTypeName = dr.SafeString((int)InterlockColumn.InterlockType).Trim();
            Number = dr.SafeString((int)InterlockColumn.Number).Trim();
            Cause = dr.SafeString((int)InterlockColumn.Cause).Trim();
            Description = dr.SafeString((int)InterlockColumn.Description).Trim();

            DynamicProperties = new List<DynamicProperty>();

            if (dynamicList != null && dynamicList.Any())
            {
                for (int d = 0; d < dynamicList.Count(); d++)
                {
                    string p = dynamicList[d];

                    DynamicProperty property = new DynamicProperty();

                    property.PropertyName = p;
                    property.PropertyValue = dr.SafeString(startColumn + d);

                    DynamicProperties.Add(property);
                }
            }
        }
        private string GetInternalLoadBalancerIPAddress(IList<VirtualIPAddress> virtualIPs, string ilbName)
        {
            var ilbIP = virtualIPs == null || !virtualIPs.Any() ? null
                      : virtualIPs.FirstOrDefault(ip => string.Equals(ip.Name, ilbName, StringComparison.OrdinalIgnoreCase));

            return ilbIP == null ? null : ilbIP.Address;
        }
        public override void Export(IList<BenchmarkReport> reports, IBenchmarkLogger logger, IEnumerable<IBenchmarkResultExtender> resultExtenders = null)
        {
            if(useCodeBlocks)
                logger.WriteLine($"```{codeBlocksSyntax}");
            logger = new BenchmarkLoggerWithPrefix(logger, prefix);
            logger.WriteLineInfo(EnvironmentInfo.GetCurrentInfo().ToFormattedString("Host"));
            logger.NewLine();

            var table = BenchmarkExporterHelper.BuildTable(reports, resultExtenders);
            // If we have Benchmarks with ParametersSets, force the "Method" columns to be displayed, otherwise it doesn't make as much sense
            var columnsToAlwaysShow = 
                (reports.Any(r => r.Benchmark.Task.ParametersSets != null) ? new[] { "Method" } : new string[0]).
                Concat((resultExtenders ?? new IBenchmarkResultExtender[0]).Select(e => e.ColumnName)).ToArray();
            PrintTable(table, logger, columnsToAlwaysShow);

            // TODO: move this logic to an analyser
            var benchmarksWithTroubles = reports.Where(r => !r.GetTargetRuns().Any()).Select(r => r.Benchmark).ToList();
            if (benchmarksWithTroubles.Count > 0)
            {
                logger.NewLine();
                logger.WriteLineError("Benchmarks with troubles:");
                foreach (var benchmarkWithTroubles in benchmarksWithTroubles)
                    logger.WriteLineError("  " + benchmarkWithTroubles.Caption);
            }
        }
Example #29
0
        public InstanceConfiguration Parse(IList<string> args)
        {
            var cfg = new InstanceConfiguration
                {
                    AppName = string.Empty,
                    Help = false,
                    Verbose = false,
                    ExtraParams = new List<string>()
                };

            var p = new OptionSet
                {
                    {"app=", v => cfg.AppName = v},
                    {"i|install", v => cfg.Install = v != null},
                    {"v|verbose", v => cfg.Verbose = v != null},
                    {"h|?|help", v => cfg.Help = v != null},
                };
            cfg.OptionSet = p;

            if (args == null || !args.Any())
            {
                cfg.Help = true;
                return cfg;
            }

            cfg.ExtraParams = p.Parse(args);
            cfg.AppName = cfg.AppName.Trim('"', '\'');
            return cfg;
        }
Example #30
0
        /// <summary>
        /// A general method which takes a list of data and calculates its corresponding aggregate value.
        /// It will be used to calculate the aggregate value of each pages individually, with considering the previous pages data.
        /// </summary>
        /// <param name="columnCellsSummaryData">List of data</param>
        /// <returns>Aggregate value</returns>
        public object ProcessingBoundary(IList<SummaryCellData> columnCellsSummaryData)
        {
            if (columnCellsSummaryData == null || !columnCellsSummaryData.Any()) return 0;

            var list = columnCellsSummaryData;
            return list.Sum(item => Convert.ToDouble(item.CellData.PropertyValue, CultureInfo.InvariantCulture));
        }