Look up routes based on top-level links.
545404
function(typeName, id, snapshot) {
        // FIXME If there is a record, try and look up the self link
        // - Need to use the function from the serializer to build the self key
        // TODO: this basically only works in the simplest of scenarios
        var route = this.getRoute(typeName, id, snapshot);
        if(!route) {
          return this._super(typeName, id, snapshot);
        }

        var url = [];
        var host = get(this, 'host');
        var prefix = this.urlPrefix();
        var param = /\{(.*?)\}/g;

        if (id) {
          if (param.test(route)) {
            url.push(route.replace(param, id));
          } else {
            url.push(route);
          }
        } else {
          url.push(route.replace(param, ''));
        }

        if (prefix) {
          url.unshift(prefix);
        }

        url = url.join('/');

        if (!host && url) {
          url = '/' + url;
        }

        return url;
      }
49884
def path_dirs(urls):
    '''
    
    '''
    path_dirs = StringCounter()
    for url in urls:
        for path_dir in filter(None, urlparse(url).path.split('/')):
            path_dirs[path_dir] += urls[url]
    return path_dirs
676948
def get_route_param_names(endpoint):
    """"""
    try:
        g = current_app.url_map.iter_rules(endpoint)
        return next(g).arguments
    except KeyError:
        return {}
807192
function getPathFromBase(href) {
    var base = route._.base;
    return base[0] === '#'
      ? (href || loc.href || '').split(base)[1] || ''
      : (loc ? getPathFromRoot(href) : href || '').replace(base, '')
  }
149959
function findRoutes (dir, fileExtensions) {
  let files = fs.readdirSync(dir)
  let resolve = f => path.join(dir, f)
  let routes = files.filter(f => fileExtensions.indexOf(path.extname(f)) !== -1).map(resolve)
  let dirs = files.filter(f => fs.statSync(path.join(dir, f)).isDirectory()).map(resolve)
  return routes.concat(...dirs.map(subdir => findRoutes(subdir, fileExtensions)))
}
482391
function routeAndCorrectedPathIndexes(routes, pathIndex) {
        for(var n=0; n<routes.length; n++) {
            var pathIndexes = routes[n].pathIndexes
            if(pathIndexes.start <= pathIndex && pathIndex <= pathIndexes.end || routes[n].route.isDefault) {
                return {routeIndex: n, pathIndex: pathIndexes.start}
            }
        }
        // else
        return {routeIndex: routes.length, pathIndex: pathIndex}
    }
492553
def _links(self):
        """"""
        total = 0.0
        for value in self.link.values():
            total += value
        return total
24463
def get_best_routes_internal(
        chain_state: ChainState,
        token_network_id: TokenNetworkID,
        from_address: InitiatorAddress,
        to_address: TargetAddress,
        amount: int,
        previous_address: Optional[Address],
) -> List[RouteState]:
    
    # TODO: Route ranking.
    # Rate each route to optimize the fee price/quality of each route and add a
    # rate from in the range [0.0,1.0].

    available_routes = list()

    token_network = views.get_token_network_by_identifier(
        chain_state,
        token_network_id,
    )

    if not token_network:
        return list()

    neighbors_heap: List[Neighbour] = list()
    try:
        all_neighbors = networkx.all_neighbors(token_network.network_graph.network, from_address)
    except networkx.NetworkXError:
        # If `our_address` is not in the graph, no channels opened with the
        # address
        return list()

    for partner_address in all_neighbors:
        # don't send the message backwards
        if partner_address == previous_address:
            continue

        channel_state = views.get_channelstate_by_token_network_and_partner(
            chain_state,
            token_network_id,
            partner_address,
        )

        if not channel_state:
            continue

        if channel.get_status(channel_state) != CHANNEL_STATE_OPENED:
            log.info(
                'Channel is not opened, ignoring',
                from_address=pex(from_address),
                partner_address=pex(partner_address),
                routing_source='Internal Routing',
            )
            continue

        nonrefundable = amount > channel.get_distributable(
            channel_state.partner_state,
            channel_state.our_state,
        )

        try:
            length = networkx.shortest_path_length(
                token_network.network_graph.network,
                partner_address,
                to_address,
            )
            neighbour = Neighbour(
                length=length,
                nonrefundable=nonrefundable,
                partner_address=partner_address,
                channelid=channel_state.identifier,
            )
            heappush(neighbors_heap, neighbour)
        except (networkx.NetworkXNoPath, networkx.NodeNotFound):
            pass

    if not neighbors_heap:
        log.warning(
            'No routes available',
            from_address=pex(from_address),
            to_address=pex(to_address),
        )
        return list()

    while neighbors_heap:
        neighbour = heappop(neighbors_heap)
        route_state = RouteState(
            node_address=neighbour.partner_address,
            channel_identifier=neighbour.channelid,
        )
        available_routes.append(route_state)
    return available_routes
456331
private function searchRouter($routes) 
    {
        foreach ($routes as $route) {
            if (!preg_match_all('#^' . $route['request'] . '$#', $this->request, $matches, PREG_OFFSET_CAPTURE))
                continue;
            // Rework matches to only contain the matches, not the orig string
            $matches = array_slice($matches, 1);

            // Extract the matched URL parameters (and only the parameters)
            $params = array_map(function ($match, $index) use ($matches) {

                // We have a following parameter: take the substring from the current param position until the next one's position (thank you PREG_OFFSET_CAPTURE)
                if (isset($matches[$index + 1]) && isset($matches[$index + 1][0]) && is_array($matches[$index + 1][0])) {
                    return trim(substr($match[0][0], 0, $matches[$index + 1][0][1] - $match[0][1]), '/');
                } // We have no following parameters: return the whole lot
                else {
                    return (isset($match[0][0]) ? trim($match[0][0], '/') : null);
                }
            }, $matches, array_keys($matches));

            $route['params'] = $params;
            return $route;
        }
        //not exists ...
        return false;
    }
194410
def get_top_paths(self):
        
        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            self.url + "/traffic/popular/paths"
        )
        if isinstance(data, list):
            return [
                github.Path.Path(self._requester, headers, item, completed=True)
                for item in data
            ]
1240825
def _add_up_route(self, results, real_time=True, stop_at_bounds=False):
        """"""

        start_bounds = self.start_coords['bounds']
        end_bounds = self.end_coords['bounds']

        def between(target, min, max):
            return target > min and target < max

        time = 0
        distance = 0
        for segment in results:
            if stop_at_bounds and segment.get('path'):
                x = segment['path']['x']
                y = segment['path']['y']
                if (
                    between(x, start_bounds.get('left', 0), start_bounds.get('right', 0)) or
                    between(x, end_bounds.get('left', 0), end_bounds.get('right', 0))
                ) and (
                    between(y, start_bounds.get('bottom', 0), start_bounds.get('top', 0)) or
                    between(y, end_bounds.get('bottom', 0), end_bounds.get('top', 0))
                ):
                    continue
            time += segment['crossTime' if real_time else 'crossTimeWithoutRealTime']
            distance += segment['length']
        route_time = time / 60.0
        route_distance = distance / 1000.0
        return route_time, route_distance
124894
function findRouteName(routeToTest) {
    if (!window.Backbone) {
        throw new Error('Dependency: Backbone is missing.');
    }
    let handlers = window.Backbone.history.handlers;
    //console.log('handlers', )
    let h = find(handlers, function (handler) {
        return handler.route.test(routeToTest);
    });
    if (h !== undefined) {
        return h.route.toString();
    }
    return some(handlers, function (handler) {
        if (handler.route.test(routeToTest)) {
            return handler.route.toString();
        }
    });
}
436311
def get_routes(self, viewset):
        
        routes = super(DynamicRouter, self).get_routes(viewset)
        routes += self.get_relation_routes(viewset)
        return routes
914559
private static Map<String, LinkAndRels> urlRelMap(Links links) {

		Map<String, LinkAndRels> urlRelMap = new LinkedHashMap<>();

		links.forEach(link -> {
			LinkAndRels linkAndRels = urlRelMap.computeIfAbsent(link.getHref(), s -> new LinkAndRels());
			linkAndRels.setLink(link);
			linkAndRels.getRels().add(link.getRel());
		});

		return urlRelMap;
	}
61607
def route_path(self, path):
        '''
        
        '''
        path = path.strip('/')
        name, _, subpath = path.partition('/')
        for service in singletons.settings.load_all('SERVICES'):
            if service.SERVICE_NAME == name:  # Found service!
                break
        else:
            return [], None  # found no service

        for partial_url, view in service.urls.items():
            partial_url = partial_url.strip('/')
            if isinstance(view, str):
                view = getattr(service, view)
            regexp = re.sub(r'<[^>]+>', r'([^/]+)', partial_url)
            matches = re.findall('^%s$' % regexp, subpath)
            if matches:
                if '(' not in regexp:
                    matches = []
                return matches, view

        return [], None
52567
def filter_reachable_routes(
        routes: List[RouteState],
        nodeaddresses_to_networkstates: NodeNetworkStateMap,
) -> List[RouteState]:
    """"""
    reachable_routes = []

    for route in routes:
        node_network_state = nodeaddresses_to_networkstates.get(
            route.node_address,
            NODE_NETWORK_UNREACHABLE,
        )

        if node_network_state == NODE_NETWORK_REACHABLE:
            reachable_routes.append(route)

    return reachable_routes
508469
def find_definition_urls(self, set_of_links):
        """"""
        definition_dict = {}
        re_link_name = re.compile('.*p_table_name=(\w+)&p_topic.*')
        for link in set_of_links:
            if link.startswith('http://'):
                table_dict = {}
                html = urlopen(link).read()
                doc = lh.fromstring(html)
                unordered_list = doc.cssselect('#main ul')[-1]
                for li in unordered_list.iterchildren():
                    a = li.find('a')
                    table_dict.update({a.text: a.attrib['href']})
                link_name = re_link_name.sub(r'\1', link).upper()
                definition_dict.update({link_name: table_dict})
        return definition_dict