예제 #1
0
def _main(cmd):
    year = cmd.year
    head = cmd.head
    tail = cmd.tail
    path = sos.path.join(sos.expanded_path(cmd.diary), "%4.4d" % year)
    Y = CAL.Year(year)
    file_name = sos.path.join(path, cmd.filename)
    pdf_name = Filename(cmd.pdf or ("plan_%s.pdf" % year), ".pdf").name
    head = cmd.head or 1
    tail = cmd.tail or 12
    if cmd.monthly:
        Plan = [PDF_Plan_Month, PDF_Plan_Month_L][bool(cmd.landscape)]
    elif cmd.Yearly:
        Plan = [PDF_Plan_Year, PDF_Plan_Year_L][bool(cmd.landscape)]
    else:
        Plan = [PDF_Plan_Week, PDF_Plan_Week_L][bool(cmd.landscape)]
        head = cmd.head or 0
        tail = cmd.tail or -1
        wd = Y.weeks[0].number
        if tail < 0:
            tail += len(Y.weeks)
        head -= wd
        tail += 1 - wd
    CAL.read_plan(Y, file_name)
    Plan \
        ( Y, pdf_name, head, tail
        , xl  = cmd.XL
        , yl  = cmd.YL
        , xo  = cmd.XO
        , yo  = cmd.YO
        )
예제 #2
0
파일: pdf.py 프로젝트: Tapyr/tapyr
def _main (cmd) :
    year      = cmd.year
    head      = cmd.head
    tail      = cmd.tail
    path      = sos.path.join (sos.expanded_path (cmd.diary), "%4.4d" % year)
    Y         = CAL.Year  (year)
    file_name = sos.path.join (path, cmd.filename)
    pdf_name  = Filename (cmd.pdf or ("plan_%s.pdf" % year), ".pdf").name
    head      = cmd.head or 1
    tail      = cmd.tail or 12
    if cmd.monthly :
        Plan  = [PDF_Plan_Month, PDF_Plan_Month_L] [bool (cmd.landscape)]
    elif cmd.Yearly :
        Plan  = [PDF_Plan_Year, PDF_Plan_Year_L] [bool (cmd.landscape)]
    else :
        Plan  = [PDF_Plan_Week, PDF_Plan_Week_L] [bool (cmd.landscape)]
        head  = cmd.head or 0
        tail  = cmd.tail or -1
        wd    = Y.weeks [0].number
        if tail < 0 :
            tail += len (Y.weeks)
        head -= wd
        tail += 1 - wd
    CAL.read_plan (Y, file_name)
    Plan \
        ( Y, pdf_name, head, tail
        , xl  = cmd.XL
        , yl  = cmd.YL
        , xo  = cmd.XO
        , yo  = cmd.YO
        )
예제 #3
0
파일: Plan.py 프로젝트: Tapyr/tapyr
def write_plan (Y, plan_file_name, replace = False) :
    today = CAL.Date_Time ()
    tail  = today.formatted ("%d.%m.%Y.%H:%M")
    if replace :
        sos.rename (plan_file_name, "%s-%s" % (plan_file_name, tail))
    else :
        plan_file_name = "%s.%s" % (plan_file_name, tail)
    CAL.write_year (Y.as_plan, plan_file_name, force = replace)
예제 #4
0
파일: Plan.py 프로젝트: xiaochang91/tapyr
def write_plan(Y, plan_file_name, replace=False):
    today = CAL.Date_Time()
    tail = today.formatted("%d.%m.%Y.%H:%M")
    if replace:
        sos.rename(plan_file_name, "%s-%s" % (plan_file_name, tail))
    else:
        plan_file_name = "%s.%s" % (plan_file_name, tail)
    CAL.write_year(Y.as_plan, plan_file_name, force=replace)
예제 #5
0
 def _from_string_time (cls, s, ** kw) :
     future = kw.get ("future")
     date   = kw.get ("date")   or CAL.Date ()
     now    = kw.get ("time")   or CAL.Time ()
     time   = CAL.Time.from_string (s)
     if future and time < now :
         date += 1
     return cls.combine (date, time)
예제 #6
0
class Service_Unavailable (Server_Error) :
    """The server is currently unable to handle the request due to a
       temporary overloading or maintenance of the server.
    """

    status_code = 503
    retry_after = CAL.Date_Time_Delta (minutes = 3)

    _spec       = \
        """ The implication is that this is a temporary condition which will
            be alleviated after some delay. If known, the length of the delay
            MAY be indicated in a Retry-After header. If no Retry-After is
            given, the client SHOULD handle the response as it would for a
            500 response.

              Note: The existence of the 503 status code does not imply that
              a server must use it when becoming overloaded. Some servers may
              wish to simply refuse the connection.
        """

    def _add_response_headers (self, resource, request, response) :
        self.__super._add_response_headers (resource, request, response)
        try :
            retry_after = self.retry_after
        except AttributeError :
            pass
        else :
            if isinstance (retry_after, CAL.Date_Time_Delta) :
                retry_after = CAL.Date_Time ().as_utc () + retry_after
            if retry_after is not None :
                response.set_header ("Retry-After", retry_after)
예제 #7
0
 def atax (self) :
     date    = self.date.formatted ("%d.%m")
     km      = self.km_business
     f       = 0.42 ### 0.42 Euro/km
     if self.date < CAL.Date_Time (2008, 7, 1) :
         f   = 0.38
     return self.atax_format % (date, f * km, km)
예제 #8
0
파일: Plan.py 프로젝트: xiaochang91/tapyr
def _main(cmd):
    year = cmd.year
    path = sos.path.join(sos.expanded_path(cmd.diary), "%4.4d" % year)
    Y = CAL.Year(year)
    file_name = sos.path.join(path, cmd.filename)
    sort = cmd.sort
    read_plan(Y, file_name)
    if cmd.add_appointment:
        sort = len(cmd.argv)
        for a in cmd.argv:
            if app_pat.match(a.strip()):
                _add_appointment(Y, app_pat, cmd.holidays_too)
            else:
                print("%s doesn't match an appointment" % a)
    if cmd.Show:
        for a in cmd.argv:
            if app_pat.match(a.strip()):
                print(a)
                pat_match = app_pat
                day, month, year, time = _date_time(Y, pat_match)
                for D in _day_generator(pat_match, day, month, year, Y):
                    print("   ", D)
            else:
                print("%s doesn't match an appointment" % a)
    if sort:
        Y.sort_appointments()
        write_plan(Y, file_name, cmd.replace)
예제 #9
0
파일: Period.py 프로젝트: JPilarr/tapyr
 def __iter__ (self) :
     d = CAL.Date_Delta (1)
     f = self.finis
     s = self.start
     while s <= f :
         yield s
         s += d
예제 #10
0
파일: Plan.py 프로젝트: xiaochang91/tapyr
def _date_time(Y, pat_match):
    if pat_match.date or pat_match.time:
        today = CAL.Date()
        if pat_match.weekday:
            wd = pat_match.weekday.lower()
            wk = int(pat_match.week or today.week)
            d = getattr(Y.weeks[wk - Y.weeks[0].number], wd).date
            if (pat_match.week is None) and d.rjd < today.rjd:
                d += 7
            day = d.day
            month = d.month
            year = d.year
        else:
            day = int(pat_match.day or today.day)
            month = int(pat_match.month or today.month)
            year = int(pat_match.year or today.year)
        time = pat_match.time or ""
        if time:
            if pat_match.hh_head:
                hh = int(pat_match.hh_head)
                mm = int(pat_match.mm_head or 0)
                time = "%2.2d:%2.2d" % (hh, mm)
                if pat_match.hh_tail:
                    hh = int(pat_match.hh_tail)
                    mm = int(pat_match.mm_tail or 0)
                    time = "%s-%2.2d:%2.2d" % (time, hh, mm)
        return day, month, year, time
    else:
        raise ValueError("`%s` must specify either date or time")
예제 #11
0
파일: Plan.py 프로젝트: xiaochang91/tapyr
def _add_appointment(Y, pat_match, holidays_too):
    day, month, year, time = _date_time(Y, pat_match)
    app = (CAL.Appointment.format %
           (time, pat_match.prio or " ", pat_match.activity))
    for D in _day_generator(pat_match, day, month, year, Y):
        if D.is_holiday and not holidays_too:
            continue
        D.add_appointments(*CAL.appointments(app))
예제 #12
0
파일: Plan.py 프로젝트: Tapyr/tapyr
def _add_appointment (Y, pat_match, holidays_too) :
    day, month, year, time = _date_time (Y, pat_match)
    app = ( CAL.Appointment.format
          % (time, pat_match.prio or " ", pat_match.activity)
          )
    for D in _day_generator (pat_match, day, month, year, Y) :
        if D.is_holiday and not holidays_too :
            continue
        D.add_appointments (* CAL.appointments (app))
예제 #13
0
 def from_julian (cls, jd, kind = "CJD") :
     k = kind
     if kind.endswith ("S") :
         jd /= 86400.0
         k = kind [:-1] + "D"
     days          = int (jd)
     seconds       = (jd - days) * 86400
     result = super (Date_Time, cls).from_julian (days, kind = k)
     return result + CAL.Time_Delta (seconds = seconds)
예제 #14
0
    def __init__(self, **kw):
        self.calendar = self
        self.__super.__init__(**kw)
        if self._cal is None:
            self.__class__._cal = CAL.Calendar()
            self.__class__.events = defaultdict_kd(self._get_events)

            def _day_get_events(this):
                return self.events[this.date.date]

            _CAL.Year.Day.events = property(_day_get_events)
예제 #15
0
 def _add_response_headers (self, resource, request, response) :
     self.__super._add_response_headers (resource, request, response)
     try :
         retry_after = self.retry_after
     except AttributeError :
         pass
     else :
         if isinstance (retry_after, CAL.Date_Time_Delta) :
             retry_after = CAL.Date_Time ().as_utc () + retry_after
         if retry_after is not None :
             response.set_header ("Retry-After", retry_after)
예제 #16
0
 def __new__ (cls, year = None, cal = None) :
     if cal is None :
         import _CAL.Calendar
         cal = CAL.Calendar ()
     D     = CAL.Date
     Table = cal._years
     if year is None :
         year = D ().year
     if year in Table :
         return Table [year]
     self = Table [year] = TFL.Meta.Object.__new__ (cls)
     self._init_ (year, cal)
     return self
예제 #17
0
파일: Plan.py 프로젝트: Tapyr/tapyr
def read_plan (Y, plan_file_name) :
    """Read information from file named `plan_file_name` and put appointments
       into `Y`
    """
    f = open (plan_file_name)
    try :
        buffer = f.read ()
    finally :
        f.close ()
    for entry in day_sep.split (buffer) :
        if day_pat.match (entry) :
            id = tuple ([int (f) for f in day_pat.day.split ("/")])
            d  = Y.dmap [id]
            head, _, tail = split_hst (entry, "\n")
            if tail :
                d.add_appointments (* CAL.appointments (tail))
예제 #18
0
파일: Plan.py 프로젝트: xiaochang91/tapyr
def read_plan(Y, plan_file_name):
    """Read information from file named `plan_file_name` and put appointments
       into `Y`
    """
    f = open(plan_file_name)
    try:
        buffer = f.read()
    finally:
        f.close()
    for entry in day_sep.split(buffer):
        if day_pat.match(entry):
            id = tuple([int(f) for f in day_pat.day.split("/")])
            d = Y.dmap[id]
            head, _, tail = split_hst(entry, "\n")
            if tail:
                d.add_appointments(*CAL.appointments(tail))
예제 #19
0
 def _init_ (self, year, cal) :
     D             = CAL.Date
     self.year     = year
     self.cal      = cal
     self.head     = h = cal.day [D (year = year, month = 1,  day = 1)]
     self.tail     = t = cal.day [D (year = year, month = 12, day = 31)]
     self.months   = [Month (self, m) for m in range (1, 13)]
     self.mmap     = {m.number : m for m in self.months}
     self.quarters = [Quarter (self, q) for q in range (1, 5)]
     self.qmap     = {q.number : q for q in self.quarters}
     self.weeks    = weeks  = []
     self.wmap     = wmap   = {}
     for w, d in self._week_creation_iter (D, cal, year, h) :
         week = Week (self, w, d)
         wmap [week.number] = week
         weeks.append (week)
         if week :
             cal.week [week.ordinal] = week
     self.holidays = CAL.holidays (year, cal.country)
예제 #20
0
파일: Year.py 프로젝트: Tapyr/tapyr
 def _init_ (self, year, cal) :
     D             = CAL.Date
     self.year     = year
     self.cal      = cal
     self.head     = h = cal.day [D (year = year, month = 1,  day = 1)]
     self.tail     = t = cal.day [D (year = year, month = 12, day = 31)]
     self.months   = [Month (self, m) for m in range (1, 13)]
     self.mmap     = {m.number : m for m in self.months}
     self.quarters = [Quarter (self, q) for q in range (1, 5)]
     self.qmap     = {q.number : q for q in self.quarters}
     self.weeks    = weeks  = []
     self.wmap     = wmap   = {}
     for w, d in self._week_creation_iter (D, cal, year, h) :
         week = Week (self, w, d)
         wmap [week.number] = week
         weeks.append (week)
         if week :
             cal.week [week.ordinal] = week
     self.holidays = CAL.holidays (year, cal.country)
예제 #21
0
 def as_plan (self) :
     self.sort_appointments ()
     d = self.date
     l = CAL.Date (d.year, 12, 31)
     holi = self.is_holiday or ""
     if holi :
         holi = "%26s" % ("=%s=" % (TFL.I18N.encode_o (holi), ),)
     return "\n".join \
         ( [ "# %s      %s#%2.2d, %s, day %d/-%d %s"
           % ( self
             , d.formatted ("%a")
             , d.week
             , d.formatted ("%d-%b-%Y")
             , d.rjd
             , l.rjd - d.rjd + 1
             , holi
             )
           ]
         + [str (a) for a in self.appointments or [""]]
         )
예제 #22
0
파일: Period.py 프로젝트: JPilarr/tapyr
 def start (self) :
     """Start date of period."""
     return CAL.Date (self.year, self.month, 1)
예제 #23
0
파일: Period.py 프로젝트: JPilarr/tapyr
class Year (_Period_) :
    """Model a calendary year.

    >>> from _TFL.json_dump import to_string as jsonified
    >>> p = Year (2012)
    >>> print (p, p.days, p.start, p.finis)
    2012 366 2012-01-01 2012-12-31

    >>> print (jsonified ([p]))
    ["2012"]

    >>> p_days = list (p)
    >>> print (p_days [0], "..", p_days [-1], ":", len (p_days))
    2012-01-01 .. 2012-12-31 : 366

    >>> for i in range (5) :
    ...     r = p + i
    ...     print (r, r.days, r.start, r.finis)
    ...
    2012 366 2012-01-01 2012-12-31
    2013 365 2013-01-01 2013-12-31
    2014 365 2014-01-01 2014-12-31
    2015 365 2015-01-01 2015-12-31
    2016 366 2016-01-01 2016-12-31

    >>> p > r
    False
    >>> p < r
    True
    >>> p == r
    False
    >>> p == p
    True

    """

    format           = "%4.4d"
    kind             = "year"
    number           = Alias_Property (kind)
    month            = property (lambda s : 1)

    _delta           = CAL.Month_Delta (12)
    _pattern         = Regexp \
        ( r"(?P<year> \d{4,4})"
          r"$"
        , flags      = re.VERBOSE
        )

    def __init__ (self, year, _ = None) :
        self.year = year
    # end def __init__

    @classmethod
    def from_date (cls, date) :
        return cls (date.year)
    # end def from_date

    def __repr__ (self) :
        return "%s (%s)"  % (self.__class__.__name__, self.number)
    # end def __repr__

    def __str__ (self) :
        return self.format % (self.number, )
예제 #24
0
파일: Period.py 프로젝트: JPilarr/tapyr
 def now (self) :
     return CAL.Date ()
예제 #25
0
파일: Period.py 프로젝트: JPilarr/tapyr
class Week (_Period_) :
    """Model a calendary week.

    >>> from _TFL.json_dump import to_string as jsonified

    >>> p = Week (2016, 16)
    >>> print (p, p.days, p.start, p.finis)
    2016/W16 7 2016-04-18 2016-04-24

    >>> print (jsonified ([p]))
    ["2016/W16"]

    >>> p_days = list (p)
    >>> print (p_days [0], "..", p_days [-1], ":", len (p_days))
    2016-04-18 .. 2016-04-24 : 7

    >>> print (", ".join (str (d) for d in p))
    2016-04-18, 2016-04-19, 2016-04-20, 2016-04-21, 2016-04-22, 2016-04-23, 2016-04-24

    >>> for i in range (5) :
    ...     r = p + i
    ...     print (r, r.days, r.start, r.finis)
    ...
    2016/W16 7 2016-04-18 2016-04-24
    2016/W17 7 2016-04-25 2016-05-01
    2016/W18 7 2016-05-02 2016-05-08
    2016/W19 7 2016-05-09 2016-05-15
    2016/W20 7 2016-05-16 2016-05-22

    >>> p > r
    False
    >>> p < r
    True
    >>> p == r
    False
    >>> p == p
    True

    >>> Week.from_string ("2016/W1")
    Week (2016, 1)

    >>> Week.now = CAL.Date (2016, 4, 19)
    >>> Week.from_string ("W13", add_year = True)
    Week (2016, 13)

    """

    format           = "%4.4d/W%d"
    kind             = "week"
    number           = Alias_Property (kind)
    start            = Alias_Property ("monday")

    _delta           = CAL.Date_Delta (7)
    _pattern         = Multi_Regexp \
        ( r"(?P<year>  \d{4,4})     (?:     [-/]) W(?P<week> \d{1,2})   $"
        , r"W(?P<week> \d{1,2}) (?: (?: \s+|[-/])  (?P<year> \d{4,4}))? $"
        , flags      = re.VERBOSE | re.IGNORECASE
        )

    def __init__ (self, * args, ** kw) :
        if kw :
            date    = kw.pop ("date")
            if args or kw :
                raise TypeError \
                    ("Need a single `date` arg or two args (year, week)")
        elif len (args) == 1 :
            date    = args [0]
            date   -= date.weekday
        else :
            date    = self._monday (* args)
        self.monday = date
        self.year   = date.year
        self.week   = date.week
    # end def __init__

    @TFL.Meta.Once_Property
    def month (self) :
        return self.monday.month
    # end def month

    @classmethod
    def from_date (cls, date) :
        return cls (date)
    # end def from_date

    @classmethod
    def _from_string_match_kw \
            (cls, s, match, add_year = False, future_p = False) :
        result = CAL.Date._from_string_match_kw (s, match)
        week   = result.pop ("week")
        year   = result.get ("year")
        if year is None :
            if add_year :
                now  = cls.now
                year = now.year
                if future_p and getattr (now, cls.kind) >= week :
                    year += 1
            else :
                raise ValueError (s)
        return dict (date = cls._monday (year, week))
    # end def _from_string_match_kw

    @classmethod
    def _monday (cls, year, week) :
        from _CAL.Year import Year as Y
        try :
            return Y (year).weeks [week].mon.date
        except IndexError :
            raise ValueError ("Invalid value for week: '%s'" % (week, ))
        except Exception :
            raise ValueError (cls.format % (year, week))
예제 #26
0
파일: Period.py 프로젝트: JPilarr/tapyr
class Quarter (_Period_) :
    """Model a calendary quarter.

    >>> from _TFL.json_dump import to_string as jsonified
    >>> p = Quarter (2000, 1)
    >>> print (p, p.days, p.start, p.finis)
    2000/Q1 91 2000-01-01 2000-03-31

    >>> print (jsonified ([p]))
    ["2000/Q1"]

    >>> p_days = list (p)
    >>> print (p_days [0], "..", p_days [-1], ":", len (p_days))
    2000-01-01 .. 2000-03-31 : 91

    >>> for i in range (8) :
    ...     r = p + i
    ...     print (r, r.days, r.start, r.finis)
    ...
    2000/Q1 91 2000-01-01 2000-03-31
    2000/Q2 91 2000-04-01 2000-06-30
    2000/Q3 92 2000-07-01 2000-09-30
    2000/Q4 92 2000-10-01 2000-12-31
    2001/Q1 90 2001-01-01 2001-03-31
    2001/Q2 91 2001-04-01 2001-06-30
    2001/Q3 92 2001-07-01 2001-09-30
    2001/Q4 92 2001-10-01 2001-12-31

    >>> p > r
    False
    >>> p < r
    True
    >>> p == r
    False
    >>> p == p
    True

    >>> Quarter.from_string ("2014/Q1")
    Quarter (2014, 1)

    >>> Quarter.from_string ("Q1 2015")
    Quarter (2015, 1)

    >>> Quarter.from_string ("2016-01-29")
    Quarter (2016, 1)

    >>> Quarter.from_string ("2015-01")
    Traceback (most recent call last):
      ...
    ValueError: 2015-01

    """

    format           = "%4.4d/Q%d"
    kind             = "quarter"
    number           = Alias_Property (kind)

    _delta           = CAL.Month_Delta (3)
    _pattern         = Multi_Regexp \
        ( r"(?P<year>     \d{4,4})     (?:     [-/]) Q(?P<quarter> \d{1,1})   $"
        , r"Q(?P<quarter> \d{1,1}) (?: (?: \s+|[-/]) (?P<year>     \d{4,4}))? $"
        , flags      = re.VERBOSE | re.IGNORECASE
        )

    def __init__ (self, year, quarter) :
        if not (1 <= quarter <= 4) :
            raise ValueError ("Illegal value for quarter: '%s'" % (quarter, ))
        self.year    = year
        self.quarter = quarter
    # end def __init__

    @TFL.Meta.Once_Property
    def month (self) :
        return 1 + 3 * (self.quarter - 1)
예제 #27
0
파일: Period.py 프로젝트: JPilarr/tapyr
class Month (_Period_) :
    """Model a calendary month.

    >>> from _TFL.json_dump import to_string as jsonified
    >>> p = Month (2016, 1)
    >>> print (p, p.days, p.start, p.finis)
    2016-01 31 2016-01-01 2016-01-31

    >>> print (jsonified ([p]))
    ["2016-01"]

    >>> p_days = list (p)
    >>> print (p_days [0], "..", p_days [-1], ":", len (p_days))
    2016-01-01 .. 2016-01-31 : 31

    >>> for i in range (8) :
    ...     r = p + i
    ...     print (r, r.days, r.start, r.finis)
    ...
    2016-01 31 2016-01-01 2016-01-31
    2016-02 29 2016-02-01 2016-02-29
    2016-03 31 2016-03-01 2016-03-31
    2016-04 30 2016-04-01 2016-04-30
    2016-05 31 2016-05-01 2016-05-31
    2016-06 30 2016-06-01 2016-06-30
    2016-07 31 2016-07-01 2016-07-31
    2016-08 31 2016-08-01 2016-08-31

    >>> p > r
    False
    >>> p < r
    True
    >>> p == r
    False
    >>> p == p
    True

    >>> Month.from_string ("2014/02")
    Month (2014, 2)

    >>> Month.from_string ("2014/03/28")
    Month (2014, 3)

    >>> with TFL.I18N.test_language ("de") :
    ...     Month.from_string ("2014-mai")
    Month (2014, 5)

    >>> Month.from_string ("2014/Q1")
    Traceback (most recent call last):
      ...
    ValueError: 2014/Q1

    """

    format           = "%4.4d-%2.2d"
    kind             = "month"
    number           = Alias_Property (kind)

    _delta           = CAL.Month_Delta (1)
    _pattern         = Multi_Regexp \
        ( r"(?P<year>  \d{4,4})    (?:     [-/])  (?P<month> \d{2,2})   $"
        , r"(?P<year>  \d{4,4})    (?: \s+|[-/])  (?P<month> [a-z]+)    $"
        , r"(?P<month> [a-z]+) (?: (?: \s+|[-/.]) (?P<year>  \d{4,4}))? $"
        , flags      = re.VERBOSE | re.IGNORECASE
        )

    def __init__ (self, year, month) :
        self.year    = year
        self.month   = month
예제 #28
0
파일: ui_display.py 프로젝트: Tapyr/tapyr
# Name
#    CAL.ui_display
#
# Purpose
#    Generic function returning a string usable for display in user interface
#
# Revision Dates
#     6-Feb-2015 (CT) Creation
#    ««revision-date»»···
#--

from   __future__ import division, print_function
from   __future__ import absolute_import, unicode_literals

from   _CAL                       import CAL

import _CAL._DTW_

from   _TFL.ui_display            import *

import datetime

@ui_display.add_type (CAL._DTW_, datetime.date, datetime.time, datetime.timedelta)
def _ui_display_date (obj) :
    return pyk.text_type (obj)
# end def _ui_display_date

if __name__ != "__main__" :
    CAL._Export ("ui_display")
### __END__ CAL.ui_display
예제 #29
0
파일: Period.py 프로젝트: JPilarr/tapyr
 def start (self) :
     return CAL.Date (self.year, self.month, self.day)
예제 #30
0
파일: Period.py 프로젝트: JPilarr/tapyr
class Day (_Period_) :
    """Model a calendary day.

    >>> from _TFL.json_dump import to_string as jsonified
    >>> p = Day (2016, 2, 27)
    >>> print (p, p.days, p.start, p.finis)
    2016-02-27 1 2016-02-27 2016-02-27

    >>> print (jsonified ([p]))
    ["2016-02-27"]

    >>> for d in p :
    ...     print (d)
    2016-02-27

    >>> for i in range (5) :
    ...     r = p + i
    ...     print (r, r.days, r.start, r.finis)
    ...
    2016-02-27 1 2016-02-27 2016-02-27
    2016-02-28 1 2016-02-28 2016-02-28
    2016-02-29 1 2016-02-29 2016-02-29
    2016-03-01 1 2016-03-01 2016-03-01
    2016-03-02 1 2016-03-02 2016-03-02

    >>> p > r
    False
    >>> p < r
    True
    >>> p == r
    False
    >>> p == p
    True

    """

    days             = property (lambda s : 1)
    finis            = Alias_Property ("start")
    format           = "%4.4d-%2.2d-%2.2d"
    kind             = "day"
    number           = Alias_Property (kind)

    _delta           = CAL.Date_Delta (1)
    _pattern         = None

    def __init__ (self, year, month, day) :
        self.year  = year
        self.month = month
        self.day   = day
    # end def __init__

    @classmethod
    def from_date (cls, date) :
        return cls (date.year, date.month, date.day)
    # end def from_date

    @TFL.Meta.Once_Property
    def start (self) :
        return CAL.Date (self.year, self.month, self.day)
    # end def start

    def __repr__ (self) :
        return "%s (%s, %s, %s)"  % \
            (self.__class__.__name__, self.year, self.month, self.day)
    # end def __repr__

    def __str__ (self) :
        return self.format % (self.year, self.month, self.day)
예제 #31
0
파일: Year.py 프로젝트: Tapyr/tapyr
        if not sos.path.isdir (path) :
            sos.mkdir (path)
        if cmd.diary :
            create_diary (Y, path)
        if cmd.create :
            if cmd.Plan :
                write_year (Y.as_plan, pfil, cmd.force)
            if cmd.View :
                write_year (Y.as_cal,  vfil, cmd.force)
# end def _main

_Command = TFL.CAO.Cmd \
    ( handler     = _main
    , opts        =
        ( "create:B?Write files"
        , "diary:B?Create a diary file per day"
        , "force:B?Overwrite existing files if any"
        , "path:S=~/diary?Path for calendar files"
        , "Plan:S=plan?Filename of plan for `year`"
        , "View:S=view?Filename of view for `year`"
        , "year:I=%d?Year for which to process calendar" % (CAL.Date ().year, )
        )
    , max_args    = 0
    )

if __name__ != "__main__" :
    CAL._Export ("Year")
else :
    _Command ()
### __END__ CAL.Year
예제 #32
0
        elif isinstance (rhs, (datetime.date, datetime.datetime)) :
            return self.new_dtw (rhs - self._body)
        else :
            return self.dt_op (-rhs, operator.add)
    # end def __rsub__

    def __str__ (self) :
        return self.as_string
    # end def __str__

    def __sub__ (self, rhs) :
        return self.dt_op (rhs, operator.sub)
    # end def __sub__

# end class Relative_Delta

class _Relative_Delta_Arg_ (TFL.CAO.Str) :
    """Argument or option with a (calendary) relative-delta value"""

    _real_name = "Relative_Delta"

    def cook (self, value, cao = None) :
        return Relative_Delta.from_string (value)
    # end def cook

# end class _Delta_Arg_

if __name__ != "__main__" :
    CAL._Export ("*")
### __END__ CAL.Relative_Delta
예제 #33
0
파일: _DTW_.py 프로젝트: Tapyr/tapyr
    # end def __lt__

    def __sub__(self, rhs):
        return self.__class__(**{self.Class._kind: self._wrapped - rhs})

    # end def __sub__

    __str__ = property(lambda s: s._wrapped.__str__)


# end class _Mutable_DTW_


@TFL._Add_Import_Callback("_TFL.json_dump")
def _import_cb_json_dump(module):
    @module.default.add_type(_DTW_, _Mutable_DTW_)
    def json_encode_cal(o):
        try:
            encoder = o._body.isoformat
        except AttributeError:
            encoder = o.__str__
        return encoder()


# end def _import_cb_json_dump

if __name__ != "__main__":
    CAL._Export("_DTW_", "_Mutable_DTW_")
### __END__ CAL._DTW_
예제 #34
0
파일: Ordinal.py 프로젝트: Tapyr/tapyr
    """Ordinal numbers for years."""

    @classmethod
    def is_first (cls, yo) :
        return False
    # end def is_first

    @classmethod
    def to_date (cls, yo) :
        """Return date corresponding to year ordinal `yo`."""
        return CAL.Date (yo, 1, 1)
    # end def to_date

    @classmethod
    def to_ordinal (cls, d) :
        """Return year ordinal for date `d`."""
        return d.year
    # end def to_ordinal

    @classmethod
    def to_year (cls, yo) :
        """Return date corresponding to year ordinal `yo`."""
        return yo
    # end def to_year

# end class Year

if __name__ == "__main__" :
    CAL._Export_Module ()
### __END__ CAL.Ordinal
예제 #35
0
 def _date(self, year):
     return CAL.Date(*easter_date(year))
예제 #36
0
파일: Period.py 프로젝트: JPilarr/tapyr
class Interval (_Period_) :
    """Model an arbitrary calendary interval.

    >>> from _TFL.json_dump import to_string as jsonified

    >>> s = CAL.Date (2016, 4, 11)
    >>> f = CAL.Date (2016, 4, 14)

    >>> p = Interval (s, f)

    >>> print (p, p.days, p.start, p.finis)
    2016-04-11..2016-04-14 4 2016-04-11 2016-04-14

    >>> print (jsonified ([p]))
    ["2016-04-11..2016-04-14"]

    >>> for d in p :
    ...     print (d)
    2016-04-11
    2016-04-12
    2016-04-13
    2016-04-14

    >>> for i in range (5) :
    ...     r = p + i
    ...     print (r, r.days, r.start, r.finis)
    ...
    2016-04-11..2016-04-14 4 2016-04-11 2016-04-14
    2016-04-12..2016-04-15 4 2016-04-12 2016-04-15
    2016-04-13..2016-04-16 4 2016-04-13 2016-04-16
    2016-04-14..2016-04-17 4 2016-04-14 2016-04-17
    2016-04-15..2016-04-18 4 2016-04-15 2016-04-18

    >>> Interval.from_string ("2016-04-18")
    Interval (Date (2016, 4, 18), Date (2016, 4, 18))

    >>> print (Interval.from_string ("2016-04-18 - 2016-04-19"))
    2016-04-18..2016-04-19

    >>> print (Interval.from_string ("2016-04-18 – 2016-04-19"))
    2016-04-18..2016-04-19

    >>> print (Interval.from_string ("2016-04-18–2016-04-19"))
    2016-04-18..2016-04-19

    >>> print (Interval.from_string ("2016-04-18 .. 2016-04-19"))
    2016-04-18..2016-04-19

    >>> print (Interval.from_string ("2016-04-18..2016-04-19"))
    2016-04-18..2016-04-19

    """

    format           = "%s..%s"
    kind             = ""
    number           = Alias_Property (kind)

    _delta           = CAL.Date_Delta (1)
    _pattern         = Regexp \
        ( r"(?P<start>[^ –]+)(?: - | ?(?:–|\.\.) ?)(?P<finis>[^ ]+)$"
        )

    def __init__ (self, start, finis) :
        self.start = start
        self.finis = finis
    # end def __init__

    @property
    def finis (self) :
        return self._finis
    # end def finis

    @finis.setter
    def finis (self, value) :
        self._finis = value
    # end def finis

    @TFL.Meta.Once_Property
    def month (self) :
        return self.start.month
    # end def month

    @property
    def start (self) :
        return self._start
    # end def start

    @start.setter
    def start (self, value) :
        self._start = value
    # end def start

    @classmethod
    def from_date (cls, date) :
        return cls (date, date)
    # end def from_date

    @classmethod
    def _from_string_match_kw \
            (cls, s, match, add_year = False, future_p = False) :
        s      = CAL.Date.from_string (match.group ("start"))
        f      = CAL.Date.from_string (match.group ("finis"))
        result = dict (start = s, finis = f)
        return result
    # end def _from_string_match_kw

    def __add__ (self, rhs) :
        delta = self._delta * rhs
        return self.__class__ (self.start + delta, self.finis + delta)
    # end def __add__

    def __repr__ (self) :
        return "%s (%r, %r)" % \
            (self.__class__.__name__, self.start, self.finis)
    # end def __repr__

    def __str__ (self) :
        return self.format % (self.start, self.finis)
    # end def __str__

    def __sub__ (self, rhs) :
        delta = self._delta * rhs
        return self.__class__ (self.start - delta, self.finis - delta)
예제 #37
0
 def _date(self, year):
     return CAL.Date(year, self.month, self.day)
예제 #38
0
파일: _DTW_.py 프로젝트: xiaochang91/tapyr
    # end def __lt__

    def __sub__(self, rhs):
        return self.__class__(**{self.Class._kind: self._wrapped - rhs})

    # end def __sub__

    __str__ = property(lambda s: s._wrapped.__str__)


# end class _Mutable_DTW_


@TFL._Add_Import_Callback("_TFL.json_dump")
def _import_cb_json_dump(module):
    @module.default.add_type(_DTW_, _Mutable_DTW_)
    def json_encode_cal(o):
        try:
            encoder = o._body.isoformat
        except AttributeError:
            encoder = o.__str__
        return encoder()


# end def _import_cb_json_dump

if __name__ != "__main__":
    CAL._Export("_DTW_", "_Mutable_DTW_")
### __END__ CAL._DTW_
예제 #39
0
Week_Day_Abbrs_3 = TFL.G8R \
    ( [ _("Mon"), _("Tue"), _("Wed"), _("Thu"), _("Fri"), _("Sat"), _("Sun")])

Week_Day_Names   = TFL.G8R \
    ( [ _("Monday"), _("Tuesday"), _("Wednesday"), _("Thursday")
      , _("Friday"), _("Saturday"), _("Sunday")
      ]
    )

Week_Days = TFL.G8R \
    ( Week_Day_Abbrs_2.words, Week_Day_Abbrs_3.words, Week_Day_Names.words)

All = TFL.G8R_Multi(Units.LC, Months.LC, Week_Days.LC)


def _show(g8r, text, lang="de", localized_p=False):
    with TFL.I18N.test_language(lang):
        globalized = g8r.globalized(text)
        result = (lang, ":", text, "-->", globalized)
        if localized_p:
            result += ("-->", g8r.localized(globalized))
        print(*result)


# end def _show

if __name__ != "__main__":
    CAL._Export_Module()
### __END__ CAL.G8R
예제 #40
0
파일: JD.py 프로젝트: Tapyr/tapyr
#     5-Jun-2004 (CT) Creation
#    11-Aug-2007 (CT) U_Test ballast removed
#    ««revision-date»»···
#--

"""A julian day number is a continuous count of days from the beginning of
the year -4712. By (astronomical) tradition, the Julian Day begins at
Greenwhich mean noon, that is, at 12h Universal Time.

see Jean Meeus, Astronomical Algorithms, 1991, 1998
"""

def JD (d, m, y) :
    """Returns Julian Day number for year `y`, month `m`, and day `d`."""
    if m <= 2 :
        y -= 1
        m += 12
    if (y, m, d) >= (1582, 10, 15) :
        a = int (y / 100)
        b = 2 - a + int (a / 4)
    else :
        b = 0
    jd = int (365.25  * (y + 4716)) + int (30.6001 * (m + 1)) + d + b - 1524.5
    return jd
# end def JD

if __name__ != "__main__" :
    from _CAL import CAL
    CAL._Export ("JD")
### __END__ JD
예제 #41
0
                    ( "Nautic twilight starts %s, ends %s"
                    % (rts.nautic_twilight_start, rts.nautic_twilight_finis)
                    )
            if cmd.astro_twilight:
                print \
                    ( "Astro  twilight starts %s, ends %s"
                    % (rts.astro_twilight_start, rts.astro_twilight_finis)
                    )


# end def _main

_Command = TFL.CAO.Cmd \
    ( handler       = _main
    , args          =
        ( "date:S=%s" % CAL.Date ()
        ,
        )
    , opts          =
        ( "astro_twilight:B?Show astro twilight (-18 degrees below horizon)"
        , "civil_twilight:B?Show civil twilight (-6 degrees below horizon)"
        , "day_length:B?Show length of day in hours"
        , "latitude:F?Latitude (north is positive)"
        , "longitude:F?Longitude (negative is east of Greenwich)"
        , "-nautic_twilight:B"
            "?Show time of nautic twilight (sun -12 degrees below horizon)"
        , "-transit:B?Show transit height"
        , "-year:I?Show sunrise/transit/set data for whole year"
        , TFL.CAO.Opt.Location
            ( name        = "Location"
            , description = "Location of observer"
예제 #42
0
파일: Delta.py 프로젝트: Tapyr/tapyr
# end class _Delta_Arg_

class _Date_Delta_Arg_ (_Delta_Arg_) :
    """Argument or option with a (calendary) date-delta value"""

    _real_name = "Date_Delta"
    D_Type     = Date_Delta

# end class _Date_Delta_Arg_

class _Date_Time_Delta_Arg_ (_Delta_Arg_) :
    """Argument or option with a (calendary) datetime-delta value"""

    _real_name = "Date_Time_Delta"
    D_Type     = Date_Time_Delta

# end class _Date_Time_Delta_Arg_

class _Time_Delta_Arg_ (_Delta_Arg_) :
    """Argument or option with a (calendary) time-delta value"""

    _real_name = "Time_Delta"
    D_Type     = Time_Delta

# end class _Time_Delta_Arg_

if __name__ != "__main__" :
    CAL._Export ("*", "_Delta_Mixin_", "_Delta_", "Delta")
### __END__ CAL.Delta