public static DateTime DateAdd(DateInterval Interval, double Number, DateTime DateValue)
        {
            int years = (int) Math.Round(Conversion.Fix(Number));
            switch (Interval)
            {
                case DateInterval.Year:
                    return CurrentCalendar.AddYears(DateValue, years);

                case DateInterval.Quarter:
                    return DateValue.AddMonths(years * 3);

                case DateInterval.Month:
                    return CurrentCalendar.AddMonths(DateValue, years);

                case DateInterval.DayOfYear:
                case DateInterval.Day:
                case DateInterval.Weekday:
                    return DateValue.AddDays((double) years);

                case DateInterval.WeekOfYear:
                    return DateValue.AddDays(years * 7.0);

                case DateInterval.Hour:
                    return DateValue.AddHours((double) years);

                case DateInterval.Minute:
                    return DateValue.AddMinutes((double) years);

                case DateInterval.Second:
                    return DateValue.AddSeconds((double) years);
            }
            throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[] { "Interval" }));
        }
        public void AggregatesPeriodInCountModeWithDailyData()
        {
            TradeBar consolidated = null;
            var period = TimeSpan.FromDays(1);
            var consolidator = new TradeBarConsolidator(2);
            consolidator.DataConsolidated += (sender, bar) =>
            {
                consolidated = bar;
            };

            var reference = new DateTime(2015, 04, 13);
            consolidator.Update(new TradeBar { Time = reference, Period = period});
            Assert.IsNull(consolidated);

            consolidator.Update(new TradeBar { Time = reference.AddDays(1), Period = period });
            Assert.IsNotNull(consolidated);

            Assert.AreEqual(TimeSpan.FromDays(2), consolidated.Period);
            consolidated = null;

            consolidator.Update(new TradeBar { Time = reference.AddDays(2), Period = period });
            Assert.IsNull(consolidated);

            consolidator.Update(new TradeBar { Time = reference.AddDays(3), Period = period });
            Assert.IsNotNull(consolidated);

            Assert.AreEqual(TimeSpan.FromDays(2), consolidated.Period);
        }
示例#3
0
文件: Date.cs 项目: KatoTek/Encompass
        /// <summary>
        ///     Adds a specified number of business <paramref name="days" /> to a <paramref name="dateTime" /> taking into account
        ///     weekends and holidays
        /// </summary>
        /// <param name="dateTime">The DateTime to add the business days to</param>
        /// <param name="days">The number of business days to add</param>
        /// <param name="weekendDays">
        ///     The days of the week to consider as the weekend. These days of the week will be excluded when
        ///     determining business days.
        /// </param>
        /// <param name="holidays">Holidays dates to exclude when determining business days</param>
        /// <returns>The new DateTime after adding the specified number of business <paramref name="days" /></returns>
        public static DateTime AddBusinessDays(DateTime dateTime, double days, DayOfWeek[] weekendDays, params DateTime[] holidays)
        {
            if (Abs(days) < TOLERANCE)
                return dateTime;

            var wholeDays = Truncate(days);
            var partDay = Abs(wholeDays) > TOLERANCE
                              ? days%wholeDays
                              : 0;
            var range = Abs(wholeDays);
            var direction = Sign(wholeDays);

            for (var wholeDay = 0; wholeDay < range; wholeDay++)
            {
                do
                    dateTime = dateTime.AddDays(direction); while (IsOutsideBusinessDays(dateTime, weekendDays, holidays));
            }

            if (IsOutsideBusinessDays(dateTime, weekendDays, holidays))
                dateTime = dateTime.AddDays(direction);

            dateTime = dateTime.AddDays(partDay);
            while (IsOutsideBusinessDays(dateTime, weekendDays, holidays))
                dateTime = dateTime.AddDays(direction);

            return dateTime;
        }
示例#4
0
		public void UpdateTimespan ()
		{
			TodaySpan = DateTime.Today;
			YesterdaySpan = TodaySpan.AddDays (-1);
			ThisWeekSpan = TodaySpan.AddDays (-((int)DateTime.Now.DayOfWeek));
			LastWeekSpan = ThisWeekSpan.AddDays (-7);
		}
示例#5
0
        public DateTime GetLastCandleClose(DateTime timeFrom, out DateTime candleOpenTime, out int nextCandlePeriod)
        {
            if (BarSettings.Intervals.Count == 1)
                if (BarSettings.Intervals[0] == 1440 * 5 && BarSettings.StartMinute == 0)
                {
                    // отдельно обработка недельного ТФ
                    candleOpenTime = timeFrom.Date;
                    if (candleOpenTime.DayOfWeek != DayOfWeek.Monday)
                    {
                        var day = (int) candleOpenTime.DayOfWeek;
                        var shiftBehind = day < 6 && day > 0 ? 1 - day : day == 0 ? -6 : -5;
                        candleOpenTime = candleOpenTime.AddDays(shiftBehind);
                    }
                    nextCandlePeriod = 0;
                    return candleOpenTime.AddDays(7);
                }

            nextCandlePeriod = 0;
            var startTime = timeFrom.Date.AddMinutes(BarSettings.StartMinute);
            if (startTime > timeFrom)
                startTime = startTime.AddDays(-1);
            var endTime = startTime;
            while (endTime <= timeFrom)
            {
                startTime = endTime;
                endTime = startTime.AddMinutes(BarSettings.Intervals[nextCandlePeriod]);
                nextCandlePeriod++;
                if (nextCandlePeriod == BarSettings.Intervals.Count)
                    nextCandlePeriod = 0;
            }
            candleOpenTime = startTime;
            return endTime;
        }
示例#6
0
文件: PayPeriodT.cs 项目: mnisl/OD
		/// <summary>Returns existing payperiod if it exists, otherwise inserts and returns a new payperiod. Throws exception if payperiod overlaps existing payperiod.</summary>
		public static PayPeriod CreateTwoWeekPayPeriodIfNotExists(DateTime start){
			PayPeriod ppNew=new PayPeriod();
			ppNew.DateStart=start;
			ppNew.DateStop=start.AddDays(13);
			ppNew.DatePaycheck=start.AddDays(16);
			//check for identical or overlapping pay periods
			PayPeriods.RefreshCache();
			foreach(PayPeriod ppInDb in PayPeriods.List) {
				if(ppInDb.DateStart == ppNew.DateStart && ppInDb.DateStop == ppNew.DateStop	&& ppInDb.DatePaycheck == ppNew.DatePaycheck){
					//identical pay period already exists.
					return ppInDb;
				}
				//if(pp.DateStart == payP.DateStart && pp.DateStop == payP.DateStop	&& pp.DatePaycheck != payP.DatePaycheck) {
				//  //identical pay period already exists, just with a different pay check date.
				//  //This is a seperate check because it may be important in the future.
				//  continue;
				//}
				if(ppInDb.DateStop > ppNew.DateStart && ppInDb.DateStart < ppNew.DateStop) {
					//pay periods overlap
					throw new Exception("Error inserting pay period. New Pay period overlaps existing pay period.\r\n");
				}
			}
			PayPeriods.Insert(ppNew);
			return ppNew;
		}
示例#7
0
        public static DateTime CalculateExpiredDate(DateTime createDate, int value, string typeOfValue)
        {
            DateTime usedDay = createDate;

            switch (typeOfValue)
            {
                case DEFAULT_TYPE_DAY:
                    usedDay = createDate.AddDays(value);
                    break;

                case DEFAULT_TYPE_MONTH:
                    usedDay = createDate.AddMonths(value);
                    break;

                case DEFAULT_TYPE_YEAR:
                    usedDay = createDate.AddYears(value);
                    break;

                default:
                    usedDay = createDate.AddDays(value);
                    break;
            }

            return usedDay;
        }
示例#8
0
        private string dealTradMonth(DateTime now)//用日期計算出交易月份是哪一個月
        {
            // 本月第一天
            DateTime firstDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0);

            // 找到第一個星期三
            int wk;//星期幾

            wk = int.Parse(firstDay.DayOfWeek.ToString("d"));

            while (wk != 3)
            {
                firstDay = firstDay.AddDays(1);
                wk = (wk + 1) % 7;
            }

            DateTime thridWeekWendesday = firstDay.AddDays(14);

            if (now.Day > thridWeekWendesday.Day)
            {
                return Convert.ToString(now.Month + 1);
            }
            else
            {
                return Convert.ToString(now.Month);
            }


        }//end dealTradMonth
示例#9
0
 public static void GetWeek(int nYear, int nNumWeek, out    DateTime dtWeekStart, out    DateTime dtWeekeEnd)
 {
     DateTime dt = new DateTime(nYear, 1, 1);
     dt = dt + new TimeSpan((nNumWeek - 1) * 7, 0, 0, 0);
     dtWeekStart = dt.AddDays(-(int)dt.DayOfWeek + (int)DayOfWeek.Monday);
     dtWeekeEnd = dt.AddDays((int)DayOfWeek.Saturday - (int)dt.DayOfWeek + 1);
 }
        public void EndOfWeek_SendDate()
        {
            var baseDate = DateTime.Now;
            var expectedDate = new DateTime(baseDate.Year, baseDate.Month, baseDate.Day, 23, 59, 59, 999, baseDate.Kind);
            var lastWeekDay = DevUtils.DateTimeExtensions.BaseDateTimeExtensions.GetDefaultLastWeekDay();
            var lastWeekBusiness = DevUtils.DateTimeExtensions.BaseDateTimeExtensions.GetDefaultLastWeekBusinessDay();

            while (true)
            {
                if (expectedDate.DayOfWeek == lastWeekDay)
                    break;

                expectedDate = (int)lastWeekDay > (int)expectedDate.DayOfWeek
                    ? expectedDate.AddDays(1)
                    : expectedDate.AddDays(-1);
            }
            Assert.AreEqual(expectedDate, baseDate.EndOfWeek(), "Error getting end of week");

            lastWeekDay = DayOfWeek.Thursday;
            DevUtils.DateTimeExtensions.BaseDateTimeExtensions.SetDefaultLastDay(lastWeekDay, lastWeekBusiness);
            expectedDate = new DateTime(baseDate.Year, baseDate.Month, baseDate.Day, 23, 59, 59, 999, baseDate.Kind);
            while (true)
            {
                if (expectedDate.DayOfWeek == lastWeekDay)
                    break;

                expectedDate = (int)lastWeekDay > (int)expectedDate.DayOfWeek
                    ? expectedDate.AddDays(1)
                    : expectedDate.AddDays(-1);
            }
            Assert.AreEqual(expectedDate, baseDate.EndOfWeek(), "Error getting end of week");
        }
示例#11
0
		public DateTime GetNextBusinessDay(DateTime date, int daysToAdd)
		{
			if (daysToAdd == 0)
				return date.Date.AddHours(StartHour);

			int foundWorkingDays = 0;

			if (IsAfterBusinessHours(date))
			{
				foundWorkingDays += daysToAdd > 0 ? -1 : 1;
			}

			while (foundWorkingDays < Math.Abs(daysToAdd))
			{
				date = daysToAdd > 0 ? date.AddDays(1) : date.AddDays(-1);

				if (IsBusinessDay(date))
				{
					foundWorkingDays++;
				}
			}

			if (IsAfterBusinessHours(date) || IsBeforeBusinessHours(date))
				return date.Date.AddHours(StartHour);
			else
				return date;
		}
示例#12
0
        public override bool OnPrePublish(IWin32Window dialogOwner, IProperties properties,
                                          IPublishingContext publishingContext, bool publish)
        {
            var info = (BlogPost) publishingContext.PostInfo;

            //look at the publish date.
            if (!info.HasDatePublishedOverride)
            {
                var nextPubDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                nextPubDate = GetNextDayOccurrence(DayOfWeek.Tuesday, nextPubDate);

                var reader = new JsonTextReader(reader: File.OpenText("Plugins\\Throttle.json"));
                var json = new Newtonsoft.Json.JsonSerializer();

                var config = json.Deserialize<Configuration>(reader);
                var wrapper = new MetaWeblogWrapper(config.Url, config.Username, config.Password);
                List<Post> recentPosts = wrapper.GetRecentPosts(10).ToList();
                while (recentPosts.Any(p => p.DateCreated >= nextPubDate && p.DateCreated < nextPubDate.AddDays(1)))
                {
                    nextPubDate = GetNextDayOccurrence(DayOfWeek.Tuesday, nextPubDate.AddDays(1));
                }
                var pubDate = new DateTime(nextPubDate.Year, nextPubDate.Month, nextPubDate.Day, 9, 0, 0);
                info.DatePublished = pubDate;
                info.DatePublishedOverride = pubDate;
            }
            return base.OnPrePublish(dialogOwner, properties, publishingContext, publish);
        }
 private static DateTime? GetExpirationDateForLeguminousCulture(DateTime landingdate, string culturetype)
 {
     switch (culturetype)
     {
         case "Боб обыкновенный":
             return landingdate.AddDays(65);
         case "Горох":
             return landingdate.AddDays(90);
         case "Люпин":
             return landingdate.AddDays(115);
         case "Фасоль":
             return landingdate.AddDays(105);
         case "Боб соевый":
             return landingdate.AddDays(75);
         case "Горошек(вика)":
             return landingdate.AddDays(135);
         case "Боб мунг":
             return landingdate.AddDays(90);
         case "Чечевица":
             return landingdate.AddDays(95);
         case "Турецкий горох":
             return landingdate.AddDays(155);
         case "Чина":
             return landingdate.AddDays(98);
     }
     return DateTime.Now;
 }
示例#14
0
		private ObservableCollection<GanttBaselineTask> GetTasks(DateTime date)
		{
			var ganttAPI = new GanttBaselineTask()
			{
				Start = date,
				End = date.AddDays(2),
				Title = "Design public API",
				Description = "Description: Design public API",
				StartPlannedDate = date.AddDays(1),
				EndPlannedDate = date.AddDays(2.5)
			};
			var ganttRendering = new GanttBaselineTask()
			{
				Start = date.AddDays(2).AddHours(8),
				End = date.AddDays(4),
				Title = "Gantt Rendering",
				Description = "Description: Gantt Rendering",
				StartPlannedDate = date.AddDays(3),
				EndPlannedDate = date.AddDays(3).AddHours(12)
			};
			var ganttDemos = new GanttBaselineTask()
			{
				Start = date.AddDays(4.5),
				End = date.AddDays(7),
				Title = "Gantt Demos",
				Description = "Description: Gantt Demos",
				StartPlannedDate = date.AddDays(5),
				EndPlannedDate = date.AddDays(6)
			};
			var milestone = new GanttBaselineTask()
			{
				Start = date.AddDays(7),
				End = date.AddDays(7).AddHours(1),
				Title = "Review",
				Description = "Description: Review",
				IsMilestone = true,
				StartPlannedDate = date.AddDays(7),
				EndPlannedDate = date.AddDays(7).AddHours(15)
			};

			ganttRendering.Dependencies.Add(new Dependency() { FromTask = ganttAPI });
			ganttDemos.Dependencies.Add(new Dependency() { FromTask = ganttRendering });

			var iterationTask = new GanttBaselineTask()
			{
				Start = date,
				End = date.AddDays(7),
				Title = "Iteration 1",
				Children = { ganttAPI, ganttRendering, ganttDemos, milestone },
				StartPlannedDate = date
			};

			var iterationTaskEndPlannedDate = GetInterationPlannedDateEnd(iterationTask.Children, date);

			iterationTask.EndPlannedDate = iterationTaskEndPlannedDate;

			ObservableCollection<GanttBaselineTask> tasks = new ObservableCollection<GanttBaselineTask>() { iterationTask };

			return tasks;
		}
示例#15
0
文件: Weekday.cs 项目: burstas/rmps
        public override DateTime Next(DateTime time, out bool changed)
        {
            changed = false;

            if (Values.Count < 1)
            {
                return time;
            }
            if (Type == CGtd.DATES_TYPE_EACH)
            {
                return time.AddDays(Values[0]);
            }
            if (Type == CGtd.DATES_TYPE_WHEN)
            {
                int idx = (int)time.DayOfWeek;
                int tmp = NextValue(idx, changed);
                if (tmp > 0)
                {
                    return time.AddDays(tmp);
                }
                if (tmp < 0)
                {
                    changed = true;
                    return time.AddDays(7 + Values[0] - idx);
                }
            }
            return time;
        }
    public DateTime GetNextWakeupTime(DateTime earliestWakeupTime)
    {
      IPowerScheduler ps = GlobalServiceProvider.Instance.Get<IPowerScheduler>();
      EPGWakeupConfig cfg = ps.Settings.GetSetting("RebootConfig").Get<EPGWakeupConfig>();
      DateTime now = DateTime.Now;

      // The earliest wakeup time cannot be in the past
      if (earliestWakeupTime < now)
        earliestWakeupTime = now;

      // Start with the earliest possible day
      DateTime nextRun = new DateTime(earliestWakeupTime.Year, earliestWakeupTime.Month, earliestWakeupTime.Day, cfg.Hour, cfg.Minutes, 0);

      // If the wakeup time is before the earliest wakeup time or if there already was a reboot on this day then take the next day
      if (nextRun < earliestWakeupTime || cfg.LastRun.Date >= nextRun.Date)
        nextRun = nextRun.AddDays(1);

      // Try the next 7 days
      for (int i = 0; i < 7; i++)
      {
        // Check if this day is configured for reboot
        if (ShouldRun(cfg.Days, nextRun.DayOfWeek))
          return nextRun;

        nextRun = nextRun.AddDays(1);
      }

      // Found no day configured for reboot
      return DateTime.MaxValue;
    }
示例#17
0
        public static DateTime GetBusinessDayShifted(DateTime referanceDate, int shiftInDays)
         {

             int ShiftSign = Math.Sign(shiftInDays);
             int ShiftInDaysAbs = Math.Abs(shiftInDays);

             List<DateTime> businessDays;
             DateTime BusinessDayOut;


             int ShiftInCalDaysAbs = (int)(Math.Max(Math.Ceiling((double)ShiftInDaysAbs * 7 / 5), ShiftInDaysAbs + 5));
             int ShiftInCalDays = ShiftInCalDaysAbs * ShiftSign;

             if (ShiftSign < 0)
             {
                 businessDays = CalendarUtilities.BusinessDays.GetBusinessDays(referanceDate.AddDays(ShiftInCalDays), referanceDate);
                 businessDays.Remove(referanceDate);
                 BusinessDayOut = businessDays[businessDays.Count - ShiftInDaysAbs];
             }

             else
             {
                 businessDays = CalendarUtilities.BusinessDays.GetBusinessDays(referanceDate, referanceDate.AddDays(ShiftInCalDays));
                 businessDays.Remove(referanceDate);
                 BusinessDayOut = businessDays[shiftInDays - 1];
             }

             return BusinessDayOut;
         }
示例#18
0
        private static int CountDays(DateTime finalDay, ref DateTime currentDay, List<DateTime> holidays)
        {
            int daysElapsed = 0;

            while (currentDay <= finalDay)
            {
                if (currentDay.DayOfWeek != DayOfWeek.Saturday && currentDay.DayOfWeek != DayOfWeek.Sunday)
                {
                    daysElapsed++;
                    currentDay = currentDay.AddDays(1);
                }
                else
                {
                    currentDay = currentDay.AddDays(1);
                }

                for (int i = 0; i < holidays.Count; i++)
                {
                    if (currentDay == holidays[i])
                    {
                        daysElapsed--;
                        break;
                    }
                }
            }

            return daysElapsed;
        }
示例#19
0
        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            initSchudule();
            ListView list;
            firstDayOfWeek = dateTimePicker.Value.AddDays(-((int)dateTimePicker.Value.DayOfWeek));
            dictShifts = dbConnector.Instance.getAllShifts(firstDayOfWeek.AddDays(-1).ToString("MM/dd/yyyy"), firstDayOfWeek.AddDays(6).ToString("MM/dd/yyyy"));
            foreach (Shift shift in dictShifts.Values)
            {
                list = null;
                try
                {
                    list = dictListView[shift.getShiftDay() + "_" + shift.getShift()];
                }
                catch (KeyNotFoundException)
                {
                    MessageBox.Show(shift.getShiftDay() + "_" + shift.getShift() + " is an Invalid Key");
                }

                foreach (Employee employeeTemp in shift.getEmployees())
                {
                    ListViewItem employeeItem = new ListViewItem(employeeTemp.getNameFirst() + " " + employeeTemp.getNameLast());
                    employeeItem.SubItems.Add(employeeTemp.getIdNumber().ToString());
                    employeeItem.SubItems.Add(PermissiomLevels.GetNameByPrem(employeeTemp.getPermissionLevel()));
                    employeeItem.SubItems.Add(employeeTemp.getEmailAddress());
                    employeeItem.SubItems.Add(employeeTemp.getPhoneNumber());
                    employeeItem.SubItems.Add(employeeTemp.getSallaryPerHour().ToString());
                    list.Items.Add(employeeItem);
                }

                list.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
                list.Enabled = true;
            }
        }
示例#20
0
        public void CreateTest()
        {
            //Arrange
            var startDate = new DateTime(123456789);
            var finishdate1 = startDate.AddDays(1);
            var finishdate2 = startDate.AddDays(345);
            var dayInterval = new Interval() {Start = startDate, Finish = finishdate1};
            var bigInterval = new Interval() {Start = startDate, Finish = finishdate2};

            var filterManager = new Mock<IFiltersManager>();
            var reportAccumulator = new Mock<IReportAccumulator>();
            var statisticsService = new Mock<IStatisticsService>();
            var reportsService = new Mock<IStandardReportService>();

            var compilerFactory = new CompilerFactory(filterManager.Object, reportAccumulator.Object, statisticsService.Object, reportsService.Object);
            
            //Act
            var statiscticsCompiler = compilerFactory.Create(dayInterval);
            var reportsCompiler = compilerFactory.Create(bigInterval);
            var allDaysReportsCompiler = compilerFactory.Create(null);

            //Assert
            Assert.IsInstanceOfType(statiscticsCompiler, typeof(StatisticsCompiler));
            Assert.IsInstanceOfType(reportsCompiler, typeof(ReportsCompiler));
            Assert.IsInstanceOfType(allDaysReportsCompiler, typeof(AllDaysReportsCompiler));
        }
示例#21
0
        private int GetBusinessDays(DateTime start, DateTime end)
        {
            if (start.DayOfWeek == DayOfWeek.Saturday)
            {
                start = start.AddDays(2);
            }
            else if (start.DayOfWeek == DayOfWeek.Sunday)
            {
                start = start.AddDays(1);
            }

            if (end.DayOfWeek == DayOfWeek.Saturday)
            {
                end = end.AddDays(-1);
            }
            else if (end.DayOfWeek == DayOfWeek.Sunday)
            {
                end = end.AddDays(-2);
            }

            int diff = (int)end.Subtract(start).TotalDays + 1;

            int result = diff / 7 * 5 + diff % 7;

            if (end.DayOfWeek < start.DayOfWeek)
            {
                return result - 2;
            }
            else
            {
                return result;
            }
        }
示例#22
0
        public Tarifa(DataRow dr,DateTime hora)
        {
            id = int.Parse(dr["id"].ToString());
            if (id > 0)
            {
                categoriaId = int.Parse(dr["catId"].ToString());
                DateTime fecha = hora;
                desde = new DateTime(fecha.Year, fecha.Month, fecha.Day, DateTime.Parse(dr["desde"].ToString()).Hour, DateTime.Parse(dr["desde"].ToString()).Minute, 0);
                int diferenciaDias = Math.Abs(Calendario.nroDia(desde) - int.Parse(dr["dia"].ToString()));
                if (diferenciaDias != 0)
                {
                    if (Calendario.nroDia(desde.AddDays(-1)) == int.Parse(dr["dia"].ToString()))
                        desde = desde.AddDays(-1);
                    if (Calendario.nroDia(desde.AddDays(1)) == int.Parse(dr["dia"].ToString()))
                        desde = desde.AddDays(1);
                }
                if (dr["hasta"].ToString() != "")
                {
                    hasta = new DateTime(desde.Year, desde.Month, desde.Day, DateTime.Parse(dr["hasta"].ToString()).Hour, DateTime.Parse(dr["hasta"].ToString()).Minute, 0);
                    if (hasta.TimeOfDay < desde.TimeOfDay)
                        hasta = hasta.AddDays(1);
                }

                int.TryParse(dr["dia"].ToString(), out dia);
                int.TryParse(dr["duracion"].ToString(), out duracion);
                decimal.TryParse(dr["precio"].ToString(), out precio);
                decimal.TryParse(dr["precioMinuto"].ToString(), out precioMinuto);
                int.TryParse(dr["extension"].ToString(), out extension);
                decimal.TryParse(dr["extensionPrecio"].ToString(), out extensionPrecio);
                int.TryParse(dr["tolerancia"].ToString(), out tolerancia);
                decimal.TryParse(dr["precioTN"].ToString(), out precioTN);
                bool.TryParse(dr["pernocte"].ToString(), out pernocte);
            }
        }
        public JsonResult Next(int no, int locationId)
        {
            today = today.AddDays(no);

            GetDate();
            GetMonth();
            period = string.Format("{0}{1}", today.Year, bulan);
            IList<TenantSubterminalDailySales> dailySales = subTerminalRepo.FindTenantSubTerminalDailySaleByPeriod(today, locationId);
            var _previousDayDate = today.AddDays(-1);
            var _twoDaysBeforeDate = today.AddDays(-2);
            IList<TenantSubterminalDailySales> previousDay = subTerminalRepo.FindTenantSubTerminalDailySaleByPeriod(_previousDayDate, locationId);
            IList<TenantSubterminalDailySales> twoDaysBefore = subTerminalRepo.FindTenantSubTerminalDailySaleByPeriod(_twoDaysBeforeDate, locationId);
            SalesAmountDay salesAmount = new SalesAmountDay()
            {
                CompanyName = "",
                LocationId = locationId,
                TotalSaleIDR = subTerminalRepo.TotalTenanSubTerminalSalePerDay(dailySales).ToString("N"),
                TotalSaleUSD = dailySales.Sum<TenantSubterminalDailySales>(y => y.TotalSalesPerTenantInUSD).ToString("N"),
                Transactiondate = today.ToString("dd MMMM yyyy"),
                PreviousDay = _previousDayDate.ToString("dd MMMM yyyy"),
                TwoDaysBefore = _twoDaysBeforeDate.ToString("dd MMMM yyyy"),
                TotalSaleIDRPreviousDay = previousDay.Sum<TenantSubterminalDailySales>(y => y.TotalSalePerTenan).ToString("N"),
                TotalSaleUSDPreviousDay = previousDay.Sum<TenantSubterminalDailySales>(y => y.TotalSalesPerTenantInUSD).ToString("N"),
                TotalSaleIDRTwoDaysBefore = twoDaysBefore.Sum<TenantSubterminalDailySales>(y => y.TotalSalePerTenan).ToString("N"),
                TotalSaleUSDTwoDaysBefore = twoDaysBefore.Sum<TenantSubterminalDailySales>(y => y.TotalSalesPerTenantInUSD).ToString("N")

            };

            return Json(salesAmount, JsonRequestBehavior.AllowGet);
        }
        private void CreateWeeklyStatReportFor(string connectionString,string sqlQuery,string reportName)
        {
            startingTime = new DateTime(Year, UnixTimeStampUtility.GetMonthNumber(Month), 01); //initialize to day 01 of the given month.
            DateTime monthEndTime = new DateTime(Year, UnixTimeStampUtility.GetMonthNumber(Month), UnixTimeStampUtility.GetDaysInMonth(Month));
            List<Tuple<string, string>> uploadsDataPoints = new List<Tuple<string, string>>();
            int week = 1;
            using (var sqlConnection = new SqlConnection(connectionString))
            {
                using (var dbExecutor = new SqlExecutor(sqlConnection))
                {
                    sqlConnection.Open();

                    while (startingTime <= monthEndTime)
                    {
                        DateTime endTime = startingTime.AddDays(7);
                        if (endTime > monthEndTime) endTime = monthEndTime;
                        try
                        {
                            var count = dbExecutor.Query<Int32>(string.Format(sqlQuery, startingTime.ToString("yyyy-MM-dd"), endTime.ToString("yyyy-MM-dd"))).SingleOrDefault();
                            uploadsDataPoints.Add(new Tuple<string, string>("Week" + week++, count.ToString()));
                        }
                        catch (NullReferenceException)
                        {
                            uploadsDataPoints.Add(new Tuple<string, string>("Week" + week++, "0"));
                        }
                        
                        startingTime = startingTime.AddDays(7);
                    }
                }
            }
            JArray reportObject = ReportHelpers.GetJson(uploadsDataPoints);
            ReportHelpers.CreateBlob(ReportStorage, reportName + Month + "MonthlyReport.json", "dashboard", "application/json", ReportHelpers.ToStream(reportObject));
        }
        public void StartOfWeek_SendDate()
        {
            var baseDate = DateTime.Now;
            var expectedDate = new DateTime(baseDate.Year, baseDate.Month, baseDate.Day, 0, 0, 0, 0, baseDate.Kind);
            var firstWeekDay = DevUtils.DateTimeExtensions.BaseDateTimeExtensions.GetDefaultFirstWeekDay();
            var firstWeekBusiness = DevUtils.DateTimeExtensions.BaseDateTimeExtensions.GetDefaultFirstWeekBusinessDay();

            while (true)
            {
                if (expectedDate.DayOfWeek == firstWeekDay)
                    break;

                expectedDate = (int)firstWeekDay > (int)expectedDate.DayOfWeek
                    ? expectedDate.AddDays(1)
                    : expectedDate.AddDays(-1);
            }
            Assert.AreEqual(expectedDate, baseDate.StartOfWeek(), "Error getting start of week");

            firstWeekDay = DayOfWeek.Thursday;
            DevUtils.DateTimeExtensions.BaseDateTimeExtensions.SetDefaultFirstDay(firstWeekDay, firstWeekBusiness);
            expectedDate = new DateTime(baseDate.Year, baseDate.Month, baseDate.Day, 0, 0, 0, 0, baseDate.Kind);
            while (true)
            {
                if (expectedDate.DayOfWeek == firstWeekDay)
                    break;

                expectedDate = (int)firstWeekDay > (int)expectedDate.DayOfWeek
                    ? expectedDate.AddDays(1)
                    : expectedDate.AddDays(-1);
            }
            Assert.AreEqual(expectedDate, baseDate.StartOfWeek(), "Error getting start of week");
        }
示例#26
0
 private static void BuildReport()
 {
     string connectionString = ThemeRepositoryFactory.Default.ConnectionProvider.GetWriteConnectionString();
     //获取当前报表统计表中已经统计到的日期
     DateTime lastDate = new DateTime(2010, 5, 22);
     string cmdText = "SELECT MAX(ReportDate) FROM VisitorsDayReport";
     object result = SqlHelper.ExecuteScalar(connectionString, System.Data.CommandType.Text, cmdText);
     if (result != DBNull.Value && Convert.ToInt32(result) > 0)
     {
         lastDate = DateTime.ParseExact(result.ToString(), "yyyyMMdd", null).AddDays(1);
     }
     //开始统计从上个统计日到今天的所有数据
     while (lastDate < DateTime.Now.Date)
     {
         cmdText = string.Format(CMD_ALL_USER_COUNT, lastDate.ToString("yyyyMMdd"), lastDate.AddDays(1).ToString("yyyyMMdd"));
         int allUserCount = Convert.ToInt32(SqlHelper.ExecuteScalar(connectionString, System.Data.CommandType.Text, cmdText));
         cmdText = string.Format(CMD_OLD_USER_COUNT, lastDate.ToString("yyyyMMdd"), lastDate.AddDays(1).ToString("yyyyMMdd"));
         int oldUserCount = Convert.ToInt32(SqlHelper.ExecuteScalar(connectionString, System.Data.CommandType.Text, cmdText));
         cmdText = string.Format(CMD_INSERT_REPORT_DATA
             , allUserCount
             , oldUserCount
             , lastDate.ToString("yyyyMMdd")
             );
         SqlHelper.ExecuteNonQuery(connectionString, System.Data.CommandType.Text, cmdText);
         Console.WriteLine(string.Format("计算完成{0}日的统计,所有用户:{1},老用户:{2}", lastDate, allUserCount, oldUserCount));
         lastDate = lastDate.AddDays(1);
     }
 }
 static void RemoveWeekendDays(ref DateTime start, ref DateTime end)
 {
     if (start.DayOfWeek == DayOfWeek.Saturday) start = start.AddDays(2);
     if (start.DayOfWeek == DayOfWeek.Sunday) start = start.AddDays(1);
     if (end.DayOfWeek == DayOfWeek.Saturday) end = end.AddDays(-1);
     if (end.DayOfWeek == DayOfWeek.Sunday) end = end.AddDays(-2);
 }
        public void FiltersExpiryRange()
        {
            var time = new DateTime(2016, 02, 26);
            var underlying = new Tick { Value = 10m, Time = time };
            var filter = new StrikeExpiryOptionFilter(0, 0, TimeSpan.FromDays(3), TimeSpan.FromDays(7));
            var symbols = new[]
            {
                Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Put, 10, time.AddDays(0)), // 0
                Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Put, 10, time.AddDays(1)), // 1
                Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Put, 10, time.AddDays(2)), // 2
                Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Put, 10, time.AddDays(3)), // 3
                Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Put, 10, time.AddDays(4)), // 4
                Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Put, 10, time.AddDays(5)), // 5
                Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Put, 10, time.AddDays(6)), // 6
                Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Put, 10, time.AddDays(7)), // 7
                Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Put, 10, time.AddDays(8)), // 8
                Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Put, 10, time.AddDays(9)), // 9
            };

            var filtered = filter.Filter(symbols, underlying).ToList();
            Assert.AreEqual(5, filtered.Count);
            Assert.AreEqual(symbols[3], filtered[0]);
            Assert.AreEqual(symbols[4], filtered[1]);
            Assert.AreEqual(symbols[5], filtered[2]);
            Assert.AreEqual(symbols[6], filtered[3]);
            Assert.AreEqual(symbols[7], filtered[4]);
        }
示例#29
0
        /// <summary>
        /// Returns the performance of the algorithm in the specified date range
        /// </summary>
        /// <param name="fromDate">The initial date of the range</param>
        /// <param name="toDate">The final date of the range</param>
        /// <param name="trades">The list of closed trades</param>
        /// <param name="profitLoss">Trade record of profits and losses</param>
        /// <param name="equity">The list of daily equity values</param>
        /// <param name="pointsPerformance">The list of algorithm performance values</param>
        /// <param name="pointsBenchmark">The list of benchmark values</param>
        /// <param name="startingCapital">The algorithm starting capital</param>
        /// <returns>The algorithm performance</returns>
        private static AlgorithmPerformance GetAlgorithmPerformance(
            DateTime fromDate, 
            DateTime toDate, 
            List<Trade> trades, 
            SortedDictionary<DateTime, decimal> profitLoss, 
            SortedDictionary<DateTime, decimal> equity, 
            List<ChartPoint> pointsPerformance, 
            List<ChartPoint> pointsBenchmark, 
            decimal startingCapital)
        {
            var periodTrades = trades.Where(x => x.ExitTime.Date >= fromDate && x.ExitTime < toDate.AddDays(1)).ToList();
            var periodProfitLoss = new SortedDictionary<DateTime, decimal>(profitLoss.Where(x => x.Key >= fromDate && x.Key.Date < toDate.AddDays(1)).ToDictionary(x => x.Key, y => y.Value));
            var periodEquity = new SortedDictionary<DateTime, decimal>(equity.Where(x => x.Key.Date >= fromDate && x.Key.Date < toDate.AddDays(1)).ToDictionary(x => x.Key, y => y.Value));

            var listPerformance = new List<double>();
            var performance = ChartPointToDictionary(pointsPerformance, fromDate, toDate);
            performance.Values.ToList().ForEach(i => listPerformance.Add((double)(i / 100)));

            var benchmark = ChartPointToDictionary(pointsBenchmark, fromDate, toDate);
            var listBenchmark = CreateBenchmarkDifferences(benchmark, periodEquity);
            EnsureSameLength(listPerformance, listBenchmark);

            var runningCapital = equity.Count == periodEquity.Count ? startingCapital : periodEquity.Values.FirstOrDefault();

            return new AlgorithmPerformance(periodTrades, periodProfitLoss, periodEquity, listPerformance, listBenchmark, runningCapital);
        }
示例#30
0
        public void GenerateCorpTriMonday(DateTime generateDate)
        {
            DateTime ReprtStartDate = generateDate.AddDays(-9);
            DateTime ReprtEndDate = generateDate.AddDays(-3);

            string[] ProcNamesW = new string[5] { "Corp_IM", "Corp_SR", "Corp_PBI", "Corp_PKE", "Corp_WO" };
            string[,] ParamsW = new string[5, 2] {
                                                    { ReprtStartDate.ToString("yyyy-MM-dd"), ReprtEndDate.ToString("yyyy-MM-dd") }
                                                    ,{ ReprtStartDate.ToString("yyyy-MM-dd"), ReprtEndDate.ToString("yyyy-MM-dd") }
                                                    ,{ ReprtStartDate.ToString("yyyy-MM-dd"), ReprtEndDate.ToString("yyyy-MM-dd") }
                                                    ,{ ReprtStartDate.ToString("yyyy-MM-dd"), ReprtEndDate.ToString("yyyy-MM-dd") }
                                                    ,{ ReprtStartDate.ToString("yyyy-MM-dd"), ReprtEndDate.ToString("yyyy-MM-dd") }
                                                 };//benchmark para add in ExecuteProcWithParam method
            string[] sheetnameW = new string[5] { "IM", "SR", "PBI", "PKE", "WO" };
            string templateReportfile = "Corp Tricare Weekly New -demo.xls";

            DBAccess dbAccess = new DBAccess();
            DataSet CorpDs = dbAccess.ExecuteProcWithParam_Navy(templateReportfile, ProcNamesW, sheetnameW, ParamsW, ReprtEndDate);

            string reportStartStr = ReprtStartDate.ToString("MMdd");
            string reportEndStr = ReprtEndDate.ToString("MMdd");
            ExcelBus excelBiz = new ExcelBus();
            string savePath = corpTrackWeekly1Path + reportStartStr + "-" + reportEndStr;
            string corpReportSavePath = savePath + @"\Corp Tricare Weekly New " + reportStartStr + "-" + reportEndStr + ".xls";

            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }
            excelBiz.ExportDataToExcel_New(corpReportSavePath, templateReportfile, ProcNamesW, sheetnameW, CorpDs);
        }
示例#31
0
    public void ReadConfig()
    {
        if (isLoadFinish == false)
        {
            return;
        }
        isLoadFinish = false;
        lock (LockObject) { GameSystem.Instance.readConfigCnt += 1; }

        string text = ResourceLoadManager.Instance.GetConfigText(name);

        if (text == null)
        {
            Debug.LogError("LoadConfig failed: " + name);
            return;
        }

        Debug.Log("Config reading " + name);
        _items.Clear();
        //读取以及处理XML文本的类
        XmlDocument xmlDoc = CommonFunction.LoadXmlConfig(GlobalConst.DIR_XML_PUSH, text);
        //解析xml的过程
        XmlNodeList nodelist = xmlDoc.SelectSingleNode("Data").ChildNodes;

        foreach (XmlElement xe in nodelist)
        {
            XmlNode comment = xe.SelectSingleNode(GlobalConst.CONFIG_SWITCH_COLUMN);
            if (comment != null && comment.InnerText == GlobalConst.CONFIG_SWITCH)
            {
                continue;
            }

            PushItem item = new PushItem();
            foreach (XmlElement xel in xe)
            {
//				Debug.Log("read push config "+xel.Name+","+xel.InnerText);
                uint value = 0;
                if (xel.Name == "id")
                {
                    uint.TryParse(xel.InnerText, out value);
                    item.id = value;
                }
                else if (xel.Name == "type")
                {
                    uint.TryParse(xel.InnerText, out value);
                    item.type = value;
                }
                else if (xel.Name == "date")
                {
                    item.date = xel.InnerText;
                }
                else if (xel.Name == "time")
                {
                    item.time = xel.InnerText;
                }
                else if (xel.Name == "online")
                {
                    uint.TryParse(xel.InnerText, out value);
                    item.online = value;
                }
                else if (xel.Name == "content")
                {
                    item.content = xel.InnerText;
                }
            }
            if (!_items.ContainsKey(item.id))
            {
                if (item.date != "0")
                {
                    System.DateTime Now = System.DateTime.Now;
                    System.DateTime CDt = System.DateTime.Parse(item.date);
//					Debug.Log("Now "+Now.ToShortDateString()+" cdt "+CDt.ToShortDateString());
                    if (Now.CompareTo(CDt.AddDays(30)) < 0 && Now.AddDays(30).CompareTo(CDt) > 0)
                    {
//						Debug.Log("add item id to list "+item.date);
                        _items.Add(item.id, item);
                    }
                }
                else
                {
                    _items.Add(item.id, item);
                }
            }
        }
    }
示例#32
0
        public void UpdateUserRole(int PortalId, int UserId, int RoleId, bool Cancel)
        {
            UserRoleInfo userRole;

            userRole = GetUserRole(PortalId, UserId, RoleId);
            Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
            if (Cancel)
            {
                if (userRole != null && userRole.ServiceFee > 0.0 && userRole.IsTrialUsed)
                {
                    userRole.ExpiryDate = DateTime.Now.AddDays(-1);
                    provider.UpdateUserRole(userRole);
                    objEventLog.AddLog(userRole, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", Services.Log.EventLog.EventLogController.EventLogType.USER_ROLE_UPDATED);
                }
                else
                {
                    DeleteUserRole(PortalId, UserId, RoleId);
                    objEventLog.AddLog("UserId", UserId.ToString(), PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, Services.Log.EventLog.EventLogController.EventLogType.USER_ROLE_DELETED);
                }
            }
            else
            {
                int             UserRoleId = -1;
                RoleInfo        role;
                System.DateTime ExpiryDate    = DateTime.Now;
                System.DateTime EffectiveDate = Null.NullDate;
                bool            IsTrialUsed   = false;
                int             Period        = 0;
                string          Frequency     = "";
                if (userRole != null)
                {
                    UserRoleId    = userRole.UserRoleID;
                    EffectiveDate = userRole.EffectiveDate;
                    ExpiryDate    = userRole.ExpiryDate;
                    IsTrialUsed   = userRole.IsTrialUsed;
                }
                role = GetRole(RoleId, PortalId);
                if (role != null)
                {
                    if (IsTrialUsed == false && role.TrialFrequency.ToString() != "N")
                    {
                        Period    = role.TrialPeriod;
                        Frequency = role.TrialFrequency;
                    }
                    else
                    {
                        Period    = role.BillingPeriod;
                        Frequency = role.BillingFrequency;
                    }
                }
                if (EffectiveDate < DateTime.Now)
                {
                    EffectiveDate = Null.NullDate;
                }
                if (ExpiryDate < DateTime.Now)
                {
                    ExpiryDate = DateTime.Now;
                }
                if (Period == Null.NullInteger)
                {
                    ExpiryDate = Null.NullDate;
                }
                else
                {
                    switch (Frequency)
                    {
                    case "N":
                        ExpiryDate = Null.NullDate;
                        break;

                    case "O":
                        ExpiryDate = new System.DateTime(9999, 12, 31);
                        break;

                    case "D":
                        ExpiryDate = ExpiryDate.AddDays(Period);
                        break;

                    case "W":
                        ExpiryDate = ExpiryDate.AddDays(Period * 7);
                        break;

                    case "M":
                        ExpiryDate = ExpiryDate.AddMonths(Period);
                        break;

                    case "Y":
                        ExpiryDate = ExpiryDate.AddYears(Period);
                        break;
                    }
                }
                if (UserRoleId != -1)
                {
                    userRole.ExpiryDate = ExpiryDate;
                    provider.UpdateUserRole(userRole);
                    objEventLog.AddLog(userRole, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", Services.Log.EventLog.EventLogController.EventLogType.USER_ROLE_UPDATED);
                }
                else
                {
                    AddUserRole(PortalId, UserId, RoleId, EffectiveDate, ExpiryDate);
                }
            }
        }
示例#33
0
    private int daysApart(System.DateTime dt1, System.DateTime dt2)
    {
        int result = 0;

        if (dt1.CompareTo(dt2) <= 0)
        {
            while (dt1.Day != dt2.Day)
            {
                result++;
                Debug.Log("1");
                dt1 = dt1.AddDays(1);
            }
            while (dt1.Month != dt2.Month)
            {
                Debug.Log("2");
                result += System.DateTime.DaysInMonth(dt1.Year, dt1.Month);
                dt1     = dt1.AddMonths(1);
            }
            while (dt1.Year != dt2.Year)
            {
                Debug.Log("3");
                if (System.DateTime.IsLeapYear(dt1.Year))
                {
                    result += 366;
                }
                else
                {
                    result += 365;
                }
                dt1 = dt1.AddYears(1);
            }
        }
        else if (dt2.CompareTo(dt1) < 0)
        {
            while (dt1.Day != dt2.Day)
            {
                Debug.Log("4");
                result++;
                dt2 = dt2.AddDays(1);
            }
            while (dt1.Month != dt2.Month)
            {
                Debug.Log("5");
                result += System.DateTime.DaysInMonth(dt2.Year, dt2.Month);
                dt2     = dt2.AddMonths(1);
            }
            while (dt1.Year != dt2.Year)
            {
                Debug.Log("6");
                if (System.DateTime.IsLeapYear(dt2.Year))
                {
                    result += 366;
                }
                else
                {
                    result += 365;
                }
                dt2 = dt2.AddYears(1);
            }
        }
        return(result);
    }
示例#34
0
    void OnGUI()
    {
        position = new Rect(position.x, position.y, 250, 200);

        GUILayout.BeginArea(new Rect(0, 7, 250, 200));

        //Year
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("<", GUILayout.Width(65)))
        {
            CurrentDate = CurrentDate.AddYears(-1);
        }

        GUILayout.FlexibleSpace();
        GUILayout.Label(CurrentDate.ToString("yyyy"), EditorStyles.boldLabel);
        GUILayout.FlexibleSpace();

        if (GUILayout.Button(">", GUILayout.Width(65)))
        {
            CurrentDate = CurrentDate.AddYears(1);
        }
        GUILayout.EndHorizontal();

        //Month
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("<", GUILayout.Width(65)))
        {
            CurrentDate = CurrentDate.AddMonths(-1);
        }

        GUILayout.FlexibleSpace();
        GUILayout.Label(CurrentDate.ToString("MMMM"), EditorStyles.boldLabel);
        GUILayout.FlexibleSpace();

        if (GUILayout.Button(">", GUILayout.Width(65)))
        {
            CurrentDate = CurrentDate.AddMonths(1);
        }
        GUILayout.EndHorizontal();

        EditorGUILayout.Space();

        //Day
        int numDays = System.DateTime.DaysInMonth(CurrentDate.Year, CurrentDate.Month);

        Days = new List <string>();
        for (int i = 1; i < numDays + 1; i++)
        {
            Days.Add(i.ToString());
        }
        int newDay = GUILayout.SelectionGrid(CurrentDate.Day - 1, Days.ToArray(), 7) + 1;
        int diff   = newDay - CurrentDate.Day;

        CurrentDate = CurrentDate.AddDays(diff);

        if (numDays <= 28)
        {
            GUILayout.Space(21);
        }

        EditorGUILayout.Space();

        if (GUILayout.Button("Select"))
        {
            if (OnPicked != null)
            {
                OnPicked(this);
            }
        }

        GUILayout.EndArea();
    }
示例#35
0
    private void BindTransferOne(ListViewControl listview, System.DateTime date)
    {
        List <ETaskTransfer> plist = TaskTransferList.Where(c => c.CreateTime >= date && c.CreateTime < date.AddDays(1)).ToList();

        listview.BindData <ETaskTransfer>("MyFootprintItemOne", plist, (i, e) =>
        {
            i.name = "MyFootprintItemOne_" + e.ID;
            i.gameObject.SetActive(true);
            i.transform.Find("TaskName").GetComponent <Text>().text = e.TaskName;
            i.transform.Find("Idea").GetComponent <Text>().text     = e.Note;
            i.transform.Find("Time").GetComponent <Text>().text     = e.CreateTime.ToString("hh:mm");
            if (e.AssignedPersonID != 0)
            {
                i.transform.Find("ToOther").gameObject.SetActive(true);
                i.transform.Find("DoProcess").gameObject.SetActive(false);
                i.transform.Find("ToOther").Find("Name (1)").GetComponent <Text>().text = e.AssignedName;
                App.Instance.ShowImage(i.transform.Find("ToOther").Find("Icon (2)").GetComponent <RawImage>(), e.AppointFace, 11);
            }
            else
            {
                i.transform.Find("ToOther").gameObject.SetActive(false);
                i.transform.Find("DoProcess").gameObject.SetActive(true);
                i.transform.Find("DoProcess").Find("Name (1)").GetComponent <Text>().text = e.StepName;
            }
        }, false);
    }
 public void DayLater()
 {
     SetupTrainingDates(currentStartingDate.AddDays(1));
 }
示例#37
0
    void ScheduleNotifications()
    {
        if (CloudUser.instance.isUserAuthenticated == false)
        {
            return;
        }

        DateTime now   = CloudDateTime.UtcNow;
        DateTime today = now.Date;

        // 2xXP bonus or conditional reward notification
        DateTime     date     = now.AddHours(1);
        E_MPGameType gameType = GetGameWithXpBonus();

        switch (gameType)
        {
        case E_MPGameType.DeathMatch:
            SheduleNotification(NotifyId.DeathMatch2xXP, TextDatabase.instance[00507000], date);
            break;

        case E_MPGameType.ZoneControl:
            SheduleNotification(NotifyId.ZoneControl2xXP, TextDatabase.instance[00507001], date);
            break;

        default:
            string text;
            if (GetConditionalRewardText(now, out text) == true)
            {
                SheduleNotification(NotifyId.ConditionalReward, text, date);
            }
            break;
        }

        // daily reward notification
        date = today.AddDays(1);
        SheduleNotification(NotifyId.InstantReward, TextDatabase.instance[00507002], date);

        // level up notification
        date = today.AddDays(2);
        if (Random.Range(0, 100) > 50)
        {
            SheduleNotification(NotifyId.DeathMatch, TextDatabase.instance[00507003], date);
        }
        else
        {
            SheduleNotification(NotifyId.ZoneControl, TextDatabase.instance[00507004], date);
        }

        // play with friends notification
        if (GameCloudManager.friendList.friends.Count > 0)
        {
            date = today.AddDays(4);
            if (Random.Range(0, 100) > 50)
            {
                SheduleNotification(NotifyId.DeathMatchFriends, TextDatabase.instance[00507005], date);
            }
            else
            {
                SheduleNotification(NotifyId.ZoneControlFriends, TextDatabase.instance[00507006], date);
            }
        }
    }
示例#38
0
    public static ChartInfo convertSleepHeaderToChartInfo(ChartInfo chartInfo, string filePath)
    {
        var          stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        StreamReader reader = new StreamReader(stream);

        string[] profileInfo = reader.ReadLine().Split(',');              //CsvFileの1行目 (Row 0)
        reader.ReadLine();                                                //Skip Row 1
        string[] sleepRecordStartTimeLine = reader.ReadLine().Split(','); //CsvFileの3行目 (Row 2)

        string sleepTime = "";

        if (chartInfo.endSleepTime != null && sleepRecordStartTimeLine.Length >= 3)
        {
            string   date    = sleepRecordStartTimeLine[0];
            string   time    = sleepRecordStartTimeLine[2];
            string[] dateArr = date.Split('/');
            string[] timeArr = time.Split(':');
            int      year    = int.Parse(dateArr[0]);
            int      month   = int.Parse(dateArr[1]);
            int      day     = int.Parse(dateArr[2]);
            int      hour    = int.Parse(timeArr[0]);
            int      min     = int.Parse(timeArr[1]);
            int      sec     = int.Parse(timeArr[2]);
            chartInfo.startSleepTime = new System.DateTime(year, month, day, hour, min, sec);

            int             sleepTimeSec = Graph.Time.GetDateDifferencePerSecond(chartInfo.startSleepTime, chartInfo.endSleepTime);
            System.TimeSpan ts           = new System.TimeSpan(hours: 0, minutes: 0, seconds: sleepTimeSec);
            int             hourWithDay  = 24 * ts.Days + ts.Hours; // 24時間超えた場合の時間を考慮
            sleepTime = string.Format("{0:00}:{1:00}", hourWithDay, ts.Minutes);
        }

        System.DateTime fileDateTime = Kaimin.Common.Utility.TransFilePathToDate(filePath);
        chartInfo.fileName  = fileDateTime.ToString();
        chartInfo.sleepTime = sleepTime;

        string tmpTime = fileDateTime.ToString("HH:mm:ss");

        if (string.Compare(tmpTime, "00:00:00") >= 0 && string.Compare(tmpTime, "09:00:00") <= 0)
        {
            //データ開始時刻がAM00:00~09:00までのデータに前日の日付として表示
            chartInfo.date = fileDateTime.AddDays(-1).ToString("M/d");
        }
        else
        {
            chartInfo.date = fileDateTime.ToString("M/d");
        }

        if (sleepRecordStartTimeLine.Length > 9) //New format
        {
            chartInfo.sleepMode         = int.Parse(sleepRecordStartTimeLine[8]);
            chartInfo.vibrationStrength = int.Parse(sleepRecordStartTimeLine[9]);
        }
        else
        {
            //Default
            chartInfo.sleepMode         = (int)SleepMode.Suppress;
            chartInfo.vibrationStrength = (int)VibrationStrength.Medium;
        }


        return(chartInfo);
    }
示例#39
0
        public TestListUI()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();

            TreeNode tmp = new TreeNode("全部");

            foreach (var element in Enum.GetNames(typeof(CommonConst.TestState)))
            {
                tmp.Nodes.Add(element);
            }
            treeView1.Nodes.Add(tmp);
            treeView1.ExpandAll();
            treeView1.SelectedNode = treeView1.Nodes[0].Nodes[0];
            //让选中项背景色呈现蓝色
            treeView1.SelectedNode.BackColor = Color.SteelBlue;
            //前景色为白色
            treeView1.SelectedNode.ForeColor = Color.White;
            System.DateTime dt = System.DateTime.Now;
            dateTimePicker1.Value = dt.AddDays(-7);

            List <PersonInfo> datasource_person = PersonDao.getAllPersonInfo();
            PersonInfo        person            = new PersonInfo();

            person.Fullname = "全部责任人";
            person.Id       = 0;
            datasource_person.Insert(0, person);
            this.comboBox2.DataSource    = datasource_person;
            this.comboBox2.DisplayMember = "Fullname";
            this.comboBox2.ValueMember   = "Id";


            List <ModuleInfo> datasource_module = ModuleDao.getAllModuleInfo();
            ModuleInfo        all = new ModuleInfo();

            all.Fullname = "全部模块";
            all.Id       = 0;
            datasource_module.Insert(0, all);
            this.comboBox1.DataSource         = datasource_module;
            this.comboBox1.DisplayMember      = "Fullname";
            this.comboBox1.ValueMember        = "Id";
            this.comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
            this.comboBox1.AutoCompleteMode   = AutoCompleteMode.SuggestAppend;

            this.comboBox3.Items.Add("全部等级");
            this.comboBox3.Items.AddRange(CommonConst.BUGLEVEL);
            this.comboBox3.SelectedIndex = 0;

            this.comboBox3.SelectedIndexChanged += new EventHandler(conditionChanged);
            this.comboBox1.SelectedIndexChanged += new EventHandler(conditionChanged);
            this.comboBox2.SelectedIndexChanged += new EventHandler(conditionChanged);

            treeView1.NodeMouseClick += new TreeNodeMouseClickEventHandler(treeView1_NodeMouseClick);
            treeView1.Leave          += new EventHandler(treeView1_Leave);
            treeView1.BeforeSelect   += new TreeViewCancelEventHandler(treeView1_BeforeSelect);

            this.listView1.DoubleClick        += new EventHandler(ListVew_DoubleClick);
            this.dateTimePicker1.ValueChanged += new EventHandler(conditionChanged);
            this.dateTimePicker2.ValueChanged += new EventHandler(conditionChanged);

            this.currentpage = 1;
            this.label3.Text = string.Format(currentstr, this.currentpage);
            this.label5.Text = string.Format(pagestr, this.pagesize);
            this.label4.Text = string.Format(countstr, (count % pagesize == 0)?count / pagesize:count / pagesize + 1, this.count);

            getTestUnitList();
            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
        }
示例#40
0
    public void UpdateCalendar()
    {
        CurrentDate = System.DateTime.Now.AddMonths(AddMonths);
        switch (CurrentDate.Month)
        {
        case 1:
            CurrentMonthString = "January";
            break;

        case 2:
            CurrentMonthString = "February";
            break;

        case 3:
            CurrentMonthString = "March";
            break;

        case 4:
            CurrentMonthString = "April";
            break;

        case 5:
            CurrentMonthString = "May";
            break;

        case 6:
            CurrentMonthString = "June";
            break;

        case 7:
            CurrentMonthString = "July";
            break;

        case 8:
            CurrentMonthString = "August";
            break;

        case 9:
            CurrentMonthString = "September";
            break;

        case 10:
            CurrentMonthString = "October";
            break;

        case 11:
            CurrentMonthString = "November";
            break;

        case 12:
            CurrentMonthString = "December";
            break;
        }

        int delta = Convert.ToInt32(CurrentDate.Day);

        System.DateTime FirstDayOfMonth = CurrentDate.AddDays(-delta + 1);
        //		print (CurrentDate);

        StartDay = 0;

        switch (FirstDayOfMonth.DayOfWeek.ToString())
        {
        case "Sunday":
            StartDay = 0;
            break;

        case "Monday":
            StartDay = 1;
            break;

        case "Tuesday":
            StartDay = 2;
            break;

        case "Wednesday":
            StartDay = 3;
            break;

        case "Thursday":
            StartDay = 4;
            break;

        case "Friday":
            StartDay = 5;
            break;

        case "Saturday":
            StartDay = 6;
            break;
        }

        EndDay = System.DateTime.DaysInMonth(CurrentDate.Year, CurrentDate.Month);

        // clear days in calendar
        for (int i = 0; i < 42; i++)
        {
            DayButtonArray[i].GetComponentInChildren <Text>().text  = "";
            DayButtonArray[i].GetComponentInChildren <Text>().color = ButtonTextColorNoWorkout;
            DayButtonArray[i].GetComponent <Image>().sprite         = ButtonBackgroundNoWorkout;
            DayButtonArray[i].GetComponent <Button>().onClick.RemoveAllListeners();
        }

        // fill in days
        var count = 1;

        for (int i = StartDay; i < (StartDay + EndDay); i++)
        {
            int tempIndex = i;
            DayButtonArray[i].GetComponentInChildren <Text>().text  = count.ToString();
            DayButtonArray[i].GetComponentInChildren <Text>().color = ButtonTextColorNoWorkout;
            DayButtonArray[i].GetComponent <Image>().sprite         = ButtonBackgroundNoWorkout;
            DayButtonArray[i].GetComponent <Button>().onClick.AddListener(() => DayButtonPressed(tempIndex + 1 - StartDay));



            System.DateTime CalendarDay      = new System.DateTime(CurrentDate.Year, CurrentDate.Month, count);
            string          DayWorkoutStatus = GetDayWorkoutData(CalendarDay);

            switch (DayWorkoutStatus)
            {
            case "NoWorkout":
                DayButtonArray[i].GetComponentInChildren <Text>().color = ButtonTextColorNoWorkout;
                DayButtonArray[i].GetComponent <Image>().sprite         = ButtonBackgroundNoWorkout;
                break;

            case "Workout":
                DayButtonArray[i].GetComponentInChildren <Text>().color = ButtonTextColorWorkout;
                DayButtonArray[i].GetComponent <Image>().sprite         = ButtonBackgroundWorkout;
                break;

            case "WorkoutSomeCompleted":
                DayButtonArray[i].GetComponentInChildren <Text>().color = ButtonTextColorWorkoutCompleted;
                DayButtonArray[i].GetComponent <Image>().sprite         = ButtonBackgroundWorkoutSomeCompleted;
                break;

            case "WorkoutCompleted":
                DayButtonArray[i].GetComponentInChildren <Text>().color = ButtonTextColorWorkoutCompleted;
                DayButtonArray[i].GetComponent <Image>().sprite         = ButtonBackgroundWorkoutCompleted;
                break;

            default:
                DayButtonArray[i].GetComponentInChildren <Text>().color = ButtonTextColorNoWorkout;
                DayButtonArray[i].GetComponent <Image>().sprite         = ButtonBackgroundNoWorkout;
                break;
            }

            // make todays text white
            if (TodaysDate.Year == CurrentDate.Year && TodaysDate.Month == CurrentDate.Month && TodaysDate.Day == count)
            {
                DayButtonArray[i].GetComponentInChildren <Text>().color = Color.black;
            }

            count += 1;
        }
        MonthText.GetComponent <Text>().text = CurrentMonthString + " " + CurrentDate.Year.ToString();
    }
示例#41
0
        // match several other cases
        // including '今天', '后天', '十三日'
        protected DateTimeResolutionResult ParseImplicitDate(string text, DateObject referenceDate)
        {
            var ret = new DateTimeResolutionResult();

            // handle "十二日" "明年这个月三日" "本月十一日"
            var match = JapaneseDateExtractorConfiguration.SpecialDate.MatchExact(text, trim: true);

            if (match.Success)
            {
                var yearStr  = match.Groups["thisyear"].Value;
                var monthStr = match.Groups["thismonth"].Value;
                var dayStr   = match.Groups["day"].Value;

                int month = referenceDate.Month, year = referenceDate.Year;
                var day = this.config.DayOfMonth[dayStr];

                bool hasYear = false, hasMonth = false;

                if (!string.IsNullOrEmpty(monthStr))
                {
                    hasMonth = true;
                    if (JapaneseDateExtractorConfiguration.NextRe.Match(monthStr).Success)
                    {
                        month++;
                        if (month == 13)
                        {
                            month = 1;
                            year++;
                        }
                    }
                    else if (JapaneseDateExtractorConfiguration.LastRe.Match(monthStr).Success)
                    {
                        month--;
                        if (month == 0)
                        {
                            month = 12;
                            year--;
                        }
                    }

                    if (!string.IsNullOrEmpty(yearStr))
                    {
                        hasYear = true;
                        if (JapaneseDateExtractorConfiguration.NextRe.Match(yearStr).Success)
                        {
                            ++year;
                        }
                        else if (JapaneseDateExtractorConfiguration.LastRe.Match(yearStr).Success)
                        {
                            --year;
                        }
                    }
                }

                ret.Timex = DateTimeFormatUtil.LuisDate(hasYear ? year : -1, hasMonth ? month : -1, day);

                DateObject futureDate, pastDate;

                if (day > MonthMaxDays[month - 1])
                {
                    futureDate = DateObject.MinValue.SafeCreateFromValue(year, month + 1, day);
                    pastDate   = DateObject.MinValue.SafeCreateFromValue(year, month - 1, day);
                }
                else
                {
                    futureDate = DateObject.MinValue.SafeCreateFromValue(year, month, day);
                    pastDate   = DateObject.MinValue.SafeCreateFromValue(year, month, day);
                    if (!hasMonth)
                    {
                        if (futureDate < referenceDate)
                        {
                            futureDate = futureDate.AddMonths(1);
                        }

                        if (pastDate >= referenceDate)
                        {
                            pastDate = pastDate.AddMonths(-1);
                        }
                    }
                    else if (!hasYear)
                    {
                        if (futureDate < referenceDate)
                        {
                            futureDate = futureDate.AddYears(1);
                        }

                        if (pastDate >= referenceDate)
                        {
                            pastDate = pastDate.AddYears(-1);
                        }
                    }
                }

                ret.FutureValue = futureDate;
                ret.PastValue   = pastDate;
                ret.Success     = true;

                return(ret);
            }

            // handle cases like "昨日", "明日", "大后天"
            match = JapaneseDateExtractorConfiguration.SpecialDayRegex.MatchExact(text, trim: true);

            if (match.Success)
            {
                var value = referenceDate.AddDays(JapaneseDateTimeParserConfiguration.GetSwiftDay(match.Value));
                ret.Timex       = DateTimeFormatUtil.LuisDate(value);
                ret.FutureValue = ret.PastValue = value;
                ret.Success     = true;

                return(ret);
            }

            match = JapaneseDateExtractorConfiguration.SpecialMonthRegex.MatchExact(text, trim: true);

            if (match.Success)
            {
                var value = referenceDate.AddMonths(JapaneseDateTimeParserConfiguration.GetSwiftMonth(match.Value));
                ret.Timex       = DateTimeFormatUtil.LuisDate(value);
                ret.FutureValue = ret.PastValue = value;
                ret.Success     = true;

                return(ret);
            }

            match = JapaneseDateExtractorConfiguration.SpecialYearRegex.MatchExact(text, trim: true);

            if (match.Success)
            {
                var value = referenceDate.AddYears(JapaneseDateTimeParserConfiguration.GetSwiftYear(match.Value));
                ret.Timex       = DateTimeFormatUtil.LuisDate(value);
                ret.FutureValue = ret.PastValue = value;
                ret.Success     = true;

                return(ret);
            }

            if (!ret.Success)
            {
                ret = MatchThisWeekday(text, referenceDate);
            }

            if (!ret.Success)
            {
                ret = MatchNextWeekday(text, referenceDate);
            }

            if (!ret.Success)
            {
                ret = MatchLastWeekday(text, referenceDate);
            }

            if (!ret.Success)
            {
                ret = MatchWeekdayAlone(text, referenceDate);
            }

            return(ret);
        }
示例#42
0
        /*************************************************************************************
        *	module: frmWeekly.cs - TLoadData
        *
        *	author: Tim Ragain
        *	date: Jan 22, 2002
        *
        *	Purpose: Takes two variables the x represents the day as an integer and the sCount is a
        *	short representing the column of the Calendar control.  This initializes the OCAData.dll
        *	control and calls the GetDailyCount and GetDailyAnon procedures.  The anonymous count is
        *	subtracted from the total count to get the customer count.  The appropriate column
        *	and row is updated.
        *************************************************************************************/
        private void TLoadData(int x, short sCount)
        {
            OCAData.CCountDailyClass rpt = new OCAData.CCountDailyClass();
            string      strArchive, strWatson;
            int         y = 0;
            RegistryKey regArchive = Registry.CurrentUser.OpenSubKey("software").OpenSubKey("microsoft", true).CreateSubKey("OCATools").CreateSubKey("OCAReports").CreateSubKey("Archive");
            RegistryKey regWatson  = Registry.CurrentUser.OpenSubKey("software").OpenSubKey("microsoft", true).CreateSubKey("OCATools").CreateSubKey("OCAReports").CreateSubKey("Watson");

            System.DateTime dDate = new System.DateTime(monthCalendar1.SelectionStart.Year, monthCalendar1.SelectionStart.Month,
                                                        monthCalendar1.SelectionStart.Day);

            long lngCount = 0, l_WatsonCount = 0, l_ArchiveCount = 0;

            statusBar1.Text = "Getting Daily Count for " + dDate.AddDays(x).Date.ToShortDateString() + " from database";
            lDate[x]        = dDate.AddDays(x).Date;
            try
            {
                lngCount = rpt.GetDailyCount(dDate.AddDays(x));
            }
            catch
            {
//				MessageBox.Show("Error: " + e.Message.ToString(), iLast.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            lock (this)
            {
                lCount[x]           = lngCount;
                axMSChart1.Column   = 1;
                axMSChart1.Row      = sCount;
                axMSChart1.RowLabel = dDate.AddDays(x).ToShortDateString();
                axMSChart1.Data     = lngCount.ToString();
            }
            UpdateStatus();

            statusBar1.Text = "Getting Daily Count for " + dDate.AddDays(x).Date.ToString() + " from Watson Server";
#if (FILE_SERVER)
            for (y = 0; y < 10; y++)
            {
                if (regWatson.GetValue("Loc" + y.ToString()).ToString().Length > 0)
                {
                    strWatson     = regWatson.GetValue("Loc" + y.ToString()).ToString();
                    l_WatsonCount = rpt.GetFileCount(OCAData.ServerLocation.Watson, strWatson, dDate.AddDays(x));
                    if (l_WatsonCount > 0)
                    {
                        y = 10;
                    }
                }
                else
                {
                    l_WatsonCount = 0;
                }
            }
            //l_WatsonCount = rpt.GetFileCount(OCAData.ServerLocation.Watson, "Z:\\", dDate.AddDays(x));
#elif (FILE_LOCAL)
            l_WatsonCount = rpt.GetFileCount(OCAData.ServerLocation.Watson, "C:\\MiniDumps\\Watson\\", dDate.AddDays(x));
#endif
            lock (this)
            {
                lWatson[x]        = l_WatsonCount;
                axMSChart1.Column = 2;
                axMSChart1.Row    = sCount;
                axMSChart1.Data   = l_WatsonCount.ToString();
            }
            UpdateStatus();

            statusBar1.Text = "Getting Daily Count for " + dDate.AddDays(x).Date.ToString() + " from Archive Server";
#if (FILE_SERVER)
            try
            {
                for (y = 0; y < 10; y++)
                {
                    if (regArchive.GetValue("Loc" + y.ToString()).ToString().Length > 0)
                    {
                        strArchive     = regArchive.GetValue("Loc" + y.ToString()).ToString();
                        l_ArchiveCount = rpt.GetFileCount(OCAData.ServerLocation.Archive, strArchive, dDate.AddDays(x));
                        if (l_ArchiveCount > 0)
                        {
                            y = 10;
                        }
                    }
                    else
                    {
                        l_ArchiveCount = 0;
                    }
                }
                //l_ArchiveCount = rpt.GetFileCount(OCAData.ServerLocation.Archive, "Y:\\", dDate.AddDays(x));
            }
            catch
            {
                l_ArchiveCount = 0;
            }
#elif (FILE_LOCAL)
            l_ArchiveCount = rpt.GetFileCount(OCAData.ServerLocation.Archive, "C:\\MiniDumps\\Archive\\", dDate.AddDays(x));
#endif
//			if(l_ArchiveCount == 0)
//			{
//#if(FILE_SERVER)
//				l_ArchiveCount = rpt.GetFileCount(OCAData.ServerLocation.Archive, "X:\\", dDate.AddDays(x));
//#elif(FILE_LOCAL)
//			l_ArchiveCount = rpt.GetFileCount(OCAData.ServerLocation.Archive, "C:\\MiniDumps\\Archive\\", dDate.AddDays(x));
//#endif
//			}
            lock (this)
            {
                lArchive[x]       = l_ArchiveCount;
                axMSChart1.Column = 3;
                axMSChart1.Row    = sCount;
                axMSChart1.Data   = l_ArchiveCount.ToString();
            }
            UpdateStatus();
            this.Refresh();
        }
示例#43
0
        /*************************************************************************************
        *	module: frmWeekly.cs - tabPage2_Paint
        *
        *	author: Tim Ragain
        *	date: Jan 22, 2002
        *
        *	Purpose: Paints the grid for the tab2 control.  The global variables lAnonymous[x] and
        *	lCustomer[x] are used to display the appropriate information to the grid.
        *************************************************************************************/
        private void tabPage2_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            Pen           curvePen = new Pen(Color.Blue);
            Pen           dbPen = new Pen(Color.DarkBlue);
            Pen           whPen = new Pen(Color.White);
            float         row = .05F;
            int           x = 0, y = 0, min = 3, max = 12, pad = 10, top = 5, cols = 4;
            int           colwidth = 0;
            PointF        pt       = new PointF(0, 0);
            Font          ft       = new Font("Verdona", 12);
            SolidBrush    sb       = new SolidBrush(Color.Black);
            StringBuilder strTemp  = new StringBuilder(40);

            System.DateTime dDate = new System.DateTime(monthCalendar1.SelectionEnd.Year, monthCalendar1.SelectionEnd.Month,
                                                        monthCalendar1.SelectionEnd.Day);

            colwidth = tabPage2.Width / cols;

            for (x = min; x < max; x++)
            {
                if (x > (min - 1) && x < top)
                {
                    e.Graphics.DrawLine(dbPen, pad, tabPage2.Height * (row * x),
                                        tabPage2.Width - pad, tabPage2.Height * (row * x));
                }
                else
                {
                    e.Graphics.DrawLine(curvePen, pad, tabPage2.Height * (row * x),
                                        tabPage2.Width - pad, tabPage2.Height * (row * x));
                }
            }
            //x y x1 y1
            for (x = 0; x < cols; x++)
            {
                //left side light blue
                e.Graphics.DrawLine(curvePen, pad + (colwidth * x),
                                    tabPage2.Height * (row * (min + 1)),
                                    pad + (colwidth * x), tabPage2.Height * (row * (max - 1)));
                //right side light blue
                e.Graphics.DrawLine(curvePen, tabPage2.Width - pad,
                                    tabPage2.Height * (row * (min + 1)),
                                    tabPage2.Width - pad, tabPage2.Height * (row * (max - 1)));
                //left side upper dark blue
                e.Graphics.DrawLine(dbPen, pad + (colwidth * x),
                                    tabPage2.Height * (row * min),
                                    pad + (colwidth * x), tabPage2.Height * (row * (min + 1)));
                //right side upper dark blue
                e.Graphics.DrawLine(dbPen, tabPage2.Width - pad,
                                    tabPage2.Height * (row * min),
                                    tabPage2.Width - pad, tabPage2.Height * (row * (min + 1)));
            }
            for (x = 0, y = 6; x < 7; x++, y--)
            {
                pt.X = pad + (colwidth * x);
                pt.Y = tabPage2.Height * (row * min);
                strTemp.Remove(0, strTemp.Length);
                switch (x)
                {
                case 0:
                    strTemp.Append("Date");
                    break;

                case 1:
                    strTemp.Append("Daily");
                    break;

                case 2:
                    strTemp.Append("Watson");
                    break;

                case 3:
                    strTemp.Append("Archive");
                    break;

                default:
                    strTemp.Append("");
                    break;
                }
                e.Graphics.DrawString(strTemp.ToString(), ft, sb, pt, System.Drawing.StringFormat.GenericDefault);
                pt.X = pad + (colwidth * 0);
                pt.Y = ((tabPage2.Height * row) * (min + (x + 1)));
                e.Graphics.DrawString(dDate.AddDays(-y).Date.ToString(), ft, sb, pt, System.Drawing.StringFormat.GenericDefault);
                pt.X = pad + (colwidth * 1);
                pt.Y = ((tabPage2.Height * row) * (min + (x + 1)));
                e.Graphics.DrawString(lCount[x].ToString(), ft, sb, pt, System.Drawing.StringFormat.GenericDefault);
                pt.X = pad + (colwidth * 2);
                pt.Y = ((tabPage2.Height * row) * (min + (x + 1)));
                e.Graphics.DrawString(lWatson[x].ToString(), ft, sb, pt, System.Drawing.StringFormat.GenericDefault);
                pt.X = pad + (colwidth * 3);
                pt.Y = ((tabPage2.Height * row) * (min + (x + 1)));
                e.Graphics.DrawString(lArchive[x].ToString(), ft, sb, pt, System.Drawing.StringFormat.GenericDefault);
            }
            curvePen.Dispose();
            dbPen.Dispose();
            whPen.Dispose();
        }
示例#44
0
        // handle cases like "三天前"
        private DateTimeResolutionResult ParserDurationWithBeforeAndAfter(string text, DateObject referenceDate)
        {
            var ret         = new DateTimeResolutionResult();
            var durationRes = durationExtractor.Extract(text, referenceDate);
            var unitStr     = string.Empty;

            if (durationRes.Count > 0)
            {
                var match = JapaneseDateExtractorConfiguration.UnitRegex.Match(text);
                if (match.Success)
                {
                    var suffix    = text.Substring((int)durationRes[0].Start + (int)durationRes[0].Length).Trim();
                    var srcUnit   = match.Groups["unit"].Value;
                    var numberStr = text.Substring((int)durationRes[0].Start, match.Index - (int)durationRes[0].Start).Trim();
                    var number    = ConvertJapaneseToNum(numberStr);

                    if (this.config.UnitMap.ContainsKey(srcUnit))
                    {
                        unitStr = this.config.UnitMap[srcUnit];

                        var beforeMatch = JapaneseDateExtractorConfiguration.BeforeRegex.Match(suffix);
                        if (beforeMatch.Success && suffix.StartsWith(beforeMatch.Value))
                        {
                            DateObject date;
                            switch (unitStr)
                            {
                            case Constants.TimexDay:
                                date = referenceDate.AddDays(-number);
                                break;

                            case Constants.TimexWeek:
                                date = referenceDate.AddDays(-7 * number);
                                break;

                            case Constants.TimexMonthFull:
                                date = referenceDate.AddMonths(-number);
                                break;

                            case Constants.TimexYear:
                                date = referenceDate.AddYears(-number);
                                break;

                            default:
                                return(ret);
                            }

                            ret.Timex       = $"{DateTimeFormatUtil.LuisDate(date)}";
                            ret.FutureValue = ret.PastValue = date;
                            ret.Success     = true;
                            return(ret);
                        }

                        var afterMatch = JapaneseDateExtractorConfiguration.AfterRegex.Match(suffix);
                        if (afterMatch.Success && suffix.StartsWith(afterMatch.Value))
                        {
                            DateObject date;
                            switch (unitStr)
                            {
                            case Constants.TimexDay:
                                date = referenceDate.AddDays(number);
                                break;

                            case Constants.TimexWeek:
                                date = referenceDate.AddDays(7 * number);
                                break;

                            case Constants.TimexMonthFull:
                                date = referenceDate.AddMonths(number);
                                break;

                            case Constants.TimexYear:
                                date = referenceDate.AddYears(number);
                                break;

                            default:
                                return(ret);
                            }

                            ret.Timex       = $"{DateTimeFormatUtil.LuisDate(date)}";
                            ret.FutureValue = ret.PastValue = date;
                            ret.Success     = true;
                            return(ret);
                        }
                    }
                }
            }

            return(ret);
        }
示例#45
0
 //本地推送
 static void IOS_NotificationMessage(string message, int day, int hour, int minute, int second)
 {
     System.DateTime time = System.DateTime.Now;
     time = time.AddDays(day).AddHours(hour).AddMinutes(minute).AddSeconds(second);
     IOS_NotificationMessage(message, time, false, CalendarUnit.Day);
 }
示例#46
0
        private static DateTimeResolutionResult GetAgoLaterResult(
            DateTimeParseResult durationParseResult,
            string afterStr,
            string beforeStr,
            DateObject referenceTime,
            IParser numberParser,
            IDateTimeUtilityConfiguration utilityConfiguration,
            AgoLaterMode mode,
            SwiftDayDelegate swiftDay)
        {
            var ret            = new DateTimeResolutionResult();
            var resultDateTime = referenceTime;
            var timex          = durationParseResult.TimexStr;

            if (((DateTimeResolutionResult)durationParseResult.Value).Mod == Constants.MORE_THAN_MOD)
            {
                ret.Mod = Constants.MORE_THAN_MOD;
            }
            else if (((DateTimeResolutionResult)durationParseResult.Value).Mod == Constants.LESS_THAN_MOD)
            {
                ret.Mod = Constants.LESS_THAN_MOD;
            }

            if (MatchingUtil.ContainsAgoLaterIndex(afterStr, utilityConfiguration.AgoRegex))
            {
                var match = utilityConfiguration.AgoRegex.Match(afterStr);
                var swift = 0;

                // Handle cases like "3 days before yesterday"
                if (match.Success && !string.IsNullOrEmpty(match.Groups["day"].Value))
                {
                    swift = swiftDay(match.Groups["day"].Value);
                }
                else if (utilityConfiguration.CheckBothBeforeAfter && match.Success && !MatchingUtil.ContainsAgoLaterIndexInBeforeString(beforeStr, utilityConfiguration.AgoRegex))
                {
                    match = utilityConfiguration.AgoRegex.Match(beforeStr + " " + afterStr);
                    if (match.Success && !string.IsNullOrEmpty(match.Groups["day"].Value))
                    {
                        swift = swiftDay(match.Groups["day"].Value);
                    }
                }

                resultDateTime = DurationParsingUtil.ShiftDateTime(timex, referenceTime.AddDays(swift), false);

                ((DateTimeResolutionResult)durationParseResult.Value).Mod = Constants.BEFORE_MOD;
            }
            else if (utilityConfiguration.CheckBothBeforeAfter && MatchingUtil.ContainsAgoLaterIndexInBeforeString(beforeStr, utilityConfiguration.AgoRegex))
            {
                var match = utilityConfiguration.AgoRegex.Match(beforeStr);
                var swift = 0;

                // Handle cases like "3 days before yesterday"
                if (match.Success && !string.IsNullOrEmpty(match.Groups["day"].Value))
                {
                    swift = swiftDay(match.Groups["day"].Value);
                }

                resultDateTime = DurationParsingUtil.ShiftDateTime(timex, referenceTime.AddDays(swift), false);

                ((DateTimeResolutionResult)durationParseResult.Value).Mod = Constants.BEFORE_MOD;
            }
            else if (MatchingUtil.ContainsAgoLaterIndex(afterStr, utilityConfiguration.LaterRegex) ||
                     MatchingUtil.ContainsTermIndex(beforeStr, utilityConfiguration.InConnectorRegex) ||
                     (utilityConfiguration.CheckBothBeforeAfter && MatchingUtil.ContainsAgoLaterIndexInBeforeString(beforeStr, utilityConfiguration.LaterRegex)))
            {
                var match = utilityConfiguration.LaterRegex.Match(afterStr);
                var swift = 0;

                if (utilityConfiguration.CheckBothBeforeAfter && MatchingUtil.ContainsAgoLaterIndexInBeforeString(beforeStr, utilityConfiguration.LaterRegex) && string.IsNullOrEmpty(match.Groups["day"].Value))
                {
                    match = utilityConfiguration.LaterRegex.Match(beforeStr);
                }

                // Handle cases like "3 days after tomorrow"
                if (match.Success && !string.IsNullOrEmpty(match.Groups["day"].Value))
                {
                    swift = swiftDay(match.Groups["day"].Value);
                }

                var yearMatch = utilityConfiguration.SinceYearSuffixRegex.Match(afterStr);
                if (yearMatch.Success)
                {
                    var yearString = yearMatch.Groups[Constants.YearGroupName].Value;
                    var yearEr     = new ExtractResult {
                        Text = yearString
                    };
                    var year = Convert.ToInt32((double)(numberParser.Parse(yearEr).Value ?? 0));
                    referenceTime = DateObject.MinValue.SafeCreateFromValue(year, 1, 1);
                }

                resultDateTime = DurationParsingUtil.ShiftDateTime(timex, referenceTime.AddDays(swift), true);

                ((DateTimeResolutionResult)durationParseResult.Value).Mod = Constants.AFTER_MOD;
            }
            else if (utilityConfiguration.CheckBothBeforeAfter && (MatchingUtil.ContainsAgoLaterIndexInBeforeString(beforeStr, utilityConfiguration.LaterRegex) ||
                                                                   MatchingUtil.ContainsAgoLaterIndex(afterStr, utilityConfiguration.InConnectorRegex) ||
                                                                   MatchingUtil.ContainsAgoLaterIndex(afterStr, utilityConfiguration.LaterRegex)))
            {
                // Check also beforeStr
                var match = utilityConfiguration.LaterRegex.Match(beforeStr);
                var swift = 0;

                if (MatchingUtil.ContainsAgoLaterIndex(afterStr, utilityConfiguration.LaterRegex) && string.IsNullOrEmpty(match.Groups["day"].Value))
                {
                    match = utilityConfiguration.LaterRegex.Match(beforeStr);
                }

                // Handle cases like "3 days after tomorrow"
                if (match.Success && !string.IsNullOrEmpty(match.Groups["day"].Value))
                {
                    swift = swiftDay(match.Groups["day"].Value);
                }

                var yearMatch = utilityConfiguration.SinceYearSuffixRegex.Match(beforeStr);
                if (yearMatch.Success)
                {
                    var yearString = yearMatch.Groups[Constants.YearGroupName].Value;
                    var yearEr     = new ExtractResult {
                        Text = yearString
                    };
                    var year = Convert.ToInt32((double)(numberParser.Parse(yearEr).Value ?? 0));
                    referenceTime = DateObject.MinValue.SafeCreateFromValue(year, 1, 1);
                }

                resultDateTime = DurationParsingUtil.ShiftDateTime(timex, referenceTime.AddDays(swift), true);

                ((DateTimeResolutionResult)durationParseResult.Value).Mod = Constants.AFTER_MOD;
            }

            if (resultDateTime != referenceTime)
            {
                if (mode.Equals(AgoLaterMode.Date))
                {
                    ret.Timex = $"{DateTimeFormatUtil.LuisDate(resultDateTime)}";
                }
                else if (mode.Equals(AgoLaterMode.DateTime))
                {
                    ret.Timex = $"{DateTimeFormatUtil.LuisDateTime(resultDateTime)}";
                }

                ret.FutureValue         = ret.PastValue = resultDateTime;
                ret.SubDateTimeEntities = new List <object> {
                    durationParseResult
                };
                ret.Success = true;
            }

            return(ret);
        }
示例#47
0
        // parse "this night"
        private DateTimeResolutionResult ParseSpecificNight(string text, DateObject referenceTime)
        {
            var    ret = new DateTimeResolutionResult();
            var    trimmedText = text.Trim();
            int    beginHour, endHour, endMin = 0;
            string timeStr;

            // handle 昨晚,今晨
            if (this.config.SpecificTimeOfDayRegex.IsExactMatch(trimmedText, trim: true))
            {
                if (!this.config.GetMatchedTimeRangeAndSwift(trimmedText, out timeStr, out beginHour, out endHour, out int swift))
                {
                    return(ret);
                }

                var date = referenceTime.AddDays(swift).Date;
                int day = date.Day, month = date.Month, year = date.Year;

                ret.Timex         = DateTimeFormatUtil.FormatDate(date) + timeStr;
                ret.FutureValue   =
                    ret.PastValue =
                        new Tuple <DateObject, DateObject>(
                            DateObject.MinValue.SafeCreateFromValue(year, month, day, beginHour, 0, 0),
                            DateObject.MinValue.SafeCreateFromValue(year, month, day, endHour, endMin, endMin));
                ret.Success = true;
                return(ret);
            }

            // handle morning, afternoon..
            if (!this.config.GetMatchedTimeRange(trimmedText, out timeStr, out beginHour, out endHour, out endMin))
            {
                return(ret);
            }

            if (this.config.SpecificTimeOfDayRegex.IsExactMatch(trimmedText, trim: true))
            {
                var swift = 0;
                if (this.config.NextRegex.IsMatch(trimmedText))
                {
                    swift = 1;
                }
                else if (this.config.LastRegex.IsMatch(trimmedText))
                {
                    swift = -1;
                }

                var date = referenceTime.AddDays(swift).Date;
                int day = date.Day, month = date.Month, year = date.Year;

                ret.Timex         = DateTimeFormatUtil.FormatDate(date) + timeStr;
                ret.FutureValue   =
                    ret.PastValue =
                        new Tuple <DateObject, DateObject>(
                            DateObject.MinValue.SafeCreateFromValue(year, month, day, beginHour, 0, 0),
                            DateObject.MinValue.SafeCreateFromValue(year, month, day, endHour, endMin, endMin));
                ret.Success = true;
                return(ret);
            }

            // handle Date followed by morning, afternoon
            var match = this.config.TimeOfDayRegex.Match(trimmedText);

            if (match.Success)
            {
                var beforeStr = trimmedText.Substring(0, match.Index).Trim();
                var ers       = this.config.DateExtractor.Extract(beforeStr, referenceTime);

                if (ers.Count == 0 || ers[0].Length != beforeStr.Length)
                {
                    return(ret);
                }

                var pr         = this.config.DateParser.Parse(ers[0], referenceTime);
                var futureDate = (DateObject)((DateTimeResolutionResult)pr.Value).FutureValue;
                var pastDate   = (DateObject)((DateTimeResolutionResult)pr.Value).PastValue;

                ret.Timex = pr.TimexStr + timeStr;

                ret.FutureValue =
                    new Tuple <DateObject, DateObject>(
                        DateObject.MinValue.SafeCreateFromValue(futureDate.Year, futureDate.Month, futureDate.Day, beginHour, 0, 0),
                        DateObject.MinValue.SafeCreateFromValue(futureDate.Year, futureDate.Month, futureDate.Day, endHour, endMin, endMin));

                ret.PastValue =
                    new Tuple <DateObject, DateObject>(
                        DateObject.MinValue.SafeCreateFromValue(pastDate.Year, pastDate.Month, pastDate.Day, beginHour, 0, 0),
                        DateObject.MinValue.SafeCreateFromValue(pastDate.Year, pastDate.Month, pastDate.Day, endHour, endMin, endMin));

                ret.Success = true;

                return(ret);
            }

            return(ret);
        }
        private DateTimeResolutionResult ParseTimeOfToday(string text, DateObject referenceTime)
        {
            var ret = new DateTimeResolutionResult();
            var ers = SingleTimeExtractor.Extract(text, referenceTime);

            if (ers.Count != 1)
            {
                return(ret);
            }

            // TODO: Add reference time
            var pr = this.config.TimeParser.Parse(ers[0], referenceTime);

            if (pr.Value == null)
            {
                return(ret);
            }

            var time = (DateObject)((DateTimeResolutionResult)pr.Value).FutureValue;

            var hour = time.Hour;
            var min  = time.Minute;
            var sec  = time.Second;

            var match = JapaneseDateTimeExtractorConfiguration.TimeOfTodayRegex.Match(text);

            if (match.Success)
            {
                var matchStr = match.Value.ToLowerInvariant();
                var swift    = 0;
                switch (matchStr)
                {
                case "今晚":
                    if (hour < Constants.HalfDayHourCount)
                    {
                        hour += Constants.HalfDayHourCount;
                    }

                    break;

                case "今早":
                case "今晨":
                    if (hour >= Constants.HalfDayHourCount)
                    {
                        hour -= Constants.HalfDayHourCount;
                    }

                    break;

                case "明晚":
                    swift = 1;
                    if (hour < Constants.HalfDayHourCount)
                    {
                        hour += Constants.HalfDayHourCount;
                    }

                    break;

                case "明早":
                case "明晨":
                    swift = 1;
                    if (hour >= Constants.HalfDayHourCount)
                    {
                        hour -= Constants.HalfDayHourCount;
                    }

                    break;

                case "昨晚":
                    swift = -1;
                    if (hour < Constants.HalfDayHourCount)
                    {
                        hour += Constants.HalfDayHourCount;
                    }

                    break;

                default:
                    break;
                }

                var date = referenceTime.AddDays(swift).Date;

                // in this situation, luisStr cannot end up with "ampm", because we always have a "morning" or "night"
                var timeStr = pr.TimexStr;
                if (timeStr.EndsWith(Constants.Comment_AmPm))
                {
                    timeStr = timeStr.Substring(0, timeStr.Length - 4);
                }

                timeStr = "T" + hour.ToString("D2") + timeStr.Substring(3);

                ret.Timex       = DateTimeFormatUtil.FormatDate(date) + timeStr;
                ret.FutureValue = ret.PastValue = DateObject.MinValue.SafeCreateFromValue(date.Year, date.Month, date.Day, hour, min, sec);
                ret.Success     = true;
                return(ret);
            }

            return(ret);
        }
        // Parse specific TimeOfDay like "this night", "early morning", "late evening"
        protected virtual DateTimeResolutionResult ParseSpecificTimeOfDay(string text, DateObject referenceTime)
        {
            var ret        = new DateTimeResolutionResult();
            var trimedText = text.Trim().ToLowerInvariant();
            var timeText   = trimedText;

            var match = this.Config.PeriodTimeOfDayWithDateRegex.Match(trimedText);

            // Extract early/late prefix from text if any
            bool hasEarly = false, hasLate = false;

            if (match.Success)
            {
                timeText = match.Groups["timeOfDay"].Value;
                if (!string.IsNullOrEmpty(match.Groups["early"].Value))
                {
                    hasEarly    = true;
                    ret.Comment = Constants.Comment_Early;
                }

                if (!hasEarly && !string.IsNullOrEmpty(match.Groups["late"].Value))
                {
                    hasLate     = true;
                    ret.Comment = Constants.Comment_Late;
                }
            }
            else
            {
                match = this.Config.AmDescRegex.Match(trimedText);
                if (!match.Success)
                {
                    match = this.Config.PmDescRegex.Match(trimedText);
                }

                if (match.Success)
                {
                    timeText = match.Value;
                }
            }

            // Handle time of day

            // Late/early only works with time of day
            // Only standard time of day (morinng, afternoon, evening and night) will not directly return
            if (!this.Config.GetMatchedTimeRange(timeText, out string timeStr, out int beginHour, out int endHour, out int endMin))
            {
                return(ret);
            }

            // Modify time period if "early" or "late" exists
            // Since 'time of day' is defined as four hour periods,
            // the first 2 hours represent early, the later 2 hours represent late
            if (hasEarly)
            {
                endHour = beginHour + 2;
                // Handling speical case: night ends with 23:59
                if (endMin == 59)
                {
                    endMin = 0;
                }
            }
            else if (hasLate)
            {
                beginHour = beginHour + 2;
            }

            match = this.Config.SpecificTimeOfDayRegex.Match(trimedText);
            if (match.Success && match.Index == 0 && match.Length == trimedText.Length)
            {
                var swift = this.Config.GetSwiftPrefix(trimedText);

                var date = referenceTime.AddDays(swift).Date;
                int day = date.Day, month = date.Month, year = date.Year;

                ret.Timex = FormatUtil.FormatDate(date) + timeStr;

                ret.FutureValue   =
                    ret.PastValue =
                        new Tuple <DateObject, DateObject>(DateObject.MinValue.SafeCreateFromValue(year, month, day, beginHour, 0, 0),
                                                           DateObject.MinValue.SafeCreateFromValue(year, month, day, endHour, endMin, endMin));

                ret.Success = true;
                return(ret);
            }

            // Handle Date followed by morning, afternoon and morning, afternoon followed by Date
            match = this.Config.PeriodTimeOfDayWithDateRegex.Match(trimedText);

            if (!match.Success)
            {
                match = this.Config.AmDescRegex.Match(trimedText);
                if (!match.Success)
                {
                    match = this.Config.PmDescRegex.Match(trimedText);
                }
            }

            if (match.Success)
            {
                var beforeStr = trimedText.Substring(0, match.Index).Trim();
                var afterStr  = trimedText.Substring(match.Index + match.Length).Trim();

                // Eliminate time period, if any
                var timePeriodErs = this.Config.TimePeriodExtractor.Extract(beforeStr);
                if (timePeriodErs.Count > 0)
                {
                    beforeStr = beforeStr.Remove(timePeriodErs[0].Start ?? 0, timePeriodErs[0].Length ?? 0).Trim();
                }
                else
                {
                    timePeriodErs = this.Config.TimePeriodExtractor.Extract(afterStr);
                    if (timePeriodErs.Count > 0)
                    {
                        afterStr = afterStr.Remove(timePeriodErs[0].Start ?? 0, timePeriodErs[0].Length ?? 0).Trim();
                    }
                }

                var ers = this.Config.DateExtractor.Extract(beforeStr, referenceTime);

                if (ers.Count == 0 || ers[0].Length != beforeStr.Length)
                {
                    var valid = false;

                    if (ers.Count > 0 && ers[0].Start == 0)
                    {
                        var midStr = beforeStr.Substring(ers[0].Start + ers[0].Length ?? 0);
                        if (string.IsNullOrWhiteSpace(midStr.Replace(',', ' ')))
                        {
                            valid = true;
                        }
                    }

                    if (!valid)
                    {
                        ers = this.Config.DateExtractor.Extract(afterStr, referenceTime);

                        if (ers.Count == 0 || ers[0].Length != afterStr.Length)
                        {
                            if (ers.Count > 0 && ers[0].Start + ers[0].Length == afterStr.Length)
                            {
                                var midStr = afterStr.Substring(0, ers[0].Start ?? 0);
                                if (string.IsNullOrWhiteSpace(midStr.Replace(',', ' ')))
                                {
                                    valid = true;
                                }
                            }
                        }
                        else
                        {
                            valid = true;
                        }
                    }

                    if (!valid)
                    {
                        return(ret);
                    }
                }

                var hasSpecificTimePeriod = false;
                if (timePeriodErs.Count > 0)
                {
                    var timePr = this.Config.TimePeriodParser.Parse(timePeriodErs[0], referenceTime);
                    if (timePr != null)
                    {
                        var periodFuture = (Tuple <DateObject, DateObject>)(((DateTimeResolutionResult)timePr.Value).FutureValue);
                        var periodPast   = (Tuple <DateObject, DateObject>)((DateTimeResolutionResult)timePr.Value).PastValue;

                        if (periodFuture == periodPast)
                        {
                            beginHour = periodFuture.Item1.Hour;
                            endHour   = periodFuture.Item2.Hour;
                        }
                        else
                        {
                            if (periodFuture.Item1.Hour >= beginHour || periodFuture.Item2.Hour <= endHour)
                            {
                                beginHour = periodFuture.Item1.Hour;
                                endHour   = periodFuture.Item2.Hour;
                            }
                            else
                            {
                                beginHour = periodPast.Item1.Hour;
                                endHour   = periodPast.Item2.Hour;
                            }
                        }

                        hasSpecificTimePeriod = true;
                    }
                }

                var pr         = this.Config.DateParser.Parse(ers[0], referenceTime);
                var futureDate = (DateObject)((DateTimeResolutionResult)pr.Value).FutureValue;
                var pastDate   = (DateObject)((DateTimeResolutionResult)pr.Value).PastValue;

                if (!hasSpecificTimePeriod)
                {
                    ret.Timex = pr.TimexStr + timeStr;
                }
                else
                {
                    ret.Timex = string.Format("({0}T{1},{0}T{2},PT{3}H)", pr.TimexStr, beginHour, endHour, endHour - beginHour);
                }

                ret.FutureValue =
                    new Tuple <DateObject, DateObject>(
                        DateObject.MinValue.SafeCreateFromValue(futureDate.Year, futureDate.Month, futureDate.Day, beginHour, 0, 0),
                        DateObject.MinValue.SafeCreateFromValue(futureDate.Year, futureDate.Month, futureDate.Day, endHour, endMin, endMin));

                ret.PastValue =
                    new Tuple <DateObject, DateObject>(
                        DateObject.MinValue.SafeCreateFromValue(pastDate.Year, pastDate.Month, pastDate.Day, beginHour, 0, 0),
                        DateObject.MinValue.SafeCreateFromValue(pastDate.Year, pastDate.Month, pastDate.Day, endHour, endMin, endMin));

                ret.Success = true;

                return(ret);
            }

            return(ret);
        }
示例#50
0
        // match several other cases
        // including '今天', '后天', '十三日'
        protected DateTimeResolutionResult ParseImplicitDate(string text, DateObject referenceDate)
        {
            var ret = new DateTimeResolutionResult();

            // handle "十二日" "明年这个月三日" "本月十一日"
            var match = ChineseDateExtractorConfiguration.SpecialDate.MatchExact(text, trim: true);

            if (match.Success)
            {
                var yearStr  = match.Groups["thisyear"].Value;
                var monthStr = match.Groups["thismonth"].Value;
                var dayStr   = match.Groups["day"].Value;

                int month = referenceDate.Month, year = referenceDate.Year;
                var day = this.config.DayOfMonth[dayStr];

                bool hasYear = false, hasMonth = false;

                if (!string.IsNullOrEmpty(monthStr))
                {
                    hasMonth = true;
                    if (ChineseDateExtractorConfiguration.NextRe.Match(monthStr).Success)
                    {
                        month++;
                        if (month == Constants.MaxMonth + 1)
                        {
                            month = Constants.MinMonth;
                            year++;
                        }
                    }
                    else if (ChineseDateExtractorConfiguration.LastRe.Match(monthStr).Success)
                    {
                        month--;
                        if (month == Constants.MinMonth - 1)
                        {
                            month = Constants.MaxMonth;
                            year--;
                        }
                    }

                    if (!string.IsNullOrEmpty(yearStr))
                    {
                        hasYear = true;
                        if (ChineseDateExtractorConfiguration.NextRe.Match(yearStr).Success)
                        {
                            ++year;
                        }
                        else if (ChineseDateExtractorConfiguration.LastRe.Match(yearStr).Success)
                        {
                            --year;
                        }
                    }
                }

                ret.Timex = DateTimeFormatUtil.LuisDate(hasYear ? year : -1, hasMonth ? month : -1, day);

                DateObject futureDate, pastDate;

                if (day > GetMonthMaxDay(year, month))
                {
                    var futureMonth = month + 1;
                    var pastMonth   = month - 1;
                    var futureYear  = year;
                    var pastYear    = year;

                    if (futureMonth == Constants.MaxMonth + 1)
                    {
                        futureMonth = Constants.MinMonth;
                        futureYear  = year++;
                    }

                    if (pastMonth == Constants.MinMonth - 1)
                    {
                        pastMonth = Constants.MaxMonth;
                        pastYear  = year--;
                    }

                    var isFutureValid = DateObjectExtension.IsValidDate(futureYear, futureMonth, day);
                    var isPastValid   = DateObjectExtension.IsValidDate(pastYear, pastMonth, day);

                    if (isFutureValid && isPastValid)
                    {
                        futureDate = DateObject.MinValue.SafeCreateFromValue(futureYear, futureMonth, day);
                        pastDate   = DateObject.MinValue.SafeCreateFromValue(pastYear, pastMonth, day);
                    }
                    else if (isFutureValid && !isPastValid)
                    {
                        futureDate = pastDate = DateObject.MinValue.SafeCreateFromValue(futureYear, futureMonth, day);
                    }
                    else if (!isFutureValid && !isPastValid)
                    {
                        futureDate = pastDate = DateObject.MinValue.SafeCreateFromValue(pastYear, pastMonth, day);
                    }
                    else
                    {
                        // Fall back to normal cases, might lead to resolution failure
                        // TODO: Ideally, this failure should be filtered out in extract phase
                        futureDate = pastDate = DateObject.MinValue.SafeCreateFromValue(year, month, day);
                    }
                }
                else
                {
                    futureDate = DateObject.MinValue.SafeCreateFromValue(year, month, day);
                    pastDate   = DateObject.MinValue.SafeCreateFromValue(year, month, day);

                    if (!hasMonth)
                    {
                        if (futureDate < referenceDate)
                        {
                            if (IsValidDate(year, month + 1, day))
                            {
                                futureDate = futureDate.AddMonths(1);
                            }
                        }

                        if (pastDate >= referenceDate)
                        {
                            if (IsValidDate(year, month - 1, day))
                            {
                                pastDate = pastDate.AddMonths(-1);
                            }
                            else if (IsNonleapYearFeb29th(year, month - 1, day))
                            {
                                pastDate = pastDate.AddMonths(-2);
                            }
                        }
                    }
                    else if (!hasYear)
                    {
                        if (futureDate < referenceDate)
                        {
                            if (IsValidDate(year + 1, month, day))
                            {
                                futureDate = futureDate.AddYears(1);
                            }
                        }

                        if (pastDate >= referenceDate)
                        {
                            if (IsValidDate(year - 1, month, day))
                            {
                                pastDate = pastDate.AddYears(-1);
                            }
                        }
                    }
                }

                ret.FutureValue = futureDate;
                ret.PastValue   = pastDate;
                ret.Success     = true;

                return(ret);
            }

            // handle cases like "昨日", "明日", "大后天"
            match = ChineseDateExtractorConfiguration.SpecialDayRegex.MatchExact(text, trim: true);

            if (match.Success)
            {
                var value = referenceDate.AddDays(ChineseDateTimeParserConfiguration.GetSwiftDay(match.Value));
                ret.Timex       = DateTimeFormatUtil.LuisDate(value);
                ret.FutureValue = ret.PastValue = DateObject.MinValue.SafeCreateFromValue(value.Year, value.Month, value.Day);
                ret.Success     = true;

                return(ret);
            }

            if (!ret.Success)
            {
                ret = MatchThisWeekday(text, referenceDate);
            }

            if (!ret.Success)
            {
                ret = MatchNextWeekday(text, referenceDate);
            }

            if (!ret.Success)
            {
                ret = MatchLastWeekday(text, referenceDate);
            }

            if (!ret.Success)
            {
                ret = MatchWeekdayAlone(text, referenceDate);
            }

            return(ret);
        }
        private DateTimeResolutionResult ParseTimeOfToday(string text, DateObject referenceTime)
        {
            var ret         = new DateTimeResolutionResult();
            var trimmedText = text.Trim();

            int    hour = 0, min = 0, sec = 0;
            string timeStr;

            var wholeMatch = this.config.SimpleTimeOfTodayAfterRegex.MatchExact(trimmedText, trim: true);

            if (!wholeMatch.Success)
            {
                wholeMatch = this.config.SimpleTimeOfTodayBeforeRegex.MatchExact(trimmedText, trim: true);
            }

            if (wholeMatch.Success)
            {
                var hourStr = wholeMatch.Groups[Constants.HourGroupName].Value;
                if (string.IsNullOrEmpty(hourStr))
                {
                    hourStr = wholeMatch.Groups["hournum"].Value;
                    hour    = this.config.Numbers[hourStr];
                }
                else
                {
                    hour = int.Parse(hourStr);
                }

                timeStr = "T" + hour.ToString("D2");
            }
            else
            {
                var ers = this.config.TimeExtractor.Extract(trimmedText, referenceTime);
                if (ers.Count != 1)
                {
                    ers = this.config.TimeExtractor.Extract(this.config.TokenBeforeTime + trimmedText, referenceTime);
                    if (ers.Count == 1)
                    {
                        ers[0].Start -= this.config.TokenBeforeTime.Length;
                    }
                    else
                    {
                        return(ret);
                    }
                }

                var pr = this.config.TimeParser.Parse(ers[0], referenceTime);
                if (pr.Value == null)
                {
                    return(ret);
                }

                var time = (DateObject)((DateTimeResolutionResult)pr.Value).FutureValue;

                hour    = time.Hour;
                min     = time.Minute;
                sec     = time.Second;
                timeStr = pr.TimexStr;
            }

            var match = this.config.SpecificTimeOfDayRegex.Match(trimmedText);

            if (match.Success)
            {
                var matchStr = match.Value;

                // Handle "last", "next"
                var swift = this.config.GetSwiftDay(matchStr);

                var date = referenceTime.AddDays(swift).Date;

                // Handle "morning", "afternoon"
                hour = this.config.GetHour(matchStr, hour);

                // In this situation, timeStr cannot end up with "ampm", because we always have a "morning" or "night"
                if (timeStr.EndsWith(Constants.Comment_AmPm, StringComparison.Ordinal))
                {
                    timeStr = timeStr.Substring(0, timeStr.Length - 4);
                }

                timeStr = "T" + hour.ToString("D2") + timeStr.Substring(3);

                ret.Timex       = DateTimeFormatUtil.FormatDate(date) + timeStr;
                ret.FutureValue = ret.PastValue = DateObject.MinValue.SafeCreateFromValue(date.Year, date.Month, date.Day, hour, min, sec);
                ret.Success     = true;
                return(ret);
            }

            return(ret);
        }
示例#52
0
        private static DateTimeResolutionResult GetAgoLaterResult(
            DateTimeParseResult durationParseResult,
            string afterStr,
            string beforeStr,
            DateObject referenceTime,
            IParser numberParser,
            IDateTimeUtilityConfiguration utilityConfiguration,
            AgoLaterMode mode,
            SwiftDayDelegate swiftDay)
        {
            var ret            = new DateTimeResolutionResult();
            var resultDateTime = referenceTime;
            var timex          = durationParseResult.TimexStr;

            if (((DateTimeResolutionResult)durationParseResult.Value).Mod == Constants.MORE_THAN_MOD)
            {
                ret.Mod = Constants.MORE_THAN_MOD;
            }
            else if (((DateTimeResolutionResult)durationParseResult.Value).Mod == Constants.LESS_THAN_MOD)
            {
                ret.Mod = Constants.LESS_THAN_MOD;
            }

            int    swift = 0;
            bool   isMatch = false, isLater = false;
            string dayStr = null;

            // Item2 is a label identifying the regex defined in Item1
            var agoLaterRegexTuples = new List <(Regex, string)>
            {
                (utilityConfiguration.AgoRegex, Constants.AGO_LABEL),
                (utilityConfiguration.LaterRegex, Constants.LATER_LABEL),
            };

            // AgoRegex and LaterRegex cases
            foreach (var regex in agoLaterRegexTuples)
            {
                // Match in afterStr
                if (MatchingUtil.ContainsAgoLaterIndex(afterStr, regex.Item1, inSuffix: true))
                {
                    isMatch = true;
                    isLater = regex.Item2 == Constants.LATER_LABEL;
                    var match = regex.Item1.Match(afterStr);
                    dayStr = match.Groups["day"].Value;
                }

                if (utilityConfiguration.CheckBothBeforeAfter)
                {
                    // Match split between beforeStr and afterStr
                    if (string.IsNullOrEmpty(dayStr) && isMatch)
                    {
                        var match = regex.Item1.Match(beforeStr + " " + afterStr);
                        dayStr = match.Groups["day"].Value;
                    }

                    // Match in beforeStr
                    if (string.IsNullOrEmpty(dayStr) && MatchingUtil.ContainsAgoLaterIndex(beforeStr, regex.Item1, inSuffix: false))
                    {
                        isMatch = true;
                        isLater = regex.Item2 == Constants.LATER_LABEL;
                        var match = regex.Item1.Match(beforeStr);
                        dayStr = match.Groups["day"].Value;
                    }
                }

                if (isMatch)
                {
                    break;
                }
            }

            // InConnectorRegex cases
            if (!isMatch)
            {
                if (MatchingUtil.ContainsTermIndex(beforeStr, utilityConfiguration.InConnectorRegex))
                {
                    // Match in afterStr
                    isMatch = isLater = true;
                    var match = utilityConfiguration.LaterRegex.Match(afterStr);
                    dayStr = match.Groups["day"].Value;
                }
                else if (utilityConfiguration.CheckBothBeforeAfter && MatchingUtil.ContainsAgoLaterIndex(afterStr, utilityConfiguration.InConnectorRegex, inSuffix: true))
                {
                    // Match in beforeStr
                    isMatch = isLater = true;
                    var match = utilityConfiguration.LaterRegex.Match(beforeStr);
                    dayStr = match.Groups["day"].Value;
                }
            }

            if (isMatch)
            {
                // Handle cases like "3 days before yesterday", "3 days after tomorrow"
                if (!string.IsNullOrEmpty(dayStr))
                {
                    swift = swiftDay(dayStr);
                }

                if (isLater)
                {
                    var yearMatch = utilityConfiguration.SinceYearSuffixRegex.Match(afterStr);
                    if (yearMatch.Success)
                    {
                        var yearString = yearMatch.Groups[Constants.YearGroupName].Value;
                        var yearEr     = new ExtractResult {
                            Text = yearString
                        };
                        var year = Convert.ToInt32((double)(numberParser.Parse(yearEr).Value ?? 0));
                        referenceTime = DateObject.MinValue.SafeCreateFromValue(year, 1, 1);
                    }
                }

                var isFuture = isLater;
                resultDateTime = DurationParsingUtil.ShiftDateTime(timex, referenceTime.AddDays(swift), future: isFuture);

                ((DateTimeResolutionResult)durationParseResult.Value).Mod = isLater ? Constants.AFTER_MOD : Constants.BEFORE_MOD;
            }

            if (resultDateTime != referenceTime)
            {
                if (mode.Equals(AgoLaterMode.Date))
                {
                    ret.Timex = $"{DateTimeFormatUtil.LuisDate(resultDateTime)}";
                }
                else if (mode.Equals(AgoLaterMode.DateTime))
                {
                    ret.Timex = $"{DateTimeFormatUtil.LuisDateTime(resultDateTime)}";
                }

                ret.FutureValue         = ret.PastValue = resultDateTime;
                ret.SubDateTimeEntities = new List <object> {
                    durationParseResult
                };
                ret.Success = true;
            }

            return(ret);
        }
    protected Dundas.Charting.WebControl.Chart DoChart(DataTable inDT, string sType, string product_type)
    {
        Dundas.Charting.WebControl.Chart chart = new Dundas.Charting.WebControl.Chart();
        DataTable dataSource = inDT.Copy();
        DataView  dv         = dataSource.DefaultView;

        this.SetChartStyle(chart);

        ChartArea chartarea;

        chartarea = chart.ChartAreas.Add("DoChart");
        chartarea.AxisX.Interval = 2;
        chartarea.AxisY.Title    = "CYCLE_TIME";
        //chartarea.AxisY2.Title = "TARGET";

        chartarea.AxisY.LabelStyle.Format = "N0";
        //chartarea.AxisY2.LabelStyle.Format = "N0";
        chartarea.AxisX.MajorGrid.LineColor = System.Drawing.Color.Silver;
        chartarea.AxisX.MinorGrid.LineColor = System.Drawing.Color.Silver;
        chartarea.AxisY.MajorGrid.LineColor = System.Drawing.Color.Silver;
        chartarea.AxisY.MinorGrid.LineColor = System.Drawing.Color.Silver;
        //chartarea.AxisY2.MajorGrid.Enabled = false;
        //chartarea.AxisY2.MinorGrid.Enabled = false;

        //設定Chart的Title
        DataTable dtDistinct = dataSource.DefaultView.ToTable(true, "SHOP");
        string    sShop      = dtDistinct.Rows[0]["SHOP"].ToString();

        sShop = sShop.Replace("T0", "C2");

        //chart.Titles.Add(sShop + "_" + sType + "PUT");
        chart.Titles.Add(sShop + "_" + product_type + "_" + sType);

        //設定Series(DAILY_PLAN_QTY,MTD_PLAN_QTY,DAILY_ACTUAL_QTY,MTD_ACTUAL_QTY)
        for (int i = 0; i < dataSource.Columns.Count; i++)
        {
            if (dataSource.Columns[i].ColumnName.ToUpper().Contains("CYCLE_TIME") || dataSource.Columns[i].ColumnName.ToUpper().Contains("TARGET"))
            {
                Series series;
                series           = chart.Series.Add(dataSource.Columns[i].ColumnName);
                series.ChartArea = chartarea.Name;
                series.EmptyPointStyle.BorderWidth = 0;
                series.ShowLabelAsValue            = false;

                if (dataSource.Columns[i].ColumnName.ToUpper().Contains("TARGET"))
                {
                    series.Type              = SeriesChartType.Line;
                    series.MarkerStyle       = MarkerStyle.Circle;
                    series.MarkerSize        = 6;
                    series.MarkerBorderWidth = 1;
                    series.MarkerBorderColor = System.Drawing.Color.Black;
                    series.BorderWidth       = 1;
                    //series.YAxisType = AxisType.Secondary;
                    series.ToolTip     = "#VALX #SERIESNAME:#VAL{N0}";
                    series.LabelFormat = "N0";
                }
                else
                {
                    series.Type        = SeriesChartType.Column;
                    series.YAxisType   = AxisType.Primary;
                    series.BorderColor = System.Drawing.Color.Black;
                    series.BorderWidth = 1;
                    series.ToolTip     = "#VALX #SERIESNAME:#VAL{N0}";
                    series.LabelFormat = "N0";
                }
            }
        }

        //日期迴圈,補足月初到月底的每一天都要呈現在Chart上面
        //因為來源的Table有些會缺少月中的某些天(MPS沒有modeling)
        System.DateTime dt = System.DateTime.Now;
        System.DateTime ThisMonBeginDay = new System.DateTime(dt.Year, dt.Month, 1);
        System.DateTime ThisMonEndDay   = ThisMonBeginDay.AddMonths(1).AddDays(-1);

        while (DateDiff(ThisMonBeginDay, ThisMonEndDay) >= 0)
        {
            foreach (Series series in chart.Series)
            {
                //用dataview來作rowfilter,有存在dv中的shift_date就呈現該column的值,不然就畫0
                //dv.RowFilter = "shift_date='" + ThisMonBeginDay.ToString("yyyyMMdd") + "' and type='" + sType + "'";
                dv.RowFilter = "shift_date='" + ThisMonBeginDay.ToString("yyyyMMdd") + "'";
                if (dv.Count > 0)
                {
                    series.Points.AddXY(ThisMonBeginDay.ToString("yyyyMMdd"), dv[0][series.Name].ToString());
                }
                else
                {
                    series.Points.AddXY(ThisMonBeginDay.ToString("yyyyMMdd"), Double.NaN);
                }
            }
            ThisMonBeginDay = ThisMonBeginDay.AddDays(1);
        }
        return(chart);
    }
示例#54
0
        public static TimexProperty TimexDateAdd(TimexProperty start, TimexProperty duration)
        {
            if (start.DayOfWeek != null)
            {
                var end = start.Clone();
                if (duration.Days != null)
                {
                    end.DayOfWeek += (int)duration.Days;
                }

                return(end);
            }

            if (start.Month != null && start.DayOfMonth != null)
            {
                if (duration.Days != null)
                {
                    if (start.Year != null)
                    {
                        var d = new System.DateTime(start.Year.Value, start.Month.Value, start.DayOfMonth.Value, 0, 0, 0);
                        d = d.AddDays((double)duration.Days.Value);

                        return(new TimexProperty {
                            Year = d.Year,
                            Month = d.Month,
                            DayOfMonth = d.Day
                        });
                    }
                    else
                    {
                        var d = new System.DateTime(2001, start.Month.Value, start.DayOfMonth.Value, 0, 0, 0);
                        d = d.AddDays((double)duration.Days.Value);

                        return(new TimexProperty
                        {
                            Month = d.Month,
                            DayOfMonth = d.Day
                        });
                    }
                }

                if (duration.Years != null)
                {
                    if (start.Year != null)
                    {
                        return(new TimexProperty
                        {
                            Year = (int)(start.Year.Value + duration.Years.Value),
                            Month = start.Month,
                            DayOfMonth = start.DayOfMonth
                        });
                    }
                }

                if (duration.Month != null)
                {
                    if (start.Month != null)
                    {
                        return(new TimexProperty
                        {
                            Year = start.Year,
                            Month = (int)(start.Month + duration.Months),
                            DayOfMonth = start.DayOfMonth
                        });
                    }
                }
            }
            return(start);
        }
        // parse specific TimeOfDay like "this night", "early morning", "late evening"
        protected virtual DateTimeResolutionResult ParseSpecificTimeOfDay(string text, DateObject referenceTime)
        {
            var ret        = new DateTimeResolutionResult();
            var trimedText = text.Trim().ToLowerInvariant();
            var timeText   = trimedText;

            var match = this.Config.PeriodTimeOfDayWithDateRegex.Match(trimedText);

            // extract early/late prefix from text if any
            bool hasEarly = false, hasLate = false;

            if (match.Success)
            {
                timeText = match.Groups["timeOfDay"].Value;
                if (!string.IsNullOrEmpty(match.Groups["early"].Value))
                {
                    hasEarly    = true;
                    ret.Comment = "early";
                }
                if (!hasEarly && !string.IsNullOrEmpty(match.Groups["late"].Value))
                {
                    hasLate     = true;
                    ret.Comment = "late";
                }
            }

            // handle time of day
            int    beginHour, endHour, endMin = 0;
            string timeStr;

            // late/early is only working iwth time of day
            // only standard time of day (morinng, afternoon, evening and night) will not directly return
            if (!this.Config.GetMatchedTimeRange(timeText, out timeStr, out beginHour, out endHour, out endMin))
            {
                return(ret);
            }

            // modify time period if "early" or "late" is existed
            // since time of day is all defined as four hours,
            // using previous 2 hours represents early
            // late 2 hours represents late
            if (hasEarly)
            {
                endHour = beginHour + 2;
                // handling speical case: night end with 23:59
                if (endMin == 59)
                {
                    endMin = 0;
                }
            }
            else if (hasLate)
            {
                beginHour = beginHour + 2;
            }

            match = this.Config.SpecificTimeOfDayRegex.Match(trimedText);
            if (match.Success && match.Index == 0 && match.Length == trimedText.Length)
            {
                var swift = this.Config.GetSwiftPrefix(trimedText);

                var date = referenceTime.AddDays(swift).Date;
                int day = date.Day, month = date.Month, year = date.Year;

                ret.Timex = FormatUtil.FormatDate(date) + timeStr;

                ret.FutureValue   =
                    ret.PastValue =
                        new Tuple <DateObject, DateObject>(DateObject.MinValue.SafeCreateFromValue(year, month, day, beginHour, 0, 0),
                                                           DateObject.MinValue.SafeCreateFromValue(year, month, day, endHour, endMin, endMin));

                ret.Success = true;
                return(ret);
            }

            // handle Date followed by morning, afternoon
            // handle morning, afternoon followed by Date
            match = this.Config.PeriodTimeOfDayWithDateRegex.Match(trimedText);
            if (match.Success)
            {
                var beforeStr = trimedText.Substring(0, match.Index).Trim();
                var ers       = this.Config.DateExtractor.Extract(beforeStr);
                if (ers.Count == 0 || ers[0].Length != beforeStr.Length)
                {
                    var afterStr = trimedText.Substring(match.Index + match.Length).Trim();
                    ers = this.Config.DateExtractor.Extract(afterStr);
                    if (ers.Count == 0 || ers[0].Length != afterStr.Length)
                    {
                        return(ret);
                    }
                }
                var pr         = this.Config.DateParser.Parse(ers[0], referenceTime);
                var futureDate = (DateObject)((DateTimeResolutionResult)pr.Value).FutureValue;
                var pastDate   = (DateObject)((DateTimeResolutionResult)pr.Value).PastValue;

                ret.Timex = pr.TimexStr + timeStr;

                ret.FutureValue =
                    new Tuple <DateObject, DateObject>(
                        DateObject.MinValue.SafeCreateFromValue(futureDate.Year, futureDate.Month, futureDate.Day, beginHour, 0, 0),
                        DateObject.MinValue.SafeCreateFromValue(futureDate.Year, futureDate.Month, futureDate.Day, endHour, endMin, endMin));

                ret.PastValue =
                    new Tuple <DateObject, DateObject>(
                        DateObject.MinValue.SafeCreateFromValue(pastDate.Year, pastDate.Month, pastDate.Day, beginHour, 0, 0),
                        DateObject.MinValue.SafeCreateFromValue(pastDate.Year, pastDate.Month, pastDate.Day, endHour, endMin, endMin));

                ret.Success = true;

                return(ret);
            }

            return(ret);
        }
        public static DTParseResult Handle(IDateTimeParser timeParser, DateTimeExtra <PeriodType> extra, DateObject refTime)
        {
            //Left is a time
            var        left = extra.NamedEntity["left"];
            TimeResult leftResult, rightResult = null;

            // 下午四点十分到五点十分
            if (extra.Type == PeriodType.FullTime)
            {
                var leftExtract = new ExtractResult
                {
                    Start  = left.Index,
                    Length = left.Length,
                    Text   = left.Value,
                    Type   = Constants.SYS_DATETIME_TIME
                };
                leftResult = timeParser.Parse(leftExtract, refTime).Data as TimeResult;
            }
            // 下午四到五点
            else
            {
                leftResult = TimeFunctions.GetShortLeft(left.Value);
            }
            //Right is a time
            var right        = extra.NamedEntity["right"];
            var rightExtract = new ExtractResult
            {
                Start  = right.Index,
                Length = right.Length,
                Text   = right.Value,
                Type   = Constants.SYS_DATETIME_TIME
            };

            rightResult = timeParser.Parse(rightExtract, refTime).Data as TimeResult;

            var ret = new DTParseResult()
            {
                Success = true
            };

            //右侧没有Desc,左侧有
            if (rightResult.LowBound == -1 && leftResult.LowBound != -1 && rightResult.Hour <= leftResult.LowBound)
            {
                rightResult.Hour += 12;
            }
            int day   = refTime.Day,
                month = refTime.Month,
                year  = refTime.Year;
            //判断右侧是否比小测的小,如果比左侧的小,则增加一天
            int hour   = leftResult.Hour > 0 ? leftResult.Hour : 0,
                min    = leftResult.Minute > 0 ? leftResult.Minute : 0,
                second = leftResult.Second > 0 ? leftResult.Second : 0;

            var leftTime = new DateObject(year, month, day, hour, min, second);

            hour   = rightResult.Hour > 0 ? rightResult.Hour : 0;
            min    = rightResult.Minute > 0 ? rightResult.Minute : 0;
            second = rightResult.Second > 0 ? rightResult.Second : 0;

            var rightTime = new DateObject(year, month, day, hour, min, second);

            if (rightTime.Hour < leftTime.Hour)
            {
                rightTime = rightTime.AddDays(1);
            }

            ret.FutureValue = ret.PastValue = new Tuple <DateObject, DateObject>(leftTime, rightTime);

            var leftTimex  = BuildTimex(leftResult);
            var rightTimex = BuildTimex(rightResult);

            ret.Timex = $"({leftTimex},{rightTimex},{BuildSpan(leftResult, rightResult)})";
            return(ret);
        }
示例#57
0
        /// <summary>
        /// 时间段是否显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void CheckBox2CheckedChanged(object sender, EventArgs e)
        {
            Point cb1p = new Point();

            cb1p = this.comboBox1.Location;
            Point cb2p = new Point();

            cb2p = this.comboBox2.Location;
            Point cb3p = new Point();

            cb3p = this.comboBox3.Location;
            if (!this.checkBox2.Checked)
            {
                this.dateTimePicker1.Dispose();
                this.dateTimePicker2.Dispose();
                this.label1.Dispose();
                this.label2.Dispose();
                cb1p.X = cb1p.X - 250;
                cb2p.X = cb2p.X - 250;
                cb3p.X = cb3p.X - 250;
                this.comboBox1.Location = cb1p;
                this.comboBox2.Location = cb2p;
                this.comboBox3.Location = cb3p;
            }
            else
            {
                this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker();
                this.dateTimePicker2 = new System.Windows.Forms.DateTimePicker();
                this.label2          = new System.Windows.Forms.Label();
                this.label1          = new System.Windows.Forms.Label();

                this.panel1.Controls.Add(this.dateTimePicker1);
                this.panel1.Controls.Add(this.dateTimePicker2);
                this.panel1.Controls.Add(this.label1);
                this.panel1.Controls.Add(this.label2);
                //
                // dateTimePicker1
                //
                this.dateTimePicker1.Location = new System.Drawing.Point(224, 17);
                this.dateTimePicker1.Name     = "dateTimePicker1";
                this.dateTimePicker1.Size     = new System.Drawing.Size(103, 21);
                System.DateTime dt = System.DateTime.Now;
                dateTimePicker1.Value         = dt.AddDays(-7);
                this.dateTimePicker1.TabIndex = 38;
                //
                // dateTimePicker2
                //
                this.dateTimePicker2.Location = new System.Drawing.Point(356, 17);
                this.dateTimePicker2.Name     = "dateTimePicker2";
                this.dateTimePicker2.Size     = new System.Drawing.Size(103, 21);
                this.dateTimePicker2.TabIndex = 39;
                //
                // label1
                //
                this.label1.Location = new System.Drawing.Point(199, 20);
                this.label1.Name     = "label1";
                this.label1.Size     = new System.Drawing.Size(19, 18);
                this.label1.TabIndex = 40;
                this.label1.Text     = "起";
                //
                // label2
                //
                this.label2.Location = new System.Drawing.Point(333, 20);
                this.label2.Name     = "label2";
                this.label2.Size     = new System.Drawing.Size(17, 18);
                this.label2.TabIndex = 41;
                this.label2.Text     = "止";
                cb1p.X = cb1p.X + 250;
                cb2p.X = cb2p.X + 250;
                cb3p.X = cb3p.X + 250;
                this.comboBox1.Location            = cb1p;
                this.comboBox2.Location            = cb2p;
                this.comboBox3.Location            = cb3p;
                this.dateTimePicker1.ValueChanged += new EventHandler(conditionChanged);
                this.dateTimePicker2.ValueChanged += new EventHandler(conditionChanged);
            }
            getTestUnitList();
        }
示例#58
0
    // Update is called once per frame
    IEnumerator WheelRoutine()
    {
        if (ProfileAssistant.main.local_profile.daily_raward < System.DateTime.Now)
        {
            System.DateTime next_reward = System.DateTime.Now;
            if (next_reward.Hour > ProfileAssistant.main.local_profile.daily_raward.Hour)
            {
                next_reward = next_reward.AddDays(1);
            }

            ProfileAssistant.main.local_profile.daily_raward = new System.DateTime(
                next_reward.Year, next_reward.Month, next_reward.Day,
                ProjectParameters.main.dailyreward_hour, 0, 0);
        }
        else if (ProfileAssistant.main.local_profile["spin"] >= 1)
        {
            ProfileAssistant.main.local_profile["spin"]--;
            ItemCounter.RefreshAll();
        }
        else if (ProfileAssistant.main.local_profile["seed"] >= spinCost)
        {
            ProfileAssistant.main.local_profile["seed"] -= spinCost;
            ItemCounter.RefreshAll();
        }
        else
        {
            UIAssistant.main.ShowPage("Store");
            yield break;
        }

        ProfileAssistant.main.SaveUserInventory();

        UpdateCounters();

        Animation anim;

        locker.SetActive(true);

        anim = spinButton.GetComponent <Animation>();
        anim.Play("SWButtonHide");
        while (anim.isPlaying)
        {
            yield return(0);
        }
        spinButton.gameObject.SetActive(false);

        speed = 0;
        while (speed < 200)
        {
            speed = Mathf.MoveTowards(speed, 200, Time.deltaTime * 90);
            wheel.Rotate(0, 0, -speed * Time.deltaTime);
            yield return(0);
        }

        stopButton.gameObject.SetActive(true);
        anim = stopButton.GetComponent <Animation>();
        anim.Play("SWButtonShow");

        stopButton.onClick.RemoveAllListeners();

        bool        stoped = false;
        UnityAction stop   = () => {
            stoped = true;
        };

        stopButton.onClick.AddListener(stop);

        while (!stoped)
        {
            wheel.Rotate(0, 0, -speed * Time.deltaTime);
            yield return(0);
        }

        stopButton.onClick.RemoveAllListeners();
        anim.Play("SWButtonHide");

        int total_probability = 0;

        foreach (SpinWheelReward reward in ProjectParameters.main.spinWheelRewards)
        {
            total_probability += reward.probability;
        }
        target = Random.Range(0, total_probability);
        for (int i = 0; i < 8; i++)
        {
            target -= ProjectParameters.main.spinWheelRewards[i].probability;
            if (target <= 0)
            {
                target = i;
                break;
            }
        }

        target_angle  = target * 45 - 360;
        intrigue      = -10f + (Random.value > 0.5f ? 22.5f : -22.5f);
        target_angle -= 360 * 3;

        current_angle = wheel.eulerAngles.z;

        while (intrigue != 0 || current_angle != target_angle + intrigue)
        {
            speed         = Mathf.MoveTowards(speed, Mathf.Min(200, Mathf.Abs(current_angle - intrigue - target_angle) / 3 + 2), Time.deltaTime * 2f * (Mathf.Abs(speed) + 5f));
            current_angle = Mathf.MoveTowards(current_angle, target_angle + intrigue, speed * Time.deltaTime);
            wheel.transform.eulerAngles = Vector3.forward * current_angle;
            if (current_angle == target_angle + intrigue)
            {
                intrigue = 0;
            }
            yield return(0);
        }

        stopButton.gameObject.SetActive(false);
        locker.SetActive(false);

        rewardIcon.sprite = ProjectParameters.main.spinWheelRewards[target].icon;

        List <string> report = new List <string>();

        foreach (string reward in ProjectParameters.main.spinWheelRewards[target].items)
        {
            string[] args  = reward.Split(':');
            int      count = int.Parse(args[1]);
            ProfileAssistant.main.local_profile[args[0]] += count;
            report.Add(LocalizationAssistant.main[BerryStoreAssistant.main.items.Find(x => x.id == args[0]).localization_name] + (count > 1 ? "(x" + count.ToString() + ")" : ""));
        }

        lastReward = string.Join(", ", report.ToArray());

        ProfileAssistant.main.SaveUserInventory();

        UpdateCounters();

        ItemCounter.RefreshAll();

        UIAssistant.main.ShowPage("SpinWheelReward");
    }
示例#59
0
  void Update()
  {
      if (Saldoactual1.GetComponent <TMP_InputField>().text != "")
      {
          ValorTotalImpuestoo.GetComponent <TMP_InputField>().text = Saldoactual1.GetComponent <TMP_InputField>().text;
          if (Saldoanterior2.GetComponent <TMP_InputField>().text != "")
          {
              ValorTotalSaldo.GetComponent <TextMeshProUGUI>().text = "" + Convert.ToInt32(double.Parse(Saldoactual1.GetComponent <TMP_InputField>().text) +
                                                                                           double.Parse(Saldoanterior2.GetComponent <TMP_InputField>().text));
          }
          else
          {
              ValorTotalSaldo.GetComponent <TextMeshProUGUI>().text = Saldoactual1.GetComponent <TMP_InputField>().text;
          }
      }
      if (Nombre.GetComponent <TMP_InputField>().text != "")
      {
          Nombre2.GetComponent <TextMeshProUGUI>().text = Nombre.GetComponent <TMP_InputField>().text;
      }

      if (Cuenta.GetComponent <TMP_InputField>().text != "")
      {
          Cuenta2.GetComponent <TextMeshProUGUI>().text = Cuenta.GetComponent <TMP_InputField>().text;
      }

      if (FacturaDesde.GetComponent <TMP_InputField>().text != "" && FacturaHasta.GetComponent <TMP_InputField>().text != "")
      {
          Desde = System.DateTime.Parse(FacturaDesde.GetComponent <TMP_InputField>().text);
          Hasta = System.DateTime.Parse(FacturaHasta.GetComponent <TMP_InputField>().text);
          fechaFactura.GetComponent <TextMeshProUGUI>().text    = ((Desde.ToString(@Myformat)).ToUpper()).Replace(".", "");
          DiaDefactura.GetComponent <TextMeshProUGUI>().text    = (Desde.Subtract(Hasta)).ToString("%d");
          FacturaMes.GetComponent <TextMeshProUGUI>().text      = (Hasta.ToString("MMMM")).ToUpper();
          MesTarifaria.GetComponent <TextMeshProUGUI>().text    = (Desde.ToString("MMMM")).ToUpper();
          FechaMaximaPago.GetComponent <TextMeshProUGUI>().text = (((Desde.AddDays(20)).ToString(@Myformat)).ToUpper()).Replace(".", "");
          PagoSaldo.GetComponent <TextMeshProUGUI>().text       = (((Desde.AddDays(20)).ToString(@Myformat)).ToUpper()).Replace(".", "");
          if (Saldoanterior.GetComponent <TMP_InputField>().text != "")
          {
              Saldoanterior2.SetActive(true);
              FechaSuspencionpago.GetComponent <TextMeshProUGUI>().text = (((Desde.AddDays(23)).ToString(@Myformat)).ToUpper()).Replace(".", "");
          }

          FechaUltimoPago.GetComponent <TextMeshProUGUI>().text = (((Desde.AddDays(-2)).ToString(@Myformat)).ToUpper()).Replace(".", "");
          if (Generacion.GetComponent <TMP_InputField>().text != "" && Trasmision.GetComponent <TMP_InputField>().text != "" &&
              Distribucion.GetComponent <TMP_InputField>().text != "" && Comercializacion.GetComponent <TMP_InputField>().text != "" &&
              Perdidas.GetComponent <TMP_InputField>().text != "" && Restricciones.GetComponent <TMP_InputField>().text != "")
          {
              TarifaTarifaria.GetComponent <TextMeshProUGUI>().text = "" + ((double.Parse(Generacion.GetComponent <TMP_InputField>().text)) +
                                                                            (double.Parse(Trasmision.GetComponent <TMP_InputField>().text)) + (double.Parse(Distribucion.GetComponent <TMP_InputField>().text)) +
                                                                            (double.Parse(Comercializacion.GetComponent <TMP_InputField>().text)) + (double.Parse(Perdidas.GetComponent <TMP_InputField>().text)) +
                                                                            (double.Parse(Restricciones.GetComponent <TMP_InputField>().text)));
          }

          if ((Desde.AddDays(-2)).ToString("MMMM").Equals("enero") || (Desde.AddDays(-2)).ToString("MMMM").Equals("mayo") ||
              (Desde.AddDays(-2)).ToString("MMMM").Equals("septiembre"))
          {
              ValorUltimoPago.GetComponent <TextMeshProUGUI>().text = "80.000";
          }
          else if ((Desde.AddDays(-2)).ToString("MMMM").Equals("febrero") || (Desde.AddDays(-2)).ToString("MMMM").Equals("junio") ||
                   (Desde.AddDays(-2)).ToString("MMMM").Equals("octubre"))
          {
              ValorUltimoPago.GetComponent <TextMeshProUGUI>().text = "100.000";
          }
          else if ((Desde.AddDays(-2)).ToString("MMMM").Equals("marzo") || (Desde.AddDays(-2)).ToString("MMMM").Equals("julio") ||
                   (Desde.AddDays(-2)).ToString("MMMM").Equals("noviembre"))
          {
              ValorUltimoPago.GetComponent <TextMeshProUGUI>().text = "56.000";
          }
          else if ((Desde.AddDays(-2)).ToString("MMMM").Equals("abril") || (Desde.AddDays(-2)).ToString("MMMM").Equals("agosto") ||
                   (Desde.AddDays(-2)).ToString("MMMM").Equals("diciembre"))
          {
              ValorUltimoPago.GetComponent <TextMeshProUGUI>().text = "112.000";
          }
          TasaInteresMoratorio.SetActive(true);
      }

      if (LecturaActual.GetComponent <TMP_InputField>().text != "" && LecturaAnterior.GetComponent <TMP_InputField>().text != "")
      {
          ConsumoActiva.GetComponent <TextMeshProUGUI>().text = "" + ((double.Parse(LecturaActual.GetComponent <TMP_InputField>().text))
                                                                      - (double.Parse(LecturaAnterior.GetComponent <TMP_InputField>().text)));
          TotalKilowatios.GetComponent <TextMeshProUGUI>().text = "" + (((double.Parse(LecturaActual.GetComponent <TMP_InputField>().text))
                                                                         - (double.Parse(LecturaAnterior.GetComponent <TMP_InputField>().text))) * double.Parse(FactorMultiplicacion.GetComponent <TMP_InputField>().text));
          ConsumoActual.GetComponent <TextMeshProUGUI>().text     = TotalKilowatios.GetComponent <TextMeshProUGUI>().text;
          ConsumoActualDias.GetComponent <TextMeshProUGUI>().text = DiaDefactura.GetComponent <TextMeshProUGUI>().text;
          Consumoanterior.SetActive(true);
          ConsumoAnteriorDias.SetActive(true);
          ValorCuotaServicioDeEnergia.SetActive(true);
          GraficasCompletos.SetActive(true);
          KilowatiosTotales.GetComponent <TextMeshProUGUI>().text = TotalKilowatios.GetComponent <TextMeshProUGUI>().text;


          if (double.Parse(TotalKilowatios.GetComponent <TextMeshProUGUI>().text) >= 270)
          {
              Act1.GetComponent <TextMeshProUGUI>().text = TotalKilowatios.GetComponent <TextMeshProUGUI>().text;
              Actgraf1.SetActive(true);
              Act2.GetComponent <TextMeshProUGUI>().text = "";
              Actgraf2.SetActive(false);
              Act3.GetComponent <TextMeshProUGUI>().text = "";
              Actgraf3.SetActive(false);
              Act4.GetComponent <TextMeshProUGUI>().text = "";
              Actgraf4.SetActive(false);
          }
          else if (double.Parse(TotalKilowatios.GetComponent <TextMeshProUGUI>().text) >= 200 && double.Parse(TotalKilowatios.GetComponent <TextMeshProUGUI>().text) < 220)
          {
              Act2.GetComponent <TextMeshProUGUI>().text = TotalKilowatios.GetComponent <TextMeshProUGUI>().text;
              Actgraf2.SetActive(true);
              Act1.GetComponent <TextMeshProUGUI>().text = "";
              Actgraf1.SetActive(false);
              Act3.GetComponent <TextMeshProUGUI>().text = "";
              Actgraf3.SetActive(false);
              Act4.GetComponent <TextMeshProUGUI>().text = "";
              Actgraf4.SetActive(false);
          }
          else if (double.Parse(TotalKilowatios.GetComponent <TextMeshProUGUI>().text) >= 220 && double.Parse(TotalKilowatios.GetComponent <TextMeshProUGUI>().text) < 270)
          {
              Act3.GetComponent <TextMeshProUGUI>().text = TotalKilowatios.GetComponent <TextMeshProUGUI>().text;
              Actgraf3.SetActive(true);
              Act2.GetComponent <TextMeshProUGUI>().text = "";
              Actgraf2.SetActive(false);
              Act1.GetComponent <TextMeshProUGUI>().text = "";
              Actgraf1.SetActive(false);
              Act4.GetComponent <TextMeshProUGUI>().text = "";
              Actgraf4.SetActive(false);
          }
          else if (double.Parse(TotalKilowatios.GetComponent <TextMeshProUGUI>().text) < 200)
          {
              Act4.GetComponent <TextMeshProUGUI>().text = TotalKilowatios.GetComponent <TextMeshProUGUI>().text;
              Actgraf4.SetActive(true);
              Act2.GetComponent <TextMeshProUGUI>().text = "";
              Actgraf2.SetActive(false);
              Act3.GetComponent <TextMeshProUGUI>().text = "";
              Actgraf3.SetActive(false);
              Act1.GetComponent <TextMeshProUGUI>().text = "";
              Actgraf1.SetActive(false);
          }
          prom = Convert.ToInt32((double.Parse(kilmes1.GetComponent <TextMeshProUGUI>().text) +
                                  double.Parse(kilmes2.GetComponent <TextMeshProUGUI>().text) +
                                  double.Parse(kilmes3.GetComponent <TextMeshProUGUI>().text) +
                                  double.Parse(kilmes4.GetComponent <TextMeshProUGUI>().text) +
                                  double.Parse(kilmes5.GetComponent <TextMeshProUGUI>().text) +
                                  double.Parse(kilmes6.GetComponent <TextMeshProUGUI>().text) +
                                  double.Parse(TotalKilowatios.GetComponent <TextMeshProUGUI>().text)) / 7);
          mes1.GetComponent <TextMeshProUGUI>().text = ((Desde.AddMonths(-5)).ToString("MMM")).ToUpper();
          mes2.GetComponent <TextMeshProUGUI>().text = ((Desde.AddMonths(-4)).ToString("MMM")).ToUpper();
          mes3.GetComponent <TextMeshProUGUI>().text = ((Desde.AddMonths(-3)).ToString("MMM")).ToUpper();
          mes4.GetComponent <TextMeshProUGUI>().text = ((Desde.AddMonths(-2)).ToString("MMM")).ToUpper();
          mes5.GetComponent <TextMeshProUGUI>().text = ((Desde.AddMonths(-1)).ToString("MMM")).ToUpper();
          mes6.GetComponent <TextMeshProUGUI>().text = (Desde.ToString("MMM")).ToUpper();

          if (prom >= 220)
          {
              Prom1.GetComponent <TextMeshProUGUI>().text = "" + prom;
              promgraf1.SetActive(true);
              Prom2.GetComponent <TextMeshProUGUI>().text = "";
              promgraf2.SetActive(false);
              Prom3.GetComponent <TextMeshProUGUI>().text = "";
              promgraf3.SetActive(false);
          }
          else if (prom >= 180 && prom < 220)
          {
              Prom2.GetComponent <TextMeshProUGUI>().text = "" + prom;
              promgraf2.SetActive(true);
              Prom1.GetComponent <TextMeshProUGUI>().text = "";
              promgraf1.SetActive(false);
              Prom3.GetComponent <TextMeshProUGUI>().text = "";
              promgraf3.SetActive(false);
          }
          else if (prom < 180)
          {
              Prom3.GetComponent <TextMeshProUGUI>().text = "" + prom;
              promgraf3.SetActive(true);
              Prom1.GetComponent <TextMeshProUGUI>().text = "";
              promgraf1.SetActive(false);
              Prom2.GetComponent <TextMeshProUGUI>().text = "";
              promgraf2.SetActive(false);
          }


          if (double.Parse(ConsumoActual.GetComponent <TextMeshProUGUI>().text) > double.Parse(Consumoanterior.GetComponent <TextMeshProUGUI>().text))
          {
              FlechaIncremento.SetActive(true);
              FlechaBajo.SetActive(false);
          }
          if (double.Parse(ConsumoActual.GetComponent <TextMeshProUGUI>().text) < double.Parse(Consumoanterior.GetComponent <TextMeshProUGUI>().text))
          {
              FlechaIncremento.SetActive(false);
              FlechaBajo.SetActive(true);
          }
          if (VEstrato.Equals("1") || VEstrato.Equals("2") || VEstrato.Equals("3"))
          {
              if (VMunicipio.Equals("LA DORADA") || VMunicipio.Equals("NORCASIA") || VMunicipio.Equals("VICTORIA") ||
                  VMunicipio.Equals("VITERBO") || VMunicipio.Equals("LA VIRGINIA"))
              {
                  if (double.Parse(TotalKilowatios.GetComponent <TextMeshProUGUI>().text) > 173)
                  {
                      KwSubsidiado.GetComponent <TextMeshProUGUI>().text        = "173";
                      KilowatiosSubsiados.GetComponent <TextMeshProUGUI>().text = "173";
                      if (VEstrato.Equals("1"))
                      {
                          ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor1;
                      }
                      else if (VEstrato.Equals("2"))
                      {
                          ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor2;
                      }
                      else if (VEstrato.Equals("3"))
                      {
                          ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor3;
                      }

                      ValorConsumoconSubsidio.GetComponent <TextMeshProUGUI>().text = "" + (double.Parse(KwSubsidiado.GetComponent <TextMeshProUGUI>().text)
                                                                                            * double.Parse(ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text));
                      KwSinSubsidiado.GetComponent <TextMeshProUGUI>().text            = "" + (double.Parse(TotalKilowatios.GetComponent <TextMeshProUGUI>().text) - 173);
                      ValorKlSinSubsidiado.GetComponent <TextMeshProUGUI>().text       = ValorKlSinSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor4;
                      ValorConsumoSinconSubsidio.GetComponent <TextMeshProUGUI>().text = "" + (double.Parse(KwSinSubsidiado.GetComponent <TextMeshProUGUI>().text)
                                                                                               * double.Parse(ValorKlSinSubsidiado.GetComponent <TextMeshProUGUI>().text));
                      ValorTotalConsumoActivo.GetComponent <TextMeshProUGUI>().text = "" + (double.Parse(ValorConsumoconSubsidio.GetComponent <TextMeshProUGUI>().text)
                                                                                            + double.Parse(ValorConsumoSinconSubsidio.GetComponent <TextMeshProUGUI>().text));
                  }
                  else
                  {
                      KwSubsidiado.GetComponent <TextMeshProUGUI>().text        = TotalKilowatios.GetComponent <TextMeshProUGUI>().text;
                      KilowatiosSubsiados.GetComponent <TextMeshProUGUI>().text = TotalKilowatios.GetComponent <TextMeshProUGUI>().text;
                      if (VEstrato.Equals("1"))
                      {
                          ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor1;
                      }
                      else if (VEstrato.Equals("2"))
                      {
                          ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor2;
                      }
                      else if (VEstrato.Equals("3"))
                      {
                          ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor3;
                      }
                      ValorConsumoconSubsidio.GetComponent <TextMeshProUGUI>().text = "" + (double.Parse(KwSubsidiado.GetComponent <TextMeshProUGUI>().text)
                                                                                            * double.Parse(ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text));
                      ValorTotalConsumoActivo.GetComponent <TextMeshProUGUI>().text    = ValorConsumoconSubsidio.GetComponent <TextMeshProUGUI>().text;
                      KwSinSubsidiado.GetComponent <TextMeshProUGUI>().text            = "";
                      ValorKlSinSubsidiado.GetComponent <TextMeshProUGUI>().text       = "";
                      ValorConsumoSinconSubsidio.GetComponent <TextMeshProUGUI>().text = "";
                  }
              }
              else
              {
                  if (double.Parse(TotalKilowatios.GetComponent <TextMeshProUGUI>().text) > 130)
                  {
                      KwSubsidiado.GetComponent <TextMeshProUGUI>().text        = "130";
                      KilowatiosSubsiados.GetComponent <TextMeshProUGUI>().text = "130";
                      if (VEstrato.Equals("1"))
                      {
                          ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor1;
                      }
                      else if (VEstrato.Equals("2"))
                      {
                          ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor2;
                      }
                      else if (VEstrato.Equals("3"))
                      {
                          ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor3;
                      }
                      ValorConsumoconSubsidio.GetComponent <TextMeshProUGUI>().text = "" + (double.Parse(KwSubsidiado.GetComponent <TextMeshProUGUI>().text)
                                                                                            * double.Parse(ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text));
                      KwSinSubsidiado.GetComponent <TextMeshProUGUI>().text            = "" + (double.Parse(TotalKilowatios.GetComponent <TextMeshProUGUI>().text) - 130);
                      ValorKlSinSubsidiado.GetComponent <TextMeshProUGUI>().text       = "" + modificacion.Valor4;
                      ValorConsumoSinconSubsidio.GetComponent <TextMeshProUGUI>().text = "" + (double.Parse(KwSinSubsidiado.GetComponent <TextMeshProUGUI>().text)
                                                                                               * double.Parse(ValorKlSinSubsidiado.GetComponent <TextMeshProUGUI>().text));
                      ValorTotalConsumoActivo.GetComponent <TextMeshProUGUI>().text = "" + (double.Parse(ValorConsumoconSubsidio.GetComponent <TextMeshProUGUI>().text)
                                                                                            + double.Parse(ValorConsumoSinconSubsidio.GetComponent <TextMeshProUGUI>().text));
                  }
                  else
                  {
                      KwSubsidiado.GetComponent <TextMeshProUGUI>().text        = TotalKilowatios.GetComponent <TextMeshProUGUI>().text;
                      KilowatiosSubsiados.GetComponent <TextMeshProUGUI>().text = TotalKilowatios.GetComponent <TextMeshProUGUI>().text;
                      if (VEstrato.Equals("1"))
                      {
                          ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor1;
                      }
                      else if (VEstrato.Equals("2"))
                      {
                          ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor2;
                      }
                      else if (VEstrato.Equals("3"))
                      {
                          ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor3;
                      }
                      ValorConsumoconSubsidio.GetComponent <TextMeshProUGUI>().text = "" + (double.Parse(KwSubsidiado.GetComponent <TextMeshProUGUI>().text)
                                                                                            * double.Parse(ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text));
                      ValorTotalConsumoActivo.GetComponent <TextMeshProUGUI>().text    = ValorConsumoconSubsidio.GetComponent <TextMeshProUGUI>().text;
                      KwSinSubsidiado.GetComponent <TextMeshProUGUI>().text            = "";
                      ValorKlSinSubsidiado.GetComponent <TextMeshProUGUI>().text       = "";
                      ValorConsumoSinconSubsidio.GetComponent <TextMeshProUGUI>().text = "";
                  }
              }
          }
          else
          {
              KwSinSubsidiado.GetComponent <TextMeshProUGUI>().text     = TotalKilowatios.GetComponent <TextMeshProUGUI>().text;
              KilowatiosSubsiados.GetComponent <TextMeshProUGUI>().text = "0";
              if (VEstrato.Equals("4"))
              {
                  ValorKlSinSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor4;
              }
              else if (VEstrato.Equals("5") || VEstrato.Equals("6"))
              {
                  ValorKlSinSubsidiado.GetComponent <TextMeshProUGUI>().text = "" + modificacion.Valor5;
              }

              ValorConsumoSinconSubsidio.GetComponent <TextMeshProUGUI>().text = "" + (double.Parse(KwSinSubsidiado.GetComponent <TextMeshProUGUI>().text)
                                                                                       * double.Parse(ValorKlSinSubsidiado.GetComponent <TextMeshProUGUI>().text));
              ValorTotalConsumoActivo.GetComponent <TextMeshProUGUI>().text = ValorConsumoSinconSubsidio.GetComponent <TextMeshProUGUI>().text;
              KwSubsidiado.GetComponent <TextMeshProUGUI>().text            = "";
              ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text       = "";
              ValorConsumoconSubsidio.GetComponent <TextMeshProUGUI>().text = "";
          }
          TarifaKilowatiosSubsidiadosTotales.GetComponent <TextMeshProUGUI>().text =
              "$" + ((Convert.ToInt32(double.Parse(KilowatiosSubsiados.GetComponent <TextMeshProUGUI>().text) * (Convert.ToInt32(double.Parse(ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text))))) -
                     (Convert.ToInt32(double.Parse(KilowatiosSubsiados.GetComponent <TextMeshProUGUI>().text) * (Convert.ToInt32(double.Parse(ValorKlSinSubsidiado.GetComponent <TextMeshProUGUI>().text))))));
          valorKilowatiosCompleto = ((Convert.ToInt32(double.Parse(KilowatiosSubsiados.GetComponent <TextMeshProUGUI>().text) * (Convert.ToInt32(double.Parse(ValorKlSubsidiado.GetComponent <TextMeshProUGUI>().text)))))
                                     - (Convert.ToInt32(double.Parse(KilowatiosSubsiados.GetComponent <TextMeshProUGUI>().text) * (Convert.ToInt32(double.Parse(ValorKlSinSubsidiado.GetComponent <TextMeshProUGUI>().text))))));


          if (ValorSaldosanteriores.GetComponent <TMP_InputField>().text != "")
          {
              ValorservicioTotal.GetComponent <TextMeshProUGUI>().text = "" + Convert.ToInt32(double.Parse(ValorServicioEnergiaFinal.GetComponent <TextMeshProUGUI>().text)
                                                                                              + double.Parse(ValorTotalCreditoSomo.GetComponent <TextMeshProUGUI>().text) + double.Parse(ValorTotalOtrosProductos.GetComponent <TextMeshProUGUI>().text)
                                                                                              + double.Parse(ValorTotalImpuestoo.GetComponent <TextMeshProUGUI>().text) + double.Parse(ValorTotalAseo.GetComponent <TextMeshProUGUI>().text)
                                                                                              + double.Parse(ValorSaldosanteriores.GetComponent <TMP_InputField>().text));
          }
          else
          {
              ValorservicioTotal.GetComponent <TextMeshProUGUI>().text = "" + (int)(double.Parse(ValorServicioEnergiaFinal.GetComponent <TextMeshProUGUI>().text)
                                                                                    + double.Parse(ValorTotalCreditoSomo.GetComponent <TextMeshProUGUI>().text) + double.Parse(ValorTotalOtrosProductos.GetComponent <TextMeshProUGUI>().text)
                                                                                    + double.Parse(ValorTotalImpuestoo.GetComponent <TextMeshProUGUI>().text) + double.Parse(ValorTotalAseo.GetComponent <TextMeshProUGUI>().text));
          }



          if (Saldoanterior.GetComponent <TMP_InputField>().text != "")
          {
              sumaTotal = (valorKilowatiosCompletoSinsubsidio + valorKilowatiosCompleto) + 8120 + 5 + Convert.ToInt32(double.Parse(Saldoanterior.GetComponent <TMP_InputField>().text));
              MesesDeuda.GetComponent <TextMeshProUGUI>().text                = "1";
              ValorServicioEnergia.GetComponent <TextMeshProUGUI>().text      = "$" + sumaTotal;
              ValorServicioEnergiaFinal.GetComponent <TextMeshProUGUI>().text = "" + ((valorKilowatiosCompletoSinsubsidio + valorKilowatiosCompleto) + 8120 + 5);
          }
          else
          {
              MesesDeuda.GetComponent <TextMeshProUGUI>().text = "0";
              sumaTotal = (valorKilowatiosCompletoSinsubsidio + valorKilowatiosCompleto) + 8120 + 5;
              ValorServicioEnergia.GetComponent <TextMeshProUGUI>().text      = "$" + sumaTotal;
              ValorServicioEnergiaFinal.GetComponent <TextMeshProUGUI>().text = "" + sumaTotal;
          }
          TarifaKilowatiosTotales.GetComponent <TextMeshProUGUI>().text = "$" + (Convert.ToInt32(double.Parse(TotalKilowatios.GetComponent <TextMeshProUGUI>().text) * (Convert.ToInt32(double.Parse(ValorKlSinSubsidiado.GetComponent <TextMeshProUGUI>().text)))));
          valorKilowatiosCompletoSinsubsidio = Convert.ToInt32(double.Parse(TotalKilowatios.GetComponent <TextMeshProUGUI>().text) * (Convert.ToInt32(double.Parse(ValorKlSinSubsidiado.GetComponent <TextMeshProUGUI>().text))));
      }

      if (LecturaActualReactiva.GetComponent <TMP_InputField>().text != "" && LecturaAnteriorReactiva.GetComponent <TMP_InputField>().text != "")
      {
          ConsumoReactiva.GetComponent <TextMeshProUGUI>().text = "" + ((double.Parse(LecturaActualReactiva.GetComponent <TMP_InputField>().text))
                                                                        - (double.Parse(LecturaAnteriorReactiva.GetComponent <TextMeshProUGUI>().text)));
          TotalKilowatios.GetComponent <TextMeshProUGUI>().text = "" + (((double.Parse(LecturaActualReactiva.GetComponent <TMP_InputField>().text))
                                                                         - (double.Parse(LecturaAnteriorReactiva.GetComponent <TMP_InputField>().text))) * double.Parse(FactorMultiplicacionReactiva.GetComponent <TMP_InputField>().text));
      }



      if (ValorComprasomos.GetComponent <TMP_InputField>().text != "" && cuotaComprasomos.GetComponent <TMP_InputField>().text != "")
      {
          CapitalComprasomos.GetComponent <TextMeshProUGUI>().text = "" + Convert.ToInt32((double.Parse(ValorComprasomos.GetComponent <TMP_InputField>().text) / double.Parse(cuotaComprasomos.GetComponent <TMP_InputField>().text))
                                                                                          * (double.Parse(cuotaComprasomos.GetComponent <TMP_InputField>().text) - 2));
          segundaaComprasomos.GetComponent <TextMeshProUGUI>().text   = ValorComprasomos.GetComponent <TMP_InputField>().text;
          cuotaFinalComprasomos.GetComponent <TextMeshProUGUI>().text = "" + ((double.Parse(cuotaComprasomos.GetComponent <TMP_InputField>().text)) - 1);
          SaldoComprasomos.GetComponent <TextMeshProUGUI>().text      = "" + Convert.ToInt32(double.Parse(ValorComprasomos.GetComponent <TMP_InputField>().text) / double.Parse(cuotaComprasomos.GetComponent <TMP_InputField>().text));
          TotalComprasomos.GetComponent <TextMeshProUGUI>().text      = "" + Convert.ToInt32(double.Parse(ValorComprasomos.GetComponent <TMP_InputField>().text) / double.Parse(cuotaComprasomos.GetComponent <TMP_InputField>().text));
          ValorTotalCreditoSomo.GetComponent <TextMeshProUGUI>().text = TotalComprasomos.GetComponent <TextMeshProUGUI>().text;
      }

      if (ValorOtros.GetComponent <TMP_InputField>().text != "")
      {
          ValorFinalOtros.GetComponent <TextMeshProUGUI>().text          = ValorOtros.GetComponent <TMP_InputField>().text;
          ValorTotalOtrosProductos.GetComponent <TextMeshProUGUI>().text = ValorOtros.GetComponent <TMP_InputField>().text;
      }

      if (ValorAseo.GetComponent <TMP_InputField>().text != "")
      {
          ValorfinalAseo.GetComponent <TextMeshProUGUI>().text = ValorAseo.GetComponent <TMP_InputField>().text;
          ValorTotalAseo.GetComponent <TextMeshProUGUI>().text = ValorAseo.GetComponent <TMP_InputField>().text;
      }
  }
示例#60
0
        // handle like "前两年" "前三个月"
        private DateTimeResolutionResult ParseNumberWithUnit(string text, DateObject referenceDate)
        {
            var ret = new DateTimeResolutionResult();

            string numStr, unitStr;

            // if there are NO spaces between number and unit
            var match = DatePeriodExtractorChs.NumberCombinedWithUnit.Match(text);

            if (match.Success)
            {
                var srcUnit   = match.Groups["unit"].Value.ToLowerInvariant();
                var beforeStr = text.Substring(0, match.Index).Trim().ToLowerInvariant();
                if (this.config.UnitMap.ContainsKey(srcUnit))
                {
                    unitStr = this.config.UnitMap[srcUnit];
                    numStr  = match.Groups["num"].Value;

                    var prefixMatch = DatePeriodExtractorChs.PastRegex.Match(beforeStr);
                    if (prefixMatch.Success && prefixMatch.Length == beforeStr.Length)
                    {
                        DateObject beginDate, endDate;
                        switch (unitStr)
                        {
                        case "D":
                            beginDate = referenceDate.AddDays(-double.Parse(numStr));
                            endDate   = referenceDate;
                            break;

                        case "W":
                            beginDate = referenceDate.AddDays(-7 * double.Parse(numStr));
                            endDate   = referenceDate;
                            break;

                        case "MON":
                            beginDate = referenceDate.AddMonths(-Convert.ToInt32(double.Parse(numStr)));
                            endDate   = referenceDate;
                            break;

                        case "Y":
                            beginDate = referenceDate.AddYears(-Convert.ToInt32(double.Parse(numStr)));
                            endDate   = referenceDate;
                            break;

                        default:
                            return(ret);
                        }

                        ret.Timex       = $"({FormatUtil.LuisDate(beginDate)},{FormatUtil.LuisDate(endDate)},P{numStr}{unitStr[0]})";
                        ret.FutureValue = ret.PastValue = new Tuple <DateObject, DateObject>(beginDate, endDate);
                        ret.Success     = true;
                        return(ret);
                    }

                    prefixMatch = DatePeriodExtractorChs.FutureRegex.Match(beforeStr);
                    if (prefixMatch.Success && prefixMatch.Length == beforeStr.Length)
                    {
                        DateObject beginDate, endDate;
                        switch (unitStr)
                        {
                        case "D":
                            beginDate = referenceDate;
                            endDate   = referenceDate.AddDays(double.Parse(numStr));
                            break;

                        case "W":
                            beginDate = referenceDate;
                            endDate   = referenceDate.AddDays(7 * double.Parse(numStr));
                            break;

                        case "MON":
                            beginDate = referenceDate;
                            endDate   = referenceDate.AddMonths(Convert.ToInt32(double.Parse(numStr)));
                            break;

                        case "Y":
                            beginDate = referenceDate;
                            endDate   = referenceDate.AddYears(Convert.ToInt32(double.Parse(numStr)));
                            break;

                        default:
                            return(ret);
                        }

                        ret.Timex =
                            $"({FormatUtil.LuisDate(beginDate.AddDays(1))},{FormatUtil.LuisDate(endDate.AddDays(1))},P{numStr}{unitStr[0]})";
                        ret.FutureValue   =
                            ret.PastValue = new Tuple <DateObject, DateObject>(beginDate.AddDays(1), endDate.AddDays(1));
                        ret.Success       = true;
                        return(ret);
                    }
                }
            }

            // for case "前两年" "后三年"
            var durationRes = Durationextractor.Extract(text);

            if (durationRes.Count > 0)
            {
                var beforeStr = text.Substring(0, (int)durationRes[0].Start).Trim().ToLowerInvariant();
                match = DatePeriodExtractorChs.UnitRegex.Match(durationRes[0].Text);
                if (match.Success)
                {
                    var srcUnit   = match.Groups["unit"].Value.ToLowerInvariant();
                    var numberStr = durationRes[0].Text.Substring(0, match.Index).Trim().ToLowerInvariant();
                    var number    = ConvertChineseToNum(numberStr);
                    if (this.config.UnitMap.ContainsKey(srcUnit))
                    {
                        unitStr = this.config.UnitMap[srcUnit];
                        numStr  = number.ToString();
                        var prefixMatch = DatePeriodExtractorChs.PastRegex.Match(beforeStr);
                        if (prefixMatch.Success && prefixMatch.Length == beforeStr.Length)
                        {
                            DateObject beginDate, endDate;
                            switch (unitStr)
                            {
                            case "D":
                                beginDate = referenceDate.AddDays(-double.Parse(numStr));
                                endDate   = referenceDate;
                                break;

                            case "W":
                                beginDate = referenceDate.AddDays(-7 * double.Parse(numStr));
                                endDate   = referenceDate;
                                break;

                            case "MON":
                                beginDate = referenceDate.AddMonths(-Convert.ToInt32(double.Parse(numStr)));
                                endDate   = referenceDate;
                                break;

                            case "Y":
                                beginDate = referenceDate.AddYears(-Convert.ToInt32(double.Parse(numStr)));
                                endDate   = referenceDate;
                                break;

                            default:
                                return(ret);
                            }

                            ret.Timex       = $"({FormatUtil.LuisDate(beginDate)},{FormatUtil.LuisDate(endDate)},P{numStr}{unitStr[0]})";
                            ret.FutureValue = ret.PastValue = new Tuple <DateObject, DateObject>(beginDate, endDate);
                            ret.Success     = true;
                            return(ret);
                        }

                        prefixMatch = DatePeriodExtractorChs.FutureRegex.Match(beforeStr);
                        if (prefixMatch.Success && prefixMatch.Length == beforeStr.Length)
                        {
                            DateObject beginDate, endDate;
                            switch (unitStr)
                            {
                            case "D":
                                beginDate = referenceDate;
                                endDate   = referenceDate.AddDays(double.Parse(numStr));
                                break;

                            case "W":
                                beginDate = referenceDate;
                                endDate   = referenceDate.AddDays(7 * double.Parse(numStr));
                                break;

                            case "MON":
                                beginDate = referenceDate;
                                endDate   = referenceDate.AddMonths(Convert.ToInt32(double.Parse(numStr)));
                                break;

                            case "Y":
                                beginDate = referenceDate;
                                endDate   = referenceDate.AddYears(Convert.ToInt32(double.Parse(numStr)));
                                break;

                            default:
                                return(ret);
                            }

                            ret.Timex =
                                $"({FormatUtil.LuisDate(beginDate.AddDays(1))},{FormatUtil.LuisDate(endDate.AddDays(1))},P{numStr}{unitStr[0]})";
                            ret.FutureValue   =
                                ret.PastValue =
                                    new Tuple <DateObject, DateObject>(beginDate.AddDays(1), endDate.AddDays(1));
                            ret.Success = true;
                            return(ret);
                        }
                    }
                }
            }
            return(ret);
        }