Determines the earliest time that a schedule goes invalid which is the
time that should be used to update resource ranges from.
514574
function nextValidStart(schedules) {
    var latest;
    for(var i = 0, len = schedules.length; i < len; i++) {
      var end = schedules[i].range[1];
      latest = !latest || end < latest ? end : latest;
    }

    return latest;
  }
636829
private void updateToNextWorkStart(Calendar cal)
   {
      Date originalDate = cal.getTime();

      //
      // Find the date ranges for the current day
      //
      ProjectCalendarDateRanges ranges = getRanges(originalDate, cal, null);

      if (ranges != null)
      {
         //
         // Do we have a start time today?
         //
         Date calTime = DateHelper.getCanonicalTime(cal.getTime());
         Date startTime = null;
         for (DateRange range : ranges)
         {
            Date rangeStart = DateHelper.getCanonicalTime(range.getStart());
            Date rangeEnd = DateHelper.getCanonicalTime(range.getEnd());
            Date rangeStartDay = DateHelper.getDayStartDate(range.getStart());
            Date rangeEndDay = DateHelper.getDayStartDate(range.getEnd());

            if (rangeStartDay.getTime() != rangeEndDay.getTime())
            {
               rangeEnd = DateHelper.addDays(rangeEnd, 1);
            }

            if (calTime.getTime() < rangeEnd.getTime())
            {
               if (calTime.getTime() > rangeStart.getTime())
               {
                  startTime = calTime;
               }
               else
               {
                  startTime = rangeStart;
               }
               break;
            }
         }

         //
         // If we don't have a start time today - find the next working day
         // then retrieve the start time.
         //
         if (startTime == null)
         {
            Day day;
            int nonWorkingDayCount = 0;
            do
            {
               cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1);
               day = Day.getInstance(cal.get(Calendar.DAY_OF_WEEK));
               ++nonWorkingDayCount;
               if (nonWorkingDayCount > MAX_NONWORKING_DAYS)
               {
                  cal.setTime(originalDate);
                  break;
               }
            }
            while (!isWorkingDate(cal.getTime(), day));

            startTime = getStartTime(cal.getTime());
         }

         DateHelper.setTime(cal, startTime);
      }
   }
831180
def get_next_future_timerange_invalid(self, timestamp):
        
        sec_from_morning = get_sec_from_morning(timestamp)
        ends = []
        for timerange in self.timeranges:
            tr_end = timerange.hend * 3600 + timerange.mend * 60
            if tr_end >= sec_from_morning:
                # Remove the last second of the day for 00->24h"
                if tr_end == 86400:
                    tr_end = 86399
                ends.append(tr_end)
        if ends != []:
            return min(ends)

        return None
1305137
private Set<Integer> matchWithClosestAisMessageIfBufferLargeEnough(
			long arrivalTime, Integer earliestTimestampLineIndex) {
		String timestampLine = getLine(earliestTimestampLineIndex);
		long time = getLineTime(earliestTimestampLineIndex);
		log.debug("ts=" + timestampLine + ",time=" + time);
		Set<Integer> removeThese;
		if (arrivalTime - time > MAXIMUM_ARRIVAL_TIME_DIFFERENCE_MS) {
			removeThese = matchWithClosestAisMessageAndFindIndexesToRemove(
					earliestTimestampLineIndex, timestampLine, time);
		} else
			removeThese = findExpiredIndexesBeforeIndex(earliestTimestampLineIndex);
		return removeThese;
	}
778511
def validate_schedule():
    """"""
    all_items = prefetch_schedule_items()
    errors = []
    for validator, _type, msg in SCHEDULE_ITEM_VALIDATORS:
        if validator(all_items):
            errors.append(msg)

    all_slots = prefetch_slots()
    for validator, _type, msg in SLOT_VALIDATORS:
        if validator(all_slots):
            errors.append(msg)
    return errors
473962
def raise_on_invalid(self, setting=True, **overrides):
        """"""
        return self.where(raise_on_invalid=setting, **overrides)
528999
def _unschedule_sending_init_updates(self):
        
        LOG.debug('Un-scheduling sending of initial Non-RTC UPDATEs'
                  ' (init. UPDATEs already sent: %s)',
                  self._sent_init_non_rtc_update)
        if self._rtc_eor_timer:
            self._rtc_eor_timer.stop()
            self._rtc_eor_timer = None
            return True
        return False
344531
def conflicts_with?(other_schedule, closing_time = nil)
      closing_time = TimeUtil.ensure_time(closing_time)
      unless terminating? || other_schedule.terminating? || closing_time
        raise ArgumentError, "One or both schedules must be terminating to use #conflicts_with?"
      end
      # Pick the terminating schedule, and other schedule
      # No need to reverse if terminating? or there is a closing time
      terminating_schedule = self
      unless terminating? || closing_time
        terminating_schedule, other_schedule = other_schedule, terminating_schedule
      end
      # Go through each occurrence of the terminating schedule and determine
      # if the other occurs at that time
      #
      last_time = nil
      terminating_schedule.each_occurrence do |time|
        if closing_time && time > closing_time
          last_time = closing_time
          break
        end
        last_time = time
        return true if other_schedule.occurring_at?(time)
      end
      # Due to durations, we need to walk up to the end time, and verify in the
      # other direction
      if last_time
        last_time += terminating_schedule.duration
        other_schedule.each_occurrence do |time|
          break if time > last_time
          return true if terminating_schedule.occurring_at?(time)
        end
      end
      # No conflict, return false
      false
    end
708831
def has_conflicting_update(self, update):
        
        # we explicitly want a flat list of updates here, that's why we call iter_updates
        # with both `initial` and `scheduled` == False
        for _, _, _, updates in self.iter_updates(initial=False, scheduled=False):
            for _update in updates:
                if (
                        update.requirement.key == _update.requirement.key and
                        (
                                update.commit_message != _update.commit_message or
                                update.requirement.latest_version_within_specs !=
                                _update.requirement.latest_version_within_specs
                        )
                ):
                    logger.info("{} conflicting with {}/{}".format(
                        update.requirement.key,
                        update.requirement.latest_version_within_specs,
                        _update.requirement.latest_version_within_specs)
                    )
                    return True
        return False
397154
def parse_schedule(schedule, action):
        
        error = None
        scheduled_at = None
        try:
            scheduled_at = dateutil.parser.parse(schedule)
            if scheduled_at.tzinfo is None:
                error = 'Timezone information is mandatory for the scheduled {0}'.format(action)
                status_code = 400
            elif scheduled_at < datetime.datetime.now(tzutc):
                error = 'Cannot schedule {0} in the past'.format(action)
                status_code = 422
            else:
                status_code = None
        except (ValueError, TypeError):
            logger.exception('Invalid scheduled %s time: %s', action, schedule)
            error = 'Unable to parse scheduled timestamp. It should be in an unambiguous format, e.g. ISO 8601'
            status_code = 422
        return (status_code, error, scheduled_at)
529966
def update_schedule_items(*args, **kw):
    """"""
    slot = kw.pop('instance', None)
    if not slot:
        return
    for item in slot.scheduleitem_set.all():
        item.save(update_fields=['last_updated'])
    # We also need to update the next slot, in case we changed it's
    # times as well
    next_slot = slot.slot_set.all()
    if next_slot.count():
        # From the way we structure the slot tree, we know that
        # there's only 1 next slot that could have changed.
        for item in next_slot[0].scheduleitem_set.all():
            item.save(update_fields=['last_updated'])
944515
private synchronized void updateLocal() throws ScheduleManagerException {
    final List<Schedule> updates = this.loader.loadUpdatedSchedules();
    for (final Schedule s : updates) {
      if (s.getStatus().equals(TriggerStatus.EXPIRED.toString())) {
        onScheduleExpire(s);
      } else {
        internalSchedule(s);
      }
    }
  }
1320185
private static <T extends Comparable<T>> void ensureValidRange(T min, T max) {
    if (min == null) {
      throw new InvalidOperationException("Null value for minimum.");
    }
    if (max == null) {
      throw new InvalidOperationException("Null value for maximum.");
    }
    if (min.compareTo(max) >= 0) {
      throw new InvalidOperationException("Invalid range: " + min + " >= " + max);
    }
  }
784487
public function validate()
    {
        parent::validate();

        $intervalUnit = $this->getRepeatIntervalUnit();
        $repeatInterval = $this->getRepeatInterval();

        if (false == in_array($intervalUnit, [IntervalUnit::SECOND, IntervalUnit::MINUTE, IntervalUnit::HOUR], true)) {
            throw new SchedulerException('Invalid repeat IntervalUnit (must be SECOND, MINUTE or HOUR).');
        }

        if ($intervalUnit < 1) {
            throw new SchedulerException('Repeat Interval cannot be zero.');
        }

        // Ensure interval does not exceed 24 hours
        $secondsInHour = 24 * 60 * 60;
        if ($intervalUnit === IntervalUnit::SECOND && $repeatInterval > $secondsInHour) {
            throw new SchedulerException(sprintf(
                'repeatInterval can not exceed 24 hours ("%s" seconds). Given "%d"', $secondsInHour, $repeatInterval));
        }

        if ($intervalUnit === IntervalUnit::MINUTE && $repeatInterval > ($secondsInHour / 60)) {
            throw new SchedulerException(sprintf(
                'repeatInterval can not exceed 24 hours ("%d" minutes). Given "%d"', $secondsInHour / 60, $repeatInterval));
        }

        if ($intervalUnit === IntervalUnit::HOUR && $repeatInterval > 24) {
            throw new SchedulerException(sprintf('repeatInterval can not exceed 24 hours. Given "%d" hours.', $repeatInterval));
        }

        // Ensure timeOfDay is in order.
        if ($this->getEndTimeOfDay() && $this->getStartTimeOfDay() > $this->getEndTimeOfDay()) {
            throw new SchedulerException(sprintf(
                'StartTimeOfDay "%s" should not come after endTimeOfDay "%s"',
                $this->getStartTimeOfDay()->format('Y:m:d H:i:s'), $this->getEndTimeOfDay()->format('Y:m:d H:i:s'))
            );
        }
    }
465571
def valid?
      schedule_type_validator = EnumAttributeValidator.new('String', ["SCHEDULED", "ASAP"])
      return false unless schedule_type_validator.valid?(@schedule_type)
      return false if !@note.nil? && @note.to_s.length > 500
      return false if !@cancel_reason.nil? && @cancel_reason.to_s.length > 100
      return true
    end
643024
def _check_time_range(time_range, now):
    '''
    
    '''
    if _TIME_SUPPORTED:
        _start = dateutil_parser.parse(time_range['start'])
        _end = dateutil_parser.parse(time_range['end'])

        return bool(_start <= now <= _end)
    else:
        log.error('Dateutil is required.')
        return False
1192938
def _onOffset(self, dt, businesshours):
        
        # if self.normalize and not _is_normalized(dt):
        #     return False
        # Valid BH can be on the different BusinessDay during midnight
        # Distinguish by the time spent from previous opening time
        if self.n >= 0:
            op = self._prev_opening_time(dt)
        else:
            op = self._next_opening_time(dt)
        span = (dt - op).total_seconds()
        if span <= businesshours:
            return True
        else:
            return False