public static Task Start(Func<CancellationToken, Task<bool>> action, TimeSpan delay, CancellationToken cancellationToken)
        {
            Ensure.IsInfiniteOrGreaterThanOrEqualToZero(delay, "delay");

            Func<CancellationToken, Task> delayTask = null;
            if (delay.Equals(TimeSpan.Zero))
            {
                delayTask = ct => Task.FromResult<object>(null);
            }
            else if (!delay.Equals(Timeout.InfiniteTimeSpan))
            {
                delayTask = ct => Task.Delay(delay, ct);
            }
            
            return Start(action, delayTask, cancellationToken);
        }
Example #2
0
    static int Equals(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2 && TypeChecker.CheckTypes <System.TimeSpan>(L, 2))
            {
                System.TimeSpan obj  = (System.TimeSpan)ToLua.CheckObject(L, 1, typeof(System.TimeSpan));
                System.TimeSpan arg0 = StackTraits <System.TimeSpan> .To(L, 2);

                bool o = obj.Equals(arg0);
                LuaDLL.lua_pushboolean(L, o);
                ToLua.SetBack(L, 1, obj);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes <object>(L, 2))
            {
                System.TimeSpan obj  = (System.TimeSpan)ToLua.CheckObject(L, 1, typeof(System.TimeSpan));
                object          arg0 = ToLua.ToVarObject(L, 2);
                bool            o    = obj.Equals(arg0);
                LuaDLL.lua_pushboolean(L, o);
                ToLua.SetBack(L, 1, obj);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: System.TimeSpan.Equals"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Example #3
0
    public bool PosTest2()
    {
        bool retVal = true;
        long randValue = 0;

        TestLibrary.TestFramework.BeginScenario("PosTest2: Equals should return true when compare with equal instance");

        try
        {
            randValue = TestLibrary.Generator.GetInt64(-55);
            TimeSpan ts1 = new TimeSpan(randValue);
            TimeSpan ts2 = new TimeSpan(randValue);

            if (!ts1.Equals(ts2 as Object))
            {
                TestLibrary.TestFramework.LogError("002.1", "Equals does not return true when compare with self instance");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] ts1.Ticks = " + ts1.Ticks + ", ts2.Ticks = " + ts2.Ticks + ", randValue = " + randValue);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
        public static float ToInches(TimeSpan pulse)
        {
            if (pulse.Equals(TimeSpan.MaxValue))
                return Single.MaxValue;

            float result = pulse.TotalMicroseconds()/148f;
            return result;
        }
Example #5
0
        public static bool AreTimesEqualToTheSecond(DateTime dt1, DateTime dt2)
        {
            //STRIP THE MILLISECONDS OUT
            var timeNowToTheSeconds = new TimeSpan(dt1.TimeOfDay.Hours, dt1.TimeOfDay.Minutes, dt1.TimeOfDay.Seconds);
            var triggerToTheSeconds = new TimeSpan(dt2.TimeOfDay.Hours, dt2.TimeOfDay.Minutes, dt2.TimeOfDay.Seconds);

            return timeNowToTheSeconds.Equals(triggerToTheSeconds);
        }
		public void EqualsWorks() {
			var time1 = new TimeSpan(15, 10, 20, 5, 14);
			var time2 = new TimeSpan(14, 10, 20, 5, 14);
			var time3 = new TimeSpan(15, 10, 20, 5, 14);

			Assert.IsFalse(time1.Equals(time2));
			Assert.IsTrue (time1.Equals(time3));
		}
      /// <summary>
      /// Gets the points per day measurement based the given frame time, work unit information, and the unit completion time.
      /// </summary>
      /// <param name="frameTime">The work unit frame time.</param>
      /// <param name="frames">The number of frames in the work unit.</param>
      /// <param name="baseCredit">The base credit assigned to the work unit.</param>
      /// <param name="kFactor">The KFactor assigned to the work unit.</param>
      /// <param name="preferredDays">The preferred deadline (in decimal days).</param>
      /// <param name="maximumDays">The final deadline (in decimal days).</param>
      /// <param name="unitTime">The overall unit completion time.</param>
      /// <returns>The points per day for the work unit.</returns>
      public static double GetPPD(TimeSpan frameTime, int frames, double baseCredit, double kFactor, double preferredDays, double maximumDays, TimeSpan unitTime)
      {
         if (frameTime.Equals(TimeSpan.Zero)) return 0;

         double basePPD = GetUPD(frameTime, frames) * baseCredit;
         double bonusMulti = GetMultiplier(kFactor, preferredDays, maximumDays, unitTime);
         double bonusPPD = Math.Round((basePPD * bonusMulti), MaxDecimalPlaces);

         return bonusPPD;
      }
Example #8
0
        private void bBonusContinue_Click(object sender, EventArgs e)
        {
            var t = new TimeSpan((int)numUpDBonusHours.Value, (int)numUpDBonusMinutes.Value, (int)numUpDBonusSeconds.Value);
            if (t.Equals(new TimeSpan()))
            {
                t = new TimeSpan();
            }

            DiscountRedactorController.InstanceDiscountRedactorController()
                .CreateNewBonus(t, tbBonusItem.Text, (int)numUpDBonusNumOfItem.Value,
                    (double)numUpDBonusMoneySum.Value, (double)numUpBonusSumDiscount.Value);
        }
Example #9
0
    void DisplayTime()
    {
        if (timeLeft.Equals(System.TimeSpan.Zero))
        {
            GameOver();
        }

        timerTextBox = GameObject.Find("Timer").GetComponent <Text>();
        timerTextBox.transform.position = new Vector3(CameraScript.minX * (-.6f), CameraScript.maxY, 0);
        timerTextBox.text = new System.DateTime(timeLeft.Ticks).ToString("mm:ss");
        ClockTick();
    }
Example #10
0
        private void bRequirementsContinue_Click(object sender, EventArgs e)
        {
            var t = new TimeSpan((int)numUpDHoursRequirement.Value, (int)numUpDMinutesRequirements.Value, (int)numUpDSecondsRequirements.Value);
            if (t.Equals(new TimeSpan()))
            {
                t = new TimeSpan();
            }

            DiscountRedactorController.InstanceDiscountRedactorController()
                .CreateNewRequirement(t, tbItemRequiredToBuy.Text, (int) numUpDNumOfItemsRequired.Value,
                    (double) numUpDMOneySumRequiredToPay.Value);
        }
Example #11
0
        public string GetTimeString(EventCalendar ev)
        {
            if (ev.customer.Length == 0)
            {
                TimeSpan to_time = new TimeSpan(Convert.ToInt32(ev.to_time.Split(':')[0]), Convert.ToInt32(ev.to_time.Split(':')[1]), 0);
                TimeSpan from_time = new TimeSpan(Convert.ToInt32(ev.from_time.Split(':')[0]), Convert.ToInt32(ev.from_time.Split(':')[1]), 0);
                DateTime event_date = DateTime.Parse(ev.date, cinfo_us, DateTimeStyles.None);

                if (from_time.Hours <= 12 && to_time.Hours >= 13)
                {
                    return ((to_time - from_time - TimeSpan.Parse("01:00:00")).Hours >= 1 ? (to_time - from_time - TimeSpan.Parse("01:00:00")).Hours.ToString() + ((to_time - from_time - TimeSpan.Parse("01:00:00")).Minutes > 1 ? ":" + (to_time - from_time - TimeSpan.Parse("01:00:00")).Minutes.ToString() + " ชม." : " ชม.") : (to_time - from_time - TimeSpan.Parse("01:00:00")).Minutes.ToString() + " นาที") + ((event_date.GetDayIntOfWeek() >= 2 && event_date.GetDayIntOfWeek() <= 6) && (from_time.Equals(TimeSpan.Parse("08:30:00")) && to_time.Equals(TimeSpan.Parse("17:30:00"))) ? "(เต็มวัน)" : "(" + from_time.ToString().Substring(0, 5) + " - " + to_time.ToString().Substring(0, 5) + ")");
                }
                else
                {
                    return ((to_time - from_time).Hours >= 1 ? (to_time - from_time).Hours.ToString() + ((to_time - from_time).Minutes > 1 ? ":" + (to_time - from_time).Minutes.ToString() + " ชม." : " ชม.") : (to_time - from_time).Minutes.ToString() + " นาที") + ((event_date.GetDayIntOfWeek() >= 2 && event_date.GetDayIntOfWeek() <= 6) && (from_time.Equals(TimeSpan.Parse("08:30:00")) && to_time.Equals(TimeSpan.Parse("17:30:00"))) ? "(เต็มวัน)" : "(" + from_time.ToString().Substring(0, 5) + " - " + to_time.ToString().Substring(0, 5) + ")");
                }
            }
            else
            {
                return ev.customer;
            }
        }
Example #12
0
        public void TestEquals()
        {
            TimeSpan t1 = new TimeSpan(1);
            TimeSpan t2 = new TimeSpan(2);
            string s = "justastring";

            Assert.AreEqual(true, t1.Equals(t1), "A1");
            Assert.AreEqual(false, t1.Equals(t2), "A2");
            Assert.AreEqual(false, t1.Equals(s), "A3");
            Assert.AreEqual(false, t1.Equals(null), "A4");
            Assert.AreEqual(true, TimeSpan.Equals(t1, t1), "A5");
            Assert.AreEqual(false, TimeSpan.Equals(t1, t2), "A6");
            Assert.AreEqual(false, TimeSpan.Equals(t1, null), "A7");
            Assert.AreEqual(false, TimeSpan.Equals(t1, s), "A8");
            Assert.AreEqual(false, TimeSpan.Equals(s, t2), "A9");
            Assert.AreEqual(true, TimeSpan.Equals(null, null), "A10");
        }
Example #13
0
 /// <summary>
 /// Compares two times for equality
 /// </summary>
 /// <param name="atime1"></param>
 /// <param name="atime2"></param>
 /// <returns>true if and only if the argument atime1 represents the same time as atime2</returns>
 public static bool TimeEquals(TimeSpan? atime1, TimeSpan? atime2)
 {
     return atime1.Equals(atime2);
 }
Example #14
0
        private async Task<HttpSourceResult> TryCache(string uri, string cacheKey, TimeSpan cacheAgeLimit)
        {
            var baseFolderName = RemoveInvalidFileNameChars(ComputeHash(_baseUri));
            var baseFileName = RemoveInvalidFileNameChars(cacheKey) + ".dat";

            var cacheFolder = Path.Combine(
                DnuEnvironment.GetFolderPath(DnuFolderPath.HttpCacheDirectory),
                baseFolderName);
            var cacheFile = Path.Combine(cacheFolder, baseFileName);

            if (!Directory.Exists(cacheFolder) && !cacheAgeLimit.Equals(TimeSpan.Zero))
            {
                Directory.CreateDirectory(cacheFolder);
            }

            // Acquire the lock on a file before we open it to prevent this process
            // from opening a file deleted by the logic in HttpSource.GetAsync() in another process
            return await ConcurrencyUtilities.ExecuteWithFileLocked(cacheFile, action: _ =>
            {
                if (File.Exists(cacheFile))
                {
                    var fileInfo = new FileInfo(cacheFile);
#if DNX451
                    var age = DateTime.UtcNow.Subtract(fileInfo.LastWriteTimeUtc);
#else
                    var age = DateTime.Now.Subtract(fileInfo.LastWriteTime);
#endif
                    if (age < cacheAgeLimit)
                    {
                        var stream = CreateAsyncFileStream(
                            cacheFile,
                            FileMode.Open,
                            FileAccess.Read,
                            FileShare.Read | FileShare.Delete);

                        return Task.FromResult(new HttpSourceResult
                        {
                            CacheFileName = cacheFile,
                            Stream = stream,
                        });
                    }
                }

                return Task.FromResult(new HttpSourceResult
                {
                    CacheFileName = cacheFile,
                });
            });
        }
        public GpggaSentence(TimeSpan utcTime, Position position, FixQuality fixQuality, int trackedSatelliteCount,
                            DilutionOfPrecision horizontalDilutionOfPrecision, Distance altitude, Distance geoidalSeparation,
                            TimeSpan differentialGpsAge, int differentialGpsStationID)
        {        
            // Use a string builder to create the sentence text
            StringBuilder builder = new StringBuilder(128);

            #region Append the command word

            // Append the command word
            builder.Append("$GPGGA");

            #endregion

            // Append a comma
            builder.Append(',');

            #region Append the UTC time

            /* Convert UTC time to a string in the form HHMMSS.SSSS. Any value less than 10 will be
             * padded with a zero.
             */

            builder.Append(_UtcTime.Hours.ToString("0#", NmeaCultureInfo));
            builder.Append(_UtcTime.Minutes.ToString("0#", NmeaCultureInfo));
            builder.Append(_UtcTime.Seconds.ToString("0#", NmeaCultureInfo));
            builder.Append(".");
            builder.Append(_UtcTime.Milliseconds.ToString("00#", NmeaCultureInfo));

            #endregion

            // Append a comma
            builder.Append(',');

            #region Append the position

            // Append latitude in the format HHMM.MMMM. 
            builder.Append(position.Latitude.ToString("HHMM.MMMM,I,", NmeaCultureInfo));
            // Append Longitude in the format HHHMM.MMMM.
            builder.Append(position.Longitude.ToString("HHHMM.MMMM,I,", NmeaCultureInfo));

            #endregion

            #region Append fix quality

            switch (fixQuality)
            {
                case FixQuality.NoFix:
                    builder.Append("0");
                    break;
                case FixQuality.GpsFix:
                    builder.Append("1");
                    break;
                case FixQuality.DifferentialGpsFix:
                    builder.Append("2");
                    break;
                case FixQuality.PulsePerSecond:
                    builder.Append("3");
                    break;
                case FixQuality.FixedRealTimeKinematic:
                    builder.Append("4");
                    break;
                case FixQuality.FloatRealTimeKinematic:
                    builder.Append("5");
                    break;
                case FixQuality.Estimated:
                    builder.Append("6");
                    break;
                case FixQuality.ManualInput:
                    builder.Append("7");
                    break;
                case FixQuality.Simulated:
                    builder.Append("8");
                    break;              
            }

            #endregion

            // Append a comma
            builder.Append(",");

            // Append the tracked (signal strength is > 0) satellite count
            builder.Append(trackedSatelliteCount.ToString(NmeaCultureInfo));

            // Append a comma
            builder.Append(",");

            // Append the numerical value of HDOP
            builder.Append(horizontalDilutionOfPrecision.Value.ToString(NmeaCultureInfo));

            // Append a comma
            builder.Append(",");

            #region Altitude above sea level

            // Append the numerical value in meters
            builder.Append(altitude.ToMeters().Value.ToString(NmeaCultureInfo));

            // Append a comma, the unit (M = meters), and another comma
            builder.Append(",M,"); 

            #endregion

            #region Geoidal separation

            // Append the numerical value in meters
            builder.Append(geoidalSeparation.ToMeters().Value.ToString(NmeaCultureInfo));

            // Append a comma
            builder.Append(",M,");

            #endregion

            #region Differential GPS information

            // Differnetial signal age in seconds
            if (!differentialGpsAge.Equals(TimeSpan.MinValue))
                builder.Append(differentialGpsAge.TotalSeconds.ToString(NmeaCultureInfo));

            // Append a comma
            builder.Append(",");

            // Station ID
            if (differentialGpsStationID != -1)
                builder.Append(differentialGpsStationID.ToString(NmeaCultureInfo));

            #endregion

            // Set this object's sentence
            SetSentence(builder.ToString());

            // Finally, append the checksum
            AppendChecksum();
        }
Example #16
0
        /// <summary>
        /// �^�C���X�p������t�H�[�}�b�g�����������擾
        /// </summary>
        /// <param name="timeSpan"></param>
        /// <returns></returns>
        private String GetTimeSpanToFormat(TimeSpan timeSpan)
        {
            if (timeSpan.Equals(TimeSpan.Zero) == true)
            {
                return Properties.Resources.UnKown;
            }

            StringBuilder result = new StringBuilder();
            result.Append(Properties.Resources.AlsoTime);

            // ����
            if (timeSpan.Hours > 0)
            {
                timeSpan.Add(new TimeSpan(0, 60 - timeSpan.Minutes, 60 - timeSpan.Seconds));

                result.AppendFormat(Properties.Resources.HoursFormat, timeSpan.Hours);
            }

            // ��
            if (timeSpan.Minutes > 0)
            {
                timeSpan.Add(new TimeSpan(0, 0, 60 - timeSpan.Seconds));

                result.AppendFormat(Properties.Resources.MinutesFormat, timeSpan.Minutes);
            }

            // �b
            if (timeSpan.Seconds > 0)
            {
                int second = (int) (Math.Floor(timeSpan.Seconds % 5.0) * 5);
                result.AppendFormat(Properties.Resources.SecondsFormat, second);
            }

            // �~���b
            if (timeSpan.Seconds == 0 && timeSpan.Milliseconds >= 0)
            {
                int second = timeSpan.Milliseconds / 200;
                result.AppendFormat(Properties.Resources.SecondsFormat, second);
            }

            return result.ToString();
        }
Example #17
0
      /// <summary>
      /// Get Points Per Day based on given Frame Time
      /// </summary>
      /// <param name="frameTime">Frame Time</param>
      /// <param name="estTimeOfUnit">Estimated Time of the Unit</param>
      /// <param name="calculateBonus">Calculate Bonus Value</param>
      public double GetPPD(TimeSpan frameTime, TimeSpan estTimeOfUnit, bool calculateBonus)
      {
         if (frameTime.Equals(TimeSpan.Zero)) return 0;

         double basePPD = GetUPD(frameTime) * Credit;
         double bonusMulti = GetMultiplier(estTimeOfUnit, calculateBonus);
         double bonusPPD = Math.Round((basePPD * bonusMulti), MaxDecimalPlaces);
         
         return bonusPPD;
      }
Example #18
0
 /// <summary />
 public bool Equals(TimeSpan other)
 {
     return(_timeSpan.Equals(other._timeSpan));
 }
		public MFTestResults Equals_Test6(  )
        {
            /// <summary>
            /// 1. Test the Equals method
            /// </summary>
            ///
            Log.Comment("Testing the Equals method");
			bool testResult = true;
			try
			{
				Random random = new Random();
				// verify same timespan computes to same hash
				for( int i = 0; i<5; i++ )
				{
					int hours = random.Next(23);
					int minutes = random.Next(59);
					int seconds = random.Next(59);
					TimeSpan ts01 = new TimeSpan( hours, minutes, seconds );
					TimeSpan ts02 = new TimeSpan( hours, minutes, seconds );
					Log.Comment( ts01.ToString() + " == " + ts02.ToString() );
                    Log.Comment("Expected true");
					testResult &= ts01.Equals(ts02);
					Log.Comment( testResult.ToString() );
                    TimeSpan ts03 = new TimeSpan(hours, minutes, seconds );
				    TimeSpan ts04 = new TimeSpan(hours + 1, minutes - 1, seconds + 1);
                    Log.Comment("Expected false");
                    testResult &= !ts03.Equals(ts04);
				}
			}
			catch
			{
				testResult = false;
			}
			return (testResult? MFTestResults.Pass: MFTestResults.Fail);
		}
Example #20
0
    public bool PosTest3()
    {
        bool retVal = true;
        long randValue1 = 0;
        long randValue2 = 0;

        TestLibrary.TestFramework.BeginScenario("PosTest3: Equals should return false when compare with not equal instance");

        try
        {
            randValue1 = TestLibrary.Generator.GetInt64(-55);
            do
            {
                randValue2 = TestLibrary.Generator.GetInt64(-55);
            } while (randValue2 == randValue1);

            TimeSpan ts1 = new TimeSpan(randValue1);
            TimeSpan ts2 = new TimeSpan(randValue2);

            if (ts1.Equals(ts2))
            {
                TestLibrary.TestFramework.LogError("003.1", "Equals does not return false when compare with not equal instance");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] ts1.Ticks = " + ts1.Ticks + ", ts2.Ticks = " + ts2.Ticks + ", randValue1 = " + randValue1 + ", randValue2 = " + randValue2);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Example #21
0
        private void timer_TaskRunner_Tick(object sender, EventArgs e)
        {
            if (task_list != null)
            {
                foreach (scheduled_tasks task in task_list)
                {
                    if (task.Enabled)
                    {
                        if (task.Frequency.HasValue)
                        {
                            switch ((scheduled_tasks.frequencys)task.Frequency)
                            {
                                case scheduled_tasks.frequencys.Seconds:
                                    {
                                        if (task.StartTime.HasValue)
                                        {
                                            int sec = (int)(DateTime.Now - task.StartTime.Value).TotalSeconds;
                                            if (sec % task.RecurSeconds == 0)
                                                task.Run();
                                        }
                                        break;
                                    }
                                case scheduled_tasks.frequencys.Daily:
                                    {
                                        if (task.StartTime.HasValue)
                                        {
                                            //Logger.WriteToLog(Urgency.INFO,"totaldays:" + (DateTime.Now.Date - task.StartTime.Value.Date).TotalDays);
                                            if (task.RecurDays > 0 && ((DateTime.Now.Date - task.StartTime.Value.Date).TotalDays % task.RecurDays == 0))
                                            {
                                                TimeSpan TimeNowToTheSeconds = DateTime.Now.TimeOfDay;
                                                TimeNowToTheSeconds = new TimeSpan(TimeNowToTheSeconds.Hours, TimeNowToTheSeconds.Minutes, TimeNowToTheSeconds.Seconds); //remove milli seconds

                                                //Logger.WriteToLog(Urgency.INFO,string.Format("taskTofD: {0}, nowTofD: {1}", task.StartTime.Value.TimeOfDay, TimeNowToTheSeconds));
                                                if (TimeNowToTheSeconds.Equals(task.StartTime.Value.TimeOfDay))
                                                    task.Run();
                                            }
                                        }
                                        break;
                                    }
                                case scheduled_tasks.frequencys.Weekly:
                                    {
                                        if (task.StartTime.HasValue)
                                        {
                                            if (task.RecurWeeks > 0 && (((Int32)(DateTime.Now.Date - task.StartTime.Value.Date).TotalDays / 7) % task.RecurWeeks == 0))  //IF RUN THIS WEEK
                                            {
                                                if (ShouldRunToday(task))  //IF RUN THIS DAY
                                                {
                                                    TimeSpan TimeNowToTheSeconds = DateTime.Now.TimeOfDay;
                                                    TimeNowToTheSeconds = new TimeSpan(TimeNowToTheSeconds.Hours, TimeNowToTheSeconds.Minutes, TimeNowToTheSeconds.Seconds);

                                                    if (TimeNowToTheSeconds.Equals(task.StartTime.Value.TimeOfDay))
                                                        task.Run();
                                                }
                                            }
                                        }
                                        break;
                                    }
                                case scheduled_tasks.frequencys.Monthly:
                                    {
                                        if (task.StartTime.HasValue)
                                        {
                                            int monthsapart = ((DateTime.Now.Year - task.StartTime.Value.Year) * 12) + DateTime.Now.Month - task.StartTime.Value.Month;
                                            //Logger.WriteToLog(Urgency.INFO,string.Format("Months Apart: {0}", monthsapart));
                                            if (task.RecurMonth > 0 && monthsapart > -1 && monthsapart % task.RecurMonth == 0)  //IF RUN THIS Month
                                            {
                                                if (ShouldRunThisDayOfMonth(task))  //IF RUN THIS DAY
                                                {
                                                    TimeSpan TimeNowToTheSeconds = DateTime.Now.TimeOfDay;
                                                    TimeNowToTheSeconds = new TimeSpan(TimeNowToTheSeconds.Hours, TimeNowToTheSeconds.Minutes, TimeNowToTheSeconds.Seconds);

                                                    if (TimeNowToTheSeconds.Equals(task.StartTime.Value.TimeOfDay))
                                                        task.Run();
                                                }
                                            }
                                        }

                                        break;
                                    }
                                case scheduled_tasks.frequencys.Once:
                                    {
                                        if (task.StartTime.HasValue)
                                        {
                                            TimeSpan TimeNowToTheSeconds = DateTime.Now.TimeOfDay;
                                            TimeNowToTheSeconds = new TimeSpan(TimeNowToTheSeconds.Hours, TimeNowToTheSeconds.Minutes, TimeNowToTheSeconds.Seconds);

                                            if (TimeNowToTheSeconds.Equals(task.StartTime.Value.TimeOfDay))
                                                task.Run();
                                        }
                                        break;
                                    }
                            }
                        }
                    }
                }
            }
        }
Example #22
0
 /// <summary>
 /// Gets the units per day measurement based the given frame time and number of frames.
 /// </summary>
 /// <param name="frameTime">The work unit frame time.</param>
 /// <param name="frames">The number of frames in the work unit.</param>
 /// <returns>The units per day for the work unit.</returns>
 public static double GetUPD(TimeSpan frameTime, int frames)
 {
    double totalTime = (frameTime.TotalSeconds * frames);
    if (totalTime <= 0.0)
    {
       return 0.0;
    }
    return frameTime.Equals(TimeSpan.Zero) ? 0.0 : 86400 / totalTime;
 }
Example #23
0
 public static string FormatTime(TimeSpan ts)
 {
     string txt = "";
     if (ts.Equals(TimeSpan.Zero))
     {
         return "0 seconds";
     }
     if (ts.Days > 0)
     {
         txt += ts.Days.ToString() + " day" + (ts.Days == 1 ? "" : "s");
     }
     if (ts.Hours > 0)
     {
         if (txt.Length > 0)
         {
             txt += " ";
         }
         txt += ts.Hours.ToString() + " hour" + (ts.Hours == 1 ? "" : "s");
     }
     if (ts.Minutes > 0)
     {
         if (txt.Length > 0)
         {
             txt += " ";
         }
         txt += ts.Minutes.ToString() + " minute" + (ts.Minutes == 1 ? "" : "s");
     }
     if (ts.Seconds > 0)
     {
         if (txt.Length > 0)
         {
             txt += " ";
         }
         txt += ts.Seconds.ToString() + " second" + (ts.Seconds == 1 ? "" : "s");
     }
     return txt;
 }
Example #24
0
        void timer_Tick(object sender, EventArgs e)
        {
            try { FrameworkDispatcher.Update(); } catch { }
            local = local.Subtract(new TimeSpan(0,0,1));
            //if timeout, ring bell
            if(local.Equals(new TimeSpan(0,0,-1)))
            {
                ringbell();

                if (current == Status.work)
                {
                    //CurrentStatus.Text = "Revise and Rest";
                    local = BreakTime.Value.Value;
                    //local = new TimeSpan(0,0,2);
                    current = Status.play;
                    message = "Rest\n";
                }
                else
                {
                    //CurrentStatus.Text = "Start your work again!";
                    local = WorkTime.Value.Value;
                    //local = new TimeSpan(0,0,4);
                    current = Status.work;
                    message = "Work\n";
                }
            }
            ForOutput.Text = message + local.ToString();
            //CurrentStatus.Text = audioPlay.Source.ToString();
        }
Example #25
0
 public static DateRange PasadoDesdeHoy(TimeSpan periodo)
 {
     if (periodo.Equals(TimeSpan.MaxValue))
         return new DateRange(DateTime.MinValue, DateTime.Today);
     return new DateRange(DateTime.Today.Subtract(periodo), DateTime.Today);
 }
Example #26
0
 /// <summary>
 /// Get Units Per Day based on given Frame Time
 /// </summary>
 /// <param name="frameTime">Frame Time</param>
 public double GetUPD(TimeSpan frameTime)
 {
    return frameTime.Equals(TimeSpan.Zero) ? 0.0 : 86400 / (frameTime.TotalSeconds * Frames);
 }
 private bool Compare(TimeSpan a, TimeSpan b)
 {
     switch (Op)
     {
         case Comparator.Eq:
             return a.Equals(b);
         case Comparator.Ne:
             return !a.Equals(b);
         case Comparator.Lt:
             return a < b;
         case Comparator.Gt:
             return a > b;
         case Comparator.Le:
             return a <= b;
         case Comparator.Ge:
             return a >= b;
         default:
             if (BoostLog.Instance != null)
                 BoostLog.Instance.WriteEntry(EventLogEntryType.Error,
                                              string.Format("Illegal TimeSpan comparison ({0})\nVal1 = {1}\nVal2 = {2}", Op, a, b),
                                              "", _alias);
             return false;
     }
 }
Example #28
0
    public static void TestEquals(TimeSpan timeSpan1, object obj, bool expected)
    {
        if (obj is TimeSpan)
        {
            TimeSpan timeSpan2 = (TimeSpan)obj;
            Assert.Equal(expected, TimeSpan.Equals(timeSpan1, timeSpan2));
            Assert.Equal(expected, timeSpan1.Equals(timeSpan2));
            Assert.Equal(expected, timeSpan1 == timeSpan2);
            Assert.Equal(!expected, timeSpan1 != timeSpan2);

            Assert.Equal(expected, timeSpan1.GetHashCode().Equals(timeSpan2.GetHashCode()));
        }
        Assert.Equal(expected, timeSpan1.Equals(obj));
    }
	public void TestEquals ()
	{
		TimeSpan t1 = new TimeSpan (1);
		TimeSpan t2 = new TimeSpan (2);
		string s = "justastring";

		AssertEquals ("A1", true, t1.Equals (t1));
		AssertEquals ("A2", false, t1.Equals (t2));
		AssertEquals ("A3", false, t1.Equals (s));
		AssertEquals ("A4", false, t1.Equals (null));
		AssertEquals ("A5", true, TimeSpan.Equals (t1, t1));
		AssertEquals ("A6", false, TimeSpan.Equals (t1, t2));
		AssertEquals ("A7", false, TimeSpan.Equals (t1, null));
		AssertEquals ("A8", false, TimeSpan.Equals (t1, s));
		AssertEquals ("A9", false, TimeSpan.Equals (s, t2));
		AssertEquals ("A10", true, TimeSpan.Equals (null,null));
	}
Example #30
0
        internal async Task<HttpSourceResult> GetAsync(string uri, string cacheKey, TimeSpan cacheAgeLimit)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();

            var result = await TryCache(uri, cacheKey, cacheAgeLimit);
            if (result.Stream != null)
            {
                _report.WriteLine(string.Format("  {0} {1}", "CACHE".Green(), uri));
                return result;
            }

            _report.WriteLine(string.Format("  {0} {1}.", "GET".Yellow(), uri));

            var request = new HttpRequestMessage(HttpMethod.Get, uri);
            if (_userName != null)
            {
                var token = Convert.ToBase64String(Encoding.ASCII.GetBytes(_userName + ":" + _password));
                request.Headers.Authorization = new AuthenticationHeaderValue("Basic", token);
            };

#if K10
            if (_proxyUserName != null)
            {
                var proxyToken = Convert.ToBase64String(Encoding.ASCII.GetBytes(_proxyUserName + ":" + _proxyPassword));
                request.Headers.ProxyAuthorization = new AuthenticationHeaderValue("Basic", proxyToken);
            }
#endif

            var response = await _client.SendAsync(request);

            var newFile = result.CacheFileName + "-new";

            // Zero value of TTL means we always download the latest package
            // So we write to a temp file instead of cache
            if (cacheAgeLimit.Equals(TimeSpan.Zero))
            {
                result.CacheFileName = Path.GetTempFileName();
                newFile = Path.GetTempFileName();
            }

            // The update of a cached file is divided into two steps:
            // 1) Delete the old file. 2) Create a new file with the same name.
            // To prevent race condition among multiple processes, here we use a lock to make the update atomic.
            await ConcurrencyUtilities.ExecuteWithFileLocked(result.CacheFileName, async _ =>
            {
                using (var stream = CreateAsyncFileStream(
                    newFile,
                    FileMode.Create,
                    FileAccess.ReadWrite,
                    FileShare.ReadWrite | FileShare.Delete))
                {
                    await response.Content.CopyToAsync(stream);
                    await stream.FlushAsync();
                }

                if (File.Exists(result.CacheFileName))
                {
                    // Process B can perform deletion on an opened file if the file is opened by process A
                    // with FileShare.Delete flag. However, the file won't be actually deleted until A close it.
                    // This special feature can cause race condition, so we never delete an opened file.
                    if (!IsFileAlreadyOpen(result.CacheFileName))
                    {
                        File.Delete(result.CacheFileName);
                    }
                }

                // If the desitnation file doesn't exist, we can safely perform moving operation.
                // Otherwise, moving operation will fail.
                if (!File.Exists(result.CacheFileName))
                {
                    File.Move(
                        newFile,
                        result.CacheFileName);
                }

                // Even the file deletion operation above succeeds but the file is not actually deleted,
                // we can still safely read it because it means that some other process just updated it
                // and we don't need to update it with the same content again.
                result.Stream = CreateAsyncFileStream(
                    result.CacheFileName,
                    FileMode.Open,
                    FileAccess.Read,
                    FileShare.Read | FileShare.Delete);

                return 0;
            });

            _report.WriteLine(string.Format("  {1} {0} {2}ms", uri, response.StatusCode.ToString().Green(), sw.ElapsedMilliseconds.ToString().Bold()));

            return result;
        }
Example #31
0
 /// <summary>
 /// Gets the time zone by offset.
 /// </summary>
 /// <param name="utcOffsetTime">The utc offset time.</param>
 /// <returns></returns>
 public static TzTimeZone GetTimeZoneByOffset(TimeSpan utcOffsetTime)
 {
     if (utcOffsetTime.Equals(TimeSpan.Zero))
     {
         return TzTimeZone.ZoneUTC;
     }
     else
     {
         // We pick the most "well-known" time zone in the set for each offset
         string zoneName;
         if (s_mainTimeZones.TryGetValue(DateTimeUtlities.ConvertTimeSpanToDouble(utcOffsetTime), out zoneName))
         {
             return GetTimeZone(zoneName);
         }
         else
         {
             // TODO do a manual search
         }
     }
     throw new TzDatabase.TzException("Cannot find time zone with UTC offset {0}.", utcOffsetTime);
 }
Example #32
0
        internal async Task<HttpSourceResult> GetAsync(string uri, string cacheKey, TimeSpan cacheAgeLimit,
            Action<Stream> ensureValidContents = null, bool throwNotFound = true)
        {
            try
            {
                await _throttle.WaitAsync();

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

                var result = await TryCache(uri, cacheKey, cacheAgeLimit);
                if (result.Stream != null)
                {
                    _reports.Quiet.WriteLine(string.Format("  {0} {1}", "CACHE".Green(), uri));
                    return result;
                }

                _reports.Quiet.WriteLine(string.Format("  {0} {1}", "GET".Yellow(), uri));

                var request = new HttpRequestMessage(HttpMethod.Get, uri);
                if (_userName != null)
                {
                    var token = Convert.ToBase64String(Encoding.ASCII.GetBytes(_userName + ":" + _password));
                    request.Headers.Authorization = new AuthenticationHeaderValue("Basic", token);
                };

                // Write the response to a file and use the file stream to avoid memory explosion
                using (var responseStream = new FileStream(
                    Path.GetTempFileName(),
                    FileMode.Create,
                    FileAccess.ReadWrite,
                    FileShare.None,
                    bufferSize: 8192,
                    options: FileOptions.Asynchronous | FileOptions.DeleteOnClose))
                {
                    HttpStatusCode statusCode;

                    using (var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
                    {
                        if (!throwNotFound && response.StatusCode == HttpStatusCode.NotFound)
                        {
                            _reports.Quiet.WriteLine(
                                $"  {response.StatusCode.ToString().Green()} {uri} {sw.ElapsedMilliseconds.ToString().Bold()}ms");
                            return new HttpSourceResult();
                        }

                        response.EnsureSuccessStatusCode();
                        statusCode = response.StatusCode;
                        await response.Content.CopyToAsync(responseStream);
                    }

                    responseStream.Seek(0, SeekOrigin.Begin);
                    ensureValidContents?.Invoke(responseStream);

                    var newFile = result.CacheFileName + "-new";

                    // Zero value of TTL means we always download the latest package
                    // So we write to a temp file instead of cache
                    if (cacheAgeLimit.Equals(TimeSpan.Zero))
                    {
                        result.CacheFileName = Path.GetTempFileName();
                        newFile = Path.GetTempFileName();
                    }

                    // The update of a cached file is divided into two steps:
                    // 1) Delete the old file. 2) Create a new file with the same name.
                    // To prevent race condition among multiple processes, here we use a lock to make the update atomic.
                    await ConcurrencyUtilities.ExecuteWithFileLocked(result.CacheFileName, action: async _ =>
                    {
                        using (var stream = CreateAsyncFileStream(
                            newFile,
                            FileMode.Create,
                            FileAccess.ReadWrite,
                            FileShare.ReadWrite | FileShare.Delete))
                        {
                            responseStream.Seek(0, SeekOrigin.Begin);
                            await responseStream.CopyToAsync(stream);
                            await stream.FlushAsync();
                        }

                        if (File.Exists(result.CacheFileName))
                        {
                        // Process B can perform deletion on an opened file if the file is opened by process A
                        // with FileShare.Delete flag. However, the file won't be actually deleted until A close it.
                        // This special feature can cause race condition, so we never delete an opened file.
                        if (!IsFileAlreadyOpen(result.CacheFileName))
                            {
                                File.Delete(result.CacheFileName);
                            }
                        }

                        // If the destination file doesn't exist, we can safely perform moving operation.
                        // Otherwise, moving operation will fail.
                        if (!File.Exists(result.CacheFileName))
                        {
                            File.Move(
                                newFile,
                                result.CacheFileName);
                        }

                        // Even the file deletion operation above succeeds but the file is not actually deleted,
                        // we can still safely read it because it means that some other process just updated it
                        // and we don't need to update it with the same content again.
                        result.Stream = CreateAsyncFileStream(
                            result.CacheFileName,
                            FileMode.Open,
                            FileAccess.Read,
                            FileShare.Read | FileShare.Delete);

                        return 0;
                    });

                    _reports.Quiet.WriteLine(string.Format("  {1} {0} {2}ms", uri, statusCode.ToString().Green(), sw.ElapsedMilliseconds.ToString().Bold()));
                }

                return result;
            }
            finally
            {
                _throttle.Release();
            }
        }
Example #33
0
    public bool PosTest4()
    {
        bool retVal = true;
        long randValue = 0;

        TestLibrary.TestFramework.BeginScenario("PosTest4: Equals should return false when compare with null reference");

        try
        {
            randValue = TestLibrary.Generator.GetInt64(-55);

            TimeSpan ts = new TimeSpan(randValue);

            if (ts.Equals(null))
            {
                TestLibrary.TestFramework.LogError("004.1", "Equals does not return false when compare with null reference");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] ts.Ticks = " + ts.Ticks + ", randValue = " + randValue);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }