Recursive function to generate a list of EDBObjects out of a model object.
322371
private String convertSubModel(OpenEngSBModel model, List<EDBObject> objects, ConnectorInformation info) {
        String contextId = ContextHolder.get().getCurrentContextId();
        String oid = ModelWrapper.wrap(model).getCompleteModelOID();
        EDBObject object = new EDBObject(oid);
        try {
            fillEDBObjectWithEngineeringObjectInformation(object, model);
        } catch (IllegalAccessException e) {
            LOGGER.warn("Unable to fill completely the EngineeringObjectInformation into the EDBObject", e);
            throw new EKBException("Unable to fill completely the EngineeringObjectInformation into the EDBObject", e);
        }
        for (OpenEngSBModelEntry entry : model.toOpenEngSBModelEntries()) {
            if (entry.getValue() == null) {
                continue;
            } else if (entry.getType().equals(FileWrapper.class)) {
                try {
                    FileWrapper wrapper = (FileWrapper) entry.getValue();
                    String content = Base64.encodeBase64String(wrapper.getContent());
                    object.putEDBObjectEntry(entry.getKey(), content, String.class);
                    object.putEDBObjectEntry(entry.getKey() + FILEWRAPPER_FILENAME_SUFFIX,
                        wrapper.getFilename(), String.class);
                } catch (IOException e) {
                    LOGGER.error(e.getMessage());
                }
            } else if (OpenEngSBModel.class.isAssignableFrom(entry.getType())) {
                OpenEngSBModel temp = (OpenEngSBModel) entry.getValue();
                String subOid = convertSubModel(temp, objects, info);
                object.putEDBObjectEntry(entry.getKey(), subOid, String.class);
            } else if (List.class.isAssignableFrom(entry.getType())) {
                List<?> list = (List<?>) entry.getValue();
                if (list == null || list.size() == 0) {
                    continue;
                }
                Boolean modelItems = null;
                for (int i = 0; i < list.size(); i++) {
                    Object item = list.get(i);
                    if (modelItems == null) {
                        modelItems = OpenEngSBModel.class.isAssignableFrom(item.getClass());
                    }
                    if (modelItems) {
                        item = convertSubModel((OpenEngSBModel) item, objects, info);
                    }
                    String entryName = getEntryNameForList(entry.getKey(), i);
                    object.putEDBObjectEntry(entryName, item, item.getClass());
                }
            } else if (entry.getType().isArray()) {
                Object[] array = (Object[]) entry.getValue();
                if (array == null || array.length == 0) {
                    continue;
                }
                Boolean modelItems = null;
                for (int i = 0; i < array.length; i++) {
                    Object item = array[i];
                    if (modelItems == null) {
                        modelItems = OpenEngSBModel.class.isAssignableFrom(item.getClass());
                    }
                    if (modelItems) {
                        item = convertSubModel((OpenEngSBModel) item, objects, info);
                    }
                    String entryName = getEntryNameForList(entry.getKey(), i);
                    object.putEDBObjectEntry(entryName, item, item.getClass());
                }
            } else if (Map.class.isAssignableFrom(entry.getType())) {
                Map<?, ?> map = (Map<?, ?>) entry.getValue();
                if (map == null || map.size() == 0) {
                    continue;
                }
                Boolean keyIsModel = null;
                Boolean valueIsModel = null;
                int i = 0;
                for (Map.Entry<?, ?> ent : map.entrySet()) {
                    if (keyIsModel == null) {
                        keyIsModel = OpenEngSBModel.class.isAssignableFrom(ent.getKey().getClass());
                    }
                    if (valueIsModel == null) {
                        valueIsModel = OpenEngSBModel.class.isAssignableFrom(ent.getValue().getClass());
                    }
                    Object key = ent.getKey();
                    Object value = ent.getValue();
                    if (keyIsModel) {
                        key = convertSubModel((OpenEngSBModel) key, objects, info);
                    }
                    if (valueIsModel) {
                        value = convertSubModel((OpenEngSBModel) value, objects, info);
                    }
                    object.putEDBObjectEntry(getEntryNameForMapKey(entry.getKey(), i), key);
                    object.putEDBObjectEntry(getEntryNameForMapValue(entry.getKey(), i), value);
                    i++;
                }
            } else {
                object.putEDBObjectEntry(entry.getKey(), entry.getValue(), entry.getType());
            }
        }
        object.putEDBObjectEntry(EDBConstants.MODEL_TYPE, model.retrieveModelName());
        object.putEDBObjectEntry(EDBConstants.MODEL_TYPE_VERSION, model.retrieveModelVersion());
        object.putEDBObjectEntry("domainId", info.getDomainId());
        object.putEDBObjectEntry("connectorId", info.getConnectorId());
        object.putEDBObjectEntry("instanceId", info.getInstanceId());
        object.putEDBObjectEntry("contextId", contextId);
        objects.add(object);
        return oid;
    }
604153
def model_to_dict(instance, **options):
    ""

    options = _defaults(options)
    attrs = {}

    if options['prehook']:
        if isinstance(options['prehook'], collections.Callable):
            instance = options['prehook'](instance)
            if instance is None:
                return attrs

    # Items in the `fields` list are the output aliases, not the raw
    # accessors (field, method, property names)
    for alias in options['fields']:

        # Get the accessor for the object
        accessor = options['aliases'].get(alias, alias)

        # Create the key that will be used in the output dict
        key = options['prefix'] + alias

        # Optionally camelcase the key
        if options['camelcase']:
            key = convert_to_camel(key)

        # Get the field value. Use the mapped value to the actually property or
        # method name. `value` may be a number of things, so the various types
        # are checked below.
        value = get_field_value(instance, accessor,
                                allow_missing=options['allow_missing'])

        # Related objects, perform some checks on their options
        if isinstance(value, (models.Model, QuerySet)):
            _options = _defaults(options['related'].get(accessor, {}))

            # If the `prefix` follows the below template, generate the
            # `prefix` for the related object
            if '%(accessor)s' in _options['prefix']:
                _options['prefix'] = _options['prefix'] % {'accessor': alias}

            if isinstance(value, models.Model):
                if len(_options['fields']) == 1 and _options['flat'] \
                        and not _options['merge']:
                    value = list(serialize(value, **_options).values())[0]
                else:
                    # Recurse, get the dict representation
                    _attrs = serialize(value, **_options)

                    # Check if this object should be merged into the parent,
                    # otherwise nest it under the accessor name
                    if _options['merge']:
                        attrs.update(_attrs)
                        continue

                    value = _attrs
            else:
                value = serialize(value, **_options)

        attrs[key] = value

    # Apply post-hook to serialized attributes
    if options['posthook']:
        attrs = options['posthook'](instance, attrs)

    return attrs
1093556
def dump_database_object(obj: T, fieldlist: Iterable[str]) -> None:
    """"""
    log.info(_LINE_EQUALS)
    log.info("DUMP OF: {}", obj)
    for f in fieldlist:
        log.info(u"{f}: {v}", f=f, v=getattr(obj, f))
    log.info(_LINE_EQUALS)
1207120
def objects_to_root(objects: List) -> Root:
    

    def _to_tree(objs: Iterable) -> Dict:
        """
        Build a tree structure from a flat list of objects.

        :param objs: The raw iterable of S3 `ObjectSummary`s, as returned by a
                     bucket listing.
        :return: The listing as a nested dictionary where keys are directory
                 and file names. The values of directories will in turn be a
                 dict. The values of keys representing files will be the
                 `ObjectSummary` instance.
        """
        path_tree = {}
        for obj in objs:
            is_dir = obj.key.endswith('/')
            chunks = [chunk for chunk in obj.key.split('/') if chunk]
            chunk_count = len(chunks)
            tmp = path_tree
            for i, chunk in enumerate(chunks):
                is_last_chunk = i == chunk_count - 1

                if is_last_chunk and not is_dir:
                    tmp[chunk] = obj
                else:
                    # must be a directory
                    if chunk not in tmp:
                        # it doesn't exist - create it
                        tmp[chunk] = {}
                    tmp = tmp[chunk]
        return path_tree

    def _to_entity(key: str, value: Union[Dict, Any]) -> Entity:
        """
        Turn a nested dictionary representing an S3 bucket into the correct
        `Entity` object.

        :param key: The name of the entity.
        :param value: If the entity is a directory, the nested dict
                      representing its contents. Otherwise, the `ObjectSummary`
                      instance representing the file.
        :return: The entity representing the entity name and value pair.
        """
        if isinstance(value, dict):
            return Directory(
                key,
                {key_: _to_entity(key_, value_)
                 for key_, value_ in value.items()})

        return File(pathlib.PurePath(value.key).name, value.size,
                    value.e_tag.strip('"'))

    tree = _to_tree(objects)
    return Root({pathlib.PurePath(key).name: _to_entity(key, value)
                 for key, value in tree.items()})
708479
def ParseObjs(self, objs, type_names):
    """"""
    for obj in objs:
      for type_name in self._RDFTypes(type_names):
        if isinstance(obj, self._GetClass(type_name)):
          yield obj
980419
def model_classes(classes = Map.model_classes)
      nested_hash = classes.each_with_object({}) do |klass, hash|
        hash[klass] = Node.new(klass)
      end
      nested_hash.each do |klass, node|
        node.parent = parent = nested_hash[klass.superclass]
        parent.children << node if parent
      end
      nested_hash.values.select { |v| v.parent.nil? }
    end
1133883
def find_model(object):
        

        models = []
        for model in GraphModel._GraphModel__models_instances.itervalues():
            for node in foundations.walkers.nodes_walker(model.root_node):
                if node is object:
                    models.append(model)

                for attribute in node.get_attributes():
                    if attribute is object:
                        models.append(model)
        return models
257326
def to_class_objects(docs, opts)
      classes = docs.map {|d| Class.new(d) }
      Relations.new(classes, opts.external)
    end
581853
def model_to_list(model_class, filter_dict=None, order_by_list=None,
                  select_related_fields=None, q_filter=None,
                  values=None,
                  to_json_method='to_json'):
    
    return model_to_page_list(model_class, page_num=None,
                              filter_dict=filter_dict, order_by_list=order_by_list,
                              select_related_fields=select_related_fields,
                              q_filter=q_filter, values=values,
                              to_json_method=to_json_method)
1137720
def make_list(obj, cast=True):
    
    if isinstance(obj, list):
        return list(obj)
    elif is_lazy_iterable(obj):
        return list(obj)
    elif isinstance(obj, (tuple, set)) and cast:
        return list(obj)
    else:
        return [obj]
254606
def _get_hierarchy(cls):
    
    bases = []
    for base in cls.mro():  # pragma: no branch
      if hasattr(base, '_get_hierarchy'):
        bases.append(base)
    del bases[-1]  # Delete PolyModel itself
    bases.reverse()
    return bases
445232
def generate_modelform(self):
        """"""

        model_class = self.get_model_class
        excludes = self.modelform_excludes if self.modelform_excludes else []
        _ObjectForm = modelform_factory(model_class, exclude=excludes)
        return _ObjectForm
179151
def _get_custom_models(models):
    """"""
    if models is None:
        models = Model.model_class_reverse_map.values()

    custom_models = OrderedDict()
    for cls in models:
        impl = getattr(cls, "__implementation__", None)

        if impl is not None:
            model = CustomModel(cls)
            custom_models[model.full_name] = model

    if not custom_models:
        return None
    return custom_models
1122098
def get_translatable_children(self, obj):
        
        collector = NestedObjects(using='default')
        collector.collect([obj])
        object_list = collector.nested()
        items = self.get_elements(object_list)
        # avoid first object because it's the main object
        return items[1:]
199938
def _list_model(self, model_cls: Type[X]) -> List[X]:
        """"""
        return self.session.query(model_cls).all()
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
1030873
private ModelDescription getDescriptionFromObject(EDBObject obj) {
        String modelName = obj.getString(EDBConstants.MODEL_TYPE);
        String modelVersion = obj.getString(EDBConstants.MODEL_TYPE_VERSION);
        if (modelName == null || modelVersion == null) {
            throw new IllegalArgumentException("The object " + obj.getOID() + " contains no model information");
        }
        return new ModelDescription(modelName, modelVersion);
    }