Example #1
0
 def get_columns(self):
     return [
         [
             self.head_template.format(
                 number_format(self.total, force_grouping=True)
             ),
             self.foot_template.format(
                 npgettext(
                     "Label on enage page", "String", "Strings", self.total
                 ).upper()
             ),
         ],
         [
             self.head_template.format(
                 number_format(self.languages, force_grouping=True)
             ),
             self.foot_template.format(
                 npgettext(
                     "Label on enage page", "Language", "Languages", self.languages
                 ).upper()
             ),
         ],
         [
             self.head_template.format(self.get_percent_text()),
             self.foot_template.format(_('Translated').upper()),
         ],
     ]
Example #2
0
def setup_translations():
    gettext('edit')
    pgettext('season', 'spring')
    pgettext('mechanical device', 'spring')
    npgettext('in a forest', 'tree', 'trees', 3)
    gettext('"double quote"')
    gettext("'single quote'")
    gettext("'single quote' with escaped \"double\"")
    gettext('"double quote" with exceped \'single\'')
    count = 3
    ngettext("You bought {} apple", "You bought {} apples", count)
Example #3
0
 def _make_blocktrans(self,
                      singular,
                      plural=None,
                      context=None,
                      trans_vars=None,
                      count_var=None):
     if trans_vars is None:
         trans_vars = {}  # pragma: no cover
     if self.environment.finalize:
         finalized_trans_vars = {
             key: self.environment.finalize(val)
             for key, val in trans_vars.items()
         }
     else:
         finalized_trans_vars = trans_vars
     if plural is None:
         if context is None:
             return ugettext(force_text(singular)) % finalized_trans_vars
         else:
             return pgettext(force_text(context),
                             force_text(singular)) % finalized_trans_vars
     else:
         if context is None:
             return ungettext(force_text(singular), force_text(plural),
                              trans_vars[count_var]) % finalized_trans_vars
         else:
             return npgettext(force_text(context), force_text(singular),
                              force_text(plural),
                              trans_vars[count_var]) % finalized_trans_vars
Example #4
0
 def get_summary_message(self):
     counter = self.qs.count()
     return npgettext(
         'Number of matching records in the dashboard sales list',
         'Found %(counter)d matching sale',
         'Found %(counter)d matching sales',
         number=counter) % {'counter': counter}
Example #5
0
 def get_summary_message(self):
     counter = self.qs.count()
     return npgettext(
         'Number of matching records in the dashboard groups list',
         'Found %(counter)d matching group',
         'Found %(counter)d matching groups',
         number=counter) % {'counter': counter}
Example #6
0
 def get_summary_message(self):
     counter = self.qs.count()
     return npgettext(
         "Number of matching records in the dashboard staff members list",
         "Found %(counter)d matching staff member",
         "Found %(counter)d matching staff members",
         number=counter,
     ) % {"counter": counter}
Example #7
0
 def get_summary_message(self):
     counter = self.qs.count()
     return npgettext(
         "Number of matching records in the tradingroom attributes list",
         "Found %(counter)d matching attribute",
         "Found %(counter)d matching attributes",
         number=counter,
     ) % {"counter": counter}
Example #8
0
 def get_summary_message(self):
     counter = self.qs.count()
     return npgettext('Number of matching records in the responses list',
                      'Found %(counter)d matching response',
                      'Found %(counter)d matching responses',
                      number=counter) % {
                          'counter': counter
                      }
Example #9
0
 def get_columns(self):
     return [
         [
             self.head_template.format(self.total),
             npgettext("Label on enage page", "String", "Strings",
                       self.total).upper(),
         ],
         [
             self.head_template.format(self.languages),
             npgettext("Label on enage page", "Language", "Languages",
                       self.languages).upper(),
         ],
         [
             self.head_template.format(self.get_percent_text()),
             _('Translated').upper(),
         ],
     ]
Example #10
0
 def get_summary_message(self):
     counter = self.qs.count()
     return npgettext(
         'Number of matching records in the dashboard '
         'shipping methods list',
         'Found %(counter)d matching shipping method',
         'Found %(counter)d matching shipping methods',
         number=counter) % {'counter': counter}
Example #11
0
 def get_summary_message(self):
     counter = self.qs.count()
     return npgettext(
         'Number of matching records in the dashboard '
         'product attributes list',
         'Found %(counter)d matching attribute',
         'Found %(counter)d matching attributes',
         number=counter) % {'counter': counter}
Example #12
0
    def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update({
            var: val.resolve(context)
            for var, val in self.extra_context.items()
        })
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            if not isinstance(count, (Decimal, float, int)):
                raise TemplateSyntaxError(
                    "%r argument to %r tag must be a number." %
                    (self.countervar, self.tag_name))
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ngettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.gettext(singular)
        default_value = context.template.engine.string_if_invalid

        def render_value(key):
            if key in context:
                val = context[key]
            else:
                val = default_value % key if '%s' in default_value else default_value
            return render_value_in_context(val, context)

        data = {v: render_value(v) for v in vars}
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError(
                    '%r is unable to format string returned by gettext: %r '
                    'using %r' % (self.tag_name, result, data))
            with translation.override(None):
                result = self.render(context, nested=True)
        if self.asvar:
            context[self.asvar] = result
            return ''
        else:
            return result
Example #13
0
 def get_summary_message(self):
     counter = self.qs.count()
     return npgettext(
         'Number of matching records in the dashboard popular categories list',
         'Found %(counter)d matching popular category',
         'Found %(counter)d matching popular categories',
         number=counter) % {
             'counter': counter
         }
Example #14
0
 def get_summary_message(self):
     counter = self.qs.count()
     return npgettext(
         'Number of matching records in the dashboard physical store list',
         'Found %(counter)d matching physical store',
         'Found %(counter)d matching physical stores',
         number=counter) % {
             'counter': counter
         }
Example #15
0
 def get_summary_message(self):
     """Returns message displayed in dashboard filter cards.
     Inherited by subclasses for record specific naming."""
     counter = self.qs.count()
     return npgettext(
         'Number of matching records in the dashboard list',
         'Found %(counter)d matching record',
         'Found %(counter)d matching records',
         number=counter) % {'counter': counter}
Example #16
0
 def get_summary_message(self):
     counter = self.qs.count()
     return npgettext(
         'Number of matching records in the dashboard super collections list',
         'Found %(counter)d matching super collection',
         'Found %(counter)d matching super collections',
         number=counter) % {
             'counter': counter
         }
Example #17
0
 def get_summary_message(self):
     counter = self.qs.count()
     return npgettext(
         'Number of matching records in the dashboard '
         'delivery zones list',
         'Found %(counter)d matching delivery zone',
         'Found %(counter)d matching delivery zones',
         number=counter) % {
             'counter': counter
         }
Example #18
0
 def get_columns(self):
     return [
         [
             self.head_template.format(number_format(self.total)),
             self.foot_template.format(
                 npgettext("Label on engage page", "String", "Strings",
                           self.total).upper()),
         ],
         [
             self.head_template.format(number_format(self.languages)),
             self.foot_template.format(
                 npgettext("Label on engage page", "Language", "Languages",
                           self.languages).upper()),
         ],
         [
             self.head_template.format(self.get_percent_text()),
             self.foot_template.format(_("Translated").upper()),
         ],
     ]
    def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ungettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.ugettext(singular)
        default_value = context.template.engine.string_if_invalid

        def render_value(key):
            if key in context:
                val = context[key]
            else:
                val = default_value % key \
                    if '%s' in default_value else default_value
            return render_value_in_context(val, context)

        data = {v: render_value(v) for v in vars}
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError(
                    "'blocktrans' is unable to format "
                    "string returned by gettext: %r "
                    "using %r" % (result, data))
            with translation.override(None):
                result = self.render(context, nested=True)
        if self.asvar:
            context[self.asvar] = result
            return ''
        else:
            return result
Example #20
0
    def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ungettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.ugettext(singular)
        default_value = context.template.engine.string_if_invalid

        def render_value(key):
            if key in context:
                val = context[key]
            else:
                val = default_value % key if '%s' in default_value else default_value
            return render_value_in_context(val, context)

        data = {v: render_value(v) for v in vars}
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError(
                    "'blocktrans' is unable to format string returned by gettext: %r using %r"
                    % (result, data)
                )
            with translation.override(None):
                result = self.render(context, nested=True)
        if self.asvar:
            context[self.asvar] = result
            return ''
        else:
            return result
Example #21
0
    def test_pgettext(self):
        # Reset translation catalog to include other/locale/de
        extended_locale_paths = settings.LOCALE_PATHS + (os.path.join(here, "other", "locale"),)
        with self.settings(LOCALE_PATHS=extended_locale_paths):
            from django.utils.translation import trans_real

            trans_real._active = local()
            trans_real._translations = {}
            with translation.override("de"):
                self.assertEqual(pgettext("unexisting", "May"), u"May")
                self.assertEqual(pgettext("month name", "May"), u"Mai")
                self.assertEqual(pgettext("verb", "May"), u"Kann")
                self.assertEqual(npgettext("search", "%d result", "%d results", 4) % 4, u"4 Resultate")
Example #22
0
    def test_pgettext(self):
        # Reset translation catalog to include other/locale/de
        self.old_locale_paths = settings.LOCALE_PATHS
        settings.LOCALE_PATHS += (os.path.join(os.path.dirname(os.path.abspath(__file__)), 'other', 'locale'),)
        from django.utils.translation import trans_real
        trans_real._active = {}
        trans_real._translations = {}
        activate('de')

        self.assertEqual(pgettext("unexisting", "May"), u"May")
        self.assertEqual(pgettext("month name", "May"), u"Mai")
        self.assertEqual(pgettext("verb", "May"), u"Kann")
        self.assertEqual(npgettext("search", "%d result", "%d results", 4) % 4, u"4 Resultate")

        settings.LOCALE_PATHS = self.old_locale_paths
Example #23
0
    def test_pgettext(self):
        # Reset translation catalog to include other/locale/de
        self.old_locale_paths = settings.LOCALE_PATHS
        settings.LOCALE_PATHS += (os.path.join(os.path.dirname(os.path.abspath(__file__)), 'other', 'locale'),)
        from django.utils.translation import trans_real
        trans_real._active = {}
        trans_real._translations = {}
        activate('de')

        self.assertEqual(pgettext("unexisting", "May"), u"May")
        self.assertEqual(pgettext("month name", "May"), u"Mai")
        self.assertEqual(pgettext("verb", "May"), u"Kann")
        self.assertEqual(npgettext("search", "%d result", "%d results", 4) % 4, u"4 Resultate")

        settings.LOCALE_PATHS = self.old_locale_paths
Example #24
0
    def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ungettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                # result = translation.ugettext(singular)
                result = PhraseDelegate(singular)
        default_value = settings.TEMPLATE_STRING_IF_INVALID
        render_value = lambda v: render_value_in_context(
            context.get(v, default_value), context)
        data = dict([(v, render_value(v)) for v in vars])
        context.pop()

        # FIX
        # try:
        #     result = result % data
        # except (KeyError, ValueError):
        #     if nested:
        #         # Either string is malformed, or it's a bug
        #         raise TemplateSyntaxError("'blocktrans' is unable to format "
        #             "string returned by gettext: %r using %r" % (result, data))
        #     with translation.override(None):
        #         result = self.render(context, nested=True)

        return result
Example #25
0
    def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ungettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                # result = translation.ugettext(singular)
                result = PhraseDelegate(singular, self.trimmed)
        render_value = lambda v: render_value_in_context(
            context.get(v, template_string_if_valid()), context)
        data = dict([(v, render_value(v)) for v in vars])
        context.pop()

        # FIX
        # try:
        #     result = result % data
        # except (KeyError, ValueError):
        #     if nested:
        #         # Either string is malformed, or it's a bug
        #         raise TemplateSyntaxError("'blocktrans' is unable to format "
        #             "string returned by gettext: %r using %r" % (result, data))
        #     with translation.override(None):
        #         result = self.render(context, nested=True)

        return result
Example #26
0
 def render(self, context, nested=False):
     if self.message_context:
         message_context = self.message_context.resolve(context)
     else:
         message_context = None
     tmp_context = {}
     for var, val in self.extra_context.items():
         tmp_context[var] = val.resolve(context)
     # Update() works like a push(), so corresponding context.pop() is at
     # the end of function
     context.update(tmp_context)
     singular, vars = self.render_token_list(self.singular)
     if self.plural and self.countervar and self.counter:
         count = self.counter.resolve(context)
         context[self.countervar] = count
         plural, plural_vars = self.render_token_list(self.plural)
         if message_context:
             result = translation.npgettext(message_context, singular,
                                            plural, count)
         else:
             result = translation.ungettext(singular, plural, count)
         vars.extend(plural_vars)
     else:
         if message_context:
             result = translation.pgettext(message_context, singular)
         else:
             result = translation.ugettext(singular)
     default_value = settings.TEMPLATE_STRING_IF_INVALID
     render_value = lambda v: render_value_in_context(
         context.get(v, default_value), context)
     data = dict((v, render_value(v)) for v in vars)
     context.pop()
     try:
         result = result % data
     except (KeyError, ValueError):
         if nested:
             # Either string is malformed, or it's a bug
             raise TemplateSyntaxError(
                 "'blocktrans' is unable to format "
                 "string returned by gettext: %r using %r" % (result, data))
         with translation.override(None):
             result = self.render(context, nested=True)
     return result
Example #27
0
 def render(self, context):
     if self.message_context:
         message_context = self.message_context.resolve(context)
     else:
         message_context = None
     tmp_context = {}
     for var, val in self.extra_context.items():
         tmp_context[var] = val.resolve(context)
     # Update() works like a push(), so corresponding context.pop() is at
     # the end of function
     context.update(tmp_context)
     singular, vars = self.render_token_list(self.singular)
     # Escape all isolated '%'
     singular = re.sub(u'%(?!\()', u'%%', singular)
     if self.plural and self.countervar and self.counter:
         count = self.counter.resolve(context)
         context[self.countervar] = count
         plural, plural_vars = self.render_token_list(self.plural)
         plural = re.sub(u'%(?!\()', u'%%', plural)
         if message_context:
             result = translation.npgettext(message_context, singular,
                                            plural, count)
         else:
             result = translation.ungettext(singular, plural, count)
         vars.extend(plural_vars)
     else:
         if message_context:
             result = translation.pgettext(message_context, singular)
         else:
             result = translation.ugettext(singular)
     data = dict([(v, _render_value_in_context(context.get(v, ''), context))
                  for v in vars])
     context.pop()
     try:
         result = result % data
     except KeyError:
         with translation.override(None):
             result = self.render(context)
     return result
Example #28
0
 def render(self, context):
     if self.message_context:
         message_context = self.message_context.resolve(context)
     else:
         message_context = None
     tmp_context = {}
     for var, val in self.extra_context.items():
         tmp_context[var] = val.resolve(context)
     # Update() works like a push(), so corresponding context.pop() is at
     # the end of function
     context.update(tmp_context)
     singular, vars = self.render_token_list(self.singular)
     # Escape all isolated '%'
     singular = re.sub('%(?!\()', '%%', singular)
     if self.plural and self.countervar and self.counter:
         count = self.counter.resolve(context)
         context[self.countervar] = count
         plural, plural_vars = self.render_token_list(self.plural)
         plural = re.sub('%(?!\()', '%%', plural)
         if message_context:
             result = translation.npgettext(message_context, singular,
                                            plural, count)
         else:
             result = translation.ungettext(singular, plural, count)
         vars.extend(plural_vars)
     else:
         if message_context:
             result = translation.pgettext(message_context, singular)
         else:
             result = translation.ugettext(singular)
     data = dict([(v, _render_value_in_context(context.get(v, ''), context)) for v in vars])
     context.pop()
     try:
         result = result % data
     except (KeyError, ValueError):
         with translation.override(None):
             result = self.render(context)
     return result
Example #29
0
 def make_tech_skill_category_list(self):
   full_tech_skill_list = TechSkill.objects.order_by('-weight')
   language_list = full_tech_skill_list.filter(category=TechSkill.LANGUAGE)
   framework_list = full_tech_skill_list.filter(category=TechSkill.FRAMEWORK)
   system_list = full_tech_skill_list.filter(category=TechSkill.SYSTEM)
   software_list = full_tech_skill_list.filter(category=TechSkill.SOFTWARE)
   database_list = full_tech_skill_list.filter(category=TechSkill.DATABASE)
   other_list = full_tech_skill_list.filter(category=TechSkill.OTHER)
   return [
     { 'list': language_list,
       'label': npgettext('category', 'Programming Language', 'Programming Languages', len(language_list)) },
     { 'list': framework_list,
       'label': npgettext('category', 'Framework', 'Frameworks', len(framework_list)) },
     { 'list': system_list,
       'label': npgettext('category', 'Operating System', 'Operating Systems', len(system_list)) },
     { 'list': software_list,
       'label': npgettext('category', 'Software', 'Softwares', len(software_list)) },
     { 'list': database_list,
       'label': npgettext('category', 'Database', 'Databases', len(database_list)) },
     { 'list': other_list,
       'label': npgettext('category', 'Other', 'Others', len(other_list)) },
   ]
Example #30
0
django.utils.translation.npgettext_lazy('context', 'nptest_lazy',
                                        'nptests_lazy', 42)

translation_module.gettext('tm_test')
translation_module.gettext_lazy('tm_test_lazy')
translation_module.gettext_noop('tm_test_noop')
translation_module.ugettext('tm_utest')
translation_module.ugettext_lazy('tm_utest_lazy')
translation_module.ugettext_noop('tm_utest_noop')
translation_module.pgettext('context', 'tm_ptest')
translation_module.pgettext_lazy('context', 'tm_ptest_lazy')
translation_module.ngettext('tm_ntest', 'tm_ntests', 42)
translation_module.ngettext_lazy('tm_ntest_lazy', 'tm_ntests_lazy', 42)
translation_module.ungettext('tm_untest', 'tm_untests', 42)
translation_module.ungettext_lazy('tm_untest_lazy', 'tm_untests_lazy', 42)
translation_module.npgettext('context', 'tm_nptest', 'tm_nptests', 42)
translation_module.npgettext_lazy('context', 'tm_nptest_lazy',
                                  'tm_nptests_lazy', 42)

translation_module_2.gettext('tm2_test')
translation_module_2.gettext_lazy('tm2_test_lazy')
translation_module_2.gettext_noop('tm2_test_noop')
translation_module_2.ugettext('tm2_utest')
translation_module_2.ugettext_lazy('tm2_utest_lazy')
translation_module_2.ugettext_noop('tm2_utest_noop')
translation_module_2.pgettext('context', 'tm2_ptest')
translation_module_2.pgettext_lazy('context', 'tm2_ptest_lazy')
translation_module_2.ngettext('tm2_ntest', 'tm2_ntests', 42)
translation_module_2.ngettext_lazy('tm2_ntest_lazy', 'tm2_ntests_lazy', 42)
translation_module_2.ungettext('tm2_untest', 'tm2_untests', 42)
translation_module_2.ungettext_lazy('tm2_untest_lazy', 'tm2_untests_lazy', 42)
Example #31
0
 def npgettext(context, singular, plural, number):
     return escape(npgettext(context, singular, plural, number))
Example #32
0
 def npgettext(context, singular, plural, number):
     return escape(npgettext(context, singular, plural, number))
Example #33
0
def nice_repr(timedelta, display='long', sep=', '):
    """
    Turns a datetime.timedelta object into a nice string repr.

    display can be 'minimal', 'short' or 'long' [default].

    >>> from datetime import timedelta as td
    >>> nice_repr(td(days=1, hours=2, minutes=3, seconds=4))
    '1 day, 2 hours, 3 minutes, 4 seconds'
    >>> nice_repr(td(days=1, seconds=1), 'minimal')
    '1d, 1s'
    """

    assert isinstance(timedelta, datetime.timedelta), 'First argument must be a timedelta.'

    result = []

    weeks = timedelta.days // 7
    days = timedelta.days % 7
    hours = timedelta.seconds // 3600
    minutes = (timedelta.seconds % 3600) // 60
    seconds = timedelta.seconds % 60

    if display == 'simple-no-seconds':
        days += weeks * 7
        if days:
            if hours or minutes:
                return '%d day%s %d:%02d' % (days, 's'[days == 1:], hours, minutes)
            return '%d day%s' % (days, 's'[days == 1:])
        else:
            return '%d:%02d' % (hours, minutes)
    elif display == 'sql':
        days += weeks * 7
        return '%d %02d:%02d:%02d' % (days, hours, minutes, seconds)
    elif display == 'simple':
        days += weeks * 7
        if days:
            return '%d day%s %02d:%02d:%02d' % (days, 's'[days == 1:], hours, minutes, seconds)
        else:
            return '%02d:%02d:%02d' % (hours, minutes, seconds)
    elif display == 'localized':
        days += weeks * 7
        if days:
            return npgettext('time format with day', '%d day %h:%m:%s', '%d days %h:%m:%s', days) \
                .replace('%d', str(days)).replace('%h', '%02d' % hours).replace('%m', '%02d' % minutes) \
                .replace('%s', '%02d' % seconds)
        else:
            return pgettext('time format without day', '%h:%m:%s') \
                .replace('%h', '%02d' % hours).replace('%m', '%02d' % minutes).replace('%s', '%02d' % seconds)
    elif display == 'localized-no-seconds':
        days += weeks * 7
        if days:
            if hours or minutes:
                return npgettext('time format no seconds with day', '%d day %h:%m', '%d days %h:%m', days) \
                    .replace('%d', str(days)).replace('%h', '%02d' % hours).replace('%m', '%02d' % minutes)
            return ungettext('%d day', '%d days', days) % days
        else:
            return pgettext('hours and minutes', '%h:%m').replace('%h', '%02d' % hours).replace('%m', '%02d' % minutes)
    elif display == 'concise':
        days += weeks * 7
        if days:
            return '%dd %02d:%02d:%02d' % (days, hours, minutes, seconds)
        else:
            return '%02d:%02d:%02d' % (hours, minutes, seconds)
    elif display == 'noday':
        days += weeks * 7
        hours += days * 24
        return '%02d:%02d:%02d' % (hours, minutes, seconds)
    elif display == 'minimal':
        words = ['w', 'd', 'h', 'm', 's']
    elif display == 'short':
        words = [' wks', ' days', ' hrs', ' min', ' sec']
    else:
        words = [' weeks', ' days', ' hours', ' minutes', ' seconds']

    values = [weeks, days, hours, minutes, seconds]

    for i in range(len(values)):
        if values[i]:
            if values[i] == 1 and len(words[i]) > 1:
                result.append('%i%s' % (values[i], words[i].rstrip('s')))
            else:
                result.append('%i%s' % (values[i], words[i]))

    return sep.join(result)
Example #34
0
 def trans(self, count):
     if self.msgctxt:
         return npgettext(self.msgctxt, self.msgid, self.plural, count)
     return ngettext(self.msgid, self.plural, count)
Example #35
0
 def npgettext(context, singular, plural, number):
     return escape(translation.npgettext(context, singular, plural, number))
Example #36
0
def nice_repr(timedelta, display='long', sep=', '):
    """
    Turns a datetime.timedelta object into a nice string repr.

    display can be 'minimal', 'short' or 'long' [default].

    >>> from datetime import timedelta as td
    >>> nice_repr(td(days=1, hours=2, minutes=3, seconds=4))
    '1 day, 2 hours, 3 minutes, 4 seconds'
    >>> nice_repr(td(days=1, seconds=1), 'minimal')
    '1d, 1s'
    """

    assert isinstance(timedelta, datetime.timedelta), 'First argument must be a timedelta.'

    result = []

    weeks = timedelta.days / 7
    days = timedelta.days % 7
    hours = timedelta.seconds / 3600
    minutes = (timedelta.seconds % 3600) / 60
    seconds = timedelta.seconds % 60

    if display == 'simple-no-seconds':
        days += weeks * 7
        if days:
            if hours or minutes:
                return '%d day%s %d:%02d' % (days, 's'[days == 1:], hours, minutes)
            return '%d day%s' % (days, 's'[days == 1:])
        else:
            return '%d:%02d' % (hours, minutes)
    elif display == 'sql':
        days += weeks * 7
        return '%d %02d:%02d:%02d' % (days, hours, minutes, seconds)
    elif display == 'simple':
        days += weeks * 7
        if days:
            return '%d day%s %02d:%02d:%02d' % (days, 's'[days == 1:], hours, minutes, seconds)
        else:
            return '%02d:%02d:%02d' % (hours, minutes, seconds)
    elif display == 'localized':
        days += weeks * 7
        if days:
            return npgettext('time format with day', '%d day %h:%m:%s', '%d days %h:%m:%s', days) \
                .replace('%d', str(days)).replace('%h', '%02d' % hours).replace('%m', '%02d' % minutes) \
                .replace('%s', '%02d' % seconds)
        else:
            return pgettext('time format without day', '%h:%m:%s') \
                .replace('%h', '%02d' % hours).replace('%m', '%02d' % minutes).replace('%s', '%02d' % seconds)
    elif display == 'localized-no-seconds':
        days += weeks * 7
        if days:
            if hours or minutes:
                return npgettext('time format no seconds with day', '%d day %h:%m', '%d days %h:%m', days) \
                    .replace('%d', str(days)).replace('%h', '%02d' % hours).replace('%m', '%02d' % minutes)
            return ungettext('%d day', '%d days', days) % days
        else:
            return pgettext('hours and minutes', '%h:%m').replace('%h', '%02d' % hours).replace('%m', '%02d' % minutes)
    elif display == 'concise':
        days += weeks * 7
        if days:
            return '%dd %02d:%02d:%02d' % (days, hours, minutes, seconds)
        else:
            return '%02d:%02d:%02d' % (hours, minutes, seconds)
    elif display == 'noday':
        days += weeks * 7
        hours += days * 24
        return '%02d:%02d:%02d' % (hours, minutes, seconds)
    elif display == 'minimal':
        words = ['w', 'd', 'h', 'm', 's']
    elif display == 'short':
        words = [' wks', ' days', ' hrs', ' min', ' sec']
    else:
        words = [' weeks', ' days', ' hours', ' minutes', ' seconds']

    values = [weeks, days, hours, minutes, seconds]

    for i in range(len(values)):
        if values[i]:
            if values[i] == 1 and len(words[i]) > 1:
                result.append('%i%s' % (values[i], words[i].rstrip('s')))
            else:
                result.append('%i%s' % (values[i], words[i]))

    return sep.join(result)
Example #37
0
from __future__ import unicode_literals
Example #38
0
 def won_quotes():
     count = Quote.objects.filter(status__won=True).count()
     return npgettext('billing-quote_stats', '{count} won',
                      '{count} won', count).format(count=count)