Exemplo n.º 1
0
def show_signup_progress (game):
	status = game.signup_status()
	# Signup has already closed
	if status == 'complete':
		message = _("Signup has closed.")
	# Signup during the game
	elif game.time_period() == game.signup_time_period():
		message = _("Signup is open during the game.")
	# If signup has yet to start
	elif status == 'inactive':
		message = _("Signup opens in {0} and closes {1} later").format(
			timeuntil(game.signup_start_time),
			timeuntil(game.signup_end_time, now=game.signup_start_time))
	# Signup is active
	else:
		# Signup closes when the game *starts*
		if game.signup_end_time == game.start_time:
			message = _("Signup closes at the start of the game.")
		# Signup closes when the game *ends*
		elif game.signup_end_time == game.end_time:
			message = _("Signup closes at the end of the game.")
		# Signup has not closed yet
		else:
			message = _("Signup closes in {0}").format(timeuntil(game.signup_end_time))
	return {'game': game, 'status': status, 'message': message}
Exemplo n.º 2
0
 def time_remaining(self):
     if self.status == self.OPEN_STATUS:
         return timeuntil(
             self.bounties().aggregate(Min('ends'))['ends__min'],
             datetime.datetime.now()).split(',')[0]
     return timeuntil(self.modified + datetime.timedelta(days=3),
                      datetime.datetime.now()).split(',')[0]
Exemplo n.º 3
0
    def test_different_timezones(self):
        """ When using two different timezones. """
        now = datetime.datetime.now()
        now_tz = timezone.make_aware(now, timezone.get_default_timezone())
        now_tz_i = timezone.localtime(now_tz, timezone.get_fixed_timezone(195))

        self.assertEqual(timesince(now), '0\xa0minutes')
        self.assertEqual(timesince(now_tz), '0\xa0minutes')
        self.assertEqual(timesince(now_tz_i), '0\xa0minutes')
        self.assertEqual(timesince(now_tz, now_tz_i), '0\xa0minutes')
        self.assertEqual(timeuntil(now), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz_i), '0\xa0minutes')
        self.assertEqual(timeuntil(now_tz, now_tz_i), '0\xa0minutes')
Exemplo n.º 4
0
 def get_timeuntil(self):
     """
     Returns a string representing the time until the next
     time this Job will be run (actually, the "string" returned
     is really an instance of ``ugettext_lazy``).
     
     >>> from chronograph.compatibility.dates import now
     >>> job = Job(next_run=now())
     >>> job.get_timeuntil().translate('en')
     u'due'
     """
     if self.disabled:
         return _('never (disabled)')
     
     delta = self.next_run - dates.now()
     if delta.days < 0:
         # The job is past due and should be run as soon as possible
         if self.check_is_running():
             return _('running')
         return _('due')
     elif delta.seconds < 60:
         # Adapted from django.utils.timesince
         count = lambda n: ungettext('second', 'seconds', n)
         return ugettext('%(number)d %(type)s') % {'number': delta.seconds,
                                                   'type': count(delta.seconds)}
     return timeuntil(self.next_run)
Exemplo n.º 5
0
 def locked_for(self, obj):
     if obj.locked_until is None:
         return u""
     elif obj.locked_until < timezone.now():
         return _(u"(expired)")
     else:
         return timeuntil(obj.locked_until)
Exemplo n.º 6
0
    def get(self, request, *args, **kwargs):
        ctx = self.get_base_context()

        if self.curl:
            # the "API" version
            ip = _get_client_ip(request)
            address = kwargs["address"]
            if kwargs.get("asset") is None:
                return JsonResponse({"message": "You must specify an asset code to send"}, status=400)

            for skip_header in settings.WHITELISTED_HEADERS:
                header = "HTTP_%s" % skip_header.replace("-", "_")
                if header in request.META:
                    cooldown_at = None
                    break
            else:
                cooldown_at = greylisted(address, ip)

            if cooldown_at:
                return JsonResponse(
                    {"message": "You are greylisted for another %s" % timeuntil(cooldown_at)}, status=403
                )
            else:
                tx = ctx["faucet"].send(ctx["wallet"], address, ip)
                amount = "%s%s" % (ctx["faucet"].sending_amount.normalize(), ctx["faucet"].asset_code)
                return JsonResponse(
                    {
                        "message": "Request received successfully. %s will be sent to %s" % (amount, address),
                        "tx": tx.id,
                    },
                    status=200,
                )

        return render(request, "faucet.html", context=ctx)
Exemplo n.º 7
0
    def get_timeuntil(self):
        """
        Returns a string representing the time until the next
        time this Job will be run (actually, the "string" returned
        is really an instance of ``ugettext_lazy``).

        >>> from chronograph.compatibility.dates import now
        >>> job = Job(next_run=now())
        >>> job.get_timeuntil().translate('en')
        u'due'
        """
        if self.disabled:
            return _('never (disabled)')

        delta = self.next_run - dates.now()
        if delta.days < 0:
            # The job is past due and should be run as soon as possible
            if self.check_is_running():
                return _('running')
            return _('due')
        elif delta.seconds < 60:
            # Adapted from django.utils.timesince
            count = lambda n: ungettext('second', 'seconds', n)
            return ugettext('%(number)d %(type)s') % {'number': delta.seconds,
                                                      'type': count(delta.seconds)}
        return timeuntil(self.next_run)
Exemplo n.º 8
0
 def locked_for(self, obj):
     if obj.locked_until is None:
         return u""
     elif obj.locked_until < timezone.now():
         return _(u"(expired)")
     else:
         return timeuntil(obj.locked_until)
Exemplo n.º 9
0
def timeuntil(value, *args):
    if value is None or isinstance(value, Undefined):
        return u''
    from django.utils.timesince import timeuntil

    value = template_localtime(value)
    return timeuntil(value, *args)
Exemplo n.º 10
0
def receive_transaction_hook_task(account_id, transaction):
    account = Account.objects.get(pk=account_id)

    if transaction['type'] != 'transaction.created':
        return

    transaction_utils.store_transaction(account, transaction['data'])

    account.current_balance += transaction['data']['amount']
    account.save()

    if account.nearing_zero_balance():
        mondo.insert_feed_item(
            account.user,
            account.mondo_account_id,
            {
                'title': "Top up your account in the next %s to avoid running out of money" % (
                    timeuntil(
                        account.time_of_zero_balance,
                    ).replace(u'\xa0', u' ')
                ),
                'image_url': settings.SITE_URL + staticfiles_storage.url(
                    'images/money-with-wings.png',
                ),
            },
        )
Exemplo n.º 11
0
 def test_depth(self):
     t = self.t + self.oneyear + self.onemonth + self.oneweek + self.oneday + self.onehour
     tests = [
         (t, 1, '1\xa0year'),
         (t, 2, '1\xa0year, 1\xa0month'),
         (t, 3, '1\xa0year, 1\xa0month, 1\xa0week'),
         (t, 4, '1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day'),
         (t, 5, '1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day, 1\xa0hour'),
         (t, 6, '1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day, 1\xa0hour'),
         (self.t + self.onehour, 5, '1\xa0hour'),
         (self.t + (4 * self.oneminute), 3, '4\xa0minutes'),
         (self.t + self.onehour + self.oneminute, 1, '1\xa0hour'),
         (self.t + self.oneday + self.onehour, 1, '1\xa0day'),
         (self.t + self.oneweek + self.oneday, 1, '1\xa0week'),
         (self.t + self.onemonth + self.oneweek, 1, '1\xa0month'),
         (self.t + self.oneyear + self.onemonth, 1, '1\xa0year'),
         (self.t + self.oneyear + self.oneweek + self.oneday, 3,
          '1\xa0year'),
     ]
     for value, depth, expected in tests:
         with self.subTest():
             self.assertEqual(timesince(self.t, value, depth=depth),
                              expected)
             self.assertEqual(timeuntil(value, self.t, depth=depth),
                              expected)
Exemplo n.º 12
0
    def get_timeuntil(self):
        """
        Returns a string representing the time until the next
        time this Job will be run.
        """
        if self.adhoc_run:
            return _('ASAP')
        elif self.disabled:
            return _('never (disabled)')
        elif not self.next_run:
            return "-"

        delta = self.next_run - tz_now()
        if delta.days < 0:
            # The job is past due and should be run as soon as possible
            return _('due')
        elif delta.seconds < 60:
            # Adapted from django.utils.timesince
            count = lambda n: ungettext('second', 'seconds', n)
            return ugettext('%(number)d %(type)s') % {
                'number': delta.seconds,
                'type': count(delta.seconds)
            }

        return timeuntil(self.next_run)
Exemplo n.º 13
0
    def handle(self, *args, **options):
        unfired = EventFire.objects.filter(
            fired=None).select_related("event").order_by("scheduled",
                                                         "id")[:50]

        self.stdout.write(
            "Fire       | Event                            | Contact    | Scheduled"
        )
        self.stdout.write(
            "-----------|----------------------------------|------------|--------------"
        )

        now = timezone.now()

        for fire in unfired:
            event = truncate(f"{fire.event.id}: {fire.event.name}", 32)
            contact = fire.contact_id

            if fire.scheduled > now:
                scheduled = timeuntil(fire.scheduled, now=now)
            else:
                scheduled = f"{timesince(fire.scheduled, now=now)} ago"

            self.stdout.write(
                f"{fire.id:10} | {event:<32} | {contact:10} | {scheduled}")
Exemplo n.º 14
0
    def get_timeuntil(self):
        """
        Returns a string representing the time until the next
        time this Job will be run (actually, the "string" returned
        is really an instance of ``ugettext_lazy``).
        
        >>> job = Job(next_run=datetime.now())
        >>> job.get_timeuntil().translate('en')
        u'due'
        """
        if not self.enabled:
            return _("never (disabled)")

        if not self.next_run:
            self.next_run = datetime.now()

        delta = self.next_run.replace(tzinfo=None) - datetime.now().replace(tzinfo=None)
        if delta.days < 0:
            # The job is past due and should be run as soon as possible
            if self.check_is_running():
                return _("running")
            return _("due")
        elif delta.seconds < 60:
            # Adapted from django.utils.timesince
            count = lambda n: ungettext("second", "seconds", n)
            return ugettext("%(number)d %(type)s") % {"number": delta.seconds, "type": count(delta.seconds)}
        return timeuntil(self.next_run)
Exemplo n.º 15
0
    def post(self, request, *args, **kwargs):
        address = request.POST.get("address")
        faucet = get_object_or_404(
            Faucet, asset_code__iexact=request.POST.get("asset"), visible=True)

        faucets = Faucet.objects.filter(visible=True).order_by("asset_code")
        ctx = {"address": address, "faucets": faucets, "faucet": faucet}
        if not address:
            messages.error(request, "You must supply a wallet address")
        elif not WALLET_RE.match(address):
            messages.error(request,
                           "That does not seem to be a valid wallet address")
        else:
            ip = _get_client_ip(request)
            cooldown_at = greylisted(address, ip)
            if cooldown_at:
                messages.warning(
                    request, "You are greylisted for another %s" %
                    timeuntil(cooldown_at))
            else:
                tx = faucet.send(address, ip)

                amount = "%s%s" % (faucet.sending_amount.normalize(),
                                   faucet.asset_code)
                messages.info(
                    request,
                    "Request received successfully. %s will be sent to %s" %
                    (amount, address))
                ctx["tx"] = tx

        return render(request, "faucet.html", context=ctx)
Exemplo n.º 16
0
def timeuntil(value, *args):
    if value is None or isinstance(value, Undefined):
        return u""
    from django.utils.timesince import timeuntil

    value = template_localtime(value)
    return timeuntil(value, *args)
Exemplo n.º 17
0
 def test_depth(self):
     t = (self.t + self.oneyear + self.onemonth + self.oneweek +
          self.oneday + self.onehour)
     tests = [
         (t, 1, "1\xa0year"),
         (t, 2, "1\xa0year, 1\xa0month"),
         (t, 3, "1\xa0year, 1\xa0month, 1\xa0week"),
         (t, 4, "1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day"),
         (t, 5, "1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day, 1\xa0hour"),
         (t, 6, "1\xa0year, 1\xa0month, 1\xa0week, 1\xa0day, 1\xa0hour"),
         (self.t + self.onehour, 5, "1\xa0hour"),
         (self.t + (4 * self.oneminute), 3, "4\xa0minutes"),
         (self.t + self.onehour + self.oneminute, 1, "1\xa0hour"),
         (self.t + self.oneday + self.onehour, 1, "1\xa0day"),
         (self.t + self.oneweek + self.oneday, 1, "1\xa0week"),
         (self.t + self.onemonth + self.oneweek, 1, "1\xa0month"),
         (self.t + self.oneyear + self.onemonth, 1, "1\xa0year"),
         (self.t + self.oneyear + self.oneweek + self.oneday, 3,
          "1\xa0year"),
     ]
     for value, depth, expected in tests:
         with self.subTest():
             self.assertEqual(timesince(self.t, value, depth=depth),
                              expected)
             self.assertEqual(timeuntil(value, self.t, depth=depth),
                              expected)
Exemplo n.º 18
0
 def test_naive_datetime_with_tzinfo_attribute(self):
     class naive(datetime.tzinfo):
         def utcoffset(self, dt):
             return None
     future = datetime.datetime(2080, 1, 1, tzinfo=naive())
     self.assertEqual(timesince(future), '0\xa0minutes')
     past = datetime.datetime(1980, 1, 1, tzinfo=naive())
     self.assertEqual(timeuntil(past), '0\xa0minutes')
Exemplo n.º 19
0
def timeuntil_filter(value, arg=None):
    """Format a date as the time until that date (i.e. "4 days, 6 hours")."""
    if not value:
        return ''
    try:
        return timeuntil(value, arg)
    except (ValueError, TypeError):
        return ''
Exemplo n.º 20
0
def timeuntil_filter(value, arg=None):
    """Formats a date as the time until that date (i.e. "4 days, 6 hours")."""
    if not value:
        return ''
    try:
        return timeuntil(value, arg)
    except (ValueError, TypeError):
        return ''
Exemplo n.º 21
0
def format_date(d):
    if not d:
        return ""

    if d < datetime.now():
        return timesince(d) + " ago"
    else:
        return "in " + timeuntil(d)
Exemplo n.º 22
0
def format_date(d):
    if not d:
        return ""

    if d < datetime.now():
        return timesince(d) + " ago"
    else:
        return "in " + timeuntil(d)
Exemplo n.º 23
0
 def get_expired_event(self, instance):  #check if the event is expired
     start_date = instance.start_date
     time_delta = timeuntil(
         start_date)  #even if it is a string, i can't compare it..
     time_zero = timesince(start_date, start_date)
     instance.expired_event = time_delta == time_zero  # validated_data.get(True, instance.expired_event)
     instance.save()
     return time_delta == time_zero
Exemplo n.º 24
0
    def get(self, request, *args, **kwargs):
        asset = kwargs.get("asset")
        if asset is not None:
            faucet = get_object_or_404(Faucet,
                                       asset_code__iexact=asset,
                                       visible=True)
        else:
            faucet = Faucet.objects.first()

        if self.curl:
            # the "API" version
            ip = _get_client_ip(request)
            address = kwargs["address"]
            if asset is None:
                return JsonResponse(
                    {"message": "You must specify an asset code to send"},
                    status=400)

            for skip_header in settings.WHITELISTED_HEADERS:
                header = "HTTP_%s" % skip_header.replace("-", "_")
                if header in request.META:
                    cooldown_at = None
                    break
            else:
                cooldown_at = greylisted(address, ip)

            if cooldown_at:
                return JsonResponse(
                    {
                        "message":
                        "You are greylisted for another %s" %
                        timeuntil(cooldown_at)
                    },
                    status=403)
            else:
                tx = faucet.send(address, ip)
                amount = "%s%s" % (faucet.sending_amount.normalize(),
                                   faucet.asset_code)
                return JsonResponse(
                    {
                        "message":
                        "Request received successfully. %s will be sent to %s"
                        % (amount, address),
                        "tx":
                        tx.txhash,
                    },
                    status=200,
                )

        # also list other faucets to get links to other assets other than the chosen one
        faucets = Faucet.objects.filter(visible=True).order_by("asset_code")

        return render(request,
                      "faucet.html",
                      context={
                          "faucets": faucets,
                          "faucet": faucet
                      })
Exemplo n.º 25
0
    def test_different_timezones(self):
        """ When using two different timezones. """
        now = datetime.datetime.now()
        now_tz = datetime.datetime.now(LocalTimezone(now))
        now_tz_i = datetime.datetime.now(FixedOffset((3 * 60) + 15))

        self.assertEquals(timesince(now), u'0 minutes')
        self.assertEquals(timesince(now_tz), u'0 minutes')
        self.assertEquals(timeuntil(now_tz, now_tz_i), u'0 minutes')
Exemplo n.º 26
0
    def test_different_timezones(self):
        """ Тестируем две различные таймзоны """
        now = datetime.datetime.now()
        now_tz = datetime.datetime.now(LocalTimezone())
        now_tz_i = datetime.datetime.now(FixedOffset((3 * 60) + 15))

        self.assertEqual(timesince(now), f'0\xa0минут')
        self.assertEqual(timesince(now_tz), "0\xa0минут")
        self.assertEqual(timeuntil(now_tz, now_tz_i), "0\xa0минут")
def timeuntil(value, arg=None):
    """Formats a date as the time until that date (i.e. "4 days, 6 hours")."""
    from django.utils.timesince import timeuntil
    if not value:
        return u''
    try:
        return timeuntil(value, arg)
    except (ValueError, TypeError):
        return u''
Exemplo n.º 28
0
 def as_columns(self):
     return (
         "{:%a %H:%M:%S}".format(self.date.datetime()),
         "{:%a %I:%M:%S %p}".format(ephem.localtime(self.date)),
         "{}".format(timeuntil(ephem.localtime(self.date))),
         "{0.key:^7}".format(self),
         "{} {}".format(get_symbol(self.body), self.body.name),
         "{0.azalt}°".format(self),
     )
Exemplo n.º 29
0
    def test_different_timezones(self):
        """ When using two different timezones. """
        now = datetime.datetime.now()
        now_tz = datetime.datetime.now(LocalTimezone(now))
        now_tz_i = datetime.datetime.now(FixedOffset((3 * 60) + 15))

        self.assertEqual(timesince(now), '0 minutes')
        self.assertEqual(timesince(now_tz), '0 minutes')
        self.assertEqual(timeuntil(now_tz, now_tz_i), '0 minutes')
Exemplo n.º 30
0
def timeuntil(value, arg=None):
    """Formats a date as the time until that date (i.e. "4 days, 6 hours")."""
    from django.utils.timesince import timeuntil
    if not value:
        return u''
    try:
        return timeuntil(value, arg)
    except (ValueError, TypeError):
        return u''
Exemplo n.º 31
0
 def remindme(self, command):
     yield from command.send_typing()
     try:
         timestamp = self.parse_time(command.args.time)
     except ValueError:
         yield from command.reply("Could not parse the time \"{}\"".format(command.args.time))
         return
     member = Member.objects.from_message(command.message)
     Message.objects.create(member=member, text=command.args.message, deliver_at=timestamp)
     yield from command.reply("I'll do so in {}".format(timeuntil(timestamp)))
Exemplo n.º 32
0
def card_text_from_machine_status(machine):
    status = dict(machine.status_choices)[machine.get_status()]
    next_reservation = machine.get_next_reservation()

    # If the machine is free for less than a day, provide the number of hours/minutes until the next reservation.
    if machine.get_status() == "F" and next_reservation is not None and (
            next_reservation.start_time - timezone.now()).days < 1:
        status = "{:} {:} {:}".format(status, _('for'),
                                      timeuntil(next_reservation.start_time))
    return status
Exemplo n.º 33
0
def humanize_date(value):
    today = date.today()
    try:
        if value > today:
            return 'In ' + timeuntil(value)
        elif value < today:
            return timesince(value) + ' ago'
        else:
            return 'Today'
    except (ValueError, TypeError):
        return ''
Exemplo n.º 34
0
 def get_display(self):
     if self.repeat_period == self.REPEAT_NEVER:
         return _("in %(timeperiod)s") % {"timeperiod": timeuntil(self.next_fire)} if self.next_fire else ""
     elif self.repeat_period == self.REPEAT_DAILY:
         time_of_day = time(self.repeat_hour_of_day, self.repeat_minute_of_hour, 0).strftime("%H:%M")
         return _("each day at %(time)s") % {"time": time_of_day}
     elif self.repeat_period == self.REPEAT_WEEKLY:
         days = [str(day) for day in self.get_repeat_days_display()]
         return _("each week on %(daysofweek)s" % {"daysofweek": ", ".join(days)})
     elif self.repeat_period == self.REPEAT_MONTHLY:
         return _("each month on the %(dayofmonth)s" % {"dayofmonth": ordinal(self.repeat_day_of_month)})
Exemplo n.º 35
0
def timediff_filter(value, arg=None):
    """Combines the functionality of timesince and timeuntil"""
    if not value:
        return ''
    try:
        if timesince(value, arg) == avoid_wrapping(ugettext('0 minutes')):
            return 'In ' + timeuntil(value, arg)
        else:
            return timesince(value, arg) + ' ago'
    except (ValueError, TypeError):
        return ''
Exemplo n.º 36
0
def cashdesk_session(session):
	try:
		cashdesk_pk = session["cashdesk"]
		cashdesk = Cashdesk.objects.get(pk=cashdesk_pk)
		cashdesk_session = cashdesk.active_session
		if (cashdesk_session.valid_until < datetime.datetime.now()):
			timeleft = timesince(cashdesk_session.valid_until) + " <span style=\"color:red\"><strong><u>overtime</u></strong></span>"
		else:
			timeleft = timeuntil(cashdesk_session.valid_until)
		return timeleft
	except:
		return "-"
Exemplo n.º 37
0
def card_text_from_machine_status(machine):
    status = machine.get_status_display()
    next_reservation = machine.get_next_reservation()

    # If the machine is free for less than a day, provide the number of hours/minutes until the next reservation.
    if (machine.get_status() == Machine.AVAILABLE
            and next_reservation is not None
            and (next_reservation.start_time - timezone.now()).days < 1):
        # Uses old format scheme due to gettext not having automatic detection of translations in f-strings
        status = "{:} {:} {:}".format(status, _('for'),
                                      timeuntil(next_reservation.start_time))
    return status
Exemplo n.º 38
0
def relative(when, include_span_tag=True):
    if not when:
        return ''
    delta = (when - datetime.now(tz=when.tzinfo)).total_seconds()
    if abs(delta) < 10:  # 10 seconds threshold
        text = ugettext(u"just now")
    elif delta < 0:
        text = ugettext(u"%s ago") % timesince(when)
    else:
        text = ugettext(u"in %s") % timeuntil(when)
    if include_span_tag:
        text = mark_safe(u"<span title='%(absolute)s'>%(relative)s</span>"
                         % {'relative': text, 'absolute': date(when, 'r')})
    return text
Exemplo n.º 39
0
def cashdesk_session(session):
    try:
        cashdesk_pk = session["cashdesk"]
        cashdesk = Cashdesk.objects.get(pk=cashdesk_pk)
        cashdesk_session = cashdesk.active_session
        if (cashdesk_session.valid_until < datetime.datetime.now()):
            timeleft = timesince(
                cashdesk_session.valid_until
            ) + " <span style=\"color:red\"><strong><u>overtime</u></strong></span>"
        else:
            timeleft = timeuntil(cashdesk_session.valid_until)
        return timeleft
    except:
        return "-"
Exemplo n.º 40
0
 def queue_estimate(self):
     """
     One-line info for estimated remaining queue wait.
     """
     now = datetime.now()
     if self.priority > 0:
         min_seconds = 60
         max_seconds = 180
         link = u'<a href="/priority/">%s</a>' % capfirst(_("priority"))
     else:
         self.preload_cache()
         browsers = self.matching_browsers()
         preload_foreign_keys(browsers, browser_group=True)
         requests = self.request_set.filter(screenshot__isnull=True)
         preload_foreign_keys(requests, browser_group=True)
         elapsed = now - self.submitted
         elapsed = elapsed.seconds + elapsed.days * 24 * 3600
         estimates = []
         for request in requests:
             estimate = request.queue_estimate(browsers)
             if estimate:
                 estimates.append(estimate - elapsed)
         if not estimates:
             return ''
         min_seconds = max(180, min(estimates) + 30)
         max_seconds = max(180, max(estimates) + 30)
         link = u'<a href="%s">%s</a>' % (self.get_absolute_url(),
                                          capfirst(_("details")))
     if min_seconds == max_seconds:
         estimate = timeuntil(now + timedelta(seconds=min_seconds))
     else:
         min_interval = timeuntil(now + timedelta(seconds=min_seconds))
         max_interval = timeuntil(now + timedelta(seconds=max_seconds))
         estimate = _("%(min_interval)s to %(max_interval)s") % locals()
     return mark_safe(u'<li>%s: %s (%s)</li>' %
                      (capfirst(_("queue estimate")), estimate, link))
Exemplo n.º 41
0
 def time_until_waiting_period(self):
     """
     Helper primarily used within templates whose sole purpose is to catch
     and display a custom message for the localized "0 minutes" otherwise
     returned by the built-in `timeuntil` template filter:
     https://docs.djangoproject.com/en/dev/ref/templates/builtins/#timeuntil
     """
     if not self.is_valid:
         return "0"
     now = timezone.now().date()
     if self.start_at > now:
         return "in_future"
     if self.end_at == now:
         return "0"
     return timeuntil(self.end_at, now)
Exemplo n.º 42
0
 def queue_estimate(self):
     """
     One-line info for estimated remaining queue wait.
     """
     now = datetime.now()
     if self.priority > 0:
         min_seconds = 60
         max_seconds = 180
         link = u'<a href="/priority/">%s</a>' % capfirst(_("priority"))
     else:
         self.preload_cache()
         browsers = self.matching_browsers()
         preload_foreign_keys(browsers, browser_group=True)
         requests = self.request_set.filter(screenshot__isnull=True)
         preload_foreign_keys(requests, browser_group=True)
         elapsed = now - self.submitted
         elapsed = elapsed.seconds + elapsed.days * 24 * 3600
         estimates = []
         for request in requests:
             estimate = request.queue_estimate(browsers)
             if estimate:
                 estimates.append(estimate - elapsed)
         if not estimates:
             return ''
         min_seconds = max(180, min(estimates) + 30)
         max_seconds = max(180, max(estimates) + 30)
         link = u'<a href="%s">%s</a>' % (
             self.get_absolute_url(), capfirst(_("details")))
     if min_seconds == max_seconds:
         estimate = timeuntil(now + timedelta(seconds=min_seconds))
     else:
         min_interval = timeuntil(now + timedelta(seconds=min_seconds))
         max_interval = timeuntil(now + timedelta(seconds=max_seconds))
         estimate = _("%(min_interval)s to %(max_interval)s") % locals()
     return mark_safe(u'<li>%s: %s (%s)</li>' % (
         capfirst(_("queue estimate")), estimate, link))
Exemplo n.º 43
0
def deadline(then):
    if not then:
        return ""

    if now() < then:
        return format_html(
            '<span class="label label-{}">{}</span>',
            deadline_color(then),
            "dans {}".format(timeuntil(then)).split(",")[0],
        )
    else:
        return format_html(
            '<span class="label label-{}">{}</span>',
            deadline_color(then),
            "il y a {} !".format(timesince(then)).split(",")[0],
        )
Exemplo n.º 44
0
Arquivo: models.py Projeto: esw/SapInt
    def get_timeuntil(self):
        """
        Returns a string representing the time until the next
        time this Job will be run.
        """
        if self.disabled:
            return _("never (disabled)")

        delta = self.next_run - datetime.now()
        if delta.days < 0:
            # The job is past due and should be run as soon as possible
            return _("due")
        elif delta.seconds < 60:
            # Adapted from django.utils.timesince
            count = lambda n: ungettext("second", "seconds", n)
            return ugettext("%(number)d %(type)s") % {"number": delta.seconds, "type": count(delta.seconds)}
        return timeuntil(self.next_run)
Exemplo n.º 45
0
 def to_dict(self):
     return {
         'id': self.pk,
         'title': self.title,
         'description': self.description,
         'start_date': self.start_date.strftime('%m-%d-%Y %H:%M'),
         'end_date': self.end_date.strftime('%m-%d-%Y %H:%M'),
         'duration': timeuntil(self.end_date, self.start_date),
         'start_date_str': self.start_date.strftime('%d %b').lstrip("0"),
         'team': self.team.to_dict(),
         'members': [ {
             'id': member.user.pk,
             'name': member.user.get_name(),
             'userpic': member.user.get_userpic_url(),
             'is_owner': member.is_owner,
             'url': reverse('user-page', kwargs={'user_id': member.user.pk})
         } for member in self.member_set.all()]
     }
Exemplo n.º 46
0
    def get_timeuntil(self):
        """
        Returns a string representing the time until the next
        time this Job will be run.
        """
        if self.disabled:
            return _('never (disabled)')

        delta = self.next_run - datetime.now()
        if delta.days < 0:
            # The job is past due and should be run as soon as possible
            return _('due')
        elif delta.seconds < 60:
            # Adapted from django.utils.timesince
            count = lambda n: ungettext('second', 'seconds', n)
            return ugettext('%(number)d %(type)s') % {'number': delta.seconds,
                                                      'type': count(delta.seconds)}
        return timeuntil(self.next_run)
Exemplo n.º 47
0
    def get_timeuntil(self):
        """
        Returns a string representing the time until the next
        time this Job will be run.
        """
        if self.adhoc_run:
            return u'ASAP'
        elif self.disabled:
            return u'never (disabled)'

        delta = self.next_run - tz_now()
        if delta.days < 0:
            # The job is past due and should be run as soon as possible
            return u'due'
        elif delta.seconds < 60:
            return u'{} sec.'.format(delta.seconds)

        return timeuntil(self.next_run)
Exemplo n.º 48
0
        def _post_clean(self):
            super(locking_form, self)._post_clean()
            # We were not passed a user, so we have no way of telling who is
            # the owner of an object's lock; better not to raise
            # ValidationError in that case
            if not user:
                return

            # If this model doesn't have primary keys, don't continue
            if not self._meta.model._meta.pk:
                return

            # If there are already errors, no point checking lock since save
            # will be prevented
            if self.errors:
                return

            # If we don't have a saved object yet, it could not have a lock
            if not self.instance.pk:
                return

            try:
                lock = Lock.objects.get_lock_for_object(self.instance)
            except Lock.DoesNotExist:
                return

            # If either of these conditions are met, we don't have an error.
            # If we pass beyond this point, we have a validation error because
            # the object is locked by a user other than the current user.
            if not lock.is_locked or lock.is_locked_by(user):
                return

            try:
                raise forms.ValidationError(
                    ("You cannot save this %(verbose_name)s because it is "
                     "locked by %(user)s. The lock will expire in "
                     "%(time_remaining)s if that user is idle.") %
                    {
                        'verbose_name': self._meta.model._meta.verbose_name,
                        'user': lock.locked_by.get_full_name(),
                        'time_remaining': timeuntil(lock.lock_expiration_time),
                    })
            except forms.ValidationError as e:
                self._update_errors({NON_FIELD_ERRORS: e.messages})
Exemplo n.º 49
0
  def getHorarios(self, ponto):
      estimativas = []
      for l in self.linhasQuePassamNoPonto(ponto):
              prev = self.getPrevisao(l,ponto,False)
              estimativas +=prev.estimativas
 
      horarios ={}
      for e in estimativas:
         ee = formata_horario(e)
         o={}
         if ee == {}:
             continue
         if  not horarios.has_key(ee['linha']):
              horarios[ee['linha']] = []
         o['data_estimada']="%s (%s)" % (ee['data_estimada'].strftime("%H:%M"),timeuntil(ee['data_estimada']))
         o['data_horario']=ee['data_horario'].strftime("%H:%M")
         o['data_pacote']=ee['data_pacote'].strftime("%H:%M")
         horarios[ee['linha']].append(o)
      return horarios 
Exemplo n.º 50
0
    def get_eta_display(self):
        import datetime
        from django.models.aurora import fetchers
        from django.utils.timesince import timeuntil

        try:
            if self.fetcher.download_rate:
                seconds = (self.metainfo.total_bytes - self.downloaded) / self.fetcher.download_rate
                days = seconds / (24 * 60 * 60)
                seconds = seconds % (24 * 60 * 60)
                
                now = datetime.datetime.now()
                delta = datetime.timedelta(days=days, seconds=seconds)

                return timeuntil(now + delta)

            else:
                return ''

        except fetchers.FetcherDoesNotExist:
            return ''
Exemplo n.º 51
0
    def time_until_expire(self):
        """
        Human-readable formatting of interval before expiration.
        """
        now = datetime.now()
        remaining = self.expire - now
        disabled = ''
        if remaining >= timedelta(minutes=29, seconds=50):
            remaining = timedelta(minutes=30)
            disabled = ' disabled="disabled"'
        interval = timeuntil(now + remaining, now)
        expire = capfirst(_("expires in %(interval)s")) % \
            {'interval': interval}
        if self.same_user():
            expire += '\n'.join(('',
'<input type="hidden" name="request_group_id" value="%d" />' % self.id,
'<input type="submit" name="extend" value="%s"%s />' % (
    unicode(capfirst(_("extend"))), disabled),
'<input type="submit" name="cancel" value="%s" />' % (
    unicode(capfirst(_("cancel"))))))
        return mark_safe('<li>%s</li>' % (expire))
Exemplo n.º 52
0
def resource_language_lock(request, project_slug, resource_slug, language_code):
    """
    View to lock a resource language.

    It uses a json response to be used with Ajax requests.
    """
    response={}
    if request.method == 'POST':
        resource = get_object_or_404(Resource.objects.select_related('project'),
            slug=resource_slug, project__slug=project_slug)
        language = get_object_or_404(Language, code=language_code)
        team = Team.objects.get_or_none(resource.project, language_code)

        try:
            lock = Lock.objects.create_update(resource, language, request.user)
            response['status'] = "OK"
            response['message'] = _("Lock created.")
            response['timeuntil'] = timeuntil(lock.expires)
        except LockError, e:
            response['status'] = "FAILED"
            response['message'] = e.message
Exemplo n.º 53
0
def gametime(game):
    if game.state == 'finished':
        since_str = timesince(game.next_ending)
        # only show the most significant part of
        # the string
        since_str, _, _ = since_str.partition(',')
        return 'Finished %s ago' % since_str.strip()
    elif game.state == 'invalid':
        since_str = timesince(game.next_ending)
        # only show the most significant part of
        # the string
        since_str, _, _ = since_str.partition(',')
        return 'Cancelled %s ago' % since_str.strip()

    until_str = timeuntil(game.next_ending)
    # add "more" just after the first set of digits, so
    # "1 hour, 15 minutes" becomes "1 more hour, 15 minutes"
    num, _, rest = until_str.partition(' ')

    state = game.state[0].upper() + game.state[1:]

    return '%s for %s more %s' % (state, num, rest)
Exemplo n.º 54
0
def tz_std_date_ago(value, user):
    """
    This is a further simplification of the kinds of time stamps we
    frequently use in our app framework. It is just like tz_std_date, except
    we return the datetime string with ' (<timesince> ago)'

    NOTE: We switch to 'timeuntil' if the date provided is in the
          the future.
    """
    if not isinstance(value, datetime):
        return ""

    # We need to see if the date is before or after now. If the date does
    # not have a timezone set then we assume it is in the server's timezone.
    #
    now = datetime.utcnow().replace(tzinfo = pytz.UTC)
    if value.tzinfo is None:
        server_tz = pytz.timezone(settings.TIME_ZONE)
        value = value.replace(tzinfo = server_tz)
    if value < now:
        return "%s (%s ago)" % (tz_std_date(value, user), timesince(value))
    else:
        return "%s (in %s)" % (tz_std_date(value, user), timeuntil(value))
Exemplo n.º 55
0
 def test_both_date_objects(self):
     """ Timesince should work with both date objects (#9672) """
     today = datetime.date.today()
     self.assertEqual(timeuntil(today + self.oneday, today), '1\xa0day')
     self.assertEqual(timeuntil(today - self.oneday, today), '0\xa0minutes')
     self.assertEqual(timeuntil(today + self.oneweek, today), '1\xa0week')
Exemplo n.º 56
0
 def test_date_objects(self):
     """ Both timesince and timeuntil should work on date objects (#17937). """
     today = datetime.date.today()
     self.assertEqual(timesince(today + self.oneday), '0\xa0minutes')
     self.assertEqual(timeuntil(today - self.oneday), '0\xa0minutes')
Exemplo n.º 57
0
 def time_remaining(self):
     if self.status == self.OPEN_STATUS:
         return timeuntil(self.bounties().aggregate(Min('ends'))['ends__min'], datetime.datetime.now()).split(',')[0]
     return timeuntil(self.modified + datetime.timedelta(days=3), datetime.datetime.now()).split(',')[0]