Deserialize a dict obj to a BioCCollection object
507483
def parse_collection(obj: dict) -> BioCCollection:
    """"""
    collection = BioCCollection()
    collection.source = obj['source']
    collection.date = obj['date']
    collection.key = obj['key']
    collection.infons = obj['infons']
    for doc in obj['documents']:
        collection.add_document(parse_doc(doc))
    return collection
993301
def Deserializer(stream_or_string, **options):
    

    geometry_field = options.get("geometry_field", "geom")

    def FeatureToPython(dictobj):
        properties = dictobj['properties']
        model_name = options.get("model_name") or properties.pop('model')
        # Deserialize concrete fields only (bypass dynamic properties)
        model = _get_model(model_name)
        field_names = [f.name for f in model._meta.fields]
        fields = {}
        for k, v in iteritems(properties):
            if k in field_names:
                fields[k] = v
        obj = {
            "model": model_name,
            "pk": dictobj.get('id') or properties.get('id'),
            "fields": fields
        }
        if isinstance(model._meta.get_field(geometry_field), GeoJSONField):
            obj['fields'][geometry_field] = dictobj['geometry']
        else:
            shape = GEOSGeometry(json.dumps(dictobj['geometry']))
            obj['fields'][geometry_field] = shape.wkt
        return obj

    if isinstance(stream_or_string, string_types):
        stream = StringIO(stream_or_string)
    else:
        stream = stream_or_string
    try:
        collection = json.load(stream)
        objects = [FeatureToPython(f) for f in collection['features']]
        for obj in PythonDeserializer(objects, **options):
            yield obj
    except GeneratorExit:
        raise
    except Exception as e:
        # Map to deserializer error
        raise DeserializationError(repr(e))
483779
def dict_to_ddb(item):
    # type: (Dict[str, Any]) -> Dict[str, Any]
    # TODO: narrow these types down
    
    serializer = TypeSerializer()
    return {key: serializer.serialize(value) for key, value in item.items()}
897258
def json_class_decoder_hook(d: Dict) -> Any:
    
    if TYPE_LABEL in d:
        typename = d.get(TYPE_LABEL)
        if typename in TYPE_MAP:
            if DEBUG:
                log.debug("Deserializing: {!r}", d)
            d.pop(TYPE_LABEL)
            descriptor = TYPE_MAP[typename]
            obj = descriptor.to_obj(d)
            if DEBUG:
                log.debug("... to: {!r}", obj)
            return obj
    return d
85911
def decodes(self, s: str) -> BioCCollection:
        
        tree = etree.parse(io.BytesIO(bytes(s, encoding='UTF-8')))
        collection = self.__parse_collection(tree.getroot())
        collection.encoding = tree.docinfo.encoding
        collection.standalone = tree.docinfo.standalone
        collection.version = tree.docinfo.xml_version
        return collection
462223
def to_dict(obj):
    
    if isinstance(obj, dict):
        return obj
    elif hasattr(obj, "to_dict"):
        return obj.to_dict()
    try:
        return simple_object_to_dict(obj)
    except:
        raise ValueError(
            "Cannot convert %s : %s to dictionary" % (
                obj, type(obj)))
828199
def deserialize_instance(model, data={}):
    ""
    ret = model()
    for k, v in data.items():
        if v is not None:
            try:
                f = model._meta.get_field(k)
                if isinstance(f, DateTimeField):
                    v = dateparse.parse_datetime(v)
                elif isinstance(f, TimeField):
                    v = dateparse.parse_time(v)
                elif isinstance(f, DateField):
                    v = dateparse.parse_date(v)
            except FieldDoesNotExist:
                pass
        setattr(ret, k, v)
    return ret
678205
def __deserialize(self, data, klass):
        
        if data is None:
            return None

        if type(klass) == str:
            if klass.startswith('list['):
                sub_kls = re.match('list\[(.*)\]', klass).group(1)
                return [self.__deserialize(sub_data, sub_kls)
                        for sub_data in data]

            if klass.startswith('dict('):
                sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2)
                return {k: self.__deserialize(v, sub_kls)
                        for k, v in iteritems(data)}

            # convert str to class
            if klass in self.NATIVE_TYPES_MAPPING:
                klass = self.NATIVE_TYPES_MAPPING[klass]
            else:
                klass = getattr(models, klass)

        if klass in self.PRIMITIVE_TYPES:
            return self.__deserialize_primitive(data, klass)
        elif klass == object:
            return self.__deserialize_object(data)
        elif klass == date:
            return self.__deserialize_date(data)
        elif klass == datetime:
            return self.__deserialize_datatime(data)
        else:
            return self.__deserialize_model(data, klass)
834497
def row_to_obj(self, row, cur):
        """"""
        obj = tornado.util.ObjectDict()
        for val, desc in zip(row, cur.description):
            obj[desc.name] = val
        return obj
340728
def to_dict(cls, obj):
        '''
        '''
        return {
            k: getattr(obj, k)
            for k in dir(obj)
            if cls.serialisable(k, obj)
        }
1059406
def rec_dict_to_numpy_dict(obj_dict):
    
    if type(obj_dict) == dict:
        return {key: rec_dict_to_numpy_dict(value) if value is not None else None for key, value in obj_dict.items()}
    elif obj_dict is None:
        return None
    else:
        return np.asarray(obj_dict)
813197
def _audience_condition_deserializer(obj_dict):
  
  return [
    obj_dict.get('name'),
    obj_dict.get('value'),
    obj_dict.get('type'),
    obj_dict.get('match')
  ]
509100
def from_dict(cls, d):
        
        def _node(obj):
            return Node(
                obj.get('nodeid'),
                Pred.surface_or_abstract(obj.get('predicate')),
                sortinfo=obj.get('sortinfo'),
                lnk=_lnk(obj.get('lnk')),
                surface=obj.get('surface'),
                base=obj.get('base'),
                carg=obj.get('carg')
            )
        def _link(obj):
            return Link(obj.get('from'), obj.get('to'),
                        obj.get('rargname'), obj.get('post'))
        def _lnk(o):
            return None if o is None else Lnk.charspan(o['from'], o['to'])
        return cls(
            nodes=[_node(n) for n in d.get('nodes', [])],
            links=[_link(l) for l in d.get('links', [])],
            lnk=_lnk(d.get('lnk')),
            surface=d.get('surface'),
            identifier=d.get('identifier')
        )
331296
def object_as_dict(obj):
    
    return {c.key: getattr(obj, c.key)
            for c in inspect(obj).mapper.column_attrs}
120840
def convert(self, obj):
        
        if self.pristine_if_invalid:
            raise NotImplementedError('pristine_if_invalid option is not supported yet')

        nex = get_nexml_el(obj)
        assert nex
        self._recursive_convert_dict(nex)
        # pluralization simplifications in hbf:
        # convert dicts to lists for the primary datastructures...
        self._dict_to_list_of_dicts(nex, 'otus')
        self._dict_to_list_of_dicts(nex, 'otus', 'otu')
        self._dict_to_list_of_dicts(nex, 'trees')
        self._dict_to_list_of_dicts(nex, 'trees', 'tree')
        self._dict_to_list_of_dicts(nex, 'trees', 'tree', 'node')
        self._dict_to_list_of_dicts(nex, 'trees', 'tree', 'edge')
        if self._add_tree_xsi_type:
            for tb in nex.get('trees', []):
                for t in tb.get('tree', []):
                    t.setdefault('@xsi:type', 'nex:FloatTree')
        nex['@nexml2json'] = str(DIRECT_HONEY_BADGERFISH)
        return obj
665611
def _bson_to_dict(data, opts):
    """"""
    try:
        obj_size = _UNPACK_INT(data[:4])[0]
    except struct.error as exc:
        raise InvalidBSON(str(exc))
    if obj_size != len(data):
        raise InvalidBSON("invalid object size")
    if data[obj_size - 1:obj_size] != b"\x00":
        raise InvalidBSON("bad eoo")
    try:
        return _elements_to_dict(data, 4, obj_size - 1, opts)
    except InvalidBSON:
        raise
    except Exception:
        # Change exception type to InvalidBSON but preserve traceback.
        _, exc_value, exc_tb = sys.exc_info()
        reraise(InvalidBSON, exc_value, exc_tb)
637899
def _to_json_type(obj, classkey=None):
    
    if isinstance(obj, dict):
        data = {}
        for (k, v) in obj.items():
            data[k] = _to_json_type(v, classkey)
        return data
    elif hasattr(obj, "_ast"):
        return _to_json_type(obj._ast())
    elif hasattr(obj, "__iter__"):
        return [_to_json_type(v, classkey) for v in obj]
    elif hasattr(obj, "__dict__"):
        data = dict([
            (key, _to_json_type(value, classkey))
            for key, value in obj.__dict__.iteritems()
            if not callable(value) and not key.startswith('_')
        ])
        if classkey is not None and hasattr(obj, "__class__"):
            data[classkey] = obj.__class__.__name__
        return data
    else:
        return obj