public void TestThatServerDispatchesManyRequests() { var startTime = DateExtensions.GetCurrentMillis(); var consumeCalls = _progress.ExpectConsumeTimes(TotalRequestsResponses); var totalPairs = TotalRequestsResponses / 2; var currentConsumeCount = 0; for (var idx = 0; idx < totalPairs; ++idx) { _client.RequestWith(ToStream(PostRequestCloseFollowing(UniqueJohnDoe())).ToArray()); _client.RequestWith(ToStream(PostRequestCloseFollowing(UniqueJaneDoe())).ToArray()); var expected = currentConsumeCount + 2; while (consumeCalls.TotalWrites < expected) { _client.ProbeChannel(); } currentConsumeCount = expected; } while (consumeCalls.TotalWrites < TotalRequestsResponses) { _client.ProbeChannel(); } consumeCalls.ReadFrom <int>("completed"); _output.WriteLine("TOTAL REQUESTS-RESPONSES: {0} TIME: {1} ms", TotalRequestsResponses, DateExtensions.GetCurrentMillis() - startTime); Assert.Equal(TotalRequestsResponses, _progress.ConsumeCount.Get()); _progress.Responses.TryPeek(out var createdResponse); Assert.NotNull(createdResponse.Headers.HeaderOf(ResponseHeader.Location)); }
public void CreateBusinessTripSubsistence(BusinessTrip trip, BusinessTripDTO businessTrip) { Subsistence sub = repo.Subsistences.Create(new Subsistence() { StartDate = DateExtensions.ParseAppString(businessTrip.Subsistence.StartDate), EndDate = DateExtensions.ParseAppString(businessTrip.Subsistence.EndDate), City = businessTrip.Subsistence.City, Country = repo.Dictionaries.GetCountry(businessTrip.Subsistence.CountryId) }); List <SubsistenceDay> days = new List <SubsistenceDay>(); foreach (SubsistenceDayDTO dayDto in businessTrip.Subsistence.Days) { days.Add(new SubsistenceDay() { Amount = dayDto.Amount, AmountPLN = dayDto.AmountPLN, ExchangeRate = dayDto.ExchangeRate, Breakfast = dayDto.Breakfast, Date = DateExtensions.ParseAppString(dayDto.Date), Dinner = dayDto.Dinner, Supper = dayDto.Supper, Night = dayDto.Night, Subsistence = sub, Diet = dayDto.Diet, IsForeign = dayDto.IsForeign }); } repo.SubsistenceDays.CreateSet(days); trip.Subsistence = sub; }
public void GetDateTimeFromString() { var isoDateTime = DateExtensions.Parse("2013-08-22 22:37:46"); var englishDateTime = DateExtensions.Parse("08/22/2013 10:37:46 PM"); Assert.AreEqual(isoDateTime, englishDateTime); }
public void Should_return_next_expected_date(BackupFrequency backupFrequency, string date, string expectedNextDate) { var dateValue = DateTime.ParseExact(date, "o", null, DateTimeStyles.RoundtripKind); var expectedNextDateValue = DateTime.ParseExact(expectedNextDate, "o", null, DateTimeStyles.RoundtripKind); Assert.Equal(expectedNextDateValue, DateExtensions.NextDateTime(backupFrequency, dateValue)); }
/// <summary> /// Get history for a specific well and present on page. /// </summary> /// <param name="drain"></param> /// <returns></returns> public async Task <PartialViewResult> OnGetDrainHistory(string drain) { var dateNow = DateTime.Now; int daysAgo = -1; switch (drain) { case "2O2": daysAgo = -14; break; case "2O1": daysAgo = -14; break; default: break; } var drainHistory = await _context.ActivityPerRows.Where(a => a.Address == drain) .Where(a => a.TimeUp >= dateNow.AddDays(daysAgo) && a.TimeUp <= dateNow) .Select(a => new ActivityPerDrainViewModel { TimeUp = a.TimeUp, TimeDiffString = DateExtensions.SecondsToHHMMSS(Math.Abs((a.TimeDown - a.TimeUp).TotalSeconds)) }) .OrderByDescending(a => a.TimeUp) .ToListAsync(); return(Partial("_DrainHistory", drainHistory)); }
public static string GetReportDateOverviewString(DateTime date) { int week = date.GetWeekOfTheYear(); DateTime weekStartDate = DateExtensions.GetFirstDateOfWeek(date.Year, week); return($@"Week {week} {date.Year} ({weekStartDate:dd.MM.yyyy} - {weekStartDate.AddDays(6):dd.MM.yyyy})"); }
public void TestThatMultipleResponsesParse(int responses) { var parser = ResponseParser.ParserFor(ToStream(MultipleResponseBuilder(responses)).ToArray()); Assert.True(parser.HasCompleted); Assert.True(parser.HasFullResponse()); Assert.False(parser.IsMissingContent); Assert.False(parser.HasMissingContentTimeExpired((long)DateExtensions.GetCurrentMillis() + 100)); var count = 0; var bodyIterator = _uniqueBodies.GetEnumerator(); while (parser.HasFullResponse()) { ++count; var response = parser.FullResponse(); Assert.NotNull(response); Assert.True(response.Version.IsHttp1_1()); Assert.True(bodyIterator.MoveNext()); var body = bodyIterator.Current; Assert.Equal(body, response.Entity.Content); } Assert.Equal(responses, count); bodyIterator.Dispose(); }
public void TestThatMultipleResponsesParse(int requests) { var parser = RequestParser.ParserFor(ToByteBuffer(MultipleRequestBuilder(requests))); Assert.True(parser.HasCompleted); Assert.True(parser.HasFullRequest()); Assert.False(parser.IsMissingContent); Assert.False(parser.HasMissingContentTimeExpired((long)DateExtensions.GetCurrentMillis() + 100)); var count = 0; var bodyIterator = _uniqueBodies.GetEnumerator(); while (parser.HasFullRequest()) { ++count; var request = parser.FullRequest(); Assert.NotNull(request); Assert.True(request.Method.IsPost()); Assert.Equal("/users", request.Uri.PathAndQuery); Assert.True(request.Version.IsHttp1_1()); Assert.True(bodyIterator.MoveNext()); var body = bodyIterator.Current; Assert.Equal(body, request.Body.Content); } Assert.Equal(requests, count); bodyIterator.Dispose(); }
public ServerActor( Resources resources, Filters filters, int port, int dispatcherPoolSize) { var start = DateExtensions.GetCurrentMillis(); _filters = filters; _world = Stage.World; _requestsMissingContent = new Dictionary <string, RequestResponseHttpContext>(); _maxMessageSize = 0; try { _dispatcherPool = new AgentDispatcherPool(Stage, resources, dispatcherPoolSize); var end = DateExtensions.GetCurrentMillis(); Logger.Info($"Server {ServerName} is listening on port: {port} started in {end - start} ms"); LogResourceMappings(resources); } catch (Exception e) { var message = $"Failed to start server because: {e.Message}"; Logger.Error(message, e); throw new InvalidOperationException(message); } }
public void ChangeDate_AddOneYear_ReturnDateToNextYear() { var extension = new DateExtensions(); var result = extension.ChangeDate("01/02/2010 23:00", '+', 525600); Assert.AreEqual("01/02/2011 23:00", result); }
public void ChangeDate_AddOneMinute_ReturnDateWithOneMinuteMore() { var extension = new DateExtensions(); var result = extension.ChangeDate("01/03/2010 23:00", '+', 1); Assert.AreEqual("01/03/2010 23:01", result); }
public void ChangeDate_TakingAnHour_ReturnDateOneHourLess() { var extension = new DateExtensions(); var result = extension.ChangeDate("01/03/2010 23:00", '-', 60); Assert.AreEqual("01/03/2010 22:00", result); }
public void ChangeDate_AddTreeDay_ReturnDateWithTreeDayMore() { var extension = new DateExtensions(); var result = extension.ChangeDate("01/03/2010 23:00", '+', 4320); Assert.AreEqual("04/03/2010 23:00", result); }
public void ChangeDate_TestNegativeValue_ReturnDateTwoYearLessWithNegativeValue() { var extension = new DateExtensions(); var result = extension.ChangeDate("01/03/2010 23:00", '-', +1051200); Assert.AreEqual("01/03/2008 23:00", result); }
public void ChangeDate_TakingTwoYear_ReturnDateTwoYearLess() { var extension = new DateExtensions(); var result = extension.ChangeDate("01/03/2010 23:00", '-', 1051200); Assert.AreEqual("01/03/2008 23:00", result); }
public void ChangeDate_TakingOneMonth_ReturnDateOneMonthLess() { var extension = new DateExtensions(); var result = extension.ChangeDate("01/03/2010 23:00", '-', 43200); Assert.AreEqual("30/01/2010 23:00", result); }
public void ChangeDate_TakingThreeDays_ReturnDateThreeDaysLess() { var extension = new DateExtensions(); var result = extension.ChangeDate("01/03/2010 23:00", '-', 4320); Assert.AreEqual("26/02/2010 23:00", result); }
public void ChangeDate_TakingOneDay_ReturnDateOneDayLess() { var extension = new DateExtensions(); var result = extension.ChangeDate("01/03/2010 23:00", '-', 1440); Assert.AreEqual("28/02/2010 23:00", result); }
public void ChangeDate_AddFirstDayOfFebuaryAndAddThirtyDays_ReturnDateThirtyDayOfMarch() { var extension = new DateExtensions(); var result = extension.ChangeDate("01/02/2010 23:00", '+', 43200); Assert.AreEqual("03/03/2010 23:00", result); }
public void ChangeDate_AddTwoHour_ReturnDateWithOneDayMore() { var extension = new DateExtensions(); var result = extension.ChangeDate("01/03/2010 23:00", '+', 120); Assert.AreEqual("02/03/2010 01:00", result); }
public void ChangeDate_Challenge_ReturnDateToChallenge() { var extension = new DateExtensions(); var result = extension.ChangeDate("01/03/2010 23:00", '+', 4000); Assert.AreEqual("04/03/2010 17:40", result); }
public void xDigitYear() { Assert.Equal(18, DateExtensions.DoubleDigitYear(2018)); Assert.Equal(8, DateExtensions.SingleDigitYear(2018)); Assert.Equal(28, DateExtensions.DoubleDigitYear(2028)); Assert.Equal(8, DateExtensions.SingleDigitYear(2028)); }
public Order(Models.Order order, Models.Customer customer, Models.Item[] items) { Id = order.Id.ToString(); DateTimeStamp = DateExtensions.ConvertToJS(order.DateTimeStamp); IsCompleted = order.IsCompleted; Customer = new Entity(customer.Id.ToString(), customer.Name); Items = items.Select(item => new OrderItem(item)).ToArray(); }
public ServerActor( Resources resources, Filters filters, int port, Configuration.SizingConf sizing, Configuration.TimingConf timing, string channelMailboxTypeName) { var start = DateExtensions.GetCurrentMillis(); _filters = filters; _dispatcherPoolIndex = 0; _world = Stage.World; _requestsMissingContent = new Dictionary <string, RequestResponseHttpContext>(); _maxMessageSize = sizing.MaxMessageSize; try { _responseBufferPool = new ConsumerByteBufferPool( ElasticResourcePool <IConsumerByteBuffer, Nothing> .Config.Of(sizing.MaxBufferPoolSize), sizing.MaxMessageSize); _dispatcherPool = new IDispatcher[sizing.DispatcherPoolSize]; for (int idx = 0; idx < sizing.DispatcherPoolSize; ++idx) { _dispatcherPool[idx] = Dispatcher.StartWith(Stage, resources); } _channel = ServerRequestResponseChannelFactory.Start( Stage, Stage.World.AddressFactory.WithHighId(ChannelName), channelMailboxTypeName, this, port, ChannelName, sizing.ProcessorPoolSize, sizing.MaxBufferPoolSize, sizing.MaxMessageSize, timing.ProbeInterval, timing.ProbeTimeout); var end = DateExtensions.GetCurrentMillis(); Logger.Info($"Server {ServerName} is listening on port: {port} started in {end - start} ms"); _requestMissingContentTimeout = timing.RequestMissingContentTimeout; LogResourceMappings(resources); } catch (Exception e) { var message = $"Failed to start server because: {e.Message}"; Logger.Error(message, e); throw new InvalidOperationException(message); } }
public static ChatServerCopyMessage GetChatServerCopyMessage(ChatActivableChannelsEnum channel, string message, WorldClient client, WorldClient target) { return(new ChatServerCopyMessage((sbyte)ChatActivableChannelsEnum.PSEUDO_CHANNEL_PRIVATE, message, (int)DateExtensions.DateTimeToUnixTimestamp(DateTime.Now), client.Character.Record.Name, (uint)target.Character.Record.Id, target.Character.Record.Name)); }
public static RiskyFlySurface GetSurfaceForCode(string nymexSymbol, string nymexOptionFilename, string qwackCode, BasicPriceCurve priceCurve, ICalendarProvider calendarProvider, ICurrencyProvider currency, IFutureSettingsProvider futureSettingsProvider) { var parsed = NYMEXOptionParser.Instance.Parse(nymexOptionFilename).Where(r => r.Symbol == nymexSymbol); var(optionExerciseType, optionMarginingType) = OptionTypeFromCode(nymexSymbol); var origin = DateTime.ParseExact(parsed.First().TradeDate, "MM/dd/yyyy", CultureInfo.InvariantCulture); var q = parsed.Where(x => x.Settle > 0).Select(x => new ListedOptionSettlementRecord { CallPut = x.PutCall == "C"?OptionType.C:OptionType.P, ExerciseType = optionExerciseType, MarginType = optionMarginingType, PV = x.Settle, Strike = x.Strike, UnderlyingFuturesCode = Year2to1(x.Contract.Split(' ')[0].Replace(nymexSymbol, qwackCode)), ExpiryDate = OptionExpiryFromNymexRecord(x, calendarProvider), ValDate = origin }).Where(z => z.ExpiryDate > origin).ToList(); var priceDict = priceCurve.PillarLabels.ToDictionary(x => x, x => priceCurve.GetPriceForDate(priceCurve.PillarDatesForLabel(x))); ListedSurfaceHelper.ImplyVols(q, priceDict, new ConstantRateIrCurve(0.0, origin, "dummy", currency.GetCurrency("USD"))); var smiles = ListedSurfaceHelper.ToDeltaSmiles(q, priceDict); var allOptionExpiries = new List <DateTime>(); var lastDate = q.Max(x => x.ExpiryDate); var dummyFutureCode = $"{qwackCode}Z{DateExtensions.SingleDigitYear(DateTime.Today.Year + 2)}"; var c = new FutureCode(dummyFutureCode, DateTime.Today.Year - 2, futureSettingsProvider); var contract = c.GetFrontMonth(origin, false); var lastContract = c.GetFrontMonth(lastDate, false); while (contract != lastContract) { var cc = new FutureCode(contract, origin.Year, futureSettingsProvider); var exp = ListedUtils.FuturesCodeToDateTime(contract); var record = new NYMEXOptionRecord { ContractMonth = exp.Month, ContractYear = exp.Year, Symbol = nymexSymbol }; var optExpiry = OptionExpiryFromNymexRecord(record, calendarProvider); if (optExpiry > origin) { allOptionExpiries.Add(optExpiry); } contract = cc.GetNextCode(false); } var surface = ListedSurfaceHelper.ToRiskyFlySurfaceStepFlat(smiles, origin, priceCurve, allOptionExpiries, currency); return(surface); }
public static ChatServerMessage GetChatServerMessage(ChatActivableChannelsEnum channel, string message, WorldClient client) { return(new ChatServerMessage((sbyte)channel, message, (int)DateExtensions.DateTimeToUnixTimestamp(DateTime.Now), string.Empty, client.Character.Id, client.Character.Name, client.Account.Id)); }
public void PVFacts() { var t = 1.0; var t2 = 2.0; var k = 0; var f = 100; var vol = 0.32; var rf = 0.05; var cp = OptionType.P; //expired is worthless var PV = TurnbullWakeman.PV(f, 0, vol, 0, t, 0, rf, OptionType.P); Assert.Equal(0, PV, 10); PV = TurnbullWakeman.PV(f, 0, vol, 0, t, 0, rf, OptionType.C); Assert.Equal(0, PV, 10); //zero strike put is worthless PV = TurnbullWakeman.PV(f, 0, vol, 0, t, t2, rf, cp); Assert.Equal(0, PV, 10); PV = TurnbullWakeman.PV(f, 50, vol, 0, -0.1, t2, rf, cp); Assert.Equal(0, PV, 10); //zero strike call is worth discounted fwd cp = OptionType.C; PV = TurnbullWakeman.PV(f, 0, vol, 0, t, t2, rf, cp); Assert.Equal(System.Math.Exp(-rf * t2) * f, PV, 2); //OTM option with zero vol is worthless vol = 0.0; k = f + 1; PV = TurnbullWakeman.PV(f, k, vol, 0, t, t2, rf, cp); Assert.Equal(0, PV, 10); //put-call parity at f==k k = f; vol = 0.32; var PVcall = TurnbullWakeman.PV(f, 0, vol, k, t, t2, rf, OptionType.C); var PVput = TurnbullWakeman.PV(f, 0, vol, k, t, t2, rf, OptionType.P); Assert.Equal(PVcall, PVput, 2); //independent fwds version var valDate = new DateTime(2019, 10, 24); var fixingStartDate = new DateTime(2019, 10, 01); var fixingEndDate = new DateTime(2019, 10, 25); var fixingDates = DateExtensions.BusinessDaysInPeriod(fixingStartDate, fixingEndDate, TestProviderHelper.CalendarProvider.Collection["NYC"]).ToArray(); var fwds = fixingDates.Select(x => 100.0).ToArray(); var sigmas = fixingDates.Select(x => 0.32).ToArray(); PV = TurnbullWakeman.PV(fwds, fixingDates, valDate, fixingEndDate, sigmas, 1, 0.0, OptionType.C, true); var blackPV = BlackFunctions.BlackPV(100.0, 1, 0.0, 1 / 365.0, 0.32, OptionType.C); Assert.Equal(blackPV, PV, 4); }
/// <summary> /// Initialises the Entity Framework model /// </summary> /// <param name="modelBuilder">EF model builder</param> protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ConfigureConventions(); ConfigureManyToMany(modelBuilder); // Special cases modelBuilder.Entity <ProjectTechnologyModel>().ToTable("project_techs"); modelBuilder.Entity <PostModel>().ToTable("blog_posts"); modelBuilder.Entity <PostModel>().Property(x => x.MainCategoryId).HasColumnName("maincategory_id"); modelBuilder.Entity <CategoryModel>().ToTable("blog_categories"); modelBuilder.Entity <CategoryModel>().Property(x => x.ParentId).HasColumnName("parent_category_id"); modelBuilder.Entity <TagModel>().ToTable("blog_tags"); modelBuilder.Entity <TagModel>().Property(x => x.ParentId).HasColumnName("parent_tag_id"); modelBuilder.Entity <DisqusCommentModel>() .ToTable("disqus_comments") .Ignore(x => x.Children); modelBuilder.Entity <PostModel>() .Property(x => x.RawContent) .HasColumnName("content"); // Backwards compatibility with old DB - Dates as UNIX times modelBuilder.Entity <PostModel>() .Property(x => x.Date) .HasConversion( x => x.ToUnix(), x => DateExtensions.FromUnix(x) ); modelBuilder.Entity <PostModel>() .Property(x => x.ShareCounts) .HasColumnName("share_counts") .HasConversion( x => JsonConvert.SerializeObject(x), x => string.IsNullOrEmpty(x) ? null : JsonConvert.DeserializeObject <IDictionary <string, int> >(x) ); modelBuilder.Entity <ProjectModel>() .Property(x => x.ProjectType) .HasColumnName("type") .HasConversion( x => x.ToString(), x => x.FirstUpper().ParseEnum <ProjectType>() ); modelBuilder.Entity <ProjectModel>() .Property(x => x.Technologies) .HasConversion( x => string.Join(",", x), x => x.Split(',') ); }
public static DateTime?StartPublishedNormalized(this IVersionable versionable) { ObjectExtensions.ValidateNotNullArgument((object)versionable, "versionable"); if (versionable.StartPublish.HasValue) { return(new DateTime?(DateExtensions.NormalizeToMinutes(versionable.StartPublish.Value))); } else { return(new DateTime?()); } }