home *** CD-ROM | disk | FTP | other *** search
/ Chip 2011 November / CHIP_2011_11.iso / Programy / Narzedzia / Calibre / calibre-0.8.18.msi / file_262 / calendar.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-09-09  |  20.9 KB  |  594 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.7)
  3.  
  4. import sys
  5. import datetime
  6. import locale as _locale
  7. __all__ = [
  8.     'IllegalMonthError',
  9.     'IllegalWeekdayError',
  10.     'setfirstweekday',
  11.     'firstweekday',
  12.     'isleap',
  13.     'leapdays',
  14.     'weekday',
  15.     'monthrange',
  16.     'monthcalendar',
  17.     'prmonth',
  18.     'month',
  19.     'prcal',
  20.     'calendar',
  21.     'timegm',
  22.     'month_name',
  23.     'month_abbr',
  24.     'day_name',
  25.     'day_abbr']
  26. error = ValueError
  27.  
  28. class IllegalMonthError(ValueError):
  29.     
  30.     def __init__(self, month):
  31.         self.month = month
  32.  
  33.     
  34.     def __str__(self):
  35.         return 'bad month number %r; must be 1-12' % self.month
  36.  
  37.  
  38.  
  39. class IllegalWeekdayError(ValueError):
  40.     
  41.     def __init__(self, weekday):
  42.         self.weekday = weekday
  43.  
  44.     
  45.     def __str__(self):
  46.         return 'bad weekday number %r; must be 0 (Monday) to 6 (Sunday)' % self.weekday
  47.  
  48.  
  49. January = 1
  50. February = 2
  51. mdays = [
  52.     0,
  53.     31,
  54.     28,
  55.     31,
  56.     30,
  57.     31,
  58.     30,
  59.     31,
  60.     31,
  61.     30,
  62.     31,
  63.     30,
  64.     31]
  65.  
  66. class _localized_month:
  67.     _months = [ datetime.date(2001, i + 1, 1).strftime for i in range(12) ]
  68.     _months.insert(0, (lambda x: ''))
  69.     
  70.     def __init__(self, format):
  71.         self.format = format
  72.  
  73.     
  74.     def __getitem__(self, i):
  75.         funcs = self._months[i]
  76.         if isinstance(i, slice):
  77.             return [ f(self.format) for f in funcs ]
  78.         return None(self.format)
  79.  
  80.     
  81.     def __len__(self):
  82.         return 13
  83.  
  84.  
  85.  
  86. class _localized_day:
  87.     _days = [ datetime.date(2001, 1, i + 1).strftime for i in range(7) ]
  88.     
  89.     def __init__(self, format):
  90.         self.format = format
  91.  
  92.     
  93.     def __getitem__(self, i):
  94.         funcs = self._days[i]
  95.         if isinstance(i, slice):
  96.             return [ f(self.format) for f in funcs ]
  97.         return None(self.format)
  98.  
  99.     
  100.     def __len__(self):
  101.         return 7
  102.  
  103.  
  104. day_name = _localized_day('%A')
  105. day_abbr = _localized_day('%a')
  106. month_name = _localized_month('%B')
  107. month_abbr = _localized_month('%b')
  108. (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
  109.  
  110. def isleap(year):
  111.     if not year % 4 == 0 and year % 100 != 0:
  112.         pass
  113.     return year % 400 == 0
  114.  
  115.  
  116. def leapdays(y1, y2):
  117.     y1 -= 1
  118.     y2 -= 1
  119.     return (y2 // 4 - y1 // 4 - y2 // 100 - y1 // 100) + (y2 // 400 - y1 // 400)
  120.  
  121.  
  122. def weekday(year, month, day):
  123.     return datetime.date(year, month, day).weekday()
  124.  
  125.  
  126. def monthrange(year, month):
  127.     if month <= month:
  128.         pass
  129.     elif not month <= 12:
  130.         raise IllegalMonthError(month)
  131.     day1 = weekday(year, month, 1)
  132.     if month == February:
  133.         pass
  134.     ndays = mdays[month] + isleap(year)
  135.     return (day1, ndays)
  136.  
  137.  
  138. class Calendar(object):
  139.     
  140.     def __init__(self, firstweekday = 0):
  141.         self.firstweekday = firstweekday
  142.  
  143.     
  144.     def getfirstweekday(self):
  145.         return self._firstweekday % 7
  146.  
  147.     
  148.     def setfirstweekday(self, firstweekday):
  149.         self._firstweekday = firstweekday
  150.  
  151.     firstweekday = property(getfirstweekday, setfirstweekday)
  152.     
  153.     def iterweekdays(self):
  154.         for i in range(self.firstweekday, self.firstweekday + 7):
  155.             yield i % 7
  156.         
  157.  
  158.     
  159.     def itermonthdates(self, year, month):
  160.         date = datetime.date(year, month, 1)
  161.         days = (date.weekday() - self.firstweekday) % 7
  162.         date -= datetime.timedelta(days = days)
  163.         oneday = datetime.timedelta(days = 1)
  164.         while True:
  165.             yield date
  166.             date += oneday
  167.             if date.month != month and date.weekday() == self.firstweekday:
  168.                 break
  169.                 continue
  170.             return None
  171.  
  172.     
  173.     def itermonthdays2(self, year, month):
  174.         for date in self.itermonthdates(year, month):
  175.             if date.month != month:
  176.                 yield (0, date.weekday())
  177.                 continue
  178.             yield (date.day, date.weekday())
  179.         
  180.  
  181.     
  182.     def itermonthdays(self, year, month):
  183.         for date in self.itermonthdates(year, month):
  184.             if date.month != month:
  185.                 yield 0
  186.                 continue
  187.             yield date.day
  188.         
  189.  
  190.     
  191.     def monthdatescalendar(self, year, month):
  192.         dates = list(self.itermonthdates(year, month))
  193.         return [ dates[i:i + 7] for i in range(0, len(dates), 7) ]
  194.  
  195.     
  196.     def monthdays2calendar(self, year, month):
  197.         days = list(self.itermonthdays2(year, month))
  198.         return [ days[i:i + 7] for i in range(0, len(days), 7) ]
  199.  
  200.     
  201.     def monthdayscalendar(self, year, month):
  202.         days = list(self.itermonthdays(year, month))
  203.         return [ days[i:i + 7] for i in range(0, len(days), 7) ]
  204.  
  205.     
  206.     def yeardatescalendar(self, year, width = 3):
  207.         months = [ self.monthdatescalendar(year, i) for i in range(January, January + 12) ]
  208.         return [ months[i:i + width] for i in range(0, len(months), width) ]
  209.  
  210.     
  211.     def yeardays2calendar(self, year, width = 3):
  212.         months = [ self.monthdays2calendar(year, i) for i in range(January, January + 12) ]
  213.         return [ months[i:i + width] for i in range(0, len(months), width) ]
  214.  
  215.     
  216.     def yeardayscalendar(self, year, width = 3):
  217.         months = [ self.monthdayscalendar(year, i) for i in range(January, January + 12) ]
  218.         return [ months[i:i + width] for i in range(0, len(months), width) ]
  219.  
  220.  
  221.  
  222. class TextCalendar(Calendar):
  223.     
  224.     def prweek(self, theweek, width):
  225.         print self.formatweek(theweek, width),
  226.  
  227.     
  228.     def formatday(self, day, weekday, width):
  229.         if day == 0:
  230.             s = ''
  231.         else:
  232.             s = '%2i' % day
  233.         return s.center(width)
  234.  
  235.     
  236.     def formatweek(self, theweek, width):
  237.         return (None, ' '.join)((lambda .0: pass)(theweek))
  238.  
  239.     
  240.     def formatweekday(self, day, width):
  241.         if width >= 9:
  242.             names = day_name
  243.         else:
  244.             names = day_abbr
  245.         return names[day][:width].center(width)
  246.  
  247.     
  248.     def formatweekheader(self, width):
  249.         return (None, ' '.join)((lambda .0: pass)(self.iterweekdays()))
  250.  
  251.     
  252.     def formatmonthname(self, theyear, themonth, width, withyear = True):
  253.         s = month_name[themonth]
  254.         if withyear:
  255.             s = '%s %r' % (s, theyear)
  256.         return s.center(width)
  257.  
  258.     
  259.     def prmonth(self, theyear, themonth, w = 0, l = 0):
  260.         print self.formatmonth(theyear, themonth, w, l),
  261.  
  262.     
  263.     def formatmonth(self, theyear, themonth, w = 0, l = 0):
  264.         w = max(2, w)
  265.         l = max(1, l)
  266.         s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1)
  267.         s = s.rstrip()
  268.         s += '\n' * l
  269.         s += self.formatweekheader(w).rstrip()
  270.         s += '\n' * l
  271.         for week in self.monthdays2calendar(theyear, themonth):
  272.             s += self.formatweek(week, w).rstrip()
  273.             s += '\n' * l
  274.         
  275.         return s
  276.  
  277.     
  278.     def formatyear(self, theyear, w = 2, l = 1, c = 6, m = 3):
  279.         w = max(2, w)
  280.         l = max(1, l)
  281.         c = max(2, c)
  282.         colwidth = (w + 1) * 7 - 1
  283.         v = []
  284.         a = v.append
  285.         a(repr(theyear).center(colwidth * m + c * (m - 1)).rstrip())
  286.         a('\n' * l)
  287.         header = self.formatweekheader(w)
  288.         for i, row in enumerate(self.yeardays2calendar(theyear, m)):
  289.             months = range(m * i + 1, min(m * (i + 1) + 1, 13))
  290.             a('\n' * l)
  291.             names = (lambda .0: pass)(months)
  292.             a(formatstring(names, colwidth, c).rstrip())
  293.             a('\n' * l)
  294.             headers = (lambda .0: pass)(months)
  295.             a(formatstring(headers, colwidth, c).rstrip())
  296.             a('\n' * l)
  297.             height = max((lambda .0: pass)(row))
  298.             for j in range(height):
  299.                 weeks = []
  300.                 for cal in row:
  301.                     if j >= len(cal):
  302.                         weeks.append('')
  303.                         continue
  304.                     weeks.append(self.formatweek(cal[j], w))
  305.                 
  306.                 a(formatstring(weeks, colwidth, c).rstrip())
  307.                 a('\n' * l)
  308.             
  309.         
  310.         return ''.join(v)
  311.  
  312.     
  313.     def pryear(self, theyear, w = 0, l = 0, c = 6, m = 3):
  314.         print self.formatyear(theyear, w, l, c, m)
  315.  
  316.  
  317.  
  318. class HTMLCalendar(Calendar):
  319.     cssclasses = [
  320.         'mon',
  321.         'tue',
  322.         'wed',
  323.         'thu',
  324.         'fri',
  325.         'sat',
  326.         'sun']
  327.     
  328.     def formatday(self, day, weekday):
  329.         if day == 0:
  330.             return '<td class="noday"> </td>'
  331.         return None % (self.cssclasses[weekday], day)
  332.  
  333.     
  334.     def formatweek(self, theweek):
  335.         s = (''.join,)((lambda .0: pass)(theweek))
  336.         return '<tr>%s</tr>' % s
  337.  
  338.     
  339.     def formatweekday(self, day):
  340.         return '<th class="%s">%s</th>' % (self.cssclasses[day], day_abbr[day])
  341.  
  342.     
  343.     def formatweekheader(self):
  344.         s = (''.join,)((lambda .0: pass)(self.iterweekdays()))
  345.         return '<tr>%s</tr>' % s
  346.  
  347.     
  348.     def formatmonthname(self, theyear, themonth, withyear = True):
  349.         if withyear:
  350.             s = '%s %s' % (month_name[themonth], theyear)
  351.         else:
  352.             s = '%s' % month_name[themonth]
  353.         return '<tr><th colspan="7" class="month">%s</th></tr>' % s
  354.  
  355.     
  356.     def formatmonth(self, theyear, themonth, withyear = True):
  357.         v = []
  358.         a = v.append
  359.         a('<table border="0" cellpadding="0" cellspacing="0" class="month">')
  360.         a('\n')
  361.         a(self.formatmonthname(theyear, themonth, withyear = withyear))
  362.         a('\n')
  363.         a(self.formatweekheader())
  364.         a('\n')
  365.         for week in self.monthdays2calendar(theyear, themonth):
  366.             a(self.formatweek(week))
  367.             a('\n')
  368.         
  369.         a('</table>')
  370.         a('\n')
  371.         return ''.join(v)
  372.  
  373.     
  374.     def formatyear(self, theyear, width = 3):
  375.         v = []
  376.         a = v.append
  377.         width = max(width, 1)
  378.         a('<table border="0" cellpadding="0" cellspacing="0" class="year">')
  379.         a('\n')
  380.         a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear))
  381.         for i in range(January, January + 12, width):
  382.             months = range(i, min(i + width, 13))
  383.             a('<tr>')
  384.             for m in months:
  385.                 a('<td>')
  386.                 a(self.formatmonth(theyear, m, withyear = False))
  387.                 a('</td>')
  388.             
  389.             a('</tr>')
  390.         
  391.         a('</table>')
  392.         return ''.join(v)
  393.  
  394.     
  395.     def formatyearpage(self, theyear, width = 3, css = 'calendar.css', encoding = None):
  396.         if encoding is None:
  397.             encoding = sys.getdefaultencoding()
  398.         v = []
  399.         a = v.append
  400.         a('<?xml version="1.0" encoding="%s"?>\n' % encoding)
  401.         a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')
  402.         a('<html>\n')
  403.         a('<head>\n')
  404.         a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding)
  405.         if css is not None:
  406.             a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css)
  407.         a('<title>Calendar for %d</title>\n' % theyear)
  408.         a('</head>\n')
  409.         a('<body>\n')
  410.         a(self.formatyear(theyear, width))
  411.         a('</body>\n')
  412.         a('</html>\n')
  413.         return ''.join(v).encode(encoding, 'xmlcharrefreplace')
  414.  
  415.  
  416.  
  417. class TimeEncoding:
  418.     
  419.     def __init__(self, locale):
  420.         self.locale = locale
  421.  
  422.     
  423.     def __enter__(self):
  424.         self.oldlocale = _locale.getlocale(_locale.LC_TIME)
  425.         _locale.setlocale(_locale.LC_TIME, self.locale)
  426.  
  427.     
  428.     def __exit__(self, *args):
  429.         _locale.setlocale(_locale.LC_TIME, self.oldlocale)
  430.  
  431.  
  432.  
  433. class LocaleTextCalendar(TextCalendar):
  434.     
  435.     def __init__(self, firstweekday = 0, locale = None):
  436.         TextCalendar.__init__(self, firstweekday)
  437.         if locale is None:
  438.             locale = _locale.getdefaultlocale()
  439.         self.locale = locale
  440.  
  441.     
  442.     def formatweekday(self, day, width):
  443.         with TimeEncoding(self.locale) as encoding:
  444.             if width >= 9:
  445.                 names = day_name
  446.             else:
  447.                 names = day_abbr
  448.             name = names[day]
  449.             if encoding is not None:
  450.                 name = name.decode(encoding)
  451.             return name[:width].center(width)
  452.  
  453.     
  454.     def formatmonthname(self, theyear, themonth, width, withyear = True):
  455.         with TimeEncoding(self.locale) as encoding:
  456.             s = month_name[themonth]
  457.             if encoding is not None:
  458.                 s = s.decode(encoding)
  459.             if withyear:
  460.                 s = '%s %r' % (s, theyear)
  461.             return s.center(width)
  462.  
  463.  
  464.  
  465. class LocaleHTMLCalendar(HTMLCalendar):
  466.     
  467.     def __init__(self, firstweekday = 0, locale = None):
  468.         HTMLCalendar.__init__(self, firstweekday)
  469.         if locale is None:
  470.             locale = _locale.getdefaultlocale()
  471.         self.locale = locale
  472.  
  473.     
  474.     def formatweekday(self, day):
  475.         with TimeEncoding(self.locale) as encoding:
  476.             s = day_abbr[day]
  477.             if encoding is not None:
  478.                 s = s.decode(encoding)
  479.             return '<th class="%s">%s</th>' % (self.cssclasses[day], s)
  480.  
  481.     
  482.     def formatmonthname(self, theyear, themonth, withyear = True):
  483.         with TimeEncoding(self.locale) as encoding:
  484.             s = month_name[themonth]
  485.             if encoding is not None:
  486.                 s = s.decode(encoding)
  487.             if withyear:
  488.                 s = '%s %s' % (s, theyear)
  489.             return '<tr><th colspan="7" class="month">%s</th></tr>' % s
  490.  
  491.  
  492. c = TextCalendar()
  493. firstweekday = c.getfirstweekday
  494.  
  495. def setfirstweekday(firstweekday):
  496.     
  497.     try:
  498.         firstweekday.__index__
  499.     except AttributeError:
  500.         raise IllegalWeekdayError(firstweekday)
  501.  
  502.     if firstweekday <= firstweekday:
  503.         pass
  504.     elif not firstweekday <= SUNDAY:
  505.         raise IllegalWeekdayError(firstweekday)
  506.     c.firstweekday = firstweekday
  507.  
  508. monthcalendar = c.monthdayscalendar
  509. prweek = c.prweek
  510. week = c.formatweek
  511. weekheader = c.formatweekheader
  512. prmonth = c.prmonth
  513. month = c.formatmonth
  514. calendar = c.formatyear
  515. prcal = c.pryear
  516. _colwidth = 20
  517. _spacing = 6
  518.  
  519. def format(cols, colwidth = _colwidth, spacing = _spacing):
  520.     print formatstring(cols, colwidth, spacing)
  521.  
  522.  
  523. def formatstring(cols, colwidth = _colwidth, spacing = _spacing):
  524.     spacing *= ' '
  525.     return (spacing.join,)((lambda .0: pass)(cols))
  526.  
  527. EPOCH = 1970
  528. _EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()
  529.  
  530. def timegm(tuple):
  531.     (year, month, day, hour, minute, second) = tuple[:6]
  532.     days = (datetime.date(year, month, 1).toordinal() - _EPOCH_ORD) + day - 1
  533.     hours = days * 24 + hour
  534.     minutes = hours * 60 + minute
  535.     seconds = minutes * 60 + second
  536.     return seconds
  537.  
  538.  
  539. def main(args):
  540.     import optparse
  541.     parser = optparse.OptionParser(usage = 'usage: %prog [options] [year [month]]')
  542.     parser.add_option('-w', '--width', dest = 'width', type = 'int', default = 2, help = 'width of date column (default 2, text only)')
  543.     parser.add_option('-l', '--lines', dest = 'lines', type = 'int', default = 1, help = 'number of lines for each week (default 1, text only)')
  544.     parser.add_option('-s', '--spacing', dest = 'spacing', type = 'int', default = 6, help = 'spacing between months (default 6, text only)')
  545.     parser.add_option('-m', '--months', dest = 'months', type = 'int', default = 3, help = 'months per row (default 3, text only)')
  546.     parser.add_option('-c', '--css', dest = 'css', default = 'calendar.css', help = 'CSS to use for page (html only)')
  547.     parser.add_option('-L', '--locale', dest = 'locale', default = None, help = 'locale to be used from month and weekday names')
  548.     parser.add_option('-e', '--encoding', dest = 'encoding', default = None, help = 'Encoding to use for output')
  549.     parser.add_option('-t', '--type', dest = 'type', default = 'text', choices = ('text', 'html'), help = 'output type (text or html)')
  550.     (options, args) = parser.parse_args(args)
  551.     if options.locale and not (options.encoding):
  552.         parser.error('if --locale is specified --encoding is required')
  553.         sys.exit(1)
  554.     locale = (options.locale, options.encoding)
  555.     if options.type == 'html':
  556.         if options.locale:
  557.             cal = LocaleHTMLCalendar(locale = locale)
  558.         else:
  559.             cal = HTMLCalendar()
  560.         encoding = options.encoding
  561.         if encoding is None:
  562.             encoding = sys.getdefaultencoding()
  563.         optdict = dict(encoding = encoding, css = options.css)
  564.         if len(args) == 1:
  565.             print cal.formatyearpage(datetime.date.today().year, **optdict)
  566.         elif len(args) == 2:
  567.             print cal.formatyearpage(int(args[1]), **optdict)
  568.         else:
  569.             parser.error('incorrect number of arguments')
  570.             sys.exit(1)
  571.     elif options.locale:
  572.         cal = LocaleTextCalendar(locale = locale)
  573.     else:
  574.         cal = TextCalendar()
  575.     optdict = dict(w = options.width, l = options.lines)
  576.     if len(args) != 3:
  577.         optdict['c'] = options.spacing
  578.         optdict['m'] = options.months
  579.     if len(args) == 1:
  580.         result = cal.formatyear(datetime.date.today().year, **optdict)
  581.     elif len(args) == 2:
  582.         result = cal.formatyear(int(args[1]), **optdict)
  583.     elif len(args) == 3:
  584.         result = cal.formatmonth(int(args[1]), int(args[2]), **optdict)
  585.     else:
  586.         parser.error('incorrect number of arguments')
  587.         sys.exit(1)
  588.     if options.encoding:
  589.         result = result.encode(options.encoding)
  590.     print result
  591.  
  592. if __name__ == '__main__':
  593.     main(sys.argv)
  594.