Construct an _OpMsg from raw bytes.
420065
def unpack(cls, msg):
        """"""
        flags, first_payload_type, first_payload_size = cls.UNPACK_FROM(msg)
        if flags != 0:
            raise ProtocolError("Unsupported OP_MSG flags (%r)" % (flags,))
        if first_payload_type != 0:
            raise ProtocolError(
                "Unsupported OP_MSG payload type (%r)" % (first_payload_type,))

        if len(msg) != first_payload_size + 5:
            raise ProtocolError("Unsupported OP_MSG reply: >1 section")

        # Convert Python 3 memoryview to bytes. Note we should call
        # memoryview.tobytes() if we start using memoryview in Python 2.7.
        payload_document = bytes(msg[5:])
        return cls(flags, payload_document)
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
1022238
def from_message(cls, message):
        
        self = cls(json=message)
        try:
            decoded_data = json.loads(message)
        except ValueError:
            # Message is not a valid JSON. Return as invalid.
            return self
        try:
            report_data = decoded_data['csp-report']
        except KeyError:
            # Message is not a valid CSP report. Return as invalid.
            return self

        # Extract individual fields
        for report_name, field_name in REQUIRED_FIELD_MAP + OPTIONAL_FIELD_MAP:
            setattr(self, field_name, report_data.get(report_name))
        # Extract integer fields
        for report_name, field_name in INTEGER_FIELD_MAP:
            value = report_data.get(report_name)
            field = self._meta.get_field(field_name)
            min_value, max_value = connection.ops.integer_field_range(field.get_internal_type())
            if min_value is None:
                min_value = 0
            # All these fields are possitive. Value can't be negative.
            min_value = max(min_value, 0)
            if value is not None and min_value <= value and (max_value is None or value <= max_value):
                setattr(self, field_name, value)
        # Extract disposition
        disposition = report_data.get('disposition')
        if disposition in dict(DISPOSITIONS).keys():
            self.disposition = disposition

        # Check if report is valid
        is_valid = True
        for field_name in dict(REQUIRED_FIELD_MAP).values():
            if getattr(self, field_name) is None:
                is_valid = False
                break
        self.is_valid = is_valid

        return self
1321517
def unpack(cls, msg, client, server, request_id):
        
        payload_document = OrderedDict()
        flags, = _UNPACK_UINT(msg[:4])
        pos = 4
        if flags != 0 and flags != 2:
            raise ValueError('OP_MSG flag must be 0 or 2 not %r' % (flags,))

        while pos < len(msg):
            payload_type, = _UNPACK_BYTE(msg[pos:pos + 1])
            pos += 1
            payload_size, = _UNPACK_INT(msg[pos:pos + 4])
            if payload_type == 0:
                doc = bson.decode_all(msg[pos:pos + payload_size],
                                      CODEC_OPTIONS)[0]
                payload_document.update(doc)
                pos += payload_size
            elif payload_type == 1:
                section_size, = _UNPACK_INT(msg[pos:pos + 4])
                pos += 4
                identifier, pos = _get_c_string(msg, pos)
                # Section starts w/ 4-byte size prefix, identifier ends w/ nil.
                documents_len = section_size - len(identifier) - 1 - 4
                documents = bson.decode_all(msg[pos:pos + documents_len],
                                            CODEC_OPTIONS)
                payload_document[identifier] = documents
                pos += documents_len

        database = payload_document['$db']
        return OpMsg(payload_document, namespace=database, flags=flags,
                     _client=client, request_id=request_id,
                     _server=server)
734314
def from_bytes(self, raw):
        ''''''
        if len(raw) < TCP._MINLEN:
            raise NotEnoughDataError("Not enough bytes ({}) to reconstruct an TCP object".format(len(raw)))
        fields = struct.unpack(TCP._PACKFMT, raw[:TCP._MINLEN])
        self._src = fields[0]
        self._dst = fields[1]
        self._seq = fields[2]        
        self._ack = fields[3]
        offset = fields[4] >> 12
        self._flags = fields[4] & 0x01ff
        self._window = fields[5]
        csum = fields[6]
        self._urg = fields[7]
        headerlen = offset * 4
        optlen = headerlen - TCP._MINLEN
        self._options.from_bytes(raw[TCP._MINLEN:headerlen])
        return raw[headerlen:]
719799
def to_mime_message(self):
        """"""
        msg = MIMEMultipart('alternative')
        msg['Subject'] = self._header(self._subject or '')

        msg['From'] = self._encoded(self._addrs_to_header([self._from]))
        msg['To'] = self._encoded(self._addrs_to_header(self._to))

        if self._cc:
            msg['CC'] = self._addrs_to_header(self._cc)

        if self._headers:
            for key, value in self._headers.items():
                msg[key] = self._header(value)

        for part in self._parts:
            type_maj, type_min = part[0].split('/')
            if type_maj == 'text' and type_min in ('html', 'plain'):
                msg.attach(MIMEText(part[1], type_min, self._charset))
            else:
                msg.attach(part[1])

        return msg
642782
def decode_msg(msg, enc='utf-8'):
    
    # We avoid the get_payload decoding machinery for raw
    # content-transfer-encodings potentially containing non-ascii characters,
    # such as 8bit or binary, as these are encoded using raw-unicode-escape which
    # seems to prevent subsequent utf-8 decoding.
    cte = str(msg.get('content-transfer-encoding', '')).lower()
    decode = cte not in ("8bit", "7bit", "binary")
    res = msg.get_payload(decode=decode)
    return decode_bytes(res, enc)
1217964
def fromMessage(klass, message, op_endpoint=UNUSED):
        
        if message.isOpenID1():
            session_type = message.getArg(OPENID_NS, 'session_type')
            if session_type == 'no-encryption':
                logging.warn('Received OpenID 1 request with a no-encryption '
                            'assocaition session type. Continuing anyway.')
            elif not session_type:
                session_type = 'no-encryption'
        else:
            session_type = message.getArg(OPENID2_NS, 'session_type')
            if session_type is None:
                raise ProtocolError(message,
                                    text="session_type missing from request")

        try:
            session_class = klass.session_classes[session_type]
        except KeyError:
            raise ProtocolError(message,
                                "Unknown session type %r" % (session_type,))

        try:
            session = session_class.fromMessage(message)
        except ValueError, why:
            raise ProtocolError(message, 'Error parsing %s session: %s' %
                                (session_class.session_type, why[0]))

        assoc_type = message.getArg(OPENID_NS, 'assoc_type', 'HMAC-SHA1')
        if assoc_type not in session.allowed_assoc_types:
            fmt = 'Session type %s does not support association type %s'
            raise ProtocolError(message, fmt % (session_type, assoc_type))

        self = klass(session, assoc_type)
        self.message = message
        self.namespace = message.getOpenIDNamespace()
        return self
812271
def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2
        """"""
        ret = cls(message.items())
        # ret now contains only the last header line for each duplicate.
        # Importing with all duplicates would be nice, but this would
        # mean to repeat most of the raw parsing already done, when the
        # message object was created. Extracting only the headers of interest 
        # separately, the cookies, should be faster and requires less
        # extra code.
        for key in duplicates:
            ret.discard(key)
            for val in message.getheaders(key):
                ret.add(key, val)
            return ret
619584
def parse_raw(self, raw):
        """"""
        if not isinstance(raw, bytes):
            raise PyVLXException("AliasArray::invalid_type_if_raw", type_raw=type(raw))
        if len(raw) != 21:
            raise PyVLXException("AliasArray::invalid_size", size=len(raw))
        nbr_of_alias = raw[0]
        if nbr_of_alias > 5:
            raise PyVLXException("AliasArray::invalid_nbr_of_alias", nbr_of_alias=nbr_of_alias)
        for i in range(0, nbr_of_alias):
            self.alias_array_.append((raw[i*4+1:i*4+3], raw[i*4+3:i*4+5]))
183577
def from_bytes(rawbytes):
        '''
        
        '''
        icmpv6popts = ICMPv6OptionList()

        i = 0
        while i < len(rawbytes):
            opttype = rawbytes[i]
            optnum = ICMPv6OptionNumber(opttype)
            obj = ICMPv6OptionClasses[optnum]()
            eaten = obj.from_bytes(rawbytes[i:])
            i += eaten
            icmpv6popts.append(obj)
        return icmpv6popts
889949
def _op_msg(flags, command, dbname, read_preference, slave_ok, check_keys,
            opts, ctx=None):
    """"""
    command['$db'] = dbname
    if "$readPreference" not in command:
        if slave_ok and not read_preference.mode:
            command["$readPreference"] = (
                ReadPreference.PRIMARY_PREFERRED.document)
        else:
            command["$readPreference"] = read_preference.document
    name = next(iter(command))
    try:
        identifier = _FIELD_MAP.get(name)
        docs = command.pop(identifier)
    except KeyError:
        identifier = ""
        docs = None
    try:
        if ctx:
            return _op_msg_compressed(
                flags, command, identifier, docs, check_keys, opts, ctx)
        return _op_msg_uncompressed(
            flags, command, identifier, docs, check_keys, opts)
    finally:
        # Add the field back to the command.
        if identifier:
            command[identifier] = docs
599555
def from_raw(self, raw: RawScalar) -> Optional[bytes]:
        """"""
        try:
            return base64.b64decode(raw, validate=True)
        except TypeError:
            return None
696162
def from_bytes(rawbytes):
        '''
        
        '''
        ipopts = IPOptionList()

        i = 0
        while i < len(rawbytes):
            opttype = rawbytes[i]
            optcopied = opttype >> 7         # high order 1 bit
            optclass = (opttype >> 5) & 0x03 # next 2 bits
            optnum = opttype & 0x1f          # low-order 5 bits are optnum
            optnum = IPOptionNumber(optnum)
            obj = IPOptionClasses[optnum]()
            eaten = obj.from_bytes(rawbytes[i:])
            i += eaten
            ipopts.append(obj)
        return ipopts
124053
def from_raw_message(cls, rawmessage):
        """"""
        return AllLinkComplete(rawmessage[2],
                               rawmessage[3],
                               rawmessage[4:7],
                               rawmessage[7],
                               rawmessage[8],
                               rawmessage[9])
64870
def _to_base_type(self, msg):
    """"""
    ent = _message_to_entity(msg, self._modelclass)
    ent.blob_ = self._protocol_impl.encode_message(msg)
    return ent
954027
def parse(cls, msg):
        """"""
        lines = msg.splitlines()
        version, status_code, reason = lines[0].split()
        headers = cls.parse_headers('\r\n'.join(lines[1:]))
        return cls(version=version, status_code=status_code,
                   reason=reason, headers=headers)