Given a resource_url, figure out what it would resolve into
15353
def find_destination_type(self, resource_url):
        '''
        
        '''
        resolvers = self.converters.values()
        for resolver in resolvers:
            # Not all resolvers are opinionated about destination types
            if not hasattr(resolver, 'get_destination_type'):
                continue

            destination_type = resolver.get_destination_type(resource_url)
            if destination_type:
                return destination_type
561184
def uri(resource, args = {})
      uri = resource.uri(args)

      query_values  = args[:query]   || {}
      header_values = args[:headers] || {}

      params.each { |param|
        name = param.name

        if param.style == 'header'
          value = header_values[name] || header_values[name.to_sym]
          value = param % value

          uri.headers[name] = value if value
        else
          value = query_values[name] || query_values[name.to_sym]
          value = param.format(value, nil, 'query')

          uri.query << value if value && !value.empty?
        end
      }

      uri
    end
964853
def url_for(self, *args: str, **kwargs: str) -> URL:
        """"""
        return self._resource.url_for(*args, **kwargs)
607972
def resolve_url(url, directory=None, permissions=None):
    

    u = urlparse(url)

    # create the name of the destination file
    if directory is None:
        directory = os.getcwd()
    filename = os.path.join(directory,os.path.basename(u.path))

    if u.scheme == '' or u.scheme == 'file':
        # for regular files, make a direct copy
        if os.path.isfile(u.path):
            if os.path.isfile(filename):
                # check to see if src and dest are the same file
                src_inode = os.stat(u.path)[stat.ST_INO]
                dst_inode = os.stat(filename)[stat.ST_INO]
                if src_inode != dst_inode:
                    shutil.copy(u.path, filename)
            else:
                shutil.copy(u.path, filename)
        else:
            errmsg  = "Cannot open file %s from URL %s" % (u.path, url)
            raise ValueError(errmsg)

    elif u.scheme == 'http' or u.scheme == 'https':
        s = requests.Session()
        s.mount(str(u.scheme)+'://',
            requests.adapters.HTTPAdapter(max_retries=5))

        # look for an ecp cookie file and load the cookies
        cookie_dict = {}
        ecp_file = '/tmp/ecpcookie.u%d' % os.getuid()
        if os.path.isfile(ecp_file):
            cj = cookielib.MozillaCookieJar()
            cj.load(ecp_file, ignore_discard=True, ignore_expires=True)
        else:
            cj = []

        for c in cj:
            if c.domain == u.netloc:
                # load cookies for this server
                cookie_dict[c.name] = c.value
            elif u.netloc == "code.pycbc.phy.syr.edu" and \
              c.domain == "git.ligo.org":
                # handle the redirect for code.pycbc to git.ligo.org
                cookie_dict[c.name] = c.value

        r = s.get(url, cookies=cookie_dict, allow_redirects=True)
        if r.status_code != 200:
            errmsg = "Unable to download %s\nError code = %d" % (url,
                r.status_code)
            raise ValueError(errmsg)

        # if we are downloading from git.ligo.org, check that we
        # did not get redirected to the sign-in page
        if u.netloc == 'git.ligo.org' or u.netloc == 'code.pycbc.phy.syr.edu':
            # Check if we have downloaded a binary file.
            if istext(r.content):
                soup = BeautifulSoup(r.content, 'html.parser')
                desc = soup.findAll(attrs={"property":"og:url"})
                if len(desc) and \
                  desc[0]['content'] == 'https://git.ligo.org/users/sign_in':
                    raise ValueError(ecp_cookie_error.format(url))

        output_fp = open(filename, 'w')
        output_fp.write(r.content)
        output_fp.close()

    else:
        # TODO: We could support other schemes such as gsiftp by
        # calling out to globus-url-copy
        errmsg  = "Unknown URL scheme: %s\n" % (u.scheme)
        errmsg += "Currently supported are: file, http, and https."
        raise ValueError(errmsg)

    if not os.path.isfile(filename):
        errmsg = "Error trying to create file %s from %s" % (filename,url)
        raise ValueError(errmsg)

    if permissions:
        if os.access(filename, os.W_OK):
            os.chmod(filename, permissions)
        else:
            # check that the file has at least the permissions requested
            s = os.stat(filename)[stat.ST_MODE]
            if (s & permissions) != permissions:
                errmsg = "Could not change permissions on %s (read-only)" % url
                raise ValueError(errmsg)

    return filename
624643
def _parse_parameters(self, resource, params):
        '''
        '''
        # remove params from resource URI (needed for paginated stuff)
        parsed_uri = urlparse(resource)
        qs = parsed_uri.query
        resource = urlunparse(parsed_uri._replace(query=''))
        prms = {}
        for tup in parse_qsl(qs):
            prms[tup[0]] = tup[1]

        # params supplied to self.get() override parsed params
        for key in params:
            prms[key] = params[key]
        return resource, prms
716591
def id_from_url(url, param_name: str) -> int:
    
    if url is None:
        raise ValueError('url is none')
    elif isinstance(url, int):
        # Seems to already be the url.
        return url
    if not url:
        raise ValueError('Seems to be empty')

    try:
        return int(url)
    except ValueError:
        pass

    parsed = urlparse(url)
    try:
        resource_url = app.url_map.bind(parsed.netloc).match(
            parsed.path
        )
    except NotFound:
        raise ValueError('No URL found')

    if param_name in resource_url[1]:
        return resource_url[1][param_name]
    else:
        raise ValueError(
            'Parameter {name} could not be extracted'.format(
                name=param_name
            )
        )
1268899
def reconstruct_uri(environ):
    
    uri = environ.get('SCRIPT_NAME', '') + environ['PATH_INFO']
    if environ.get('QUERY_STRING'):
        uri += '?' + environ['QUERY_STRING']
    return uri
403098
function resolveUrl( url, contextUrl, ignoreSameOriginPolicy ) {

		function getProtocol( url ) {
			return url.substring(0, url.indexOf("//"));
		}

		function getProtocolAndHost( url ) {
			return url.substring(0, url.indexOf("/", 8));
		}

		if (!contextUrl) {
			contextUrl = baseUrl;
		}

		// protocol-relative path
		if (url.substring(0,2)=="//") {
			url = getProtocol(contextUrl) + url;
		}

		// absolute path
		if (/^https?:\/\//i.test(url)) {
			return !ignoreSameOriginPolicy && getProtocolAndHost(contextUrl) != getProtocolAndHost(url) ? null : url ;
		}

		// root-relative path
		if (url.charAt(0)=="/")	{
			return getProtocolAndHost(contextUrl) + url;
		}

		// relative path
		var contextUrlPath = contextUrl.split(/[?#]/)[0]; // ignore query string in the contextUrl
		if (url.charAt(0) != "?" && contextUrlPath.charAt(contextUrlPath.length - 1) != "/") {
			contextUrlPath = contextUrlPath.substring(0, contextUrlPath.lastIndexOf("/") + 1);
		}

		return contextUrlPath + url;
	}
274986
def resolve(self, uri=None, **parts):
		""""""
		
		if uri:
			result = self.__class__(urljoin(str(self), str(uri)))
		else:
			result = self.__class__(self)
		
		for part, value in parts.items():
			if part not in self.__all_parts__:
				raise TypeError("Unknown URI component: " + part)
			
			setattr(result, part, value)
		
		return result
45579
def resolve(track_url):
    
    try:
        path = urlparse.urlparse(track_url).path
        tracks = client.get('/tracks', q=path)

        if tracks:
            return tracks[0]
        else:
            raise ValueError('Track not found for URL {}'.format(track_url))
    except Exception as e:
        raise ValueError('Error obtaining track by url: {}'.format(str(e)))
461789
def resolve_url(self, catalog_url):
        
        if catalog_url != '':
            resolver_base = catalog_url.split('catalog.xml')[0]
            resolver_url = resolver_base + self.url_path
            resolver_xml = session_manager.urlopen(resolver_url)
            tree = ET.parse(resolver_xml)
            root = tree.getroot()
            if 'name' in root.attrib:
                self.catalog_name = root.attrib['name']
            else:
                self.catalog_name = 'No name found'
            resolved_url = ''
            found = False
            for child in root.iter():
                if not found:
                    tag_type = child.tag.split('}')[-1]
                    if tag_type == 'dataset':
                        if 'urlPath' in child.attrib:
                            ds = Dataset(child)
                            resolved_url = ds.url_path
                            found = True
            if found:
                return resolved_url
            else:
                log.warning('no dataset url path found in latest.xml!')
1061984
def gen_url_name(resource):
    "  "

    if resource._meta.parent:
        yield resource._meta.parent._meta.url_name

    if resource._meta.prefix:
        yield resource._meta.prefix

    for p in resource._meta.url_params:
        yield p

    yield resource._meta.name
1080595
def get_resource_url(resource):
    
    path = model_path(resource)
    parsed = list(urlparse.urlparse(path))
    parsed[1] = ""
    return urlparse.urlunparse(parsed)
758800
def _get_resource_uri(self, guid=None):
        
        uri = self.uri + '/v1/resource'
        if guid:
            uri += '/' + urllib.quote_plus(guid)
        return uri
8402
function resolveURL(url, path) {
  if (typeof url !== 'string' || typeof path !== 'string') {
    return new Error('url-and-path-required');
  }

  /* Remove leading and duplicate slashes */
  url = url.replace(/\/{2,}/g, '/').replace(/^\//, '').replace(':/','://');

  let parsedUrl = urlModule.parse(url);
  if (protocols.indexOf(parsedUrl.protocol) < 0 || !parsedUrl.host) {
    return new Error('invalid-url');
  }

  let resolvedUrl = urlModule.resolve(parsedUrl.href, path);
  return resolvedUrl;
}
179623
def parse_resource_from_url(self, url):
        
        # special case for the api root
        if url == '/api':
            return 'api'
        elif url == '/katello':
            return 'katello'

        match = self.resource_pattern.match(url)
        if match:
            return match.groupdict().get('resource', None)
1089716
def resolve_redirects_if_needed(self, uri):
        
        if type(uri) == type("string") or type(uri) == type(u"unicode"):

            if uri.startswith("www."):  # support for lazy people
                uri = "http://%s" % str(uri)
            if uri.startswith("http://"):
                # headers = "Accept: application/rdf+xml"  # old way
                headers = {'Accept': "application/rdf+xml"}
                req = urllib2.Request(uri, headers=headers)
                res = urllib2.urlopen(req)
                uri = res.geturl()

        else:
            raise Exception("A URI must be in string format.")

        return uri