def setUp(self): GettextBaseTest.setUp(self) with open(MMOFILE, 'rb') as fp: try: self.t = gettext.GNUTranslations(fp) except: self.tearDown() raise
def test_plural_forms2(self): eq = self.assertEqual with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) x = t.ngettext('There is %s file', 'There are %s files', 1) eq(x, 'Hay %s fichero') x = t.ngettext('There is %s file', 'There are %s files', 2) eq(x, 'Hay %s ficheros')
def test_lgettext_2(self): with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) lgettext = t.lgettext with self.assertDeprecated('lgettext'): self.assertEqual(lgettext('mullusk'), b'bacon') with self.assertDeprecated('lgettext'): self.assertEqual(lgettext('spam'), b'spam')
def setUp(self): GettextBaseTest.setUp(self) fp = open(UMOFILE, 'rb') try: self.t = gettext.GNUTranslations(fp) finally: fp.close() self._ = self.t.ugettext
def setUp(self): GettextBaseTest.setUp(self) fp = open(UMOFILE, 'rb') try: self.t = gettext.GNUTranslations(fp) #because bug in line 77 finally: fp.close() self._ = self.t.ugettext # because line 308 didn't run
def test_merge_gnutranslations_not_translations(self): import gettext t = gettext.GNUTranslations() t._catalog = {'a': 'b'} inst = self._makeOne() inst.merge(t) self.assertEqual(inst._catalog['a'], 'b')
def test_usability(pofile): # Use polib to write a mofile with tempfile.NamedTemporaryFile(mode="w+b") as mofile: pofile = polib.pofile(pofile) pofile.save_as_mofile(mofile.name) # Try to open it _t = gettext.GNUTranslations(fp=mofile)
def translation(messages_dir, languages = None): """Load the translation for the user's language and return a function which translates a string into its unicode equivalent.""" mofile = find(messages_dir, languages) if not mofile: return lambda x: x import gettext return gettext.GNUTranslations(file(mofile)).ugettext
def set_translation(service, lang): """ Set current translation to lang """ global _ugettext if lang != "en": # Check .mo file mo_path = "services/%s/translations/%s/LC_MESSAGES/messages.mo" % (service, lang) if os.path.exists(mo_path): logger.info("Setting '%s' translation", mo_path) with open(mo_path, mode="rb") as f: if six.PY3: _ugettext = gettext.GNUTranslations(f).lgettext else: _ugettext = gettext.GNUTranslations(f).ugettext else: logger.info("No translation for language '%s'. Using 'en' instead", lang)
def setTranslations(): global gt if gt: return else: file = open(mofile, "rb") if file: gt = gettext.GNUTranslations(file) return
def test_bad_major_version(self): with open(MOFILE_BAD_MAJOR_VERSION, 'rb') as fp: with self.assertRaises(OSError) as cm: gettext.GNUTranslations(fp) exception = cm.exception self.assertEqual(exception.errno, 0) self.assertEqual(exception.strerror, "Bad version number 5") self.assertEqual(exception.filename, MOFILE_BAD_MAJOR_VERSION)
def get_translations(language): mo_filename = os.path.join(os.path.dirname(__file__), 'translations_dir', language + '.mo') if os.path.exists(mo_filename): mo_file = open(mo_filename, 'rb') translations = gettext.GNUTranslations(mo_file) mo_file.close() return translations return None
def init_translator(self): ctx = get_ctx() if not ctx: self.translator = gettext.GNUTranslations() return super(TemplateTranslator, self).__init__() if not self.__lastlang == ctx.locale: self.__lastlang = ctx.locale self.translator = gettext.translation("contents", join(self.i18npath, '_compiled'), languages=[ctx.locale], fallback=True)
def get_language(lang): """Get the GNUTranslations instance of a specific language""" path = pkg_resources.resource_filename("botogram", "i18n/%s.mo" % lang) if not os.path.exists(path): raise ValueError('Language "%s" is not supported by botogram' % lang) with open(path, "rb") as f: gt = gettext.GNUTranslations(f) return gt
def _translator(domain): filename = EngineUtils.joinResMgrPath('text/lc_messages', domain + '.mo') content = EngineUtils.getResMgrBinaryFileContent(filename) if content is None: raise IOError(errno.ENOENT, 'no translation file found for domain', domain) with TranslationFile(content, filename) as fakefile: translation = gettext.GNUTranslations(fakefile) return translation
def open_translations( locale: str, directory_path: str) -> Optional[gettext.GNUTranslations]: try: with open( os.path.join(directory_path, 'locale', locale.replace('-', '_'), 'LC_MESSAGES', 'betty.mo'), 'rb') as f: return gettext.GNUTranslations(f) except FileNotFoundError: return None
def test_lgettext_output_encoding(self): with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) lgettext = t.lgettext with self.assertDeprecated('set_output_charset'): t.set_output_charset('utf-16') with self.assertDeprecated('lgettext'): self.assertEqual(lgettext('mullusk'), 'bacon'.encode('utf-16')) with self.assertDeprecated('lgettext'): self.assertEqual(lgettext('spam'), 'spam'.encode('utf-16'))
def start(self): result = True self.help_file = self.app_name + '.htb' #SETUP LANGUAGE lang_catalog = getdefaultlocale()[0] list_trans = [] current_trans = -1 i = 0 self.wx_coding = 'ansi' if wx.USE_UNICODE: self.wx_coding = 'unicode' if os.path.exists('lang/%s'%lang_catalog): for dir_name in os.listdir('lang'): if os.path.exists('lang/%s/%s_%s.mo'%(dir_name, self.app_name, self.wx_coding)): if dir_name == lang_catalog: current_trans = i self.help_file = 'lang/' + dir_name + '/'+ self.help_file list_trans.append(gettext.GNUTranslations(open('lang/%s/%s_%s.mo'%(dir_name, self.app_name, self.wx_coding), 'rb'))) i += 1 if len(list_trans) > 0: try: list_trans[current_trans].install(unicode = wx.USE_UNICODE) except: print print_error() if current_trans == -1: trans = gettext.NullTranslations() trans.install(unicode = wx.USE_UNICODE) # SETUP WX LANGUAGE TRANSLATION TO OS DEFAULT LANGUAGE # WX DIRECTORY MUST BE TO CONTAIN LANG DIRECTORY self.locale = wx.Locale(wx.LANGUAGE_DEFAULT) # CHECK EXISTS INSTANCE name_user = wx.GetUserId() name_instance = self.app_name + '::' self.instance_checker = wx.SingleInstanceChecker(name_instance + name_user) if self.instance_checker.IsAnotherRunning(): wx.MessageBox(_('Software is already running.'), _('Warning')) return False # CREATE HTML HELP CONTROLLER wx.FileSystem.AddHandler(wx.ZipFSHandler()) self.help_controller = HtmlHelpController() if os.path.exists(self.help_file): self.help_controller.AddBook(self.help_file) #ABOUT APPLICATION self.developers = [_('Max Kolosov')] self.copyright = _('(C) 2009 Max Kolosov') self.web_site = ('http://vosolok2008.narod.ru', _('Home page')) self.email = ('mailto:[email protected]', _('email for feedback')) self.license = _('BSD license') self.about_description = _('wxPython bass music player.') #CREATE MAIN FRAME self.main_frame = main_frame(None, wx.ID_ANY, self.app_name, app = self) self.SetTopWindow(self.main_frame) self.main_frame.Show() return result
def test_lazy_translated(): # prepare translations T = gettext.GNUTranslations() T._catalog = {'invitation': 'invitaci\xf3n'} _ = T.gettext msg = Message(html='...', subject=lazy_string(_, 'invitation')) assert decode_header(msg.as_message()['subject']) == _('invitation') msg = Message(html='...', subject='invitaci\xf3n') assert decode_header(msg.as_message()['subject']) == 'invitaci\xf3n'
def install(self, lang): if self.translation.has_key(lang): if not self.translation[lang].transobj: self.translation[ lang].transobj = obj = gettext.GNUTranslations( file(self.translation[lang].mofile, 'rb')) func = self.translation[lang].transobj.ugettext else: obj = gettext.NullTranslations() func = obj.ugettext return func
def __init__(self): self.translators = { locale: gettext.GNUTranslations( open( gettext.find(GETTEXT_DOMAIN, GETTEXT_DIR, languages=[locale]), 'rb')) for locale in available_locales.keys() if locale != 'pt_BR' # No translation file for en_US } self.locale_stack = list()
def getTranslation(language): global g_Translations if language not in g_Translations: filename = os.path.join(sys.path[0], 'assets', 'locales', language, 'plexconnect.mo') try: fp = open(filename, 'rb') g_Translations[language] = gettext.GNUTranslations(fp) fp.close() except IOError: g_Translations[language] = gettext.NullTranslations() return g_Translations[language]
def setup(self, language: str) -> None: mofile = gettext.find("monkq", locale_dir, [language]) if mofile is None: warn("monkq doesn't support the language {}. It would use English". format(language)) self._translation = gettext.NullTranslations() else: self._fp = open(mofile, 'rb') self._translation = gettext.GNUTranslations( self._fp) # type: ignore self._fp.close()
def setUp(self): GettextBaseTest.setUp(self) fp = open(MMOFILE, 'rb') try: try: self.t = gettext.GNUTranslations(fp) except: self.tearDown() raise finally: fp.close()
def __init__(self, course, taskid, content, task_fs, translations_fs, hook_manager, task_problem_types): """ Init the task. course is a Course object, taskid the task id, and content is a dictionnary containing the data needed to initialize the Task object. If init_data is None, the data will be taken from the course tasks' directory. """ self._course = course self._taskid = taskid self._fs = task_fs self._hook_manager = hook_manager self._data = content self._environment = self._data.get('environment', None) # Response is HTML self._response_is_html = self._data.get("responseIsHTML", False) # Limits self._limits = {"time": 20, "memory": 1024, "disk": 1024} if "limits" in self._data: try: self._limits['time'] = int(self._data["limits"].get("time", 20)) self._limits['hard_time'] = int(self._data["limits"].get("hard_time", 3 * self._limits['time'])) self._limits['memory'] = int(self._data["limits"].get("memory", 1024)) self._limits['disk'] = int(self._data["limits"].get("disk", 1024)) if self._limits['time'] <= 0 or self._limits['hard_time'] <= 0 or self._limits['memory'] <= 0 or self._limits['disk'] <= 0: raise Exception("Invalid limit") except: raise Exception("Invalid limit") if "problems" not in self._data: raise Exception("Tasks must have some problems descriptions") # Network access in grading container? self._network_grading = self._data.get("network_grading", False) # i18n self._translations = {} if not translations_fs: translations_fs = task_fs.from_subfolder("$i18n") if translations_fs.exists(): for f in translations_fs.list(folders=False, files=True, recursive=False): lang = f[0:len(f) - 3] if translations_fs.exists(lang + ".mo"): self._translations[lang] = gettext.GNUTranslations(translations_fs.get_fd(lang + ".mo")) else: self._translations[lang] = gettext.NullTranslations() # Check all problems self._problems = [] for problemid in self._data['problems']: self._problems.append(self._create_task_problem(problemid, self._data['problems'][problemid], task_problem_types)) # Order self._order = int(self._data.get('order', -1))
def test_lngettext_2(self): with open(self.mofile, 'rb') as fp: t = gettext.GNUTranslations(fp) lngettext = t.lngettext x = lngettext('There is %s file', 'There are %s files', 1) self.assertEqual(x, b'Hay %s fichero') x = lngettext('There is %s file', 'There are %s files', 2) self.assertEqual(x, b'Hay %s ficheros') x = lngettext('There is %s directory', 'There are %s directories', 1) self.assertEqual(x, b'There is %s directory') x = lngettext('There is %s directory', 'There are %s directories', 2) self.assertEqual(x, b'There are %s directories')
def test_ignore_comments_in_headers_issue36239(self): """Checks that comments like: #-#-#-#-# messages.po (EdX Studio) #-#-#-#-# are ignored. """ with open(MOFILE, 'wb') as fp: fp.write(base64.decodebytes(GNU_MO_DATA_ISSUE_17898)) with open(MOFILE, 'rb') as fp: t = gettext.GNUTranslations(fp) self.assertEqual(t.info()["plural-forms"], "nplurals=2; plural=(n != 1);")
def test_the_alternative_interface(self): eq = self.assertEqual # test the alternative interface fp = open(self.mofile, 'rb') t = gettext.GNUTranslations(fp) fp.close() # Install the translation object t.install() eq(_('nudge nudge'), 'wink wink') # Try unicode return type t.install(unicode=True) eq(_('mullusk'), 'bacon')
def init_localization(): '''prepare l10n''' locale.setlocale(locale.LC_ALL, '') filename = "meocloud_mo/%s.mo" % locale.getlocale()[0][0:2] path = os.path.join(os.path.dirname(os.path.realpath(__file__)), filename) try: trans = gettext.GNUTranslations(open(path, "rb")) except IOError: trans = gettext.NullTranslations() trans.install()
def init_internationalization(): ''' prepare l10n ''' filename = "res/Macsen_%s.mo" % macsen_language try: trans = gettext.GNUTranslations(open(filename, "rb")) except IOError: print("Locale %s not found. Will use default locale strings" % macsen_language) trans = gettext.NullTranslations() trans.install()