Unpack binary message header data obtained as a reply from HANA
        :param raw_header: binary string containing message header data
        :returns: named tuple for easy access of header data
185811
def header_from_raw_header_data(cls, raw_header):
        
        try:
            header = MessageHeader(*cls.header_struct.unpack(raw_header))
        except struct.error:
            raise Exception("Invalid message header received")
        return header
1373923
def parse_results_header(cls, header):
        
        header = IORMetricsExtractor.RE_MULTIPLE_SPACES.sub(' ', header)
        header = header.split(' ')
        return header
567046
def _raw_name_string(bufr, strings_offset, str_offset, length):
        
        offset = strings_offset + str_offset
        tmpl = '%ds' % length
        return unpack_from(tmpl, bufr, offset)[0]
729581
def from_raw(conn, raw):
        ''''''
        frame_type = struct.unpack('>l', raw[0:4])[0]
        message = raw[4:]
        if frame_type == FRAME_TYPE_MESSAGE:
            return Message(conn, frame_type, message)
        elif frame_type == FRAME_TYPE_RESPONSE:
            return Response(conn, frame_type, message)
        elif frame_type == FRAME_TYPE_ERROR:
            return Error(conn, frame_type, message)
        else:
            raise TypeError('Unknown frame type: %s' % frame_type)
679298
def _parse_header_links(response):
    
    values = response.headers.getRawHeaders(b'link', [b''])
    value = b','.join(values).decode('ascii')
    with LOG_HTTP_PARSE_LINKS(raw_link=value) as action:
        links = {}
        replace_chars = u' \'"'
        for val in re.split(u', *<', value):
            try:
                url, params = val.split(u';', 1)
            except ValueError:
                url, params = val, u''

            link = {}
            link[u'url'] = url.strip(u'<> \'"')
            for param in params.split(u';'):
                try:
                    key, value = param.split(u'=')
                except ValueError:
                    break
                link[key.strip(replace_chars)] = value.strip(replace_chars)
            links[link.get(u'rel') or link.get(u'url')] = link
        action.add_success_fields(parsed_links=links)
        return links
1016023
def from_raw_message(cls, rawmessage):
        """"""
        empty = cls.create_empty(0x00)
        userdata_dict = cls.normalize(empty, rawmessage)
        return Userdata(userdata_dict)
756901
private function parseRequestHeaders($raw_headers)
    {
        $request_headers = new CaseInsensitiveArray();
        list($first_line, $headers) = $this->parseHeaders($raw_headers);
        $request_headers['Request-Line'] = $first_line;
        foreach ($headers as $key => $value) {
            $request_headers[$key] = $value;
        }
        return $request_headers;
    }
361970
def decode_mail_header(value, default_charset='us-ascii'):
    
    try:
        headers = decode_header(value)
    except email.errors.HeaderParseError:
        return str_decode(str_encode(value, default_charset, 'replace'), default_charset)
    else:
        for index, (text, charset) in enumerate(headers):
            logger.debug("Mail header no. {index}: {data} encoding {charset}".format(
                index=index,
                data=str_decode(text, charset or 'utf-8', 'replace'),
                charset=charset))
            try:
                headers[index] = str_decode(text, charset or default_charset,
                                            'replace')
            except LookupError:
                # if the charset is unknown, force default
                headers[index] = str_decode(text, default_charset, 'replace')

        return ''.join(headers)
1129141
def __send_message_recv_reply(self, packed_message):
        
        payload = io.BytesIO()
        try:
            with self._socket_lock:
                self._socket.sendall(packed_message)

                # Read first message header
                raw_header = self._socket.recv(32)
                header = ReplyMessage.header_from_raw_header_data(raw_header)

                # from pyhdb.lib.stringlib import allhexlify
                # print 'Raw msg header:', allhexlify(raw_header)
                msg = 'Message header (32 bytes): sessionid: %d, packetcount: %d, length: %d, size: %d, noofsegm: %d'
                debug(msg, *(header[:5]))

                # Receive complete message payload
                while payload.tell() < header.payload_length:
                    _payload = self._socket.recv(header.payload_length - payload.tell())
                    if not _payload:
                        break   # jump out without any warning??
                    payload.write(_payload)

                debug('Read %d bytes payload from socket', payload.tell())

                # Keep session id of connection up to date
                if self.session_id != header.session_id:
                    self.session_id = header.session_id
                    self.packet_count = -1
        except socket.timeout:
            raise ConnectionTimedOutError()
        except (IOError, OSError) as error:
            raise OperationalError("Lost connection to HANA server (%r)" % error)

        payload.seek(0)  # set pointer position to beginning of buffer
        return ReplyMessage.unpack_reply(header, payload)
812213
def header(self):
        

        if self._header_encoding is None:
            return self._header
        else:
            return self._header.decode(self._header_encoding)
878197
def parse_message(message, nodata=False):
    
    header = read_machine_header(message)
    h_len = __get_machine_header_length(header)
    meta_raw = message[h_len:h_len + header['meta_len']]
    meta = __parse_meta(meta_raw, header)
    data_start = h_len + header['meta_len']
    data = b''
    if not nodata:
        data = __decompress(
            meta,
            message[data_start:data_start + header['data_len']]
        )
    return header, meta, data
3740
def _encode_message_header(cls, client_id, correlation_id, request_key,
                               api_version=0):
        
        return (struct.pack('>hhih',
                            request_key,          # ApiKey
                            api_version,          # ApiVersion
                            correlation_id,       # CorrelationId
                            len(client_id)) +     # ClientId size
                client_id)
76228
def _generate_response_head_bytes(status_code, headers):
    

    head_string = str(status_code) + _DELIMITER_NEWLINE
    header_tuples = sorted((k, headers[k]) for k in headers)

    for name, value in header_tuples:
        name = _get_header_correctly_cased(name)

        if _should_sign_response_header(name):
            head_string += _FORMAT_HEADER_STRING.format(name, value)

    return (head_string + _DELIMITER_NEWLINE).encode()
614919
def decode_body(headers: MutableMapping, body: bytes) -> dict:
    

    type_, encoding = parse_content_type(headers)
    decoded_body = body.decode(encoding)

    # There is one api that just returns `ok` instead of json. In order to have a consistent API we decided to modify the returned payload into a dict.
    if type_ == "application/json":
        payload = json.loads(decoded_body)
    else:
        if decoded_body == "ok":
            payload = {"ok": True}
        else:
            payload = {"ok": False, "data": decoded_body}

    return payload
740713
public static function parseHeaders(string $raw_header): array
    {
        $raw_header = explode("\r\n\r\n", $raw_header);
        if (count($raw_header) > 1) {
            $headers = [];
            foreach ($raw_header as $header) {
                $headers[] = self::parseHeader($header);
            }

            return $headers;
        } else {
            return self::parseHeader($raw_header[0]);
        }
    }
650711
def _unpack_sdp_into_packet(packet, bytestring):
    
    # Extract the header and the data from the packet
    packet.data = bytestring[10:]  # Everything but the header

    # Unpack the header
    (flags, packet.tag, dest_cpu_port, src_cpu_port,
     packet.dest_y, packet.dest_x,
     packet.src_y, packet.src_x) = struct.unpack_from('<2x8B', bytestring)
    packet.reply_expected = flags == FLAG_REPLY

    # Neaten up the combined VCPU and port fields
    packet.dest_cpu = dest_cpu_port & 0x1f
    packet.dest_port = (dest_cpu_port >> 5)  # & 0x07
    packet.src_cpu = src_cpu_port & 0x1f
    packet.src_port = (src_cpu_port >> 5)
821760
def _unpack_headers(self, headers):
        
        return dict((k,v[0]) for (k,v) in headers.getAllRawHeaders())