コード例 #1
0
        public DateTime?GetInitialSpanDate(long PeriodicSpan)
        {
            DateTime?result = Machine.ActivationDate;

            if (IgnoreDate == null || PeriodicSpan == 0)
            {
                return(result);
            }

            if (IgnoreDate != null)
            {
                result = IgnoreDate;
            }

            while (result < DateTime.UtcNow)
            {
                DateTime?newInit = result?.AddHours(PeriodicSpan);

                if (newInit < DateTime.UtcNow)
                {
                    result = result?.AddHours(PeriodicSpan);
                    if (result > IgnoreDate)
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            return(result);
        }
コード例 #2
0
            public static DateTime InstantToDateTime(double instant, DateTime start, TimeUnits units = TimeUnits.SECONDS)
            {
                DateTime instantAsDate = start;

                switch (units)
                {
                   case TimeUnits.YEARS:
                  instantAsDate = start.AddYears((int)instant);
                  break;
                   case TimeUnits.MONTHS:
                  instantAsDate = start.AddMonths((int)instant);
                  break;
                   case TimeUnits.DAYS:
                  instantAsDate = start.AddDays(instant);
                  break;
                   case TimeUnits.HOURS:
                  instantAsDate = start.AddHours(instant);
                  break;
                   case TimeUnits.MINUTES:
                  instantAsDate = start.AddMinutes(instant);
                  break;
                   case TimeUnits.SECONDS:
                  instantAsDate = start.AddSeconds(instant);
                  break;
                }

                return instantAsDate;
            }
コード例 #3
0
        private static async Task UpdateFlightInCalendars(List <string> crewMembers, int flightNumber, string departureGate, DateTime?newDepartureTime = null)
        {
            foreach (var userId in crewMembers)
            {
                // Get the event
                var matchingEvents = await graphClient.GetEventsInUserCalendar(userId,
                                                                               $"categories/any(a:a eq 'Assigned Flight') and subject eq 'Flight {flightNumber}'");

                var flightEvent = matchingEvents.CurrentPage.FirstOrDefault();
                if (flightEvent != null)
                {
                    if (newDepartureTime != null)
                    {
                        flightEvent.Start.DateTime = newDepartureTime?.ToString("s");
                        flightEvent.End.DateTime   = newDepartureTime?.AddHours(4).ToString("s");
                        await graphClient.UpdateEventInUserCalendar(userId, flightEvent);
                    }

                    var flightExtension = new OpenTypeExtension
                    {
                        ODataType      = "microsoft.graph.openTypeExtension",
                        ExtensionName  = "com.contoso.flightData",
                        AdditionalData = new Dictionary <string, object>()
                    };

                    flightExtension.AdditionalData.Add("departureGate", departureGate);
                    flightExtension.AdditionalData.Add("crewMembers", crewMembers);

                    await graphClient.UpdateFlightExtension(userId, flightEvent.Id, flightExtension);
                }
            }
        }
コード例 #4
0
ファイル: HomeController.cs プロジェクト: dargirov/mugcore
        public IActionResult Index(DateTime?from, DateTime?to)
        {
            var orders           = this.orders.Get().Where(o => o.ConfirmationStatus != ConfirmationStatus.Denied).ToList();
            var bulletins        = this.bulletins.Get().OrderByDescending(b => b.Id).ToList();
            var feedbacks        = this.feedbacks.Get().OrderByDescending(x => x.IsNew).ThenByDescending(x => x.Id).ToList();
            var imagesCount      = this.images.Get().Count();
            var priceChartOrders = new List <Order>();

            foreach (var order in this.orders.Get().Where(o => o.OrderStatus == OrderStatus.Finalized))
            {
                if (!priceChartOrders.Any(x => x.CreatedOn.ToShortDateString() == order.CreatedOn.ToShortDateString()))
                {
                    priceChartOrders.Add(order);
                }
            }

            var firstDayOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

            var viewModel = new IndexViewModel()
            {
                Orders              = orders,
                Bulletin            = bulletins,
                ImagesCount         = imagesCount,
                PriceChartOrders    = priceChartOrders,
                Feedbacks           = feedbacks,
                LogErrorMessages    = this.logger.GetLogMessages(x => x.Code == "500"),
                LogNotFoundMessages = this.logger.GetLogMessages(x => x.Code == "400"),
                StatsFrom           = from ?? firstDayOfMonth,
                StatsTo             = to?.AddHours(23).AddMinutes(59).AddSeconds(59) ?? firstDayOfMonth.AddMonths(1).AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59),
            };

            return(this.View(viewModel));
        }
コード例 #5
0
        protected override async void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            if (requestCode == 200 && resultCode == Result.Ok)
            {
                int      hour          = data.GetIntExtra("hour", 0);
                int      minute        = data.GetIntExtra("minute", 0);
                DateTime?scheduledTime = DateTime.Today;
                if (hour == 0 && minute == 0)
                {
                    scheduledTime = null;
                }
                else
                {
                    scheduledTime = scheduledTime?.AddHours(hour).AddMinutes(minute);
                }


                long   healthServiceId = data.GetLongExtra("serviceId", 0);
                string token           = SettingsHelper.GetToken(this);

                appState = AppState.Searching;
                Picasso.With(this).Load(Resource.Drawable.button_searching).Into(btnGo);
                pulsator.Visibility = ViewStates.Visible;
                helpView.SetText(Resource.String.searching);

                Animation animation = new TranslateAnimation(0, 0, 0, 250);
                animation.Duration  = 300;
                animation.FillAfter = true;
                helpView.StartAnimation(animation);

                pulsator.Stop();
                pulsator.Start();

                double latitude = -6.791992, longitude = 39.208219;
                if (_currentLocation != null)
                {
                    latitude  = _currentLocation.Latitude;
                    longitude = _currentLocation.Longitude;
                }
                ServiceRequest request = new ServiceRequest()
                {
                    Latitude        = latitude,
                    Longitude       = longitude,
                    Status          = RequestStatus.Initiated,
                    HealthServiceId = healthServiceId,
                    ScheduledTime   = scheduledTime
                };

                requestId = await ServiceHelper.LogRequest(token, request);

                if (requestId > 0)
                {
                    //timer = new Timer(2000);
                    //timer.Elapsed += Timer_Elapsed;
                    //timer.Start();
                }
            }
            base.OnActivityResult(requestCode, resultCode, data);
        }
コード例 #6
0
        public IQueryable <TituloDespesaPagamentoResumoVW> listarPagamentoDespesas(string descricao, int idCentroCusto, int idMacroConta, int idContaBancaria, string flagPago, string pesquisarPor, DateTime?dtInicio, DateTime?dtFim)
        {
            var query = from OTituloDespesaPag in db.TituloDespesaPagamentoResumoVW
                        .Where(x => x.dtExclusao == null) select OTituloDespesaPag;

            query = query.condicoesSeguranca();

            if (!String.IsNullOrEmpty(descricao))
            {
                int buscaNumerica = descricao.onlyNumber().toInt();

                if (buscaNumerica > 0)
                {
                    query = query.Where(x => (x.idTituloPagamento == buscaNumerica || x.idTituloDespesa == buscaNumerica));
                }
                else
                {
                    query = query.Where(x =>
                                        (x.descricao.Contains(descricao) ||
                                         x.descParcela.Contains(descricao) ||
                                         x.nomePessoa.Contains(descricao) ||
                                         x.nroDocumentoPessoa == descricao));
                }
            }

            if (idCentroCusto > 0)
            {
                query = query.Where(x => x.idCentroCusto == idCentroCusto);
            }


            if (idMacroConta > 0)
            {
                query = query.Where(x => x.idMacroConta == idMacroConta);
            }

            if (idContaBancaria > 0)
            {
                query = query.Where(x => x.idContaBancaria == idContaBancaria);
            }

            if (!String.IsNullOrEmpty(flagPago))
            {
                query = (flagPago == "S") ? query.Where(x => x.dtPagamento != null) : query.Where(x => x.dtPagamento == null);
            }

            dtFim = dtFim?.AddHours(23).AddMinutes(59).AddSeconds(59);

            if (pesquisarPor == "P")
            {
                query = query.Where(x => (x.dtPagamento >= dtInicio) && (x.dtPagamento <= dtFim));
            }
            else
            {
                query = query.Where(x => (x.dtVencimentoDespesa >= dtInicio) && (x.dtVencimentoDespesa <= dtFim));
            }

            return(query);
        }
コード例 #7
0
ファイル: SspiSecurityToken.cs プロジェクト: smulholland2/wcf
 public SspiSecurityToken(NetworkCredential networkCredential, bool extractGroupsForWindowsAccounts, bool allowUnauthenticatedCallers)
 {
     _networkCredential = SecurityUtils.GetNetworkCredentialsCopy(networkCredential);
     _extractGroupsForWindowsAccounts = extractGroupsForWindowsAccounts;
     _allowUnauthenticatedCallers = allowUnauthenticatedCallers;
     _effectiveTime = DateTime.UtcNow;
     _expirationTime = _effectiveTime.AddHours(10);
 }
コード例 #8
0
ファイル: SspiSecurityToken.cs プロジェクト: smulholland2/wcf
 public SspiSecurityToken(TokenImpersonationLevel impersonationLevel, bool allowNtlm, NetworkCredential networkCredential)
 {
     _impersonationLevel = impersonationLevel;
     _allowNtlm = allowNtlm;
     _networkCredential = SecurityUtils.GetNetworkCredentialsCopy(networkCredential);
     _effectiveTime = DateTime.UtcNow;
     _expirationTime = _effectiveTime.AddHours(10);
 }
コード例 #9
0
ファイル: DateTimeTests.cs プロジェクト: kronic/corefxlab
        public void CanAddHoursAcrossDstTransition_StartWithMismatchedKind()
        {
            var tz = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
            var dt = new DateTime(2015, 3, 8, 9, 0, 0, DateTimeKind.Utc);
            var result = dt.AddHours(1, tz);

            var expected = new DateTimeOffset(2015, 3, 8, 3, 0, 0, TimeSpan.FromHours(-7));
            Assert.Equal(expected, result);
            Assert.Equal(expected.Offset, result.Offset);
        }
コード例 #10
0
        public IQueryable <TituloReceitaPagamentoResumoVW> listarPagamentoReceitasExcluidas(string descricao, int idCentroCusto, int idTipoReceita, string flagPago, string pesquisarPor, DateTime?dtInicio, DateTime?dtFim, int?idMacroConta, int?idContaBancaria)
        {
            var query = from TR in this.db.TituloReceitaPagamentoResumoVW
                        .Where(x => x.dtExclusao != null)
                        select TR;

            query = query.condicoesSeguranca();

            if (!String.IsNullOrEmpty(descricao))
            {
                query = query.Where(x => x.descricao.Contains(descricao));
            }

            if (idCentroCusto > 0)
            {
                query = query.Where(x => x.idCentroCusto == idCentroCusto);
            }

            if (idMacroConta > 0)
            {
                query = query.Where(x => x.idMacroConta == idMacroConta);
            }

            if (idContaBancaria > 0)
            {
                query = query.Where(x => x.idContaBancaria == idContaBancaria);
            }

            if (!String.IsNullOrEmpty(flagPago))
            {
                query = (flagPago == "S") ? query.Where(x => x.dtPagamento != null) : query.Where(x => x.dtPagamento == null);
            }

            dtFim = dtFim?.AddHours(23).AddMinutes(59).AddSeconds(59);

            if (pesquisarPor == "P")
            {
                query = query.Where(x => (x.dtPagamento >= dtInicio) && (x.dtPagamento <= dtFim));
            }
            else if (pesquisarPor == "E")
            {
                query = query.Where(x => (x.dtExclusao >= dtInicio) && (x.dtExclusao <= dtFim));
            }
            else if (pesquisarPor == "C")
            {
                query = query.Where(x => (x.dtCredito >= dtInicio) && (x.dtCredito <= dtFim));
            }
            else
            {
                query = query.Where(x => (x.dtVencimentoRecebimento >= dtInicio) && (x.dtVencimentoRecebimento <= dtFim));
            }

            return(query);
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: wagnerteixeira/systore
 static DateTime?addhour(DateTime?dateTime)
 {
     if (dateTime.HasValue)
     {
         if ((dateTime?.Hour == 2) && (dateTime?.Minute == 0))
         {
             return(dateTime?.AddHours(1));
         }
         else
         {
             return(dateTime);
         }
     }
     else
     {
         return(dateTime);
     }
 }
        private void fillList()
        {
            int    low = 0; int height = 0; int middle = 0; int ok = 0;
            double lowMin = 0; double heightMin = 0; double middleMin = 0; double okMin = 0;
            double lowMinDay = 0; double heightMinDay = 0; double middleMinDay = 0; double okMinDay = 0;
            int    lowDay = 0; int heightDay = 0; int middleDay = 0; int okDay = 0;

            if (_context.TemperatureSekv.Any())
            {
                var listTemp = _context.TemperatureSekv.ToList();
                Helpers.SekvenceHelper.LimitCheck loader = new Helpers.SekvenceHelper.LimitCheck();
                //DateTime actualForSummary = DateTime.Parse("2017-01-01T12:04:19Z");
                DateTime actualForSummary = DateTime.Now;

                foreach (var t in listTemp)
                {
                    DateTime convertedDate = DateTime.Parse(t.TimeStart);
                    String   durationTime = null;
                    String   endTimeString = "NA"; String endDateString = "";
                    double   time = 0;
                    try
                    {
                        DateTime endtime = DateTime.Parse(t.TimeClose);
                        time = (endtime - convertedDate).TotalMinutes;
                        var x = time - Math.Truncate(time);
                        durationTime  = Math.Truncate(time).ToString() + " min " + Math.Round(x * 60).ToString() + " sec";
                        endDateString = endtime.ToLongDateString();
                        endTimeString = endtime.ToLongTimeString();
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine("Exception parse date " + e.ToString());
                        durationTime = "NA";
                    }

                    if (actualForSummary <= convertedDate.AddHours(12))
                    {
                        switch (t.Upozornenie)
                        {
                        case 0: ok++;
                            okMin += time;
                            break;

                        case 1: low++;
                            lowMin += time;

                            break;

                        case -1: low++;
                            lowMin += time;

                            break;

                        case 2: middle++;
                            middleMin += time;

                            break;

                        case 3: height++;
                            heightMin += time;

                            break;
                        }
                    }

                    if (actualForSummary <= convertedDate.AddHours(24))
                    {
                        switch (t.Upozornenie)
                        {
                        case 0:
                            okDay++;
                            okMinDay += time;

                            break;

                        case 1:
                            lowDay++;
                            lowMinDay += time;

                            break;

                        case -1:
                            lowDay++;
                            lowMinDay += time;

                            break;

                        case 2:
                            middleDay++;
                            middleMinDay += time;

                            break;

                        case 3:
                            heightDay++;
                            heightMinDay += time;

                            break;
                        }
                    }

                    TemperatureObj tem = new TemperatureObj()
                    {
                        TempId      = t.TeplSekvId,
                        Value       = "~" + t.Sekvencia.ToString("n2") + " °C",
                        LongDate    = convertedDate.ToLongDateString(),
                        Date        = convertedDate.ToShortDateString(),
                        Time        = convertedDate.ToLongTimeString(),
                        DateEnd     = endDateString,
                        TimeEnd     = endTimeString,
                        Duration    = durationTime,
                        Upozornenie = t.Upozornenie,
                        Alert       = loader.getStringValuePulseAndTempLimit(t.Upozornenie)
                    };

                    SequenceList.Add(tem);
                }
                fillPageWithSequence(SequenceList.Last());
            }
            else
            {
                TempAlert = "Neexistuje žiadna sekvencia";
            }

            HeightTwelve = "Vysoké: ~" + Math.Truncate(heightMin).ToString() + " min";
            MiddleTwelve = "Stredné: ~" + Math.Truncate(middleMin).ToString() + " min";
            LowTwelve    = "Slabé: ~" + Math.Truncate(lowMin).ToString() + " min";
            OkTwelve     = "OK: ~" + Math.Truncate(okMin).ToString() + " min";

            HeightDay = HeightTwelve = "Vysoké: ~" + Math.Truncate(heightMinDay).ToString() + " min";
            MiddleDay = "Stredné: ~" + Math.Truncate(middleMinDay).ToString() + " min";
            LowDay    = "Slabé: ~" + Math.Truncate(lowMinDay).ToString() + " min";
            OkDay     = "OK: ~" + Math.Truncate(okMinDay).ToString() + " min";

            // System.Diagnostics.Debug.WriteLine("/////CAS: " + okMin + " " + lowMin + " " + middleMin + " " + heightMin  + " " + Math.Truncate(okMin).ToString());


            SequenceList = new ObservableCollection <TemperatureObj>(SequenceList.Reverse());
        }
コード例 #13
0
    /// <summary>
    /// Unites the data sources and compiles it to a file
    /// </summary>
    /// <returns>file name of the compiled file</returns>
    private string uniteFiles(string fileName)
    {
        string retval = "";

        //Set up the Unite Object
        ASAUniteV3._BlackNite uniter = new ASAUniteV3.BlackNite();
        uniter.Init();
        uniter.AOI_West      = (float)_BBox.west;
        uniter.AOI_East      = (float)_BBox.east;
        uniter.AOI_North     = (float)_BBox.north;
        uniter.AOI_South     = (float)_BBox.south;
        uniter.AOI_startTmin = DateTime2Int(_StartDate.AddHours(0));
        uniter.AOI_endTmin   = DateTime2Int(_EndDate.AddHours(10));
        uniter.DepthFile     = _BathyLocation + "\\ETOP2.dos";
        uniter.CellSizeKm    = 5;
        uniter.OutNCType     = 1;
        uniter.OutUnit       = "Knots";
        uniter.TimeStepMin   = 60;
        if (outputDirectory.Contains("WINDS"))
        {
            uniter.WindOut = true;
        }
        else
        {
            uniter.WindOut = false;
        }
        uniter.Sources = "WUHAN";
        //Loop through and add all the files
        if (_FileList.Count == 0)
        {
            return("ERROR: No files found in the given time range");
        }

        foreach (string file in _FileList)
        {
            uniter.AddFiles(file);
        }

        try
        {
            int status = 0;
            retval = _OuputDirectory + fileName + ".nc";
            if (uniter.Make(retval) > -1)
            {
                string blank = "";
                while (status < 100)
                {
                    status = uniter.Progress(ref blank);
                    if (status < 0)
                    {
                        retval = "ERROR: ASAUnite has failed" + uniter.Error;
                        break;
                    }
                }
            }
            else
            {
                retval = "ERROR: " + uniter.Error;
            }
        }
        catch (Exception ex)
        {
            retval = "ERROR: " + ex.Message;
        }
        return(retval);
    }
コード例 #14
0
        private DateTime?ProcessHourlyPattern(RecurrenceRule recurrence, RecurrenceRuleException[] exceptions,
                                              int timeZoneShift)
        {
            try
            {
                log.LogFunctionStart();

                var      startDate      = recurrence.StartDate ?? DateTime.UtcNow;
                DateTime?targetDate     = startDate;
                var      spanSinceStart = (int)(DateTime.UtcNow - startDate).TotalHours;

                var occurrenceCount = recurrence.OccurrenceCount;

                if (targetDate < DateTime.UtcNow)
                {
                    if (occurrenceCount != null)
                    {
                        occurrenceCount -= spanSinceStart / recurrence.HourlyFrequency + 1;
                        log.Log($"Remaining occurrences: {occurrenceCount}");
                    }

                    targetDate = targetDate?.AddHours(spanSinceStart - (spanSinceStart % recurrence.HourlyFrequency ?? 1));
                    log.Log($"New target date after jump range: {targetDate}.", LogLevel.Debug);
                }

                var exceptionRetryCount = 10000;

                while (true)
                {
                    if (occurrenceCount != null && occurrenceCount <= 0)
                    {
                        log.Log("Occurrences exceeded.", LogLevel.Warning);
                        targetDate = null;
                        break;
                    }

                    if (targetDate > recurrence.EndDate)
                    {
                        log.Log("Generated date exceeds the end date.", LogLevel.Warning);
                        targetDate = null;
                        break;
                    }

                    targetDate = targetDate.Value.AddHours(recurrence.HourlyFrequency ?? 1);

                    // must be in the future
                    if (targetDate >= DateTime.UtcNow)
                    {
                        // not excluded
                        if (IsExcluded(targetDate.Value, exceptions, timeZoneShift))
                        {
                            // too many exclusion retries could lead to an infinite loop
                            if (--exceptionRetryCount <= 0)
                            {
                                throw new InvalidPluginExecutionException("Couldn't find a target date." +
                                                                          " Please relax the exclusion rules.");
                            }

                            continue;
                        }

                        break;
                    }

                    occurrenceCount--;
                }

                log.Log($"Target date: {targetDate}");

                return(targetDate);
            }
            catch (Exception ex)
            {
                log.Log(ex);
                throw;
            }
            finally
            {
                log.LogFunctionEnd();
            }
        }
コード例 #15
0
 public static DateTime NormalizeHour(DateTime tm, int hourOffset = 0)
 {
     return(tm.AddHours(-hourOffset).AddMinutes(-tm.Minute).AddSeconds(-tm.Second).AddMilliseconds(-tm.Millisecond));
 }
コード例 #16
0
 public static DateTime NormalizeDay(DateTime tm)
 {
     return(tm.AddHours(-tm.Hour).AddMinutes(-tm.Minute).AddSeconds(-tm.Second).AddMilliseconds(-tm.Millisecond));
 }
コード例 #17
0
        private void initiateComputationVariables()
        {
            // Early OT or OT of from yesterday
            //  This may be special for client
            scheduledTimeIn = day;
            scheduledTimeIn = scheduledTimeIn.ChangeTime(employeeWorkSchedule.WorkSchedule.TimeStart.Hours,
                                                         employeeWorkSchedule.WorkSchedule.TimeStart.Minutes, 0, 0);

            scheduledTimeOut = day;
            // If scheduled clock out time is less than clock in time
            // scheduled out should be tomorrow
            if (employeeWorkSchedule.WorkSchedule.TimeEnd < employeeWorkSchedule.WorkSchedule.TimeStart)
            {
                scheduledTimeOut = day.AddDays(1);
            }

            scheduledTimeOut = scheduledTimeOut.ChangeTime(employeeWorkSchedule.WorkSchedule.TimeEnd.Hours,
                                                           employeeWorkSchedule.WorkSchedule.TimeEnd.Minutes, 0, 0);

            clockIn = attendance.ClockIn;
            // Count hour before 12 midnight
            // If different date set clock in to 12AM
            if (attendance.ClockIn.Date.CompareTo(day.Date) < 0)
            {
                clockIn = day;
            }

            clockOut = attendance.ClockOut;

            if (clockOut.Value.Date.CompareTo(day.Date) > 0)
            {
                clockOut = day.AddDays(1);
            }

            // TODO I assume that the night dif start time starts at night time yesterday
            // and end time is morning of today's date
            var ndStartTime = DateTime.Parse(_settingService.GetByKey(SCHEDULE_NIGHTDIF_TIME_START));
            var ndEndTime   = DateTime.Parse(_settingService.GetByKey(SCHEDULE_NIGHTDIF_TIME_END));

            nightDifStartTime = day.AddDays(-1);
            nightDifStartTime = nightDifStartTime.ChangeTime(ndStartTime.Hour, ndStartTime.Minute, 0, 0);

            nightDifEndTime = day;
            nightDifEndTime = nightDifEndTime.ChangeTime(ndEndTime.Hour, ndEndTime.Minute, 0, 0);

            arrivedEarlierThanScheduled        = clockIn < scheduledTimeIn;
            isWithinGracePeriod                = this.isWtnGracePeriod(clockIn, scheduledTimeIn);
            isWithinAdvanceOtPeriod            = this.isForAdvanceOT(clockIn, scheduledTimeIn);
            clockoutLaterThanScheduled         = clockOut > scheduledTimeOut;
            clockOutGreaterThanNDEndTime       = clockOut > nightDifEndTime;
            isClockInLaterThanScheduledTimeOut = clockIn > scheduledTimeOut;

            //Change clockin if within grace period and is per hour
            if (isWithinGracePeriod && isGracePeriodPerHour)
            {
                clockIn = clockIn.ChangeTime(clockIn.Hour, 0, 0, 0);
            }
            else if (this.isWtnTimeInAdjustmentPeriod(clockIn))
            //Change clockin if within time adjustment period of time in
            {
                clockIn = clockIn.AddHours(1);
                clockIn = clockIn.ChangeTime(clockIn.Hour, 0, 0, 0);
            }

            //Change clockout if within time adjustment period of time out
            if (this.isWtnTimeOutAdjustmentBeforePeriod(clockOut.Value))
            {
                //Before clockout hour
                clockOut = clockOut.Value.AddHours(1);
                clockOut = clockOut.Value.ChangeTime(clockOut.Value.Hour, 0, 0, 0);
            }
            else if (this.isWtnTimeOutAdjustmentAfterPeriod(clockOut.Value))
            {
                //After clockout hour
                clockOut = clockOut.Value.ChangeTime(clockOut.Value.Hour, 0, 0, 0);
            }
        }
コード例 #18
0
        public override void Method()
        {
            IQuery <Person> q = this.DbContext.Query <Person>();

            var space = new char[] { ' ' };

            DateTime startTime = DateTime.Now;
            DateTime endTime   = startTime.AddDays(1);
            var      ret       = q.Select(a => new
            {
                Id = a.Id,

                //CustomFunction = DbFunctions.MyFunction(a.Id), //自定义函数

                String_Length = (int?)a.Name.Length,           //LENGTH("PERSON"."NAME")
                Substring     = a.Name.Substring(0),           //SUBSTR("PERSON"."NAME",0 + 1,LENGTH("PERSON"."NAME"))
                Substring1    = a.Name.Substring(1),           //SUBSTR("PERSON"."NAME",1 + 1,LENGTH("PERSON"."NAME"))
                Substring1_2  = a.Name.Substring(1, 2),        //SUBSTR("PERSON"."NAME",1 + 1,2)
                ToLower       = a.Name.ToLower(),              //LOWER("PERSON"."NAME")
                ToUpper       = a.Name.ToUpper(),              //UPPER("PERSON"."NAME")
                IsNullOrEmpty = string.IsNullOrEmpty(a.Name),  //too long
                Contains      = (bool?)a.Name.Contains("s"),   //
                Trim          = a.Name.Trim(),                 //TRIM("PERSON"."NAME")
                TrimStart     = a.Name.TrimStart(space),       //LTRIM("PERSON"."NAME")
                TrimEnd       = a.Name.TrimEnd(space),         //RTRIM("PERSON"."NAME")
                StartsWith    = (bool?)a.Name.StartsWith("s"), //
                EndsWith      = (bool?)a.Name.EndsWith("s"),   //
                Replace       = a.Name.Replace("l", "L"),

                /* oracle is not supported DbFunctions.Diffxx. */
                //DiffYears = DbFunctions.DiffYears(startTime, endTime),//
                //DiffMonths = DbFunctions.DiffMonths(startTime, endTime),//
                //DiffDays = DbFunctions.DiffDays(startTime, endTime),//
                //DiffHours = DbFunctions.DiffHours(startTime, endTime),//
                //DiffMinutes = DbFunctions.DiffMinutes(startTime, endTime),//
                //DiffSeconds = DbFunctions.DiffSeconds(startTime, endTime),//
                //DiffMilliseconds = DbFunctions.DiffMilliseconds(startTime, endTime),//
                //DiffMicroseconds = DbFunctions.DiffMicroseconds(startTime, endTime),//

                /* ((CAST(:P_0 AS DATE)-CAST(:P_1 AS DATE)) * 86400000 + CAST(TO_CHAR(CAST(:P_0 AS TIMESTAMP),'ff3') AS NUMBER) - CAST(TO_CHAR(CAST(:P_1 AS TIMESTAMP),'ff3') AS NUMBER)) / 86400000 */
                SubtractTotalDays         = endTime.Subtract(startTime).TotalDays,         //
                SubtractTotalHours        = endTime.Subtract(startTime).TotalHours,        //...
                SubtractTotalMinutes      = endTime.Subtract(startTime).TotalMinutes,      //...
                SubtractTotalSeconds      = endTime.Subtract(startTime).TotalSeconds,      //...
                SubtractTotalMilliseconds = endTime.Subtract(startTime).TotalMilliseconds, //...

                AddYears   = startTime.AddYears(1),                                        //ADD_MONTHS(:P_0,12 * 1)
                AddMonths  = startTime.AddMonths(1),                                       //ADD_MONTHS(:P_0,1)
                AddDays    = startTime.AddDays(1),                                         //(:P_0 + 1)
                AddHours   = startTime.AddHours(1),                                        //(:P_0 + NUMTODSINTERVAL(1,'HOUR'))
                AddMinutes = startTime.AddMinutes(2),                                      //(:P_0 + NUMTODSINTERVAL(2,'MINUTE'))
                AddSeconds = startTime.AddSeconds(120),                                    //(:P_0 + NUMTODSINTERVAL(120,'SECOND'))
                                                                                           //AddMilliseconds = startTime.AddMilliseconds(20000),//不支持

                Now         = DateTime.Now,                                                //SYSTIMESTAMP
                UtcNow      = DateTime.UtcNow,                                             //SYS_EXTRACT_UTC(SYSTIMESTAMP)
                Today       = DateTime.Today,                                              //TRUNC(SYSDATE,'DD')
                Date        = DateTime.Now.Date,                                           //TRUNC(SYSTIMESTAMP,'DD')
                Year        = DateTime.Now.Year,                                           //CAST(TO_CHAR(SYSTIMESTAMP,'yyyy') AS NUMBER)
                Month       = DateTime.Now.Month,                                          //CAST(TO_CHAR(SYSTIMESTAMP,'mm') AS NUMBER)
                Day         = DateTime.Now.Day,                                            //CAST(TO_CHAR(SYSTIMESTAMP,'dd') AS NUMBER)
                Hour        = DateTime.Now.Hour,                                           //CAST(TO_CHAR(SYSTIMESTAMP,'hh24') AS NUMBER)
                Minute      = DateTime.Now.Minute,                                         //CAST(TO_CHAR(SYSTIMESTAMP,'mi') AS NUMBER)
                Second      = DateTime.Now.Second,                                         //CAST(TO_CHAR(SYSTIMESTAMP,'ss') AS NUMBER)
                Millisecond = DateTime.Now.Millisecond,                                    //CAST(TO_CHAR(SYSTIMESTAMP,'ff3') AS NUMBER)
                DayOfWeek   = DateTime.Now.DayOfWeek,                                      //(CAST(TO_CHAR(SYSTIMESTAMP,'D') AS NUMBER) - 1)

                Int_Parse     = int.Parse("1"),                                            //CAST(N'1' AS NUMBER)
                Int16_Parse   = Int16.Parse("11"),                                         //CAST(N'11' AS NUMBER)
                Long_Parse    = long.Parse("2"),                                           //CAST(N'2' AS NUMBER)
                Double_Parse  = double.Parse("3"),                                         //CAST(N'3' AS BINARY_DOUBLE)
                Float_Parse   = float.Parse("4"),                                          //CAST(N'4' AS BINARY_FLOAT)
                Decimal_Parse = decimal.Parse("5"),                                        //CAST(N'5' AS NUMBER)
                                                                                           //Guid_Parse = Guid.Parse("D544BC4C-739E-4CD3-A3D3-7BF803FCE179"),//不支持

                Bool_Parse     = bool.Parse("1"),                                          //
                DateTime_Parse = DateTime.Parse("1992-1-16"),                              //TO_TIMESTAMP(N'1992-1-16','yyyy-mm-dd hh24:mi:ssxff')

                B        = a.Age == null ? false : a.Age > 1,                              //三元表达式
                CaseWhen = Case.When(a.Id > 100).Then(1).Else(0)                           //case when
            }).ToList();

            ConsoleHelper.WriteLineAndReadKey();
        }
コード例 #19
0
        public async Task <ScheduledToastNotification> AddPomodoroFinishedToastNotificationScheduleAsync(DateTime time, string audioUri, bool isRemoveOthers = true)
        {
            if (ApiInformation.IsTypePresent("Windows.ApplicationModel.Background.ToastNotificationActionTrigger") == false)
            {
                return(null);
            }

            if (time < DateTime.Now)
            {
                return(null);
            }

            if (isRemoveOthers)
            {
                await RemovePomodoroFinishedToastNotificationScheduleAsync();
            }

            var toastBuilder = CreatePomodoroToastBuilder();

            if (string.IsNullOrWhiteSpace(audioUri) == false)
            {
                toastBuilder.AddAudio(new Uri(audioUri));
            }

            ScheduledToastNotification toast = null;
            XmlDocument xml = null;

            if (time < DateTime.Now)
            {
                return(null);
            }

            try
            {
                xml   = toastBuilder.GetXml();
                toast = new ScheduledToastNotification(xml, time)
                {
                    Tag            = PomodoroTag,
                    Group          = ToastGroup,
                    ExpirationTime = time.AddHours(1),
                    Id             = _id++.ToString()
                };

                var toastNotifier = await ToastNotificationToolkit.CreateToastNotifierAsync();

                toastNotifier.AddToSchedule(toast);
                Debug.WriteLine("add pomodoro:" + toast.Id);
            }
            catch (Exception ex)
            {
                var properties = new Dictionary <string, string>
                {
                    { "xml", xml.GetXml() },
                    { "time", time.ToString() },
                    { "now", DateTime.Now.ToString() },
                    { "utc_now", DateTimeOffset.UtcNow.ToString() },
                };
                Microsoft.AppCenter.Crashes.Crashes.TrackError(ex, properties);
                throw;
            }

            return(toast);
        }
コード例 #20
0
        private void btnSelect_Click(object sender, EventArgs e)
        {
            DateTime BeginTime = this.DTPBeginDate.Value.Date;

            BeginTime = BeginTime.AddHours((double)this.NUDBeginHour.Value);
            BeginTime = BeginTime.AddMinutes((double)this.NUDBeginMinute.Value);
            DateTime EndTime = this.DTPEndDate.Value.Date;

            EndTime = EndTime.AddHours((double)this.NUDEndHour.Value);
            EndTime = EndTime.AddMinutes((double)this.NUDEndMinute.Value);

            string name   = this.txtName.Text;
            string Class  = this.txtClass.Text;
            string number = this.txtNumber.Text;

            if (Access.IsHasSQLInject(name) || Access.IsHasSQLInject(Class) || Access.IsHasSQLInject(number))
            {
                MessageBox.Show("请勿输入敏感词!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!string.IsNullOrEmpty(number))
            {
                try
                {
                    number = string.Format("[学号] = {0}", int.Parse(number));
                }
                catch
                {
                    MessageBox.Show("请输入正确的学号", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            else
            {
                number = "1=1";
            }
            if (!string.IsNullOrEmpty(Class))
            {
                Class = string.Format("[班级名称] = '{0}'", Class);
            }
            else
            {
                Class = "1=1";
            }
            if (!string.IsNullOrEmpty(name))
            {
                name = string.Format("[姓名] = '{0}'", name);
            }
            else
            {
                name = "1=1";
            }

            string sql = string.Format("SELECT s.*,t.[购票时间],t.[类型] FROM " +
                                       "(SELECT * FROM [学生表] WHERE {0} AND {1} AND {2})s " +
                                       "INNER JOIN " +
                                       "(SELECT * FROM " +
                                       "(SELECT * FROM [礼堂表] WHERE [票价] = 0 AND [开始时间] Between #{3}# AND #{4}#) a " +
                                       "INNER JOIN [票务表] t ON a.ID = t.礼堂ID) t" +
                                       " ON s.[学号] = t.[购买者ID]",
                                       number, name, Class, BeginTime, EndTime);

            try
            {
                this.dataGridView1.DataSource = Access.obj.GetDataTable(sql);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #21
0
        public async Task <ActionResult <CallVolumeChart> > GetCallVolumeChartData([FromQuery] DateTime?fromDate = null, [FromQuery] DateTime?toDate = null)
        {
            if (fromDate == null)
            {
                fromDate = DateTime.Now.AddDays(Convert.ToDouble(config.GetValue <string>("DefaultReportFromDate")));
            }

            if (toDate == null)
            {
                toDate = DateTime.Now;
            }

            TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");

            fromDate = TimeZoneInfo.ConvertTimeFromUtc(fromDate.GetValueOrDefault().ToUniversalTime(), cstZone);

            toDate = TimeZoneInfo.ConvertTimeFromUtc(toDate.GetValueOrDefault().ToUniversalTime(), cstZone);

            toDate = toDate?.AddHours(23).AddMinutes(59).AddSeconds(59);

            var labs = GetLabs().Result.Value;

            var callTypes = new List <string>()
            {
                "MISSED", "INCOMING", "OUTGOING"
            };

            Dictionary <string, List <ChartMetrics> > callVolumeDictionary = new Dictionary <string, List <ChartMetrics> >();

            foreach (var item in callTypes)
            {
                var callType = new List <ChartMetrics>();

                foreach (var labName in labs)
                {
                    ChartMetrics chartV2 = new ChartMetrics();

                    chartV2.Name = labName;

                    callType.Add(chartV2);
                }

                callVolumeDictionary.Add(item, callType);
            }

            var validCalls = await context.ValidCalls
                             .Where(s => s.EventTime >= fromDate && s.EventTime <= toDate)
                             .Select(x => new { x.LabName, x.ValidCallId, CallType = x.CallType.ToUpper() })
                             .ToListAsync();

            var missedCalls = await context.MissedCalls
                              .Where(s => s.EventTime >= fromDate && s.EventTime <= toDate)
                              .Select(x => new { x.LabName, x.Id, CallType = "MISSED" })
                              .ToListAsync();

            var groupedValidCalls = validCalls.GroupBy(vc => new { vc.LabName, vc.CallType })
                                    .Select(group => new
            {
                Metric = group.Key,
                Count  = group.Count()
            }).ToList();

            var groupedMissedCalls = missedCalls.GroupBy(vc => new { vc.LabName, vc.CallType })
                                     .Select(group => new
            {
                Metric = group.Key,
                Count  = group.Count()
            }).ToList();

            foreach (var item in groupedMissedCalls)
            {
                if (item.Metric.CallType == null)
                {
                    continue;
                }

                var callType = callVolumeDictionary[item.Metric.CallType] as List <ChartMetrics>;

                callType.Where(m => m.Name.ToUpper() == item.Metric.LabName.ToUpper()).ToList().ForEach(s => s.count = item.Count);
            }

            foreach (var item in groupedValidCalls)
            {
                if (item.Metric.CallType == null)
                {
                    continue;
                }

                var callType = callVolumeDictionary[item.Metric.CallType] as List <ChartMetrics>;

                callType.Where(m => m.Name.ToUpper() == item.Metric.LabName.ToUpper()).ToList().ForEach(s => s.count = item.Count);
            }

            CallVolumeChart response = new CallVolumeChart();

            response.labs = labs;

            response.callTypes = callTypes;

            response.volumeData = callVolumeDictionary;

            response.countData = new List <List <string> >();

            foreach (var item in callVolumeDictionary.Values)
            {
                response.countData.Add(item.Select(m => m.count.ToString()).ToList());
            }

            return(response);
        }
コード例 #22
0
        public void Local_Time()
        {
            DateTime d      = new DateTime(2019, 10, 31, 14, 10, 22);
            double   offset = -7;

            //INSTANCE CHECK

            //Coordinate in UTC
            Coordinate cUTC = new Coordinate(47.60357, -122.32945, d);
            //Coordinate in UTC - offset added to account for UTC date differing
            Coordinate sUTC = new Coordinate(47.60357, -122.32945, d.AddDays(offset / Math.Abs(offset) * -1));
            //Coordinate in Local
            Coordinate lLoc = new Coordinate(47.60357, -122.32945, d);
            //Coordinate in local + offset (for cel coord comparision)
            Coordinate simUTC = new Coordinate(47.60357, -122.32945, d.AddHours(-offset));

            lLoc.Offset = offset;


            Celestial cCel = cUTC.CelestialInfo;
            Celestial sCel = sUTC.CelestialInfo;
            Celestial lCel = lLoc.CelestialInfo;
            Celestial bCel = simUTC.CelestialInfo;

            Local_Time_Checker(cCel, lCel, sCel, bCel, offset);

            //STATIC CHECK

            cCel = Celestial.CalculateCelestialTimes(47.60357, -122.32945, d);
            sCel = Celestial.CalculateCelestialTimes(47.60357, -122.32945, d.AddDays(offset / Math.Abs(offset) * -1));
            lCel = Celestial.CalculateCelestialTimes(47.60357, -122.32945, d, offset);
            bCel = Celestial.CalculateCelestialTimes(47.60357, -122.32945, d.AddHours(-offset));

            Local_Time_Checker(cCel, lCel, sCel, bCel, offset);


            //With EagerLoad
            EagerLoad el = new EagerLoad(EagerLoadType.Celestial);

            cCel = Celestial.CalculateCelestialTimes(47.60357, -122.32945, d, el);
            sCel = Celestial.CalculateCelestialTimes(47.60357, -122.32945, d.AddDays(offset / Math.Abs(offset) * -1), el);
            lCel = Celestial.CalculateCelestialTimes(47.60357, -122.32945, d, el, offset);
            bCel = Celestial.CalculateCelestialTimes(47.60357, -122.32945, d.AddHours(-offset), el);

            Local_Time_Checker(cCel, lCel, sCel, bCel, offset);

            //VALIDATIONS
            //IN RANGE
            cUTC.Offset = -12;
            cUTC.Offset = 12;
            cCel        = new Celestial(0, 0, DateTime.Now, -12);
            cCel        = new Celestial(0, 0, DateTime.Now, 14);
            cCel        = new Celestial(0, 0, DateTime.Now, -12, new EagerLoad());
            cCel        = new Celestial(0, 0, DateTime.Now, 14, new EagerLoad());
            cCel        = Celestial.CalculateCelestialTimes(0, 0, DateTime.Now, -12);
            cCel        = Celestial.CalculateCelestialTimes(0, 0, DateTime.Now, 14);
            cCel        = Celestial.CalculateCelestialTimes(0, 0, DateTime.Now, new EagerLoad(), 14);
            cCel        = Celestial.CalculateCelestialTimes(0, 0, DateTime.Now, new EagerLoad(), -12);

            //OUT OF RANGE
            Assert.ThrowsException <ArgumentOutOfRangeException>(() => { cUTC.Offset = -13; });
            Assert.ThrowsException <ArgumentOutOfRangeException>(() => { cUTC.Offset = 15; });
            Assert.ThrowsException <ArgumentOutOfRangeException>(() => { cCel = new Celestial(0, 0, DateTime.Now, -13); });
            Assert.ThrowsException <ArgumentOutOfRangeException>(() => { cCel = new Celestial(0, 0, DateTime.Now, 15); });
            Assert.ThrowsException <ArgumentOutOfRangeException>(() => { cCel = new Celestial(0, 0, DateTime.Now, -13, new EagerLoad()); });
            Assert.ThrowsException <ArgumentOutOfRangeException>(() => { cCel = new Celestial(0, 0, DateTime.Now, 15, new EagerLoad()); });
            Assert.ThrowsException <ArgumentOutOfRangeException>(() => { cCel = Celestial.CalculateCelestialTimes(0, 0, DateTime.Now, -13); });
            Assert.ThrowsException <ArgumentOutOfRangeException>(() => { cCel = Celestial.CalculateCelestialTimes(0, 0, DateTime.Now, 15); });
            Assert.ThrowsException <ArgumentOutOfRangeException>(() => { cCel = Celestial.CalculateCelestialTimes(0, 0, DateTime.Now, new EagerLoad(), -13); });
            Assert.ThrowsException <ArgumentOutOfRangeException>(() => { cCel = Celestial.CalculateCelestialTimes(0, 0, DateTime.Now, new EagerLoad(), 15); });
        }
コード例 #23
0
        public async Task <ActionResult <CallPurposeChart> > GetCallPurposeChartData([FromQuery] DateTime?fromDate = null, [FromQuery] DateTime?toDate = null)
        {
            if (fromDate == null)
            {
                fromDate = DateTime.Now.AddDays(Convert.ToDouble(config.GetValue <string>("DefaultReportFromDate")));
            }


            if (toDate == null)
            {
                toDate = DateTime.Now;
            }


            TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");

            fromDate = TimeZoneInfo.ConvertTimeFromUtc(fromDate.GetValueOrDefault().ToUniversalTime(), cstZone);

            toDate = TimeZoneInfo.ConvertTimeFromUtc(toDate.GetValueOrDefault().ToUniversalTime(), cstZone);

            toDate = toDate?.AddHours(23).AddMinutes(59).AddSeconds(59);

            var labs = GetLabs().Result.Value;

            var callPurpose = await context.CallPurpose.ToListAsync();

            var purposes = callPurpose.Select(m => m.PurposeoftheCall).ToList();

            Dictionary <string, List <ChartMetrics> > purposeDictionary = new Dictionary <string, List <ChartMetrics> >();

            foreach (var item in purposes)
            {
                var purpose = new List <ChartMetrics>();

                foreach (var lab in labs)
                {
                    ChartMetrics chartV2 = new ChartMetrics();

                    chartV2.Name = lab;

                    purpose.Add(chartV2);
                }

                purposeDictionary.Add(item, purpose);
            }

            var validCalls = await context.ValidCalls
                             .Where(s => s.EventTime >= fromDate && s.EventTime <= toDate)
                             .Select(x => new { x.LabName, x.ValidCallId, x.CallPurpose })
                             .ToListAsync();

            var groupedValidCalls = validCalls.GroupBy(vc => new { vc.LabName, vc.CallPurpose })
                                    .Select(group => new
            {
                Metric = group.Key,
                Count  = group.Count()
            }).ToList();

            foreach (var item in groupedValidCalls)
            {
                List <ChartMetrics> purpose = new List <ChartMetrics>();
                //if (item.Metric.CallPurpose == null)
                //    continue;

                if (item.Metric.CallPurpose?.Length > 0)
                {
                    purpose = purposeDictionary[item.Metric.CallPurpose] as List <ChartMetrics>;
                }
                else
                {
                    purpose = purposeDictionary["Blanks"] as List <ChartMetrics>;
                }

                purpose.Where(m => m.Name == item.Metric.LabName).ToList().ForEach(s => s.count = item.Count);
            }

            CallPurposeChart response = new CallPurposeChart();

            response.labs = labs;

            response.purposes = purposeDictionary.Keys.ToList();

            response.purposeData = purposeDictionary;

            response.countData = new List <List <int> >();

            foreach (var item in purposeDictionary.Values)
            {
                response.countData.Add(item.Select(m => m.count).ToList());
            }
            response.sumData = new List <string>();

            foreach (var item in response.countData)
            {
                response.sumData.Add(item.ToList().Sum().ToString());
            }

            return(response);
        }
コード例 #24
0
        /// <summary>
        /// request instrument history
        /// запрос истории по инструменту
        /// </summary>
        public List <Candle> GetCandleHistory(string nameSec, TimeFrame tf)
        {
            SecurityIb contractIb =
                _secIB.Find(
                    contract =>
                    contract.Symbol + "_" + contract.SecType + "_" + contract.Exchange == nameSec);

            if (contractIb == null)
            {
                return(null);;
            }

            DateTime timeEnd   = DateTime.Now.ToUniversalTime();
            DateTime timeStart = timeEnd.AddMinutes(60);

            string barSize = "1 min";

            int mergeCount = 0;


            if (tf == TimeFrame.Sec1)
            {
                barSize   = "1 sec";
                timeStart = timeEnd.AddMinutes(10);
            }
            else if (tf == TimeFrame.Sec5)
            {
                barSize = "5 secs";
            }
            else if (tf == TimeFrame.Sec15)
            {
                barSize = "15 secs";
            }
            else if (tf == TimeFrame.Sec30)
            {
                barSize = "30 secs";
            }
            else if (tf == TimeFrame.Min1)
            {
                timeStart = timeEnd.AddHours(15);
                barSize   = "1 min";
            }
            else if (tf == TimeFrame.Min5)
            {
                timeStart = timeEnd.AddHours(50);
                barSize   = "5 mins";
            }
            else if (tf == TimeFrame.Min15)
            {
                timeStart = timeEnd.AddHours(150);
                barSize   = "15 mins";
            }
            else if (tf == TimeFrame.Min30)
            {
                timeStart = timeEnd.AddHours(250);
                barSize   = "30 mins";
            }
            else if (tf == TimeFrame.Hour1)
            {
                timeStart = timeEnd.AddHours(1300);
                barSize   = "1 hour";
            }
            else if (tf == TimeFrame.Hour2)
            {
                timeStart  = timeEnd.AddHours(2100);
                barSize    = "1 hour";
                mergeCount = 2;
            }
            else if (tf == TimeFrame.Hour4)
            {
                timeStart  = timeEnd.AddHours(4200);
                barSize    = "1 hour";
                mergeCount = 4;
            }
            else if (tf == TimeFrame.Day)
            {
                barSize   = "1 day";
                timeStart = timeEnd.AddDays(701);
            }
            else
            {
                return(null);
            }

            CandlesRequestResult = null;

            _client.GetCandles(contractIb, timeEnd, timeStart, barSize, "TRADES");

            DateTime startSleep = DateTime.Now;

            while (true)
            {
                Thread.Sleep(1000);

                if (startSleep.AddSeconds(15) < DateTime.Now)
                {
                    break;
                }

                if (CandlesRequestResult != null)
                {
                    break;
                }
            }

            if (CandlesRequestResult != null &&
                CandlesRequestResult.CandlesArray.Count != 0)
            {
                if (mergeCount != 0)
                {
                    return(Merge(CandlesRequestResult.CandlesArray, mergeCount));
                }

                return(CandlesRequestResult.CandlesArray);
            }


            _client.GetCandles(contractIb, timeEnd, timeStart, barSize, "MIDPOINT");

            startSleep = DateTime.Now;

            while (true)
            {
                Thread.Sleep(1000);

                if (startSleep.AddSeconds(15) < DateTime.Now)
                {
                    break;
                }

                if (CandlesRequestResult != null)
                {
                    break;
                }
            }

            if (CandlesRequestResult != null &&
                CandlesRequestResult.CandlesArray.Count != 0)
            {
                if (mergeCount != 0)
                {
                    return(Merge(CandlesRequestResult.CandlesArray, mergeCount));
                }

                return(CandlesRequestResult.CandlesArray);
            }

            return(null);
        }
コード例 #25
0
        public int Get(string Team_ID, string Task_Name, string Desc, string Date, string R_C)
        {
            if (!GF.session_check())
            {
                return(5);
            }
            if (!GF.Check_if_Joined(Team_ID))
            {
                return(4);
            }
            usid = GF.get_usid();

            this.Team_ID   = Team_ID;
            this.Task_Name = Task_Name;
            while (true)
            {
                R_UUID = Guid.NewGuid().ToString();
                if (check_id(R_UUID))
                {
                    break;
                }
            }
            DateTime R;

            try { R = DateTime.Parse(Date); }
            catch
            {
                R = DateTime.Now;
            }
            DateTime S = R.Date;

            S = S.AddHours(R.Hour); S = S.AddMinutes(R.Minute); S = S.AddSeconds(R.Second);
            try
            {
                Report_Content = JsonConvert.DeserializeObject <List <Day> >(R_C.Replace("\\\"", "\""));
            }
            catch (Newtonsoft.Json.JsonException e)
            {
                Report_Content = new List <Day>();
            }

            if (!Check_Task_f())
            {
                Insert_Task();
            }


            foreach (Day x in Report_Content)
            {
                k += (int)x.Hours;
            }
            paralist = new List <SqlParameter>
            {
                new SqlParameter("@rid", R_UUID),
                new SqlParameter("@usid", usid),
                new SqlParameter("@team_id", Team_ID),
                new SqlParameter("@date", S),
                new SqlParameter("@hours", k),
                new SqlParameter("@desc", Desc),
                new SqlParameter("@task_n", Task_Name)
            };
            Query = add_Report_1;
            foreach (Day x in Report_Content)
            {
                para1 = "@parai" + i;
                para2 = "@paraii" + i;
                paralist.Add(new SqlParameter(para1, ((int)x.Hours)));
                paralist.Add(new SqlParameter(para2, x.Date));
                Query += add_Report_2 + para1 + "," + para2 + ");";
                i++;
            }
            Query += add_Report_3;
            try
            {
                if (DB_Connection.sql_insert_update(Query, paralist))
                {
                    return(1);
                }
                return(0);
            }
            catch
            {
                return(0);
            }
        }
コード例 #26
0
        public void Check(float deltaTime)
        {
            #region Sleeping

            if (IsSleeping)
            {
                _sleepingCounter += deltaTime;

                if (_sleepingCounter >= _sleepHealthCheckPeriod)
                {
                    // need to check health and advance time

                    //($"Sleep iteration done. Checks was {_sleepHealthChecksLeft}, now it's {_sleepHealthChecksLeft-1}");

                    _sleepingCounter = 0f;
                    _sleepHealthChecksLeft--;

                    if (_sleepHealthChecksLeft == 0)
                    {
                        // Done sleeping

                        var newWorldTime = _sleepStartTime.AddHours(_sleepDurationGameHours);

                        //($"Done sleeping. Wake up exact time is {newWorldTime.ToShortTimeString()}, warmth deltaTime is {deltaTime}");

                        _sleepTimeAdvanceFunc?.Invoke(newWorldTime);

                        _gc.Health.UnconsciousMode = false;
                        _gc.Health.SetFatiguePercentage(_fatigueValueAfterSleep);
                        _gc.Health.Status.CheckTime = newWorldTime;

                        IsSleeping = false;

                        _wakeUpAction?.Invoke();
                    }
                    else
                    {
                        var iteration    = SleepHealthChecksCount - _sleepHealthChecksLeft;
                        var newWorldTime = _sleepStartTime.AddHours((_sleepDurationGameHours / SleepHealthChecksCount) * iteration);

                        deltaTime = (float)(newWorldTime - _gc.WorldTime.Value).TotalSeconds;

                        //($"Mid-sleep check. New mid-sleep time is {newWorldTime.ToShortTimeString()}, warmth deltaTime is {deltaTime}");

                        _sleepTimeAdvanceFunc?.Invoke(newWorldTime);

                        _gc.Health.Status.LastSleepTime = newWorldTime;
                    }
                }
            }

            #endregion

            #region Lerping Warmth Level

            if (_warmthLerpCounter.HasValue)
            {
                if (_warmthLerpCounter < WarmthLevelUpdateInterval)
                {
                    _warmthLerpCounter += deltaTime;
                }

                if (_warmthLerpCounter > WarmthLevelUpdateInterval)
                {
                    _warmthLerpCounter = WarmthLevelUpdateInterval;
                }

                WarmthLevelCached = Helpers.Lerp(_warmthLerpBase, _warmthLerpTarget, _warmthLerpCounter.Value / WarmthLevelUpdateInterval);
            }

            #endregion

            #region Warmth Level Refresh

            _warmthLevelTimeoutCounter += deltaTime;

            if (_warmthLevelTimeoutCounter > WarmthLevelUpdateInterval)
            {
                _warmthLevelTimeoutCounter = WarmthLevelUpdateInterval;
            }

            if (_warmthLevelTimeoutCounter >= WarmthLevelUpdateInterval)
            {
                _warmthLerpCounter = null;

                _warmthLevelTimeoutCounter = 0f;

                UpdateWarmthLevelCache();

                _warmthLerpCounter = 0;
            }

            #endregion

            #region Wetness Level Refresh

            _wetnessLevelTimeoutCounter += deltaTime;

            if (_wetnessLevelTimeoutCounter > WetnessLevelUpdateInterval)
            {
                _wetnessLevelTimeoutCounter = WetnessLevelUpdateInterval;
            }

            if (_wetnessLevelTimeoutCounter >= WetnessLevelUpdateInterval)
            {
                _wetnessLevelTimeoutCounter = 0f;

                _wetnessController.Check(deltaTime);
            }

            #endregion
        }
コード例 #27
0
        public void AddRecentChange_GetRecentChanges()
        {
            ISettingsStorageProviderV30 prov = GetProvider();

            Collectors.SettingsProvider = prov;

            DateTime dt = DateTime.Now;

            Assert.IsTrue(prov.AddRecentChange("MainPage", "Main Page", null, dt, Log.SystemUsername, ScrewTurn.Wiki.PluginFramework.Change.PageUpdated, ""), "AddRecentChange should return true");
            Assert.IsTrue(prov.AddRecentChange("MainPage", "Home Page", null, dt.AddHours(1), "admin", ScrewTurn.Wiki.PluginFramework.Change.PageUpdated, "Added info"), "AddRecentChange should return true");

            Assert.IsTrue(prov.AddRecentChange("MainPage", "Home Page", null, dt.AddHours(5), "admin", ScrewTurn.Wiki.PluginFramework.Change.PageRenamed, ""), "AddRecentChange should return true");
            Assert.IsTrue(prov.AddRecentChange("MainPage", "Main Page", null, dt.AddHours(6), "admin", ScrewTurn.Wiki.PluginFramework.Change.PageRolledBack, ""), "AddRecentChange should return true");
            Assert.IsTrue(prov.AddRecentChange("MainPage", "Main Page", null, dt.AddHours(7), "admin", ScrewTurn.Wiki.PluginFramework.Change.PageDeleted, ""), "AddRecentChange should return true");

            Assert.IsTrue(prov.AddRecentChange("MainPage", "Main Page", "Subject", dt.AddHours(2), "admin", ScrewTurn.Wiki.PluginFramework.Change.MessagePosted, ""), "AddRecentChange should return true");
            Assert.IsTrue(prov.AddRecentChange("MainPage", "Main Page", "Subject", dt.AddHours(3), "admin", ScrewTurn.Wiki.PluginFramework.Change.MessageEdited, ""), "AddRecentChange should return true");
            Assert.IsTrue(prov.AddRecentChange("MainPage", "Main Page", "Subject", dt.AddHours(4), "admin", ScrewTurn.Wiki.PluginFramework.Change.MessageDeleted, ""), "AddRecentChange should return true");

            RecentChange[] changes = prov.GetRecentChanges();

            Assert.AreEqual(8, changes.Length, "Wrong recent change count");

            Assert.AreEqual("MainPage", changes[0].Page, "Wrong page");
            Assert.AreEqual("Main Page", changes[0].Title, "Wrong title");
            Assert.AreEqual("", changes[0].MessageSubject, "Wrong message subject");
            Tools.AssertDateTimesAreEqual(dt, changes[0].DateTime);
            Assert.AreEqual(Log.SystemUsername, changes[0].User, "Wrong user");
            Assert.AreEqual(ScrewTurn.Wiki.PluginFramework.Change.PageUpdated, changes[0].Change, "Wrong change");
            Assert.AreEqual("", changes[0].Description, "Wrong description");

            Assert.AreEqual("MainPage", changes[1].Page, "Wrong page");
            Assert.AreEqual("Home Page", changes[1].Title, "Wrong title");
            Assert.AreEqual("", changes[1].MessageSubject, "Wrong message subject");
            Tools.AssertDateTimesAreEqual(dt.AddHours(1), changes[1].DateTime);
            Assert.AreEqual("admin", changes[1].User, "Wrong user");
            Assert.AreEqual(ScrewTurn.Wiki.PluginFramework.Change.PageUpdated, changes[1].Change, "Wrong change");
            Assert.AreEqual("Added info", changes[1].Description, "Wrong description");

            Assert.AreEqual("MainPage", changes[2].Page, "Wrong page");
            Assert.AreEqual("Main Page", changes[2].Title, "Wrong title");
            Assert.AreEqual("Subject", changes[2].MessageSubject, "Wrong message subject");
            Tools.AssertDateTimesAreEqual(dt.AddHours(2), changes[2].DateTime);
            Assert.AreEqual("admin", changes[2].User, "Wrong user");
            Assert.AreEqual(ScrewTurn.Wiki.PluginFramework.Change.MessagePosted, changes[2].Change, "Wrong change");
            Assert.AreEqual("", changes[2].Description, "Wrong description");

            Assert.AreEqual("MainPage", changes[3].Page, "Wrong page");
            Assert.AreEqual("Main Page", changes[3].Title, "Wrong title");
            Assert.AreEqual("Subject", changes[3].MessageSubject, "Wrong message subject");
            Tools.AssertDateTimesAreEqual(dt.AddHours(3), changes[3].DateTime);
            Assert.AreEqual("admin", changes[3].User, "Wrong user");
            Assert.AreEqual(ScrewTurn.Wiki.PluginFramework.Change.MessageEdited, changes[3].Change, "Wrong change");
            Assert.AreEqual("", changes[3].Description, "Wrong description");

            Assert.AreEqual("MainPage", changes[4].Page, "Wrong page");
            Assert.AreEqual("Main Page", changes[4].Title, "Wrong title");
            Assert.AreEqual("Subject", changes[4].MessageSubject, "Wrong message subject");
            Tools.AssertDateTimesAreEqual(dt.AddHours(4), changes[4].DateTime);
            Assert.AreEqual("admin", changes[4].User, "Wrong user");
            Assert.AreEqual(ScrewTurn.Wiki.PluginFramework.Change.MessageDeleted, changes[4].Change, "Wrong change");
            Assert.AreEqual("", changes[4].Description, "Wrong description");

            Assert.AreEqual("MainPage", changes[5].Page, "Wrong page");
            Assert.AreEqual("Home Page", changes[5].Title, "Wrong title");
            Assert.AreEqual("", changes[5].MessageSubject, "Wrong message subject");
            Tools.AssertDateTimesAreEqual(dt.AddHours(5), changes[5].DateTime);
            Assert.AreEqual("admin", changes[5].User, "Wrong user");
            Assert.AreEqual(ScrewTurn.Wiki.PluginFramework.Change.PageRenamed, changes[5].Change, "Wrong change");
            Assert.AreEqual("", changes[5].Description, "Wrong description");

            Assert.AreEqual("MainPage", changes[6].Page, "Wrong page");
            Assert.AreEqual("Main Page", changes[6].Title, "Wrong title");
            Assert.AreEqual("", changes[6].MessageSubject, "Wrong message subject");
            Tools.AssertDateTimesAreEqual(dt.AddHours(6), changes[6].DateTime);
            Assert.AreEqual("admin", changes[6].User, "Wrong user");
            Assert.AreEqual(ScrewTurn.Wiki.PluginFramework.Change.PageRolledBack, changes[6].Change, "Wrong change");
            Assert.AreEqual("", changes[6].Description, "Wrong description");

            Assert.AreEqual("MainPage", changes[7].Page, "Wrong page");
            Assert.AreEqual("Main Page", changes[7].Title, "Wrong title");
            Assert.AreEqual("", changes[7].MessageSubject, "Wrong message subject");
            Tools.AssertDateTimesAreEqual(dt.AddHours(7), changes[7].DateTime);
            Assert.AreEqual("admin", changes[7].User, "Wrong user");
            Assert.AreEqual(ScrewTurn.Wiki.PluginFramework.Change.PageDeleted, changes[7].Change, "Wrong change");
            Assert.AreEqual("", changes[7].Description, "Wrong description");
        }
コード例 #28
0
 private void CalculateDateAndTime(DateTime time)
 {
     DateAndTime = time.AddHours(Offset);
 }
コード例 #29
0
            public IEnumerator <object[]> GetEnumerator()
            {
                DateTime inputDate  = DateTime.Now;
                string   calcMethod = "Add Second(s)";
                int      increment  = 1;
                DateTime outputDate = inputDate.AddSeconds(increment);

                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDate });

                calcMethod = "Add Minute(s)";
                outputDate = inputDate.AddMinutes(increment);
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDate });

                calcMethod = "Add Hour(s)";
                outputDate = inputDate.AddHours(increment);
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDate });

                calcMethod = "Add Day(s)";
                outputDate = inputDate.AddDays(increment);
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDate });

                calcMethod = "Add Month(s)";
                outputDate = inputDate.AddMonths(increment);
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDate });

                calcMethod = "Add Year(s)";
                outputDate = inputDate.AddYears(increment);
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDate });

                calcMethod = "Subtract Second(s)";
                outputDate = inputDate.AddSeconds(increment * -1);
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDate });

                calcMethod = "Subtract Minute(s)";
                outputDate = inputDate.AddMinutes(increment * -1);
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDate });

                calcMethod = "Subtract Year(s)";
                outputDate = inputDate.AddYears(increment * -1);
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDate });

                calcMethod = "Subtract Day(s)";
                outputDate = inputDate.AddDays(increment * -1);
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDate });

                calcMethod = "Subtract Month(s)";
                outputDate = inputDate.AddMonths(increment * -1);
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDate });

                calcMethod = "Subtract Year(s)";
                outputDate = inputDate.AddYears(increment * -1);
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDate });

                calcMethod = "Get Next Day";
                int outputDateInt = inputDate.AddDays(increment).Day;

                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDateInt });

                calcMethod    = "Get Next Month";
                outputDateInt = inputDate.AddMonths(increment).Month;
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDateInt });

                calcMethod    = "Get Next Year";
                outputDateInt = inputDate.AddYears(increment).Year;
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDateInt });

                calcMethod    = "Get Previous Day";
                outputDateInt = inputDate.AddDays(increment * -1).Day;
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDateInt });

                calcMethod    = "Get Previous Month";
                outputDateInt = inputDate.AddMonths(increment * -1).Month;
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDateInt });

                calcMethod    = "Get Previous Year";
                outputDateInt = inputDate.AddYears(increment * -1).Year;
                yield return(new object[] { inputDate, calcMethod, increment.ToString(), outputDateInt });
            }
コード例 #30
0
        private void TestOverlaps(OverlapsInclude overlapsInclude, DateTime now)
        {
            //current   =>          |****|
            //1         => |****|
            //2         =>      |****|
            //3         =>           |**|
            //4         =>              |****|
            //5         =>                  |****|
            //6         =>     |***>|
            //7         =>               |<***|

            var current = DateTimeRange.Create(now.AddHours(1), now.AddHours(2));

            var dateTimeRange1 = DateTimeRange.Create(_mockNow.AddHours(0), _mockNow.AddHours(0.5));
            var dateTimeRange2 = DateTimeRange.Create(_mockNow.AddHours(0.5), _mockNow.AddHours(1.5));
            var dateTimeRange3 = DateTimeRange.Create(_mockNow.AddHours(1.2), _mockNow.AddHours(1.6));
            var dateTimeRange4 = DateTimeRange.Create(_mockNow.AddHours(1.6), _mockNow.AddHours(2.5));
            var dateTimeRange5 = DateTimeRange.Create(_mockNow.AddHours(2.5), _mockNow.AddHours(3));
            var dateTimeRange6 = DateTimeRange.Create(_mockNow.AddHours(0.5), _mockNow.AddHours(1));
            var dateTimeRange7 = DateTimeRange.Create(_mockNow.AddHours(2), _mockNow.AddHours(3));

            current.Overlaps(dateTimeRange1, overlapsInclude).ShouldFalse();
            current.Overlaps(dateTimeRange2, overlapsInclude).ShouldTrue();
            current.Overlaps(dateTimeRange3, overlapsInclude).ShouldTrue();
            current.Overlaps(dateTimeRange4, overlapsInclude).ShouldTrue();
            current.Overlaps(dateTimeRange5, overlapsInclude).ShouldFalse();
            if (overlapsInclude == OverlapsInclude.Begin || overlapsInclude == OverlapsInclude.Both)
            {
                current.Overlaps(dateTimeRange6, overlapsInclude).ShouldTrue();
            }
            else
            {
                current.Overlaps(dateTimeRange6, overlapsInclude).ShouldFalse();
            }


            if (overlapsInclude == OverlapsInclude.End || overlapsInclude == OverlapsInclude.Both)
            {
                current.Overlaps(dateTimeRange7, overlapsInclude).ShouldTrue();
            }
            else
            {
                current.Overlaps(dateTimeRange7, overlapsInclude).ShouldFalse();
            }
        }
コード例 #31
0
ファイル: ServerPretend.cs プロジェクト: eliot2/StarsInMotion
        public bool WaitListShip(string Username, string ShipName)
        {
            List <string> WaitListedShipsList = GetAllWaitListedShips();

            if (WaitListedShipsList.Contains(ShipName))
            {
                Debug.Log("Can't waitlist this: " + ShipName + ", it's already rented!!");
                return(false);
            }
            //test to make sure we were given a proper UserName
            bool UsernameFound   = false;
            int  MatchingUserNum = 0;

            for (int i = 0; i < UserList.Count; i++)
            {
                if (UserList[i].Username == Username)
                {
                    UsernameFound   = true;
                    MatchingUserNum = i;
                }
            }
            if (UsernameFound == false)
            {
                return(UsernameFound);
            }

            DateTime OldestWaitEntry = DateTime.MinValue;

            //Search through users and find the user waitlisting this ship that is highest
            for (int i = 0; i < UserList.Count; i++)
            {
                //if person waitlisting target ship.
                if (UserList[i].WaitListShipName == ShipName)
                {
                    //check and see if they are the oldest / most recent to add to wait list.
                    if (UserList[i].WaitExpireTime.CompareTo(OldestWaitEntry) > 0)
                    {
                        Debug.Log("User " + Username + " has latest date: " + UserList[i].WaitExpireTime.ToString());
                        OldestWaitEntry = UserList[i].WaitExpireTime;
                    }
                }
            }

            //if the renter is wait list #1, check to see if the ship is rented.
            //if the ship isn' rented and our user hasn't rented a ship, rent the ship
            bool ShipRented = false;

            for (int i = 0; i < UserList.Count; i++)
            {
                if (UserList[i].RentedShipName == ShipName)
                {
                    ShipRented = true;
                }
            }
            if (ShipRented == false && UserList[MatchingUserNum].RentedShipName == "")
            {
                RentingShip(Username, ShipName);
                Debug.Log("WaitList attempted, Rented instead");
                return(false);
            }
            //If the user can't auto-rent the ship, it gets waitlisted:
            else
            {
                Debug.Log("Ship Currently Waitlisted, renting instead");
                //if no one else had waitlisted this ship . . .
                if (OldestWaitEntry.CompareTo(DateTime.MinValue) == 0)
                {
                    OldestWaitEntry = DateTime.Now;
                }
            }

            //WaitList time is last person in waitlist + rent time.
            OldestWaitEntry = OldestWaitEntry.AddHours(TOTAL_RENT_TIME);

            //reassign all stuff to insert into userlists. Structs can't be modified,
            // only reassigned.
            UserProfile tempProf;

            tempProf.Username         = UserList[MatchingUserNum].Username;
            tempProf.Password         = UserList[MatchingUserNum].Password;
            tempProf.Credits          = UserList[MatchingUserNum].Credits;
            tempProf.TimeToReturnBy   = UserList[MatchingUserNum].TimeToReturnBy;
            tempProf.RentedShipName   = UserList[MatchingUserNum].RentedShipName;
            tempProf.WaitExpireTime   = OldestWaitEntry;
            tempProf.WaitListShipName = ShipName;
            UserList[MatchingUserNum] = tempProf;
            Debug.Log("WaitList attempted, Waitlisting Success: TIme: " + OldestWaitEntry.ToString());
            UpdateWaitLists(Username);
            return(true);
        }
コード例 #32
0
        public async Task <ActionResult <CallTrendChart> > CallTrendChartData([Required][FromQuery] string labName, [FromQuery] DateTime?fromDate = null, [FromQuery] DateTime?toDate = null)
        {
            if (fromDate == null)
            {
                fromDate = DateTime.Now.AddDays(Convert.ToDouble(config.GetValue <string>("DefaultReportFromDate")));
            }

            if (toDate == null)
            {
                toDate = DateTime.Now;
            }


            TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");

            fromDate = TimeZoneInfo.ConvertTimeFromUtc(fromDate.GetValueOrDefault().ToUniversalTime(), cstZone);

            toDate = TimeZoneInfo.ConvertTimeFromUtc(toDate.GetValueOrDefault().ToUniversalTime(), cstZone);

            toDate = toDate?.AddHours(23).AddMinutes(59).AddSeconds(59);

            labName = labName.Equals("All", StringComparison.InvariantCultureIgnoreCase) ? null: labName.ToUpper();

            CallTrendChart response = new CallTrendChart();

            var labs = GetLabs().Result.Value;

            var months = GetMonths(fromDate.GetValueOrDefault(), toDate.GetValueOrDefault());

            response.labs = labs;

            response.period = months;

            response.labName = labName ?? "All";

            var callTypes = new List <string>()
            {
                "MISSED", "INCOMING", "OUTGOING"
            };

            response.callTypes = callTypes;

            Dictionary <string, List <ChartMetrics> > callTrendDictionary = new Dictionary <string, List <ChartMetrics> >();

            foreach (var item in callTypes)
            {
                var callType = new List <ChartMetrics>();

                foreach (var month in months)
                {
                    ChartMetrics chartV2 = new ChartMetrics();

                    chartV2.Name = month;

                    callType.Add(chartV2);
                }

                callTrendDictionary.Add(item, callType);
            }

            var validCalls = await context.ValidCalls
                             .Where(s => s.EventTime >= fromDate && s.EventTime <= toDate && s.LabName.ToUpper() == (labName ?? s.LabName.ToUpper()))
                             .Select(x => new { x.EventTime, x.ValidCallId, CallType = x.CallType.ToUpper() })
                             .ToListAsync();

            var missedCalls = await context.MissedCalls
                              .Where(s => s.EventTime >= fromDate && s.EventTime <= toDate && s.LabName.ToUpper() == (labName ?? s.LabName.ToUpper()))
                              .Select(x => new { x.EventTime, x.Id, CallType = "MISSED" })
                              .ToListAsync();

            var groupedValidCalls = validCalls.GroupBy(vc => new { vc.EventTime.Month, vc.EventTime.Year, vc.CallType })
                                    .Select(group => new
            {
                Metric = group.Key,
                Count  = group.Count()
            }).ToList();

            var groupedMissedCalls = missedCalls.GroupBy(vc => new { vc.EventTime.Month, vc.EventTime.Year, vc.CallType })
                                     .Select(group => new
            {
                Metric = group.Key,
                Count  = group.Count()
            }).ToList();

            foreach (var item in groupedValidCalls)
            {
                if (item.Metric.CallType == null)
                {
                    continue;
                }

                var purpose = callTrendDictionary[item.Metric.CallType] as List <ChartMetrics>;

                purpose.Where(m => m.Name == CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthGenitiveNames[item.Metric.Month - 1] + " " + item.Metric.Year).ToList().ForEach(s => s.count = item.Count);
            }

            foreach (var item in groupedMissedCalls)
            {
                if (item.Metric.CallType == null)
                {
                    continue;
                }

                var purpose = callTrendDictionary[item.Metric.CallType] as List <ChartMetrics>;

                purpose.Where(m => m.Name == CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthGenitiveNames[item.Metric.Month - 1] + " " + item.Metric.Year).ToList().ForEach(s => s.count = item.Count);
            }

            response.trendData = callTrendDictionary;

            response.countData = new List <List <string> >();

            foreach (var item in callTrendDictionary.Values)
            {
                response.countData.Add(item.Select(m => m.count.ToString()).ToList());
            }

            return(response);
        }
コード例 #33
0
ファイル: SQLiteDemo.cs プロジェクト: whw0828/EPASServer
        public static void Method()
        {
            IQuery <User> q = context.Query <User>();

            var space = new char[] { ' ' };

            DateTime startTime = DateTime.Now;
            DateTime endTime   = DateTime.Now.AddDays(1);

            var ret = q.Select(a => new
            {
                Id = a.Id,

                String_Length = (int?)a.Name.Length,                       //LENGTH([Users].[Name])
                Substring     = a.Name.Substring(0),                       //SUBSTR([Users].[Name],0 + 1)
                Substring1    = a.Name.Substring(1),                       //SUBSTR([Users].[Name],1 + 1)
                Substring1_2  = a.Name.Substring(1, 2),                    //SUBSTR([Users].[Name],1 + 1,2)
                ToLower       = a.Name.ToLower(),                          //LOWER([Users].[Name])
                ToUpper       = a.Name.ToUpper(),                          //UPPER([Users].[Name])
                IsNullOrEmpty = string.IsNullOrEmpty(a.Name),              //CASE WHEN ([Users].[Name] IS NULL OR [Users].[Name] = '') THEN 1 ELSE 0 END = 1
                Contains      = (bool?)a.Name.Contains("s"),               //[Users].[Name] LIKE '%' || 's' || '%'
                StartsWith    = (bool?)a.Name.StartsWith("s"),             //[Users].[Name] LIKE 's' || '%'
                EndsWith      = (bool?)a.Name.EndsWith("s"),               //[Users].[Name] LIKE '%' || 's'
                Trim          = a.Name.Trim(),                             //TRIM([Users].[Name])
                TrimStart     = a.Name.TrimStart(space),                   //LTRIM([Users].[Name])
                TrimEnd       = a.Name.TrimEnd(space),                     //RTRIM([Users].[Name])

                DiffYears   = DbFunctions.DiffYears(startTime, endTime),   //(CAST(STRFTIME('%Y',@P_0) AS INTEGER) - CAST(STRFTIME('%Y',@P_1) AS INTEGER))
                DiffMonths  = DbFunctions.DiffMonths(startTime, endTime),  //((CAST(STRFTIME('%Y',@P_0) AS INTEGER) - CAST(STRFTIME('%Y',@P_1) AS INTEGER)) * 12 + (CAST(STRFTIME('%m',@P_0) AS INTEGER) - CAST(STRFTIME('%m',@P_1) AS INTEGER)))
                DiffDays    = DbFunctions.DiffDays(startTime, endTime),    //CAST((JULIANDAY(@P_0) - JULIANDAY(@P_1)) AS INTEGER)
                DiffHours   = DbFunctions.DiffHours(startTime, endTime),   //CAST((JULIANDAY(@P_0) - JULIANDAY(@P_1)) * 24 AS INTEGER)
                DiffMinutes = DbFunctions.DiffMinutes(startTime, endTime), //CAST((JULIANDAY(@P_0) - JULIANDAY(@P_1)) * 1440 AS INTEGER)
                DiffSeconds = DbFunctions.DiffSeconds(startTime, endTime), //CAST((JULIANDAY(@P_0) - JULIANDAY(@P_1)) * 86400 AS INTEGER)
                //DiffMilliseconds = DbFunctions.DiffMilliseconds(startTime, endTime),//不支持 Millisecond
                //DiffMicroseconds = DbFunctions.DiffMicroseconds(startTime, endTime),//不支持 Microseconds

                AddYears   = startTime.AddYears(1),     //DATETIME(@P_0,'+' || 1 || ' years')
                AddMonths  = startTime.AddMonths(1),    //DATETIME(@P_0,'+' || 1 || ' months')
                AddDays    = startTime.AddDays(1),      //DATETIME(@P_0,'+' || 1 || ' days')
                AddHours   = startTime.AddHours(1),     //DATETIME(@P_0,'+' || 1 || ' hours')
                AddMinutes = startTime.AddMinutes(2),   //DATETIME(@P_0,'+' || 2 || ' minutes')
                AddSeconds = startTime.AddSeconds(120), //DATETIME(@P_0,'+' || 120 || ' seconds')
                //AddMilliseconds = startTime.AddMilliseconds(2000),//不支持

                Now         = DateTime.Now,             //DATETIME('NOW','LOCALTIME')
                UtcNow      = DateTime.UtcNow,          //DATETIME()
                Today       = DateTime.Today,           //DATE('NOW','LOCALTIME')
                Date        = DateTime.Now.Date,        //DATE('NOW','LOCALTIME')
                Year        = DateTime.Now.Year,        //CAST(STRFTIME('%Y',DATETIME('NOW','LOCALTIME')) AS INTEGER)
                Month       = DateTime.Now.Month,       //CAST(STRFTIME('%m',DATETIME('NOW','LOCALTIME')) AS INTEGER)
                Day         = DateTime.Now.Day,         //CAST(STRFTIME('%d',DATETIME('NOW','LOCALTIME')) AS INTEGER)
                Hour        = DateTime.Now.Hour,        //CAST(STRFTIME('%H',DATETIME('NOW','LOCALTIME')) AS INTEGER)
                Minute      = DateTime.Now.Minute,      //CAST(STRFTIME('%M',DATETIME('NOW','LOCALTIME')) AS INTEGER)
                Second      = DateTime.Now.Second,      //CAST(STRFTIME('%S',DATETIME('NOW','LOCALTIME')) AS INTEGER)
                Millisecond = DateTime.Now.Millisecond, //@P_2 直接计算 DateTime.Now.Millisecond 的值
                DayOfWeek   = DateTime.Now.DayOfWeek,   //CAST(STRFTIME('%w',DATETIME('NOW','LOCALTIME')) AS INTEGER)

                Byte_Parse   = byte.Parse("1"),         //CAST('1' AS INTEGER)
                Int_Parse    = int.Parse("1"),          //CAST('1' AS INTEGER)
                Int16_Parse  = Int16.Parse("11"),       //CAST('11' AS INTEGER)
                Long_Parse   = long.Parse("2"),         //CAST('2' AS INTEGER)
                Double_Parse = double.Parse("3.1"),     //CAST('3.1' AS REAL)
                Float_Parse  = float.Parse("4.1"),      //CAST('4.1' AS REAL)
                //Decimal_Parse = decimal.Parse("5"),//不支持
                //Guid_Parse = Guid.Parse("D544BC4C-739E-4CD3-A3D3-7BF803FCE179"),//不支持 'D544BC4C-739E-4CD3-A3D3-7BF803FCE179'

                Bool_Parse     = bool.Parse("1"),              //CAST('1' AS INTEGER)
                DateTime_Parse = DateTime.Parse("2014-01-01"), //DATETIME('2014-01-01')
            }).ToList();

            ConsoleHelper.WriteLineAndReadKey();
        }
コード例 #34
0
ファイル: _HTTPDateParse.cs プロジェクト: uQr/referencesource
        ParseHttpDate(
                     String DateString,
                     out DateTime dtOut
                     ) {
            int index = 0;
            int i = 0, iLastLettered = -1;
            bool fIsANSIDateFormat = false;
            int [] rgdwDateParseResults = new int[MAX_FIELD_DATE_ENTRIES];
            bool fRet = true;
            char [] lpInputBuffer = DateString.ToCharArray();

            dtOut = new DateTime();

            //
            // Date Parsing v2 (1 more to go), and here is how it works...
            //  We take a date string and churn through it once, converting
            //  integers to integers, Month,Day, and GMT strings into integers,
            //  and all is then placed IN order in a temp array.
            //
            // At the completetion of the parse stage, we simple look at
            //  the data, and then map the results into the correct
            //  places in the SYSTIME structure.  Simple, No allocations, and
            //  No dirting the data.
            //
            // The end of the function does something munging and pretting
            //  up of the results to handle the year 2000, and TZ offsets
            //  Note: do we need to fully handle TZs anymore?
            //

            while (index < DateString.Length && i < MAX_FIELD_DATE_ENTRIES) {
                if (lpInputBuffer[index] >= '0' && lpInputBuffer[index] <= '9') {
                    //
                    // we have a numerical entry, scan through it and convent to DWORD
                    //

                    rgdwDateParseResults[i] = 0;

                    do {
                        rgdwDateParseResults[i] *= BASE_DEC;
                        rgdwDateParseResults[i] += (lpInputBuffer[index] - '0');
                        index++;
                    } while (index < DateString.Length &&
                             lpInputBuffer[index] >= '0' &&
                             lpInputBuffer[index] <= '9');

                    i++; // next token
                }
                else if ((lpInputBuffer[index] >= 'A' && lpInputBuffer[index] <= 'Z') ||
                         (lpInputBuffer[index] >= 'a' && lpInputBuffer[index] <= 'z')) {
                    //
                    // we have a string, should be a day, month, or GMT
                    //   lets skim to the end of the string
                    //

                    rgdwDateParseResults[i] =
                    MapDayMonthToDword(lpInputBuffer, index);

                    iLastLettered = i;

                    // We want to ignore the possibility of a time zone such as PST or EST in a non-standard
                    // date format such as "Thu Dec 17 16:01:28 PST 1998" (Notice that the year is _after_ the time zone
                    if ((rgdwDateParseResults[i] == DATE_TOKEN_ERROR)
                        &&
                        !(fIsANSIDateFormat && (i==DATE_ANSI_INDEX_YEAR))) {
                        fRet = false;
                        goto quit;
                    }

                    //
                    // At this point if we have a vaild string
                    //  at this index, we know for sure that we're
                    //  looking at a ANSI type DATE format.
                    //

                    if (i == DATE_ANSI_INDEX_MONTH) {
                        fIsANSIDateFormat = true;
                    }

                    //
                    // Read past the end of the current set of alpha characters,
                    //  as MapDayMonthToDword only peeks at a few characters
                    //

                    do {
                        index++;
                    } while (index < DateString.Length &&
                             ( (lpInputBuffer[index] >= 'A' && lpInputBuffer[index] <= 'Z') ||
                               (lpInputBuffer[index] >= 'a' && lpInputBuffer[index] <= 'z') ));

                    i++; // next token
                }
                else {
                    //
                    // For the generic case its either a space, comma, semi-colon, etc.
                    //  the point is we really don't care, nor do we need to waste time
                    //  worring about it (the orginal code did).   The point is we
                    //  care about the actual date information, So we just advance to the
                    //  next lexume.
                    //

                    index++;
                }
            }

            //
            // We're finished parsing the string, now take the parsed tokens
            //  and turn them to the actual structured information we care about.
            //  So we build lpSysTime from the Array, using a local if none is passed in.
            //

            int year;
            int month;
            int day;
            int hour;
            int minute;
            int second;
            int millisecond;

            millisecond =  0;

            if (fIsANSIDateFormat) {
                day    = rgdwDateParseResults[DATE_ANSI_INDEX_DAY];
                month  = rgdwDateParseResults[DATE_ANSI_INDEX_MONTH];
                hour   = rgdwDateParseResults[DATE_ANSI_INDEX_HRS];
                minute = rgdwDateParseResults[DATE_ANSI_INDEX_MINS];
                second = rgdwDateParseResults[DATE_ANSI_INDEX_SECS];
                if (iLastLettered != DATE_ANSI_INDEX_YEAR) {
                    year   = rgdwDateParseResults[DATE_ANSI_INDEX_YEAR];
                }
                else {
                    // This is a fix to get around toString/toGMTstring (where the timezone is
                    // appended at the end. (See above)
                    year   = rgdwDateParseResults[DATE_INDEX_TZ];
                }
            }
            else {
                day    = rgdwDateParseResults[DATE_1123_INDEX_DAY];
                month  = rgdwDateParseResults[DATE_1123_INDEX_MONTH];
                year   = rgdwDateParseResults[DATE_1123_INDEX_YEAR];
                hour   = rgdwDateParseResults[DATE_1123_INDEX_HRS];
                minute = rgdwDateParseResults[DATE_1123_INDEX_MINS];
                second = rgdwDateParseResults[DATE_1123_INDEX_SECS];
            }

            //
            // Normalize the year, 90 == 1990, handle the year 2000, 02 == 2002
            //  This is Year 2000 handling folks!!!  We get this wrong and
            //  we all look bad.
            //

            if (year < 100) {
                year += ((year < 80) ? 2000 : 1900);
            }

            //
            // if we got misformed time, then plug in the current time
            // !lpszHrs || !lpszMins || !lpszSec
            //

            if ((i < 4)
                || (day > 31)
                || (hour > 23)
                || (minute > 59)
                || (second > 59)) {
                fRet = false;
                goto quit;
            }

            //
            // Now do the DateTime conversion
            //

            dtOut = new DateTime (year, month, day, hour, minute, second, millisecond);

            //
            // we want the system time to be accurate. This is _suhlow_
            // The time passed in is in the local time zone; we have to convert this into GMT.
            //

            if (iLastLettered==DATE_ANSI_INDEX_YEAR) {
                // this should be an unusual case.
                dtOut = dtOut.ToUniversalTime();
            }

            //
            // If we have an Offset to another Time Zone
            //   then convert to appropriate GMT time
            //

            if ((i > DATE_INDEX_TZ &&
                 rgdwDateParseResults[DATE_INDEX_TZ] != DATE_TOKEN_GMT)) {

                //
                // if we received +/-nnnn as offset (hhmm), modify the output FILETIME
                //

                double offset;

                offset = (double) rgdwDateParseResults[DATE_INDEX_TZ];
                dtOut.AddHours(offset);
            }

            // In the end, we leave it all in LocalTime

            dtOut = dtOut.ToLocalTime();

            quit:

            return fRet;
        }
コード例 #35
0
ファイル: ApproachVolumeChart.cs プロジェクト: zfx1982/ATSPM
        public DataTable CreateVolumeMetricsTable(string direction1, string direction2, int D1TV, int D2TV, SortedDictionary <DateTime, int> D1Volumes, SortedDictionary <DateTime, int> D2Volumes, ApproachVolumeOptions options)
        {
            DateTime startTime = new DateTime();
            DateTime endTime   = new DateTime();
            bool     missingD1 = false;
            bool     missingD2 = false;

            //Create the Volume Metrics table
            if (D1Volumes.Count > 0)
            {
                startTime = D1Volumes.First().Key;
                endTime   = D1Volumes.Last().Key;
                missingD1 = true;
            }
            else if (D1Volumes.Count > 0)
            {
                startTime = D2Volumes.First().Key;
                endTime   = D2Volumes.Last().Key;
                missingD2 = true;
            }
            else if (missingD1 || missingD2)
            {
                DataTable emptytable = new DataTable();
                return(emptytable);
            }

            TimeSpan timeDiff = endTime.Subtract(startTime);


            DataTable  volMetrics        = new DataTable();
            int        binSizeMultiplier = 60 / options.SelectedBinSize;
            DataColumn volMetName        = new DataColumn();
            DataColumn volMetValue       = new DataColumn();

            volMetName.ColumnName  = "Metric";
            volMetValue.ColumnName = "Values";


            bool validKfactors = false;

            if (timeDiff.TotalHours >= 23 && timeDiff.TotalHours < 25)
            {
                validKfactors = true;
            }
            SortedDictionary <DateTime, int> biDirVolumes    = new SortedDictionary <DateTime, int>();
            SortedDictionary <int, int>      D1HourlyVolumes = new SortedDictionary <int, int>();
            SortedDictionary <int, int>      D2HourlyVolumes = new SortedDictionary <int, int>();

            // if (!missingD1 && !missingD2)
            // {
            //add the two volume dictionaries to get a total dictionary
            foreach (KeyValuePair <DateTime, int> current in D1Volumes)
            {
                if (D2Volumes.ContainsKey(current.Key))
                {
                    biDirVolumes.Add(current.Key, (D2Volumes[current.Key] + current.Value));
                }
            }

            KeyValuePair <DateTime, int> biDirPeak = findPeakHour(biDirVolumes, binSizeMultiplier);
            DateTime biDirPeakHour   = biDirPeak.Key;
            int      biDirPeakVolume = biDirPeak.Value;
            int      biDirPHvol      = findPeakValueinHour(biDirPeakHour, biDirVolumes, binSizeMultiplier);
            // Find Total PHF
            double biDirPHF = 0;

            if (biDirPHvol > 0)
            {
                biDirPHF = Convert.ToDouble(biDirPeakVolume) / Convert.ToDouble((biDirPHvol * binSizeMultiplier));
                biDirPHF = SetSigFigs(biDirPHF, 3);
            }

            string biDirPeakHourString = biDirPeakHour.ToShortTimeString() + " - " + biDirPeakHour.AddHours(1).ToShortTimeString();

            //   }

            //  if (!missingD1)
            //  {
            KeyValuePair <DateTime, int> D1Peak = findPeakHour(D1Volumes, binSizeMultiplier);
            DateTime D1PeakHour       = D1Peak.Key;
            int      D1PeakHourVolume = D1Peak.Value;
            int      D1PHvol          = findPeakValueinHour(D1PeakHour, D1Volumes, binSizeMultiplier);
            // Find the Peak hour factor for Direciton1
            double D1PHF = 0;

            if (D1PHvol > 0)
            {
                D1PHF = Convert.ToDouble(D1PeakHourVolume) / Convert.ToDouble((D1PHvol * binSizeMultiplier));
                D1PHF = SetSigFigs(D1PHF, 3);
            }

            // }

            // if (!missingD2)
            // {
            KeyValuePair <DateTime, int> D2Peak = findPeakHour(D2Volumes, binSizeMultiplier);

            DateTime D2PeakHour       = D2Peak.Key;
            int      D2PeakHourVolume = D2Peak.Value;
            int      D2PHvol          = findPeakValueinHour(D2PeakHour, D2Volumes, binSizeMultiplier);
            // Find the Peak hour factor for Direciton2
            double D2PHF = 0;

            if (D2PHvol > 0)
            {
                D2PHF = Convert.ToDouble(D2PeakHourVolume) / Convert.ToDouble((D2PHvol * binSizeMultiplier));
                D2PHF = SetSigFigs(D2PHF, 3);
            }
            // }

            string D1PeakHourString = D1PeakHour.ToShortTimeString() + " - " + D1PeakHour.AddHours(1).ToShortTimeString();
            string D2PeakHourString = D2PeakHour.ToShortTimeString() + " - " + D2PeakHour.AddHours(1).ToShortTimeString();


            int    totalVolume = D1TV + D2TV;
            string PHKF        = SetSigFigs((Convert.ToDouble(biDirPeakVolume) / Convert.ToDouble(totalVolume)), 3).ToString();
            string D1PHKF      = SetSigFigs((Convert.ToDouble(D1PeakHourVolume) / Convert.ToDouble(D1TV)), 3).ToString();
            string D1PHDF      = findPHDF(D1PeakHour, D1PeakHourVolume, D2Volumes, binSizeMultiplier).ToString();
            string D2PHKF      = SetSigFigs((Convert.ToDouble(D2PeakHourVolume) / Convert.ToDouble(D2TV)), 3).ToString();
            string D2PHDF      = findPHDF(D2PeakHour, D2PeakHourVolume, D1Volumes, binSizeMultiplier).ToString();

            volMetrics.Columns.Add(volMetName);
            volMetrics.Columns.Add(volMetValue);


            volMetrics.Rows.Add(new Object[] { "Total Volume", totalVolume.ToString("N0") });
            volMetrics.Rows.Add(new Object[] { "Peak Hour", biDirPeakHourString });
            volMetrics.Rows.Add(new Object[] { "Peak Hour Volume", string.Format("{0:#,0}", biDirPeakVolume) });
            volMetrics.Rows.Add(new Object[] { "PHF", biDirPHF.ToString() });

            if (validKfactors)
            {
                volMetrics.Rows.Add(new Object[] { "Peak-Hour K-factor", PHKF });
            }
            else
            {
                volMetrics.Rows.Add(new Object[] { "Peak-Hour K-factor", "NA" });
            }

            volMetrics.Rows.Add(new Object[] { "", "" });
            volMetrics.Rows.Add(new Object[] { (direction1 + " Total Volume"), D1TV.ToString("N0") });
            volMetrics.Rows.Add(new Object[] { (direction1 + " Peak Hour"), D1PeakHourString });
            volMetrics.Rows.Add(new Object[] { (direction1 + " Peak Hour Volume"), string.Format("{0:#,0}", D1PeakHourVolume) });
            volMetrics.Rows.Add(new Object[] { (direction1 + " PHF"), D1PHF.ToString() });

            if (validKfactors)
            {
                volMetrics.Rows.Add(new Object[] { (direction1 + " Peak-Hour K-factor"), D1PHKF });
            }
            else
            {
                volMetrics.Rows.Add(new Object[] { (direction1 + " Peak-Hour K-factor"), "NA" });
            }

            volMetrics.Rows.Add(new Object[] { (direction1 + " Peak-Hour D-factor"), D1PHDF });
            volMetrics.Rows.Add(new Object[] { "", "" });
            volMetrics.Rows.Add(new Object[] { (direction2 + " Total Volume"), D2TV.ToString("N0") });
            volMetrics.Rows.Add(new Object[] { (direction2 + " Peak Hour"), D2PeakHourString });
            volMetrics.Rows.Add(new Object[] { (direction2 + " Peak Hour Volume"), string.Format("{0:#,0}", D2PeakHourVolume) });
            volMetrics.Rows.Add(new Object[] { (direction2 + " PHF"), D2PHF.ToString("N0") });

            if (validKfactors)
            {
                volMetrics.Rows.Add(new Object[] { (direction2 + " Peak-Hour K-factor"), D2PHKF });
            }
            else
            {
                volMetrics.Rows.Add(new Object[] { (direction2 + " Peak-Hour K-factor"), "NA" });
            }

            volMetrics.Rows.Add(new Object[] { (direction2 + " Peak-Hour D-factor"), D2PHDF });



            info.Direction1       = direction1;
            info.Direction2       = direction2;
            info.D1PeakHour       = D1PeakHourString;
            info.D2PeakHour       = D2PeakHourString;
            info.D1PeakHourVolume = D1PeakHourVolume.ToString();
            info.D1PeakHourKValue = D1PHKF;
            info.D1PeakHourDValue = D1PHDF;
            info.D1PHF            = D1PHF.ToString();
            info.D2PeakHourVolume = D2PeakHourVolume.ToString();
            info.D2PeakHourKValue = D2PHKF;
            info.D2PeakHourDValue = D2PHDF;
            info.D2PHF            = D2PHF.ToString();
            info.TotalVolume      = totalVolume.ToString();
            info.PeakHour         = biDirPeakHour.ToString();
            info.PeakHourVolume   = biDirPeakVolume.ToString();
            info.PHF             = biDirPHF.ToString();
            info.PeakHourKFactor = PHKF;
            info.D1TotalVolume   = D1TotalVolume.ToString();
            info.D2TotalVolume   = D2TotalVolume.ToString();



            return(volMetrics);
        }