Return a readable name from a URL path.

    Useful to log requests on Piwik with categories tree structure.
    See: http://piwik.org/faq/how-to/#faq_62
7181
def extract_name_from_path(path):
    
    base_path, query_string = path.split('?')
    infos = base_path.strip('/').split('/')[2:]  # Removes api/version.
    if len(infos) > 1:  # This is an object.
        name = '{category} / {name}'.format(
            category=infos[0].title(),
            name=infos[1].replace('-', ' ').title()
        )
    else:  # This is a collection.
        name = '{category}'.format(category=infos[0].title())
    return safe_unicode(name)
353737
def read_cldr_names(path, language, category):
    
    filename = data_filename('{}/{}/{}.json'.format(path, language, category))
    fulldata = json.load(open(filename, encoding='utf-8'))
    data = fulldata['main'][language]['localeDisplayNames'][category]
    return data
755637
def relation_path_for(from_name, to_name, identifier_type, identifier_key=None):
    
    return "/{}/<{}:{}>/{}".format(
        name_for(from_name),
        identifier_type,
        identifier_key or "{}_id".format(name_for(from_name)),
        name_for(to_name),
    )
1063114
def get_filename(page, content_type, data):
    
    avoid_collision = uuid.uuid4().hex[:8]

    name_parts = data.name.split('.')
    if len(name_parts) > 1:
        name = slugify('.'.join(name_parts[:-1]), allow_unicode=True)
        ext = slugify(name_parts[-1])
        name = name + '.' + ext
    else:
        name = slugify(data.name)
    filename = os.path.join(
        settings.PAGE_UPLOAD_ROOT,
        'page_' + str(page.id),
        content_type + '-' + avoid_collision + '-' + name
    )
    return filename
223505
def toPairTreePath(name):
    """"""
    sName = sanitizeString(name)
    chunks = []
    for x in range(0, len(sName)):
        if x % 2:
            continue
        if (len(sName) - 1) == x:
            chunk = sName[x]
        else:
            chunk = sName[x: x + 2]
        chunks.append(chunk)
    return os.sep.join(chunks) + os.sep
442846
def get_path_name(self):
        
        path = fix_raw_path(os.path.dirname(os.path.abspath(self.path)))
        name = os.path.basename(self.path)
        return path, name
37952
def make_dir_name_from_url(url):
    """"""
    url_path = urlparse(url).path
    head, tail = os.path.split(url_path)
    # If tail happens to be empty as in case `/foo/`, use foo.
    # If we are looking at a valid but ugly path such as
    # `/foo/.git`, use the "foo" not the ".git".
    if len(tail) is 0 or tail[0] is ".":
        head, tail = os.path.split(head)
    dir_name, ext = os.path.splitext(tail)
    return dir_name
952889
def get_path_name(self):
        
        complete_path = os.path.dirname(os.path.abspath(self.path))
        name = self.path.replace(complete_path + PATH_SEPARATOR, "")
        if name.endswith("/"):
            name = name[: -1]

        return complete_path, name
96878
def get_name_from_url(url):
    

    head, tail = ntpath.split(url)
    params_index = tail.find("&")
    if params_index != -1:
        tail = tail[:params_index]
    params_index = tail.find("?")
    if params_index != -1:
        tail = tail[:params_index]

    basename = ntpath.basename(url)
    params_b_index = basename.find("&")
    if params_b_index != -1:
        basename = basename[:params_b_index]
    return tail or basename
1341501
private static final String getFileName(String path) {
        int index = path.lastIndexOf('/');//stop using File.separatorChar as we are not even remotely close to be using that ANYwhere else - apparently. This makes it fail on Windows systems
        int prefixLength = prefixLength(path);
        if (index < prefixLength) return path.substring(prefixLength);
        return path.substring(index + 1);
    }
579077
def get_name(node):
  
  if isinstance(node, gast.Name):
    return node.id
  elif isinstance(node, (gast.Subscript, gast.Attribute)):
    return get_name(node.value)
  else:
    raise TypeError
405833
def filename_for(self, subpath):
        
        try:
            filename = self.readme_for(subpath)
            return os.path.relpath(filename, self.root_directory)
        except ReadmeNotFoundError:
            return None
1232819
public static String getFilename(String path) throws IllegalArgumentException {
        if (Pattern.matches(sPatternUrl, path))
            return getURLFilename(path);

        return new File(path).getName();
    }
826609
def with_name(self, name):
        
        # N.B. DOES cleanup query/fragment
        if not isinstance(name, str):
            raise TypeError("Invalid name type")
        if "/" in name:
            raise ValueError("Slash in name is not allowed")
        name = self._PATH_QUOTER(name)
        if name in (".", ".."):
            raise ValueError(". and .. values are forbidden")
        parts = list(self.raw_parts)
        if self.is_absolute():
            if len(parts) == 1:
                parts.append(name)
            else:
                parts[-1] = name
            parts[0] = ""  # replace leading '/'
        else:
            parts[-1] = name
            if parts[0] == "/":
                parts[0] = ""  # replace leading '/'
        return URL(
            self._val._replace(path="/".join(parts), query="", fragment=""),
            encoded=True,
        )
818591
def avro_name(url):  # type: (AnyStr) -> AnyStr
    
    frg = urllib.parse.urldefrag(url)[1]
    if frg != '':
        if '/' in frg:
            return frg[frg.rindex('/') + 1:]
        return frg
    return url
560041
def get_handler_name(route: Route, logic: Callable) -> str:
    
    if route.handler_name is not None:
        return route.handler_name
    if any(m for m in route.methods if m.method.lower() == 'post'):
        # A list endpoint
        if route.heading != 'API':
            return '{}ListHandler'.format(get_valid_class_name(route.heading))
        return '{}ListHandler'.format(get_valid_class_name(logic.__name__))
    if route.heading != 'API':
        return '{}Handler'.format(get_valid_class_name(route.heading))
    return '{}Handler'.format(get_valid_class_name(logic.__name__))
239910
def GET_name_history(self, path_info, name):
        
        if not check_name(name) and not check_subdomain(name):
            return self._reply_json({'error': 'Invalid name or subdomain'}, status_code=400)

        qs_values = path_info['qs_values']
        page = qs_values.get('page', None)

        if page is None:
            page = "0"        # compatibility 

        try:
            assert len(page) < 10
            page = int(page)
            assert page >= 0
            assert page <= 2**32 - 1
        except:
            log.error("Invalid page")
            self._reply_json({'error': 'Invalid page'}, status_code=400)
            return

        blockstackd_url = get_blockstackd_url()
        res = blockstackd_client.get_name_history_page(name, page, hostport=blockstackd_url)
        if json_is_error(res):
            log.error('Failed to get name history for {}: {}'.format(name, res['error']))
            return self._reply_json({'error': res['error']}, status_code=res.get('http_status', 502))

        return self._reply_json(res['history'])