[START translate_translate_text_with_glossary_beta]
327881
static TranslateTextResponse translateTextWithGlossary(
      String projectId,
      String location,
      String name,
      String text,
      String sourceLanguageCode,
      String targetLanguageCode) {
    try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {

      LocationName locationName =
          LocationName.newBuilder().setProject(projectId).setLocation(location).build();
      GlossaryName glossaryName =
          GlossaryName.newBuilder()
              .setProject(projectId)
              .setLocation(location)
              .setGlossary(name)
              .build();
      TranslateTextGlossaryConfig translateTextGlossaryConfig =
          TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build();
      TranslateTextRequest translateTextRequest =
          TranslateTextRequest.newBuilder()
              .setParent(locationName.toString())
              .setMimeType("text/plain")
              .setSourceLanguageCode(sourceLanguageCode)
              .setTargetLanguageCode(targetLanguageCode)
              .addContents(text)
              .setGlossaryConfig(translateTextGlossaryConfig)
              .build();

      // Call the API
      TranslateTextResponse response = translationServiceClient.translateText(translateTextRequest);
      System.out.format(
          "Translated text: %s", response.getTranslationsList().get(0).getTranslatedText());
      return response;

    } catch (Exception e) {
      throw new RuntimeException("Couldn't create client.", e);
    }
  }
459832
def translate_links(self, text, in_comment=None):
        
        def replace_link(matchobj):
            ref = matchobj.group(1)
            return '<a href = "%s">%s</a>' % (
                    self.translate_ref_to_url(ref, in_comment), ref)
        return re.sub('{@link ([\w#]+)}', replace_link, text)
979998
def translation_for(key, lang)
      self.translations.find_or_initialize_by(translation_key_id: key.id, lang: lang.to_s, translator_type: self.class.name)
    end
530324
def get_strings_to_translate(self, po):
        
        strings = []
        for index, entry in enumerate(po):
            if not self.need_translate(entry):
                continue
            strings.append(humanize_placeholders(entry.msgid))
            if entry.msgid_plural:
                strings.append(humanize_placeholders(entry.msgid_plural))
        return strings
723987
def sofia_process_text():
    """"""
    if request.method == 'OPTIONS':
        return {}
    response = request.body.read().decode('utf-8')
    body = json.loads(response)
    text = body.get('text')
    auth = body.get('auth')
    sp = sofia.process_text(text, auth=auth)
    return _stmts_from_proc(sp)
52423
def translate(source, dictionary):
    '''
    '''
    toks = tokenize.generate_tokens(StringIO(source).readline)
    result = []
    for toktype, tokvalue, _, _, _ in toks:
        if toktype == tokenize.NAME and tokvalue in dictionary:
            result.append((toktype, dictionary[tokvalue]))
        else:
            result.append((toktype, tokvalue))
    return tokenize.untokenize(result)
1304807
function(str, lex) {
  if (lex) {
    w.plugin({
      words: lex
    });
  }
  let doc = buildText(str, w);
  doc.tagger();
  return doc;
}
1300921
def translate(self):
        """"""
        expressions, varnames, funcnames = self.expr.translate()

        argnames = []
        for varname in varnames:
            argnames.append(VARIABLE_PREFIX + varname)
        for funcname in funcnames:
            argnames.append(FUNCTION_PREFIX + funcname)

        func = compile_func(
            argnames,
            [ast.Return(ast.List(expressions, ast.Load()))],
        )

        def wrapper_func(values={}, functions={}):
            args = {}
            for varname in varnames:
                args[VARIABLE_PREFIX + varname] = values[varname]
            for funcname in funcnames:
                args[FUNCTION_PREFIX + funcname] = functions[funcname]
            parts = func(**args)
            return u''.join(parts)

        return wrapper_func
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))
1159387
def _translate_symbols(string):
    """"""
    res = []
    string = str(string)
    for s in re.split(r'(\W+)', string, flags=re.UNICODE):
        tex_str = _GREEK_DICTIONARY.get(s)
        if tex_str:
            res.append(tex_str)
        elif s.lower() in _GREEK_DICTIONARY:
            res.append(_GREEK_DICTIONARY[s])
        else:
            res.append(s)
    return "".join(res)
1099977
function translate(d) {
    return function (signatureItems, identInfo, comments) {
        var plurals = signatureItems[0], factor = signatureItems[2], _a = signatureItems[4], args = _a === void 0 ? null : _a;
        // Checks
        if (!factor || !utils_1.isValidQuantifier(factor)) {
            _1.panic('_nt: parameter #1 (factor) should be a numeric literal, value or expression', identInfo);
            return;
        }
        if (!plurals || plurals.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
            _1.panic('_nt: parameter #0 (plurality strings) should be an array literal', identInfo);
            return;
        }
        var list = utils_1.getArrayListNode(plurals);
        if (!list) {
            _1.panic('_nt: parameter #0 (plurality strings) should be an array literal', identInfo);
            return;
        }
        var _b = utils_1.getArrayListElements(list), items = _b.items, strings = _b.strings;
        if (items.length !== strings.length) {
            _1.panic('_nt: parameter #0 (plurality strings) should contain only strings', identInfo);
            return;
        }
        if (!utils_1.validatePluralPlaceholders(args, strings)) {
            // TODO check %n match also, what if %1 then %5 in string?
            _1.panic('_nt: optional arguments count mismatch', identInfo);
            return;
        }
        // All ok, add to dict
        var entry = {
            type: 'plural',
            entry: [strings[0], strings[strings.length - 1]],
            occurences: [],
            translations: [],
            comments: comments
        };
        var key = utils_1.makeKey(entry);
        utils_1.addToDict(d, key, entry, identInfo);
    };
}
699829
def translate_book(translators=(HyperlinkStyleCorrector().translate, translate_line_footnotes),
                   book_dir=BOOK_PATH, dest=None, include_tags=None,
                   ext='.nlpiabak', skip_untitled=True):
    
    if callable(translators) or not hasattr(translators, '__len__'):
        translators = (translators,)

    sections = get_tagged_sections(book_dir=book_dir, include_tags=include_tags)
    file_line_maps = []

    for fileid, (filepath, tagged_lines) in enumerate(sections):
        logger.info('filepath={}'.format(filepath))
        destpath = filepath
        if not dest:
            copyfile(filepath, filepath + '.' + ext.lstrip('.'))
        elif os.path.sep in dest:
            destpath = os.path.join(dest, os.path.basename(filepath))
        else:
            destpath = os.path.join(os.path.dirname(filepath), dest, os.path.basename(filepath))
        ensure_dir_exists(os.path.dirname(destpath))
        with open(destpath, 'w') as fout:
            logger.info('destpath={}'.format(destpath))
            for lineno, (tag, line) in enumerate(tagged_lines):
                if (include_tags is None or tag in include_tags or
                        any((tag.startswith(t) for t in include_tags))):
                    for translate in translators:
                        new_line = translate(line)  # TODO: be smarter about writing to files in-place
                        if line != new_line:
                            file_line_maps.append((fileid, lineno, filepath, destpath, line, new_line))
                            line = new_line
                fout.write(line)
    return file_line_maps
1316616
def babelfy(self, text, params=None):
        
        self._entities = list()
        self._all_entities = list()
        self._merged_entities = list()
        self._all_merged_entities = list()
        self._text = " ".join(word.strip() for word in text.split())

        params = params or self._params
        params['key'] = self._api_key
        params['text'] = self._text
        if (sys.version < '3' and isinstance(params['text'], unicode)) or (sys.version >= '3' and isinstance(params['text'], bytes)): #pylint: disable=undefined-variable
            params['text'] = params['text'].encode('utf-8')
        url = BABELFY_API_URL + '?' + urlencode(params)

        request = Request(url)
        request.add_header('Accept-encoding', 'gzip')
        response = urlopen(request)
        if sys.version < '3':
            buf = StringIO(response.read())
        else:
            buf = BytesIO(response.read())
        f = gzip.GzipFile(fileobj=buf)
        reader = codecs.getreader('utf-8')
        self._data = json.load(reader(f))
94108
def _get_translate():
    
    translate = {}
    model_path = pkg_resources.resource_filename('hwrt', 'misc/')
    translation_csv = os.path.join(model_path, 'latex2writemathindex.csv')
    arguments = {'newline': '', 'encoding': 'utf8'}
    with open(translation_csv, 'rt', **arguments) as csvfile:
        contents = csvfile.read()
    lines = contents.split("\n")
    for csvrow in lines:
        csvrow = csvrow.split(',')
        if len(csvrow) == 1:
            writemathid = csvrow[0]
            latex = ""
        else:
            writemathid, latex = csvrow[0], csvrow[1:]
            latex = ','.join(latex)
        translate[latex] = writemathid
    return translate
1107272
def translate(self, closed_regex=True):
        
        """
        if closed_regex:
            return self.regex
        else:
            return translate(self.pattern, closed_regex=False, **self.flags)
214032
def pgettext(self, context, string, domain=None, **variables):
        """"""
        t = self.get_translations(domain)
        return t.upgettext(context, string) % variables
839925
function (translationId, interpolateParams, Interpolator, defaultTranslationText, sanitizeStrategy) {
      // Start with the fallbackLanguage with index 0
      return resolveForFallbackLanguage((startFallbackIteration > 0 ? startFallbackIteration : fallbackIndex), translationId, interpolateParams, Interpolator, defaultTranslationText, sanitizeStrategy);
    }