Пример #1
0
 /// <summary>
 /// Remove process from blacklist
 /// </summary>
 public static void RemoveFromProcessBlacklist(IEnumerable <ProcessId> processes)
 {
     if (processBlacklist != null)
     {
         processBlacklist = Set.difference(processBlacklist, Set.createRange(processes.Map(p => p.Path).Distinct()));
     }
 }
Пример #2
0
        public IEnumerable <Overtech.ViewModels.Store.ScaleModel> ListByMaster(long masterId)
        {
            IEnumerable <Overtech.DataModels.Store.ScaleModel> dataModel = _scaleBrandService.ListScaleModels(masterId);
            IEnumerable <Overtech.ViewModels.Store.ScaleModel> viewModel = dataModel.Map <Overtech.DataModels.Store.ScaleModel, Overtech.ViewModels.Store.ScaleModel>();

            return(viewModel);
        }
Пример #3
0
        private static List <SubscriptionInfo> GetSubscriptionInfos(IRedisClient redis, IEnumerable <string> subIds)
        {
            var keys  = subIds.Map(x => RedisIndex.Subscription.Fmt(x));
            var infos = redis.GetValues <SubscriptionInfo>(keys);

            return(infos);
        }
Пример #4
0
        public IEnumerable <Overtech.ViewModels.Sale.SaleCustomer> ListAllByMaster(long masterId)
        {
            IEnumerable <Overtech.DataModels.Sale.SaleCustomer> dataModel = _salesService.ListSaleCustomers(masterId);
            IEnumerable <Overtech.ViewModels.Sale.SaleCustomer> viewModel = dataModel.Map <Overtech.DataModels.Sale.SaleCustomer, Overtech.ViewModels.Sale.SaleCustomer>();

            return(viewModel);
        }
Пример #5
0
        public DataSourceResult ListByMaster([System.Web.Http.ModelBinding.ModelBinder(typeof(WebApiDataSourceRequestModelBinder))] DataSourceRequest request, long masterId)
        {
            IEnumerable <Overtech.DataModels.Sale.SaleCustomer> dataModel = _salesService.ListSaleCustomers(masterId);
            IEnumerable <Overtech.ViewModels.Sale.SaleCustomer> viewModel = dataModel.Map <Overtech.DataModels.Sale.SaleCustomer, Overtech.ViewModels.Sale.SaleCustomer>();

            return(viewModel.ToDataSourceResult(request));
        }
        public static Validation <Hand> Create(IEnumerable <string> inputs)
        {
            var cardErrors = new List <Error>();

            var handToValidate = inputs
                                 .Map(Card.CreateValidCard)
                                 .Bind(v => v.Match(
                                           errors =>
            {
                cardErrors.AddRange(errors);
                return(None);
            },
                                           card => Some(card)))
                                 .Aggregate(new Hand(), (hand, card) =>
            {
                hand.Add(card);
                return(hand);
            });

            if (cardErrors.Any())
            {
                return(Invalid(cardErrors));
            }

            var validators = new List <Validator <Hand> > {
                MustHaveFiveCards, CannotHaveDuplicates
            };

            return(Validation.HarvestErrors(validators)(handToValidate).Match(
                       errors => Invalid(errors),
                       Valid));
        }
Пример #7
0
        public void MapShouldThrowExceptionForNullEnumerable()
        {
            // Fixture setup
            IEnumerable <int> enumerable = null;

            // Exercise system and verify outcome
            Assert.Throws <ArgumentNullException>(() => enumerable.Map(i => i.ToString()));
        }
Пример #8
0
        /// <summary>
        /// Inserts all elements in <paramref name="ts"/> at <paramref name="index"/>.
        /// </summary>
        /// <param name="index">The index where the new element shall be inserted.</param>
        /// <param name="ts">The collection of values to insert.</param>
        /// <exception cref="ArgumentOutOfRangeException"><c>index</c> is out of range.</exception>
        public RandomAccessSequence <T> InsertRangeAt(int index, IEnumerable <T> ts)
        {
            Requires.That.IsIndexInRange(this, index, "index").Check();
            var ftSplit = _ft.SplitAt(index);

            return(new RandomAccessSequence <T>(
                       ftSplit.Item1.AppendRange(ts.Map(x => new Element(x))) + ftSplit.Item2));
        }
Пример #9
0
        /// <summary>
        /// Returns a record of 2 immutable sequences where first sequence satisfies the predicate and second doesn't. Handles null sequence.
        /// </summary>
        public static Record <IImmutableList <T>, IImmutableList <T> > ConditionalSplit <T>(this IEnumerable <T> enumerable, Func <T, bool> predicate)
        {
            var collection = enumerable.Map();
            var left       = collection.Where(predicate).Map();
            var right      = collection.Where(i => !predicate(i)).Map();

            return(Record.Create(left, right));
        }
Пример #10
0
        public static void DeleteFiles(this IVirtualPathProvider pathProvider, IEnumerable<IVirtualFile> files)
        {
            var writableFs = pathProvider as IVirtualFiles;
            if (writableFs == null)
                throw new InvalidOperationException(ErrorNotWritable.Fmt(pathProvider.GetType().Name));

            writableFs.DeleteFiles(files.Map(x => x.VirtualPath));
        }
Пример #11
0
        // [ "my track 1", "my track 2", "track 3" ] -> [ "track" ]
        public static MutableStringHashSet FindCommonTokens(IEnumerable <string> strings)
        {
            var tokens       = strings.Map(SplitToTokens).ToList();
            var commonTokens = new MutableStringHashSet(tokens.Count == 0 ? Enumerable.Empty <string>() : tokens[0]);

            tokens.Skip(1).Iter(commonTokens.IntersectWith);
            return(commonTokens);
        }
Пример #12
0
 /// <summary>
 /// Executes specified operation on items from sequence and return successful Exc (represented by unit) if all operations are successful. Otherwise, return failure. Handles null enumerable
 /// </summary>
 public static Exc <Unit, E> ForEach <T, E>(this IEnumerable <T> enumerable, Action <T> operation) where E : Exception
 {
     return(Exc.Create <Unit, E>(_ =>
     {
         enumerable.Map().ToList().ForEach(operation);
         return Unit.Value;
     }));
 }
Пример #13
0
 public static bool ContainsAny_NullAware <T>(this IEnumerable <T> items, IEnumerable <T> expectedItems)
 {
     if (expectedItems == null)
     {
         return(false);
     }
     return(expectedItems.Map(items.Contains_NullAware).All(b => b));
 }
        public void Map_SourceIsEmpty_ThrowArgumentNullException()
        {
            //Act
            Action action = () => _sourceNull.Map(_ => { });

            //Assert
            action.Should().ThrowExactly <ArgumentNullException>();
        }
Пример #15
0
 public static void Map <T>(this IEnumerable <T> collection, Action <T> callback)
 {
     collection.Map <T>(item =>
     {
         callback.Invoke(item);
         return(MapResult.Success);
     });
 }
Пример #16
0
    public static async Task <IEnumerable <A> > Somes <A>(this IEnumerable <OptionAsync <A> > self)
    {
        var res = await self.Map(o => o.Data)
                  .WindowMap(identity)
                  .ConfigureAwait(false);

        return(res.Filter(x => x.IsSome).Map(x => x.Value).ToArray());
    }
        /// <summary>
        /// 新增修改充值赠送规则
        /// </summary>
        /// <param name="data"></param>
        /// <param name="rules"></param>
        /// <param name="products"></param>
        public static void SetRules(IEnumerable <RechargePresentRule> rules)
        {
            //  var data = Mapper.Map<IEnumerable<RechargePresentRule>, List<RechargePresentRuleInfo>>(rules);

            var data = rules.Map <List <RechargePresentRuleInfo> >();

            _iRechargePresentRuleService.SetRules(data);
        }
Пример #18
0
 /// <inheritdoc/>
 public async Task ProcessDiscoveryResultsAsync(string discovererId,
                                                DiscoveryResultModel result, IEnumerable <DiscoveryEventModel> events)
 {
     await _client.ProcessDiscoveryResultsAsync(discovererId,
                                                new DiscoveryResultListApiModel {
         Result = result.Map <DiscoveryResultApiModel>(),
         Events = events.Map <List <DiscoveryEventApiModel> >()
     });
 }
Пример #19
0
        public static string ToMessage(this IEnumerable <IdentityError> errors)
        {
            if (errors == null)
            {
                throw new ArgumentNullException(nameof(errors));
            }

            return(string.Join(" ,", errors.Map(e => $"Code: {e.Code} Message: {e.Description}")));
        }
Пример #20
0
 public Map <string, T> GetHashFields <T>(string key, IEnumerable <string> fields) =>
 Retry(() =>
       Db.HashGet(key, fields.Map(x => (RedisValue)x).ToArray())
       .Zip(fields)
       .Filter(x => !x.Item1.IsNullOrEmpty)
       .Fold(
           Map <string, T>(),
           (m, e) => m.Add(e.Item2, JsonConvert.DeserializeObject <T>(e.Item1)))
       .Filter(v => notnull <T>(v)));
Пример #21
0
        /// <summary>
        /// Pattern-matches on the sequence. Handles null sequence.
        /// </summary>
        public static R Match <T, R>(this IEnumerable <T> sequence, Func <Unit, R> ifEmpty, Func <T, IImmutableList <T>, R> ifNotEmpty)
        {
            var list = sequence.Map();

            return(list.Count.Match(
                       0, _ => ifEmpty(Unit.Value),
                       _ => ifNotEmpty(list.First(), list.Skip(1).Map())
                       ));
        }
Пример #22
0
        public void Map_ThrowsArgumentNullException_WhenSourceIsNull()
        {
            // Arrange
            IEnumerable <int> source = null;

            // Act
            // Assert
            Assert.Throws <ArgumentNullException>(() => source.Map(n => n + 1).Count());
        }
        internal string[] ConfigureHosts(IEnumerable<string> hosts)
        {
            if (hosts == null)
                return new string[0];

            return HostFilter == null
                ? hosts.ToArray()
                : hosts.Map(HostFilter).ToArray();
        }
Пример #24
0
        private void AddBindings(IEnumerable <IBinding> bindings)
        {
            bindings.Map(binding => this.bindings.Add(binding.Service, binding));

            lock (this.bindingCache)
            {
                this.bindingCache.Clear();
            }
        }
Пример #25
0
        /// <summary>
        /// Pattern-matches on the sequence. Handles null sequence.
        /// In case of more items, performs aggregation.
        /// </summary>
        public static R Match <T, R>(this IEnumerable <T> sequence, Func <Unit, R> ifEmpty, Func <T, R> ifSingle, Func <T, T, T> ifMultiple) where T : R
        {
            var list = sequence.Map();

            return(list.Count.Match(
                       0, _ => ifEmpty(Unit.Value),
                       1, _ => ifSingle(list.First()),
                       _ => list.Aggregate(ifMultiple)
                       ));
        }
Пример #26
0
        public void DeleteFiles(IEnumerable <string> virtualFilePaths)
        {
            var filePaths = virtualFilePaths.Map(x => {
                var filePath = SanitizePath(x);
                return(ResolveGistFileName(filePath) ?? filePath);
            });

            Gateway.DeleteGistFiles(GistId, filePaths.ToArray());
            ClearGist();
        }
Пример #27
0
        /// <summary>
        /// Pattern-matches on the sequence. Handles null sequence.
        /// </summary>
        public static R Match <T, R>(this IEnumerable <T> sequence, Func <Unit, R> ifEmpty, Func <T, R> ifSingle, Func <IImmutableList <T>, R> ifMultiple)
        {
            var list = sequence.Map();

            return(list.Count.Match(
                       0, _ => ifEmpty(Unit.Value),
                       1, _ => ifSingle(list.First()),
                       _ => ifMultiple(list)
                       ));
        }
Пример #28
0
        internal string[] ConfigureHosts(IEnumerable <string> hosts)
        {
            if (hosts == null)
            {
                return(TypeConstants.EmptyStringArray);
            }

            return(HostFilter == null
                ? hosts.ToArray()
                : hosts.Map(HostFilter).ToArray());
        }
Пример #29
0
 public static void ProcessClassRelationships(IEnumerable<OntologyClass> classes)
 {
     foreach (var ontCls in classes)
     {
         ontCls.IncomingRelationships = classes
             .Map(c => c.OutgoingRelationships.AsEnumerable())
             .Flatten()
             .Where(p => p.Range == ontCls.Name)
             .ToArray();
     }
 }
Пример #30
0
        internal string[] ConfigureHosts(IEnumerable <string> hosts)
        {
            if (hosts == null)
            {
                return(new string[0]);
            }

            return(HostFilter == null
                ? hosts.ToArray()
                : hosts.Map(HostFilter).ToArray());
        }
Пример #31
0
 public static void ProcessClassRelationships(IEnumerable <OntologyClass> classes)
 {
     foreach (OntologyClass ontCls in classes)
     {
         ontCls.IncomingRelationships = classes
                                        .Map(c => Enumerable.AsEnumerable <OntologyProperty>(c.OutgoingRelationships))
                                        .Flatten()
                                        .Where(p => p.Range == ontCls.Name)
                                        .ToArray();
     }
 }
Пример #32
0
        public void DeleteRelatedItems <T>(object hash, IEnumerable <object> ranges)
        {
            var table = DynamoMetadata.GetTable <T>();

            if (table.HashKey == null || table.RangeKey == null)
            {
                throw new ArgumentException($"Related table '{typeof(T).Name}' needs both a HashKey and RangeKey");
            }

            DeleteItems <T>(ranges.Map(range => new DynamoId(hash, range)));
        }
Пример #33
0
        /// <summary>
        /// Process blacklist
        /// Prevents javascript process access to server processes unless they're not on the blacklist
        /// NOTE: The blacklist and whitelist is an either/or situation, you must decide on whether to
        /// white or blacklist a set of processes.
        /// </summary>
        /// <param name="processes">Processes to add to the whitelist</param>
        public static void AddToProcessBlacklist(IEnumerable<ProcessId> processes)
        {
            lock (sync)
            {
                Set<string> set = Set.createRange(processes.Map(x => x.Path).Distinct());
                processBlacklist = processBlacklist == null
                    ? processBlacklist = set
                    : processBlacklist.Union(set);

                processWhitelist = null;
            }
        }
Пример #34
0
 /// <summary>
 /// Map only basic info available in table model
 /// </summary>
 /// <param name="actor"></param>
 /// <returns></returns>
 public static Model.Actor Map(this Table.Actor actor, 
     Table.Category mostPlayedCategory, IEnumerable<Table.Film> longestFilms, int filmCount)
 {
     return new Model.Actor {
     Id = actor.actor_id,
     FirstName = actor.first_name,
     LastName = actor.last_name,
     MostPLayedFilmCategory = mostPlayedCategory.Map(),
     FilmCount = filmCount,
     ThreeLongestFilms = longestFilms.Map()
     };
 }
Пример #35
0
        public RedisSentinel(IEnumerable<string> sentinelHosts, string masterName = null)
        {
            this.SentinelHosts = sentinelHosts != null
                ? sentinelHosts.Map(x => x.ToRedisEndpoint(defaultPort:RedisNativeClient.DefaultPortSentinel)).ToArray()
                : null;
            
            if (SentinelHosts == null || SentinelHosts.Length == 0)
                throw new ArgumentException("sentinels must have at least one entry");

            this.masterName = masterName ?? DefaultMasterName;
            IpAddressMap = new Dictionary<string, string>();
            RedisManagerFactory = (masters,slaves) => new PooledRedisClientManager(masters, slaves);
            ResetWhenObjectivelyDown = true;
            ResetWhenSubjectivelyDown = true;
            SentinelWorkerTimeout = TimeSpan.FromMilliseconds(100);
            WaitBetweenSentinelLookups = TimeSpan.FromMilliseconds(250);
            MaxWaitBetweenSentinelLookups = TimeSpan.FromSeconds(60);
        }
Пример #36
0
 private void WriteNonStaticTableSchema(string schema, string table, IEnumerable<string> columns) {
   myWriter.WriteLine("  public class {0}Table {{", myNameConverter.ConvertName(table));
   myWriter.WriteLine("    public readonly SqlColumn {0};",
                ", ".Join(columns.Map(x => myNameConverter.ConvertName(x))));
   myWriter.WriteLine("    public readonly ISqlTable Table;");
   myWriter.WriteLine();
   
   myWriter.WriteLine("    public {0}Table(string tableName) {{", myNameConverter.ConvertName(table));
   myWriter.WriteLine("      Table = new RealSqlTable(\"{0}\", tableName);", schema + "." + table);
   
   foreach (string column in columns) {
     myWriter.WriteLine("      {0} = new SqlColumn(\"{1}\", Table);",
                        myNameConverter.ConvertName(column), column);
   }
   
   myWriter.WriteLine("    }");
   
   myWriter.WriteLine("  }");
   myWriter.WriteLine();
 }
Пример #37
0
        private List<QuestionResult> ToQuestionResults(IEnumerable<Question> questions)
        {
            var uniqueUserIds = questions.Map(x => x.UserId).ToHashSet();
            var usersMap = GetUsersByIds(uniqueUserIds).ToDictionary(x => x.Id);

            var results = questions.Map(x => new QuestionResult { Question = x });
            var resultsMap = results.ToDictionary(q => q.Question.Id);

            results.ForEach(x => x.User = usersMap[x.Question.UserId]);

            //Batch multiple operations in a single pipelined transaction (i.e. for a single network request/response)
            RedisManager.ExecTrans(trans =>
            {
                foreach (var question in questions)
                {
                   var q = question;

                   trans.QueueCommand(r => r.GetSetCount(QuestionUserIndex.UpVotes(q.Id)),
                       voteUpCount => resultsMap[q.Id].VotesUpCount = voteUpCount);

                   trans.QueueCommand(r => r.GetSetCount(QuestionUserIndex.DownVotes(q.Id)),
                       voteDownCount => resultsMap[q.Id].VotesDownCount = voteDownCount);

                   trans.QueueCommand(r => r.As<Question>().GetRelatedEntitiesCount<Answer>(q.Id),
                       answersCount => resultsMap[q.Id].AnswersCount = answersCount);
                }
            });

            return results;
        }
 public void PivotizeTag (Tag tag, IEnumerable<int> postIds)
 {
     var relativeBinnedCxmlPath = tag.ComputeBinnedPath (".cxml");
     var absoluteBinnedCxmlPath = Path.Combine (_settings.AbsoluteOutputFolder, relativeBinnedCxmlPath);
     Directory.CreateDirectory (Path.GetDirectoryName (absoluteBinnedCxmlPath));
     using (var outputStream = absoluteBinnedCxmlPath.CreateWriteStream ())
     {
         var streamReaders = postIds.Map (postId =>
             {
                 var relativeBinnedXmlPath = Post.ComputeBinnedPath (postId, ".xml", _settings.FileNameIdFormat);
                 var absoluteBinnedXmlPath = Path.Combine (_settings.AbsoluteWorkingFolder, relativeBinnedXmlPath);
                 var sr = new StreamReader (absoluteBinnedXmlPath);
                 return sr;
             }
         );
         PivotizeTag (tag, streamReaders, outputStream);
     }
 }
Пример #39
0
 /// <summary>
 /// Remove process from blacklist
 /// </summary>
 public static void RemoveFromProcessBlacklist(IEnumerable<ProcessId> processes)
 {
     if (processBlacklist != null)
     {
         processBlacklist = Set.difference(processBlacklist, Set.createRange(processes.Map(p => p.Path).Distinct()));
     }
 }
        public static void DeleteFiles(this IVirtualPathProvider pathProvider, IEnumerable<IVirtualFile> files)
        {
            var writableFs = pathProvider as IVirtualFiles;
            if (writableFs == null)
                throw new InvalidOperationException(ErrorNotWritable.Fmt(pathProvider.GetType().Name));

            writableFs.DeleteFiles(files.Map(x => x.VirtualPath));
        }
        internal string[] ConfigureHosts(IEnumerable<string> hosts)
        {
            if (hosts == null)
                return TypeConstants.EmptyStringArray;

            return HostFilter == null
                ? hosts.ToArray()
                : hosts.Map(HostFilter).ToArray();
        }
Пример #42
0
 private static List<SubscriptionInfo> GetSubscriptionInfos(IRedisClient redis, IEnumerable<string> subIds)
 {
     var keys = subIds.Map(x => RedisIndex.Subscription.Fmt(x));
     var infos = redis.GetValues<SubscriptionInfo>(keys);
     return infos;
 }
Пример #43
0
 List<SkillEffect>[] GenSkillEffects(IEnumerable<Skill> ss)
 {
     var l = IENX.Init(x => new List<SkillEffect>(), Enum.GetNames(typeof(SkillTarget)).Length).ToArray();
     foreach (var i in ss.Map(x => x.Effects).Flatten().GroupBy(x => x.Target))
     {
         l[(int)i.Key].AddRange(i);
     }
     return l;
 }