コード例 #1
0
        public async Task TestTimingWheel()
        {
            var outputs = new Dictionary <string, DateTime>();

            // Ã뼶ʱ¼äÂÖ
            var timer = TimingWheelTimer.Build(TimeSpan.FromSeconds(1), 10);

            outputs.Add("00", DateTime.Now);

            timer.AddTask(TimeSpan.FromMilliseconds(5000), () => { outputs.Add("20", DateTime.Now); });
            timer.AddTask(TimeSpan.FromMilliseconds(2000), () => { outputs.Add("11", DateTime.Now); });

            timer.Start();

            timer.AddTask(TimeSpan.FromSeconds(12), () => { outputs.Add("30", DateTime.Now); });
            timer.AddTask(TimeSpan.FromSeconds(2), () => { outputs.Add("12", DateTime.Now); });

            await Task.Delay(TimeSpan.FromSeconds(15));

            timer.Stop();

            outputs.Add("99", DateTime.Now);

            Console.WriteLine(string.Join(Environment.NewLine, outputs.Select(o => $"{o.Key}, {o.Value:HH:mm:ss.ffff}")));

            Assert.AreEqual(6, outputs.Count);
            Assert.AreEqual(2, Calc(outputs.Skip(1).First().Value, outputs.First().Value));
            Assert.AreEqual(2, Calc(outputs.Skip(2).First().Value, outputs.First().Value));
            Assert.AreEqual(5, Calc(outputs.Skip(3).First().Value, outputs.First().Value));
            Assert.AreEqual(12, Calc(outputs.Skip(4).First().Value, outputs.First().Value));
        }
コード例 #2
0
        private static string WriteSimpleGetMethod(Dictionary <string, BlockInfo> blockFieldSetList, string tab, string classPrefix, string typeName)
        {
            if (blockFieldSetList.Count == 2)
            {
                var inBlock  = blockFieldSetList.First();
                var outBlock = blockFieldSetList.Skip(1).First();

                if (inBlock.Value.BlockType == BlockType.input && outBlock.Value.BlockType == BlockType.output)
                {
                    return(WriteInblockAndOutblock(inBlock, outBlock, tab, classPrefix, typeName));
                }
            }
            else if (blockFieldSetList.Count == 3)
            {
                var inBlock   = blockFieldSetList.First();
                var outBlock  = blockFieldSetList.Skip(1).First();
                var outBlocks = blockFieldSetList.Skip(2).First();

                if (inBlock.Value.BlockType == BlockType.input &&
                    (outBlock.Value.BlockType == BlockType.output && outBlock.Value.HasOccurs == false) &&
                    (outBlocks.Value.BlockType == BlockType.output && outBlocks.Value.HasOccurs == true))
                {
                    return(WriteInblockAndOutblock(inBlock, outBlocks, tab, classPrefix, typeName));
                }
            }

            return("");
        }
コード例 #3
0
    protected void LoadData(string bulan)
    {
        using (DataClassesDatabaseDataContext db = new DataClassesDatabaseDataContext())
        {
            HiddenFieldIDBulan.Value = bulan;
            LabelHeader.Text         = "PENYESUAIAN PRESENSI (" + new DateTime(DropDownListTahun.SelectedValue.ToInt(), bulan.ToInt(), 1).Date.ToString("MMMM").ToUpper() + ")";
            Dictionary <int, string[]> ListData = new Dictionary <int, string[]>();

            int JumlahHari = DateTime.DaysInMonth(int.Parse(DropDownListTahun.SelectedItem.Value), int.Parse(bulan));

            //CARI DI DATABASE
            var ListSchedulling = db.TBPenggunaLogKehadirans
                                  .Where(item =>
                                         item.IDPengguna == int.Parse(DropDownListPegawai.SelectedItem.Value) &&
                                         item.JamMasuk.Value.Year == new DateTime(DropDownListTahun.SelectedValue.ToInt(), bulan.ToInt(), 1).Year&&
                                         item.JamKeluar.Value.Month == new DateTime(DropDownListTahun.SelectedValue.ToInt(), bulan.ToInt(), 1).Month)
                                  .Select(item => new
            {
                Hari = item.JamMasuk.Value.Day,
                item.JamMasuk,
                item.JamKeluar,
                Keterangan = item.Keterangan
            });

            MultiView.Visible = true;
            MultiView.SetActiveView(ScheduleHarian);

            for (int i = 1; i <= JumlahHari; i++)
            {
                string[] dataSchedulling = new string[3];

                var Schedule = ListSchedulling.FirstOrDefault(item => item.Hari == i);

                if (Schedule != null)
                {
                    dataSchedulling[0] = Schedule.JamMasuk.Value.ToString("HH:mm");
                    dataSchedulling[1] = Schedule.JamKeluar.Value.ToString("HH:mm");
                    dataSchedulling[2] = Schedule.Keterangan;
                    ListData.Add(i, dataSchedulling);
                }
                else
                {
                    ListData.Add(i, dataSchedulling);
                }
            }

            RepeaterSchedule1.DataSource = ListData.Take(10);
            RepeaterSchedule1.DataBind();

            RepeaterSchedule2.DataSource = ListData.Skip(10).Take(10);
            RepeaterSchedule2.DataBind();

            RepeaterSchedule3.DataSource = ListData.Skip(20);
            RepeaterSchedule3.DataBind();
        }
    }
コード例 #4
0
        public override nint GetItemsCount(UICollectionView collectionView, nint section)
        {
            if (dictionary != null)
            {
                int count = dictionary.Skip((int)section).FirstOrDefault().Value.Count;
                return(count);
            }

            return(0);
        }
コード例 #5
0
        public static void DrawBarChart <TList>(this PaintEventArgs e, List <TList> list, Dictionary <string, Color> propertiesColors)
        {
            #region PrepareData
            Type           T                 = typeof(TList);
            PropertyInfo[] props             = propertiesColors.Skip(1).Select(name => T.GetProperty(name.Key)).ToArray();
            Color[]        colors            = propertiesColors.Skip(1).Select(item => item.Value).ToArray();
            PropertyInfo   columnNamePropery = T.GetProperty(propertiesColors.First().Key);
            //Растояние для колонок
            float columnWidth = DiagramArea.Width / list.Count;

            //Ареа для одного колумна
            RectangleF columnArea = new RectangleF(
                DiagramArea.X + Spacing,
                DiagramArea.Y,
                columnWidth - 2 * Spacing,
                DiagramArea.Height);
            //Ареа рисование тайтла колумна
            RectangleF columnTextArea = new RectangleF(
                DiagramArea.X + Spacing,
                DiagramArea.Y + DiagramArea.Height - Font.Height,
                columnWidth - 2 * Spacing,
                Font.Height);
            #endregion PrepareData
            #region DrawingData
            //Проход по всей коллекции значений
            list.ForEach(item =>
            {
                float valueHeight  = 0F;
                float filledHeight = 0F;
                //Проход по свойствам для отображения
                for (int i = 0; i < props.Count(); ++i)
                {
                    //Высота столбца для одного из полей
                    valueHeight = (float)Convert.ToDouble(props[i].GetValue(item)) * Scale;
                    //Отрисовка части колонки
                    e.Graphics.FillRectangle(new SolidBrush(colors[i]),
                                             columnArea.X,
                                             columnArea.Y + columnArea.Height - valueHeight - filledHeight,
                                             columnArea.Width,
                                             valueHeight
                                             );

                    filledHeight += valueHeight;
                }

                //Подпись колонки
                e.Graphics.DrawString(columnNamePropery.GetValue(item).ToString(), Font, Brush, columnTextArea, StringFormat);

                //Cмещение текста и колонки
                columnTextArea.X += columnWidth;
                columnArea.X     += columnWidth;
            });
            #endregion DrawingData
        }
コード例 #6
0
 public void CalculateRows(double alpha, double beta)
 {
     foreach (KeyValuePair <double, Row> pair in _data.Skip(2))
     {
         Row prevRow    = _data[pair.Key - 1];
         Row currentRow = pair.Value;
         CalculateSmoothed(prevRow, currentRow, alpha);
         CalculateTrend(prevRow, currentRow, beta);
         CalculateForecast(prevRow, currentRow);
         CalculateSquaredErrors(currentRow);
     }
 }
コード例 #7
0
        /// <summary>
        /// Update the binder >> not_reviewed tag for the documents
        /// </summary>
        /// <param name="reviewsetRecord"></param>
        private void UpdateTag(DocumentRecordCollection reviewsetRecord)
        {
            var indexManagerProxy = new IndexManagerProxy(reviewsetRecord.ReviewsetDetails.MatterId, reviewsetRecord.ReviewsetDetails.CollectionId);
            var documentList      = reviewsetRecord.DocumentTags.
                                    GroupBy(item => item.DocumentId).ToDictionary(group => group.Key, group => group.ToList());
            var tagsList = new Dictionary <string, KeyValuePair <string, string> >();

            // create key value pair for every document to be updated in Search Sub System
            foreach (var document in documentList)
            {
                var strTags = string.Join(",", document.Value.Where(x => x.Status == 1).
                                          Select(t => String.Format(EVSearchSyntax.TagValueFormat + "{0}", t.TagId)).ToArray());
                tagsList.Add(document.Key,
                             string.IsNullOrEmpty(strTags)
                                 ? new KeyValuePair <string, string>(EVSystemFields.Tag, string.Empty)
                                 : new KeyValuePair <string, string>(EVSystemFields.Tag, strTags));
            }

            const int batchSize      = 1000;
            var       processedCount = 0;

            while (processedCount != tagsList.Count)
            {
                Dictionary <string, KeyValuePair <string, string> > batchTags;
                if ((tagsList.Count - processedCount) < batchSize)
                {
                    batchTags       = tagsList.Skip(processedCount).Take(tagsList.Count - processedCount).ToDictionary(x => x.Key, x => x.Value);
                    processedCount += tagsList.Count - processedCount;
                }
                else
                {
                    batchTags       = tagsList.Skip(processedCount).Take(batchSize).ToDictionary(x => x.Key, x => x.Value);
                    processedCount += batchSize;
                }

                if (!batchTags.Any())
                {
                    continue;
                }

                var docs = batchTags.Select(doc => new DocumentBeo()
                {
                    Id     = doc.Key,
                    Fields = new Dictionary <string, string> {
                        { doc.Value.Key, doc.Value.Value }
                    }
                }).ToList();

                indexManagerProxy.BulkUpdateDocumentsAsync(docs);
            }
        }
コード例 #8
0
        /// <summary>
        /// 再帰処理用
        /// </summary>
        /// <param name="elements"></param>
        private static void writeMx(Dictionary <string, List <string> > dic, string line)
        {
            if (dic.Count == 1)
            {
                using (StreamWriter writer = new StreamWriter(OUTPATH, true, Encoding.GetEncoding("shift_jis")))
                {
                    int lc = 0;
                    foreach (var data in dic.Values.First())
                    {
                        var s = line + "".PadLeft(lc, '\t') + data;
                        writer.WriteLine(s);
                        lc++;
                    }
                }
            }
            else
            {
                //要素にあるcsvデータ毎に、さらにまだ掘る
                //Excel用に貼り付けしたいので、データが変わったらタブ区切りを仕込んでおく
                int loopCount = 0;
                foreach (var data in dic.Values.First())
                {
                    //貼り付けたいExcelが項目ごとに列を持っているので、出力項目の左右に必要数分tabを差し込んでいる。
                    string untilNow = line + "".PadLeft(loopCount, '\t') + data + "\t".PadLeft(dic.Values.First().Count - loopCount, '\t');
                    writeMx(dic.Skip(1).ToDictionary(p => p.Key, p => p.Value), untilNow);
                    loopCount++;

                    Console.Write("★");
                    Console.SetCursorPosition(0, Console.CursorTop);
                    Console.Write("☆");
                }
            }
        }
コード例 #9
0
        // TODO: HORRIBLE CODE, that did not port well, I will rewrite this in future parts
        void DrawCode(int x, int y, int nLines)
        {
            var lastIdx = mapAsm.Last().Key;

            if (!mapAsm.ContainsKey(nes.Cpu6502.Pc))
            {
                return;
            }
            var it_a   = mapAsm.Single(s => s.Key == nes.Cpu6502.Pc);
            int nLineY = (nLines >> 1) * 10 + y;

            if (it_a.Key != lastIdx)
            {
                DrawString(x, nLineY, it_a.Value, PixelColor.CYAN);

                foreach (var asm in mapAsm.Skip(mapAsm.Keys.ToList().IndexOf(it_a.Key) + 1).Take(10))
                {
                    nLineY += 10;
                    DrawString(x, nLineY, asm.Value);
                }
            }

            nLineY = (nLines >> 1) * 10 + y;
            if (it_a.Key != lastIdx)
            {
                foreach (var asm in mapAsm.Reverse().Skip(mapAsm.Keys.Reverse().ToList().IndexOf(it_a.Key) + 1).Take(10))
                {
                    nLineY -= 10;
                    DrawString(x, nLineY, asm.Value);
                }
            }
        }
コード例 #10
0
 private static int FindLowestIndentationLevel(Dictionary<int, int> levels)
 {
     var indentLevels = (levels.ContainsKey(0) && levels[0] == 0) ? levels.Skip(1) : levels;
     int lowestLevel = indentLevels.Aggregate(
         int.MaxValue, (current, level) => (level.Value < current) ? level.Value : current);
     return (lowestLevel == int.MaxValue) ? 0 : lowestLevel;
 }
コード例 #11
0
        private int DetectCategory(string[] keywords)
        {
            int categoryId = -1;

            // fill image category

            foreach (string keyword in keywords)
            {
                var category = this.childCategories.FirstOrDefault(kvp => kvp.Value.ToLower().Contains(keyword.ToLower()));

                if (this.childCategories.Contains(category))
                {
                    categoryId = category.Key;
                    break;
                }

                category = this.parentCategories.FirstOrDefault(kvp => kvp.Value.ToLower().Contains(keyword.ToLower()));
                if (this.parentCategories.Contains(category))
                {
                    categoryId = category.Key;
                    break;
                }
            }

            if (categoryId == -1)
            {
                // no categories match, get the random category
                Random rand = new Random();
                categoryId = parentCategories.Skip(rand.Next(parentCategories.Count)).First().Key;
            }

            return(categoryId);
        }
コード例 #12
0
ファイル: ModBusRtuClient.cs プロジェクト: illuillu/IoTClient
        /// <summary>
        /// 分批读取,默认按19个地址打包读取
        /// </summary>
        /// <param name="addresses">地址集合</param>
        /// <param name="batchNumber">批量读取数量</param>
        /// <returns></returns>
        public Result <Dictionary <string, object> > BatchRead(Dictionary <string, DataTypeEnum> addresses, int batchNumber = 19)
        {
            var result = new Result <Dictionary <string, object> >();

            result.Value = new Dictionary <string, object>();

            var batchCount = Math.Ceiling((float)addresses.Count / batchNumber);

            for (int i = 0; i < batchCount; i++)
            {
                var tempAddresses = addresses.Skip(i * batchNumber).Take(batchNumber).ToDictionary(t => t.Key, t => t.Value);
                var tempResult    = BatchRead(tempAddresses);
                if (tempResult.IsSucceed)
                {
                    foreach (var item in tempResult.Value)
                    {
                        result.Value.Add(item.Key, item.Value);
                    }
                }
                else
                {
                    result.IsSucceed = false;
                    result.Err       = tempResult.Err;
                }
            }
            return(result.EndTime());
        }
コード例 #13
0
 private static void SaveCurrentResults()
 {
     Console.Write("Выполняется сохранение данных:\r\n" +
                   "Словарь соответствий названий улиц... ");
     using (var writer = new StreamWriter(@"correspStreet.txt", true))
     {
         foreach (var correspStr in _correspondenceStreetNames.Skip(_correspStrCount))
         {
             writer.WriteLine($"{correspStr.Key};{correspStr.Value}");
         }
         _correspStrCount = _correspondenceStreetNames.Count;
     }
     Console.Write("Выполнено\r\nСловарь соответствий адресов...");
     using (var writer = new StreamWriter(@"correspAddr.txt", true))
     {
         foreach (var correspAddr in _correspondenceAddresses.Skip(_correspAddrCount))
         {
             writer.WriteLine($"{correspAddr.Key};{correspAddr.Value}");
         }
         _correspAddrCount = _correspondenceAddresses.Count;
     }
     Console.Write("Выполнено\r\nДанные в БД... ");
     _db.SaveChanges();
     Console.Write("Выполнено");
 }
コード例 #14
0
ファイル: ArtifactWikiBot.cs プロジェクト: ketura/Artificer
        private async Task UploadArticleBatchesAsync(Dictionary <string, string> articles)
        {
            List <Dictionary <string, string> > batches = new List <Dictionary <string, string> >();
            int batchCount = articles.Count() / BatchSize;

            if (articles.Count() % BatchSize != 0)
            {
                batchCount++;
            }
            for (int i = 1; i <= batchCount; i++)
            {
                int start = (i - 1) * BatchSize;
                batches.Add(new Dictionary <string, string>(articles.Skip(start).Take(BatchSize)));
            }

            int all   = batches.Count;
            int total = 0;

            foreach (var batch in batches)
            {
                await UploadArticlesAsync(batch);

                total++;
                Console.WriteLine($"{total} of {all} batches complete.");
            }
        }
コード例 #15
0
        public async Task ApiV3WCObject_GetVariationsToUpdate()
        {
            var skusQuantities = new Dictionary <string, int>
            {
                { Testsku, 21 },
                { "testsku2", 23 }
            };
            const int productIdNew       = 2;
            const int productIdExisting  = 1;
            var       variationsToUpdate = new Dictionary <ProductId, IEnumerable <QuantityUpdate> >
            {
                { new ProductId(productIdExisting),
                  new List <QuantityUpdate>() }
            };
            const string nonManagedSku = "testsku2";

            ApiV3WCObject.GetVariationsToUpdate(skusQuantities, await CollectVariationsByProductFromAllPagesAsync(nonManagedSku, 11), productIdNew, variationsToUpdate);

            Assert.AreEqual(productIdExisting, variationsToUpdate.First().Key.Id);
            var secondProduct = variationsToUpdate.Skip(1).First();

            Assert.AreEqual(1, secondProduct.Value.Count());
            var newVariation = secondProduct.Value.First();

            Assert.AreEqual(skusQuantities.First().Key, newVariation.Sku);
            Assert.AreEqual(skusQuantities.First().Value, newVariation.Quantity);
        }
コード例 #16
0
        public bool GetNextFromFolder(int batchSize)
        {
            var batchData = folderMapData.Skip(counter * batchSize).Take(batchSize).ToList();

            if (batchData.Count == 0)
            {
                return(false);
            }

            List <float> byteData  = new List <float>();
            List <byte>  labelData = new List <byte>();

            foreach (var item in batchData)
            {
                Bitmap bmp = new Bitmap(item.Key);
                byteData.AddRange(bmp.ParallelExtractCHW());

                for (int i = 1; i <= labels; i++)
                {
                    if (item.Value == i)
                    {
                        labelData.Add(1);
                    }
                    else
                    {
                        labelData.Add(0);
                    }
                }
            }

            CurrentX = Value.CreateBatch(features, byteData, GlobalParameters.Device);
            CurrentY = Value.CreateBatch(features, labelData.Select(b => (float)b).ToList(), GlobalParameters.Device);

            return(true);
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: pnowosie/GCJ
        private static void Main(string[] args)
        {
            int MAX = 50;

            GenerateP(MAX);

            var numbers = pali.Skip(1)
                          .SelectMany(p => p.Value)
                          .Where(p => !p.StartsWith("0"))
                          .Select(BigInteger.Parse)
                          .OrderBy(p => p)
                          .ToList();

            var T = int.Parse(io.ReadLine());

            foreach (var c in T.Times())
            {
                var l = io.ReadLine().Split();

                BigInteger A = BigInteger.Parse(l.First()),
                           B = BigInteger.Parse(l.Last());

                var Cnt = numbers.Select(p => p * p)
                          .SkipWhile(q => q < A)
                          .TakeWhile(q => q <= B)
                          .Count(IsP);

                io.WriteLine(c.MakeOutput(Cnt));
            }
        }
コード例 #18
0
        public static string ToDString <T>(this Dictionary <string, T> map)
        {
            var output =
                "[";

            if (map.Any())
            {
                var p = map.FirstOrDefault();

                if (int.TryParse(p.Key, out int key))
                {
                    output += p.Value;
                }
                else
                {
                    output += String.Format("{0}: {1}", p.Key, p.Value);
                }
            }
            foreach (var pair in map.Skip(1))
            {
                if (int.TryParse(pair.Key, out int key))
                {
                    output += "; " + pair.Value;
                }
                else
                {
                    output += String.Format("; {0}: {1}", pair.Key, pair.Value);
                }
            }

            output +=
                "]";

            return(output);
        }
コード例 #19
0
            public long totalweight()
            {
                long total = edges.Skip(1).Sum(v => v.Value.weight);

                Console.WriteLine("total weight" + total);
                return(total);
            }
コード例 #20
0
        public Entity ToEntity(Dictionary <string, object> jsEntity)
        {
            if (strategy.PrimaryIdAttribute == null)
            {
                var jsonEntity = new Entity(strategy.EntityLogicalName);

                foreach (var attribute in jsEntity)
                {
                    jsonEntity.Attributes[attribute.Key] = ConvertToCrm(attribute);
                }

                return(jsonEntity);
            }
            else
            {
                var idName = jsEntity.Keys.First();
                var id     = Guid.Parse((string)jsEntity[idName]);

                var jsonEntity = new Entity(strategy.EntityLogicalName, id)
                {
                    Attributes = { [strategy.PrimaryIdAttribute] = id }
                };

                foreach (var attribute in jsEntity.Skip(1))
                {
                    jsonEntity.Attributes[attribute.Key] = ConvertToCrm(attribute);
                }

                return(jsonEntity);
            }
        }
コード例 #21
0
ファイル: DateUtils.cs プロジェクト: leks4leks/PEold
        public static Dictionary <string, decimal> ConvertToQuarter(Dictionary <string, decimal> data, MainModel mainModel)
        {
            if (!mainModel.IsItQuarter && (mainModel.EndDate - mainModel.StartDate).Days < 365)
            {
                return(data);
            }
            var result = new Dictionary <string, decimal>();

            for (int i = 0; i < data.Count; i = i + 3)
            {
                var ttMon = mainModel.StartDate.Month;
                while ((int)QuarterEnum.I != ttMon &&
                       (int)QuarterEnum.II != ttMon &&
                       (int)QuarterEnum.III != ttMon &&
                       (int)QuarterEnum.IV != ttMon)
                {
                    ttMon--;
                }
                var quarter = string.Format("{0}, {1}", mainModel.StartDate.Month + i > 12
                    ? ((QuarterEnum)ttMon + i - 12)
                    : ((QuarterEnum)ttMon + i),
                                            mainModel.StartDate.Year + ((i + 3) / 12) - mainModel.TimeSpan);
                result.Add(quarter, data.Skip(i).Take((data.Count - i) < 3 ? data.Count - i : 3).Sum(j => j.Value));
            }

            return(result);
        }
        public async Task Get_Estimated_Expired_Funds_Calculates_ExpiredFunds()
        {
            var sut          = _moqer.Resolve <ExpiredFundsService>();
            var expiredFunds = _moqer.GetMock <IExpiredFunds>();

            IDictionary <CalendarPeriod, decimal> calledFundIn  = null;
            IDictionary <CalendarPeriod, decimal> calledFundOut = null;
            IDictionary <CalendarPeriod, decimal> calledExpired = null;
            int calledMonths = 0;

            expiredFunds.Setup(s => s.GetExpiringFunds(It.IsAny <IDictionary <CalendarPeriod, decimal> >(), It.IsAny <IDictionary <CalendarPeriod, decimal> >(), null, 24))
            .Callback <IDictionary <CalendarPeriod, decimal>, IDictionary <CalendarPeriod, decimal>, IDictionary <CalendarPeriod, decimal>, int>(
                (fundsIn, fundsOut, expired, months) =>
            {
                calledFundIn  = fundsIn;
                calledFundOut = fundsOut;
                calledExpired = expired;
                calledMonths  = months;
            });

            var expiringFunds = sut.GetExpiringFunds(_accountEstimationProjectionModels.AsReadOnly(), _netLevyTotals, _paymentTotals, ProjectionGenerationType.LevyDeclaration, new DateTime(2018, 09, 24));


            calledFundIn.ShouldAllBeEquivalentTo(_estimatedExpiredFundsIn);
            calledFundOut.ShouldAllBeEquivalentTo(_estimatedExpiredFundsOut.Skip(1));
            calledExpired.ShouldAllBeEquivalentTo(expiringFunds);
            calledMonths.Should().Be(24);
        }
コード例 #23
0
        public void Init(string ip)
        {
            try
            {
                GeoData geoData;
                lock (_data)
                {
                    if (_data.ContainsKey(ip))
                    {
                        geoData = _data[ip];
                    }
                    else
                    {
                        var provider = new Profit365.GeoIP.GeoLocationProvider();
                        _data[ip] = geoData = Newtonsoft.Json.JsonConvert.DeserializeObject <GeoData>(provider.GetLocationByIP(ip).raw);
                        if (_data.Count > 500)
                        {
                            _data = _data.Skip(100).Take(400).ToDictionary(x => x.Key, x => x.Value);
                        }
                    }
                }

                CountryCode  = geoData.CountryCode;
                CountryName  = geoData.CountryName;
                City         = geoData.City;
                Region       = geoData.Region;
                RegionName   = geoData.RegionName;
                Latitude     = geoData.Latitude;
                Longitude    = geoData.Longitude;
                TimeZone     = geoData.TimeZone;
                Organization = geoData.Organization;
                ISP          = geoData.ISP;
            }
            catch (Exception) {}
        }
コード例 #24
0
    public static void GetCodes(Dictionary <char, float> v, Dictionary <char, string> code)
    {
        int count = GetMinDifference(v);

        Dictionary <char, float> d1 = v.Take(count).ToDictionary(c => c.Key, c => c.Value);
        Dictionary <char, float> d2 = v.Skip(count).ToDictionary(c => c.Key, c => c.Value);

        foreach (KeyValuePair <char, float> b in d1)
        {
            code[b.Key] += '1';
        }

        foreach (KeyValuePair <char, float> b in d2)
        {
            code[b.Key] += '0';
        }

        if (d1.Count > 1)
        {
            GetCodes(d1, code);
        }

        if (d2.Count > 1)
        {
            GetCodes(d2, code);
        }
    }
コード例 #25
0
        public static Dictionary<string, decimal> ConvertToQuarter(Dictionary<string, decimal> data, MainModel mainModel)
        {
            if (!mainModel.IsItQuarter && (mainModel.EndDate - mainModel.StartDate).Days < 365)
            {
                return data;
            }
            var result = new Dictionary<string, decimal>();

            for (int i = 0; i < data.Count; i=i+3)
            {
                var ttMon = mainModel.StartDate.Month;
                while ((int)QuarterEnum.I != ttMon &&
                    (int)QuarterEnum.II != ttMon &&
                    (int)QuarterEnum.III != ttMon &&
                    (int)QuarterEnum.IV != ttMon)
                {
                    ttMon--;
                }
                var quarter = string.Format("{0}, {1}", mainModel.StartDate.Month + i > 12
                    ? ((QuarterEnum)ttMon + i - 12)
                    : ((QuarterEnum)ttMon + i),
                    mainModel.StartDate.Year + ((i + 3) / 12) - mainModel.TimeSpan);
                result.Add(quarter, data.Skip(i).Take((data.Count - i) < 3 ? data.Count - i : 3).Sum(j => j.Value));
            }

            return result;
        }
コード例 #26
0
ファイル: MediaPlayer.cs プロジェクト: mono-soc-2011/banshee
        public Playlist [] GetPlaylists(uint index, uint max_count, string order, bool reverse_order)
        {
            var playlist_sources = ServiceManager.SourceManager.FindSources <AbstractPlaylistSource> ();

            switch (order)
            {
            case "Alphabetical":
                playlist_sources = playlist_sources.OrderBy(p => p.Name);
                break;

            case "UserDefined":
                playlist_sources = playlist_sources.OrderBy(p => p.Order);
                break;
            }
            if (reverse_order)
            {
                playlist_sources = playlist_sources.Reverse();
            }

            var playlists = new List <Playlist> ();

            foreach (var pl in playlist_sources.Skip((int)index).Take((int)max_count))
            {
                playlists.Add(BuildPlaylistFromSource(pl));
            }
            return(playlists.ToArray());
        }
コード例 #27
0
        public BulkResponse Write(IOrganizationService service, Dictionary <string, OrganizationRequest> requestsToBeProcessed)
        {
            BulkResponse bulkWriteResponse = new BulkResponse();

            bulkWriteResponse.Responses = new List <BulkResponseItem>();

            int batchNumber           = 0;
            int recordsToProcessCount = requestsToBeProcessed.Count;

            while (recordsToProcessCount > _batchSize || recordsToProcessCount > 0)
            {
                Dictionary <string, OrganizationRequest> currentBatchOfRequests = requestsToBeProcessed.Skip(batchNumber * _batchSize).Take(_batchSize).ToDictionary(x => x.Key, x => x.Value);

                OrganizationRequestCollection orgReqs = new OrganizationRequestCollection();
                orgReqs.AddRange(currentBatchOfRequests.Values.ToList());

                ExecuteMultipleResponse response = ExecuteMultiple(service, orgReqs);

                List <BulkResponseItem> bulkResponses = ReadExecuteMultipleResponse(response, currentBatchOfRequests);
                bulkWriteResponse.Responses.AddRange(bulkResponses);
                bulkWriteResponse.HasErrors = response.IsFaulted;


                recordsToProcessCount = recordsToProcessCount - currentBatchOfRequests.Count;
                batchNumber++;
            }



            return(bulkWriteResponse);
        }
コード例 #28
0
        // EDSM flight log synchronization
        public static void syncFromStarMapService(DateTime?lastSync = null, IProgress <string> progress = null)
        {
            Logging.Info("Syncing from EDSM");

            try
            {
                Dictionary <string, StarMapLogInfo> systems  = StarMapService.Instance.getStarMapLog(lastSync);
                Dictionary <string, string>         comments = StarMapService.Instance.getStarMapComments();

                int total = systems.Count;
                int i     = 0;

                while (i < total)
                {
                    int batchSize = Math.Min(total, StarMapService.syncBatchSize);
                    syncEdsmLogBatch(systems.Skip(i).Take(batchSize).ToDictionary(x => x.Key, x => x.Value), comments);
                    i = i + batchSize;
                }
                Logging.Info("EDSM sync completed");
            }
            catch (EDSMException edsme)
            {
                Logging.Debug("EDSM error received: " + edsme.Message);
            }
            catch (ThreadAbortException e)
            {
                Logging.Debug("EDSM update stopped by user: " + e.Message);
            }
        }
コード例 #29
0
ファイル: OnePointMosaic.cs プロジェクト: kDanil/net-vips
        public string Execute(string[] args)
        {
            Image mosaicedImage = null;

            for (var i = 0; i < ImagesMarksDict.Count; i += 2)
            {
                var items = ImagesMarksDict.Skip(i).Take(2).ToList();

                var firstItem  = items[0];
                var secondItem = items[1];

                var image          = Image.NewFromFile(firstItem.Key);
                var secondaryImage = Image.NewFromFile(secondItem.Key);
                var horizontalPart = image.Mosaic(secondaryImage, Enums.Direction.Horizontal, firstItem.Value[0],
                                                  firstItem.Value[1], secondItem.Value[0], secondItem.Value[1]);

                if (mosaicedImage == null)
                {
                    mosaicedImage = horizontalPart;
                }
                else
                {
                    var verticalMarks = VerticalMarks.Skip(i - 2).Take(2).ToList();
                    mosaicedImage = mosaicedImage.Mosaic(horizontalPart, Enums.Direction.Vertical, verticalMarks[1][0],
                                                         verticalMarks[1][1], verticalMarks[0][0], verticalMarks[0][1]);
                }

                mosaicedImage = mosaicedImage.Globalbalance();
            }

            mosaicedImage.WriteToFile("1-pt-mosaic.jpg");

            return("See 1-pt-mosaic.jpg");
        }
コード例 #30
0
        public override Dictionary <long, WordData> GetFilteredEntities(Dictionary <long, WordData> dictionary)
        {
            var entitiesCountLimit = GetEntitiesCountLimit(dictionary.Count);

            return(dictionary.Skip(dictionary.Count - entitiesCountLimit)
                   .Take(entitiesCountLimit).ToDictionary(x => x.Key, y => y.Value));
        }
コード例 #31
0
        private void UpdateTransform()
        {
            var first  = _grabPoints.FirstOrDefault();
            var second = _grabPoints.Skip(1).FirstOrDefault();

            if (first.Key == null)
            {
                return;
            }
            if (second.Key == null)
            {
                UpdateTranslation(first.Key.Transform.position, first.Value);
            }
            else
            {
                var meanCurPos = (first.Key.Transform.position + second.Key.Transform.position) * 0.5f;
                var meanDstPos = (first.Value + second.Value) * 0.5f;
                UpdateTranslation(meanCurPos, meanDstPos);

                var worldDiff = first.Key.Transform.position - second.Key.Transform.position;
                var localDiff = first.Value - second.Value;

                UpdateRotation(meanDstPos, worldDiff, localDiff);
                UpdateScale(worldDiff, localDiff);
            }
        }
コード例 #32
0
        public static InlineKeyboardMarkup CreateInlineKeyboardButton(Dictionary <string, string> buttonList, int columns)
        {
            int rows = (int)Math.Ceiling(buttonList.Count / (double)columns);

            InlineKeyboardButton[][] buttons = new InlineKeyboardButton[rows][];

            for (int i = 0; i < buttons.Length; i++)
            {
                buttons[i] = buttonList
                             .Skip(i * columns)
                             .Take(columns)
                             .Select(direction =>
                {
                    if (direction.Value.CheckUrlValid())
                    {
                        return(InlineKeyboardButton.WithUrl(direction.Key, direction.Value));
                    }
                    else
                    {
                        return(InlineKeyboardButton.WithCallbackData(direction.Key, direction.Value));
                    }
                })
                             .ToArray();
            }
            return(new InlineKeyboardMarkup(buttons));
        }
コード例 #33
0
ファイル: LicensingSmasher.cs プロジェクト: CrustyJew/DirtBag
        public async Task<Dictionary<string, PostAnalysisResults>> Analyze( List<Post> posts ) {

            var toReturn = new Dictionary<string, PostAnalysisResults>();
            var youTubePosts = new Dictionary<string, List<Post>>();

            foreach ( var post in posts ) {
                toReturn.Add( post.Id, new PostAnalysisResults( post, ModuleEnum ) );
                var ytID = YouTubeHelpers.ExtractVideoId( post.Url.ToString() );

                if ( !string.IsNullOrEmpty( ytID ) ) {
                    if ( !youTubePosts.ContainsKey( ytID ) ) youTubePosts.Add( ytID, new List<Post>() );
                    youTubePosts[ytID].Add( post );
                }

            }
            var yt = new YouTubeService( new BaseClientService.Initializer { ApiKey = YouTubeAPIKey } );

            var req = yt.Videos.List( "snippet" );
            for ( var i = 0; i < youTubePosts.Keys.Count; i += 50 ) {
                var ids = youTubePosts.Keys.Skip( i ).Take( 50 );
                req.Id = string.Join( ",", ids );

                var ytScrape = ScrapeYouTube( youTubePosts.Skip( i ).Take( 50 ).ToDictionary( p => p.Key, p => p.Value ), toReturn );
                var response = await req.ExecuteAsync();

                foreach ( var vid in response.Items ) {
                    var redditPosts = youTubePosts[vid.Id];
                    //var scores = toReturn[post.Id].Scores;

                    var termMatches = TermMatching.Matches( vid.Snippet.Description ).Cast<Match>().Select( m => m.Value ).ToList();
                    termMatches.AddRange( TermMatching.Matches( vid.Snippet.Title ).Cast<Match>().Select( m => m.Value ).ToList().Distinct() );
                    if ( termMatches.Count > 0 ) {
                        foreach ( var post in redditPosts ) {
                            toReturn[post.Id].Scores.Add( new AnalysisScore( STRINGMATCH_SCORE * Settings.ScoreMultiplier, "YouTube video title or description has the following term(s): " + string.Join( ", ", termMatches ), "Match: " + string.Join( ", ", termMatches ), ModuleName, RemovalFlair ) );
                        }
                    }

                }
                await ytScrape;
            }

            return toReturn;
        }
コード例 #34
0
		public void AttachmentStorage_GetAttachmentsAfter(string requestedStorage)
		{
			const int ITEM_COUNT = 20;
			const int SKIP_INDEX = ITEM_COUNT / 4;
			using (var storage = NewTransactionalStorage(requestedStorage))
			{
				var inputData = new Dictionary<Etag, RavenJObject>();
				storage.Batch(
					mutator =>
					{
						int index = 0;
						for (int itemIndex = 0; itemIndex < ITEM_COUNT; itemIndex++)
						{
							var item = RavenJObject.FromObject(new { Name = "Bar_" + itemIndex, Key = "Foo_" + index });
							var dataStream = new MemoryStream();
							item.WriteTo(dataStream);
							// ReSharper disable once RedundantAssignment
							var newEtag = mutator.Attachments.AddAttachment("Foo_" + (index++), null, dataStream, new RavenJObject());
							inputData.Add(newEtag, item);
						}
					});

				var etagAfterSkip = inputData.Skip(SKIP_INDEX).First().Key;

				IList<AttachmentInformation> fetchedAttachmentInformation = null;

				storage.Batch(viewer => fetchedAttachmentInformation = viewer.Attachments.GetAttachmentsAfter(etagAfterSkip, ITEM_COUNT, 4096).ToList());

				Assert.NotNull(fetchedAttachmentInformation);

				//SKIP_INDEX + 1 is because Linq's Skip() fetches items >= than index, and GetAttachmentsAfter() fetches items > than index
				var relevantInputEtags = inputData.Skip(SKIP_INDEX + 1)
												  .Select(row => row.Key)
												  .ToHashSet();

				//verify that all relevant etags were fetched
				var relevantFetchedEtags = fetchedAttachmentInformation.Select(row => row.Etag);
				Assert.True(relevantInputEtags.SetEquals(relevantFetchedEtags));
			}
		}
コード例 #35
0
        public ResultCreazioneFile GetModello770(int idCondominio, int idAzienda, int anno, int? idFornitoreModello770, DateTime dataDichiarazione, int? numeroIscrizioneCaf, bool intermediarioDichiarazioneCondominio, bool enteDichiarante, PersonaDTO firmatarioDichiarazione, PersonaDTO intermediarioDichiarazione)
        {
            byte[] bytes = null;
            var message = string.Empty;
            const int progressivoInvioTelematico = 0;
            const int numeroInviiTelematici = 0;

            var numeroRecordB = 0;
            int numeroRecordD = 0;
            const int numeroRecordI = 0;

            StreamWriter sw = null;
            try
            {
                var fileName = Path.GetTempPath() + "\\" + Guid.NewGuid();
                if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
                    fileName = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.DataDirectory + "\\" + Guid.NewGuid();
                if (File.Exists(fileName))
                    File.Delete(fileName);

                var condominio = _daoFactory.GetCondominioDao().GetById(idCondominio, false);

                // =============================================================================================
                // Ritenute da inserire nel modello 770
                // =============================================================================================
                var ritenute = _ritenutaService.GetByCondominioAnno(idCondominio, idAzienda, anno);

                // -----------------------------------------------------------------
                // Raggruppamento per periodo riferimento, tributo, data versamento
                // -----------------------------------------------------------------
                var ritenutePerMese = from item in ritenute
                                      group item by item.GetPeriodoRiferimento(false) + "¥" + item.PagamentoRiferimento.ScadenzaRiferimento.SpesaRiferimento.FornitoreRiferimento.CodiceTributo + "¥" + item.GetDataVersamento().GetValueOrDefault().ToShortDateString() into itemPerMese
                                      select itemPerMese;

                // =============================================================================================
                // Creazione del file
                // =============================================================================================
                // calcolo eventuali importi versati in eccesso
                var importiVersatiInEccesso = ritenute.Where(item => item.Tipo == TipoVersamentoRitenutaEnum.Eccesso).Sum(item => item.Importo.GetValueOrDefault());

                using (sw = File.CreateText(fileName))
                {
                    var codiceFiscale = condominio.Azienda.CodiceFiscale;
                    if (intermediarioDichiarazione != null)
                        codiceFiscale = intermediarioDichiarazione.CodiceFiscale;
                    if (intermediarioDichiarazioneCondominio)
                        codiceFiscale = condominio.CodiceFiscale;

                    writeTestataA("77S", codiceFiscale, anno, progressivoInvioTelematico, numeroInviiTelematici, sw);
                    writeRowB(condominio, dataDichiarazione, importiVersatiInEccesso > 0, ritenute.Count > 0, idFornitoreModello770, numeroIscrizioneCaf, intermediarioDichiarazioneCondominio, enteDichiarante, firmatarioDichiarazione, intermediarioDichiarazione, sw);
                    numeroRecordB++;

                    // ---------------------------------------------------------------------
                    //  Scrittura quadro ST e SX
                    // ---------------------------------------------------------------------
                    var datiST = new Dictionary<string, DatiST>();
                    var index = 0;
                    var countRow = 0;
                    foreach (var itemGroup in ritenutePerMese)
                    {
                        countRow++;

                        // Nel calcolo dell'importo delle ritenute operate NON devono essere compresi gli importi versati in eccesso
                        // Nel calcolo dell'importo delle ritenute versate DEVONO essere compresi gli importi versati in eccesso
                        datiST.Add(itemGroup.Key, new DatiST(itemGroup.Sum(item => item.Importo.GetValueOrDefault()), itemGroup.Where(item => item.Tipo == TipoVersamentoRitenutaEnum.Normale).Sum(item => item.ImportoInteressi.GetValueOrDefault()), itemGroup.Where(item => item.Tipo == TipoVersamentoRitenutaEnum.Normale).Sum(item => item.ImportoSanzione.GetValueOrDefault()), itemGroup.Sum(item => item.ImportoConInteressi)));
                        if(countRow == 12)
                        {
                            index++;

                            // -------------------------------------------------------------------------------------------------------------------------
                            // Un solo record può contenere al massimo 10 elementi ST, i dati sono quindi suddivisi in gruppi di 10 - bugid#7872
                            // -------------------------------------------------------------------------------------------------------------------------
                            // Si precisa che qualora la tabella che costituisce la seconda parte del record di tipo “D” ed “I”
                            // non  fosse  sufficiente  ad  accogliere  tutti  i  dati  della 
                            // dichiarazione, sarà necessario predisporre un nuovo record dello stesso tipo. In generale, 
                            // la presenza di più di un record di tipo “D” ed “I”  all’interno di 
                            // una stessa dichiarazione può derivare da due possibili situazioni: 
                            //
                            //     i  dati  da  registrare  sono  in  numero  tale  da  non  poter  essere  interamente  contenuti 
                            //      nella tabella del record; in tal caso è necessario predisporre un nuovo record dello 
                            //      stesso  tipo  con  lo  stesso  valore  del  campo  “Progressivo  modulo”; 
                            //
                            //     i  dati  da  registrare  sono  relativi  a  più  prospetti  ST,  SV,  SX,  SY  caratterizzati  da 
                            //      differenti  valori  del  campo  posto  in  alto  a  destra    (“Mod.  N.”); in  questo  caso  è  necessario 
                            //      predisporre  più  record  caratterizzati  da  differenti  valori  del  “Progressivo  modulo”. 
                            // -------------------------------------------------------------------------------------------------------------------------

                            var countSameModule = Math.Ceiling(Convert.ToDecimal(countRow) / 10m);
                            for (var i = 0; i < countSameModule; i++)
                            {
                                writeRowD(condominio, index, i*10, datiST.Skip(i*10).Take(10), importiVersatiInEccesso, sw);
                                importiVersatiInEccesso = 0;
                                numeroRecordD++;
                            }

                            countRow = 0;
                            datiST.Clear();
                        }
                    }
                    if (datiST.Count > 0)
                    {
                        index++;
                        writeRowD(condominio, index, 0, datiST, importiVersatiInEccesso, sw);
                        importiVersatiInEccesso = 0;
                        numeroRecordD++;
                    }

                    writePiedeZ(numeroRecordB, numeroRecordD, numeroRecordI, sw);
                }

                var infile = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                bytes = new byte[infile.Length];
                infile.Read(bytes, 0, bytes.Length);

                return new ResultCreazioneFile(bytes, message);
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Errore inaspettato durante la creazione del file per il modello 770 - {0} - condominio:{1} - anno:{2}", ex, Library.Utility.GetMethodDescription(), idCondominio, anno);
                message = "Si sono verificati problemi inaspettati durante la generazione del modello 770." + Environment.NewLine + "Controllare il log per ulteriori dettagli.";
                return new ResultCreazioneFile(bytes, message);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                }
            }
        }
コード例 #36
0
		public void AttachmentStorage_GetAttachmentsAfter_With_TakeParameter_And_MaxSizeParameter(string requestedStorage)
		{
			var input = new List<dynamic>
			           {
				           new { SkipIndex = 5, Take = 10, MaxSize = 4096},
						   new { SkipIndex = 10, Take = 3, MaxSize = 4096},
						   new { SkipIndex = 6, Take = 15, MaxSize = 4096},
						   new { SkipIndex = 6, Take = 15, MaxSize = 256},
						   new { SkipIndex = 5, Take = 0, MaxSize = 4096},
						   new { SkipIndex = 5, Take = 15, MaxSize = 0},
						   new { SkipIndex = 0, Take = 15, MaxSize = 4096},
					   };

			foreach (var d in input)
			{
				var skipIndex = (int)d.SkipIndex;
				var take = (int)d.Take;
				var maxSize = (int)d.MaxSize;

				var itemCount = (skipIndex + take) * 3;
				using (var storage = NewTransactionalStorage(requestedStorage))
				{
					var inputData = new Dictionary<Etag, RavenJObject>();
					storage.Batch(
						mutator =>
						{
							int index = 0;
							for (int itemIndex = 0; itemIndex < itemCount; itemIndex++)
							{
								var item = RavenJObject.FromObject(new { Name = "Bar_" + itemIndex, Key = "Foo_" + index });
								var dataStream = new MemoryStream();
								item.WriteTo(dataStream);
								// ReSharper disable once RedundantAssignment
								var newEtag = mutator.Attachments.AddAttachment("Foo_" + (index++), null, dataStream, new RavenJObject());
								inputData.Add(newEtag, item);
							}
						});

					var etagAfterSkip = inputData.Skip(skipIndex).First().Key;

					IList<AttachmentInformation> fetchedAttachmentInformation = null;
					storage.Batch(viewer => fetchedAttachmentInformation = viewer.Attachments.GetAttachmentsAfter(etagAfterSkip, take, maxSize).ToList());

					if (maxSize == 0 || take == 0)
						Assert.Empty(fetchedAttachmentInformation);
					else
					{
						//skipIndex + 1 is because Linq's Skip() fetches items >= than index, and GetAttachmentsAfter() fetches items > than index
						var inputDataAfterSkip = inputData.Skip(skipIndex + 1)
							.Take(take)
							.ToDictionary(item => item.Key, item => item.Value);

						var filteredInputData = new Dictionary<Etag, RavenJObject>();
						//limit resulting data by accumulated size
						var totalSizeCounter = 0;
						storage.Batch(viewer =>
						{
							foreach (var item in inputDataAfterSkip)
							{
								var itemSize = viewer.Attachments.GetAttachment(item.Value.Value<string>("Key")).Size;
								totalSizeCounter += itemSize;

								if (totalSizeCounter >= maxSize) break;
								filteredInputData.Add(item.Key, item.Value);
							}
						});

						//verify that all relevant etags were fetched
						Assert.Empty(filteredInputData.Keys
							.Except(fetchedAttachmentInformation.Select(row => row.Etag)));
						Assert.Empty(fetchedAttachmentInformation.Select(row => row.Etag)
							.Except(filteredInputData.Keys));

						for (int itemIndex = skipIndex + 1, fetchedItemIndex = 0;
							itemIndex < skipIndex + 1 + ((filteredInputData.Count < take) ? filteredInputData.Count : take);
							itemIndex++, fetchedItemIndex++)
						{
							var fetchedItem = fetchedAttachmentInformation[fetchedItemIndex];
							Assert.Equal(fetchedItem.Key, filteredInputData[fetchedItem.Etag].Value<string>("Key"));
						}
					}
				}

			}
		}
コード例 #37
0
        public static void Put_RandomDelete_ByteArray(int cnt, int durationSec, bool speed, int payloadSizeMin, int payloadSizeMax, int deleteFreq, bool isParallel)
        {
            using (var pile = new DefaultPile())
              {
            pile.AllocMode = speed ? AllocationMode.FavorSpeed : AllocationMode.ReuseSpace;
            pile.Start();
            var startTime = DateTime.UtcNow;
            var tasks = new List<Task>();
            for (var t = 0; t < (isParallel ? (System.Environment.ProcessorCount - 1) : 1); t++)
              tasks.Add(Task.Factory.StartNew(() =>
            {
              var wlc = 0;
              while (true)
              {
                if ((DateTime.UtcNow - startTime).TotalSeconds >= durationSec) return;

                var dict = new Dictionary<int, CheckByteArray>();

                Console.WriteLine("Starting a batch of {0}".Args(cnt));
                for (int i = 0; i < cnt; i++)
                {
                  var payloadSize = NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(payloadSizeMin, payloadSizeMax);
                  var val = new byte[payloadSize];
                  val[0] = (byte)NFX.ExternalRandomGenerator.Instance.NextRandomInteger;
                  val[payloadSize - 1] = (byte)NFX.ExternalRandomGenerator.Instance.NextRandomInteger;

                  var ptr = pile.Put(val);

                  var element = new CheckByteArray(ptr, payloadSize - 1, val[0], val[payloadSize - 1]);
                  dict.Add(i, element);

                  if (dict.Count > 0 && i % deleteFreq == 0)
                  {
                    while (true)
                    {
                      var idx = i - NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, i);

                      CheckByteArray stored;
                      if (dict.TryGetValue(idx, out stored))
                      {
                        ptr = stored.Ptr;
                        pile.Delete(ptr);
                        dict.Remove(idx);
                        break;
                      }
                    }
                  }

                  if (dict.Count > 16 && NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, 100) > 98)
                  {
                    var toRead = NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(8, 64);
                    wlc++;
                    if (wlc % 125 == 0)
                      Console.WriteLine("Thread {0} is reading {1} elements, total {2}"
                        .Args(Thread.CurrentThread.ManagedThreadId, toRead, dict.Count));
                    for (var k = 0; k < toRead; k++)
                    {
                      var kvp = dict.Skip(NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, dict.Count - 1)).First();
                      var buf = pile.Get(kvp.Value.Ptr) as byte[];
                      Assert.AreEqual(kvp.Value.FirstByte, buf[0]);
                      Assert.AreEqual(kvp.Value.LastByte, buf[kvp.Value.IdxLast]);
                    }
                  }
                }

                Console.WriteLine("Thread {0} is doing final read of {1} elements".Args(Thread.CurrentThread.ManagedThreadId, dict.Count));
                foreach (var kvp in dict)
                {
                  var buf = pile.Get(kvp.Value.Ptr) as byte[];
                  Assert.AreEqual(kvp.Value.FirstByte, buf[0]);
                  Assert.AreEqual(kvp.Value.LastByte, buf[kvp.Value.IdxLast]);
                }
              }
            }, TaskCreationOptions.LongRunning));
            Task.WaitAll(tasks.ToArray());
              }
        }
コード例 #38
0
        /// <summary>
        /// Update the binder >> not_reviewed tag for the documents
        /// </summary>
        /// <param name="reviewsetRecord"></param>
        private void UpdateTag(DocumentRecordCollection reviewsetRecord)
        {
            var indexManagerProxy = new IndexManagerProxy(reviewsetRecord.ReviewsetDetails.MatterId, reviewsetRecord.ReviewsetDetails.CollectionId);
            var documentList = reviewsetRecord.DocumentTags.
                GroupBy(item => item.DocumentId).ToDictionary(group => group.Key, group => group.ToList());
            var tagsList = new Dictionary<string, KeyValuePair<string, string>>();

            // create key value pair for every document to be updated in Search Sub System
            foreach (var document in documentList)
            {
                var strTags = string.Join(",", document.Value.Where(x => x.Status == 1).
                    Select(t => String.Format(EVSearchSyntax.TagValueFormat + "{0}", t.TagId)).ToArray());
                tagsList.Add(document.Key,
                             string.IsNullOrEmpty(strTags)
                                 ? new KeyValuePair<string, string>(EVSystemFields.Tag, string.Empty)
                                 : new KeyValuePair<string, string>(EVSystemFields.Tag, strTags));
            }

            const int batchSize = 1000;
            var processedCount = 0;
            while (processedCount != tagsList.Count)
            {
                Dictionary<string, KeyValuePair<string, string>> batchTags;
                if ((tagsList.Count - processedCount) < batchSize)
                {
                    batchTags = tagsList.Skip(processedCount).Take(tagsList.Count - processedCount).ToDictionary(x => x.Key, x => x.Value);
                    processedCount += tagsList.Count - processedCount;
                }
                else
                {
                    batchTags = tagsList.Skip(processedCount).Take(batchSize).ToDictionary(x => x.Key, x => x.Value);
                    processedCount += batchSize;
                }

                if (!batchTags.Any()) continue;

                var docs = batchTags.Select(doc => new DocumentBeo()
                {
                    Id = doc.Key,
                    Fields = new Dictionary<string, string> { { doc.Value.Key, doc.Value.Value } }
                }).ToList();

                indexManagerProxy.BulkUpdateDocumentsAsync(docs);
            }
        }
コード例 #39
0
        public ActionResult Part_Agreement_Good_Page()
        {
            string provence = Request.Params["provence"];
            string city = Request.Params["city"];
            string price = Request.Params["price"];
            string gys = Request.Params["gys"];
            string id = Request.Params["id"];//商品类别id
            string type = Request.Params["type"];//品牌名称
            // string id = "665";
            // string type = "联想";
            int page = 1;
            if (!string.IsNullOrWhiteSpace(Request.Params["page"]))
            {
                int.TryParse(Request.Params["page"], out page);
            }
            var q = Query<商品>.Where(
                o => o.采购信息.参与协议采购 
                    && o.审核数据.审核状态 == 审核状态.审核通过 
                    && o.商品信息.品牌 != null
                    );

            IEnumerable<BsonValue> p_l = null;
            var q_gys = Query.Null;
            if (!string.IsNullOrEmpty(gys))//根据所有条件查找或根据名称查找
            {
                q_gys = q_gys.And(Query<供应商>.Matches(o => o.企业基本信息.企业名称, gys));
            }

            if (!string.IsNullOrEmpty(provence) && provence != "不限省份")//根据省份查找
            {
                
                q_gys = q_gys.And(Query<供应商>.Where(o=>o.供应商用户信息.协议供应商所属地区.Any(p=>p.省份.Contains(provence))));
                if (!string.IsNullOrEmpty(city) && city != "不限城市")//根据城市查找
                {
                    q_gys = q_gys.And(Query<供应商>.Where(o=>o.供应商用户信息.协议供应商所属地区.Any(p=>p.城市.Contains(city))));
                }
            }
            if (q_gys != null)
            { 
                p_l = 用户管理.列表用户<供应商>(0, 0,
                    Fields<供应商>.Include(o => o.Id),
                    Query<供应商>.EQ(o => o.审核数据.审核状态, 审核状态.审核通过).And(q_gys)
                    ).Select(o => o["_id"]);
            }
            if (!string.IsNullOrEmpty(price))//根据价格查找
            {
            }
            List<商品> good = null;
            if (p_l != null)
            {
                //good = 商品管理.查询分类下商品(long.Parse(id), 0, 0, q.And(Query<商品>.In(o => o.商品信息.所属供应商.用户ID, p_l)), false, SortBy.Ascending("销售信息.价格"));
                good = 商品管理.查询分类下商品(long.Parse(id), 0, 0, q.And(Query<商品>.In(o => o.商品信息.所属供应商.用户ID, p_l))).ToList();
                good.Sort((_1, _2) => _1.销售信息.价格 > _2.销售信息.价格?1:_1.销售信息.价格 < _2.销售信息.价格?-1:0);
            }
            else
            {
                //good = 商品管理.查询分类下商品(long.Parse(id), 0, 0, q, false, SortBy.Ascending("销售信息.价格"));
                good = 商品管理.查询分类下商品(long.Parse(id), 0, 0, q).ToList();
                good.Sort((_1, _2) => _1.销售信息.价格 > _2.销售信息.价格?1:_1.销售信息.价格 < _2.销售信息.价格?-1:0);
            }
            var listagree = new Dictionary<商品, List<string>>();
            
            foreach (var k in good)
            {
                var brand = k.商品信息.品牌 != null ? k.商品信息.品牌.ToLower().Replace(" ", "") : null;
                var t = string.IsNullOrWhiteSpace(type)
                    ? string.IsNullOrWhiteSpace(type)
                    : (!string.IsNullOrWhiteSpace(type) && brand == type);
                if (t)
                {
                    var gh = 商品管理.查询分类下商品(long.Parse(id), 0, 0, q.And(Query<商品>.Where(p => p.商品信息.型号!=null && p.商品信息.型号 == k.商品信息.型号))).ToList();
                    gh.Sort((_1, _2) => _1.销售信息.价格 > _2.销售信息.价格 ? 1 : _1.销售信息.价格 < _2.销售信息.价格 ? -1 : 0);

                    var min_Price = k.销售信息.价格.ToString();
                    var max_Price = k.销售信息.价格.ToString();
                    if (gh.Any())
                    {
                        min_Price = gh.First().销售信息.价格.ToString();
                        max_Price = gh.Last().销售信息.价格.ToString();
                    }
                    var li = new List<string>();
                    li.Add(min_Price);
                    li.Add(max_Price);
                    listagree.Add(k, li);
                }
            }
            long listcount = listagree.Count();
            long maxpagesize = Math.Max((listcount + PAGESIZE_AGREEGOOD - 1) / PAGESIZE_AGREEGOOD, 1);

            ViewData["currentPage"] = page;
            ViewData["pagecount"] = maxpagesize;
            ViewData["商品分类ID"] = id;
            int start_index = PAGESIZE_AGREEGOOD * (page - 1);

            ViewData["分类商品"] = listagree.Skip(start_index).Take(PAGESIZE_AGREEGOOD).ToList();
            return PartialView("Part_Agreement/Part_Agreement_Good_Page");
        }
コード例 #40
0
ファイル: Loader.cs プロジェクト: hooperk/Starship
        /// <summary>
        /// Load a starship form the old .sss format
        /// </summary>
        /// <param name="fs">Filestream open to active .sss file</param>
        /// <returns>Starship imported from old format</returns>
        /// <exception cref="FormatException">If string values stored in numeric fields</exception>
        /// <exception cref="ArgumentException">If non-standard classes listed</exception>
        public Starship LoadSSS(FileStream fs)
        {
            Dictionary<String, String> file = new Dictionary<string, string>();
            using (StreamReader sr = new StreamReader(fs))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    int pos = line.IndexOf(":");
                    if (pos > 0)
                    {
                        file.Add(line.Substring(0, pos), line.Substring(pos + 1, line.Length - pos - 1));
                    }
                }
            }
            Starship ship = new Starship();
            if (!(String.IsNullOrWhiteSpace(file["customhullname"]) || String.IsNullOrWhiteSpace(file["customhullspeed"]) || String.IsNullOrWhiteSpace(file["customhullman"])
                || String.IsNullOrWhiteSpace(file["customhulldet"]) || String.IsNullOrWhiteSpace(file["customhullint"]) || String.IsNullOrWhiteSpace(file["customhullarmour"])
                || String.IsNullOrWhiteSpace(file["customhullturret"]) || String.IsNullOrWhiteSpace(file["customhullspace"]) || String.IsNullOrWhiteSpace(file["customhullclass"])))
            {
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customhullsp"]))
                    sp = int.Parse(file["customhullsp"]);
                HullType type = HullType.None;
                switch (file["customhullclass"])
                {
                    case "Battle":
                        type = HullType.BattleCruiser;
                        break;
                    case "Grand":
                        type = HullType.GrandCruiser;
                        break;
                    default:
                        type = (HullType)Enum.Parse(typeof(HullType), file["customhullclass"]);
                        break;
                }
                int prow = 0;
                int port = 0;
                int starboard = 0;
                int aft = 0;
                int dorsal = 0;
                int keel = 0;
                for (int i = 1; i <= 6; i++)
                {
                    switch (file["customslot" + i])
                    {
                        case "Prow":
                            prow++;
                            break;
                        case "Port":
                            port++;
                            break;
                        case "Starboard":
                            starboard++;
                            break;
                        case "Dorsal":
                            dorsal++;
                            break;
                        case "Keel":
                            keel++;
                            break;
                        case "Aft":
                            aft++;
                            break;
                    }
                }
                Hulls.Add(new Hull(file["customhullname"], int.Parse(file["customhullspeed"]), int.Parse(file["customhullman"]), int.Parse(file["customhulldet"]), int.Parse(file["customhullint"]),
                    int.Parse(file["customhullarmour"]), int.Parse(file["customhullspace"]), sp, type, file["customhullspecial"], RuleBook.Custom, 0, int.Parse(file["customhullturret"]), prow, dorsal,
                    (port + starboard) / 2, keel, aft));

            }
            ship.Hull = Hulls.Where(x => x.Name.Equals(file["hull"], StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            HullType shipClass = HullType.None;
            if (ship.Hull != null)
                shipClass = ship.Hull.HullTypes;
            //now that ship class and hopefully hull is set, can add custom weapons, then other components custom components can have their hulltypes == shipClass
            for (int i = 1; i <= 6; i++)
            {
                //add each custom weapon - check for duplication
                if (!(String.IsNullOrWhiteSpace(file["customweapon" + i]) || String.IsNullOrWhiteSpace(file["customweapon" + i + "type"]) || String.IsNullOrWhiteSpace(file["customweapon" + i + "range"])))
                {
                    String name = file["customweapon" + i];
                    WeaponType type = WeaponType.Macrobattery;
                    switch (file["customweapon" + i + "type"])
                    {
                        case "Lance":
                            type = WeaponType.Lance;
                            break;
                        case "Landing Bays":
                            type = WeaponType.LandingBay;
                            break;
                        case "Torpedo Tubes":
                            type = WeaponType.TorpedoTube;
                            break;
                        case "Nova Cannon":
                            type = WeaponType.NovaCannon;
                            break;
                    }
                    WeaponSlot slots = WeaponSlot.Auxiliary;//just to be very certain not to have uninitialised
                    if (!String.IsNullOrWhiteSpace(file["customslot" + i]))
                    {
                        slots = (WeaponSlot)Enum.Parse(typeof(WeaponSlot), file["customslot" + i]);
                    }
                    else
                    {
                        switch (type)
                        {
                            case WeaponType.Macrobattery:
                                if (name.IndexOf("Broadside", StringComparison.OrdinalIgnoreCase) >= 0)//ignorecase search for broadside to apply broadside rules
                                    slots = WeaponSlot.Side;
                                else
                                    slots = WeaponSlot.All;
                                break;
                            case WeaponType.Lance:
                                slots = WeaponSlot.Lance;
                                break;
                            case WeaponType.LandingBay:
                                slots = WeaponSlot.Side;
                                break;
                            //case WeaponType.NovaCannon:
                            //    slots = WeaponSlot.Prow;
                            //    break;
                            //case WeaponType.TorpedoTube:
                            //    slots = WeaponSlot.Prow | WeaponSlot.Keel;
                            //    break;
                        }
                    }
                    int str = 0;
                    if (!String.IsNullOrWhiteSpace(file["customweapon" + i + "str"]))
                        str = int.Parse(file["customweapon" + i + "str"]);
                    DiceRoll damage = new DiceRoll(file["customweapon" + i + "dice"]);
                    if (!String.IsNullOrWhiteSpace(file["customweapon" + i + "damage"]))
                        damage += int.Parse(file["customweapon" + i + "damage"]);
                    int range = int.Parse(file["customweapon" + i + "range"]);
                    int crit = 0;
                    if (!String.IsNullOrWhiteSpace(file["customweapon" + i + "crit"]))
                        crit = int.Parse(file["customweapon" + i + "crit"]);
                    int space = 0;
                    if (!String.IsNullOrWhiteSpace(file["customweapon" + i + "space"]))
                        space = int.Parse(file["customweapon" + i + "space"]);
                    int sp = 0;
                    if (!String.IsNullOrWhiteSpace(file["customweapon" + i + "sp"]))
                        sp = int.Parse(file["customweapon" + i + "sp"]);
                    int power = 0;
                    if (!String.IsNullOrWhiteSpace(file["customweapon" + i + "power"]))
                        power = int.Parse(file["customweapon" + i + "power"]);
                    string special = file["customweapon" + i + "special"];
                    HullType weaponClass = HullType.All;
                    if (ship.Hull != null)
                        weaponClass = ship.Hull.HullTypes;
                    switch (type)
                    {
                        case WeaponType.TorpedoTube:
                            Weapons.Add(new TorpedoTubes(name, weaponClass, power, space, sp, str, 0, RuleBook.Custom, 0, special: special));
                            break;
                        case WeaponType.NovaCannon:
                            Weapons.Add(new NovaCannon(name, weaponClass, power, space, sp, damage, range, RuleBook.Custom, 0, special));
                            break;
                        case WeaponType.LandingBay:
                            Weapons.Add(new LandingBay(name, weaponClass, slots, power, space, sp, str, RuleBook.Custom, 0, special: special));
                            break;
                        default:
                            Weapons.Add(new Weapon(name, type, weaponClass, slots, power, space, sp, str, damage, crit, range, RuleBook.Custom, 0, special: special));
                            break;
                    }
                }
            }
            int length = ship.Weapons.Length;
            for (int i = 0; i < length; i++)
            {
                //add each weapon
                string name = file["weapon" + (length - i)];
                switch (name)
                {
                    case Old.BombardmentCannons:
                        name = Names.BombardmentCannons;
                        break;
                    case Old.JovianMissiles:
                        name = Names.JovianMissiles;
                        break;
                    case Old.LatheGravCulverin:
                        name = Names.LatheGravCulverin;
                        break;
                    case Old.MarsBroadsides:
                        name = Names.MarsBroadsides;
                        break;
                    case Old.MarsMacrocannons:
                        name = Names.MarsMacrocannons;
                        break;
                    case Old.MezoaLanceBattery:
                        name = Names.MezoaLanceBattery;
                        break;
                    case Old.MezoaLance:
                        name = Names.MezoaLance;
                        break;
                    case Old.RyzaPlasma:
                        name = Names.RyzaPlasma;
                        break;
                }
                Weapon weapon = Weapons.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (weapon != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrWhiteSpace(file["weapon" + (length - i) + "quality"]))
                        quality = (Quality)Enum.Parse(typeof(Quality), file["weapon" + (length - i) + "quality"]);
                    WeaponQuality wq = WeaponQuality.None;
                    //wxq1 & wxq2 for WeaponQuality, weapxmod for turbo
                    for (int j = 1; j <= 2; j++)
                    {
                        switch (file["w" + (length - i) + "q" + j])
                        {
                            case "Space":
                                wq |= WeaponQuality.Space;
                                break;
                            case "Range":
                                wq |= WeaponQuality.Range;
                                break;
                            case "Crit Rating":
                                wq |= WeaponQuality.Crit;
                                break;
                            case "Strength":
                                wq |= WeaponQuality.Strength;
                                break;
                            case "Damage":
                                wq |= WeaponQuality.Damage;
                                break;
                        }
                    }
                    Quality turbo = Quality.None;
                    if (!String.IsNullOrWhiteSpace(file["weap" + (length - i) + "mod"]))
                        turbo = (Quality)Enum.Parse(typeof(Quality), file["weap" + (length - i) + "mod"]);
                    if (quality != Quality.Common || turbo != Quality.None)
                        ship.Weapons[i] = new Weapon(weapon.Name, weapon.Type, weapon.HullTypes, weapon.Slots, weapon.RawPower, weapon.RawSpace, weapon.RawSP, weapon.RawStrength, weapon.RawDamage, weapon.RawCrit, weapon.RawRange,
                            weapon.Origin, weapon.PageNumber, quality, wq, weapon.RawSpecial, turbo, weapon.ComponentOrigin);
                    else
                        ship.Weapons[i] = weapon;
                }
            }
            if (!(String.IsNullOrWhiteSpace(file["customplasmaname"]) || String.IsNullOrWhiteSpace(file["customplasmapower"]) || String.IsNullOrWhiteSpace(file["customplasmaspace"])))
            {
                string name = file["customplasmaname"];
                int power = int.Parse(file["customplasmapower"]);
                int space = int.Parse(file["customplasmaspace"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customplasmasp"]))
                {
                    sp = int.Parse(file["customplasmasp"]);
                }
                string special = file["customplasmaspecial"];
                PlasmaDrives.Add(new PlasmaDrive(name, shipClass, power, space, special, RuleBook.Custom, 0, sp));
            }
            if (!(String.IsNullOrWhiteSpace(file["customwarpname"]) || String.IsNullOrWhiteSpace(file["customwarppower"]) || String.IsNullOrWhiteSpace(file["customwarpspace"])))
            {
                string name = file["customwarpname"];
                int power = int.Parse(file["customwarppower"]);
                int space = int.Parse(file["customwarpspace"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customwarpsp"]))
                {
                    sp = int.Parse(file["customwarpsp"]);
                }
                string special = file["customwarpspecial"];
                WarpDrives.Add(new WarpDrive(name, shipClass, power, space, RuleBook.Custom, 0, sp, special));
            }
            if (!(String.IsNullOrWhiteSpace(file["customgellarname"]) || String.IsNullOrWhiteSpace(file["customgellarpower"])))
            {
                string name = file["customgellarname"];
                int power = int.Parse(file["customgellarpower"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customgellarsp"]))
                {
                    sp = int.Parse(file["customgellarsp"]);
                }
                string special = file["customgellarspecial"];
                GellarFields.Add(new GellarField(name, shipClass, power, special, RuleBook.Custom, 0, sp));
            }
            bool shieldsDone = false;//if a custom shield was used, don't count the custom shields twice
            if (!(String.IsNullOrWhiteSpace(file["customvoidname"]) || String.IsNullOrWhiteSpace(file["customvoidpower"])
                || String.IsNullOrWhiteSpace(file["customvoidspace"])))
            {
                string name = file["customvoidname"];
                int power = int.Parse(file["customvoidpower"]);
                int space = int.Parse(file["customvoidspace"]);
                int sp = 0;
                int str = 0;
                if(!String.IsNullOrWhiteSpace(file["customshield"]))
                    int.Parse(file["customshield"]);
                if (!String.IsNullOrWhiteSpace(file["customvoidsp"]))
                {
                    sp = int.Parse(file["customvoidsp"]);
                }
                string special = file["customvoidspecial"];
                VoidShields.Add(new VoidShield(name, shipClass, power, space, str, RuleBook.Custom, 0, special, sp: sp));
                shieldsDone = true;
            }
            if (!(String.IsNullOrWhiteSpace(file["custombridgename"]) || String.IsNullOrWhiteSpace(file["custombridgepower"]) || String.IsNullOrWhiteSpace(file["custombridgespace"])))
            {
                string name = file["custombridgename"];
                int power = int.Parse(file["custombridgepower"]);
                int space = int.Parse(file["custombridgespace"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["custombridgesp"]))
                {
                    sp = int.Parse(file["custombridgesp"]);
                }
                string special = file["custombridgespecial"];
                Bridges.Add(new Bridge(name, shipClass, power, space, RuleBook.Custom, 0, special, sp));
            }
            if (!(String.IsNullOrWhiteSpace(file["customlifename"]) || String.IsNullOrWhiteSpace(file["customlifepower"]) || String.IsNullOrWhiteSpace(file["customlifespace"])))
            {
                string name = file["customlifename"];
                int power = int.Parse(file["customlifepower"]);
                int space = int.Parse(file["customlifespace"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customlifesp"]))
                {
                    sp = int.Parse(file["customlifesp"]);
                }
                string special = file["customlifespecial"];
                LifeSustainers.Add(new LifeSustainer(name, shipClass, power, space, 0, RuleBook.Custom, 0, special, sp: sp));
            }
            if (!(String.IsNullOrWhiteSpace(file["customcrewname"]) || String.IsNullOrWhiteSpace(file["customcrewpower"]) || String.IsNullOrWhiteSpace(file["customcrewspace"])))
            {
                string name = file["customcrewname"];
                int power = int.Parse(file["customcrewpower"]);
                int space = int.Parse(file["customcrewspace"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customcrewsp"]))
                {
                    sp = int.Parse(file["customcrewsp"]);
                }
                string special = file["customcrewspecial"];
                CrewQuarters.Add(new CrewQuarters(name, shipClass, power, space, 0, RuleBook.Custom, 0, special, sp: sp));
            }
            if (!(String.IsNullOrWhiteSpace(file["customaugurname"]) || String.IsNullOrWhiteSpace(file["customaugurpower"])))
            {
                string name = file["customaugurname"];
                int power = int.Parse(file["customaugurpower"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customaugursp"]))
                {
                    sp = int.Parse(file["customaugursp"]);
                }
                string special = file["customaugurspecial"];
                AugurArrays.Add(new Augur(name, power, RuleBook.Custom, 0, special: special, sp: sp));
            }
            if (!String.IsNullOrWhiteSpace(file["custommachine"]))
                ship.GMMachineSpirit = file["custommachine"];
            if (!String.IsNullOrWhiteSpace(file["customhistory"]))
                ship.GMShipHistory = file["customhistory"];
            if (!String.IsNullOrWhiteSpace(file["customspeed"]))
                ship.GMSpeed = int.Parse(file["customspeed"]);
            if (!String.IsNullOrWhiteSpace(file["customint"]))
                ship.GMHullIntegrity = int.Parse(file["customint"]);
            if (!String.IsNullOrWhiteSpace(file["customdet"]))
                ship.GMDetection = int.Parse(file["customdet"]);
            if (!String.IsNullOrWhiteSpace(file["customman"]))
                ship.GMManoeuvrability = int.Parse(file["customman"]);
            if (!String.IsNullOrWhiteSpace(file["customarmour"]))
                ship.GMArmour = int.Parse(file["customarmour"]);
            if (!String.IsNullOrWhiteSpace(file["customturret"]))
                ship.GMTurretRating = int.Parse(file["customturret"]);
            if (!String.IsNullOrWhiteSpace(file["custommorale"]))
                ship.GMMorale = int.Parse(file["custommorale"]);
            if (!String.IsNullOrWhiteSpace(file["customcrew"]))
                ship.GMCrewPopulation = int.Parse(file["customcrew"]);
            if (!(shieldsDone || String.IsNullOrWhiteSpace(file["customshield"])))
                ship.GMShields = int.Parse(file["customshield"]);
            ship.GMSpecial = file["customspecial"];
            //custom components as one blob
            if (!(String.IsNullOrWhiteSpace(file["customcomppower"]) && String.IsNullOrWhiteSpace(file["customcompgenerate"])))
            {
                bool doBoth = !(String.IsNullOrWhiteSpace(file["customcomppower"]) || String.IsNullOrWhiteSpace(file["customcompgenerate"]));//if both present, separate comps for generate
                if (doBoth)
                    ship.SupplementalComponents.Add(new Supplemental("Custom Generators", ship.Hull.HullTypes, int.Parse(file["customcompgenerate"]), 0, 0, RuleBook.Custom, 0, generated: true));
                bool usingPower = doBoth || !String.IsNullOrWhiteSpace(file["customcompgenerate"]);
                int space = 0;
                if (!String.IsNullOrWhiteSpace(file["customcompspace"]))
                    space = int.Parse(file["customcompspace"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customcompsp"]))
                    sp = int.Parse(file["customcompsp"]);
                ship.SupplementalComponents.Add(new Supplemental("Custom Components", ship.Hull.HullTypes, (usingPower ? int.Parse(file["customcomppower"]) : int.Parse(file["customcompgenerate"])), space, sp, RuleBook.Custom, 0, special: file["customcomponents"], generated: !usingPower));//account for power being used or generated, all added as one blob to be shown in special field
            }
            //essential components
            {//Plasmadrive
                string name = file["plasma"];
                PlasmaDrive plasma = null;
                HullType size = HullType.None;
                bool modified = false;
                name = name.Replace(" Pattern", "-Pattern");
                if (name.Equals(Old.SprintTrader))
                    name = Names.SprintTrader;
                if (name.Equals(Old.EscortDrive))
                    name = Names.EscortDrive;
                if (name.StartsWith("Modified "))
                {
                    modified = true;
                    name = name.Substring(9);
                }
                if (name.Equals(Old.Viperdrive))
                    name = Names.Viperdrive;
                if (name.StartsWith(Names.WarcruiserDrive))
                {
                    if (name.EndsWith("Large"))
                        size = HullType.CruiserPlus;
                    else
                        size = HullType.LightCruiser;
                    plasma = PlasmaDrives.Where(x => x.Name.Equals(Names.WarcruiserDrive) && x.HullTypes == size).FirstOrDefault();
                }
                else if (name.StartsWith(Names.MimicDrive))
                {
                    switch (name.Substring(Names.MimicDrive.Length))
                    {
                        case "Huge":
                            size = HullType.CruiserPlus;
                            break;
                        case "Large":
                            size = HullType.LightCruiser;
                            break;
                        case "Medium":
                            size = HullType.Raider | HullType.Frigate;
                            break;
                        case "Small":
                            size = HullType.Transport;
                            break;
                    }
                    plasma = PlasmaDrives.Where(x => x.Name.Equals(Names.MimicDrive) && x.HullTypes == size).FirstOrDefault();
                }
                else
                {
                    plasma = PlasmaDrives.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                }
                if (plasma != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["plasmaquality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["plasmaquality"]);
                        if (quality == Quality.Good)
                        {
                            switch (file["plasmachoice"])
                            {
                                case "Power":
                                    quality = Quality.Efficient;
                                    break;
                                case "Space":
                                    quality = Quality.Slim;
                                    break;
                            }
                        }
                    }
                    ship.PlasmaDrive = new PlasmaDrive(plasma.RawName, plasma.HullTypes, plasma.RawPower, plasma.RawSpace, plasma.RawSpecial, plasma.Origin, plasma.PageNumber, plasma.RawSP, quality, plasma.Speed, plasma.Manoeuvrability, plasma.ComponentOrigin, modified);
                }//Warp Drive
                WarpDrive warp = WarpDrives.Where(x => x.Name.Equals(file["warp"], StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (warp != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["warpquality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["warpquality"]);
                        if (quality == Quality.Good)
                        {
                            switch (file["warpchoice"])
                            {
                                case "Power":
                                    quality = Quality.Efficient;
                                    break;
                                case "Space":
                                    quality = Quality.Slim;
                                    break;
                            }
                        }
                    }
                    ship.WarpDrive = new WarpDrive(warp.Name, warp.HullTypes, warp.RawPower, warp.RawSpace, warp.Origin, warp.PageNumber, warp.RawSP, warp.RawSpecial, quality, warp.ComponentOrigin);
                }//Gellar Field
                GellarField gellar = GellarFields.Where(x => x.Name.Equals(file["gellar"], StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (gellar != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["gellarquality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["gellarquality"]);
                    }
                    ship.GellarField = new GellarField(gellar.Name, gellar.HullTypes, gellar.RawPower, gellar.RawSpecial, gellar.Origin, gellar.PageNumber, gellar.RawSP, gellar.NavigateWarp, quality, gellar.ComponentOrigin);
                }//Void shield
                name = file["void"];
                if (name.Equals(Old.RepulsorShield))
                    name = Names.RepulsorShield;
                VoidShield shield = VoidShields.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (shield != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["voidquality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["voidquality"]);
                        if (quality == Quality.Good)
                        {
                            switch (file["voidchoice"])
                            {
                                case "Power":
                                    quality = Quality.Efficient;
                                    break;
                                case "Space":
                                    quality = Quality.Slim;
                                    break;
                            }
                        }
                    }
                    ship.VoidShield = new VoidShield(shield.Name, shield.HullTypes, shield.RawPower, shield.RawSpace, shield.Strength, shield.Origin, shield.PageNumber, shield.RawSpecial, quality, shield.RawSP, shield.ComponentOrigin);
                }//Ship's Bridge
                name = file["bridge"];
                size = HullType.All;
                if (name.EndsWith(", Large"))
                {
                    size = HullType.AllCruiser;
                }
                else if (name.EndsWith(", Small"))
                {
                    size = ~HullType.AllCruiser;
                }
                Bridge bridge = Bridges.Where(x => name.StartsWith(x.Name, StringComparison.OrdinalIgnoreCase) && (x.HullTypes & size) != 0).FirstOrDefault();
                if (bridge != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["bridgequality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["bridgequality"]);
                        if (quality == Quality.Good)
                        {
                            switch (file["bridgechoice"])
                            {
                                case "Power":
                                    quality = Quality.Efficient;
                                    break;
                                case "Space":
                                    quality = Quality.Slim;
                                    break;
                            }
                        }
                    }
                    ship.ShipBridge = new Bridge(bridge.Name, bridge.HullTypes, bridge.RawPower, bridge.RawSpace, bridge.Origin, bridge.PageNumber, bridge.RawSpecial, bridge.RawSP, quality, bridge.Manoeuvrability, bridge.BSModifier, bridge.Command, bridge.Repair, bridge.Pilot, bridge.NavigateWarp, bridge.ComponentOrigin, bridge.MiningObjective, bridge.CreedObjective, bridge.MilitaryObjective, bridge.TradeObjective, bridge.CriminalObjective, bridge.ExplorationObjective);
                }//Life Sustainer
                name = file["life"];
                size = HullType.All;
                name = name.Replace("Vitae ", "Vitae-");
                if (name.EndsWith(", Large"))
                {
                    size = HullType.AllCruiser;
                }
                else if (name.EndsWith(", Small"))
                {
                    size = ~HullType.AllCruiser;
                }
                LifeSustainer sustainer = LifeSustainers.Where(x => name.StartsWith(x.Name, StringComparison.OrdinalIgnoreCase) && (x.HullTypes & size) != 0).FirstOrDefault();
                if (sustainer != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["lifequality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["lifequality"]);
                        if (quality == Quality.Good)
                        {
                            switch (file["lifechoice"])
                            {
                                case "Power":
                                    quality = Quality.Efficient;
                                    break;
                                case "Space":
                                    quality = Quality.Slim;
                                    break;
                            }
                        }
                    }
                    ship.LifeSustainer = new LifeSustainer(sustainer.Name, sustainer.HullTypes, sustainer.RawPower, sustainer.RawSpace, sustainer.Morale, sustainer.Origin, sustainer.PageNumber, sustainer.RawSpecial, quality, sustainer.RawSP, sustainer.MoraleLoss, sustainer.CrewLoss, sustainer.ComponentOrigin);
                }//crew quarters
                name = file["quarters"];
                size = HullType.All;
                if (name.EndsWith(", Large"))
                {
                    size = HullType.AllCruiser;
                }
                else if (name.EndsWith(", Small"))
                {
                    size = ~HullType.AllCruiser;
                }
                CrewQuarters quarters = CrewQuarters.Where(x => name.StartsWith(x.Name, StringComparison.OrdinalIgnoreCase) && (x.HullTypes & size) != 0).FirstOrDefault();
                if (quarters != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["quartersquality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["quartersquality"]);
                        if (quality == Quality.Good)
                        {
                            switch (file["quarterschoice"])
                            {
                                case "Power":
                                    quality = Quality.Efficient;
                                    break;
                                case "Space":
                                    quality = Quality.Slim;
                                    break;
                            }
                        }
                    }
                    ship.CrewQuarters = new CrewQuarters(quarters.Name, quarters.HullTypes, quarters.RawPower, quarters.RawSpace, quarters.Morale, quarters.Origin, quarters.PageNumber, quarters.RawSpecial, quality, quarters.RawSP, quarters.MoraleLoss, quarters.ComponentOrigin);
                }//Augur Arrays
                Augur arrays = AugurArrays.Where(x => x.Name.Equals(file["augur"], StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (arrays != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["augurquality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["augurquality"]);
                    }
                    ship.AugurArrays = new Augur(arrays.Name, arrays.RawPower, arrays.Origin, arrays.PageNumber, arrays.DetectionRating, arrays.RawSpecial, quality, arrays.RawSP, arrays.Manoeuvrability, arrays.BSModifier, arrays.MiningObjective, arrays.CreedObjective, arrays.MilitaryObjective, arrays.TradeObjective, arrays.CriminalObjective, arrays.ExplorationObjective, arrays.ComponentOrigin);
                }
            }//end of essential components
            switch (file["machine"])
            {
                case "A Nose For Trouble":
                    ship.MachineSpirit = MachineSpirit.ANoseForTrouble;
                    break;
                case "Blasphemous Tendencies":
                    ship.MachineSpirit = MachineSpirit.BlasphemousTendencies;
                    break;
                case "Martial Hubris":
                    ship.MachineSpirit = MachineSpirit.MartialHubris;
                    break;
                case "Rebellious":
                    ship.MachineSpirit = MachineSpirit.Rebellious;
                    break;
                case "Stoic":
                    ship.MachineSpirit = MachineSpirit.Stoic;
                    break;
                case "Skittish":
                    ship.MachineSpirit = MachineSpirit.Skittish;
                    break;
                case "Wrothful":
                    ship.MachineSpirit = MachineSpirit.Wrothful;
                    break;
                case "Resolute":
                    ship.MachineSpirit = MachineSpirit.Resolute;
                    break;
                case "Adventurous":
                    ship.MachineSpirit = MachineSpirit.Adventurous;
                    break;
                case "Ancient and Wise":
                    ship.MachineSpirit = MachineSpirit.AncientAndWise;
                    break;
            }
            switch (file["history"])
            {
                case "Reliquary of Mars":
                    ship.ShipHistory = ShipHistory.ReliquaryOfMars;
                    break;
                case "Haunted":
                    ship.ShipHistory = ShipHistory.Haunted;
                    break;
                case "Emissary of the Imperator":
                    ship.ShipHistory = ShipHistory.EmissaryOfTheImperator;
                    break;
                case "Wolf in Sheeps Clothing":
                    ship.ShipHistory = ShipHistory.WolfInSheepsClothing;
                    break;
                case "Turbulent Past":
                    ship.ShipHistory = ShipHistory.TurbulentPast;
                    break;
                case "Death Cult":
                    ship.ShipHistory = ShipHistory.DeathCult;
                    break;
                case "Wrested from a Space Hulk":
                    ship.ShipHistory = ShipHistory.WrestedFromASpaceHulk;
                    break;
                case "Temperamental Warp Engine":
                    ship.ShipHistory = ShipHistory.TemperamentalWarpEngine;
                    break;
                case "Finances in Arrears":
                    ship.ShipHistory = ShipHistory.FinancesInArrears;
                    break;
                case "Xenophilous":
                    ship.ShipHistory = ShipHistory.Xenophilous;
                    break;
            }
            if (!String.IsNullOrWhiteSpace(file["crew"]))
                ship.CrewRace = (Race)Enum.Parse(typeof(Race), file["crew"]);
            if (!String.IsNullOrWhiteSpace(file["crewrating"]))
            {
                CrewRating rating = 0;
                if (Enum.TryParse<CrewRating>(file["crewrating"], out rating))
                    ship.CrewRating = (int)rating;
                else
                    ship.CrewRating = (int)Enum.Parse(typeof(ServitorQuality), file["crewrating"]);
            }
            if (!String.IsNullOrWhiteSpace(file["crewmod"]))
                ship.GMCrewRating = int.Parse(file["crewmod"]);
            if (!String.IsNullOrWhiteSpace(file["arrestor"]))
                ship.ArresterEngines = (Quality)Enum.Parse(typeof(Quality), file["arrestor"]);
            if (!String.IsNullOrWhiteSpace(file["cherubim"]))
                ship.CherubimAerie = (Quality)Enum.Parse(typeof(Quality), file["cherubim"]);
            if (!String.IsNullOrWhiteSpace(file["improvements"]))
                ship.CrewImprovements = (Quality)Enum.Parse(typeof(Quality), file["imperovements"]);
            if (!String.IsNullOrWhiteSpace(file["disciplinarium"]))
                ship.Disciplinarium = (Quality)Enum.Parse(typeof(Quality), file["disciplinarium"]);
            if (!String.IsNullOrWhiteSpace(file["distribute"]))
                ship.DistributedCargoHold = (Quality)Enum.Parse(typeof(Quality), file["distributed"]);
            if (!String.IsNullOrWhiteSpace(file["mimic"]))
                ship.MimicDrive = (Quality)Enum.Parse(typeof(Quality), file["mimic"]);
            if (!String.IsNullOrWhiteSpace(file["ostentatious"]))
                ship.OstentatiousDisplayOfWealth = (Quality)Enum.Parse(typeof(Quality), file["ostentatious"]);
            if (!String.IsNullOrWhiteSpace(file["overload"]))
                ship.OverloadShieldCapacitors = (Quality)Enum.Parse(typeof(Quality), file["overload"]);
            if (!String.IsNullOrWhiteSpace(file["resolution"]))
                ship.ResolutionArena = (Quality)Enum.Parse(typeof(Quality), file["resolution"]);
            if (!String.IsNullOrWhiteSpace(file["secondary"]))
                ship.SecondaryReactor = (Quality)Enum.Parse(typeof(Quality), file["secondary"]);
            if (!String.IsNullOrWhiteSpace(file["starchart"]))
                ship.StarchartCollection = (Quality)Enum.Parse(typeof(Quality), file["starchart"]);
            if (!String.IsNullOrWhiteSpace(file["trooper"]))
                ship.StormTrooperDetachment = (Quality)Enum.Parse(typeof(Quality), file["trooper"]);
            if (!String.IsNullOrWhiteSpace(file["superior"]))
                ship.SuperiorDamageControl = (Quality)Enum.Parse(typeof(Quality), file["superior"]);
            if (!String.IsNullOrWhiteSpace(file["targeting"]))
                ship.TargettingMatrix = (Quality)Enum.Parse(typeof(Quality), file["targeting"]);
            if (!String.IsNullOrWhiteSpace(file["vaulted"]))
                ship.VaultedCeilings = (Quality)Enum.Parse(typeof(Quality), file["vaulted"]);
            switch (file["background"])
            {
                case "Thulian Explorator Vessel":
                    ship.Background = Background.ThulianExploratorVessel;
                    break;
                case "Reaver of the Unbeholden Reaches":
                    ship.Background = Background.ReaverOfTheUnbeholdenReaches;
                    break;
                case "Veteran of the Angevin Crusade":
                    ship.Background = Background.VeteranOfTheAngevinCrusade;
                    break;
                case "Implacable Foe of The Fleet":
                    ship.Background = Background.ImplacableFoeOfTheFleet;
                    break;
                case "Steadfast Ally of the Fleet":
                    ship.Background = Background.SteadfastAllyofTheFleet;
                    break;
                case "Planet-Bound for Millenia":
                    if (!String.IsNullOrWhiteSpace(file["hullloss"]))
                    {
                        byte loss = byte.Parse(file["hullloss"]);
                        ship.Background = (Background)loss;//and it to get number of hull lost
                    }
                    else
                        ship.Background = Background.PlanetBoundForMillenia;
                    break;
            }
            //supplemental components
            if (shipClass == HullType.None)
                shipClass = HullType.All;//if not set by a hull, now set assumed class to max
            foreach (KeyValuePair<String, String> pair in file.Skip(243))//supplemental components start after the first 243 entries
            {
                if (!String.IsNullOrWhiteSpace(pair.Value))
                {
                    String name = pair.Key.Replace("†","");
                    Quality quality = Quality.Common;
                    if (name.StartsWith("Poor Quality "))
                    {
                        name = name.Substring(13);
                        quality = Quality.Poor;
                    }
                    else if (name.StartsWith("Slim "))
                    {
                        name = name.Substring(5);
                        quality = Quality.Slim;
                    }
                    else if (name.StartsWith("Efficient "))
                    {
                        name = name.Substring(10);
                        quality = Quality.Efficient;
                    }
                    else if (name.StartsWith("Good Quality "))
                    {
                        name = name.Substring(13);
                        quality = Quality.Good;
                    }
                    else if (name.StartsWith("Best Quality"))
                    {
                        name = name.Substring(13);
                        quality = Quality.Best;
                    }
                    switch (name)
                    {
                        case Old.CogitatorInterlink:
                            name = Names.CogitatorInterlink;
                            break;
                        case Old.JammingSystem:
                            name = Names.JammingSystem;
                            break;
                    }
                    //check for all with same name, then get the largest one(ships capable of say cruiser and transport use cruiser size if that is what is available)
                    Supplemental component = Supplementals.Where(x => name.StartsWith(x.Name, StringComparison.OrdinalIgnoreCase)).OrderByDescending(x => x.HullTypes).FirstOrDefault();
                    int count = int.Parse(pair.Value);
                    if (component != null)
                    {
                        for (int i = 0; i < count; i++)
                            ship.SupplementalComponents.Add(new Supplemental(component.Name, component.HullTypes, component.RawPower, component.RawSpace, component.RawSP, component.Origin, component.PageNumber, component.RamDamage, component.RawSpecial, quality, component.Speed, component.Manoeuvrability, component.HullIntegrity, component.Armour, component.TurretRating, component.Morale, component.CrewPopulation, component.ProwArmour, component.CrewRating, component.MiningObjective, component.CreedObjective, component.MilitaryObjective, component.TradeObjective, component.CriminalObjective, component.ExplorationObjective, component.PowerGenerated, component.DetectionRating, component.AuxiliaryWeapon, component.MacrobatteryModifier, component.BSModifier, component.NavigateWarp, component.CrewLoss, component.MoraleLoss, component.ComponentOrigin, component.Replace, component.Max));
                    }
                }
            }
            return ship;
        }
コード例 #41
0
ファイル: FormSubmit.cs プロジェクト: JBTech/AngleSharp
        public async Task PostMulipartFormdataShouldEchoAllValuesCorrectly()
        {
            if (Helper.IsNetworkAvailable())
            {
                var fields = new Dictionary<String, String>
                {
                    { "myname", "foo" },
                    { "bar", "this is some longer text" },
                    { "yeti", "0" },
                };
                var result = await PostDocumentAsync(fields, MimeTypes.MultipartForm);
                var rows = result.QuerySelectorAll("tr");
                var raw = result.QuerySelector("#input").TextContent;

                Assert.AreEqual(3, rows.Length);

                Assert.AreEqual("myname", rows[0].QuerySelector("th").TextContent);
                Assert.AreEqual(fields["myname"], rows[0].QuerySelector("td").TextContent);

                Assert.AreEqual("bar", rows[1].QuerySelector("th").TextContent);
                Assert.AreEqual(fields["bar"], rows[1].QuerySelector("td").TextContent);

                Assert.AreEqual("yeti", rows[2].QuerySelector("th").TextContent);
                Assert.AreEqual(fields["yeti"], rows[2].QuerySelector("td").TextContent);

                var lines = raw.Split('\n');

                Assert.AreEqual(15, lines.Length);

                var emptyLines = new[] { 0, 3, 7, 11, 14 };
                var sameLines = new[] { 1, 5, 9 };
                var nameLines = new[] { 2, 6, 10 };
                var valueLines = new[] { 4, 8, 12 };

                foreach (var emptyLine in emptyLines)
                    Assert.AreEqual(String.Empty, lines[emptyLine]);

                for (int i = 1; i < sameLines.Length; i++)
                    Assert.AreEqual(lines[sameLines[0]], lines[sameLines[i]]);

                Assert.AreEqual(lines[sameLines[0]] + "--", lines[lines.Length - 2]);

                for (int i = 0; i < nameLines.Length; i++)
                {
                    var field = fields.Skip(i).First();
                    Assert.AreEqual("Content-Disposition: form-data; name=\"" + field.Key + "\"", lines[nameLines[i]]);
                    Assert.AreEqual(field.Value, lines[valueLines[i]]);
                }
            }
        }
コード例 #42
0
        public override IOpenSearchResponse GetResponse()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();

            AtomFeed feed = new AtomFeed();

            int count = string.IsNullOrEmpty(parameters["count"]) ? 20 : int.Parse(parameters["count"]);
            int page = string.IsNullOrEmpty(parameters["startPage"]) ? 1 : int.Parse(parameters["startPage"]);
            int index = string.IsNullOrEmpty(parameters["startIndex"]) ? 1 : int.Parse(parameters["startIndex"]);
            string type = string.IsNullOrEmpty(parameters["auxtype"]) ? "aux_resorb" : parameters["auxtype"];
            bool withOrbits = parameters["orbits"] == "true";

            int absindex = index + ((page - 1) * count);
            int queryindex = absindex % 20;
            int querypage = (absindex / 20) + 1;

            List<AtomItem> items = new List<AtomItem>();

            while (items.Count() < count)
            {

                Uri url = BuildUrl(qcBaseUrl, count, index, page, type, parameters["start"], parameters["stop"]);

                var request = HttpWebRequest.Create(url);

                log.DebugFormat("Query: {0}", url);

                HtmlDocument doc = new HtmlDocument();

                using (var response = request.GetResponse())
                {
                    doc.Load(response.GetResponseStream());
                }

                Dictionary<string, Uri> list = new Dictionary<string, Uri>();

                var pagesli = doc.DocumentNode.SelectNodes("/html/body/div/div/div/div[1]/div/ul/li");
                int lastpage = 1;

                if (pagesli != null)
                {
                    lastpage = pagesli.Max(li =>
                    {
                        int pageo = 0;
                        if (int.TryParse(li.FirstChild.InnerText, out pageo))
                            return pageo;
                        return 0;
                    });
                }

                if (lastpage < querypage)
                    break;

                var trs = doc.DocumentNode.SelectNodes("/html/body/div/div/div/div[1]/table/tbody/tr");

                if (trs == null)
                    break;

                foreach (HtmlNode tr in trs)
                {
                    var a = tr.SelectSingleNode("td/a");
                    log.Debug(a.InnerText);
                    HtmlAttribute href = a.Attributes["href"];
                    var producturl = new Uri(string.Format("{0}/{1}/{2}", qcBaseUrl, type, href.Value));
                    log.Debug(producturl);
                    list.Add(a.InnerText, producturl);
                }

                if (list.Count() == 0)
                    break;

                if (items.FirstOrDefault(i => i.Identifier == list.Last().Key.Replace(".EOF", "")) != null)
                    break;

                items.AddRange(BuildAtomItem(list.Skip(queryindex - 1).Take(count - items.Count()), withOrbits));

                queryindex = 1;
                page++;

            }

            feed.Items = items;

            sw.Stop();

            return new Terradue.OpenSearch.Response.AtomOpenSearchResponse(feed, sw.Elapsed);
        }
コード例 #43
0
        public static void appendEvent(string ClassName, string Method, Dictionary<string, string> Properties)
        {
            deleteLastXLinesInFile(FilePath, 3);

            sw = new StreamWriter(FilePath, true);
            sw.WriteLine("      <div class='panel-group'>");
            sw.WriteLine("        <div class='panel panel-default " + TestParametersClass.StepStatus + "'>");
            sw.WriteLine("          <div class='panel-heading " + TestParametersClass.StepStatus + "'>");
            sw.WriteLine("            <h3 class='panel-title'>");
            sw.WriteLine("              <a data-toggle='collapse' id='Toggle' href='#collapse" + Properties["Step ID"] + "'>Step ID: " + Properties["Step ID"] + "</a>");
            sw.WriteLine("              <p class='" + TestParametersClass.StepStatus + "' id='StepResult'>Step " + TestParametersClass.StepStatus + "</p>");
            sw.WriteLine("            </h3>");
            sw.WriteLine("          </div>");
            sw.WriteLine("          <div id='collapse" + Properties["Step ID"] + "' class='panel-collapse collapse in'>");
            sw.WriteLine("            <div class='panel-body'>");
            sw.WriteLine("              <div class='table'>");
            sw.WriteLine("                <div class='PropertiesTableCell'>");
            sw.WriteLine("                  <TABLE class='PropertiesTable'>");

            foreach (KeyValuePair<string, string> entry in Properties.Skip(2))
            {
                string Name = entry.Key;
                string Value = entry.Value;

                if (Value != "")
                {
                    sw.WriteLine("                    <TR>");
                    sw.WriteLine("                      <TD class='PropertyName" + Properties["Step Status"] + "'>" + Name + "</TD>");
                    sw.WriteLine("                      <TD class='PropertyValue" + Properties["Step Status"] + "'>" + Value + "</TD>");
                    sw.WriteLine("                    </TR>");
                }
            }

            sw.WriteLine("                  </TABLE>");
            sw.WriteLine("                </div>");
            sw.WriteLine("                <div class='ScreenshotCell'>");

            if (TestParametersClass.BrowserOpen)
            {
                sw.WriteLine("                  <a href='" + TestParametersClass.LocalScreenshotFilePathForResultFile + "'>");
                sw.WriteLine("                    <img class='ScreenshotMini' src='" + TestParametersClass.LocalScreenshotFilePathForResultFile + "'>");
                sw.WriteLine("                  </a>");
            }

            sw.WriteLine("                </div>");
            sw.WriteLine("              </div>");
            sw.WriteLine("            </div>");
            sw.WriteLine("          </div>");
            sw.WriteLine("        </div>");
            sw.WriteLine("      </div>");
            sw.WriteLine("    </div>");
            sw.WriteLine("  </BODY>");
            sw.WriteLine("</HTML>");
            sw.Dispose();
        }
コード例 #44
0
ファイル: Sync.cs プロジェクト: matutee/ElasticSearchSync
        private SyncResponse IndexProcess(Dictionary<object, Dictionary<string, object>> data, SyncResponse syncResponse)
        {
            var c = 0;
            while (c < data.Count())
            {
                var partialData = data.Skip(c).Take(_config.BulkSize).ToDictionary(x => x.Key, x => x.Value);

                var bulkResponse = BulkIndexProcess(partialData);

                syncResponse.BulkResponses.Add(bulkResponse);
                syncResponse.IndexedDocuments += bulkResponse.AffectedDocuments;
                syncResponse.Success = syncResponse.Success && bulkResponse.Success;

                log.Info(String.Format("bulk duration: {0}ms. so far {1} documents have been indexed successfully.", bulkResponse.Duration, syncResponse.IndexedDocuments));
                c += _config.BulkSize;
            }

            return syncResponse;
        }
コード例 #45
0
ファイル: Problem185.cs プロジェクト: charvey/ProjectEuler
        public ulong S_1(Dictionary<ulong, int> guesses)
        {
            ulong start = 1;
            ulong stop = 10;
            while(stop<guesses.First().Key)
            {
                start *= 10;
                stop *= 10;
            }

            var poss = new List<ulong>();

            foreach (var g in guesses.Take(1))
            {
                ulong guess = g.Key;
                int correct = g.Value;

                for (ulong i = start; i < guess; i++)
                {
                    ulong diff = guess - i;
                    int count = 0;

                    while (diff > 0)
                    {
                        if (diff%10 == 0)
                        {
                            count++;
                            if (count > correct)
                            {
                                //continue to for loop
                                diff = 0;
                            }
                        }

                        diff /= 10;
                    }

                    if (count == correct)
                        poss.Add(i);

                }
                for (ulong i = guess + 1; i < stop; i++)
                {
                    ulong diff = i - guess;
                    int count = 0;

                    while (diff > 0)
                    {
                        if (diff%10 == 0)
                        {
                            count++;
                            if (count > correct)
                            {
                                //continue to for loop
                                diff = 0;
                            }
                        }

                        diff /= 10;
                    }

                    if (count == correct)
                        poss.Add(i);
                }
            }

            foreach (var g in guesses.Skip(1))
            {
                ulong guess = g.Key;
                int correct = g.Value;

                foreach (var p in poss)
                {
                    ulong diff = p > guess ? p - guess : guess - p;
                    int count = 0;

                    while (diff > 0)
                    {
                        if (diff%10 == 0)
                        {
                            count++;
                            if (count > correct)
                            {
                                //continue to for loop
                                diff = 0;
                            }
                        }

                        diff /= 10;
                    }

                    if (count != correct)
                        poss.Remove(p);
                }
            }

            Debug.Assert(poss.Count==1);

            return poss.Single();
        }