public void TestFiniteReverseAggregate() { var seq = new List<int> { 1, 2, 3, 4, 5 }; Assert.That(seq.ReverseAggregate(0, (x, acc) => acc.Value + x), Is.EqualTo(seq.Sum())); Assert.That(seq.ReverseAggregate((x1, x2) => x1 + x2.Value), Is.EqualTo(seq.Sum())); }
public void Check_if_data_is_not_retrieved_from_queue() { const int N = 200; const int N_THREADS = 3; var sut = new Parallelize(N_THREADS); var are = new AutoResetEvent(false); var results = new List<int>(); var threads = new Dictionary<int,bool>(); Action<IMessage> dequeue = _ => { lock(results) { if (!threads.ContainsKey(Thread.CurrentThread.ManagedThreadId)) threads.Add(Thread.CurrentThread.ManagedThreadId, true); var i = (int) _.Data; results.Add(i); if (results.Count == N) are.Set(); Thread.Sleep(i % 20); } }; sut.Start(); for(var i = 1; i<=N; i++) sut.Process(new Message("x", i), dequeue); Assert.IsTrue(are.WaitOne(4000)); Assert.AreEqual((N*(N+1)/2), results.Sum()); Assert.AreEqual(N_THREADS, threads.Count); }
public void Download(byte[] data, int bufferSize, DownloadSegmentPositions[] segmentPositionInfos) { BeforeDownload(); DownloadStream inputStream = new DownloadStream(data); IList<ISegmentDownloadTask> segmentDownloadTasks = new List<ISegmentDownloadTask>(segmentPositionInfos.Length); IList<DownloadStream> downloadStreams = new List<DownloadStream>(segmentPositionInfos.Length); MemoryStream outputStream = new MemoryStream(); for (int i = 0; i < segmentPositionInfos.Length; i++) { DownloadSegmentPositions segmentPosition = segmentPositionInfos[i]; byte[] dataPart = data.Skip((int) segmentPosition.StartPosition).Take((int)(segmentPosition.EndPosition - segmentPosition.StartPosition + 1)).ToArray(); DownloadStream downloadStream = new DownloadStream(dataPart); segmentDownloadTasks.Add(CreateSegmentDownloadTask(bufferSize, CreateSegmentDownloader(downloadStream, segmentPosition), CreateSegmentWriter(outputStream))); downloadStreams.Add(downloadStream); } SegmentDownloadManager segmentDownloadManager = new SegmentDownloadManager(new SegmentDownloadTaskCollection(segmentDownloadTasks)); segmentDownloadManager.Start(); segmentDownloadManager.Finish(true); AfterDownload(); long totalDownloads = downloadStreams.Sum(x => x.TotalDownloads); Assert.AreEqual(data.Length, totalDownloads); Assert.AreEqual(inputStream.ToArray().Take(data.Length).ToArray(), outputStream.ToArray().Take(data.Length).ToArray()); Assert.AreEqual(inputStream.ToArray(), outputStream.ToArray()); }
public void FindPandigitalProducts() { var products = new List<int>(); // Highest pandigital standalone number = 987654321 // Square root of this is 31426 //var limit = (int) Math.Pow(10, 9); // Most lopsided calc would be single digit * 4 digit => 4/5 digit product for (int a = 1; a < 10000; ++a) { for (int b = (a + 1); b < 10000; ++b) { var product = a * b; if (product < 1000) continue; // Not going to have enough digits between a, b and product if (product > 99999) break; // Too many digits if (products.Contains(product)) continue; var isPandigital = IsPandigital(a, b, product); if (isPandigital) products.Add(product); } } var sum = products.Sum(); Console.WriteLine("Sum: {0}", sum); foreach (var product in products) { Console.WriteLine(" {0}", product); } sum.Should().Be(45228); }
public void FindAmicableNumbersUnderTenThousand() { const long limit = 10000; var list = new List<long>(); for (long l = 1; l < limit; ++l) { if (list.Contains(l)) continue; var amicable = GetAmicablePair(l); if (amicable != 0 && amicable < limit) { list.Add(l); if (!list.Contains(amicable)) list.Add(amicable); } } foreach (var l in list) { Console.WriteLine(l); } var result = list.Sum(); Console.WriteLine("Sum of amicable numbers is: {0}", result); result.Should().Be(31626); }
public void Check_if_data_is_not_retrieved_from_queue() { const int N = 200; const int N_THREADS = 3; var sut = new Parallelize<int>(N_THREADS); var are = new AutoResetEvent(false); var results = new List<int>(); var threads = new Dictionary<long,bool>(); Action<int> dequeue = _ => { lock(results) { if (!threads.ContainsKey(Thread.CurrentThread.GetHashCode())) threads.Add(Thread.CurrentThread.GetHashCode(), true); results.Add(_); if (results.Count == N) are.Set(); Thread.Sleep(_ % 10); } }; sut.Start(); for(var i = 1; i<=N; i++) sut.Process(i, dequeue); Assert.IsTrue(are.WaitOne(4000)); Assert.AreEqual((N*(N+1)/2), results.Sum()); Assert.AreEqual(N_THREADS, threads.Count); }
public void Should38() { var times = new List<long>(); var lines = File.ReadAllLines("C:\\tmp\\badphonenumber-clean.log"); foreach (var line in lines) { var stopwatch = new Stopwatch(); stopwatch.Start(); var isValidNumber = IsValidNumber(line.Trim()); stopwatch.Stop(); if (isValidNumber) { Console.WriteLine("{0}", line); } times.Add(stopwatch.ElapsedMilliseconds); Thread.Sleep(TimeSpan.FromMilliseconds(500)); } var average = times.Average(); var count = times.Count; var sum = times.Sum(); var max = times.Max(); Console.WriteLine("{0} ms. {1} numbers. {2} sum. {3} max", average, count, sum, max); }
public void Add_method_accepts_unknown_number_of_numbers() { // Allow the Add method to handle an unknown amount of numbers // Arrange var randomNumber = new Random().Next(1, 100); var numbersList = new List<int>(randomNumber); var builder = new StringBuilder(); for (var index = 0; index < randomNumber; index++) { var thisNumber = new Random().Next(0, 100); numbersList.Add(thisNumber); if (builder.Length > 0) builder.Append(","); builder.Append(thisNumber); } var numbers = builder.ToString(); var expected = numbersList.Sum(); // Act var actual = new Calculator().Add(numbers); // Assert Assert.That(actual, Is.EqualTo(expected)); }
public void FileSizeSumTestManyGBs() { var list = new List<FileSize>(); Enumerable.Range(1, 1024 * 1024 * 10).ToList().ForEach(it => list.Add(new FileSize(1, Prefix.Mb))); var result = new FileSize(10, Prefix.Tb); list.Sum().Should().Be(result); }
public void should_sum_values() { var nums = new List<int> { 5, 9, 1, 10 }; int sum = nums.Sum(); sum.ShouldBe(25); }
public void Process_messages_on_different_threads() { Console.WriteLine("test thread: {0}", Thread.CurrentThread.GetHashCode()); var frc = new FlowRuntimeConfiguration(); frc.AddStream(new Stream(".in", "doParallel**")); frc.AddStream(new Stream("doParallel", ".out")); var threads = new Dictionary<long, int>(); frc.AddFunc<int, int>("doParallel", x => { lock (threads) { if ( threads.ContainsKey( Thread.CurrentThread.GetHashCode())) threads[Thread.CurrentThread.GetHashCode()] += 1; else threads.Add(Thread.CurrentThread.GetHashCode(), 1); } Console.WriteLine("thread {0}: {1}.", Thread.CurrentThread.GetHashCode(), x); Thread.Sleep((DateTime.Now.Millisecond % 100 + 1) * 50); return x; }); using (var sut = new FlowRuntime(frc)) { var are = new AutoResetEvent(false); var results = new List<int>(); sut.Result += _ => { Console.WriteLine("result: {0}.", _.Data); lock (results) { results.Add((int) _.Data); if (results.Count == 5) are.Set(); } }; sut.Process(new Message(".in", 1)); sut.Process(new Message(".in", 2)); sut.Process(new Message(".in", 3)); sut.Process(new Message(".in", 4)); sut.Process(new Message(".in", 5)); Assert.IsTrue(are.WaitOne(10000), "Processing took too long; not enough numbers received"); Assert.AreEqual(15, results.Sum(), "Wrong sum; some number got processed twice"); } }
public void CommandExecuted_event_contains_sequential_entry_ids() { var config = new EngineConfiguration() .ForImmutability() .ForIsolatedTest(); var engine = Engine.Create<ImmutableModel>(config); var sequence = new List<ulong>(); engine.CommandExecuted += (s, e) => sequence.Add(e.JournalEntryId); for(int i = 1; i <=100; i++) engine.Execute(new AppendNumberCommand(i)); var sum = engine.Execute(m => m.Numbers().Sum()); Assert.AreEqual(sum, sequence.Sum(n => (decimal) n)); }
public void should_be_able_to_specify_property_to_sum() { var jedi = new List<Jedi> { new Jedi("Yoda").MidichlorianCountIs(1000), new Jedi("Anakin Skywalker").MidichlorianCountIs(3000), new Jedi("Luke Skywalker").MidichlorianCountIs(1500), new Jedi("Obi-wan Kenobi").MidichlorianCountIs(500), }; int sum = jedi.Sum(j => j.MidichlorianCount); sum.ShouldBe(6000); }
public void 配列をたくさん作って合成() { var data = GetTestData(); for (var i = 0; i < 1000; i++) { var list = new List<double[]>(); var spectrums = new double[data.Length][]; Parallel.For( 0, data.Length, j => spectrums[j] = ArrayFactory.ByFuncDouble(GetSingleGoussianFunc(data[j].Pc, data[j].Pr), 4096)); var array = new double[4096]; Parallel.For(0, 4096, j => array[j] = list.Sum(a => a[j])); } }
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 == null); Assert.IsTrue(agg == null); }
public void should_handle_unknown_amount_of_digits() { //arrange var calc = new StringCalculator(); var countNumbers = new Random().Next(10); var list = new List<int>(); for (int i = 0; i < list.Count; i++) { list.Add(new Random().Next(10)); } //act var result = calc.Add(String.Join(",", list)); //accert result.ShouldBeEquivalentTo(list.Sum()); }
public void AggregatesTicksIntoSecondBars() { var timeProvider = new ManualTimeProvider(TimeZones.NewYork); var enumerator = new TradeBarBuilderEnumerator(Time.OneSecond, TimeZones.NewYork, timeProvider); // noon new york time var currentTime = new DateTime(2015, 10, 08, 12, 0, 0); timeProvider.SetCurrentTime(currentTime); // add some ticks var ticks = new List<Tick> { new Tick(currentTime, "SPY", 199.55m, 199, 200) {Quantity = 10}, new Tick(currentTime, "SPY", 199.56m, 199.21m, 200.02m) {Quantity = 5}, new Tick(currentTime, "SPY", 199.53m, 198.77m, 199.75m) {Quantity = 20}, new Tick(currentTime, "SPY", 198.77m, 199.75m) {Quantity = 0}, new Tick(currentTime, "SPY", 199.73m, 198.77m, 199.75m) {Quantity = 20}, new Tick(currentTime, "SPY", 198.77m, 199.75m) {Quantity = 0}, }; foreach (var tick in ticks) { enumerator.ProcessData(tick); } // even though no data is here, it will still return true Assert.IsTrue(enumerator.MoveNext()); Assert.IsNull(enumerator.Current); // advance a second currentTime = currentTime.AddSeconds(1); timeProvider.SetCurrentTime(currentTime); Assert.IsTrue(enumerator.MoveNext()); Assert.IsNotNull(enumerator.Current); // in the spirit of not duplicating the above code 5 times (OHLCV, we'll assert these ere as well) var bar = (TradeBar)enumerator.Current; Assert.AreEqual(currentTime.AddSeconds(-1), bar.Time); Assert.AreEqual(currentTime, bar.EndTime); Assert.AreEqual("SPY", bar.Symbol.Value); Assert.AreEqual(ticks.First().LastPrice, bar.Open); Assert.AreEqual(ticks.Max(x => x.LastPrice), bar.High); Assert.AreEqual(ticks.Min(x => x.LastPrice), bar.Low); Assert.AreEqual(ticks.Last().LastPrice, bar.Close); Assert.AreEqual(ticks.Sum(x => x.Quantity), bar.Volume); }
public void ShouldAggregateListOfOrderInfos() { var fullList = new List<IDepthOrderInfo>(); fullList.Add(new DepthOrderInfo { Price = 12.0001m, Amount = 1 }); fullList.Add(new DepthOrderInfo { Price = 12.99999m, Amount = 1 }); fullList.Add(new DepthOrderInfo { Price = 13.499999m, Amount = 2 }); fullList.Add(new DepthOrderInfo { Price = 13.99999m, Amount = 3 }); fullList.Add(new DepthOrderInfo { Price = 13.79m, Amount = 0.5m }); var aggregatedList = DepthHelper.GetAggregatedAskOrderList(fullList, 0.5m); Assert.AreEqual(1, aggregatedList.Find(a => a.Price == 12.0001m).Amount); Assert.AreEqual(1, aggregatedList.Find(a => a.Price == 12.5m).Amount); Assert.AreEqual(2, aggregatedList.Find(a => a.Price == 13).Amount); Assert.AreEqual(3.5, aggregatedList.Find(a => a.Price == 13.5m).Amount); Assert.AreEqual(fullList.Sum(a => a.Amount), aggregatedList.Sum(b => b.Amount)); }
public void TwoRangesWithFailureInSecond() { var oldRanges = new List<Range>(); oldRanges.Add(Range.ByPosition(10, 19)); oldRanges.Add(Range.ByPosition(30, 49)); var contentLength = oldRanges.Sum(rangeIter => rangeIter.Length); Assert.AreEqual(30, contentLength); var newRanges = JobsUtil.RetryRanges(oldRanges, 15, contentLength); Assert.AreEqual(1, newRanges.Count()); var range = newRanges.ElementAt(0); Assert.AreEqual(34, range.Start); Assert.AreEqual(49, range.End); }
public void Scan_FourDifferentBooks_ReturnsPriceWithCorrectDiscount() { // Arrange var list = new List<Book> { _book1, _book2, _book3, _book4, }; double totalPrice = list.Sum(x => x.Price); double expected = totalPrice - (totalPrice * 0.20); // Act var actual = _priceCalculator.Scan(list.ToArray()); // Assert actual.Should().Be(expected); }
public void FailureOnLastByteOfFirstRange() { var oldRanges = new List<Range> {Range.ByPosition(10, 19), Range.ByPosition(30, 49)}; var contentLength = oldRanges.Sum(rangeIter => rangeIter.Length); Assert.AreEqual(30, contentLength); var newRanges = JobsUtil.RetryRanges(oldRanges, 10, contentLength); Assert.AreEqual(2, newRanges.Count()); var range1 = newRanges.ElementAt(0); Assert.AreEqual(19, range1.Start); Assert.AreEqual(19, range1.End); var range2 = newRanges.ElementAt(1); Assert.AreEqual(30, range2.Start); Assert.AreEqual(49, range2.End); }
public void FindAllDoubleBasePalindromesBelowAMillion() { var list = new List<int>(); for (var number = 1; number < 1000000; ++number) { var result = IsDoubleBasePalindrome(number); if (result) list.Add(number); } var sumOfList = list.Sum(); Console.WriteLine("Sum: {0}", sumOfList); foreach (var number in list) { Console.WriteLine(" {0}", number); } sumOfList.Should().Be(872187); }
public void FindAllTruncatablePrimes() { var list = new List<int>(); foreach (var prime in primes) { if (prime < 8) continue; var result = IsTruncatablePrime(prime); if (result) list.Add(prime); if (list.Count == 11) break; } var sumOfList = list.Sum(); Console.WriteLine("Sum: {0}", sumOfList); foreach (var tp in list) { Console.WriteLine(" {0}", tp); } sumOfList.Should().Be(748317); }
public async Task Test_Can_Bulk_Batched_Insert_Items() { const int N = 200 * 1000; using (var db = await OpenTestPartitionAsync()) { db.DefaultTimeout = 60 * 1000; Log("Generating {0:N0} random items...", N); var location = await GetCleanDirectory(db, "Bulk", "Insert"); var rnd = new Random(2403); var data = Enumerable.Range(0, N) .Select((x) => new KeyValuePair<int, int>(x, 16 + (int)(Math.Pow(rnd.NextDouble(), 4) * 1000))) .ToList(); long totalSize = data.Sum(x => (long)x.Value); Log("Total size is ~ {0:N0} bytes", totalSize); Log("Starting..."); long called = 0; var uniqueKeys = new HashSet<int>(); var batchCounts = new List<int>(); var trSizes = new List<long>(); var sw = Stopwatch.StartNew(); long count = await Fdb.Bulk.InsertBatchedAsync( db, data, (kvps, tr) => { ++called; batchCounts.Add(kvps.Length); foreach (var kv in kvps) { uniqueKeys.Add(kv.Key); tr.Set( location.Pack(kv.Key), Slice.FromString(new string('A', kv.Value)) ); } trSizes.Add(tr.Size); //Log("> Added {0:N0} items to transaction, yielding {1:N0} bytes", kvps.Length, tr.Size); }, new Fdb.Bulk.WriteOptions() { BatchCount = 100 }, this.Cancellation ); sw.Stop(); //note: calls to Progress<T> are async, so we need to wait a bit ... Thread.Sleep(640); // "Should be enough" Log("Done in {0:N3} sec for {1:N0} keys and {2:N0} bytes", sw.Elapsed.TotalSeconds, count, totalSize); Log("> Throughput {0:N0} key/sec and {1:N3} MB/sec", count / sw.Elapsed.TotalSeconds, totalSize / (1024 * 1024 * sw.Elapsed.TotalSeconds)); Log("Called {0:N0} for {1:N0} unique keys", called, uniqueKeys.Count); Assert.That(count, Is.EqualTo(N), "count"); Assert.That(uniqueKeys.Count, Is.EqualTo(N), "unique keys"); Assert.That(batchCounts.Sum(), Is.EqualTo(N), "total of keys per batch (no retries)"); Log("Batch counts: {0}", String.Join(", ", batchCounts)); Log("Batch sizes : {0}", String.Join(", ", trSizes)); Log("Total Size : {0:N0}", trSizes.Sum()); // read everything back... Log("Reading everything back..."); var stored = await db.ReadAsync((tr) => { return tr.GetRange(location.ToRange()).ToArrayAsync(); }, this.Cancellation); Assert.That(stored.Length, Is.EqualTo(N), "DB contains less or more items than expected"); for (int i = 0; i < stored.Length; i++) { Assert.That(stored[i].Key, Is.EqualTo(location.Pack(data[i].Key)), "Key #{0}", i); Assert.That(stored[i].Value.Count, Is.EqualTo(data[i].Value), "Value #{0}", i); } // cleanup because this test can produce a lot of data await location.RemoveAsync(db, this.Cancellation); } }
private static TestResult Calculate( long[] samples ) { var max = 0L; var min = Int64.MaxValue; var sum = 0L; var unbiasedVariance = 0.0; for ( int i = 0; i < samples.Length; i++ ) { max = Math.Max( max, samples[ i ] ); min = Math.Min( min, samples[ i ] ); sum += samples[ i ]; } var average = sum * 1.0 / samples.Length; for ( int i = 0; i < samples.Length; i++ ) { unbiasedVariance += Math.Pow( samples[ i ] - average, 2 ); } unbiasedVariance /= ( samples.Length - 1 ); var unbiasedStdDev = Math.Pow( unbiasedVariance, 0.5 ); var normalSamples = new List<long>( samples.Length ); var normalLower = average - unbiasedStdDev; var normalUpper = average + unbiasedStdDev; // Filters iregular values for ( int i = 0; i < samples.Length; i++ ) { if ( normalLower < samples[ i ] && samples[ i ] < normalUpper ) { normalSamples.Add( samples[ i ] ); } } return new TestResult { AverageElapsedTicks = normalSamples.Sum() / normalSamples.Count, MaxElapsedTicks = max, MinElapsedTicks = min, StandardDeviation = unbiasedStdDev }; }
public void should_handle_unknown_amount_of_numbers() { //arrange var calc = new StringCalcClass(); var rand = new Random(); var digitsNumber = rand.Next(10); var digits = new List<int>(); for (int i = 0; i < digitsNumber; i++) { digits.Add(rand.Next(10)); } //act var result = calc.Add(string.Join(",",digits)); //assert result.ShouldBeEquivalentTo(digits.Sum()); }
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)); }
private static int Sum(List<int> listOfNumbers) { return listOfNumbers.Sum(); }
public void DeveTotalizarPrecoAoAlterarQuantidadeDeItensDoCarrinho() { var produto = ProdutoBuilder.UmProduto().ComId(1).ComPreco(500).Constroi(); var produtoDiferente = ProdutoBuilder.UmProduto().ComId(2).ComPreco(1000).Constroi(); var item = ItemPedidoBuilder.UmItem().ComProduto(produto).ComQuantidade(1).Constroi(); var itemDiferente = ItemPedidoBuilder.UmItem().ComProduto(produtoDiferente).ComQuantidade(3).Constroi(); _carrinho.Adiciona(item); _carrinho.Adiciona(itemDiferente); var itensNoCarrinho = new List<ItemPedido> { item, itemDiferente }; itensNoCarrinho.Where(i => i.Equals(item)).Single().IncrementaQuantidade(1); itensNoCarrinho.Where(i => i.Equals(itemDiferente)).Single().DecrementaQuantidade(1); _carrinho.Atualizar(itensNoCarrinho); var totalEsperado = itensNoCarrinho.Sum(i => i.Valor); Assert.AreEqual(totalEsperado, _carrinho.ValorTotal); }
public void PrintingEnumerablesWithNulls() { var list = new List<int?> { 1, 2, null, 4, 5 }; PAssert.IsTrue(() => list.Sum() == null); }