Un-escape any percent-escape sequences in a URI that are unreserved
 characters. This leaves all reserved, illegal and non-ASCII bytes encoded.

 @param [String] uri

 @return [String]
961105
def unquote_unreserved(uri)
      parts = uri.split('%')

      (1..parts.length-1).each do |i|
        h = parts[i][0..1]

        if h =~ /^([\h]{2})(.*)/ and c = $1.to_i(16).chr and UNRESERVED_SET.include?(c)
          parts[i] = c + $2
        else
          parts[i] = '%' + parts[i]
        end
      end

      parts.join
    end
84153
function unesc(string) {
    return string.replace(/\\"/g, '"').replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\t/g, '\t').replace(/\\\\/g, '\\');
}
940949
private String[] decodePathTokens(String uri) {
		// Need to split the original URI (instead of QueryStringDecoder#path) then decode the tokens (components),
		// otherwise /test1/123%2F456 will not match /test1/:p1

		int qPos = uri.indexOf("?");
		String encodedPath = (qPos >= 0) ? uri.substring(0, qPos) : uri;

		String[] encodedTokens = PathPattern.removeSlashesAtBothEnds(encodedPath).split("/");

		String[] decodedTokens = new String[encodedTokens.length];
		for (int i = 0; i < encodedTokens.length; i++) {
			String encodedToken = encodedTokens[i];
			decodedTokens[i] = QueryStringDecoder.decodeComponent(encodedToken);
		}

		return decodedTokens;
	}
594415
def percent_encode_non_ascii_headers(self, encoding='UTF-8'):
        
        def do_encode(m):
            return "*={0}''".format(encoding) + quote(to_native_str(m.group(1)))

        for index in range(len(self.headers) - 1, -1, -1):
            curr_name, curr_value = self.headers[index]
            try:
                # test if header is ascii encodable, no action needed
                curr_value.encode('ascii')
            except:
                new_value = self.ENCODE_HEADER_RX.sub(do_encode, curr_value)
                if new_value == curr_value:
                    new_value = quote(curr_value)

                self.headers[index] = (curr_name, new_value)
773039
function encode(uri) {
    
    var prefix,
        protocolCode,
        encoded;

    // check each protocol, unless we've found a match
    // "urn:" is the one exception where we need to keep checking
    // slice so we don't check ""
    protocols.slice(1).forEach(function(protocol) {                        
        if ((!prefix || prefix === "urn:") && uri.indexOf(protocol) === 0) { 
            prefix = protocol;
        }
    });

    if (!prefix) {
        prefix = "";
    }
    
    encoded = util.stringToBytes(uri.slice(prefix.length));
    protocolCode = protocols.indexOf(prefix);    
    // prepend protocol code
    encoded.unshift(protocolCode);
    
    return encoded; 
}
1013877
def normalize_uri(self, uri):
        """"""
        return urllib.quote(
            re.sub(r"\s", '+', uri.strip().lower()),
            safe = '~@#$&()*!+=:),.?/\'')
1159095
private String encodeUri( String uri ) {
    String newUri = "";
    StringTokenizer st = new StringTokenizer( uri, "/ ", true );
    while ( st.hasMoreTokens()) {
      String tok = st.nextToken();
      if ( tok.equals( "/" ))
        newUri += "/";
      else if ( tok.equals( " " ))
        newUri += "%20";
      else {
        try {
          newUri += URLEncoder.encode( tok, "UTF-8" );
        } catch( UnsupportedEncodingException e ) {
          throw  Log.errRTExcept(e);
        }
      }
    }
    return newUri;
  }
1157945
def normalize_uri(cls, uri):
		
		uri = WWebRoute.multiple_slashes_re.sub("/", uri)

		# remove last slash
		if len(uri) > 1:
			if uri[-1] == '/':
				uri = uri[:-1]

		return uri
1129638
function parseUri(str) {
    var parser = re.uri_parser;
    var parserKeys = ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "isColonUri", "relative", "path", "directory", "file", "query", "anchor"];
    var m = parser.exec(str || '');
    var parts = {};

    parserKeys.forEach(function(key, i) {
      parts[key] = m[i] || '';
    });

    return parts;
  }
1148080
public static URI urlToUri( URL url ) throws URISyntaxException {

		URI uri;
		try {
			// Possible failing step.
			uri = url.toURI();

		} catch( Exception e ) {
			// URL did not comply with RFC 2396 => illegal non-escaped characters.
			try {
				uri = new URI(
						url.getProtocol(),
						url.getUserInfo(),
						url.getHost(),
						url.getPort(),
						url.getPath(),
						url.getQuery(),
						url.getRef());

			} catch( Exception e1 ) {
				throw new URISyntaxException( String.valueOf( url ), "Broken URL." );
			}
		}

		uri = uri.normalize();
		return uri;
	}
903108
def base64_url_decode(str)
      encoded_str = str.tr('-_', '+/')
      encoded_str += '=' while !(encoded_str.size % 4).zero?
      Base64.decode64(encoded_str)
    end
409237
static void unescape(final char[] text, final int offset, final int len, final Writer writer,
                         final UriEscapeType escapeType, final String encoding)
                         throws IOException {

        if (text == null) {
            return;
        }

        final int max = (offset + len);

        int readOffset = offset;

        for (int i = offset; i < max; i++) {

            final char c = text[i];

            /*
             * Check the need for an unescape operation at this point
             */

            if (c != ESCAPE_PREFIX && (c != '+' || !escapeType.canPlusEscapeWhitespace())) {
                continue;
            }


            /*
             * At this point we know for sure we will need some kind of unescape, so we
             * can increase the offset copy all the contents pending up to this point.
             */

            if (i - readOffset > 0) {
                writer.write(text, readOffset, (i - readOffset));
            }


            /*
             * Deal with possible '+'-escaped whitespace (application/x-www-form-urlencoded)
             */
            if (c == '+') {
                // if we reached this point with c == '+', it's escaping a whitespace
                writer.write(' ');
                readOffset = i + 1;
                continue;
            }


            /*
             * ESCAPE PROCESS
             * --------------
             * If there are more than one percent-encoded/escaped sequences together, we will
             * need to unescape them all at once (because they might be bytes --up to 4-- of
             * the same char).
             */

            // Max possible size will be the remaining amount of chars / 3
            final byte[] bytes = new byte[(max-i)/3];
            char aheadC = c;
            int pos = 0;

            while (((i + 2) < max) && aheadC == ESCAPE_PREFIX) {
                bytes[pos++] = parseHexa(text[i + 1], text[i + 2]);
                i += 3;
                if (i < max) {
                    aheadC = text[i];
                }
            }

            if (i < max && aheadC == ESCAPE_PREFIX) {
                // Incomplete escape sequence!
                throw new IllegalArgumentException("Incomplete escaping sequence in input");
            }

            try {
                writer.write(new String(bytes, 0, pos, encoding));
            } catch (final UnsupportedEncodingException e) {
                throw new IllegalArgumentException("Exception while escaping URI: Bad encoding '" + encoding + "'", e);
            }


            readOffset = i;

        }


        /*
         * -----------------------------------------------------------------------------------------------
         * Final cleaning: return the original String object if no unescape was actually needed. Otherwise
         *                 append the remaining escaped text and return.
         * -----------------------------------------------------------------------------------------------
         */

        if (max - readOffset > 0) {
            writer.write(text, readOffset, (max - readOffset));
        }

    }
69005
def clean_iri(uri_string):
    ''''''
    uri_string = str(uri_string).strip()
    if uri_string[:1] == "<" and uri_string[len(uri_string)-1:] == ">":
        uri_string = uri_string[1:len(uri_string)-1]
    return uri_string
124013
@Override
    @Basic
    @Column(name = "URI", columnDefinition="TEXT")
    public String getUri() {
	return this.getNamespaceURI()
		+ qnU.unescapeProvLocalName(getLocalPart());
    }
386627
def iri2uri(uri):
	""""""

	assert uri != None, 'iri2uri must be passed a non-none string!'

	original = uri
	if isinstance(uri ,str):
		(scheme, authority, path, query, fragment) = urllib.parse.urlsplit(uri)
		authority = authority.encode('idna').decode('utf-8')
		# For each character in 'ucschar' or 'iprivate'
		#  1. encode as utf-8
		#  2. then %-encode each octet of that utf-8
		# path = urllib.parse.quote(path)
		uri = urllib.parse.urlunsplit((scheme, authority, path, query, fragment))
		uri = "".join([encode(c) for c in uri])

	# urllib.parse.urlunsplit(urllib.parse.urlsplit({something})
	# strips any trailing "?" chars. While this may be legal according to the
	# spec, it breaks some services. Therefore, we patch
	# the "?" back in if it has been removed.
	if original.endswith("?") and not uri.endswith("?"):
		uri = uri+"?"
	return uri
276109
function fixedEncodeURIComponent (str) {
    return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
      return '%' + c.charCodeAt(0).toString(16);
    });
  }
717301
function (uri) {
  return encodeURIComponent(uri)
    .replace(/!/g, '%21')
    .replace(/'/g, '%27')
    .replace(/\(/g, '%28')
    .replace(/\)/g, '%29')
    .replace(/\*/g, '%2A');
}