예제 #1
0
def main():  # no test coverage
    log.info("GargBot 3000 scheduler starter")
    try:
        while True:
            schedule.clear()

            hour = local_hour_at_utc(2)
            log.info(f"Scheduling database.backup at {hour}")
            schedule.every().day.at(hour).do(database.backup)

            hour = local_hour_at_utc(7)
            log.info(f"Scheduling send_congrats at {hour}")
            schedule.every().day.at(hour).do(greetings.send_congrats)

            hour = local_hour_at_utc(10)
            log.info(f"Scheduling sync reminder at {hour}")
            schedule.every().day.at(hour).do(health.run_sync_reminding)

            hour = local_hour_at_utc(11)
            delete_time = f"{hour}:55"
            log.info(f"Scheduling sync reminder deletion at {delete_time}")
            schedule.every().day.at(delete_time).do(health.run_sync_deleting)

            hour = local_hour_at_utc(12)
            log.info(f"Scheduling update_journey at {hour}")
            schedule.every().day.at(hour).do(journey.run_updates)

            now = pendulum.now(config.tz)
            tomorrow = pendulum.tomorrow(config.tz).at(now.hour, now.minute, now.second)
            seconds_until_this_time_tomorrow = (tomorrow - now).seconds
            for _ in range(seconds_until_this_time_tomorrow):
                schedule.run_pending()
                time.sleep(1)
    except KeyboardInterrupt:
        sys.exit()
예제 #2
0
파일: zup.py 프로젝트: johannfr/zup
 def _schedule_next_run(self):
     next_run = Configuration.get("next_run")
     if len(next_run) == 0 or pendulum.parse(next_run) < pendulum.now():
         LOG.debug("Schedule run in the future")
         if Configuration.get("schedule_type",
                              DEFAULT_SCHEDULE_TYPE) == "schedule":
             scheduled_run = None
             for time_value in Configuration.get("schedule_list",
                                                 DEFAULT_SCHEDULE_LIST):
                 hours, minutes = time_value.split(":")
                 pendulum_time = pendulum.today().add(hours=int(hours),
                                                      minutes=int(minutes))
                 if pendulum_time > pendulum.now():
                     scheduled_run = pendulum_time
                     break
             if scheduled_run is None:
                 hours, minutes = Configuration.get(
                     "schedule_list", DEFAULT_SCHEDULE_LIST)[0].split(":")
                 scheduled_run = pendulum.tomorrow().add(
                     hours=int(hours), minutes=int(minutes))
         else:
             interval_hours = Configuration.get("interval_hours",
                                                DEFAULT_INTERVAL_HOURS)
             interval_minutes = Configuration.get("interval_minutes",
                                                  DEFAULT_INTERVAL_MINUTES)
             scheduled_run = pendulum.now().add(hours=interval_hours,
                                                minutes=interval_minutes)
         LOG.debug("Next run scheduled at: %s", scheduled_run)
         Configuration.set("next_run", scheduled_run.for_json())
     else:
         LOG.debug("We were probably executed manually. Won't schedule.")
예제 #3
0
def GetScheduleDate():
    if Config.REDIRECT_DATE:
        return Config.REDIRECT_DATE
    hour = pendulum.now(TZ).hour
    minute = pendulum.now(TZ).minute
    weekday = pendulum.now(TZ).weekday()
    if weekday == 6:
        return pendulum.tomorrow(TZ).__format__(FORMAT)
    elif weekday < 5:
        if (hour >= 10) and ((hour <= 23) and (minute <= 59)):
            return pendulum.tomorrow(TZ).__format__(FORMAT)
        return pendulum.today(TZ).__format__(FORMAT)
    else:
        if (hour >= 10) and ((hour <= 23) and (minute <= 59)):
            return pendulum.now().add(days=2).__format__(FORMAT)
        return pendulum.today(TZ).__format__(FORMAT)
예제 #4
0
파일: streams.py 프로젝트: Mu-L/airbyte
    def stream_slices(self,
                      stream_state: Mapping[str, Any] = None,
                      **kwargs) -> Iterable[Optional[Mapping[str, any]]]:
        if not stream_state:
            stream_state = {}

        from_date = pendulum.parse(
            stream_state.get(self.cursor_field, self.start_date))
        end_date = max(from_date, pendulum.tomorrow("UTC"))

        date_diff = end_date - from_date
        if date_diff.years > 0:
            interval = pendulum.duration(months=1)
        elif date_diff.months > 0:
            interval = pendulum.duration(weeks=1)
        elif date_diff.weeks > 0:
            interval = pendulum.duration(days=1)
        else:
            interval = pendulum.duration(hours=1)

        while True:
            to_date = min(from_date + interval, end_date)
            yield {
                "from": from_date.isoformat(),
                "to": to_date.add(seconds=1).isoformat()
            }
            from_date = to_date
            if from_date >= end_date:
                break
예제 #5
0
def sign_in(mocker, user):
    secret = os.environ.get('JWT_SECRET', 'secret')
    claims = dict(sub=user.id, iat=pendulum.now(), exp=pendulum.tomorrow())
    mocker.patch.object(jwt, 'decode', return_value=claims)

    access_token = jwt.encode(claims, secret).decode("utf-8")
    return f'JWT {access_token}'
예제 #6
0
    def _parse_optinput(self, ctx, optional_input):
        date = pendulum.now()
        append_team = ""
        timezone = ""
        args_dev = self._parseargs(optional_input)
        if args_dev.get('--tz'):
            # grab the user-defined timezone
            timezone = args_dev.get('--tz')
            # see if it's a short-hand timezone first
            timezone = self.short_tzs.get(timezone.lower()) or timezone
            # now check if it's valid
            try:
                _ = pendulum.timezone(timezone)
            except Exception:
                return
        if args_dev.get('extra_text', '').lower() == "yesterday":
            date = pendulum.yesterday().in_tz(timezone
                                              or self.default_other_tz)
        elif args_dev.get('extra_text', '').lower() == "tomorrow":
            date = pendulum.tomorrow().in_tz(timezone or self.default_other_tz)
        else:
            try:
                date = pendulum.parse(args_dev.get('extra_text'), strict=False)
            except Exception as err:
                LOGGER.error(f"[6] {err}")
                append_team = args_dev.get('extra_text').lower()

        return date, append_team, timezone, args_dev
예제 #7
0
def Day_Ahead_Prices():

    from entsoe import EntsoePandasClient
    import pandas as pd
    import os
    import pendulum


    today=      pendulum.today().strftime('%Y-%m-%d')
    tomorrow =  pendulum.tomorrow().add(days=1).strftime('%Y-%m-%d')


    client = EntsoePandasClient(api_key='bd39354a-6404-40d1-b289-90a2d8135862')

    start = pd.Timestamp(today, tz='Europe/Oslo')
    end = pd.Timestamp(tomorrow, tz='Europe/Oslo')
    country_code = 'NO-3'  #Trondheim


    ts = client.query_day_ahead_prices(country_code, start=start, end=end)

    pris=[]

    for x in range(0, 48):
        pris.append(ts[x])
        
    return pris
예제 #8
0
def get_application_historical_metrics():
    metrics = defaultdict(list)
    period = pendulum.period(pendulum.Pendulum(2016, 11, 1), pendulum.tomorrow())
    for dt in period.range('days'):
        date = dt.to_date_string()
        timestamp = dt.to_iso8601_string()
        query = '''
  WITH app_metrics AS (SELECT type, count(*) total_count
                FROM
                  (SELECT DISTINCT ON (object_id) date_trunc('day', created_at) AS day, type, object_id FROM audit_event
                  WHERE ((object_type = 'Application'
                          AND object_id NOT IN (SELECT id FROM application WHERE status = 'deleted') )
                          OR object_type = 'SupplierDomain')
                  AND created_at < :date
                  ORDER BY object_id, created_at DESC ) a
                GROUP BY type)
    SELECT * FROM app_metrics
    UNION SELECT 'started_application', sum(total_count) FROM app_metrics
      WHERE type IN ('submit_application','approve_application','create_application','revert_application')
    UNION SELECT 'completed_application', sum(total_count) FROM app_metrics
      WHERE type IN ('submit_application','approve_application','revert_application')
                '''
        for row in db.session.execute(query, {'date': date}).fetchall():
            metrics[row['type'] + "_count"].append({"value": row["total_count"], "ts": timestamp})

    return jsonify(metrics)
예제 #9
0
 def test_first_created_field(helpers):
     datetimeValue = pendulum.tomorrow()
     theRecord = pytest.app.records.create(
         **{
             "Required Date & Time": pendulum.now(),
             "First Created": datetimeValue
         })
     assert theRecord["First Created"] != datetimeValue
예제 #10
0
 def test_first_created_field_on_save(helpers):
     datetimeValue = pendulum.tomorrow()
     theRecord = pytest.app.records.create(
         **{"Required Date & Time": pendulum.now()})
     theOriginalTimeCreated = theRecord["First Created"]
     theRecord["First Created"] = datetimeValue
     theRecord.save()
     assert theRecord["First Created"] == theOriginalTimeCreated
예제 #11
0
def test_backoff_time(patch_base_class, http_status, response_text,
                      expected_backoff_time):
    response_mock = MagicMock()
    response_mock.status_code = http_status
    response_mock.text = response_text
    stream = AppsflyerStream()
    if expected_backoff_time == "Midnight":
        expected_backoff_time = (pendulum.tomorrow("UTC") -
                                 pendulum.now("UTC")).seconds
    assert stream.backoff_time(response_mock) == expected_backoff_time
예제 #12
0
def get_filepattern_fillins():
    """
    This will build all of the fill-ins that can be used when creating file patterns.
    I.e. these are the possible variables that can be used inside braces when specifying file names.

    If you'd like to add more fill-ins, please add entries to the fillins dictionary below.
    For example, if you wanted to add the date of the current week's Monday, you could do:

    fillins['monday'] = str(pendulum.today().last(pendulum.MONDAY))
    
    Returns
    -------
    fillins: dict
        A dict containing the possible variables that can be used in a file pattern
    """
    fillins = {}

    for prefix in ['', 'tomorrow', 'yesterday', 'weekending']:
        if prefix == '':
            base = pendulum.today()
        if prefix == 'tomorrow':
            base = pendulum.tomorrow()
        elif prefix == 'yesterday':
            base = pendulum.yesterday()
        elif prefix == 'weekending':
            base = pendulum.today().next(pendulum.SATURDAY)

        day = str(base.day)
        if len(day) == 1:
            day = '0' + day
        if prefix == '':
            fillins['day'] = day
        else:
            fillins[prefix] = day

        if prefix == '':
            prefix = 'today'
        fillins[prefix + 'nameupper'] = base.strftime('%A')
        fillins[prefix + 'namelower'] = base.strftime('%A').lower()
        fillins[prefix + 'nametruncupper'] = base.strftime('%a')
        fillins[prefix + 'nametrunclower'] = base.strftime('%a').lower()
        if prefix == 'today':
            prefix = ''

        month = str(base.month)
        if len(month) == 1:
            month = '0' + month
        fillins[prefix + 'month'] = str(month)

        year = str(base.year)
        fillins[prefix + 'year'] = year
        fillins[prefix + 'truncyear'] = year[-2:]

    return fillins
예제 #13
0
파일: yc.py 프로젝트: paul-wolf/yewcal
def today(ctx):
    """Create a calendar event."""
    events = read_events()
    events = list(
        filter(
            lambda e: e.dt.replace(tzinfo=pytz.timezone(e.timezone)) >=
            pendulum.today() and e.dt.replace(tzinfo=pytz.timezone(e.timezone)
                                              ) < pendulum.tomorrow(), events))
    for e in events:
        # dt = e.dt.replace(tzinfo=pytz.timezone(e.timezone))
        print(arrow.get(e.dt).humanize(), e.summary)
 def list(self):
     utc = pendulum.timezone('UTC')
     from_dttm = pendulum.today(tz=utc)
     to_dttm = pendulum.tomorrow(tz=utc)
     logger.info(
         f'Getting DAG schedules - from: {from_dttm} and to: {to_dttm}')
     dag_schedules = get_dag_schedules(from_dttm, to_dttm)
     return self.render_template('dag_schedule_graph/index.html',
                                 from_timestamp=timestamp_ms(from_dttm),
                                 to_timestamp=timestamp_ms(to_dttm),
                                 dag_schedules=json.dumps(dag_schedules))
예제 #15
0
    async def reset(self, ctx):
        """Countdown till next reset."""
        now = pendulum.now(KR_TIME)
        quest_reset = pendulum.tomorrow(KR_TIME).add(
            hours=4) if now.hour > 3 else pendulum.today(KR_TIME).add(hours=4)

        reset_countdown = quest_reset.diff(now)
        em = Embed(
            description=
            f":alarm_clock: The next reset will happen in {reset_countdown.as_interval()}. :alarm_clock:"
        )
        await helpers.message_handler(em, ctx, 20, embed=True)
예제 #16
0
    def backoff_time(self, response: requests.Response) -> Optional[float]:
        if self.is_raw_data_reports_reached_limit(response):
            now = pendulum.now("UTC")
            midnight = pendulum.tomorrow("UTC")
            wait_time = (midnight - now).seconds
        elif self.is_aggregate_reports_reached_limit(response):
            wait_time = 60
        else:
            return super().backoff_time(response)

        AirbyteLogger().log(
            "INFO", f"Rate limit exceded. Retry in {wait_time} seconds.")
        return wait_time
예제 #17
0
파일: zup.py 프로젝트: johannfr/zup
    def _snooze(self, duration):
        if duration > 0:
            LOG.debug("Snooze: Normal duration: %d", duration)
            next_run = pendulum.now().add(minutes=duration)
        else:
            LOG.debug("Snooze: Special duration: %d", duration)
            if duration == -1:
                next_run = pendulum.tomorrow().add(hours=6)
            elif duration == -2:
                next_run = pendulum.now().next(pendulum.MONDAY).add(hours=6)

        Configuration.set("next_run", next_run.for_json())
        self.hide()
예제 #18
0
 def set_today_or_tomorrow_time(self,
                                hours,
                                minutes=0,
                                period=None,
                                day='today'):
     if period == 'pm' and hours < 12:
         hours = hours + 12
     #
     if day == 'tomorrow':
         begin = pendulum.tomorrow(self.__timezone)
     else:
         begin = pendulum.today(self.__timezone)
     #
     return begin + timedelta(hours=hours, minutes=minutes)
예제 #19
0
def _get_year() -> int:
    east = "US/Eastern"

    now = pendulum.now(tz=east)

    if now.month == 12:
        if now.hour == 23:
            # if it's right before 12AM in December, use tomorrow as the default date
            # because it's almost AOC time
            return pendulum.tomorrow(east).year
        elif now.hour == 0:
            # if it's after 12AM in December, use yestrday as the default date because
            # you probably want to do yesteray's date
            return pendulum.today(east).year

    return int(os.environ.get("AOC_YEAR", 0)) or now.year
예제 #20
0
def schedule():
    """
    Used to limit time of day tasks can execute. Currenty set to run tasks between midnight and 8am daily.
    """

    c = inspect()
    task_cnt = len(c.scheduled()[config['CELERY_WORKER_NAME']])

    tomorrow = pendulum.tomorrow()
    # tomorrow_midnight = now.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=int(task_cnt/24))
    # tomorrow_8am = now.replace(hour=8, minute=0, second=0, microsecond=0) + timedelta(days=int(task_cnt/24))
    minute_offset = task_cnt % 24 * 20
    scheduled_start = tomorrow + timedelta(minutes=minute_offset) + timedelta(
        seconds=10)

    return scheduled_start
예제 #21
0
    def get_params(self, ctx, page):
        since_date_raw = self.get_start_date(ctx, 'since_date')

        lookback_days = ctx.config.get('email_stats_lookback_days',
                                       EMAILS_LOOKBACK_DAYS)
        since_date = pendulum.parse(since_date_raw).in_timezone("UTC").add(
            days=-lookback_days)
        until_date = pendulum.tomorrow().in_timezone("UTC")

        return {
            "per_page": EMAILS_PAGE_SIZE,
            "page": page,
            "since": since_date.to_date_string(),
            "until": until_date.to_date_string(),
            "sort": "ascending"
        }
예제 #22
0
 def _parseDate(self, string):
     """parse date"""
     date = string[:3].lower()
     if date in self.FUZZY_DAYS or string.lower() in self.FUZZY_DAYS:
         if date == "yes":
             date_string = pendulum.yesterday("US/Eastern").format(
                 "YYYYMMDD")
             return date_string
         elif date == "tod" or date == "ton":
             date_string = pendulum.now("US/Eastern").format("YYYYMMDD")
             return date_string
         elif date == "tom":
             date_string = pendulum.tomorrow("US/Eastern").format(
                 "YYYYMMDD")
             return date_string
         elif date == "sun":
             date_string = (pendulum.now("US/Eastern").next(
                 pendulum.SUNDAY).format("YYYYMMDD"))
             return date_string
         elif date == "mon":
             date_string = (pendulum.now("US/Eastern").next(
                 pendulum.MONDAY).format("YYYYMMDD"))
             return date_string
         elif date == "tue":
             date_string = (pendulum.now("US/Eastern").next(
                 pendulum.TUESDAY).format("YYYYMMDD"))
             return date_string
         elif date == "wed":
             date_string = (pendulum.now("US/Eastern").next(
                 pendulum.WEDNESDAY).format("YYYYMMDD"))
             return date_string
         elif date == "thu":
             date_string = (pendulum.now("US/Eastern").next(
                 pendulum.THURSDAY).format("YYYYMMDD"))
             return date_string
         elif date == "fri":
             date_string = (pendulum.now("US/Eastern").next(
                 pendulum.FRIDAY).format("YYYYMMDD"))
             return date_string
         elif date == "sat":
             date_string = (pendulum.now("US/Eastern").next(
                 pendulum.SATURDAY).format("YYYYMMDD"))
             return date_string
         else:
             return string
     else:
         return string
예제 #23
0
 def _parseDate(self, string):
     """parse date"""
     date = string[:3].lower()
     if date in self.FUZZY_DAYS or string.lower() in self.FUZZY_DAYS:
         if date == 'yes':
             date_string = pendulum.yesterday('US/Eastern').format(
                 'YYYYMMDD')
             return date_string
         elif date == 'tod' or date == 'ton':
             date_string = pendulum.now('US/Eastern').format('YYYYMMDD')
             return date_string
         elif date == 'tom':
             date_string = pendulum.tomorrow('US/Eastern').format(
                 'YYYYMMDD')
             return date_string
         elif date == 'sun':
             date_string = pendulum.now('US/Eastern').next(
                 pendulum.SUNDAY).format('YYYYMMDD')
             return date_string
         elif date == 'mon':
             date_string = pendulum.now('US/Eastern').next(
                 pendulum.MONDAY).format('YYYYMMDD')
             return date_string
         elif date == 'tue':
             date_string = pendulum.now('US/Eastern').next(
                 pendulum.TUESDAY).format('YYYYMMDD')
             return date_string
         elif date == 'wed':
             date_string = pendulum.now('US/Eastern').next(
                 pendulum.WEDNESDAY).format('YYYYMMDD')
             return date_string
         elif date == 'thu':
             date_string = pendulum.now('US/Eastern').next(
                 pendulum.THURSDAY).format('YYYYMMDD')
             return date_string
         elif date == 'fri':
             date_string = pendulum.now('US/Eastern').next(
                 pendulum.FRIDAY).format('YYYYMMDD')
             return date_string
         elif date == 'sat':
             date_string = pendulum.now('US/Eastern').next(
                 pendulum.SATURDAY).format('YYYYMMDD')
             return date_string
         else:
             return string
     else:
         return string
예제 #24
0
    def test_after_today(self):
        validate = Validator().validate({
            'date': '2020-05-21T22:00:00',
        }, after_today(['date']))

        self.assertEqual(len(validate), 0)

        validate = Validator().validate(
            {
                'date': pendulum.tomorrow().to_datetime_string(),
            }, after_today(['date']))

        self.assertEqual(len(validate), 0)

        validate = Validator().validate({
            'date': '1975-05-21T22:00:00',
        }, after_today(['date']))

        self.assertEqual(validate,
                         {'date': ['The date must be a date after today.']})
예제 #25
0
    def test_is_future(self):
        validate = Validator().validate({
            'date': '2020-05-21T22:00:00',
        }, is_future(['date']))

        self.assertEqual(len(validate), 0)

        validate = Validator().validate(
            {
                'date': pendulum.tomorrow().to_datetime_string(),
            }, is_future(['date'], tz='America/New_York'))

        self.assertEqual(len(validate), 0)

        validate = Validator().validate(
            {
                'date': pendulum.yesterday().to_datetime_string(),
            }, is_future(['date']))

        self.assertEqual(validate,
                         {'date': ['The date must be a time in the past.']})
예제 #26
0
def test_current_price_for_a_region_updated_when_matching_required(
        client, admin_users, supplier_user,
        service_prices_with_multiple_region):
    from app.models import ServiceTypePrice

    res = client.post('/2/login',
                      data=json.dumps({
                          'emailAddress': admin_users[0].email_address,
                          'password': '******'
                      }),
                      content_type='application/json')
    assert res.status_code == 200

    ceiling_id = 2
    new_price = 290
    response = client.post('/2/ceiling-prices/{}'.format(ceiling_id),
                           data=json.dumps({
                               'ceilingPrice': new_price,
                               'setCurrentPriceToCeiling': True
                           }),
                           content_type='application/json')
    assert response.status_code == 200

    prices = ServiceTypePrice.query\
        .filter(ServiceTypePrice.service_type_id == 1,
                ServiceTypePrice.supplier_code == 1,
                ServiceTypePrice.sub_service_id == 1,
                ServiceTypePrice.region_id == 2,
                ServiceTypePrice.service_type_price_ceiling_id == 2)\
        .order_by(ServiceTypePrice.updated_at.desc())\
        .all()

    current_price = prices[0]
    previous_price = prices[1]
    assert current_price.date_from == pendulum.tomorrow().date()
    assert current_price.date_to == pendulum.Date.create(2050, 1, 1)
    assert current_price.price == 290.00

    assert previous_price.date_to == pendulum.today().date()
    assert previous_price.price == 200.50
예제 #27
0
def start_task_loop(*, minute_interval: int):

    while True:
        now = pendulum.now("UTC")
        start = now.subtract(minutes=now.minute,
                             seconds=now.second,
                             microseconds=now.microsecond)
        end = pendulum.tomorrow("UTC")

        periods = list(
            pendulum.period(start, end).range("minutes", minute_interval))

        for period in periods:
            if pendulum.now("UTC") > period:
                continue
            else:
                while pendulum.now("UTC") < period:
                    sleep(1)
                else:
                    start_time = time()
                    start_pipeline(period.int_timestamp)
                    end_time = time()
                    logger.debug(
                        f"Took {end_time- start_time} seconds to run.")
예제 #28
0
    def _match_price_to_ceiling(self, price_id, ceiling_price=None):
        """ Update the current price to the value of its ceiling.
        An optional ceiling_price is provided in case the current price does not exist

        This does not handle scenarios where the current_price may be updated
        by another request/transaction.

        :param price_id:        identifier of the db-record to be updated
        :param ceiling_price:   ServiceTypePriceCeiling object
        """
        existing_price = self.prices_service.get(
            price_id) if price_id else None

        date_from = pendulum.tomorrow(
            current_app.config['DEADLINES_TZ_NAME']).date()
        date_to = pendulum.Date.create(2050, 1, 1)

        if existing_price:
            existing_price.date_to = date_from.subtract(days=1)
            self.prices_service.add_price(
                existing_price, date_from, date_to,
                existing_price.service_type_price_ceiling.price)
        else:
            if not ceiling_price:
                raise Exception(
                    "Ceiling price required to create new price record")
            self.prices_service.create(
                supplier_code=ceiling_price.supplier_code,
                service_type_id=ceiling_price.service_type_id,
                region_id=ceiling_price.region_id,
                date_from=pendulum.today(
                    current_app.config['DEADLINES_TZ_NAME']).date(),
                date_to=date_to,
                price=ceiling_price.price,
                sub_service_id=ceiling_price.sub_service_id,
                service_type_price_ceiling_id=ceiling_price.id)
def suppliers(app, request):
    with app.app_context():
        for i in range(1, 6):
            db.session.add(
                Supplier(
                    abn=i,
                    code=(i),
                    name='Test Supplier{}'.format(i),
                    contacts=[Contact(name='auth rep', email='*****@*****.**')],
                    data={
                        'representative': 'auth rep',
                        'phone': '0123456789',
                        'email': '*****@*****.**',
                        'documents': {
                            "liability": {
                                "filename":
                                "1.pdf",
                                "expiry":
                                pendulum.tomorrow().date().to_date_string()
                            },
                            "workers": {
                                "filename":
                                "2.pdf",
                                "expiry":
                                pendulum.tomorrow().date().to_date_string()
                            },
                            "financial": {
                                "filename": "3.pdf"
                            }
                        },
                        'pricing': {
                            "Emerging technologies": {
                                "maxPrice": "1000"
                            },
                            "Support and Operations": {
                                "maxPrice": "100"
                            },
                            "Agile delivery and Governance": {
                                "maxPrice": "1000"
                            },
                            "Data science": {
                                "maxPrice": "100"
                            },
                            "Change, Training and Transformation": {
                                "maxPrice": "1000"
                            },
                            "Training, Learning and Development": {
                                "maxPrice": "1000"
                            },
                            "Strategy and Policy": {
                                "maxPrice": "1000"
                            },
                            "Software engineering and Development": {
                                "maxPrice": "1000"
                            },
                            "User research and Design": {
                                "maxPrice": "1000"
                            },
                            "Recruitment": {
                                "maxPrice": "1000"
                            }
                        }
                    }))

            db.session.flush()

        framework = Framework.query.filter(
            Framework.slug == "digital-marketplace").first()
        db.session.add(
            SupplierFramework(supplier_code=1, framework_id=framework.id))

        db.session.commit()
        yield Supplier.query.all()
예제 #30
0
    def cbb(self, irc, msg, args, options, team=None):
        """[--date] [--all] [team]
        Fetches college basketball scores/schedule for given date and/or team.
        Defaults to today and top 25 teams (if playing, otherwise shows all games).
        Use --all to show results for all teams.
        """
        channel = msg.args[0]
        if channel == irc.nick:
            channel = msg.nick
        options = dict(options)
        date = options.get('date')
        if 'all' in options:
            all = True
        else:
            all = False
        if date:
            if date.lower() in ['yesterday', 'tomorrow', 'today']:
                if date.lower() in 'yesterday':
                    date = pendulum.yesterday().format('YYYYMMDD')
                elif date.lower() in 'tomorrow':
                    date = pendulum.tomorrow().format('YYYYMMDD')
                else:
                    date = pendulum.now().format('YYYYMMDD')
            else:
                try:
                    date = pendulum.parse(date,
                                          strict=False).format('YYYYMMDD')
                except:
                    irc.reply('Invalid date format')
                    return
            SCORES = self._checkscores(date)
            if date not in SCORES:
                niceDate = pendulum.parse(date)
                niceDate = "{0}/{1}/{2}".format(niceDate.month, niceDate.day,
                                                niceDate.year)
                irc.reply('No games found for {}.'.format(date))
        else:
            today = pendulum.now().format('YYYYMMDD')
            yesterday = pendulum.yesterday().format('YYYYMMDD')
            tomorrow = date = pendulum.tomorrow().format('YYYYMMDD')
            SCORES = self._checkscores()
            if today in SCORES:
                date = today
            elif yesterday in SCORES:
                date = yesterday
            elif tomorrow in SCORES:
                date = tomorrow
            else:
                irc.reply('No games found.')
                return

        if team:
            if len(team) > 2:
                reply = []
                # single team
                for key, value in SCORES[date].items():
                    if team.lower() in value['lookup']['abbr'].lower():
                        #print(team.lower(), '\t', value['lookup']['abbr'].lower())
                        reply.append(value['long'])
                        #break
                if not reply:
                    for key, value in SCORES[date].items():
                        if team.lower() in value['lookup']['full'].lower():
                            reply.append(value['long'])
                            #break
                if not reply:
                    irc.reply(
                        'ERROR: no match found for your input: {}'.format(
                            team))
                    return
                else:
                    if len(reply) <= 4:
                        for item in reply:
                            irc.sendMsg(ircmsgs.privmsg(channel, item))
                    else:
                        for item in reply:
                            irc.reply(item)
                return
            else:
                irc.reply('ERROR: search string too short')
                return
        else:
            niceDate = pendulum.parse(date)
            niceDate = "{0}/{1}/{2}".format(niceDate.month, niceDate.day,
                                            niceDate.year)
            reply = ' | '.join(value['short']
                               for item, value in SCORES[date].items()
                               if value['top25'])
            if reply and not all:
                irc.reply(
                    "Showing teams in the top 25 for {0}. Use --all to see more games."
                    .format(niceDate),
                    prefixNick=False)
                irc.reply(reply, prefixNick=False)
            else:
                reply = ' | '.join(value['short']
                                   for item, value in SCORES[date].items())
                irc.reply("Showing all games for {0}.".format(niceDate),
                          prefixNick=False)
                irc.reply(reply, prefixNick=False)
            return

        return
예제 #31
0
    def _checkscores(self, cdate=None):
        if cdate:
            #today = pendulum.parse(cdate, strict=False).format('YYYYMMDD')
            #yesterday = pendulum.parse(cdate, strict=False).subtract(days=1).format('YYYYMMDD')
            #tomorrow = pendulum.parse(cdate, strict=False).add(days=1).format('YYYYMMDD')
            dates = [cdate]
        else:
            today = pendulum.now().format('YYYYMMDD')
            yesterday = pendulum.yesterday().format('YYYYMMDD')
            tomorrow = pendulum.tomorrow().format('YYYYMMDD')
            dates = [yesterday, today, tomorrow]

        data = collections.OrderedDict()
        for date in dates:
            tmp = requests.get(SCOREBOARD.format(date=date), timeout=10)
            tmp = json.loads(tmp.content)
            tmp_date = pendulum.parse(
                tmp['eventsDate']['date'],
                strict=False).in_tz('US/Eastern').format('YYYYMMDD')
            data[tmp_date] = tmp['events']

        #print(data)
        """
        'day': {'game1': {'short', 'long'},
                'game2': {'short', 'long'}}
        """
        games = collections.OrderedDict()
        for day, d in data.items():
            #print(day, d)
            if d:
                games[day] = collections.OrderedDict()
                for event in d:
                    key = event['id']
                    lookup = {
                        'abbr': '{}'.format(event['shortName']),
                        'full': '{}'.format(event['name'])
                    }
                    comp = event['competitions'][0]
                    time = pendulum.parse(comp['date'],
                                          strict=False).in_tz('US/Eastern')
                    short_time = time.format('h:mm A zz')
                    long_time = time.format('dddd, MMM Do, h:mm A zz')
                    status = comp['status']['type']['state']
                    is_ended = comp['status']['type']['completed']
                    top25 = True if (
                        0 < comp['competitors'][0]['curatedRank']['current'] <=
                        25
                        or 0 < comp['competitors'][1]['curatedRank']['current']
                        <= 25) else False
                    home_rank = '(#{})'.format(comp['competitors'][0]['curatedRank']['current']) \
                        if 0 < comp['competitors'][0]['curatedRank']['current'] <= 25 else ''
                    away_rank = '(#{})'.format(comp['competitors'][1]['curatedRank']['current']) \
                        if 0 < comp['competitors'][1]['curatedRank']['current'] <= 25 else ''
                    home_short = comp['competitors'][0]['team']['abbreviation']
                    home_long = comp['competitors'][0]['team']['displayName']
                    away_short = comp['competitors'][1]['team']['abbreviation']
                    away_long = comp['competitors'][1]['team']['displayName']
                    home_score = int(comp['competitors'][0]['score'])
                    away_score = int(comp['competitors'][1]['score'])
                    broadcasts = []
                    try:
                        for thing in comp['broadcasts']:
                            for station in thing['names']:
                                broadcasts.append(station)
                    except:
                        pass
                    #print(home_short, away_short, '\t||\t', top25, status, comp['competitors'][0]['curatedRank']['current'],
                    #                                                       comp['competitors'][1]['curatedRank']['current'])
                    if status == 'pre':
                        # pre
                        short = '{} @ {} {}'.format(away_short, home_short,
                                                    short_time)
                        long = '{}{} @ {}{} | {}{}'.format(
                            away_long, away_rank, home_long, home_rank,
                            long_time, " [TV: {}]".format(
                                ", ".join(broadcasts) if broadcasts else ""))
                    else:
                        # inp
                        if is_ended:
                            clock_short = ircutils.mircColor('F', 'red')
                            clock_long = ircutils.mircColor('Final', 'red')
                        else:
                            if 'Halftime' in comp['status']['type']['detail']:
                                clock_short = ircutils.mircColor(
                                    'HT', 'orange')
                                clock_long = ircutils.mircColor(
                                    'Halftime', 'orange')
                            else:
                                clock_short = ircutils.mircColor(
                                    comp['status']['type']
                                    ['shortDetail'].replace(' - ',
                                                            ' '), 'green')
                                clock_long = ircutils.mircColor(
                                    comp['status']['type']['detail'], 'green')
                        try:
                            last_play = ' | \x02Last Play:\x02 {}'.format(comp['situation']['lastPlay']['text']) \
                                if 'situation' in comp else ''
                        except:
                            last_play = ''
                        if away_score > home_score:
                            away_short_str = ircutils.bold('{} {}'.format(
                                away_short, away_score))
                            away_long_str = ircutils.bold('{}{} {}'.format(
                                away_long, away_rank, away_score))
                            home_short_str = '{} {}'.format(
                                home_short, home_score)
                            home_long_str = '{}{} {}'.format(
                                home_long, home_rank, home_score)
                        elif home_score > away_score:
                            away_short_str = '{} {}'.format(
                                away_short, away_score)
                            away_long_str = '{}{} {}'.format(
                                away_long, away_rank, away_score)
                            home_short_str = ircutils.bold('{} {}'.format(
                                home_short, home_score))
                            home_long_str = ircutils.bold('{}{} {}'.format(
                                home_long, home_rank, home_score))
                        else:
                            away_short_str = '{} {}'.format(
                                away_short, away_score)
                            away_long_str = '{}{} {}'.format(
                                away_long, away_rank, away_score)
                            home_short_str = '{} {}'.format(
                                home_short, home_score)
                            home_long_str = '{}{} {}'.format(
                                home_long, home_rank, home_score)
                        short = '{} {} {}'.format(away_short_str,
                                                  home_short_str, clock_short)
                        long = '{} @ {} - {}{}'.format(away_long_str,
                                                       home_long_str,
                                                       clock_long, last_play)
                    games[day][key] = {
                        'short': short,
                        'long': long,
                        'ended': is_ended,
                        'top25': top25,
                        'lookup': lookup
                    }

                # sort events
                games[day] = collections.OrderedDict(
                    sorted(games[day].items(), key=lambda k: k[1]['ended']))

        return games
예제 #32
0
def test_tomorrow():
    now = pendulum.now().start_of("day")
    tomorrow = pendulum.tomorrow()
    assert isinstance(tomorrow, DateTime)
    assert now.diff(tomorrow).in_days() == 1
def suppliers(app, request):
    with app.app_context():
        for i in range(1, 6):
            db.session.add(Supplier(
                abn=i,
                code=(i),
                name='Test Supplier{}'.format(i),
                contacts=[Contact(name='auth rep', email='*****@*****.**')],
                data={
                    'documents': {
                        "liability": {
                            "filename": "1.pdf",
                            "expiry": pendulum.tomorrow().date().to_date_string()
                        },
                        "workers": {
                            "filename": "2.pdf",
                            "expiry": pendulum.tomorrow().date().to_date_string()
                        },
                        "financial": {
                            "filename": "3.pdf"
                        }
                    },
                    'pricing': {
                        "Emerging technologies": {
                            "maxPrice": "1000"
                        },
                        "Support and Operations": {
                            "maxPrice": "100"
                        },
                        "Agile delivery and Governance": {
                            "maxPrice": "1000"
                        },
                        "Data science": {
                            "maxPrice": "100"
                        },
                        "Change, Training and Transformation": {
                            "maxPrice": "1000"
                        },
                        "Training, Learning and Development": {
                            "maxPrice": "1000"
                        },
                        "Strategy and Policy": {
                            "maxPrice": "1000"
                        },
                        "Software engineering and Development": {
                            "maxPrice": "1000"
                        },
                        "User research and Design": {
                            "maxPrice": "1000"
                        },
                        "Recruitment": {
                            "maxPrice": "1000"
                        }
                    }
                }
            ))

            db.session.flush()

        framework = Framework.query.filter(Framework.slug == "digital-marketplace").first()
        db.session.add(SupplierFramework(supplier_code=1, framework_id=framework.id))

        db.session.commit()
        yield Supplier.query.all()