Пример #1
0
def plaintext_post_handler(bot, message):
    if bot.settings['content_status']['text'] is False:
        yield bot.bot.send_message(pgettext('User send text message for verification while texts is disabled',
                                            'Accepting text messages are disabled'),
                                   reply_to_message=message)
        return

    mes = message['text']
    if mes.strip() != '':
        if bot.settings['text_min'] <= len(mes) <= bot.settings['text_max']:
            yield _request_message_confirmation(bot, message)
            report_botan(message, 'slave_message')
            return {
                'sent_message': message
            }
        else:
            report_botan(message, 'slave_message_invalid')
            yield bot.send_message(pgettext('Incorrect text message received', 'Sorry, but we can proceed only '
                                                                               'messages with length between '
                                                                               '{min_msg_length} and {max_msg_length} '
                                                                               'symbols.')
                                   .format(min_msg_length=format_number(bot.settings['text_min'], bot.language),
                                           max_msg_length=format_number(bot.settings['text_max'], bot.language)),
                                   reply_to_message=message)
    else:
        report_botan(message, 'slave_message_empty')
        yield bot.send_message(pgettext('User sent empty message', 'Seriously??? 8===3'),
                               reply_to_message=message)
Пример #2
0
 def float(self, number):
     print(number)
     if isinstance(number, float):
         print(number, format_number(number, locale=self.locale),
               self.locale)
         return format_number(number, locale=self.locale)
     return number
Пример #3
0
def dashboard():
    db = get_db()
    # Any amount of cash will be displayed
    cash = [a for a in current_user.assets if (a.asset_symbol == "_CASH")][0]
    cash.asset_amount_display = format_number(cash.asset_amount,
                                              locale="en_US")
    # Empty assets for stocks will not be displayed
    stocks = [
        a for a in current_user.assets
        if (a.asset_symbol != "_CASH") and (a.asset_amount > 0)
    ]

    # Compute stocks' market value by company's market price * asset_amount
    # Then compute net worth by summing up cash and stocks market value
    net_worth = cash.asset_amount
    for stock in stocks:
        market_price = db.query(Company).get(stock.asset_symbol).market_price
        stock.market_value = market_price * stock.asset_amount
        stock.market_value_display = format_number(stock.market_value,
                                                   locale="en_US")
        stock.asset_amount_display = format_number(int(stock.asset_amount),
                                                   locale="en_US")
        net_worth += stock.market_value
    net_worth_display = format_number(net_worth, locale="en_US")
    return render_template("exchange/dashboard.html",
                           cash=cash,
                           stocks=stocks,
                           net_worth=net_worth_display,
                           title="Dashboard")
Пример #4
0
 def format_top_votes(row):
     return npgettext(
         'Votes count',
         '{votes_cnt} vote (with {votes_yes_cnt} {thumb_up_sign})',
         '{votes_cnt} votes (with {votes_yes_cnt} {thumb_up_sign})',
         row[0]).format(votes_cnt=format_number(row[0], bot.language),
                        votes_yes_cnt=format_number(row[1], bot.language),
                        thumb_up_sign=Emoji.THUMBS_UP_SIGN)
Пример #5
0
def landing(request):
    """Customer Care Landing page."""

    twitter = request.twitter

    # Stats. See customercare.cron.get_customercare_stats.
    activity = cache.get(settings.CC_TWEET_ACTIVITY_CACHE_KEY)
    if activity and 'resultset' in activity:
        statsd.incr('customercare.stats.activity.hit')
        activity_stats = []
        for act in activity['resultset']:
            if act is None:  # Sometimes we get bad data here.
                continue
            activity_stats.append((act[0], {
                'requests': format_number(act[1], locale='en_US'),
                'replies': format_number(act[2], locale='en_US'),
                'perc': act[3] * 100,
            }))
    else:
        statsd.incr('customercare.stats.activity.miss')
        activity_stats = []

    contributors = cache.get(settings.CC_TOP_CONTRIB_CACHE_KEY)
    if contributors and 'resultset' in contributors:
        statsd.incr('customercare.stats.contributors.hit')
        contributor_stats = {}
        for contrib in contributors['resultset']:
            # Create one list per time period
            period = contrib[1]
            if not contributor_stats.get(period):
                contributor_stats[period] = []
            elif len(contributor_stats[period]) == 16:
                # Show a max. of 16 people.
                continue

            contributor_stats[period].append({
                'name': contrib[2],
                'username': contrib[3],
                'count': contrib[4],
                'avatar': contributors['avatars'].get(contrib[3]),
            })
    else:
        statsd.incr('customercare.stats.contributors.miss')
        contributor_stats = {}

    return jingo.render(request, 'customercare/landing.html', {
        'activity_stats': activity_stats,
        'contributor_stats': contributor_stats,
        'canned_responses': CANNED_RESPONSES,
        'tweets': _get_tweets(locale=request.locale,
                              https=request.is_secure()),
        'authed': twitter.authed,
        'twitter_user': (twitter.api.auth.get_username() if
                         twitter.authed else None),
        'filters': FILTERS,
    })
Пример #6
0
def month_stats_ajax(request):
    user_total = ClickStats.objects.total_for_user_period(
        request.user, request.POST['month'], request.POST['year'])
    site_avg = ClickStats.objects.average_for_period(
        request.POST['month'], request.POST['year'])

    locale = current_locale()
    results = {'user_total': format_number(user_total, locale=locale),
               'site_avg': format_number(site_avg, locale=locale)}
    return HttpResponse(json.dumps(results), mimetype='application/json')
Пример #7
0
def month_stats_ajax(request):
    user_total = ClickStats.objects.total(badge_instance__user=request.user,
                                          month=request.POST['month'],
                                          year=request.POST['year'])
    site_avg = ClickStats.objects.average_for_period(month=request.POST['month'],
                                                     year=request.POST['year'])

    locale = Locale.parse(get_language(), sep='-')
    results = {'user_total': format_number(user_total, locale=locale),
               'site_avg': format_number(site_avg, locale=locale)}
    return HttpResponse(json.dumps(results), mimetype='application/json')
Пример #8
0
def landing(request):
    """Customer Care Landing page."""

    twitter = request.twitter

    canned_responses = CannedCategory.objects.filter(locale=request.locale)

    # Stats. See customercare.cron.get_customercare_stats.
    activity = cache.get(settings.CC_TWEET_ACTIVITY_CACHE_KEY)
    if activity and 'resultset' in activity:
        activity_stats = []
        for act in activity['resultset']:
            if act is None:  # Sometimes we get bad data here.
                continue
            activity_stats.append((act[0], {
                'requests': format_number(act[1], locale='en_US'),
                'replies': format_number(act[2], locale='en_US'),
                'perc': act[3] * 100,
            }))
    else:
        activity_stats = []

    contributors = cache.get(settings.CC_TOP_CONTRIB_CACHE_KEY)
    if contributors and 'resultset' in contributors:
        contributor_stats = {}
        for contrib in contributors['resultset']:
            # Create one list per time period
            period = contrib[1]
            if not contributor_stats.get(period):
                contributor_stats[period] = []
            elif len(contributor_stats[period]) == 16:
                # Show a max. of 16 people.
                continue

            contributor_stats[period].append({
                'name': contrib[2],
                'username': contrib[3],
                'count': contrib[4],
                'avatar': contributors['avatars'].get(contrib[3]),
            })
    else:
        contributor_stats = {}

    return jingo.render(request, 'customercare/landing.html', {
        'activity_stats': activity_stats,
        'contributor_stats': contributor_stats,
        'canned_responses': canned_responses,
        'tweets': _get_tweets(locale=request.locale),
        'authed': twitter.authed,
        'twitter_user': (twitter.api.auth.get_username() if
                         twitter.authed else None),
        'filters': FILTERS,
    })
Пример #9
0
def month_stats_ajax(request):
    user_total = ClickStats.objects.total_for_user_period(
        request.user, request.POST['month'], request.POST['year'])
    site_avg = ClickStats.objects.average_for_period(request.POST['month'],
                                                     request.POST['year'])

    locale = current_locale()
    results = {
        'user_total': format_number(user_total, locale=locale),
        'site_avg': format_number(site_avg, locale=locale)
    }
    return HttpResponse(json.dumps(results), mimetype='application/json')
Пример #10
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)
Пример #11
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)
Пример #12
0
def landing(request):
    """Customer Care Landing page."""

    twitter = request.twitter

    canned_responses = CannedCategory.objects.filter(locale=request.locale)

    # Stats. See customercare.cron.get_customercare_stats.
    activity = cache.get(settings.CC_TWEET_ACTIVITY_CACHE_KEY)
    if activity:
        activity_stats = []
        for act in activity['resultset']:
            activity_stats.append((act[0], {
                'requests': format_number(act[1], locale='en_US'),
                'replies': format_number(act[2], locale='en_US'),
                'perc': act[3] * 100,
            }))
    else:
        activity_stats = []

    contributors = cache.get(settings.CC_TOP_CONTRIB_CACHE_KEY)
    if contributors:
        contributor_stats = {}
        for contrib in contributors['resultset']:
            # Create one list per time period
            period = contrib[1]
            if not contributor_stats.get(period):
                contributor_stats[period] = []
            elif len(contributor_stats[period]) == 16:
                # Show a max. of 16 people.
                continue

            contributor_stats[period].append({
                'name': contrib[2],
                'username': contrib[3],
                'count': contrib[4],
                'avatar': contributors['avatars'].get(contrib[3]),
            })
    else:
        contributor_stats = []

    return jingo.render(request, 'customercare/landing.html', {
        'activity_stats': activity_stats,
        'contributor_stats': contributor_stats,
        'canned_responses': canned_responses,
        'tweets': _get_tweets(locale=request.locale),
        'authed': twitter.authed,
        'twitter_user': (twitter.api.auth.get_username() if
                         twitter.authed else None),
        'filters': FILTERS,
    })
Пример #13
0
def has_oversold_error(form, campaign, start, end, bid, cpm, target, location):
    ndays = (to_date(end) - to_date(start)).days
    total_request = calc_impressions(bid, cpm)
    daily_request = int(total_request / ndays)
    oversold = inventory.get_oversold(target,
                                      start,
                                      end,
                                      daily_request,
                                      ignore=campaign,
                                      location=location)

    if oversold:
        min_daily = min(oversold.values())
        available = min_daily * ndays
        msg_params = {
            'available': format_number(available, locale=c.locale),
            'target': target.pretty_name,
            'start': start.strftime('%m/%d/%Y'),
            'end': end.strftime('%m/%d/%Y'),
        }
        c.errors.add(errors.OVERSOLD_DETAIL,
                     field='bid',
                     msg_params=msg_params)
        form.has_errors('bid', errors.OVERSOLD_DETAIL)
        return True
Пример #14
0
    def format_number(self, number):
        """Return the given number formatted

        >>> Locale('en', 'US').format_number(1099)
        u'1,099'
        """
        return numbers.format_number(number, self)
Пример #15
0
    def build(self, results, criteria):
        tree = Tree()
        for value, count in results:
            if value or self.missing_label:
                value, label = self.decode(value, default_value=value, default_label=value)
                remove_url = criteria.build_remove_filter_url(self, value)
                add_url = None if remove_url else criteria.build_add_filter_url(self, value)
                if remove_url or add_url:  # Only items with an URL get displayed.
                    if value:
                        path = value.split(sep=self.path_separator)
                    else:
                        path = [value]

                    # Build the tree path. Part of the path may or may not already
                    # exist as the facet values are not ordered.
                    node = tree  # Start at tree root.
                    for component in path:
                        node = node['children'][component]
                    # Add data at the leaf.
                    node['node'] = {
                        'label': label,
                        'count': count,
                        'count_formatted': format_number(count, locale=get_locale()),
                        'remove_url': remove_url,
                        'add_url': add_url,
                    }
        return self.sort_tree(tree)
Пример #16
0
def dashboard(request, template, context=None):
    """
    Performs common operations needed by pages using the 'dashboard' template.
    """
    if context is None:
        context = {}

    locale = current_locale()

    # Set context variables needed by all dashboard pages
    context['newsitem'] = NewsItem.objects.current()
    context['user_has_created_badges'] = request.user.has_created_badges()

    if context['user_has_created_badges']:
        clicks_total = ClickStats.objects.total_for_user(request.user)

        # Add Facebook clicks to total
        fb_user = request.user.get_linked_account()
        if fb_user is not None:
            clicks_total += FacebookClickStats.objects.total_for_user(fb_user)

        context['user_clicks_total'] = format_number(clicks_total,
                                                     locale=locale)

        # Leaderboard
        try:
            context['show_leaderboard'] = True
            context['leaderboard'] = (Leaderboard.objects
                                      .top_users(settings.LEADERBOARD_SIZE))
            context['user_standing'] = (Leaderboard.objects
                                        .get(user=request.user))
        except Leaderboard.DoesNotExist:
            context['show_leaderboard'] = False

    return jingo.render(request, template, context)
Пример #17
0
def n_get_text(state, loc, s, p, n, *a, **kw):
    escape = state['escape']
    n, wrapper = (n.value, n.wrapper) if isinstance(n, Wrap) else (n, None)
    n = n or 0
    msg = loc.catalog.get((s, p) if s else p)
    s2 = None
    if msg:
        try:
            s2 = msg.string[loc.catalog.plural_func(n)]
        except Exception as e:
            website.tell_sentry(e, state)
    if not s2:
        s2 = s if n == 1 else p
        if loc != LOCALE_EN:
            loc = LOCALE_EN
            state['partial_translation'] = True
    kw['n'] = format_number(n, locale=loc) or n
    if wrapper:
        kw['n'] = wrapper % kw['n']
    try:
        return i_format(loc, escape(_decode(s2)), *a, **kw)
    except Exception as e:
        website.tell_sentry(e, state)
        return i_format(LOCALE_EN, escape(_decode(s if n == 1 else p)), *a,
                        **kw)
Пример #18
0
    def fetch_threads_from_messages(self,
                                    channel_id,
                                    messages,
                                    max_messages,
                                    oldest=None,
                                    latest=None) -> dict:
        """returns threads from all messages from for a channel as dict"""
        threads = dict()
        thread_num = 0
        thread_messages_total = 0
        for msg in messages:
            if "thread_ts" in msg and msg["thread_ts"] == msg["ts"]:
                thread_ts = msg["thread_ts"]
                thread_num += 1
                thread_messages = self._fetch_messages_from_thread(
                    channel_id, thread_ts, max_messages, oldest, latest)
                threads[thread_ts] = thread_messages
                thread_messages_total += len(thread_messages)

        if thread_messages_total:
            logger.info(
                "Received a total of %s messages from %d threads",
                format_number(thread_messages_total, locale=self._locale),
                thread_num,
            )
        else:
            logger.info("This channel has no threads")

        return threads
Пример #19
0
 def build(self, results, criteria, active_only=False):
     items = []
     for value, count in results:
         if value or self.missing_label:
             value, label = self.decode(value,
                                        default_value=value,
                                        default_label=value)
             remove_url = criteria.build_remove_filter_url(self, value)
             if remove_url or active_only:
                 add_url = None
             else:
                 add_url = criteria.build_add_filter_url(self, value)
             if remove_url or add_url:  # Only items with an URL get displayed.
                 items.append({
                     'label':
                     label,
                     'count':
                     count,
                     'count_formatted':
                     format_number(count, locale=get_locale()),
                     'remove_url':
                     remove_url,
                     'add_url':
                     add_url,
                 })
     return self.sort_items(items)
Пример #20
0
def hoarder_asset_fetching(order_id):
    from core.models.hoarder.transactions import sxb
    from core.models.hoarder.order import HoarderOrder
    from core.models.hoarder.errors import FetchAssetError, AssetNotChangedError
    order = HoarderOrder.get(order_id)
    try:
        sxb.fetch_asset(order)
    except FetchAssetError as e:
        if isinstance(e, AssetNotChangedError):
            since_delta = datetime.datetime.now() - order.creation_time
            if since_delta > datetime.timedelta(hours=6):
                if bearychat.configured:
                    # 长时间资产未发生变化将发往BC提醒,并从队列中跳出
                    quota = format_number(order.amount, locale='en_US')
                    result = u'`成功`:clap: '
                    color = '#00FF00'
                    message = u'已执行 **自动取消同步资产信息 ¥{}** {},当前状态 `{}`'.format(
                        quota, result, order.status.display_text)
                    txt = u'**用户:** ( {} ) 已经 **{}** 了, **随心攒订单** *{}* (*{}*) 资产已同步.'.format(
                        order.user_id,
                        format_timedelta(since_delta, locale='zh_CN'),
                        order.id_,
                        order.order_code,
                    )
                    attachment = bearychat.attachment(title=None,
                                                      text=message,
                                                      color=color,
                                                      images=[])
                    bearychat.say(txt, attachments=[attachment])
                return
        raise WorkerTaskError(unicode(e))
Пример #21
0
def i_format(loc, s, *a, **kw):
    if a:
        a = list(a)
    for c, f in [(a, enumerate), (kw, dict.items)]:
        for k, o in f(c):
            o, wrapper = (o.value, o.wrapper) if isinstance(o, Wrap) else (o, None)
            if isinstance(o, text_type):
                pass
            elif isinstance(o, Decimal):
                c[k] = format_decimal(o, locale=loc)
            elif isinstance(o, int):
                c[k] = format_number(o, locale=loc)
            elif isinstance(o, Money):
                c[k] = loc.format_money(o)
            elif isinstance(o, MoneyBasket):
                c[k] = loc.format_money_basket(o)
            elif isinstance(o, Age):
                c[k] = format_timedelta(o, locale=loc, **o.format_args)
            elif isinstance(o, timedelta):
                c[k] = format_timedelta(o, locale=loc)
            elif isinstance(o, datetime):
                c[k] = format_datetime(o, locale=loc)
            elif isinstance(o, date):
                c[k] = format_date(o, locale=loc)
            elif isinstance(o, Locale):
                c[k] = loc.languages.get(o.language) or o.language.upper()
            elif isinstance(o, Currency):
                c[k] = loc.currencies.get(o, o)
            if wrapper:
                c[k] = wrapper % (c[k],)
    return s.format(*a, **kw)
Пример #22
0
def i_format(loc, s, *a, **kw):
    if a:
        a = list(a)
    for c, f in [(a, enumerate), (kw, dict.items)]:
        for k, o in f(c):
            o, wrapper = (o.value, o.wrapper) if isinstance(o, Wrap) else (o, None)
            if isinstance(o, text_type):
                pass
            elif isinstance(o, Decimal):
                c[k] = format_decimal(o, locale=loc)
            elif isinstance(o, int):
                c[k] = format_number(o, locale=loc)
            elif isinstance(o, Money):
                c[k] = loc.format_money(o)
            elif isinstance(o, MoneyBasket):
                c[k] = loc.format_money_basket(o)
            elif isinstance(o, Age):
                c[k] = format_timedelta(o, locale=loc, **o.format_args)
            elif isinstance(o, timedelta):
                c[k] = format_timedelta(o, locale=loc)
            elif isinstance(o, datetime):
                c[k] = format_datetime(o, locale=loc)
            elif isinstance(o, date):
                c[k] = format_date(o, locale=loc)
            elif isinstance(o, Locale):
                c[k] = loc.languages.get(o.language) or o.language.upper()
            elif isinstance(o, Currency):
                c[k] = loc.currencies.get(o, o)
            if wrapper:
                c[k] = wrapper % (c[k],)
    return s.format(*a, **kw)
Пример #23
0
def l10n_format_number(ctx, number):
    """
    Formats a number according to the current locale. Wraps around
    babel.numbers.format_number.
    """
    lang = get_locale(ctx['LANG'])
    return format_number(number, locale=lang)
Пример #24
0
def l10n_format_number(ctx, number):
    """
    Formats a number according to the current locale. Wraps around
    babel.numbers.format_number.
    """
    lang = get_locale(ctx['LANG'])
    return format_number(number, locale=lang)
Пример #25
0
def localize_number(obj, locale, format=None, currency=None):
    """add???
    
    :param obj: add???
    :param locale: add???
    :param format: add???. Default value is ``None``
    :param currency: add???. Default value is ``None``
    :returns: add???
    """
    if format:
        flist = format.split(';')
        if len(flist) > 2:
            if obj == 0:
                return flist[2]
            else:
                format = '%s;%s' % (flist[0], flist[1])
        if currency:
            print currency
            return numbers.format_currency(obj,
                                           currency=currency,
                                           format=format,
                                           locale=locale)
        else:
            return numbers.format_decimal(obj, format=format, locale=locale)
    else:
        return numbers.format_number(obj, locale=locale)
Пример #26
0
    def number(self, number):
        """Return an integer number formatted for the locale.

        >>> fmt = Format('en_US')
        >>> fmt.number(1099)
        u'1,099'
        """
        return format_number(number, locale=self.locale)
Пример #27
0
    def number(self, number):
        """Return an integer number formatted for the locale.

        >>> fmt = Format('en_US')
        >>> fmt.number(1099)
        u'1,099'
        """
        return format_number(number, locale=self.locale)
Пример #28
0
def month_stats_ajax(request, month, year):
    user_total = ClickStats.objects.total_for_user_period(request.user, month,
                                                          year)
    site_avg = ClickStats.objects.average_for_period(month, year)

    locale = current_locale()
    results = {'user_total': format_number(user_total, locale=locale),
               'site_avg': format_number(site_avg, locale=locale)}

    # Get linked Facebook click count if available.
    facebook_user = request.user.get_linked_account()
    if facebook_user is not None:
        fb_total = FacebookClickStats.objects.total_for_month(facebook_user,
                                                              year, month)
        results['fb_total'] = format_number(fb_total, locale=locale)

    return HttpResponse(json.dumps(results), mimetype='application/json')
Пример #29
0
def predict(new):
    file_name = 'finalized_model.sav'
    model = pickle.load(open(file_name, 'rb'))
    y_pred = model.predict(new.reshape(1, -1))
    y_pred = str(round(y_pred[0], 2))
    y_pred = "RM " + str(format_number(y_pred, locale='en_US'))

    return y_pred
Пример #30
0
def format_number(number):
    """Return the given number formatted for the locale in request
    
    :param number: the number to format
    :return: the formatted number
    :rtype: unicode
    """
    locale = get_locale()
    return numbers.format_number(number, locale=locale)
Пример #31
0
def format_number(number):
    """Return the given number formatted for the locale in request

    :param number: the number to format
    :return: the formatted number
    :rtype: unicode
    """
    locale = get_locale()
    return numbers.format_number(number, locale=locale)
Пример #32
0
def format_number(number, request=None):
    """Return the given number formatted for the locale in request

    :param number: the number to format
    :param request: the current Request object
    :return: the formatted number
    :rtype: str
    """
    return numbers.format_number(number, locale=get_locale(request))
Пример #33
0
def test_smoke_numbers(locale):
    locale = Locale.parse(locale)
    for number in (
            Decimal("-33.76"),  # Negative Decimal
            Decimal("13.37"),  # Positive Decimal
            1.2 - 1.0,  # Inaccurate float
            10,  # Plain old integer
            0,  # Zero
    ):
        assert numbers.format_number(number, locale=locale)
Пример #34
0
def price_format_decimal_to_currency(value, currency='EUR'):
    if value:
        try:
            if currency in CURRENCY_PATTERNS.keys():
                value = CURRENCY_PATTERNS[currency]['format'] % format_number(value, locale = CURRENCY_PATTERNS[currency]['locale'])
            else:
                return value
        except:
            return value
    return value
Пример #35
0
def price_format_decimal_to_currency(value, currency='EUR'):
    if value:
        try:
            if currency in CURRENCY_PATTERNS.keys():
                value = CURRENCY_PATTERNS[currency]['format'] % format_number(value, locale = CURRENCY_PATTERNS[currency]['locale'])
            else:
                return value
        except:
            return value
    return value
Пример #36
0
 def number(self, value):
     """
     Format number
     :param value:   The value to format
     :return:        The formatted number
     """
     if value % 1 == 0:
         return format_number(value, locale=self._locale)
     else:
         return format_decimal(value, locale=self._locale)
Пример #37
0
def test_smoke_numbers(locale):
    locale = Locale.parse(locale)
    for number in (
        Decimal("-33.76"),  # Negative Decimal
        Decimal("13.37"),  # Positive Decimal
        1.2 - 1.0,  # Inaccurate float
        10,  # Plain old integer
        0,  # Zero
    ):
        assert numbers.format_number(number, locale=locale)
Пример #38
0
 def number(self, number):
     """Return an integer number formatted for the locale.
     
     >>> fmt = Format('en_US')
     >>> fmt.number(1099) == u('1,099')
     True
     
     :see: `babel.numbers.format_number`
     """
     return format_number(number, locale=self.locale)
Пример #39
0
    def number(self, number):
        """Return an integer number formatted for the locale.

        >>> fmt = Format('en_US')
        >>> fmt.number(1099) == '1,099'
        True

        :see: `babel.numbers.format_number`
        """
        return format_number(number, locale=self.locale)
Пример #40
0
def format_number(number):
    """Return a formatted number.

    Note that this function does the same as :func:`format_decimal`,
    but without the possibility to specify custom formats.

    This function is also available in the template context as filter
    named `numberformat`.
    """
    locale = get_locale()
    return numbers.format_number(number, locale=locale)
Пример #41
0
def format_number(number):
    """Return a formatted number.

    Note that this function does the same as :func:`format_decimal`,
    but without the possibility to specify custom formats.

    This function is also available in the template context as filter
    named `numberformat`.
    """
    locale = get_locale()
    return numbers.format_number(number, locale=locale)
Пример #42
0
def format_element(element):
    # literal
    for value in element.get('http://www.w3.org/1999/02/22-rdf-syntax-ns#value', []):
        type = value.get('@type', '')
        val = value.get('@value', '')
        if type == 'http://www.w3.org/2001/XMLSchema#dateTime':
            bc = (val[0] == '-')
            try:
                return format_datetime(datetime.strptime(val, ('-' if bc else '') + '%Y-%m-%dT%H:%M:%SZ'),
                                       locale=locale, format='full') + (
                           ' ' + locale.eras['wide'][0] if bc else '')
            except ValueError:
                return val
        elif type == 'http://www.w3.org/2001/XMLSchema#date':
            bc = (val[0] == '-')
            try:
                return format_date(datetime.strptime(val, ('-' if bc else '') + '%Y-%m-%dZ'), locale=locale,
                                   format='full') + (' ' + locale.eras['wide'][0] if bc else '')
            except ValueError:
                return val
        elif type == 'http://www.w3.org/2001/XMLSchema#decimal' or \
                type == 'http://www.w3.org/2001/XMLSchema#double' or \
                type == 'http://www.w3.org/2001/XMLSchema#float':
            return format_decimal(float(val), locale=locale)
        elif type == 'http://www.w3.org/2001/XMLSchema#integer':
            return format_number(int(val), locale=locale)
        elif type == 'http://www.w3.org/2001/XMLSchema#time':
            try:
                return format_time(datetime.strptime(val, '%H:%M:%SZ'), locale=locale, format='full')
            except ValueError:
                return val
        else:
            return val

    # entities
    types = element.get('@type', [])

    if 'http://schema.org/GeoCoordinates' in types and \
            'http://schema.org/latitude' in element and \
            'http://schema.org/longitude' in element:
        latitude = float(element['http://schema.org/latitude'][0]['@value'])
        longitude = float(element['http://schema.org/longitude'][0]['@value'])
        lat_dir = 'north' if latitude >= 0 else 'south'
        lon_dir = 'east' if longitude >= 0 else 'west'
        return format_unit(abs(latitude), 'angle-degree', locale=locale) + ' ' + lat_dir + ' ' + \
               format_unit(abs(longitude), 'angle-degree', locale=locale) + ' ' + lon_dir
    else:
        for same_as in element.get('http://schema.org/sameAs', []):
            url = same_as.get('@id', same_as.get('@value', ''))
            if url.startswith('http://twitter.com/'):
                return url.replace('http://twitter.com/', '@')
        for name in element.get('http://schema.org/name', []):
            return name.get('@value', '')
    return ''
Пример #43
0
def humanize_number(number, locale=None):
    """
    Utility function which will take a integer/float value and convert it
    into a humanized format.
    """
    # http://babel.pocoo.org/en/latest/api/numbers.html
    if locale is None:
        lang = get_language()
        if lang is None:
            lang = "en"
        locale = to_locale(lang)
    return format_number(number, locale=locale)
Пример #44
0
    def format_number(self, number):
        """Returns the given number formatted for the current locale. Example::

            >>> format_number(1099, locale='en_US')
            u'1,099'

        :param number:
            The number to format.
        :returns:
            The formatted number.
        """
        return numbers.format_number(number, locale=self.locale)
Пример #45
0
    def format_number(self, number, locale=None, **kwargs):
        """Return the given number formatted for the locale in the
        current request.

        :param number: the number to format
        :param locale: Overwrite the global locale.

        """
        if number in ('', None):
            return ''
        locale = utils.normalize_locale(locale) or self.get_locale()
        return numbers.format_number(number, locale=locale, **kwargs)
Пример #46
0
def _update_timer():
    if not g.live_config['thebutton_is_active']:
        print "%s: thebutton is inactive" % datetime.now(g.tz)
        websockets.send_broadcast(namespace="/thebutton",
                                  type="not_started",
                                  payload={})
        return

    expiration_time = has_timer_expired()
    if expiration_time:
        seconds_elapsed = (datetime.now(g.tz) -
                           expiration_time).total_seconds()
        print "%s: timer is expired %s ago" % (datetime.now(
            g.tz), seconds_elapsed)

        websockets.send_broadcast(namespace="/thebutton",
                                  type="expired",
                                  payload={"seconds_elapsed": seconds_elapsed})
        return

    if not has_timer_started():
        print "%s: timer not started" % datetime.now(g.tz)
        websockets.send_broadcast(namespace="/thebutton",
                                  type="not_started",
                                  payload={})
        return

    seconds_left = round(get_seconds_left())
    if seconds_left < 0:
        print "%s: timer just expired" % datetime.now(g.tz)
        mark_timer_expired(datetime.now(g.tz))
        websockets.send_broadcast(namespace="/thebutton",
                                  type="just_expired",
                                  payload={})
    else:
        now = datetime.now(g.tz)
        now_str = datetime_to_str(now)
        tick_mac = make_tick_mac(int(seconds_left), now_str)
        print "%s: timer is ticking %s" % (datetime.now(g.tz), seconds_left)
        websockets.send_broadcast(
            namespace="/thebutton",
            type="ticking",
            payload={
                "seconds_left":
                seconds_left,
                "now_str":
                now_str,
                "tick_mac":
                tick_mac,
                "participants_text":
                format_number(get_num_participants(), locale='en'),
            },
        )
Пример #47
0
def month_stats_ajax(request, month, year):
    # Check for placeholder values and return a 400 if they are present.
    if month == ':month:' or year == ':year:':
        return JSONResponseBadRequest({'error': 'Invalid year/month value.'})

    user_total = ClickStats.objects.total_for_user_period(request.user, month,
                                                          year)
    site_avg = ClickStats.objects.average_for_period(month, year)

    locale = current_locale()
    results = {'user_total': format_number(user_total, locale=locale),
               'site_avg': format_number(site_avg, locale=locale)}

    # Get linked Facebook click count if available.
    facebook_user = request.user.get_linked_account()
    if facebook_user is not None:
        fb_total = FacebookClickStats.objects.total_for_month(facebook_user,
                                                              year, month)
        results['fb_total'] = format_number(fb_total, locale=locale)

    return JSONResponse(results)
Пример #48
0
    def format_number(self, number):
        """Returns the given number formatted for the current locale. Example::

            >>> format_number(1099, locale='en_US')
            u'1,099'

        :param number:
            The number to format.
        :returns:
            The formatted number.
        """
        return numbers.format_number(number, locale=self.locale)
Пример #49
0
def xm_payment_tracking(order_id):
    """同步新投米用户订单支付状态"""
    from core.models.hoard.xinmi import XMOrder, XMProfile

    expected_status_set = frozenset([
        XMOrder.Status.success,
        XMOrder.Status.failure,
    ])

    order = XMOrder.get(order_id)
    user_id = order.user_id
    xm_profile = XMProfile.get(user_id)
    xm_profile.assets(pull_remote=True)
    origin_status = order.status
    if origin_status in expected_status_set:
        return

    # 当订单属于自然失败时不再更新状态
    if origin_status not in [XMOrder.Status.paying, XMOrder.Status.shelved]:
        return

    # 长时间未被结算中心处理的订单将发往BC提醒
    since_delta = datetime.datetime.now() - order.creation_time
    if since_delta > datetime.timedelta(hours=6):
        from core.models.hoard.xinmi.transaction import cancel_order
        cancel_order(order.order_code)
        order = XMOrder.get_by_order_code(order.order_code)
        if order.status in [XMOrder.Status.failure, XMOrder.Status.success]:
            if not bearychat.configured:
                return
            result = u'`成功`:clap: '
            color = '#00FF00'
        else:
            result = u'`失败`:eyes: '
            color = '#FF0000'
        if bearychat.configured:
            quota = format_number(order.amount, locale='en_US')
            message = u'已执行 **自动取消订单释放债权¥{}** {},当前状态 `{}`'.format(
                quota, result, order.status.label)
            txt = u'**用户:** ( {} ) 已经 **{}** 了, **新米订单** *{}* (*{}*) 状态仍为 **{}**.'.format(
                order.user_id,
                format_timedelta(since_delta, locale='zh_CN'), order.id_,
                order.order_code, origin_status.label, )
            attachment = bearychat.attachment(title=None, text=message, color=color, images=[])
            bearychat.say(txt, attachments=[attachment])

    error_msg = (
        u'tube:{0}, order_id:{1}, order code:{2}, '
        u'new status:{3},user_id:{4}')

    raise WorkerTaskError(error_msg.format(xm_payment_tracking.tube, order.id_,
                                           order.order_code, origin_status.name, order.user_id))
Пример #50
0
def format_number(number):
    """Returns the given number formatted for a specific locale.

    >>> format_number(1099, locale='en_US')
    u'1,099'

    :param number:
        The number to format.
    :return:
        The formatted number.
    """
    # Do we really need this one?
    return numbers.format_number(number, locale=local.locale)
Пример #51
0
    def _fetch_pages(
        self,
        method,
        key: str,
        args: dict = None,
        limit: int = None,
        max_rows: int = None,
        items_name: str = None,
        collection_name: str = None,
        print_result: bool = True,
    ) -> list:
        """helper for retrieving all pages from an API endpoint"""
        # fetch first page
        page = 1
        output_str = (
            f"Fetching {items_name if items_name else method} "
            f"from {collection_name if collection_name else 'Slack'}")
        logger.info(output_str)
        if not args:
            args = {}
        if not limit:
            limit = settings.SLACK_PAGE_LIMIT
        base_args = {**args, **{"limit": limit}}
        response = getattr(self._client, method)(**base_args)
        assert response["ok"]
        rows = response[key]

        # fetch additional page (if any)
        while ((not max_rows or len(rows) < max_rows)
               and response.get("response_metadata")
               and response["response_metadata"].get("next_cursor")):
            page += 1
            logger.info("%s - page %s", output_str, page)
            sleep(1)  # need to wait 1 sec before next call due to rate limits
            page_args = {
                **base_args,
                **{
                    "cursor": response["response_metadata"].get("next_cursor"),
                },
            }
            response = getattr(self._client, method)(**page_args)
            assert response["ok"]
            rows += response[key]

        if print_result:
            logger.info(
                "Received a total of %s %s",
                format_number(len(rows), locale=self._locale),
                items_name if items_name else "objects",
            )
        return rows
Пример #52
0
 def render(self, name, value, attrs=None):
     from babel.numbers import parse_number
     from babel.numbers import format_number
     from babel.numbers import NumberFormatError
     locale=get_current_language()
     if value is None: value = ""
     if value and isinstance(value, basestring):
         try:
             value = parse_number(value, locale=locale)
         except NumberFormatError:
             pass
     if value is not "" and not isinstance(value, basestring):
         value = format_number(value, locale=locale)
     return super(IntegerWidget, self).render(name, value, attrs)
Пример #53
0
def n_get_text(tell_sentry, request, loc, s, p, n, *a, **kw):
    n = n or 0
    msg = loc.catalog.get((s, p))
    s2 = None
    if msg:
        try:
            s2 = msg.string[loc.catalog.plural_func(n)]
        except Exception as e:
            tell_sentry(e, request)
    if s2 is None:
        loc = 'en'
        s2 = s if n == 1 else p
    kw['n'] = format_number(n, locale=loc) or n
    if isinstance(s2, bytes):
        s2 = s2.decode('ascii')
    return s2.format(*a, **kw)
Пример #54
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
Пример #55
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
Пример #56
0
def n_get_text(tell_sentry, state, loc, s, p, n, *a, **kw):
    escape = state['escape']
    n = n or 0
    msg = loc.catalog.get((s, p))
    s2 = None
    if msg:
        try:
            s2 = msg.string[loc.catalog.plural_func(n)]
        except Exception as e:
            tell_sentry(e, state)
    if not s2:
        loc = 'en'
        s2 = s if n == 1 else p
    kw['n'] = format_number(n, locale=loc) or n
    if isinstance(s2, bytes):
        s2 = s2.decode('ascii')
    return escape(s2).format(*a, **kw)
Пример #57
0
def n_get_text(state, loc, s, p, n, *a, **kw):
    escape = state['escape']
    n = n or 0
    msg = loc.catalog.get((s, p))
    s2 = None
    if msg:
        try:
            s2 = msg.string[loc.catalog.plural_func(n)]
        except Exception as e:
            website.tell_sentry(e, state, allow_reraise=True)
    if not s2:
        loc = LOCALE_EN
        s2 = s if n == 1 else p
    kw['n'] = format_number(n, locale=loc) or n
    if isinstance(s2, bytes):
        s2 = s2.decode('ascii')
    return i_format(loc, escape(s2), *a, **kw)
Пример #58
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
Пример #59
0
def format_number(number, locale=None):
    """Returns the given number formatted for a specific locale.

    .. code-block:: python

       >>> format_number(1099, locale='en_US')
       u'1,099'

    :param number:
        The number to format.
    :param locale:
        A locale code. If not set, uses the currently loaded locale.
    :returns:
        The formatted number.
    """
    locale = locale or get_locale()
    return numbers.format_number(number, locale=locale)
Пример #60
0
def i_format(loc, s, *a, **kw):
    if a:
        a = list(a)
    for c, f in [(a, enumerate), (kw, dict.items)]:
        for k, o in f(c):
            if isinstance(o, Decimal):
                c[k] = format_decimal(o, locale=loc)
            elif isinstance(o, int):
                c[k] = format_number(o, locale=loc)
            elif isinstance(o, Money):
                c[k] = format_money(*o, locale=loc)
            elif isinstance(o, datedelta):
                c[k] = format_timedelta(o, locale=loc, granularity='day')
            elif isinstance(o, timedelta):
                c[k] = format_timedelta(o, locale=loc)
            elif isinstance(o, datetime):
                c[k] = format_datetime(o, locale=loc)
    return s.format(*a, **kw)