Builds and returns a meta-model for Entity language.
439357
def get_entity_mm():
    
    type_builtins = {
            'integer': SimpleType(None, 'integer'),
            'string': SimpleType(None, 'string')
    }
    entity_mm = metamodel_from_file(join(this_folder, 'entity.tx'),
                                    classes=[SimpleType],
                                    builtins=type_builtins)

    return entity_mm
1347521
def build_schema(self, fields, language):
        
        content_field_name = ''
        mapping = {
            DJANGO_CT: {'type': 'string', 'index': 'not_analyzed', 'include_in_all': False},
            DJANGO_ID: {'type': 'string', 'index': 'not_analyzed', 'include_in_all': False},
        }

        for field_name, field_class in fields.items():
            field_mapping = FIELD_MAPPINGS.get(
                field_class.field_type, DEFAULT_FIELD_MAPPING).copy()
            if field_class.boost != 1.0:
                field_mapping['boost'] = field_class.boost

            if field_class.document is True:
                content_field_name = field_class.index_fieldname

            # Do this last to override `text` fields.
            if field_mapping['type'] == 'string':
                # Use the language analyzer for text fields.
                if field_mapping['analyzer'] == DEFAULT_FIELD_MAPPING['analyzer']:
                    field_mapping['analyzer'] = get_analyzer_for(language)
                if field_class.indexed is False or hasattr(field_class, 'facet_for'):
                    field_mapping['index'] = 'not_analyzed'
                    del field_mapping['analyzer']

            mapping[field_class.index_fieldname] = field_mapping

        return content_field_name, mapping
112978
def build(properties = {})
      entity = self.class.entity_class.new(:session => session)

      entity.update_properties(properties)
      entity.partial = false

      append(entity)
      initialize_properties_with_values_from_owner(entity)

      entity
    end
475978
def create_entity(project_id, entity_type_id, entity_value, synonyms):
    """"""
    import dialogflow_v2 as dialogflow
    entity_types_client = dialogflow.EntityTypesClient()

    # Note: synonyms must be exactly [entity_value] if the
    # entity_type's kind is KIND_LIST
    synonyms = synonyms or [entity_value]

    entity_type_path = entity_types_client.entity_type_path(
        project_id, entity_type_id)

    entity = dialogflow.types.EntityType.Entity()
    entity.value = entity_value
    entity.synonyms.extend(synonyms)

    response = entity_types_client.batch_create_entities(
        entity_type_path, [entity])

    print('Entity created: {}'.format(response))
762705
private Map<String, EntityMetadata> getEntityMetadataCol(ApplicationMetadata appMetadata, String persistenceUnit)
    {
        Metamodel metaModel = appMetadata.getMetamodel(persistenceUnit);
        Map<String, EntityMetadata> entityMetadataMap = ((MetamodelImpl) metaModel).getEntityMetadataMap();
        return entityMetadataMap;
    }
796383
def _get_translated_model(self, language_code=None, use_fallback=False, auto_create=False, meta=None):
        
        if self._parler_meta is None:
            raise ImproperlyConfigured("No translation is assigned to the current model!")
        if self._translations_cache is None:
            raise RuntimeError("Accessing translated fields before super.__init__() is not possible.")

        if not language_code:
            language_code = self._current_language
            if language_code is None:
                raise ValueError(get_null_language_error())

        if meta is None:
            meta = self._parler_meta.root  # work on base model by default

        local_cache = self._translations_cache[meta.model]

        # 1. fetch the object from the local cache
        try:
            object = local_cache[language_code]

            # If cached object indicates the language doesn't exist, need to query the fallback.
            if not is_missing(object):
                return object
        except KeyError:
            # 2. No cache, need to query
            # Check that this object already exists, would be pointless otherwise to check for a translation.
            if not self._state.adding and self.pk is not None:
                prefetch = self._get_prefetched_translations(meta=meta)
                if prefetch is not None:
                    # 2.1, use prefetched data
                    # If the object is not found in the prefetched data (which contains all translations),
                    # it's pointless to check for memcached (2.2) or perform a single query (2.3)
                    for object in prefetch:
                        if object.language_code == language_code:
                            local_cache[language_code] = object
                            _cache_translation(object)  # Store in memcached
                            return object
                else:
                    # 2.2, fetch from memcached
                    object = get_cached_translation(self, language_code, related_name=meta.rel_name, use_fallback=use_fallback)
                    if object is not None:
                        # Track in local cache
                        if object.language_code != language_code:
                            local_cache[language_code] = MISSING  # Set fallback marker
                        local_cache[object.language_code] = object
                        return object
                    elif is_missing(local_cache.get(language_code, None)):
                        # If get_cached_translation() explicitly set the "does not exist" marker,
                        # there is no need to try a database query.
                        pass
                    else:
                        # 2.3, fetch from database
                        try:
                            object = self._get_translated_queryset(meta).get(language_code=language_code)
                        except meta.model.DoesNotExist:
                            pass
                        else:
                            local_cache[language_code] = object
                            _cache_translation(object)  # Store in memcached
                            return object

        # Not in cache, or default.
        # Not fetched from DB

        # 3. Auto create?
        if auto_create:
            # Auto create policy first (e.g. a __set__ call)
            kwargs = {
                'language_code': language_code,
            }
            if self.pk:
                # ID might be None at this point, and Django does not allow that.
                kwargs['master'] = self

            object = meta.model(**kwargs)
            local_cache[language_code] = object
            # Not stored in memcached here yet, first fill + save it.
            return object

        # 4. Fallback?
        fallback_msg = None
        lang_dict = get_language_settings(language_code)

        if language_code not in local_cache:
            # Explicitly set a marker for the fact that this translation uses the fallback instead.
            # Avoid making that query again.
            local_cache[language_code] = MISSING  # None value is the marker.
            if not self._state.adding or self.pk is not None:
                _cache_translation_needs_fallback(self, language_code, related_name=meta.rel_name)

        fallback_choices = [lang_dict['code']] + list(lang_dict['fallbacks'])
        if use_fallback and fallback_choices:
            # Jump to fallback language, return directly.
            # Don't cache under this language_code
            for fallback_lang in fallback_choices:
                if fallback_lang == language_code:  # Skip the current language, could also be fallback 1 of 2 choices
                    continue

                try:
                    return self._get_translated_model(fallback_lang, use_fallback=False, auto_create=auto_create, meta=meta)
                except meta.model.DoesNotExist:
                    pass

            fallback_msg = " (tried fallbacks {0})".format(', '.join(lang_dict['fallbacks']))

        # None of the above, bail out!
        raise meta.model.DoesNotExist(
            "{0} does not have a translation for the current language!\n"
            "{0} ID #{1}, language={2}{3}".format(self._meta.verbose_name, self.pk, language_code, fallback_msg or ''
        ))
419219
def from_entity(cls, entity: Entity) -> 'DictModel':
        
        dict_obj = {}
        for field_name in entity.meta_.attributes:
            dict_obj[field_name] = getattr(entity, field_name)
        return dict_obj
594064
private Language toLanguage(Entity emxLanguageEntity) {
    Language language = languageFactory.create();
    language.setCode(emxLanguageEntity.getString(EMX_LANGUAGE_CODE));
    language.setName(emxLanguageEntity.getString(EMX_LANGUAGE_NAME));
    return language;
  }
173178
def create_translated_fields_serializer(shared_model, meta=None, related_name=None, **fields):
    
    if not related_name:
        translated_model = shared_model._parler_meta.root_model
    else:
        translated_model = shared_model._parler_meta[related_name].model

    # Define inner Meta class
    if not meta:
        meta = {}
    meta['model'] = translated_model
    meta.setdefault('fields', ['language_code'] + translated_model.get_translated_fields())

    # Define serialize class attributes
    attrs = {}
    attrs.update(fields)
    attrs['Meta'] = type('Meta', (), meta)

    # Dynamically create the serializer class
    return type('{0}Serializer'.format(translated_model.__name__), (serializers.ModelSerializer,), attrs)
393959
private static TableModel entity2ModelWithConfig(Class<?> entityClass) {
		TableModel model;
		model = entity2ModelIgnoreConfigMethod(entityClass);
		Method method = null;
		try {
			method = entityClass.getMethod("config", TableModel.class);
		} catch (Exception e) {// NOSONAR
		}
		if (method != null)
			try {
				method.invoke(null, model);
			} catch (Exception e) {
				throw new DialectException(e);
			}
		if (model == null)
			throw new DialectException("Can not create TableModel for entityClass " + entityClass);
		return model;
	}
433062
def entityLabel(rdfGraph, anEntity, language=DEFAULT_LANGUAGE, getall=True):
    

    if getall:
        temp = []
        for o in rdfGraph.objects(anEntity, RDFS.label):
            temp += [o]
        return temp
    else:
        for o in rdfGraph.objects(anEntity, RDFS.label):
            if getattr(o, 'language') and getattr(o, 'language') == language:
                return o
        return ""
1025420
private function buildTranslations(ClassMetadataInfo $meta, $gender, $locale)
    {
        $entityName = $this->entityNamer->name($meta->getName());

        $entityTranslatable = $this->translatableManager->isTranslatable($meta->getName());

        $parseDocComments = !in_array($locale, self::$ignoreDocCommentLocales);

        $translations = [
            $entityName => $this->getModel($locale),
        ];
        $translations[$entityName]['entity'] = $this->getPropertyTranslations(
            $meta,
            $parseDocComments,
            $locale,
            $entityTranslatable ? ['translations'] : []
        );

        if ($entityTranslatable) {
            $translations[$entityName]['entity'] = array_merge($translations[$entityName]['entity'], $this->getPropertyTranslations(
                $this->em->getClassMetadata($this->translatableManager->getTranslationClass($meta->getName())),
                $parseDocComments,
                $locale,
                [
                    'locale',
                    'translatable',
                ]
            ));
        }

        $translations[$entityName]['entity'] = $this->normalizePropertyTranslations($translations[$entityName]['entity']);

        $entityTranslation = $this->getClassTranslation($meta->getReflectionClass(), $parseDocComments);

        $cases = $this->getCases($entityTranslation);

        $startsWithAcronym = $this->startsWithAcronym($entityTranslation);

        return $this->replacePlaceholders($translations, [
            '@trans@'                  => $entityTranslation,
            '@trans_lower@'            => $startsWithAcronym ? $entityTranslation : StringsUtil::lowercaseFirst($entityTranslation),
            '@trans_lower_accusative@' => $startsWithAcronym ? $cases['accusative'] : StringsUtil::lowercaseFirst($cases['accusative']),
            '@trans_lower_genitive@'   => $startsWithAcronym ? $cases['genitive'] : StringsUtil::lowercaseFirst($cases['genitive']),
            '@trans_multiple@'         => $cases['multiple'],
        ], array_keys(self::$genders), $gender);
    }
1180051
def _build_object(self, nm, clsdata, parents,**kw):
        logger.debug(util.lazy_format("Building object {0}", nm))

        # To support circular references, we tag objects that we're
        # currently building as "under construction"
        self.under_construction.add(nm)

        props = {}
        defaults = set()

        properties = {}
        for p in parents:
            properties = util.propmerge(properties, p.__propinfo__)

        if 'properties' in clsdata:
            properties = util.propmerge(properties, clsdata['properties'])

        name_translation = {}

        for prop, detail in properties.items():
            logger.debug(util.lazy_format("Handling property {0}.{1}",nm, prop))
            properties[prop]['raw_name'] = prop
            name_translation[prop] = prop.replace('@', '')
            prop = name_translation[prop]

            if detail.get('default', None) is not None:
                defaults.add(prop)

            if detail.get('type', None) == 'object':
                uri = "{0}/{1}_{2}".format(nm,
                                           prop, "<anonymous>")
                self.resolved[uri] = self.construct(
                    uri,
                    detail,
                    (ProtocolBase,))

                props[prop] = make_property(prop,
                                            {'type': self.resolved[uri]},
                                            self.resolved[uri].__doc__)
                properties[prop]['type'] = self.resolved[uri]

            elif 'type' not in detail and '$ref' in detail:
                ref = detail['$ref']
                uri = util.resolve_ref_uri(self.resolver.resolution_scope, ref)
                logger.debug(util.lazy_format(
                    "Resolving reference {0} for {1}.{2}",
                    ref, nm, prop
                ))
                if uri in self.resolved:
                    typ = self.resolved[uri]
                else:
                    typ = self.construct(uri, detail, (ProtocolBase,))

                props[prop] = make_property(prop,
                                            {'type': typ},
                                            typ.__doc__)
                properties[prop]['$ref'] = uri
                properties[prop]['type'] = typ

            elif 'oneOf' in detail:
                potential = self.resolve_classes(detail['oneOf'])
                logger.debug(util.lazy_format("Designating {0} as oneOf {1}", prop, potential))
                desc = detail[
                    'description'] if 'description' in detail else ""
                props[prop] = make_property(prop,
                                            {'type': potential}, desc
                                            )

            elif 'type' in detail and detail['type'] == 'array':
                if 'items' in detail and isinstance(detail['items'], dict):
                    if '$ref' in detail['items']:
                        uri = util.resolve_ref_uri(
                            self.resolver.resolution_scope,
                            detail['items']['$ref'])
                        typ = self.construct(uri, detail['items'])
                        constraints = copy.copy(detail)
                        constraints['strict'] = kw.get('strict')
                        propdata = {
                            'type': 'array',
                            'validator': python_jsonschema_objects.wrapper_types.ArrayWrapper.create(
                                uri,
                                item_constraint=typ,
                                **constraints)}

                    else:
                        uri = "{0}/{1}_{2}".format(nm,
                                                   prop, "<anonymous_field>")
                        try:
                            if 'oneOf' in detail['items']:
                                typ = TypeProxy([
                                    self.construct(uri + "_%s" % i, item_detail)
                                    if '$ref' not in item_detail else
                                    self.construct(util.resolve_ref_uri(
                                        self.resolver.resolution_scope,
                                        item_detail['$ref']),
                                        item_detail)

                                    for i, item_detail in enumerate(detail['items']['oneOf'])]
                                    )
                            else:
                                typ = self.construct(uri, detail['items'])

                            constraints = copy.copy(detail)
                            constraints['strict'] = kw.get('strict')
                            propdata = {'type': 'array',
                                        'validator': python_jsonschema_objects.wrapper_types.ArrayWrapper.create(
                                            uri,
                                            item_constraint=typ,
                                            **constraints)}

                        except NotImplementedError:
                            typ = detail['items']
                            constraints = copy.copy(detail)
                            constraints['strict'] = kw.get('strict')
                            propdata = {'type': 'array',
                                        'validator': python_jsonschema_objects.wrapper_types.ArrayWrapper.create(
                                            uri,
                                            item_constraint=typ,
                                            **constraints)}

                    props[prop] = make_property(prop,
                                                propdata,
                                                typ.__doc__)
                elif 'items' in detail:
                    typs = []
                    for i, elem in enumerate(detail['items']):
                        uri = "{0}/{1}/<anonymous_{2}>".format(nm, prop, i)
                        typ = self.construct(uri, elem)
                        typs.append(typ)

                    props[prop] = make_property(prop,
                                                {'type': typs},
                                                )

            else:
                desc = detail[
                    'description'] if 'description' in detail else ""
                uri = "{0}/{1}".format(nm, prop)
                typ = self.construct(uri, detail)

                props[prop] = make_property(prop, {'type': typ}, desc)

        
        if 'oneOf' in clsdata:
            klasses = self.resolve_classes(clsdata['oneOf'])
            # Need a validation to check that it meets one of them
            props['__validation__'] = {'type': klasses}

        props['__extensible__'] = pattern_properties.ExtensibleValidator(
            nm,
            clsdata,
            self)

        props['__prop_names__'] = name_translation

        props['__propinfo__'] = properties
        required = set.union(*[p.__required__ for p in parents])

        if 'required' in clsdata:
            for prop in clsdata['required']:
                required.add(prop)

        invalid_requires = [req for req in required if req not in props['__propinfo__']]
        if len(invalid_requires) > 0:
          raise validators.ValidationError("Schema Definition Error: {0} schema requires "
                                           "'{1}', but properties are not defined"
                                           .format(nm, invalid_requires))

        props['__required__'] = required
        props['__has_default__'] = defaults
        if required and kw.get("strict"):
            props['__strict__'] = True

        props['__title__'] = clsdata.get('title')
        cls = type(str(nm.split('/')[-1]), tuple(parents), props)
        self.under_construction.remove(nm)

        return cls
489841
def create_model_class(cls, name, table_name, attrs, validations=None, *, otherattrs=None,
                         other_bases=None):
    """"""
    members = dict(table_name=table_name, attrs=attrs, validations=validations or [])
    if otherattrs:
      members.update(otherattrs)
    return type(name, other_bases or (), members)
422772
private function newMetaQuery()
	{
		$meta_model = $this->metaModel();
		$meta_instance = new $meta_model;
		
		$query = $meta_instance->newQuery();
		
		if (method_exists($this, 'metaContext')) {
			if (method_exists($meta_model, 'applyQueryContext')) {
				call_user_func_array(
					array($meta_model, 'applyQueryContext'),
					array($query, $this->metaContext())
				);
			}
		}
		
		return $query;
	}
509830
public function buildModelCriteria()
    {
        $query = new FeatureTypeQuery();

        /* manage translations */
        $this->configureI18nProcessing($query, array('TITLE', 'DESCRIPTION'));

        if (null !== $id = $this->getId()) {
            $query->filterById($id);
        }

        if (null !== $id = $this->getExcludeId()) {
            $query->filterById($id, Criteria::NOT_IN);
        }

        if (null !== $slug = $this->getSlug()) {
            $query->filterBySlug($slug);
        }

        if (null !== $featureId = $this->getFeatureId()) {
            $join = new Join();

            $join->addExplicitCondition(
                FeatureTypeTableMap::TABLE_NAME,
                'ID',
                null,
                FeatureFeatureTypeTableMap::TABLE_NAME,
                'FEATURE_TYPE_ID',
                null
            );

            $join->setJoinType(Criteria::JOIN);

            $query
                ->addJoinObject($join, 'feature_type_join')
                ->addJoinCondition(
                    'feature_type_join',
                    '`feature_feature_type`.`feature_id` IN (?)',
                    implode(',', $featureId),
                    null,
                    \PDO::PARAM_INT
                );
        }

        foreach ($this->getOrder() as $order) {
            switch ($order) {
                case "id":
                    $query->orderById();
                    break;
                case "id-reverse":
                    $query->orderById(Criteria::DESC);
                    break;
                case "slug":
                    $query->orderBySlug();
                    break;
                case "slug-reverse":
                    $query->orderBySlug(Criteria::DESC);
                    break;
            }
        }
        return $query;
    }
102158
public function buildModelCriteria()
    {
        $query = DealerContactQuery::create();

        // manage translations
        $this->configureI18nProcessing(
            $query,
            [
                'LABEL',
            ],
            null,
            'ID',
            $this->getForceReturn()
        );

        if (null != $default = $this->getDefault()) {
            $query->filterByIsDefault($default);
        }

        if ($id = $this->getId()) {
            $query->filterById($id);
        }

        if ($dealer_id = $this->getDealerId()) {
            $query->filterByDealerId($dealer_id);
        }

        foreach ($this->getOrder() as $order) {
            switch ($order) {
                case 'id':
                    $query->orderById();
                    break;
                case 'id-reverse':
                    $query->orderById(Criteria::DESC);
                    break;
                case 'label':
                    $query->orderByLabel();
                    break;
                case 'label-reverse':
                    $query->orderByLabel(Criteria::DESC);
                    break;
                case 'default-first':
                    $query->orderByIsDefault(Criteria::DESC);
                    break;
                default:
                    break;
            }
        }

        return $query;
    }