/*
If start date, IntervalType or interval number is changed the interval information must be calculated new
The internal UTC Start date must be set to the begin of an interval
The interval size and the row size must be calculated
979584
function _calculateIntervals() {

		var oStartDate = this.getStartDate();
		var oEndDate;
		var iIntervals = this.getIntervals();
		var sIntervalType = this.getIntervalType();

		this._oUTCStartDate = _calculateStartDate.call(this, oStartDate);

		switch (sIntervalType) {
		case CalendarIntervalType.Hour:
			oEndDate = new UniversalDate(this._oUTCStartDate.getTime());
			oEndDate.setUTCHours(oEndDate.getUTCHours() + iIntervals);
			this._iMinDelta = this._iHoursMinDelta;
			break;

		case CalendarIntervalType.Day:
		case CalendarIntervalType.Week:
		case CalendarIntervalType.OneMonth:
			oEndDate = new UniversalDate(this._oUTCStartDate.getTime());
			oEndDate.setUTCDate(oEndDate.getUTCDate() + iIntervals);
			this._iMinDelta = this._iDaysMinDelta;
			break;

		case CalendarIntervalType.Month:
			oEndDate = new UniversalDate(this._oUTCStartDate.getTime());
			oEndDate.setUTCMonth(oEndDate.getUTCMonth() + iIntervals);
			this._iMinDelta = this._iMonthsMinDelta;
			break;

		default:
			throw new Error("Unknown IntervalType: " + sIntervalType + "; " + this);
		}

		oEndDate.setUTCMilliseconds(-1);
		this._iRowSize = oEndDate.getTime() - this._oUTCStartDate.getTime();
		this._iIntervalSize = Math.floor(this._iRowSize / iIntervals);
		this._oUTCEndDate = oEndDate;

	}
706863
private void validateTimeSeriesMetric(DateTime from, DateTime to, HistogramIntervalType interval)
            throws InvalidMetricCriteriaException {
        long millis = to.getMillis() - from.getMillis();
        long divBy = ONE_DAY_MILLIS;
        switch (interval) {
        case day:
            divBy = ONE_DAY_MILLIS;
            break;
        case hour:
            divBy = ONE_HOUR_MILLIS;
            break;
        case minute:
            divBy = ONE_MINUTE_MILLIS;
            break;
        case month:
            divBy = ONE_MONTH_MILLIS;
            break;
        case week:
            divBy = ONE_WEEK_MILLIS;
            break;
        default:
            break;
        }
        long totalDataPoints = millis / divBy;
        if (totalDataPoints > 5000) {
            throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("OrganizationResourceImpl.MetricDataSetTooLarge")); //$NON-NLS-1$
        }
    }
205096
public Date adjustDate(final Date startDate, final int increment, final NonWorkingDayChecker<Date> checker) {
        final Calendar cal = Utils.getCal(startDate);

        while (checker.isNonWorkingDay(cal.getTime())) {
            if (increment < 0) {
                cal.add(Calendar.DAY_OF_MONTH, -1);
            } else {
                cal.add(Calendar.DAY_OF_MONTH, 1);
            }
        }

        return cal.getTime();
    }
573128
function adjustStartPoint(rowIndex, cellIndex, cell, isSelectedCell) {
            if (rowIndex === _startPoint.rowPos && _startPoint.colPos >= cell.cellIndex && cell.cellIndex <= cellIndex && !isSelectedCell) {
                _startPoint.colPos++;
            }
        }
44497
private void initializeDefaultCenturyStart(long baseTime) {
        defaultCenturyBase = baseTime;
        // clone to avoid messing up date stored in calendar object
        // when this method is called while parsing
        Calendar tmpCal = (Calendar)calendar.clone();
        tmpCal.setTimeInMillis(baseTime);
        tmpCal.add(Calendar.YEAR, -80);
        defaultCenturyStart = tmpCal.getTime();
        defaultCenturyStartYear = tmpCal.get(Calendar.YEAR);
    }
1313567
function setDate(momentInstance, year, month, day) {
    var d = momentInstance._d;
    if (momentInstance._isUTC) {
        /*eslint-disable new-cap*/
        momentInstance._d = new Date(Date.UTC(year, month, day,
            d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()));
        /*eslint-enable new-cap*/
    } else {
        momentInstance._d = new Date(year, month, day,
            d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
    }
}
905789
final void internalReset(long initialValue) {
		Cell[] as = cells;
		base = initialValue;
		if (as != null) {
			int n = as.length;
			for (int i = 0; i < n; ++i) {
				Cell a = as[i];
				if (a != null) a.value = initialValue;
			}
		}
	}
1173820
@VisibleForTesting
  List<Long> prepareRowBaseTimesRollup() {
    final RollupInterval interval = rollup_query.getRollupInterval();

    // standard TSDB table format, i.e. we're using the default table and schema
    if (interval.getUnits() == 'h') {
      return prepareRowBaseTimes();
    } else {
      final List<Long> row_base_times = new ArrayList<Long>(
          (int) ((end_row_time - start_row_time) / interval.getIntervals()));

      long ts = RollupUtils.getRollupBasetime(start_row_time, interval);
      while (ts <= end_row_time) {
        row_base_times.add(ts);
        // TODO - possible this could overshoot in some cases. It shouldn't
        // if the rollups are properly configured, but... you know. Check it.
        ts = RollupUtils.getRollupBasetime(ts + 
            (interval.getIntervalSeconds() * interval.getIntervals()), interval);
      }
      return row_base_times;
    }
  }
676088
public static void initGlobals()
    {
        if (gDateFormat == null)
        {   // NOTE: You MUST synchronize before using any of these
            // For dates and times, synchronize on the gCalendar
            gCalendar = Calendar.getInstance();

            gDateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
            gTimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
            gLongTimeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM);
            gDateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
            gLongDateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
            gDateShortFormat = DateFormat.getDateInstance(DateFormat.SHORT);
            gDateShortTimeFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
            gGMTDateTimeFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);

            gDateSqlFormat = gDateShortFormat;  // By default use these formats - Change if different
            gTimeSqlFormat = gTimeFormat;
            gDateTimeSqlFormat = gDateShortTimeFormat;
            // For all of these, synchronize on the object you are using
            gIntegerFormat = NumberFormat.getInstance();
            gIntegerFormat.setParseIntegerOnly(true);

            gCurrencyFormat = NumberFormat.getCurrencyInstance();
            
            gNumberFormat = NumberFormat.getInstance();
            gNumberFormat.setParseIntegerOnly(false);
            gNumberFormat.setMinimumFractionDigits(2);
            gNumberFormat.setMaximumFractionDigits(2);
            if (gNumberFormat instanceof DecimalFormat)
            {
                gchDot = ((DecimalFormat)gNumberFormat).getDecimalFormatSymbols().getDecimalSeparator();
                gchMinus = ((DecimalFormat)gNumberFormat).getDecimalFormatSymbols().getMinusSign();
            }

            gPercentFormat = NumberFormat.getPercentInstance();
        }
    }
840784
function iterateOverDateParams(params, fn, startIndex, endIndex) {

  function run(name, unit, i) {
    var val = getDateParam(params, name);
    if (isDefined(val)) {
      fn(name, val, unit, i);
    }
  }

  iterateOverDateUnits(function (unit, i) {
    var result = run(unit.name, unit, i);
    if (result !== false && i === DAY_INDEX) {
      // Check for "weekday", which has a distinct meaning
      // in the context of setting a date, but has the same
      // meaning as "day" as a unit of time.
      result = run('weekday', unit, i);
    }
    return result;
  }, startIndex, endIndex);

}
586681
public static Collection<TimeSlot> calculateTimeSots( Day day, int intervalSeconds, Time startTime, Time endTime)
   {
      if(intervalSeconds <1)
      {
         throw new IllegalArgumentException("interval seconds cannot be less than one");
      }
      
      int count = 1*60*60*24/intervalSeconds;
      
      ArrayList<TimeSlot> slots = new ArrayList<TimeSlot>(count);   
      
      TimeSlot startSlot = TimeSlot.firstSlot(day,startTime, intervalSeconds);
      TimeSlot slot = startSlot;
      
      while(slot != null)
      {
         slots.add(slot);
         slot = slot.nextTimeSlot(intervalSeconds,endTime);
      }          
      
      return slots;
   }
629809
public void setInto(ReadWritablePeriod writablePeriod, Object object, Chronology chrono) {
        ReadableInterval interval = (ReadableInterval) object;
        chrono = (chrono != null ? chrono : DateTimeUtils.getIntervalChronology(interval));
        long start = interval.getStartMillis();
        long end = interval.getEndMillis();
        int[] values = chrono.get(writablePeriod, start, end);
        for (int i = 0; i < values.length; i++) {
            writablePeriod.setValue(i, values[i]);
        }
    }
131230
function() {
    this.addType(
      'interval',
      function(value) {
        if (value === null) return null
        return validator.toString(value + '')
      },
      {
        migration: ['interval'],
        operators: {
          defaults: ['eq', 'not']
        }
      }
    )
  }
269270
protected int handleComputeMonthStart(int eyear, int month, boolean useMonth) {

        // If the month is out of range, adjust it into range, and
        // modify the extended year value accordingly.
        if (month < 0 || month > 11) {
            int[] rem = new int[1];
            eyear += floorDivide(month, 12, rem);
            month = rem[0];
        }

        boolean isLeap = eyear%4 == 0;
        int y = eyear - 1;
        int julianDay = 365*y + floorDivide(y, 4) + (JAN_1_1_JULIAN_DAY - 3);

        isGregorian = (eyear >= gregorianCutoverYear);
        if (invertGregorian) {
            isGregorian = !isGregorian;
        }
        if (isGregorian) {
            isLeap = isLeap && ((eyear%100 != 0) || (eyear%400 == 0));
            // Add 2 because Gregorian calendar starts 2 days after
            // Julian calendar
            julianDay += floorDivide(y, 400) - floorDivide(y, 100) + 2;
        }

        // At this point julianDay indicates the day BEFORE the first
        // day of January 1, <eyear> of either the Julian or Gregorian
        // calendar.

        if (month != 0) {
            julianDay += MONTH_COUNT[month][isLeap?3:2];
        }

        return julianDay;
    }
1050985
public final void setStartDate(Date startDate) {
                if (this.startDate == null || !this.startDate.equals(startDate)) {
                        if (startDate != null && endDate != null && endDate.before(startDate)) {
                                throw new ParameterException("The start date must be before the end date of the filter.");
                        }
                        this.startDate = startDate;
                        setChanged();
                        notifyObservers();
                }
        }
59461
function preparePeriod(period, value, year) {

    var range;
    var subUnit;
    var start;
    var length;
    var unit;

    switch (period) {
      case 'year':
        unit = 'month';
        break;
      case 'month':
        unit = 'dayOfYear';
        break;
      case 'dayOfYear':
        unit = 'hourOfYear';
        break;
    }

    var result = {
      year: year,
      period: period,
      unit: unit
    };

    var utc = moment().utc();

    if (year) {
      utc.year(year);
    } else {
      year = utc.year();
    }

    if (value || value ===0) {
      utc[period](value);
    } else {
      value = utc[period]();
    }

    result.value = value;
    result.period = period;

    switch (unit) {

      case 'month':
        switch (period) {
          case 'year':
            range = _.range(12);
            break;

          default:
        }

        subUnit = 'dayOfYear';
        break;

      case 'dayOfYear':

        switch (period) {
          case 'month':
            start = utc.month(value).date(1).dayOfYear();
            length = utc.month(value).daysInMonth();

            range = _.range(start, start + length);
            break;

          default:
        }

        subUnit = 'hourOfYear';
        break;

      case 'hourOfYear':

        switch (period) {
          case 'dayOfYear':
            start = utc.dayOfYear(value).hour(0).hourOfYear();
            length = 24;

            range = _.range(start, start + length);
            break;

          default:
        }
        break;
    }

    result.subUnit = subUnit;

    if (!range) {

      var err = new Error('Could not calculate the range');
      err.statusCode = 400;
      err.code = 'NO_RANGE_SET';

      throw err;
    }

    return {
      unit: unit,
      range: range,
      year: year,
      result: result
    };

  }
665895
public void scheduleAtWithInterval(final org.easybatch.core.job.Job job, final Date startTime, final int interval) throws JobSchedulerException {
        checkNotNull(job, "job");
        checkNotNull(startTime, "startTime");

        String name = job.getName();
        String jobName = JOB_NAME_PREFIX + name;
        String triggerName = TRIGGER_NAME_PREFIX + name;

        SimpleScheduleBuilder scheduleBuilder = simpleSchedule()
                .withIntervalInSeconds(interval)
                .repeatForever();

        Trigger trigger = newTrigger()
                .withIdentity(triggerName)
                .startAt(startTime)
                .withSchedule(scheduleBuilder)
                .forJob(jobName)
                .build();

        JobDetail jobDetail = getJobDetail(job, jobName);

        try {
            LOGGER.info("Scheduling job ''{}'' to start at {} and every {} second(s)", name, startTime, interval);
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            throw new JobSchedulerException(format("Unable to schedule job '%s'", name), e);
        }
    }