Exemple #1
0
 /// <summary>
 /// Converts timespan to something like: "9d", "3d 22h", "18h", "3h 22m", "22m"
 /// </summary>
 /// <param name="timespan"></param>
 /// <returns></returns>
 /// <remarks>
 /// Shows just minutes for t less than 1h, only hours between 6-24h, only days if 6d or more
 /// </remarks>
 public static string FormatTimeSpanForDisplay(TimeSpan timespan)
 {
     double totalHours = timespan.TotalHours;
     if (totalHours < 0)
     {
         return "error";
     }
     else if (totalHours < 1)
     {
         return timespan.ToString("m'm'");
     }
     else if (totalHours < 6)
     {
         return timespan.ToString("h'h 'm'm'");
     }
     else if (totalHours < 24)
     {
         return timespan.ToString("h'h'");
     }
     else if (totalHours < 144)
     {
         return timespan.ToString("d'd 'h'h'");
     }
     else
     {
         return timespan.ToString("d'd'");
     }
 }
 public string FormatTimeSpan(TimeSpan timeSpan)
 {
     if (timeSpan.Hours != 0 || timeSpan.Days != 0)
         return timeSpan.ToString("g", CultureInfo);
     else
         return timeSpan.ToString(@"mm\:ss");
 }
Exemple #3
0
 /// <summary>
 /// Converts timespan to something like: "9d", "3d 22h", "18h", "3h 22m", "22m"
 /// </summary>
 /// <param name="timespan"></param>
 /// <returns></returns>
 /// <remarks>
 /// Shows just minutes for t less than 1h, only hours between 6-24h, only days if 6d or more
 /// </remarks>
 public static string FormatTimeSpanForDisplay(TimeSpan timespan)
 {
     double totalMinutes = timespan.TotalMinutes;
     if (totalMinutes < 0)
     {
         return "error";
     }
     else if (totalMinutes < 10)
     {
         return timespan.ToString("m'm 's's'");
     }
     else if (totalMinutes < 1 * 60)
     {
         return timespan.ToString("m'm'");
     }
     else if (totalMinutes < 6 * 60)
     {
         return timespan.ToString("h'h 'm'm'");
     }
     else if (totalMinutes < 24 * 60)
     {
         return timespan.ToString("h'h'");
     }
     else if (totalMinutes < 144 * 60)
     {
         return timespan.ToString("d'd 'h'h'");
     }
     else
     {
         return timespan.ToString("d'd'");
     }
 }
Exemple #4
0
 /// <summary>
 /// Formats a timespan for logger output.
 /// </summary>
 /// <owner>JomoF</owner>
 /// <param name="t"></param>
 /// <returns>String representation of time-span.</returns>
 internal static string FormatTimeSpan(TimeSpan t) 
 {
     string rawTime = t.ToString(); // Timespan is a value type and can't be null.
     int rawTimeLength = rawTime.Length;
     int prettyLength = System.Math.Min(11, rawTimeLength);
     return t.ToString().Substring(0, prettyLength);
 }
Exemple #5
0
        public static string PrettyDeltaTime(TimeSpan span, string rough = "")
        {
            int day = Convert.ToInt32(span.ToString("%d"));
              int hour = Convert.ToInt32(span.ToString("%h"));
              int minute = Convert.ToInt32(span.ToString("%m"));

              if (span.CompareTo(TimeSpan.Zero) == -1) {
            Log($"Time to sync the clock?{span}", ConsoleColor.Red);
            return "a few seconds";
              }

              if (day > 1) {
            if (hour == 0) return $"{day} days";
            return $"{day} days {hour}h";
              }

              if (day == 1) {
            if (hour == 0) return "1 day";
            return $"1 day {hour}h";
              }

              if (hour == 0) return $"{rough}{minute}m";
              if (minute == 0) return $"{rough}{hour}h";

              return $"{rough}{hour}h {minute}m";
        }
    protected Boolean validarCita(String id)
    {
        DataTable cita  = new DataTable();
        LCita     lCita = new LCita();

        cita = lCita.obtenerCita(Convert.ToInt32(id));
        DateTime fecha_actual = new DateTime();

        fecha_actual = DateTime.Now;
        String   hora_cita, aux_fecha;
        DateTime dia_cita = new DateTime();

        dia_cita  = DateTime.Parse(cita.Rows[0]["dia"].ToString());
        aux_fecha = Convert.ToString(dia_cita.ToShortDateString());
        hora_cita = cita.Rows[0]["hora_inicio"].ToString();
        aux_fecha = aux_fecha + " " + hora_cita;
        System.TimeSpan diferencia_dias = DateTime.Parse(aux_fecha).Subtract(fecha_actual);
        int             dias            = int.Parse(diferencia_dias.ToString("dd"));
        int             horas           = int.Parse(diferencia_dias.ToString("hh"));

        if (dias > 0)
        {
            return(true);
        }
        else if (horas >= 6)
        {
            return(true);
        }
        else
        {
            throw new Exception();
        }
    }
Exemple #7
0
 private string FormatTimeZoneOffset(TimeSpan offset)
 {
     if (offset.TotalSeconds > 0)
         return offset.ToString("'+'hhmm");
     else
         return offset.ToString("'-'hhmm");
 }
        private static string GetDurationFromSeconds(double duration)
        {
            var span = new TimeSpan(0, 0, (int) duration);

              var minutes = span.ToString("mm");
              var hrs = span.ToString("hh");
              return string.Format("{0} hrs {1} mins", hrs, minutes);
        }
        public void CatchingRoundBug()
        {
            // Summed ticks
            const long value = 71731720000; //Total

            // Specific flights
            const long flight1 = 5228130000;
            const long flight2 = 4842030000;
            const long flight3 = 58475460000;
            const long flight4 = 3186100000;
            
            // Values
            Debug.Print(value.TotalHoursWithMinutesAsDecimal());
            Debug.Print(flight1.TotalHoursWithMinutesAsDecimal());
            Debug.Print(flight2.TotalHoursWithMinutesAsDecimal());
            Debug.Print(flight3.TotalHoursWithMinutesAsDecimal());
            Debug.Print(flight4.TotalHoursWithMinutesAsDecimal());

            Debug.Print((flight1 + flight2 + flight3 + flight4).ToString());
            Debug.Print(value.ToString());

            // Analyse the output of a clean timespan
            var timeSpan = new TimeSpan(value);
            Debug.Print(timeSpan.ToString());
            Debug.Print(timeSpan.ToString("g"));
            Debug.Print(timeSpan.TotalHours.ToString(CultureInfo.InvariantCulture));
            Debug.Print(timeSpan.TotalHours.ToString("#00.0", CultureInfo.InvariantCulture) + " Please notice the rounding error that leads to an hour being added to the total");
            Debug.Print(timeSpan.TotalHours.ToString("#00.00", CultureInfo.InvariantCulture) + " Please notice the fixed rounded value");
            Debug.Print(timeSpan.TotalHours.ToString("#0.00", CultureInfo.InvariantCulture) + " Please notice the removed leading zero");
            Debug.Print(timeSpan.TotalMinutes.ToString(CultureInfo.InvariantCulture));
            Debug.Print(timeSpan.TotalMinutes.ToString("#00", CultureInfo.InvariantCulture));

            // Original formula
            var resultFormula = string.Format("{0}:{1}"
                    , timeSpan.TotalHours.ToString("#00.0").Substring(0, timeSpan.TotalHours.ToString("#00.0", CultureInfo.InvariantCulture).IndexOf(".", StringComparison.InvariantCulture))
                    , timeSpan.Minutes.ToString("#00"));
            Debug.Print(resultFormula);

            var resultFixedFormula = string.Format("{0}:{1}"
                , timeSpan.TotalHours.ToString("#0.000", CultureInfo.InvariantCulture).Substring(0, timeSpan.TotalHours.ToString("#0.000", CultureInfo.InvariantCulture).IndexOf(".", StringComparison.InvariantCulture))
                , timeSpan.Minutes.ToString("#00"));
            Debug.Print(resultFixedFormula);
            

            // Validate the resulting corrected formual is functioning
            var result = value.TotalHoursWithMinutesAsDecimal();
            Assert.AreEqual(result, "1:59");
        }
Exemple #10
0
        //データの詳細を決定する
        string DataDetail(
            List <Data> dataList,
            SleepData.HeadDir headDir,
            params SleepData.BreathState[] targetStates)
        {
            int detectTime = 0;

            foreach (SleepData.BreathState breathState in targetStates)
            {
                // 0~10秒
                detectTime += dataList.Where(
                    data =>
                    data.HeadDir1.Equals(headDir) && data.GetBreathState1().Equals(breathState)
                    ).Count() * 10;     //検知データ件数×10秒で検知時間を計算

                // 11~20秒
                detectTime += dataList.Where(
                    data =>
                    data.HeadDir2.Equals(headDir) && data.GetBreathState2().Equals(breathState)
                    ).Count() * 10;     //検知データ件数×10秒で検知時間を計算

                // 21~30秒
                detectTime += dataList.Where(
                    data =>
                    data.HeadDir3.Equals(headDir) && data.GetBreathState3().Equals(breathState)
                    ).Count() * 10;     //検知データ件数×10秒で検知時間を計算
            }

            System.TimeSpan timeSpan = new System.TimeSpan(0, 0, detectTime);

            return(timeSpan.ToString()); //hh:mm:ssの形式に変換して返す
        }
Exemple #11
0
    public string total_rent_price(DateTime c1, DateTime c2, int car_id)
    {
        int day_count = 0;

        System.TimeSpan days = TimeSpan.Zero;
        if ((c1 != null && c2 != null) && c1 < c2 && c1 >= DateTime.Now.Date && c2 >= DateTime.Now.Date)
        {
            days = c2.Subtract(c1);
        }
        string tmp_days = days.ToString();

        string[] tmp_days_arr = tmp_days.Split('.');
        if ((c1 != c2) && c1 < c2 && c1 >= DateTime.Now.Date && c2 >= DateTime.Now.Date)
        {
            if (Convert.ToInt32(tmp_days_arr[0]) > 0)
            {
                day_count = Convert.ToInt32(tmp_days_arr[0]);
            }
        }
        if (c1 == c2)
        {
            day_count = 1;
        }
        return("Total price = " + (day_count * getDailyprice(car_id)).ToString());
    }
Exemple #12
0
 public void Close()
 {
     System.Threading.Thread.Sleep(1000);  // allow time for queue to drain
     endTime   = DateTime.Now;
     logIsOpen = false;
     try
     {
         logWriter.WriteLine("**************************************");
         logWriter.WriteLine("End of log for: " + logName);
         logWriter.WriteLine("End time: " + DateTime.Now.ToLongTimeString() + " " + DateTime.Now.ToLongDateString());
         runTime = endTime.Subtract(startTime);
         logWriter.WriteLine("Program Runtime: " + runTime.ToString());
         logWriter.Flush();
         string mils       = runTime.Milliseconds.ToString();
         int    secs       = runTime.Seconds;
         int    mins       = runTime.Minutes;
         int    hrs        = runTime.Hours;
         int    minsInSecs = mins * 60;
         int    hrsInSecs  = hrs * 60 * 60;
         int    totalSecs  = hrsInSecs + minsInSecs + secs;
         elapsedTime = System.Convert.ToDecimal(totalSecs.ToString() + "." + mils);
         logWriter.WriteLine("Runtime in seconds: " + elapsedTime.ToString());
         logWriter.Flush();
         logWriter.WriteLine("preparing to send data to log server");
         logWriter.Close();
     }
     catch (Exception ex)
     {
         logWriter.WriteLine("ERROR: " + ex.Message);
         logWriter.Flush();
     }
 }
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Import a file containing translations for one or more lists.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public bool ImportTranslatedLists(string filename, FdoCache cache, IProgress progress)
		{
#if DEBUG
			DateTime dtBegin = DateTime.Now;
#endif
			using (var inputStream = FileUtils.OpenStreamForRead(filename))
			{
				var type = Path.GetExtension(filename).ToLowerInvariant();
				if (type == ".zip")
				{
					using (var zipStream = new ZipInputStream(inputStream))
					{
						var entry = zipStream.GetNextEntry(); // advances it to where we can read the one zipped file.
						using (var reader = new StreamReader(zipStream, Encoding.UTF8))
							ImportTranslatedLists(reader, cache, progress);
					}
				}
				else
				{
					using (var reader = new StreamReader(inputStream, Encoding.UTF8))
						ImportTranslatedLists(reader, cache, progress);
				}
			}
#if DEBUG
			DateTime dtEnd = DateTime.Now;
			TimeSpan span = new TimeSpan(dtEnd.Ticks - dtBegin.Ticks);
			Debug.WriteLine(String.Format("Elapsed time for loading translated list(s) from {0} = {1}",
				filename, span.ToString()));
#endif
			return true;
		}
Exemple #14
0
        private async void btnReadAll_Click(object sender, EventArgs e)
        {
            label1.Text = "Processing...";
            txtResult.Text = "";
            MSMQHandler.MSMQHandler mh = new MSMQHandler.MSMQHandler(System.Configuration.ConfigurationManager.AppSettings["MSMQPath"]);
            StringBuilder s = new StringBuilder();

            TimeSpan inicio = new TimeSpan(DateTime.Now.Ticks);
            List<Tuple<string, string>> messages = await mh.ReadQueueAsync();
            if (messages.Count() > 0)
            {
                TimeSpan fim = new TimeSpan(DateTime.Now.Ticks);
                s.Append("=================================\r\n");
                s.Append("READING...\r\n");
                s.Append("=================================\r\n");
                s.Append("Inicio: " + inicio.ToString() + "\r\n");
                s.Append("=================================\r\n");
                s.Append("Fim: " + fim.ToString() + "\r\n");
                s.Append("=================================\r\n");
                s.Append("Tempo Total: " + (fim - inicio).ToString() + "\r\n");
                s.Append("=================================\r\n");
                s.Append("Total Msg: " + messages.Count() + "\r\n");
                s.Append("=================================\r\n");

                foreach (Tuple<string, string> t in messages)
                {
                    s.Append(t.Item1 + " - at " + t.Item2 + "\r\n");
                }
                txtResult.Text = s.ToString();
            }
            label1.Text = "Completed";
        }
Exemple #15
0
        private void btnShredIt_Click(object sender, EventArgs e)
        {
            Shredder shre = new Shredder();
            shre.SourceFile = txtSrcFile.Text;
            shre.TargetFolder = txtTargetFolder.Text;

            try
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();

                shre.ShredFile();

                sw.Stop();

                //long microseconds = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));

                TimeSpan ts = new TimeSpan(sw.ElapsedTicks);

                MessageBox.Show(ts.ToString());

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #16
0
 /// <summary>
 /// Formats a string and calls Log(...) if in DEBUG mode.
 /// </summary>
 /// <param name="description"></param>
 /// <param name="timeSpan"></param>
 public static void LogBenchmark(string description, TimeSpan timeSpan)
 {
     #if (DEBUG)
     string msg = DateTime.Now.ToString() + " | " + description;
     Log(msg + " | " + timeSpan.ToString());
     #endif
 }
    public IEnumerator StartDialogueSaving(string location)
    {
        GameControl.control.Freeze();
        currentState = DialogueStates.SavingDialogue;
        GameControl.control.saveRoomName = location;
        savingPanel.GetComponentInChildren <Text>().text = "Saving...";
        yield return(StartCoroutine(GameControl.control.Save()));

        yield return(new WaitForSeconds(0.2f));

        savingPanel.GetComponentInChildren <Text>().text = "Saved!";

        GameControl.control.LoadTemp();
        characterNameText.text = GameControl.control.playerName;
        System.TimeSpan ts = System.TimeSpan.FromSeconds((int)GameControl.control.playedTimeTemp);
        playTimeText.text = ts.ToString();
        locationText.text = GameControl.control.saveRoomNameTemp;

        for (int i = 0; i < 7; i++)
        {
            saveLens.transform.GetChild(i).gameObject.SetActive(GameControl.control.lensTemp[i]);
            saveMasks.transform.GetChild(i).gameObject.SetActive(GameControl.control.masksTemp[i]);
        }

        YesButton.Select();
        YesButton.OnSelect(null);
        yield return(new WaitForEndOfFrame());

        yield return(WaitForKeyDown("Submit"));

        GameControl.control.Unfreeze();
        currentState = DialogueStates.NoDialogue;
    }
Exemple #18
0
        private async void btnListQueue_Click(object sender, EventArgs e)
        {
            label1.Text = "Processing...";
            txtResult.Text = "";
            ActiveMQReader r = new ActiveMQReader(System.Configuration.ConfigurationManager.AppSettings["ActiveMQURL"], System.Configuration.ConfigurationManager.AppSettings["ActiveMQName"]);
            StringBuilder s = new StringBuilder();

            TimeSpan inicio = new TimeSpan(DateTime.Now.Ticks);
            List<Tuple<string, string>> messages = r.ListQueue();
            if (messages.Count() > 0)
            {
                TimeSpan fim = new TimeSpan(DateTime.Now.Ticks);
                s.Append("=================================\r\n");
                s.Append("LISTING...\r\n");
                s.Append("=================================\r\n");
                s.Append("Inicio: " + inicio.ToString() + "\r\n");
                s.Append("=================================\r\n");
                s.Append("Fim: " + fim.ToString() + "\r\n");
                s.Append("=================================\r\n");
                s.Append("Tempo Total: " + (fim - inicio).ToString() + "\r\n");
                s.Append("=================================\r\n");
                s.Append("Total Msg: " + messages.Count() + "\r\n");
                s.Append("=================================\r\n");

                foreach (Tuple<string, string> t in messages)
                {
                    s.Append(t.Item1 + " - at " + t.Item2 + "\r\n");
                }
                txtResult.Text = s.ToString();
            }
            label1.Text = "Completed";

        }
        public Message Request(Message requestMessage, TimeSpan timeout)
        {
            ThrowIfDisposedOrNotOpen();
            lock (this.writeLock)
            {
                try
                {
                    // Write the request message
                    this.WriteRequestMessage(requestMessage);

                    // Wait for the response
                    SoapMessageTableEntity soapMessage;
                    if (!this.WaitForReplyMessage(timeout, out soapMessage))
                    {
                        throw new TimeoutException(timeout.ToString());
                    }

                    // Read the reply message
                    Message replyMessage = this.ReadMessage(string.Format(ConfigurationConstants.ReplyTable, this.tableName), soapMessage);
                    return replyMessage;
                }
                catch (StorageException exception)
                {
                    throw new CommunicationException(exception.Message, exception);
                }
            }
        }
    // Update is called once per frame
    void Update()
    {
        if (!_timerEnabled)
        {
            return;
        }

        float secondsLeft = Math.Max(secondsInGame - (Time.time - _startTime), 0);

        System.TimeSpan t = System.TimeSpan.FromSeconds(secondsLeft);
        textObject.GetComponent <Text>().text = t.ToString("mm\\:ss");

        // Flash thrice every 10s or every second during the last 10
        int floorSec = Mathf.FloorToInt(secondsLeft);

        if (floorSec % 10 == 0 || floorSec % 10 == 9 || floorSec % 10 == 8 || floorSec < 10)
        {
            _canvasGroup.alpha = 1 - (Mathf.Ceil(secondsLeft) - secondsLeft);
        }
        else
        {
            _canvasGroup.alpha = 0;
        }

        if (secondsLeft <= 0 && !_endEventFired)
        {
            onTimerComplete.Invoke();
            _endEventFired = true;
        }
    }
Exemple #21
0
        private async void btnWriteSync_Click(object sender, EventArgs e)
        {
            if (!double.IsNaN(double.Parse(txtNrThreads.Text.Trim())))
            {
                int total = Int32.Parse(txtNrThreads.Text.Trim());

                lblProcessing.Text = "Processing...";

                MSMQHandler.MSMQHandler mh = new MSMQHandler.MSMQHandler(System.Configuration.ConfigurationManager.AppSettings["MSMQPath"]);

                TimeSpan inicio = new TimeSpan(DateTime.Now.Ticks);
                txtResult.Text += "==== Sync Output ==== Message size: " + cmbMessageSize.Text + " ==== # Threads: " + txtNrThreads.Text + "  \r\n";
                txtResult.Text += "Inicio: " + inicio.ToString() + "\r\n";
                string message = GetMessage();

                for (int i = 0; i < total; i++)
                {
                    mh.WriteToQueue(message, "test_" + i.ToString(), i);
                }

                TimeSpan fim = new TimeSpan(DateTime.Now.Ticks);

                txtResult.Text += "Fim: " + fim.ToString() + "\r\n";
                txtResult.Text += "Total: " + (fim - inicio).ToString() + "\r\n";

                lblProcessing.Text = "Completed.";
            }
        }
Exemple #22
0
        public static string TimeSpanDetailToMiliseconds(TimeSpan ts)
        {
            var sb = new StringBuilder();

            try
            {
                var fmt = ts.Days > 0 ? @"dd\.hh\:mm\:ss\.fff" : @"hh\:mm\:ss\.fff";

                var test = ts.ToString(fmt);

                if (ts.Days > 0)
                {
                    sb.Append($"{ts.Days:00} Days  ");
                }

                sb.Append($"{ts.Hours:00} Hours  ");
                sb.Append($"{ts.Minutes:00} Minutes  ");
                sb.Append($"{ts.Seconds:00} Seconds  ");
                sb.Append($"{ts.Milliseconds:000} Milliseconds");

                return sb.ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
 public Message Request(Message message, TimeSpan timeout)
 {
     ThrowIfDisposedOrNotOpen();
     lock (this.writeLock)
     {
         try
         {
             File.Delete(PathToFile(Via, "reply"));
             using (FileSystemWatcher watcher = new FileSystemWatcher(Via.AbsolutePath, "reply"))
             {
                 ManualResetEvent replyCreated = new ManualResetEvent(false);
                 watcher.Changed += new FileSystemEventHandler(
                    delegate(object sender, FileSystemEventArgs e) { replyCreated.Set(); }
                 );
                 watcher.EnableRaisingEvents = true;
                 WriteMessage(PathToFile(via, "request"), message);
                 if (!replyCreated.WaitOne(timeout, false))
                 {
                     throw new TimeoutException(timeout.ToString());
                 }
             }
         }
         catch (IOException exception)
         {
             throw ConvertException(exception);
         }
         return ReadMessage(PathToFile(Via, "reply"));
     }
 }
Exemple #24
0
        public void OutputRunStats(TimeSpan totalRuntime, IEnumerable<RunStats> runners, List<string> skippedTests)
        {
            var sb = new StringBuilder();

            sb.AppendLine(_ganttChartBuilder.GenerateGanttChart(runners));

            sb.AppendLine("<pre>");
            sb.AppendLine("Total Runtime: " + totalRuntime.ToString());
            foreach (var r in runners.OrderByDescending(t => t.RunTime))
            {
                AppendTestFinishedLine(sb, r);
            }

            if (skippedTests.Count > 0)
            {
                sb.AppendLine();
                sb.AppendLine("Did not run:");
                foreach (var r in skippedTests)
                {
                    sb.AppendFormat("'{0}'", r);
                    sb.AppendLine();
                }
            }
            sb.AppendLine("</pre>");

            File.WriteAllText(_settings.ResultsStatsFilepath, sb.ToString());
        }
Exemple #25
0
        private void BtnCannyEdgeDetect_Click(object sender, EventArgs e)
        {
            DateTime dt1 = new DateTime();
            DateTime dt2 = new DateTime();
            TimeSpan dt3 = new TimeSpan();
            float TH, TL, Sigma;
            int MaskSize;

            dt1 = DateTime.Now;
            pg1.Value = 0;
            TH = (float)Convert.ToDouble(TxtTH.Text);
            TL = (float)Convert.ToDouble(TxtTL.Text);

            MaskSize = Convert.ToInt32(TxtGMask.Text);
            Sigma = (float)Convert.ToDouble(TxtSigma.Text);
            pg1.Value = 10;
            CannyData = new Canny((Bitmap)IrisImage.Image,TH,TL,MaskSize,Sigma );

            HystThreshImage.Image = CannyData.DisplayImage(CannyData.NonMax);

            GaussianFilteredImage.Image = CannyData.DisplayImage(CannyData.FilteredImage);

            GNL.Image = CannyData.DisplayImage(CannyData.GNL);

            GNH.Image = CannyData.DisplayImage(CannyData.GNH);

            CannyEdges.Image = CannyData.DisplayImage(CannyData.EdgeMap);

            dt2 = DateTime.Now;
            dt3 = dt2 - dt1;
            time.Text = dt3.ToString();
            pg1.Value = 100;
        }
Exemple #26
0
  void Start()
  {
      modificacion = FindObjectOfType <ValoresDefecto>();
      print(modificacion.Valor1);
      Myformat = @"dd/MMM/yyyy";
      prueba   = "12/04/2021";
      valor    = "11/05/2021";
      DropdownItemSelected1(Municipio);
      DropdownItemSelected2(Estrato);
      Municipio.onValueChanged.AddListener(delegate { DropdownItemSelected1(Municipio); });
      Estrato.onValueChanged.AddListener(delegate { DropdownItemSelected2(Estrato); });
      FactorMultiplicacion.GetComponent <TMP_InputField>().text         = "1";
      FactorMultiplicacionReactiva.GetComponent <TMP_InputField>().text = "1";
      Hasta      = System.DateTime.Parse(prueba);
      Desde      = System.DateTime.Parse(valor);
      Resultado  = Desde.Subtract(Hasta);
      suspencion = Desde.AddDays(21);
      FechaPago  = Desde.AddMonths(-1);

      print(Hasta.ToString(@Myformat));
      print(Hasta.ToString("MMMM"));
      print(Resultado.ToString("%d"));
      print(suspencion.ToString(@Myformat));
      print(Desde.ToString(@Myformat));
      print(FechaPago.ToString(@Myformat));
      print((FechaPago.ToString("MMM")).ToUpper());
  }
 /// <summary>
 /// Creates a <see cref="EventTimer"/>
 /// </summary>
 /// <param name="period"></param>
 /// <param name="dayOffset"></param>
 EventTimer(TimeSpan period, TimeSpan dayOffset)
     : base(MessageClass.Component)
 {
     m_period = period;
     m_dayOffset = dayOffset;
     Log.InitialStackMessages = Log.InitialStackMessages.Union("Timer", string.Format("EventTimer: {0} in {1}", m_period.ToString(), m_dayOffset.ToString()));
 }
Exemple #28
0
		[Test] // ctor (Int64)
		public void Constructor1 ()
		{
			OracleTimeSpan ots;
			TimeSpan ts;
			
			ts = new TimeSpan (29, 7, 34, 58, 200);
			ots = new OracleTimeSpan (ts.Ticks);
			Assert.AreEqual (ts.Days, ots.Days, "#A1");
			Assert.AreEqual (ts.Hours, ots.Hours, "#A2");
			Assert.IsFalse (ots.IsNull, "#A3");
			Assert.AreEqual (ts.Milliseconds, ots.Milliseconds, "#A4");
			Assert.AreEqual (ts.Minutes, ots.Minutes, "#A5");
			Assert.AreEqual (ts.Seconds, ots.Seconds, "#A6");
			Assert.AreEqual (ts, ots.Value, "#A7");
			Assert.AreEqual (ts.ToString (), ots.ToString (), "#A8");

			ts = new TimeSpan (0L);
			ots = new OracleTimeSpan (0L);
			Assert.AreEqual (ts.Days, ots.Days, "#B1");
			Assert.AreEqual (ts.Hours, ots.Hours, "#B2");
			Assert.IsFalse (ots.IsNull, "#B3");
			Assert.AreEqual (ts.Milliseconds, ots.Milliseconds, "#B4");
			Assert.AreEqual (ts.Minutes, ots.Minutes, "#B5");
			Assert.AreEqual (ts.Seconds, ots.Seconds, "#B6");
			Assert.AreEqual (ts, ots.Value, "#B7");
			Assert.AreEqual (ts.ToString (), ots.ToString (), "#B8");
		}
Exemple #29
0
 public static int GetImportanceValue(DateTime date, DateTime startDate)
 {
     System.TimeSpan diff = startDate.Subtract(date);
     if (diff.ToString().Contains("-"))
     {
         return(0);
     }
     if (!diff.ToString().Contains("."))
     {
         return(8);
     }
     else
     {
         return(1);
     }
 }
Exemple #30
0
        static void Main(string[] args)
        {
            //Creating Timespan
            var timeSpan  = new System.TimeSpan(1, 2, 3);
            var timeSpan1 = new System.TimeSpan(1, 0, 0);
            var timeSpan2 = System.TimeSpan.FromHours(1);

            var start    = DateTime.Now;
            var end      = DateTime.Now.AddMinutes(2);
            var duration = end - start;

            Console.WriteLine("Duration: " + duration);

            //Properties
            Console.WriteLine("Minutes: " + timeSpan.Minutes);
            Console.WriteLine("Total Minutes: " + timeSpan.TotalMinutes);

            //Add
            Console.WriteLine("Add Example: " + timeSpan.Add(System.TimeSpan.FromMinutes(8)));
            Console.WriteLine("Subtract Example: " + timeSpan.Subtract(System.TimeSpan.FromMinutes(2)));

            // ToString
            Console.WriteLine("ToString " + timeSpan.ToString());

            // Parse
            Console.WriteLine("Parse: " + System.TimeSpan.Parse("01:02:03"));
        }
        public string getConnectionStatsStr()
        {
            string ret = "";

            IEnumerator i = map.Keys.GetEnumerator();
            while (i.MoveNext())
            {
                if (map[i.Current] != null)
                {
                    DateTime startTime = ((ClientConnection)map[i.Current]).getStartTime();
                    TimeSpan uptime = new TimeSpan(DateTime.Now.Ticks - startTime.Ticks);
                    ret += i.Current + " :\n ";
                    ret += "connect time: " + startTime.ToString() + "\n";;
                    ret += "duration: " + uptime.ToString() + "\n";
                    ret += "incoming msg count: " + ((ClientConnection)map[i.Current]).getIncomingMsgCount() + "\n";
                    ret += "outgoing msg count: " + ((ClientConnection)map[i.Current]).getOutgoingMsgCount() + "\n";
                }
                else
                {
                    Context.getInstance().getLogger().log("Found NULL connection", (string)i.Current, Logger.LEVEL_WARN);
                    map.Remove(i.Current);
                }
            }
            return ret;
        }
        /// <summary>
        /// 创建门店的构造函数
        /// </summary>
        public WePoiBaseInfo(string bName, string prov, string city, string addr, string tel,
            List<string> cate, OffsetType offset, double lgt, double lat, List<WePhotoUrl> phList,
            string special, TimeSpan beg, TimeSpan end)
        {
            TkDebug.AssertArgumentNullOrEmpty(bName, "bName", null);
            TkDebug.AssertArgumentNullOrEmpty(prov, "prov", null);
            TkDebug.AssertArgumentNullOrEmpty(city, "city", null);
            TkDebug.AssertArgumentNullOrEmpty(addr, "addr", null);
            TkDebug.AssertArgumentNullOrEmpty(tel, "tel", null);
            TkDebug.AssertArgumentNull(cate, "cate", null);
            TkDebug.AssertArgumentNull(phList, "phList", null);
            TkDebug.AssertArgumentNullOrEmpty(special, "special", null);

            BusinessName = bName;
            Province = prov;
            City = city;
            Address = addr;
            Telephone = tel;
            Categories = cate;
            OffsetType = offset;
            Longitude = lgt;
            Latitude = lat;
            PhotoList = phList;
            Special = special;
            OpenTime = beg.ToString("hh\\:mm") + "-" + end.ToString("hh\\:mm");
        }
        public ScreenRecordForm( IPluginHost pluginHost )
            : base(pluginHost)
        {
            this.StickyWindow = new DroidExplorer.UI.StickyWindow ( this );
            CommonResolutions = GetCommonResolutions ( );
            InitializeComponent ( );

            var defaultFile = "screenrecord_{0}_{1}.mp4".With ( this.PluginHost.Device, DateTime.Now.ToString ( "yyyy-MM-dd-hh" ) );
            this.location.Text = "/sdcard/{0}".With ( defaultFile );

            var resolution = new VideoSize ( PluginHost.CommandRunner.GetScreenResolution ( ) );
            var sizes = CommonResolutions.Concat ( new List<VideoSize> { resolution } ).OrderBy ( x => x.Size.Width ).Select ( x => x ).ToList ( );
            resolutionList.DataSource = sizes;
            resolutionList.DisplayMember = "Display";
            resolutionList.ValueMember = "Size";
            resolutionList.SelectedItem = resolution;

            rotateList.DataSource = GetRotateArgumentsList ( );
            rotateList.DisplayMember = "Display";
            rotateList.ValueMember = "Arguments";

            var bitrates = new List<BitRate> ( );

            for ( int i = 1; i < 25; i++ ) {
                bitrates.Add ( new BitRate ( i ) );
            }

            bitrateList.DataSource = bitrates;
            bitrateList.DisplayMember = "Display";
            bitrateList.ValueMember = "Value";
            bitrateList.SelectedItem = bitrates.Single ( x => x.Mbps == 4 );
            var ts = new TimeSpan ( 0, 0, 0, timeLimit.Value, 0 );
            displayTime.Text = ts.ToString ( );
        }
Exemple #34
0
        public static bool TryFormat(this System.TimeSpan value, Span <char> destination, out int charsWritten, ReadOnlySpan <char> format = default)
        {
            var f    = GetFormat(format);
            var span = ((f == null) ? value.ToString() : value.ToString(f)).AsSpan();

            if (span.TryCopyTo(destination))
            {
                charsWritten = span.Length;
                return(true);
            }
            else
            {
                charsWritten = 0;
                return(false);
            }
        }
        public string TransferTimeString;        // computed

        public void Normalise()
        {
            ShipTypeFD         = JournalFieldNaming.NormaliseFDShipName(ShipType);
            ShipType           = JournalFieldNaming.GetBetterShipName(ShipTypeFD);
            ShipType_Localised = ShipType_Localised.Alt(ShipType);
            TransferTimeSpan   = new System.TimeSpan((int)(TransferTime / 60 / 60), (int)((TransferTime / 60) % 60), (int)(TransferTime % 60));
            TransferTimeString = TransferTimeSpan.ToString();
        }
 public void Normalise()
 {
     NameFD             = JournalFieldNaming.NormaliseFDItemName(Name); // Name comes in with strange characters, normalise out
     Name               = JournalFieldNaming.GetBetterItemName(NameFD); // and look up a better name
     Name_Localised     = Name_Localised.Alt(Name);
     TransferTimeSpan   = new System.TimeSpan((int)(TransferTime / 60 / 60), (int)((TransferTime / 60) % 60), (int)(TransferTime % 60));
     TransferTimeString = TransferTime > 0 ? TransferTimeSpan.ToString() : "";
 }
        public void stopTimer()
        {
            stopTime  = System.DateTime.Now;
            totalTime = stopTime.Subtract(startTime);

            Report.Info("stop time = " + stopTime.ToString());
            Report.Info("total elapsed time = " + totalTime.ToString());
        }
    // string time coming from server
    public string ConvertTime(string timeInSeconds)
    {
        int val = Convert.ToInt32(timeInSeconds);

        System.TimeSpan time = System.TimeSpan.FromSeconds(val);

        return(time.ToString(@"mm\:ss"));
    }
Exemple #39
0
    // Update is called once per frame
    void Update()
    {
        time += Time.deltaTime;

        System.TimeSpan timeSpan = System.TimeSpan.FromSeconds(time);

        text.text = timeSpan.ToString("mm\\:ss");
    }
Exemple #40
0
        /// <summary>
        /// 时间差
        /// </summary>
        /// <param name="adddate"></param>
        /// <returns></returns>
        public string GetDiff(string adddate)
        {
            DateTime date1 = new DateTime(Convert.ToDateTime(adddate).Year, Convert.ToDateTime(adddate).Month, Convert.ToDateTime(adddate).Day);
            DateTime date2 = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, System.DateTime.Now.Day);

            System.TimeSpan diff = date1 - date2;
            return(diff.ToString());
        }
Exemple #41
0
        static void Main(string[] args)
        {
            System.Int32 i;
            String       s;

            s = Console.ReadLine();
            if (Int32.TryParse(s, out i))
            {
                Int32.TryParse(s, out i);
            }
            else
            {
                Console.WriteLine(s + " is not an integer");
            }



            int ii;

            String ss;

            ss = Console.ReadLine();
            if (Int32.TryParse(ss, out ii))
            {
                Int32.TryParse(ss, out ii);
            }
            else
            {
                Console.WriteLine(ss + " is not an integer");
            }

            if (i < ii)
            {
                Console.WriteLine(i.ToString() + " is less than " + ii.ToString());
            }

            if (ii < i)
            {
                Console.WriteLine(ii.ToString() + " is less than " + i.ToString());
            }

            Console.WriteLine("----");


            //Dato beregninger
            System.DateTime d1 = System.DateTime.Now;
            System.DateTime d2 = System.DateTime.Today;

            Console.WriteLine("Now: " + d1.ToString());
            Console.WriteLine("Today: " + d2.ToString());
            System.TimeSpan ts = d2.Subtract(d1);



            Console.WriteLine(ts.ToString());

            Console.ReadKey();
        }
Exemple #42
0
    private string parseDuration(float remainingDuration)
    {
        System.TimeSpan t = System.TimeSpan.FromSeconds(remainingDuration);
        //int minutes = (int) (remainingDuration / 60);
        //int seconds = (int) (remainingDuration % 60);
        string line = t.ToString(@"dd\.hh\:mm\:ss");

        return(line);
    }
Exemple #43
0
 public static string GetFormatedTime(this System.TimeSpan value)
 {
     //string typeOfRetutn = "";
     //if (value.Days > 0)
     //{
     //    value.we
     //}
     return(value.ToString(hms));
 }
Exemple #44
0
    public override void Process(string sessionName)
    {
        List <TrackerEvent> events = Tracker.instance.GetTestEvents(sessionName);

        System.DateTime starTime  = System.DateTime.MinValue;
        System.TimeSpan totalTime = System.TimeSpan.Zero;

        System.DateTime lastAimEvent = System.DateTime.MinValue;
        System.TimeSpan totalTimeIn  = System.TimeSpan.Zero;


        bool isIn = false; //Para evitar dobles

        foreach (TrackerEvent e in events)
        {
            if (e.eventType == EventType.SESSION_START)
            {
                starTime = e.time;
            }
            else if (e.eventType == EventType.SESSION_END)
            {
                totalTime = (e.time - starTime);
            }
            //Si es un evento de tipo AIM, lo procesamos
            if (e.eventType == EventType.AIM)
            {
                AimEvent aimEvent = ((AimEvent)e);

                //Si el jugador apunta la bola, apuntamos el tiempo
                if (!isIn && aimEvent.aimEventType == AimEventType.AIM_IN)
                {
                    lastAimEvent = e.time;
                    isIn         = true;
                }
                else if (isIn && aimEvent.aimEventType == AimEventType.AIM_OUT)
                {
                    System.DateTime timeOut = e.time;

                    totalTimeIn += (timeOut - lastAimEvent);
                    isIn         = false;
                }

                Debug.Log("Evento aim: " + ((AimEvent)e).aimEventTypeString);
            }
        }

        Debug.Log("Time in: " + totalTimeIn.ToString(@"mm\:ss\.fff") + " / " + totalTime.ToString(@"mm\:ss\.fff"));
        Debug.Log("Percentage: " + (totalTimeIn.TotalMilliseconds / totalTime.TotalMilliseconds) * 100 + "%");

        //Analisis
        notaFinal = (float)((totalTimeIn.TotalMilliseconds / totalTime.TotalMilliseconds) * 100);
        GameObject.FindObjectOfType <GUIManager>().SetNota(notaFinal);
        if (GameObject.FindObjectOfType <GameSessionManager>() != null && GameSessionManager.Instance.GetCompleteTest())
        {
            GameObject.FindObjectOfType <AnalysisManager>().addStadistic(stat.tracking, notaFinal);
        }
    }
Exemple #45
0
    // Update is called once per frame
    void Update()
    {
        if (gameOver)
        {
            GameOver();
        }

        System.TimeSpan ts = timer.Elapsed;
        timerString        = ts.ToString().Substring(3, 5);
        stopwatchText.text = timerString;
    }
Exemple #46
0
    private IEnumerator UpdateTimer()
    {
        while (timerGoing)
        {
            elapsedTime     += Time.deltaTime;
            timePlaying      = System.TimeSpan.FromSeconds(elapsedTime);
            timeCounter.text = timePlaying.ToString("mm':'ss'.'ff");

            yield return(null);
        }
    }
Exemple #47
0
        private void vName_SelectedIndexChanged(object sender, EventArgs e)
        {
            ent = new Cfirst();
            DateTime dateTime = DateTime.Today;
            Varieties_supplypermessions vsp = (from em in ent.Varieties_supplypermessions where
                                               em.Varieties == vName.Text select em).First();
            supplyPermession sp = (from en in ent.supplyPermessions where en.SuplyId == vsp.SupplyId select en).First();

            System.TimeSpan diff = dateTime.Subtract((DateTime)sp.history);
            Duration.Text = diff.ToString();
        }
Exemple #48
0
        static void Main(string[] args)
        {
            Class1 Petya = new Class1();
            Class1 Vasya = new Class1();

            Petya.Birth = new DateTime(2007, 4, 15);
            Vasya.Birth = new DateTime(2008, 1, 1);
            System.TimeSpan daysCount = Vasya.Birth.Subtract(Petya.Birth);

            Console.WriteLine(daysCount.ToString());
        }
Exemple #49
0
        private void button1_Click(object sender, EventArgs e)
        {
            System.DateTime firstDate  = new System.DateTime(2000, 01, 01);
            System.DateTime secondDate = new System.DateTime(2000, 05, 31);

            System.TimeSpan diff  = secondDate.Subtract(firstDate);
            System.TimeSpan diff1 = secondDate - firstDate;

            String diff2 = (secondDate - firstDate).TotalDays.ToString();

            MessageBox.Show(diff1.ToString());
        }
Exemple #50
0
 // Update is called once per frame
 void Update()
 {
     timer -= Time.deltaTime;
     System.TimeSpan timeSpan = System.TimeSpan.FromSeconds(timer);
     chronoText.text            = timeSpan.ToString(@"mm\:ss");
     EndGameStats.remainingTime = timer;
     if (timer < 0.0f)
     {
         EndGameStats.remainingTime = 0.0f;
         GetComponent <SceneChange>().ChangeScene();
     }
 }
Exemple #51
0
    IEnumerator CountTimePlay()
    {
        yield return(timeCountPlay);

        if (gameState == GameState.play)
        {
            timePlay++;
            timeSpanTemp          = System.TimeSpan.FromSeconds(timePlay);
            uiPanel.timeText.text = timeSpanTemp.ToString("mm':'ss");
        }
        StartCoroutine(CountTimePlay());
    }
        static string Align(System.TimeSpan interval)
        {
            string intervalStr = interval.ToString();
            int    pointIndex  = intervalStr.IndexOf(':');

            pointIndex = intervalStr.IndexOf('.', pointIndex);
            if (pointIndex < 0)
            {
                intervalStr += "        ";
            }
            return(intervalStr);
        }
Exemple #53
0
    void Update()
    {
        if (!done)
        {
            System.TimeSpan ts = stopwatch.Elapsed;
            Timer.SetText(ts.ToString(@"mm\:ss\.fff"));
        }

        if (SaveButton.interactable != save)
        {
            SaveButton.interactable = save;
        }
    }
 public override void Initialize()
 {
     base.Initialize();
     updateIncrement   = new TimeSpan(0, 3, 0, 0);
     timeSpeed         = 1440F / minutesPerDay;
     timeElapsed       = new TimeSpan();
     timeElapsedString = timeElapsed.ToString();
     gameTime          = new TimeSpan(0, 12, 0, 0);
     lastUpdate        = gameTime;
     nextUpdate        = lastUpdate.Add(updateIncrement);
     gameTimeString    = gameTime.ToString();
     timeIncrement     = 1;
 }
Exemple #55
-1
 private void ResetSW_Click(object sender, RoutedEventArgs e)
 {
     if (ResetSW.Content.ToString() == "Resume")
     {
         StreamReader sreader = new StreamReader(@"stopwatch.txt");
         hrs = sreader.ReadLine();
         mins = sreader.ReadLine();
         secs = sreader.ReadLine();
         mils = sreader.ReadLine();
         sreader.Close();
         int hr = int.Parse(hrs);
         int min = int.Parse(mins);
         int sec = int.Parse(secs);
         int mil = int.Parse(mils);
         ResetSW.Content = "Reset";
         res = new TimeSpan(0, hr, min, sec, mil);
         ts = res;
         StopwatchTB.Text = ts.ToString();
         sw.Start();
         dtimer.Start();
         ResetSW.IsEnabled = false;
         StartSW.Content = "Pause";
     }
     else
     {
         sw.Reset();
         res = zero;
         StopwatchTB.Text = sw.Elapsed.ToString("mm\\:ss\\.ff");
         ResetSW.IsEnabled = false;
     }
 }
Exemple #56
-1
        /**   private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {

        }
          * **/
        private void Canny_Click(object sender, EventArgs e)
        {
            DateTime dt1 = new DateTime();
            DateTime dt2 = new DateTime();
            TimeSpan dt3 = new TimeSpan();
            float TH, TL;

            dt1 = DateTime.Now;
            pg1.Value = 0;
            TH = (float)Convert.ToDouble(TxtTH.Text);
            TL = (float)Convert.ToDouble(TxtTL.Text);

            pg1.Value = 10;

            CannyData = new Canny((Bitmap)cannyPic.Image, TH, TL);

            cannyPicRe.Image = CannyData.DisplayImage(CannyData.NonMax);

            cannyPicRe.Image = CannyData.DisplayImage(CannyData.GNL);

            cannyPicRe.Image = CannyData.DisplayImage(CannyData.GNH);

            cannyPicRe.Image = CannyData.DisplayImage(CannyData.EdgeMap);

            dt2 = DateTime.Now;
            dt3 = dt2 - dt1;
            time.Text = dt3.ToString();
            pg1.Value = 100;
        }
Exemple #57
-1
        protected void addroommoviebtn_Click(object sender, EventArgs e)
        {
            Calendar2.Visible = false;
            pnlEdit.Visible = false;
            pnlAdd.Visible = true;
            movieddl.DataSource = Business_Logic.MovieLogic.getMovieList();
            movieddl.DataTextField = "Movie_Name";
            movieddl.DataValueField = "Movie_ID";
            movieddl.DataBind();
            m = Business_Logic.MovieLogic.getMovieByPK(Convert.ToInt32(movieddl.SelectedValue));
            Label7.Text = Convert.ToString(m.Movie_ID);
            Label9.Text = m.Movie_Name;
            Label11.Text = Convert.ToString(m.Duration);
            Label13.Text = m.Description;
            Label15.Text = Convert.ToString(m.Ratings);

            TimeSpan st = TimeSpan.Parse(starttimeddl.SelectedValue);
            int dur = Convert.ToInt32(Label11.Text);
            int hf = dur / 30;
            int left = hf / 2;
            int right = hf % 2 + 1;
            TimeSpan final = new TimeSpan(st.Hours + left, st.Minutes + right * 30, 0);

            addetlb.Text = final.ToString(@"hh\:mm");
        }
        //takes info and makes a message that shows the component, method, timespan, properties
        //then shows it as an informative message to trace listeners
        public void TraceApi(string componentName, string method, TimeSpan timespan, string properties)
        {
            string message = String.Concat("Component:", componentName, "; Method:", method, ";Timespan:",
                timespan.ToString(), ";Properties:", properties);

            Trace.TraceInformation(message);
        }
Exemple #59
-1
 internal void SessionMessagePumpStart(string messagePumpType, string environment, string path, TimeSpan autoRenewSessionTimeout, int maxConcurrentSessions)
 {
     if (IsEnabled())
     {
         SessionMessagePumpStart(messagePumpType, environment, path, autoRenewSessionTimeout.ToString(), maxConcurrentSessions);
     }
 }
        // methods
        public static string ToString(TimeSpan value)
        {
            const int msInOneSecond = 1000;
            const int msInOneMinute = 60 * msInOneSecond;
            const int msInOneHour = 60 * msInOneMinute;

            var ms = (long)value.TotalMilliseconds;
            if( (ms % msInOneHour) == 0 )
            {
                return string.Format("{0}h", ms / msInOneHour);
            }
            else if( (ms % msInOneMinute) == 0 && ms < msInOneHour )
            {
                return string.Format("{0}m", ms / msInOneMinute);
            }
            else if( (ms % msInOneSecond) == 0 && ms < msInOneMinute )
            {
                return string.Format("{0}s", ms / msInOneSecond);
            }
            else if( ms < 1000 )
            {
                return string.Format("{0}ms", ms);
            }
            else
            {
                return value.ToString();
            }
        }