Requote uri if it contains non-ascii chars, spaces etc.
515776
def requote_uri(uri):
    
    # To reduce tabulator import time
    import requests.utils
    if six.PY2:
        def url_encode_non_ascii(bytes):
            pattern = '[\x80-\xFF]'
            replace = lambda c: ('%%%02x' % ord(c.group(0))).upper()
            return re.sub(pattern, replace, bytes)
        parts = urlparse(uri)
        uri = urlunparse(
            part.encode('idna') if index == 1
            else url_encode_non_ascii(part.encode('utf-8'))
            for index, part in enumerate(parts))
    return requests.utils.requote_uri(uri)
1263168
def literalize_string(content, is_unicode=False):
    
    '''

    quote_mark = "'"
    if "'" in content:
        quote_mark = '"'
        if '"' in content:
            quote_mark = "'"
            content = content.replace(r"'", r"\'")

    if '\n' in content:
        quote_mark *= 3

    return 'u'[not is_unicode:]+quote_mark+content+quote_mark
433836
def _quote_query(query):
    """"""
    return "&".join("%s=%s" % (
        k, urllib_quote(
            unicode(query[k]).encode('utf-8'), safe='~'))
            for k in sorted(query))
77629
def encode(self, string):
        
        if isinstance(string, unicode):
            string = string.encode("utf-8")
        return quote(string, safe="~")
621451
def orcid_uri_to_orcid(value):
    ""
    if value is None:
        return value
    replace_values = ['http://orcid.org/', 'https://orcid.org/']
    for replace_value in replace_values:
        value = value.replace(replace_value, '')
    return value
991706
static String normalizeUri(String s) {
    int n = s.length();
    boolean colonsIrrelevant = false;
    for (int i = 0; i < n; ++i) {
      char ch = s.charAt(i);
      switch (ch) {
        case '/': case '#': case '?': case ':':
          colonsIrrelevant = true;
          break;
        case '(': case ')':
        case '{': case '}':
          return normalizeUriFrom(s, i, colonsIrrelevant);
        case '\u0589':
        case '\u05c3':
        case '\u2236':
        case '\uff1a':
          if (!colonsIrrelevant) {
            return normalizeUriFrom(s, i, false);
          }
          break;
        default:
          if (ch <= 0x20) {
            return normalizeUriFrom(s, i, false);
          }
          break;
      }
    }
    return s;
  }
537887
def _raw(s):
    """"""

    if isinstance(s, list):
        s = "\n".join(_raw(item) for item in s)

    if s == EOF:
        return "EOF"

    s = repr(s)  # Get raw representation of string
    s = s[1:-1]  # Strip away quotation marks
    if len(s) > 15:
        s = s[:15] + "..."  # Truncate if too long
    return s
48279
public String normalizeUri(String uri, boolean isWindows)
    throws IOException
  {
    CharBuffer cb = new CharBuffer();

    int len = uri.length();

    if (_maxURILength < len)
      throw new BadRequestException(L.l("The request contains an illegal URL because it is too long."));

    char ch;
    if (len == 0 || (ch = uri.charAt(0)) != '/' && ch != '\\')
      cb.append('/');

    for (int i = 0; i < len; i++) {
      ch = uri.charAt(i);

      if (ch == '/' || ch == '\\') {
      dots:
        while (i + 1 < len) {
          ch = uri.charAt(i + 1);

          if (ch == '/' || ch == '\\')
            i++;
          else if (ch != '.')
            break dots;
          else if (len <= i + 2
                   || (ch = uri.charAt(i + 2)) == '/' || ch == '\\') {
            i += 2;
          }
          else if (ch != '.')
            break dots;
          else if (len <= i + 3
                   || (ch = uri.charAt(i + 3)) == '/' || ch == '\\') {
            int j;

            for (j = cb.length() - 1; j >= 0; j--) {
              if ((ch = cb.charAt(j)) == '/' || ch == '\\')
                break;
            }
            if (j > 0)
              cb.length(j);
            else
              cb.length(0);
            i += 3;
          } else {
            throw new BadRequestException(L.l("The request contains an illegal URL."));
          }
        }

        while (isWindows && cb.length() > 0
               && ((ch = cb.lastChar()) == '.' || ch == ' ')) {
          cb.length(cb.length() - 1);

          if (cb.length() > 0
              && (ch = cb.lastChar()) == '/' || ch == '\\') {
            cb.length(cb.length() - 1);
            // server/003n
            continue;
          }
        }

        cb.append('/');
      }
      else if (ch == 0)
        throw new BadRequestException(L.l("The request contains an illegal URL."));
      else
        cb.append(ch);
    }

    while (isWindows && cb.length() > 0
           && ((ch = cb.lastChar()) == '.' || ch == ' ')) {
      cb.length(cb.length() - 1);
    }

    return cb.toString();
  }
782214
function _filter_uri($str) {
		if ($str != '' && $this->permitted_uri_chars != '' && $this->enable_query_strings == FALSE) {
			// preg_quote() in PHP 5.3 escapes -, so the str_replace() and addition of - to preg_quote() is to maintain backwards
			// compatibility as many are unaware of how characters in the permitted_uri_chars will be parsed as a regex pattern
			if (!preg_match("|^[" . str_replace(array ('\\-','\-' ), '-', preg_quote($this->permitted_uri_chars, '-')) . "]+$|i", $str)) {
				show_error('The URI you submitted has disallowed characters.', 400);
			}
		}

		// Convert programatic characters to entities
		$bad=array ('$','(',')','%28','%29' );
		$good=array ('&#36;','&#40;','&#41;','&#40;','&#41;' );

		return str_replace($bad, $good, $str);
	}
498180
def clean_text(self, url, **kwargs):
        """"""
        try:
            return normalize_url(url)
        except UnicodeDecodeError:
            log.warning("Invalid URL: %r", url)
1015682
def safe_unicode(string):
    """"""
    if not PY3:
        uni = string.replace(u'\u2019', "'")
        return uni.encode('utf-8')
        
    return string
859167
def quote_from_bytes(bs, safe='/'):
    
    if not isinstance(bs, (bytes, bytearray)):
        raise TypeError("quote_from_bytes() expected bytes")
    if not bs:
        return str('')
    ### For Python-Future:
    bs = bytes(bs)
    ###
    if isinstance(safe, str):
        # Normalize 'safe' by converting to bytes and removing non-ASCII chars
        safe = str(safe).encode('ascii', 'ignore')
    else:
        ### For Python-Future:
        safe = bytes(safe)
        ###
        safe = bytes([c for c in safe if c < 128])
    if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe):
        return bs.decode()
    try:
        quoter = _safe_quoters[safe]
    except KeyError:
        _safe_quoters[safe] = quoter = Quoter(safe).__getitem__
    return str('').join([quoter(char) for char in bs])
598937
def requote_uri(uri):
    
    safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
    safe_without_percent = "!#$&'()*+,/:;=?@[]~"
    try:
        # Unquote only the unreserved characters
        # Then quote only illegal characters (do not quote reserved,
        # unreserved, or '%')
        return quote(unquote_unreserved(uri), safe=safe_with_percent)
    except ValueError:
        # We couldn't unquote the given URI, so let's try quoting it, but
        # there may be unquoted '%'s in the URI. We need to make sure they're
        # properly quoted so they do not cause issues elsewhere.
        return quote(uri, safe=safe_without_percent)
422152
def _codec_error_url_quote(e):
    
    out = _fast_url_quote(e.object[e.start : e.end])

    if PY2:
        out = out.decode("utf-8")

    return out, e.end
1009940
def quoted(s):
    
    # strip any existing quotes
    s = s.strip(u'"')
    # don't add quotes for minus or leading space
    if s[0] in (u'-', u' '):
        return s
    if u' ' in s or u'/' in s:
        return u'"%s"' % s
    else:
        return s
52331
def encode_and_quote(data):
    """"""
    if data is None:
        return None

    if isinstance(data, unicode):
        data = data.encode("utf-8")
    return urllib.quote_plus(data)
708210
def urlparse(uri):
    """"""
    scheme, netloc, path, params, query, fragment = parse.urlparse(uri)
    return (
        parse.unquote(scheme),
        parse.unquote(netloc),
        parse.unquote(path),
        parse.unquote(params),
        parse.unquote(query),
        parse.unquote(fragment)
    )