Decode a list of headers.

	Takes a list of bytestrings, returns a list of unicode strings.
	The character set for each bytestring is individually decoded.
9931
def decode_headers(header_list):
	'''
	
	'''

	decoded_headers = []
	for header in header_list:
		if cchardet:
			inferred = cchardet.detect(header)
			if inferred and inferred['confidence'] > 0.8:
				# print("Parsing headers!", header)
				decoded_headers.append(header.decode(inferred['encoding']))
			else:
				decoded_headers.append(header.decode('iso-8859-1'))
		else:    # pragma: no cover
			# All bytes are < 127 (e.g. ASCII)
			if all([char & 0x80 == 0 for char in header]):
				decoded_headers.append(header.decode("us-ascii"))
			elif isUTF8Strict(header):
				decoded_headers.append(header.decode("utf-8"))
			else:
				decoded_headers.append(header.decode('iso-8859-1'))

	return decoded_headers
1100910
def populate_headers(headers):
    
    result = [''] * len(headers[0])
    values = [''] * len(headers)
    for k_index in range(0, len(headers)):
        for i_index in range(0, len(headers[k_index])):
            if headers[k_index][i_index]:
                values[k_index] = normalizer(
                    str(headers[k_index][i_index]))  # pass to str

            if len(exclude_empty_values(result)) > i_index:
                result[i_index] += "-{}".format(values[k_index])
            else:
                result[i_index] += str(values[k_index])

    return result
699413
def stream_decode_response_unicode(iterator, r):
    """"""
    encoding = get_encoding_from_headers(r.headers)
    if encoding is None:
        for item in iterator:
            yield item
        return

    decoder = codecs.getincrementaldecoder(encoding)(errors='replace')
    for chunk in iterator:
        rv = decoder.decode(chunk)
        if rv:
            yield rv
    rv = decoder.decode('', final=True)
    if rv:
        yield rv
397859
def header_encode(header_bytes, charset='iso-8859-1'):
    
    if not header_bytes:
        return ""
    if isinstance(header_bytes, str):
        header_bytes = header_bytes.encode(charset)
    encoded = b64encode(header_bytes).decode("ascii")
    return '=?%s?b?%s?=' % (charset, encoded)
1259522
def to_str(s):
    
    if isinstance(s, bytes):
        s = s.decode('utf-8')
    elif not isinstance(s, str):
        s = str(s)
    return s
121241
def decode(cls, data, bytes_to_read=None):
        
        if isinstance(data, bytes):
            data = io.BytesIO(data)
        if bytes_to_read is None:
            bytes_to_read = Int32.decode(data)

        # if FetchRequest max_bytes is smaller than the available message set
        # the server returns partial data for the final message
        # So create an internal buffer to avoid over-reading
        raw = io.BytesIO(data.read(bytes_to_read))

        items = []
        while bytes_to_read:
            try:
                offset = Int64.decode(raw)
                msg_bytes = Bytes.decode(raw)
                bytes_to_read -= 8 + 4 + len(msg_bytes)
                items.append((offset, len(msg_bytes), Message.decode(msg_bytes)))
            except ValueError:
                # PartialMessage to signal that max_bytes may be too small
                items.append((None, None, PartialMessage()))
                break
        return items
1174914
def split_header_value(str)
      return [] if str.nil?
      str = str.dup.strip
      binary_encode(str)
      str.scan(%r'\G((?:"(?:\\.|[^"])+?"|[^",]+)+)
                    (?:,\s*|\Z)'xn).flatten
    end
947758
def parse_headers(lines, offset=0):
    
    headers = {}
    for header_line in lines[offset:]:
        header_match = HEADER_LINE_RE.match(header_line)
        if header_match:
            key = header_match.group('key')
            key = re.sub(r'\\.', _unescape_header, key)
            if key not in headers:
                value = header_match.group('value')
                value = re.sub(r'\\.', _unescape_header, value)
                headers[key] = value
    return headers
1053691
def _try_decode_list(content):
        
        result = list()
        for value in content:
            result.append(try_utf8_decode(value))
        return result
575461
public static String parseCharset(Map<String, String> headers) {
        return parseCharset(headers, HTTP.DEFAULT_CONTENT_CHARSET);
    }
354662
async def read_headers(stream: asyncio.StreamReader) -> "Headers":
    
    # https://tools.ietf.org/html/rfc7230#section-3.2

    # We don't attempt to support obsolete line folding.

    headers = Headers()
    for _ in range(MAX_HEADERS + 1):
        line = await read_line(stream)
        if line == b"":
            break

        # This may raise "ValueError: not enough values to unpack"
        raw_name, raw_value = line.split(b":", 1)
        if not _token_re.fullmatch(raw_name):
            raise ValueError("Invalid HTTP header name: %r" % raw_name)
        raw_value = raw_value.strip(b" \t")
        if not _value_re.fullmatch(raw_value):
            raise ValueError("Invalid HTTP header value: %r" % raw_value)

        name = raw_name.decode("ascii")  # guaranteed to be ASCII at this point
        value = raw_value.decode("ascii", "surrogateescape")
        headers[name] = value

    else:
        raise ValueError("Too many HTTP headers")

    return headers
1339935
private String[] extractAndDecodeHeader(String header) throws IOException {

        byte[] base64Token = header.substring(6).getBytes(CREDENTIALS_CHARSET);
        byte[] decoded;
        try {
            decoded = Base64.decode(base64Token);
        } catch (IllegalArgumentException e) {
            throw new BadCredentialsException("Failed to decode basic authentication token");
        }

        String token = new String(decoded, CREDENTIALS_CHARSET);

        int delim = token.indexOf(":");

        if (delim == -1) {
            throw new BadCredentialsException("Invalid basic authentication token");
        }
        return new String[] {token.substring(0, delim), token.substring(delim + 1)};
    }
248500
def string(s):
    
    ret = ['"']
    for c in s:
        if ' ' <= c < '\x7f':
            if c == "'" or c == '"' or c == '\\':
                ret.append('\\')
            ret.append(c)
            continue
        elif c <= '\x7f':
            if c in ('\r', '\n', '\t'):
                # unicode-escape produces bytes
                ret.append(c.encode('unicode-escape').decode("ascii"))
                continue
        i = ord(c)
        ret.append('\\u')
        ret.append('%x' % (i >> 12))
        ret.append('%x' % ((i >> 8) & 0x0f))
        ret.append('%x' % ((i >> 4) & 0x0f))
        ret.append('%x' % (i & 0x0f))
    ret.append('"')
    return ''.join(ret)
394848
public T decode(ProtoHead head, InputStream in, Charset charset) throws IOException {
        this.head = head;
        return decodeContent(in, charset);
    }
741483
def _encodeHeader(headerValue):
    
    try:
        return headerValue.encode('ascii', 'strict')
    except UnicodeError:
        encoded = headerValue.encode("utf-8")
        return header.Header(encoded, "UTF-8").encode()
1255401
def decode_response(data):
    '''
    '''
    res = CaseInsensitiveDict()
    for dataline in data.decode('utf-8').splitlines()[1:]:
        dataline = dataline.strip()
        if not dataline:
            continue
        line_parts = dataline.split(':', 1)
        # This is to deal with headers with no value.
        if len(line_parts) < 2:
            line_parts = (line_parts[0], '')
        res[line_parts[0].strip()] = line_parts[1].strip()
    return res
826234
def decode(data, encoding='utf-8', errors='strict'):
    
    data_type = type(data)

    if data_type == bytes:
        return bytes2unicode(data, encoding, errors)
    if data_type in (dict, list, tuple):
        if data_type == dict:
            data = data.items()
        return data_type(map(decode, data))
    return data