Example #1
0
    def __init__(self,
                 sourceLang,
                 targetLang,
                 sourceLocale,
                 targetLocale,
                 fullmatch=False):
        """Initialize a PercentTranslator instance

           Args:
              sourceLang (str): source language in full spelling, e.g., 'English'
                                ignored if sourceLocale is provided
              sourceLocale (str): source locale identifier
              targetLang (str): target language in full spelling, e.g., 'French'
                                ignored if targetLocale is provided
              targetLocale (str): target locale identifier
              fullmatch (bool): whether to full-match a text or not
                                if True, PercentTranslator can act as an independent translator
                                if False, PercentTranslator must work with other translators
        """

        self.srcLang = NAME_YAPPN_MAPPINGS[sourceLang]
        self.srcLocale = sourceLocale if sourceLocale else re.sub(
            '-', '_', CULTURE_CODES[sourceLang][0])
        self.tgtLocale = targetLocale if targetLocale else re.sub(
            '-', '_', CULTURE_CODES[targetLang][0])
        self._fullmatch = fullmatch

        self.srcDecimalSymbol = numbers.get_decimal_symbol(self.srcLocale)
        self.tgtDecimalSymbol = numbers.get_decimal_symbol(self.tgtLocale)
Example #2
0
def format_scientific_field(spec, prec, number, locale):
    prec = SCIENTIFIC_DECIMAL_DIGITS if prec is None else int(prec)
    format_ = u'0.%sE+000' % (u'#' * prec)
    pattern = parse_pattern(format_)
    decimal_symbol = get_decimal_symbol(locale)
    string = pattern.apply(number, locale).replace(u'.', decimal_symbol)
    return string.lower() if spec.islower() else string
Example #3
0
def format_scientific_field(spec, prec, number, locale):
    prec = SCIENTIFIC_DECIMAL_DIGITS if prec is None else int(prec)
    format_ = u'0.%sE+000' % (u'#' * prec)
    pattern = parse_pattern(format_)
    decimal_symbol = get_decimal_symbol(locale)
    string = pattern.apply(number, locale).replace(u'.', decimal_symbol)
    return string.lower() if spec.islower() else string
Example #4
0
def parse_value(value):
    """
    Accepts a string value and attempts to parce it as a currency value.

    Returns the extracted numeric value converted to a string
    """
    l_currency_language_code, l_currency_code = _getCodes()

    curSym = get_currency_symbol(l_currency_code, l_currency_language_code)
    grpSym = get_group_symbol(locale=l_currency_language_code.lower())
    decSym = get_decimal_symbol(locale=l_currency_language_code.lower())

    # Convert the Official characters into what comes from the keyboard.
    #   This section may need to grow over time.
    #   - Character 160 is a non-breaking space, which is different from a typed space
    if ord(grpSym) == 160:
        value = value.replace(u" ", grpSym)

    allSym = _getSymbols(value)
    invalidSym = allSym.replace(curSym, "").replace(grpSym, "").replace(decSym, "").replace(u"-", "")

    value = value.replace(curSym, "")

    if allSym.count(decSym) > 1:
        raise NumberFormatError(default_error_messages["decimal_symbol"] % decSym)
    elif (allSym.count(decSym) == 1 and allSym[-1] != decSym) or len(invalidSym) > 0:
        raise NumberFormatError(default_error_messages["invalid_format"] % (grpSym, decSym))
    elif value.count(decSym) == 1:
        value = parse_decimal(value, locale=l_currency_language_code.lower())
    else:
        value = parse_number(value, locale=l_currency_language_code.lower())

    # The value is converted into a string because the parse functions return
    # floats
    return str(value)
def parse_value(value):
    """
    Accepts a string value and attempts to parce it as a currency value.

    Returns the extracted numeric value converted to a string
    """
    l_currency_language_code, l_currency_code = _getCodes()

    curSym = get_currency_symbol(l_currency_code, l_currency_language_code)
    grpSym = get_group_symbol(locale=l_currency_language_code.lower())
    decSym = get_decimal_symbol(locale=l_currency_language_code.lower())

    # Convert the Official characters into what comes from the keyboard.
    #   This section may need to grow over time.
    #   - Character 160 is a non-breaking space, which is different from a typed space
    if ord(grpSym) == 160:
        value = value.replace(u' ', grpSym)

    allSym = _getSymbols(value)
    invalidSym = allSym.replace(curSym, '').replace(
        grpSym, '').replace(decSym, '').replace(u'-', '')

    value = value.replace(curSym, '')

    if allSym.count(decSym) > 1:
        raise NumberFormatError(default_error_messages['decimal_symbol'] % decSym)
    if (allSym.count(decSym) == 1 and allSym[-1] != decSym) or invalidSym:
        raise NumberFormatError(default_error_messages['invalid_format'] % (grpSym, decSym))
    if value.count(decSym) == 1:
        value = parse_decimal(value, locale=l_currency_language_code.lower())
    else:
        value = parse_number(value, locale=l_currency_language_code.lower())

    # The value is converted into a string because the parse functions return floats
    return str(value)
Example #6
0
    def get_decimal_symbol(self):
        """Return the symbol used to separate decimal fractions

        >>> Locale('en', 'US').get_decimal_symbol()
        u'.'
        """
        return numbers.get_decimal_symbol(self)
Example #7
0
def parse_decimal(string, locale):
    locale = Locale.parse(locale)
    decimal_symbol = get_decimal_symbol(locale)
    group_symbol = get_group_symbol(locale)
    group_symbol = " " if group_symbol == "\xa0" else group_symbol
    return Decimal(
        string.replace(group_symbol, "").replace(decimal_symbol, "."))
Example #8
0
def number_size_format(size, lang="en"):
    '''
    Formatea un tamaño de fichero en el idioma actual
    '''
    if not size:
        return None, None
    elif int(float(size))==0:
        return "0", ("B","bytes")

    if lang in format_cache:
        decimal_sep, group_sep = format_cache[lang]
    else:
        decimal_sep, group_sep = format_cache[lang] = (get_decimal_symbol(lang), get_group_symbol(lang))

    try:
        if size<1000: # no aplica para los bytes
            return str(size), ("B","bytes")
        else:
            size = log(float(size),1000)
            number = 1000**(size-int(size))

            # parte decimal
            dec_part = int((number-int(number))*100)
            dec_part = "" if dec_part==0 else decimal_sep+"0"+str(dec_part) if dec_part<10 else decimal_sep+str(dec_part)

            # genera salida
            return ''.join(
                reversed([c + group_sep if i != 0 and i % 3 == 0 else c for i, c in enumerate(reversed(str(int(number))))])
            ) + dec_part, (("KB","kilobytes"),("MB","megabytes"),("GB","gigabytes"),("TB","terabytes"))[int(size)-1]
    except BaseException as e:
        logging.exception(e)
        return None, None
Example #9
0
def format_currency_with_options(number,
                                 currency,
                                 locale='en',
                                 trailing_zeroes=True):
    s = format_currency(number, currency, locale=locale)
    if not trailing_zeroes:
        s = s.replace(get_decimal_symbol(locale) + '00', '')
    return s
Example #10
0
def format_money(number,
                 currency,
                 format=None,
                 locale='en',
                 trailing_zeroes=True):
    s = format_currency(number, currency, format, locale=locale)
    if not trailing_zeroes:
        s = s.replace(get_decimal_symbol(locale) + '00', '')
    return s
Example #11
0
 def normalize_amount_str(self, formatted: str, ndigits: int = 4):
     decimal_symbol = get_decimal_symbol(self.locale)
     str_number_parts = formatted.partition(decimal_symbol)
     if str_number_parts[2] == "":
         # 3,995 -> 3,995.0
         return f"{formatted}{decimal_symbol}0"
     elif len(str_number_parts[2]) <= 2:
         # 1.1 -> 1.1 ; 1.12 -> 1.12
         return formatted
     else:
         # 1.123 -> 1.1230 ; 1.0123 -> 1.0123 ; 0.00123 -> 0.00123 ; 1.001 -> 1.0010
         return formatted + "0" * (ndigits - len(str_number_parts[2]))
Example #12
0
 def __getitem__(self, name):
     char = name[0]
     num = len(name)
     if char == 'G':
         return self.format_era(char, num)
     elif char in ('y', 'Y', 'u'):
         return self.format_year(char, num)
     elif char in ('Q', 'q'):
         return self.format_quarter(char, num)
     elif char in ('M', 'L'):
         return self.format_month(char, num)
     elif char in ('w', 'W'):
         return self.format_week(char, num)
     elif char == 'd':
         return self.format(self.value.day, num)
     elif char == 'D':
         return self.format_day_of_year(num)
     elif char == 'F':
         return self.format_day_of_week_in_month()
     elif char in ('E', 'e', 'c'):
         return self.format_weekday(char, num)
     elif char == 'a':
         return self.format_period(char)
     elif char == 'h':
         if self.value.hour % 12 == 0:
             return self.format(12, num)
         else:
             return self.format(self.value.hour % 12, num)
     elif char == 'H':
         return self.format(self.value.hour, num)
     elif char == 'K':
         return self.format(self.value.hour % 12, num)
     elif char == 'k':
         if self.value.hour == 0:
             return self.format(24, num)
         else:
             return self.format(self.value.hour, num)
     elif char == 'm':
         return self.format(self.value.minute, num)
     elif char == 's':
         return self.format(self.value.second, num)
     elif char == 'S':
         return self.format_frac_seconds(num)
     elif char == 'T':
         return self.format_decimal_frac_seconds(num)
     elif char == 'A':
         return self.format_milliseconds_in_day(num)
     elif char in ('z', 'Z', 'v', 'V'):
         return self.format_timezone(char, num)
     elif char == '_':
         return get_decimal_symbol(self.locale)
     else:
         raise KeyError('Unsupported date/time field %r' % char)
 def __call__(self, form, field):
     data = field.raw_data[0].replace(
         numbers.get_group_symbol(DEFAULT_LOCALE), '').replace(' ', '')
     decimal_symbol = numbers.get_decimal_symbol(DEFAULT_LOCALE)
     if data and decimal_symbol in data:
         if self.max_decimals == 0:
             raise validators.ValidationError(
                 self.messages['INVALID_INTEGER'])
         elif len(data.split(decimal_symbol)[1]) > self.max_decimals:
             raise validators.ValidationError(
                 self.messages['INVALID_DECIMAL'] %
                 dict(max=self.max_decimals))
Example #14
0
 def __getitem__(self, name):
     char = name[0]
     num = len(name)
     if char == 'G':
         return self.format_era(char, num)
     elif char in ('y', 'Y', 'u'):
         return self.format_year(char, num)
     elif char in ('Q', 'q'):
         return self.format_quarter(char, num)
     elif char in ('M', 'L'):
         return self.format_month(char, num)
     elif char in ('w', 'W'):
         return self.format_week(char, num)
     elif char == 'd':
         return self.format(self.value.day, num)
     elif char == 'D':
         return self.format_day_of_year(num)
     elif char == 'F':
         return self.format_day_of_week_in_month()
     elif char in ('E', 'e', 'c'):
         return self.format_weekday(char, num)
     elif char == 'a':
         return self.format_period(char)
     elif char == 'h':
         if self.value.hour % 12 == 0:
             return self.format(12, num)
         else:
             return self.format(self.value.hour % 12, num)
     elif char == 'H':
         return self.format(self.value.hour, num)
     elif char == 'K':
         return self.format(self.value.hour % 12, num)
     elif char == 'k':
         if self.value.hour == 0:
             return self.format(24, num)
         else:
             return self.format(self.value.hour, num)
     elif char == 'm':
         return self.format(self.value.minute, num)
     elif char == 's':
         return self.format(self.value.second, num)
     elif char == 'S':
         return self.format_frac_seconds(num)
     elif char == 'T':
         return self.format_decimal_frac_seconds(num)
     elif char == 'A':
         return self.format_milliseconds_in_day(num)
     elif char in ('z', 'Z', 'v', 'V'):
         return self.format_timezone(char, num)
     elif char == '_':
         return get_decimal_symbol(self.locale)
     else:
         raise KeyError('Unsupported date/time field %r' % char)
Example #15
0
    def test_bins_nulls(self):
        rows = []

        for i in range(0, 100):
            rows.append([Decimal(i) / Decimal('100')])

        rows.append([None])

        new_table = Table(rows, self.column_names,
                          self.column_types).bins('number')

        self.assertColumnNames(new_table, ['number', 'Count'])
        self.assertColumnTypes(new_table, [Text, Number])

        self.assertSequenceEqual(new_table.rows[0], [
            u'[0' + get_decimal_symbol() + u'0 - 0' + get_decimal_symbol() +
            u'1)', 10
        ])
        self.assertSequenceEqual(new_table.rows[3], [
            u'[0' + get_decimal_symbol() + u'3 - 0' + get_decimal_symbol() +
            u'4)', 10
        ])
        self.assertSequenceEqual(new_table.rows[9], [
            u'[0' + get_decimal_symbol() + u'9 - 1' + get_decimal_symbol() +
            u'0]', 10
        ])
        self.assertSequenceEqual(new_table.rows[10], [None, 1])
Example #16
0
    def test_print_table_max_precision(self):
        rows = (
            ('1.745', 1.745, 1.72),
            ('11.123456', 11.123456, 5.10),
            ('0', 0, 0.10)
        )

        column_names = ['text_number', 'real_long_number', 'real_short_number']
        column_types = [
            self.text_type,
            self.number_type,
            self.number_type
        ]
        table = Table(rows, column_names, column_types)

        output = six.StringIO()
        table.print_table(output=output, max_precision=2)
        lines = output.getvalue().split('\n')

        # Text shouldn't be affected
        self.assertIn(u' 1.745 ', lines[2])
        self.assertIn(u' 11.123456 ', lines[3])
        self.assertIn(u' 0 ', lines[4])
        # Test real precision above max
        self.assertIn(u' 1' + get_decimal_symbol() + u'74… ', lines[2])
        self.assertIn(u' 11' + get_decimal_symbol() + u'12… ', lines[3])
        self.assertIn(u' 0' + get_decimal_symbol() + u'00… ', lines[4])
        # Test real precision below max
        self.assertIn(u' 1' + get_decimal_symbol() + u'72 ', lines[2])
        self.assertIn(u' 5' + get_decimal_symbol() + u'10 ', lines[3])
        self.assertIn(u' 0' + get_decimal_symbol() + u'10 ', lines[4])
Example #17
0
def number_size_format_filter(size):
    '''
    Formatea un tamaño de fichero en el idioma actual
    '''
    size=log(size,1024)
    decsep = get_decimal_symbol(locale=g.lang)
    intpart = format_decimal(round(1024**(size-int(size)), 2), locale=g.lang)
    if decsep in intpart:
        intpart, decpart = intpart.split(decsep)
        if len(decpart) > 2: # format_decimal sufre de problemas de precisión
            decpart = str(round(float("0.%s" % decpart), 2))[2:]
        return "%s%s%s %s" % (intpart, decsep, decpart.ljust(2, "0"), ("B","KiB","MiB","GiB","TiB")[int(size)])
    return "%s%s00 %s" % (intpart, decsep, ("B","KiB","MiB","GiB","TiB")[int(size)])
Example #18
0
 def __call__(self, form, field):
     data = (field.raw_data[0].replace(
         numbers.get_group_symbol(flask_babel.get_locale()),
         "").replace(" ", ""))
     decimal_symbol = numbers.get_decimal_symbol(flask_babel.get_locale())
     if data and decimal_symbol in data:
         if self.max_decimals == 0:
             raise validators.ValidationError(
                 self.messages["INVALID_INTEGER"])
         if len(data.split(decimal_symbol)[1]) > self.max_decimals:
             raise validators.ValidationError(
                 self.messages["INVALID_DECIMAL"] %
                 dict(max=self.max_decimals))
Example #19
0
def parse_decimal(string, force_decimal=False):
    """Parse a localized decimal string into a float if `force_decimal` is
    False, else into a real :class:`decimal.Decimal` value.

    :param string: localized decimal string value
    :param force_decimal: whether to return Decimal instead of float
    """
    locale = get_locale()
    sep = numbers.get_decimal_symbol(locale)
    num, decimals = string.rsplit(sep, 1)
    num = numbers.parse_number(num, locale=locale)
    string = '%s.%s' % (num, decimals)
    return Decimal(string) if force_decimal else float(string)
Example #20
0
def format_decimal(value, digits=2):
    locale = get_locale()
    v = ("%%.%df" % digits) % value
    if not digits:
        return numbers.format_number(value, locale=locale)
    num, decimals = v.split(".", 1)

    if num == "-0":
        val = "-0"
    else:
        val = numbers.format_number(int(num), locale=locale)

    return val + unicode(numbers.get_decimal_symbol(locale) + decimals)
Example #21
0
def parse_decimal(string, force_decimal=False):
    """Parse a localized decimal string into a float if `force_decimal` is
    False, else into a real :class:`decimal.Decimal` value.

    :param string: localized decimal string value
    :param force_decimal: whether to return Decimal instead of float
    """
    locale = get_locale()
    sep = numbers.get_decimal_symbol(locale)
    num, decimals = string.rsplit(sep, 1)
    num = numbers.parse_number(num, locale=locale)
    string = '%s.%s' % (num, decimals)
    return Decimal(string) if force_decimal else float(string)
Example #22
0
def format_decimal(value, digits=2):
    locale = get_locale()
    v = ("%%.%df" % digits) % value
    if digits == 0:
        return numbers.format_number(value, locale=locale)
    num, decimals = v.split(".", 1)

    if num == "-0":
        val = "-0"
    else:
        val = numbers.format_number(int(num), locale=locale)

    return val + unicode(numbers.get_decimal_symbol(locale) + decimals)
Example #23
0
def add_helpers_to_context(tell_sentry, context, loc, request=None):
    context['locale'] = loc
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(tell_sentry, request, loc, *a, **kw)
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_currency_with_options(*a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['parse_decimal'] = lambda *a: parse_decimal(*a, locale=loc)
    def _to_age(delta):
        try:
            return to_age(delta, loc)
        except:
            return to_age(delta, 'en')
    context['to_age'] = _to_age
Example #24
0
def add_helpers_to_context(tell_sentry, context, loc, request=None):
    context['locale'] = loc
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(tell_sentry, request, loc, *a, **kw)
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_currency_with_options(*a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['parse_decimal'] = lambda *a: parse_decimal(*a, locale=loc)
    def _to_age(delta, **kw):
        try:
            return to_age(delta, loc, **kw)
        except:
            return to_age(delta, 'en', **kw)
    context['to_age'] = _to_age
Example #25
0
def add_helpers_to_context(context, loc):
    context['escape'] = lambda s: s  # to be overriden by renderers
    context['locale'] = loc
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(context, loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(context, loc, *a, **kw)
    context['Money'] = Money
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_money(
        *a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['format_datetime'] = lambda *a: format_datetime(*a, locale=loc)
    context['format_date'] = lambda *a: format_date(*a, locale=loc)
    context['get_lang_options'] = lambda *a, **kw: get_lang_options(
        context['request'], loc, *a, **kw)
    context['to_age'] = to_age

    def format_delta(s, *a):
        return format_decimal(s, *a, format='+#,##0.00;-#,##0.00', locale=loc)

    context['format_delta'] = format_delta

    def parse_decimal_or_400(s, *a):
        try:
            return parse_decimal(s, *a, locale=loc)
        except (InvalidOperation, NumberFormatError, ValueError):
            raise InvalidNumber(s)

    context['parse_decimal'] = parse_decimal_or_400

    def to_age_str(o, **kw):
        if not isinstance(o, datetime):
            kw.setdefault('granularity', 'day')
        return format_timedelta(to_age(o), locale=loc, **kw)

    context['to_age_str'] = to_age_str

    def getdoc(name):
        versions = context['website'].docs[name]
        for lang in context['request'].accept_langs:
            doc = versions.get(lang)
            if doc:
                return doc
        return versions['en']

    context['getdoc'] = getdoc
Example #26
0
def add_helpers_to_context(tell_sentry, context, loc):
    context['escape'] = lambda s: s  # to be overriden by renderers
    context['locale'] = loc
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(context, loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(tell_sentry, context, loc, *a, **kw)
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_currency_with_options(*a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['parse_decimal'] = lambda *a: parse_decimal(*a, locale=loc)
    def _to_age(delta, **kw):
        try:
            return to_age(delta, loc, **kw)
        except:
            return to_age(delta, 'en', **kw)
    context['to_age'] = _to_age
Example #27
0
def inbound(request):
    context = request.context
    loc = context.locale = get_locale_for_request(request)
    context.decimal_symbol = get_decimal_symbol(locale=loc)
    context._ = lambda s, *a, **kw: get_text(request, loc, s, *a, **kw)
    context.ngettext = lambda *a, **kw: n_get_text(request, loc, *a, **kw)
    context.format_number = lambda *a: format_number(*a, locale=loc)
    context.format_decimal = lambda *a: format_decimal(*a, locale=loc)
    context.format_currency = lambda *a: format_currency(*a, locale=loc)
    context.format_percent = lambda *a: format_percent(*a, locale=loc)
    context.parse_decimal = lambda *a: parse_decimal(*a, locale=loc)
    def _to_age(delta):
        try:
            return to_age(delta, loc)
        except:
            return to_age(delta, 'en')
    context.to_age = _to_age
Example #28
0
def add_helpers_to_context(tell_sentry, context, loc):
    context["escape"] = lambda s: s  # to be overriden by renderers
    context["locale"] = loc
    context["decimal_symbol"] = get_decimal_symbol(locale=loc)
    context["_"] = lambda s, *a, **kw: get_text(context, loc, s, *a, **kw)
    context["ngettext"] = lambda *a, **kw: n_get_text(tell_sentry, context, loc, *a, **kw)
    context["format_number"] = lambda *a: format_number(*a, locale=loc)
    context["format_decimal"] = lambda *a: format_decimal(*a, locale=loc)
    context["format_currency"] = lambda *a, **kw: format_currency_with_options(*a, locale=loc, **kw)
    context["format_percent"] = lambda *a: format_percent(*a, locale=loc)
    context["parse_decimal"] = lambda *a: parse_decimal(*a, locale=loc)

    def _to_age(delta, **kw):
        try:
            return to_age(delta, loc, **kw)
        except:
            return to_age(delta, "en", **kw)

    context["to_age"] = _to_age
Example #29
0
def add_helpers_to_context(website, request):
    context = request.context
    loc = context["locale"] = get_locale_for_request(request, website)
    context["decimal_symbol"] = get_decimal_symbol(locale=loc)
    context["_"] = lambda s, *a, **kw: get_text(request, loc, s, *a, **kw)
    context["ngettext"] = lambda *a, **kw: n_get_text(website, request, loc, *a, **kw)
    context["format_number"] = lambda *a: format_number(*a, locale=loc)
    context["format_decimal"] = lambda *a: format_decimal(*a, locale=loc)
    context["format_currency"] = lambda *a, **kw: format_currency_with_options(*a, locale=loc, **kw)
    context["format_percent"] = lambda *a: format_percent(*a, locale=loc)
    context["parse_decimal"] = lambda *a: parse_decimal(*a, locale=loc)

    def _to_age(delta):
        try:
            return to_age(delta, loc)
        except:
            return to_age(delta, "en")

    context["to_age"] = _to_age
Example #30
0
def add_helpers_to_context(tell_sentry, context, loc):
    context['escape'] = lambda s: s  # to be overriden by renderers
    context['locale'] = loc
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(context, loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(tell_sentry, context, loc, *a, **kw)
    context['Money'] = Money
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_money(*a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['format_datetime'] = lambda *a: format_datetime(*a, locale=loc)
    context['parse_decimal'] = lambda *a: parse_decimal(*a, locale=loc)
    context['to_age'] = to_age
    def to_age_str(o, **kw):
        if not isinstance(o, datetime):
            kw.setdefault('granularity', 'day')
        return format_timedelta(to_age(o), locale=loc, **kw)
    context['to_age_str'] = to_age_str
Example #31
0
def inbound(request):
    context = request.context
    loc = context.locale = get_locale_for_request(request)
    context.decimal_symbol = get_decimal_symbol(locale=loc)
    context._ = lambda s, *a, **kw: get_text(request, loc, s, *a, **kw)
    context.ngettext = lambda *a, **kw: n_get_text(request, loc, *a, **kw)
    context.format_number = lambda *a: format_number(*a, locale=loc)
    context.format_decimal = lambda *a: format_decimal(*a, locale=loc)
    context.format_currency = lambda *a, **kw: format_currency_with_options(
        *a, locale=loc, **kw)
    context.format_percent = lambda *a: format_percent(*a, locale=loc)
    context.parse_decimal = lambda *a: parse_decimal(*a, locale=loc)

    def _to_age(delta):
        try:
            return to_age(delta, loc)
        except:
            return to_age(delta, 'en')

    context.to_age = _to_age
Example #32
0
def add_helpers_to_context(website, request):
    context = request.context
    loc = context['locale'] = get_locale_for_request(request, website)
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(request, loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(website, request, loc, *
                                                      a, **kw)
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_currency_with_options(
        *a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['parse_decimal'] = lambda *a: parse_decimal(*a, locale=loc)

    def _to_age(delta):
        try:
            return to_age(delta, loc)
        except:
            return to_age(delta, 'en')

    context['to_age'] = _to_age
Example #33
0
def number_size_format_filter(size, lang=None):
    '''
    Formatea un tamaño de fichero en el idioma actual
    '''
    if not size:
        return ""
    elif int(float(size))==0:
        return "0 B"

    if not lang:
        lang = g.lang

    if lang in format_cache:
        decimal_sep, group_sep = format_cache[lang]
    else:
        decimal_sep, group_sep = format_cache[lang] = (get_decimal_symbol(lang), get_group_symbol(lang))

    try:
        if float(size)<1000: # no aplica para los bytes
            return str(size)+" B"
        else:
            size = log(float(size),1024)
            number = 1024**(size-int(size))

            fix=0
            if number>=1000: #para que los tamaños entre 1000 y 1024 pasen a la unidad siguiente
                number/=1024
                fix=1

            # parte decimal
            dec_part = int((number-int(number))*100)
            dec_part = "" if dec_part==0 else decimal_sep+"0"+str(dec_part) if dec_part<10 else decimal_sep+str(dec_part)

            # genera salida
            return ''.join(
                reversed([c + group_sep if i != 0 and i % 3 == 0 else c for i, c in enumerate(reversed(str(int(number))))])
            ) + dec_part + (" KiB"," MiB"," GiB"," TiB")[int(size)-1+fix]
    except BaseException as e:
        logging.exception(e)
        return ""
Example #34
0
def add_helpers_to_context(tell_sentry, context, loc):
    context['escape'] = lambda s: s  # to be overriden by renderers
    context['locale'] = loc
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(context, loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(tell_sentry, context, loc, *a, **kw)
    context['Money'] = Money
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_money(*a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['format_datetime'] = lambda *a: format_datetime(*a, locale=loc)
    context['get_lang_options'] = lambda *a, **kw: get_lang_options(context['request'], loc, *a, **kw)
    context['to_age'] = to_age

    def parse_decimal_or_400(s, *a):
        try:
            return parse_decimal(s, *a, locale=loc)
        except (InvalidOperation, NumberFormatError, ValueError):
            raise InvalidNumber(s)

    context['parse_decimal'] = parse_decimal_or_400

    def to_age_str(o, **kw):
        if not isinstance(o, datetime):
            kw.setdefault('granularity', 'day')
        return format_timedelta(to_age(o), locale=loc, **kw)

    context['to_age_str'] = to_age_str

    def getdoc(name):
        versions = context['website'].docs[name]
        for lang in context['request'].accept_langs:
            doc = versions.get(lang)
            if doc:
                return doc
        return versions['en']

    context['getdoc'] = getdoc
Example #35
0
def number_size_format(size, lang="en"):
    '''
    Formatea un tamaño de fichero en el idioma actual
    '''
    if not size:
        return None, None
    elif int(float(size)) == 0:
        return "0", ("B", "bytes")

    if lang in format_cache:
        decimal_sep, group_sep = format_cache[lang]
    else:
        decimal_sep, group_sep = format_cache[lang] = (
            get_decimal_symbol(lang), get_group_symbol(lang))

    try:
        if size < 1000:  # no aplica para los bytes
            return str(size), ("B", "bytes")
        else:
            size = log(float(size), 1000)
            number = 1000**(size - int(size))

            # parte decimal
            dec_part = int((number - int(number)) * 100)
            dec_part = "" if dec_part == 0 else decimal_sep + "0" + str(
                dec_part) if dec_part < 10 else decimal_sep + str(dec_part)

            # genera salida
            return ''.join(
                reversed([
                    c + group_sep if i != 0 and i % 3 == 0 else c
                    for i, c in enumerate(reversed(str(int(number))))
                ])) + dec_part, (("KB", "kilobytes"), ("MB", "megabytes"),
                                 ("GB", "gigabytes"),
                                 ("TB", "terabytes"))[int(size) - 1]
    except BaseException as e:
        logging.exception(e)
        return None, None
Example #36
0
    def __init__(self,
                 curFormat,
                 curCode,
                 sourceLang,
                 targetLang,
                 sourceLocale,
                 targetLocale,
                 fullmatch=False):
        """Initialize a CurrencyTranslator instance

           Args:
              curFormat (str): currency symbol format
                              'symbol' (symbol-only, e.g., '$') or 'standard' (the one used by babel, e.g., '$US')
              curCode (str): currency code, e.g., 'USD'
              sourceLang (str): source language in full spelling, e.g., 'English'
                                ignored if sourceLocale is provided
              sourceLocale (str): source locale identifier
              targetLang (str): target language in full spelling, e.g., 'French'
                                ignored if targetLocale is provided
              targetLocale (str): target locale identifier
              fullmatch (bool): whether to full-match a text or not
                                if True, CurrencyTranslator can act as an independent translator
                                if False, CurrencyTranslator must work with other translators
        """

        assert curFormat in ('symbol', 'standard')

        self._curFormat = curFormat
        self.curCode = curCode
        self.srcLang = NAME_YAPPN_MAPPINGS[sourceLang]
        self.tgtLang = NAME_YAPPN_MAPPINGS[targetLang]
        self.srcLocale = sourceLocale if sourceLocale else re.sub(
            '-', '_', CULTURE_CODES[sourceLang][0])
        self.tgtLocale = targetLocale if targetLocale else re.sub(
            '-', '_', CULTURE_CODES[targetLang][0])
        self._fullmatch = fullmatch

        self.srcDecimalSymbol = numbers.get_decimal_symbol(self.srcLocale)
Example #37
0
def format_decimal(decimal, digits=2):
    """Returns a formatted decimal value in the context of current locale. The
    appropriate thousands grouping and the decimal separator are used according
    to the current locale.

    For example::

        >>> format_decimal(12345.4321, digits=2)
        ... '12,345.43'
        >>> format_decimal(Decimal('12345.4321'), digits=2)
        ... '12,345.43'


    :param decimal: a float or Decimal value
    :param digits: number of digits to the right of decimal seperator
    """
    locale = get_locale()
    value = ('%%.%df' % digits) % decimal
    num, decimals = value.split('.')
    num = numbers.format_number(int(num), locale=locale)
    if digits == 0:
        return num
    return num + numbers.get_decimal_symbol(locale) + decimals
Example #38
0
def add_helpers_to_context(tell_sentry, context, loc):
    context['escape'] = lambda s: s  # to be overriden by renderers
    context['locale'] = loc
    context['decimal_symbol'] = get_decimal_symbol(locale=loc)
    context['_'] = lambda s, *a, **kw: get_text(context, loc, s, *a, **kw)
    context['ngettext'] = lambda *a, **kw: n_get_text(tell_sentry, context,
                                                      loc, *a, **kw)
    context['Money'] = Money
    context['format_number'] = lambda *a: format_number(*a, locale=loc)
    context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
    context['format_currency'] = lambda *a, **kw: format_money(
        *a, locale=loc, **kw)
    context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
    context['format_datetime'] = lambda *a: format_datetime(*a, locale=loc)
    context['parse_decimal'] = lambda *a: parse_decimal(*a, locale=loc)
    context['to_age'] = to_age

    def to_age_str(o, **kw):
        if not isinstance(o, datetime):
            kw.setdefault('granularity', 'day')
        return format_timedelta(to_age(o), locale=loc, **kw)

    context['to_age_str'] = to_age_str
Example #39
0
def format_decimal(decimal, digits=2):
    """Returns a formatted decimal value in the context of current locale. The
    appropriate thousands grouping and the decimal separator are used according
    to the current locale.

    For example::

        >>> format_decimal(12345.4321, digits=2)
        ... '12,345.43'
        >>> format_decimal(Decimal('12345.4321'), digits=2)
        ... '12,345.43'


    :param decimal: a float or Decimal value
    :param digits: number of digits to the right of decimal seperator
    """
    locale = get_locale()
    value = ('%%.%df' % digits) % decimal
    num, decimals = value.split('.')
    num = numbers.format_number(int(num), locale=locale)
    if digits == 0:
        return num
    return num + numbers.get_decimal_symbol(locale) + decimals
Example #40
0
    def _get_currency_parts(self, amount, currency, locale):
        formatted = babel_numbers.format_currency(
            number=amount,
            currency=currency,
            locale=locale
        )
        amount = formatted
        currency = ""
        currency_last = amount[0].isdigit()
        if currency_last:
            while not amount[-1].isdigit():
                currency = amount[-1] + currency
                amount = amount[:-1]
        else:
            while not amount[0].isdigit():
                currency += amount[0]
                amount = amount[1:]

        return (
            amount,
            currency,
            currency_last,
            babel_numbers.get_decimal_symbol(locale)
        )
Example #41
0
def format_currency_with_options(number, currency, locale='en', trailing_zeroes=True):
    s = format_currency(number, currency, locale=locale)
    if not trailing_zeroes:
        s = s.replace(get_decimal_symbol(locale)+'00', '')
    return s
Example #42
0
 def clean(self, value):
     locale = get_request().locale
     value = value.replace(numbers.get_group_symbol(locale), "").replace(numbers.get_decimal_symbol(locale), ".")
     return forms.DecimalField(self, value)
Example #43
0
 def get_dec_sep(self):
     return get_decimal_symbol(locale=self.locale)
Example #44
0
def test_get_decimal_symbol():
    assert numbers.get_decimal_symbol('en_US') == u'.'
Example #45
0
def get_decimal_format(locale=LC_TIME):
    """Get decimal point for the locale."""
    return get_decimal_symbol(locale)
Example #46
0
def get_dec_sep(request):
    return get_decimal_symbol(locale=get_locale(request))
Example #47
0
def format_money(number, currency, format=None, locale='en', trailing_zeroes=True):
    s = format_currency(number, currency, format, locale=locale)
    if not trailing_zeroes:
        s = s.replace(get_decimal_symbol(locale)+'00', '')
    return s
Example #48
0
def format_currency_with_options(number, currency, format=None, locale="en", trailing_zeroes=True):
    s = format_currency(number, currency, format, locale=locale)
    if not trailing_zeroes:
        s = s.replace(get_decimal_symbol(locale) + "00", "")
    return s
Example #49
0
 def get_decimal_symbol(self):
     """Return the symbol used to separate decimal fractions
     """
     return numbers.get_decimal_symbol(self)
Example #50
0
def test_get_decimal_symbol():
    assert numbers.get_decimal_symbol('en_US') == u'.'
Example #51
0
 def currency(self,bizplace_id,user_id):
     symbol=get_currency_symbol(bizplace_store.get(bizplace_id,fields=['currency']))
     user_locale = dbaccess.stores.memberpref_store.get_by(dict(member=user_id), ['language'])[0]['language']
     decimal=get_decimal_symbol(user_locale)
     group=get_group_symbol(user_locale)
     return dict(symbol=symbol, decimal=decimal, group=group)