Get an Unicode string located at the given address.
172228
def get_string_u_at_rva(self, rva, max_length = 2**16, encoding=None):
        """"""

        # If the RVA is invalid let the exception reach the callers. All
        # call-sites of get_string_u_at_rva() will handle it.
        data = self.get_data(rva, 2)
        # max_length is the maximum count of 16bit characters needs to be
        # doubled to get size in bytes
        max_length <<= 1

        requested = min(max_length, 256)
        data = self.get_data(rva, requested)
        # try to find null-termination
        null_index = -1
        while True:
            null_index = data.find(b'\x00\x00', null_index + 1)
            if null_index == -1:
                data_length = len(data)
                if data_length < requested or data_length == max_length:
                    null_index = len(data) >> 1
                    break
                else:
                    # Request remaining part of data limited by max_length
                    data += self.get_data(rva + data_length, max_length - data_length)
                    null_index = requested - 1
                    requested = max_length

            elif null_index % 2 == 0:
                null_index >>= 1
                break

        # convert selected part of the string to unicode
        uchrs = struct.unpack('<{:d}H'.format(null_index), data[:null_index * 2])
        s = u''.join(map(chr, uchrs))

        if encoding:
            return b(s.encode(encoding, 'backslashreplace_'))

        return b(s.encode('utf-8', 'backslashreplace_'))
1372885
def b2u(string):
    
    if (isinstance(string, bytes) or
        (PY2 and isinstance(string, str))):
        return string.decode('utf-8')
    return string
1258831
def get_text_v3(address, stream, mapped=False):
    

    if address == 0:
        return ""

    if mapped:
        size, = UINT16_uf(stream, address + 2)
        text_bytes = stream[address + 4: address + size]
    else:
        stream.seek(address + 2)
        size = UINT16_u(stream.read(2))[0] - 4
        text_bytes = stream.read(size)
    try:
        text = text_bytes.strip(b" \r\t\n\0").decode("latin-1")
    except UnicodeDecodeError as err:
        try:
            from cchardet import detect

            encoding = detect(text_bytes)["encoding"]
            text = text_bytes.strip(b" \r\t\n\0").decode(encoding)
        except ImportError:
            logger.warning(
                'Unicode exception occured and "cChardet" package is '
                'not installed. Mdf version 3 expects "latin-1" '
                "strings and this package may detect if a different"
                " encoding was used"
            )
            raise err

    return text
72329
def urlencode_unicode(data, doseq=0):
    """"""
    data_iter = None
    if isdict(data):
        data_iter = list(data.items())
    elif islist(data):
        data_iter = data

    if data_iter:
        for i, (key, value) in enumerate(data_iter):
            if isinstance(value, text_type):
                # try to convert to str
                try:
                    safe_val = str(value)
                except UnicodeEncodeError:
                    # try to encode as utf-8
                    # if an exception is raised here then idk what to do
                    safe_val = value.encode('utf-8')
                finally:
                    if isdict(data):
                        data[key] = safe_val
                    else:
                        data[i] = (key, safe_val)

    return urlencode(data, doseq=doseq)
652960
def unicoder(p):
    
    if isinstance(p, unicode):
        return p
    if isinstance(p, str):
        return decoder(p)
    else:
        return unicode(decoder(p))
1110644
def _safe_string(self, source, encoding='utf-8'):
        """"""
        if not isinstance(source, str):
            return source.encode(encoding)
        return str(source)
385428
public static String readURLToString(URL u, String encoding) throws IOException {
		for (int i = 0; i < 30; ++i) {
			URLConnection conn = u.openConnection();

			// handle HTTP URLs
			if (conn instanceof HttpURLConnection) {
				HttpURLConnection hconn = (HttpURLConnection)conn;

				// set timeouts
				hconn.setConnectTimeout(15000);
				hconn.setReadTimeout(15000);

				// handle redirects
				switch (hconn.getResponseCode()) {
				case HttpURLConnection.HTTP_MOVED_PERM:
				case HttpURLConnection.HTTP_MOVED_TEMP:
					String location = hconn.getHeaderField("Location");
					u = new URL(u, location);
					continue;
				}
			}

			return readStreamToString(conn.getInputStream(), encoding);
		}

		throw new IOException("Too many HTTP redirects");
	}
1150134
def verify_signature_unicode(self, address, signature, message):
        """"""
        hexdata = binascii.hexlify(message.encode("utf-8"))
        return self.verify_signature(address, signature, hexdata)
406771
def utf8(value):
    
    """
    try:
        if isinstance(value, bytes):
            return value.decode('utf-8')
        else:
            return value
    except Exception:
        raise ValueError('Not UTF-8: %r' % value)
1131343
def safe_str(value):
    
    if sys.version_info < (3,0) and isinstance(value, unicode):
        return value.encode('utf-8')
    else:
        return str(value)
606012
def getStringForBytes(self, s):
        
        h = hash(s)
        u = self._unicodes.get(h, None)

        if u is not None:
            return u

        u = self._unicodes[h] = s.decode('utf-8')

        return u
173210
def get_named_unicode(self, i):
        """"""

        index = i.index
        value = []
        try:
            if next(i) != '{':
                raise SyntaxError("Named Unicode missing '{'' at %d!" % (i.index - 1))
            c = next(i)
            while c != '}':
                value.append(c)
                c = next(i)
        except StopIteration:
            raise SyntaxError("Unmatched '}' at %d!" % index)

        return ''.join(value)
324564
def str_to_inet(address):
    
    # First try ipv4 and then ipv6
    try:
        return socket.inet_pton(socket.AF_INET, address)
    except socket.error:
        return socket.inet_pton(socket.AF_INET6, address)
379606
private String buildUri(final String address) throws UnsupportedEncodingException {

        final StringBuilder sb = new StringBuilder();
        sb.append(protocol)
          .append("://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=")
          .append(address);

        if(apiKey != null) {
            sb.append("&apiKey=").append(apiKey);
        }
        if (regionBias != null) {
            sb.append("&region=").append(regionBias);
        }
        return sb.toString();
    }
19849
def ensure_str(text):
    """
    if isinstance(text, unicode):
        try:
            return text.encode(pyreadline_codepage, u"replace")
        except (LookupError, TypeError):
            return text.encode(u"ascii", u"replace")
    return text
872862
def geocode(self, string, bounds=None, region=None,
                language=None, sensor=False):
        '''
        '''
        if isinstance(string, unicode):
            string = string.encode('utf-8')

        params = {
            'address': self.format_string % string,
            'sensor': str(sensor).lower()
        }

        
        if bounds:
            params['bounds'] = bounds
            
        if region:
            params['region'] = region
            
        if language:
            params['language'] = language
            

        if not self.premier:
            url = self.get_url(params)
        else:
            url = self.get_signed_url(params)

        return self.GetService_url(url)
42645
def force_unicode(value):
    
    if not isinstance(value, (str, unicode)):
        value = unicode(value)
    if isinstance(value, str):
        value = value.decode('utf-8')
    return value