below for adding new locale to an existing translation
426256
def create_for_locale
      field_key = FieldKey.find_by_global_key(params[:i18n_key])
      phrase = I18n::Backend::ActiveRecord::Translation.find_or_create_by(
        key: field_key.global_key,
      locale: params[:locale]
)
      unless phrase.value.present?
        I18n.backend.reload!
        phrase.value = params[:i18n_value]
        phrase.save!
      end
      render json: { success: true }
    end
169027
private void sendTranslationUpdate(String translation, String locale, boolean outdated) throws JSONException {
        JSONObject jsonTranslationValueObject = new JSONObject();
        jsonTranslationValueObject.put("translation", translation);
        jsonTranslationValueObject.put("outdated", outdated);
        jsonTranslationValueObject.put("locale", locale);
        jsonTranslationValueObject.put("approx", true);
        jsonTranslation.put("target", jsonTranslationValueObject);

        // Translate in english
        httpPut("translations/" + locale + "/" + keyName, jsonTranslation.toString());
    }
416958
def help_center_section_translation_update(self, section_id, locale, data, **kwargs):
        ""
        api_path = "/api/v2/help_center/sections/{section_id}/translations/{locale}.json"
        api_path = api_path.format(section_id=section_id, locale=locale)
        return self.call(api_path, method="PUT", data=data, **kwargs)
172157
def v2_translator(self, option):
        
        new_option = option
        new_value = getattr(self, option)

        renaming_pairs = {
            "dontfrag": "dont_fragment",
            "maxhops": "max_hops",
            "firsthop": "first_hop",
            "use_NSID": "set_nsid_bit",
            "cd": "set_cd_bit",
            "do": "set_do_bit",
            "qbuf": "include_qbuf",
            "recursion_desired": "set_rd_bit",
            "noabuf": "include_abuf"
        }
        if option in renaming_pairs.keys():
            warninglog = (
                "DeprecationWarning: {0} option has been deprecated and "
                "renamed to {1}."
            ).format(option, renaming_pairs[option])
            print(warninglog)
            new_option = renaming_pairs[option]

        # noabuf was changed to include_abuf so we need a double-negative
        if option == "noabuf":
            new_value = not new_value

        return new_option, new_value
376337
function () {
          for (var key in translationIds) {
            if (translationIds.hasOwnProperty(key) && translationIds[key] !== undefined) {
              updateTranslation(key, translationIds[key], scope, scope.interpolateParams, scope.defaultText, scope.translateNamespace);
            }
          }
        }
1346017
function addTextLocale(locale, body, options = {}) {
  const gt = new Gettext();
  const domain = 'messages';
  const {
    filter,
    gettextDefaultCharset = 'UTF-8',
  } = options;

  if (body.length > 0) {
    gt.addTranslations(locale, domain, po.parse(body, gettextDefaultCharset));
  }

  if (filter) {
    const filterAsync = Promise.promisify(filter);
    return filterAsync(gt, locale);
  }

  return Promise.resolve(gt.catalogs[locale] && gt.catalogs[locale][domain].translations);
}
619061
def clean_translated_locales(configuration, langs=None):
    
    if not langs:
        langs = configuration.translated_locales
    for locale in langs:
        clean_locale(configuration, locale)
114124
public function actionUpdate()
    {
        
        $this->outVerbose("Updating language '" . $this->options['language'] . "' for extension '" . $this->options['extension'] . "'...");
        $sortingMethod = tao_helpers_translation_TranslationFile::SORT_ASC_I;
        
       	// Get virgin translations from the source code and manifest.
       	$filePaths = array();
        foreach (self::$WHITE_LIST as $subFolder) {
            $filePaths[] = $this->options['input'] . DIRECTORY_SEPARATOR. $subFolder;
        }
        
       	$extensions = array('php', 'tpl', 'js', 'ejs');
       	$sourceCodeExtractor = new tao_helpers_translation_SourceCodeExtractor($filePaths, $extensions);
       	$sourceCodeExtractor->extract();
    	
       	$translationFile = new tao_helpers_translation_POFile();
        $translationFile->setSourceLanguage(tao_helpers_translation_Utils::getDefaultLanguage());
        $translationFile->setTargetLanguage($this->options['language']);
       	$translationFile->addTranslationUnits($sourceCodeExtractor->getTranslationUnits());
       	
        $file = MenuService::getStructuresFilePath($this->options['extension']);
        if (!is_null($file)) {
            $structureExtractor = new tao_helpers_translation_StructureExtractor(array($file));
           	$structureExtractor->extract();
            $structureUnits = $structureExtractor->getTranslationUnits();
            $this->outVerbose(count($structureUnits) . ' units extracted from structures.xml.');
            $translationFile->addTranslationUnits($structureUnits);
        }

       	// For each TU that was recovered, have a look in an older version
       	// of the translations.
       	$oldFilePath = $this->buildLanguagePath($this->options['extension'], $this->options['language']) . '/' .self::DEF_PO_FILENAME;
       	$translationFileReader = new tao_helpers_translation_POFileReader($oldFilePath);
       	$translationFileReader->read();
       	$oldTranslationFile = $translationFileReader->getTranslationFile();
       	
       	foreach ($oldTranslationFile->getTranslationUnits() as $oldTu) {
       		if (($newTu = $translationFile->getBySource($oldTu)) !== null && $oldTu->getTarget() != '') {
       			// No duplicates in TFs so I simply add it whatever happens.
       			// If it already has the same one, it means we will update it.
       			$newTu->setTarget($oldTu->getTarget());
       		}
       	}
        
       	$sortedTranslationFile = new tao_helpers_translation_POFile();
        $sortedTranslationFile->setSourceLanguage($translationFile->getSourceLanguage());
        $sortedTranslationFile->setTargetLanguage($translationFile->getTargetLanguage());
       	$sortedTranslationFile->addTranslationUnits($translationFile->sortBySource($sortingMethod));
       	$this->preparePOFile($sortedTranslationFile, true);
       	
       	// Write the new ones.
       	$poFileWriter = new tao_helpers_translation_POFileWriter($oldFilePath, $sortedTranslationFile);
       	$poFileWriter->write();
        $this->outVerbose("PO translation file '" . basename($oldFilePath) . "' in '" . $this->options['language'] . "' updated for extension '" . $this->options['extension'] . "'.");

		$translatableProperties = array(OntologyRdfs::RDFS_LABEL, OntologyRdfs::RDFS_COMMENT);

		// We now deal with RDF models.
        foreach ($this->getOntologyFiles() as $f){
                // Loop on 'master' models.
				$translationFile = $this->extractPoFileFromRDF($f, $translatableProperties);

                // The slave RDF file is the translation of the ontology that we find in /extId/Locales/langCode.
                $slavePOFilePath = $this->buildLanguagePath($this->options['extension'], $this->options['language']) . '/' . $this->getOntologyPOFileName($f);
                if (file_exists($slavePOFilePath)){
                    // Read the existing RDF Translation file for this RDF model.
                    $poReader = new tao_helpers_translation_POFileReader($slavePOFilePath);
                    $poReader->read();
                    $slavePOFile = $poReader->getTranslationFile();
                    
                    // Try to update translation units found in the master PO file with
                    // targets found in the old translation of the ontology.
                    foreach ($slavePOFile->getTranslationUnits() as $oTu){
                        $translationFile->addTranslationUnit($oTu);
                    }
                    
                    // Remove Slave PO file. It will be overwritten by the modified Master PO file.
                    tao_helpers_File::remove($slavePOFilePath);
                }
                
                // Write Master PO file as the new Slave PO file.
                $rdfWriter = new tao_helpers_translation_POFileWriter($slavePOFilePath, $translationFile);
                $rdfWriter->write();
                $this->outVerbose("Translation model {$this->getOntologyPOFileName($f)}  in '" . $this->options['language'] . "' updated for extension '" . $this->options['extension'] . "'.");
        }
        
       	$this->outVerbose("Language '" . $this->options['language'] . "' updated for extension '" . $this->options['extension'] . "'.");
        
    }
396842
def _new_gnu_trans(self, localedir, use_null_fallback=True):
        
        use_null_fallback = False
        return gettext_module.translation(
            domain=self.domain,
            localedir=localedir,
            languages=[self.language],
            codeset='utf-8',
            fallback=use_null_fallback)
1245331
function setLocale(newLocale) {
      this.locale = newLocale;
      var invertedObjs = tia.cU.invertMapObj(newLocale);

      this.invertedLocaleFirstKey = invertedObjs.invertedMapFirstKey;
      this.invertedLocaleAllKeys = invertedObjs.invertedMapAllKeys;

      return {
        locale: this.locale,
        invertedLocaleFirstKey: invertedObjs.invertedMapFirstKey,
        invertedLocaleAllKeys: invertedObjs.invertedMapAllKeys,
      };
    }
1329784
private String replaceMacros(String msg, String contentLocale) {

        CmsMacroResolver resolver = CmsMacroResolver.newInstance();
        resolver.addMacro(MACRO_DECORATION, m_decoration);
        resolver.addMacro(MACRO_DECORATIONKEY, m_decorationKey);
        if (m_locale != null) {
            resolver.addMacro(MACRO_LOCALE, m_locale.toString());
            if (!contentLocale.equals(m_locale.toString())) {
                resolver.addMacro(MACRO_LANGUAGE, "lang=\"" + m_locale.toString() + "\"");
            }
        }

        return resolver.resolveMacros(msg);
    }
1085719
public static function add(array $translates, string $locale = null) : void
    {
        $locale = ($locale === null) ? I18n::$locale : $locale;

        if (isset(I18n::$dictionary[$locale])) {
            I18n::$dictionary[$locale] += $translates;
        } else {
            I18n::$dictionary[$locale] = $translates;
        }
    }
643002
function translate(key, options, hasOwnOptions) {

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

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

			if (!t) {
				translations[lng][key] = key;
			} else if (!translations[lng][key] || hasOwnOptions) {
				translations[lng][key] = t(key, options);
			}

		}
569931
function REPLACE_LOCALE(state, payload) {
      // reduce the given translations to a single-depth tree
      var translations = flattenTranslations(payload.translations); // replace the translations entirely

      state.translations[payload.locale] = translations; // make sure to notify vue of changes (this might break with new vue versions)

      try {
        if (state.translations.__ob__) {
          state.translations.__ob__.dep.notify();
        }
      } catch (ex) {}
    }
954438
def add_translations(
        self, module_name, translations_dir="translations", domain="messages"
    ):
        
        module = importlib.import_module(module_name)
        for path in (Path(p, translations_dir) for p in module.__path__):
            if not (path.exists() and path.is_dir()):
                continue

            if not os.access(str(path), os.R_OK):
                self.app.logger.warning(
                    "Babel translations: read access not allowed {}, skipping."
                    "".format(repr(str(path).encode("utf-8")))
                )
                continue

            self._translations_paths.append((str(path), domain))
183485
public void actionChangeElementLanguage() {

        // save eventually changed content of the editor
        Locale oldLocale = CmsLocaleManager.getLocale(getParamOldelementlanguage());
        Locale newLocale = getElementLocale();
        try {
            setEditorValues(oldLocale);
            if (!m_content.validate(getCms()).hasErrors(oldLocale)) {
                // no errors found in content
                if (!m_content.hasLocale(newLocale)) {
                    // check if we should copy the content from a default locale
                    boolean addNew = true;
                    List<Locale> locales = OpenCms.getLocaleManager().getDefaultLocales(getCms(), getParamResource());
                    if (locales.size() > 1) {
                        // default locales have been set, try to find a match
                        try {
                            m_content.copyLocale(locales, newLocale);
                            addNew = false;
                        } catch (CmsXmlException e) {
                            // no matching default locale was available, we will create a new one later
                        }
                    }
                    if (addNew) {
                        // create new element if selected language element is not present
                        try {
                            m_content.addLocale(getCms(), newLocale);
                        } catch (CmsXmlException e) {
                            if (LOG.isErrorEnabled()) {
                                LOG.error(e.getLocalizedMessage(), e);
                            }
                        }
                    }
                }
                //save to temporary file
                writeContent();
                // set default action to suppress error messages
                setAction(ACTION_DEFAULT);
            } else {
                // errors found, switch back to old language to show errors
                setParamElementlanguage(getParamOldelementlanguage());
                // set stored locale to null to reinitialize it
                m_elementLocale = null;
            }
        } catch (Exception e) {
            // should usually never happen
            if (LOG.isInfoEnabled()) {
                LOG.info(e.getLocalizedMessage(), e);
            }
        }
    }
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"))