def _get_submissions(course_factory, submission_manager, user_manager, translations, courseid, taskid, with_input, submissionid=None): """ Helper for the GET methods of the two following classes """ try: course = course_factory.get_course(courseid) except: raise APINotFound("Course not found") if not user_manager.course_is_open_to_user(course, lti=False): raise APIForbidden("You are not registered to this course") try: task = course.get_task(taskid) except: raise APINotFound("Task not found") if submissionid is None: submissions = submission_manager.get_user_submissions(task) else: try: submissions = [submission_manager.get_submission(submissionid)] except: raise APINotFound("Submission not found") if submissions[0]["taskid"] != task.get_id( ) or submissions[0]["courseid"] != course.get_id(): raise APINotFound("Submission not found") output = [] for submission in submissions: submission = submission_manager.get_feedback_from_submission( submission, show_everything=user_manager.has_staff_rights_on_course( course, user_manager.session_username()), translation=translations.get(user_manager.session_language(), gettext.NullTranslations())) data = { "id": str(submission["_id"]), "submitted_on": str(submission["submitted_on"]), "status": submission["status"], "is_late_submission": submission.get("is_late_submission", False) } if with_input: data["input"] = submission_manager.get_input_from_submission( submission, True) # base64 encode file to allow JSON encoding for d in data["input"]: if isinstance(d, dict) and d.keys() == {"filename", "value"}: d["value"] = base64.b64encode(d["value"]).decode("utf8") if submission["status"] == "done": data["grade"] = submission.get("grade", 0) data["result"] = submission.get("result", "crash") data["feedback"] = submission.get("text", "") data["problems_feedback"] = submission.get("problems", {}) output.append(data) return 200, output
def get_feedback_from_submission(self, submission, only_feedback=False, show_everything=False, translation=gettext.NullTranslations()): """ Get the input of a submission. If only_input is False, returns the full submissions with a dictionnary object at the key "input". Else, returns only the dictionnary. If show_everything is True, feedback normally hidden is shown. """ if only_feedback: submission = {"text": submission.get("text", None), "problems": dict(submission.get("problems", {}))} if "text" in submission: submission["text"] = ParsableText(submission["text"], submission["response_type"], show_everything, translation).parse() if "problems" in submission: for problem in submission["problems"]: if isinstance(submission["problems"][problem], str): # fallback for old-style submissions submission["problems"][problem] = (submission.get('result', 'crash'), ParsableText(submission["problems"][problem], submission["response_type"], show_everything, translation).parse()) else: # new-style submission submission["problems"][problem] = (submission["problems"][problem][0], ParsableText(submission["problems"][problem][1], submission["response_type"], show_everything, translation).parse()) return submission
# CODE IS POETRY import os, gtk, sys, gettext, locale from canaimasemilla.main import Main from canaimasemilla.constructor import UserMessage from canaimasemilla.translator import MAIN_ROOT_ERROR_TITLE, MAIN_ROOT_ERROR_MSG from canaimasemilla.config import * gtk.gdk.threads_init() if __name__ == "__main__": settinglocale = locale.setlocale(locale.LC_ALL, '') naminglocale = LOCALEDIR+'/'+locale.getlocale()[0]+'/LC_MESSAGES/c-s-gui.mo' try: gettext.GNUTranslations(open(naminglocale, 'rb')).install() except Exception: gettext.NullTranslations().install() if os.geteuid() != 0: dialog = UserMessage( message = MAIN_ROOT_ERROR_MSG, title = MAIN_ROOT_ERROR_TITLE, type = gtk.MESSAGE_ERROR, buttons = gtk.BUTTONS_OK, c_1 = gtk.RESPONSE_OK, f_1 = sys.exit, p_1 = (1,) ) else: app = Main() gtk.main() sys.exit()
os.environ['LANG'] = lang + '.' + enc if enc else lang logger.info('Locale set to: %s', os.environ['LANG']) _localedir = os.path.join(os.path.dirname(ZIM_EXECUTABLE), 'locale') try: if os.path.isdir(_localedir): # We are running from a source dir - use the locale data included there gettext.install('zim', _localedir, names=('_', 'gettext', 'ngettext')) else: # Hope the system knows where to find the data gettext.install('zim', None, names=('_', 'gettext', 'ngettext')) except: logger.exception('Error loading translation') trans = gettext.NullTranslations() trans.install(names=('_', 'gettext', 'ngettext')) ## Check environment if os.name == 'nt': # Windows specific environment variables # os.environ does not support setdefault() ... if not 'USER' in os.environ or not os.environ['USER']: os.environ['USER'] = os.environ['USERNAME'] if not 'HOME' in os.environ or not os.environ['HOME']: if 'USERPROFILE' in os.environ: os.environ['HOME'] = os.environ['USERPROFILE'] elif 'HOMEDRIVE' in os.environ and 'HOMEPATH' in os.environ:
"/usr/X11R6/share/icewm/", "/usr/lib/icewm/" ]: try: if os.path.exists(iipath) and os.path.isdir(iipath): MY_ICEWM_PATH = iipath return iipath except: pass MY_ICEWM_PATH = "/usr/X11R6/lib/X11/icewm/" # we didnt find the path, use a default return "/usr/X11R6/lib/X11/icewm/" ## added 2.18.2003 - some suggested consolidation, also preliminary localization support # gettext locale support - icewmcp icewmcp_xtext = gettext.NullTranslations() try: # open icewmcp.mo in /usr/share/locale or whatever f_gettext = 0 icewmcp_xtext = getForcedLocale("icewmcp") if not icewmcp_xtext == None: f_gettext = 1 else: for LOCALE_DIR in locale_dirs: # open the first catalog we find, try ./locale dir first try: icewmcp_xtext = gettext.translation("icewmcp", LOCALE_DIR) f_gettext = 1 break except: pass if not f_gettext == 1:
def __init__(self): self._translations = gettext.NullTranslations()
def _fetch(lang, fallback=None): global _translations res = _translations.get(lang, None) if res is not None: return res loc = to_locale(lang) def _translation(path): try: t = gettext_module.translation('django', path, [loc], DjangoTranslation) t.set_language(lang) return t except IOError: return None res = _translation(globalpath) # We want to ensure that, for example, "en-gb" and "en-us" don't share # the same translation object (thus, merging en-us with a local update # doesn't affect en-gb), even though they will both use the core "en" # translation. So we have to subvert Python's internal gettext caching. base_lang = lambda x: x.split('-', 1)[0] if base_lang(lang) in [base_lang(trans) for trans in _translations]: res._info = res._info.copy() res._catalog = res._catalog.copy() def _merge(path): t = _translation(path) if t is not None: if res is None: return t else: res.merge(t) return res for appname in reversed(settings.INSTALLED_APPS): app = import_module(appname) apppath = os.path.join(os.path.dirname(app.__file__), 'locale') if os.path.isdir(apppath): res = _merge(apppath) localepaths = [ os.path.normpath(path) for path in settings.LOCALE_PATHS ] if (projectpath and os.path.isdir(projectpath) and os.path.normpath(projectpath) not in localepaths): res = _merge(projectpath) for localepath in reversed(settings.LOCALE_PATHS): if os.path.isdir(localepath): res = _merge(localepath) if res is None: if fallback is not None: res = fallback else: return gettext_module.NullTranslations() _translations[lang] = res return res
# # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gettext import json import os languages = [ dirname for dirname in os.listdir(os.path.join('.', 'locale')) if os.path.isdir(os.path.join('.', 'locale', dirname)) ] + [None] for language in languages: if not language: lang = gettext.NullTranslations() else: try: lang = gettext.translation('pext_module_radio', localedir=os.path.join('.', 'locale'), languages=[language]) except FileNotFoundError: lang = gettext.NullTranslations() print("No {} metadata translation available for pext_module_radio". format(language)) continue lang.install() filename = 'metadata_{}.json'.format( language) if language else 'metadata.json'
def setup_gettext(localedir, ui_language=None, logger=None): """Setup locales, load translations, install gettext functions.""" if not logger: logger = lambda *a, **b: None # noqa: E731 current_locale = '' if ui_language: try: current_locale = locale.normalize(ui_language + '.' + locale.getpreferredencoding()) locale.setlocale(locale.LC_ALL, current_locale) except Exception as e: logger(e) else: if IS_WIN: from ctypes import windll try: current_locale = locale.windows_locale[ windll.kernel32.GetUserDefaultUILanguage()] current_locale += '.' + locale.getpreferredencoding() locale.setlocale(locale.LC_ALL, current_locale) except KeyError: try: current_locale = locale.setlocale(locale.LC_ALL, '') except Exception as e: logger(e) except Exception as e: logger(e) elif IS_MACOS: try: import Foundation defaults = Foundation.NSUserDefaults.standardUserDefaults() current_locale = defaults.objectForKey_('AppleLanguages')[0] current_locale = current_locale.replace('-', '_') locale.setlocale(locale.LC_ALL, current_locale) except Exception as e: logger(e) else: try: locale.setlocale(locale.LC_ALL, '') current_locale = '.'.join(locale.getlocale(locale.LC_MESSAGES)) except Exception as e: logger(e) os.environ['LANGUAGE'] = os.environ['LANG'] = current_locale QLocale.setDefault(QLocale(current_locale)) logger("Using locale %r", current_locale) try: logger("Loading gettext translation, localedir=%r", localedir) trans = gettext.translation("picard", localedir) logger("Loading gettext translation (picard-countries), localedir=%r", localedir) trans_countries = gettext.translation("picard-countries", localedir) logger("Loading gettext translation (picard-attributes), localedir=%r", localedir) trans_attributes = gettext.translation("picard-attributes", localedir) except OSError as e: logger(e) trans = gettext.NullTranslations() trans_countries = gettext.NullTranslations() trans_attributes = gettext.NullTranslations() trans.install(['ngettext']) builtins.__dict__['gettext_countries'] = trans_countries.gettext builtins.__dict__['gettext_attributes'] = trans_attributes.gettext if hasattr(trans_attributes, 'pgettext'): builtins.__dict__['pgettext_attributes'] = trans_attributes.pgettext else: def pgettext(context, message): return gettext_ctxt(trans_attributes.gettext, message, context) builtins.__dict__['pgettext_attributes'] = pgettext logger("_ = %r", _) logger("N_ = %r", N_) logger("ngettext = %r", ngettext) logger("gettext_countries = %r", gettext_countries) logger("gettext_attributes = %r", gettext_attributes) logger("pgettext_attributes = %r", pgettext_attributes)
def translation(language): """ Returns a translation object. This translation object will be constructed out of multiple GNUTranslations objects by merging their catalogs. It will construct a object for the requested language and add a fallback to the default language, if it's different from the requested language. """ global _translations t = _translations.get(language, None) if t is not None: return t from django.conf import settings # set up the right translation class klass = DjangoTranslation if sys.version_info < (2, 4): klass = DjangoTranslation23 globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale') if settings.SETTINGS_MODULE is not None: parts = settings.SETTINGS_MODULE.split('.') project = __import__(parts[0], {}, {}, []) projectpath = os.path.join(os.path.dirname(project.__file__), 'locale') else: projectpath = None def _fetch(lang, fallback=None): global _translations loc = to_locale(lang) res = _translations.get(lang, None) if res is not None: return res def _translation(path): try: t = gettext_module.translation('django', path, [loc], klass) t.set_language(lang) return t except IOError, e: return None res = _translation(globalpath) def _merge(path): t = _translation(path) if t is not None: if res is None: return t else: res.merge(t) return res for localepath in settings.LOCALE_PATHS: if os.path.isdir(localepath): res = _merge(localepath) if projectpath and os.path.isdir(projectpath): res = _merge(projectpath) for appname in settings.INSTALLED_APPS: p = appname.rfind('.') if p >= 0: app = getattr(__import__(appname[:p], {}, {}, [appname[p+1:]]), appname[p+1:]) else: app = __import__(appname, {}, {}, []) apppath = os.path.join(os.path.dirname(app.__file__), 'locale') if os.path.isdir(apppath): res = _merge(apppath) if res is None: if fallback is not None: res = fallback else: return gettext_module.NullTranslations() _translations[lang] = res return res
# In Python 2, stdout expects encoded byte strings, or else it will # encode them with the ascii 'codec' if sys.version_info.major == 2: text = text.encode('utf-8') print(text) # Expand description end if end: print(end, end='') # Compile a list of translation classes to all supported languages. # The first translation is always a NullTranslations. translations = [("en", gettext.NullTranslations())] for lang in languages: try: trans = gettext.translation("options", localedir, [lang]) except IOError: sys.stderr.write("Warning: language '%s' not found.\n" % lang) continue translations.append((lang, trans)) # Regular expressions: reLibintl_h = re.compile(r'#\s*include\s*<libintl.h>') reDESC = re.compile( r'(\s*DRI_CONF_DESC\s*\(\s*)([a-z]+)(\s*,\s*)(gettext\s*\(\s*")(.*)("\s*\))(\s*\)[ \t]*\\?)$' ) reDESC_BEGIN = re.compile( r'(\s*DRI_CONF_DESC_BEGIN\s*\(\s*)([a-z]+)(\s*,\s*)(gettext\s*\(\s*")(.*)("\s*\))(\s*\)[ \t]*\\?)$'
they will be copied to any packages with those resources. The destination will be 'Portal 2/bee2_dev/' if that exists, or 'Portal 2/bee2/' otherwise. """ import utils import gettext from srctools.filesys import RawFileSystem utils.fix_cur_directory() # Don't write to a log file, users of this should be able to handle a command # prompt. LOGGER = utils.init_logging(main_logger=__name__) # This is needed to allow us to import things properly. gettext.NullTranslations().install(['gettext', 'ngettext']) import os import sys import logging from pathlib import Path from typing import List import shutil from BEE2_config import GEN_OPTS from packageLoader import (packages as PACKAGES, find_packages, LOGGER as packages_logger) # If true, user said * for packages - use last for all. PACKAGE_REPEAT = None # type: RawFileSystem
def disable(): global __enabled__ __enabled__ = False if __installed__: gettext.NullTranslations().install(True)
def __init__(self, schema_name, schema_dir=None, schema_filename=None, **options): if not schema_filename: schema_filename = schema_name + ".gschema.xml" if not schema_dir: schema_dir = gtweak.GSETTINGS_SCHEMA_DIR for xdg_dir in GLib.get_system_data_dirs(): dir = os.path.join(xdg_dir, "glib-2.0", "schemas") if os.path.exists(os.path.join(dir, schema_filename)): schema_dir = dir break schema_path = os.path.join(schema_dir, schema_filename) if not os.path.exists(schema_path): logging.critical("Could not find schema %s" % schema_path) assert (False) self._schema_name = schema_name self._schema = {} try: dom = xml.dom.minidom.parse(schema_path) global_gettext_domain = dom.documentElement.getAttribute( 'gettext-domain') try: if global_gettext_domain: # We can't know where the schema owner was installed, let's assume it's # the same prefix as ours global_translation = gettext.translation( global_gettext_domain, gtweak.LOCALE_DIR) else: global_translation = gettext.NullTranslations() except IOError: global_translation = None logging.debug("No translated schema for %s (domain: %s)" % (schema_name, global_gettext_domain)) for schema in dom.getElementsByTagName("schema"): gettext_domain = schema.getAttribute('gettext-domain') try: if gettext_domain: translation = gettext.translation( gettext_domain, gtweak.LOCALE_DIR) else: translation = global_translation except IOError: translation = None logging.debug("Schema not translated %s (domain: %s)" % (schema_name, gettext_domain)) if schema_name == schema.getAttribute("id"): for key in schema.getElementsByTagName("key"): name = key.getAttribute("name") # summary is 'compulsory', description is optional # …in theory, but we should not barf on bad schemas ever try: summary = key.getElementsByTagName( "summary")[0].childNodes[0].data except: summary = "" logging.info("Schema missing summary %s (key %s)" % (os.path.basename(schema_path), name)) try: description = key.getElementsByTagName( "description")[0].childNodes[0].data except: description = "" # if missing translations, use the untranslated values self._schema[name] = dict( summary=translation.gettext(summary) if translation else summary, description=translation.gettext(description) if translation else description) except: logging.critical("Error parsing schema %s (%s)" % (schema_name, schema_path), exc_info=True)
def setUp(self): unittest.TestCase.setUp(self) import gettext gettext.NullTranslations().install()
.. py:attribute:: CONVENTION Container for all the locale conventions, see http://docs.python.org/library/locale.html#locale.localeconv ''' locale.setlocale(locale.LC_ALL, '') LOCALE_PATH = os.path.join(os.path.dirname(__file__), 'locale') gettext.bindtextdomain('natural', LOCALE_PATH) gettext.textdomain('natural') try: TRANSLATION = gettext.translation('natural', LOCALE_PATH) _ = TRANSLATION.ugettext except IOError: _ = gettext.NullTranslations().ugettext # generic CONVENTION = locale.localeconv() def _multi(singular, plural, count): ''' Provides translations for plural and singular forms of a term. ''' if count == 1: return singular else: return plural
async def init_state(app): # We have to put "kill" into a dict to prevent getting: # DeprecationWarning: Changing state of started or joined application is deprecated app["data"] = {"kill": False} if "db" not in app: app["db"] = None app["users"] = { "Random-Mover": User(app, bot=True, username="******"), "Fairy-Stockfish": User(app, bot=True, username="******"), "Discord-Relay": User(app, anon=True, username="******"), } app["users"]["Random-Mover"].bot_online = True app["lobbysockets"] = {} app["seeks"] = {} app["games"] = {} app["chat"] = collections.deque([], 200) app["channels"] = set() app["highscore"] = {variant: ValueSortedDict(neg) for variant in VARIANTS} app["crosstable"] = {} app["stats"] = {} # counters for games app["g_cnt"] = 0 # last game played app["tv"] = None # fishnet active workers app["workers"] = set() # fishnet works app["works"] = {} # fishnet worker tasks app["fishnet"] = asyncio.PriorityQueue() # fishnet workers monitor app["fishnet_monitor"] = {} app["fishnet_versions"] = {} for key in FISHNET_KEYS: app["fishnet_monitor"][FISHNET_KEYS[key]] = collections.deque([], 50) rm = app["users"]["Random-Mover"] for variant in VARIANTS: variant960 = variant.endswith("960") variant_name = variant[:-3] if variant960 else variant byoyomi = variant == "janggi" or variant.endswith("shogi") or variant == "shogun" seek = Seek(rm, variant_name, base=5, inc=30 if byoyomi else 3, level=0, chess960=variant960, byoyomi_period=1 if byoyomi else 0) app["seeks"][seek.id] = seek rm.seeks[seek.id] = seek ai = app["users"]["Fairy-Stockfish"] loop = asyncio.get_event_loop() loop.create_task(BOT_task(ai, app)) loop.create_task(BOT_task(rm, app)) # Configure templating. app["jinja"] = {} base = os.path.dirname(__file__) for lang in LANGUAGES: # Generate compiled mo file folder = os.path.join(base, "../lang/", lang, "LC_MESSAGES") poname = os.path.join(folder, "server.po") moname = os.path.join(folder, "server.mo") try: with open(poname, 'rb') as po_file: po_lines = [line for line in po_file if line[:8] != b"#, fuzzy"] mo = Msgfmt(po_lines).get() with open(moname, 'wb') as mo_file: mo_file.write(mo) except PoSyntaxError: log.error("PoSyntaxError in %s" % poname) # Create translation class try: translation = gettext.translation("server", localedir="lang", languages=[lang]) except FileNotFoundError: log.warning("Missing translations file for lang %s" % lang) translation = gettext.NullTranslations() env = jinja2.Environment( enable_async=True, extensions=['jinja2.ext.i18n'], loader=jinja2.FileSystemLoader("templates"), autoescape=jinja2.select_autoescape(["html"])) env.install_gettext_translations(translation, newstyle=True) app["jinja"][lang] = env if app["db"] is None: return # Read users and highscore from db try: cursor = app["db"].user.find() async for doc in cursor: if doc["_id"] not in app["users"]: perfs = doc.get("perfs") if perfs is None: perfs = {variant: DEFAULT_PERF for variant in VARIANTS} app["users"][doc["_id"]] = User( app, username=doc["_id"], title=doc.get("title"), first_name=doc.get("first_name"), last_name=doc.get("last_name"), country=doc.get("country"), bot=doc.get("title") == "BOT", perfs=perfs, enabled=doc.get("enabled", True) ) db_collections = await app["db"].list_collection_names() if "highscore" not in db_collections: await generate_highscore(app["db"]) cursor = app["db"].highscore.find() async for doc in cursor: app["highscore"][doc["_id"]] = ValueSortedDict(neg, doc["scores"]) if "crosstable" not in db_collections: await generate_crosstable(app["db"]) cursor = app["db"].crosstable.find() async for doc in cursor: app["crosstable"][doc["_id"]] = doc await app["db"].game.create_index("us") await app["db"].game.create_index("v") await app["db"].game.create_index("y") await app["db"].game.create_index("by") except Exception: print("Maybe mongodb is not running...") raise
"""Activate, get and deactivate translations.""" import gettext as gettext_module import os.path from threading import local __all__ = ["activate", "deactivate", "gettext", "ngettext"] _TRANSLATIONS = {None: gettext_module.NullTranslations()} _CURRENT = local() def _get_default_locale_path(): try: if __file__ is None: return None return os.path.join(os.path.dirname(__file__), "locale") except NameError: return None def get_translation(): try: return _TRANSLATIONS[_CURRENT.locale] except (AttributeError, KeyError): return _TRANSLATIONS[None] def activate(locale, path=None): """Activate internationalisation. Set `locale` as current locale. Search for locale in directory `path`.
async def new_job(self, msg: BackendNewJob): language = msg.inputdata.get("@lang", "") translation = self._translations.get(language, gettext.NullTranslations()) # TODO: this would probably require a refactor. # This may pose problem with apps that start multiple MCQAgents in the same process... builtins.__dict__['_'] = translation.gettext course_fs = self._fs.from_subfolder(msg.course_id) task_fs = course_fs.from_subfolder(msg.task_id) translations_fs = task_fs.from_subfolder("$i18n") if not translations_fs.exists(): translations_fs = task_fs.from_subfolder("student").from_subfolder( "$i18n") if not translations_fs.exists(): translations_fs = course_fs.from_subfolder( "$common").from_subfolder("$i18n") if not translations_fs.exists(): translations_fs = course_fs.from_subfolder("$common").from_subfolder("student")\ .from_subfolder("$i18n") if translations_fs.exists() and translations_fs.exists(language + ".mo"): translations = { language: gettext.GNUTranslations( translations_fs.get_fd(language + ".mo")) } else: translations = {language: gettext.NullTranslations()} task_problems = msg.task_problems problems = [] for problemid, problem_content in task_problems.items(): problem_class = self._problem_types.get( problem_content.get('type', "")) problems.append( problem_class(problemid, problem_content, translations, task_fs)) result, need_emul, text, problems, error_count, mcq_error_count, state = self.check_answer( problems, msg.inputdata, language) internal_messages = { "_wrong_answer_multiple": _("Wrong answer. Make sure to select all the valid possibilities"), "_wrong_answer": _("Wrong answer"), "_correct_answer": _("Correct answer"), } for key, (p_result, messages) in problems.items(): messages = [ internal_messages[message] if message in internal_messages else message for message in messages ] problems[key] = (p_result, "\n\n".join(messages)) if need_emul: self._logger.warning( "Task %s/%s is not a pure MCQ but has env=MCQ", msg.course_id, msg.task_id) raise CannotCreateJobException("Task wrongly configured as a MCQ") if error_count != 0: text.append(_("You have {} wrong answer(s).").format(error_count)) if mcq_error_count != 0: text.append("\n\n" + _( "Among them, you have {} invalid answers in the multiple choice questions" ).format(mcq_error_count)) nb_subproblems = len(task_problems) if nb_subproblems == 0: grade = 0.0 text.append("No subproblems defined") await self.send_job_result(msg.job_id, "crashed", "\n".join(text), grade, problems, {}, {}, "", None) else: grade = 100.0 * float(nb_subproblems - error_count) / float(nb_subproblems) await self.send_job_result(msg.job_id, ("success" if result else "failed"), "\n".join(text), grade, problems, {}, {}, state, None)
def get_translation_obj(self, language): return self._translations.get(language, gettext.NullTranslations())
"""i18n and l10n support for git-cola""" from __future__ import division, absolute_import, unicode_literals import gettext as _gettext import os import sys from . import compat from . import core from . import resources _null_translation = _gettext.NullTranslations() _translation = _null_translation def gettext(s): try: txt = _translation.ugettext(s) except AttributeError: # Python 3 compat _translation.ugettext = _translation.gettext txt = _translation.gettext(s) # handle @@verb / @@noun txt = txt.replace('@@verb', '').replace('@@noun', '') return txt def ngettext(s, p, n): try: txt = _translation.ungettext(s, p, n) except AttributeError: # Python 3 compat
def __init__(self, course, taskid, content, filesystem, plugin_manager, task_problem_types): # We load the descriptor of the task here to allow plugins to modify settings of the task before it is read by the Task constructor if not id_checker(taskid): raise Exception("Task with invalid id: " + course.get_id() + "/" + taskid) content = _migrate_from_v_0_6(content) self._course = course self._taskid = taskid self._fs = filesystem self._plugin_manager = plugin_manager self._data = content if "problems" not in self._data: raise Exception("Tasks must have some problems descriptions") # i18n self._translations = {} self._course_fs = self._fs.from_subfolder(course.get_id()) self._course_fs.ensure_exists() self._task_fs = self._course_fs.from_subfolder(taskid) self._task_fs.ensure_exists() self._translations_fs = self._task_fs.from_subfolder("$i18n") if not self._translations_fs.exists(): self._translations_fs = self._task_fs.from_subfolder("student").from_subfolder("$i18n") if not self._translations_fs.exists(): self._translations_fs = self._course_fs.from_subfolder("$common").from_subfolder("$i18n") if not self._translations_fs.exists(): self._translations_fs = self._course_fs.from_subfolder("$common").from_subfolder( "student").from_subfolder("$i18n") if self._translations_fs.exists(): for f in self._translations_fs.list(folders=False, files=True, recursive=False): lang = f[0:len(f) - 3] if self._translations_fs.exists(lang + ".mo"): self._translations[lang] = gettext.GNUTranslations(self._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)) # Env type self._environment_id = self._data.get('environment_id', 'default') self._environment_type = self._data.get('environment_type', 'unknown') self._environment_parameters = self._data.get("environment_parameters", {}) env_type_obj = get_env_type(self._environment_type) if env_type_obj is None: raise Exception(_("Environment type {0} is unknown").format(self._environment_type)) # Ensure that the content of the dictionary is ok self._environment_parameters = env_type_obj.check_task_environment_parameters(self._environment_parameters) # Name and context self._name = self._data.get('name', 'Task {}'.format(self.get_id())) self._context = self._data.get('context', "") # Authors if isinstance(self._data.get('author'), str): # verify if author is a string self._author = self._data['author'] else: self._author = "" if isinstance(self._data.get('contact_url'), str): self._contact_url = self._data['contact_url'] else: self._contact_url = "" # Submission storage self._stored_submissions = int(self._data.get("stored_submissions", 0)) # Default download self._evaluate = self._data.get("evaluate", "best") # Grade weight self._weight = float(self._data.get("weight", 1.0)) # _accessible self._accessible = AccessibleTime(self._data.get("accessible", None)) # Group task self._groups = bool(self._data.get("groups", False)) # Submission limits self._submission_limit = self._data.get("submission_limit", {"amount": -1, "period": -1}) # Input random self._input_random = int(self._data.get("input_random", 0)) # Regenerate input random self._regenerate_input_random = bool(self._data.get("regenerate_input_random", False)) # Category tags self._categories = self._data.get("categories", [])
The translated version of the object's docstring. """ try: doc = object.__doc__ except AttributeError: return None if not isinstance(doc, str): return None return inspect.cleandoc(_(doc)) _user_locale = _get_user_locale() if _user_locale in _TRANSLATED_LANGUAGES: _POTRANSLATOR_TRANSLATIONS = gettext.translation( domain="potranslator", localedir=_TRANSLATIONS_PATH, languages=[_user_locale], fallback=True, codeset="UTF-8", ) else: _POTRANSLATOR_TRANSLATIONS = gettext.NullTranslations() _POTRANSLATOR_TRANSLATIONS.install() # Replaces the getdoc method inspect.getdoc = _getdoc from .potranslator import PoTranslator
def get_translation(): """ Returns the gettext.Translation instance that has been initialized with install_gettext(). """ return _translation or gettext.NullTranslations()
def setUp(self): super(TranslationFixture, self).setUp() nulltrans = gettext.NullTranslations() gettext_fixture = fixtures.MonkeyPatch('gettext.translation', lambda *x, **y: nulltrans) self.gettext_patcher = self.useFixture(gettext_fixture)
def get_context(self, language): """ Get the context(description) of this task """ context = self.gettext(language, self._context) if self._context else "" vals = self._hook_manager.call_hook('task_context', course=self.get_course(), task=self, default=context) return ParsableText(vals[0], "rst", self._translations.get(language, gettext.NullTranslations())) if len(vals) \ else ParsableText(context, "rst", self._translations.get(language, gettext.NullTranslations()))
def install_domain(domain=None, language=None, prefer_local_catalog=False): """Install a text domain suitable for the main script.""" # text domain directly specified ? if domain is None: _log.info('domain not specified, deriving from script name') # get text domain from name of script domain = os.path.splitext(os.path.basename(sys.argv[0]))[0] _log.info('text domain is [%s]' % domain) # http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html _log.debug('searching message catalog file for system locale [%s]' % system_locale) _log.debug('checking process environment:') for env_var in ['LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG']: tmp = os.getenv(env_var) if env_var is None: _log.debug(' ${%s} not set' % env_var) else: _log.debug(' ${%s} = [%s]' % (env_var, tmp)) # language codes to try lang_candidates = [] # first: explicit language or default system language # language=None: unadulterated default language for user (locale.getlocale()[0] value) # language != None: explicit language setting as passed in by the caller lang_candidates.append(language) if language is not None: _log.info('explicit request for target language [%s]' % language) # next: try default language for user if explicit language fails lang_candidates.append(None) # next try locale.getlocale()[0], if different (this can be strange on, say, Windows: Hungarian_Hungary) if locale.getlocale()[0] not in lang_candidates: lang_candidates.append(locale.getlocale()[0]) # next try locale.get*default*locale()[0], if different if locale.getdefaultlocale()[0] not in lang_candidates: lang_candidates.append(locale.getdefaultlocale()[0]) _log.debug( 'languages to try for translation: %s (None: implicit system default)', lang_candidates) initial_lang = os.getenv('LANG') _log.info('initial ${LANG} setting: %s', initial_lang) # loop over language candidates for lang_candidate in lang_candidates: # setup baseline _log.debug('resetting ${LANG} to initial user default [%s]', initial_lang) if initial_lang is None: del os.environ['LANG'] lang2log = '$LANG=<>' else: os.environ['LANG'] = initial_lang lang2log = '$LANG(default)=%s' % initial_lang # setup candidate language if lang_candidate is not None: _log.info( 'explicitly overriding system locale language [%s] by setting ${LANG} to [%s]', initial_lang, lang_candidate) os.environ['LANG'] = lang_candidate lang2log = '$LANG(explicit)=%s' % lang_candidate if __install_domain(domain=domain, prefer_local_catalog=prefer_local_catalog, language=lang2log): return True # install a dummy translation class _log.warning("falling back to NullTranslations() class") # this shouldn't fail dummy = gettext.NullTranslations() dummy.install() return True
def get_lang_attr(self): filename = os.path.join(self.locale_dir, self.lang, "LC_MESSAGES", "eduactiv8.mo") self.trans[self.lang] = gettext.GNUTranslations(open(filename, "rb")) try: self.trans[self.lang] = gettext.GNUTranslations( open(filename, "rb")) except IOError: print("Locale not found. Using default messages") self.trans[self.lang] = gettext.NullTranslations() self.trans[self.lang].install() import i18n.custom.default self.oi18n = i18n.custom.default.I18n() self.kbrd = None self.ltr_text = True self.ltr_numbers = True self.ltr_math = True self.has_uc = True self.has_cursive = True font_variant = 0 self.ico_suffix = "" self.lang_id = 0 # used to identify the language in database - do not reorganize numbers when adding new language if self.lang == 'en_US': import i18n.custom.en_us import i18n.custom.word_lists.en_us_di import i18n.custom.kbrd.en_us import i18n.custom.kbrd.en_course import i18n.custom.a4a_py.en_US as a4a_word_lst # self.voice = ["-s 170","-a 100","-p 80","-ven-us+m1"] self.voice = ["-ven-us+m1"] self.di = i18n.custom.word_lists.en_us_di.di self.lang_file = i18n.custom.en_us self.kbrd = i18n.custom.kbrd.en_us self.kbrd_course_mod = i18n.custom.kbrd.en_course self.lang_id = 1 elif self.lang == 'pl': import i18n.custom.pl import i18n.custom.word_lists.pl_di import i18n.custom.kbrd.pl import i18n.custom.kbrd.pl_course import i18n.custom.a4a_py.pl as a4a_word_lst # self.voice = ["-s 160","-a 100","-p 80","-vpl+m1"] #"-g 5", self.voice = ["-vpl+m1"] self.di = i18n.custom.word_lists.pl_di.di self.lang_file = i18n.custom.pl self.kbrd = i18n.custom.kbrd.pl self.kbrd_course_mod = i18n.custom.kbrd.pl_course self.lang_id = 3 elif self.lang == 'sr': import i18n.custom.sr import i18n.custom.word_lists.sr_di import i18n.custom.a4a_py.en_GB as a4a_word_lst # self.voice = ["-s 160","-a 100","-p 80","-vpl+m1"] #"-g 5", self.voice = ["-vsr+m1"] self.di = i18n.custom.word_lists.sr_di.di self.lang_file = i18n.custom.sr self.lang_id = 19 self.ico_suffix = "ru" self.has_cursive = False self.time2str_short = self.lang_file.time2str_short elif self.lang == 'ca': import i18n.custom.ca import i18n.custom.word_lists.ca_di import i18n.custom.a4a_py.ca as a4a_word_lst self.voice = ["-vca+m1"] self.di = i18n.custom.word_lists.ca_di.di self.lang_file = i18n.custom.ca self.lang_id = 5 elif self.lang == 'es_ES': import i18n.custom.es import i18n.custom.word_lists.es_di import i18n.custom.a4a_py.es as a4a_word_lst self.voice = ["-ves+m1"] self.di = i18n.custom.word_lists.es_di.di self.lang_file = i18n.custom.es self.lang_id = 8 elif self.lang == 'pt_PT': import i18n.custom.pt import i18n.custom.word_lists.pt_di import i18n.custom.a4a_py.pt as a4a_word_lst self.voice = ["-vpt-pt+m1"] self.di = i18n.custom.word_lists.pt_di.di self.lang_file = i18n.custom.pt self.lang_id = 9 elif self.lang == 'fr': import i18n.custom.fr import i18n.custom.word_lists.fr_di import i18n.custom.kbrd.fr import i18n.custom.kbrd.fr_course import i18n.custom.a4a_py.fr as a4a_word_lst self.voice = ["-vfr+m1"] self.di = i18n.custom.word_lists.fr_di.di self.lang_file = i18n.custom.fr self.kbrd = i18n.custom.kbrd.fr self.kbrd_course_mod = i18n.custom.kbrd.fr_course self.lang_id = 10 elif self.lang == 'it': import i18n.custom.it import i18n.custom.word_lists.it_di import i18n.custom.a4a_py.it as a4a_word_lst self.voice = ["-vit+m1"] self.di = i18n.custom.word_lists.it_di.di self.lang_file = i18n.custom.it self.lang_id = 11 elif self.lang == 'de': import i18n.custom.de import i18n.custom.word_lists.de_di import i18n.custom.kbrd.de import i18n.custom.kbrd.de_course import i18n.custom.a4a_py.de as a4a_word_lst self.voice = ["-vde+m1"] self.di = i18n.custom.word_lists.de_di.di self.lang_file = i18n.custom.de self.kbrd = i18n.custom.kbrd.de self.kbrd_course_mod = i18n.custom.kbrd.de_course self.lang_id = 12 elif self.lang == 'ru': import i18n.custom.ru import i18n.custom.word_lists.ru_di import i18n.custom.kbrd.ru import i18n.custom.kbrd.ru_course import i18n.custom.a4a_py.ru as a4a_word_lst # self.voice = ["-s 130","-a 100","-p 80","-vru+m1"] # self.voice = ["-vru+m1"] s 150 -vru self.voice = ["-s 150", "-vru"] self.di = i18n.custom.word_lists.ru_di.di self.lang_file = i18n.custom.ru self.kbrd = i18n.custom.kbrd.ru self.kbrd_course_mod = i18n.custom.kbrd.ru_course self.time2spk_short = self.lang_file.time2spk_short self.time2str_short = self.lang_file.time2str_short self.time2spk = self.lang_file.time2spk self.ico_suffix = "ru" self.lang_id = 13 elif self.lang == 'uk': import i18n.custom.uk import i18n.custom.word_lists.uk_di import i18n.custom.kbrd.uk import i18n.custom.kbrd.uk_course import i18n.custom.a4a_py.uk as a4a_word_lst self.voice = None self.di = i18n.custom.word_lists.uk_di.di self.lang_file = i18n.custom.uk self.kbrd = i18n.custom.kbrd.uk self.kbrd_course_mod = i18n.custom.kbrd.uk_course self.ico_suffix = "ru" self.lang_id = 14 elif self.lang == 'fi': import i18n.custom.fi import i18n.custom.word_lists.fi_di import i18n.custom.a4a_py.en_GB as a4a_word_lst self.voice = ["-vfi+m1"] self.di = i18n.custom.word_lists.fi_di.di self.lang_file = i18n.custom.fi self.lang_id = 15 elif self.lang == 'el': # Greek import i18n.custom.el import i18n.custom.word_lists.el_di import i18n.custom.kbrd.el import i18n.custom.kbrd.el_course import i18n.custom.a4a_py.el as a4a_word_lst self.voice = ["-vel+m1"] self.di = i18n.custom.word_lists.el_di.di self.lang_file = i18n.custom.el self.kbrd = i18n.custom.kbrd.el self.kbrd_course_mod = i18n.custom.kbrd.el_course self.ico_suffix = "el" self.lang_id = 16 elif self.lang == 'he': # Hebrew import i18n.custom.he import i18n.custom.word_lists.he_di import i18n.custom.a4a_py.en_GB as a4a_word_lst self.voice = ["-ven+m1"] # None self.di = i18n.custom.word_lists.he_di.di self.lang_file = i18n.custom.he self.time2spk = self.lang_file.time2spk self.ltr_text = False self.has_uc = False self.has_cursive = False self.alpha = i18n.custom.he.alpha self.n2spk = self.lang_file.n2spk # font_variant = 1 self.ico_suffix = "he" self.lang_id = 17 elif self.lang == 'lkt': import i18n.custom.lkt import i18n.custom.word_lists.lkt_di import i18n.custom.a4a_py.lkt as a4a_word_lst self.voice = None self.has_cursive = False self.di = i18n.custom.word_lists.lkt_di.di self.lang_file = i18n.custom.lkt # self.alpha = i18n.custom.cn.alpha # self.n2spk = self.lang_file.n2spk self.ico_suffix = "" self.lang_id = 20 else: # self.lang == 'en_GB': import i18n.custom.en_gb import i18n.custom.word_lists.en_gb_di import i18n.custom.kbrd.en_gb import i18n.custom.kbrd.en_course import i18n.custom.a4a_py.en_GB as a4a_word_lst self.voice = ["-ven+m1"] self.di = i18n.custom.word_lists.en_gb_di.di self.lang_file = i18n.custom.en_gb self.kbrd = i18n.custom.kbrd.en_gb self.kbrd_course_mod = i18n.custom.kbrd.en_course self.lang_id = 1 # languages that have not been translated are temporarily switched off """ elif self.lang == 'sk': import i18n.custom.sk import i18n.custom.word_lists.sk_di # self.voice = ["-s 160","-a 100","-p 80","-vpl+m1"] #"-g 5", self.voice = ["-vsk+m1"] self.di = i18n.custom.word_lists.sk_di.di self.lang_file = i18n.custom.sk self.lang_id = 4 elif self.lang == 'da': import i18n.custom.da import i18n.custom.word_lists.da_di self.voice = ["-vda+m1"] self.di = i18n.custom.word_lists.da_di.di self.lang_file = i18n.custom.da self.lang_id = 6 elif self.lang == 'nl': import i18n.custom.nl import i18n.custom.word_lists.nl_di self.voice = ["-vnl+m1"] self.di = i18n.custom.word_lists.nl_di.di self.lang_file = i18n.custom.nl self.lang_id = 7 elif self.lang == 'ar': # Arabic import i18n.custom.ar import i18n.custom.word_lists.ar_di self.voice = None self.di = i18n.custom.word_lists.ar_di.di self.lang_file = i18n.custom.ar self.ltr_text = False self.has_uc = False self.has_cursive = False self.alpha = i18n.custom.ar.alpha self.n2spk = self.lang_file.n2spk self.ico_suffix = "ar" self.lang_id = 2 elif self.lang == 'cn': import i18n.custom.cn import i18n.custom.word_lists.cn_di self.voice = None self.di = i18n.custom.word_lists.cn_di.di self.lang_file = i18n.custom.cn # self.alpha = i18n.custom.cn.alpha # self.n2spk = self.lang_file.n2spk self.ico_suffix = "" self.lang_id = 18 """ if self.lang in ["ar", "he"]: self.config.font_multiplier = 1.1 self.config.font_line_height_adjustment = 1.5 self.config.font_start_at_adjustment = 5 else: self.config.font_multiplier = 1 self.config.font_line_height_adjustment = 1 self.config.font_start_at_adjustment = 0 if self.kbrd is None: import i18n.custom.kbrd.en_gb import i18n.custom.kbrd.en_course self.kbrd = i18n.custom.kbrd.en_gb self.kbrd_course_mod = i18n.custom.kbrd.en_course self.d = dict() self.b = dict() self.dp = dict() self.kbrd_course = self.kbrd_course_mod.course self.d.update(self.oi18n.d) self.d.update(self.lang_file.d) self.b.update(self.oi18n.b) self.numbers = self.lang_file.numbers self.numbers2090 = self.lang_file.numbers2090 self.n2txt = self.lang_file.n2txt self.time2str = self.lang_file.time2str self.fract2str = self.lang_file.fract2str self.solid_names = self.oi18n.solid_names self.shape_names = self.oi18n.shape_names self.letter_names = self.lang_file.letter_names self.config.set_font_family(font_variant) if not self.ltr_text: for each_d in [self.d, self.b]: for key in each_d.keys(): if isinstance(each_d[key], list): for index in range(len(each_d[key])): if sys.version_info < (3, 0): if isinstance(each_d[key][index], basestring): each_d[key][index] = reverse( each_d[key][index], self.alpha, self.lang) else: if isinstance(each_d[key][index], str): each_d[key][index] = reverse( each_d[key][index], self.alpha, self.lang) else: each_d[key] = reverse(each_d[key], self.alpha, self.lang) for each in [self.solid_names, self.shape_names]: for index in range(len(each)): if sys.version_info < (3, 0): if isinstance(each[index], basestring): each[index] = reverse(each[index], self.alpha, self.lang) else: if isinstance(each[index], str): each[index] = reverse(each[index], self.alpha, self.lang) self.dp.update(self.d) self.dp.update(self.lang_file.dp) if self.lang == "he": s = unival(self.d['abc_flashcards_word_sequence'][0]) if len(s) > 0: if s[0] == unival("א"): self.d['abc_flashcards_word_sequence'] = self.d[ 'abc_flashcards_word_sequencer'] self.alphabet_lc = self.lang_file.alphabet_lc self.alphabet_uc = self.lang_file.alphabet_uc self.accents_lc = self.lang_file.accents_lc self.accents_uc = self.lang_file.accents_uc self.d["a4a_animals"] = a4a_word_lst.d["a4a_animals"] self.d["a4a_sport"] = a4a_word_lst.d["a4a_sport"] self.d["a4a_body"] = a4a_word_lst.d["a4a_body"] self.d["a4a_people"] = a4a_word_lst.d["a4a_people"] self.d["a4a_food"] = a4a_word_lst.d["a4a_food"] self.d["a4a_clothes_n_accessories"] = a4a_word_lst.d[ "a4a_clothes_n_accessories"] self.d["a4a_actions"] = a4a_word_lst.d["a4a_actions"] self.d["a4a_construction"] = a4a_word_lst.d["a4a_construction"] self.d["a4a_nature"] = a4a_word_lst.d["a4a_nature"] self.d["a4a_jobs"] = a4a_word_lst.d["a4a_jobs"] self.d["a4a_fruit_n_veg"] = a4a_word_lst.d["a4a_fruit_n_veg"] self.d["a4a_transport"] = a4a_word_lst.d["a4a_transport"]
def translation(language): """ Returns a translation object. This translation object will be constructed out of multiple GNUTranslations objects by merging their catalogs. It will construct a object for the requested language and add a fallback to the default language, if it's different from the requested language. """ global _translations t = _translations.get(language, None) if t is not None: return t from google.appengine._internal.django.conf import settings globalpath = os.path.join( os.path.dirname(sys.modules[settings.__module__].__file__), 'locale') if settings.SETTINGS_MODULE is not None: parts = settings.SETTINGS_MODULE.split('.') project = import_module(parts[0]) projectpath = os.path.join(os.path.dirname(project.__file__), 'locale') else: projectpath = None def _fetch(lang, fallback=None): global _translations loc = to_locale(lang) res = _translations.get(lang, None) if res is not None: return res def _translation(path): try: t = gettext_module.translation('django', path, [loc], DjangoTranslation) t.set_language(lang) return t except IOError, e: return None res = _translation(globalpath) # We want to ensure that, for example, "en-gb" and "en-us" don't share # the same translation object (thus, merging en-us with a local update # doesn't affect en-gb), even though they will both use the core "en" # translation. So we have to subvert Python's internal gettext caching. base_lang = lambda x: x.split('-', 1)[0] if base_lang(lang) in [base_lang(trans) for trans in _translations]: res._info = res._info.copy() res._catalog = res._catalog.copy() def _merge(path): t = _translation(path) if t is not None: if res is None: return t else: res.merge(t) return res for localepath in settings.LOCALE_PATHS: if os.path.isdir(localepath): res = _merge(localepath) for appname in settings.INSTALLED_APPS: app = import_module(appname) apppath = os.path.join(os.path.dirname(app.__file__), 'locale') if os.path.isdir(apppath): res = _merge(apppath) if projectpath and os.path.isdir(projectpath): res = _merge(projectpath) if res is None: if fallback is not None: res = fallback else: return gettext_module.NullTranslations() _translations[lang] = res return res
def setUp(self) -> None: gettext.NullTranslations().install()