public void BuildRepoert() { var items = new List<SettlementDetails> { new SettlementDetails { Name = "A", Amount = 1m, }, new SettlementDetails { Name = "B", Amount = 2m, Amount1 = 2, }, new SettlementDetails { Name = "C", Amount = 3m, Amount1 = 1, } }; var target = new DataTable<SettlementDetails>(); target.Column("Name", s => s.Name); //計算列 IColumn colum4CalculateRow1 = target.Column("Amount0", s => s.Amount).Sum<decimal?>(); IColumn colum4CalculateRow2 = target.Column("Amount1", s => s.Amount1).Sum<decimal?>(); target.Sum<decimal?>("Amount+Amount1", colum4CalculateRow1, colum4CalculateRow2); target.SetData(items); var columns = new[] { "Name", "Amount0", "Amount1", "Amount+Amount1" }; int index = 0; //check column Name; foreach (IColumn column in target.Columns) { Assert.AreEqual(columns[index], column.Name); index++; } //check the row item0; index = 0; foreach (var item in target.GetRows()) { Assert.AreEqual(items[index].Name, item[0]); Assert.AreEqual(items[index].Amount, item[1]); Assert.AreEqual(items[index].Amount1, item[2]); Assert.AreEqual((items[index].Amount ?? 0) + (items[index].Amount1 ?? 0), item[3], "row is " + index); index++; } Assert.AreEqual(items.Sum(item => item.Amount), (colum4CalculateRow1).SumResult()); Assert.AreEqual(items.Sum(item => item.Amount1), (colum4CalculateRow2).SumResult()); }
public void TestSumIenumerable() { List<int> tl = new List<int>() { 1, 2, 3 }; int sum = tl.Sum<int>(); Console.WriteLine(sum); Assert.AreEqual(6, sum, "Error in result of sum"); }
public void All() { var e1 = Emit<LotsOfParams>.NewDynamicMethod(); var args = new List<int>(); for (ushort i = 0; i < 260; i++) { e1.LoadConstant(i); e1.StoreArgument(i); args.Add(i); } for (ushort i = 0; i < 260; i++) { e1.LoadArgument(i); } for (var i = 0; i < 259; i++) { e1.Add(); } e1.Return(); var d1 = e1.CreateDelegate(); var x = (int)d1.DynamicInvoke(args.Cast<object>().ToArray()); Assert.AreEqual(args.Sum(), x); }
public BestFitFunctions(int maxBoxSize, int slotSize, int numBoxes) { Boxes = new List<Box>(); Slots = new List<Slot>(); m_SlotSize = slotSize; Random rand = new Random(); for (int i = 0; i < numBoxes; i++) { Boxes.Add(new Box() { Weight = rand.Next(maxBoxSize), Id = i }); } double sumOfBoxes = Boxes.Sum(b => b.Weight); double bestFit = 0; for (int i = 1; i <= 10; i++) { double slots = (sumOfBoxes * i) / slotSize; double fit = slots - Math.Floor(slots); if (fit > bestFit) { SlotsCountExact = slots; System.Diagnostics.Debug.WriteLine("Optimal fit sum " + slots); bestFit = fit; Repetitions = i; m_NumSlots = (int)Math.Ceiling(slots); } } m_SlotIndexBitSize = Convert.ToString(m_NumSlots - 1, 2).Length; Slots = new List<Slot>(); for (int i = 0; i < m_NumSlots; i++) Slots.Add(new Slot() { Size = m_SlotSize }); }
public void AllNonGeneric() { var returnType = typeof(LotsOfParams).GetMethod("Invoke").ReturnType; var paramTypes = typeof(LotsOfParams).GetMethod("Invoke").GetParameters().Select(p => p.ParameterType).ToArray(); var e1 = Emit.NewDynamicMethod(returnType, paramTypes); var args = new List<int>(); for (ushort i = 0; i < 260; i++) { e1.LoadConstant(i); e1.StoreArgument(i); args.Add(i); } for (ushort i = 0; i < 260; i++) { e1.LoadArgument(i); } for (var i = 0; i < 259; i++) { e1.Add(); } e1.Return(); var d1 = e1.CreateDelegate<LotsOfParams>(); var x = (int)d1.DynamicInvoke(args.Cast<object>().ToArray()); Assert.AreEqual(args.Sum(), x); }
public void All() { var e1 = Emit<LotsOfParams>.NewDynamicMethod(); for (ushort i = 0; i < 260; i++) { e1.LoadArgumentAddress(i); e1.LoadIndirect<int>(); } for (var i = 0; i < 259; i++) { e1.Add(); } e1.Return(); var d1 = e1.CreateDelegate(); var rand = new Random(); var args = new List<int>(); for (var i = 0; i < 260; i++) { args.Add(rand.Next(10)); } var ret = (int)d1.DynamicInvoke(args.Cast<object>().ToArray()); Assert.AreEqual(args.Sum(), ret); }
public void Performance_test_get_properties_for_type_without_cache() { // Arrange // Pre-load all of the Domain Types so we can test against a Pool containing existing objects. IEnumerable<Type> types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes()); types.AsParallel().ForAll(type => PropertyCache.GetPropertiesForType(type)); var times = new List<double>(); const int _iterations = 1000; // Act for (int count = 0; count < _iterations; count++) { // Remove PayItem so we can test it not existing in the Pool. TypeCache.ClearTypeFromPool<TypePoolFixture>(); // Act var timer = new Stopwatch(); timer.Start(); IEnumerable<PropertyInfo> results = PropertyCache.GetPropertiesForType<TypePoolFixture>(); timer.Stop(); times.Add(timer.Elapsed.TotalMilliseconds); } Debug.WriteLine($"The average time to fetch an uncached collection of properties over {_iterations} iterations was {times.Sum() / times.Count}ms"); }
public void OpdaterRostatistikTest() { //NB: DENNE TEST SLETTER ALT DATA I BASEN UnitTestHelper.InitierAlleKomponenterMedDefault(); UnitTestHelper.SletAlt(); Baad baad = UnitTestHelper.LavEnkeltBaad(); UnitTestHelper.IndsaetXNytMedlem(1, MedlemsstatusEnum.Aktiv); Medlem medlem = UnitTestHelper.HentFoersteMedlem(); DateTime detteAar = DateTime.UtcNow.Subtract(new TimeSpan(1, 0, 0, 0)); DateTime sidsteAar = detteAar.Subtract(TimeSpan.FromDays(365)); List<int> turlaengderDetteAar = new List<int>(); List<int> turlaengderSidsteAar = new List<int>(); Random r = new Random(); for (int i = 0; i < 5; i++) { int turlaengde = r.Next(100); turlaengderDetteAar.Add(turlaengde); UnitTestHelper.OpretTurPaaBaadOgMedlem(medlem.ID, baad.ID, detteAar, turlaengde); turlaengde = r.Next(100); turlaengderSidsteAar.Add(turlaengde); UnitTestHelper.OpretTurPaaBaadOgMedlem(medlem.ID, baad.ID, sidsteAar, turlaengde); } MedlemBO medlemBO = new MedlemBO(medlem); medlemBO.OpdaterRostatistik(); Assert.AreEqual(medlem.Rostatistik.KilometerDetteAar, turlaengderDetteAar.Sum()); Assert.AreEqual(medlem.Rostatistik.KilometerSidsteAar, turlaengderSidsteAar.Sum()); }
public void TestSumAggregate() { List<int?> l = new List<int?> { 0, 3, null, 4, 5 }; int? sum = l.Sum(); int? agg = l.Aggregate((int?)0, (s, x) => s + x); Assert.IsFalse(sum == (int?)null); Assert.IsTrue(agg == (int?)null); }
public void Sum_Empty_DefaultMoney() { var source = new List<MoneyStub>(); var actual = source.Sum(s => s.Value); Assert.AreEqual(0, actual.Amount); Assert.AreEqual("BRL", actual.Currency); }
public void GetDivisors() { var divisors = new List<int>(); { //220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110 divisors = Utils.GetDivisors(220).ToList(); Assert.AreEqual(divisors.Count, 11); Assert.AreEqual(divisors.Sum(), 284); } { //284 are 1, 2, 4, 71 and 142 divisors = Utils.GetDivisors(284).ToList(); Assert.AreEqual(divisors.Count, 5); Assert.AreEqual(divisors.Sum(), 220); } }
public void EmptyCollectionTest() { List<int> list = new List<int>(); try { list.Sum(); } catch (ArgumentException e) { Assert.AreEqual(e.Message, string.Format("{0} is empty", list.GetType())); } }
public void Sum_Source_Money() { var source = new List<MoneyStub>() { new MoneyStub() { Value = Money.Reais(1) }, new MoneyStub() { Value = Money.Reais(2) }, new MoneyStub() { Value = Money.Reais(3) } }; var actual = source.Sum(s => s.Value); Assert.AreEqual(6, actual.Amount); Assert.AreEqual("BRL", actual.Currency); }
private double GetScore(List<double> source, int clicknum) { var result = (double)0; int count = source.Count; if (clicknum > count) { var num = clicknum / count; result += source.Sum() * num; clicknum = clicknum % count; } for (int i = 0; i < clicknum; i++) { result += source[i]; } return result; }
public async Task BenchmarkAsync() { await WarmupAsync(); var measureResults = new List<TimeSpan>(); for (var interation = 0; interation < IterationCount; interation++) { var measureResult = await MeasureAsync(ActionAsync); measureResults.Add(measureResult); } for (var i = 0; i < measureResults.Count; i++) { Console.WriteLine("#{0}: {1}", i, measureResults[i]); } var averageTicks = measureResults.Sum(timeSpan => timeSpan.Ticks)/measureResults.Count; var average = TimeSpan.FromTicks(averageTicks); Console.WriteLine("Average: {0}", average); }
public Int32 Q1TripleStep(Int32 steps) // assumption that steps fists in n { List<Int32> ways = new List<Int32> { 1, 1, 2 }; if (steps <= 1) return ways[steps]; // here we assume that 0 steps can be chosen in one way. // Hangs. Bug? // Contract.Assert(steps > 2); int stepsRemaining = steps - 2; while (stepsRemaining > 0) { stepsRemaining--; ways.Add(ways.Sum()); ways.RemoveAt(0); } Contract.Ensures(ways.Count == 3); return ways.Last(); }
public void AddNumber_Random() { var num = new Random().Next(0, 100); List<int> nums = new List<int>(); StringBuilder input = new StringBuilder(); Random r = new Random(); for (int i = 0; i < num; i++) { int nextNum = r.Next(0, num); nums.Add(nextNum); input.Append(nextNum + ","); } var expectedResult = nums.Sum(); Calculator c = new Calculator(); int result = c.Add(input.ToString()); Assert.AreEqual(expectedResult, result); }
public void Performance_test_get_properties_for_type_with_cache_from_large_cache_pool_using_predicate() { // Arrange // Pre-load all of the Types so we can test against a Pool containing existing objects. IEnumerable<Type> types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes()); types.AsParallel().ForAll(type => PropertyCache.GetPropertiesForType(type)); const int _iterations = 1000; var times = new List<double>(); // Act for (int count = 0; count < _iterations; count++) { var timer = new Stopwatch(); timer.Start(); var results = PropertyCache.GetPropertiesForType<TypePoolFixture>( property => Attribute.IsDefined(property, typeof(AttributeFixture))); timer.Stop(); times.Add(timer.Elapsed.TotalMilliseconds); } Debug.WriteLine($"The average time to fetch a cached collection of filtered properties from a large pool over {_iterations} iterations was {times.Sum() / times.Count}ms"); }
public void AdjustRatiosTest() { Object expected, actual; GeneratePaperTemplate_Accessor target = new GeneratePaperTemplate_Accessor(); List<AutoRatio> ratios; // 正常情况 ratios = new List<AutoRatio>(); ratios.Add(new AutoRatio("单选题", 0.2)); ratios.Add(new AutoRatio("多选题", 0.2)); ratios.Add(new AutoRatio("判断题", 0.2)); ratios.Add(new AutoRatio("公文改错题", 0.1)); ratios.Add(new AutoRatio("计算题", 0.1)); ratios.Add(new AutoRatio("案例分析题", 0.1)); ratios.Add(new AutoRatio("问答题", 0.1)); expected = ratios.Sum(m => m.percent); actual = target.AdjustRatios(ratios).Sum(m => m.percent); Assert.AreEqual(expected, actual); actual = null; // 未设置出题比例 ratios = new List<AutoRatio>(); expected = "未设置出题比例。"; try { target.AdjustRatios(ratios); } catch (Exception ex) { actual = ex; } Assert.AreEqual(expected, ((Exception)actual).Message); actual = null; // 出题比例小于 50% ratios = new List<AutoRatio>(); ratios.Add(new AutoRatio("单选题", 0)); ratios.Add(new AutoRatio("多选题", 0)); ratios.Add(new AutoRatio("判断题", 0)); ratios.Add(new AutoRatio("公文改错题", 0.1)); ratios.Add(new AutoRatio("计算题", 0.1)); ratios.Add(new AutoRatio("案例分析题", 0.1)); ratios.Add(new AutoRatio("问答题", 0.1)); expected = "出题比例小于 50% 。"; try { target.AdjustRatios(ratios); } catch (Exception ex) { actual = ex; } Assert.AreEqual(expected, ((Exception)actual).Message); actual = null; // 出题比例大于 100% ratios = new List<AutoRatio>(); ratios.Add(new AutoRatio("单选题", 0.3)); ratios.Add(new AutoRatio("多选题", 0.2)); ratios.Add(new AutoRatio("判断题", 0.2)); ratios.Add(new AutoRatio("公文改错题", 0.1)); ratios.Add(new AutoRatio("计算题", 0.1)); ratios.Add(new AutoRatio("案例分析题", 0.1)); ratios.Add(new AutoRatio("问答题", 0.1)); expected = "出题比例大于 100% 。"; try { target.AdjustRatios(ratios); } catch (Exception ex) { actual = ex; } Assert.AreEqual(expected, ((Exception)actual).Message); actual = null; // 自动补缺 ratios = new List<AutoRatio>(); ratios.Add(new AutoRatio("单选题", 0)); ratios.Add(new AutoRatio("多选题", 0)); ratios.Add(new AutoRatio("判断题", 0)); ratios.Add(new AutoRatio("公文改错题", 0)); ratios.Add(new AutoRatio("计算题", 0.2)); ratios.Add(new AutoRatio("案例分析题", 0.2)); ratios.Add(new AutoRatio("问答题", 0.2)); expected = 0.34; actual = target.AdjustRatios(ratios); Assert.AreEqual(expected, (Double)((List<AutoRatio>)actual)[((List<AutoRatio>)actual).Count - 1].percent); actual = null; }
public void Sum() { // arrange List<int> listInt = new List<int>() { 1, 2, 3 }; List<long> listlong = new List<long>() { 1, 2, 3 }; List<double> listdouble = new List<double>() { 1.1d, 2.2d, 3.3d }; List<decimal> listdecimal = new List<decimal>() { new decimal(1.1), new decimal(2.2), new decimal(3.3) }; // act int actualInt = listInt.Sum(x => x); long actuallong = listlong.Sum(x => x); double actualdouble = listdouble.Sum(x => x); decimal actualdecimal = listdecimal.Sum(x => x); // assert Assert.AreEqual(6, actualInt); Assert.AreEqual(6, actuallong); Assert.AreEqual(6.6d, actualdouble, 0d); Assert.AreEqual(new decimal(6.6), actualdecimal); }
private void PrepareCloudFileWithDifferentSizeRange(CloudFile cloudFile) { List<int> ranges = new List<int>(); List<int> gaps = new List<int>(); // Add one 4MB - 16MB range ranges.Add(random.Next(4 * 1024 * 1024, 16 * 1024 * 1024)); // Add one 1B range ranges.Add(1); int remainingPageNumber = random.Next(10, 20); // Add ten - twenty 1B - 4MB range for (int i = 0; i < remainingPageNumber; ++i) { ranges.Add(random.Next(1, 4 * 1024 * 1024)); } // Add one 4M - 8M gap gaps.Add(random.Next(4 * 1024 * 1024, 8 * 1024 * 1024)); // Add 512B - 2048B gaps for (int i = 1; i < ranges.Count - 1; ++i) { gaps.Add(random.Next(1, 512 * 4)); } if (DMLibTestContext.DestType == DMLibDataType.PageBlob) { int totalSize = ranges.Sum() + gaps.Sum(); int remainder = totalSize % 512; if (remainder != 0) { ranges[ranges.Count - 1] += 512 - remainder; } } ranges.Shuffle(); gaps.Shuffle(); CloudFileHelper.GenerateCloudFileWithRangedData(cloudFile, ranges, gaps); }
public void TestLinqAverage2() { var connectionString = _connectionString + "StoreName=" + Guid.NewGuid(); var context = new MyEntityContext(connectionString); var ages = new List<int>(); for (int i = 0; i < 1000; i++) { var entity = context.Entities.Create(); entity.SomeString = "Person" + i; int age = 20 + (i / 20); entity.SomeInt = age; ages.Add(age); } context.SaveChanges(); var total1 = context.Entities.Sum(e => e.SomeInt); var total2 = ages.Sum(); var q1 = context.Entities.Count(); var q2 = ages.Count; Assert.AreEqual(total2 / q2, total1 / q1); Assert.AreEqual(1000, context.Entities.Count()); Assert.AreEqual(ages.Average(), context.Entities.Average(e => e.SomeInt)); }
public void TestJoinLists() { // Create a new list of apps var apps = new List<EmailApplication>() { new EmailApplication() {Id = 1, CustomerId = 1, IPAccessRestrictions = "123.43.56.2"}, new EmailApplication() {Id = 2, CustomerId = 1, IPAccessRestrictions = "123.43.56.36"}, new EmailApplication() {Id = 3, CustomerId = 1}, new EmailApplication() {Id = 4, CustomerId = 2}, new EmailApplication() {Id = 5, CustomerId = 3, IPAccessRestrictions = "123.43.45.1"} }; var customers = new List<Customer>(); foreach (var customer in m_repository.GetSortedCustomers()) { // customer.Applications = apps.Where(a => a.CustomerId == customer.Id).ToList(); customers.Add(customer); } // Join customers to applications (with filter to those with IP restrictions) var joinQuery = customers.Join(apps, c => c.Id, a => a.CustomerId, (c, a) => new { Name = c.LastName + ", " + c.FirstName, IpRestrictions = a.IPAccessRestrictions }).Where(w => !String.IsNullOrEmpty(w.IpRestrictions)); foreach (var item in joinQuery) { Debug.WriteLine(item.Name.ToString() + " : " + item.IpRestrictions); } // Try to get customers with IP access restrictions var manyQuery = customers .Select(c => c.Applications .Where(a => !String.IsNullOrEmpty(a.IPAccessRestrictions))); foreach (var item in manyQuery) { Debug.WriteLine(item.ToString()); } // The above query is an enumerable of an enumerable, which ain't great // Using SelectMany will flatten a parent/child relationship and allow projection on either var customersWithIpRestrictions = customers .SelectMany(c => c.Applications .Where(a => !String.IsNullOrEmpty(a.IPAccessRestrictions)), // project to customer (c, a) => c) .Distinct(); foreach (var item in customersWithIpRestrictions) { Debug.WriteLine(item.LastName + ", " + item.FirstName); } Debug.WriteLine(customers.Sum(c => 1)); var groupBy = apps.GroupBy(a => a.CustomerId, a => a.Id, (key, id) => new { ClientId = key, NumApps = id.Sum(a => 1), MeanApps = id.Sum() / id.Sum(a => 1), Avg = id.Average() }); foreach (var item in groupBy) { Debug.WriteLine(item.ClientId + " has this many apps: " + item.NumApps + " with mean: " + item.Avg); } var modeJoin = apps.Join(customers, a => a.CustomerId, c => c.Id, (a, c) => new { ClientName = c.LastName + ", " + c.FirstName, ApplicationId = a.Id }); var modeQuery = modeJoin.GroupBy(e => e.ClientName) .OrderByDescending(group => group.Count()) .Select(group => group.Key); Debug.WriteLine("ClientId with most apps: " + modeQuery.FirstOrDefault()); Assert.IsNotNull(joinQuery); }
private static void CreateSectionFiveExample001(PdfBuilder pdfBuilder, MarginInfo parentPadding) { var secionFiveExampleTable = pdfBuilder.CreateOuterTable( "140 310", Resources.ArialFont, PdfBuilder.DefaultHeadingTwoFontSize, parentPadding, keepContentTogether: true); // create table row heading pdfBuilder.CreateOuterTableRowHeading( secionFiveExampleTable, "Example Section 5 Heading"); pdfBuilder.BlankRow(secionFiveExampleTable); // Create dates var exampleItem01Row = secionFiveExampleTable.Rows.Add(); pdfBuilder.CreateOuterTableRowCells( exampleItem01Row, "Example item 01", DateTime.Now.ToShortDateString(), padding: PdfBuilder.DefaultSubHeadingBottomPadding); var exampleItem02Row = secionFiveExampleTable.Rows.Add(); pdfBuilder.CreateOuterTableRowCells( exampleItem02Row, "Example item 02", "example info", padding: PdfBuilder.DefaultSubHeadingBottomPadding); var exampleItem03Row = secionFiveExampleTable.Rows.Add(); pdfBuilder.CreateOuterTableRowCells( exampleItem03Row, "Example item 03", "example info", padding: PdfBuilder.DefaultSubHeadingBottomPadding); var exampleItem04Row = secionFiveExampleTable.Rows.Add(); pdfBuilder.CreateOuterTableRowCells( exampleItem04Row, "Example item 04", "example info", padding: PdfBuilder.DefaultSubHeadingBottomPadding); pdfBuilder.BlankRow(secionFiveExampleTable); // create an overly complex arrangement of data and values to demonstrate the flexibility of the aspose pdf builder. var orderedNumbers = new[] { "0001", "0002", "0003" }; var examplePairsAsGroup = new List<KeyValuePair<string, decimal>> { new KeyValuePair<string, decimal>(orderedNumbers[0], 10000), new KeyValuePair<string, decimal>(orderedNumbers[0], 10000), new KeyValuePair<string, decimal>(orderedNumbers[0], 10000), new KeyValuePair<string, decimal>(orderedNumbers[1], 20000), new KeyValuePair<string, decimal>(orderedNumbers[1], 20000), new KeyValuePair<string, decimal>(orderedNumbers[1], 20000), new KeyValuePair<string, decimal>(orderedNumbers[2], 30000), new KeyValuePair<string, decimal>(orderedNumbers[2], 30000), new KeyValuePair<string, decimal>(orderedNumbers[2], 30000) }.OrderBy(x => x.Key) .GroupBy(x => x.Key) .ToArray(); // calculate totals - terrible example... var orderedNumbers0001 = examplePairsAsGroup.SelectMany(x => x).Where(x => x.Key == orderedNumbers[0]).ToArray(); var orderedNumbers0002 = examplePairsAsGroup.SelectMany(x => x).Where(x => x.Key == orderedNumbers[1]).ToArray(); var orderedNumbers0003 = examplePairsAsGroup.SelectMany(x => x).Where(x => x.Key == orderedNumbers[2]).ToArray(); var exampleTotalsAsGroup = new List<KeyValuePair<string, decimal>> { new KeyValuePair<string, decimal>(orderedNumbers[0], orderedNumbers0001[0].Value + orderedNumbers0002[0].Value + orderedNumbers0003[0].Value), new KeyValuePair<string, decimal>(orderedNumbers[1], orderedNumbers0001[1].Value + orderedNumbers0002[1].Value + orderedNumbers0003[1].Value), new KeyValuePair<string, decimal>(orderedNumbers[2], orderedNumbers0001[2].Value + orderedNumbers0002[2].Value + orderedNumbers0003[2].Value) }.OrderBy(x => x.Key) .GroupBy(x => x.Key) .ToArray(); var useWidths = "53 80 79 79 80 79"; // remember - a user can specify less or more columns and pass them into CreateInnerTable. // Create an inner table var exampleInnerTable = pdfBuilder.CreateInnerTable(useWidths, secionFiveExampleTable); // Create Header Inner Table row var exampleInnerHeaderRow = pdfBuilder.CreateInnerTableRow(exampleInnerTable, parentPadding); // Create Header Cell Titles var titles = new List<HeaderCell> { new HeaderCell { Content = "Side Content Name" } }; var additionalNames = new [] { "example 01", "example 02", "example 03" }.GroupBy(x => x).ToArray(); titles.AddRange(additionalNames.Select(name => new HeaderCell { Content = "ex name " + name.Key })); titles.Add(new HeaderCell { Content = "Total" }); pdfBuilder.CreateInnerTableHeaderCells(exampleInnerHeaderRow, titles.ToArray()); // Display example pairs by their ordered numbers foreach (var epag in examplePairsAsGroup) { var cellContentByFy = new List<DisplayCell> { new DisplayCell { Content = epag.Key, IsDate = true } }; cellContentByFy.AddRange(epag.Select(x => new DisplayCell { Content = x.Value.ToString("C"), IsCurrency = true }).ToArray()); cellContentByFy.Add(new DisplayCell { Content = epag.Sum(x => x.Value).ToString("C"), IsCurrency = true }); var itemRow = pdfBuilder.CreateInnerTableRow(exampleInnerTable, parentPadding); pdfBuilder.CreateInnerTableItemCells( itemRow, cellContent: cellContentByFy.ToArray()); } // Display Totals var cellContentTotals = new List<DisplayCell> { new DisplayCell { Content = "Totals", IsHeader = true } }; cellContentTotals.AddRange(exampleTotalsAsGroup.Select(x => new DisplayCell { Content = x.Sum(sum => sum.Value).ToString("C"), IsTotal = true, IsCurrency = true }).ToArray()); cellContentTotals.Add(new DisplayCell { Content = exampleTotalsAsGroup.Sum(sum => sum.Sum(x => x.Value)).ToString("C"), IsTotal = true, IsCurrency = true }); var projectCostCentreTotalRow = pdfBuilder.CreateInnerTableRow(exampleInnerTable, PdfBuilder.DefaultOuterPadding); pdfBuilder.CreateInnerTableItemCells( projectCostCentreTotalRow, cellContent: cellContentTotals.ToArray()); pdfBuilder.BlankRow(); }
public void basic_gof_visitor() { IEnumerable<Shape> draw = new List<Shape> { new Circle(new System.Drawing.Point(0, 1), 10), new Rectangle(new System.Drawing.Point(20, 5), 10, 30) }; double all_area = draw.Sum(s => s.Area); Assert.AreEqual<double>(100D * Math.PI + 300, all_area); var width = new WidthOperation(); draw.Aggregate(width, (whole, next) => { next.Accept(whole); return whole; }); Assert.AreEqual<double>(50D, width.Result); var length = new LengthOperation(); draw.Aggregate(length, (whole, next) => { next.Accept(whole); return whole; }); Assert.AreEqual<double>(56D, length.Result); var area = new AreaOperation(); draw.Aggregate(area, (whole, next) => { next.Accept(whole); return whole; }); Assert.AreEqual<double>(all_area, area.Result); }
public async Task Z_Test_0171() { Helper.CleanDatabase(); var single1 = new SingleMany {ColumnInt = 1}; var single2 = new SingleMany {ColumnInt = 8}; var single3 = new SingleMany {ColumnInt = 64}; var many1 = new List<SingleMany> {new SingleMany {ColumnInt = 512}, new SingleMany {ColumnInt = 1024}, new SingleMany {ColumnInt = 2048}}; var many2 = new List<SingleMany> {new SingleMany {ColumnInt = 4096}, new SingleMany {ColumnInt = 8192}, new SingleMany {ColumnInt = 16384}}; var many3 = new List<SingleMany> {new SingleMany {ColumnInt = 32768}, new SingleMany {ColumnInt = 65536}, new SingleMany {ColumnInt = 131072}}; Helper.LinkSingleMany(single1, single2, single3, many1, many2, many3); Helper.InsertFromMetas("BulkInsert2;BulkInsert3;UpdateValue2;UpdateValue3".Split(';').ToList(), single1, single2, single3, many1, many2, many3); Helper.UpdateFromMetas("BulkInsert2;BulkInsert3;UpdateValue2;UpdateValue3".Split(';').ToList(), single1, single2, single3, many1, many2, many3); // GET count before int columnInt_before = 0; int columnUpdateInt_before = 0; int columnInt_Key_before = 0; int columnUpdateInt_Key_before = 0; using (var connection = Helper.GetConnection()) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnInt) FROM SingleMany), 0)"; columnInt_before = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnUpdateInt) FROM SingleMany), 0)"; columnUpdateInt_before = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnInt) FROM SingleMany_Key), 0)"; columnInt_Key_before = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnUpdateInt) FROM SingleMany_Key), 0)"; columnUpdateInt_Key_before = Convert.ToInt32(command.ExecuteScalar()); } } using (var cn = Helper.GetConnection()) { cn.Open(); // PreTest // Action await cn.BulkActionAsync(action => action.BulkMerge(many1, x => x.Many2, x => x.Many3)); } // GET count int columnInt = 0; int columnUpdateInt = 0; int columnInt_Key = 0; int columnUpdateInt_Key = 0; using (var connection = Helper.GetConnection()) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnInt) FROM SingleMany), 0)"; columnInt = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnUpdateInt) FROM SingleMany), 0)"; columnUpdateInt = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnInt) FROM SingleMany_Key), 0)"; columnInt_Key = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnUpdateInt) FROM SingleMany_Key), 0)"; columnUpdateInt_Key = Convert.ToInt32(command.ExecuteScalar()); } } // Test Assert.AreEqual(columnInt_before + many1.Sum(x => x.ColumnInt), columnInt); Assert.AreEqual(many1.Sum(x => x.Many2.Sum(y => y.ColumnInt)) + many1.Sum(x => x.Many3.Sum(y => y.ColumnInt)), columnUpdateInt); Assert.AreEqual(columnInt_Key_before, columnInt_Key); Assert.AreEqual(columnUpdateInt_Key_before, columnUpdateInt_Key); }
public void Sum_abnormal() { // arrange List<int> listInt = new List<int>(); List<long> listLong = new List<long>(); List<double> listDouble = new List<double>(); List<decimal> listBigDecimal = new List<decimal>(); Func<int, int> funcInt = null; Func<long, int> funcLong = null; Func<double, int> funcDouble = null; Func<decimal, int> funcDecimal = null; // act and assert try { listInt.Sum(funcInt); Assert.Fail(); } catch (Exception e) { Assert.IsTrue(e is ArgumentNullException); } try { listLong.Sum(funcLong); Assert.Fail(); } catch (Exception e) { Assert.IsTrue(e is ArgumentNullException); } try { listDouble.Sum(funcDouble); Assert.Fail(); } catch (Exception e) { Assert.IsTrue(e is ArgumentNullException); } try { listBigDecimal.Sum(funcDecimal); Assert.Fail(); } catch (Exception e) { Assert.IsTrue(e is ArgumentNullException); } }
public void Sum_overflow() { // arrange List<int> listOverflowInt = new List<int>() { int.MaxValue, 1 }; List<int> listUnderflowInt = new List<int>() { int.MinValue, -1 }; List<long> listOverflowLong = new List<long>() { long.MaxValue, 1l }; List<long> listUnderflowLong = new List<long>() { long.MinValue, -1l }; // act and assert try { listOverflowInt.Sum(x => x); Assert.Fail(); } catch (Exception e) { Assert.IsTrue(e is OverflowException); } try { listUnderflowInt.Sum(x => x); Assert.Fail(); } catch (Exception e) { Assert.IsTrue(e is OverflowException); } try { listOverflowLong.Sum(x => x); Assert.Fail(); } catch (Exception e) { Assert.IsTrue(e is OverflowException); } try { listUnderflowLong.Sum(x => x); Assert.Fail(); } catch (Exception e) { Assert.IsTrue(e is OverflowException); } }
public void Z_Test_0030() { Helper.CleanDatabase(); var single1 = new SingleMany {ColumnInt = 1}; var single2 = new SingleMany {ColumnInt = 8}; var single3 = new SingleMany {ColumnInt = 64}; var many1 = new List<SingleMany> {new SingleMany {ColumnInt = 512}, new SingleMany {ColumnInt = 1024}, new SingleMany {ColumnInt = 2048}}; var many2 = new List<SingleMany> {new SingleMany {ColumnInt = 4096}, new SingleMany {ColumnInt = 8192}, new SingleMany {ColumnInt = 16384}}; var many3 = new List<SingleMany> {new SingleMany {ColumnInt = 32768}, new SingleMany {ColumnInt = 65536}, new SingleMany {ColumnInt = 131072}}; Helper.LinkSingleMany(single1, single2, single3, many1, many2, many3); Helper.InsertFromMetas("".Split(';').ToList(), single1, single2, single3, many1, many2, many3); Helper.UpdateFromMetas("".Split(';').ToList(), single1, single2, single3, many1, many2, many3); // GET count before int columnInt_before = 0; int columnUpdateInt_before = 0; int columnInt_Key_before = 0; int columnUpdateInt_Key_before = 0; using (var connection = Helper.GetConnection()) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnInt) FROM SingleMany), 0)"; columnInt_before = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnUpdateInt) FROM SingleMany), 0)"; columnUpdateInt_before = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnInt) FROM SingleMany_Key), 0)"; columnInt_Key_before = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnUpdateInt) FROM SingleMany_Key), 0)"; columnUpdateInt_Key_before = Convert.ToInt32(command.ExecuteScalar()); } } using (var cn = Helper.GetConnection()) { cn.Open(); // PreTest // Action cn.BulkInsert("key", many1, x => x.Single1, x => x.Single2, x => x.Single3); } // GET count int columnInt = 0; int columnUpdateInt = 0; int columnInt_Key = 0; int columnUpdateInt_Key = 0; using (var connection = Helper.GetConnection()) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnInt) FROM SingleMany), 0)"; columnInt = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnUpdateInt) FROM SingleMany), 0)"; columnUpdateInt = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnInt) FROM SingleMany_Key), 0)"; columnInt_Key = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnUpdateInt) FROM SingleMany_Key), 0)"; columnUpdateInt_Key = Convert.ToInt32(command.ExecuteScalar()); } } // Test Assert.AreEqual(0, columnInt); Assert.AreEqual(0, columnUpdateInt); Assert.AreEqual(many1.Sum(x => x.ColumnInt) + many1.Sum(x => x.Single1.ColumnInt) + many1.Sum(x => x.Single2.ColumnInt) + many1.Sum(x => x.Single3.ColumnInt), columnInt_Key); Assert.AreEqual(0, columnUpdateInt_Key); }
public void SumTest() { List<int> posIntList = new List<int>(); List<int> intList = new List<int>(); List<decimal> posDecimalList = new List<decimal>(); List<decimal> decimalList = new List<decimal>(); int sign = -1; for (int i = 0; i < 10; i++) { posIntList.Add(i + 1); intList.Add((i + 1) * sign); posDecimalList.Add((i + 1) / 10m); decimalList.Add(((i + 1) / 10m) * sign); sign *= -1; } Assert.AreEqual(55, posIntList.Sum()); Assert.AreEqual(5, intList.Sum()); Assert.AreEqual(5.5m, posDecimalList.Sum()); Assert.AreEqual(.5m, decimalList.Sum()); }