Ejemplo n.º 1
0
def create_resource(project, cpu):
    now = dt.now()
    if project.type == "a":
        month = int(current_app.config.get("ACC_TYPE_A", 6))
        ttl = now + rd(month=+month)
    elif project.type == "h":
        month = int(current_app.config.get("ACC_TYPE_H", 6))
        ttl = now + rd(month=+month)
    else:  # For project type B
        year = now.year + 1
        month = int(current_app.config.get("ACC_START_MONTH", 3))
        if "ACC_START_DAY" in current_app.config:
            day = int(current_app.config.get("ACC_START_DAY", 1))
        else:
            day = monthrange(year, month)[1]
        ttl = dt(year, month, day, 0, 0, 0)

    from code.database.schema import Resources

    resource = Resources(
        approve=current_user,
        valid=True,
        cpu=cpu,
        type=project.type,
        project=project.get_name(),
        ttl=ttl,
        treated=False
    )
    return resource
Ejemplo n.º 2
0
def get_holiday():
    """Return today's holiday.

    US Holidays include:
    - New Year's Day
    - Martin Luther King, Jr. Day
    - Washington's Birthday
    - Memorial Day
    - Independence Day
    - Labor Day
    - Columbus Day
    - Veterans Day
    - Thanksgiving
    - Christmas Day

    https://pypi.python.org/pypi/holidays
    """
    now = timezone.localtime(timezone.now())
    today = now.date()
    year = today.year
    us_holidays = holidays.US(years=year)
    us_holidays.observed = False
    us_holidays.append({
        date(year, 2, 2): 'Groundhog Day',
        date(year, 2, 14): 'Valentine\'s Day',
        date(year, 3, 14): 'Pi Day',
        date(year, 3, 17): 'St. Patrick\'s Day',
        date(year, 4, 1): 'April Fools\' Day',
        date(year, 4, 22): 'Earth Day',
        date(year, 5, 4): 'Star Wars Day: May the Fourth Be With You',
        date(year, 5, 5): 'Cinco de Mayo',
        date(year, 6, 14): 'Flag Day',
        date(year, 9, 19): 'International Talk Like a Pirate Day',
        date(year, 10, 21): 'Back to the Future Day',
        date(year, 10, 31): 'Halloween',
        date(year, 12, 24): 'Christmas Eve',
        date(year, 12, 31): 'New Year\'s Eve',
        date(year, 5, 1) + rd(weekday=SU(+2)): 'Mother\'s Day',
        date(year, 6, 1) + rd(weekday=SU(+3)): 'Father\'s Day',
        date(year, 4, 30) + rd(weekday=FR(-1)): 'Arbor Day',
        easter(year): 'Easter',
    })
    if year % 2 == 0:
        us_holidays.append({
            date(year, 11, 1) + rd(weekday=MO) + rd(days=+1): 'Election Day',
        })
    try:
        holiday = us_holidays[today]
    except KeyError:
        return None
    return {
        'icon': holiday_icons.get(holiday, None),
        'name': holiday,
        'date': today,
    }
Ejemplo n.º 3
0
    def _set_observed(self, holiday_name, holiday_date):
        """
        Sets the specified holiday, including an "observed" holiday
        on either Friday or Monday if the true holiday falls on a weekend.

        :param name: the name of the holiday.
        :param date: the date of the holiday.
        """
        self[holiday_date] = holiday_name
        if self.observed and holiday_date.weekday() == 5:
            # Observe holiday on Friday.
            self[holiday_date + rd(days=-1)] = holiday_name + ' (Observed)'
        elif self.observed and holiday_date.weekday() == 6:
            # Observe holiday on Monday.
            self[holiday_date + rd(days=+1)] = holiday_name + ' (Observed)'
Ejemplo n.º 4
0
 def __rsub__(self, other):
     if getattr(self, 'bdays', None) is not None:
         other = parse(other)
         if self.bdays == 0:
             while other.weekday() in self.weekdays_off or other in self.holidays:
                 other += rd(days=-1)
     return self.__neg__().__radd__(other)
Ejemplo n.º 5
0
def view_all():
    user_agencies = current_user.get_agencies if current_user.is_agency else ''
    return render_template(
        'request/all.html',
        form=SearchRequestsForm(),
        holidays=sorted(get_holidays_date_list(
            datetime.utcnow().year,
            (datetime.utcnow() + rd(years=DEFAULT_YEARS_HOLIDAY_LIST)).year)
        ),
        user_agencies=user_agencies
    )
    def _populate(self, year):
        """
        Populates holidays for a calendar year.

        :param year: the calendar year.
        """
        # Populate with built-in holidays.
        super(SLOCOHolidays, self)._populate(year)

        # Add Lincoln's Birthday.
        name = 'Lincoln\'s Birthday'
        if self.observed and datetime.date(year, 2, 12).weekday() == 5:
            self[datetime.date(year, 2, 11)] = name
        elif self.observed and datetime.date(year, 2, 12).weekday() == 6:
            self[datetime.date(year, 2, 13)] = name
        else:
            self[datetime.date(year, 2, 12)] = name

        # Add day after Thanksgiving.
        name = 'Thanksgiving'
        self[datetime.date(year, 11, 1) + rd(weekday=rrule.TH(+4)) + rd(days=+1)] = name
    def _adjust_for_holidays(self, holidays, the_date, backwards=True):
        """
        Returns a date, adjusted for holidays if necessary.

        :param the_date: the date to check.
        :param backwards: direction to move if date coincides with a holiday.
        :rtype: datetime.datetime.
        """
        while the_date in holidays:
            the_date += rd(days=-1 if backwards else 1)

        return the_date
Ejemplo n.º 8
0
 def __add__(self, other):
     if isinstance(other, relativedelta):
         ret = rd.__add__(self, other)
         ret.__class__ = relativedelta
         for attr in ('bdays', 'bhours', 'bminutes', 'bseconds'):
             if getattr(self, attr, None) is not None:
                 if getattr(other, attr, None) is not None:
                     setattr(ret, attr,
                             getattr(self, attr) + getattr(other, attr))
                 else:
                     setattr(ret, attr, getattr(self, attr))
             elif getattr(other, attr, None) is not None:
                 setattr(ret, attr, getattr(other, attr))
         return ret
     ret = parse(other)
     # If we are adding any time (not just dates) the ret object to return
     # must be a datetime object; a date object will not work
     if not isinstance(ret, datetime) \
             and (self.bhours or self.bminutes or self.bseconds):
         ret = datetime.combine(ret, datetime.min.time())
     for attr in ('bseconds', 'bminutes', 'bhours', 'bdays'):
         if getattr(self, attr, None) is not None:
             while ret.weekday() in self.weekdays_off or ret in self.holidays:
                 ret += rd(days=+1)
             while attr != "bdays" and \
                     (ret.time() < self.btstart or
                      ret.time() >= self.btend):
                 ret += rd(**{attr[1:]: +1})
             i = getattr(self, attr)
             a = +1 if i > 0 else -1
             while i != 0:
                 ret += rd(**{attr[1:]: a})
                 while ret.weekday() in self.weekdays_off or ret in self.holidays:
                     ret += rd(days=a)
                 while attr != "bdays" and \
                         (ret.time() < self.btstart or
                          ret.time() >= self.btend):
                     ret += rd(**{attr[1:]: a})
                 i -= a
     return rd.__add__(self, ret)
Ejemplo n.º 9
0
    def _populate(self, year):

        eday = easter(year, method=EASTER_ORTHODOX)

        # New Years
        self[date(year, JAN, 1)] = "Πρωτοχρονιά [New Year's Day]"
        # Epiphany
        self[date(year, JAN, 6)] = "Θεοφάνεια [Epiphany]"

        # Clean Monday
        self[eday - rd(days=48)] = "Καθαρά Δευτέρα [Clean Monday]"

        # Independence Day
        self[date(year, MAR, 25)] = "Εικοστή Πέμπτη Μαρτίου [Independence Day]"

        # Easter Monday
        self[eday + rd(days=1)] = "Δευτέρα του Πάσχα [Easter Monday]"

        # Labour Day
        self[date(year, MAY, 1)] = "Εργατική Πρωτομαγιά [Labour day]"

        # Monday of the Holy Spirit
        self[eday +
             rd(days=50
                )] = "Δευτέρα του Αγίου Πνεύματος [Monday of the Holy Spirit]"

        # Assumption of Mary
        self[date(year, AUG, 15)] = "Κοίμηση της Θεοτόκου [Assumption of Mary]"

        # Ochi Day
        self[date(year, OCT, 28)] = "Ημέρα του Όχι [Ochi Day]"

        # Christmas
        self[date(year, DEC, 25)] = "Χριστούγεννα [Christmas]"

        # Day after Christmas
        self[date(
            year, DEC,
            26)] = "Επόμενη ημέρα των Χριστουγέννων [Day after Christmas]"
Ejemplo n.º 10
0
def getAge(date):
    today = datetime.datetime.today()
    try:
        date = datetime.datetime.strptime(date, "%Y-%m-%d")
    except:
        print("Error in the date")
        return
    age = rd(today, date).years

    if age <= 0:
        print('Please enter age above 0')
        return
    approval(age)
Ejemplo n.º 11
0
def getTestAge(date):
    today = datetime.datetime.today()
    # date = "05/12/1991"
    try:
        date = datetime.datetime.strptime(date, "%Y-%m-%d")
    except:
        print("Error in the date")
        return
    age = rd(today, date).years

    if age <= 0:
        print('Please enter age above 0')
    return age
Ejemplo n.º 12
0
 def pencairan_kredit(self):
     pokok = self.pokok * 1.0
     total_biaya = sum(biaya.nominal for biaya in self.biaya_line)
     if self.account_cair.id == False:
         raise Warning(_('Metode Pencairan tidak boleh kosong'))
     else:
         self.status = 'cair'
         self.tgl_cair = fields.Date.today()
         tgl_cair = fields.Date.from_string(self.tgl_cair)
         for item in self.kredit_line:
             tgl_jt = tgl_cair + rd(months=item.sequence)
             item.tgl_jt = tgl_jt.strftime(DATE_FORMAT)
     return
Ejemplo n.º 13
0
 def storeholiday(self, hol_date, hol_name):
     """
     Function to store the holiday name in the appropriate
     date and to implement Section 4(2) of the Holidays Act:
     'if any day specified in the Schedule falls on a Sunday,
     the day next following not being itself a public holiday
     is declared a public holiday in Singapore.'
     """
     if hol_date.weekday() == SUN:
         self[hol_date] = hol_name + " [Sunday]"
         self[hol_date + rd(days=+1)] = "Monday following " + hol_name
     else:
         self[hol_date] = hol_name
Ejemplo n.º 14
0
 def validasi_kredit(self):
     to = fields.Datetime.from_string(self.apply_to)
     sekarang = datetime.datetime.now() + rd(hours=-7)
     if (self.apply_2 == self.apply_key) and (to >= sekarang):
         self.state = 'validate'
     else:
         if to < sekarang:
             raise Warning(
                 _('Tidak dapat divalidasi, token kadaluwarsa, silahkan generate token baru-2'
                   ))
         else:
             raise Warning(_('Tidak dapat divalidasi, kode apply 2 salah'))
     return
Ejemplo n.º 15
0
 def _populate(self, year):
     # New Year's Day
     if year > 1911:
         self[
             date(year, JAN, 1)
         ] = "Founding of the Republic of China  (New Year's Day)"
         hol_date = self.cnls.lunar_n_y_date(year)
         self[hol_date + rd(days=-1)] = "Chinese New Year's Eve"
         self[hol_date] = "Spring Festival"
         self[hol_date + rd(days=1)] = "Spring Festival"
         self[hol_date + rd(days=2)] = "Spring Festival"
         self[date(year, APR, 4)] = "Children's Day"
         self[self.cnls.lunar_to_gre(year, 5, 5)] = "Dragon Boat Festival"
         self[self.cnls.lunar_to_gre(year, 8, 15)] = "Mid-Autumn Festival"
         self[date(year, OCT, 10)] = "National Day"
         self[date(year, OCT, 11)] = "National Day"
     if year > 1947:
         self[date(year, FEB, 28)] = "Peace Memorial Day"
     if year == 2021:
         hol_date = self.cnls.lunar_n_y_date(year)
         self[hol_date + rd(days=3)] = "Spring Festival"
         self[hol_date + rd(days=4)] = "Spring Festival"
Ejemplo n.º 16
0
    def get_next_update_time(self, ts, tpt_id):
        """
        DESCRIPTION
        -----------
        Calculate the beginning timestamp of the next timeperiod dimension based on 
        the current timestamp or timestamp provided.

        PARAMETERS
        ----------
        ts : dt.datetime, dt.timestamp
            A datetime or timestamp object representing the beginning timestamp 
            of the next timeperiod dimension from the current timestamp or timestamp
            provided.
        tpt_id : int 
            An integer representing the timeperiod type id association created in 
            the database.

        RETURNS
        -------
        A timestamp or datetime object representing the beginning timestamp of the
        next timeperiod dimension based on the timeperiod type provided.

        MODIFICATIONS
        -------------
        Created : 4/25/19
        Modified : 5/1/19
            - Adapted from the TimePeriodDimensionStreaming class.
        """
        ts = ts.replace(second=0, microsecond=0)
        if tpt_id == 1:
            next_update_ts = ts + td(minutes=1)
        elif tpt_id == 2:
            next_update_ts = ts + td(minutes=5 + 5 - ts.minute % 5)
        elif tpt_id == 3:
            next_update_ts = ts + td(minutes=15 + 15 - ts.minute % 15)
        elif tpt_id == 4:
            next_update_ts = ts + td(minutes=30 + 30 - ts.minute % 30)
        elif tpt_id == 5:
            next_update_ts = (ts + td(hours=1)).replace(minute=0)
        elif tpt_id == 6:
            next_update_ts = (ts +
                              td(hours=4 + 4 - ts.hour % 4)).replace(minute=0)
        elif tpt_id == 7:
            next_update_ts = (ts + td(days=1)).replace(hour=0, minute=0)
        elif tpt_id == 8:
            next_update_ts = (
                ts + td(days=self.begin_weekday - ts.weekday())).replace(
                    hour=0, minute=0)
        elif tpt_id == 9:
            next_update_ts = ts.replace(day=1, hour=0, minute=0) + rd(months=1)
        return next_update_ts
Ejemplo n.º 17
0
    def _populate(self, year):

        eday = easter(year, method=EASTER_ORTHODOX)

        # New Year
        for day in [1, 2]:
            self[date(year, JAN, day)] = "Anul Nou"

        # Anniversary of the formation of the United Principalities
        self[date(year, JAN, 24)] = "Unirea Principatelor Române"

        # Easter (Friday, Sunday and Monday)
        for day_after_easter in [-2, 0, 1]:
            self[eday + rd(days=day_after_easter)] = "Paștele"

        # Labour Day
        self[date(year, MAY, 1)] = "Ziua Muncii"

        # Children's Day (since 2017)
        if year >= 2017:
            self[date(year, JUN, 1)] = "Ziua Copilului"

        # Whit Monday
        for day_after_easter in [49, 50]:
            self[eday + rd(days=day_after_easter)] = "Rusaliile"

        # Assumption of Mary
        self[date(year, AUG, 15)] = "Adormirea Maicii Domnului"

        # St. Andrew's Day
        self[date(year, NOV, 30)] = "Sfântul Andrei"

        # National Day
        self[date(year, DEC, 1)] = "Ziua Națională a României"

        # Christmas Day
        self[date(year, DEC, 25)] = "Crăciunul"
        self[date(year, DEC, 26)] = "Crăciunul"
Ejemplo n.º 18
0
    def _populate(self, year):
        # New years
        self[date(year, JAN, 1)] = "Nieuwjaarsdag"

        easter_date = easter(year)

        # Easter
        self[easter_date] = "Pasen"

        # Second easter day
        self[easter_date + rd(days=1)] = "Paasmaandag"

        # Ascension day
        self[easter_date + rd(days=39)] = "O.L.H. Hemelvaart"

        # Pentecost
        self[easter_date + rd(days=49)] = "Pinksteren"

        # Pentecost monday
        self[easter_date + rd(days=50)] = "Pinkstermaandag"

        # International Workers' Day
        self[date(year, MAY, 1)] = "Dag van de Arbeid"

        # Belgian National Day
        self[date(year, JUL, 21)] = "Nationale feestdag"

        # Assumption of Mary
        self[date(year, AUG, 15)] = "O.L.V. Hemelvaart"

        # All Saints' Day
        self[date(year, NOV, 1)] = "Allerheiligen"

        # Armistice Day
        self[date(year, NOV, 11)] = "Wapenstilstand"

        # First christmas
        self[date(year, DEC, 25)] = "Kerstmis"
Ejemplo n.º 19
0
 def _populate(self, year):
     # New Year's Day
     name = "Нова година"
     self[date(year, JAN, 1)] = name
     self[date(year, JAN, 2)] = name
     if self.observed and date(year, JAN, 1).weekday() in WEEKEND:
         self[date(year, JAN, 3)] = name + " (Observed)"
     # Orthodox Christmas
     name = "Божић"
     self[date(year, JAN, 7)] = name
     # Statehood day
     name = "Дан државности Србије"
     self[date(year, FEB, 15)] = name
     self[date(year, FEB, 16)] = name
     if self.observed and date(year, FEB, 15).weekday() in WEEKEND:
         self[date(year, FEB, 17)] = name + " (Observed)"
     # International Workers' Day
     name = "Празник рада"
     self[date(year, MAY, 1)] = name
     self[date(year, MAY, 2)] = name
     if self.observed and date(year, MAY, 1).weekday() in WEEKEND:
         if date(year, MAY, 2) == easter(year, method=EASTER_ORTHODOX):
             self[date(year, MAY, 4)] = name + " (Observed)"
         else:
             self[date(year, MAY, 3)] = name + " (Observed)"
     # Armistice day
     name = "Дан примирја у Првом светском рату"
     self[date(year, NOV, 11)] = name
     if self.observed and date(year, NOV, 11).weekday() == SUN:
         self[date(year, NOV, 12)] = name + " (Observed)"
     # Easter
     self[easter(year, method=EASTER_ORTHODOX) -
          rd(days=2)] = "Велики петак"
     self[easter(year, method=EASTER_ORTHODOX) -
          rd(days=1)] = "Велика субота"
     self[easter(year, method=EASTER_ORTHODOX)] = "Васкрс"
     self[easter(year, method=EASTER_ORTHODOX) +
          rd(days=1)] = "Други дан Васкрса"
Ejemplo n.º 20
0
    def _populate(self, year):
        e = easter(year)

        # New Year's Day
        self[date(year, JAN, 1)] = "uusaasta"

        # Independence Day, anniversary of the Republic of Estonia
        self[date(year, FEB, 24)] = "iseseisvuspäev"

        # Good Friday
        self[e - rd(days=2)] = "suur reede"

        # Easter Sunday
        self[e] = "ülestõusmispühade 1. püha"

        # Spring Day
        self[date(year, MAY, 1)] = "kevadpüha"

        # Pentecost
        self[e + rd(days=49)] = "nelipühade 1. püha"

        # Victory Day
        self[date(year, JUN, 23)] = "võidupüha"

        # Midsummer Day
        self[date(year, JUN, 24)] = "jaanipäev"

        # Day of Restoration of Independence
        self[date(year, AUG, 20)] = "taasiseseisvumispäev"

        # Christmas Eve
        self[date(year, DEC, 24)] = "jõululaupäev"

        # Christmas Day
        self[date(year, DEC, 25)] = "esimene jõulupüha"

        # Boxing Day
        self[date(year, DEC, 26)] = "teine jõulupüha"
Ejemplo n.º 21
0
def today():
    """Get the previous 24 hours.

    Returns:
        TYPE: Description
    """

    # 24 hours ago.
    from_date = dt.now() + rd(dt.now(), days=-1)

    # Get latest from date.
    records = get_latest(from_date)

    return Response(records, mimetype='application/json')
Ejemplo n.º 22
0
    def get_delta(self):
        """Get a delta object in order to add/remove a period on a datetime.

        :return: delta object in order to add/remove a period on a datetime.
        :rtype: relativedelta
        """

        unit_values = self.unit_values

        parameters = {(name + "s"): unit_values[name] for name in unit_values}

        result = rd(**parameters)

        return result
Ejemplo n.º 23
0
    def write(self, vals):
        '''This method is to set Discharge Date according to changes in.

        admission date or duration fields.
        '''
        addmissiondate = self.admission_date
        if vals.get('admission_date'):
            addmissiondate = datetime.strptime(vals.get('admission_date'),
                                               DEFAULT_SERVER_DATETIME_FORMAT)
        if vals.get('admission_date') or vals.get('duration'):
            duration_months = vals.get('duration') or self.duration
            discharge_date = addmissiondate + rd(months=duration_months)
            vals.update({'discharge_date': discharge_date})
        return super(HostelStudent, self).write(vals)
Ejemplo n.º 24
0
    def get_delta(self):
        """Get a delta object in order to add/remove a period on a datetime.

        :return: delta object in order to add/remove a period on a datetime.
        :rtype: relativedelta
        """

        unit_values = self.unit_values

        parameters = {(name + 's'): unit_values[name] for name in unit_values}

        result = rd(**parameters)

        return result
Ejemplo n.º 25
0
 def test_view_all_anon(self, render_template_patch, search_requests_form_patch):
     """
     Test render_template in request.views.view_all is called once for anonymous user.
     """
     with self.client:
         self.client.get('/request/view_all')
         render_template_patch.assert_called_once_with(
             'request/all.html',
             form=search_requests_form_patch(),
             holidays=sorted(get_holidays_date_list(
                 datetime.utcnow().year,
                 (datetime.utcnow() + rd(years=DEFAULT_YEARS_HOLIDAY_LIST)).year)
             )
         )
Ejemplo n.º 26
0
    def _populate(self, year):
        if year > 1987:
            self[date(year, JAN, 1)] = "New Year's Day"

            if year > 2017:
                # https://en.wikipedia.org/wiki/Robert_Gabriel_Mugabe_National_Youth_Day
                self[date(year, FEB,
                          21)] = "Robert Gabriel Mugabe National Youth Day"

            e = easter(year)
            good_friday = e - rd(days=2)
            easter_saturday = e - rd(days=1)
            easter_monday = e + rd(days=1)
            self[good_friday] = "Good Friday"
            self[easter_saturday] = "Easter Saturday"
            self[easter_monday] = "Easter Monday"

            self[date(year, APR, 18)] = "Independence Day"

            self[date(year, MAY, 1)] = "Workers' Day"
            self[date(year, MAY, 25)] = "Africa Day"

            # 2nd Monday of August
            # Find the date of the 2nd Monday
            # for the given year
            zimbabwe_heroes_day = date(year, AUG, 8)
            while zimbabwe_heroes_day.isoweekday() != MON and (
                    8 <= zimbabwe_heroes_day.day <= 14):
                zimbabwe_heroes_day = zimbabwe_heroes_day + rd(days=1)

            self[zimbabwe_heroes_day] = "Zimbabwe Heroes' Day"

            # 2nd Tuesday of August
            # Find the date of the 2nd Tuesday
            # for the given year
            defence_forces_day = datetime(year, AUG, 8)
            while defence_forces_day.isoweekday() != TUE and (
                    8 <= defence_forces_day.day <= 14):
                defence_forces_day = defence_forces_day + rd(days=1)

            self[defence_forces_day] = "Defense Forces Day"

            self[date(year, DEC, 22)] = "Unity Day"
            self[date(year, DEC, 25)] = "Christmas Day"
            self[date(year, DEC, 26)] = "Boxing Day"

            for k, v in list(self.items()):
                if self.observed and k.weekday() == SUN and k.year == year:
                    add_days = 1
                    while self.get(k + rd(days=add_days)) is not None:
                        add_days += 1
                    self[k + rd(days=add_days)] = v + " (Observed)"
Ejemplo n.º 27
0
    def _populate(self, year):
        # New years
        self[date(year, JAN, 1)] = "Nieuwjaarsdag"

        easter_date = easter(year)

        # Easter
        self[easter_date] = "Eerste paasdag"

        # Second easter day
        self[easter_date + rd(days=1)] = "Tweede paasdag"

        # Ascension day
        self[easter_date + rd(days=39)] = "Hemelvaart"

        # Pentecost
        self[easter_date + rd(days=49)] = "Eerste Pinksterdag"

        # Pentecost monday
        self[easter_date + rd(days=50)] = "Tweede Pinksterdag"

        # First christmas
        self[date(year, DEC, 25)] = "Eerste Kerstdag"

        # Second christmas
        self[date(year, DEC, 26)] = "Tweede Kerstdag"

        # Liberation day
        if year >= 1945 and year % 5 == 0:
            self[date(year, MAY, 5)] = "Bevrijdingsdag"

        # Kingsday
        if year >= 2014:
            kings_day = date(year, APR, 27)
            if kings_day.weekday() == SUN:
                kings_day = kings_day - rd(days=1)

            self[kings_day] = "Koningsdag"

        # Queen's day
        if 1891 <= year <= 2013:
            queens_day = date(year, APR, 30)
            if year <= 1948:
                queens_day = date(year, AUG, 31)

            if queens_day.weekday() == SUN:
                if year < 1980:
                    queens_day = queens_day + rd(days=1)
                else:
                    queens_day = queens_day - rd(days=1)

            self[queens_day] = "Koninginnedag"
Ejemplo n.º 28
0
    def _populate(self, year):

        eday = easter(year, method=EASTER_ORTHODOX)

        # New Years
        self[date(year, JAN, 1)] = "Πρωτοχρονιά [New Year's Day]"
        # Epiphany
        self[date(year, JAN, 6)] = "Θεοφάνεια [Epiphany]"

        # Clean Monday
        self[eday - rd(days=48)] = "Καθαρά Δευτέρα [Clean Monday]"

        # Independence Day
        self[date(year, MAR,
                  25)] = "Εικοστή Πέμπτη Μαρτίου [Independence Day Of Greece]"

        # Cyprus National Day
        self[date(year, APR, 1)] = "Cyprus National Day [Cyprus National Day ]"

        # Good Friday
        self[eday - rd(days=2)] = "Μεγάλη Παρασκευή [Good Friday]"

        # Holy Saturday
        self[eday - rd(days=1)] = "Μεγάλο Σάββατο [Holy Saturday]"

        # Holy Sunday Easter
        self[eday] = "Κυριακή του Πάσχα [Easter Sunday]"

        # Easter Monday
        self[eday + rd(days=1)] = "Δευτέρα του Πάσχα [Easter Monday]"

        # Easter Tuesday (Must Change)
        self[eday + rd(days=2)] = "Τρίτη του Πάσχα  [Easter Tuesday]"

        # Labour Day
        self[date(year, MAY, 1)] = "Εργατική Πρωτομαγιά [Labour day]"

        # Monday of the Holy Spirit
        self[eday + rd(days=50)] = \
            "Δευτέρα του Αγίου Πνεύματος [Monday of the Holy Spirit]"

        # Assumption of Mary
        self[date(year, AUG, 15)] = "Κοίμηση της Θεοτόκου [Assumption of Mary]"

        # Cyprus Independence Day
        self[date(year, OCT,
                  28)] = "Ημέρα Ανεξαρτησίας Κύπρου [Cyprus Independence Day ]"

        # Ochi Day
        self[date(year, OCT, 28)] = "Ημέρα του Όχι [Ochi Day]"

        # Christmas
        self[date(year, DEC, 25)] = "Χριστούγεννα [Christmas]"

        # Day after Christmas
        self[date(year, DEC, 26)] = \
            "Επόμενη ημέρα των Χριστουγέννων [Boxing Day]"
Ejemplo n.º 29
0
    def calc_wait_seconds(self, time_period_type_cd, use_utc=False, wait_seconds=0):
        """
        DESCRIPTION
        -----------
        Calculate the amount of time in seconds to the next interval given a
        time period frequency and the current timestamp.

        PARAMETERS
        ----------
        time_period_type_cd : str
            A string value representing the relative frequency of the interval
            used ("1-day", "1-week", "1-month")   
        wait_seconds : int (default=0)
            An optional amount of additional seconds to add to the timestamp at
            which the next interval takes place. 

        RETURNS
        -------
        A float value representing the number of seconds necessary to wait or sleep
        until the next interval timestamp is reached.

        MODIFICATIONS
        -------------
        Created : 4/22/19
        Modifed : 4/22/19
            - Incorporated option for use of UTC timestamp
        Modified : 4/30/19
            - Changed function name to calc_wait_seconds from get_next_interval_time
        """
        if use_utc == False:
            curr_ts = self.est_ts 
            begin_day = self.est_ts.replace(hour=0, minute=0, second=0, microsecond=0)
        elif use_utc == True:
            curr_ts = self.utc_ts 
            begin_day = self.utc_ts.replace(hour=0, minute=0, second=0, microsecond=0)

        if time_period_type_cd == "1-day":
            if (begin_day.weekday() <= 3) | (begin_day.weekday() == 6): # if current weekday is Sunday-Thurs
                next_interval = begin_day + td(days=1)
            else: # if current weekday is Friday-Saturday
                next_interval = begin_day.replace(hour=17 if use_utc == False else 22) + td(days=6-begin_day.weekday())
        elif time_period_type_cd == "1-week":            
            next_interval = begin_day.replace(hour=17 if use_utc == False else 22) + td(days=6-begin_day.weekday())                
        elif time_period_type_cd == "1-month":
            next_interval = begin_day.replace(day=1) + rd(months=1) 
            if next_interval.weekday() == 5: # if next interval lands on a Saturday, replace with market open Sunday
                next_interval = next_interval.replace(hour=17 if use_utc == False else 22) + td(days=1)
                print(next_interval)  
        return (next_interval - curr_ts).total_seconds() + wait_seconds
Ejemplo n.º 30
0
 def _get_season(self, local_now):
     '''
     returns the current liturgical season using local time
     '''
     baptism_of_our_lord = date(local_now.year, 1, 6) + rd(days=1,
                                                           weekday=SU(+1))
     ash_wednesday = easter(local_now.year) - rd(days=46)
     maundy_thursday = easter(local_now.year) - rd(days=3)
     pentecost = easter(local_now.year) + rd(days=49)
     first_sunday_of_advent = date(local_now.year, 12, 25) - rd(
         days=1, weekday=SU(-4))
     christmas = date(local_now.year, 12, 25)
     season = 'ORDINARY'
     if local_now.date() < baptism_of_our_lord:
         season = 'CHRISTMAS'
     elif local_now.date() >= baptism_of_our_lord and local_now.date(
     ) < ash_wednesday:
         season = 'ORDINARY'
     elif local_now.date() >= ash_wednesday and local_now.date(
     ) < maundy_thursday:
         season = 'LENT'
     elif local_now.date() >= maundy_thursday and local_now.date() < easter(
             local_now.year):
         season = 'TRIDUUM'
     elif local_now.date() >= easter(
             local_now.year) and local_now.date() < pentecost:
         season = 'EASTER'
     elif local_now.date() >= pentecost and local_now.date(
     ) < first_sunday_of_advent:
         season = 'ORDINARY'
     elif local_now.date() >= first_sunday_of_advent and local_now.date(
     ) < christmas:
         season = 'ADVENT'
     elif local_now.date() >= christmas:
         season = 'CHRISTMAS'
     return season
Ejemplo n.º 31
0
    def _populate(self, year):
        self[date(year, JAN, 1)] = "Deň vzniku Slovenskej republiky"
        self[date(year, JAN, 6)] = "Zjavenie Pána (Traja králi a" \
                                   " vianočnýsviatok pravoslávnych" \
                                   " kresťanov)"

        e = easter(year)
        self[e - rd(days=2)] = "Veľký piatok"
        self[e + rd(days=1)] = "Veľkonočný pondelok"

        self[date(year, MAY, 1)] = "Sviatok práce"

        if year >= 1997:
            self[date(year, MAY, 8)] = "Deň víťazstva nad fašizmom"

        self[date(year, JUL, 5)] = "Sviatok svätého Cyrila a svätého Metoda"

        self[date(year, AUG, 29)] = "Výročie Slovenského národného" \
                                    " povstania"

        self[date(year, SEP, 1)] = "Deň Ústavy Slovenskej republiky"

        self[date(year, SEP, 15)] = "Sedembolestná Panna Mária"
        if year == 2018:
            self[date(year, OCT, 30)] = "100. výročie prijatia" \
                " Deklarácie slovenského národa"
        self[date(year, NOV, 1)] = "Sviatok Všetkých svätých"

        if year >= 2001:
            self[date(year, NOV, 17)] = "Deň boja za slobodu a demokraciu"

        self[date(year, DEC, 24)] = "Štedrý deň"

        self[date(year, DEC, 25)] = "Prvý sviatok vianočný"

        self[date(year, DEC, 26)] = "Druhý sviatok vianočný"
Ejemplo n.º 32
0
    def _populate(self, year):
        if year > 1995:
            # https://www.ilo.org/dyn/travail/docs/2093/Public%20Holidays%20Act%201995.pdf
            self[date(year, JAN, 1)] = "New Year's Day"
            self[date(year, MAR, 11)] = "Moshoeshoe's Day"

            if year == 2002:
                # https://tinyurl.com/lesothourl
                self[date(year, APR, 4)] = "Heroes Day"
                self[date(year, MAY, 25)] = "Africa Day"

            if year < 2002:
                self[date(year, APR, 4)] = "Heroes Day"

            if year > 2002:
                self[date(year, MAY, 25)] = "Africa/Heroes Day"

            e = easter(year)
            good_friday = e - rd(days=2)
            easter_monday = e + rd(days=1)
            ascension_day = e + rd(days=39)

            self[good_friday] = "Good Friday"
            self[easter_monday] = "Easter Monday"
            self[ascension_day] = "Ascension Day"
            self[date(year, MAY, 1)] = "Workers' Day"

            if year > 1997:
                # https://en.wikipedia.org/wiki/Letsie_III
                self[date(year, JUL, 17)] = "King's Birthday"
            if year <= 1997:
                self[date(year, MAY, 2)] = "King's Birthday"

            self[date(year, OCT, 4)] = "National Independence Day"
            self[date(year, DEC, 25)] = "Christmas Day"
            self[date(year, DEC, 26)] = "Boxing Day"
Ejemplo n.º 33
0
    def _populate(self, year):
        # New Year's Day
        self[date(year, JAN, 1)] = "Año Nuevo [New Year's Day]"

        self[date(year, MAY, 1)] = "Dia Mundial del Trabajador"

        self[date(year, JUN, 24)] = "Batalla de Carabobo"

        self[date(year, JUL, 5)] = "Dia de la Independencia"

        self[date(year, JUL, 24)] = "Natalicio de Simón Bolívar"

        self[date(year, OCT, 12)] = "Día de la Resistencia Indígena"

        # Christmas Day
        self[date(year, DEC, 24)] = "Nochebuena"

        self[date(year, DEC, 25)] = "Día de Navidad"

        self[date(year, DEC, 31)] = "Fiesta de Fin de Año"

        # Semana Santa y Carnaval

        if date(year, APR, 19) == (easter(year) - rd(days=2)):
            self[
                easter(year) - rd(days=2)
            ] = "Viernes Santo y Declaración de la Independencia"
        else:
            # self[easter(year) - rd(weekday=FR(-1))] = "Viernes Santo"
            self[date(year, APR, 19)] = "Declaración de la Independencia"
            self[easter(year) - rd(days=2)] = "Viernes Santo"

        # self[easter(year) - rd(weekday=TH(-1))] = "Jueves Santo"

        if date(year, APR, 19) == (easter(year) - rd(days=3)):
            self[easter(year) - rd(days=3)] = (
                "Jueves Santo y Declaración " "de la Independencia"
            )
        else:
            # self[easter(year) - rd(weekday=FR(-1))] = "Viernes Santo"
            self[date(year, APR, 19)] = "Declaración de la Independencia"
            self[easter(year) - rd(days=3)] = "Jueves Santo"

        self[easter(year) - rd(days=47)] = "Martes de Carnaval"

        self[easter(year) - rd(days=48)] = "Lunes de Carnaval"
Ejemplo n.º 34
0
def whenord(m):
    try:
        if m.text == '22 months':
            User.ORDdate = User.BMTdate + rd(months=22) - dt.timedelta(days=1)
            update_user(m.chat.id, m.from_user.first_name, User.BMTdate,
                        User.ORDdate)
            ord_calculator(m)
        elif m.text == '24 months':
            User.ORDdate = User.BMTdate + rd(months=24) - dt.timedelta(days=1)
            update_user(m.chat.id, m.from_user.first_name, User.BMTdate,
                        User.ORDdate)
            ord_calculator(m)
        elif m.text == '/quit':
            bot.reply_to(
                m,
                f'Encik is sad to see you go..  *˚‧º·(˚ ˃̣̣̥᷄⌓˂̣̣̥᷅ )‧º·˚*',
                parse_mode='markdown')
            delete_user(m.chat.id)
        else:
            bot.reply_to(
                m,
                f'Semula, please key in only *"22 months"* or *"24 months"* or use the buttons.',
                parse_mode='markdown')
            bot.register_next_step_handler(m, whenord)

    except AttributeError:
        return

    except Exception as e:
        bot.reply_to(
            m,
            'Oooops! Please forward this to t.me/FakeEncikTan to report this bug #whenord'
        )
        print(e)
        print("whenord not working")
        return
Ejemplo n.º 35
0
    def _populate(self, year):
        # Observed since 1975
        # TODO do more research on history of Angolan holidays

        if year > 2018:
            self[date(year, MAR, 23)] = "Dia da Libertação da África Austral"

        if year > 1979:
            self[date(year, SEP, 17)] = "Dia do Herói Nacional"

        if year > 1974:
            self[date(year, 1, 1)] = "Ano novo"

            e = easter(year)
            good_friday = e - rd(days=2)
            self[good_friday] = "Sexta-feira Santa"

            # carnival is the Tuesday before Ash Wednesday
            # which is 40 days before easter excluding sundays
            carnival = e - rd(days=46)
            while carnival.weekday() != TUE:
                carnival = carnival - rd(days=1)
            self[carnival] = "Carnaval"

            self[date(year, FEB, 4)] = "Dia do Início da Luta Armada"
            self[date(year, MAR, 8)] = "Dia Internacional da Mulher"
            self[date(year, APR, 4)] = "Dia da Paz e Reconciliação"
            self[date(year, MAY, 1)] = "Dia Mundial do Trabalho"
            self[date(year, SEP, 17)] = "Dia dos Heroes Nacional"
            self[date(year, NOV, 2)] = "Dia dos Finados"
            self[date(year, NOV, 11)] = "Dia da Independência"
            self[date(year, DEC, 25)] = "Dia de Natal e da Família"

        # As of 1995/1/1, whenever a public holiday falls on a Sunday,
        # it rolls over to the following Monday
        # Since 2018 when a public holiday falls on the Tuesday or Thursday
        # the Monday or Friday is also a holiday
        for k, v in list(self.items()):
            if self.observed and year > 1974:
                if k.weekday() == SUN:
                    self[k + rd(days=1)] = v + " (Observed)"
            if self.observed and year > 2017:
                if k.weekday() == SUN:
                    pass
            if self.observed and year > 2017:
                if k.weekday() == TUE:
                    self[k - rd(days=1)] = v + " (Day off)"
                elif k.weekday() == THU:
                    self[k + rd(days=1)] = v + " (Day off)"
            if self.observed and year > 1994 and k.weekday() == SUN:
                self[k + rd(days=1)] = v + " (Observed)"
Ejemplo n.º 36
0
    def _populate(self, year):
        self[date(year, JAN, 1)] = "Ano Novo"

        e = easter(year)

        # carnival is no longer a holiday, but some companies let workers off.
        # @todo recollect the years in which it was a public holiday
        # self[e - rd(days=47)] = "Carnaval"
        self[e - rd(days=2)] = "Sexta-feira Santa"
        self[e] = "Páscoa"

        # Revoked holidays in 2013–2015
        if year < 2013 or year > 2015:
            self[e + rd(days=60)] = "Corpo de Deus"
            self[date(year, OCT, 5)] = "Implantação da República"
            self[date(year, NOV, 1)] = "Dia de Todos os Santos"
            self[date(year, DEC, 1)] = "Restauração da Independência"

        self[date(year, 4, 25)] = "Dia da Liberdade"
        self[date(year, 5, 1)] = "Dia do Trabalhador"
        self[date(year, 6, 10)] = "Dia de Portugal"
        self[date(year, 8, 15)] = "Assunção de Nossa Senhora"
        self[date(year, DEC, 8)] = "Imaculada Conceição"
        self[date(year, DEC, 25)] = "Dia de Natal"
Ejemplo n.º 37
0
 def onchange_day_to_return_book(self):
     ''' This method calculate a book return date.
     @param self : Object Pointer
     @param cr : Database Cursor
     @param uid : Current Logged in User
     @param ids : Current Records
     @param name : Functional field's name
     @param args : Other arguments
     @param context : standard Dictionary
     @return : Dictionary having identifier of the record as key
               and the book return date as value'''
     t = "%Y-%m-%d %H:%M:%S"
     diff = rd(days=self.day_to_return_book or 0.0)
     if self.date_issue and diff:
         ret_date = datetime.strptime(self.date_issue, t) + diff
         self.date_return = ret_date
Ejemplo n.º 38
0
 def get_header_data(self, data):
     attend_month = self.env['student.attendance.by.month'].browse(
         self._context.get('active_id'))
     start_dt = datetime.strptime(attend_month.month.date_start, '%Y-%m-%d')
     end_dt = datetime.strptime(attend_month.month.date_stop, '%Y-%m-%d')
     #        delta = end_dt - start_dt
     data_dict = {}
     day_list = []
     week_day_list = []
     while start_dt <= end_dt:
         week_day = start_dt.strftime('%a')
         week_day_list.append(week_day)
         day_list.append(start_dt.day)
         start_dt = start_dt + rd(days=1)
     data_dict.update({'week_day': week_day_list, 'day_list': day_list})
     return [data_dict]
Ejemplo n.º 39
0
 def _compute_penalty(self):
     ''' This method calculate a penalty on book .
     @return : Dictionary having identifier of the record as key
               and penalty as value
     '''
     for line in self:
         if line.date_return:
             start_day = datetime.strptime(line.actual_return_date.strftime('%Y-%m-%d %H:%M:%S'),
                                           DEFAULT_SERVER_DATETIME_FORMAT)
             end_day = datetime.strptime(line.date_return.strftime('%Y-%m-%d %H:%M:%S'),
                                         DEFAULT_SERVER_DATETIME_FORMAT)
             if start_day > end_day:
                 diff = rd(start_day.date(), end_day.date())
                 day = float(diff.days) or 0.0
                 if line.day_to_return_book:
                     line.penalty = day * line.name.fine_late_return or 0.0
Ejemplo n.º 40
0
    def _populate(self, year):
        """
        Populates holidays for the specified year.

        :param year: the calendar year.
        """
        # Populate with built-in holidays.
        holidays.UnitedStates._populate(self, year)

        # Add SLO County specific holidays.
        additional_holidays = {
            "Lincoln's Birthday":   date(year, 2, 12),
            'Thanksgiving Holiday': date(year, 11, 1) + rd(weeks=3, weekday=FR),
        }

        for holiday_name, holiday_date in additional_holidays.iteritems():
            self._set_observed(holiday_name, holiday_date)
Ejemplo n.º 41
0
 def __keytransform__(self, key):
     if isinstance(key, datetime):
         key = key.date()
     elif isinstance(key, date):
         key = key
     elif isinstance(key, int) or isinstance(key, float):
         key = datetime.fromtimestamp(key).date()
     elif isinstance(key, str) or isinstance(key, unicode):
         try:
             key = parse(key).date()
         except TypeError:
             raise ValueError("Cannot parse date from string '%s'" % key)
     else:
         raise TypeError("Cannot convert type '%s' to date." % type(key))
     # Treat Dec 31 as part of the next year
     # because it can be an Observed date for New Year's Day
     year = (key+rd(days=+1)).year
     if self.expand and year not in self.years:
         self.years.add(year)
         self._populate(year)
     return key
Ejemplo n.º 42
0
def get_date_by_relative_str(curdate, relativestr):
    """
    get new date by adding relative date/time given in relativestr to curdate

    >>> print get_date_by_relative_str(date(2014,01,15), "1w")
    2014-01-22
    >>> print get_date_by_relative_str(date(2014,01,31), "4w")
    2014-02-28
    >>> print get_date_by_relative_str(date(2014,07,17), "mon")
    2014-07-21
    >>> print get_date_by_relative_str(date(2014,07,17), "mo")
    2014-07-21
    >>> print get_date_by_relative_str(date(2014,07,21), "mo")
    2014-07-28
    >>> print get_date_by_relative_str(date(2014,07,17), "mond")
    2014-07-21
    >>> print get_date_by_relative_str(date(2014,07,17), "monday")
    2014-07-21
    >>> print get_date_by_relative_str(date(2014,07,17), "10d")
    2014-07-27
    >>> print get_date_by_relative_str(date(2014,07,31), "2m")
    2014-09-30
    >>> print get_date_by_relative_str(date(2012,02,29), "3y")
    2015-02-28
    >>> print get_date_by_relative_str(date(2014,02,01), "04-25")
    2014-04-25
    >>> print get_date_by_relative_str(date(2014,02,01), "25")
    2014-02-25
    >>> print get_date_by_relative_str(date(2014,02,01), "01")
    2014-03-01
    >>> print get_date_by_relative_str(date(2014,02,01), "1")
    2014-03-01
    >>> print get_date_by_relative_str(date(2014,02,05), "1")
    2014-03-01
    >>> print get_date_by_relative_str(date(2014,02,01), "jan14")
    2015-01-14
    >>> print get_date_by_relative_str(date(2014,02,01), "december-25")
    2014-12-25
    >>> print get_date_by_relative_str(date(2014,02,01), "2014-1-1")
    2014-01-01
    >>> print get_date_by_relative_str(date(2014,02,01), "2015-12-31")
    2015-12-31
    >>> print get_date_by_relative_str(date(2014,02,01), "tom")
    2014-02-02
    >>> print get_date_by_relative_str(date(2014,02,01), "tomorrow")
    2014-02-02
    >>> print get_date_by_relative_str(datetime(2014,02,01,12,30,59), "tomorrow")
    2014-02-02 12:30:59
    >>> print get_date_by_relative_str(datetime(2014,02,01,12,30,59), "tom#1000")
    2014-02-02 10:00:00
    >>> print get_date_by_relative_str(datetime(2014,07,17,12,30,59), "mo#10")
    2014-07-21 10:00:00
    >>> print get_date_by_relative_str(datetime(2014,07,17,12,30,59), "4-3#1035")
    2014-04-03 10:35:00
    >>> print get_date_by_relative_str(datetime(2014,02,01,12,30,59), "t#2014")
    2014-02-01 20:14:00
    >>> print get_date_by_relative_str(date(2014,02,05), "today")
    2014-02-05
    """

    DATE_MATCHERS = dict({
        r"to?d?a?y?$"                         : lambda d, m: d,
        r"tomo?r?r?o?w?"                      : lambda d, m: d + rd(days=1),
        r"mon?d?a?y?"                         : lambda d, m: (d + rd(weekday=MO)) if (d + rd(weekday=MO) > d) else (d + rd(weekday=MO(2))),   # use next weekday if the result is not in the future
        r"tue?s?d?a?y?"                       : lambda d, m: (d + rd(weekday=TU)) if (d + rd(weekday=TU) > d) else (d + rd(weekday=TU(2))),
        r"wed?n?e?s?d?a?y?"                   : lambda d, m: (d + rd(weekday=WE)) if (d + rd(weekday=WE) > d) else (d + rd(weekday=WE(2))),
        r"thu?r?s?d?a?y?"                     : lambda d, m: (d + rd(weekday=TH)) if (d + rd(weekday=TH) > d) else (d + rd(weekday=TH(2))),
        r"fri?d?a?y?"                         : lambda d, m: (d + rd(weekday=FR)) if (d + rd(weekday=FR) > d) else (d + rd(weekday=FR(2))),
        r"sat?u?r?d?a?y?"                     : lambda d, m: (d + rd(weekday=SA)) if (d + rd(weekday=SA) > d) else (d + rd(weekday=SA(2))),
        r"sun?d?a?y?"                         : lambda d, m: (d + rd(weekday=SU)) if (d + rd(weekday=SU) > d) else (d + rd(weekday=SA(2))),
        r"^([0-9]+)d"                         : lambda d, m: d + rd(days=int(m[0])), 
        r"^([0-9]+)w"                         : lambda d, m: d + rd(weeks=int(m[0])), 
        r"^([0-9]+)m"                         : lambda d, m: d + rd(months=int(m[0])), 
        r"^([0-9]+)y"                         : lambda d, m: d + rd(years=int(m[0])), 
        r"^([0-9]{1,2})$"                     : lambda d, m: (d + rd(day=int(m[0]))) if (d + rd(day=int(m[0])) > d) else (d + rd(months=1, day=int(m[0]))),
        r"^([0-9]{1,2})-([0-9]{1,2})$"        : lambda d, m: d + rd(month=int(m[0]),day=int(m[1])),
        r"janu?a?r?y?-?([0-9]{,2})"           : lambda d, m: (d + rd(month=1,  day=int(m[0]))) if (d + rd(month=1,  day=int(m[0])) > d) else (d + rd(years=1, month=1,  day=int(m[0]))),
        r"febr?u?a?r?y?-?([0-9]{,2})"         : lambda d, m: (d + rd(month=2,  day=int(m[0]))) if (d + rd(month=2,  day=int(m[0])) > d) else (d + rd(years=1, month=2,  day=int(m[0]))),
        r"marc?h?-?([0-9]{,2})"               : lambda d, m: (d + rd(month=3,  day=int(m[0]))) if (d + rd(month=3,  day=int(m[0])) > d) else (d + rd(years=1, month=3,  day=int(m[0]))),
        r"apri?l?-?([0-9]{,2})"               : lambda d, m: (d + rd(month=4,  day=int(m[0]))) if (d + rd(month=4,  day=int(m[0])) > d) else (d + rd(years=1, month=4,  day=int(m[0]))),
        r"may-?([0-9]{,2})"                   : lambda d, m: (d + rd(month=5,  day=int(m[0]))) if (d + rd(month=5,  day=int(m[0])) > d) else (d + rd(years=1, month=5,  day=int(m[0]))),
        r"june?-?([0-9]{,2})"                 : lambda d, m: (d + rd(month=6,  day=int(m[0]))) if (d + rd(month=6,  day=int(m[0])) > d) else (d + rd(years=1, month=6,  day=int(m[0]))),
        r"july?-?([0-9]{,2})"                 : lambda d, m: (d + rd(month=7,  day=int(m[0]))) if (d + rd(month=7,  day=int(m[0])) > d) else (d + rd(years=1, month=7,  day=int(m[0]))),
        r"augu?s?t?-?([0-9]{,2})"             : lambda d, m: (d + rd(month=8,  day=int(m[0]))) if (d + rd(month=8,  day=int(m[0])) > d) else (d + rd(years=1, month=8,  day=int(m[0]))),
        r"sept?e?m?b?e?r?-?([0-9]{,2})"       : lambda d, m: (d + rd(month=9,  day=int(m[0]))) if (d + rd(month=9,  day=int(m[0])) > d) else (d + rd(years=1, month=9,  day=int(m[0]))),
        r"octo?b?e?r?-?([0-9]{,2})"           : lambda d, m: (d + rd(month=10, day=int(m[0]))) if (d + rd(month=10, day=int(m[0])) > d) else (d + rd(years=1, month=10, day=int(m[0]))),
        r"nove?m?b?e?r?-?([0-9]{,2})"         : lambda d, m: (d + rd(month=11, day=int(m[0]))) if (d + rd(month=11, day=int(m[0])) > d) else (d + rd(years=1, month=11, day=int(m[0]))),
        r"dece?m?b?e?r?-?([0-9]{,2})"         : lambda d, m: (d + rd(month=12, day=int(m[0]))) if (d + rd(month=12, day=int(m[0])) > d) else (d + rd(years=1, month=12, day=int(m[0]))),
        r"([0-9]{4})-([0-9]{,2})-([0-9]{,2})" : lambda d, m: d + rd(year=int(m[0]), month=int(m[1]), day=int(m[2]))    
    })

    TIME_MATCHERS = dict({
        r"([0-9]{2})"                : lambda d, m: d + rd(hour=int(m[0]), minute=0, second=0),
        r"([0-9]{2})([0-9]{2})"      : lambda d, m: d + rd(hour=int(m[0]), minute=int(m[1]), second=0),
    })

    if '#' in relativestr:
        daterelativestr, timerelativestr = relativestr.split("#", 2)
    else:
        daterelativestr = relativestr
        timerelativestr = None

    retval = None

    for datepatternstr, dateevaluator in DATE_MATCHERS.iteritems():
        matchgr = re.match(datepatternstr, daterelativestr)
        if matchgr:
            retval = dateevaluator(curdate, matchgr.groups())
            break

    if timerelativestr:
        for timepatternstr, timeevaluator in TIME_MATCHERS.iteritems():
            matchgr = re.match(timepatternstr, timerelativestr)
            if matchgr:
                retval = timeevaluator(retval, matchgr.groups())

    return retval
Ejemplo n.º 43
0
 def __add__(self, other):
     other_class = other.__class__
     if isinstance(other, relativedelta):
         ret = rd.__add__(self, other)
         ret.__class__ = self.__class__
         for attr in ('bdays', 'bhours', 'bminutes', 'bseconds'):
             if getattr(self, attr, None) is not None:
                 if getattr(other, attr, None) is not None:
                     setattr(ret, attr,
                             getattr(self, attr) + getattr(other, attr))
                 else:
                     setattr(ret, attr, getattr(self, attr))
             elif getattr(other, attr, None) is not None:
                 setattr(ret, attr, getattr(other, attr))
         return ret
     # If we are adding any time (not just dates) the ret object to return
     # must be a datetime object; a date object will not work
     if isinstance(other, date) and not isinstance(other, datetime) \
             and (getattr(self, 'bhours', 0) or
                  getattr(self, 'bminutes', 0) or
                  getattr(self, 'bseconds', 0) or
                  getattr(self, 'hours', 0) or
                  getattr(self, 'minutes', 0) or
                  getattr(self, 'seconds', 0) or
                  getattr(self, 'microseconds', 0) or
                  getattr(self, 'hour', 0) or
                  getattr(self, 'minute', 0) or
                  getattr(self, 'second', 0) or
                  getattr(self, 'microsecond', 0)):
         other = datetime.combine(other, datetime.min.time())
         other_class = other.__class__
     if isinstance(other, time):
         other = datetime.combine(date.today(), other)
     for attr in ('bseconds', 'bminutes', 'bhours', 'bdays'):
         if getattr(self, attr, None) is not None:
             while other.weekday() not in self.workdays \
                     or other in self.holidays:
                 other += rd(days=+1)
             while attr != "bdays" and \
                     (other.time() < self.btstart or
                      other.time() >= self.btend):
                 other += rd(**{attr[1:]: +1})
             i = getattr(self, attr)
             a = +1 if i > 0 else -1
             while i != 0:
                 other += rd(**{attr[1:]: a})
                 while other.weekday() not in self.workdays \
                         or other in self.holidays:
                     other += rd(days=a)
                 while attr != "bdays" and \
                         (other.time() < self.btstart or
                          other.time() >= self.btend):
                     other += rd(**{attr[1:]: a})
                 i -= a
     ret = rd.__add__(self, other)
     # Ensure when relativedelta is added to `other` object that it returns
     # the same type of object as `other`
     if ret.__class__ != other_class:
         if issubclass(other_class, datetime):
             ret = other_class(*(ret.timetuple()[:6] +
                                 (ret.microsecond, ret.tzinfo)))
         elif issubclass(other_class, date):
             ret = other_class(*(ret.timetuple()[:3]))
         elif issubclass(other_class, time):
             ret = other_class(ret.hour, ret.minute, ret.second,
                               ret.microsecond, ret.tzinfo)
     return ret
Ejemplo n.º 44
0
 def __init__(self, dt1=None, dt2=None, bdays=None, holidays=None,
              bhours=None, bminutes=None, bseconds=None,
              btstart=None, btend=None, weekdays_off=None, *args, **kwargs):
     self.holidays = holidays
     if self.holidays is None:
         self.holidays = getattr(relativedelta, 'holidays', ())
     self.weekdays_off = weekdays_off
     if self.weekdays_off is None:
         self.weekdays_off = getattr(relativedelta, 'weekdays_off', (5, 6))
     self.btstart = btstart
     if self.btstart is None:
         self.btstart = getattr(relativedelta, 'btstart', time(9))
     self.btend = btend
     if self.btend is None:
         self.btend = getattr(relativedelta, 'btend', time(17))
     if dt1 and dt2:
         # Convert to datetime objects
         dt1 = parse(dt1)
         dt2 = parse(dt2)
         if isinstance(dt1, date) and not isinstance(dt1, datetime):
             dt1 = datetime.combine(dt1, datetime.min.time())
         elif isinstance(dt1, time):
             dt1 = datetime.combine(datetime.now(), dt1)
         if isinstance(dt2, date) and not isinstance(dt2, datetime):
             dt2 = datetime.combine(dt2, datetime.min.time())
         elif isinstance(dt2, time):
             dt2 = datetime.combine(datetime.now(), dt2)
         # Call super init before setting self.bdays to avoid base __radd__
         # from calling child __add__ and creating infinite loop
         rd.__init__(self, dt1, dt2, *args, **kwargs)
         c = defaultdict(int)
         d1 = max(dt1, dt2)
         d2 = min(dt1, dt2)
         if d1.weekday() in self.weekdays_off or d1 in self.holidays:
             c['bdays'] += 1
         for attr in ('bhours', 'bminutes', 'bseconds'):
             while getattr(d1, attr[1:-1]) != getattr(d2, attr[1:-1]):
                 d2 += rd(**{attr[1:]: +1})
                 if d2.time() >= self.btstart and d2.time() < self.btend:
                     c[attr] += 1
         while d1 > d2:
             d2 += rd(days=+1)
             if d2.weekday() not in self.weekdays_off and d2 not in self.holidays:
                 c['bdays'] += 1
         self.bdays = c['bdays']
         self.bhours = c['bhours']
         self.bminutes = c['bminutes']
         self.bseconds = c['bseconds']
         if dt2 > dt1:
             self.bdays *= -1
             self.bhours *= -1
             self.bminutes *= -1
             self.bseconds *= -1
     else:
         self.bdays = bdays
         self.bhours = bhours
         self.bminutes = bminutes
         self.bseconds = bseconds
         bd = rd(datetime.combine(datetime.now(), self.btend),
                 datetime.combine(datetime.now(), self.btstart))
         if isinstance(self.bdays, float):
             self.bhours = self.bhours or 0
             self.bhours += (self.bdays % 1) * \
                            (bd.hours + bd.minutes / 60 +
                             bd.seconds / 60 / 60)
             self.bdays = int(math.floor(self.bdays))
             if self.bdays == 0:
                 self.bdays = None
         if isinstance(self.bhours, float):
             self.bminutes = self.bminutes or 0
             self.bminutes += (self.bhours % 1) * 60
             self.bhours = int(math.floor(self.bhours))
             if self.bhours == 0:
                 self.bhours = None
         if isinstance(self.bminutes, float):
             self.bseconds = self.bseconds or 0
             self.bseconds += int((self.bminutes % 1) * 60)
             self.bminutes = int(math.floor(self.bminutes))
             if self.bminutes == 0:
                 self.bminutes = None
         rd.__init__(self, dt1, dt2, *args, **kwargs)
Ejemplo n.º 45
0
 def __init__(self, dt1=None, dt2=None, bdays=None,
              bhours=None, bminutes=None, bseconds=None,
              holidays=None, workdays=None, btstart=None, btend=None,
              *args, **kwargs):
     self.holidays = holidays
     if self.holidays is None:
         self.holidays = bdateutil.HOLIDAYS
     self.workdays = workdays
     if self.workdays is None:
         self.workdays = bdateutil.WORKDAYS
     if not self.workdays or self.workdays[0] not in range(7):
         raise ValueError("workdays must contain integers 0-6")
     self.btstart = btstart
     if self.btstart is None:
         self.btstart = bdateutil.BTSTART
     self.btend = btend
     if self.btend is None:
         self.btend = bdateutil.BTEND
     if not isinstance(self.btstart, time):
         raise TypeError("btstart must be of type time")
     if not isinstance(self.btend, time):
         raise TypeError("btend must be of type time")
     if self.btstart >= self.btend:
         raise ValueError("btend must be greater than btstart")
     if dt1 and dt2:
         # Convert to datetime objects
         dt1 = parse(dt1)
         dt2 = parse(dt2)
         if isinstance(dt1, date) and not isinstance(dt1, datetime):
             dt1 = datetime.combine(dt1, datetime.min.time())
         elif isinstance(dt1, time):
             dt1 = datetime.combine(datetime.now(), dt1)
         if isinstance(dt2, date) and not isinstance(dt2, datetime):
             dt2 = datetime.combine(dt2, datetime.min.time())
         elif isinstance(dt2, time):
             dt2 = datetime.combine(datetime.now(), dt2)
         # Call super init before setting self.bdays to avoid base __radd__
         # from calling child __add__ and creating infinite loop
         rd.__init__(self, dt1, dt2, *args, **kwargs)
         c = defaultdict(int)
         d1 = max(dt1, dt2)
         d2 = min(dt1, dt2)
         if d1.weekday() not in self.workdays or d1 in self.holidays:
             c['bdays'] += 1
         for attr in ('bhours', 'bminutes', 'bseconds'):
             while getattr(d1, attr[1:-1]) != getattr(d2, attr[1:-1]):
                 d2 += rd(**{attr[1:]: +1})
                 if d2.time() >= self.btstart and d2.time() < self.btend:
                     c[attr] += 1
         while d1 > d2:
             d2 += rd(days=+1)
             if d2.weekday() in self.workdays and d2 not in self.holidays:
                 c['bdays'] += 1
         self.bdays = c['bdays']
         self.bhours = c['bhours']
         self.bminutes = c['bminutes']
         self.bseconds = c['bseconds']
         if dt2 > dt1:
             self.bdays *= -1
             self.bhours *= -1
             self.bminutes *= -1
             self.bseconds *= -1
     else:
         self.bdays = bdays
         self.bhours = bhours
         self.bminutes = bminutes
         self.bseconds = bseconds
         bd = rd(datetime.combine(datetime.now(), self.btend),
                 datetime.combine(datetime.now(), self.btstart))
         if isinstance(self.bdays, float):
             self.bhours = self.bhours or 0
             self.bhours += (self.bdays % 1) * \
                            (bd.hours + bd.minutes / 60 +
                             bd.seconds / 60 / 60)
             self.bdays = int(math.floor(self.bdays))
             if self.bdays == 0:
                 self.bdays = None
         if isinstance(self.bhours, float):
             self.bminutes = self.bminutes or 0
             self.bminutes += (self.bhours % 1) * 60
             self.bhours = int(math.floor(self.bhours))
             if self.bhours == 0:
                 self.bhours = None
         if isinstance(self.bminutes, float):
             self.bseconds = self.bseconds or 0
             self.bseconds += int((self.bminutes % 1) * 60)
             self.bminutes = int(math.floor(self.bminutes))
             if self.bminutes == 0:
                 self.bminutes = None
         rd.__init__(self, dt1, dt2, *args, **kwargs)
Ejemplo n.º 46
0
    def command(self):
        config=load_config(self.args)
        from ebetl.lib.views import get_dailytotals,get_dailymenuitems, sync_do, sync_dmi, sync_lilliput, print_fact_dmi
        if self.options.fromd:
            fromd = dt.strptime(self.options.fromd, "%Y%m%d")
        if self.options.tod:
            tod = dt.strptime(self.options.tod, "%Y%m%d") + td(days=1)
        else:
            try:
                tod = fromd + td(days=1)
            except:
                pass
        if self.options.items:
            #(u'000351', 1, u'351 ARQUATA', 2014, 1, 2, 1, u'PANETTERIA', 17, u'PANETTERIA', 207.73120000000006, 8.308799999999996, 216.03999999999996)
            retly_tmp = get_dailymenuitems(fromd - rd(years=1), tod - rd(years=1))
            retly = []
            for r in retly_tmp:
                row = list(r)
                row[3] = row[3]+1
                retly.append(row)
            maply = get_map(retly)
            ret = get_dailymenuitems(fromd, tod)
            mapcy = get_map(ret)
            results = []
            for k in ret:
                pdv = k[0]
                y = k[3]                
                m = k[4]
                d = k[5]
                acc_num=k[6]
                rep_num=k[8]
                try:
                    ly = maply[pdv][y][m][d][acc_num][rep_num]
                    ly = ly[10:]
                    
                except:
                    ly = ["0","0","0"]
                results.append(list(k)+list(ly)) 
            for k in retly:
                pdv = k[0]
                y = k[3]                
                m = k[4]
                d = k[5]
                acc_num=k[6]
                rep_num=k[8]
                try:
                    mapcy[pdv][y][m][d][acc_num][rep_num]                    
                except:
                    results.append(k[0:10]+["0","0","0"]+k[10:])                 
            #for i in results:
            #    p = [str(j).replace('.',',') for j in i]
            #    print "|".join(p)   
            sync_dmi(results)                                                                                              

        elif not self.options.sync and not self.options.printr:    
            # (u'000297', 2013, 1, 8, 396, 14.901287878787729, 5396.611399999985, 504.2985999999985, 5900.909999999941)
            retly_tmp = get_dailytotals(fromd - rd(years=1), tod - rd(years=1))
            retly = []
            for r in retly_tmp:
                row = list(r)
                row[1] = row[1]+1
                retly.append(row)            
            maply = get_map_do(retly)
            ret = get_dailytotals(fromd, tod)
            mapcy = get_map_do(ret)
            
            results = []
            
            for k in ret:
                pdv = k[0]
                y = k[1]
                m = k[2]
                d = k[3]
                
                try:
                    ly = maply[pdv][y][m][d]
                    ly = ly[4:]
                    
                except:
                    ly = ["0","0","0","0","0"]
                results.append(list(k)+list(ly)) 
            for k in retly:
                pdv = k[0]
                y = k[1]
                m = k[2]
                d = k[3]
                try:
                    mapcy[pdv][y][m][d]           
                except:
                    results.append(k[0:4]+["0","0","0","0","0"]+k[4:])                 
            #for i in results:
            #    p = [str(j).replace('.',',') for j in i]
            #    print "|".join(p)
            sync_do(results)
            #print results                          
        if self.options.sync:
            sync_lilliput()
        if self.options.printr:
            from prettytable import PrettyTable
            ret, tot = print_fact_dmi('000351', fromd, tod)            
            print tot
            x = PrettyTable(["Famiglia", "Tot AC", "Tot AP", "Diff"])
            x.align["Famiglia"] = "l" 
            x.align["Tot"] = "r" 
            x.align["Tot AC"] = "r"             
            x.align["Tot AP"] = "r"             
            x.align["Diff"] = "r"              
            x.padding_width = 1 # One space between column edges and contents (default)
            x.float_format = '.2'
            for r in ret:
                x.add_row(r)
            for t in tot:
                t_lst = ['TOTALE'] + [i for i in t]
                x.add_row(t_lst)
                       
            print x
Ejemplo n.º 47
0
    def _log_progress(self, queue, documents, start, end):
        count = queue.get_queue_count()
        doc_count = len(documents)

        self._log.info(queue.get_id() + ':Combinations: ' + str(count))
        self._log.info(queue.get_id() + ':There are ' + str(count * doc_count) + ' steps to go (docs * combinations)')
        if (start and end):
            time_range = (end - start).total_seconds()
            time_range = time_range * count
            # No proper average this is very rough
            fmt = '{0.days} days {0.hours} hours {0.minutes} minutes {0.seconds} seconds'
            self._log.info(queue.get_id() + ':Rough estimated time left:' + str(fmt.format(rd(seconds=time_range))))
Ejemplo n.º 48
0
def extended_denmark(years=False, sun=False, moon=False, week=False,
                     time=False, outformat='text'):
    """Extends the official public holidays of Denmark"""

    # Populate the holiday list with the default DK holidays
    holidays_dk = holidays.Denmark(years=years)

    # Extend with other dates
    for year in years:
        if week:
            weeknumbers = WeekNumber(year)
            for key in weeknumbers.weeknumbers:
                holidays_dk.append({key: weeknumbers.weeknumbers[key]})

        if sun:
            sun_rise_sun_set = SunRiseSunSet(year)
            for key in sorted(sun_rise_sun_set.sun_rise_sun_set):
                holidays_dk.append({key:
                                       sun_rise_sun_set.sun_rise_sun_set[key]})

        if moon:
            moon_phases = MoonPhases(year, outformat=outformat)
            for key in sorted(moon_phases.moon_phases):
                holidays_dk.append({key: moon_phases.moon_phases[key]})

        # Equinoxes and solstices
        spring_equinox = ephem.next_equinox(str(year))
        summer_solstice = ephem.next_solstice(spring_equinox)
        fall_equinox = ephem.next_equinox(summer_solstice)
        winter_solstice = ephem.next_solstice(fall_equinox)
        # Bright nights, nights when sun is not under 18 deg below horizon
        brightnights = bright_nights(year)
        holidays_dk.append({brightnights[0]: 'Lyse nætter begynder'})
        holidays_dk.append({brightnights[1]: 'Lyse nætter slutter'})

        if time:
            holidays_dk.append({utc2localtime(spring_equinox.datetime()):
                           'Forårsjævndøgn %s' %
                       utc2localtime(spring_equinox.datetime(),
                                     format='hhmm')})
            holidays_dk.append({utc2localtime(summer_solstice.datetime()):
                           'Sommersolhverv %s' %
                       utc2localtime(summer_solstice.datetime(),
                                     format='hhmm')})
            holidays_dk.append({utc2localtime(fall_equinox.datetime()):
                           'Efterårsjævndøgn %s' %
                       utc2localtime(fall_equinox.datetime(),
                                     format='hhmm')})
            holidays_dk.append({utc2localtime(winter_solstice.datetime()):
                           'Vintersolhverv %s' %
                       utc2localtime(winter_solstice.datetime(),
                                     format='hhmm')})
        else:
            holidays_dk.append({utc2localtime(spring_equinox.datetime()): 'Forårsjævndøgn'})
            holidays_dk.append({utc2localtime(summer_solstice.datetime()): 'Sommersolhverv'})
            holidays_dk.append({utc2localtime(fall_equinox.datetime()): 'Efterårsjævndøgn'})
            holidays_dk.append({utc2localtime(winter_solstice.datetime()): 'Vintersolhverv'})

        # Add other Danish holidays and events
        holidays_dk.append({datetime.date(year, 1, 6): 'Helligtrekonger'})
        holidays_dk.append({datetime.date(year, 2, 2): 'Kyndelmisse'})
        holidays_dk.append({datetime.date(year, 2, 14): 'Valentinsdag'})
        holidays_dk.append({datetime.date(year, 3, 8): 'Kvindernes internationale kampdag'})
        holidays_dk.append({easter(year) + rd(weekday=SU(-8)): 'Fastelavn'})
        holidays_dk.append({easter(year) + rd(weekday=SU(-2)): 'Palmesøndag'})
        holidays_dk.append({datetime.date(year, 4, 9): 'Danmarks besættelse (1940)'})
        holidays_dk.append({datetime.date(year, 3, 31) + rd(weekday=SU(-1)): 'Sommertid begynder'}) # Last sunday in March
        holidays_dk.append({datetime.date(year, 5, 1) + rd(weekday=SU(+2)): 'Mors dag'})
        holidays_dk.append({datetime.date(year, 5, 1): 'Arbejdernes internationale kampdag'})
        holidays_dk.append({datetime.date(year, 5, 9): 'Europadag'})
        holidays_dk.append({datetime.date(year, 6, 15): 'Valdemarsdag'})
        holidays_dk.append({datetime.date(year, 6, 23): 'Sankthansaften'})
        holidays_dk.append({datetime.date(year, 6, 24): 'Sankthansdag'})
        holidays_dk.append({datetime.date(year, 5, 4): 'Danmarks befrielsesaften'})
        holidays_dk.append({datetime.date(year, 5, 5): 'Danmarks befrielse (1945)'})
        holidays_dk.append({datetime.date(year, 6, 5): 'Fars dag'})
        holidays_dk.append({datetime.date(year, 6, 5): 'Grundlovsdag'})
        holidays_dk.append({datetime.date(year, 10, 31): 'Halloween'})
        holidays_dk.append({datetime.date(year, 11, 10): 'Mortensaften'})
        holidays_dk.append({datetime.date(year, 11, 11): 'Mortensdag'})
        holidays_dk.append({datetime.date(year, 11, 1) + rd(weekday=SU(+1)): 'Allehelgensdag'})
        holidays_dk.append({datetime.date(year, 10, 31) + rd(weekday=SU(-1)): 'Sommertid slutter'}) # Last sunday in October
        holidays_dk.append({datetime.date(year, 12, 13): 'Sankta Lucia'})
        for i in range(4):
            holidays_dk.append({datetime.date(year, 12, 24) +
                                rd(weekday=SU(-(i+1))):
                                    '%s. søndag i advent' % abs(4-i)})

        holidays_dk.append({datetime.date(year, 12, 24): 'Juleaftensdag'})
        holidays_dk.append({datetime.date(year, 12, 31): 'Nytårsaftensdag'})

    return holidays_dk
Ejemplo n.º 49
0
    def _populate(self, year):
        if self.country == "US":
            # New Year's Day
            if year > 1870:
                self[date(year, 1, 1)] = "New Year's Day"
                if self.observed and date(year,1,1).weekday() == 5:
                    self[date(year,1,1)+rd(days=-1)] = "New Year's Day (Observed)"
                elif self.observed and date(year,1,1).weekday() == 6:
                    self[date(year,1,1)+rd(days=+1)] = "New Year's Day (Observed)"

            # Martin Luther King, Jr. Day
            if year >= 1986:
                self[date(year, 1, 1)+rd(weekday=MO(+3))] = "Martin Luther King, Jr. Day"

            # Washington's Birthday
            if year > 1970:
                self[date(year, 2, 1)+rd(weekday=MO(+3))] = "Washington's Birthday"
            elif year >= 1879:
                self[date(year, 2,22)] = "Washington's Birthday"

            # Memorial Day
            if year > 1970:
                self[date(year, 5,31)+rd(weekday=MO(-1))] = "Memorial Day"
            elif year >= 1888:
                self[date(year, 5,30)] = "Memorial Day"

            # Independence Day
            if year > 1870:
                self[date(year, 7, 4)] = "Independence Day"
                if self.observed and date(year,7,4).weekday() == 5:
                    self[date(year,7,4)+rd(days=-1)] = "Independence Day (Observed)"
                elif self.observed and date(year,7,4).weekday() == 6:
                    self[date(year,7,4)+rd(days=+1)] = "Independence Day (Observed)"

            # Labor Day
            if year >= 1894:
                self[date(year, 9, 1)+rd(weekday=MO)] = "Labor Day"

            # Columbus Day
            if year >= 1970:
                self[date(year,10, 1)+rd(weekday=MO(+2))] = "Columbus Day"
            elif year >= 1937:
                self[date(year,10,12)] = "Columbus Day"

            # Veterans Day
            if year > 1953:
                name = "Veterans Day"
            else:
                name = "Armistice Day"
            if 1978 > year > 1970:
                self[date(year,10, 1)+rd(weekday=MO(+4))] = name
            elif year >= 1938:
                self[date(year,11,11)] = name
                if self.observed and  date(year,11,11).weekday() == 5:
                    self[date(year,11,11)+rd(days=-1)] = name + " (Observed)"
                elif self.observed and date(year,11,11).weekday() == 6:
                    self[date(year,11,11)+rd(days=+1)] = name + " (Observed)"

            # Thanksgiving
            if year > 1870:
                self[date(year,11, 1)+rd(weekday=TH(+4))] = "Thanksgiving"

            # Christmas Day
            if year > 1870:
                self[date(year,12,25)] = "Christmas Day"
                if self.observed and  date(year,12,25).weekday() == 5:
                    self[date(year,12,25)+rd(days=-1)] = "Christmas Day (Observed)"
                elif self.observed and date(year,12,25).weekday() == 6:
                    self[date(year,12,25)+rd(days=+1)] = "Christmas Day (Observed)"

        elif self.country == "CA":
            # New Year's Day
            if year >= 1867:
                self[date(year, 1, 1)] = "New Year's Day"
                if self.observed and date(year,1,1).weekday() == 5:
                    self[date(year,1,1)+rd(days=-1)] = "New Year's Day (Observed)"
                elif self.observed and date(year,1,1).weekday() == 6:
                    self[date(year,1,1)+rd(days=+1)] = "New Year's Day (Observed)"

            # Islander Day
            if self.prov == 'PE' and year >= 2010:
                self[date(year,2,1)+rd(weekday=MO(+3))] = "Islander Day"
            elif self.prov == 'PE' and year == 2009:
                self[date(year,2,1)+rd(weekday=MO(+2))] = "Islander Day"

            # Family Day / Louis Riel Day (MB)
            if self.prov in ('AB','SK','ON') and year >= 2008:
                self[date(year,2,1)+rd(weekday=MO(+3))] = "Family Day"
            elif self.prov in ('AB','SK') and year >= 2007:
                self[date(year,2,1)+rd(weekday=MO(+3))] = "Family Day"
            elif self.prov == 'AB' and year >= 1990:
                self[date(year,2,1)+rd(weekday=MO(+3))] = "Family Day"
            elif self.prov == 'BC' and year >= 2013:
                self[date(year,2,1)+rd(weekday=MO(+2))] = "Family Day"
            elif self.prov == 'MB' and year >= 2008:
                self[date(year,2,1)+rd(weekday=MO(+3))] = "Louis Riel Day"

            # St. Patrick's Day
            if self.prov == 'NL' and year >= 1900:
                dt = date(year,3,17)
                # Nearest Monday to March 17
                dt1 = date(year,3,17)+rd(weekday=MO(-1))
                dt2 = date(year,3,17)+rd(weekday=MO(+1))
                if dt2 - dt <= dt - dt1:
                    self[dt2] = "St. Patrick's Day"
                else:
                    self[dt1] = "St. Patrick's Day"

            # Good Friday
            if self.prov != 'QC' and year >= 1867:
                self[easter(year)+rd(weekday=FR(-1))] = "Good Friday"

            # Easter Monday
            if self.prov == 'QC' and year >= 1867:
                self[easter(year)+rd(weekday=MO)] = "Easter Monday"

            # St. George's Day
            if self.prov == 'NL' and year == 2010:
                # 4/26 is the Monday closer to 4/23 in 2010
                # but the holiday was observed on 4/19? Crazy Newfies!
                self[date(2010,4,19)] = "St. George's Day"
            elif self.prov == 'NL' and year >= 1990:
                dt = date(year,4,23)
                # Nearest Monday to April 23
                dt1 = dt+rd(weekday=MO(-1))
                dt2 = dt+rd(weekday=MO(+1))
                if dt2 - dt < dt - dt1:
                    self[dt2] = "St. George's Day"
                else:
                    self[dt1] = "St. George's Day"

            # Victoria Day / National Patriotes Day (QC)
            if self.prov not in ('NB', 'NS', 'PE', 'NL','QC') and year >= 1953:
                self[date(year,5,24)+rd(weekday=MO(-1))] = "Victoria Day"
            elif self.prov == 'QC' and year >= 1953:
                self[date(year,5,24)+rd(weekday=MO(-1))] = "National Patriotes Day"

            # National Aboriginal Day
            if self.prov == 'NT' and year >= 1996:
                self[date(year,6,21)] = "National Aboriginal Day"

            # St. Jean Baptiste Day
            if self.prov == 'QC' and year >= 1925:
                self[date(year,6,24)] = "St. Jean Baptiste Day"
                if self.observed and date(year,6,24).weekday() == 6:
                    self[date(year,6,25)] = "St. Jean Baptiste Day (Observed)"

            # Discovery Day
            if self.prov == 'NL' and year >= 1997:
                dt = date(year,6,24)
                # Nearest Monday to June 24
                dt1 = dt+rd(weekday=MO(-1))
                dt2 = dt+rd(weekday=MO(+1))
                if dt2 - dt <= dt - dt1:
                    self[dt2] = "Discovery Day"
                else:
                    self[dt1] = "Discovery Day"
            elif self.prov == 'YU' and year >= 1912:
                self[date(year,8,1)+rd(weekday=MO(+3))] = "Discovery Day"

            # Canada Day / Memorial Day (NL)
            if self.prov != 'NL' and year >= 1867:
                self[date(year,7,1)] = "Canada Day"
                if self.observed and date(year,7,1).weekday() in (5,6):
                    self[date(year,7,1)+rd(weekday=MO)] = "Canada Day (Observed)"
            elif year >= 1867:
                self[date(year,7,1)] = "Memorial Day"
                if self.observed and date(year,7,1).weekday() in (5,6):
                    self[date(year,7,1)+rd(weekday=MO)] = "Memorial Day (Observed)"

            # Nunavut Day
            if self.prov == 'NU' and year >= 2001:
                self[date(year,7,9)] = "Nunavut Day"
                if self.observed and date(year,7,9).weekday() == 6:
                    self[date(year,7,10)] = "Nunavut Day (Observed)"
            elif self.prov == 'NU' and year == 2000:
                self[date(2000,4,1)] = "Nunavut Day"

            # Civic Holiday
            if self.prov in ('SK','ON','MB','NT') and year >= 1900:
                self[date(year,8,1)+rd(weekday=MO)] = "Civic Holiday"
            elif self.prov in ('BC') and year >= 1974:
                self[date(year,8,1)+rd(weekday=MO)] = "British Columbia Day"

            # Labour Day
            if year >= 1894:
                self[date(year,9,1)+rd(weekday=MO)] = "Labour Day"

            # Thanksgiving
            if self.prov not in ('NB','NS','PE','NL') and year >= 1931:
                self[date(year,10,1)+rd(weekday=MO(+2))] = "Thanksgiving"

            # Remembrance Day
            if self.prov not in ('ON','QC','NS','NL','NT','PE','SK') and year >= 1931:
                self[date(year,11,11)] = "Remembrance Day"
            elif self.prov in ('NS','NL','NT','PE','SK') and year >= 1931:
                self[date(year,11,11)] = "Remembrance Day"
                if self.observed and date(year,11,11).weekday() == 6:
                    self[date(year,11,11)+rd(weekday=MO)] = "Remembrance Day (Observed)"

            # Christmas Day
            if year >= 1867:
                self[date(year,12,25)] = "Christmas Day"
                if self.observed and date(year,12,25).weekday() == 5:
                    self[date(year,12,24)] = "Christmas Day (Observed)"
                elif self.observed and date(year,12,25).weekday() == 6:
                    self[date(year,12,26)] = "Christmas Day (Observed)"

            # Boxing Day
            if year >= 1867:
                if self.observed and date(year,12,26).weekday() in (5,6):
                    self[date(year,12,26)+rd(weekday=MO)] = "Boxing Day (Observed)"
                elif self.observed and date(year,12,26).weekday() == 0:
                    self[date(year,12,27)] = "Boxing Day (Observed)"
                else:
                    self[date(year,12,26)] = "Boxing Day"
Ejemplo n.º 50
0
 def __init__(self):
    self.relativedelta = {\
       'S5': rd(seconds = 5), 'S10': rd(seconds = 10), 'S15': rd(seconds = 15),\
       'S30': rd(seconds = 30), 'M1': rd(minutes = 1), 'M2': rd(minutes = 2),\
       'M3': rd(minutes = 3), 'M4': rd(minutes = 4), 'M5': rd(minutes = 5),\
       'M10': rd(minutes = 10), 'M15': rd(minutes = 15), 'M30': rd(minutes = 30),\
       'H1': rd(hours = 1), 'H2': rd(hours = 2), 'H3': rd(hours = 3),\
       'H4': rd(hours = 4), 'H6': rd(hours = 6), 'H8': rd(hours = 8), \
       'H12': rd(hours = 12), 'D': rd(days = 1), 'W': rd(weeks = 1),\
       'M': rd(months = 1)}   
Ejemplo n.º 51
0
def signalGenerator(tradeInfo, priceClass, eventQueue, strategyParameters):
   #should implement mid prices
    q_sma = strategyParameters.q_sma
    s_sma = strategyParameters.s_sma
    

    while(True):#init values
        if(eventQueue.queue):
            previous_quick_sma = (eventQueue.queue[0]['mid'] + sum(priceClass.mid_Prices[-(q_sma-1):]))/q_sma
            previous_slow_sma = (eventQueue.queue[0]['mid'] + sum(priceClass.mid_Prices[-(s_sma-1):]))/s_sma
            eventQueue.dequeue()
            break


    


    while(True):
        if(eventQueue.queue):

            

            new_tick = eventQueue.queue[0]['mid']
            eventQueue.dequeue()

            quick_sma = (new_tick + sum(priceClass.mid_Prices[-(q_sma-1):]))/q_sma        
            slow_sma = (new_tick + sum(priceClass.mid_Prices[-(s_sma-1):]))/s_sma
            #print(new_tick, quick_sma, slow_sma)




            

            if(quick_sma - slow_sma > 0 and previous_quick_sma - previous_slow_sma <= 0):
                #trade only when sma's crossover by a significant amount (arbitrary 0.5 pips)

                trade_details = orderRequest(tradeInfo, 'buy', 100000)
                trade_details = json.loads(trade_details)

                if(trade_details['tradeOpened']):
                    modifyTrade(tradeInfo, trade_details['tradeOpened']['id'], trailingStop = 5)
                else:
                    print("No trade to modify")

                print("Bought 1 unit of EUR_USD")
                print(new_tick, '     ', "quick_sma = ", quick_sma, '    ', "slow_sma = ", slow_sma)   
                winsound.Beep(600,500)
             
                

            elif(quick_sma - slow_sma < 0 and previous_quick_sma - previous_slow_sma >= 0):
                trade_details = orderRequest(tradeInfo, 'sell', 100000)
                trade_details = json.loads(trade_details)

                if(trade_details['tradeOpened']):
                    modifyTrade(tradeInfo, trade_details['tradeOpened']['id'], trailingStop = 5)
                else:
                    print("No trade to modify")

                print("Sold 1 unit of EUR_USD")
                print(new_tick, '     ', "quick_sma = ", quick_sma, '    ', "slow_sma = ", slow_sma)
                winsound.Beep(400,500)



            previous_quick_sma = quick_sma
            previous_slow_sma = slow_sma

            print('new_tick: ', new_tick, 'quick_sma: ', quick_sma)
            print('slow_sma: ', slow_sma, '\n')
            
        yield datetime.utcnow() + rd(seconds = 1/(len(eventQueue.queue)+1))
Ejemplo n.º 52
0
         print(get_currentsong(server, port, password))
 elif option == "stats":
     if servername == None:
         print("Error: Missing server name. Run "+sys.argv[0]+" help for help.")
     else:
         server = get_config(servername, "server")
         port = get_config(servername, "port")
         password = get_config(servername, "password")
         npquery = check_np(server, port, password)
         stats = npquery[2]
         songs = stats.get("songs")
         artists = stats.get("artists")
         albums = stats.get("albums")
         playtime = stats.get("db_playtime")
         fmt = '{0.days} days, {0.hours} hours, {0.minutes} minutes, {0.seconds} seconds'
         human_playtime = fmt.format(rd(seconds=int(playtime)))
         human_playtime = str(human_playtime)
         print("MPD Database Stats: "+songs+" songs, "+artists+" artists, "+albums+" albums. Total Playtime: "+human_playtime+".")
 elif option == "debug":
     if servername == None:
         print("Error: Missing server name. Run "+sys.argv[0]+" help for help.")
     else:
         server = get_config(servername, "server")
         port = get_config(servername, "port")
         password = get_config(servername, "password")
         npquery = check_np(server, port, password)
         print(npquery)
 elif option == "control":
     if servername == None:
         print("Error: Missing server name. Run "+sys.argv[0]+" help for help.")
     else:
Ejemplo n.º 53
0
def view(request_id):
    """
    This function is for testing purposes of the view a request back until backend functionality is implemented.

    :return: redirect to view request page
    """
    try:
        current_request = Requests.query.filter_by(id=request_id).one()
        assert current_request.agency.is_active
    except NoResultFound:
        print("Request with id '{}' does not exist.".format(request_id))
        sentry.captureException()
        return abort(404)
    except AssertionError:
        print("Request belongs to inactive agency.")
        sentry.captureException()
        return abort(404)

    holidays = sorted(get_holidays_date_list(
        datetime.utcnow().year,
        (datetime.utcnow() + rd(years=DEFAULT_YEARS_HOLIDAY_LIST)).year)
    )

    active_users = []
    assigned_users = []
    if current_user.is_agency:
        for agency_user in current_request.agency.active_users:
            if not agency_user in current_request.agency.administrators and (agency_user != current_user):
                # populate list of assigned users that can be removed from a request
                if agency_user in current_request.agency_users:
                    assigned_users.append(agency_user)
                # append to list of active users that can be added to a request
                else:
                    active_users.append(agency_user)

    permissions = {
        'acknowledge': permission.ACKNOWLEDGE,
        'deny': permission.DENY,
        'extend': permission.EXTEND,
        'close': permission.CLOSE,
        're_open': permission.RE_OPEN,
        'add_file': permission.ADD_FILE,
        'edit_file_privacy': permission.EDIT_FILE_PRIVACY,
        'delete_file': permission.DELETE_FILE,
        'add_note': permission.ADD_NOTE,
        'edit_note_privacy': permission.EDIT_NOTE_PRIVACY,
        'delete_note': permission.DELETE_NOTE,
        'add_link': permission.ADD_LINK,
        'edit_link_privacy': permission.EDIT_LINK_PRIVACY,
        'delete_link': permission.DELETE_LINK,
        'add_instructions': permission.ADD_OFFLINE_INSTRUCTIONS,
        'edit_instructions_privacy': permission.EDIT_OFFLINE_INSTRUCTIONS_PRIVACY,
        'delete_instructions': permission.DELETE_OFFLINE_INSTRUCTIONS,
        'generate_letter': permission.GENERATE_LETTER,
        'add_user': permission.ADD_USER_TO_REQUEST,
        'edit_user': permission.EDIT_USER_REQUEST_PERMISSIONS,
        'remove_user': permission.REMOVE_USER_FROM_REQUEST,
        'edit_title': permission.EDIT_TITLE,
        'edit_title_privacy': permission.CHANGE_PRIVACY_TITLE,
        'edit_agency_request_summary': permission.EDIT_AGENCY_REQUEST_SUMMARY,
        'edit_agency_request_summary_privacy': permission.CHANGE_PRIVACY_AGENCY_REQUEST_SUMMARY,
        'edit_requester_info': permission.EDIT_REQUESTER_INFO
    }

    # Build permissions dictionary for checking on the front-end.
    for key, val in permissions.items():
        if current_user.is_anonymous or not current_request.user_requests.filter_by(
                user_guid=current_user.guid).first():
            permissions[key] = False
        else:
            permissions[key] = is_allowed(current_user, request_id, val) if not current_user.is_anonymous else False

    # Build dictionary of current permissions for all assigned users.
    assigned_user_permissions = {}
    for u in assigned_users:
        assigned_user_permissions[u.guid] = UserRequests.query.filter_by(
            request_id=request_id, user_guid=u.guid).one().get_permission_choice_indices()

    point_of_contact = get_current_point_of_contact(request_id)
    if point_of_contact:
        current_point_of_contact = {'user_guid': point_of_contact.user_guid}
    else:
        current_point_of_contact = {'user_guid': ''}

    # Determine if the Agency Request Summary should be shown.
    show_agency_request_summary = False

    if current_user in current_request.agency_users \
            or current_request.agency_request_summary \
            and (current_request.requester == current_user
                 and current_request.status == request_status.CLOSED
                 and not current_request.privacy['agency_request_summary']
                 or current_request.status == request_status.CLOSED
                 and current_request.agency_request_summary_release_date
                 and current_request.agency_request_summary_release_date
                 < datetime.utcnow()
                 and not current_request.privacy['agency_request_summary']):
        show_agency_request_summary = True

    # Determine if the title should be shown.
    show_title = (current_user in current_request.agency_users or
                  current_request.requester == current_user or
                  not current_request.privacy['title'])

    # Determine if "Generate Letter" functionality is enabled for the agency.
    if 'letters' in current_request.agency.agency_features:
        generate_letters_enabled = current_request.agency.agency_features['letters']['generate_letters']
    else:
        generate_letters_enabled = False

    # Determine if custom request forms are enabled
    if 'enabled' in current_request.agency.agency_features['custom_request_forms']:
        custom_request_forms_enabled = current_request.agency.agency_features['custom_request_forms']['enabled']
    else:
        custom_request_forms_enabled = False

    # Determine if custom request form panels should be expanded by default
    if 'expand_by_default' in current_request.agency.agency_features['custom_request_forms']:
        expand_by_default = current_request.agency.agency_features['custom_request_forms']['expand_by_default']
    else:
        expand_by_default = False

    # Determine if request description should be hidden when custom forms are enabled
    if 'description_hidden_by_default' in current_request.agency.agency_features['custom_request_forms']:
        description_hidden_by_default = current_request.agency.agency_features['custom_request_forms']['description_hidden_by_default']
    else:
        description_hidden_by_default = False

    return render_template(
        'request/view_request.html',
        request=current_request,
        status=request_status,
        agency_users=current_request.agency_users,
        edit_requester_form=EditRequesterForm(current_request.requester),
        contact_agency_form=ContactAgencyForm(current_request),
        deny_request_form=DenyRequestForm(current_request.agency.ein),
        close_request_form=CloseRequestForm(current_request.agency.ein),
        reopen_request_form=ReopenRequestForm(current_request.agency.ein),
        remove_user_request_form=RemoveUserRequestForm(assigned_users),
        add_user_request_form=AddUserRequestForm(active_users),
        edit_user_request_form=EditUserRequestForm(assigned_users),
        generate_acknowledgment_letter_form=GenerateAcknowledgmentLetterForm(current_request.agency.ein),
        generate_denial_letter_form=GenerateDenialLetterForm(current_request.agency.ein),
        generate_closing_letter_form=GenerateClosingLetterForm(current_request.agency.ein),
        generate_extension_letter_form=GenerateExtensionLetterForm(current_request.agency.ein),
        generate_envelope_form=GenerateEnvelopeForm(current_request.agency_ein, current_request.requester),
        generate_response_letter_form=GenerateResponseLetterForm(current_request.agency.ein),
        assigned_user_permissions=assigned_user_permissions,
        current_point_of_contact=current_point_of_contact,
        holidays=holidays,
        assigned_users=assigned_users,
        active_users=active_users,
        permissions=permissions,
        show_agency_request_summary=show_agency_request_summary,
        show_title=show_title,
        is_requester=(current_request.requester == current_user),
        permissions_length=len(permission.ALL),
        generate_letters_enabled=generate_letters_enabled,
        custom_request_forms_enabled = custom_request_forms_enabled,
        expand_by_default=expand_by_default,
        description_hidden_by_default=description_hidden_by_default
    )
Ejemplo n.º 54
0
    def _populate(self, year):
        # New Year's Day
        if year > 1870:
            name = "New Year's Day"
            self[date(year, 1, 1)] = name
            if self.observed and date(year, 1, 1).weekday() == 6:
                self[date(year, 1, 1) + rd(days=+1)] = name + " (Observed)"
            elif self.observed and date(year, 1, 1).weekday() == 5:
                # Add Dec 31st from the previous year without triggering
                # the entire year to be added
                expand = self.expand
                self.expand = False
                self[date(year, 1, 1) + rd(days=-1)] = name + " (Observed)"
                self.expand = expand
            # The next year's observed New Year's Day can be in this year
            # when it falls on a Friday (Jan 1st is a Saturday)
            if self.observed and date(year, 12, 31).weekday() == 4:
                self[date(year, 12, 31)] = name + " (Observed)"

        # Martin Luther King, Jr. Day
        if year >= 1986:
            name = "Martin Luther King, Jr. Day"
            self[date(year, 1, 1) + rd(weekday=MO(+3))] = name

        # Washington's Birthday
        name = "Washington's Birthday"
        if year > 1970:
            self[date(year, 2, 1) + rd(weekday=MO(+3))] = name
        elif year >= 1879:
            self[date(year, 2, 22)] = name

        # Memorial Day
        if year > 1970:
            self[date(year, 5, 31) + rd(weekday=MO(-1))] = "Memorial Day"
        elif year >= 1888:
            self[date(year, 5, 30)] = "Memorial Day"

        # Independence Day
        if year > 1870:
            name = "Independence Day"
            self[date(year, 7, 4)] = name
            if self.observed and date(year, 7, 4).weekday() == 5:
                self[date(year, 7, 4) + rd(days=-1)] = name + " (Observed)"
            elif self.observed and date(year, 7, 4).weekday() == 6:
                self[date(year, 7, 4) + rd(days=+1)] = name + " (Observed)"

        # Labor Day
        if year >= 1894:
            self[date(year, 9, 1) + rd(weekday=MO)] = "Labor Day"

        # Columbus Day
        name = "Columbus Day"
        if year >= 1970:
            self[date(year, 10, 1) + rd(weekday=MO(+2))] = name
        elif year >= 1937:
            self[date(year, 10, 12)] = name

        # Election Day
        if year >= 2015:
            dt = date(year, 11, 1) + rd(weekday=MO)
            self[dt + rd(days=+1)] = "Election Day"

        # Veterans Day
        if year > 1953:
            name = "Veterans Day"
        else:
            name = "Armistice Day"
        if 1978 > year > 1970:
            self[date(year, 10, 1) + rd(weekday=MO(+4))] = name
        elif year >= 1938:
            self[date(year, 11, 11)] = name
            if self.observed and date(year, 11, 11).weekday() == 5:
                self[date(year, 11, 11) + rd(days=-1)] = name + " (Observed)"
            elif self.observed and date(year, 11, 11).weekday() == 6:
                self[date(year, 11, 11) + rd(days=+1)] = name + " (Observed)"

        # Thanksgiving
        if year > 1870:
            self[date(year, 11, 1) + rd(weekday=TH(+4))] = "Thanksgiving"

        # Christmas Day
        if year > 1870:
            name = "Christmas Day"
            self[date(year, 12, 25)] = "Christmas Day"
            if self.observed and date(year, 12, 25).weekday() == 5:
                self[date(year, 12, 25) + rd(days=-1)] = name + " (Observed)"
            elif self.observed and date(year, 12, 25).weekday() == 6:
                self[date(year, 12, 25) + rd(days=+1)] = name + " (Observed)"