Updates FieldTranslations table
508462
def update_translations(condition=None):
		
		if condition is None:
			condition = {}

		# Number of updated translations
		num_translations = 0
		
		# Module caching
		FieldTranslation._init_module_cache()

		# Current languages dict
		LANGUAGES = dict(lang for lang in MODELTRANSLATION_LANG_CHOICES)
		if settings.LANGUAGE_CODE in LANGUAGES:
			del LANGUAGES[settings.LANGUAGE_CODE]

		# For each module, we are going to update the translations
		for key in FieldTranslation._modules.keys():
			module = FieldTranslation._modules[key]

			# Class of the module
			clsmembers = inspect.getmembers(sys.modules[key], inspect.isclass)
			for cls in clsmembers:
				cls = cls[1]

				# If the model has in Meta "translatable_fields", we insert this fields
				if hasattr(cls,"_meta") and not cls._meta.abstract and hasattr(cls._meta,"translatable_fields") and len(cls._meta.translatable_fields)>0:
					objects = cls.objects.filter(**condition)
					
					# For each object, language and field are updated
					for obj in objects:
						for lang in LANGUAGES.keys():
							for field in cls._meta.translatable_fields:
								if FieldTranslation.update(obj=obj, field=field, lang=lang, context=""):
									num_translations += 1
		return num_translations
869636
def with_translations(*locales)
      locales = translated_locales if locales.empty?
      where :translations.matches => {:locale => {"$in" => locales.flatten}}.merge(required_fields_criteria)
    end
44485
def update_field_geolocalization(field, value)
      final_value = {
        lat: value[:lat],
        lng: value[:lng],
        address: value[:address]
      }
      field.update(value: final_value)
    end
107013
public function afterUpdate()
    {
        /** @var ActiveRecord $owner */
        $owner = $this->owner;

        if ($owner->isRelationPopulated('translations')) {
            $translations = $this->indexByLanguage($owner->getRelatedRecords()['translations']);
            $this->saveTranslations($translations);
        }
    }
85100
function  updateTemplate(tbName, schema, columns, inData)  {
	var  insertObj = {},
		 jsonObj = {},
		 schemaCol = schema.columns,
		 isNewSQL = schemaCol.indexOf('_c_json') >= 0;

	// if columns are specified in the SQL expression, remove input data which are
	// not  specified in columns
	if (columns)  {
		var  ndata = {},
			 keys = Object.getOwnPropertyNames(inData);
		for (var i in keys)  {
			var  key = keys[i];
			if (columns.indexOf(key) >= 0)
				ndata[key] = inData[key];
		}
		inData = ndata;
	}
	
	// needs to decide what goes to sql columns and what goes to the json column
	var  keys = Object.getOwnPropertyNames(inData);
	for (var i in keys)  {
		var  key = keys[i];
		if (schemaCol.indexOf(key) >= 0)
			insertObj[key] = inData[key];
		else  if (isNewSQL)
			jsonObj[key] = inData[key];
	}

	var  insertCol = Object.keys( insertObj );
	if (Object.keys(jsonObj).length)  {
		// prepare the json column
		insertCol.push('_c_json');
		//insertObj._c_json = JSON.stringify(jsonObj);
	}

	var  updateSBI = soar.sqlTemplate(tbName);
	updateSBI.column( insertCol );

	return  {sbi: updateSBI, data: insertObj, _c_json: jsonObj};
}
871375
def translate_value(field, value)
      translated_value = field.complete_value[value.to_sym]
      raise ScopedSearch::QueryNotSupported, "'#{field.field}' should be one of '#{field.complete_value.keys.join(', ')}', but the query was '#{value}'" if translated_value.nil?
      translated_value
    end
1037677
def export_translations(request, language):
	
	FieldTranslation.delete_orphan_translations()
	translations = FieldTranslation.objects.filter(lang=language)
	for trans in translations:
		trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"")
		trans.translation = trans.translation.replace("'","\'").replace("\"","\\\"")
	replacements = {"translations":translations, "lang":language}
	if len(settings.ADMINS)>0:
		replacements["last_translator"] = settings.ADMINS[0][0]
		replacements["last_translator_email"] = settings.ADMINS[0][1]
	if settings.WEBSITE_NAME:
		replacements["website_name"] = settings.WEBSITE_NAME
	response = render(request=request, template_name='modeltranslation/admin/export_translations.po', dictionary=replacements, context_instance=RequestContext(request), content_type="text/x-gettext-translation")
	response['Content-Disposition'] = 'attachment; filename="{0}.po"'.format(language)
	return response
552247
protected function moveI18nColumns()
    {
        $table     = $this->getTable();
        $i18nTable = $this->i18nTable;

        $i18nValidateParams = [];
        foreach ($this->getI18nColumnNamesFromConfig() as $columnName) {
            if (!$i18nTable->hasColumn($columnName)) {
                if (!$table->hasColumn($columnName)) {
                    throw new EngineException(sprintf('No column named %s found in table %s', $columnName, $table->getName()));
                }

                $column = $table->getColumn($columnName);
                $i18nTable->addColumn(clone $column);

                // validate behavior: move rules associated to the column
                if ($table->hasBehavior('validate')) {
                    $validateBehavior = $table->getBehavior('validate');
                    $params = $validateBehavior->getParametersFromColumnName($columnName);
                    $i18nValidateParams = array_merge($i18nValidateParams, $params);
                    $validateBehavior->removeParametersFromColumnName($columnName);
                }
                // FIXME: also move FKs, and indices on this column
            }

            if ($table->hasColumn($columnName)) {
                $table->removeColumn($columnName);
            }
        }

        // validate behavior
        if (count($i18nValidateParams) > 0) {
            $i18nVbehavior = new ValidateBehavior();
            $i18nVbehavior->setName('validate');
            $i18nVbehavior->setParameters($i18nValidateParams);
            $i18nTable->addBehavior($i18nVbehavior);

            // current table must have almost 1 validation rule
            $validate = $table->getBehavior('validate');
            $validate->addRuleOnPk();
        }
    }
193669
private function updateSectionTable()
    {
        $this->em->getConnection()->executeUpdate('SET FOREIGN_KEY_CHECKS=0');

        $schemaTool = new SchemaTool($this->em);
        $schemaManager = $this->em->getConnection()->getSchemaManager();
        $sectionMeta = $this->em->getClassMetadata('BackBee\NestedNode\Section');
        $tableSection = $sectionMeta->getTableName();

        if (false === $schemaManager->tablesExist([$tableSection])) {
            $this->output->writeln(sprintf('<info>Creating table `%s`</info>', $tableSection));
            $schemaTool->createSchema(array($sectionMeta));
        } else {
            if (false === $this->overrideExisting) {
                return $this;
            }

            $this->output->writeln(sprintf('<info>Updating table `%s`</info>',$tableSection));
            $schemaTool->updateSchema(array($sectionMeta), true);
            $this->em->getConnection()->executeUpdate(sprintf('DELETE FROM %s WHERE 1=1', $tableSection));
        }

        $query = sprintf(
                'INSERT INTO %s (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ',
                $tableSection,
                $this->requiredFields['uid'],
                $this->requiredFields['root_uid'],
                $this->requiredFields['parent_uid'],
                $this->requiredFields['leftnode'],
                $this->requiredFields['rightnode'],
                $this->requiredFields['level'],
                $this->requiredFields['created'],
                $this->requiredFields['modified'],
                $sectionMeta->getSingleAssociationJoinColumnName('_page'),
                $this->requiredFields['site_uid']
        );
        
        $pageMeta = $this->em->getClassMetadata('BackBee\NestedNode\Page');
        $tablePage = $pageMeta->getTableName();

        $query .= sprintf('SELECT %s, %s, %s, %s, %s, %s, %s, %s, %s, %s FROM %s WHERE %s > %s + 1',
                $this->requiredFields['uid'],
                $this->requiredFields['root_uid'],
                $this->requiredFields['parent_uid'],
                $this->requiredFields['leftnode'],
                $this->requiredFields['rightnode'],
                $this->requiredFields['level'],
                $this->requiredFields['created'],
                $this->requiredFields['modified'],
                $this->requiredFields['uid'],
                $this->requiredFields['site_uid'],
                $tablePage,
                $this->requiredFields['rightnode'],
                $this->requiredFields['leftnode']
        );

        $result = $this->em->getConnection()->executeQuery($query);
        $this->em->getConnection()->executeUpdate('SET FOREIGN_KEY_CHECKS=1');

        $this->output->writeln(sprintf(' - %d section rows created', $result->rowCount()));

        return $this;
    }
1095717
private function setLangProperties()
    {
        if (empty($this->obElement) || !$this->obElement->isClassExtendedWith('RainLab.Translate.Behaviors.TranslatableModel')) {
            return;
        }

        //Check translate model property
        if (empty($this->obElement->translatable) || !is_array($this->obElement->translatable)) {
            return;
        }

        //Get active lang list from Translate plugin
        $arLangList = self::getActiveLangList();
        if (empty($arLangList)) {
            return;
        }

        //Process translatable fields
        foreach ($this->obElement->translatable as $sField) {
            //Check field name
            if (empty($sField) || (!is_string($sField) && !is_array($sField))) {
                continue;
            }

            if (is_array($sField)) {
                $sField = array_shift($sField);
            }

            if (!isset($this->arModelData[$sField]) || array_key_exists($sField, (array) $this->obElement->attachOne) || array_key_exists($sField, (array) $this->obElement->attachMany)) {
                continue;
            }

            //Save field value with different lang code
            foreach ($arLangList as $sLangCode) {
                $sLangField = $sField.'|'.$sLangCode;
                $sValue = $this->obElement->lang($sLangCode)->$sField;
                $this->setAttribute($sLangField, $sValue);
            }
        }
    }
1334214
def _save_translations(sender, instance, *args, **kwargs):
	
	
	# If we are in a site with one language there is no need of saving translations
	if site_is_monolingual():
		return False

	cls = sender

	# If its class has no "translatable_fields" then there are no translations
	if not hasattr(cls._meta, "translatable_fields"):
		return False

	# For each translatable field, get its value, computes its md5 and for each language creates its
	# empty translation.
	for field in cls._meta.translatable_fields:
		value = getattr(instance,field)
		if not value is None:
			md5_value = checksum(value)
			setattr( instance, u"md5"+field, md5_value )
			for lang in settings.LANGUAGES:
				lang = lang[0]
				# print "({0}!={1}) = {2}".format(lang, settings.LANGUAGE_CODE,lang!=settings.LANGUAGE_CODE)
				if lang != settings.LANGUAGE_CODE:
					context = u"Updating from object"
					if hasattr(instance, "trans_context"):
						context = getattr(instance, "trans_context")
					trans = FieldTranslation.update(instance, field, lang, context)
527718
def get_localized_field_name(context, field):
    """"""
    attrs = [
             translation.get_language(), 
             translation.get_language()[:2], 
             settings.LANGUAGE_CODE
            ]
            
    def predicate(x):
        field_name = get_real_fieldname(field, x)
        if hasattr(context, field_name):
            return field_name
        return None

    return first_match(predicate, attrs)
982589
def _get_translated_field_names(model_instance):
        
        hvad_internal_fields = ['id', 'language_code', 'master', 'master_id', 'master_id']
        translated_field_names = set(model_instance._translated_field_names) - set(hvad_internal_fields)
        return translated_field_names
642658
def _set_dict_translations(instance, dict_translations):
	

	# If class has no translatable fields get out
	if not hasattr(instance._meta, "translatable_fields"):
		return False

	# If we are in a site with one language there is no need of saving translations
	if site_is_monolingual():
		return False

	# Translatable fields
	translatable_fields = instance._meta.translatable_fields

	# For each translatable field and for each language (excluding default language), we have to see if there is
	# two dynamic fields:
	# - <attribute>_<language_code>: translated atribute in <language_code>.
	#   For example: name_fr, name_es, description_it, etc.
	# - <attribute>_is_fuzzy_<language_code>: is a provisional translation of <attribute> for language <language_code>.
	#   For example: name_is_fuzzy_fr, name_is_fuzzy_es, description_is_fuzzy_it, etc.
	for field in translatable_fields:
		for lang in settings.LANGUAGES:
			lang = lang[0]
			if lang != settings.LANGUAGE_CODE:
					
				# Translated field name
				trans_field = trans_attr(field,lang)
				# If translated field name is in the dict, we assign it to the object
				if dict_translations.has_key(trans_field):
					setattr(instance,trans_field,dict_translations[trans_field])
					
				# Is fuzzy attribute
				trans_isfuzzy = trans_is_fuzzy_attr(field,lang)
				# If "is fuzzy" name is in the dict, we assign it to the object
				if dict_translations.has_key(trans_isfuzzy):
					is_fuzzy_value = (dict_translations[trans_isfuzzy]=="1") or (dict_translations[trans_isfuzzy]==1)
					setattr(instance,trans_isfuzzy, is_fuzzy_value)
697475
def _translate_table(self, dest_dir, table_name, translations_writer):
        
        in_filename = os.path.join(self.src_dir, '%s.txt' % table_name)
        if not os.path.exists(in_filename):
            raise Exception('No %s' % table_name)

        out_filename = os.path.join(dest_dir, '%s.txt' % table_name)
        with open(in_filename, 'rb') as in_file:
            reader = csv.DictReader(in_file)
            if not reader.fieldnames or not any_translatable_field(
                    reader.fieldnames):
                print('Copying %s with no translatable columns' % table_name)
                shutil.copy(in_filename, out_filename)
                return 0
            table_translator = TableTranslator(
                table_name, reader.fieldnames, self.old_translations,
                translations_writer)
            with open(out_filename, 'w+b') as out_file:
                writer = csv.DictWriter(out_file, fieldnames=reader.fieldnames)
                writer.writeheader()
                for row in reader:
                    writer.writerow(table_translator.translate_row(row))

            table_translator.write_for_field_values()
            print('\ttranslation rows: %s' %
                  table_translator.total_translation_rows)
            return table_translator.total_translation_rows
54291
public void addTranslationDTO(String locale, String value, boolean outdated, boolean approximate) {
        translations.add(new TranslationDTO(locale, value, outdated, approximate));
    }
523049
public function addSimpleSelectFieldsAsAlias($field, $alias, $table = false): self
    {
        if (!$table) {
            $table = $this->getDbTableName();
        }
        // Translation field
        if (\in_array($field, $this->getTranslationFields(), true)) {
            ++$this->translation_join_count;
            $this->addJoinTable(['cms_translations', $this->getTranslationTableJoinAlias() . $this->translation_join_count], 'id', $field, 'LEFT', $table);

            $this->sql_select_fields[] = [
                'table' => $this->getTranslationTableJoinAlias() . $this->translation_join_count . '',
                'field' => $this->getLanguage(),
                'as'    => $alias,
                'type'  => TableStructure::FIELD_TYPE_TRANSLATION
            ];
        } else {
            $this->sql_select_fields[] = [
                'table' => $table,
                'field' => $field,
                'as'    => $alias,
                'type'  => 'simple'
            ];
        }

        return $this;
    }