public IList<Type> ExtractIntegrationJobTypesFromAssemblies(IList<Assembly> assembliesWithJobs)
 {
     return assembliesWithJobs
         .SelectMany(x => x.GetTypes())
         .Where(x => typeof(IIntegrationJob).IsAssignableFrom(x) && x.IsClass)
         .ToList();
 }
        //todo: Link content to a content cache similar to openwraps package cache. Use same mechanism?
        public ContentLocator()
        {
            var environment = ServiceLocator.GetService<IEnvironment>();
            var packageManager = ServiceLocator.GetService<IPackageManager>();

            var baseDirectory = LocalFileSystem.Instance.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory);

            contentRoot = baseDirectory.GetDirectory("Content");
            contentRoot.MustExist();

            foreach (var scopedDescriptor in environment.ScopedDescriptors)
            {
                var files = packageManager.GetProjectExports<ContentFolderExport>(scopedDescriptor.Value.Value,
                                                                                  environment.ProjectRepository,
                                                                                  environment.ExecutionEnvironment);

                contentPathSources = files.SelectMany(x => x).Distinct().Select(x => x.Directory).ToList();
                foreach (
                    var pathSource in
                        contentPathSources.SelectMany(contentPathSource => contentPathSource.Directories()))
                {
                    pathSource.LinkTo(contentRoot.GetDirectory(pathSource.Name).MustExist().Path.FullPath);
                }
            }
        }
      public SchemaScope(JTokenType tokenType, IList<JsonSchemaModel> schemas)
      {
        _tokenType = tokenType;
        _schemas = schemas;

        _requiredProperties = schemas.SelectMany<JsonSchemaModel, string>(GetRequiredProperties).Distinct().ToDictionary(p => p, p => false);
      }
        private void ColoriseDupFilesWithDifferentPaths(ref IList<ProjectModel> projects)
        {
            // If there's a different version reference between 2 or more projects then flag this.
            // Example: ProjectA has EF 4.3.1. ProjectB has EF 5.0. We need to flag this in the UI.
            var children = projects.SelectMany(p => p.Children);
            children.Where(c => c.ItemType != "ProjectReference")
                .ToList()
                .ForEach(c =>
                    {
                        if (c.IsConflicting)
                            return;

                        var similar = children.Where(x => x.Filename.Equals(c.Filename, StringComparison.CurrentCultureIgnoreCase)
                            && !x.ItemLocation.Replace(@"..\", "").Equals(c.ItemLocation.Replace(@"..\", ""), StringComparison.CurrentCultureIgnoreCase)).ToList();
                        if (similar.Any())
                        {
                            int i = _r.Next(_pairedColors.Count - 1);
                            Color color = _pairedColors.Skip(i).First();
                            c.SimilarRefences = similar.ToList();
                            c.Color = color;
                            c.IsConflicting = true;
                            similar.ForEach(x =>
                                                {
                                                    x.Color = color;
                                                    x.IsConflicting = true;
                                                });
                        }
                    });
        }
 /// <summary>
 /// Searches for lunch menu URLs through all search engines with given query strings.
 /// </summary>
 /// <param name="queries">Query-strings to search with.</param>
 public IList<string> SearchForLunchMenuURLs(IList<string> queries)
 {
     return queries.SelectMany(SearchForLunchMenuURLs)
                   .AsParallel()
                   .Distinct(new UrlComparer())
                   .ToList();
 }
 public FactoryClass(IConstructorArgList argList, IList<IFactoryMethod> methods)
 {
     m_argList = argList;
     Methods = methods;
     foreach (var definition in methods.SelectMany(m => m.ConstructorArgs))
         argList.Add(definition);
 }
Example #7
1
 private static List<byte> Escape(IList<byte> p)
 {
     return p.SelectMany(q =>
         q == 0x7E ? new byte[] { 0x7d, 0x02 }
             : (q == 0x7D ? new byte[] { 0x7D, 0x01 }
                 : new[] { q })
     ).ToList();
 }
        /// <summary>
        ///     Mapping list of date models into list of timeslot models
        /// </summary>
        /// <param name="dates">List of date models</param>
        /// <returns>List of timeslot models</returns>

        public static IList<TimeSlot> MapToTimeSlot(IList<EventModel.DatesModel> dates)
        {
            return dates.SelectMany(d => d.Times.Select(time => new TimeSlot()
            {
                Id = time.Id.GetValueOrDefault(),
                DateTime = d.Date.Add(TimeSpan.Parse(time.Time))
            }).ToList()).ToList();
        }
Example #9
1
        public IList<CatalogDto> GetUsersCatalogs(IList<long> userIds)
        {
            var userCatalogIds = userIds
                    .SelectMany(x => Call<IList<long>>("get-user-catalogs", new { UserId = x }))
                    .Distinct().ToArray();

            return Get(userCatalogIds);
        }
        public ValidatedContractBlock(IList<ValidatedStatement> validatedContractBlock)
        {
            Contract.Requires(validatedContractBlock != null);

            _validatedContractBlock = validatedContractBlock;

            _contractBlock = validatedContractBlock.Select(x => x.ProcessedStatement).ToList();
            _validationResults = validatedContractBlock.SelectMany(x => x.ValidationResults).ToList();
        }
Example #11
1
        public bool UpdateValues(IList<AFValues> valsList)
        {
            IList<AFValue> valsToWrite = new List<AFValue>();

            valsToWrite = valsList.SelectMany(i => i).ToList();

            AFErrors<AFValue> errors = AFListData.UpdateValues(valsToWrite, AFUpdateOption.Replace);

            return (errors == null) ? true : false;
        }
 private IList<ISymbol> GenerateMembers(
     IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers,
     CancellationToken cancellationToken)
 {
     return
         unimplementedMembers.SelectMany(t => t.Item2)
                             .Select(m => GenerateMember(m, cancellationToken))
                             .WhereNotNull()
                             .ToList();
 }
 public double GetPointsPerMinute(IList<Player> players, bool? homeFixtures)
 {
     var fixtures = players.SelectMany(p => p.PastFixtures).ToList();
     if(homeFixtures.HasValue)
     {
         fixtures = fixtures.Where(pf => pf.Home == homeFixtures).ToList();
     }
     var totalMinutes = fixtures.Sum(f => f.MinutesPlayed);
     var totalPoints = fixtures.Sum(f => f.TotalPointsScored);
     return totalPoints/(double)totalMinutes;
 }
Example #14
1
        public Game(IList<Team> teams, Contract contract, IEnumerable<Card> deck, ILogger logger)
        {
            _logger = logger;
            Contract = contract;

            Teams = teams;
            _numberOfPlayers = teams.SelectMany(t => t.Players).Count();

            Declarer = Contract.Team.Players.First(); // TODO: This probably isn't right!
            Dummy = Contract.Team.Players.Last(); // TODO: This probably isn't right!

            Deal(deck, Declarer); //TODO: This Probably isn't right!
        }
            public SchemaScope(JTokenType tokenType, IList<JsonSchemaModel> schemas)
            {
                _tokenType = tokenType;
                _schemas = schemas;

                _requiredProperties = schemas.SelectMany<JsonSchemaModel, string>(GetRequiredProperties).Distinct().ToDictionary(p => p, p => false);

                if (tokenType == JTokenType.Array && schemas.Any(s => s.UniqueItems))
                {
                    IsUniqueArray = true;
                    UniqueArrayItems = new List<JToken>();
                }
            }
        public List<JsonPostResponse> Convert(IList<Post> posts, string username)
        {
            var list = posts.SelectMany(post => new List<JsonPostResponse>{
                Convert(post, username)
            });

            return list.ToList<JsonPostResponse>();
            //List<JsonPostResponse> convertedPosts = new List<JsonPostResponse>();
            //foreach (Post post in posts)
            //{
            //    convertedPosts.Add(Convert(post, username));
            //}
            //return convertedPosts;
        }
        public PersistentTaskController(ChannelGraph graph, ILogger logger, ITaskMonitoringSource factory, IList<IPersistentTaskSource> sources)
        {
            _graph = graph;
            _logger = logger;
            _factory = factory;
            sources.Each(x => _sources[x.Protocol] = x);

            _agents.OnMissing = uri => {
                var persistentTask = FindTask(uri);
                return persistentTask == null ? null : _factory.BuildAgentFor(persistentTask);
            };

            _permanentTasks = sources.SelectMany(x => x.PermanentTasks()).ToArray();
        }
Example #18
0
    public DbReader(DbConnection conn, IEnumerable<IReadOnlyItem> items)
    {
      _conn = conn;
      _items = items.ToList();
      
      _type = items.Select(i => i.Type().Value).FirstOrDefault();
      _count = _items.Count;
      GetMetadata();

      foreach (var rel in _items.SelectMany(i => i.Relationships())
                                .OrderBy(i => i.Type().Value))
      {
        _items.Add(rel);
      };
    }
        public virtual TeamStrength CalculateLastSeasonForm(IList<Player> players, int seasonEndYear)
        {
            var seasonRecords =
                players.SelectMany(p => p.PastSeasons.Where(ps => ps.SeasonEndYear == seasonEndYear)).ToList();
            var totalMinutes = seasonRecords.Sum(s => s.MinutesPlayed);
            var totalPoints = seasonRecords.Sum(s => s.TotalPointsScored);

            return new TeamStrength
                   {
                       SamplePlayers = players.Count,
                       TotalMinutes = totalMinutes,
                       TotalPointsScored = totalPoints,
                       PointsPerMinute = totalPoints/(double)totalMinutes,
                   };
        }
 public Dictionary<TimeSpan, List<CollectedSugar>> CollectByHour(Meal meal,
     IList<ReplacementItem> replacementItems)
 {
     this.meal = meal;
     IEnumerable<Tuple<Sugar, ReplacementItem>> sugarTuples = replacementItems
         .SelectMany(replacementItem => replacementItem.Pattern.After,
             (replacementItem, sugar) => new Tuple<Sugar, ReplacementItem>(sugar, replacementItem));
     var collectedSugars = sugarTuples.Select(tuple =>
         new CollectedSugar { Collected = GetSugarCopyWithRelativeTime(tuple), Source = tuple.Item2 });
     var groupped = collectedSugars
         .GroupBy(collectedSugar => new TimeSpan(collectedSugar.Collected.DateTime.Hour, 0, 0));
     return groupped.ToDictionary(groupping => groupping.Key + TimeSpan.FromMinutes(Math.Round(
             groupping.Average(collectedSugar => collectedSugar.Collected.DateTime.Minute))),
         groupping => groupping.ToList());
 }
Example #21
0
        public HBaseRowData(IList<TRowResult> rowResult)
        {
            Key = rowResult[0].Row;
            Columns = new Dictionary<byte[], IList<IHBaseCellData>>();

            foreach (var column in rowResult.SelectMany(r => r.Columns))
            {
                if (Columns.ContainsKey(column.Key))
                {
                    Columns[column.Key].Add(new HBaseCellData(column.Value));
                }
                else
                {
                    Columns.Add(column.Key, new List<IHBaseCellData> { new HBaseCellData(column.Value)  });
                }
            }
        }
Example #22
0
 public static DoughnutChart GetAverageGameDurationPriceDoughnut(IList<DetailedStatistics> detailedStatistics)
 {
     var allReports = detailedStatistics.SelectMany(s => s.Reports).ToList();
       var averageDuration = allReports.Sum(r => r.ElapsedTime) / allReports.Count();
       var averageGameDirationDoughnut = new DoughnutChart();
       averageGameDirationDoughnut.Data = new List<SimpleData>()
       {
     new SimpleData()
     {
       Value = averageDuration,
       Label = "Среднее время одной игры",
       Color = Colors.Blue
     }
       };
       averageGameDirationDoughnut.ChartConfiguration.Responsive = true;
       return averageGameDirationDoughnut;
 }
Example #23
0
 public static DoughnutChart GetAverageGamePriceDoughnut(IList<DetailedStatistics> detailedStatistics)
 {
     var allReports = detailedStatistics.SelectMany(s => s.Reports).ToList();
       var averagePrice = allReports.Sum(r => r.Cost) / allReports.Count();
       var averageGamePriceDoughnut = new DoughnutChart();
       averageGamePriceDoughnut.Data = new List<SimpleData>()
       {
     new SimpleData()
     {
       Value = averagePrice,
       Label = "Средняя цена за игру",
       Color = Colors.Blue
     }
       };
       averageGamePriceDoughnut.ChartConfiguration.Responsive = true;
       return averageGamePriceDoughnut;
 }
Example #24
0
        void model_Changed(IList<IChange> changes)
        {
            notifyIcon.Icon = GetIcon(changes.Count);
            
            int countOfDistinctFilesTouched = changes.SelectMany(change => change.Files)
                .Select(path => path.Path).Distinct().Count();

            if (!changes.Any(log => log.IsRelevant))
            {
                return;
            }

            IChange latestChange = changes[changes.Count - 1];
            string title = latestChange.User + "'s checked in" + sizeOf(latestChange.Files.Count) + ".";
            string text = latestChange.Message +
                          "\r\nYou have " + SayPlural(changes.Count, " pending change")
                          + ", touching " + SayPlural(countOfDistinctFilesTouched, " file") + ".";
            notifyIcon.ShowBalloonTip(10*1000, title, text, BalloonTipIcon.Info);
        }
Example #25
0
        public static MapperConfiguration ConfigureAutomapper(IList<Type> types)
        {
            var profiles =
                types.SelectMany(t => t.GetInterfaces(), (t, i) => new { t, i })
                    .Where(
                        type =>
                            typeof(Profile).IsAssignableFrom(type.t) && 
                            !type.t.IsAbstract &&
                            !type.t.IsInterface)
                    .Select(type => (Profile)Activator.CreateInstance(type.t));


            var config = new MapperConfiguration(cfg =>
            {
                foreach (var profile in profiles)
                {
                    cfg.AddProfile(profile);
                }
            });

            return config;
        }
Example #26
0
		private static void Export2Mht(
			IServiceProvider provider,
			IList<IMsg> msgs,
			Stream fs,
			ProgressDelegate pd)
		{
			var encoding = Encoding.UTF8;
			using (var sw = new StreamWriter(fs, Encoding.Default))
			{
				sw.Write(
					_mhtHeader,
					DateTime.Now.ToString("ddd, d MMM yyyy h:m:s zz00", CultureInfo.InvariantCulture),
					encoding.HeaderName);
				sw.Flush();

				var htmlText = BuildHTMLPage(provider, msgs, pd, true, Encoding.UTF8);
				var page = encoding.GetBytes(htmlText);
				fs.Write(page, 0, page.Length);

				var usedSmileFiles =
					msgs
						.SelectMany(msg => TextFormatter.GetSmileFiles(msg.Body))
						.Distinct();

				const string prefix = @"ForumImages\";

				foreach (var smileName in usedSmileFiles)
				{
					var smileImage =
						provider
							.GetRequiredService<IStyleImageManager>()
							.GetImage(prefix + smileName, StyleImageType.ConstSize);
					var ifi = ImageFormatInfo.FromImageFormat(smileImage.RawFormat);

					sw.Write(_mhtContentImageHeader, ifi.MimeType, smileName, ifi.Extension);

					using (var ms = new MemoryStream())
					{
						smileImage.Save(ms, smileImage.RawFormat);
						sw.Write(Convert.ToBase64String(ms.ToArray(), Base64FormattingOptions.InsertLineBreaks));
					}
				}

				sw.Write(_mhtFooter);
			}
		}
Example #27
0
 private void ApplyResult(ParametersInfo info, IList<RemapAlarmResult> result)
 {
     _reporter.Report(result.SelectMany(r => r.Notifications));
     _dispatcherService.Invoke(() => ApplyStatus(info, result));
     ApplyCurrentQueries(info, result);
     ApplyHistoryQueries(info, result);
 }
Example #28
0
 private void ApplyHistoryQueries(ParametersInfo info, IList<RemapAlarmResult> result)
 {
     for (var i = 0; i < result.Count; i++)
     {
         var p = info.Parameters[i];
         var r = result[i];
         var alarmCategory = _categories[p.Item1.CategoryId];
         foreach (var a in r.History.SelectMany(alarms => alarms))
         {
             var alarmInfo = alarmCategory.GetAlarmInfo(a.AlarmId);
             a.SetAlarmInfo(alarmInfo.Item1, alarmInfo.Item2, alarmCategory);
         }
         var callbacks = p.Item3;
         for (var j = 0; j < callbacks.Length; j++)
         {
             var callback = callbacks[j];
             var alarms = r.History[info.CommonCurrentInfo.Count + j];
             callback(alarms);
         }
     }
     for (var i = 0; i < info.CommonHistoryInfo.Count; i++)
     {
         var historyInfo = info.CommonHistoryInfo[i];
         var i1 = i;
         var alarms = result.SelectMany(r => r.History[i1]);
         switch (historyInfo.Item2)
         {
             case CriteriaType.DownFromInfinity:
             case CriteriaType.DownFrom:
             case CriteriaType.DownFromOrEqual:
                 alarms = alarms.OrderByDescending(a => a.StartTime).ThenByDescending(a => a.UserId).Take(historyInfo.Item3);
                 break;
             case CriteriaType.UpFromInfinity:
             case CriteriaType.UpFrom:
             case CriteriaType.UpFromOrEqual:
                 alarms = alarms.OrderBy(a => a.StartTime).ThenBy(a => a.UserId).Take(historyInfo.Item3).Reverse();
                 break;
         }
         var callback = historyInfo.Item1;
         var alarmsArray = alarms.ToArray();
         callback(alarmsArray);
     }
 }
 /// <summary>
 /// Decides what information from a ChromatogramGroupInfo should be thrown away.
 /// ChromatogramGroupInfo's can have the the retention time range shortened, and certain
 /// transitions discarded.
 /// </summary>
 private MinimizedChromGroup MinimizeChromGroup(Settings settings, ChromatogramGroupInfo chromatogramGroupInfo, IList<TransitionGroupDocNode> transitionGroups)
 {
     var fileIndexes = new List<int>();
     for (int fileIndex = 0; fileIndex < Document.Settings.MeasuredResults.Chromatograms.Count; fileIndex++)
     {
         var chromatogramSet = Document.Settings.MeasuredResults.Chromatograms[fileIndex];
         if (chromatogramSet.MSDataFilePaths.Any(path=>Equals(path, chromatogramGroupInfo.FilePath)))
         {
             fileIndexes.Add(fileIndex);
         }
     }
     var chromatograms = chromatogramGroupInfo.TransitionPointSets.ToArray();
     Assume.IsTrue(Equals(chromatogramGroupInfo.NumTransitions, chromatograms.Length));
     var keptTransitionIndexes = new List<int>();
     double minRetentionTime = Double.MaxValue;
     double maxRetentionTime = -Double.MaxValue;
     for (int i = 0; i < chromatograms.Length; i++)
     {
         var chromatogram = chromatograms[i];
         var matchingTransitions = new List<TransitionDocNode>();
         foreach (var transitionDocNode in transitionGroups.SelectMany(tg => tg.Transitions))
         {
             if (0!=ChromKey.CompareTolerant((float) chromatogram.ProductMz, (float) transitionDocNode.Mz, _tolerance))
             {
                 continue;
             }
             matchingTransitions.Add(transitionDocNode);
             foreach (var fileIndex in fileIndexes)
             {
                 var chromatogramSet = transitionDocNode.Results[fileIndex];
                 if (chromatogramSet == null)
                 {
                     continue;
                 }
                 foreach (var transitionChromInfo in chromatogramSet)
                 {
                     if (transitionChromInfo.IsEmpty)
                     {
                         continue;
                     }
                     minRetentionTime = Math.Min(minRetentionTime, transitionChromInfo.StartRetentionTime);
                     maxRetentionTime = Math.Max(maxRetentionTime, transitionChromInfo.EndRetentionTime);
                 }
             }
         }
         bool kept = !settings.DiscardUnmatchedChromatograms
             || matchingTransitions.Count > 0;
         if (kept)
         {
             keptTransitionIndexes.Add(i);
         }
     }
     var result = new MinimizedChromGroup(chromatogramGroupInfo.Header)
                      {
                          RetainedTransitionIndexes = keptTransitionIndexes,
                      };
     if (settings.NoiseTimeRange.HasValue && minRetentionTime < maxRetentionTime)
     {
         if (null == chromatogramGroupInfo.Times)
         {
             // Chromatogram was unreadable.
             result.RetainedTransitionIndexes.Clear();
         }
         else
         {
             result.SetStartEndTime(chromatogramGroupInfo.Times, (float)(minRetentionTime - settings.NoiseTimeRange), (float)(maxRetentionTime + settings.NoiseTimeRange));
         }
     }
     return result;
 }
        private void HandleFunctionOrPredicate(CommonTree tree, CommonTree name, IList<CommonTree> parameters, CommonTree returnSpec, ImageSource glyph)
        {
            if (tree == null || name == null)
                return;

            var navigationType = EditorNavigationTypeRegistryService.GetEditorNavigationType(PredefinedEditorNavigationTypes.Members);
            var startToken = _tokens[tree.TokenStartIndex];
            var stopToken = _tokens[tree.TokenStopIndex];
            Span span = new Span(startToken.StartIndex, stopToken.StopIndex - startToken.StartIndex + 1);
            SnapshotSpan ruleSpan = new SnapshotSpan(Snapshot, span);
            SnapshotSpan ruleSeek = new SnapshotSpan(Snapshot, new Span(name.Token.StartIndex, 0));

            string functionDisplayName = (name.Type == DOT) ? GetNameText((CommonTree)name.Children[1]) : GetNameText(name);
            string thisType = (name.Type == DOT) ? GetNameText((CommonTree)name.Children[0]) : null;
            IEnumerable<string> thisParam = !string.IsNullOrEmpty(thisType) ? Enumerable.Repeat(string.Format("this : {0}", thisType), 1) : Enumerable.Empty<string>();
            IList<string> parameterText = thisParam.Concat(parameters != null ? parameters.SelectMany(GetParameterText) : new string[0]).ToArray();
            string returnText = returnSpec != null ? string.Format(" : {0}", GetNameText(returnSpec)) : string.Empty;
            string displayName = string.Format("{0} {1}[{2}]{3}", tree.Text, functionDisplayName, string.Join(", ", parameterText), returnText);
            _targets.Add(new EditorNavigationTarget(displayName, navigationType, ruleSpan, ruleSeek, glyph));
        }