Example #1
0
File: api.py Project: l0rb/og_api
 def _doApiRequest(self, type, append=""):
     type_to_update_intervall = {
             'playerData': timedelta(days=7),
             'alliances': timedelta(days=1),
             'players': timedelta(days=1),
             'highscore': timedelta(hours=1),
             }
     api_data = self.cache.lookup(self.server+"_"+type+append)
     need_download = False
     if not api_data:
         logger.info("Need download because %s is not cached")
         need_download = True
     else:
         try:
             # exception when response is "player not found"
             timestamp = int(textextract(api_data, 'timestamp="', '"'))
         except:
             timestamp = os.path.getmtime(self.cache.get_path(self.server+"_"+type+append))
         timestamp = datetime.fromtimestamp(timestamp)
         if timestamp + type_to_update_intervall[type] < datetime.now():
             logger.info("Need download because %s is more than 12h old" % (self.server+"_"+type))
             need_download = True
     if need_download:
         r = self.requests.get('http://'+self.server+'/api/'+type+'.xml'+append)
         self.cache.write(self.server+"_"+type+append, r.text)
         api_data = r.text
     return (need_download, type, append), api_data
 def test_external_task_sensor_fn(self):
     self.test_time_sensor()
     # check that the execution_fn works
     t = ExternalTaskSensor(
         task_id='test_external_task_sensor_check_delta',
         external_dag_id=TEST_DAG_ID,
         external_task_id=TEST_TASK_ID,
         execution_date_fn=lambda dt: dt + timedelta(0),
         allowed_states=['success'],
         dag=self.dag
     )
     t.run(
         start_date=DEFAULT_DATE,
         end_date=DEFAULT_DATE,
         ignore_ti_state=True
     )
     # double check that the execution is being called by failing the test
     t2 = ExternalTaskSensor(
         task_id='test_external_task_sensor_check_delta',
         external_dag_id=TEST_DAG_ID,
         external_task_id=TEST_TASK_ID,
         execution_date_fn=lambda dt: dt + timedelta(days=1),
         allowed_states=['success'],
         timeout=1,
         poke_interval=1,
         dag=self.dag
     )
     with self.assertRaises(exceptions.AirflowSensorTimeout):
         t2.run(
             start_date=DEFAULT_DATE,
             end_date=DEFAULT_DATE,
             ignore_ti_state=True
         )
Example #3
0
    def generate_inventory_data(self, inventories, is_online=1):
        start_day = datetime.date.today()
        end_day = start_day + datetime.timedelta(days=89)

        manual_confirm_count = []
        if is_online == 1:
            day = start_day
            while day <= end_day:
                month = int("{}{:0>2d}".format(day.year, day.month))
                for inventory in inventories:
                    if inventory.month == month:
                        manual_confirm_count.append(str(inventory.get_day(day.day)))
                        break
                day = day + datetime.timedelta(days=1)
        else:
            #manual_confirm_count = ['0' for i in range(90)]
            manual_confirm_count = '0' * 90

        data = {}
        data['chain_id'] = CHAIN_ID

        if inventories[0].merchant_id in SPEC_STOCK_PUSH:
            data['ota_id'] = SPEC_STOCK_PUSH[inventories[0].merchant_id]
        else:
            data['ota_id'] = 0

        data['hotel_id'] = str(inventories[0].hotel_id)
        data['room_type_id'] = str(inventories[0].roomtype_id)
        data['manual_confirm_counts'] = '|'.join(manual_confirm_count)
        data['start_date'] = start_day
        data['end_date'] = end_day
        data['is_soldout_auto_close'] = 1

        return data
Example #4
0
def gen_datetime(min_date=None, max_date=None):
    """Returns a random datetime value

    :param max_date: A valid ``datetime.datetime`` object.
    :param max_date: A valid ``datetime.datetime`` object.
    :raises: ``ValueError`` if arguments are not valid ``datetime.datetime``
        objects.
    :returns: Random ``datetime.datetime`` object.

    """

    _min_value = (datetime.datetime.now() -
                  datetime.timedelta(365 * MIN_YEARS))
    _max_value = (datetime.datetime.now() +
                  datetime.timedelta(365 * MAX_YEARS))

    if min_date is None:
        min_date = _min_value
    if max_date is None:
        max_date = _max_value

    # Validation
    if not isinstance(min_date, datetime.datetime):
        raise ValueError("%s is not a valid datetime.datetime object")
    if not isinstance(max_date, datetime.datetime):
        raise ValueError("%s is not a valid datetime.datetime object")

    # Check that max_date is not before min_date
    assert min_date < max_date

    # Pick a time between min and max dates
    diff = max_date - min_date
    seconds = random.randint(0, diff.days * 3600 * 24 + diff.seconds)

    return min_date + datetime.timedelta(seconds=seconds)
    def test_go_live_page_will_be_published(self):
        # Connect a mock signal handler to page_published signal
        signal_fired = [False]
        signal_page = [None]
        def page_published_handler(sender, instance, **kwargs):
            signal_fired[0] = True
            signal_page[0] = instance
        page_published.connect(page_published_handler)


        page = SimplePage(
            title="Hello world!",
            slug="hello-world",
            live=False,
            go_live_at=timezone.now() - timedelta(days=1),
        )
        self.root_page.add_child(instance=page)

        page.save_revision(approved_go_live_at=timezone.now() - timedelta(days=1))

        p = Page.objects.get(slug='hello-world')
        self.assertFalse(p.live)
        self.assertTrue(PageRevision.objects.filter(page=p).exclude(approved_go_live_at__isnull=True).exists())

        management.call_command('publish_scheduled_pages')

        p = Page.objects.get(slug='hello-world')
        self.assertTrue(p.live)
        self.assertFalse(PageRevision.objects.filter(page=p).exclude(approved_go_live_at__isnull=True).exists())

        # Check that the page_published signal was fired
        self.assertTrue(signal_fired[0])
        self.assertEqual(signal_page[0], page)
        self.assertEqual(signal_page[0], signal_page[0].specific)
Example #6
0
    def test_maybe_timedelta(self):
        D = maybe_timedelta

        for i in (30, 30.6):
            self.assertEqual(D(i), timedelta(seconds=i))

        self.assertEqual(D(timedelta(days=2)), timedelta(days=2))
Example #7
0
def daterange(start_date, end_date):
    if start_date <= end_date:
        for n in range((end_date - start_date).days + 1):
            yield start_date + datetime.timedelta(n)
    else:
        for n in range((start_date - end_date).days + 1):
            yield start_date - datetime.timedelta(n)
Example #8
0
    def test_linked_in_add_to_profile_btn_not_appearing_without_config(self):
        # Without linked-in config don't show Add Certificate to LinkedIn button
        self.client.login(username="jack", password="test")

        CourseModeFactory.create(
            course_id=self.course.id,
            mode_slug='verified',
            mode_display_name='verified',
            expiration_datetime=datetime.now(pytz.UTC) - timedelta(days=1)
        )

        CourseEnrollment.enroll(self.user, self.course.id, mode='honor')

        self.course.start = datetime.now(pytz.UTC) - timedelta(days=2)
        self.course.end = datetime.now(pytz.UTC) - timedelta(days=1)
        self.course.display_name = u"Omega"
        self.course = self.update_course(self.course, self.user.id)

        download_url = 'www.edx.org'
        GeneratedCertificateFactory.create(
            user=self.user,
            course_id=self.course.id,
            status=CertificateStatuses.downloadable,
            mode='honor',
            grade='67',
            download_url=download_url
        )
        response = self.client.get(reverse('dashboard'))

        self.assertEquals(response.status_code, 200)
        self.assertNotIn('Add Certificate to LinkedIn', response.content)

        response_url = 'http://www.linkedin.com/profile/add?_ed='
        self.assertNotContains(response, escape(response_url))
Example #9
0
def generate_plan(wave, hours, minutes):
    goal_time = datetime.timedelta(
        hours=hours,
        minutes=minutes,
    )
    goal_pace_sec = goal_time.seconds / RACE_DIST
    start_time = wave_starts[wave]
    goal_finish = start_time + goal_time
    beer_time = goal_finish + datetime.timedelta(hours=1)

    for details in viewing_points.values():
        eta = start_time + datetime.timedelta(seconds=details["Mile"] * goal_pace_sec)
        details["ETA"] = eta.strftime("%I:%M %p")

    min_between_2_3 = (viewing_points[3]["Mile"] - viewing_points[2]["Mile"]) * goal_pace_sec / 60
    viewing_points[2]["Notes"] = viewing_points[2]["Notes"].replace(
        "$BETWEEN", str(int(min_between_2_3))
    )

    friend_link = "http://nycmarathon.aws.af.cm/?" + urlencode(
        {"wave": wave, "hours": hours, "minutes": minutes}
    )

    #write_kml(viewing_points)
    return (start_time, goal_pace_sec, goal_finish, beer_time, viewing_points, friend_link)
    def test_expiry_date_range(self):
        """
        Test that the verifications are filtered on the given range. Email is not sent for any verification with
        expiry date out of range
        """
        user = UserFactory.create()
        verification_in_range = self.create_and_submit(user)
        verification_in_range.status = 'approved'
        verification_in_range.expiry_date = now() - timedelta(days=1)
        verification_in_range.save()

        user = UserFactory.create()
        verification = self.create_and_submit(user)
        verification.status = 'approved'
        verification.expiry_date = now() - timedelta(days=5)
        verification.save()

        call_command('send_verification_expiry_email', '--days-range=2')

        # Check that only one email is sent
        self.assertEqual(len(mail.outbox), 1)

        # Verify that the email is not sent to the out of range verification
        expiry_email_date = SoftwareSecurePhotoVerification.objects.get(pk=verification.pk).expiry_email_date
        self.assertIsNone(expiry_email_date)
Example #11
0
    def get_datetime_at_period_ix(self, ix):
        """
        Get the datetime at a given period.

        :param period: The index of the period.

        :returns: The datetime.
        """

        if self.timestep_period_duration == TimePeriod.millisecond:
            return self.start_datetime + timedelta(milliseconds=ix)
        elif self.timestep_period_duration == TimePeriod.second:
            return self.start_datetime + timedelta(seconds=ix)
        elif self.timestep_period_duration == TimePeriod.minute:
            return self.start_datetime + timedelta(minutes=ix)
        elif self.timestep_period_duration == TimePeriod.hour:
            return self.start_datetime + timedelta(hours=ix)
        elif self.timestep_period_duration == TimePeriod.day:
            return self.start_datetime + relativedelta(days=ix)
        elif self.timestep_period_duration == TimePeriod.week:
            return self.start_datetime + relativedelta(days=ix*7)
        elif self.timestep_period_duration == TimePeriod.month:
            return self.start_datetime + relativedelta(months=ix)
        elif self.timestep_period_duration == TimePeriod.year:
            return self.start_datetime + relativedelta(years=ix)
    def test_dry_run_flag(self):
        """
        Test that the dry run flags sends no email and only logs the the number of email sent in each batch
        """
        user = UserFactory.create()
        verification = self.create_and_submit(user)
        verification.status = 'approved'
        verification.expiry_date = now() - timedelta(days=1)
        verification.save()

        start_date = now() - timedelta(days=1)  # using default days
        count = 1

        with LogCapture(LOGGER_NAME) as logger:
            call_command('send_verification_expiry_email', '--dry-run')
            logger.check(
                (LOGGER_NAME,
                 'INFO',
                 u"For the date range {} - {}, total Software Secure Photo verification filtered are {}"
                 .format(start_date.date(), now().date(), count)
                 ),
                (LOGGER_NAME,
                 'INFO',
                 u"This was a dry run, no email was sent. For the actual run email would have been sent "
                 u"to {} learner(s)".format(count)
                 ))
        self.assertEqual(len(mail.outbox), 0)
Example #13
0
def login_and_forward(request, user, forward=None, message=None):
    if user.is_suspended():
        return forward_suspended_user(request, user)

    user.backend = "django.contrib.auth.backends.ModelBackend"
    login(request, user)

    if message is None:
        message = _("Welcome back %s, you are now logged in") % user.username

    request.user.message_set.create(message=message)

    if not forward:
        forward = request.session.get(ON_SIGNIN_SESSION_ATTR, reverse('index'))

    pending_data = request.session.get(PENDING_SUBMISSION_SESSION_ATTR, None)

    if pending_data and (user.email_isvalid or pending_data['type'] not in settings.REQUIRE_EMAIL_VALIDATION_TO):
        submission_time = pending_data['time']
        if submission_time < datetime.datetime.now() - datetime.timedelta(minutes=int(settings.HOLD_PENDING_POSTS_MINUTES)):
            del request.session[PENDING_SUBMISSION_SESSION_ATTR]
        elif submission_time < datetime.datetime.now() - datetime.timedelta(minutes=int(settings.WARN_PENDING_POSTS_MINUTES)):
            user.message_set.create(message=(_("You have a %s pending submission.") % pending_data['data_name']) + " %s, %s, %s" % (
                html.hyperlink(reverse('manage_pending_data', kwargs={'action': _('save')}), _("save it")),
                html.hyperlink(reverse('manage_pending_data', kwargs={'action': _('review')}), _("review")),
                html.hyperlink(reverse('manage_pending_data', kwargs={'action': _('cancel')}), _("cancel"))
            ))
        else:
            return manage_pending_data(request, _('save'), forward)

    return HttpResponseRedirect(forward)
Example #14
0
	def checkday(self, day):
		"""
		Check the day of unit
		Input: day - datetime/date, tested day
		Return: value of work unit or None
		"""
		if type(day) == datetime:
			day = day.date()
		if day in self.days:
			lgood = self.days[day].gettimetuple()
			lbad = []
			if day.weekday() in self.pauses:
				thStart = datetime.combine(day, self.pauses[day.weekday()].time)
				thEnd = thStart + timedelta(seconds = (self.pauses[day.weekday()].duration*60))
				lbad.append((thStart, thEnd))
			if day in self.incidents:
			        for inc in self.incidents[day]:
			                dtStart = inc.datetime
			                dtEnd = dtStart + timedelta(minutes = inc.duration)
			                lbad.append((dtStart, dtEnd))
			lbad = segment.union(lbad)
			result = (lgood[1] - lgood[0]).total_seconds()/60
			for l in lbad:
			        z = segment.getintersection(lgood, l)
			        if z:
			                result -= (z[1] - z[0]).total_seconds()/60
			return result
Example #15
0
def test_parse_timewindow_now_plus_delta():
    now = datetime.datetime.now(tzutc())
    start,end = parse_timewindow("+ 2 hours")
    assert start >= now
    assert start < now + datetime.timedelta(seconds=5)
    assert end > start
    assert end - start == datetime.timedelta(hours=2)
Example #16
0
 def read_lock(self, lockfile):
     """ Read job info from existing lock file. Raise an IOError if the
         lockfile cannot be read
     """
     lock = open(lockfile, 'r')
     temp = pickle.load(lock)
     lock.close()
     logging.debug("Read JobInfo from lock:\n%s", temp)
     self.__dict__ = temp.__dict__
     if self.start_time > 0:
         walltime = int(time.time() - self.start_time)
         self.resources_used['walltime'] \
         = str(datetime.timedelta(seconds=walltime))
     (cput, mem, vmem, threads) = get_cpu_mem_info(self.pid)
     if cput > 0:
         self.resources_used['cput'] \
         = str(datetime.timedelta(seconds=cput))
     if mem > 0:
         self.resources_used['mem'] = format_bytes(mem)
     if vmem > 0:
         self.resources_used['vmem'] = format_bytes(vmem)
     if threads > 0:
         self.resources_used['threads'] = threads
     self.job_id = os.path.splitext(os.path.basename(lockfile))[0]
     self.lockfile = lockfile
Example #17
0
    def test_08_publishing(self):
        self.create_default_page_set()

        page = Page.objects.get(pk=1)
        page2 = Page.objects.get(pk=2)
        self.is_published(page.get_absolute_url(), should_be=False)
        self.is_published(page2.get_absolute_url(), should_be=False)

        page.active = True
        page.save()
        page2.active = True
        page2.save()
        self.is_published(page.get_absolute_url(), should_be=True)
        self.is_published(page2.get_absolute_url(), should_be=True)

        old_publication = page.publication_date
        page.publication_date = datetime.now() + timedelta(days=1)
        page.save()
        self.is_published(page.get_absolute_url(), should_be=False)

        # Should be not accessible because of its parent's inactivity
        self.is_published(page2.get_absolute_url(), should_be=False)

        page.publication_date = old_publication
        page.publication_end_date = datetime.now() - timedelta(days=1)
        page.save()
        self.is_published(page.get_absolute_url(), should_be=False)

        # Should be not accessible because of its parent's inactivity
        self.is_published(page2.get_absolute_url(), should_be=False)

        page.publication_end_date = datetime.now() + timedelta(days=1)
        page.save()
        self.is_published(page.get_absolute_url(), should_be=True)
        self.is_published(page2.get_absolute_url(), should_be=True)
Example #18
0
def InformacionGeneral():
	fecha=datetime.now().strftime('%H:%M:%S %d/%m/%Y ')
	resultado="####---"+fecha+"---####\n"
	resultado+="--Sensores---------------------------------------\n"
	resultado+="| "+humedad1._nombre+" -> "+humedad1.get("datoImpreso")+" \n"
	resultado+="| "+humedad2._nombre+" -> "+humedad2.get("datoImpreso")+" \n"
	resultado+="| "+humedad3._nombre+" -> "+humedad3.get("datoImpreso")+" \n"
#	resultado+="| "+ph1._nombre+" -> "+str(fn.ConvertirPH(ph1))+"/14\n"
#	resultado+="| "+electro1._nombre+" -> "+str(fn.ConvertirEC(electro1))+" s/m\n"
#	resultado+="| "+solar._nombre+" -> "+str(solar.get("datoDigital"))+"/"+str(solar.get("totalDigital"))+"\n"
#	resultado+="| "+luzinterior._nombre+" -> "+str(luzinterior.get("datoDigital"))+"/"+str(luzinterior.get("totalDigital"))+"\n"
	resultado+="-------------------------------------------------\n\n"
	resultado+="--Controladores----------------------------------\n"
	resultado+="| "+bombaAgua._nombre+" -> "+str(bombaAgua._estado)+" \n"
#	resultado+="| "+iluminacion._nombre+" -> "+str(iluminacion._estado)+"\n"
	resultado+="-------------------------------------------------\n\n"
	if(sistemaRiego._riegoActivo):
		resultado+="--Tiempo de Riego--------------------------------\n"
		resultado+="| Tiempo regado -> "+str(timedelta(seconds=sistemaRiego._tiempoRiego))+"\n"
		resultado+="| Tiempo restante -> "+str(timedelta(seconds=(op.TIEMPO_DE_RIEGO-sistemaRiego._tiempoRiego)))+" \n"
		resultado+="-------------------------------------------------\n\n"

#	if(len(op.ERRORES)):
#		resultado+="--Errores: --------------------------------\n"
#		for error in op.ERRORES:
#			resultado+=error

	return resultado
Example #19
0
    def get_expired_reporters(cls, today):
        # we'll check anybody who hasn't been seen in between 15 and 45 days
        expired_start = today - datetime.timedelta(45)
        expired_end = today - datetime.timedelta(15)

        # reporter reminder type
        expired_type = ReminderType.objects.get(name = "Inactive Reporter")
        inactive = [ r for r in Reporter.objects.all() if r.is_expired() ]

        reporters = set()

        for reporter in inactive:
            # get our most recent reminder
            reminders = Reminder.objects.filter(reporter=reporter, type=expired_type).order_by('-date')

            # we've had a previous reminder
            if reminders:
                last_reminder = reminders[0]
                # if we were last seen before the reminder, we've already been reminded, skip over
                try:
                    if reporter.last_seen() < last_reminder.date:   continue
                except: pass

            # otherwise, pop this reporter on
            reporters.add(reporter)

        return reporters
Example #20
0
def _parse_datetime_value(value):
    # timezones are not supported and are assumed UTC
    if value[-1] == 'Z':
        value = value[:-1]

    value_len = len(value)
    if value_len in (8, 10):
        value = datetime.strptime(value, '%Y-%m-%d').replace(
            tzinfo=timezone.utc,
        )
        return [value, value + timedelta(days=1)]
    elif value[4] == '-':
        try:
            value = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S').replace(
                tzinfo=timezone.utc,
            )
        except ValueError:
            value = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f').replace(
                tzinfo=timezone.utc,
            )
    else:
        value = datetime.utcfromtimestamp(float(value)).replace(
            tzinfo=timezone.utc,
        )
    return [value - timedelta(minutes=5), value + timedelta(minutes=6)]
Example #21
0
def HolidayDateByYear(year):
    holidays = {str(year) + "-01-01": "New Year's Day",
                str(year) + "-12-24": "Christmas Eve", 
                str(year) + "-12-25": "Christmas Day",
                str(year) + "-12-31": "New Year's Eve",
                str(year) + "-07-04": "Independence Day",}
    for k in holiday_formulas:
        temp_date = None
        if holiday_formulas[k][0] < 0:
            if holiday_formulas[k][2] > 11:
                days = 31
            else:
                days = ((date(int(year), holiday_formulas[k][2] + 1, 1) - date(int(year), holiday_formulas[k][2], 1))).days
            temp_date = date(int(year), holiday_formulas[k][2], days)
            delta = -timedelta(days=1)
        else:
            start_day = (7 * holiday_formulas[k][0]) + 1
            if start_day == 0:
                start_day = 1
            temp_date = date(int(year), holiday_formulas[k][2], start_day)
            delta = timedelta(days=1)
        while not temp_date.strftime("%A") == holiday_formulas[k][1]:
            temp_date = temp_date + delta
            if not temp_date.month == holiday_formulas[k][2]:
                continue
        if len(holiday_formulas[k]) > 3:
            temp_date = temp_date + timedelta(days=holiday_formulas[k][3])
        holidays[str(year) + "-" + str(holiday_formulas[k][2]).zfill(2) + "-" + str(temp_date.day).zfill(2)] = k
    return holidays
Example #22
0
 def run(self, **kwargs):
     from apps.rss_feeds.models import Feed        
     settings.LOG_TO_STREAM = True
     now = datetime.datetime.utcnow()
     
     # Active feeds
     feeds = Feed.objects.filter(
         next_scheduled_update__lte=now,
         active=True
     ).exclude(
         active_subscribers=0
     ).order_by('?')
     Feed.task_feeds(feeds)
     
     # Mistakenly inactive feeds
     day = now - datetime.timedelta(days=1)
     feeds = Feed.objects.filter(
         last_update__lte=day, 
         queued_date__lte=day,
         min_to_decay__lte=60*24,
         active_subscribers__gte=1
     ).order_by('?')[:20]
     if feeds: Feed.task_feeds(feeds)
     
     week = now - datetime.timedelta(days=7)
     feeds = Feed.objects.filter(
         last_update__lte=week, 
         queued_date__lte=day,
         active_subscribers__gte=1
     ).order_by('?')[:20]
     if feeds: Feed.task_feeds(feeds)
Example #23
0
    def get_chart_data(self, instance, max_days=90):
        if hasattr(instance, '_state'):
            db = instance._state.db
        else:
            db = 'default'

        if not has_charts(db):
            return []

        hours = max_days * 24
        today = datetime.datetime.now().replace(microsecond=0, second=0, minute=0)
        min_date = today - datetime.timedelta(hours=hours)

        method = get_sql_date_trunc('date', db)

        chart_qs = list(instance.messagecountbyminute_set\
                          .filter(date__gte=min_date)\
                          .extra(select={'grouper': method}).values('grouper')\
                          .annotate(num=Sum('times_seen')).values_list('grouper', 'num')\
                          .order_by('grouper'))

        if not chart_qs:
            return []

        rows = dict(chart_qs)

        #just skip zeroes
        first_seen = hours
        while not rows.get(today - datetime.timedelta(hours=first_seen)) and first_seen > 24:
            first_seen -= 1

        return [rows.get(today - datetime.timedelta(hours=d), 0) for d in xrange(first_seen, -1, -1)]
Example #24
0
    def _apply_datespan_shifts(self, datespan):
        if datespan and not isinstance(datespan, DateSpan):
            raise ValueError("datespan must be an instance of DateSpan")

        if datespan:
            datespan = copy.copy(datespan)
            now = datetime.datetime.utcnow()

            # make sure we don't go over the current day
            # remember, there is no timezone support for this yet
            if datespan.enddate > now:
                datespan.enddate = now

            datespan.enddate = datespan.enddate.replace(hour=23, minute=59, second=59, microsecond=999999)
            if self.fixed_datespan_days:
                datespan.startdate = datespan.enddate - datetime.timedelta(days=self.fixed_datespan_days,
                                                                           microseconds=-1)
            if self.fixed_datespan_months:
                # By making the assumption that the end date is always the end of the month
                # the first months adjustment is accomplished by moving the start date to
                # the beginning of the month. Any additional months are subtracted in the usual way
                start = self.get_first_day_of_month(datespan.enddate.year, datespan.enddate.month)
                start_year, start_month = add_months(start.year, start.month, -(self.fixed_datespan_months - 1))
                datespan.startdate = start.replace(year=start_year, month=start_month)

            if self.startdate_shift:
                datespan.startdate = datespan.startdate + datetime.timedelta(days=self.startdate_shift)
            if self.enddate_shift:
                datespan.enddate = datespan.enddate + datetime.timedelta(days=self.enddate_shift)
            
        return datespan
Example #25
0
    def search(self, serie, numero, remitente, destinatario, sucursal, fecha):
        flat = serie or numero or remitente or destinatario or fecha
        tz = timezone.get_current_timezone()
        if flat:
            if fecha:
                "si se ingreso fecha"
                date = datetime.strptime(fecha, "%d/%m/%Y")
                end_date = timezone.make_aware(date, tz)
                start_date = end_date - timedelta(days=7)
            else:

                date = datetime.strptime("01/10/2015", "%d/%m/%Y")
                end_date = timezone.now()
                start_date = timezone.make_aware(date, tz)
        else:
            end_date = timezone.now()
            start_date = end_date - timedelta(days=7)

        busqueda = self.annotate(
            saldo=F('depositslip__total_amount')-F('amount')
        ).filter(
            depositslip__serie__icontains=serie,
            depositslip__number__icontains=numero,
            depositslip__sender__full_name__icontains=remitente,
            depositslip__addressee__full_name__icontains=destinatario,
            depositslip__state='2',
            depositslip__destination=sucursal,
            depositslip__created__range=(start_date, end_date)
        )
        return busqueda
    def test1(self):
        """ sequence 4 is missed, so we should have straight line
        interpolation between 3 and 5.
        """
        tvd = [(0, 1, 0, 1),
               (3, 2, 1./4, 2),
               (7, 3, -1./13, 3),
               (20, 3, 1./13, 5),  # missed seq 4
               (24, 1, 0, 9)]  # missed 6,7,8
        data = []
        now = datetime(2001, 1, 1)
        for (t, v, d, s) in tvd:
            data.append((now + timedelta(minutes=1*t), v, d, s))

        result = list(PartSplineReconstruct
                     (src=SipPhenom(src=data,
                                    interval=timedelta(minutes=1)),
                      threshold=0.1))
        for ptup in result:
            self.assertTrue(ptup.dashed is not None)
            intvl = int(my_total_seconds((ptup.dt - now)) /
                        my_total_seconds(timedelta(minutes=1)))
            if intvl >= 7 and intvl <= 20:
                self.assertEquals(ptup.sp, 3)
            if intvl > 20 and intvl <= 25:
                self.assertEquals(ptup.sp, (intvl - 20) * (1.-3.)/(24-20) + 3)


        for i, ptup in enumerate(result):
            intvl = int(my_total_seconds((ptup.dt - now)) /
                        my_total_seconds(timedelta(minutes=1)))
            self.assertEquals(i, intvl)
Example #27
0
    def setUp(self):
        super(GroupEventsOldestTest, self).setUp()
        self.login_as(user=self.user)

        project = self.create_project()
        min_ago = (timezone.now() - timedelta(minutes=1)).isoformat()[:19]
        two_min_ago = (timezone.now() - timedelta(minutes=2)).isoformat()[:19]

        self.event1 = self.store_event(
            data={
                'event_id': 'a' * 32,
                'environment': 'staging',
                'fingerprint': ['group_1'],
                'timestamp': two_min_ago
            },
            project_id=project.id,
        )

        self.event2 = self.store_event(
            data={
                'event_id': 'b' * 32,
                'environment': 'production',
                'fingerprint': ['group_1'],
                'timestamp': min_ago
            },
            project_id=project.id,
        )

        self.group = Group.objects.first()
Example #28
0
    def test_task_due_date(self):
        self.test_add_tasklist()

        today = datetime.datetime.utcnow().replace(tzinfo=utc)

        #  0   Not Due
        not_due_date = today + datetime.timedelta(days=7)
        not_due = TaskModels.Task.objects.create(name="Not Due",
                                                tasklist_id=1,
                                                due_date=not_due_date)
        self.assertEquals(not_due.is_due, 0)

        #  1   Due Today
        due_today_date = today + datetime.timedelta(seconds=10)
        due_today = TaskModels.Task.objects.create(name="Due Today",
                                                  tasklist_id=1,
                                                  due_date=due_today_date)
        self.assertEquals(due_today.is_due, 1)

        # -1   Overdue
        overdue_date = today
        overdue = TaskModels.Task.objects.create(name="Overdue",
                                                tasklist_id=1,
                                                due_date=overdue_date)
        self.assertEquals(overdue.is_due, -1)
Example #29
0
def email_daily_ratings():
    """
    Does email for yesterday's ratings (right after the day has passed).
    Sends an email containing all reviews for that day for certain app.
    """
    if not waffle.switch_is_active('ratings'):
        return

    dt = datetime.datetime.today() - datetime.timedelta(1)
    yesterday = datetime.datetime(dt.year, dt.month, dt.day, 0, 0, 0)
    today = yesterday + datetime.timedelta(1)
    pretty_date = '%04d-%02d-%02d' % (dt.year, dt.month, dt.day)

    yesterday_reviews = Review.objects.filter(created__gte=yesterday,
                                              created__lt=today,
                                              addon__type=amo.ADDON_WEBAPP)

    # For each app in yesterday's set of reviews, gather reviews and email out.
    apps = set(review.addon for review in yesterday_reviews)
    for app in apps:
        # Email all reviews in one email for current app in loop.
        author_emails = app.authors.values_list('email', flat=True)
        subject = 'Firefox Marketplace reviews for %s on %s' % (app.name,
                                                                pretty_date)

        context = {'reviews': (yesterday_reviews.filter(addon=app).
                               order_by('-created')),
                   'base_url': settings.SITE_URL,
                   'pretty_date': pretty_date}

        send_mail_jinja(subject, 'ratings/emails/daily_digest.html',
                        context, recipient_list=author_emails,
                        perm_setting='app_new_review')
Example #30
0
    def _test_file_time_getter_tz_handling_off(self, getter):
        # Django's TZ (and hence the system TZ) is set to Africa/Algiers which
        # is UTC+1 and has no DST change. We can set the Django TZ to something
        # else so that UTC, Django's TIME_ZONE, and the system timezone are all
        # different.
        now_in_algiers = timezone.make_aware(datetime.now())

        with timezone.override(timezone.get_fixed_timezone(-300)):
            # At this point the system TZ is +1 and the Django TZ
            # is -5.
            self.assertFalse(self.storage.exists('test.file.tz.off'))

            f = ContentFile('custom contents')
            f_name = self.storage.save('test.file.tz.off', f)
            self.addCleanup(self.storage.delete, f_name)
            dt = getter(f_name)
            # dt should be naive, in system (+1) TZ
            self.assertTrue(timezone.is_naive(dt))

            # The three timezones are indeed distinct.
            naive_now = datetime.now()
            algiers_offset = now_in_algiers.tzinfo.utcoffset(naive_now)
            django_offset = timezone.get_current_timezone().utcoffset(naive_now)
            utc_offset = timezone.utc.utcoffset(naive_now)
            self.assertGreater(algiers_offset, utc_offset)
            self.assertLess(django_offset, utc_offset)

            # dt and naive_now should be the same effective time.
            self.assertLess(abs(dt - naive_now), timedelta(seconds=2))
            # If we convert dt to an aware object using the Algiers
            # timezone then it should be the same effective time to
            # now_in_algiers.
            _dt = timezone.make_aware(dt, now_in_algiers.tzinfo)
            self.assertLess(abs(_dt - now_in_algiers), timedelta(seconds=2))