Convert a dict to TLV8 bytes.
540220
def write_tlv(data):
    """"""
    tlv = b''
    for key, value in data.items():
        tag = bytes([int(key)])
        length = len(value)
        pos = 0

        # A tag with length > 255 is added multiple times and concatenated into
        # one buffer when reading the TLV again.
        while pos < len(value):
            size = min(length, 255)
            tlv += tag
            tlv += bytes([size])
            tlv += value[pos:pos+size]
            pos += size
            length -= size
    return tlv
4213
def to_unicode(data, encoding='UTF-8'):
    """"""
    if isinstance(data, unicode_type):
        return data

    if isinstance(data, bytes):
        return unicode_type(data, encoding=encoding)

    if hasattr(data, '__iter__'):
        try:
            dict(data)
        except TypeError:
            pass
        except ValueError:
            # Assume it's a one dimensional data structure
            return (to_unicode(i, encoding) for i in data)
        else:
            # We support 2.6 which lacks dict comprehensions
            if hasattr(data, 'items'):
                data = data.items()
            return dict(((to_unicode(k, encoding), to_unicode(v, encoding)) for k, v in data))

    return data
814597
def to_bytes(s, encoding=None, errors='strict'):
    '''
    
    '''
    if encoding is None:
        # Try utf-8 first, and fall back to detected encoding
        encoding = ('utf-8', __salt_system_encoding__)
    if not isinstance(encoding, (tuple, list)):
        encoding = (encoding,)

    if not encoding:
        raise ValueError('encoding cannot be empty')

    exc = None
    if six.PY3:
        if isinstance(s, bytes):
            return s
        if isinstance(s, bytearray):
            return bytes(s)
        if isinstance(s, six.string_types):
            for enc in encoding:
                try:
                    return s.encode(enc, errors)
                except UnicodeEncodeError as err:
                    exc = err
                    continue
            # The only way we get this far is if a UnicodeEncodeError was
            # raised, otherwise we would have already returned (or raised some
            # other exception).
            raise exc  # pylint: disable=raising-bad-type
        raise TypeError('expected bytes, bytearray, or str')
    else:
        return to_str(s, encoding, errors)
1265729
def _long_to_bytes(n, length, byteorder):
    
    if byteorder == 'little':
        indexes = range(length)
    else:
        indexes = reversed(range(length))
    return bytearray((n >> i * 8) & 0xff for i in indexes)
1227479
def to_python(self):
        """"""
        mapping = {}
        for row in self.rows:
            mapping[row[0]] = _format_python_value(row[1])
        return mapping
1073721
def translate_bytes(val):
    '''
    
    '''
    try:
        val = int(val)
    except (TypeError, ValueError):
        if not isinstance(val, six.string_types):
            val = six.text_type(val)
    return val
787017
def _serialize_dict(cls, data):
        '''
        
        '''
        return b64encode(zlib.compress(cPickle.dumps(data, protocol=2))).decode()
547301
def decode_dict(data):
    
    if six.PY3:
        return data
    rv = {}
    for key, value in iteritems(data):
        if isinstance(key, text_type):
            key = key.encode('utf-8')

        if isinstance(value, text_type):
            value = value.encode('utf-8')
        elif isinstance(value, list):
            value = _decode_list(value)
        # no need to recurse into dict, json library will do that
        rv[key] = value
    return rv
330454
def _bytes_to_json(value):
    """"""
    if isinstance(value, bytes):
        value = base64.standard_b64encode(value).decode("ascii")
    return value
678023
def to_bytes(s):
    
    if sys.version_info < (3,):
        return "".join(map(chr, s))
    else:
        return bytes(s)
1040819
def _dict_to_teleport(dict_value):
    """"""
    if len(dict_value) == 1:
        for key, value in dict_value.items():
            if key is str:
                return {"Map": from_val(value)}

    optional = {}
    required = {}
    for key, value in dict_value.items():
        if isinstance(key, Optional):
            optional[key.value] = from_val(value)
        else:
            required[key] = from_val(value)

    return {"Struct": {
        "required": required,
        "optional": optional}}
1371869
def pack_bytes(self, obj_dict, encoding=None):
        """"""
        assert self.dict_to_bytes or self.dict_to_string
        encoding = encoding or self.default_encoding or 'utf-8'
        LOGGER.debug('%r encoding dict with encoding %s', self, encoding)
        if self.dict_to_bytes:
            return None, self.dict_to_bytes(obj_dict)
        try:
            return encoding, self.dict_to_string(obj_dict).encode(encoding)
        except LookupError as error:
            raise web.HTTPError(
                406, 'failed to encode result %r', error,
                reason='target charset {0} not found'.format(encoding))
        except UnicodeEncodeError as error:
            LOGGER.warning('failed to encode text as %s - %s, trying utf-8',
                           encoding, str(error))
            return 'utf-8', self.dict_to_string(obj_dict).encode('utf-8')
933444
def to_bytes(value):
    """"""
    if isinstance(value, unicode):
        return value.encode('utf8')
    elif not isinstance(value, str):
        return str(value)
    return value
936288
def from_dict(cls: typing.Type[T], dikt) -> T:
        """"""
        return util.deserialize_model(dikt, cls)
930419
def to_bytes(s, encoding="utf-8"):
    
    if isinstance(s, six.binary_type):
        return s
    else:
        return six.text_type(s).encode(encoding)
1321010
def decode_dict_keys(d, coding="utf-8"):
    """"""
    assert compat.PY2
    res = {}
    for k, v in d.items():  #
        if type(k) is str:
            k = k.decode(coding)
        if type(v) is dict:
            v = decode_dict_keys(v, coding)
        res[k] = v
    return res
702840
def _bytes_from_json(value, field):
    """"""
    if _not_null(value, field):
        return base64.standard_b64decode(_to_bytes(value))