Add mapping data to a translatable entity
420183
private function mapTranslatable(ClassMetadata $metadata)
    {
        // In the case A -> B -> TranslatableInterface, B might not have mapping defined as it
        // is probably defined in A, so in that case, we just return.
        if (!isset($this->mappings[$metadata->name])) {
            return;
        }

        $config = $this->mappings[$metadata->name];
        $mapping = $config['translation']['mapping'];

        $metadata->mapManyEmbedded([
            'fieldName' => $mapping['translatable']['translations'],
            'targetDocument' => $config['translation']['model'],
            'strategy' => 'set',
        ]);
    }
367677
@Override
    public void addRelationIntoMetadata(Field relationField, EntityMetadata metadata)
    {
        // taking field's type as foreign entity, ignoring "targetEntity"
        Class<?> targetEntity = relationField.getType();

        ManyToOne ann = relationField.getAnnotation(ManyToOne.class);
        Relation relation = new Relation(relationField, targetEntity, null, ann.fetch(), Arrays.asList(ann.cascade()),
                ann.optional(), null, // mappedBy is null
                Relation.ForeignKey.MANY_TO_ONE);

        boolean isJoinedByFK = relationField.isAnnotationPresent(JoinColumn.class);

        if (relationField.isAnnotationPresent(AssociationOverride.class))
        {
            AssociationOverride annotation = relationField.getAnnotation(AssociationOverride.class);
            JoinColumn[] joinColumns = annotation.joinColumns();

            relation.setJoinColumnName(joinColumns[0].name());

        }
        else if (isJoinedByFK)
        {
            JoinColumn joinColumnAnn = relationField.getAnnotation(JoinColumn.class);
            relation.setJoinColumnName(StringUtils.isBlank(joinColumnAnn.name()) ? relationField.getName()
                    : joinColumnAnn.name());
        }
        else
        {
            relation.setJoinColumnName(relationField.getName());
        }

        relation.setBiDirectionalField(metadata.getEntityClazz());
        metadata.addRelation(relationField.getName(), relation);

    }
178397
def save(self):
        
        active_language = get_language()
        for (name, value) in self.cleaned_data.items():
            if name not in registry:
                name, code = name.rsplit('_modeltranslation_', 1)
            else:
                code = None
            setting_obj, created = Setting.objects.get_or_create(name=name)
            if settings.USE_MODELTRANSLATION:
                if registry[name]["translatable"]:
                    try:
                        activate(code)
                    except:
                        pass
                    finally:
                        setting_obj.value = value
                        activate(active_language)
                else:
                    # Duplicate the value of the setting for every language
                    for code in OrderedDict(settings.LANGUAGES):
                        setattr(setting_obj,
                                build_localized_fieldname('value', code),
                                value)
            else:
                setting_obj.value = value
            setting_obj.save()
1241451
function () {
          for (var key in translationIds) {
            if (translationIds.hasOwnProperty(key)) {
              updateTranslation(key, translationIds[key], scope, scope.interpolateParams, scope.defaultText);
            }
          }
        }
613785
function Mapping() {
    this.generatedLine = 0;
    this.generatedColumn = 0;
    this.source = null;
    this.originalLine = null;
    this.originalColumn = null;
    this.name = null;
  }
1070104
void addUrlNameMapping(String name, Locale locale, CmsUUID structureId) {

        m_urlNameMappingEntries.add(new InternalUrlNameMappingEntry(structureId, name, locale));
    }
52921
function translate(key, options, hasOwnOptions) {

			var lng = options.lng || 'auto';

			if (!translations[lng]) {
				translations[lng] = {};
			}

			if (!t) {

				translations[lng][key] = 'defaultLoadingValue' in options ? options.defaultLoadingValue :
					'defaultValue' in options ? options.defaultValue :
					'defaultLoadingValue' in globalOptions ? globalOptions.defaultLoadingValue : key;

			} else if (!translations[lng][key] || hasOwnOptions) {

				translations[lng][key] = t(key, options);

			}

		}
723909
public function mapToGoogle(Entity $obj_gds_entity, \google\appengine\datastore\v4\Entity $obj_entity)
    {
        // Key
        $this->configureGoogleKey($obj_entity->mutableKey(), $obj_gds_entity);

        // Properties
        $arr_field_defs = $this->obj_schema->getProperties();
        foreach($obj_gds_entity->getData() as $str_field_name => $mix_value) {
            $obj_prop = $obj_entity->addProperty();
            $obj_prop->setName($str_field_name);
            $obj_val = $obj_prop->mutableValue();
            if(isset($arr_field_defs[$str_field_name])) {
                $this->configureGooglePropertyValue($obj_val, $arr_field_defs[$str_field_name], $mix_value);
            } else {
                $arr_dynamic_data = $this->determineDynamicType($mix_value);
                $this->configureGooglePropertyValue($obj_val, ['type' => $arr_dynamic_data['type'], 'index' => TRUE], $arr_dynamic_data['value']);
            }
        }
    }
653630
private static function handleObjectOrArrayValues($formData, $translatable, $languages = [])
    {
        if($formData['type']['inputType'] == 'db') {
            $tmpArr = [];
            $primaryKey = "";
            if($formData['dbTable']['belongsTo'] == 'User') {
                $primaryKey = "userID";
            }else if($formData['dbTable']['belongsTo'] == 'PostType') {
                $primaryKey = "postID";
            }

            if($translatable) {
                if(is_array($formData['value']) && !count($formData['value'])) {
                    foreach ($languages as $language){
                        $tmpArr[$language['slug']] = "";
                    }
                    return json_encode($tmpArr);
                }

                if($formData['value'] != "") {
                    foreach ($formData['value'] as $langSlug => $valuesByLang){
                        if($valuesByLang == "") {
                            $tmpArr[$langSlug] = "";
                            continue;
                        }
                        if($formData['isMultiple']) {
                            $c = 0;
                            foreach ($valuesByLang as $singleValue){
                                if(isset($singleValue[$primaryKey])) {
                                    $tmpArr[$langSlug][] = $singleValue[$primaryKey];
                                    $c++;
                                }
                            }
                        }else{
                            if(isset($valuesByLang[$primaryKey])) {
                                $tmpArr[$langSlug] = $valuesByLang[$primaryKey];
                            }
                        }
                    }
                }
            }else{

                if($formData['isMultiple']) {
                    $c = 0;
                    foreach ($formData['value'] as $singleValue){
                        if(isset($singleValue[$primaryKey])) {
                            $tmpArr[] = $singleValue[$primaryKey];
                            $c++;
                        }
                    }
                }else{
                    if(isset($formData['value'][$primaryKey])) {
                        $tmpArr = $formData['value'][$primaryKey];
                    }
                }
            }

            return json_encode($tmpArr);
        }else{
            if($translatable) {
                return json_encode($formData['value']);
            }else{
                return implode(",", $formData['value']);
            }
        }
    }
631977
def save_translations(self, instance, translated_data):
        
        for meta in self.Meta.model._parler_meta:
            translations = translated_data.get(meta.rel_name, {})
            for lang_code, model_fields in translations.items():
                translation = instance._get_translated_model(lang_code, auto_create=True, meta=meta)
                for field, value in model_fields.items():
                    setattr(translation, field, value)

        # Go through the same hooks as the regular model,
        # instead of calling translation.save() directly.
        instance.save_translations()
78186
def add_data(self, request, pk=None):
        """"""
        # add data to entity
        resp = super().add_data(request, pk)

        # add data to collections in which entity is
        entity = self.get_object()
        for collection in entity.collections.all():
            collection.data.add(*request.data['ids'])

        return resp
1116006
public function setTranslations(array $data, $model, $entity, $delete_existing = true)
    {
        if (empty($data['translation']) || empty($data["{$entity}_id"]) || !$model->isSupportedEntity($entity)) {
            return null;
        }

        foreach ($data['translation'] as $language => $translation) {

            if ($delete_existing) {

                $conditions = array(
                    'entity' => $entity,
                    'language' => $language,
                    "{$entity}_id" => $data["{$entity}_id"]
                );

                $model->delete($conditions);
            }

            $translation['entity'] = $entity;
            $translation['language'] = $language;
            $translation["{$entity}_id"] = $data["{$entity}_id"];

            $model->add($translation);
        }

        return true;
    }
1307431
protected function setData()
    {
        $this->initElementObject();
        if (empty($this->obElement)) {
            return;
        }

        //Set default lang (if update cache with non default lang)
        if (self::$bLangInit && !empty(self::$sDefaultLang) && $this->obElement->isClassExtendedWith('RainLab.Translate.Behaviors.TranslatableModel')) {
            $this->obElement->lang(self::$sDefaultLang);
        }

        //Get cached field list from model and add fields to cache array
        $this->setCachedFieldList();

        //Get element data
        $arResult = $this->getElementData();
        if (empty($arResult) || !is_array($arResult)) {
            $arResult = [];
        }

        //Add fields values to cached array
        foreach ($arResult as $sField => $sValue) {
            $this->setAttribute($sField, $sValue);
        }

        //Save lang properties (integration with Translate plugin)
        $this->setLangProperties();

        //Run methods from $arExtendResult array
        $this->setExtendData();
    }
853555
private void processEntity(Entity entity, double latitude, double longitude) {
        // Only add entities that fall within the bounding box (if set)
        BoundingBox bb = this.configuration.getBboxConfiguration();
        if (bb != null && !bb.contains(latitude, longitude)) {
            return;
        }

        // Only add entities that have data
        if (entity.getTags().isEmpty()) {
            return;
        }

        // Only add named entities (if set)
        if (this.configuration.isNames()) {
            String name = getTagValue(entity.getTags(), "name");
            if (name == null || name.isEmpty()) {
                return;
            }
        }

        // Process entity
        Map<String, String> tagMap = new TreeMap<>();
        Set<PoiCategory> categories = new HashSet<>();
        for (Tag tag : entity.getTags()) {
            String key = tag.getKey().toLowerCase(Locale.ENGLISH);
            if (this.tagMappingResolver.getMappingTags().contains(key)) {
                // Check if there is a POI category for this tag and add POI to DB
                String tagStr = key + "=" + tag.getValue();
                try {
                    // Get categories from tag
                    List<PoiCategory> pcs = this.tagMappingResolver.getCategoriesFromTag(tagStr);

                    // Get categories from key, if tag wasn't matched
                    // Note: key categories should be parents of their value categories
                    if (pcs == null) {
                        pcs = this.tagMappingResolver.getCategoriesFromTag(key);
                    }

                    if (pcs != null) {
                        for (PoiCategory pc : pcs) {
                            // Add entity if its category matches
                            if (this.categoryFilter.isAcceptedCategory(pc)) {
                                // Collect the POI tags in a sorted manner (once)
                                if (tagMap.isEmpty()) {
                                    for (Tag t : entity.getTags()) {
                                        tagMap.put(t.getKey().toLowerCase(Locale.ENGLISH), t.getValue());
                                    }
                                }
                                categories.add(pc);
                            }
                        }
                    }
                } catch (UnknownPoiCategoryException e) {
                    LOGGER.warning("The '" + tagStr + "' tag refers to a POI that does not exist: " + e.getMessage());
                }
            }
        }

        // Store POI
        if (!tagMap.isEmpty()) {
            writePOI(this.poiAdded++, latitude, longitude, tagMap, categories);
        }
    }
837410
def import_translations(request, language):
	
	def _import_po_file(uploadedfile, lang):
		lines = []
		for line in uploadedfile:
			lines.append(line)
		num_lines = len(lines)
		
		prog_ctxt = re.compile(r"msgctxt\s+\"(?P<id>\d+)--(?P<model>\w+)--(?P<object_id>\d+)--(?P<field>\w+)\"")
		prog_msgid = re.compile(r"msgid\s+\"(?P<source_text>.+)\"$")
		prog_msgstr = re.compile(r"msgstr\s+(?P<trans>.+)")
		
		i = 0
		while i < num_lines:
			line = lines[i]
			result = prog_ctxt.match(line)
			if result:
				id = result.group("id")
				is_fuzzy = (lines[i-1] == "#, fuzzy\n")

				source_text = lines[i+1]
				translation_line = lines[i+2]

				# Traducción
				g = prog_msgstr.match(translation_line)
				if g is None:
					i += 1
					continue
				translation = g.group("trans").replace("msgstr","")[1:-1].replace("\\\"","\"").replace('\\\'','\'')
					
				# Obtención de la traducción a partir del id
				try:
					field_trans = FieldTranslation.objects.get(id=id)
				except FieldTranslation.DoesNotExist:
					source_text = source_text.replace("msgid","")[1:-1].replace("\\\"","\"").replace('\\\'','\'')
					source_md5 = hashlib.md5(source_text.encode("utf-8")).hexdigest()
					field_trans = FieldTranslation(model=result.group("model"), object_id=result.group("object_id"), field=result.group("field"), lang=lang, source_text=source_text, source_md5=source_md5)
					
				# Establecemos la traducción y si es fuzzy
				field_trans.translation = translation
				field_trans.is_fuzzy = is_fuzzy
				field_trans.save()
				#print translation
				#print is_fuzzy
				i += 4
			i += 1
	
	# Elimina traducciones que no estén asociadas a ningún objeto
	FieldTranslation.delete_orphan_translations()
	
	# Acceso obligatoriamente por POST
	if request.method != "POST":
		return HttpResponseRedirect(reverse("modeltranslation:admin_url"))
	
	form = ImportTranslationsForm(request.POST, request.FILES)
	if form.is_valid():
		_import_po_file(request.FILES['file'], language)
		#cache = TransCache.factory()
		#cache.clear()
		return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(language,"all")))

	return HttpResponseRedirect(reverse("modeltranslation:admin_url"))
994668
private function appendMapping(QueryBuilder $queryBuilder, MappingInterface $mapping, $locale, $locales)
    {
        if ($mapping->onlyPublished()) {
            $queryBuilder->andWhere(
                $this->qomFactory->comparison(
                    $this->qomFactory->propertyValue(
                        'node',
                        $this->propertyEncoder->localizedSystemName('state', $locale)
                    ),
                    '=',
                    $this->qomFactory->literal(WorkflowStage::PUBLISHED)
                )
            );
        }

        $properties = $mapping->getProperties();
        foreach ($properties as $propertyName) {
            $this->appendSingleMapping($queryBuilder, $propertyName, $locales);
        }

        if ($mapping->resolveUrl()) {
            $this->appendUrlMapping($queryBuilder, $locales);
        }
    }
709078
def _map(self, data_item):
        ""
        delegate = self.delegate
        logger.debug(f'mapping: {data_item}')
        if self.clobber or not self.exists(data_item.id):
            logger.debug(f'exist: {data_item.id}: {self.exists(data_item.id)}')
            delegate.dump(data_item.id, data_item)