ToString() публичный Метод

public ToString ( ) : String
Результат String
 public virtual bool runTest()
   {
   int iCountErrors = 0;
   int iCountTestcases = 0;
   Console.Error.WriteLine( strName + ": " + strTest + " runTest started..." );
   TimeSpan	ts;
   String		strDefTime = "00:00:00";
   long[]		lTicks = { 0L, 10000L, 1000*10000L, -1 };
   String[]	strResults =
   {
     "00:00:00",
     "00:00:00.0010000",
     "00:00:01",
     "-00:00:00.0000001",
   };
   do
     {
     Console.Error.WriteLine( "[]  Construct and verify TimeSpan objects" );
     try
       {
       for ( int ii = 0; ii < lTicks.Length; ++ii )
	 {
	 ++iCountTestcases;
	 ts = new TimeSpan( lTicks[ii] );
	 if ( String.Equals( ts.ToString(), strResults[ii] ) != true )
	   {
	   String strInfo = strTest + " error: ";
	   strInfo = strInfo + "Expected TimeSpan string <" + strResults[ii] + "> ";
	   strInfo = strInfo + "Returned TimeSpan string <" + ts.ToString() + "> ";
	   Console.WriteLine( strTest+ "E_101b: " + strInfo );
	   ++iCountErrors;
	   break;
	   }
	 }
       }
     catch (Exception ex)
       {
       Console.WriteLine( strTest+ "E_10001: Unexpected Exception: " + ex.ToString() );
       ++iCountErrors;
       break;
       }
     }
   while ( false );
   Console.Error.Write( strName );
   Console.Error.Write( ": " );
   if ( iCountErrors == 0 )
     {
     Console.Error.WriteLine( strTest + " iCountTestcases==" + iCountTestcases + " paSs" );
     return true;
     }
   else
     {
     System.String strFailMsg = null;
     Console.WriteLine( strTest+ strPath );
     Console.WriteLine( strTest+ "FAiL" );
     Console.Error.WriteLine( strTest + " iCountErrors==" + iCountErrors );
     return false;
     }
   }
Пример #2
0
    //--------------------------------------------------------------------------------------------

    static string FormatElapsed(TimeSpan dt)
        {
        StringBuilder result = new StringBuilder();
        if (dt.Days != 0)
            {
            result.Append(dt.ToString(@"%d"));
            result.Append(dt.Days <= 1 ? " day " : " days ");
            }
        result.Append(dt.ToString(@"hh\:mm\:ss\.ff"));
        return result.ToString();
        }
Пример #3
0
 public string GetTimeZoneStringFromDouble(double TimeZoneOffset, string TimeZoneName)
 {
     int hour = Convert.ToInt32(Math.Floor(TimeZoneOffset));
     int minute = Convert.ToInt32((TimeZoneOffset - hour) * 60.0);
     TimeSpan span = new TimeSpan(hour, minute, 0);
     string timezone_string = span.ToString().Remove(span.ToString().Length - 3) + ") " + TimeZoneName;
     if (hour >= 0)
         return "(GMT+" + timezone_string;
     else
         return "(GMT" + timezone_string;
 }
Пример #4
0
 public virtual bool runTest()
   {
   int iCountErrors = 0;
   int iCountTestcases = 0;
   Console.Error.WriteLine( strName + ": " + strTest + " runTest started..." );
   TimeSpan	ts;
   String		strDefTime = "00:00:00";
   do
     {
     ++iCountTestcases;
     Console.Error.WriteLine( "[]  Construct default TimeSpan object" );
     try
       {
       ts = new TimeSpan();
       if ( String.Equals( ts.ToString(), "00:00:00") != true )
	 {
	 String strInfo = strTest + " error: ";
	 strInfo = strInfo + "Expected TimeSpan string <00:00:00>";
	 strInfo = strInfo + "Returned TimeSpan string <"+ ts.ToString() + "> ";
	 Console.WriteLine( strTest+ "E_101b: " + strInfo );
	 ++iCountErrors;
	 break;
	 }
       }
     catch (Exception ex)
       {
       Console.WriteLine( strTest+ "E_10001: Unexpected Exception: " + ex.ToString() );
       ++iCountErrors;
       break;
       }
     }
   while ( false );
   Console.Error.Write( strName );
   Console.Error.Write( ": " );
   if ( iCountErrors == 0 )
     {
     Console.Error.WriteLine( strTest + " iCountTestcases==" + iCountTestcases + " paSs" );
     return true;
     }
   else
     {
     System.String strFailMsg = null;
     Console.WriteLine( strTest+ strPath );
     Console.WriteLine( strTest+ "FAiL" );
     Console.Error.WriteLine( strTest + " iCountErrors==" + iCountErrors );
     return false;
     }
   }
Пример #5
0
 public void convert_seconds(int seconds)
 {
     TimeSpan duration = new TimeSpan(0, 0, 0, seconds);
     string output = null;
     output = duration.ToString(@"hh\:mm\:ss");
     Console.WriteLine(output);
 }
Пример #6
0
        private void SaveSettings_CallsUpdateSetting_WithRightParameters(string stringValue, int?integerValue, DateTime?datetimeValue, TimeSpan?timeSpanValue)
        {
            // Arrange
            var moduleInfo = GetModuleInfo;
            var settings   = new MyNullableSettings
            {
                StringProperty   = stringValue,
                IntegerProperty  = integerValue,
                DateTimeProperty = datetimeValue,
                TimeSpanProperty = timeSpanValue,
            };

            this.MockModuleSettings(moduleInfo, new Hashtable());
            this.MockTabModuleSettings(moduleInfo, new Hashtable());
            var expectedStringValue = stringValue ?? string.Empty;

            this.MockModuleController.Setup(pc => pc.UpdateModuleSetting(ModuleId, "StringProperty", expectedStringValue));
            var integerString = integerValue?.ToString() ?? string.Empty;

            this.MockPortalController.Setup(pc => pc.UpdatePortalSetting(PortalId, "IntegerProperty", integerString, true, Null.NullString, false));
            var dateTimeString = datetimeValue?.ToString("o", CultureInfo.InvariantCulture) ?? string.Empty;

            this.MockModuleController.Setup(mc => mc.UpdateModuleSetting(ModuleId, "DateTimeProperty", dateTimeString));
            var timeSpanString = timeSpanValue?.ToString("c", CultureInfo.InvariantCulture) ?? string.Empty;

            this.MockModuleController.Setup(mc => mc.UpdateTabModuleSetting(TabModuleId, "TimeSpanProperty", timeSpanString));

            var settingsRepository = new MyNullableSettingsRepository();

            // Act
            settingsRepository.SaveSettings(moduleInfo, settings);

            // Assert
            this.MockRepository.VerifyAll();
        }
Пример #7
0
        private void GetSettings_GetsValues_FromCorrectSettings(string stringValue, int?integerValue, DateTime?datetimeValue, TimeSpan?timeSpanValue)
        {
            // Arrange
            var expectedStringValue = stringValue ?? string.Empty;
            var moduleInfo          = GetModuleInfo;
            var portalSettings      = new Dictionary <string, string> {
                ["IntegerProperty"] = integerValue?.ToString() ?? string.Empty,
            };
            var moduleSettings = new Hashtable {
                ["DateTimeProperty"] = datetimeValue?.ToString("o", CultureInfo.InvariantCulture) ?? string.Empty, ["StringProperty"] = expectedStringValue,
            };
            var tabModuleSettings = new Hashtable {
                ["TimeSpanProperty"] = timeSpanValue?.ToString("c", CultureInfo.InvariantCulture) ?? string.Empty,
            };

            this.MockPortalSettings(moduleInfo, portalSettings);
            this.MockModuleSettings(moduleInfo, moduleSettings);
            this.MockTabModuleSettings(moduleInfo, tabModuleSettings);

            var settingsRepository = new MyNullableSettingsRepository();

            // Act
            var settings = settingsRepository.GetSettings(moduleInfo);

            // Assert
            Assert.AreEqual(expectedStringValue, settings.StringProperty, "The retrieved string property value is not equal to the stored one");
            Assert.AreEqual(integerValue, settings.IntegerProperty, "The retrieved integer property value is not equal to the stored one");
            Assert.AreEqual(datetimeValue, settings.DateTimeProperty, "The retrieved datetime property value is not equal to the stored one");
            Assert.AreEqual(timeSpanValue, settings.TimeSpanProperty, "The retrieved timespan property value is not equal to the stored one");
            this.MockRepository.VerifyAll();
        }
Пример #8
0
        /// <inheritdoc/>
        public override void DefineHtmlBuilder()
        {
            TimeSpan?timeValue = null;

            if (this.Value != null)
            {
                timeValue = (TimeSpan)this.Value;
            }

            Guid itemId = Guid.NewGuid();

            this.HtmlBuilder.StartElement(HtmlTags.Div)
            .WithId($"timepicker-{itemId}")
            .WithClasses("input-group date")
            .Append(x => x
                    .OpenElement(HtmlTags.Div)
                    .WithClasses("input-group")
                    .Append(xx => xx
                            .OpenElement(HtmlTags.Input)
                            .WithAttribute("type", "text")
                            .WithAttribute("name", this.TargetProperty)
                            .WithClasses("form-control timepicker-popup")
                            .WithAttributeIf("value", timeValue?.ToString(SystemFormats.TimeFormat), timeValue.HasValue))
                    .Append(xx => xx
                            .OpenElement(HtmlTags.Div)
                            .WithClasses("input-group-addon input-group-append")
                            .Append(xxx => xxx
                                    .OpenElement(HtmlTags.Span)
                                    .WithClasses("mdi mdi-clock input-group-text"))));
        }
Пример #9
0
        private void LogScheduledTaskRun()
        {
            var intervalString = _intervalOrOffsetFromNow?.ToString() ??
                                 _scheduledTimeAsDateTimeOffset?.ToString() ?? _scheduledTime?.ToString() ?? _crontab;

            Console.WriteLine($"Running Scheduled Task with interval: {intervalString}");
        }
Пример #10
0
        public static MvcHtmlString TimeSpanPicker(this HtmlHelper helper, ValueLine valueLine)
        {
            TimeSpan?value = (TimeSpan?)valueLine.UntypedValue;

            if (valueLine.ReadOnly)
            {
                MvcHtmlString result = MvcHtmlString.Empty;
                if (valueLine.WriteHiddenOnReadonly)
                {
                    result = result.Concat(HiddenWithoutId(valueLine.Prefix, value?.ToString(valueLine.Format)));
                }

                return(result.Concat(helper.FormControlStatic(valueLine, valueLine.Prefix, value?.ToString(valueLine.Format), valueLine.ValueHtmlProps)));
            }

            var dateFormatAttr = valueLine.PropertyRoute.PropertyInfo.GetCustomAttribute <TimeSpanDateFormatAttribute>();

            if (dateFormatAttr != null)
            {
                return(helper.TimePicker(valueLine.Prefix, true, value, dateFormatAttr.Format, CultureInfo.CurrentCulture, valueLine.ValueHtmlProps));
            }
            else
            {
                valueLine.ValueHtmlProps.AddCssClass("form-control");
                return(helper.TextBox(valueLine.Prefix, value == null ? "" : value.Value.ToString(valueLine.Format, CultureInfo.CurrentCulture), valueLine.ValueHtmlProps));
            }
        }
Пример #11
0
    static void Main()
    {
        TimeSpan ts = new TimeSpan();
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();

        uint termValue = 0;
        uint result = 0;
        uint firstTerm = 1;
        uint secondTerm = 1;

        while(termValue < 4000001)
        {
            uint tempSum = firstTerm + secondTerm;
            if(tempSum % 2 == 0)
                result += tempSum;
            firstTerm = secondTerm;
            secondTerm = tempSum;
            termValue = tempSum;
        }

        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        ts = stopWatch.Elapsed;
        Console.WriteLine(result.ToString());
        Console.WriteLine(ts.ToString());
    }
Пример #12
0
        private void UpdateStatus(long readBytesPerSecond = -1, long writeBytesPerSecond = -1, long writeBytesRemaining = 0, long readBytesRemaining = 0, long verifyBytesPerSecond = 0)
        {
            const decimal EstimatedReadVsWriteSpeedRatio = 2M;

            if (ActivityLogTextBox.InvokeRequired)
            {
                UpdateStatusDelegate d = new UpdateStatusDelegate(UpdateStatus);
                Invoke(d, new object[] { readBytesPerSecond, writeBytesPerSecond, writeBytesRemaining, readBytesRemaining, verifyBytesPerSecond });
                return;
            }

            UpdateSpeedAverage(readBytesPerSecond, writeBytesPerSecond);

            decimal bytesPerSecond = 0;

            if (writeBytesPerSecond > 0)
            {
                bytesPerSecond = _averageWriteBytesPerSecond;
            }
            else if (readBytesPerSecond > 0)
            {
                bytesPerSecond = _averageReadBytesPerSecond;
            }

            TimeSpan?elapsedTime        = null;
            TimeSpan?writeTimeRemaining = null;
            TimeSpan?readTimeRemaining  = null;
            TimeSpan?totalTimeRemaining = null;

            if (_startDateTime != null)
            {
                elapsedTime        = new TimeSpan(0, 0, (int)(DateTime.Now - _startDateTime.Value).TotalSeconds);
                writeTimeRemaining = new TimeSpan(0, 0, bytesPerSecond < .01M ? 0 : (int)((decimal)writeBytesRemaining / bytesPerSecond));
                if (verifyBytesPerSecond > 1000)
                {
                    readTimeRemaining = new TimeSpan(0, 0, bytesPerSecond < .01M ? 0 : (int)((decimal)readBytesRemaining / verifyBytesPerSecond));                       // Assume read speed is the same as write speed since we do not know for sure.
                }
                else
                {
                    readTimeRemaining = new TimeSpan(0, 0, bytesPerSecond < .01M ? 0 : (int)((writeBytesPerSecond > 0 ? EstimatedReadVsWriteSpeedRatio : 1M)
                                                                                             * (decimal)readBytesRemaining / bytesPerSecond)); // Assume read speed is the same as write speed since we do not know for sure.
                }
                totalTimeRemaining = writeTimeRemaining + readTimeRemaining;
            }

            // Display to the user...
            ElapsedTimeLabel.Text        = elapsedTime?.ToString() ?? PALCEHOLDER_VALUE;
            TotalTimeRemainingLabel.Text = totalTimeRemaining?.ToString() ?? PALCEHOLDER_VALUE;

            if (_mediaTester != null)
            {
                WrittenBytesLabel.Text  = (_mediaTester?.TotalBytesWritten.ToString("#,##0") ?? PALCEHOLDER_VALUE) + BYTES;
                VerifiedBytesLabel.Text = (_mediaTester?.TotalBytesVerified.ToString("#,##0") ?? PALCEHOLDER_VALUE) + BYTES;
                FailedBytesLabel.Text   = (_mediaTester?.TotalBytesFailed.ToString("#,##0") ?? PALCEHOLDER_VALUE) + BYTES;
            }

            ProgressBar.Value = _mediaTester == null ? 0 : (int)(10M * _mediaTester.ProgressPercent);
        }
Пример #13
0
        private void ConfirmButton_Click(object sender, RoutedEventArgs e)
        {
            error.Content = "";
            ClassroomEntry selectedClassroom = (ClassroomEntry)_classroomComboBox.SelectedItem;
            RoomEntry      selectedRoom      = (RoomEntry)_roomNameComboBox.SelectedItem;
            int            repetitivity      = _regularityComboBox.SelectedIndex;

            WindowsXamlHost windowsHost    = _timePicker;
            TimePicker      timePickerHour = (TimePicker)windowsHost.Child;

            WindowsXamlHost windowsHost2         = _durationTimePicker;
            TimePicker      durationTimePicker   = (TimePicker)windowsHost2.Child;
            TimeSpan?       durationTimeSelected = durationTimePicker.SelectedTime;

            if (durationTimeSelected == null)
            {
                error.Foreground = new SolidColorBrush(Colors.Red);
                error.Content    = "Spécifier une durée";
                return;
            }
            TimeSpan?hourTimeSelected = timePickerHour.SelectedTime;

            if (hourTimeSelected == null)
            {
                error.Foreground = new SolidColorBrush(Colors.Red);
                error.Content    = "Spécifier une heure.";
                return;
            }
            DateTime?dateSelected = _firstDatePciker.SelectedDate;

            if (dateSelected == null)
            {
                error.Foreground = new SolidColorBrush(Colors.Red);
                error.Content    = "Spécifier une date de première séance";
                return;
            }

            DateTime dateSelectedNotNull = (DateTime)dateSelected;

            dateSelectedNotNull = dateSelectedNotNull.AddHours((double)hourTimeSelected?.Hours).AddMinutes((double)hourTimeSelected?.Minutes);

            int scheduleId = Database.Insert.Schedule.One(selectedClassroom.ID, selectedRoom.ID, repetitivity, dateSelectedNotNull, (TimeSpan)hourTimeSelected);

            ScheduleOption.ScheduleOptionDisplay scheduleDisplay = new ScheduleOption.ScheduleOptionDisplay()
            {
                ID           = scheduleId,
                ClassroomId  = selectedClassroom.ID,
                NextDate     = dateSelectedNotNull.ToString("g", GlobalVariable.culture),
                Duration     = durationTimeSelected?.ToString(@"hh\:mm"),
                Repetitivity = repetitivity == 0 ? "Une fois par semaine" : "Une semaine sur deux",
                Room         = Database.Get.Room.NameFromID(selectedRoom.ID)
            };

            //TODO: Make this work but not mendatory for now
            //ScheduleOption.scheduleDisplayCollection.Add(scheduleDisplay);
            error.Foreground = new SolidColorBrush(Colors.Green);
            error.Content    = "Horaire ajouté avec succès";
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        ObjectName = screenObject.Property("Object Name").Value;
        OSAEObjectState os = OSAEObjectStateManager.GetObjectStateValue(ObjectName);
        CurrentState = os.Value;

        OffTimer = Convert.ToUInt16(OSAEObjectPropertyManager.GetObjectPropertyValue(ObjectName, "OFF TIMER").Value);
        TimeInState = (int)os.TimeInState;

        string sBackColor = screenObject.Property("Back Color").Value;
        string sForeColor = screenObject.Property("Fore Color").Value;
        string sPrefix = screenObject.Property("Prefix").Value;
        string sSuffix = screenObject.Property("Suffix").Value;
        string iFontSize = screenObject.Property("Font Size").Value;

        if (CurrentState == "OFF")
            sValue = os.StateLabel;
        else
        {
            span = TimeSpan.FromSeconds(OffTimer - TimeInState); //Or TimeSpan.FromSeconds(seconds); (see Jakob C´s answer)
            sValue = span.ToString(@"mm\:ss");
        }

        TimerLabel.Text = sValue;
        TimerLabel.Attributes.Add("Style", "position:absolute;top:" + (Int32.Parse(screenObject.Property("Y").Value) + 50).ToString() + "px;left:" + (Int32.Parse(screenObject.Property("X").Value) + 10).ToString() + "px;z-index:" + (Int32.Parse(screenObject.Property("ZOrder").Value) + 10).ToString() + ";");

        if (sBackColor != "")
        {
            try
            {
                TimerLabel.BackColor = Color.FromName(sBackColor);
            }
            catch (Exception)
            {
            }
        }
        if (sForeColor != "")
        {
            try
            {
                TimerLabel.ForeColor = Color.FromName(sForeColor);
            }
            catch (Exception)
            {
            }
        }
        if (iFontSize != "")
        {
            try
            {
                TimerLabel.Font.Size = new FontUnit(iFontSize);
            }
            catch (Exception)
            {
            }
        }
    }
 public void CheckTimeSpan(TimeSpan value, string format)
 {
     var parsed = Format.Parse(format);
     var formatter = new StringFormatter(pool);
     formatter.Append(value, parsed);
     var result = formatter.ToString();
     var clrResult = value.ToString(format, CultureInfo.InvariantCulture);
     Assert.Equal(clrResult, result);
 }
        public void FormatTimeSpan()
        {
            var time = new TimeSpan(1000, 23, 40, 30, 12345);
            var sb = new StringFormatter();

            sb.Append(time);
            Assert.Equal(time.ToString("", CultureInfo.InvariantCulture), sb.ToString());
            sb.Clear();
        }
Пример #17
0
        public void UpdateData()
        {
            var gameState = Engine.GameState;

            Grounded.Visibility = gameState.IsGrounded ? Visibility.Visible : Visibility.Hidden;
            Climbing.Visibility = gameState.IsClimbing ? Visibility.Visible : Visibility.Hidden;
            Gliding.Visibility  = gameState.IsGliding ? Visibility.Visible : Visibility.Hidden;
            Swimming.Visibility = gameState.IsSwimming ? Visibility.Visible : Visibility.Hidden;

            FlightCooldown.Visibility = gameState.FlightIsOnCooldown ? Visibility.Visible : Visibility.Hidden;
            FlightTime.Text           = gameState.FlightDuration.ToString("ss','fff");
            GlideTime.Text            = gameState.GlideDuration.ToString("ss','fff");
            TimeSpan setupTime = gameState.FlightDuration - gameState.GlideDuration;

            SetupTime.Text = setupTime.ToString("ss','fff");

            CurrentTime.Text = TimeTrial.CurrentTime.ToString("ss','fff");
            TimeSpan?delta = TimeTrial.Delta;

            if (delta == null)
            {
                Delta.Text = "";
            }
            else
            {
                string sign = delta > TimeSpan.Zero ? "+" : "-";
                Delta.Text = sign + delta?.ToString("ss','fff");
            }
            BestTime.Text = TimeTrial.BestTime?.ToString("ss','fff");

            FrameCountdown -= 1;
            if (FrameCountdown <= 0)
            {
                FrameCountdown = RefreshPeriod;

                // values with low refresh rate for readability
                MaxAltitude.Text = gameState.MaxAltitude.ToString("F2");
                MaxHorSpeed.Text = gameState.MaxHorizontalSpeed.ToString("F2");

                PositionX.Text = gameState.Position.X.ToString("F2");
                PositionY.Text = gameState.Position.Z.ToString("F2");
                Altitude.Text  = gameState.Position.Y.ToString("F2");

                HorizontalSpeed.Text = gameState.HorizontalSpeed.ToString("F2");
                VerticalSpeed.Text   = gameState.Velocity.Y.ToString("F2");
            }

            VolleyballHits.Text = gameState.VolleyballHits.ToString();
            if (gameState.VolleyballHits > VolleyballHitsBest)
            {
                VolleyballHitsBest = gameState.VolleyballHits;
            }
            VolleyballBest.Text = VolleyballHitsBest.ToString();
        }
Пример #18
0
 /// <summary>
 /// Given a preset name, looks up its definition in the presetDictionary.
 /// </summary>
 /// <param name="presetName">The name of the preset to retrieve.</param>
 /// <param name="timeCodeTimeSpan">Timecode for thumbnail.</param>
 /// <returns>Returns the preset of the preset name.</returns>
 public string GetPresetForPresetName(string presetName, TimeSpan?timeCodeTimeSpan)
 {
     _ = presetName ?? throw new System.ArgumentException($@"{nameof(presetName)} is invalid", nameof(presetName));
     if (presetDictionary.TryGetValue(presetName, out string presetValue))
     {
         var replaceWith = timeCodeTimeSpan?.ToString() ?? "{Best}";
         presetValue = presetValue.Replace(ThumbnailStartToken, replaceWith, System.StringComparison.InvariantCulture);
         return(presetValue);
     }
     return(presetName);
 }
        /// <summary>
        /// Sets the refresh token lifetime associated with the authentication ticket.
        /// </summary>
        /// <param name="ticket">The authentication ticket.</param>
        /// <param name="lifetime">The refresh token lifetime to store.</param>
        /// <returns>The authentication ticket.</returns>
        public static AuthenticationTicket SetRefreshTokenLifetime([NotNull] this AuthenticationTicket ticket, TimeSpan?lifetime)
        {
            if (ticket == null)
            {
                throw new ArgumentNullException(nameof(ticket));
            }

            var value = lifetime?.ToString("c", CultureInfo.InvariantCulture);

            return(ticket.SetProperty(OpenIdConnectConstants.Properties.RefreshTokenLifetime, value));
        }
        public string ReqHistoryTickDays(string symbol, int days, int?maxDatapoints = null, TimeSpan?beginFilterTime = null, TimeSpan?endFilterTime = null,
                                         DataDirection?dataDirection = null, string requestId = null, int?datapointsPerSend = null)
        {
            // HTD,[Symbol],[Days],[MaxDatapoints],[BeginFilterTime],[EndFilterTime],[DataDirection],[RequestID],[DatapointsPerSend]<CR><LF>
            var beginFilterTimeFormat = beginFilterTime?.ToString(HistoricalDataTimeFormat) ?? string.Empty;
            var endFilterTimeFormat   = endFilterTime?.ToString(HistoricalDataTimeFormat) ?? string.Empty;
            var dataDirectionFormat   = dataDirection.HasValue ? ((int)dataDirection).ToString() : null;
            var request = $"HTD,{symbol.ToUpper()},{days},{maxDatapoints},{beginFilterTimeFormat},{endFilterTimeFormat},{dataDirectionFormat},{requestId},{datapointsPerSend}{IQFeedDefault.ProtocolTerminatingCharacters}";

            return(request);
        }
        public string ReqHistoryTickTimeframe(string symbol, DateTime?beginDate, DateTime?endDate,
                                              int?maxDatapoints = null, TimeSpan?beginFilterTime = null, TimeSpan?endFilterTime = null,
                                              int?dataDirection = null, string requestId         = null, int?datapointsPerSend  = null)
        {
            // HTT,[Symbol],[BeginDate BeginTime],[EndDate EndTime],[MaxDatapoints],[BeginFilterTime],[EndFilterTime],[DataDirection],[RequestID],[DatapointsPerSend]<CR><LF>
            var beginDateFormat       = beginDate?.ToString(HistoricalDataDatetimeFormat) ?? string.Empty;
            var endDateFormat         = endDate?.ToString(HistoricalDataDatetimeFormat) ?? string.Empty;
            var beginFilterTimeFormat = beginFilterTime?.ToString(HistoricalDataTimeFormat) ?? string.Empty;
            var endFilterTimeFormat   = endFilterTime?.ToString(HistoricalDataTimeFormat) ?? string.Empty;
            var request = $"HTT,{symbol.ToUpper()},{beginDateFormat},{endDateFormat},{maxDatapoints},{beginFilterTimeFormat},{endFilterTimeFormat},{dataDirection},{requestId},{datapointsPerSend}{IQFeedDefault.ProtocolTerminatingCharacters}";

            return(request);
        }
        public string ReqHistoryIntervalDays(string symbol, int interval, int days, int?maxDatapoints = null, TimeSpan?beginFilterTime = null, TimeSpan?endFilterTime = null,
                                             DataDirection?dataDirection = null, string requestId = null, int?datapointsPerSend = null, HistoricalIntervalType?intervalType = null, LabelAtBeginning?labelAtBeginning = null)
        {
            // HID,[Symbol],[Interval],[Days],[MaxDatapoints],[BeginFilterTime],[EndFilterTime],[DataDirection],[RequestID],[DatapointsPerSend],[IntervalType],[LabelAtBeginning]<CR><LF>
            var beginFilterTimeFormat  = beginFilterTime?.ToString(HistoricalDataTimeFormat) ?? string.Empty;
            var endFilterTimeFormat    = endFilterTime?.ToString(HistoricalDataTimeFormat) ?? string.Empty;
            var dataDirectionFormat    = dataDirection.HasValue ? ((int)dataDirection).ToString() : null;
            var intervalTypeFormat     = intervalType?.ToString().ToLower();
            var labelAtBeginningFormat = labelAtBeginning.HasValue ? ((int)labelAtBeginning).ToString() : null;
            var request = $"HID,{symbol.ToUpper()},{interval},{days},{maxDatapoints},{beginFilterTimeFormat},{endFilterTimeFormat},{dataDirectionFormat},{requestId},{datapointsPerSend},{intervalTypeFormat},{labelAtBeginningFormat}{IQFeedDefault.ProtocolTerminatingCharacters}";

            return(request);
        }
Пример #23
0
 public Boolean runTest()
   {
   Console.WriteLine( s_strTFPath +" "+ s_strTFName +" ,for "+ s_strComponentBeingTested +"  ,Source ver "+ s_strDtTmVer );
   String strBaseLoc;
   StringBuilder sblMsg = new StringBuilder( 99 );
   m_verbose = false;
   try
     {
     m_strLoc = "Loc_normalTests";
     int D = 3;      
     int h = 4;      
     int m = 5;      
     int s = 42;     
     TimeSpan test = new TimeSpan();
     String   teststr =  "" ;
     test = TimeSpan.MinValue;
     TestValue( test.ToString(  ), test, "r" );
     for ( D = 0; D < 100; D += 10 ) {
     for ( h = 0; h < 24; h+=5 ) {
     for ( m = 0; m < 60; m += 5 ) {
     for ( s = 0; s < 60; s += 15 ) {
     teststr =  D + "." + h +":"+m+":"+s ;
     test = new TimeSpan( D, h, m, s );
     TestValue( teststr, test, "." );
     } 
     }
     }
     }
     m_strLoc = "Loc_exepTests";
     TestException( null, "System.ArgumentNullException", "A" );
     TestException( "00.5555.12.09", "System.OverflowException", "F" );
     TestException( "", "System.FormatException", "F" );
     Console.Write(Environment.NewLine);
     Console.WriteLine( "Total Tests Ran: " + iCountTestcases + " Failed Tests: " + iCountErrors );
     }
   catch( Exception exc_general )
     {
     ++iCountErrors;
     Console.WriteLine( "Error Err_8888yyy ("+ s_strTFAbbrev +")!  Unexpected exception thrown sometime after m_strLoc=="+ m_strLoc +" ,exc_general=="+ exc_general );
     }
   if ( iCountErrors == 0 )
     {
     Console.WriteLine( "paSs.   "+ s_strTFPath +" "+ s_strTFName +"  ,iCountTestcases=="+ iCountTestcases );
     return true;
     }
   else
     {
     Console.WriteLine( "FAiL!   "+ s_strTFPath +" "+ s_strTFName +"  ,iCountErrors=="+ iCountErrors +" ,BugNums?: "+ s_strActiveBugNums );
     return false;
     }
   }
Пример #24
0
    // Update is called once per frame
    void Update()
    {
        if (PlayerData.Time != null & PlayerData.Time.Length > 0)
        {
            DateTime time = new DateTime();
            time = DateTime.Parse(PlayerPrefs.GetString("Time"));

            TimeSpan diff = new TimeSpan();

            diff = DateTime.Now - time;

            text.text = diff.ToString();
        }
    }
Пример #25
0
    void Update()
    {
        TimeSpan timeOne = new TimeSpan();
        TimeSpan timeTwo = new TimeSpan();
        Stopwatch timer = Stopwatch.StartNew();

        FunctionThatDoesStuff();
        timeOne = timer.Elapsed;
        AnotherFunction();
        timeTwo = timer.Elapsed;

        timer.Stop();
        UnityEngine.Debug.Log("Time One: " + timeOne.ToString() + "    Time Two: " + (timeTwo - timeOne).ToString());
    }
Пример #26
0
	protected string GetTime(TimeSpan time)
	{
		if (time == TimeSpan.MinValue || time == TimeSpan.MaxValue)
			return "";

		string s = time.ToString();

		if (s.Length > 12)
			s = s.Substring(0, 12);

		if (time.TotalSeconds <= 1)
			s = string.Format("<font color=gray>{0}</font>", s);

		return s;
	}
Пример #27
0
    protected void timer1_Tick(object sender, EventArgs e)
    {
        string sf = ddl.SelectedValue.ToString() ;
        string tt = TextBox1.Text + " " + sf;

        DateTime d1 = TextBox1.Text != string.Empty ? Convert.ToDateTime(tt) : DateTime.MinValue;

        TimeSpan tspan = d1 - DateTime.Now;
        tspan = new TimeSpan(tspan.Days, tspan.Hours, tspan.Minutes,tspan.Seconds);
        //        remaining.Seconds);
        if (tspan.TotalSeconds < 0)
            tspan = TimeSpan.Zero;

        Label1.Text = tspan.ToString();
    }
Пример #28
0
        protected override void Init(IDictionary <string, string> arguments, CancellationToken cancellationToken)
        {
            _directory = CommandHelpers.GetLuceneDirectory(arguments, out var destination);
            _source    = arguments.GetOrThrow <string>(Arguments.Source);
            _verbose   = arguments.GetOrDefault(Arguments.Verbose, false);

            _registration = arguments.GetOrDefault <string>(Arguments.Registration);
            if (_registration == null)
            {
                Logger.LogInformation("Lucene index will be created up to the end of the catalog (alternatively if you provide a registration it will not pass that)");
            }

            _catalogBaseAddress = arguments.GetOrDefault <string>(Arguments.CatalogBaseAddress);
            if (_catalogBaseAddress == null)
            {
                Logger.LogInformation("No catalogBaseAddress was specified so the Lucene index will NOT contain the storage paths");
            }

            _storageBaseAddress = arguments.GetOrDefault <string>(Arguments.StorageBaseAddress);

            var commitTimeoutInSeconds = arguments.GetOrDefault <int?>(Arguments.CommitTimeoutInSeconds);

            if (commitTimeoutInSeconds.HasValue)
            {
                _commitTimeout = TimeSpan.FromSeconds(commitTimeoutInSeconds.Value);
            }
            else
            {
                _commitTimeout = null;
            }

            Logger.LogInformation("CONFIG source: \"{ConfigSource}\" registration: \"{Registration}\"" +
                                  " catalogBaseAddress: \"{CatalogBaseAddress}\" storageBaseAddress: \"{StorageBaseAddress}\" commitTimeout: \"{CommmitTimeout}\"",
                                  _source,
                                  _registration ?? "(null)",
                                  _catalogBaseAddress ?? "(null)",
                                  _storageBaseAddress ?? "(null)",
                                  _commitTimeout?.ToString() ?? "(null)");

            _handlerFunc = CommandHelpers.GetHttpMessageHandlerFactory(
                TelemetryService,
                _verbose,
                _catalogBaseAddress,
                _storageBaseAddress);

            _destination = destination;
            TelemetryService.GlobalDimensions[TelemetryConstants.Destination] = _destination;
        }
Пример #29
0
 public void WriteToRow(int index)
 {
     Globals.Breakdowns.Cells[index, 1].Resize[1, 11].Value = new object[] {
         ID,
         Date,
         TimeFrom?.ToString() ?? "",
         TimeTo?.ToString() ?? "",
         EmployeeCode ?? "",
         Project,
         Phase,
         Code,
         Employee,
         TimeID,
         Status
     };
 }
Пример #30
0
        /// <summary>
        /// Returns list of entries.
        /// </summary>
        public Entry[] List(DateTime?dateFrom = null, DateTime?dateTo = null,
                            TimeSpan?timeFrom = null, TimeSpan?timeTo = null)
        {
            var parameters = new[]
            {
                new { name = nameof(dateFrom), value = dateFrom?.ToString("yyyy-MM-dd") },
                new { name = nameof(dateTo), value = dateTo?.ToString("yyyy-MM-dd") },
                new { name = nameof(timeFrom), value = timeFrom?.ToString() },
                new { name = nameof(timeTo), value = timeTo?.ToString() }
            }
            .Where(p => p.value != null)
            .Select(p => $"{p.name}={p.value}")
            .ToArray();
            var query = string.Join("&", parameters);

            return(_client.GetAsync("/api/entries?" + query).ReadResponse <Entry[]>());
        }
        /// <summary>
        /// Gets the list of filter names to be applied to this asset, given filtering parameters.
        /// </summary>
        /// <param name="startTime">The optional start time for filtering.</param>
        /// <param name="endTime">The optional end time for filtering.</param>
        /// <returns>The list of filter names to be applied to this asset.</returns>
        private async Task <List <string> > GetListFiltersAsync(TimeSpan?startTime, TimeSpan?endTime, string uniqueness, string assetName)
        {
            List <string> listFilters = null;

            if (startTime != null || endTime != null)
            {
                string filterName = "filter-time-" + uniqueness;
                PresentationTimeRange presTimeRange = new PresentationTimeRange(
                    startTime?.Ticks,
                    endTime?.Ticks,
                    null,
                    null,
                    TimeSpan.TicksPerSecond);
                listFilters = new List <string>()
                {
                    filterName
                };

                try
                {
                    AssetFilter newAssetFilter = await this.MediaServicesV3SdkWrapper.AssetFiltersCreateOrUpdateAsync(
                        assetName,
                        filterName,
                        new AssetFilter()
                    {
                        PresentationTimeRange = presTimeRange
                    }).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    var msg = "AMS v3 Publish. Error when creating asset filter.";
                    var exceptionToThrow = new GridwichPublicationAssetFilterCreateException(
                        assetName,
                        msg,
                        ex);

                    // Providing additional specific details:
                    exceptionToThrow.Data.Add("startTime", startTime?.ToString());
                    exceptionToThrow.Data.Add("endTime", endTime?.ToString());

                    throw exceptionToThrow;
                }
            }

            return(listFilters);
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     DataView dv = (DataView)DateSelect.Select(DataSourceSelectArguments.Empty);
     DateTime dd = (DateTime)dv.Table.Rows[0][0];
     TextBox1.Text = dd.ToShortDateString();
     TextBox2.Text = ((int)dv.Table.Rows[0][1]).ToString();
     era = (Double)dv.Table.Rows[0][2];
     gt = (Double)dv.Table.Rows[0][3];
     tgt.Text = gt.ToString("n2");
     tera.Text = era.ToString("n2");
     DataView dvd = (DataView)EventDetails.Select(DataSourceSelectArguments.Empty);
     dt = (DateTime)dvd.Table.Rows[0][0];
     st = (TimeSpan)dvd.Table.Rows[0][1];
     et = (TimeSpan)dvd.Table.Rows[0][2];
     rdate.Text = dt.ToShortDateString();
     stime.Text = st.ToString();
     etime.Text = et.ToString();
 }
Пример #33
0
        private static string FormatTimeSpan(TimeSpan?value)
        {
            if (value == null)
            {
                return(null);
            }

            string result = value?.ToString(@"hh\:mm");

            if (value?.Days > 0)
            {
                result = value?.Days + "." + result;
            }
            if (value?.Seconds > 0)
            {
                result = result + ":" + value?.Seconds.ToString("d2");
            }

            return(result);
        }
Пример #34
0
        private void UpdateRunTime()
        {
            try
            {
                TimeSpan?run    = null;
                TimeSpan?start  = TimeSpanExtensions.ParseTimeSpan(txtStart.Text);
                TimeSpan?finish = TimeSpanExtensions.ParseTimeSpan(txtFinish.Text);

                if (start != null && finish != null)
                {
                    run = (new RoundedTimeSpan((TimeSpan)(finish - start), 2, RoundedTimeSpan.ERoundType.Floor)).TimeSpan;
                }

                if (run != null)
                {
                    txtRun.Text = run?.ToString(@"mm\:ss\,ff");
                }
            }
            catch (Exception)
            { }
        }
Пример #35
0
    static void Main()
    {
        TimeSpan ts = new TimeSpan();
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();

        int result = 0;
        for(short i = 3;i<1000;i++)
        {
            if (IsMultiple(3, i) || IsMultiple(5, i))
            {
                result += i;
            }

        }

        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        ts = stopWatch.Elapsed;
        Console.WriteLine(result.ToString());
        Console.WriteLine(ts.ToString());
    }
 protected string ConvertTime(TimeSpan d)
 {
     string s = "", post = "";
     string testing = d.ToString();
     string ss = testing.Substring(0, 2);
     int x = Convert.ToInt32(ss);
     if (x > 12)
     {
         x = x - 12;
         post = "pm";
     }
     else if (x < 12)
     {
         post = "am";
     }
     else if (x == 12)
     {
         post = "pm";
     }
     s = x.ToString() + ":" + testing.Substring(3, 2) + post;
     return s;
 }
Пример #37
0
    static void Main(string[] args)
    {
        DateTime tiempo1 = DateTime.Now;

            int i, n, f1 = 0, f2 = 1, res = 0;
            Console.Write("Introduzca un numero n para marcar el limite de la sucesion: \n");
            n = int.Parse(Console.ReadLine());
            Console.WriteLine("la sucesion resultante es:");
            Console.WriteLine(f1);
            Console.WriteLine(f2);
            for (i = 0; i <= n-3; i++)
            {
                res = f1 + f2;
                Console.WriteLine(res);
                f1 = f2;
                f2 = res;
            }
            DateTime tiempo2 = DateTime.Now;
            TimeSpan total = new TimeSpan(tiempo2.Ticks - tiempo1.Ticks);
            Console.Write("Tiempo en segundos: " + total.ToString());
            Console.ReadLine();
    }
Пример #38
0
    static void Main()
    {
        TimeSpan ts = new TimeSpan();
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();

        if(capicua("22333322"))
            Console.WriteLine("NICE");
        else
            Console.WriteLine("F**K");

        int aux1;
        int bestOne = 0;
        for(int i = 999; i > 0; i--)
        {
            for(int j = 999; j > 0; j--)
            {
                aux1 = j * i;
               /* if(aux1<1000)
                    Console.Write("0");
                if(aux1<100)
                    Console.Write("0");
                if(aux1<10)
                    Console.Write("0");
                Console.Write(aux1.ToString() + " ");        */
                if (capicua(aux1.ToString()) && aux1 > bestOne)
                    bestOne = aux1;
            }
         //   Console.WriteLine();
        }
        Console.WriteLine(bestOne.ToString());
        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        ts = stopWatch.Elapsed;
        Console.WriteLine(ts.ToString());
    }
Пример #39
0
        private static string GenerateGroupedByUpdateTimeRow(char separator, uint hour, Edge edge, TimeSpan?latestDuration)
        {
            var row = new List <string>
            {
                hour.ToString(),
                latestDuration?.ToString() ?? string.Empty,
                edge.Id,
                edge.Fid.ToString(),
                edge.OsmId.ToString(),
                edge.HighwayName ?? string.Empty,
                edge.HighwayType.ToString(),
                edge.IsOneWay.ToString(),
                edge.MaxSpeed?.ToString() ?? string.Empty,
                edge.Length.ToString(),
                edge.XFromPoint.ToString(),
                edge.YFromPoint.ToString(),
                edge.XToPoint.ToString(),
                edge.YToPoint.ToString(),
                edge.XMidPoint.ToString(),
                edge.YMidPoint.ToString()
            };

            return(string.Join(separator.ToString(), row));
        }
Пример #40
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            string Value = null;

            output.TagName = "input";
            output.TagMode = TagMode.StartTagOnly;
            output.Attributes.Add("type", "text");
            output.Attributes.Add("name", Field.Name);

            if (Range.HasValue && Range.Value && string.IsNullOrEmpty(RangeSplit))
            {
                RangeSplit = "~";
            }

            if (DefaultValue != null)
            {
                Value = DefaultValue;
            }
            else
            {
                if (Field.ModelExplorer.ModelType == typeof(string))
                {
                    Value = Field.Model?.ToString() ?? Value;
                }
                else if (Range.HasValue && Range.Value && Field.ModelExplorer.ModelType == typeof(DateRange))
                {
                    var dateRange = Field.Model as DateRange;
                    if (string.IsNullOrEmpty(Format))
                    {
                        Value = dateRange?.ToString(DateTimeFormatDic[Type], RangeSplit) ?? Value;
                    }
                    else
                    {
                        Value = dateRange?.ToString(Format, RangeSplit) ?? Value;
                    }
                }
                else if (Field.ModelExplorer.ModelType == typeof(TimeSpan) || Field.ModelExplorer.ModelType == typeof(TimeSpan?))
                {
                    TimeSpan?df = Field.Model as TimeSpan?;
                    if (df == TimeSpan.MinValue)
                    {
                        df = null;
                    }
                    Value = df?.ToString();
                }
                else
                {
                    DateTime?df = Field.Model as DateTime?;
                    if (df == DateTime.MinValue)
                    {
                        df = null;
                    }
                    if (string.IsNullOrEmpty(Format))
                    {
                        Value = df?.ToString(DateTimeFormatDic[Type]) ?? Value;
                    }
                    else
                    {
                        Value = df?.ToString(Format) ?? Value;
                    }
                }
            }
            output.Attributes.Add("value", Value);
            output.Attributes.Add("class", "layui-input");
            if (GlobalServices.GetRequiredService <Configs>().UiOptions.DateTime.DefaultReadonly)
            {
                output.Attributes.Add("readonly", "readonly");
            }

            if (!string.IsNullOrEmpty(Min))
            {
                if (int.TryParse(Min, out int minRes))
                {
                    Min = minRes.ToString();
                }
                else
                {
                    Min = $"'{Min}'";
                }
            }
            if (!string.IsNullOrEmpty(Max))
            {
                if (int.TryParse(Max, out int maxRes))
                {
                    Max = maxRes.ToString();
                }
                else
                {
                    Max = $"'{Max}'";
                }
            }

            if (Lang == null)
            {
                if (Enum.TryParse <DateTimeLangEnum>(Program._localizer["LayuiDateLan"], true, out var testlang))
                {
                    Lang = testlang;
                }
            }

            var content = $@"
<script>
layui.use(['laydate'],function(){{
  var laydate = layui.laydate;
  var dateIns = laydate.render({{
    elem: '#{Id}',
    type: '{Type.ToString().ToLower()}'
    {(string.IsNullOrEmpty(RangeSplit) ? string.Empty : $",range:'{RangeSplit}'")}
    {(string.IsNullOrEmpty(Format) ? string.Empty : $",format: '{Format}'")}
    {(string.IsNullOrEmpty(Min) ? string.Empty : $",min: {Min}")}
    {(string.IsNullOrEmpty(Max) ? string.Empty : $",max: {Max}")}
    {(!ZIndex.HasValue ? string.Empty : $",zIndex: {ZIndex.Value}")}
    {(!ShowBottom.HasValue ? string.Empty : $",showBottom: {ShowBottom.Value.ToString().ToLower()}")}
    {(!ConfirmOnly.HasValue ? string.Empty : ShowBottom.HasValue && ShowBottom.Value && ConfirmOnly.Value || !ShowBottom.HasValue && ConfirmOnly.Value ? $",btns: ['confirm']" : string.Empty)}
    {(!Calendar.HasValue ? string.Empty : $",calendar: {Calendar.Value.ToString().ToLower()}")}
    {(!Lang.HasValue ? string.Empty : $",lang: '{Lang.Value.ToString().ToLower()}'")}
    {(Mark == null || Mark.Count == 0 ? string.Empty : $",mark: {JsonConvert.SerializeObject(Mark)}")}
    {(string.IsNullOrEmpty(ReadyFunc) ? string.Empty : $",ready: function(value){{{ReadyFunc}(value,dateIns)}}")}
    {(string.IsNullOrEmpty(ChangeFunc) ? string.Empty : $",change: function(value,date,endDate){{{ChangeFunc}(value,date,endDate,dateIns)}}")}
    {(string.IsNullOrEmpty(DoneFunc) ? string.Empty : $",done: function(value,date,endDate){{{DoneFunc}(value,date,endDate,dateIns)}}")}
  }});
}})
</script>
";

            output.PostElement.AppendHtml(content);
            base.Process(context, output);
        }
    public void RefreshUI(ChallengeGridID index)
    {
        if (MogoWorld.thePlayer.level < SystemRequirementData.dataMap.Get((int)index).requestLevel)
        {
            NewChallengeUIViewManager.Instance.SetGridEnable(SystemRequirementData.dataMap.Get((int)index).pos, false);
            NewChallengeUIViewManager.Instance.SetGridStatus(SystemRequirementData.dataMap.Get((int)index).pos, string.Format("{0}级解锁", SystemRequirementData.dataMap.Get((int)index).requestLevel));
            //ChallengeUIViewManager.Instance.SetChallengeTextColor((int)ChallengeGridID.ClimbTower, SystemUIColorManager.RED);
        }
        else
        {
            NewChallengeUIViewManager.Instance.SetGridEnable(SystemRequirementData.dataMap.Get((int)index).pos, true);

            switch (index)
            {
                case ChallengeGridID.ClimbTower:
                    {
                        NewChallengeUIViewManager.Instance.SetGridStatus((int)ChallengeGridID.ClimbTower, LanguageData.GetContent(26345, ClimbTowerUILogicManager.Instance.Data.FailCount));
                        ChallengeUIViewManager.Instance.SetChallengeTextColor((int)ChallengeGridID.ClimbTower, SystemUIColorManager.BROWN);
                    }
                    break;
                case ChallengeGridID.DoorOfBury:
                    {

                    }
                    break;
                case ChallengeGridID.Sanctuary:
                    {

                        if (nextTimeSec == 0) // 可挑战:结束倒计时中
                        {

                            ChallengeUIViewManager.Instance.ShowEnterTipFX((int)ChallengeGridID.Sanctuary, true);
                            ChallengeUIViewManager.Instance.AddTimer(2, endTime,
                                (curTime) =>
                                {
                                    var span = new TimeSpan(curTime * TimeSpan.TicksPerSecond);
                                    ChallengeUIViewManager.Instance.SetChallengeTextColor((int)ChallengeGridID.Sanctuary, SystemUIColorManager.BROWN);
                                    ChallengeUIViewManager.Instance.SetChallengeText((int)ChallengeGridID.Sanctuary,
                                        Convert.ToDateTime(span.ToString()).
                                        ToString(string.Format("mm{0}ss{1}{2}",
                                        LanguageData.GetContent(7102),
                                        LanguageData.GetContent(7103),
                                        LanguageData.GetContent(7135))));
                                },
                                () =>
                                {
                                    ChallengeUIViewManager.Instance.SetChallengeText((int)ChallengeGridID.Sanctuary, LanguageData.GetContent(7136)); // 活动已结束
                                    ChallengeUIViewManager.Instance.SetChallengeTextColor((int)ChallengeGridID.Sanctuary, SystemUIColorManager.BROWN);
                                    ChallengeUIViewManager.Instance.ShowEnterTipFX((int)ChallengeGridID.Sanctuary, false);

                                    EventDispatcher.TriggerEvent(Events.SanctuaryEvent.QuerySanctuaryInfo);
                                });
                        }
                        else // CD倒计时
                        {
                            var span = new TimeSpan(nextTimeSec * TimeSpan.TicksPerSecond);
                            var midTime = MogoTime.Instance.GetCurrentDateTime() + span;
                            ChallengeUIViewManager.Instance.SetChallengeTextColor((int)ChallengeGridID.Sanctuary, SystemUIColorManager.RED);
                            ChallengeUIViewManager.Instance.SetChallengeText((int)ChallengeGridID.Sanctuary, midTime.
                                ToString(string.Format("{0}HH{1}mm{2}{3}",
                                LanguageData.GetContent(7130),
                                LanguageData.GetContent(7101),
                                LanguageData.GetContent(7102),
                                LanguageData.GetContent(7131))));
                            ChallengeUIViewManager.Instance.ShowEnterTipFX((int)ChallengeGridID.Sanctuary, false);

                        }
                    }
                    break;
                case ChallengeGridID.DragonMatch:
                    {

                    }
                    break;
                case ChallengeGridID.OgreMustDie:
                    {

                    }
                    break;
                default:
                    break;
            }
        }
    }
Пример #42
0
        /// <summary>
        /// Obtiene el historial clínico del paciente
        /// </summary>
        /// <param name="piIdHistorialClinico"></param>
        /// <param name="piIdConsulta"></param>
        /// <param name="piIdPaciente"></param>
        /// <param name="piIdColaborador"></param>
        /// <param name="piIdFolio"></param>
        /// <param name="psIdTipoDoctor"></param>
        /// <returns></returns>
        public IMDResponse <List <EntHistorialClinico> > BGetHistorialMedico(int?piIdHistorialClinico = null, int?piIdConsulta = null, int?piIdPaciente = null, int?piIdColaborador = null, int?piIdFolio = null, string psIdTipoDoctor = null)
        {
            IMDResponse <List <EntHistorialClinico> > response = new IMDResponse <List <EntHistorialClinico> >();

            string metodo = nameof(this.BGetHistorialMedico);

            logger.Info(IMDSerialize.Serialize(67823458524619, $"Inicia {metodo}(int? piIdHistorialClinico = null, int? piIdConsulta = null, int? piIdPaciente = null, int? piIdColaborador = null, int? piIdFolio = null)", piIdHistorialClinico, piIdConsulta, piIdPaciente, piIdColaborador, piIdFolio));

            try
            {
                IMDResponse <DataTable> resGetHistorialClinico = datConsulta.DGetHistorialMedico(piIdHistorialClinico, piIdConsulta, piIdPaciente, piIdColaborador, piIdFolio, psIdTipoDoctor);
                if (resGetHistorialClinico.Code != 0)
                {
                    return(resGetHistorialClinico.GetResponse <List <EntHistorialClinico> >());
                }

                List <EntHistorialClinico> lstHistorial = new List <EntHistorialClinico>();

                foreach (DataRow drHistorial in resGetHistorialClinico.Result.Rows)
                {
                    IMDDataRow dr = new IMDDataRow(drHistorial);

                    EntHistorialClinico entHistorialClinico = new EntHistorialClinico
                    {
                        dtFechaCreacion       = dr.ConvertTo <DateTime?>("dtFechaCreacion"),
                        dtFechaConsultaFin    = dr.ConvertTo <DateTime?>("dtFechaConsultaFin"),
                        dtFechaConsultaInicio = dr.ConvertTo <DateTime?>("dtFechaConsultaInicio"),
                        fAltura             = dr.ConvertTo <double>("fAltura"),
                        fPeso               = dr.ConvertTo <double>("fPeso"),
                        iIdConsulta         = dr.ConvertTo <int>("iIdConsulta"),
                        iIdHistorialClinico = dr.ConvertTo <int>("iIdHistorialClinico"),
                        sAlergias           = dr.ConvertTo <string>("sAlergias"),
                        sComentarios        = dr.ConvertTo <string>("sComentarios"),
                        sDiagnostico        = dr.ConvertTo <string>("sDiagnostico"),
                        sFechaCreacion      = string.Empty,
                        sSintomas           = dr.ConvertTo <string>("sSintomas"),
                        sTratamiento        = dr.ConvertTo <string>("sTratamiento"),
                    };

                    entHistorialClinico.sFechaCreacion       = entHistorialClinico.dtFechaCreacion?.ToString("ddd dd/MM/yyyy hh:mm tt");
                    entHistorialClinico.sFechaConsultaInicio = entHistorialClinico.dtFechaConsultaInicio?.ToString("ddd dd/MM/yyyy hh:mm tt");
                    entHistorialClinico.sFechaConsultaFin    = entHistorialClinico.dtFechaConsultaFin?.ToString("ddd dd/MM/yyyy hh:mm tt");

                    //Calcular la duración de la consulta
                    TimeSpan?dff = entHistorialClinico.dtFechaConsultaFin - entHistorialClinico.dtFechaConsultaInicio;

                    entHistorialClinico.sDuracionConsulta = dff?.ToString(@"hh\:mm\:ss");

                    lstHistorial.Add(entHistorialClinico);
                }

                response.Code    = 0;
                response.Message = "Se ha consultado el historial clínico.";
                response.Result  = lstHistorial;
            }
            catch (Exception ex)
            {
                response.Code    = 67823458525396;
                response.Message = "Ocurrió un error inesperado al consultar el historial clínico.";

                logger.Error(IMDSerialize.Serialize(67823458525396, $"Error en {metodo}(int? piIdHistorialClinico = null, int? piIdConsulta = null, int? piIdPaciente = null, int? piIdColaborador = null, int? piIdFolio = null): {ex.Message}", piIdHistorialClinico, piIdConsulta, piIdPaciente, piIdColaborador, piIdFolio, ex, response));
            }
            return(response);
        }
Пример #43
0
 private void WriteTime(TimeSpan value, byte scale, int length, TdsParserStateObject stateObj)
 {
     if (0 > value.Ticks || value.Ticks >= TimeSpan.TicksPerDay)
     {
         throw SQL.TimeOverflow(value.ToString());
     }
     long time = value.Ticks / TdsEnums.TICKS_FROM_SCALE[scale];
     WritePartialLong(time, length, stateObj);
 }
Пример #44
0
 public static string ToString(TimeSpan value)
 {
     return value.ToString();
 }
Пример #45
0
        public string ReqBarWatch(string symbol, int interval, DateTime?beginDate = null, int?maxDaysOfDatapoints = null, int?maxDatapoints = null,
                                  TimeSpan?beginFilterTime = null, TimeSpan?endFilterTime = null, string requestId = null, DerivativeIntervalType?intervalType = null, int?updateInterval = null)
        {
            var request = $"BW,{symbol.ToUpper()},{interval},{beginDate?.ToString(DerivativeDatetimeFormat)},{maxDaysOfDatapoints},{maxDatapoints},{beginFilterTime?.ToString(DerivativeTimeFormat)},{endFilterTime?.ToString(DerivativeTimeFormat)},{requestId},{intervalType?.ToString().ToLower()},{updateInterval},{IQFeedDefault.ProtocolTerminatingCharacters}";

            return(request);
        }
Пример #46
0
    public static void TestToString()
    {
        var timeSpan1 = new TimeSpan(1, 2, 3);
        var timeSpan2 = new TimeSpan(1, 2, 3);
        var timeSpan3 = new TimeSpan(1, 2, 4);

        var timeSpan4 = new TimeSpan(1, 2, 3, 4);
        var timeSpan5 = new TimeSpan(1, 2, 3, 4);
        var timeSpan6 = new TimeSpan(1, 2, 3, 5);

        var timeSpan7 = new TimeSpan(1, 2, 3, 4, 5);
        var timeSpan8 = new TimeSpan(1, 2, 3, 4, 5);
        var timeSpan9 = new TimeSpan(1, 2, 3, 4, 6);

        Assert.Equal(timeSpan1.ToString(), timeSpan2.ToString());
        Assert.Equal(timeSpan1.ToString("c"), timeSpan2.ToString("c"));
        Assert.Equal(timeSpan1.ToString("c", null), timeSpan2.ToString("c", null));
        Assert.NotEqual(timeSpan1.ToString(), timeSpan3.ToString());
        Assert.NotEqual(timeSpan1.ToString(), timeSpan4.ToString());
        Assert.NotEqual(timeSpan1.ToString(), timeSpan7.ToString());

        Assert.Equal(timeSpan4.ToString(), timeSpan5.ToString());
        Assert.Equal(timeSpan4.ToString("c"), timeSpan5.ToString("c"));
        Assert.Equal(timeSpan4.ToString("c", null), timeSpan5.ToString("c", null));
        Assert.NotEqual(timeSpan4.ToString(), timeSpan6.ToString());
        Assert.NotEqual(timeSpan4.ToString(), timeSpan7.ToString());

        Assert.Equal(timeSpan7.ToString(), timeSpan8.ToString());
        Assert.Equal(timeSpan7.ToString("c"), timeSpan8.ToString("c"));
        Assert.Equal(timeSpan7.ToString("c", null), timeSpan8.ToString("c", null));
        Assert.NotEqual(timeSpan7.ToString(), timeSpan9.ToString());
    }
 private static string TimeSpanToString(TimeSpan?time)
 {
     return(time?.ToString(@"mm\:ss\.ffff", CultureInfo.InvariantCulture) ?? "??:??.????");
 }
Пример #48
0
 static string formatTime(TimeSpan?time)
 {
     return(time?.ToString(@"mm\:ss\.ff"));
 }
Пример #49
0
        public static string TimeSpanFmt(TimeSpan?span)
        {
            string timeSpanFmt = @"\:mm\:ss";

            return(span?.HoursCount() + span?.ToString(timeSpanFmt));
        }
Пример #50
0
 public RequestBuilder Body(string name, TimeSpan?value)
 {
     return(BodyInternal(name, value?.ToString(TimeFormat)));
 }
Пример #51
0
 private void UpdateTimer()
 {
     timer += Time.deltaTime;
     TimeSpan span = new TimeSpan(0, 0, (int)timer);
     StringBuilder sb = new StringBuilder();
     sb.Append(span.ToString()[3]);
     sb.Append(span.ToString()[4]);
     sb.Append(span.ToString()[5]);
     sb.Append(span.ToString()[6]);
     sb.Append(span.ToString()[7]);
     timerText.text = sb.ToString();
 }
Пример #52
0
 private static string GetBestTimeSpanString(TimeSpan span)
 {
     if (!_foundTimeSpan2)
     {
         try
         {
             var assembly = Assembly.LoadFrom("TimeSpan2.dll");
             if (assembly != null)
             {
                 _timeSpan2Type = assembly.GetType("System.TimeSpan2", false, false);
                 if (_timeSpan2Type != null)
                     _foundTimeSpan2 = true;
             }
         }
         catch { }
     }
     if (_foundTimeSpan2 && (_timeSpan2Type != null))
     {
         try
         {
             var obj2 = Activator.CreateInstance(_timeSpan2Type, new object[] { span });
             if (obj2 != null)
             {
                 var method = _timeSpan2Type.GetMethod("ToString", new Type[] { typeof(string) });
                 if (method != null)
                 {
                     var obj3 = method.Invoke(obj2, new object[] { "f" });
                     if (obj3 != null)
                         return obj3.ToString();
                 }
             }
         }
         catch { }
     }
     return span.ToString();
 }
 public static string Convert(TimeSpan?timeSpan)
 {
     return(timeSpan?.ToString(@"mm\:ss") ?? string.Empty);
 }
Пример #54
0
 public static void TestToString_Invalid()
 {
     var timeSpan = new TimeSpan();
     Assert.Throws<FormatException>(() => timeSpan.ToString("y")); // Invalid format
     Assert.Throws<FormatException>(() => timeSpan.ToString("cc")); // Invalid format
 }
Пример #55
0
 public static string TimeToString(TimeSpan t)
 {
     var s = t.ToString();
     if (s.IndexOf(".") != -1)
         return s.Substring(0, s.IndexOf("."));
     else
         return s;
 }   
Пример #56
0
 /// <summary>
 /// UpTime ToString
 /// </summary>
 /// <param name="upTime"></param>
 /// <returns></returns>
 public static string UpTimeToString(TimeSpan?upTime)
 => upTime == null
         ? ""
         : upTime?.ToString(@"d\.hh\:mm");
Пример #57
0
    private void GetTotalTime()
    {
        // Session["starttime"] = DateTime.Now;
        if (Session["starttime"] != null)
        {
            pnltimer.Visible = true;
            DateTime startTime, endTime;
            string output = "";
            TimeSpan span;
            //if (Session["starttime"] == null)
            //    Session["starttime"] = DateTime.Now;

            startTime = DateTime.Parse(Session["starttime"].ToString());
            startTime = (DateTime)Session["starttime"];
            endTime = DateTime.Now;

            span = new TimeSpan(endTime.Ticks - startTime.Ticks);
            string[] newtime = span.ToString().Split(new char[] { '.' });
            lblTime.Text = newtime[0];// span.ToString().Split(new char[]{('.')};
        }
        //span = new TimeSpan(endTime.Ticks - startTime.Ticks);
        //lblTime.Text = span.TotalSeconds.ToString();
        //Response.Write("<hr>Time Using StringBuilder: " + span.TotalSeconds.ToString() + "<hr>");
    }
Пример #58
0
 protected String ConvertTimeSpanToString(TimeSpan time)
 {
     return time.ToString().Split('.')[0];
 }
        public async Task Message_TimeOutReachedResponse()
        {
            TimeSpan?  timeout    = TimeSpan.FromTicks(1);
            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix).ConfigureAwait(false);

            using (ServiceClient sender = ServiceClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString))
                using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, Client.TransportType.Amqp))
                {
                    await sender.SendAsync(testDevice.Id, new Message(Encoding.ASCII.GetBytes($"TestTimeout {timeout?.ToString()}")), timeout).ConfigureAwait(false);
                }
        }
 private static string FormatTimeSpanString(TimeSpan? ts)
 {
     if (ts == null)
         return "Unknown";
     string timeSpanString = ts.ToString();
     int idx = timeSpanString.LastIndexOf(".");
     if (idx <= 0) return timeSpanString;
     return timeSpanString.Substring(0, idx);
 }