Example #1
1
def smsSender(service):
    # try:
    global CC
    global CC1
    primary = "RIVATE STRING"
    id = "PRIVATE STRING"
    event = service.events().get(calendarId=primary, eventId=id).execute()
    CC += 1
    CC1 += 1
    # put in ip in sms
    now = datetime.datetime.now()
    event["start"]["dateTime"] = (
        (now + datetime.timedelta(minutes=40)).strftime("%Y-%m-%d")
        + "T"
        + (now + datetime.timedelta(minutes=40)).strftime("%H:%M:%S")
        + "+01:00"
    )
    event["end"]["dateTime"] = (
        (now + datetime.timedelta(minutes=45)).strftime("%Y-%m-%d")
        + "T"
        + (now + datetime.timedelta(minutes=45)).strftime("%H:%M:%S")
        + "+01:00"
    )
    updated_event = service.events().update(calendarId=primary, eventId=event["id"], body=event).execute()
    CC += 1
    CC1 += 1
    # except:
    #    print "Error occured, sms error."
    #    print sys.exc_info()[0]
    #    print "middle"
    #    print sys.exc_traceback.tb_lineno
    #    print "sms error done"
    return
Example #2
1
def start_end_date_for_period(period, default_start_date=False, default_end_date=False):
    """Return the start and end date for a goal period based on today

    :param str default_start_date: string date in DEFAULT_SERVER_DATE_FORMAT format
    :param str default_end_date: string date in DEFAULT_SERVER_DATE_FORMAT format

    :return: (start_date, end_date), dates in string format, False if the period is
    not defined or unknown"""
    today = date.today()
    if period == "daily":
        start_date = today
        end_date = start_date
    elif period == "weekly":
        delta = timedelta(days=today.weekday())
        start_date = today - delta
        end_date = start_date + timedelta(days=7)
    elif period == "monthly":
        month_range = calendar.monthrange(today.year, today.month)
        start_date = today.replace(day=1)
        end_date = today.replace(day=month_range[1])
    elif period == "yearly":
        start_date = today.replace(month=1, day=1)
        end_date = today.replace(month=12, day=31)
    else:  # period == 'once':
        start_date = default_start_date  # for manual goal, start each time
        end_date = default_end_date

        return (start_date, end_date)

    return (datetime.strftime(start_date, DF), datetime.strftime(end_date, DF))
Example #3
1
 def setUpClass(cls):
     cls.time_delta_s = 1
     cls.number_of_lines = 10000
     cls.line_padding = 42
     cls.start_date = datetime(year=2000, month=1, day=1)
     cls.opened_file = OperationCountingFileWrapper(
         DataGeneratorLogSource(
             start_time=cls.start_date,
             time_delta=timedelta(seconds=cls.time_delta_s),
             number_of_lines=cls.number_of_lines,
             line_padding=cls.line_padding,
             datetime_format="%c",
         )
     )  # yapf: disable
     cls.repetitions = 6
     cls.file_with_repeated_lines = OperationCountingFileWrapper(
         DataGeneratorLogSource(
             start_time=cls.start_date,
             time_delta=timedelta(seconds=cls.time_delta_s),
             number_of_lines=cls.number_of_lines,
             line_padding=cls.line_padding,
             datetime_format="%c",
             repetitions=cls.repetitions,
         )
     )  # yapf: disable
 def test_pending_but_idle(self):
     self.assertJobFlowIs(
         self.mock_emr_job_flows["j-PENDING_BUT_IDLE"],
         from_end_of_hour=timedelta(minutes=5),
         has_pending_steps=True,
         idle_for=timedelta(hours=2, minutes=50),
     )
Example #5
1
def generate_counts():
    """
    Generate dashboard counts.
    """

    counts = mongo_connector(settings.COL_COUNTS)
    samples = mongo_connector(settings.COL_SAMPLES)
    emails = mongo_connector(settings.COL_EMAIL)
    indicators = mongo_connector(settings.COL_INDICATORS)
    domains = mongo_connector(settings.COL_DOMAINS)
    pcaps = mongo_connector(settings.COL_PCAPS)
    today = datetime.datetime.fromordinal(datetime.datetime.now().toordinal())
    start = datetime.datetime.now()
    last_seven = start - datetime.timedelta(7)
    last_thirty = start - datetime.timedelta(30)
    count = {}
    count["Samples"] = samples.find().count()
    count["Emails"] = emails.find().count()
    count["Indicators"] = indicators.find().count()
    count["PCAPs"] = pcaps.find().count()
    count["Domains"] = domains.find().count()
    count["Emails Today"] = emails.find({"source.instances.date": {"$gte": today}}).count()
    count["Emails Last 7"] = emails.find({"source.instances.date": {"$gte": last_seven}}).count()
    count["Emails Last 30"] = emails.find({"source.instances.date": {"$gte": last_thirty}}).count()
    count["Indicators Today"] = indicators.find({"source.instances.date": {"$gte": today}}).count()
    count["Indicators Last 7"] = indicators.find({"source.instances.date": {"$gte": last_seven}}).count()
    count["Indicators Last 30"] = indicators.find({"source.instances.date": {"$gte": last_thirty}}).count()
    counts.update({"name": "counts"}, {"$set": {"counts": count}}, upsert=True)
Example #6
1
    def test_algo_with_rl_violation(self):
        sim_params = factory.create_simulation_parameters(start=list(LEVERAGED_ETFS.keys())[0], num_days=4)

        trade_history = factory.create_trade_history(
            "BZQ", [10.0, 10.0, 11.0, 11.0], [100, 100, 100, 300], timedelta(days=1), sim_params
        )
        self.source = SpecificEquityTrades(event_list=trade_history)

        algo = RestrictedAlgoWithoutCheck(symbol="BZQ", sim_params=sim_params)
        with self.assertRaises(TradingControlViolation) as ctx:
            algo.run(self.source)

        self.check_algo_exception(algo, ctx, 0)

        # repeat with a symbol from a different lookup date

        trade_history = factory.create_trade_history(
            "JFT", [10.0, 10.0, 11.0, 11.0], [100, 100, 100, 300], timedelta(days=1), sim_params
        )
        self.source = SpecificEquityTrades(event_list=trade_history)

        algo = RestrictedAlgoWithoutCheck(symbol="JFT", sim_params=sim_params)
        with self.assertRaises(TradingControlViolation) as ctx:
            algo.run(self.source)

        self.check_algo_exception(algo, ctx, 0)
Example #7
1
    def fire_ready(cls):
        """Fires all direct subscriptions with notifications as well as
        all summary & digest subscriptions with notifications that are ready.
        Clears the mailbox queue.
        """
        now = datetime.utcnow()
        # Queries to find all matching subscription objects
        q_direct = dict(type="direct", queue_empty=False)
        if MAILBOX_QUIESCENT:
            q_direct["last_modified"] = {"$lt": now - MAILBOX_QUIESCENT}
        q_digest = dict(type={"$in": ["digest", "summary"]}, next_scheduled={"$lt": now})

        def find_and_modify_direct_mbox():
            return cls.query.find_and_modify(
                query=q_direct, update={"$set": dict(queue=[], queue_empty=True)}, new=False
            )

        for mbox in take_while_true(find_and_modify_direct_mbox):
            mbox.fire(now)

        for mbox in cls.query.find(q_digest):
            next_scheduled = now
            if mbox.frequency.unit == "day":
                next_scheduled += timedelta(days=mbox.frequency.n)
            elif mbox.frequency.unit == "week":
                next_scheduled += timedelta(days=7 * mbox.frequency.n)
            elif mbox.frequency.unit == "month":
                next_scheduled += timedelta(days=30 * mbox.frequency.n)
            mbox = cls.query.find_and_modify(
                query=dict(_id=mbox._id),
                update={"$set": dict(next_scheduled=next_scheduled, queue=[], queue_empty=True)},
                new=False,
            )
            mbox.fire(now)
    def run(self):
        end_time = dt.utcnow()
        if self.__last_run:
            start_time = self.__last_run + datetime.timedelta(seconds=1)
        else:
            start_time = end_time - datetime.timedelta(seconds=60)

        # Set the start_time for the next run
        self.__last_run = end_time

        logger.info(
            "Running CloudwatchCollector on %s metrics between %s and %s"
            % (len(self.__config["metrics"]), start_time, end_time)
        )

        for metric in self.__config["metrics"]:
            # TODO: Support for dimensions for dynamo table names
            # http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/MonitoringDynamoDB.html
            namespace = metric["namespace"]
            metric_name = metric["metric_name"]

            # Collect the remaining metric dimensions besides metric_name and namespace
            dimensions = {}
            for key in metric:
                if not key in ("metric_name", "namespace"):
                    dimensions[inflection.camelize(key)] = metric[key]

            # If metric_name is a list, process each seperately with the same values for namespace and dimensions
            if isinstance(metric_name, list):
                [self.process_metrics(name, namespace, dimensions, start_time, end_time) for name in metric_name]
            else:
                self.process_metrics(metric_name, namespace, dimensions, start_time, end_time)
Example #9
0
    def test_is_item_still_editable(self):
        item = DictLikeClass()

        h.CFG.DATA_UPDATE_ALLOWED_DURATION = 0
        item.created = datetime.datetime.now() - datetime.timedelta(0, 10)

        item.type = DictLikeClass({"id": 5})
        eq_(False, h.is_item_still_editable(item))

        item.type.id = "comment"
        eq_(False, h.is_item_still_editable(item))

        h.CFG.DATA_UPDATE_ALLOWED_DURATION = -1
        item.type.id = "comment"
        item.created = datetime.datetime.now() - datetime.timedelta(0, 10)
        eq_(True, h.is_item_still_editable(item))

        h.CFG.DATA_UPDATE_ALLOWED_DURATION = 12
        item.created = datetime.datetime.now() - datetime.timedelta(0, 10)
        eq_(
            True, h.is_item_still_editable(item), "created: {}, now: {}".format(item.created, datetime.datetime.now())
        )  # This test will pass only if the test duration is less than 120s !!!

        h.CFG.DATA_UPDATE_ALLOWED_DURATION = 8
        item.created = datetime.datetime.now() - datetime.timedelta(0, 10)
        eq_(False, h.is_item_still_editable(item))
Example #10
0
def KalendarCreate(first_day_class, days_in_cycle):
    Kalendar.objects.all().delete()
    day = date(first_day_class.year, 8, 1)
    last_day = date(first_day_class.year + 1, 6, 30)

    while day < first_day_class:
        holiday = Day_No.objects.get(day_name="H")
        if day.weekday() < 5:
            k = Kalendar(date=day, day_no=holiday)
            k.save()
        day = day + timedelta(days=1)

    i = 1
    while day <= last_day:
        if day.weekday() < 5:
            k = Kalendar(date=day, day_no=Day_No.objects.get(day_name=str(i)))
            k.save()
            if i == days_in_cycle:
                i = 1
            else:
                i = i + 1
        day = day + timedelta(days=1)

    while day <= date(first_day_class.year + 1, 7, 31):
        if day.weekday() < 5:
            k = Kalendar(date=day, day_no=Day_No.objects.get(day_name="H"))
            k.save()
        day = day + timedelta(days=1)
Example #11
0
    def ComputeDates(self, date_str, gmt_date):
        persian_date = None
        if gmt_date == None:
            patterns = [{"format": "%Y/%m/%d - %H:%M:%S", "diff": Setting.persian_timezone_seconds}]
            for pt in patterns:
                try:
                    tt = jdatetime.datetime.strptime(date_str, pt["format"])

                    persian_date = tt
                    gmt_date = persian_date.togregorian()

                    gmt_date -= datetime.timedelta(0, pt["diff"])

                    break
                except Exception as ex:
                    Setting.error_log.WriteLog("date convertion " + ex.__str__())
                    pass
        else:
            gmt_date = datetime.datetime(
                gmt_date.tm_year, gmt_date.tm_mon, gmt_date.tm_mday, gmt_date.tm_hour, gmt_date.tm_min, gmt_date.tm_sec
            )

        tmp_date = gmt_date + datetime.timedelta(0, Setting.persian_timezone_seconds)
        persian_date = jdatetime.datetime.fromgregorian(datetime=tmp_date)
        return gmt_date, persian_date
Example #12
0
def add_data_for_gui_frontends(tender_data):
    now = get_now()
    # tender_data.data.enquiryPeriod['startDate'] = (now + timedelta(minutes=2)).isoformat()
    tender_data.data.enquiryPeriod["endDate"] = (now + timedelta(minutes=6)).isoformat()
    tender_data.data.tenderPeriod["startDate"] = (now + timedelta(minutes=7)).isoformat()
    tender_data.data.tenderPeriod["endDate"] = (now + timedelta(minutes=11)).isoformat()
    return tender_data
Example #13
0
    def add_footer(self):
        buffer = self.log_buffer
        self.footer_mark = buffer.create_mark("footer", buffer.get_end_iter(), True)
        window = self.daily_window(self.looking_at_date)
        total_work, total_slacking = window.totals()
        weekly_window = self.weekly_window(self.looking_at_date)
        week_total_work, week_total_slacking = weekly_window.totals()
        work_days_this_week = weekly_window.count_days()

        self.w("\n")
        self.w("Total work done: ")
        self.w(format_duration(total_work), "duration")
        self.w(" (")
        self.w(format_duration(week_total_work), "duration")
        self.w(" this week")
        if work_days_this_week:
            per_diem = week_total_work / work_days_this_week
            self.w(", ")
            self.w(format_duration(per_diem), "duration")
            self.w(" per day")
        self.w(")\n")
        self.w("Total slacking: ")
        self.w(format_duration(total_slacking), "duration")
        self.w(" (")
        self.w(format_duration(week_total_slacking), "duration")
        self.w(" this week")
        if work_days_this_week:
            per_diem = week_total_slacking / work_days_this_week
            self.w(", ")
            self.w(format_duration(per_diem), "duration")
            self.w(" per day")
        self.w(")\n")

        if self.looking_at_date is None:
            time_left = self.time_left_at_work(total_work)
        else:
            time_left = None
        if time_left is not None:
            time_to_leave = datetime.datetime.now() + time_left
            if time_left < datetime.timedelta(0):
                time_left = datetime.timedelta(0)
            self.w("Time left at work: ")
            self.w(format_duration(time_left), "duration")
            self.w(" (till ")
            self.w(time_to_leave.strftime("%H:%M"), "time")
            self.w(")")

        if self.settings.show_office_hours and self.looking_at_date is None:
            self.w("\nAt office today: ")
            hours = datetime.timedelta(hours=self.settings.hours)
            total = total_slacking + total_work
            self.w("%s " % format_duration(total), "duration")
            self.w("(")
            if total > hours:
                self.w(format_duration(total - hours), "duration")
                self.w(" overtime")
            else:
                self.w(format_duration(hours - total), "duration")
                self.w(" left")
            self.w(")")
Example #14
0
def deliver_hotness():
    """
    Calculate hotness of all add-ons.

    a = avg(users this week)
    b = avg(users three weeks before this week)
    hotness = (a-b) / b if a > 1000 and b > 1 else 0
    """
    frozen = set(f.id for f in FrozenAddon.objects.all())
    all_ids = list((Addon.objects.exclude(type=amo.ADDON_PERSONA).values_list("id", flat=True)))
    now = datetime.now()
    one_week = now - timedelta(days=7)
    four_weeks = now - timedelta(days=28)
    for ids in chunked(all_ids, 300):
        addons = Addon.objects.no_cache().filter(id__in=ids).no_transforms()
        ids = [a.id for a in addons if a.id not in frozen]
        qs = UpdateCount.objects.filter(addon__in=ids).values_list("addon").annotate(Avg("count"))
        thisweek = dict(qs.filter(date__gte=one_week))
        threeweek = dict(qs.filter(date__range=(four_weeks, one_week)))
        for addon in addons:
            this, three = thisweek.get(addon.id, 0), threeweek.get(addon.id, 0)
            if this > 1000 and three > 1:
                addon.update(hotness=(this - three) / float(three))
            else:
                addon.update(hotness=0)
        # Let the database catch its breath.
        time.sleep(10)
Example #15
0
def estimate_sub_second_time(files, interval):
    """
    Estimate the capture time of a sequence with sub-second precision

    EXIF times are only given up to a second of precission. This function
    uses the given interval between shots to Estimate the time inside that
    second that each picture was taken.
    """
    if interval <= 0.0:
        return [exif_time(f) for f in files]

    onesecond = datetime.timedelta(seconds=1.0)
    T = datetime.timedelta(seconds=interval)
    for i, f in enumerate(files):
        m = exif_time(f)
        if i == 0:
            smin = m
            smax = m + onesecond
        else:
            m0 = m - T * i
            smin = max(smin, m0)
            smax = min(smax, m0 + onesecond)

    if smin > smax:
        print("Interval not compatible with EXIF times")
        return None
    else:
        s = smin + (smax - smin) / 2
        return [s + T * i for i in range(len(files))]
Example #16
0
    def test_refresh_credentials(self):
        now = datetime.now()
        first_expiration = (now + timedelta(seconds=10)).strftime("%Y-%m-%dT%H:%M:%SZ")
        credentials = {
            u"AccessKeyId": u"first_access_key",
            u"Code": u"Success",
            u"Expiration": first_expiration,
            u"LastUpdated": u"2012-08-31T21:43:40Z",
            u"SecretAccessKey": u"first_secret_key",
            u"Token": u"first_token",
            u"Type": u"AWS-HMAC",
        }
        instance_config = {"iam": {"security-credentials": {"allowall": credentials}}}
        self.get_instance_metadata.return_value = instance_config
        p = provider.Provider("aws")
        self.assertEqual(p.access_key, "first_access_key")
        self.assertEqual(p.secret_key, "first_secret_key")
        self.assertEqual(p.security_token, "first_token")
        self.assertIsNotNone(p._credential_expiry_time)

        # Now set the expiration to something in the past.
        expired = now - timedelta(seconds=20)
        p._credential_expiry_time = expired
        credentials["AccessKeyId"] = "second_access_key"
        credentials["SecretAccessKey"] = "second_secret_key"
        credentials["Token"] = "second_token"
        self.get_instance_metadata.return_value = instance_config

        # Now upon attribute access, the credentials should be updated.
        self.assertEqual(p.access_key, "second_access_key")
        self.assertEqual(p.secret_key, "second_secret_key")
        self.assertEqual(p.security_token, "second_token")
Example #17
0
    def test_contest_get_game_for_date(self):
        """
            Tests if a game is retrieved for a given date and that proper
            exception is raised if game not found
        """
        self.initialize()
        contest_helper = ContestHelper()

        # no game yesterday
        the_date = datetime.today() - timedelta(1)
        try:
            contest_helper.get_game_for_date(self.contest, the_date)
            raise Exception("No NoGameException raised!")
        except NoGameException:
            the_game = None
        self.assertEquals(the_game, None)

        # game1 today
        the_date = datetime.now()
        the_game = contest_helper.get_game_for_date(self.contest, the_date)
        self.assertEquals(the_game, self.game1)

        # game2 tomorrow
        the_date = datetime.today() + timedelta(1)
        the_game = contest_helper.get_game_for_date(self.contest, the_date)
        self.assertEquals(the_game, self.game2)
Example #18
0
 def get_recent_dates(self):
     today = datetime.datetime.utcnow()
     # today -= datetime.timedelta(days=400) #debug
     # the upper boundary is excluded in the search, add one day
     end_date = today + datetime.timedelta(days=1)
     begin_date = end_date - datetime.timedelta(days=32)
     return begin_date, end_date
Example #19
0
    def post(self):
        config = ndb.Key(Settings, "config").get()
        if not config:
            config = Settings(id="config")

        config.secret_key = self.request.get("secret_key")

        early_due_date = self.request.get("early_due_date")
        try:
            early_due_date = datetime.strptime(early_due_date, "%B %d, %Y - %I:%M %p")
            early_due_date += timedelta(hours=5)  # Eastern TZ offset
            config.early_due_date = early_due_date
        except:
            config.early_due_date = "Please put in a valid date (ex. February 1, 2015 - 11:59 PM)"
        due_date = self.request.get("due_date")
        try:
            due_date = datetime.strptime(due_date, "%B %d, %Y - %I:%M %p")
            due_date += timedelta(hours=5)  # Eastern TZ offset
            config.due_date = due_date
        except:
            config.due_date = "Please put in a valid date (ex. February 14, 2015 - 11:59 PM)"

        config.sendgrid_username = self.request.get("sendgrid_username")
        config.sendgrid_password = self.request.get("sendgrid_password")

        config.recaptcha_site_key = self.request.get("recaptcha_site_key")
        config.recaptcha_secret = self.request.get("recaptcha_secret")

        config.put()
        self._serve_page()
Example #20
0
    def piecewise_statistics(self, window_size, statistics=[("generic", "mean")], time_period=False, name=""):

        if time_period == False:
            start = self.timeframe[0] - timedelta(
                hours=self.timeframe[0].hour,
                minutes=self.timeframe[0].minute,
                seconds=self.timeframe[0].second,
                microseconds=self.timeframe[0].microsecond,
            )
            end = self.timeframe[1] + timedelta(
                hours=23 - self.timeframe[1].hour,
                minutes=59 - self.timeframe[1].minute,
                seconds=59 - self.timeframe[1].second,
                microseconds=999999 - self.timeframe[1].microsecond,
            )
        else:
            start = time_period[0]
            end = time_period[1]

        # print("Piecewise statistics: {}".format(self.name))

        windows = []

        start_dts = start
        end_dts = start + window_size

        while start_dts < end:

            window = Bout.Bout(start_dts, end_dts)
            windows.append(window)

            start_dts = start_dts + window_size
            end_dts = end_dts + window_size

        return self.build_statistics_channels(windows, statistics, name=name)
Example #21
0
 def __init__(self, doneEvent=None):
     FSM.__init__(self, "PartyPlannerFSM")
     DirectFrame.__init__(self)
     self.doneEvent = doneEvent
     self.stateArray = [
         "Off",
         "Welcome",
         "PartyEditor",
         #'Guests',  jjkoletar: this should mean that it skips over the guests state
         "Date",
         "Time",
         "Invitation",
         "Farewell",
     ]
     self.partyTime = base.cr.toontownTimeManager.getCurServerDateTime()
     self.partyNowTime = base.cr.toontownTimeManager.getCurServerDateTime()
     minutesToNextFifteen = 15 - self.partyTime.minute % 15
     self.cleanPartyTime = self.partyTime + timedelta(minutes=minutesToNextFifteen, seconds=-self.partyTime.second)
     self.partyTime = self.cleanPartyTime
     self.guests = []
     self.isPrivate = False
     self.selectedCalendarGuiDay = None
     self.gui = loader.loadModel("phase_4/models/parties/partyPlannerGUI")
     self.partyDuration = timedelta(hours=PartyGlobals.DefaultPartyDuration)
     self.timeTypeToMaxValue = {"hour": 23, "minute": 59}
     self.timeTypeToChangeAmount = {"hour": (1, -1), "minute": (15, -15), "ampm": (1, -1)}
     self.partyInfo = None
     self.asapMinuteRounding = config.GetInt(
         "party-asap-minute-rounding", PartyGlobals.PartyPlannerAsapMinuteRounding
     )
     self.load()
     self.request("Welcome")
     return
Example #22
0
def fix_plus_n(epg, channels):
    import re
    from copy import copy
    from datetime import timedelta

    epg_chns = epg.get_channels()
    exp = re.compile("(\+\d+)$")
    fix = []

    # Find potential candidates for a fix
    for c in channels:
        if c not in epg_chns:
            r = exp.search(c.uri)
            if r:
                os = int(r.group(1))
                uri = c.uri.replace(r.group(1), "")
                for c1 in channels:
                    if uri == c1.uri:
                        fix.append((c, os * 60, c1))
                        break

    # Fix the channels
    for (plus, offset, base) in fix:
        sched = epg.get_schedule(base)
        if not sched:
            continue
        log.info("pyepg - fix missing plusN channel %s" % plus.title)
        for e in sched:
            n = copy(e)
            n.channel = plus
            n.start = n.start + timedelta(minutes=offset)
            n.stop = n.stop + timedelta(minutes=offset)
            epg.add_broadcast(n)
 def __init__(self, tzoffsetfrom, tzoffsetto, isdst, tzname=None, rrule=None):
     self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom)
     self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto)
     self.tzoffsetdiff = self.tzoffsetto - self.tzoffsetfrom
     self.isdst = isdst
     self.tzname = tzname
     self.rrule = rrule
    def test_can_enter_expiry_date(self):
        browser = Browser(self.layer["app"])
        portal = self.layer["portal"]
        setRoles(portal, TEST_USER_ID, ("Member", "Manager"))
        document = createObject(
            portal, "Document", "effective_date_transition_doc", delete_first=True, title="Workflow note"
        )
        transaction.commit()

        browser_login(portal, browser)
        browser.open(document.absolute_url())
        browser.getLink("Manage page").click()
        browser.getLink("Public draft").click()
        workflow_actions = browser.getControl(name="form.widgets.workflow_action:list")
        workflow_actions.getControl(value="publish").click()
        # We set up a comment this time

        next_year = datetime.now() + timedelta(365)
        next_year = next_year - timedelta(seconds=next_year.second, microseconds=next_year.microsecond)
        browser.getControl(name="form.widgets.expiration_date-day").value = str(next_year.day)
        browser.getControl(name="form.widgets.expiration_date-month").value = [str(next_year.month)]
        browser.getControl(name="form.widgets.expiration_date-year").value = str(next_year.year)
        browser.getControl(name="form.widgets.expiration_date-hour").value = str(next_year.hour)
        browser.getControl(name="form.widgets.expiration_date-min").value = str(next_year.minute)
        browser.getControl("Save").click()

        # and it shows up in the workflow history
        self.assertEqual("publish", document.workflow_history["plone_workflow"][-1]["action"])
        self.assertEqual("published", portal.portal_workflow.getInfoFor(document, "review_state"))
        self.assertEqual(DateTime(next_year), document.getRawExpirationDate())

        portal.manage_delObjects(["effective_date_transition_doc"])
Example #25
0
 def recent_activity(self, min_count=2):
     comments = self.comments.filter(deleted=False)
     today = datetime.date.today()
     day = today.day
     month = today.month
     year = today.year
     # get today's commments count
     today_comments_count = comments.filter(
         created_on__day=day, created_on__month=month, created_on__year=year
     ).count()
     if today_comments_count >= min_count:
         return today_comments_count, _("today")
     # get this week comments count
     week = today.isocalendar()[1]
     first_day = datetime.date(year, 1, 1)
     delta_days = first_day.isoweekday() - 1
     delta_weeks = week
     if year == first_day.isocalendar()[0]:
         delta_weeks -= 1
     week_start_delta = datetime.timedelta(days=-delta_days, weeks=delta_weeks)
     week_start = first_day + week_start_delta
     week_end_delta = datetime.timedelta(days=7 - delta_days, weeks=delta_weeks)
     week_end = first_day + week_end_delta
     this_week_comments_count = comments.filter(created_on__gte=week_start, created_on__lt=week_end).count()
     if this_week_comments_count >= min_count:
         return this_week_comments_count, _("this week")
     # get this month comments count
     this_month_comments_count = comments.filter(created_on__month=month, created_on__year=year).count()
     return this_month_comments_count, _("this month")
    def test_can_enter_expiration_date_without_transaction(self):
        browser = Browser(self.layer["app"])
        portal = self.layer["portal"]
        setRoles(portal, TEST_USER_ID, ("Member", "Manager"))
        document = createObject(
            portal, "Document", "expiration_date_without_transition_doc", delete_first=True, title="Workflow note"
        )
        transaction.commit()

        browser_login(portal, browser)
        browser.open(document.absolute_url())
        browser.getLink("Manage page").click()
        browser.getLink("Public draft").click()

        # Don't select any workflow action, but set date
        next_year = datetime.now() + timedelta(365)
        next_year = next_year - timedelta(seconds=next_year.second, microseconds=next_year.microsecond)
        browser.getControl(name="form.widgets.expiration_date-day").value = str(next_year.day)
        browser.getControl(name="form.widgets.expiration_date-month").value = [str(next_year.month)]
        browser.getControl(name="form.widgets.expiration_date-year").value = str(next_year.year)
        browser.getControl(name="form.widgets.expiration_date-hour").value = str(next_year.hour)
        browser.getControl(name="form.widgets.expiration_date-min").value = str(next_year.minute)
        browser.getControl("Save").click()

        # Still draft, but expiration date set
        self.assertEqual("visible", portal.portal_workflow.getInfoFor(document, "review_state"))
        self.assertEqual(DateTime(next_year), document.getRawExpirationDate())
Example #27
0
    def _get_next_report_date(self, cr, uid, ids, field_name, arg, context=None):
        """Return the next report date based on the last report date and report
        period.

        :return: a string in DEFAULT_SERVER_DATE_FORMAT representing the date"""
        res = {}
        for challenge in self.browse(cr, uid, ids, context=context):
            last = datetime.strptime(challenge.last_report_date, DF).date()
            if challenge.report_message_frequency == "daily":
                next = last + timedelta(days=1)
                res[challenge.id] = next.strftime(DF)
            elif challenge.report_message_frequency == "weekly":
                next = last + timedelta(days=7)
                res[challenge.id] = next.strftime(DF)
            elif challenge.report_message_frequency == "monthly":
                month_range = calendar.monthrange(last.year, last.month)
                next = last.replace(day=month_range[1]) + timedelta(days=1)
                res[challenge.id] = next.strftime(DF)
            elif challenge.report_message_frequency == "yearly":
                res[challenge.id] = last.replace(year=last.year + 1).strftime(DF)
            # frequency == 'once', reported when closed only
            else:
                res[challenge.id] = False

        return res
Example #28
0
def test_realert(ea):
    hits = ["2014-09-26T12:35:%sZ" % (x) for x in range(60)]
    matches = [{"@timestamp": x} for x in hits]
    ea.current_es.search.return_value = hits
    with mock.patch("elastalert.elastalert.Elasticsearch"):
        ea.rules[0]["realert"] = datetime.timedelta(seconds=50)
        ea.rules[0]["type"].matches = matches
        ea.run_rule(ea.rules[0], END, START)
        assert ea.rules[0]["alert"][0].alert.call_count == 1

    # Doesn't alert again
    matches = [{"@timestamp": x} for x in hits]
    with mock.patch("elastalert.elastalert.Elasticsearch"):
        ea.run_rule(ea.rules[0], END, START)
        ea.rules[0]["type"].matches = matches
        assert ea.rules[0]["alert"][0].alert.call_count == 1

    # mock ts_now() to past the realert time
    matches = [{"@timestamp": hits[0]}]
    with mock.patch("elastalert.elastalert.ts_now") as mock_ts:
        with mock.patch("elastalert.elastalert.Elasticsearch"):
            # mock_ts is converted twice to add tzinfo
            mock_ts.return_value = ts_to_dt(dt_to_ts(datetime.datetime.utcnow() + datetime.timedelta(minutes=10)))
            ea.rules[0]["type"].matches = matches
            ea.run_rule(ea.rules[0], END, START)
            assert ea.rules[0]["alert"][0].alert.call_count == 2
Example #29
0
def test_when_delta():
    # Test that the event length is calculated correctly
    ev = Event(namespace_id=0)
    # Time: minutes is 0 if start/end at same time
    ev.start = arrow.get(2015, 01, 01, 10, 00, 00)
    ev.end = arrow.get(2015, 01, 01, 10, 00, 00)
    when = ev.when
    assert isinstance(when, Time)
    assert ev.length == timedelta(minutes=0)

    # TimeSpan
    ev.start = arrow.get(2015, 01, 01, 10, 00, 00)
    ev.end = arrow.get(2015, 01, 01, 10, 30, 00)
    when = ev.when
    assert isinstance(when, TimeSpan)
    assert ev.length == timedelta(minutes=30)

    # Date: notice days is 0 if starts/ends on same day
    ev.all_day = True
    ev.start = arrow.get(2015, 01, 01, 00, 00, 00)
    ev.end = arrow.get(2015, 01, 01, 00, 00, 00)
    when = ev.when
    assert isinstance(when, Date)
    assert ev.length == timedelta(days=0)

    # DateSpan
    ev.all_day = True
    ev.start = arrow.get(2015, 01, 01, 10, 00, 00)
    ev.end = arrow.get(2015, 01, 02, 10, 00, 00)
    when = ev.when
    assert isinstance(when, DateSpan)
    assert ev.length == timedelta(days=1)
Example #30
0
def bootstrap(request):
    # Don't create dummy playlist tracks if playlist tracks already exist!
    pl_tracks = PlaylistTrack.all().fetch(1)
    if len(pl_tracks) > 0:
        return HttpResponse(status=404)

    playlist = ChirpBroadcast()

    minutes = 0
    tracks = Track.all().fetch(100)
    for track in tracks:
        pl_track = PlaylistTrack(
            playlist=playlist,
            selector=request.user,
            established=datetime.now() - timedelta(minutes=minutes),
            artist=track.album.album_artist,
            album=track.album,
            track=track,
        )
        pl_track.put()
        if minutes > 0 and minutes % 25 == 0:
            pl_break = PlaylistBreak(playlist=playlist, established=datetime.now() - timedelta(minutes=minutes - 1))
            pl_break.put()
        minutes += 5

    return HttpResponseRedirect("/playlists/")