Decode this report from a msgpack encoded binary blob.
348578
def decode(self):
        """"""

        report_dict = msgpack.unpackb(self.raw_report, raw=False)

        events = [IOTileEvent.FromDict(x) for x in report_dict.get('events', [])]
        readings = [IOTileReading.FromDict(x) for x in report_dict.get('data', [])]

        if 'device' not in report_dict:
            raise DataError("Invalid encoded FlexibleDictionaryReport that did not "
                            "have a device key set with the device uuid")

        self.origin = report_dict['device']
        self.report_id = report_dict.get("incremental_id", IOTileReading.InvalidReadingID)
        self.sent_timestamp = report_dict.get("device_sent_timestamp", 0)
        self.origin_streamer = report_dict.get("streamer_index")
        self.streamer_selector = report_dict.get("streamer_selector")
        self.lowest_id = report_dict.get('lowest_id')
        self.highest_id = report_dict.get('highest_id')

        return readings, events
595658
def decode_nfo( buffer ):
    """"""
    assert utils.is_bytes( buffer )
    return '\n'.join( [''.join( [CP437[y] for y in x] ) for x in buffer.split( b'\r\n' )] )
1255488
def decode_ber(ber):
    
    ber = bytearray(ber)
    length = ber[0]
    bytes_read = 1
    if length > 127:
        bytes_read += length & 127 # Strip off the high bit
        length = 0
        for i in range(1, bytes_read):
            length += ber[i] << (8 * (bytes_read - i - 1))
    return length, bytes_read
1012353
def decodebytes(input):
    """"""
    py_version = sys.version_info[0]
    if py_version >= 3:
        return _decodebytes_py3(input)
    return _decodebytes_py2(input)
830117
def smart_decode(binary, errors="strict"):
    
    d = chardet.detect(binary)
    encoding = d["encoding"]
    confidence = d["confidence"]

    text = binary.decode(encoding, errors=errors)
    return text, encoding, confidence
1031575
def from_msgpack(b, *, max_bin_len=MAX_BIN_LEN, max_str_len=MAX_STR_LEN):
    
    # Docs for raw parameter are somewhat hard to find so they're copied here:
    #   If true, unpack msgpack raw to Python bytes (default).
    #   Otherwise, unpack to Python str (or unicode on Python 2) by decoding with UTF-8 encoding (recommended).
    #   In msgpack >= 0.6, max_xxx_len is reduced from 2 GB to 1 MB, so we set the relevant ones
    #       to 2 GB as to not run into issues with the size of the values returned from rpcq
    return msgpack.loads(b, object_hook=_object_hook, raw=False,
                         max_bin_len=max_bin_len, max_str_len=max_str_len)
882766
def decode_file(fname):
    """"""
    if _debug: decode_file._debug("decode_file %r", fname)

    if not pcap:
        raise RuntimeError("failed to import pcap")

    # create a pcap object, reading from the file
    p = pcap.pcap(fname)

    # loop through the packets
    for i, (timestamp, data) in enumerate(p):
        try:
            pkt = decode_packet(data)
            if not pkt:
                continue
        except Exception as err:
            if _debug: decode_file._debug("    - exception decoding packet %d: %r", i+1, err)
            continue

        # save the packet number (as viewed in Wireshark) and timestamp
        pkt._number = i + 1
        pkt._timestamp = timestamp

        yield pkt
838573
def Decode(self, encoded_data):
    
    try:
      # TODO: replace by libuna implementation or equivalent. The behavior of
      # base64.b64decode() does not raise TypeError for certain invalid base64
      # data e.g. b'\x01\x02\x03\x04\x05\x06\x07\x08' these are silently
      # ignored.
      decoded_data = base64.b64decode(encoded_data)
    except (TypeError, binascii.Error) as exception:
      raise errors.BackEndError(
          'Unable to decode base64 stream with error: {0!s}.'.format(
              exception))

    return decoded_data, b''
1249002
def decode(self, encoded_payload):
        """"""
        self.packets = []
        while encoded_payload:
            if six.byte2int(encoded_payload[0:1]) <= 1:
                packet_len = 0
                i = 1
                while six.byte2int(encoded_payload[i:i + 1]) != 255:
                    packet_len = packet_len * 10 + six.byte2int(
                        encoded_payload[i:i + 1])
                    i += 1
                self.packets.append(packet.Packet(
                    encoded_packet=encoded_payload[i + 1:i + 1 + packet_len]))
            else:
                i = encoded_payload.find(b':')
                if i == -1:
                    raise ValueError('invalid payload')

                # extracting the packet out of the payload is extremely
                # inefficient, because the payload needs to be treated as
                # binary, but the non-binary packets have to be parsed as
                # unicode. Luckily this complication only applies to long
                # polling, as the websocket transport sends packets
                # individually wrapped.
                packet_len = int(encoded_payload[0:i])
                pkt = encoded_payload.decode('utf-8', errors='ignore')[
                    i + 1: i + 1 + packet_len].encode('utf-8')
                self.packets.append(packet.Packet(encoded_packet=pkt))

                # the engine.io protocol sends the packet length in
                # utf-8 characters, but we need it in bytes to be able to
                # jump to the next packet in the payload
                packet_len = len(pkt)
            encoded_payload = encoded_payload[i + 1 + packet_len:]
173333
def decode(vol, filename, content):
  """"""
  bbox = Bbox.from_filename(filename)
  content_len = len(content) if content is not None else 0

  if not content:
    if vol.fill_missing:
      content = ''
    else:
      raise EmptyVolumeException(filename)

  shape = list(bbox.size3()) + [ vol.num_channels ]

  try:
    return chunks.decode(
      content, 
      encoding=vol.encoding, 
      shape=shape, 
      dtype=vol.dtype, 
      block_size=vol.compressed_segmentation_block_size,
    )
  except Exception as error:
    print(red('File Read Error: {} bytes, {}, {}, errors: {}'.format(
        content_len, bbox, filename, error)))
    raise
1236672
def decode_network_packet(buf):
    
    off = 0
    blen = len(buf)

    while off < blen:
        ptype, plen = header.unpack_from(buf, off)

        if plen > blen - off:
            raise ValueError("Packet longer than amount of data in buffer")

        if ptype not in _decoders:
            raise ValueError("Message type %i not recognized" % ptype)

        yield ptype, _decoders[ptype](ptype, plen, buf[off:])
        off += plen
474014
def decode_qp_numpy(msg, return_matrix=True):
    
    import numpy as np

    result = msg['answer']

    # Build some little endian type encodings
    double_type = np.dtype(np.double)
    double_type = double_type.newbyteorder('<')
    int_type = np.dtype(np.int32)
    int_type = int_type.newbyteorder('<')

    # Decode the simple buffers
    result['energies'] = np.frombuffer(base64.b64decode(result['energies']),
                                       dtype=double_type)

    if 'num_occurrences' in result:
        result['num_occurrences'] = \
            np.frombuffer(base64.b64decode(result['num_occurrences']),
                        dtype=int_type)

    result['active_variables'] = \
        np.frombuffer(base64.b64decode(result['active_variables']),
                      dtype=int_type)

    # Measure out the binary data size
    num_solutions = len(result['energies'])
    active_variables = result['active_variables']
    num_variables = len(active_variables)
    total_variables = result['num_variables']

    # Decode the solutions, which will be a continuous run of bits
    byte_type = np.dtype(np.uint8)
    byte_type = byte_type.newbyteorder('<')
    bits = np.unpackbits(np.frombuffer(base64.b64decode(result['solutions']),
                         dtype=byte_type))

    # Clip off the extra bits from encoding
    if num_solutions:
        bits = np.reshape(bits, (num_solutions, bits.size // num_solutions))
        bits = np.delete(bits, range(num_variables, bits.shape[1]), 1)

    # Switch from bits to spins
    default = 3
    if msg['type'] == 'ising':
        bits = bits.astype(np.int8)
        bits *= 2
        bits -= 1
        default = 0

    # Fill in the missing variables
    solutions = np.full((num_solutions, total_variables), default, dtype=np.int8)
    solutions[:, active_variables] = bits
    result['solutions'] = solutions

    # If the final result shouldn't be numpy formats switch back to python objects
    if not return_matrix:
        result['energies'] = result['energies'].tolist()
        if 'num_occurrences' in result:
            result['num_occurrences'] = result['num_occurrences'].tolist()
        result['active_variables'] = result['active_variables'].tolist()
        result['solutions'] = result['solutions'].tolist()

    return result
810631
def decode_b64(data):
    ''''''
    byte_string = data.encode('utf-8')
    decoded = base64.b64decode(byte_string)
    return decoded.decode('utf-8')
188615
def to_bytes(s, encoding="utf-8"):
    """"""
    if isinstance(s, six.binary_type):
        return s
    if six.PY3:
        return bytes(s, encoding)
    return s.encode(encoding)
461384
def decode_sent_msg(pref, message, pretty=False):
    
    newline = "\n" if pretty else " "
    indent = "    " if pretty else ""
    start = newline + indent

    out = []
    out.append("%s%s{%sSEQNUM: %d," % (pref, newline, start, message[Const.W_SEQ]))
    out.append("%sCOMPRESSION: %d," % (start, message[Const.W_COMPRESSION]))
    out.append("%sHASH: %s...," % (start, str(binascii.b2a_hex(message[Const.W_HASH]).decode('ascii'))[:10]))
    out.append("%sMESSAGE:%s{%sCLIENTREF: %s," % (start, start, start + indent,
                                                  message[Const.W_MESSAGE][Const.M_CLIENTREF]))
    out.append("%sRESOURCE: %s," % (start + indent, R_TYPES[message[Const.W_MESSAGE][Const.M_RESOURCE]]))
    out.append("%sTYPE: %s," % (start + indent, C_TYPES[message[Const.W_MESSAGE][Const.M_TYPE]]))
    out.append("%sACTION: %s," % (start + indent, message[Const.W_MESSAGE][Const.M_ACTION]))
    if Const.M_RANGE in message[Const.W_MESSAGE]:
        out.append("%sRANGE: %s," % (start + indent, message[Const.W_MESSAGE][Const.M_RANGE]))
    out.append("%sPAYLOAD: %s%s}%s}" % (start + indent, message[Const.W_MESSAGE][Const.M_PAYLOAD], start, newline))

    return ''.join(out)
359080
def _zp_decode(self, msg):
        """"""
        zone_partitions = [ord(x)-0x31 for x in msg[4:4+Max.ZONES.value]]
        return {'zone_partitions': zone_partitions}
855255
def decode_imod(packet, channel=1):
    """"""
    val = str(packet.get(QSDATA, ''))
    if len(val) == 8 and val.startswith('4e'):
        try:
            _map = ((5, 1), (5, 2), (5, 4), (4, 1), (5, 1), (5, 2))[
                channel - 1]
            return (int(val[_map[0]], 16) & _map[1]) == 0
        except IndexError:
            return None
    return None