use will duplicate a new Model class and bind ec
        
        ec is Engine name or Sesstion object
6134
def use(cls, ec):
        
        
        if isinstance(ec, (str, unicode)):
            m = get_model(cls._alias, ec, signal=False)
        else:
            m = cls._use(ec)
        return m
749407
function createInstances(seqObj, models, config, done) {
    Object.keys(models).forEach((key) => {
      let modelObj = models[key],
        attributes = {},
        options = thorin.util.extend({}, modelObj.options);
      modelObj.privateAttributes = [];
      // map the attributes
      Object.keys(modelObj.fields).forEach((fieldName) => {
        let fieldOpt = modelObj.fields[fieldName];
        if (modelObj.getters[fieldName]) {
          fieldOpt.get = modelObj.getters[fieldName];
        }
        if (modelObj.setters[fieldName]) {
          fieldOpt.set = modelObj.setters[fieldName];
        }
        if (fieldOpt.private) {
          modelObj.privateAttributes.push(fieldName);
        }
        attributes[fieldName] = fieldOpt;
      });
      if (options.createdAt === true) options.createdAt = 'created_at';
      if (options.updatedAt === true) {
        options.updatedAt = 'updated_at';
        if (!attributes[options.updatedAt]) {
          attributes[options.updatedAt] = {
            defaultValue: null,
            allowNull: true,
            type: sequelize.DATE
          }
        }
      }
      if (options.deletedAt === true) {
        options.deletedAt = 'deleted_at';
        if (!attributes[options.deletedAt]) {
          attributes[options.deletedAt] = {
            defaultValue: null,
            allowNull: true,
            type: sequelize.DATE
          }
        }
      }
      // create the inner options.
      options.underscored = true;
      options.charset = config.options.charset || 'utf8';
      options.collate = config.options.collate || 'utf8_general_ci';
      options.tableName = modelObj.tableName;
      options.indexes = modelObj.indexes;
      options.instanceMethods = modelObj.methods;
      options.classMethods = modelObj.statics;
      options.hooks = modelObj.hooks;
      options.validate = {};
      let validatorId = 0;
      // set validations
      modelObj.validations.forEach((item) => {
        if (item.name) { // we have a field validator.
          if (!attributes[item.name]) {
            console.warn('Thorin.sql: model ' + key + " does not have field " + item.name + ' for validator.');
            return;
          }
          if (!attributes[item.name].validate) attributes[item.name].validate = {};
          attributes[item.name].validate['validate' + item.name + validatorId] = item.fn;
          validatorId++;
          return;
        }
        // we have a model validator.
        options.validate['thorinValidate' + validatorId] = item.fn;
        validatorId++;
      });

      // wrap the toJSON function to exclude private fields.
      function ToJSON(jsonName) {
        if (jsonName === 'result') jsonName = 'default';
        let args = Array.prototype.slice.call(arguments);
        if (typeof jsonName === 'undefined') {
          jsonName = 'default';
        } else if (typeof jsonName === 'string') {
          args.splice(0, 1);  //remove the name.
        }
        let jsonFn = modelObj.jsons[jsonName],
          result = this.dataValues;
        if (typeof jsonFn === 'undefined' && jsonName !== 'default') { // silent fallback
          if (typeof modelObj.jsons['default'] === 'function') {
            result = modelObj.jsons['default'].apply(this, args);
          }
        } else {
          if (typeof modelObj.jsons[jsonName] === 'function') {
            result = modelObj.jsons[jsonName].apply(this, args);
          } else {
            result = this.dataValues;
          }
        }
        if (result === this) {
          result = this.dataValues;
        }
        if (typeof result === 'object' && result != null) {
          for (let i = 0; i < modelObj.privateAttributes.length; i++) {
            if (typeof result[modelObj.privateAttributes[i]] !== 'undefined') {
              delete result[modelObj.privateAttributes[i]];
            }
          }
        }
        return result;
      }

      options.instanceMethods['toJSON'] = ToJSON;
      // we do a synonym to .json()
      options.instanceMethods['json'] = ToJSON;

      // Check model prefix
      if (typeof modelObj.prefix === 'string' && typeof options.tableName === 'string') {
        options.tableName = modelObj.prefix + options.tableName;
      }
      var modelInstance;
      try {
        modelInstance = seqObj.define(modelObj.code, attributes, options);
      } catch (e) {
        console.error('Thorin.sql: could not create sequelize schema for: ' + modelObj.code + '\n', e.stack);
        return;
      }
      if (typeof attributes['id'] === 'undefined') {
        if (modelObj.options.primaryKey === false) {
          modelInstance.removeAttribute('id');
        }
      }
      modelObj.setInstance(modelInstance);
    });
    done();
  }
934758
@Override
	protected void fixInstanceClass(EClassifier eClassifier) {
		if (eClassifier.getInstanceClassName() == null) {
			eClassifier.setInstanceClassName("org.bimserver.models.geometry." + eClassifier.getName());
			setGeneratedClassName(eClassifier);
		}
	}
841489
function AdaptationEngine(node) {
  this.node = node;
  this.modelObjMapper = new ModelObjectMapper();
  const factory = new kevoree.factory.DefaultKevoreeFactory();
  this.compare = factory.createModelCompare();
  this.alreadyProcessedTraces = {};
  this.targetModel = null;
}
1339277
function(name, spec){
        if(!name) return;
        var el = et.Element('engine');
        el.attrib.name = name;
        if(spec){
            el.attrib.spec = spec;
        }
        this.doc.getroot().append(el);
    }
553974
private Object makeModelObject(String formName) {
		Object object = null;
		Class modelClass = null;
		try {
			modelClass = (Class) modelFactory.getModelClasses(formName);
			if (modelClass == null) {
				throw new Exception(" not found the model in config xml, formName=" + formName);
			}
			object = modelClass.newInstance();
			// inject
			modelProxyInjection.injectProperties(object);
		} catch (Exception e) {
			Debug.logError("[JdonFramework]--> call Model: " + modelClass + " error:" + e, module);
		}
		return object;
	}
1092959
function Model(name, config) {
	this.name = name;

	utils.defaultsDeep(config, {
		attributes: {},
		sharedMethods: {},
		clientMethods: {},
		serverMethods: {},
		hooks: {},
		options: {
			allowREST: true,
			middlewares: [],
			generateClientModel: true,
			hooks: {}
		},
		relationships: {}
	});

	//Copy all configs to the model object
	for(var c in config) {
		if(config.hasOwnProperty(c)) {
			this[c] = config[c];
		}
	}

	return this;
}
1311200
function ModelClassFactory(name, options) {
        if (!isUndef(options)) {
          return config(name, options);
        }
        return registry[name] || undefined;
      }
621724
def register(self, model, **attr):
        
        metadata = self.metadata
        if not isinstance(model, Table):
            model_name = self._create_model(model, **attr)
            if not model_name:
                return
            model, name = model_name
            table = model.__table__
            self._declarative_register[name] = model

            if name in self._bases:
                for model in self._bases.pop(name):
                    self.register(model)
        else:
            table = model.tometadata(metadata)
            model = table

        # Register engine
        engine = None
        label = table.info.get('bind_label')
        keys = ('%s.%s' % (label, table.key),
                label, None) if label else (None,)
        #
        # Find the engine for this table
        for key in keys:
            engine = self.get_engine(key)
            if engine:
                break
        assert engine
        self.binds[table] = engine

        return model
1291493
def copy_non_ecf(props, target):
    # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any]
    
    target.update(
        {key: value for key, value in props.items() if key not in ECFPROPNAMES}
    )
    return target
200176
public void registerTemplateEngine(Class<? extends TemplateEngine> engineClass) {
        if (templateEngine != null) {
            log.debug("Template engine already registered, ignoring '{}'", engineClass.getName());
            return;
        }

        try {
            TemplateEngine engine = engineClass.newInstance();
            setTemplateEngine(engine);
        } catch (Exception e) {
            throw new PippoRuntimeException(e, "Failed to instantiate '{}'", engineClass.getName());
        }
    }
216500
def clone(instance, substitutions, ignore=()):
    
    substitutions[instance.id] = new_object_id()

    def substitute(value):
        try:
            hash(value)
        except Exception:
            return value
        else:
            return substitutions.get(value, value)

    return instance.__class__(**{
        key:  substitute(value)
        for key, value in iter_items(instance, ignore)
    }).create()
22023
public static void reloadInstance(CFMLEngine engine, ConfigServerImpl configServer)
	    throws SAXException, ClassException, PageException, IOException, TagLibException, FunctionLibException, BundleException {
	Resource configFile = configServer.getConfigFile();

	if (configFile == null) return;
	if (second(configServer.getLoadTime()) > second(configFile.lastModified())) return;
	int iDoNew = doNew(engine, configServer.getConfigDir(), false).updateType;
	boolean doNew = iDoNew != NEW_NONE;

	load(configServer, loadDocument(configFile), true, doNew);

	((CFMLEngineImpl) ConfigWebUtil.getEngine(configServer)).onStart(configServer, true);
    }
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;
    }
272611
def transform_model(cls) -> None:
    
    if cls.name != "Model":
        appname = "models"
        for mcls in cls.get_children():
            if isinstance(mcls, ClassDef):
                for attr in mcls.get_children():
                    if isinstance(attr, Assign):
                        if attr.targets[0].name == "app":
                            appname = attr.value.value

        mname = "{}.{}".format(appname, cls.name)
        MODELS[mname] = cls

        for relname, relval in FUTURE_RELATIONS.get(mname, []):
            cls.locals[relname] = relval

        for attr in cls.get_children():
            if isinstance(attr, Assign):
                try:
                    attrname = attr.value.func.attrname
                except AttributeError:
                    pass
                else:
                    if attrname in ["ForeignKeyField", "ManyToManyField"]:
                        tomodel = attr.value.args[0].value
                        relname = ""
                        if attr.value.keywords:
                            for keyword in attr.value.keywords:
                                if keyword.arg == "related_name":
                                    relname = keyword.value.value

                        if not relname:
                            relname = cls.name.lower() + "s"

                        # Injected model attributes need to also have the relation manager
                        if attrname == "ManyToManyField":
                            relval = [
                                attr.value.func,
                                MANAGER.ast_from_module_name("tortoise.fields").lookup(
                                    "ManyToManyRelationManager"
                                )[1][0],
                            ]
                        else:
                            relval = [
                                attr.value.func,
                                MANAGER.ast_from_module_name("tortoise.fields").lookup(
                                    "RelationQueryContainer"
                                )[1][0],
                            ]

                        if tomodel in MODELS:
                            MODELS[tomodel].locals[relname] = relval
                        else:
                            FUTURE_RELATIONS.setdefault(tomodel, []).append((relname, relval))

    cls.locals["_meta"] = [
        MANAGER.ast_from_module_name("tortoise.models").lookup("MetaInfo")[1][0].instantiate_class()
    ]
    if "id" not in cls.locals:
        cls.locals["id"] = [nodes.ClassDef("id", None)]
1198607
def get_duplicated_model(self, class_inst, new_class_name):
        
        # Ref: http://www.cnblogs.com/Jerryshome/archive/2012/12/21/2827492.html
        attr_dict = {'__module__': self.module_name}
        for field in class_inst.__dict__['_meta'].fields:
            if self.is_relation_field_needed:
                attr_dict[field.name] = copy_field(field)
            elif not is_relation_field(field):
                attr_dict[field.name] = copy_field(field)
        # duplicated_model_class = type("Meta", (), {"abstract": True})
        duplicated_model_class = type(new_class_name, (models.Model,), attr_dict)
        # The following codes are not working
        # if hasattr(class_inst, "__str__"):
        #     setattr(duplicated_model_class, "__str__", getattr(class_inst, "__str__"))
        # if hasattr(class_inst, "__str__"):
        #     str_func = getattr(class_inst, "__str__")
        #     duplicated_model_class.__str__ = str_func
        return duplicated_model_class
207710
function refreshModel(o) {
  if (!(o instanceof Model)) {throw new TypeError('Model expected')}
  _.forEach(o.elements(), refreshElement)
}