Creates a class-based entity with fixed values, using all of the supported data types.
434883
def create_entity_class(self):
        '''
        
        '''
        entity = Entity()

        # Partition key and row key must be strings and are required
        entity.PartitionKey = 'pk{}'.format(str(uuid.uuid4()).replace('-', ''))
        entity.RowKey = 'rk{}'.format(str(uuid.uuid4()).replace('-', ''))

        # Some basic types are inferred
        entity.age = 39  # EdmType.INT64
        entity.large = 933311100  # EdmType.INT64
        entity.sex = 'male'  # EdmType.STRING
        entity.married = True  # EdmType.BOOLEAN
        entity.ratio = 3.1  # EdmType.DOUBLE
        entity.birthday = datetime(1970, 10, 4)  # EdmType.DATETIME

        # Binary, Int32 and GUID must be explicitly typed
        entity.binary = EntityProperty(EdmType.BINARY, b'xyz')
        entity.other = EntityProperty(EdmType.INT32, 20)
        entity.clsid = EntityProperty(EdmType.GUID, 'c9da6455-213d-42c9-9a79-3e9149a57833')
        return entity
871613
private Entity toEntity(EntityType entityType, Entity emxEntity) {
    Entity entity = entityManager.create(entityType, POPULATE);
    for (Attribute attr : entityType.getAtomicAttributes()) {
      if (attr.getExpression() == null && !attr.isMappedBy()) {
        String attrName = attr.getName();
        Object emxValue = emxEntity.get(attrName);

        AttributeType attrType = attr.getDataType();
        switch (attrType) {
          case BOOL:
          case DATE:
          case DATE_TIME:
          case DECIMAL:
          case EMAIL:
          case ENUM:
          case HTML:
          case HYPERLINK:
          case INT:
          case LONG:
          case SCRIPT:
          case STRING:
          case TEXT:
            Object value = emxValue != null ? DataConverter.convert(emxValue, attr) : null;
            if ((!attr.isAuto() || value != null) && (!attr.hasDefaultValue() || value != null)) {
              entity.set(attrName, value);
            }
            break;
          case CATEGORICAL:
          case FILE:
          case XREF:
            // DataConverter.convert performs no conversion for reference types
            Entity refEntity = toRefEntity(attr, emxValue);

            // do not set generated auto refEntities to null
            if ((!attr.isAuto() || refEntity != null)
                && (!attr.hasDefaultValue() || refEntity != null)) {
              entity.set(attrName, refEntity);
            }
            break;
          case CATEGORICAL_MREF:
          case MREF:
            // DataConverter.convert performs no conversion for reference types
            List<Entity> refEntities = toRefEntities(attr, emxValue);

            // do not set generated auto refEntities to null
            if (!refEntities.isEmpty()) {
              entity.set(attrName, refEntities);
            }
            break;
          case COMPOUND:
            throw new IllegalAttributeTypeException(attrType);
          default:
            throw new UnexpectedEnumException(attrType);
        }
      }
    }
    return entity;
  }
1353556
def _normalize_entity(value):
  """"""
  if ndb is not None and isinstance(value, ndb.Model):
    return None
  if getattr(value, "_populate_internal_entity", None):
    return value._populate_internal_entity()
  return value
586969
def create(cls, values, **context):
        
        schema = cls.schema()
        model = cls

        # check for creating inherited classes from a sub class
        polymorphic_columns = schema.columns(flags=orb.Column.Flags.Polymorphic)
        if polymorphic_columns:
            polymorphic_column = polymorphic_columns.values()[0]
            schema_name = values.get(polymorphic_column.name(), schema.name())
            if schema_name and schema_name != schema.name():
                schema = orb.system.schema(schema_name)
                if not schema:
                    raise orb.errors.ModelNotFound(schema=schema_name)
                else:
                    model = schema.model()

        column_values = {}
        collector_values = {}

        for key, value in values.items():
            obj = schema.collector(key) or schema.column(key)
            if isinstance(obj, orb.Collector):
                collector_values[key] = value
            else:
                column_values[key] = value

        # create the new record with column values (values stored on this record)
        record = model(context=orb.Context(**context))
        record.update(column_values)
        record.save()

        # save any collector values after the model is generated (values stored on other records)
        record.update(collector_values)

        return record
679277
private Object populateEntityFromHbaseData(Object entity, HBaseData hbaseData, EntityMetadata m, Object rowKey,
            List<String> relationNames)
    {

        try
        {

            // Raw data retrieved from HBase for a particular row key (contains
            // all column families)

            Map<String, Object> relations = new HashMap<String, Object>();

            if (entity.getClass().isAssignableFrom(EnhanceEntity.class))
            {
                relations = ((EnhanceEntity) entity).getRelations();
                entity = ((EnhanceEntity) entity).getEntity();

            }

            // Populate columns data

            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    m.getPersistenceUnit());
            EntityType entityType = metaModel.entity(m.getEntityClazz());

            Set<Attribute> attributes = entityType.getAttributes();

            String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();
            String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();

            if (discrColumn != null && hbaseData.getColumnValue(discrColumn) != null && discrValue != null)
            {
                byte[] discrimnatorValue = hbaseData.getColumnValue(discrColumn);
                String actualDiscriminatorValue = Bytes.toString(discrimnatorValue);
                if (actualDiscriminatorValue != null && !actualDiscriminatorValue.equals(discrValue))
                {
                    entity = null;
                    return entity;
                }
            }

            for (Attribute attribute : attributes)
            {
                Class javaType = ((AbstractAttribute) attribute).getBindableJavaType();
                String key = ((AbstractAttribute) attribute).getJPAColumnName();
                if (metaModel.isEmbeddable(javaType))
                {
                    EmbeddableType columnFamily = metaModel.embeddable(javaType);

                    Field columnFamilyFieldInEntity = (Field) attribute.getJavaMember();
                    Class<?> columnFamilyClass = columnFamilyFieldInEntity.getType();

                    // Get a name->field map for columns in this column family
                    Map<String, Field> columnNameToFieldMap = MetadataUtils.createColumnsFieldMap(m, columnFamily);

                    // Column family can be either @Embedded or
                    // @EmbeddedCollection
                    if (Collection.class.isAssignableFrom(columnFamilyClass))
                    {
                        Map<Integer, Object> elementCollectionObjects = new HashMap<Integer, Object>();

                        Field embeddedCollectionField = (Field) attribute.getJavaMember();
                        Object[] embeddedObjectArr = new Object[hbaseData.getColumns().size()];
                        Object embeddedObject = MetadataUtils.getEmbeddedGenericObjectInstance(embeddedCollectionField);

                        Map<String, byte[]> hbaseValues = hbaseData.getColumns();

                        Set<String> columnNames = hbaseValues.keySet();

                        for (String columnName : columnNames)
                        {
                            byte[] columnValue = hbaseData.getColumnValue(columnName);

                            if (columnName.startsWith(((AbstractAttribute) attribute).getJPAColumnName()))
                            {
                                String cfNamePostfix = MetadataUtils.getEmbeddedCollectionPostfix(columnName);
                                int cfNameCounter = Integer.parseInt(cfNamePostfix);
                                embeddedObject = elementCollectionObjects.get(cfNameCounter);

                                if (embeddedObject == null)
                                {

                                    embeddedObject = MetadataUtils
                                            .getEmbeddedGenericObjectInstance(embeddedCollectionField);
                                }

                                // Set Hbase data into the embedded object
                                setHBaseDataIntoObject(columnName, columnValue, columnNameToFieldMap, embeddedObject,
                                        metaModel.isEmbeddable(javaType));

                                elementCollectionObjects.put(cfNameCounter, embeddedObject);

                            }

                            if (relationNames != null && relationNames.contains(hbaseData.getColumnFamily())
                                    && columnValue.length != 0)
                            {
                                relations
                                        .put(hbaseData.getColumnFamily(),
                                                getObjectFromByteArray(entityType, columnValue,
                                                        hbaseData.getColumnFamily(), m));
                            }

                            // Save embedded object into Cache, needed while
                            // updation and deletion
                            ElementCollectionCacheManager.getInstance().addElementCollectionCacheMapping(rowKey,
                                    embeddedObject, hbaseData.getColumnFamily());
                        }

                        for (Integer integer : elementCollectionObjects.keySet())
                        {
                            embeddedObjectArr[integer] = elementCollectionObjects.get(integer);
                        }

                        Collection embeddedCollection = MetadataUtils
                                .getEmbeddedCollectionInstance(embeddedCollectionField);
                        embeddedCollection.addAll(Arrays.asList(embeddedObjectArr));
                        embeddedCollection.removeAll(Collections.singletonList(null));
                        embeddedObjectArr = null; // Eligible for GC

                        // Now, set the embedded collection into entity
                        if (embeddedCollection != null && !embeddedCollection.isEmpty())
                        {
                            PropertyAccessorHelper.set(entity, embeddedCollectionField, embeddedCollection);
                        }
                    }
                    else
                    {
                        Object existsColumnFamilyObj = PropertyAccessorHelper.getObject(entity,
                                columnFamilyFieldInEntity);
                        Object columnFamilyObj = existsColumnFamilyObj != null ? existsColumnFamilyObj
                                : columnFamilyClass.newInstance();

                        Map<String, byte[]> hbaseValues = hbaseData.getColumns();
                        Set<String> columnNames = hbaseValues.keySet();

                        for (String columnName : columnNames)
                        {
                            byte[] columnValue = hbaseData.getColumnValue(columnName);
                            if (relationNames != null && relationNames.contains(hbaseData.getColumnFamily())
                                    && columnValue.length != 0)
                            {
                                relations
                                        .put(hbaseData.getColumnFamily(),
                                                getObjectFromByteArray(entityType, columnValue,
                                                        hbaseData.getColumnFamily(), m));
                            }
                            // Set Hbase data into the column family object
                            // Get Column from metadata
                            Field columnField = columnNameToFieldMap.get(columnName);
                            if (columnField != null && columnValue.length != 0)
                            {
                                if (columnFamilyFieldInEntity.isAnnotationPresent(Embedded.class)
                                        || columnFamilyFieldInEntity.isAnnotationPresent(EmbeddedId.class)
                                        || columnFamilyFieldInEntity.isAnnotationPresent(ElementCollection.class))
                                {
                                    PropertyAccessorHelper.set(columnFamilyObj, columnField,
                                            HBaseUtils.fromBytes(columnValue, columnField.getType()));
                                }
                                else
                                {
                                    columnFamilyObj = getObjectFromByteArray(entityType, columnValue,
                                            hbaseData.getColumnFamily(), m);
                                }
                            }
                        }

                        PropertyAccessorHelper.set(entity, columnFamilyFieldInEntity, columnFamilyObj);
                    }
                }
                else if (!attribute.getName().equals(m.getIdAttribute().getName()))
                {
                    Field columnField = (Field) attribute.getJavaMember();
                    String columnName = ((AbstractAttribute) attribute).getJPAColumnName();

                    byte[] columnValue = hbaseData.getColumnValue(columnName);

                    if (relationNames != null && relationNames.contains(columnName) && columnValue != null
                            && columnValue.length > 0)
                    {
                        relations.put(columnName, getObjectFromByteArray(entityType, columnValue, columnName, m));
                    }
                    else if (columnValue != null && columnValue.length > 0)

                    {
                        PropertyAccessorHelper.set(entity, columnField,
                                HBaseUtils.fromBytes(columnValue, columnField.getType()));
                    }
                }
            }

            if (!relations.isEmpty())
            {

                return new EnhanceEntity(entity, rowKey, relations);
            }

            return entity;
        }
        catch (PropertyAccessException e1)
        {
            throw new RuntimeException(e1);
        }
        catch (InstantiationException e1)
        {
            throw new RuntimeException(e1);
        }
        catch (IllegalAccessException e1)
        {
            throw new RuntimeException(e1);
        }
    }
275134
private function createEntityClassParameter()
    {
        $id = $this->getServiceId('class');
        if (!$this->container->hasParameter($id)) {
            $this->container->setParameter($id, $this->options['entity']);
        }

        $this->configureInheritanceMapping(
            $this->prefix.'.'.$this->resourceName,
            $this->options['entity'],
            $this->options['repository']
        );
    }
64422
private Object instantiateEntity(Class entityClass, Object entity)
    {
        if (entity == null)
        {
            return KunderaCoreUtils.createNewInstance(entityClass);
        }
        return entity;
    }
1141885
def generate(
        cls: Type[T], data: Generic, name: str = None, *, recursive: bool = True
    ) -> T:
        """"""
        if name is None:
            name = cls.__name__
        kls = make_class(name, {k: ib(default=None) for k in data}, bases=(cls,))
        data = {
            k: (
                cls.generate(v, k.title())
                if recursive and isinstance(v, Mapping)
                else v
            )
            for k, v in data.items()
        }
        return kls(**data)
773394
public static <E> JpaRepositoryConfig<E> create(Class<E> entityClass) {
        return builder(entityClass).build();
    }
277350
private Object instantiateEntity(Class entityClass, Object entity)
    {
        try
        {
            if (entity == null)
            {
                return entityClass.newInstance();
            }
            return entity;
        }
        catch (InstantiationException e)
        {
            log.error("Error while instantiating " + entityClass + ", Caused by: ", e);
        }
        catch (IllegalAccessException e)
        {
            log.error("Error while instantiating " + entityClass + ", Caused by: ", e);
        }
        return null;
    }
1270260
private void generateEntity(M2MEntity entity) {
		entity.propertyPrimaryKey = TypeName.LONG;
		entity.propertyKey1 = findPrimaryKeyFieldType(entity.entity1Name.toString());
		entity.propertyKey2 = findPrimaryKeyFieldType(entity.entity2Name.toString());
		if (!entity.needToCreate) {
			return;
		}

		String tableName = entity.tableName;
		String entityClassName = entity.name;

		AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDaoMany2Many.class, entity.getPackageName(),
				entityClassName);

		Converter<String, String> converterFK = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_CAMEL);
		Converter<String, String> converterFieldName = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
		Converter<String, String> converterField2ColumnName = CaseFormat.LOWER_CAMEL
				.converterTo(CaseFormat.LOWER_UNDERSCORE);
		String fkPrefix = converterFK.convert(entity.idName);

		String fk1Name = converterField2ColumnName.convert(entity.entity1Name.simpleName() + fkPrefix);
		String fk2Name = converterField2ColumnName.convert(entity.entity2Name.simpleName() + fkPrefix);

		String field1Name = converterFieldName.convert(entity.entity1Name.simpleName() + fkPrefix);
		String field2Name = converterFieldName.convert(entity.entity2Name.simpleName() + fkPrefix);

		List<SQLProperty> properties = new ArrayList<SQLProperty>();

		// we define property type later
		{
			SQLProperty property = new SQLProperty(entity.idName, entity.getClassName(), entity.propertyPrimaryKey);
			property.columnType = ColumnType.PRIMARY_KEY;
			property.columnName = entity.idName;
			property.setNullable(false);
			property.setPrimaryKey(true);
			property.foreignParentClassName = null;
			properties.add(property);
		}

		{
			SQLProperty property = new SQLProperty(field1Name, entity.getClassName(), entity.propertyKey1);
			property.columnType = ColumnType.INDEXED;
			property.columnName = fk1Name;
			property.setNullable(false);
			property.setPrimaryKey(false);
			property.onDeleteAction = ForeignKeyAction.CASCADE;
			property.foreignParentClassName = entity.entity1Name.toString();
			properties.add(property);
		}

		{
			SQLProperty property = new SQLProperty(field2Name, entity.getClassName(), entity.propertyKey2);
			property.columnType = ColumnType.INDEXED;
			property.columnName = fk2Name;
			property.setNullable(false);
			property.setPrimaryKey(false);
			property.onDeleteAction = ForeignKeyAction.CASCADE;
			property.foreignParentClassName = entity.entity2Name.toString();
			properties.add(property);
		}

		// @formatter:off
		classBuilder = TypeSpec.classBuilder(entityClassName).addModifiers(Modifier.PUBLIC)
				.addAnnotation(AnnotationSpec.builder(BindSqlType.class).addMember("name", "$S", tableName).build());
		// @formatter:on

		if (entity.immutable) {
			// create constructor
			Builder constructorBuilder = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC);
			for (SQLProperty p : properties) {
				constructorBuilder
						.addParameter(ParameterSpec.builder(p.getPropertyType().getTypeName(), p.getName()).build());
				constructorBuilder.addStatement("this.$L=$L", p.getName(), p.getName());
			}
			classBuilder.addMethod(constructorBuilder.build());
		}

		Modifier fieldModifier = entity.immutable ? Modifier.PRIVATE : Modifier.PUBLIC;

		// javadoc for class
		classBuilder.addJavadoc("<p>");
		classBuilder.addJavadoc("\nGenerated entity implementation for <code>$L</code>\n", entity.name);
		classBuilder.addJavadoc("</p>\n");
		JavadocUtility.generateJavadocGeneratedBy(classBuilder);
		// classBuilder.addJavadoc(" @see $T\n",		

		{
			// @formatter:off
			FieldSpec fieldSpec = FieldSpec.builder(entity.propertyPrimaryKey, entity.idName, fieldModifier)
					.addJavadoc("Primary key\n")
					.addAnnotation(AnnotationSpec.builder(BindSqlColumn.class)
							.addMember("columnType", "$T.$L", ColumnType.class, ColumnType.PRIMARY_KEY).build())
					.build();
			// @formatter:on
			classBuilder.addField(fieldSpec);
		}

		{
			// @formatter:off
			FieldSpec fieldSpec = FieldSpec
					.builder(entity.propertyKey1, field1Name, fieldModifier)
					.addJavadoc("Foreign key to $T model class\n", entity.entity1Name)
					.addAnnotation(AnnotationSpec.builder(BindSqlColumn.class)
							.addMember(AnnotationAttributeType.PARENT_ENTITY.getValue(), "$T.class", entity.entity1Name)
							.addMember(AnnotationAttributeType.ON_DELETE.getValue(), "$T.$L", ForeignKeyAction.class,
									ForeignKeyAction.CASCADE)
							.build())
					.build();
			// @formatter:on
			classBuilder.addField(fieldSpec);
		}

		{
			// @formatter:off
			FieldSpec fieldSpec = FieldSpec
					.builder(entity.propertyKey2, field2Name, fieldModifier)
					.addJavadoc("Foreign key to $T model class\n", entity.entity2Name)
					.addAnnotation(AnnotationSpec.builder(BindSqlColumn.class)
							.addMember(AnnotationAttributeType.PARENT_ENTITY.getValue(), "$T.class", entity.entity2Name)
							.addMember(AnnotationAttributeType.ON_DELETE.getValue(), "$T.$L", ForeignKeyAction.class,
									ForeignKeyAction.CASCADE)
							.build())
					.build();
			// @formatter:on
			classBuilder.addField(fieldSpec);
		}

		if (entity.immutable) {
			// getters
			for (SQLProperty p : properties) {
				Builder methodBuilder = MethodSpec
						.methodBuilder("get" + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, p.getName()))
						.returns(p.getPropertyType().getTypeName()).addStatement("return this.$L", p.getName())
						.addModifiers(Modifier.PUBLIC);

				classBuilder.addMethod(methodBuilder.build());
			}
		}

		TypeSpec typeSpec = classBuilder.build();

		try {
			JavaWriterHelper.writeJava2File(filer, entity.getPackageName(), typeSpec);
		} catch (IOException e) {
			throw new KriptonRuntimeException(e);
		}

		GeneratedTypeElement entityElement = new GeneratedTypeElement(entity.getPackageName(), classBuilder.build(),
				tableName, fk1Name + ", " + fk2Name);

		entityElement.properties = properties;

		entityResult.add(entityElement);
	}
636875
def save(self, commit=True):
        

        if self.errors:
            raise ValueError("The %s could not be saved because the data didn't"
                             " validate." % self.instance._meta.object_name)

        # create entity instance, don't save yet
        instance = super(BaseDynamicEntityForm, self).save(commit=False)

        # assign attributes
        for name in instance.get_schema_names():
            value = self.cleaned_data.get(name)
            setattr(instance, name, value)

        # save entity and its attributes
        if commit:
            instance.save()

        return instance
995757
def create_set(self, set_id, etype, entities):
        
        if etype not in {"sample", "pair", "participant"}:
            raise ValueError("Unsupported entity type:" + str(etype))

        payload = "membership:" + etype + "_set_id\t" + etype + "_id\n"

        for e in entities:
            if e.etype != etype:
                msg =  "Entity type '" + e.etype + "' does not match "
                msg += "set type '" + etype + "'"
                raise ValueError(msg)
            payload += set_id + '\t' + e.entity_id + '\n'


        r = fapi.upload_entities(self.namespace, self.name,
                                    payload, self.api_url)
        fapi._check_response_code(r, 201)
1232826
private function buildEntity()
    {
        $classname = $this->classname;
        if (class_exists($classname) && $this->isRegistryEntity(new $classname())) {
            $this->entity = new $classname();
            $this->buildEntityClass();
        } else {
            $this->entity = new \stdClass();
            $this->buildStdClass();
        }
    }
1158769
function createEntityObject(e) {
		var obj = {id: e.id, className: e.constructor.name, children: []};
		if (e.children && e.children.length > 0) {
			e.children.forEach(function(c) {
				obj.children.push(createEntityObject(c));
			});
		}
		return obj;
	}
1002356
def _create(cls, model_class, *args, **kwargs):
        """"""
        session = cls._meta.sqlalchemy_session
        session_persistence = cls._meta.sqlalchemy_session_persistence
        if cls._meta.force_flush:
            session_persistence = SESSION_PERSISTENCE_FLUSH

        obj = model_class(*args, **kwargs)
        if session is None:
            raise RuntimeError("No session provided.")
        session.add(obj)
        if session_persistence == SESSION_PERSISTENCE_FLUSH:
            session.flush()
        elif session_persistence == SESSION_PERSISTENCE_COMMIT:
            session.commit()
        return obj
1320247
def construct(cls: Type['Model'], values: 'DictAny', fields_set: 'SetStr') -> 'Model':
        
        m = cls.__new__(cls)
        object.__setattr__(m, '__values__', values)
        object.__setattr__(m, '__fields_set__', fields_set)
        return m