예제 #1
0
        public void UpdateRequests(ApplicationUser user, IReadOnlyList <Business.Model.Request> requests)
        {
            var activeDates = this.dateCalculator.GetActiveDates();

            var firstDbDate = DbConvert.LocalDate.ToDb(activeDates.First());
            var lastDbDate  = DbConvert.LocalDate.ToDb(activeDates.Last());

            var existingUserActiveRequests = this.context.Requests
                                             .Where(r => r.ApplicationUser == user && r.DbDate >= firstDbDate && r.DbDate <= lastDbDate)
                                             .ToArray();

            var requestsToRemove = existingUserActiveRequests
                                   .Where(existing => requests.All(r => existing.Date != r.Date));

            var requestsToAdd = requests
                                .Where(r => existingUserActiveRequests.All(existing => existing.Date != r.Date))
                                .Select(r => new Request {
                ApplicationUserId = user.Id, Date = r.Date
            });

            this.context.Requests.RemoveRange(requestsToRemove);
            this.context.Requests.AddRange(requestsToAdd);

            var existingUserActiveAllocations = this.context.Allocations
                                                .Where(a => a.ApplicationUser == user && a.DbDate >= firstDbDate && a.DbDate <= lastDbDate)
                                                .ToArray();

            var allocationsToRemove = existingUserActiveAllocations
                                      .Where(existing => requests.All(r => existing.Date != r.Date));

            this.context.Allocations.RemoveRange(allocationsToRemove);

            this.context.SaveChanges();
        }
예제 #2
0
        private IEnumerable <IValueWrapper> GetItems(IValueWrapper item)
        {
            var type = item.Value.GetType();

            if (type.IsArray && item.Value is Array array && array.Rank == _indices.Count)
            {
                // TODO: These casts are probably going to fail for mixed-type indices. Need a more robust way to go about it.
                if (_indices.All(i => i is int))
                {
                    return new IValueWrapper[] { new SimpleValueWrapper(array.GetValue(_indices.Cast <int>().ToArray())) }
                }
                ;
                if (_indices.All(i => i is long))
                {
                    return new IValueWrapper[] { new SimpleValueWrapper(array.GetValue(_indices.Cast <long>().ToArray())) }
                }
                ;
            }

            // Get public indexers with a single parameter
            // this list should be pretty short, most types will expose at most one or two of these
            var indexer = type
                          .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                          .FirstOrDefault(p => p.CanRead && p.GetMethod != null && MatchesIndexArguments(p.GetIndexParameters()));

            if (indexer == null)
            {
                return(Enumerable.Empty <IValueWrapper>());
            }
            var value = indexer.GetMethod.Invoke(item.Value, _indices.ToArray());

            return(new IValueWrapper[] { new SimpleValueWrapper(value) });
        }
예제 #3
0
        public static PackageResult Success(NugetPackage package, IReadOnlyList <PackageResult> dependencies, Option <MoreInformation> moreInformation)
        {
            var isAggregationPackage = package.SupportType == SupportType.NoDotNetLibraries &&
                                       dependencies.Any() &&
                                       dependencies.All(d => d.SupportType == SupportType.PreRelease ||
                                                        d.SupportType == SupportType.Supported ||
                                                        d.SupportType == SupportType.KnownReplacementAvailable ||
                                                        d.SupportType == SupportType.Unsupported
                                                        );

            var isSupportedAggregationPackage = isAggregationPackage &&
                                                dependencies.All(d => d.SupportType == SupportType.PreRelease || d.SupportType == SupportType.Supported);

            var supportType = isSupportedAggregationPackage
                ? (package.IsPrerelease ? SupportType.Supported : SupportType.PreRelease)
                : (isAggregationPackage ? SupportType.Unsupported : package.SupportType);

            return(new PackageResult()
            {
                PackageName = package.Id,
                Dependencies = dependencies,
                SupportType = supportType,
                ProjectUrl = package.ProjectUrl,
                MoreInformation = moreInformation
            });
        }
        public ProjectSettingsDlg(ProjectSettingsViewModel model)
        {
            InitializeComponent();

            m_txtRecordingProjectName.MaxLength = model.Project.MaxProjectNameLength;

            for (int i = 0; i < m_cboBookMarker.Items.Count; i++)
            {
                var chapterAnnouncement = (ChapterAnnouncement)i;
                m_cboBookMarker.Items[i] = new ChapterAnnouncementItem(LocalizationManager.GetDynamicString(GlyssenInfo.kApplicationId,
                                                                                                            "DialogBoxes.ProjectSettingsDlg.ChapterAnnouncementTab.BookMarkerComboBox.Items." + chapterAnnouncement,
                                                                                                            m_cboBookMarker.Items[i].ToString()), chapterAnnouncement);
            }

            IReadOnlyList <BookScript> books = model.Project.IncludedBooks.Any() ? model.Project.IncludedBooks : model.Project.Books;

            if (books.All(book => string.IsNullOrEmpty(book.PageHeader)))
            {
                RemoveItemFromBookMarkerCombo(ChapterAnnouncement.PageHeader);
            }
            if (books.All(book => string.IsNullOrEmpty(book.MainTitle)))
            {
                RemoveItemFromBookMarkerCombo(ChapterAnnouncement.MainTitle1);
            }

            LocalizeItemDlg <TMXDocument> .StringsLocalized += HandleStringsLocalized;
            ProjectSettingsViewModel = model;
            HandleStringsLocalized();
        }
예제 #5
0
        public static string GetCommonDirectoryPath(IReadOnlyList <string> paths)
        {
            // TODO: Unit tests, optimize
            string commonPath = String.Empty;

            List <string> separatedPath = paths
                                          .First(str => str.Length == paths.Max(st2 => st2.Length))
                                          .Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)
                                          .ToList();

            foreach (string pathSegment in separatedPath.AsEnumerable())
            {
                if (commonPath.Length == 0 && paths.All(str => str.StartsWith(pathSegment)))
                {
                    commonPath = pathSegment;
                }
                else if (paths.All(str => str.StartsWith(commonPath + Path.DirectorySeparatorChar + pathSegment)))
                {
                    commonPath += Path.DirectorySeparatorChar + pathSegment;
                }
                else
                {
                    break;
                }
            }

            return(commonPath);
        }
예제 #6
0
        public void All()
        {
            Assert.IsTrue(m_source.All(x => 0 <= x));
            Assert.IsFalse(m_source.All(x => 1 <= x));

            var empty = new int[0];

            Assert.IsTrue(empty.All(x => 0 <= x));
        }
예제 #7
0
        /// <summary>
        /// Merges a collection of view models with a list of models
        /// </summary>
        public static void MergeCollection <TViewModel, TModel>(
            this ICollection <TViewModel> collection,
            IReadOnlyList <TModel> updated,
            IMergeStrategy <TModel, TViewModel> strategy)
            where TViewModel : IIdentifiableObject
            where TModel : IIdentifiableObject
        {
            // Remove those without id or not existing in the updated collection
            var removed = collection.Where(r => r.Id == 0 || updated.All(u => u.Id != r.Id)).ToList();

            foreach (var obj in removed)
            {
                collection.Remove(obj);
            }

            foreach (var updatedModel in updated)
            {
                var match = collection.FirstOrDefault(r => r.Id == updatedModel.Id);
                if (match != null)
                {
                    strategy.UpdateModel(match, updatedModel);
                }
                else
                {
                    var vm = strategy.FromModel(updatedModel);
                    collection.Add(vm);
                }
            }
        }
예제 #8
0
파일: World.cs 프로젝트: azm102/exercises
        private bool IsCompleted()
        {
            var allCargosDelivered = _warehouses.All(x => x.Cargos.All(y => y.Destination == x));
            var transportsIsEmpty  = !_transports.Any(x => x.Track?.Cargo != null);

            return(allCargosDelivered && transportsIsEmpty);
        }
        private void SetupWallSideActuators(IEnumerable <GrabableItemData> items, IReadOnlyList <ActuatorItemData> actuators)
        {
            if (actuators.Any())
            {
                CurrentGrabableItems = items;

                var factory = parser.TryMatchFactory(actuators, items.Any());
                if (factory != null)
                {
                    CurrentTile.SubItems.Add(factory.CreateItem(builder, CurrentTile, actuators));
                }
                else
                {
                    if (actuators.All(x => x.ActuatorType != 5 && x.ActuatorType != 6))
                    {
                        foreach (var i in actuators)
                        {
                            Point?absolutePosition = null;
                            if (i.ActionLocation is RemoteTarget)
                            {
                                absolutePosition = ((RemoteTarget)i.ActionLocation).Position.Position.ToAbsolutePosition(builder.CurrentMap);
                            }

                            CurrentTile.SubItems.Add(new Actuator(builder.GetWallPosition(i.TilePosition, CurrentTile), $"{absolutePosition} {i.DumpString()}"));
                        }
                    }
                    else
                    {
                    }
                }
            }
        }
예제 #10
0
        public static bool IsFiltered(this Customer customer, IReadOnlyList <string> columFilters)
        {
            if (columFilters.All(string.IsNullOrEmpty))
            {
                return(true);
            }
            var values = customer.GetType()
                         .GetProperties()
                         .Select(propertyInfo => propertyInfo.GetValue(customer, null).ToString().ToLower())
                         .ToList();

            var isEqual = true;

            foreach (var columFilter in columFilters.ToList())
            {
                var index = columFilters.ToList().IndexOf(columFilter);
                if (values[index].ToLower().Contains(columFilter.ToLower()) || string.IsNullOrEmpty(columFilter))
                {
                    continue;
                }

                isEqual = false;
            }
            return(isEqual);
        }
        public async Task WhenNoTax_ItShouldPersistRecords()
        {
            this.guidCreator.Setup(v => v.CreateSqlSequential()).Returns(Guid.NewGuid).Verifiable();

            IReadOnlyList <AppendOnlyLedgerRecord> results = null;

            this.persistCommittedRecords
            .Setup(v => v.ExecuteAsync(It.IsAny <IReadOnlyList <AppendOnlyLedgerRecord> >()))
            .Callback <IReadOnlyList <AppendOnlyLedgerRecord> >(r => { results = r; })
            .Returns(Task.FromResult(0));

            await this.target.ExecuteAsync(
                EnactingUserId,
                UserId,
                Timestamp,
                TotalAmount,
                TotalAmount,
                TransactionReference,
                StripeChargeId,
                TaxamoTransactionKey,
                Comment);

            Assert.IsNotNull(results);
            Assert.AreEqual(2, results.Count);

            Assert.IsTrue(results.All(v => v.TransactionType == LedgerTransactionType.CreditRefund));
            Assert.IsTrue(results.Sum(v => v.Amount) == 0);
        }
예제 #12
0
        public static bool CanSynchronize(IReadOnlyList<Ticker> tickers, ISimulationSettings settings, out string error)
        {
            if (tickers == null) throw new ArgumentNullException("tickers");
            if (settings == null) throw new ArgumentNullException("settings");

            if (tickers.Count == 0)
            {
                error = "There must be least one ticker.";
                return false;
            }

            if (tickers.Select(t => t.Name.ToLowerInvariant()).GroupBy(name => name).Count() < tickers.Count)
            {
                error = "Ticker names must be unique.";
                return false;
            }

            if (settings.Get<SimulationRangeSetting>().Type == SimulationRangeType.Common &&
                tickers.Select(t => t.From).Max() > tickers.Select(t => t.To).Min())
            {
                error = "Tickers do not have common range.";
                return false;
            }

            if (settings.Get<CommissionSetting>().Value < 0)
            {
                error = "Commission cannot be negative.";
                return false;
            }

            if (settings.Get<CommissionSetting>().Type == CommissionType.Percent &&
                settings.Get<CommissionSetting>().Value >= 100)
            {
                error = "Commission of percentage type must be smaller than 100 %.";
                return false;
            }

            if (settings.Get<SimulationRangeSetting>().Type == SimulationRangeType.FromToDates &&
                settings.Get<SimulationRangeSetting>().From > settings.Get<SimulationRangeSetting>().To)
            {
                error = "Simulation range is invalid.";
                return false;
            }

            if (settings.Get<InitialEquitySetting>().Value < 1)
            {
                error = "Initial equity cannot be smaller than 1.";
                return false;
            }

            if (settings.Get<SimulationRangeSetting>().Type == SimulationRangeType.FromToDates &&
                tickers.All(t => t.From > settings.Get<SimulationRangeSetting>().To || t.To < settings.Get<SimulationRangeSetting>().From))
            {
                error = "No quotes matching specified simulation time range.";
                return false;
            }

            error = null;
            return true;
        }
        public async Task CreateOrUpdatePullRequestMergeStatusInfoAsync(string pullRequestUrl, IReadOnlyList <MergePolicyEvaluationResult> evaluations)
        {
            (string owner, string repo, int id) = ParsePullRequestUri(pullRequestUrl);
            // Get the sha of the latest commit for the current PR
            string prSha = (await Client.PullRequest.Get(owner, repo, id))?.Head?.Sha;

            if (prSha == null)
            {
                throw new InvalidOperationException("We cannot find the sha of the pull request");
            }

            // Get a list of all the merge policies checks runs for the current PR
            List <CheckRun> existingChecksRuns =
                (await Client.Check.Run.GetAllForReference(owner, repo, prSha))
                .CheckRuns.Where(e => e.ExternalId.StartsWith(MergePolicyConstants.MaestroMergePolicyCheckRunPrefix)).ToList();

            var toBeAdded   = evaluations.Where(e => existingChecksRuns.All(c => c.ExternalId != CheckRunId(e, prSha)));
            var toBeUpdated = existingChecksRuns.Where(c => evaluations.Any(e => c.ExternalId == CheckRunId(e, prSha)));
            var toBeDeleted = existingChecksRuns.Where(c => evaluations.All(e => c.ExternalId != CheckRunId(e, prSha)));

            foreach (var newCheckRunValidation in toBeAdded)
            {
                await Client.Check.Run.Create(owner, repo, CheckRunForAdd(newCheckRunValidation, prSha));
            }
            foreach (var updatedCheckRun in toBeUpdated)
            {
                MergePolicyEvaluationResult eval           = evaluations.Single(e => updatedCheckRun.ExternalId == CheckRunId(e, prSha));
                CheckRunUpdate newCheckRunUpdateValidation = CheckRunForUpdate(eval);
                await Client.Check.Run.Update(owner, repo, updatedCheckRun.Id, newCheckRunUpdateValidation);
            }
            foreach (var deletedCheckRun in toBeDeleted)
            {
                await Client.Check.Run.Update(owner, repo, deletedCheckRun.Id, CheckRunForDelete(deletedCheckRun));
            }
        }
예제 #14
0
        public void User_Name_Contains_No_Punctuations()
        {
            var containsPunctuations =
                GetUserNames.All(s => s.Any(char.IsPunctuation));

            Assert.IsFalse(containsPunctuations);
        }
        /// <summary>
        /// Gets the labels for the specified instances in native data format.
        /// </summary>
        /// <param name="instances">The instances to get the labels for.</param>
        /// <param name="instanceSource">The instance source.</param>
        /// <param name="labelSource">An optional label source.</param>
        /// <returns>The labels in native data format.</returns>
        /// <exception cref="BayesPointMachineClassifierException">Thrown if a label is unknown.</exception>
        protected override int[] GetNativeLabels(
            IReadOnlyList <TInstance> instances, TInstanceSource instanceSource, TLabelSource labelSource = default(TLabelSource))
        {
            Debug.Assert(instances != null, "The instances must not be null.");
            Debug.Assert(instances.All(instance => instance != null), "An instance must not be null.");
            Debug.Assert(instanceSource != null, "The instance source must not be null.");

            // Get all labels and check them
            int labelIndex   = 0;
            var nativeLabels = new int[instances.Count];

            foreach (var instance in instances)
            {
                TLabel standardLabel = this.StandardMapping.GetLabelSafe(instance, instanceSource, labelSource);

                int nativeLabel;
                if (!this.classLabelSet.TryGetIndex(standardLabel, out nativeLabel))
                {
                    throw new BayesPointMachineClassifierException("The class label '" + standardLabel + "' is unknown.");
                }

                nativeLabels[labelIndex] = nativeLabel;

                labelIndex++;
            }

            return(nativeLabels);
        }
예제 #16
0
        public IVector FindDistances(IReadOnlyList <IVector> data, DistanceMetric distance)
        {
            Debug.Assert(IsValid && data.All(v => v.IsValid));
            if (distance == DistanceMetric.Cosine)
            {
                var norm     = DotProduct(this);
                var dataNorm = data.Select(d => d.DotProduct(d)).ToList();
                var ret      = new float[data.Count];
                for (var i = 0; i < data.Count; i++)
                {
                    ret[i] = Convert.ToSingle(1d - DotProduct(data[i]) / Math.Sqrt(norm * dataNorm[i]));
                }
                return(_cuda.CreateVector(data.Count, i => ret[i]));
            }

            if (distance == DistanceMetric.Euclidean || distance == DistanceMetric.Manhattan)
            {
                var ret = _cuda.CalculateDistances(new[] { this }, data, distance);
                return(ret.ReshapeAsVector());
            }
            else
            {
                var distanceFunc = _GetDistanceFunc(distance);
                var ret          = new float[data.Count];
                for (var i = 0; i < data.Count; i++)
                {
                    ret[i] = distanceFunc(data[i]);
                }
                return(_cuda.CreateVector(data.Count, i => ret[i]));
            }
        }
        private Expression RewritePropertyAccess(
            Expression expression,
            IReadOnlyList <IPropertyBase> properties,
            IQuerySource querySource)
        {
            if (querySource != null &&
                properties.Count > 0 &&
                properties.All(p => p is INavigation) &&
                properties[properties.Count - 1] is INavigation lastNavigation &&
                lastNavigation.IsCollection())
            {
                var qsre = new QuerySourceReferenceExpression(querySource);

                CollectionNavigationIncludeResultOperators.Add(
                    new IncludeResultOperator(properties.Cast <INavigation>().ToArray(), qsre));

                var parameter       = Expression.Parameter(querySource.ItemType, querySource.ItemName);
                var accessorBody    = BuildCollectionAccessorExpression(parameter, properties);
                var emptyCollection = lastNavigation.GetCollectionAccessor().Create();

                return(Expression.Call(
                           ProjectCollectionNavigationMethodInfo
                           .MakeGenericMethod(querySource.ItemType, expression.Type),
                           qsre,
                           Expression.Lambda(
                               Expression.Coalesce(
                                   accessorBody,
                                   Expression.Constant(emptyCollection, accessorBody.Type)),
                               parameter)));
            }

            return(expression);
        }
예제 #18
0
        public static List<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> epgData, IReadOnlyList<RecordingInfo> currentRecordings, ILogger logger)
        {
            List<TimerInfo> timers = new List<TimerInfo>();

            // Filtered Per Show
            var filteredEpg = epgData.Where(epg => epg.Id.Substring(0, 10) == seriesTimer.Id); 

            if (!seriesTimer.RecordAnyTime)
            {
                filteredEpg = filteredEpg.Where(epg => (seriesTimer.StartDate.TimeOfDay == epg.StartDate.TimeOfDay));
            }

            if (seriesTimer.RecordNewOnly)
            {
                filteredEpg = filteredEpg.Where(epg => !epg.IsRepeat); //Filtered by New only
            }

            if (!seriesTimer.RecordAnyChannel)
            {
                filteredEpg = filteredEpg.Where(epg => string.Equals(epg.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase));
            }

            filteredEpg = filteredEpg.Where(epg => seriesTimer.Days.Contains(epg.StartDate.DayOfWeek)); 
         
            filteredEpg = filteredEpg.Where(epg => currentRecordings.All(r => r.Id.Substring(0, 14) != epg.Id.Substring(0, 14))); //filtered recordings already running
            
            filteredEpg = filteredEpg.GroupBy(epg => epg.Id.Substring(0, 14)).Select(g => g.First()).ToList();

            foreach (var epg in filteredEpg)
            {
                timers.Add(CreateTimer(epg, seriesTimer));
            }

            return timers;
        }
예제 #19
0
        // Combines 1 or more LayerTranslators as CompositionShape subgraphs under a ShapeVisual.
        static Visual GetVisualForLayerTranslators(CompositionContext context, IReadOnlyList <LayerTranslator> shapes)
        {
            Debug.Assert(shapes.All(s => s.IsShape), "Precondition");

            var compositionShapes = shapes.Select(s => (shape: s.GetShapeRoot(context), subgraph: s)).Where(s => s.shape != null).ToArray();

            switch (compositionShapes.Length)
            {
            case 0:
                return(null);

            case 1:
                // There's only 1 shape. Get it to translate directly to a Visual.
                return(compositionShapes[0].subgraph.GetVisualRoot(context));

            default:
                // There are multiple contiguous shapes. Group them under a ShapeVisual.
                // The ShapeVisual has to have a size (it clips to its size).
                // TODO - if the shape graphs share the same opacity and/or visiblity, get them
                //        to translate without opacity/visiblity and we'll pull those
                //        into the Visual.
                var shapeVisual = context.ObjectFactory.CreateShapeVisualWithChild(compositionShapes[0].shape, context.Size);

                shapeVisual.SetDescription(context, () => "Layer aggregator");

                for (var i = 1; i < compositionShapes.Length; i++)
                {
                    shapeVisual.Shapes.Add(compositionShapes[i].shape);
                }

                return(shapeVisual);
            }
        }
예제 #20
0
        private static IEnumerable <long> AllLocations(IReadOnlyList <char> mask)
        {
            if (mask.All(x => x != 'X'))
            {
                yield return(Convert.ToInt64(string.Join("", mask.ToArray()), 2));
            }
            else
            {
                List <long> toReturn = new();
                var         loc      = mask.ToList().IndexOf('X');

                var zero = mask.ToArray();
                zero[loc] = '0';
                toReturn.AddRange(AllLocations(zero));


                var one = mask.ToArray();
                one[loc] = '1';
                toReturn.AddRange(AllLocations(one));

                foreach (var item in toReturn)
                {
                    yield return(item);
                }
            }
        }
예제 #21
0
        public static List <Token> GetAllTokens(string mdParagraph)
        {
            var allTokens = new List <Token>();
            var position  = 0;

            while (position < mdParagraph.Length)
            {
                var symbolRepeatCount = GeneralFunctions.SymbolInRowCount(
                    mdParagraph[position], mdParagraph, position);
                if (Tags.All(tag => symbolRepeatCount != tag.Md.Length))
                {
                    position += symbolRepeatCount;
                }
                else if (TryGetToken(mdParagraph, position, symbolRepeatCount, out var possibleToken))
                {
                    allTokens.Add(possibleToken);
                    position += possibleToken.Tag.Md.Length;
                }
                else
                {
                    position++;
                }
            }

            return(allTokens);
        }
        public static async Task CreateLabelsAsync(
            IGitHubClient client,
            string org,
            string repo,
            ILogger logger,
            IEnumerable <NewLabel> desiredLabels)
        {
            logger.LogInformation("Ensuring tags exist");

            IReadOnlyList <Label> labels = await client.Issue.Labels.GetAllForRepository(org, repo);

            async Task MakeLabel(NewLabel label)
            {
                if (labels.All(l => l.Name != label.Name))
                {
                    logger.LogInformation("Missing tag {tag}, creating...", label.Name);
                    await TryCreateAsync(() =>
                                         client.Issue.Labels.Create(org, repo, label),
                                         logger);
                }
            }

            await Task.WhenAll(desiredLabels.Select(MakeLabel));

            logger.LogInformation("Tags ensured");
        }
예제 #23
0
 /// <summary>
 /// Translates the given values. Each value is taken as the value for the id at its index
 /// (ids as in <see cref="Ids"/>).
 /// </summary>
 /// <param name="values">the values to translates</param>
 /// <returns>the translated values. Null if the values should not be translated, e.g. the stat should be
 /// hidden. This is the case for stats without effect or stats that are not meant to be visible to players.
 /// </returns>
 /// <exception cref="ArgumentException">if the number of values does not match the number of
 /// <see cref="Ids"/></exception>
 public string Translate(IReadOnlyList <int> values)
 {
     if (values.Count != Ids.Count)
     {
         throw new ArgumentException("Number of values does not match number of ids");
     }
     if (values.All(v => v == 0))
     {
         // stats with all values being zero (before applying handlers) have no effect
         return(null);
     }
     foreach (var entry in _jsonTranslation.English)
     {
         bool match = entry.Condition
                      .EquiZip(values, (c, v) => c == null || (c.Min <= v && v <= c.Max))
                      .All();
         if (match)
         {
             var formatInputs = new List <string>();
             for (var i = 0; i < values.Count; i++)
             {
                 var value = (double)values[i];
                 foreach (var handler in entry.IndexHandlers[i])
                 {
                     value = handler.Apply(value);
                 }
                 formatInputs.Add(entry.Formats[i].Apply(value));
             }
             var suffix = _jsonTranslation.IsHidden ? " (Hidden)" : "";
             return(string.Format(CultureInfo.InvariantCulture, entry.FormatString,
                                  formatInputs.ToArray <object>()) + suffix);
         }
     }
     return(null);
 }
        /// <summary>
        /// Translates the given values. Each value is taken as the value for the id at its index
        /// (ids as in <see cref="Ids"/>).
        /// </summary>
        /// <param name="values">the values to translates</param>
        /// <returns>the translated values. Null if the values should not be translated, e.g. the stat should be
        /// hidden. This is the case for stats without effect or stats that are not meant to be visible to players.
        /// </returns>
        /// <exception cref="ArgumentException">if the number of values does not match the number of
        /// <see cref="Ids"/></exception>
        public string?Translate(IReadOnlyList <int> values)
        {
            if (values.Count != Ids.Count)
            {
                throw new ArgumentException("Number of values does not match number of ids");
            }

            if (values.All(v => v == 0))
            {
                // stats with all values being zero (before applying handlers) have no effect
                return(null);
            }
            foreach (var entry in _jsonTranslation.English)
            {
                bool match = entry.Condition
                             .EquiZip(values, (c, v) => c == null || Evaluate(c, v))
                             .All();
                if (match)
                {
                    if (entry.FormatString == string.Empty)
                    {
                        return(null);
                    }

                    return(FormatEntry(entry, values));
                }
            }
            return(null);
        }
예제 #25
0
파일: TextLine.cs 프로젝트: zyj0021/PdfPig
        /// <summary>
        /// Create a new <see cref="TextLine"/>.
        /// </summary>
        /// <param name="words">The words contained in the line.</param>
        public TextLine(IReadOnlyList <Word> words)
        {
            if (words == null)
            {
                throw new ArgumentNullException(nameof(words));
            }

            if (words.Count == 0)
            {
                throw new ArgumentException("Empty words provided.", nameof(words));
            }

            Words = words;

            Text = string.Join(" ", words.Where(s => !string.IsNullOrWhiteSpace(s.Text)).Select(x => x.Text));

            var minX = words.Min(x => x.BoundingBox.Left);
            var minY = words.Min(x => x.BoundingBox.Bottom);
            var maxX = words.Max(x => x.BoundingBox.Right);
            var maxY = words.Max(x => x.BoundingBox.Top);

            BoundingBox = new PdfRectangle(minX, minY, maxX, maxY);

            if (words.All(x => x.TextDirection == words[0].TextDirection))
            {
                TextDirection = words[0].TextDirection;
            }
            else
            {
                TextDirection = TextDirection.Unknown;
            }
        }
예제 #26
0
 public void AnnounceDraw(Symbol winner, IReadOnlyList <Symbol> board)
 {
     if (winner == Symbol.Empty && board.All(o => o != Symbol.Empty))
     {
         Console.WriteLine("IT'S A DRAW");
     }
 }
예제 #27
0
        public static List <TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer, IEnumerable <ProgramInfo> epgData, IReadOnlyList <RecordingInfo> currentRecordings, ILogger logger)
        {
            List <TimerInfo> timers = new List <TimerInfo>();

            // Filtered Per Show
            var filteredEpg = epgData.Where(epg => epg.Id.Substring(0, 10) == seriesTimer.Id);

            if (!seriesTimer.RecordAnyTime)
            {
                filteredEpg = filteredEpg.Where(epg => (seriesTimer.StartDate.TimeOfDay == epg.StartDate.TimeOfDay));
            }

            if (seriesTimer.RecordNewOnly)
            {
                filteredEpg = filteredEpg.Where(epg => !epg.IsRepeat); //Filtered by New only
            }

            if (!seriesTimer.RecordAnyChannel)
            {
                filteredEpg = filteredEpg.Where(epg => string.Equals(epg.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase));
            }

            filteredEpg = filteredEpg.Where(epg => seriesTimer.Days.Contains(epg.StartDate.DayOfWeek));

            filteredEpg = filteredEpg.Where(epg => currentRecordings.All(r => r.Id.Substring(0, 14) != epg.Id.Substring(0, 14))); //filtered recordings already running

            filteredEpg = filteredEpg.GroupBy(epg => epg.Id.Substring(0, 14)).Select(g => g.First()).ToList();

            foreach (var epg in filteredEpg)
            {
                timers.Add(CreateTimer(epg, seriesTimer));
            }

            return(timers);
        }
예제 #28
0
        public GateAddress(IReadOnlyList <int> glyphList)
        {
            if (!glyphList.All(g => Enum.IsDefined(typeof(Glyph), g)))
            {
                return;
            }

            Glyph1 = (Glyph)glyphList[0];
            Glyph2 = (Glyph)glyphList[1];
            Glyph3 = (Glyph)glyphList[2];
            Glyph4 = (Glyph)glyphList[3];
            Glyph5 = (Glyph)glyphList[4];
            Glyph6 = (Glyph)glyphList[5];

            Address = new Dictionary <int, Glyph>
            {
                { 1, Glyph1 },
                { 2, Glyph2 },
                { 3, Glyph3 },
                { 4, Glyph4 },
                { 5, Glyph5 },
                { 6, Glyph6 }
            };
            IsValid = true;
            if (glyphList.Distinct().Count() != 6)
            {
                IsValid = false;
            }
        }
예제 #29
0
 void UpdateLoadAllButton()
 {
     if (loadAllTables.Visible = tables.Any(t => t.State == TableState.NotLoaded))
     {
         loadAllTables.Enabled = tables.All(t => t.State != TableState.Loading);
     }
 }
예제 #30
0
 // Compare to: CallExpression.Reduce.__UnpackListHelper
 static MSAst.Expression UnpackBasesHelper(IReadOnlyList <Arg> bases)
 {
     if (bases.Count == 0)
     {
         return(Expression.Call(AstMethods.MakeEmptyTuple));
     }
     else if (bases.All(arg => arg.ArgumentInfo.Kind is ArgumentType.Simple))
     {
         return(Expression.Call(AstMethods.MakeTuple,
                                Expression.NewArrayInit(
                                    typeof(object),
                                    ToObjectArray(bases.Select(arg => arg.Expression).ToList())
                                    )
                                ));
     }
     else
     {
         var expressions = new ReadOnlyCollectionBuilder <MSAst.Expression>(bases.Count + 2);
         var varExpr     = Expression.Variable(typeof(PythonList), "$coll");
         expressions.Add(Expression.Assign(varExpr, Expression.Call(AstMethods.MakeEmptyList)));
         foreach (var arg in bases)
         {
             if (arg.ArgumentInfo.Kind == ArgumentType.List)
             {
                 expressions.Add(Expression.Call(AstMethods.ListExtend, varExpr, AstUtils.Convert(arg.Expression, typeof(object))));
             }
             else
             {
                 expressions.Add(Expression.Call(AstMethods.ListAppend, varExpr, AstUtils.Convert(arg.Expression, typeof(object))));
             }
         }
         expressions.Add(Expression.Call(AstMethods.ListToTuple, varExpr));
         return(Expression.Block(typeof(PythonTuple), new MSAst.ParameterExpression[] { varExpr }, expressions));
     }
 }
예제 #31
0
 public Line(int lineNumber, int oldLineNumber, IReadOnlyList <LinePart> parts)
 {
     LineNumber    = lineNumber;
     OldLineNumber = oldLineNumber;
     IsNew         = parts.All(p => p.Status == LinePartStatus.New);
     Parts         = parts;
 }
예제 #32
0
        public I3DTensor CreateTensor(IReadOnlyList <IMatrix> data)
        {
            var first = data.First();

            Debug.Assert(data.All(m => m.RowCount == first.RowCount && m.ColumnCount == first.ColumnCount));
            return(new Gpu3DTensor(this, first.RowCount, first.ColumnCount, data.Count, data.Select(m => m.Clone()).Cast <GpuMatrix>().ToList()));
        }
예제 #33
0
        public PersistenceRequest(Stream stream, int expectedStreamSequence, IReadOnlyList<UnpersistedEvent> events)
            : this(events)
        {
            Argument.RequiresNotNull(stream, nameof(stream));
            Argument.Requires(expectedStreamSequence >= 0 || expectedStreamSequence == ExpectedSequence.Any, nameof(expectedStreamSequence));
            Argument.Requires(events.All(e => e.Stream.Equals(stream)), nameof(events), $"All events must belong to the stream '{stream}'");

            this.Stream = stream;
            this.ExpectedStreamSequence = expectedStreamSequence;
            this.Events = events;
        }
            private void AugmentCompletionsBasedOnLinesBefore(IReadOnlyList<RobotsTxtLineSyntax> before, IList<Completion> completions)
            {
                // first line
                if (!before.Any())
                {
                    completions.Add(ToCompletion("User-agent"));
                }

                // right after User-agent
                else if (before.All(l => l.NameToken.Value.Equals("User-agent", StringComparison.InvariantCultureIgnoreCase)))
                {
                    completions.Add(ToCompletion("User-agent"));
                    completions.Add(ToCompletion("Allow"));
                    completions.Add(ToCompletion("Disallow"));
                    completions.Add(ToCompletion("Sitemap"));
                    completions.Add(ToCompletion("Host"));
                    completions.Add(ToCompletion("Crawl-delay"));
                }

                // any other case
                else
                {
                    completions.Add(ToCompletion("Allow"));
                    completions.Add(ToCompletion("Disallow"));
                    completions.Add(ToCompletion("Sitemap"));

                    if (!before.Any(l => l.NameToken.Value.Equals("Host", StringComparison.InvariantCultureIgnoreCase)))
                        completions.Add(ToCompletion("Host"));

                    if (!before.Any(l => l.NameToken.Value.Equals("Crawl-delay", StringComparison.InvariantCultureIgnoreCase)))
                        completions.Add(ToCompletion("Crawl-delay"));
                }
            }
예제 #35
0
        private void SetupWallSideActuators(IEnumerable<GrabableItemData> items, IReadOnlyList<ActuatorItemData> actuators)
        {
            if (actuators.Any())
            {
                CurrentGrabableItems = items;

                var factory = parser.TryMatchFactory(actuators, items.Any());
                if (factory != null)
                {
                    CurrentTile.SubItems.Add(factory.CreateItem(builder, CurrentTile, actuators));
                }
                else
                {
                    if(actuators.All(x => x.ActuatorType != 5 && x.ActuatorType != 6))
                    {
                        foreach (var i in actuators)
                        {
                            Point? absolutePosition = null;
                            if (i.ActionLocation is RemoteTarget)
                                absolutePosition = ((RemoteTarget) i.ActionLocation).Position.Position.ToAbsolutePosition(builder.CurrentMap);

                            CurrentTile.SubItems.Add(new Actuator(builder.GetWallPosition(i.TilePosition, CurrentTile), $"{absolutePosition} {i.DumpString()}"));
                        }
                    }
                    else
                    {
                        
                    }
                }
            }
        }
        public IReadOnlyList<IRange> Search(string currentText, IReadOnlyList<IRange> ranges)
        {
            Contract.Requires(currentText != null);
            Contract.Requires(ranges != null);
            Contract.Requires(ranges.All(range => range != null));

            if (Strategy == LookupStrategy.NONE || ranges.Count == 0 || currentText.Equals(OriginalText))
            {
                return ranges;
            }

            var regexSearchStr = new StringBuilder();

            var offset = 0;
            for(var i = 0;i < ranges.Count ; i++)
            {
                var range = ranges[i];
                var surface = OriginalText.Substring(range.Start, range.Length);

                if (offset != range.Start)
                {
                    if (range.Start - offset > 1)
                    {
                        regexSearchStr.Append(".*?");
                    }
                    regexSearchStr.Append("(?:");
                    regexSearchStr.Append(Regex.Escape(OriginalText.Substring(range.Start-1,1)));
                    if(offset == 0) {
                        regexSearchStr.Append("|\\A");
                    }
                    regexSearchStr.Append(")");
                }
                offset = range.End;

                regexSearchStr.Append("(" + Regex.Escape(surface) + ")");
            }

            Regex regex = new Regex(regexSearchStr.ToString(), RegexOptions.Multiline);

            var searchTextRange = OriginalText.Substring(0, Math.Min(OriginalText.Length, ranges[ranges.Count -1].End+1));
            var matchesBefore = regex.Matches(searchTextRange).Count;

            //Contract.Assert(matchesBefore >= 1);

            var currentMatches = regex.Matches(currentText);

            List<IRange> result = new List<IRange>();
            {
                var i = 0;
                foreach(System.Text.RegularExpressions.Match match in currentMatches){
                    i++;
                    if(i == Math.Min(matchesBefore, currentMatches.Count))
                    {
                        Contract.Assert(match.Groups.Count -1 == ranges.Count);
                        var r = -1;
                        foreach (Group group in match.Groups)
                        {
                            r++;
                            if (r == 0)
                            {
                                continue;
                            }
                            var range = ranges[r -1];
                            Contract.Assert(OriginalText.Substring(range.Start,range.Length).Equals(group.Value));

                            result.Add(new Range(group.Index, group.Index + group.Length));
                        }
                    }
                }
            }

            return result;
        }