public ActionResult Index(FormCollection formCollection)
        {
            var dossierId = Convert.ToInt32(formCollection["dossierId"]);

            var fields = fService.GetFieldsByDossier(dossierId);
            var list = new List<FieldInputz>();
            foreach (var field in fields)
            {
                var f = new FieldInputz();
                f.InjectFrom(field);
                decimal v;
                if (!decimal.TryParse(formCollection["c" + f.Id], out v))
                    f.ErrorMessage = "valoarea " + formCollection["c" + f.Id] + " nu este valida pentru acest camp";
                f.Value = v;
                list.Add(f);
            }

            if (list.Any(o => o.HasError))
            {
                ViewData["dossierId"] = dossierId;
                return View(list);
            }

            var fieldValues = list.AsParallel().Select(
                fieldInputz => new FieldValue { FieldId = fieldInputz.Id, Value = fieldInputz.Value, DossierId = dossierId }).ToList();

            dService.Init(fieldValues, dossierId);
            return View("success");
        }
Example #2
0
File: GHB.cs Project: Rarve/FRES
        protected List<string> GetUrlsFromPage(string pageUrl)
        {
            var urls = new List<string>();
            try
            {
                var html = Client.RetrieveHtmlStrGet(pageUrl).Result;
                urls = RegexHelper.GetMatchStr(html, @"(\/detail-)[0-9]{0,20}").Distinct().Select(x => URL_DTLS + x).ToList();

                var res = urls.AsParallel().WithDegreeOfParallelism(ParallismDegree).Select(x =>
                    new RealEstateE()
                    {
                        Url = x.Trim(),
                        State = 0,
                        RecordStatus = 1,
                        Source = SourceName
                    }
                ).ToList();

                DataHelper.InsertRealEstateE(res);
            }
            catch (Exception ex)
            {
                lock (sync)
                {
                    File.AppendAllText("D:/RE/A_" + this.GetType().Name + ".log", DateTime.Now.ToString("yyyyMMdd HH:mm") + "," + pageUrl + "," + ex.GetBaseException().Message + "\r\n");
                }
            }
            return urls;
        }
Example #3
0
        /// <summary>
        /// To do. Create a clever search algorithm.
        /// </summary>
        /// <param name="Word"></param>
        /// <param name="Collection"></param>
        /// <returns></returns>
        public string GetSimilar(string Word, List<string> Collection)
        {
            if (Word.IsNullOrEmpty())
            {
                return Word;
            }

            Dictionary<string, int> keys = new Dictionary<string, int>();

            /*foreach (string s in words.Keys)
            {
                if (s.EndsWith(Word))
                {
                    keys.Add(s, s.Length);
                }
            }*/

            Collection.AsParallel().ForAll(s =>
            {
                if (s.EndsWith(Word))
                {
                    keys.Add(s, s.Length);
                }
            });

            if (!keys.Any() && Word.Length > 2)
            {
                return this.GetSimilar(Word.Substring(1), Collection);
            }

            string key = keys.OrderBy(val => val.Value).FirstOrDefault().Key;

            return key;
        }
Example #4
0
        public static void H()
        {
            Console.WriteLine("loading..");

            //init some stuff
            List<string> list = new List<string>();
            //  Stopwatch sw = new Stopwatch();
            Random r = new Random();
            double sum = 0;
            DateTime dt;
            for (int i = 0; i < 1000000; i++)
            {
                list.Add(r.Next(0, 999999).ToString());
            }

            //non parallel time
            Console.WriteLine("starting");

            dt = DateTime.Now;
            foreach (string f in list)
            {
                MD5(f);
            }
            Console.WriteLine($"non parallel time: {(DateTime.Now - dt).Seconds} seconds");

            //parallel
            sum = 0;
            dt = DateTime.Now;

               list.AsParallel().ForAll(str => MD5(str));

            Console.WriteLine($"parallel time:{ (DateTime.Now - dt).Seconds} seconds");

            Console.WriteLine("end");
        }
Example #5
0
File: Main.cs Project: danisein/Wox
        public static void IndexPrograms()
        {
            // todo why there is a lock??
            lock (lockObject)
            {
                var sources = DefaultProgramSources();
                if (_settings.ProgramSources != null &&
                    _settings.ProgramSources.Count(o => o.Enabled) > 0)
                {
                    sources.AddRange(_settings.ProgramSources);
                }

                _sources = sources.AsParallel()
                                  .Where(s => s.Enabled && SourceTypes.ContainsKey(s.Type))
                                  .Select(s =>
                                  {
                                      var sourceClass = SourceTypes[s.Type];
                                      var constructorInfo = sourceClass.GetConstructor(new[] { typeof(ProgramSource) });
                                      var programSource = constructorInfo?.Invoke(new object[] { s }) as IProgramSource;
                                      return programSource;
                                  })
                                  .Where(s => s != null).ToList();

                _programs = _sources.AsParallel()
                                    .SelectMany(s => s.LoadPrograms())
                                    // filter duplicate program
                                    .GroupBy(x => new { ExecutePath = x.Path, ExecuteName = x.ExecutableName })
                                    .Select(g => g.First())
                                    .ToList();

                _cache.Programs = _programs;
            }
        }
Example #6
0
        private void MoveFood(object sender, ElapsedEventArgs e)
        {
            this.Position = this.Position + this._direction * (40 - this._salts);

            List<Virus> clients = new List<Client>(this.Realm.Clients).OfType<Virus>().ToList();

            // Verifica se algum virus vai comer
            Virus virus = clients.AsParallel().FirstOrDefault(v => v.InsideClient(this.Position));
            if (virus != null)
            {
                virus.Score += this.Score;
                this.StopMove();
                this.Realm.RemoveFood(this);

                if (virus.Score > 200)
                    virus.Split(this._direction);

                if (this._time != null)
                    this._time.Stop();
            }
            else
            {
                if (this._salts++ > 10)
                    this._time.Stop();
            }
        }
Example #7
0
    static void Main(string[] args)
    {
        List<Student> list = new List<Student>()
        {
            new Student(){ ID=1, Name="jack", Age=20},
            new Student(){ ID=1, Name="mary", Age=25},
            new Student(){ ID=1, Name="joe", Age=29},
            new Student(){ ID=1, Name="Aaron", Age=25},
        };

        //这里我们会对age建立一组键值对
        var map = list.AsParallel().ToLookup(i => i.Age, count => 1);

        //化简统计
        var reduce = from IGrouping<int, int> singleMap
                     in map.AsParallel()
                     select new
                     {
                         Age = singleMap.Key,
                         Count = singleMap.Count()
                     };

        ///最后遍历
        reduce.ForAll(i =>
        {
            Console.WriteLine("当前Age={0}的人数有:{1}人", i.Age, i.Count);
        });
        Console.Read();
    }
Example #8
0
        /// <summary>
        /// Выполняет поиск 
        /// </summary>
        /// <param name="article"></param>
        /// <returns></returns>
        public IList<SearchResultItem> Search(string article)
        {
            // Список всех поставщиков
            var vendors = new List<IVendorSearcher>();

            // Формируем список поставщиков исходя из настроек
            var settingsRep = Locator.GetService<ISettingsRepository>();
            if (settingsRep.GetValue<bool>("search_autotrader"))
            {
                vendors.Add(new AutoTradeSearcher());
            }
            if (settingsRep.GetValue<bool>("search_mxgroup"))
            {
                vendors.Add(new MXGroupSearcher());
            }
            if (settingsRep.GetValue<bool>("search_berg"))
            {
                vendors.Add(new BergSearcher());
            }

            // Выбираем данные параллельно
            var fetched = vendors.AsParallel().Select(v => v.Search(article));

            // Формируем результат
            var result = new List<SearchResultItem>();
            foreach (var fetch in fetched)
            {
                result.AddRange(fetch.Where(r => r.Quantity != 0));
            }
            return result;
        }
 public IHttpActionResult Periodical(List<LabourPeriodical> periodicals)
 {
     periodicals.AsParallel().ForAll(x=>SmallQuoteEstimator.Australia.LabourEstimator.Periodical(x));
     return Ok(new
     {
         data = periodicals
     });
 }
 public static List<string> ParallelEncrypt(
     List<string> data,
     CancellationToken cancellationToken)
 {
     return data.AsParallel().WithCancellation(
         cancellationToken).Select(
             (item) => Encrypt(item)).ToList();
 }
Example #11
0
        public string Crack(List<string> plaintext, string target)
        {
            var targetBytes = HexHelper.StringToByteArray(target);
            ThreadLocal<MD5> md5 = new ThreadLocal<MD5>(() => MD5.Create());

            var match = plaintext.AsParallel().Where(p => ByteArrayCompare(targetBytes, md5.Value.ComputeHash(Encoding.Default.GetBytes(p)))).FirstOrDefault();
            return match;
        }
		public List<int> ForAll ()
		{
			var myData = new List<int> () { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

			var ints = new List<int> ();

			myData.AsParallel ().ForAll (x => ints.Add (x));

			return ints;
		}
		public List<int>  WithNatural ()
		{
			var myData = new List<int> () { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

			var data =
				(from value in myData.AsParallel ()
				 select value);

			return data.ToList ();
		}
        public IHttpActionResult Periodical(List<Periodical> periodicals, int weeks)
        {
            periodicals.AsParallel()
                .ForAll(periodical => SmallQuoteEstimator.Australia.PriceEstimator.PeriodicalPrice(periodical, weeks));

            return Ok(new
            {
                data = periodicals
            });
        }
        public IHttpActionResult Equipment(List<EquipmentSupply> equipments)
        {
            equipments.AsParallel()
                .ForAll(equipment => SmallQuoteEstimator.Australia.PriceEstimator.EquipmentPrice(equipment));

            return Ok(new
            {
                data = equipments
            });
        }
 public List<IisApplication> ScanDirectory(string directory)
 {
     #if ASYNC_TEST
     Thread.Sleep(TimeSpan.FromSeconds(2));
     #endif
     var apps = new List<DirectoryInfo>();
     AddWebAppDirs(directory, apps);
     var result = apps.AsParallel().Select(GetApplicationInfo).ToList();
     return result;
 }
        public static void ShowParallelLinq(List<string> data)
        {
            OrderedParallelQuery<string> parallelGroups = data.AsParallel().OrderBy(item => item);

            // Show the total count of items still
            // matches the original count
            //System.Diagnostics.Trace.Assert(
            //  data.Count == parallelGroups.Sum(
            //      item => item.Count()));

        }
Example #18
0
 private static long FindCommonAncestor(List<Person> population)
 {
     int populationCount = population.Count;
     var ancestors = ProduceAncestorIds(Ancestor.AncestorCount);
     return ancestors.AsParallel()
                     .Where(ancestor => population
                         .AsParallel()
                         .Where(person => person.Ancestors.Contains(ancestor))
                         .Count() == populationCount)
                     .DefaultIfEmpty(-1)
                     .First();
 }
Example #19
0
 /// <summary>
 /// ドメインサービスの起動。
 /// </summary>
 private async void StartupDomainService()
 {
     try {
         Hosts = new List<ServiceHost>();
         Disposable.Create(() =>
         {
             Hosts
                 .AsParallel()
                 .Where(a => a.State == CommunicationState.Opened)
                 .ForAll(a => a.Close());
         }).Add(Tasks);
         {
             Debug.WriteLine("## host setting start ##");
             var host = new ServiceHost(typeof(SignpostService), Const.ServiceUrl);
             host
                 .AddServiceEndpoint(typeof(ISignpostContext), new BasicHttpBinding(), "");
             Hosts.Add(host);
             Debug.WriteLine("## host setting end ##");
         }
         {
             Debug.WriteLine("## host setting start ##");
             var host = new ServiceHost(typeof(StaticContentsService), Const.BaseUri);
             host
                 .AddServiceEndpoint(typeof(IStaticContents), new WebHttpBinding(), "")
                 .Behaviors.Add(new WebHttpBehavior());
             Hosts.Add(host);
             Debug.WriteLine("## host setting end ##");
         }
         foreach (var h in Hosts) {
             Debug.WriteLine("## host[{0}] Open...");
             await h.OpenAsync();
             Debug.WriteLine("## host[{0}] Opened. Status={1}, SingletonInstance={2}",
                 h.BaseAddresses.FirstOrDefault(),
                 h.State, h.SingletonInstance);
         }
         FinLoad();
     }
     catch (AddressAccessDeniedException aadEx) {
         var buf = new StringBuilder();
         buf.AppendLine(aadEx.ToString());
         buf.AppendLine();
         buf.AppendLine("----* 以下のコマンドを管理権限で実行してください *----");
         buf.AppendLine(string.Format(
             "netsh http add urlacl url={0}://+:{1}/ user={2}",
             Const.BaseUri.Scheme, Const.BaseUri.Port, Environment.UserName));
         Debug.WriteLine(buf.ToString());
     }
     catch (Exception ex) {
         var buf = new StringBuilder();
         buf.AppendLine(ex.ToString());
         Debug.WriteLine(buf.ToString());
     }
 }
Example #20
0
 public void UnloadFiles(List<IFileInfo> fiels, string folder)
 {
     foreach (var fileInfo in fiels.AsParallel())
     {
         try
         {
             _filesRepository.GetFileToFolder(fileInfo, folder);
         }
         catch (Exception)
         {
         }
     }
 }
Example #21
0
 private void RunTest(string queueName, int messageCount, int queueCount, ILogProvider logProvider)
 {
     var tasks = new List<Task>(queueCount);
     for (var i = 0; i < queueCount; i++)
     {
         var producer = new ProducerShared();
         var task = new Task(() => producer.RunTest<PostgreSqlMessageQueueInit, FakeMessage>(queueName, ConnectionInfo.ConnectionString, false, messageCount,
             logProvider, Helpers.GenerateData, Helpers.NoVerification, true, false));
         tasks.Add(task); 
     }
     tasks.AsParallel().ForAll(x => x.Start());
     Task.WaitAll(tasks.ToArray());
 }
		public List<int> CancellationExtension ()
		{
			var cs = new CancellationTokenSource ();
			var myData = new List<int> () { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
			var data = myData.AsParallel ().
			           Select (x => PauseSelect (x)).
				WithCancellation (cs.Token);

			Thread.Sleep (1);
			cs.Cancel ();

			return data.ToList ();
		}
		public List<int>  CancellatioNatural ()
		{
			var cs = new CancellationTokenSource ();
			var myData = new List<int> () { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
			var data =
				(from Value in myData.AsParallel ().WithCancellation (cs.Token)
				 select PauseSelect (Value));

			Thread.Sleep (1);
			cs.Cancel ();

			return data.ToList ();
		}
        public static IEnumerable<Tuple<string, UniversalValue>> Distribution(this IList<UniversalValue> input, List<Tuple<UniversalValue, UniversalValue>> groups)
        {
            if (input == null)
                throw new ArgumentNullException("input");
            UniversalValue first = input.FirstOrDefault();
            double totalCount = input.Count();
            if (first == null)
                throw new Exception("Sequence contains no elements");
            if (first.Type != groups.First().Item1.Type)
                throw new Exception("Input type not equals to group type");

            switch (first.Type)
            {
                case UniversalValue.UniversalClassType.Numeric:
                    return groups.AsParallel().AsOrdered().Select(
                        g =>
                        new Tuple<string, UniversalValue>(("From " + g.Item1 + " to " + g.Item2).Replace(".",","),
                                                          new UniversalValue(
                                                              (input.Count(i => i.DoubleValue >= g.Item1.DoubleValue && i.DoubleValue < g.Item2.DoubleValue)
                                                              / totalCount)*100)));
                case UniversalValue.UniversalClassType.String:
                    return groups.AsParallel().AsOrdered().Select(
                        g =>
                        new Tuple<string, UniversalValue>(g.Item1.StringValue,
                                                          new UniversalValue(
                                                              (input.Count(i => i.StringValue == g.Item1.StringValue)
                                                              / totalCount) * 100)));
                case UniversalValue.UniversalClassType.TimeSpan:
                    return groups.AsParallel().AsOrdered().Select(
                        g =>
                            new Tuple<string, UniversalValue>(("From " + g.Item1 + " to " + g.Item2).Replace(".",","),
                                                          new UniversalValue(
                                                              (input.Count(i => i.TimespanValue >= g.Item1.TimespanValue && i.TimespanValue < g.Item2.TimespanValue)
                                                              / totalCount) * 100)));
                default:
                    throw new Exception("Percentile operarion not supported for " + first.Type);

            }
        }
        public void ShowParallelLinq(List<string> data)
        {
            ParallelQuery<IGrouping<char, string>> parallelGroups;
            parallelGroups =
                from text in data.AsParallel()
                orderby text
                group text by text[0];

            // Show the total count of items still
            // matches the original count
            //System.Diagnostics.Trace.Assert(
            //    data.Count == parallelGroups.Sum(
            //    item => item.Count()));
        }
Example #26
0
        /// <summary>
        /// Stops the specified workers.
        /// </summary>
        /// <param name="workers">The workers.</param>
        public void Stop(List<IWorker> workers)
        {
            Guard.NotNull(() => workers, workers);

            _waitForEventOrCancel.Set();
            _waitForEventOrCancel.Cancel();

            if (workers.Count == 0) return;

            //wait for workers to stop
            WaitForDelegate.Wait(() => workers.Any(r => r.Running), _configuration.TimeToWaitForWorkersToStop);
            if (workers.Any(r => r.Running))
            {
                workers.AsParallel().ForAll(w => w.AttemptToTerminate());
            }

            var alCancel = workers.Where(worker => worker.Running).ToList();

            //attempt to cancel workers if any are still running
            if (alCancel.Count > 0)
            {
                _cancelWorkSource.CancellationTokenSource.Cancel();
                WaitForDelegate.Wait(() => alCancel.Any(r => r.Running), _configuration.TimeToWaitForWorkersToCancel);
                if (alCancel.Any(r => r.Running))
                {
                    alCancel.AsParallel().ForAll(w => w.AttemptToTerminate());
                }
            }

            //force kill workers that are still running by aborting the thread, or waiting until work has completed
            var alForceTerminate = workers.Where(worker => worker.Running).ToList();
            if (alForceTerminate.Count > 0)
            {
                alForceTerminate.AsParallel().ForAll(w => w.TryForceTerminate());
            }

            //dispose workers - they are created by a factory, and must be disposed of
            foreach (var worker in workers)
            {
                try
                {
                    worker.Dispose();
                }
                catch (Exception e)
                {
                    _log.ErrorException("An error has occurred while disposing of a worker", e, null);
                }
            }
        }
Example #27
0
 public static void Pa()
 {
     Thread.Sleep(3000);
     List<string> names = new List<string>();
     names.Add("naynish"); names.Add("jay");
     names.Add("tripti"); names.Add("purab");
     Parallel.ForEach(names, Display);
     var result = from item in names.AsParallel()
                  select item;
     foreach (var item in result)
     {
         Console.WriteLine(item);
     }
     eve.Set();
 }
Example #28
0
        public static ParallelQuery<SteamApp> GetSteamApps()
        {
            var appIdsToRun = new List<int>();

            for (var i = MininumAppId; i < MaximumAppId; i++)
            {
                appIdsToRun.Add(i);
            }

            return appIdsToRun
                .AsParallel()
                .WithDegreeOfParallelism(MaximumCoresToOccupy)
                .Select(async appId => await GetSteamApp(appId))
                .Select(sa => sa.Result)
                .Where(sa => sa != null);
        }
Example #29
0
        static void Main(string[] args)
        {
            WorkItems = new BlockingCollection<WorkItem>();

            var consumers = new List<Consumer>();
            consumers.Add(new Consumer());
            consumers.Add(new Consumer());
            consumers.Add(new Consumer());

            Task.Factory.StartNew(() =>
            {
                consumers.AsParallel().ForAll(x => x.Consume());
            });

            new Producer().Produce();
        }
Example #30
0
        public static void SaveSiteMap(List<SiteMapItemDb> siteMapsInfo, string fileName)
        {
            var sitemapGenerator = new SitemapGenerator();
            var xmlDoc =
                sitemapGenerator.GenerateSiteMap(
                    siteMapsInfo.AsParallel().Select(s => new SitemapItem(s.Url, s.LastModified, s.ChangeFrequency)));

            using (var compressedFileStream = new FileStream(fileName, FileMode.Create))
            {
                using (GZipStream compressionStream = new GZipStream(compressedFileStream,
                    CompressionMode.Compress))
                {
                    xmlDoc.Save(compressionStream);
                }
            }
        }