コード例 #1
0
 public Task BulkSend(IEnumerable<Marble> items)
 {
     _marbles.AddRange(items);
     if (items.LastOrDefault()?.Kind == NotificationKind.OnCompleted)
         _completion.SetResult(null);
     else if (items.LastOrDefault()?.Kind == NotificationKind.OnError)
         _completion.SetException(new Exception(items.Last().Value.ToString()));
     return Task.CompletedTask;
 }
コード例 #2
0
ファイル: TranslateExtension.cs プロジェクト: iiasa/Agrotutor
        protected TypeInfo GetRootObjectType(IServiceProvider serviceProvider)
        {
            // Little workaround to get page object https://forums.xamarin.com/discussion/33678/x-reference-not-working
            IRootObjectProvider       rootObjectProvider  = serviceProvider.GetService(typeof(IRootObjectProvider)) as IRootObjectProvider;
            SimpleValueTargetProvider valueTargetProvider =
                serviceProvider.GetService(typeof(IProvideValueTarget)) as SimpleValueTargetProvider;

            // If XamlCompilation is active, IRootObjectProvider is not available, but SimpleValueTargetProvider is available
            // If XamlCompilation is inactive, IRootObjectProvider is available, but SimpleValueTargetProvider is not available
            if (rootObjectProvider == null && valueTargetProvider == null)
            {
                throw new ArgumentException(
                          $"{nameof(serviceProvider)} does not provide an {nameof(IRootObjectProvider)} or {nameof(SimpleValueTargetProvider)}");
            }


            if (rootObjectProvider != null)
            {
                if (rootObjectProvider.RootObject is ResourceDictionary dictionary)
                {
                    return(dictionary?.GetType().GetTypeInfo());
                }

                return((rootObjectProvider.RootObject as Element)?.GetType().GetTypeInfo());
            }

            PropertyInfo propertyInfo = valueTargetProvider.GetType()
                                        .GetTypeInfo()
                                        .DeclaredProperties.FirstOrDefault(dp => dp.Name.Contains("ParentObjects"));

            if (propertyInfo == null)
            {
                throw new ArgumentNullException("ParentObjects");
            }

            IEnumerable <object> parentObjects = propertyInfo.GetValue(valueTargetProvider) as IEnumerable <object>;
            object parentObject = parentObjects?.LastOrDefault(x => x.GetType().GetTypeInfo().IsSubclassOf(typeof(ResourceDictionary)));

            if (parentObject == null)
            {
                parentObject = parentObjects?.LastOrDefault(x => x.GetType().GetTypeInfo().IsSubclassOf(typeof(Element)));
            }

            if (parentObject == null)
            {
                throw new ArgumentNullException("parentObject");
            }

            return(parentObject.GetType().GetTypeInfo());
        }
コード例 #3
0
        // For testing
        internal KestrelServerImpl(
            IEnumerable <IConnectionListenerFactory> transportFactories,
            IEnumerable <IMultiplexedConnectionListenerFactory>?multiplexedFactories,
            ServiceContext serviceContext)
        {
            if (transportFactories == null)
            {
                throw new ArgumentNullException(nameof(transportFactories));
            }

            _transportFactory            = transportFactories.LastOrDefault();
            _multiplexedTransportFactory = multiplexedFactories?.LastOrDefault();

            if (_transportFactory == null && _multiplexedTransportFactory == null)
            {
                throw new InvalidOperationException(CoreStrings.TransportNotFound);
            }

            ServiceContext = serviceContext;

            Features         = new FeatureCollection();
            _serverAddresses = new ServerAddressesFeature();
            Features.Set <IServerAddressesFeature>(_serverAddresses);

            _transportManager = new TransportManager(_transportFactory, _multiplexedTransportFactory, ServiceContext);

            HttpCharacters.Initialize();
        }
コード例 #4
0
        public async Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> events)
        {
            // Workaround for event hub sending null on timeout
            events = events ?? Enumerable.Empty<EventData>();

            if(!await _elasticSearchWriter.WriteAsync(events.ToList(), _token).ConfigureAwait(false))
            {
                return;
            }

            try
            {
                EventData checkpointEventData = events.LastOrDefault();

                await context.CheckpointAsync(checkpointEventData);

                WarmStorageEventSource.Log.CheckpointCompleted(ProcessorName, _eventHubName, context.Lease.PartitionId, checkpointEventData.Offset);
            }
            catch (Exception ex)
            {
                if (!(ex is StorageException || ex is LeaseLostException))
                {
                    throw;
                }

                WarmStorageEventSource.Log.UnableToCheckpoint(ex, ProcessorName, _eventHubName, context.Lease.PartitionId);
            }
        }
コード例 #5
0
		public bool Process(ILogger logger, IEnumerable<string> args, MetaProjectPersistence metaProject, ComponentsList components, string packagesOutputDirectory)
		{
			var nugetNamePattern = args.FirstOrDefault();
			if (nugetNamePattern == null || nugetNamePattern.StartsWith("-") || nugetNamePattern.EndsWith("\"")) {
				logger.Error("No nuget pattern specified");
				return true;
			}
			var nugetComponent = components.FindComponent<INugetSpec>(nugetNamePattern);
			if (nugetComponent == null)
				return true;
			logger.Info("== Nuget to add: {0}", nugetComponent);
			var componentNamePattern = args.LastOrDefault();
			if (componentNamePattern == null || componentNamePattern.StartsWith("-") || componentNamePattern.EndsWith("\"")) {
				logger.Error("No component pattern specified");
				return true;
			}
			var specificComponent = components.FindComponent<IProject>(componentNamePattern);
			if (specificComponent == null)
				return true;
			logger.Info("== Component to reference nuget: {0}", specificComponent);
			if (specificComponent == nugetComponent) {
				logger.Error("Nuget can't be added to itself");
				return true;
			}
			specificComponent.AddNuget(logger, nugetComponent, components, packagesOutputDirectory);
			return true;
		}
コード例 #6
0
        public async Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> events)
        {
            // Workaround for event hub sending null on timeout
            events = events ?? Enumerable.Empty<EventData>();

            foreach (var eventData in events)
            {
                var updateTemperatureEvent = JsonConvert.DeserializeObject<UpdateTemperatureEvent>(Encoding.UTF8.GetString(eventData.GetBytes()));
                eventData.Properties["BuildingId"] = _buildingLookupService.GetBuildingId(updateTemperatureEvent.DeviceId);
            }

            if(!await _elasticSearchWriter.WriteAsync(events.ToList(), _token).ConfigureAwait(false))
            {
                return;
            }

            try
            {
                EventData checkpointEventData = events.LastOrDefault();

                await context.CheckpointAsync(checkpointEventData);

                WarmStorageEventSource.Log.CheckpointCompleted(ProcessorName, _eventHubName, context.Lease.PartitionId, checkpointEventData.Offset);
            }
            catch (Exception ex)
            {
                if (!(ex is StorageException || ex is LeaseLostException))
                {
                    throw;
                }

                WarmStorageEventSource.Log.UnableToCheckpoint(ex, ProcessorName, _eventHubName, context.Lease.PartitionId);
            }
        }
コード例 #7
0
		public bool Process(ILogger logger, IEnumerable<string> args, MetaProjectPersistence metaProject, ComponentsList components, string packagesOutputDirectory)
		{
			// BIG TODO: reengineer command parsing
			var componentNamePattern = args.LastOrDefault();
			if (componentNamePattern == null || componentNamePattern.StartsWith("-") || componentNamePattern.EndsWith("\"")) {
				logger.Error("No component pattern specified");
				return true;
			}
			string tags = args.ParseStringParameter("tags");
			string licenseUrl = args.ParseStringParameter("licenseUrl");
			string projectUrl = args.ParseStringParameter("projectUrl");
			string iconUrl = args.ParseStringParameter("iconUrl");
			string copyright = args.ParseStringParameter("copyright");
			bool requireLicenseAcceptance = args.Contains("-r");
			if (licenseUrl == null && requireLicenseAcceptance) {
				logger.Error("Requiring license acceptance demands a license url");
				return true;
			}
			var specificComponent = components.FindComponent<IProject>(componentNamePattern, c => c.CanBecomeNugget);
			if (specificComponent == null)
				return true;
			if (specificComponent.PromoteToNuget(logger, packagesOutputDirectory, tags,
				licenseUrl, projectUrl, iconUrl, copyright, requireLicenseAcceptance) != null)
				ScanCommand.Rescan(logger, metaProject, components);
			return true;
		}
コード例 #8
0
        public override Character GetTarget(IEnumerable<Character> targetsList)
        {
            return targetsList.LastOrDefault(character => (character.Team != this.Team && character.IsAlive));

            //var target = targetsList.LastOrDefault(character => (character.Team != this.Team && character.IsAlive));
            //return target;
        }
コード例 #9
0
ファイル: Last.cs プロジェクト: emrahoner/CsQuery
        /// <summary>
        /// Filter for the last element in the selection set
        /// </summary>
        ///
        /// <param name="selection">
        /// The sequence of elements prior to this filter being applied.
        /// </param>
        ///
        /// <returns>
        /// The last element in the selection.
        /// </returns>

        public IEnumerable<IDomObject> Filter(IEnumerable<IDomObject> selection)
        {
            var last = selection.LastOrDefault();
            if (last != null)
            {
                yield return last;
            } 
        }
コード例 #10
0
        public override int DetermineNodeId(IEnumerable <int> trail)
        {
            int nodeId = trail.LastOrDefault();

            nodeId = Helper.Reverse(nodeId);

            return nodeId;
        }
コード例 #11
0
ファイル: AbsolutePathRewriter.cs プロジェクト: piksel/nuke
 private string GetGlobbingMethod(SyntaxNode node, IEnumerable <string> wildcardparts = null)
 {
     return((wildcardparts?.LastOrDefault()?.Contains(".") ?? false) ||
            node.Parent?.Parent?.Parent is InvocationExpressionSyntax invocationExpression &&
            (invocationExpression.GetIdentifierName() == "GetFiles" ||
             invocationExpression.GetIdentifierName() == "CopyFiles")
         ? "GlobFiles"
         : "GlobDirectories");
 }
コード例 #12
0
ファイル: Program.cs プロジェクト: vadimostanin/GA
 private static IEnumerable<string> GetNodes(string id, IEnumerable<string[]> lines)
 {
     var line = lines.LastOrDefault(l => l[0] == id);
     if (line == null)
     {
         return new[] { "_" };
     }
     var newId = line[3];
     return (new[] { id }).Union(GetNodes(newId, lines));
 }
コード例 #13
0
        public string MatchesConstraints(IEnumerable<string> packageVersions, string versionConstraint,
            string branch = null) {
            var doVersion = !string.IsNullOrWhiteSpace(versionConstraint);
            var doBranch = !string.IsNullOrWhiteSpace(branch);
            packageVersions = packageVersions.OrderBy(x => new SpecificVersion("x", x).Version);

            if (doBranch) {
                return doVersion
                    ? packageVersions.LastOrDefault(
                        x =>
                            x.EndsWith("-" + branch) &&
                            MatchesVersionConstraint(x.Split('-').First(), versionConstraint))
                    : packageVersions.LastOrDefault(x => x.EndsWith("-" + branch));
            }

            return doVersion
                ? packageVersions.LastOrDefault(x => MatchesVersionConstraint(x.Split('-').First(), versionConstraint))
                : null;
        }
コード例 #14
0
        protected async Task ProcessEventsAsync(IEnumerable <EventData> events)
        {
            if (events == null)
            {
                if (this.Host.EventProcessorOptions.InvokeProcessorAfterReceiveTimeout)
                {
                    // Assumes that .NET Core client will call with empty EventData on receive timeout.
                    events = Enumerable.Empty <EventData>();
                }
                else
                {
                    return;
                }
            }

            // Synchronize to serialize calls to the processor.
            // The handler is not installed until after OpenAsync returns, so ProcessEventsAsync cannot conflict with OpenAsync.
            // There could be a conflict between ProcessEventsAsync and CloseAsync, however. All calls to CloseAsync are
            // protected by synchronizing too.
            using (await this.ProcessingAsyncLock.LockAsync().ConfigureAwait(false))
            {
                ProcessorEventSource.Log.PartitionPumpInvokeProcessorEventsStart(this.Host.Id,
                                                                                 this.PartitionContext.PartitionId, events?.Count() ?? 0);
                try
                {
                    EventData last = events?.LastOrDefault();
                    if (last != null)
                    {
                        ProcessorEventSource.Log.PartitionPumpInfo(
                            this.Host.Id,
                            this.PartitionContext.PartitionId,
                            "Updating offset in partition context with end of batch " + last.SystemProperties.Offset + "/" + last.SystemProperties.SequenceNumber);
                        this.PartitionContext.SetOffsetAndSequenceNumber(last);
                        if (this.Host.EventProcessorOptions.EnableReceiverRuntimeMetric)
                        {
                            this.PartitionContext.RuntimeInformation.LastSequenceNumber  = last.LastSequenceNumber;
                            this.PartitionContext.RuntimeInformation.LastEnqueuedOffset  = last.LastEnqueuedOffset;
                            this.PartitionContext.RuntimeInformation.LastEnqueuedTimeUtc = last.LastEnqueuedTime;
                            this.PartitionContext.RuntimeInformation.RetrievalTime       = last.RetrievalTime;
                        }
                    }

                    await this.Processor.ProcessEventsAsync(this.PartitionContext, events).ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    ProcessorEventSource.Log.PartitionPumpInvokeProcessorEventsError(this.Host.Id, this.PartitionContext.PartitionId, e.ToString());
                    await this.ProcessErrorAsync(e).ConfigureAwait(false);
                }
                finally
                {
                    ProcessorEventSource.Log.PartitionPumpInvokeProcessorEventsStop(this.Host.Id, this.PartitionContext.PartitionId);
                }
            }
        }
コード例 #15
0
        public static IEnumerable<SortingInfo> AddRequiredSort(IEnumerable<SortingInfo> sort, IEnumerable<string> requiredSelectors) {
            sort = sort ?? new SortingInfo[0];
            requiredSelectors = requiredSelectors.Except(sort.Select(i => i.Selector));

            var desc = sort.LastOrDefault()?.Desc;

            return sort.Concat(requiredSelectors.Select(i => new SortingInfo {
                Selector = i,
                Desc = desc != null && desc.Value
            }));
        }
コード例 #16
0
ファイル: FileRepository.cs プロジェクト: slyn/SprinklingApp
        private long GetNextIdValue <TEntity>() where TEntity : BaseEntity, new()
        {
            IEnumerable <TEntity> list = GetList <TEntity>(x => true);
            TEntity last = list?.LastOrDefault();

            if (last != null)
            {
                return(last.Id + 1);
            }

            return(1);
        }
コード例 #17
0
        private void AdvancedListView_ItemAppearing(object sender, ItemVisibilityEventArgs e)
        {
            Entity en = e.Item as Entity;
            IEnumerable <Entity> list = ItemsSource.Cast <Entity>();
            int dataCount             = list.Count();

            //throw new NotImplementedException();
            if (list?.LastOrDefault()?.Id == en?.Id)
            {
                GetData?.Execute(dataCount);
            }
        }
コード例 #18
0
        protected async Task ProcessEventsAsync(IEnumerable <EventData> events)
        {
            // Assumes that .NET Core client will call with null on receive timeout.
            if (events == null && !this.Host.EventProcessorOptions.InvokeProcessorAfterReceiveTimeout)
            {
                return;
            }

            // Synchronize to serialize calls to the processor.
            // The handler is not installed until after OpenAsync returns, so ProcessEventsAsync cannot conflict with OpenAsync.
            // There could be a conflict between ProcessEventsAsync and CloseAsync, however. All calls to CloseAsync are
            // protected by synchronizing too.
            using (await this.ProcessingAsyncLock.LockAsync())
            {
                int eventCount = events != null?events.Count() : 0;

                ProcessorEventSource.Log.PartitionPumpInvokeProcessorEventsStart(this.Host.Id, this.PartitionContext.PartitionId, eventCount);
                try
                {
                    if (eventCount > 0)
                    {
                        var lastMessage = events.Last();
                        this.PartitionContext.SequenceNumber = lastMessage.SystemProperties.SequenceNumber;
                        this.PartitionContext.Offset         = lastMessage.SystemProperties.Offset;
                    }

                    await this.Processor.ProcessEventsAsync(this.PartitionContext, events);
                }
                catch (Exception e)
                {
                    // TODO -- do we pass errors from IEventProcessor.ProcessEventsAsync to IEventProcessor.ProcessErrorAsync?
                    // Depending on how you look at it, that's either pointless (if the user's code throws, the user's code should already know about it) or
                    // a convenient way of centralizing error handling.
                    // For the meantime just trace it.
                    ProcessorEventSource.Log.PartitionPumpInvokeProcessorEventsError(this.Host.Id, this.PartitionContext.PartitionId, e.ToString());
                }
                finally
                {
                    ProcessorEventSource.Log.PartitionPumpInvokeProcessorEventsStop(this.Host.Id, this.PartitionContext.PartitionId);
                }

                EventData last = events?.LastOrDefault();
                if (last != null)
                {
                    ProcessorEventSource.Log.PartitionPumpInfo(
                        this.Host.Id,
                        this.PartitionContext.PartitionId,
                        "Updating offset in partition context with end of batch " + last.SystemProperties.Offset + "/" + last.SystemProperties.SequenceNumber);
                    this.PartitionContext.SetOffsetAndSequenceNumber(last);
                }
            }
        }
コード例 #19
0
ファイル: AggregateRoot.cs プロジェクト: icedage/CashLady
        public void LoadsFromHistory(IEnumerable<Event> history)
        {
            foreach (var e in history)
            {
                ApplyChange(e, false);
            }

            var lastEvent = history.LastOrDefault();
            if (lastEvent != null)
            {
                Version = lastEvent.Version;
            }
        }
コード例 #20
0
ファイル: TypeCompletion.cs プロジェクト: mhusen/Eto
		public override IEnumerable<CompletionItem> GetClasses(IEnumerable<string> path, Func<Type, bool> filter)
		{
			var prefixWithColon = PrefixWithColon;

			string contentProperty;
			var nodeType = GetNodeType(path.LastOrDefault(), out contentProperty);
			var contentType = GetContentType(nodeType, contentProperty);

			var types = GetExportedTypes();
			if (filter != null)
			{
				foreach (var result in types.Where(filter))
				{
					// special case, don't allow windows as a child control
					if (contentType != null
					    && typeof(Window).IsAssignableFrom(result))
						continue;
						

					yield return new CompletionItem
					{ 
						Name = prefixWithColon + result.Name, 
						Description = XmlComments.GetSummary(result),
						Type = CompletionType.Class
					}; 
				}
			}

			if (contentType != null 
				&& !contentType.IsAbstract 
				&& !types.Contains(contentType)
				&& contentType.Assembly == Assembly)
				yield return new CompletionItem
				{ 
					Name = prefixWithColon + contentType.Name, 
					Description = XmlComments.GetSummary(contentType),
					Type = CompletionType.Class
				}; 
			if (nodeType != null)
			{
				yield return new CompletionItem
				{
					Name = prefixWithColon + nodeType.Name + ".",
					Description = "Add a property tag",
					Type = CompletionType.Property
				};
			}

		}
コード例 #21
0
 /// <summary>
 /// Constructeur.
 /// </summary>
 /// <param name="year">Année de l'édition du tournoi.</param>
 /// <param name="matchs">Liste des matches du tournoi pour cette édition.</param>
 public TournamentPalmares(uint year, IEnumerable <Services.Match> matchs)
 {
     Year     = year;
     Winner   = matchs?.FirstOrDefault(_ => _.Round == Services.Round.F)?.Winner?.Name ?? "N/A";
     Finalist = matchs?.FirstOrDefault(_ => _.Round == Services.Round.F)?.Loser?.Name ?? "N/A";
     if (matchs?.Any(_ => _.Round == Services.Round.BR) == true)
     {
         SemiFinalist1 = matchs?.FirstOrDefault(_ => _.Round == Services.Round.BR)?.Winner?.Name ?? "N/A";
         SemiFinalist2 = matchs?.FirstOrDefault(_ => _.Round == Services.Round.BR)?.Loser?.Name ?? "N/A";
     }
     else
     {
         SemiFinalist1 = matchs?.FirstOrDefault(_ => _.Round == Services.Round.SF)?.Loser?.Name ?? "N/A";
         SemiFinalist2 = matchs?.LastOrDefault(_ => _.Round == Services.Round.SF)?.Loser?.Name ?? "N/A";
     }
 }
コード例 #22
0
        public static async Task CursorQuery(this IDataService service, string collection, string query, Func <IItem, Task> action, int batchSize = 100)
        {
            IEnumerable <IItem> data = null;
            string skipToken         = null;

            do
            {
                skipToken = data?.LastOrDefault()?.Id;
                data      = await service.QueryAsync(collection, query, skipToken, batchSize);

                foreach (var datum in data)
                {
                    await action(datum);
                }
            } while(data.Count() == batchSize);
        }
		public string GetUrlUsingCategoryPathOrCanonical(IProduct product, IEnumerable<ICategory> categoryPath)
		{
			var category = categoryPath.LastOrDefault();
			if (category != null && product.Categories.Any(c => c.Id == category.Id))
			{
				return _categoryCatalogUrlService.GetUrlForPath(categoryPath) + "/" + product.UrlName;
			}
			
			category = product.Categories.FirstOrDefault();

			// todo: products can get their own url using storeUrl/productUrlName, but resolving and name conflicts need to be fixed
			if (category == null)
			{
				return product.UrlName;
			}

			return _categoryCatalogUrlService.GetCanonicalUrl(category) + "/" + product.UrlName;
		}
コード例 #24
0
        /// <summary>
        /// Execute index job
        /// </summary>
        /// <returns></returns>
        public override string Execute()
        {
            OnStatusChanged($"Starting execution of {GetType()}");
            if (_vulcanIndexContentJobSettings.EnableAlwaysUp)
            {
                _vulcanHandler.DeleteIndex(VulcanHelper.TempAlias); // make sure any temp index is cleared
            }
            else
            {
                _vulcanHandler.DeleteIndex(); // delete all language indexes
            }

            var totalIndexedCount   = 0;
            var isCacheScopeFeature = _vulcanFeatures?.LastOrDefault(x => x is IVulcanFeatureCacheScope) as IVulcanFeatureCacheScope;

            if (_vulcanIndexContentJobSettings.EnableParallelIndexers)
            {
                Parallel.ForEach(_vulcanIndexers.AsParallel(), new ParallelOptions()
                {
                    MaxDegreeOfParallelism = _vulcanIndexContentJobSettings.ParallelDegree
                }, indexer =>
                {
                    ExecuteIndexer(indexer, isCacheScopeFeature, ref totalIndexedCount);
                });
            }
            else
            {
                foreach (var indexer in _vulcanIndexers)
                {
                    ExecuteIndexer(indexer, isCacheScopeFeature, ref totalIndexedCount);
                }
            }

            // ReSharper disable once InvertIf
            if (_vulcanIndexContentJobSettings.EnableAlwaysUp)
            {
                Logger.Warning("Always up enabled... swapping indices...");
                _vulcanHandler.SwitchAliasAllCultures(VulcanHelper.TempAlias, VulcanHelper.MasterAlias);
                _vulcanHandler.DeleteIndex(VulcanHelper.TempAlias);
                Logger.Warning("Index swap completed.");
            }

            return($"Vulcan successfully indexed {totalIndexedCount} item(s) across {_vulcanIndexers.Count()} indexers!");
        }
コード例 #25
0
ファイル: TypeCompletion.cs プロジェクト: mhusen/Eto
		public override Func<Type, bool> GetFilter(IEnumerable<string> path)
		{
			string propertyName;
			var nodeType = GetNodeType(path.LastOrDefault(), out propertyName);
			var contentType = GetContentType(nodeType, propertyName);
			if (contentType != null)
			{
				var converter = TypeDescriptor.GetConverter(contentType);
				if (converter != null)
				{
					return t => contentType.IsAssignableFrom(t) || converter.CanConvertFrom(t);
				}
				else
				{
					return contentType.IsAssignableFrom;
				}
			}
			return null;
		}
コード例 #26
0
        public static async Task <DateTimeOffset> CursorEvents(this IDataService service, string collection, DateTimeOffset from, Func <Event, Task> action, int batchSize = 1000)
        {
            IEnumerable <Event> events = null;
            string         skipToken   = null;
            DateTimeOffset?end         = null;
            DateTimeOffset start       = DateTimeOffset.UtcNow;

            do
            {
                skipToken = events?.LastOrDefault()?.Id;
                events    = await service.GetEventsAsync(collection, from, skipToken, batchSize);

                foreach (var ev in events)
                {
                    await action(ev);
                }

                end = events.LastOrDefault()?.TrackAt;
            } while(events.Count() == batchSize);
            return(new DateTimeOffset(Math.Max(start.Ticks, end?.ToUniversalTime().Ticks ?? 0), TimeSpan.Zero));
        }
コード例 #27
0
        Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable <EventData> events)
        {
            var eventsArgs = new ReceivedEventArgs();

            eventsArgs.events = events;
            this.OnProcessEvents?.Invoke(this, new Tuple <PartitionContext, ReceivedEventArgs>(context, eventsArgs));
            EventData lastEvent = events?.LastOrDefault();

            // Checkpoint with last event?
            if (eventsArgs.checkPointLastEvent && lastEvent != null)
            {
                return(context.CheckpointAsync(lastEvent));
            }

            // Checkpoint batch? This should checkpoint with last message delivered.
            if (eventsArgs.checkPointBatch)
            {
                return(context.CheckpointAsync());
            }

            return(Task.CompletedTask);
        }
コード例 #28
0
        /// <summary>
        /// Selects the dependency package from the list of candidate packages
        /// according to <paramref name="dependencyVersion"/>.
        /// </summary>
        /// <param name="packages">The list of candidate packages.</param>
        /// <param name="dependencyVersion">The rule used to select the package from
        /// <paramref name="packages"/> </param>
        /// <returns>The selected package.</returns>
        /// <remarks>Precondition: <paramref name="packages"/> are ordered by ascending version.</remarks>
        internal static IPackage SelectDependency(this IEnumerable <IPackage> packages, DependencyVersion dependencyVersion)
        {
            if (packages == null || !packages.Any())
            {
                return(null);
            }

            if (dependencyVersion == DependencyVersion.Lowest)
            {
                return(packages.FirstOrDefault());
            }
            else if (dependencyVersion == DependencyVersion.Highest)
            {
                return(packages.LastOrDefault());
            }
            else if (dependencyVersion == DependencyVersion.HighestPatch)
            {
                var groups = from p in packages
                             group p by new { p.Version.Version.Major, p.Version.Version.Minor } into g
                orderby g.Key.Major, g.Key.Minor
                select g;
                return((from p in groups.First()
                        orderby p.Version descending
                        select p).FirstOrDefault());
            }
            else if (dependencyVersion == DependencyVersion.HighestMinor)
            {
                var groups = from p in packages
                             group p by new { p.Version.Version.Major } into g
                orderby g.Key.Major
                select g;
                return((from p in groups.First()
                        orderby p.Version descending
                        select p).FirstOrDefault());
            }

            throw new ArgumentOutOfRangeException("dependencyVersion");
        }
コード例 #29
0
        public async Task UpdateTrackOnMap(IEnumerable <Tuple <double?, double?> > trackPlaces)
        {
            if (trackPlaces.Any())
            {
                this.Pins.Add(getStartFinishPin(new Position(trackPlaces.FirstOrDefault().Item1 ?? 0, trackPlaces.FirstOrDefault().Item2 ?? 0), true));
                Polyline trace = new Polyline()
                {
                    StrokeColor = Color.DodgerBlue,
                    StrokeWidth = 10,
                };
                foreach (var place in trackPlaces)
                {
                    trace.Geopath.Add(new Position(place.Item1 ?? 0, place.Item2 ?? 0));
                }
                this.Pins.Add(getStartFinishPin(new Position(trackPlaces.LastOrDefault().Item1 ?? 0, trackPlaces.LastOrDefault().Item2 ?? 0), false));
                this.MapElements.Add(trace);

                /*this.MapElements.Add(new Circle()
                 * {
                 *  Center = new Position(trackPlaces.FirstOrDefault().Item1??0, trackPlaces.FirstOrDefault().Item2??0),
                 *  Radius = new Distance(250),
                 *  StrokeColor = Color.FromHex("#88FF0000"),
                 *  StrokeWidth = 8,
                 *  FillColor = Color.Red
                 * });
                 * this.MapElements.Add(trace);
                 * this.MapElements.Add(new Circle()
                 * {
                 *  Center = new Position(trackPlaces.LastOrDefault().Item1??0, trackPlaces.LastOrDefault().Item2??0),
                 *  Radius = new Distance(250),
                 *  StrokeColor = Color.FromHex("#88FF0000"),
                 *  StrokeWidth = 8,
                 *  FillColor = Color.Black
                 * });*/
                //this.Pins.Add(Pin);
                //await this.CenterMap(trackPlaces.FirstOrDefault().Item1??0, trackPlaces.FirstOrDefault().Item2??0);
            }
        }
コード例 #30
0
        private Rectangle GetCurrentRectangle()
        {
            Frame currentFrame = null;

            // See if we can find the frame
            TimeSpan accumulatedTime = new TimeSpan();

            foreach (var frame in _frames)
            {
                if (accumulatedTime + frame.Duration >= _timeIntoAnimation)
                {
                    currentFrame = frame;
                    break;
                }
                else
                {
                    accumulatedTime += frame.Duration;
                }
            }

            // If no frame was found, then try the last frame,
            // just in case timeIntoAnimation somehow exceeds Duration
            if (currentFrame == null)
            {
                currentFrame = _frames.LastOrDefault();
            }

            // If we found a frame, return its rectangle, otherwise
            // return an empty rectangle (one with no width or height)
            if (currentFrame != null)
            {
                return(currentFrame.SourceRectangle);
            }
            else
            {
                return(Rectangle.Empty);
            }
        }
        private async Task <long?> UpdateApprenticeshipsWithEpaOrgId(IEnumerable <SubmissionEvent> submissionEvents)
        {
            foreach (var submissionEvent in submissionEvents)
            {
                if (!submissionEvent.ApprenticeshipId.HasValue)
                {
                    _logger.Warn($"Ignoring SubmissionEvent '{submissionEvent.Id}' with no ApprenticheshipId");
                }
                else
                {
                    try
                    {
                        await _apprenticeshipRepository.UpdateApprenticeshipEpa(submissionEvent.ApprenticeshipId.Value, submissionEvent.EPAOrgId);
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e, $"Ignoring failed attempt to set EPAOrgId to '{submissionEvent.EPAOrgId}' for apprenticeship with id '{submissionEvent.ApprenticeshipId.Value}'\r\n");
                    }
                }
            }

            return(submissionEvents.LastOrDefault()?.Id);
        }
コード例 #32
0
ファイル: GameDal.cs プロジェクト: DelLitt/FCWebSite
        // TODO: Add option to select games where goals is not null

        public Game GetTeamNearestGame(int teamId, IEnumerable <int> roundIds, DateTime date)
        {
            if (Guard.IsEmptyIEnumerable(roundIds))
            {
                return(null);
            }

            IEnumerable <Game> teamGames = Context.Game.Where(g => roundIds.Contains(g.roundId) &&
                                                              (g.homeId == teamId || g.awayId == teamId) &&
                                                              date >= g.GameDate)
                                           .OrderBy(g => g.GameDate)
                                           .Take(LimitEntitiesSelections)
                                           .ToList();

            Game game = teamGames.LastOrDefault();

            if (game != null)
            {
                FillRelations(new[] { game });
            }

            return(game);
        }
コード例 #33
0
ファイル: EasyExtension.cs プロジェクト: stonezhu870/never
        /// <summary>
        /// 最优匹配
        /// </summary>
        /// <param name="topRule"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        internal static RegisterRule LastCompatible(this RegisterRule topRule, IEnumerable <RegisterRule> collection)
        {
            if (collection == null)
            {
                return(null);
            }

            for (var i = collection.Count() - 1; i >= 0; i--)
            {
                var rule = collection.ElementAt(i);
                if (rule.Builded || rule.OptionalBuilded)
                {
                    return(rule);
                }

                if ((rule.ImplementationType.IsInterface || rule.ImplementationType.IsAbstract))
                {
                    continue;
                }
            }

            return(collection.LastOrDefault());
        }
コード例 #34
0
        protected override bool MoveToNextResultPage(IWebDriver driver)
        {
            RemoveEuNotif(driver);

            IWebElement navBar = driver.FindElements(By.TagName("nav")).FirstOrDefault(nav => nav.GetAttribute("class")?.Contains("paging") ?? false);

            if (navBar == null)
            {
                return(false);
            }

            IEnumerable <IWebElement> items = navBar.FindElements(By.ClassName("paging-item "))
                                              .OrderBy(item => (int.TryParse(item.Text, out int p) ? 1 : -1) * p)
                                              .ToList();

            if (items.LastOrDefault()?.GetAttribute("class")?.Contains("current") ?? false)
            {
                return(false);
            }

            navBar.FindElements(By.ClassName("paging-navButton")).Last().Click();
            return(true);
        }
コード例 #35
0
        public IEnumerable <Property> BuildEntity(IEnumerable <PropertyDataDto> dtos)
        {
            var properties = new List <Property>();

            foreach (var propertyType in _contentType.CompositionPropertyTypes)
            {
                var propertyDataDto = dtos.LastOrDefault(x => x.PropertyTypeId == propertyType.Id);
                var property        = propertyDataDto == null
                                   ? propertyType.CreatePropertyFromValue(null)
                                   : propertyType.CreatePropertyFromRawValue(propertyDataDto.GetValue,
                                                                             propertyDataDto.VersionId.Value,
                                                                             propertyDataDto.Id);

                //on initial construction we don't want to have dirty properties tracked
                property.CreateDate = _createDate;
                property.UpdateDate = _updateDate;
                // http://issues.umbraco.org/issue/U4-1946
                property.ResetDirtyProperties(false);
                properties.Add(property);
            }

            return(properties);
        }
コード例 #36
0
ファイル: Thumbnail.cs プロジェクト: dxc31202/ZXStudio
    public static void DeleteBitmap(string fileName)
    {
        try
        {
            OpenFile(ThumDBFile, "Images");
            XElement root = xdoc.Root;

            IEnumerable <XElement> file = from g in root.Elements("Image")
                                          where g.Attributes("Filename").Any(att => att.Value == fileName)
                                          select g;

            XElement foundElement = file.LastOrDefault();
            if (foundElement != null)
            {
                foundElement.Remove();
            }
        }
        catch { }
        finally
        {
            CloseFile(ThumDBFile);
        }
    }
コード例 #37
0
        public override void WriteCell(Point2D cellPos, int cellIndex, IEnumerable <ISpatial2DThing <T> > contents)
        {
            WriteStartCell();

            ISpatial2DThing <T> last = contents.LastOrDefault();

            if (last != null && !last.Colour.IsTransparent)
            {
                XmlWriter.WriteAttributeString("style", "color: " + last.Colour.ToHex());
            }

            if (contents.Count() == 1 && !string.IsNullOrEmpty(last.Id))
            {
                XmlWriter.WriteAttributeString("id", last.Id);
            }

            foreach (var item in contents)
            {
                WriteItem(item);
            }

            XmlWriter.WriteEndElement();
        }
コード例 #38
0
        private void LoadDefaultInterpreter(bool suppressChangeEvent = false)
        {
            string id = null, version = null;
            var    store = _settings.GetReadOnlySettingsStore(SettingsScope.UserSettings);

            if (store.CollectionExists(DefaultInterpreterOptionsCollection))
            {
                id      = store.GetString(DefaultInterpreterOptionsCollection, DefaultInterpreterSetting, string.Empty);
                version = store.GetString(DefaultInterpreterOptionsCollection, DefaultInterpreterVersionSetting, string.Empty);
            }

            var newDefault = FindInterpreter(id, version) ??
                             Interpreters.LastOrDefault(fact => fact.CanBeAutoDefault());

            if (suppressChangeEvent)
            {
                _defaultInterpreter = newDefault;
            }
            else
            {
                DefaultInterpreter = newDefault;
            }
        }
コード例 #39
0
        public JsonResult Resume_CurrentChildStage(string studentID, string parentNameEn)
        {
            IEnumerable <StudentApplyStageEntity> childStages = GetChildStageList(studentID, parentNameEn);
            StudentApplyStageEntity currentChild;

            if (childStages == null)
            {
                return(Json(new { GetResult = false, Msg = "学生ID 为空,或不存在指定的阶段" }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                if (childStages.Count(s => s.Percentage > 0 && s.Percentage < 100) > 0)
                {
                    currentChild = childStages.LastOrDefault(s => s.Percentage > 0 && s.Percentage < 100);
                }
                else
                {
                    currentChild = childStages.First(s => s.Percentage > 0);
                }

                return(Json(new { CurrentChildNameEn = currentChild.StageNameEn, CurrentChildNo = currentChild.StageNo }, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #40
0
        public virtual IEnumerable <Commit> GetFromTo(DateTime start, DateTime end)
        {
            ThrowWhenDisposed();
            Logger.Debug(Resources.GettingAllCommitsFromToTime, start, end);

            IEnumerable <Guid> selectedCommitIds = _stamps.Where(x => x.Value >= start && x.Value < end).Select(x => x.Key);
            Guid firstCommitId = selectedCommitIds.FirstOrDefault();
            Guid lastCommitId  = selectedCommitIds.LastOrDefault();

            if (lastCommitId == Guid.Empty && lastCommitId == Guid.Empty)
            {
                return(new Commit[] {});
            }

            Commit startingCommit = _commits.FirstOrDefault(x => x.CommitId == firstCommitId);
            Commit endingCommit   = _commits.FirstOrDefault(x => x.CommitId == lastCommitId);

            int startingCommitIndex = (startingCommit == null) ? 0 : _commits.IndexOf(startingCommit);
            int endingCommitIndex   = (endingCommit == null) ? _commits.Count - 1 : _commits.IndexOf(endingCommit);
            int numberToTake        = endingCommitIndex - startingCommitIndex + 1;

            return(_commits.Skip(_commits.IndexOf(startingCommit)).Take(numberToTake));
        }
コード例 #41
0
        private Vector3 DoCalcPosition(float time, out bool targetReached)
        {
            var speed = _enemy.Speed;
            var index = Mathf.FloorToInt(time / speed);

            if (index >= _path.Count() - 1)
            {
                targetReached = true;
                return(_path.LastOrDefault());
            }

            targetReached = false;
            if (index <= 0 && Mathf.Approximately(time, 0))
            {
                return(_path.FirstOrDefault());
            }

            var stepFrom = _path.ElementAt(index);
            var stepTo   = _path.ElementAt(index + 1);
            var k        = Mathf.Clamp01((time - speed * index) / speed);

            return(Vector3.Lerp(stepFrom, stepTo, k));
        }
コード例 #42
0
    static IEnumerable <int []> BuildAvaliableList(IEnumerable <int []> meetingsCloolect)
    {
        var start  = 0;
        var result = new List <int[]> ();

        foreach (var item in meetingsCloolect)
        {
            if (start < item[0])
            {
                result.Add(CreateTimeSlot(start, item[0]));
            }
            start = item[1];
        }

        var last   = meetingsCloolect.LastOrDefault();
        int endDay = 2400;

        if (last != null && last[1] < endDay)
        {
            result.Add(CreateTimeSlot(last[1], endDay));
        }
        return(result);
    }
コード例 #43
0
        internal static void Replace(BubbleGroup group, IEnumerable <VisualBubble> bubbles)
        {
            var unifiedGroup = @group as UnifiedBubbleGroup;

            if (unifiedGroup != null)
            {
                foreach (var innerGroup in unifiedGroup.Groups)
                {
                    Replace(innerGroup, bubbles);
                }
            }

            for (int i = 0; i < @group.Bubbles.Count; i++)
            {
                var bubble            = @group.Bubbles[i];
                var bubbleReplacement = bubbles.LastOrDefault(x => x.ID == bubble.ID);
                if (bubbleReplacement != null)
                {
                    @group.Bubbles.RemoveAt(i);
                    @group.Bubbles.Insert(i, bubbleReplacement);
                }
            }
        }
コード例 #44
0
    /// <summary>
    ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
    ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
    ///     any release. You should only use it directly in your code with extreme caution and knowing that
    ///     doing so can result in application failures when updating to a new Entity Framework Core release.
    /// </summary>
    protected virtual T Select(string?language, IEnumerable <T> services)
    {
        if (string.IsNullOrEmpty(language))
        {
            language = "C#";
        }

        var legacyService = services.LastOrDefault(s => s.Language == null);

        if (legacyService != null)
        {
            return(legacyService);
        }

        var matches = services.Where(s => string.Equals(s.Language, language, StringComparison.OrdinalIgnoreCase)).ToList();

        if (matches.Count == 0)
        {
            throw new OperationException(DesignStrings.NoLanguageService(language, typeof(T).ShortDisplayName()));
        }

        return(matches.Last());
    }
コード例 #45
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public CSharpDbContextGenerator(
#pragma warning disable CS0618 // Type or member is obsolete
            [NotNull] IEnumerable <IScaffoldingProviderCodeGenerator> legacyProviderCodeGenerators,
#pragma warning restore CS0618 // Type or member is obsolete
            [NotNull] IEnumerable <IProviderCodeGenerator> providerCodeGenerators,
            [NotNull] IAnnotationCodeGenerator annotationCodeGenerator,
            [NotNull] ICSharpUtilities cSharpUtilities)
        {
            Check.NotNull(legacyProviderCodeGenerators, nameof(legacyProviderCodeGenerators));
            Check.NotNull(providerCodeGenerators, nameof(providerCodeGenerators));
            Check.NotNull(annotationCodeGenerator, nameof(annotationCodeGenerator));
            Check.NotNull(cSharpUtilities, nameof(cSharpUtilities));

            if (!legacyProviderCodeGenerators.Any() && !providerCodeGenerators.Any())
            {
                throw new ArgumentException(AbstractionsStrings.CollectionArgumentIsEmpty(nameof(providerCodeGenerators)));
            }

            _legacyProviderCodeGenerator = legacyProviderCodeGenerators.LastOrDefault();
            _providerCodeGenerator       = providerCodeGenerators.LastOrDefault();
            _annotationCodeGenerator     = annotationCodeGenerator;
            _cSharpUtilities             = cSharpUtilities;
        }
コード例 #46
0
        /// <summary>
        /// Gets the relevant TFS <see cref="ChangesetSummary"/> for the root changeset given a set 
        /// of <see cref="ExtendedMerge"/> objects and a given <paramref name="tfsPathParentBranch"/>.
        /// </summary>
        /// <param name="merges">An array of <see cref="ExtendedMerge"/> objects describing the a set of merges.</param>
        /// <param name="tfsPathParentBranch">The tfs Path Parent Branch.</param>
        /// <param name="tfsPathBranchToCreate">The tfs Path Branch To Create.</param>
        /// <remarks>
        /// Each <see cref="ChangeType"/> uses the SourceChangeset, SourceItem, TargetChangeset, and TargetItem 
        /// properties with different semantics, depending on what it needs to describe, so the strategy to determine
        /// whether we are interested in a given ExtendedMerge summary depends on the SourceItem's <see cref="ChangeType"/>.
        /// </remarks>
        /// <returns><value>True</value> if the given <paramref name="merge"/> is relevant; <value>False</value> otherwise.
        /// </returns>
        private static ChangesetSummary GetRelevantChangesetBasedOnChangeType(IEnumerable<ExtendedMerge> merges, string tfsPathParentBranch, string tfsPathBranchToCreate)
        {
            merges = (merges ?? new ExtendedMerge[] {}).ToArray();
            var merge = merges.LastOrDefault(m => m.SourceItem.Item.ServerItem.Equals(tfsPathParentBranch, StringComparison.InvariantCultureIgnoreCase))
                     ?? merges.LastOrDefault();

            if (merge == null)
            {
                throw new GitTfsException("An unexpected error occured when trying to find the root changeset.\nFailed to find root changeset for " + tfsPathBranchToCreate + " branch in " + tfsPathParentBranch + " branch");
            }

            if (merge.SourceItem.ChangeType.HasFlag(ChangeType.Branch)
                || merge.SourceItem.ChangeType.HasFlag(ChangeType.Merge)
                || merge.SourceItem.ChangeType.HasFlag(ChangeType.Add))
            {
                Trace.WriteLine("Found C" + merge.SourceChangeset.ChangesetId + " on branch " + merge.SourceItem.Item.ServerItem);
                return merge.SourceChangeset;
            }
            if(merge.SourceItem.ChangeType.HasFlag(ChangeType.Rename))
            {
                Trace.WriteLine("Found C" + merge.TargetChangeset.ChangesetId + " on branch " + merge.TargetItem.Item);
                return merge.TargetChangeset;
            }
            throw new GitTfsException(
                "Don't know (yet) how to find the root changeset for an ExtendedMerge of type " +
                merge.SourceItem.ChangeType,
                new string[]
                            {
                                "Open an Issue on Github to notify the community that you need support for '" +
                                merge.SourceItem.ChangeType + "': https://github.com/git-tfs/git-tfs/issues"
                            });
        }
コード例 #47
0
ファイル: FDesktop.cs プロジェクト: lapuinka/naps2
        private void UpdateThumbnails(IEnumerable<int> selection, bool scrollToSelection)
        {
            UpdateThumbnails();
            SelectedIndices = selection;

            // We would like to maintain the current scroll if scrollToSelection is false, but that's not easy with ListView
            // In the meantime just scroll to selection anyway (the alternative is to always pop to the top)
            // TODO: Rewrite ThumbnailList.UpdateImages to detect and perform incremental updates

            // Scroll to selection
            thumbnailList1.EnsureVisible(SelectedIndices.LastOrDefault());
            thumbnailList1.EnsureVisible(SelectedIndices.FirstOrDefault());
        }
コード例 #48
0
        /// <summary>
        /// Transform an IEnumerable of <see cref="HttpMessageHandler"/>s into
        /// a chain of <see cref="HttpMessageHandler"/>s.
        /// </summary>
        /// <param name="handlers">
        /// Chain of <see cref="HttpMessageHandler" /> instances. 
        /// All but the last should be <see cref="DelegatingHandler"/>s. 
        /// </param>
        /// <returns>A chain of <see cref="HttpMessageHandler"/>s</returns>
        private static HttpMessageHandler CreatePipeline(IEnumerable<HttpMessageHandler> handlers)
        {
            HttpMessageHandler pipeline = handlers.LastOrDefault() ?? DefaultHandlerFactory();
            DelegatingHandler dHandler = pipeline as DelegatingHandler;
            if (dHandler != null)
            {
                dHandler.InnerHandler = DefaultHandlerFactory();
                pipeline = dHandler;
            }

            // Wire handlers up in reverse order
            IEnumerable<HttpMessageHandler> reversedHandlers = handlers.Reverse().Skip(1);
            foreach (HttpMessageHandler handler in reversedHandlers)
            {
                dHandler = handler as DelegatingHandler;
                if (dHandler == null)
                {
                    throw new ArgumentException(
                        string.Format(
                        "All message handlers except the last must be of the type '{0}'",
                        typeof(DelegatingHandler).Name));
                }

                dHandler.InnerHandler = pipeline;
                pipeline = dHandler;
            }

            return pipeline;
        }
コード例 #49
0
ファイル: Mage.cs プロジェクト: reminchev/SoftUni-Projects
 public override Character GetTarget(IEnumerable<Character> targetsList)
 {
     Character target = targetsList.LastOrDefault(t => t.IsAlive && t.Team != this.Team);
     return target;
 }
コード例 #50
0
ファイル: Mage.cs プロジェクト: EBojilova/SoftUni-3
 public override Character GetTarget(IEnumerable<Character> targetsList)
 {
     var target = targetsList.LastOrDefault(s => s.Team != this.Team && s.IsAlive);
     return target;
 }
コード例 #51
0
ファイル: TfsPlugin.cs プロジェクト: EdwinTai/git-tfs
 public PluginLoaderException(string message, IEnumerable<Exception> failures)
     : base(message, failures.LastOrDefault())
 {
     InnerExceptions = failures;
 }
コード例 #52
0
        internal static void Replace(BubbleGroup group, IEnumerable<VisualBubble> bubbles)
        {
            var unifiedGroup = @group as UnifiedBubbleGroup;
            if (unifiedGroup != null)
            {
                foreach (var innerGroup in unifiedGroup.Groups)
                {
                    Replace(innerGroup, bubbles);
                }
            }

            for (int i = 0; i < @group.Bubbles.Count; i++)
            {
                var bubble = @group.Bubbles[i];
                var bubbleReplacement = bubbles.LastOrDefault(x => x.ID == bubble.ID);
                if (bubbleReplacement != null)
                {
                    @group.Bubbles.RemoveAt(i);
                    @group.Bubbles.Insert(i, bubbleReplacement);
                }
            }
        }
コード例 #53
0
 private static string CreateRangeString(int key, IEnumerable<int> ranges)
 {
     return ranges.LastOrDefault(x => x < key) + " to " + (key - 1);
 }
コード例 #54
0
        /// <summary>
        /// Transform an IEnumerable of <see cref="HttpMessageHandler"/>s into
        /// a chain of <see cref="HttpMessageHandler"/>s.
        /// </summary>
        /// <param name="handlers">
        /// Chain of <see cref="HttpMessageHandler" /> instances. 
        /// All but the last should be <see cref="DelegatingHandler"/>s. 
        /// </param>
        /// <returns>A chain of <see cref="HttpMessageHandler"/>s</returns>
        private static HttpMessageHandler CreatePipeline(IEnumerable<HttpMessageHandler> handlers)
        {
            HttpMessageHandler pipeline = handlers.LastOrDefault() ?? GetDefaultHttpClientHandler();
            DelegatingHandler dHandler = pipeline as DelegatingHandler;
            if (dHandler != null)
            {
                dHandler.InnerHandler = GetDefaultHttpClientHandler();
                pipeline = dHandler;
            }

            // Wire handlers up in reverse order
            IEnumerable<HttpMessageHandler> reversedHandlers = handlers.Reverse().Skip(1);
            foreach (HttpMessageHandler handler in reversedHandlers)
            {
                dHandler = handler as DelegatingHandler;
                if (dHandler == null)
                {
                    throw new ArgumentException(
                        string.Format(
                        Resources.HttpMessageHandlerExtensions_WrongHandlerType,
                        typeof(DelegatingHandler).Name));
                }

                dHandler.InnerHandler = pipeline;
                pipeline = dHandler;
            }

            return pipeline;
        }
コード例 #55
0
        private static bool ExistsSymbol(int code, IEnumerable<Tuple<int, int>> existingSymbolList)
        {
            var smallerOrLesserEntry = existingSymbolList.LastOrDefault(x => x.Item1 <= code);

            if (smallerOrLesserEntry != null)
            {
                var firstValue = smallerOrLesserEntry.Item1;
                var lastValue = firstValue + smallerOrLesserEntry.Item2;

                return code >= firstValue && code < lastValue;
            }
            return false;
        }
コード例 #56
0
 private static string GetRequestedByFromCommit(IEnumerable<IBuildInformationNode> commits)
 {
     var lastCommit = commits.LastOrDefault();
     if (lastCommit == null) return null;
     return lastCommit.Fields["Committer"];
 }
コード例 #57
0
 public override Character GetTarget(IEnumerable<Character> targetsList)
 {
     return targetsList.LastOrDefault(c => c.IsAlive && c.Team != this.Team);
 }
コード例 #58
0
			private void RenderSitemapNodes(HtmlTextWriter writer, IEnumerable<Zongsoft.Plugins.PluginTreeNode> nodes)
			{
				if(nodes == null)
					return;

				var last = nodes.LastOrDefault();

				foreach(var node in nodes)
				{
					var treeNode = node.UnwrapValue<Controls.TreeViewNode>(Zongsoft.Plugins.ObtainMode.Auto, this, null);

					if(treeNode != null)
					{
						//生成<dt>开始元素
						writer.RenderBeginTag(HtmlTextWriterTag.Dt);

						if(node == last)
						{
							writer.WriteEncodedText(treeNode.Text);
						}
						else
						{
							writer.AddAttribute(HtmlTextWriterAttribute.Href, string.IsNullOrWhiteSpace(treeNode.NavigateUrl) ? "#" : treeNode.NavigateUrl);
							writer.AddAttribute(HtmlTextWriterAttribute.Alt, treeNode.ToolTip);
							writer.RenderBeginTag(HtmlTextWriterTag.A);
							writer.WriteEncodedText(treeNode.Text);
							writer.RenderEndTag();
						}

						//生成</dt>结束元素
						writer.RenderEndTag();

						//处理描述元素
						if(!string.IsNullOrWhiteSpace(treeNode.Description))
						{
							writer.RenderBeginTag(HtmlTextWriterTag.Dd);
							writer.WriteEncodedText(treeNode.Description);
							writer.RenderEndTag();
						}
					}
				}
			}
コード例 #59
0
 /// <summary>
 /// Return all position-type matches. These are selectors that are keyed to the position within the selection
 /// set itself.
 /// </summary>
 /// <param name="list"></param>
 /// <param name="selector"></param>
 /// <returns></returns>
 protected IEnumerable<IDomObject> GetResultPositionMatches(IEnumerable<IDomObject> list, Selector selector)
 {
     switch (selector.PositionType)
     {
         case PositionType.First:
             IDomObject first = list.FirstOrDefault();
             if (first != null)
             {
                 yield return first;
             }
             break;
         case PositionType.Last:
             IDomObject last = list.LastOrDefault();
             if (last != null)
             {
                 yield return last;
             }
             break;
         case PositionType.IndexEquals:
             int critIndex = selector.PositionIndex;
             if (critIndex < 0)
             {
                 critIndex = list.Count() + critIndex;
             }
             bool ok = true;
             IEnumerator<IDomObject> enumerator = list.GetEnumerator();
             for (int i = 0; i <= critIndex && ok; i++)
             {
                 ok = enumerator.MoveNext();
             }
             if (ok)
             {
                 yield return enumerator.Current;
             }
             else
             {
                 yield break;
             }
             break;
         case PositionType.IndexGreaterThan:
             int index = 0;
             foreach (IDomObject obj in list)
             {
                 if (index++ > selector.PositionIndex)
                 {
                     yield return obj;
                 }
             }
             break;
         case PositionType.IndexLessThan:
             int indexLess = 0;
             foreach (IDomObject obj in list)
             {
                 if (indexLess++ < selector.PositionIndex)
                 {
                     yield return obj;
                 }
                 else
                 {
                     break;
                 }
             }
             break;
     }
     yield break;
 }
コード例 #60
0
        void CheckSelectionInt(IEnumerable<Slide> slides)
        {
            if (!_inited) return;
            //check if Slides must be pre-chached
            if (slides.Count() > 0)
            {
                Slide CurrentSlide = slides.LastOrDefault();
                if (CurrentSlide != null)
                {
                    PresentationController.Instance.LoadSlide(CurrentSlide);
                    PresentationController.Instance.CanSelectNextSlide = this.CanSelectNextSlide(CurrentSlide);
                    PresentationController.Instance.CanSelectPrevSlide = this.CanSelectPrevSlide(CurrentSlide);
                }
            }
            else
            {
                PresentationController.Instance.CanSelectNextSlide = false;
                PresentationController.Instance.CanSelectPrevSlide = false;
            }

            if (OnCheckSelection != null)
                OnCheckSelection(this.SelectionList);

            PresentationController.Instance.SendSelectionChanged(slides);
            (Viewer as Control).Invalidate();
        }