calculates and stored the next date in this recurrence.
775120
private void fetchNext() {
        if (null != this.pendingUtc_ || this.done_) {
            return;
        }

        DateValue dUtc = this.generateInstance();

        // check the exit condition
        if (null != dUtc && this.condition_.apply(dUtc)) {
            this.pendingUtc_ = dUtc;
            this.yearGenerator_.workDone();
        } else {
            this.done_ = true;
        }
    }
1074295
def next(time, base)
      current = time
      until match?(current, base) && current > time
        pot_next = align(potential_next(current, base), base)
        pot_next += min_step if pot_next == current

        current = pot_next
      end

      current
    end
930603
private int getNextDayOfWeek(int day, int dayOfWeek)
    {
        if (!contains(daysOfWeek, dayOfWeek))
        {
            long higher = higher(daysOfWeek, dayOfWeek);
            if (higher != 0)
            {
                return day + (first(higher) - dayOfWeek);
            }

            return day + (7 - dayOfWeek) + first(daysOfWeek);
        }

        return day;
    }
572246
public function next()
    {
        if ($this->current === null) {
            $this->rewind();
        }

        if ($this->validationResult !== static::END_ITERATION) {
            $this->key++;

            $this->incrementCurrentDateUntilValid();
        }
    }
864241
private void calcCurrentItem() {
        int pointerAngle;

        // calculate the correct pointer angle, depending on clockwise drawing or not
        if(mOpenClockwise) {
            pointerAngle = (mIndicatorAngle + 360 - mPieRotation) % 360;
        }
        else {
            pointerAngle = (mIndicatorAngle + 180 + mPieRotation) % 360;
        }

        for (int i = 0; i < mPieData.size(); ++i) {
            PieModel model = mPieData.get(i);
            if (model.getStartAngle() <= pointerAngle && pointerAngle <= model.getEndAngle()) {
                if (i != mCurrentItem) {
                    setCurrentItem(i, false);
                }
                break;
            }
        }
    }
4281
private void estimateNextExecution() {
		synchronized (TIMER_LOCK) {
			if (fixedDelay) {
				scheduledExecutionTime = period + System.currentTimeMillis();
			} else {
				if (firstExecution == 0) {
					// save timestamp of first execution
					firstExecution = scheduledExecutionTime;
				}
				long now = System.currentTimeMillis();
				long executedTime = (numInvocations++ * period);
				scheduledExecutionTime = firstExecution + executedTime;
				if(logger.isDebugEnabled()) {
					logger.debug("next execution estimated to run at " + scheduledExecutionTime);
				}
				if(logger.isDebugEnabled()) {
					logger.debug("current time is " + now);
				}
			}
		}
	}
1055475
public function process_recurrences()
    {
        $array = $this->cal;
        $events = $array['VEVENT'];

        if (empty($events)) {
            return false;
        }

        foreach ($array['VEVENT'] as $anEvent) {
            if (isset($anEvent['RRULE']) && $anEvent['RRULE'] != '') {
                // Recurring event, parse RRULE and add appropriate duplicate events
                $rrules = [];
                $rrule_strings = explode(';', $anEvent['RRULE']);
                foreach ($rrule_strings as $s) {
                    list($k, $v) = explode('=', $s);
                    $rrules[$k] = $v;
                }
                // Get frequency
                $frequency = $rrules['FREQ'];
                // Get Start timestamp
                $start_timestamp = $this->iCalDateToUnixTimestamp($anEvent['DTSTART']);
                $end_timestamp = $this->iCalDateToUnixTimestamp($anEvent['DTEND']);
                $event_timestamp_offset = $end_timestamp - $start_timestamp;
                // Get Interval
                $interval = (isset($rrules['INTERVAL']) && $rrules['INTERVAL'] != '') ? $rrules['INTERVAL'] : 1;

                if (in_array($frequency, ['MONTHLY', 'YEARLY']) && isset($rrules['BYDAY']) && $rrules['BYDAY'] != '') {
                    // Deal with BYDAY
                    $day_number = intval($rrules['BYDAY']);
                    if (empty($day_number)) { // Returns 0 when no number defined in BYDAY
                        if (!isset($rrules['BYSETPOS'])) {
                            $day_number = 1; // Set first as default
                        } elseif (is_numeric($rrules['BYSETPOS'])) {
                            $day_number = $rrules['BYSETPOS'];
                        }
                    }
                    $day_number = ($day_number == -1) ? 6 : $day_number; // Override for our custom key (6 => 'last')
                    $week_day = substr($rrules['BYDAY'], -2);
                    $day_ordinals = [
                        1 => 'first',
                        2 => 'second',
                        3 => 'third',
                        4 => 'fourth',
                        5 => 'fifth',
                        6 => 'last',
                        ];

                    $weekdays = [
                        'SU' => 'sunday',
                        'MO' => 'monday',
                        'TU' => 'tuesday',
                        'WE' => 'wednesday',
                        'TH' => 'thursday',
                        'FR' => 'friday',
                        'SA' => 'saturday',
                        ];
                }

                $until_default = date_create('now');
                $until_default->modify($this->default_span.' year');
                $until_default->setTime(23, 59, 59); // End of the day
                $until_default = date_format($until_default, 'Ymd\THis');

                if (isset($rrules['UNTIL'])) {
                    // Get Until
                    $until = $this->iCalDateToUnixTimestamp($rrules['UNTIL']);
                } elseif (isset($rrules['COUNT'])) {
                    $frequency_conversion = [
                        'DAILY'   => 'day',
                        'WEEKLY'  => 'week',
                        'MONTHLY' => 'month',
                        'YEARLY'  => 'year',
                        ];

                    $count_orig = (is_numeric($rrules['COUNT']) && $rrules['COUNT'] > 1) ? $rrules['COUNT'] : 0;
                    $count = ($count_orig - 1); // Remove one to exclude the occurrence that initialises the rule
                    $count += ($count > 0) ? $count * ($interval - 1) : 0;
                    $offset = "+$count ".$frequency_conversion[$frequency];
                    $until = strtotime($offset, $start_timestamp);

                    if (in_array($frequency, ['MONTHLY', 'YEARLY']) && isset($rrules['BYDAY']) && $rrules['BYDAY'] != '') {
                        $dtstart = date_create($anEvent['DTSTART']);
                        for ($i = 1; $i <= $count; $i++) {
                            $dtstart_clone = clone $dtstart;
                            $dtstart_clone->modify('next '.$frequency_conversion[$frequency]);
                            $offset = "{$day_ordinals[$day_number]} {$weekdays[$week_day]} of ".$dtstart_clone->format('F Y H:i:01');
                            $dtstart->modify($offset);
                        }

                        // Jumping X months forwards doesn't mean the end date will fall on the same day defined in BYDAY
                        // Use the largest of these to ensure we are going far enough in the future to capture our final end day
                        $until = max($until, $dtstart->format('U'));
                    }

                    unset($offset);
                } else {
                    $until = $this->iCalDateToUnixTimestamp($until_default);
                }

                if (!isset($anEvent['EXDATE_array'])) {
                    $anEvent['EXDATE_array'] = [];
                }

                // Decide how often to add events and do so
                switch ($frequency) {
                    case 'DAILY':
                        // Simply add a new event each interval of days until UNTIL is reached
                        $offset = "+$interval day";
                        $recurring_timestamp = strtotime($offset, $start_timestamp);

                        while ($recurring_timestamp <= $until) {
                            // Add event
                            $anEvent['DTSTART'] = date('Ymd\THis', $recurring_timestamp);
                            $anEvent['DTEND'] = date('Ymd\THis', $recurring_timestamp + $event_timestamp_offset);

                            $search_date = $anEvent['DTSTART'];
                            $is_excluded = array_filter($anEvent['EXDATE_array'], function ($val) use ($search_date) {
                                return is_string($val) && strpos($search_date, $val) === 0;
                            });

                            if (!$is_excluded) {
                                $events[] = $anEvent;
                            }

                            // Move forwards
                            $recurring_timestamp = strtotime($offset, $recurring_timestamp);
                        }
                        break;
                    case 'WEEKLY':
                        // Create offset
                        $offset = "+$interval week";
                        // Build list of days of week to add events
                        $weekdays = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];

                        if (isset($rrules['BYDAY']) && $rrules['BYDAY'] != '') {
                            $bydays = explode(',', $rrules['BYDAY']);
                        } else {
                            $weekTemp = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];
                            $findDay = $weekTemp[date('w', $start_timestamp)];
                            $bydays = [$findDay];
                        }

                        // Get timestamp of first day of start week
                        $week_recurring_timestamp = (date('w', $start_timestamp) == 0) ? $start_timestamp : strtotime('last Sunday '.date('H:i:s', $start_timestamp), $start_timestamp);

                        // Step through weeks
                        while ($week_recurring_timestamp <= $until) {
                            // Add events for bydays
                            $day_recurring_timestamp = $week_recurring_timestamp;

                            foreach ($weekdays as $day) {
                                // Check if day should be added

                                if (in_array($day, $bydays) && $day_recurring_timestamp > $start_timestamp && $day_recurring_timestamp <= $until) {
                                    // Add event to day
                                    $anEvent['DTSTART'] = date('Ymd\THis', $day_recurring_timestamp);
                                    $anEvent['DTEND'] = date('Ymd\THis', $day_recurring_timestamp + $event_timestamp_offset);

                                    $search_date = $anEvent['DTSTART'];
                                    $is_excluded = array_filter($anEvent['EXDATE_array'], function ($val) use ($search_date) { return is_string($val) && strpos($search_date, $val) === 0; });

                                    if (!$is_excluded) {
                                        $events[] = $anEvent;
                                    }
                                }

                                // Move forwards a day
                                $day_recurring_timestamp = strtotime('+1 day', $day_recurring_timestamp);
                            }

                            // Move forwards $interval weeks
                            $week_recurring_timestamp = strtotime($offset, $week_recurring_timestamp);
                        }
                        break;
                    case 'MONTHLY':
                        // Create offset
                        $offset = "+$interval month";
                        $recurring_timestamp = strtotime($offset, $start_timestamp);

                        if (isset($rrules['BYMONTHDAY']) && $rrules['BYMONTHDAY'] != '') {
                            // Deal with BYMONTHDAY
                            $monthdays = explode(',', $rrules['BYMONTHDAY']);

                            while ($recurring_timestamp <= $until) {
                                foreach ($monthdays as $monthday) {
                                    // Add event
                                    $anEvent['DTSTART'] = date('Ym'.sprintf('%02d', $monthday).'\THis', $recurring_timestamp);
                                    $anEvent['DTEND'] = date('Ymd\THis', $this->iCalDateToUnixTimestamp($anEvent['DTSTART']) + $event_timestamp_offset);

                                    $search_date = $anEvent['DTSTART'];
                                    $is_excluded = array_filter($anEvent['EXDATE_array'], function ($val) use ($search_date) { return is_string($val) && strpos($search_date, $val) === 0; });

                                    if (!$is_excluded) {
                                        $events[] = $anEvent;
                                    }
                                }

                                // Move forwards
                                $recurring_timestamp = strtotime($offset, $recurring_timestamp);
                            }
                        } elseif (isset($rrules['BYDAY']) && $rrules['BYDAY'] != '') {
                            $start_time = date('His', $start_timestamp);

                            while ($recurring_timestamp <= $until) {
                                $event_start_desc = "{$day_ordinals[$day_number]} {$weekdays[$week_day]} of ".date('F Y H:i:s', $recurring_timestamp);
                                $event_start_timestamp = strtotime($event_start_desc);

                                if ($event_start_timestamp > $start_timestamp && $event_start_timestamp < $until) {
                                    $anEvent['DTSTART'] = date('Ymd\T', $event_start_timestamp).$start_time;
                                    $anEvent['DTEND'] = date('Ymd\THis', $this->iCalDateToUnixTimestamp($anEvent['DTSTART']) + $event_timestamp_offset);

                                    $search_date = $anEvent['DTSTART'];
                                    $is_excluded = array_filter($anEvent['EXDATE_array'], function ($val) use ($search_date) { return is_string($val) && strpos($search_date, $val) === 0; });

                                    if (!$is_excluded) {
                                        $events[] = $anEvent;
                                    }
                                }

                                // Move forwards
                                $recurring_timestamp = strtotime($offset, $recurring_timestamp);
                            }
                        }
                        break;
                    case 'YEARLY':
                        // Create offset
                        $offset = "+$interval year";
                        $recurring_timestamp = strtotime($offset, $start_timestamp);
                        $month_names = [
                            1  => 'January',
                            2  => 'February',
                            3  => 'March',
                            4  => 'April',
                            5  => 'May',
                            6  => 'June',
                            7  => 'July',
                            8  => 'August',
                            9  => 'September',
                            10 => 'October',
                            11 => 'November',
                            12 => 'December',
                            ];

                        // Check if BYDAY rule exists
                        if (isset($rrules['BYDAY']) && $rrules['BYDAY'] != '') {
                            $start_time = date('His', $start_timestamp);

                            while ($recurring_timestamp <= $until) {
                                $event_start_desc = "{$day_ordinals[$day_number]} {$weekdays[$week_day]} of {$month_names[$rrules['BYMONTH']]} ".date('Y H:i:s', $recurring_timestamp);
                                $event_start_timestamp = strtotime($event_start_desc);

                                if ($event_start_timestamp > $start_timestamp && $event_start_timestamp < $until) {
                                    $anEvent['DTSTART'] = date('Ymd\T', $event_start_timestamp).$start_time;
                                    $anEvent['DTEND'] = date('Ymd\THis', $this->iCalDateToUnixTimestamp($anEvent['DTSTART']) + $event_timestamp_offset);

                                    $search_date = $anEvent['DTSTART'];
                                    $is_excluded = array_filter($anEvent['EXDATE_array'], function ($val) use ($search_date) { return is_string($val) && strpos($search_date, $val) === 0; });

                                    if (!$is_excluded) {
                                        $events[] = $anEvent;
                                    }
                                }

                                // Move forwards
                                $recurring_timestamp = strtotime($offset, $recurring_timestamp);
                            }
                        } else {
                            $day = date('d', $start_timestamp);
                            $start_time = date('His', $start_timestamp);

                            // Step through years
                            while ($recurring_timestamp <= $until) {
                                // Add specific month dates
                                if (isset($rrules['BYMONTH']) && $rrules['BYMONTH'] != '') {
                                    $event_start_desc = "$day {$month_names[$rrules['BYMONTH']]} ".date('Y H:i:s', $recurring_timestamp);
                                } else {
                                    $event_start_desc = $day.date('F Y H:i:s', $recurring_timestamp);
                                }

                                $event_start_timestamp = strtotime($event_start_desc);

                                if ($event_start_timestamp > $start_timestamp && $event_start_timestamp < $until) {
                                    $anEvent['DTSTART'] = date('Ymd\T', $event_start_timestamp).$start_time;
                                    $anEvent['DTEND'] = date('Ymd\THis', $this->iCalDateToUnixTimestamp($anEvent['DTSTART']) + $event_timestamp_offset);

                                    $search_date = $anEvent['DTSTART'];
                                    $is_excluded = array_filter($anEvent['EXDATE_array'], function ($val) use ($search_date) { return is_string($val) && strpos($search_date, $val) === 0; });

                                    if (!$is_excluded) {
                                        $events[] = $anEvent;
                                    }
                                }

                                // Move forwards
                                $recurring_timestamp = strtotime($offset, $recurring_timestamp);
                            }
                        }
                        break;

                    $events = (isset($count_orig) && sizeof($events) > $count_orig) ? array_slice($events, 0, $count_orig) : $events; // Ensure we abide by COUNT if defined
                }
            }
        }
        $this->cal['VEVENT'] = $events;
    }
530179
@Override
    public int next() {
        // if we have cached break positions and we're still in the range
        // covered by them, just move one step forward in the cache
        if (fCachedBreakPositions != null) {
            if (fPositionInCache < fCachedBreakPositions.length - 1) {
                ++fPositionInCache;
                int pos = fCachedBreakPositions[fPositionInCache];
                fText.setIndex(pos);
                return pos;
            }
            else {
                reset();
            }
        }

        int startPos = current();
        fDictionaryCharCount = 0;
        int result = handleNext(fRData.fFTable);
        if (fDictionaryCharCount > 0) {
            result = checkDictionary(startPos, result, false);
        }
        return result;
    }
995304
def store(self, deferred_result):
        
        self._counter += 1
        self._stored[self._counter] = deferred_result
        return self._counter
242341
public function next()
    {
        ++$this->counter;
        if (!$this->valid()) {
            return;
        }

        $this->currentDate =
            DateTimeParser::parse(
                $this->dates[$this->counter - 1],
                $this->startDate->getTimezone()
            );
    }
482902
def next_update(self, value):
        

        if not isinstance(value, datetime):
            raise TypeError(_pretty_message(
                '''
                next_update must be an instance of datetime.datetime, not %s
                ''',
                _type_name(value)
            ))

        self._next_update = value
1135858
private void ensureNext() {
        // Check if the current scan result has more keys (i.e. the index did not reach the end of the result list)
        if (resultIndex < scanResult.getResult().size()) {
            return;
        }
        // Since the current scan result was fully iterated,
        // if there is another cursor scan it and ensure next key (recursively)
        if (!FIRST_CURSOR.equals(scanResult.getStringCursor())) {
            scanResult = scan(scanResult.getStringCursor(), scanParams);
            resultIndex = 0;
            ensureNext();
        }
    }
762961
private SortedSet<Date> calculateDates() {

        if (null == m_allDates) {
            SortedSet<Date> result = new TreeSet<>();
            if (isAnyDatePossible()) {
                Calendar date = getFirstDate();
                int previousOccurrences = 0;
                while (showMoreEntries(date, previousOccurrences)) {
                    result.add(date.getTime());
                    toNextDate(date);
                    previousOccurrences++;
                }
            }
            m_allDates = result;
        }
        return m_allDates;
    }
960662
public int next() {
        int curIndex = _index;
        // Compute the next index.
        if( _index >= 0 ) {
            int i = _state.length - 1;

            while( i >= 0 ) {
                _index += _sum[i];
                if( ++_state[i] < _ranges[i] )
                    break;
                _index -= _sum[i] * _ranges[i];
                _state[i] = 0;
                i--;
            }

            if( i == -1 )
                _index = -1;
        }
        // Return the current index.
        return curIndex;
    }
1306817
def offset(self, date, n_days):
        '''
        
        '''
#CONSIDER: raise an exception if a date is not in self
        index = self.index(date) + n_days
        if index < 0:
            index = 0
        if index > len(self) - 1:
            index = len(self) - 1
        return self[index]
1074550
def get_next_occurrence(tx: ScheduledTransaction) -> date:
    
    # Reference documentation:
    # https://github.com/MisterY/gnucash-portfolio/issues/3

    # Preparing ref day is an important part before the calculation.
    # It should be:
    #   a) the last occurrence date + 1, or
    #   b) the recurrence start date - 1.
    # because the refDate is the date from which the due dates are being calculated. To include
    # the ones starting today, we need to calculate from the day before.
    ref_datum: Datum = Datum()
    if tx.last_occur:
        #ref_datum.set_value(tx.last_occur)
        ref_datum.from_date(tx.last_occur)
        ref_datum.add_days(1)
    else:
        ref_datum.from_date(tx.recurrence.recurrence_period_start)
        ref_datum.subtract_days(1)
    ref_date: datetime = ref_datum.value

    # today = datetimeutils.today_date()
    #today = Datum().today()
    # skipped schedule
    #if ref_date > today: 
    #    ref_date = today

    ###########################################################
    # The code below mimics the function
    # recurrenceNextInstance(const Recurrence *r, const GDate *refDate, GDate *nextDate)
    # https://github.com/Gnucash/gnucash/blob/115c0bf4a4afcae4269fe4b9d1e4a73ec7762ec6/libgnucash/engine/Recurrence.c#L172

    start_date: Datum = Datum()
    #start_date: datetime = tx.recurrence.recurrence_period_start
    start_date.from_date(tx.recurrence.recurrence_period_start)
    if ref_date < start_date.value:
        # If the occurrence hasn't even started, the next date is the start date.
        # this should also handle the "once" type in most cases.
        return start_date.value.date()

    # start at refDate.
    next_date: Datum = Datum()
    # next_date: datetime = ref_date
    next_date.from_datetime(ref_date)

    # last_date: datetime = tx.last_occur
    # print(tx.name, base_date, tx.recurrence.recurrence_period_start,
    #       tx.recurrence.recurrence_mult, tx.recurrence.recurrence_period_type)

    # /* Step 1: move FORWARD one period, passing exactly one occurrence. */

    mult: int = tx.recurrence.recurrence_mult
    period: str = tx.recurrence.recurrence_period_type
    wadj = tx.recurrence.recurrence_weekend_adjust

    # Not all periods from the original file are included at the moment.
    if period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                   RecurrencePeriod.END_OF_MONTH.value]):
        if period == RecurrencePeriod.YEAR.value:
            mult *= 12

        # handle weekend adjustment here.
        ## Takes care of short months.
        # next_weekday = datetimeutils.get_day_name(next_date)
        next_weekday = next_date.get_day_name()
        if wadj == WeekendAdjustment.BACK.value and (
                period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                            RecurrencePeriod.END_OF_MONTH.value]) and
                (next_weekday == "Saturday" or next_weekday == "Sunday")):
            # "Allows the following Friday-based calculations to proceed if 'next'
            #  is between Friday and the target day."
            days_to_subtract = 1 if next_weekday == "Saturday" else 2

            # next_date = datetimeutils.subtract_days(next_date, days_to_subtract)
            next_date.subtract_days(days_to_subtract)

        if wadj == WeekendAdjustment.BACK.value and (
                period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                            RecurrencePeriod.END_OF_MONTH.value]) and next_weekday == "Friday"):
            next_date = handle_friday(next_date, period, mult, start_date)

        # Line 274.
        temp_date = next_date.clone()
        if (temp_date.is_end_of_month() or
                (period in [RecurrencePeriod.MONTH.value, RecurrencePeriod.YEAR.value]
                 and (next_date.get_day() >= start_date.get_day()))
           ):
            # next_date = datetimeutils.add_months(next_date, mult)
            next_date.add_months(mult)
            # Set at end of month again (?!)
            #next_date = datetimeutils.get_end_of_month(next_date)
        else:
            # one fewer month fwd because of the occurrence in this month.
            next_date.add_months(mult - 1)

    # elif period == "once":
    #     next_date = tx.recurrence.recurrence_period_start

    elif period == RecurrencePeriod.DAY.value:
        logging.warning("daily not handled")

    else:
        logging.info(f"recurrence not handled: {period}")

    #######################
    # Step 2
    # "Back up to align to the base phase. To ensure forward
    # progress, we never subtract as much as we added (x % mult < mult)"

    if period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                   RecurrencePeriod.END_OF_MONTH.value]):
        n_months = (
            12 * (next_date.get_year() - start_date.get_year()) +
            (next_date.get_month() - start_date.get_month())
        )
        next_date.subtract_months(n_months % mult)

        # dim
        days_in_month = datetimeutils.get_days_in_month(
            next_date.get_year(), next_date.get_month())

        # Handle adjustment for 3 ways.
        if (period == RecurrencePeriod.END_OF_MONTH.value or
                next_date.get_day() >= days_in_month):
            # Set to last day of the month.
            next_date.set_day(days_in_month)
        else:
            # Same day as the start.
            next_date.set_day(start_date.get_day())

        # Adjust for dates on the weekend.
        if (period == RecurrencePeriod.YEAR.value or period == RecurrencePeriod.MONTH.value or
                period == RecurrencePeriod.END_OF_MONTH.value):
            weekday = next_date.get_day_name()
            if weekday == "Saturday" or weekday == "Sunday":
                if wadj == WeekendAdjustment.BACK.value:
                    next_date.subtract_days(1 if weekday == "Saturday" else 2)
                elif wadj == WeekendAdjustment.FORWARD.value:
                    next_date.add_days(2 if weekday == "Saturday" else 1)

    return next_date.value.date()
649997
def next_date(self):
        
        nextDt = self.__localAfter(timezone.localtime(), dt.time.min)
        if nextDt is not None:
            return nextDt.date()