Build a new feed by restricting this one to only the stops,
    trips, shapes, etc. used by the routes with the given list of
    route IDs.
    Return the resulting feed.
330507
def restrict_to_routes(feed: "Feed", route_ids: List[str]) -> "Feed":
    
    # Initialize the new feed as the old feed.
    # Restrict its DataFrames below.
    feed = feed.copy()

    # Slice routes
    feed.routes = feed.routes[feed.routes["route_id"].isin(route_ids)].copy()

    # Slice trips
    feed.trips = feed.trips[feed.trips["route_id"].isin(route_ids)].copy()

    # Slice stop times
    trip_ids = feed.trips["trip_id"]
    feed.stop_times = feed.stop_times[
        feed.stop_times["trip_id"].isin(trip_ids)
    ].copy()

    # Slice stops
    stop_ids = feed.stop_times["stop_id"].unique()
    feed.stops = feed.stops[feed.stops["stop_id"].isin(stop_ids)].copy()

    # Slice calendar
    service_ids = feed.trips["service_id"]
    if feed.calendar is not None:
        feed.calendar = feed.calendar[
            feed.calendar["service_id"].isin(service_ids)
        ].copy()

    # Get agency for trips
    if "agency_id" in feed.routes.columns:
        agency_ids = feed.routes["agency_id"]
        if len(agency_ids):
            feed.agency = feed.agency[
                feed.agency["agency_id"].isin(agency_ids)
            ].copy()

    # Now for the optional files.
    # Get calendar dates for trips.
    if feed.calendar_dates is not None:
        feed.calendar_dates = feed.calendar_dates[
            feed.calendar_dates["service_id"].isin(service_ids)
        ].copy()

    # Get frequencies for trips
    if feed.frequencies is not None:
        feed.frequencies = feed.frequencies[
            feed.frequencies["trip_id"].isin(trip_ids)
        ].copy()

    # Get shapes for trips
    if feed.shapes is not None:
        shape_ids = feed.trips["shape_id"]
        feed.shapes = feed.shapes[
            feed.shapes["shape_id"].isin(shape_ids)
        ].copy()

    # Get transfers for stops
    if feed.transfers is not None:
        feed.transfers = feed.transfers[
            feed.transfers["from_stop_id"].isin(stop_ids)
            | feed.transfers["to_stop_id"].isin(stop_ids)
        ].copy()

    return feed
220114
def _route(self, mapper):
        

        # Build up the keyword arguments to feed to connect()
        kwargs = dict(conditions=dict(function=self._filter))

        # Restrict the verbs
        if self.verbs:
            kwargs['conditions']['method'] = self.verbs

        # Add requirements, if provided
        if self.requirements:
            kwargs['requirements'] = self.requirements

        # Hook to allow subclasses to override arguments to connect()
        uri = self.route(self.uri, kwargs)

        # Create the route
        mapper.connect(None, uri, **kwargs)
668730
def routes(cls, application=None):
        
        if application:
            for route in cls._routes:
                application.add_handlers(route['host'], route['spec'])
        else:
            return [route['spec'] for route in cls._routes]
367104
def get_current_waypoints(boatd=None):
    '''
    
    '''

    if boatd is None:
        boatd = Boatd()

    content = boatd.get('/waypoints')
    return [Point(*coords) for coords in content.get('waypoints')]
581925
def bfs(self, graph, start):
        
        newstatediag = {}

        # maintain a queue of paths
        queue = []
        visited = []
        # push the first path into the queue
        queue.append(start)
        while queue:
            # get the first path from the queue
            state = queue.pop(0)
            # get the last node from the path
            # visited
            visited.append(state.id)
            # enumerate all adjacent nodes, construct a new path and push it
            # into the queue
            for key in state.trans:
                if state.trans[key] != []:
                    if key not in visited:
                        for nextstate in graph:
                            if graph[nextstate].id == key:
                                queue.append(graph[nextstate])
                                break
        i = 0
        for state in graph:
            if graph[state].id in visited:
                newstatediag[i] = graph[state]
                i = i + 1

        return newstatediag
1156708
def MergeDataSets(self):
    
    rules = set()
    for (schedule, merge_map, zone_map) in ([self.feed_merger.a_schedule,
                                             self.feed_merger.a_merge_map,
                                             self.feed_merger.a_zone_map],
                                            [self.feed_merger.b_schedule,
                                             self.feed_merger.b_merge_map,
                                             self.feed_merger.b_zone_map]):
      for fare in schedule.GetFareAttributeList():
        for fare_rule in fare.GetFareRuleList():
          fare_id = merge_map[
              schedule.GetFareAttribute(fare_rule.fare_id)].fare_id
          route_id = (fare_rule.route_id and
                      merge_map[schedule.GetRoute(fare_rule.route_id)].route_id)
          origin_id = (fare_rule.origin_id and
                       zone_map[fare_rule.origin_id])
          destination_id = (fare_rule.destination_id and
                            zone_map[fare_rule.destination_id])
          contains_id = (fare_rule.contains_id and
                         zone_map[fare_rule.contains_id])
          rules.add((fare_id, route_id, origin_id, destination_id,
                     contains_id))
    for fare_rule_tuple in rules:
      migrated_fare_rule = transitfeed.FareRule(*fare_rule_tuple)
      self.feed_merger.merged_schedule.AddFareRuleObject(migrated_fare_rule)

    if rules:
      self.feed_merger.problem_reporter.FareRulesBroken(self)
    print('Fare Rules: union has %d fare rules' % len(rules))
    return True
1310795
def clean(feed: "Feed") -> "Feed":
    
    feed = feed.copy()
    ops = [
        "clean_ids",
        "clean_times",
        "clean_route_short_names",
        "drop_zombies",
    ]
    for op in ops:
        feed = globals()[op](feed)

    return feed
1338538
def assign_routes(self, app):
        """"""
        for grp in self.filters:
            for f in self.filters[grp]:
                if f.route_func:
                    f.register_route(app)

        for c in self.charts:
            if c.route_func:
                c.register_route(app)
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
896514
def regenerate_routes(self):
        ''
        for destination, origins in self.regexes.items():
            # we want only the names that match the destination regexes.
            resolved = [
                name for name in self.names
                if name is not destination
                and any(origin.search(name) for origin in origins)
            ]

            ignores = self.ignore_regexes.get(destination, [])
            for origin in resolved:
                destinations = self.routes.setdefault(origin, set())

                if any(ignore.search(origin) for ignore in ignores):
                    self.logger.info('ignoring route "%s" -> "%s"', origin, destination)
                    try:
                        destinations.remove(destination)
                        self.logger.debug('removed "%s" -> "%s"', origin, destination)
                    except KeyError:
                        pass

                    continue

                if destination not in destinations:
                    self.logger.info('added route "%s" -> "%s"', origin, destination)

                destinations.add(destination)
110004
def make_router(*routings):
    
    routes = []
    for routing in routings:
        methods, regex, app = routing[:3]
        if isinstance(methods, basestring):
            methods = (methods,)
        vars = routing[3] if len(routing) >= 4 else {}
        routes.append((methods, re.compile(unicode(regex)), app, vars))

    def router(environ, start_response):
        """Dispatch request to controllers."""
        req = webob.Request(environ)
        split_path_info = req.path_info.split('/')
        if split_path_info[0]:
            # When path_info doesn't start with a "/" this is an error or a attack => Reject request.
            # An example of an URL with such a invalid path_info: http://127.0.0.1http%3A//127.0.0.1%3A80/result?...
            ctx = contexts.Ctx(req)
            headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx)
            return wsgihelpers.respond_json(ctx,
                dict(
                    apiVersion = 1,
                    error = dict(
                        code = 400,  # Bad Request
                        message = ctx._(u"Invalid path: {0}").format(req.path_info),
                        ),
                    ),
                headers = headers,
                )(environ, start_response)
        for methods, regex, app, vars in routes:
            match = regex.match(req.path_info)
            if match is not None:
                if methods is not None and req.method not in methods:
                    ctx = contexts.Ctx(req)
                    headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx)
                    return wsgihelpers.respond_json(ctx,
                        dict(
                            apiVersion = 1,
                            error = dict(
                                code = 405,
                                message = ctx._(u"You cannot use HTTP {} to access this URL. Use one of {}.").format(
                                    req.method, methods),
                                ),
                            ),
                        headers = headers,
                        )(environ, start_response)
                if getattr(req, 'urlvars', None) is None:
                    req.urlvars = {}
                req.urlvars.update(match.groupdict())
                req.urlvars.update(vars)
                req.script_name += req.path_info[:match.end()]
                req.path_info = req.path_info[match.end():]
                return app(req.environ, start_response)
        ctx = contexts.Ctx(req)
        headers = wsgihelpers.handle_cross_origin_resource_sharing(ctx)
        return wsgihelpers.respond_json(ctx,
            dict(
                apiVersion = 1,
                error = dict(
                    code = 404,  # Not Found
                    message = ctx._(u"Path not found: {0}").format(req.path_info),
                    ),
                ),
            headers = headers,
            )(environ, start_response)

    return router
655091
def transport_routes(self):
        
        routes = {}
        try:
            big_div = self._ad_page_content.find(
                'div', {"class": "half_area_box_right"})
            uls = big_div.find("ul")
            if uls is None:
                return None
            for li in uls.find_all('li'):
                route_li = li.text.split(':')
                routes[route_li[0]] = [x.strip()
                                       for x in route_li[1].split(',')]
            return routes
        except Exception as e:
            if self._debug:
                logging.error(e.args[0])
            return 'N/A'
222871
function buildRoutes(app, api, graphqlEndpoint) {
  return function (done) {
    api.forEachOperation(function (path, method, operation) {
      buildRoute(app, path, method, operation, graphqlEndpoint);
    });
    done(null, api);
  }
}
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();
    }
1042448
def make_paths(paths, weights=None):
    
    npaths = len(paths)
    weights = weights or [1] * npaths
    assert len(paths) == len(weights)

    G = nx.DiGraph()
    for path, w in zip(paths, weights):
        for a, b in pairwise(path):
            update_weight(G, a, b, w)
    return G
296765
def getRoutes(self):
        
        routes = []
        try:
            out = subprocess.Popen([routeCmd, "-n"], 
                                   stdout=subprocess.PIPE).communicate()[0]
        except:
            raise Exception('Execution of command %s failed.' % ipCmd)
        lines = out.splitlines()
        if len(lines) > 1:
            headers = [col.lower() for col in lines[1].split()]
            for line in lines[2:]:
                routes.append(dict(zip(headers, line.split())))
        return routes
876388
def getTracesByIds(self, trace_ids, adjust):
    
    self.send_getTracesByIds(trace_ids, adjust)
    return self.recv_getTracesByIds()