Take a Python object and return it as a tuple (value, value_type), a
        blob and a one-char code for what type it is
355338
def encode(self, obj):
        
        if self._is_valid_mysql_bigint(obj):
            return obj, 'i'

        value = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
        value_type = 'p'
        if (
            self._compress_min_length
            and len(value) >= self._compress_min_length
        ):
            value = zlib.compress(value, self._compress_level)
            value_type = 'z'
        return value, value_type
85210
def _as_list(obj):
    """"""
    if obj is None:
        return None
    elif isinstance(obj, string_types):
        return [obj]
    elif isinstance(obj, tuple):
        return list(obj)
    elif not hasattr(obj, '__len__'):
        return [obj]
    else:
        return obj
906246
def value_to_python(self, value):
        
        if not isinstance(value, bytes):
            raise tldap.exceptions.ValidationError("should be a bytes")

        length = len(value) - 8
        if length % 4 != 0:
            raise tldap.exceptions.ValidationError("Invalid sid")

        length = length // 4

        array = struct.unpack('<bbbbbbbb' + 'I' * length, value)

        if array[1] != length:
            raise tldap.exceptions.ValidationError("Invalid sid")

        if array[2:7] != (0, 0, 0, 0, 0):
            raise tldap.exceptions.ValidationError("Invalid sid")

        array = ("S", ) + array[0:1] + array[7:]
        return "-".join([str(i) for i in array])
693800
def value_to_db(self, value):
        
        assert isinstance(value, six.integer_types)
        return str(value).encode("utf_8")
387745
def _numpy_to_python(obj):
    
    if isinstance(obj, dict):
        return {k: _numpy_to_python(v) for k, v in obj.items()}
    elif isinstance(obj, (list, tuple, np.ndarray)):
        return [_numpy_to_python(x) for x in obj]
    elif isinstance(obj, FormattedFeatureName):
        return obj.value
    elif isinstance(obj, _numpy_string_types):
        return six.text_type(obj)
    elif hasattr(obj, 'dtype') and np.isscalar(obj):
        if np.issubdtype(obj, np.floating):
            return float(obj)
        elif np.issubdtype(obj, np.integer):
            return int(obj)
        elif np.issubdtype(obj, np.bool_):
            return bool(obj)
    return obj
1048763
def tupleize(element, ignore_types=(str, bytes)):
    """"""
    if hasattr(element, '__iter__') and not isinstance(element, ignore_types):
        return element
    else:
        return tuple((element,))
824262
def _encode(self, obj):
        

        if self._use_hook:
            obj = self.encode_hook(obj)

        # first try simple strict checks

        _objtype = obj.__class__

        if _objtype is str:
            return self._encode_str(obj)

        if _objtype is bool:
            if obj:
                return 'true'
            else:
                return 'false'

        if _objtype is int or _objtype is float:
            return self._encode_numbers(obj)

        if _objtype is list or _objtype is tuple:
            return self._encode_list(obj)

        if obj is None:
            return 'null'

        if _objtype is dict or obj is OrderedDict:
            return self._encode_dict(obj)

        if _objtype is UUID:
            return '"' + str(obj) + '"'

        if _objtype is Decimal:
            return '"' + str(obj) + '"'

        # For all non-std types try __mm_json__ and then __mm_serialize__ before any isinstance
        # checks

        try:
            sx_json_data = obj.__mm_json__
        except AttributeError:
            pass
        else:
            try:
                data = sx_json_data()
            except NotImplementedError:
                pass
            else:
                if isinstance(data, bytes):
                    return data.decode('utf-8')
                else:
                    return self._encode_str(data, escape_quotes=False)
        try:
            sx_encoder = obj.__mm_serialize__
        except AttributeError:
            pass
        else:
            try:
                data = sx_encoder()
            except NotImplementedError:
                pass
            else:
                return self._encode(data)

        # do more in-depth class analysis

        if isinstance(obj, UUID):
            return '"' + str(obj) + '"'

        if isinstance(obj, str):
            return self._encode_str(obj)

        if isinstance(obj, (list, tuple, set, frozenset, Set)):
            return self._encode_list(obj)

        if isinstance(obj, Sequence) and not isinstance(obj, (bytes, bytearray)):
            return self._encode_list(obj)

        if isinstance(obj, (dict, OrderedDict, Mapping)):
            return self._encode_dict(obj)

        # note: number checks using isinstance should come after True/False checks
        if isinstance(obj, Number):
            return self._encode_numbers(obj)

        if isinstance(obj, (date, time)):
            return '"' + obj.isoformat() + '"'

        return self._encode(self.default(obj))
38011
def arbitrary_object_to_string(a_thing):
    """"""
    # is it None?
    if a_thing is None:
        return ''
    # is it already a string?
    if isinstance(a_thing, six.string_types):
        return a_thing
    if six.PY3 and isinstance(a_thing, six.binary_type):
        try:
            return a_thing.decode('utf-8')
        except UnicodeDecodeError:
            pass
    # does it have a to_str function?
    try:
        return a_thing.to_str()
    except (AttributeError, KeyError, TypeError):
        # AttributeError - no to_str function?
        # KeyError - DotDict has no to_str?
        # TypeError - problem converting
        # nope, no to_str function
        pass
    # is this a type proxy?
    try:
        return arbitrary_object_to_string(a_thing.a_type)
    except (AttributeError, KeyError, TypeError):
        #
        # nope, no a_type property
        pass
    # is it a built in?
    try:
        return known_mapping_type_to_str[a_thing]
    except (KeyError, TypeError):
        # nope, not a builtin
        pass
    # is it something from a loaded module?
    try:
        if a_thing.__module__ not in ('__builtin__', 'builtins', 'exceptions'):
            if a_thing.__module__ == "__main__":
                module_name = (
                    sys.modules['__main__']
                    .__file__[:-3]
                    .replace('/', '.')
                    .strip('.')
                )
            else:
                module_name = a_thing.__module__
            return "%s.%s" % (module_name, a_thing.__name__)
    except AttributeError:
        # nope, not one of these
        pass
    # maybe it has a __name__ attribute?
    try:
        return a_thing.__name__
    except AttributeError:
        # nope, not one of these
        pass
    # punt and see what happens if we just cast it to string
    return str(a_thing)
208008
def get_type(obj, **kwargs):
    """"""
    t = type(obj)

    s = extract_type(str(t))

    return 'Type: {}'.format(s)
890154
def dumps(obj, **kwargs):
    """"""

    t = type(obj)
    if obj is True:
        return u'true'
    elif obj is False:
        return u'false'
    elif obj == None:
        return u'null'
    elif t == type('') or t == type(u''):
        single = "'" in obj
        double = '"' in obj
        if single and double:
            return json.dumps(obj)
        elif single:
            return '"' + obj + '"'
        else:
            return "'" + obj + "'"
    elif t is float or t is int:
        return str(obj)
    elif t is dict:
        return u'{' + u','.join([
            _dumpkey(k) + u':' + dumps(v) for k, v in obj.items()
        ]) + '}'
    elif t is list:
        return u'[' + ','.join([dumps(el) for el in obj]) + u']'
    else:  # pragma: no cover
        return u''
142554
def _from_python_type(self, obj, field, pytype):
        """"""
        json_schema = {
            'title': field.attribute or field.name,
        }

        for key, val in TYPE_MAP[pytype].items():
            json_schema[key] = val

        if field.dump_only:
            json_schema['readonly'] = True

        if field.default is not missing:
            json_schema['default'] = field.default

        # NOTE: doubled up to maintain backwards compatibility
        metadata = field.metadata.get('metadata', {})
        metadata.update(field.metadata)

        for md_key, md_val in metadata.items():
            if md_key == 'metadata':
                continue
            json_schema[md_key] = md_val

        if isinstance(field, fields.List):
            json_schema['items'] = self._get_schema_for_field(
                obj, field.container
            )
        return json_schema
298842
def to_python(self, value):
        """"""
        if value is None or value == '':
            return {}

        if isinstance(value, six.string_types):
            res = loads(value)
        else:
            res = value

        if isinstance(res, dict):
            return JSONDict(**res)
        elif isinstance(res, list):
            return JSONList(res)

        return res
295705
def _attrs_to_tuple(obj, attrs):
    
    return tuple(getattr(obj, a.name) for a in attrs)
837054
def dumps_bytes(obj):
    
    b = dumps(obj)
    if isinstance(b, unicode):
        b = b.encode("ascii")
    return b
408107
def decompress(obj, return_type="bytes"):
    
    if isinstance(obj, binary_type):
        b = zlib.decompress(obj)
    elif isinstance(obj, string_types):
        b = zlib.decompress(base64.b64decode(obj.encode("utf-8")))
    else:
        raise TypeError("input cannot be anything other than str and bytes!")

    if return_type == "bytes":
        return b
    elif return_type == "str":
        return b.decode("utf-8")
    elif return_type == "obj":
        return pickle.loads(b)
    else:
        raise ValueError(
            "'return_type' has to be one of 'bytes', 'str' or 'obj'!")
419915
def dumpable_obj(obj):
    ''' '''

    if isinstance(obj, list):
        _return_list = []
        for item in obj:
            if isinstance(item, list):
                _return_list.append(dumpable_obj(item))
            elif isinstance(item, set):
                _return_list.append(list(item))
            elif isinstance(item, dict):
                _return_list.append(dumpable_obj(item))
            else:
                try:
                    json.dumps(item)
                    _return_list.append(item)
                except:
                    _return_list.append(str(type(item)))
        return _return_list
    elif isinstance(obj, set):
        return list(obj)
    elif isinstance(obj, dict):
        _return_obj = {}
        for key, item in obj.items():
            if isinstance(item, list):
                _return_obj[key] = dumpable_obj(item)
            elif isinstance(item, set):
                _return_obj[key] = list(item)
            elif isinstance(item, dict):
                _return_obj[key] = dumpable_obj(item)
            else:
                try:
                    json.dumps(item)
                    _return_obj[key] = item
                except:
                    _return_obj[key] = str(type(item))
        return _return_obj
    else:
        try:
            json.dumps(obj)
            return obj
        except:
            return str(type(obj))
870006
def encode(self, value):
        ""
        if isinstance(value, Token):
            return value.encoded_value
        elif isinstance(value, bytes):
            return value
        elif isinstance(value, bool):
            # special case bool since it is a subclass of int
            raise DataError("Invalid input of type: 'bool'. Convert to a "
                            "byte, string or number first.")
        elif isinstance(value, float):
            value = repr(value).encode()
        elif isinstance(value, (int, long)):
            # python 2 repr() on longs is '123L', so use str() instead
            value = str(value).encode()
        elif not isinstance(value, basestring):
            # a value we don't know how to deal with. throw an error
            typename = type(value).__name__
            raise DataError("Invalid input of type: '%s'. Convert to a "
                            "byte, string or number first." % typename)
        if isinstance(value, unicode):
            value = value.encode(self.encoding, self.encoding_errors)
        return value