Given a stop_id and time in seconds since midnight return the next
    trips to visit the stop.
547470
def handle_json_GET_stoptrips(self, params):
    """"""
    schedule = self.server.schedule
    stop = schedule.GetStop(params.get('stop', None))
    time = int(params.get('time', 0))
    date = params.get('date', "")

    time_trips = stop.GetStopTimeTrips(schedule)
    time_trips.sort()  # OPT: use bisect.insort to make this O(N*ln(N)) -> O(N)
    # Keep the first 5 after param 'time'.
    # Need make a tuple to find correct bisect point
    time_trips = time_trips[bisect.bisect_left(time_trips, (time, 0)):]
    time_trips = time_trips[:5]
    # TODO: combine times for a route to show next 2 departure times
    result = []
    for time, (trip, index), tp in time_trips:
      service_id = trip.service_id
      service_period = schedule.GetServicePeriod(service_id)
      if date and not service_period.IsActiveOn(date):
        continue
      headsign = None
      # Find the most recent headsign from the StopTime objects
      for stoptime in trip.GetStopTimes()[index::-1]:
        if stoptime.stop_headsign:
          headsign = stoptime.stop_headsign
          break
      # If stop_headsign isn't found, look for a trip_headsign
      if not headsign:
        headsign = trip.trip_headsign
      route = schedule.GetRoute(trip.route_id)
      trip_name = ''
      if route.route_short_name:
        trip_name += route.route_short_name
      if route.route_long_name:
        if len(trip_name):
          trip_name += " - "
        trip_name += route.route_long_name
      if headsign:
        trip_name += " (Direction: %s)" % headsign

      result.append((time, (trip.trip_id, trip_name, trip.service_id), tp))
    return result
734737
public Iterable<StopTime> getOrderedStopTimesForTrip (String trip_id) {
        Map<Fun.Tuple2, StopTime> tripStopTimes =
                stop_times.subMap(
                        Fun.t2(trip_id, null),
                        Fun.t2(trip_id, Fun.HI)
                );
        return tripStopTimes.values();
    }
958834
async def get_departures(self):
        """"""
        from .common import CommonFunctions
        common = CommonFunctions(self.loop, self.session)
        departures = []
        endpoint = '{}/StopVisit/GetDepartures/{}'.format(BASE_URL,
                                                          str(self.stopid))
        data = await common.api_call(endpoint)
        for entries in data or []:
            try:
                data = entries['MonitoredVehicleJourney']
                if self.destination is not None:
                    if data['DestinationName'] == self.destination:
                        data = entries['MonitoredVehicleJourney']
                        line = data['LineRef']
                        destinationname = data['DestinationName']
                        monitored = data['MonitoredCall']
                        time = monitored['ExpectedDepartureTime']
                        departures.append({"time": time,
                                           "line": line,
                                           "destination": destinationname})
                else:
                    data = entries['MonitoredVehicleJourney']
                    line = data['LineRef']
                    destinationname = data['DestinationName']
                    monitored = data['MonitoredCall']
                    time = monitored['ExpectedDepartureTime']
                    departures.append({"time": time,
                                       "line": line,
                                       "destination": destinationname})
            except (TypeError, KeyError, IndexError) as error:
                LOGGER.error('Error connecting to Ruter, %s', error)
        self._departures = await common.sort_data(departures, 'time')
1258278
def get_next_departures(stop, filter_line=None, num_line_groups=1, verbose=False):
    

    # Get departures table from online service
    # (great: we don't have to iterate over multiple pages).

    url = BVG_URL_PAT % stop
    if verbose:
        print('- Fetching table for URL "%s".' % url)
    try:
        tables = pd.read_html(url.encode('utf-8'))
    except urllib.error.URLError:
        msg = 'Not connected to the internet?'
        termcolor.cprint(msg, 'red', attrs=['bold'])
        sys.exit(1)
    except ValueError:
        return []
    table = tables[0]
    table.columns = ['Departure', 'Line', 'Destination']

    if verbose:
        print('- Got table with %d entries for "%s".' % (len(table), stop))

    # Cleanup

    # Drop entries with '*' in column Departure...
    # (causes trouble when resulting in an empty table!)
    # table = table[table.Departure.apply(lambda row: " *" not in row)]
    # So, instead remove '*' in column Departure...
    table.is_copy = False # prevents SettingWithCopyWarning
    table.Departure = table.apply(
        lambda row: re.sub('\s*\*\s*', '', row.Departure), axis=1)

    # Replace regex ' +' with ' ' in column Line...
    table.Line = table.apply(lambda row: re.sub(' +', ' ', row.Line), axis=1)

    # Filter desired number of unique combinations of Line and Destination column.
    indices = []
    for i in range(num_line_groups):
        try:
            indices += sorted([tab.index.values[i] 
                for line_dest, tab in table.groupby(['Line', 'Destination'])])
        except IndexError:
            break
    table = table[table.index.map(lambda x: x in indices)]

    # Insert a left-most column with minutes and seconds from now 
    # until the departure time.
    table.insert(0, "Wait", table.Departure.apply(lambda dep: wait_time(dep)))

    # Filter on desired lines only
    if filter_line:
        table = table[table.Line.apply(
            lambda cell: filter_line.lower().encode('utf-8') in cell.lower())]

    return table
174200
def updateNexttime(self, now):
        '''
        
        '''
        if self._recidxnexttime is not None and not self.recur:
            del self.recs[self._recidxnexttime]

        while self.recs and self.nexttime <= now:

            lowtime = 999999999999.9

            # Find the lowest next time of all of our recs (backwards, so we can delete)
            for i in range(len(self.recs) - 1, -1, -1):
                rec = self.recs[i]
                nexttime = rec.nexttime(self.nexttime)
                if nexttime == 0.0:
                    # We blew by and missed a fixed-year appointment, either due to clock shenanigans, this query going
                    # really long, or the initial requirement being in the past
                    logger.warning(f'Missed an appointment: {rec}')
                    del self.recs[i]
                    continue
                if nexttime < lowtime:
                    lowtime = nexttime
                    lowidx = i

            if not self.recs:
                break

            self._recidxnexttime = lowidx
            self.nexttime = lowtime

        if not self.recs:
            self._recidxnexttime = None
            self.nexttime = None
            return
776786
function _info(stops) {
    if ( LOG ) {
      let p = "";
      for ( let i = 0; i < segments.length * 2; i++ ) {
        p = p + " ";
      }

      _log(p + "...Trip " + trip.id);
      _log(p + "   Stop: " + enter.name + " @ " + trip.getStopTime(enter).departure.getTimeReadable());
      _log(p + "   Segments: " + segments.length);
      _printSegments(segments, p + "   ");

      let stopNames = [];
      for ( let i = 0; i < stops.length; i++ ) {
        stopNames.push(stops[i].name);
      }
      _log(p + "   Transfer Stops: " + stops.length + " (" + stopNames.join(', ') + ")");
    }
  }
867779
def read_trip_counts_by_date(path: str) -> Dict[datetime.date, int]:
    """"""
    feed = load_raw_feed(path)
    return _trip_counts_by_date(feed)
1023115
def range_hourly(start=None, stop=None, timezone='UTC', count=None):
    
    return stops(start=start, stop=stop, freq=HOURLY, timezone=timezone, count=count)
793812
def find_stop(self, query, direction=""):
        
        _directions = ["inbound", "outbound", ""]
        direction = direction.lower()
        if direction == "inbound":
            stops = self.inbound_stops
        elif direction == "outbound":
            stops = self.outbound_stops
        else:
            stops = self.inbound_stops + self.outbound_stops
        
        found = []
        for stop in stops:
            q = str(query).lower()
            if q in stop.name.lower() or q in str(stop.id).lower():
                found.append(stop)
        return found
452425
def get_start_and_end_times(
    feed: "Feed", date: Optional[str] = None
) -> List[str]:
    
    st = feed.get_stop_times(date)
    return (
        st["departure_time"].dropna().min(),
        st["arrival_time"].dropna().max(),
    )
522536
def _pass_list(self) -> List[Dict[str, Any]]:
        """"""
        stops: List[Dict[str, Any]] = []
        for stop in self.journey.PassList.BasicStop:
            index = stop.get("index")
            station = stop.Location.Station.HafasName.Text.text
            station_id = stop.Location.Station.ExternalId.text
            stops.append({"index": index, "stationId": station_id, "station": station})
        return stops
239220
def handle_json_GET_neareststops(self, params):
    """'"""
    schedule = self.server.schedule
    lat = float(params.get('lat'))
    lon = float(params.get('lon'))
    limit = int(params.get('limit'))
    stops = schedule.GetNearestStops(lat=lat, lon=lon, n=limit)
    return [StopToTuple(s) for s in stops]
476773
def next_close(self, dt):
        
        idx = next_divider_idx(self.market_closes_nanos, dt.value)
        return pd.Timestamp(self.market_closes_nanos[idx], tz=UTC)
1297622
def _GetTripIndex(self, schedule=None):
    
    trip_index = []
    for trip, sequence in self._GetTripSequence(schedule):
      for index, st in enumerate(trip.GetStopTimes()):
        if st.stop_sequence == sequence:
          trip_index.append((trip, index))
          break
      else:
        raise RuntimeError("stop_sequence %d not found in trip_id %s" %
                           sequence, trip.trip_id)
    return trip_index
580127
def ValidateStopTimesForTrip(self, problems, trip, stop_times):
    """"""
    prev_departure_secs = -1
    consecutive_stop_times_with_potentially_same_time = 0
    consecutive_stop_times_with_fully_specified_same_time = 0

    def CheckSameTimeCount():
      # More than five consecutive stop times with the same time?  Seems not
      # very likely (a stop every 10 seconds?).  In practice, this warning
      # affects about 0.5% of current GTFS trips.
      if (prev_departure_secs != -1 and
          consecutive_stop_times_with_fully_specified_same_time > 5):
        problems.TooManyConsecutiveStopTimesWithSameTime(trip.trip_id,
            consecutive_stop_times_with_fully_specified_same_time,
            prev_departure_secs)
    for index, st in enumerate(stop_times):
      if st.arrival_secs is None or st.departure_secs is None:
        consecutive_stop_times_with_potentially_same_time += 1
        continue
      if (prev_departure_secs == st.arrival_secs and
        st.arrival_secs == st.departure_secs):
        consecutive_stop_times_with_potentially_same_time += 1
        consecutive_stop_times_with_fully_specified_same_time = (
            consecutive_stop_times_with_potentially_same_time)
      else:
        CheckSameTimeCount()
        consecutive_stop_times_with_potentially_same_time = 1
        consecutive_stop_times_with_fully_specified_same_time = 1
      prev_departure_secs = st.departure_secs

    # Make sure to check one last time at the end
    CheckSameTimeCount()
251320
def _AddStopTimeObjectUnordered(self, stoptime, schedule):
    """"""
    stop_time_class = self.GetGtfsFactory().StopTime
    cursor = schedule._connection.cursor()
    insert_query = "INSERT INTO stop_times (%s) VALUES (%s);" % (
       ','.join(stop_time_class._SQL_FIELD_NAMES),
       ','.join(['?'] * len(stop_time_class._SQL_FIELD_NAMES)))
    cursor = schedule._connection.cursor()
    cursor.execute(
        insert_query, stoptime.GetSqlValuesTuple(self.trip_id))
626704
def GetRandomLocationsNearStops(schedule):
  """"""
  locations = []
  for s in schedule.GetStopList():
    locations.append(AddNoiseToLatLng(s.stop_lat, s.stop_lon))
  return locations