method used to construct instances from query results
        this is where polymorphic deserialization occurs
333932
def _construct_instance(cls, values):
        
        # we're going to take the values, which is from the DB as a dict
        # and translate that into our local fields
        # the db_map is a db_field -> model field map
        items = values.items()
        field_dict = dict([(cls._db_map.get(k, k),v) for k,v in items])

        if cls._is_polymorphic:
            poly_key = field_dict.get(cls._polymorphic_column_name)

            if poly_key is None:
                raise PolyMorphicModelException('polymorphic key was not found in values')

            poly_base = cls if cls._is_polymorphic_base else cls._polymorphic_base

            klass = poly_base._get_model_by_polymorphic_key(poly_key)
            if klass is None:
                poly_base._discover_polymorphic_submodels()
                klass = poly_base._get_model_by_polymorphic_key(poly_key)
                if klass is None:
                    raise PolyMorphicModelException(
                        'unrecognized polymorphic key {} for class {}'.format(poly_key, poly_base.__name__)
                    )

            if not issubclass(klass, cls):
                raise PolyMorphicModelException(
                    '{} is not a subclass of {}'.format(klass.__name__, cls.__name__)
                )

            field_dict = {k: v for k, v in field_dict.items() if k in klass._columns.keys()}

        else:
            klass = cls

        instance = klass(**field_dict)
        instance._is_persisted = True
        return instance
1329072
private void _processMetadata(HashMap<String, Object> result) {
		// the collections in the result can be either an object[] or a HashSet<object>, depending on the serializer that is used
		Object methods = result.get("methods");
		Object attrs = result.get("attrs");
		Object oneways = result.get("oneways");

		if(methods instanceof Object[]) {
			Object[] methods_array = (Object[]) methods;
			this.pyroMethods = new HashSet<String>();
			for(int i=0; i<methods_array.length; ++i) {
				this.pyroMethods.add((String) methods_array[i]);
			}
		} else if(methods!=null) {
			this.pyroMethods = getSetOfStrings(methods);
		}
		if(attrs instanceof Object[]) {
			Object[] attrs_array = (Object[]) attrs;
			this.pyroAttrs = new HashSet<String>();
			for(int i=0; i<attrs_array.length; ++i) {
				this.pyroAttrs.add((String) attrs_array[i]);
			}
		} else if(attrs!=null) {
			this.pyroAttrs = getSetOfStrings(attrs);
		}
		if(oneways instanceof Object[]) {
			Object[] oneways_array = (Object[]) oneways;
			this.pyroOneway = new HashSet<String>();
			for(int i=0; i<oneways_array.length; ++i) {
				this.pyroOneway.add((String) oneways_array[i]);
			}
		} else if(oneways!=null) {
			this.pyroOneway = getSetOfStrings(oneways);
		}

		if(pyroMethods.isEmpty() && pyroAttrs.isEmpty()) {
			throw new PyroException("remote object doesn't expose any methods or attributes");
		}
	}
376167
function convertExistingQueryProps(json, builder) {
  const keys = Object.keys(json);

  for (let i = 0, l = keys.length; i < l; ++i) {
    const key = keys[i];
    const value = json[key];

    if (isQueryProp(value)) {
      json[key] = queryPropToKnexRaw(value, builder);
    }
  }

  return json;
}
1151572
def deserialize(self, value, **kwargs):
        
        kwargs.update({'trusted': kwargs.get('trusted', False)})
        if self.deserializer is not None:
            return self.deserializer(value, **kwargs)
        if value is None:
            return None
        if isinstance(value, string_types):
            return value
        if issubclass(self.instance_class, base.HasProperties):
            return self.instance_class.deserialize(value, **kwargs)
        return self.from_json(value, **kwargs)
1129263
@Override
    public <T> PagedResult<T> deserializeDataWrapper(Class<T> objectClass, java.io.InputStream inputStream) throws JSONSerializerException{
        Util.throwIfNull(objectClass, inputStream);

        PagedResult<T> rw = null;

        try {
            // Read the json input stream into a List.
            rw = OBJECT_MAPPER.readValue(inputStream,
                    OBJECT_MAPPER.getTypeFactory().constructParametrizedType(PagedResult.class, PagedResult.class, objectClass));
        } catch (JsonParseException e) {
            throw new JSONSerializerException(e);
        } catch (JsonMappingException e) {
            throw new JSONSerializerException(e);
        } catch (IOException e) {
            throw new JSONSerializerException(e);
        }

        return rw;
    }
759944
function parseMembers(params, constructor, isFinal) {
        var opts = { isFinal: !!isFinal },
            key,
            value,
            cache = {},
            unallowed;

        // Add each method metadata, verifying its signature
        if (hasOwn(params, '$statics')) {
            // Check if is an object
            if (!isObject(params.$statics)) {
                throw new Error('$statics definition of class "' + params.$name + '" must be an object.');
            }

            // Check reserved keywords
            checkKeywords(params.$statics, 'statics');

            // Check unallowed keywords
            unallowed = testKeywords(params.$statics);
            if (unallowed) {
                throw new Error('$statics ' + (isFinal ? 'inside $finals ' : '') + ' of class "' + constructor.prototype.$name + '" contains an unallowed keyword: "' + unallowed + '".');
            }

            opts.isStatic = true;

            for (key in params.$statics) {
                value = params.$statics[key];

                if (isFunction(value) && !value[$class] && !value[$interface]) {
                    addMethod(key, value, constructor, opts);
                } else {
                    addProperty(key, value, constructor, opts);
                }
            }

            delete opts.isStatic;
            delete params.$statics;
        }

        // Save certain keywords in the cache for the loop bellow to work faster
        if (hasOwn(params, '$implements')) {
            cache.$implements = params.$implements;
            delete params.$implements;
        }

        if (hasOwn(params, '$abstracts')) {
            cache.$abstracts = params.$abstracts;
            delete params.$abstracts;
        }

        for (key in params) {
            value = params[key];

            if (isFunction(value) && !value[$class] && !value[$interface]) {
                addMethod(key, value, constructor, opts);
            } else {
                addProperty(key, value, constructor, opts);
            }
        }

        // Restore from cache
        mixIn(params, cache);
    }
1103687
private static TypeSerializer<?>[] createRegisteredSubclassSerializers(
			LinkedHashSet<Class<?>> registeredSubclasses,
			ExecutionConfig executionConfig) {

		final TypeSerializer<?>[] subclassSerializers = new TypeSerializer[registeredSubclasses.size()];

		int i = 0;
		for (Class<?> registeredClass : registeredSubclasses) {
			subclassSerializers[i] = TypeExtractor.createTypeInfo(registeredClass).createSerializer(executionConfig);
			i++;
		}

		return subclassSerializers;
	}
509721
private Collection<IndexedInstance> getInstancesForVertex(Map<String, AttributeValueMap> map, AtlasVertex foundVertex) {

        //loop through the unique attributes.  For each attribute, check to see if the vertex property that
        //corresponds to that attribute has a value from one or more of the instances that were passed in.

        for(Map.Entry<String, AttributeValueMap> entry : map.entrySet()) {

            String propertyName = entry.getKey();
            AttributeValueMap valueMap = entry.getValue();

            Object vertexValue = foundVertex.getProperty(propertyName, Object.class);

            Collection<IndexedInstance> instances = valueMap.get(vertexValue);
            if(instances != null && instances.size() > 0) {
                //return first match.  Let the underling graph determine if this is a problem
                //(i.e. if the other unique attributes change be changed safely to match what
                //the user requested).
                return instances;
            }
            //try another attribute
        }
        return Collections.emptyList();
    }
234615
def deserialize_object(self, attr, **kwargs):
        
        if attr is None:
            return None
        if isinstance(attr, ET.Element):
            # Do no recurse on XML, just return the tree as-is
            return attr
        if isinstance(attr, basestring):
            return self.deserialize_basic(attr, 'str')
        obj_type = type(attr)
        if obj_type in self.basic_types:
            return self.deserialize_basic(attr, self.basic_types[obj_type])
        if obj_type is _long_type:
            return self.deserialize_long(attr)

        if obj_type == dict:
            deserialized = {}
            for key, value in attr.items():
                try:
                    deserialized[key] = self.deserialize_object(
                        value, **kwargs)
                except ValueError:
                    deserialized[key] = None
            return deserialized

        if obj_type == list:
            deserialized = []
            for obj in attr:
                try:
                    deserialized.append(self.deserialize_object(
                        obj, **kwargs))
                except ValueError:
                    pass
            return deserialized

        else:
            error = "Cannot deserialize generic object with type: "
            raise TypeError(error + str(obj_type))
314501
def process(self, obj, parent=None, parent_key=None, depth=0):
        
        if isinstance(obj, list):
            for key, o in enumerate(obj):
                # traverse into lists of objects
                self.process(o, parent=obj, parent_key=key, depth=depth)
        elif isinstance(obj, dict):
            dynamic = self.is_dynamic(obj)
            returned = isinstance(obj, ReturnDict)
            if dynamic or returned:
                # recursively check all fields
                for key, o in six.iteritems(obj):
                    if isinstance(o, list) or isinstance(o, dict):
                        # lists or dicts indicate a relation
                        self.process(
                            o,
                            parent=obj,
                            parent_key=key,
                            depth=depth +
                            1
                        )

                if not dynamic or getattr(obj, 'embed', False):
                    return

                serializer = obj.serializer
                name = serializer.get_plural_name()
                instance = getattr(obj, 'instance', serializer.instance)
                instance_pk = instance.pk if instance else None
                pk = getattr(obj, 'pk_value', instance_pk) or instance_pk

                # For polymorphic relations, `pk` can be a dict, so use the
                # string representation (dict isn't hashable).
                pk_key = repr(pk)

                # sideloading
                seen = True
                # if this object has not yet been seen
                if pk_key not in self.seen[name]:
                    seen = False
                    self.seen[name].add(pk_key)

                # prevent sideloading the primary objects
                if depth == 0:
                    return

                # TODO: spec out the exact behavior for secondary instances of
                # the primary resource

                # if the primary resource is embedded, add it to a prefixed key
                if name == self.plural_name:
                    name = '%s%s' % (
                        settings.ADDITIONAL_PRIMARY_RESOURCE_PREFIX,
                        name
                    )

                if not seen:
                    # allocate a top-level key in the data for this resource
                    # type
                    if name not in self.data:
                        self.data[name] = []

                    # move the object into a new top-level bucket
                    # and mark it as seen
                    self.data[name].append(obj)
                else:
                    # obj sideloaded, but maybe with other fields
                    for o in self.data.get(name, []):
                        if o.instance.pk == pk:
                            o.update(obj)
                            break

                # replace the object with a reference
                if parent is not None and parent_key is not None:
                    parent[parent_key] = pk
451440
@Override
    public org.fcrepo.server.types.gen.FieldSearchResult findObjects(org.fcrepo.server.types.gen.ArrayOfString resultFields,
                                                                     java.math.BigInteger maxResults,
                                                                     org.fcrepo.server.types.gen.FieldSearchQuery query) {
        MessageContext ctx = context.getMessageContext();
        Context context = ReadOnlyContext.getSoapContext(ctx);
        assertInitialized();
        try {
            String[] resultFieldsArray =
                    resultFields.getItem().toArray(EMPTY_STRING_ARRAY);

            org.fcrepo.server.search.FieldSearchResult result =
                    m_access.findObjects(context,
                                         resultFieldsArray,
                                         maxResults.intValue(),
                                         TypeUtility
                                                 .convertGenFieldSearchQueryToFieldSearchQuery(query));
            return TypeUtility
                    .convertFieldSearchResultToGenFieldSearchResult(result);
        } catch (Throwable th) {
            LOG.error("Error finding objects", th);
            throw CXFUtility.getFault(th);
        }
    }
206614
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
      Hashtable<?, ?> environment) throws Exception {
    Reference ref = (Reference) obj;
    String className = ref.getClassName();
    // Old names are here for those who still use them
    if (className.equals("org.postgresql.ds.PGSimpleDataSource")
        || className.equals("org.postgresql.jdbc2.optional.SimpleDataSource")
        || className.equals("org.postgresql.jdbc3.Jdbc3SimpleDataSource")) {
      return loadSimpleDataSource(ref);
    } else if (className.equals("org.postgresql.ds.PGConnectionPoolDataSource")
        || className.equals("org.postgresql.jdbc2.optional.ConnectionPool")
        || className.equals("org.postgresql.jdbc3.Jdbc3ConnectionPool")) {
      return loadConnectionPool(ref);
    } else if (className.equals("org.postgresql.ds.PGPoolingDataSource")
        || className.equals("org.postgresql.jdbc2.optional.PoolingDataSource")
        || className.equals("org.postgresql.jdbc3.Jdbc3PoolingDataSource")) {
      return loadPoolingDataSource(ref);
    } else {
      return null;
    }
  }
487886
Type instantiatePolymorphicSignatureInstance(Env<AttrContext> env,
                                            MethodSymbol spMethod,  // sig. poly. method or null if none
                                            Resolve.MethodResolutionContext resolveContext,
                                            List<Type> argtypes) {
        final Type restype;

        //The return type for a polymorphic signature call is computed from
        //the enclosing tree E, as follows: if E is a cast, then use the
        //target type of the cast expression as a return type; if E is an
        //expression statement, the return type is 'void' - otherwise the
        //return type is simply 'Object'. A correctness check ensures that
        //env.next refers to the lexically enclosing environment in which
        //the polymorphic signature call environment is nested.

        switch (env.next.tree.getTag()) {
            case TYPECAST:
                JCTypeCast castTree = (JCTypeCast)env.next.tree;
                restype = (TreeInfo.skipParens(castTree.expr) == env.tree) ?
                    castTree.clazz.type :
                    syms.objectType;
                break;
            case EXEC:
                JCTree.JCExpressionStatement execTree =
                        (JCTree.JCExpressionStatement)env.next.tree;
                restype = (TreeInfo.skipParens(execTree.expr) == env.tree) ?
                    syms.voidType :
                    syms.objectType;
                break;
            default:
                restype = syms.objectType;
        }

        List<Type> paramtypes = Type.map(argtypes, new ImplicitArgType(spMethod, resolveContext.step));
        List<Type> exType = spMethod != null ?
            spMethod.getThrownTypes() :
            List.of(syms.throwableType); // make it throw all exceptions

        MethodType mtype = new MethodType(paramtypes,
                                          restype,
                                          exType,
                                          syms.methodClass);
        return mtype;
    }
809713
private <T, Y> TypedQuery<T> createTypedQueryIn(Class<T> entityCls,
            SingularAttribute<T, Y> attribute, List<Y> values) {
        EntityManager entityManager = this.entityManagerProvider.get();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<T> criteriaQuery = builder.createQuery(entityCls);
        Root<T> root = criteriaQuery.from(entityCls);
        Path<Y> path = root.get(attribute);
        CriteriaBuilder.In<Y> in = builder.in(path);
        if (values != null) {
            for (Y val : values) {
                in.value(val);
            }
        }
        return entityManager.createQuery(criteriaQuery.where(in));
    }
814860
private Flowable<List<ServiceInstance>> convertInstancesResulttoServiceInstances(ListInstancesResult instancesResult) {
        List<ServiceInstance> serviceInstances = new ArrayList<>();
        for (InstanceSummary instanceSummary : instancesResult.getInstances()) {
            try {
                String uri = "http://" + instanceSummary.getAttributes().get("URI");
                ServiceInstance serviceInstance = new EC2ServiceInstance(instanceSummary.getId(), new URI(uri)).metadata(instanceSummary.getAttributes()).build();
                serviceInstances.add(serviceInstance);
            } catch (URISyntaxException e) {
                return Flowable.error(e);
            }
        }
        return Flowable.just(serviceInstances);
    }
199242
private <T> ResultIterable<T> findByExample(Class<?> type, Map<PrimitivePropertyMethodMetadata<PropertyMetadata>, Object> entity) {
        sessionContext.getCacheSynchronizationService().flush();
        EntityTypeMetadata<EntityMetadata> entityTypeMetadata = sessionContext.getMetadataProvider().getEntityMetadata(type);
        EntityDiscriminator entityDiscriminator = entityTypeMetadata.getDatastoreMetadata().getDiscriminator();
        if (entityDiscriminator == null) {
            throw new XOException("Type " + type.getName() + " has no discriminator (i.e. cannot be identified in datastore).");
        }
        ResultIterator<Entity> iterator = sessionContext.getDatastoreSession().getDatastoreEntityManager().findEntity(entityTypeMetadata, entityDiscriminator,
                entity);
        AbstractInstanceManager<EntityId, Entity> entityInstanceManager = sessionContext.getEntityInstanceManager();
        ResultIterator<T> resultIterator = new ResultIterator<T>() {

            @Override
            public boolean hasNext() {
                return iterator.hasNext();
            }

            @Override
            public T next() {
                Entity entity = iterator.next();
                return entityInstanceManager.readInstance(entity);
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("Cannot remove instance.");
            }

            @Override
            public void close() {
                iterator.close();
            }
        };
        XOTransaction xoTransaction = sessionContext.getXOTransaction();
        final ResultIterator<T> transactionalIterator = xoTransaction != null ? new TransactionalResultIterator<>(resultIterator, xoTransaction)
                : resultIterator;
        return sessionContext.getInterceptorFactory().addInterceptor(new AbstractResultIterable<T>() {
            @Override
            public ResultIterator<T> iterator() {
                return transactionalIterator;
            }
        }, ResultIterable.class);
    }
683752
def __deserialize(self, data, klass):
        
        if data is None:
            return None

        if type(klass) == str:
            from tradenity.resources.paging import Page
            if klass.startswith('page['):
                sub_kls = re.match('page\[(.*)\]', klass).group(1)
                return Page([self.__deserialize(sub_data, sub_kls)
                            for sub_data in data["items"]], self.__deserialize_page_info(data["__meta"]))
            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 six.iteritems(data)}

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

        if klass in self.PRIMITIVE_TYPES:
            return self.__deserialize_primitive(data, klass)
        elif klass == object:
            return self.__deserialize_object(data)
        elif klass == datetime.date:
            return self.__deserialize_date(data)
        elif klass == datetime.datetime:
            return self.__deserialize_datatime(data)
        else:
            return self.__deserialize_model(data, klass)