Exemplo n.º 1
0
    def __init__(self,parent,y,m,d):
        tk.Frame.__init__(self,parent,bd=2,relief=tk.GROOVE)
        self.year = y
        self.month = m
        self.chosenrow = (d - 1 + ((monthrange(y,m)[0] + 1) % 7))/7

        self.dayArray = ["Su","Mo","Tu","We","Th","Fr","Sa"]
        setfirstweekday(6)

        f = tk.Frame(self)
        f.pack(fill=tk.X)
        tk.Button(f,
            text='<',
            command=self.__decrease,
            relief=tk.FLAT).pack(side=tk.LEFT)
        self.l = tk.Label(f)
        self.l.pack(side=tk.LEFT,expand="yes",fill='x')
	self.__redrawlabel()
        tk.Button(f,
            text='>',
            command=self.__increase,
            relief=tk.FLAT).pack(side=tk.RIGHT)

        self.c = tk.Canvas(self,
            width=155,height=135,
            bg='white',bd=2,relief=tk.GROOVE)
        self.c.bind('<1>', self.__click)
        self.c.pack()
       
        self.__fill_canvas()
        self.__setchosen(self.chosenrow)
def get_calendar_weeks(date_obj):
    """Given a selected month, build a calendar with events
    
        Input: year, month (from selected_day)
       Output: A list of the weeks. Each week is a list of seven datetime.date objects.
    """
    if python_version()[:3] in ['2.3', '2.4']:
        pass
    else:           
        # For python 2.5 or higher, use built-in "monthdatescalendar" method
        cal = calendar.Calendar(calendar.SUNDAY)        # start the day of the week on sunday
        # a list of the weeks. Each week is a list of seven datetime.date objects.
        return cal.monthdatescalendar(date_obj.year, date_obj.month)   
       
        return cal_weeks        
        
    # built lists of datetime objects using older python
    calendar.setfirstweekday(calendar.SUNDAY)       # set sunday to first day of week
    week_lists = calendar.monthcalendar(date_obj.year, date_obj.month)  #   pull array of arrays
    cal_weeks = []
    for idx, wk in enumerate(week_lists):
        wk = map(lambda day_num: date(year=date_obj.year, month=date_obj.month, day=day_num), wk)
        cal_weeks.append(wk)
     
    cal_weeks[0] = fill_in_days(cal_weeks[0], is_first_week=True)
    cal_weeks[-1] = fill_in_days(cal_weeks[-1], is_first_week=False)
    
    return cal_weeks
Exemplo n.º 3
0
    def get_context_data(self, **kwargs):
        firstweekday = 0 + SHIFT_WEEKSTART
        while firstweekday < 0:
            firstweekday += 7
        while firstweekday > 6:
            firstweekday -= 7
        month = [[]]
        week = 0
        start = datetime(year=self.year, month=self.month, day=1, tzinfo=utc)
        end = datetime(
            year=self.year, month=self.month, day=1, tzinfo=utc
        ) + relativedelta(months=1)

        occurrences = []
        cal = calendar.Calendar()
        cal.setfirstweekday(firstweekday)
        all_occurrences = self.get_queryset().filter(start_time__month=self.month, start_time__year=self.year)
        print '------------'
        print all_occurrences
        for day in cal.itermonthdays(self.year, self.month):
            current = False
            if day:
                date = datetime(year=self.year, month=self.month, day=day,
                                tzinfo=utc)
                if date.date() == now().date():
                    current = True
            month[week].append((day, all_occurrences.filter(start_time__day=day), current))
            if len(month[week]) == 7:
                month.append([])
                week += 1
        calendar.setfirstweekday(firstweekday)
        weekdays = [_(header) for header in calendar.weekheader(10).split()]
        ctx = {'month': month, 'date': date, 'weekdays': weekdays}
        return ctx
Exemplo n.º 4
0
def bulk_ajax(request):
  eventrepeat = get_object_or_404(EventRepeat,id=request.GET['eventrepeat_id'])
  if 'day_string' in request.POST:
    st = eventrepeat.start_time
    start = timezone.datetime(*([int(s) for s in request.POST['day_string'].split('-')]+[st.hour,st.minute]))
    if request.POST['action'] == 'remove':
      eventrepeat.month_occurrences.filter(start=start).delete()
    else:
      eventrepeat.eventoccurrence_set.get_or_create(
        start=start,
        end_time=eventrepeat.end_time,
        event=eventrepeat.event
      )
  occurrences = [arrow.get(eo.start).format("YYYY-M-D") for eo in eventrepeat.month_occurrences]
  months = []
  for month in range(5):
    start = arrow.now().replace(day=1,months=month)
    calendar.setfirstweekday(calendar.SUNDAY)
    months.append({
      'name': start.format("MMMM YYYY"),
      'weeks': calendar.monthcalendar(start.year, start.month),
      'number': "%s-%s"%(start.year,start.month)
    })
  return JsonResponse({
    'months': months,
    'occurrences': occurrences,
    'eventrepeat': eventrepeat.as_json,
  })
Exemplo n.º 5
0
Arquivo: cal.py Projeto: sqram/Cally
	def get_cal(self, m, y):
		calendar.setfirstweekday(calendar.SUNDAY)
		cal = calendar.monthcalendar(y, m)
		days = list()
		header = "sun mon tue wed thur fri sat".split(" ")
		cal.insert(0,header)
		return cal
Exemplo n.º 6
0
def	date(request, dates):
    gdate = int(dates)
    year = gdate//10000
    day = gdate%100
    month = (gdate%10000-day)//100

    if 'user_name' in request.session:
        session = dict({'user_name':request.session['user_name']})
    else:
            return HttpResponseRedirect(reverse('umbrella_system:login'))

    calendar.setfirstweekday(calendar.SUNDAY)
    dt = datetime.datetime.fromtimestamp(time.mktime((year, month+1, 1, 0, 0, 0, 0, 0, 0)))
    next_date = dict({'year':dt.year,'month':dt.month,})
    dt = datetime.datetime.fromtimestamp(time.mktime((year, month-1, 1, 0, 0, 0, 0, 0, 0)))
    last_date = dict({'year':dt.year,'month':dt.month,})
    cal = dict({'year':year,'month':month,'days':calendar.monthcalendar(year, month),})
    dt = datetime.datetime(year, month, day)
    rooms = Room.objects.all()
    i = 0
    roomset={}
    for rooma in rooms:
        orders = Order.objects.filter(room=rooma,order_day=dt)
        wari={}
        for order in orders:
            times = dict({'time':order.time_zone_id,'user':order.user.name})
            wari.update({order.time_zone_id:times})
        room = dict({'name':rooma.name,'wari':wari})
        roomset.update({rooma.name:room})
        i += 1

    contexts = dict({'cal':cal,'next_date':next_date,'last_date':last_date,'rooms':Room.objects.all(),'roomset':roomset,'i':i})

    return HttpResponse(render(request,'umbrella_system/date.html',contexts))
Exemplo n.º 7
0
 def fnFillCalendar(self):
   init_x_pos = 20
   arr_y_pos = [110,130,150,170,190,210]
   intposarr = 0
   self.canvas.delete("DayButton")
   self.canvas.update()
   intyear = int(self.year_var.get())
   calendar.setfirstweekday(6)
   monthcal = calendar.monthcalendar(intyear, self.intmonth)  
   for row in monthcal:
       xpos = init_x_pos 
       ypos = arr_y_pos[intposarr]
       for item in row:    
           stritem = str(item)
           if stritem == "0":
               xpos += 27
           else :
               tagNumber = tuple((self.tagBaseNumber,stritem))
               self.canvas.create_text(xpos, ypos , text=stritem, 
               font=fnta,tags=tagNumber) 
               xpos += 27
       intposarr += 1
   self.canvas.tag_bind ("DayButton", "<ButtonRelease-1>", self.fnClickNumber)
   self.canvas.tag_bind ("DayButton", "<Enter>", self.fnOnMouseOver)
   self.canvas.tag_bind ("DayButton", "<Leave>", self.fnOnMouseOut)   
Exemplo n.º 8
0
def setup_locale(lc_all: str,
                 first_weekday: int = None,
                 *,
                 lc_collate: str = None,
                 lc_ctype: str = None,
                 lc_messages: str = None,
                 lc_monetary: str = None,
                 lc_numeric: str = None,
                 lc_time: str = None) -> str:
    """Shortcut helper to setup locale for backend application.

    :param lc_all: Locale to use.
    :param first_weekday:
        Weekday for start week. 0 for Monday, 6 for Sunday. By default: None
    :param lc_collate: Collate locale to use. By default: ``<lc_all>``
    :param lc_ctype: Ctype locale to use. By default: ``<lc_all>``
    :param lc_messages: Messages locale to use. By default: ``<lc_all>``
    :param lc_monetary: Monetary locale to use. By default: ``<lc_all>``
    :param lc_numeric: Numeric locale to use. By default: ``<lc_all>``
    :param lc_time: Time locale to use. By default: ``<lc_all>``
    """
    if first_weekday is not None:
        calendar.setfirstweekday(first_weekday)

    locale.setlocale(locale.LC_COLLATE, lc_collate or lc_all)
    locale.setlocale(locale.LC_CTYPE, lc_ctype or lc_all)
    locale.setlocale(locale.LC_MESSAGES, lc_messages or lc_all)
    locale.setlocale(locale.LC_MONETARY, lc_monetary or lc_all)
    locale.setlocale(locale.LC_NUMERIC, lc_numeric or lc_all)
    locale.setlocale(locale.LC_TIME, lc_time or lc_all)

    return locale.setlocale(locale.LC_ALL, lc_all)
Exemplo n.º 9
0
 def __init__(self, year, months=[], firstDay=calendar.SUNDAY, drawSauce=True, sepMonths='/', lang='English'):
     """ Setup basic things """
     # params
     self.drawSauce = drawSauce # draw supplementary image?
     self.year = year
     self.months = months
     self.lang = lang
     # day order
     self.dayOrder = localization[self.lang][1]
     if firstDay == calendar.SUNDAY:
         dl = self.dayOrder[:6]
         dl.insert(0, self.dayOrder[6])
         self.dayOrder = dl
     self.mycal = calendar.Calendar(firstDay)
     self.layerImg = 'Calendar image'
     self.layerCal = 'Calendar'
     self.pStyleDate = "Date" # paragraph styles
     self.pStyleWeekday = "Weekday"
     self.pStyleMonth = "Month"
     self.pStyleWeekNo = "WeekNo"
     self.masterPage = "Weekdays"
     self.sepMonths = sepMonths
     # settings
     self.firstPage = True # create only 2nd 3rd ... pages. No 1st one.
     calendar.setfirstweekday(firstDay)
     progressTotal(len(months))
Exemplo n.º 10
0
def reservation_day(request):
	ts = Table.objects.all()
	if not ts:
		message = 'ERROR: A table map has not yet been set up.'
		return render_to_response('index.html', {
			'message': message,
		})
	months = [
		'January', 'February', 'March', 'April', 'May', 'June', 
		'July', 'August', 'September', 'October', 'November', 'December',
	]
	calendar.setfirstweekday(calendar.SUNDAY)
	this_year = int(time.strftime('%Y', time.localtime()))
	next_year = this_year
	this_month = int(time.strftime('%m', time.localtime()))
	next_month = this_month + 1
	if next_month == 13:
		next_year = next_year + 1
		next_month = 1
	this_month_cal = calendar.monthcalendar(this_year, this_month)
	next_month_cal = calendar.monthcalendar(next_year, next_month)
	this_month_year = '%s %d' % (months[this_month-1], this_year)
	next_month_year = '%s %d' % (months[next_month-1], next_year)
	message = 'Select the day when you would like to reserve a table.'
	return render_to_response('reservation_day.html', {
		'message': message,
		'this_month_cal': this_month_cal,
		'next_month_cal': next_month_cal,
		'this_month_year': this_month_year,
		'next_month_year': next_month_year,
	})
Exemplo n.º 11
0
 def __init__(self):
     now = datetime.now()
     calendar.setfirstweekday(calendar.SUNDAY)
     self.year = now.year
     self.month = now.month
     self.day = now.day
     self.format_string = str('%s'+'%3s'*6)
Exemplo n.º 12
0
def month_calendar(year, month, days, service):
    calendar.setfirstweekday(calendar.SUNDAY)
    month_calendar = calendar.monthcalendar(int(year), int(month))
    
    month_name = calendar.month_name[int(month)]
    month_href = reverse('services:month', args=(service.slug, year, month))

    html = '<table><thead>'
    html += '<tr><th colspan="7"><a href="{0}">{1}</a></th></tr>'.format(month_href, month_name)
    html += '<tr><th>s</th><th>m</th><th>t</th><th>w</th><th>t</th><th>f</th><th>s</th></tr>'
    html += '</thead><tbody>'
    for week in month_calendar:
        html += '<tr>'
        for day in week:
            if day == 0:
                str_day = ''
            else:
                str_day = str(day).zfill(2)
            if str_day in days:
                day_href = reverse('services:day', args=(service.slug, year, month, str_day))
                html += '<td><a href="{0}">{1}</a></td>'.format(day_href, str_day)
            else:
                html += '<td>{0}</td>'.format(str_day)
        html += '</tr>'
    html += '</tbody></table>'
    return html
Exemplo n.º 13
0
def prob2():

  import datetime, calendar

  instring = requestString("Please enter your birthday (in format 1776-07-04)") 
  hold = instring.split("-")
 
  calendar.setfirstweekday(6) #make calendar Sun->Sat
  calMonth = calendar.month(int(hold[0]), int(hold[1])) #hold[0] is year, hold[1] is month
  printNow(" ")
  printNow(calMonth)

  today = datetime.date.today()
  holdtheyear = today.strftime("%Y")  #save off this year string
  
  #today
  t_day = datetime.datetime(int(holdtheyear), int(today.strftime("%m")), int(today.strftime("%d")))
  
  # next birthday
  nb_day = datetime.datetime(int(holdtheyear), int(hold[1]), int(hold[2]))
  
  diff = nb_day - t_day
  printNow("Just %i days until your next birthday!" % diff.days)
  
  #days of week from Mon-Sun
  dow = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
  
  hold4th = datetime.datetime(1776, 7, 4).weekday()  
  printNow("\nThe 4th of July, 1776 was a %s." % dow[hold4th])
Exemplo n.º 14
0
def events_month(request, year, month):
    events_from = datetime(int(year), int(month), 1)
    # the following three lines converts the weeks_in_month name to norwegian (e.g. January -> Januar)
    import locale

    locale.setlocale(locale.LC_TIME, 'nb_NO.UTF-8')
    month_name = events_from.strftime("%B")

    # https://docs.djangoproject.com/en/dev/topics/db/queries/#querysets-are-lazy)
    # force evaluation of the queryset here, to avoid a bunch of queries on further lookups on the set.
    events = list(CalendarEntry.objects.filter(entry_date__year=year, entry_date__month=month))

    calendar.setfirstweekday(calendar.MONDAY)

    weeks_in_month = []
    for weekdays in calendar.monthcalendar(events_from.year, events_from.month):
        week = []
        for weekday in weekdays:
            events_found = []
            for event in events:
                if event.entry_date.day == weekday:
                    events_found.append(event)
            week.append((weekday, events_found))
        weeks_in_month.append(week)

    events_to_context = {
        'weeks_in_month': weeks_in_month,
        'month_name': month_name,
        'year': year,
        'month': month,
        'system_message': SYSTEM_MESSAGE
        }

    return render_to_response('geocal/events_month.html', events_to_context, context_instance=RequestContext(request))
Exemplo n.º 15
0
 def validate_options(self):
     #inkex.errormsg( self.options.input_encode )
     # Convert string names lists in real lists
     m = re.match('\s*(.*[^\s])\s*', self.options.month_names)
     self.options.month_names = re.split('\s+', m.group(1))
     m = re.match('\s*(.*[^\s])\s*', self.options.day_names)
     self.options.day_names = re.split('\s+', m.group(1))
     # Validate names lists
     if len(self.options.month_names) != 12:
         inkex.errormsg('The month name list "' + \
                      str(self.options.month_names) + \
                      '" is invalid. Using default.')
         self.options.month_names = ['January', 'February', 'March',
                                     'April', 'May', 'June',
                                     'July', 'August', 'September',
                                     'October', 'November', 'December']
     if len(self.options.day_names) != 7:
         inkex.errormsg('The day name list "'+
                      str(self.options.day_names)+
                      '" is invalid. Using default.')
         self.options.day_names = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu',
                                   'Fri','Sat']
     # Convert year 0 to current year
     if self.options.year == 0: self.options.year = datetime.today().year
     # Year 1 starts it's week at monday, obligatorily
     if self.options.year == 1: self.options.start_day = 'mon'
     # Set the calendar start day
     if self.options.start_day=='sun':
         calendar.setfirstweekday(6)
     else:
         calendar.setfirstweekday(0)
     # Convert string numbers with unit to user space float numbers
     self.options.month_width  = self.unittouu( self.options.month_width )
     self.options.month_margin = self.unittouu( self.options.month_margin )
Exemplo n.º 16
0
def vertical_month(month=datetime.date.today().month,
                   year=datetime.date.today().year,
                   today=datetime.date.today(),
                   weeknumber=False,
                   count=3,
                   firstweekday=0):
    """
    returns a list() of str() of weeks for a vertical arranged calendar

    :param month: first month of the calendar,
                  if non given, current month is assumed
    :type month: int
    :param year: year of the first month included,
                 if non given, current year is assumed
    :type year: int
    :param today: day highlighted, if non is given, current date is assumed
    :type today: datetime.date()
    :param weeknumber: if not False the iso weeknumber will be shown for each
                       week, if weeknumber is 'right' it will be shown in its
                       own column, if it is 'left' it will be shown interleaved
                       with the month names
    :type weeknumber: str/bool
    :returns: calendar strings,  may also include some
              ANSI (color) escape strings
    :rtype: list() of str()
    """

    khal = list()
    w_number = '    ' if weeknumber == 'right' else ''
    calendar.setfirstweekday(firstweekday)
    _calendar = calendar.Calendar(firstweekday)
    khal.append(
        style('    ' + calendar.weekheader(2) + ' ' + w_number, bold=True)
    )
    for _ in range(count):
        for week in _calendar.monthdatescalendar(year, month):
            new_month = len([day for day in week if day.day == 1])
            strweek = str_week(week, today)
            if new_month:
                m_name = style(month_abbr(week[6].month).ljust(4), bold=True)
            elif weeknumber == 'left':
                m_name = \
                    style(' {:2} '.format(getweeknumber(week[0])), bold=True)
            else:
                m_name = '    '
            if weeknumber == 'right':
                w_number = \
                    style(' {}'.format(getweeknumber(week[0])), bold=True)
            else:
                w_number = ''

            sweek = m_name + strweek + w_number
            if sweek != khal[-1]:
                khal.append(sweek)
        month = month + 1
        if month > 12:
            month = 1
            year = year + 1
    return khal
Exemplo n.º 17
0
 def __init__(self,request,theDate):
     calendar.setfirstweekday(6)
     self.request = request
     self.givenDate = theDate
     self.monthday = datetime.datetime.date(theDate)
     self.monthList = ['January',  'February',  'March',  'April',  'May',
              'June',  'July',  'August',  'September',  'October',
              'November',  'December']
Exemplo n.º 18
0
 def buildMonthCalendar(self, year, month):
     """Python standard calendar for a given month
     :param year: interger. The year of the calendar
     :param month: integer. Month number
     :return: a list of day numbers list : [ [0,0,1,2,3,4,5], [6,7,8 ...] ...]
     """
     calendar.setfirstweekday(calendar.MONDAY)
     return calendar.monthcalendar(year, month)
 def buildMonthCalendar(self, year, month):
     """
     year: interger. The year of the calendar
     month: integer. Month number
     return a list of day number list : [ [0,0,1,2,3,4,5], [6,7,8 ...] ...]
     """
     calendar.setfirstweekday(calendar.MONDAY)
     return calendar.monthcalendar(year, month)
Exemplo n.º 20
0
 def __init__(self, owner, day=1):
     """owner - owner of this calendar, day - day to shown"""
     calendar.setfirstweekday(calendar.SUNDAY)
     self.owner = owner
     self.day = day
     self.curr = None
     self.db_cal = None
     self.db_events = None
Exemplo n.º 21
0
def getDays(offset=0):
    calendar.setfirstweekday(calendar.SUNDAY)
    # Days contains the abbrevations for the days of the week

    today = date.today() + timedelta(offset*7)
    delta = timedelta((today.weekday()+1) % 7)
    first = today - delta
    delta = timedelta(1)

    days = []
    for i in range(6, 13):
        isToday = (offset == 0 and (i % 7) == ((today.weekday()) % 7))
        days.append({"title": calendar.day_abbr[i % 7],
                     "today": isToday})

    year = first.strftime("%Y")
    month = first.strftime("%B")
    day = first.strftime("%d").lstrip("0")

    last = first + timedelta(6)

    header = month + " " + day
    if (year != last.strftime("%Y")):
        header += ", " + year
    header += " - "

    if (month != last.strftime("%B")):
        header += " " + last.strftime("%B") + " "

    header += last.strftime("%d").lstrip("0") + ", " + last.strftime("%Y")

    dates = []
    for i in range(7):
        dates.append({"year": (first.year),
                      "month": (first.month-1),
                      "day": (first.day)})

        days[i]['title'] += " "+first.strftime("%m/").lstrip("0") + \
                            first.strftime("%d").lstrip("0")

        first = first + delta

    hour = 12
    hours = []

    for i in range(24):
        string = str(hour)
        if (i < 12):
            string = string + " AM"
        else:
            string = string + " PM"
        hours.append(string)
        if hour == 12:
            hour = 1
        else:
            hour = hour + 1

    return days, hours, dates, header
Exemplo n.º 22
0
def getWeeks(offset=0):
    calendar.setfirstweekday(calendar.SUNDAY)
    # Days contains the abbrevations for the days of the week

    today = date.today()
    current = date.today() + relativedelta(months=offset)
    first, monthrange = calendar.monthrange(current.year, current.month)
    first = (first+1) % 7
    previousMonth = current + relativedelta(months=-1)
    hold, previousMonthrange = calendar.monthrange(previousMonth.year, previousMonth.month)

    days = []
    for i in range(6, 13):
        days.append({"title": calendar.day_abbr[i % 7]})

    header = current.strftime("%B %Y")

    dates = []
    weeks = []
    for i in range(first):
        isToday = False
        if (today.year == previousMonth.year and
                    today.month == previousMonth.month and
                    today.day == previousMonthrange+i-first):

            isToday = True

        dates.append({"date": previousMonthrange+i-first+1,
                      "thisMonth": False,
                      "today": isToday})

    for i in range(first, monthrange+first):
        isToday = False
        if (current.year == today.year and
                    current.month == today.month and
                    i == current.day - first + 1):

            isToday = True
        dates.append({"date": i-first+1, "thisMonth": True, "today": isToday})
        if (i % 7 == 6):
            weeks.append(dates)
            dates = []

    nextMonth = (current + relativedelta(months=1))
    for i in range(monthrange+first+1, monthrange+first+8):
        isToday = False
        if (today.year == nextMonth.year and
                    today.month == nextMonth.month and
                    today.day == i - monthrange - first):

            isToday = True

        dates.append({"date": i - monthrange-first, "thisMonth": False, "today": isToday})
        if ((i-1) % 7 == 6):
            weeks.append(dates)
            break

    return days, weeks, header
Exemplo n.º 23
0
 def get_time_range(self):
     now = datetime.datetime.now()
     today = datetime.datetime(now.year, now.month, now.day)
     
     # Set first weekday to Sunday
     calendar.setfirstweekday(6)
     
     prev_range = []
     if self.time_period == 'DA':
         time_range = [today + datetime.timedelta(minutes=10 * x) for x in range(now.hour * 6 + now.minute / 10 + 1)]
         prev_range = [time - datetime.timedelta(days=7) for time in time_range]
         time_interval = 'minute'
     elif self.time_period == '24':
         time_range = [now - datetime.timedelta(minutes=10 * x) for x in range(24 * 6 + 1)]
         time_range.reverse()
         prev_range = [time - datetime.timedelta(days=7) for time in time_range]
         time_interval = 'minute'
     elif self.time_period == 'WE':
         day_of_week = calendar.weekday(now.year, now.month, now.day)
         first_week_day = today - datetime.timedelta(days=day_of_week)
         time_range = [first_week_day + datetime.timedelta(hours=x) for x in range(now.hour + day_of_week * 24 + 1)]
         prev_range = [time - datetime.timedelta(days=7) for time in time_range]
         time_interval = 'hour'
     elif self.time_period == '7D':
         time_range = [now - datetime.timedelta(hours=x) for x in range(24 * 7 + 1)]
         time_range.reverse()
         prev_range = [time - datetime.timedelta(days=7) for time in time_range]
         time_interval = 'hour'
     elif self.time_period == 'MO':
         first_month_day = datetime.datetime(now.year, now.month, 1)
         time_range = [first_month_day + datetime.timedelta(days=x) for x in range(now.day + 1)]
         if now.month == 1:
             prev_first_month_day = datetime.datetime(now.year - 1, 12, 1)
         else:
             prev_first_month_day = datetime.datetime(now.year, now.month - 1, 1)
         #TODO fix bug here if previous month has less days than this one
         prev_range = [prev_first_month_day + datetime.timedelta(days=x) for x in range(now.day + 1)]
         time_interval = 'day'
     elif self.time_period == '28':
         time_range = [now - datetime.timedelta(days=x) for x in range(28 + 1)]
         time_range.reverse()
         prev_range = [time - datetime.timedelta(days=28) for time in time_range]
         time_interval = 'day'
     elif self.time_period == 'YR':
         first_year_day = datetime.datetime(now.year, 1, 1)
         day_of_year = now.timetuple().tm_yday
         time_range = [first_year_day + datetime.timedelta(days=10 * x) for x in range(day_of_year / 10 + 1)]
         prev_first_year_day = datetime.datetime(now.year - 1, 1, 1)
         prev_range = [prev_first_year_day + datetime.timedelta(days=10 * x) for x in range(day_of_year / 10 + 1)]
         time_interval = 'month'
     elif self.time_period == '36':
         time_range = [now - datetime.timedelta(days=365) for x in range(365 + 1)]
         time_range.reverse()
         prev_range = [time - datetime.timedelta(days=365) for time in time_range]
         time_interval = 'month'
     return time_range, prev_range, time_interval
     """
Exemplo n.º 24
0
 def make_calendar(year, month):
     # just first days of weeks are required
     z_trim = lambda x: [d for d in x if d != 0]
     cal.setfirstweekday(cal.MONDAY)
     weeks = cal.monthcalendar(year, month)
     weeks[0] = z_trim(weeks[0])
     weeks[-1] = z_trim(weeks[-1])
     logger.Logger.debug("Calendar for month {}".format(str([(wd[0], wd[-1]) for wd in weeks])))
     return [(wd[0], wd[-1]) for wd in weeks]
Exemplo n.º 25
0
	def _renderTemplate(self, node, year, month, links, dayrenderer):
		fd = calendar.firstweekday()
		calendar.setfirstweekday(self._firstWeekday)
		weeks = calendar.monthcalendar(year, month) # a list of seven-item lists
		calendar.setfirstweekday(fd)
		if len(weeks) == 5:
			weeks.append([0, 0, 0, 0, 0, 0, 0])
		node.caption.content = self._months[month - 1] + " " + str(year) # set table caption
		node.week.repeat(self._renderWeek, weeks, links, self._WeekendTrackerGen(self._isSundayFirst), year, month, dayrenderer) # render weekly rows
Exemplo n.º 26
0
 def update(self, clear=True):
     calendar.setfirstweekday(self.firstWeekDay)
     if clear: self.clear()
     if self.hidden:
         self.clear()
         return False
     if not self.value:
         self.addstr(self.rely, self.relx, "No value set")
     else:
         year  = self.value.year
         month = self.value.month
         monthname = self.value.strftime('%B')
         day   = self.value.day
     
         # Print the Title Line
         if self.do_colors():
             self.parent.curses_pad.addstr(self.rely, self.relx, ("%s, %s" % (monthname, year)), 
                                                 self.parent.theme_manager.findPair(self))
         else:
             self.parent.curses_pad.addstr(self.rely, self.relx, ("%s, %s" % (monthname, year)))
     
         # Print the day names
         # weekheader puts an extra space at the end of each name
         if self.do_colors():
             self.parent.curses_pad.addstr(self.rely+1, self.relx, calendar.weekheader(self.__class__.DAY_FIELD_WIDTH - 1),
                                             self.parent.theme_manager.findPair(self, 'LABEL'))
         else:
             self.parent.curses_pad.addstr(self.rely+1, self.relx, calendar.weekheader(self.__class__.DAY_FIELD_WIDTH - 1))
     
         # Print the days themselves
         cal_data = calendar.monthcalendar(year, month)
         print_line = self.rely+2
     
         for calrow in cal_data:
             print_column = self.relx
         
             for thisday in calrow:
                 if thisday is 0:
                     pass
                 elif day == thisday:
                     if self.do_colors():
                         self.parent.curses_pad.addstr(print_line, print_column, str(thisday), curses.A_STANDOUT | self.parent.theme_manager.findPair(self, self.color))
                     else:
                         self.parent.curses_pad.addstr(print_line, print_column, str(thisday), curses.A_STANDOUT)
                 else:
                     if self.do_colors():
                         self.parent.curses_pad.addstr(print_line, print_column, str(thisday), self.parent.theme_manager.findPair(self, self.color))
                     else:
                         self.parent.curses_pad.addstr(print_line, print_column, str(thisday))
                 print_column += self.__class__.DAY_FIELD_WIDTH
         
             print_line += 1
         # Print some help
         if self.do_colors():
             self.parent.curses_pad.addstr(self.rely+9, self.relx, "keys: dwmyDWMYt", self.parent.theme_manager.findPair(self, 'LABEL'))
         else:
             self.parent.curses_pad.addstr(self.rely+9, self.relx, "keys: dwmyDWMYt")
Exemplo n.º 27
0
    def manage_editProperties(self,first_day_week,REQUEST=None):
        """ Manage the edited values """

        if first_day_week == 'Monday':
            calendar.setfirstweekday(0)
        else:
            calendar.setfirstweekday(6)
        self.ZCacheable_invalidate()
        return PropertyManager.manage_editProperties(self,REQUEST)
Exemplo n.º 28
0
def get_calendar(year, month):
    blank_week = [0, 0, 0, 0, 0, 0, 0]
    calendar.setfirstweekday(calendar.SUNDAY)
    c = calendar.monthcalendar(year, month)
    if len(c) == 4:
        c.append(blank_week)
    if len(c) == 5:
        c.append(blank_week)
    return c    
Exemplo n.º 29
0
def date_checker():
    number_sundays = 0
    calendar.setfirstweekday(6)

    for year in range(1901, 2001, 1):
        for month in range(1, 13, 1):
            if calendar.weekday(year, month, 1) == calendar.SUNDAY:
                number_sundays += 1
    return number_sundays
Exemplo n.º 30
0
def setup_locale(locale: str, first_weekday: int = None) -> str:
    """Setup locale for backend application.

    :param locale: Locale to use.
    :param first_weekday:
        Weekday for start week. 0 for Monday, 6 for Sunday. By default: None
    """
    if first_weekday is not None:
        calendar.setfirstweekday(first_weekday)
    return setlocale(LC_ALL, locale)
def main():
    while True:

        time = datetime.now()
        hour = int(time.strftime("%-H"))
        month = int(time.now().strftime('%-m'))
        year = int(time.now().strftime('%Y'))

        for i in range(1):
            print('_________Starting new loop___________' + '\n')
            """At the following hours (midnight, midday and 6 pm), perform
               a calibration of the display's colours"""

            if hour is 0 or hour is 12 or hour is 18:
                print('performing calibration for colours now')
                calibration()

            print(
                'Date:',
                time.strftime('%a %-d %b %y') + ', time: ' +
                time.strftime('%H:%M') + '\n')
            """Create a blank white page, for debugging, change mode to
            to 'RGB' and and save the image by uncommenting the image.save
            line at the bottom"""
            image = Image.new('L', (EPD_HEIGHT, EPD_WIDTH), 'white')
            draw = (ImageDraw.Draw(image)).bitmap
            """Draw the icon with the current month's name"""
            image.paste(im_open(mpath + str(time.strftime("%B") + '.jpeg')),
                        monthplace)
            """Draw a line seperating the weather and Calendar section"""
            image.paste(seperator, seperatorplace)
            """Draw the icons with the weekday-names (Mon, Tue...) and
               draw a circle  on the current weekday"""
            if (week_starts_on == "Monday"):
                calendar.setfirstweekday(calendar.MONDAY)
                image.paste(weekmon, weekplace)
                draw(weekdaysmon[(time.strftime("%a"))], weekday)

            if (week_starts_on == "Sunday"):
                calendar.setfirstweekday(calendar.SUNDAY)
                image.paste(weeksun, weekplace)
                draw(weekdayssun[(time.strftime("%a"))], weekday)
            """Using the built-in calendar function, draw icons for each
               number of the month (1,2,3,...28,29,30)"""
            cal = calendar.monthcalendar(time.year, time.month)
            #print(cal) #-uncomment for debugging with incorrect dates

            for numbers in cal[0]:
                image.paste(im_open(dpath + str(numbers) + '.jpeg'),
                            positions['a' + str(cal[0].index(numbers) + 1)])
            for numbers in cal[1]:
                image.paste(im_open(dpath + str(numbers) + '.jpeg'),
                            positions['b' + str(cal[1].index(numbers) + 1)])
            for numbers in cal[2]:
                image.paste(im_open(dpath + str(numbers) + '.jpeg'),
                            positions['c' + str(cal[2].index(numbers) + 1)])
            for numbers in cal[3]:
                image.paste(im_open(dpath + str(numbers) + '.jpeg'),
                            positions['d' + str(cal[3].index(numbers) + 1)])
            for numbers in cal[4]:
                image.paste(im_open(dpath + str(numbers) + '.jpeg'),
                            positions['e' + str(cal[4].index(numbers) + 1)])
            try:
                for numbers in cal[5]:
                    image.paste(
                        im_open(dpath + str(numbers) + '.jpeg'),
                        positions['f' + str(cal[5].index(numbers) + 1)])
            except IndexError:
                pass
            """Custom function to display text on the E-Paper.
            Tuple refers to the x and y coordinates of the E-Paper display,
            with (0, 0) being the top left corner of the display."""
            def write_text(box_width, box_height, text, tuple):
                text_width, text_height = font.getsize(text)
                if (text_width, text_height) > (box_width, box_height):
                    raise ValueError('Sorry, your text is too big for the box')
                else:
                    x = int((box_width / 2) - (text_width / 2))
                    y = int((box_height / 2) - (text_height / 2))
                    space = Image.new('L', (box_width, box_height), color=255)
                    ImageDraw.Draw(space).text((x, y), text, fill=0, font=font)
                    image.paste(space, tuple)

            """ Handling Openweathermap API"""
            print("Connecting to Openweathermap API servers...")
            owm = pyowm.OWM(api_key)
            if owm.is_API_online() is True:
                observation = owm.weather_at_place(location)
                print("weather data:")
                weather = observation.get_weather()
                weathericon = weather.get_weather_icon_name()
                Humidity = str(weather.get_humidity())
                cloudstatus = str(weather.get_clouds())
                weather_description = (str(weather.get_status()))

                if units == "metric":
                    Temperature = str(
                        int(weather.get_temperature(unit='celsius')['temp']))
                    windspeed = str(int(weather.get_wind()['speed']))
                    write_text(50, 35, Temperature + " °C", (334, 0))
                    write_text(100, 35, windspeed + " km/h", (114, 0))

                if units == "imperial":
                    Temperature = str(
                        int(weather.get_temperature('fahrenheit')['temp']))
                    windspeed = str(int(weather.get_wind()['speed'] * 0.621))
                    write_text(50, 35, Temperature + " °F", (334, 0))
                    write_text(100, 35, windspeed + " mph", (114, 0))

                if hours == "24":
                    sunrisetime = str(
                        datetime.fromtimestamp(
                            int(weather.get_sunrise_time(
                                timeformat='unix'))).strftime('%-H:%M'))
                    sunsettime = str(
                        datetime.fromtimestamp(
                            int(weather.get_sunset_time(
                                timeformat='unix'))).strftime('%-H:%M'))

                if hours == "12":
                    sunrisetime = str(
                        datetime.fromtimestamp(
                            int(weather.get_sunrise_time(
                                timeformat='unix'))).strftime('%-I:%M'))
                    sunsettime = str(
                        datetime.fromtimestamp(
                            int(weather.get_sunset_time(
                                timeformat='unix'))).strftime('%-I:%M'))

                print('Temperature: ' + Temperature + ' °C')
                print('Humidity: ' + Humidity + '%')
                print('Icon code: ' + weathericon)
                print('weather-icon name: ' + weathericons[weathericon])
                print('Wind speed: ' + windspeed + 'km/h')
                print('Sunrise-time: ' + sunrisetime)
                print('Sunset time: ' + sunsettime)
                print('Cloudiness: ' + cloudstatus + '%')
                print('Weather description: ' + weather_description + '\n')
                """Drawing the fetched weather icon"""
                image.paste(
                    im_open(wpath + weathericons[weathericon] + '.jpeg'),
                    wiconplace)
                """Drawing the fetched temperature"""
                image.paste(tempicon, tempplace)
                """Drawing the fetched humidity"""
                image.paste(humicon, humplace)
                write_text(50, 35, Humidity + " %", (334, 35))
                """Drawing the fetched sunrise time"""
                image.paste(sunriseicon, sunriseplace)
                write_text(50, 35, sunrisetime, (249, 0))
                """Drawing the fetched sunset time"""
                image.paste(sunseticon, sunsetplace)
                write_text(50, 35, sunsettime, (249, 35))
                """Drawing the wind icon"""
                image.paste(windicon, windiconspace)
                """Write a short weather description"""
                write_text(144, 35, weather_description, (70, 35))

            else:
                image.paste(no_response, wiconplace)
            """Filter upcoming events from your iCalendar/s"""
            print('Fetching events from your calendar' + '\n')
            events_this_month = []
            upcoming = []
            for icalendars in ical_urls:
                decode = str(urlopen(icalendars).read().decode())
                #fix a bug related to Alarm action by replacing parts of the icalendar
                fix_e_1 = decode.replace(
                    'BEGIN:VALARM\r\nACTION:NONE',
                    'BEGIN:VALARM\r\nACTION:DISPLAY\r\nDESCRIPTION:')
                fix_e_2 = fix_e_1.replace(
                    'BEGIN:VALARM\r\nACTION:EMAIL',
                    'BEGIN:VALARM\r\nACTION:DISPLAY\r\nDESCRIPTION:')
                #uncomment line below to display your calendar in ical format
                #print(fix_e_2)
                ical = Calendar(fix_e_2)
                for events in ical.events:
                    if time.now().strftime('%-m %Y') == (events.begin).format(
                            'M YYYY') and (events.begin).format(
                                'DD') >= time.now().strftime('%d'):
                        upcoming.append({
                            'date': events.begin.format('DD MMM'),
                            'event': events.name
                        })
                        events_this_month.append(
                            int((events.begin).format('D')))
                    if month == 12:
                        if (1, year + 1) == (1, int((events.begin).year)):
                            upcoming.append({
                                'date':
                                events.begin.format('DD MMM'),
                                'event':
                                events.name
                            })
                    if month != 12:
                        if (month + 1,
                                year) == (events.begin).format('M YYYY'):
                            upcoming.append({
                                'date':
                                events.begin.format('DD MMM'),
                                'event':
                                events.name
                            })  # HS sort events by date

            def takeDate(elem):
                return elem['date']

            upcoming.sort(key=takeDate)

            del upcoming[4:]
            # uncomment the following 2 lines to display the fetched events
            # from your iCalendar
            print('Upcoming events:')
            print(upcoming)

            #Credit to Hubert for suggesting truncating event names
            def write_text_left(box_width, box_height, text, tuple):
                text_width, text_height = font.getsize(text)
                while (text_width, text_height) > (box_width, box_height):
                    text = text[0:-1]
                    text_width, text_height = font.getsize(text)
                y = int((box_height / 2) - (text_height / 2))
                space = Image.new('L', (box_width, box_height), color=255)
                ImageDraw.Draw(space).text((0, y), text, fill=0, font=font)
                image.paste(space, tuple)

            """Write event dates and names on the E-Paper"""
            for dates in range(len(upcoming)):
                write_text(70, 25, (upcoming[dates]['date']),
                           date_positions['d' + str(dates + 1)])

            for events in range(len(upcoming)):
                write_text_left(314, 25, (upcoming[events]['event']),
                                event_positions['e' + str(events + 1)])
            """Draw smaller squares on days with events"""
            for numbers in events_this_month:
                if numbers in cal[0]:
                    draw(positions['a' + str(cal[0].index(numbers) + 1)],
                         eventicon)
                if numbers in cal[1]:
                    draw(positions['b' + str(cal[1].index(numbers) + 1)],
                         eventicon)
                if numbers in cal[2]:
                    draw(positions['c' + str(cal[2].index(numbers) + 1)],
                         eventicon)
                if numbers in cal[3]:
                    draw(positions['d' + str(cal[3].index(numbers) + 1)],
                         eventicon)
                if numbers in cal[4]:
                    draw(positions['e' + str(cal[4].index(numbers) + 1)],
                         eventicon)
                try:
                    if numbers in cal[5]:
                        draw(positions['f' + str(cal[5].index(numbers) + 1)],
                             eventicon)
                except IndexError:
                    pass
            """Draw a larger square on today's date"""
            today = time.day
            if today in cal[0]:
                draw(positions['a' + str(cal[0].index(today) + 1)], dateicon)
            if today in cal[1]:
                draw(positions['b' + str(cal[1].index(today) + 1)], dateicon)
            if today in cal[2]:
                draw(positions['c' + str(cal[2].index(today) + 1)], dateicon)
            if today in cal[3]:
                draw(positions['d' + str(cal[3].index(today) + 1)], dateicon)
            if today in cal[4]:
                draw(positions['e' + str(cal[4].index(today) + 1)], dateicon)
            try:
                if today in cal[5]:
                    draw(positions['f' + str(cal[5].index(today) + 1)],
                         dateicon)
            except IndexError:
                pass

            print('Initialising E-Paper Display')
            epd.init()
            sleep(5)
            print('Converting image to data and sending it to the display')
            print('This may take a while...' + '\n')
            epd.display_frame(epd.get_frame_buffer(image.rotate(270,
                                                                expand=1)))
            # Uncomment following line to save image
            #image.save(path+'test.png')
            del events_this_month[:]
            del upcoming[:]
            print('Data sent successfully')
            print('Powering off the E-Paper until the next loop' + '\n')
            epd.sleep()

            for i in range(1):
                nexthour = ((60 - int(time.strftime("%-M"))) * 60) - (int(
                    time.strftime("%-S")))
                sleep(nexthour)
Exemplo n.º 32
0
def localize(locale_name: str = 'pl_PL.UTF-8',
             first_weekday: int = calendar.MONDAY):
    """Set program locale and first day of the week."""
    locale.setlocale(locale.LC_ALL, locale_name)
    calendar.setfirstweekday(first_weekday)
Exemplo n.º 33
0
import calendar
import itertools
import logging
from datetime import datetime, timedelta, time
from dateutil import parser
from django import http
from django.db import models
from django.template.context import RequestContext
from django.shortcuts import get_object_or_404, render

from .models import Event, Occurrence
from . import utils, forms
from .conf import swingtime_settings

if swingtime_settings.CALENDAR_FIRST_WEEKDAY is not None:
    calendar.setfirstweekday(swingtime_settings.CALENDAR_FIRST_WEEKDAY)


def event_listing(request,
                  template='swingtime/event_list.html',
                  events=None,
                  **extra_context):
    '''
    View all ``events``.
    
    If ``events`` is a queryset, clone it. If ``None`` default to all ``Event``s.
    
    Context parameters:
    
    ``events``
        an iterable of ``Event`` objects
Exemplo n.º 34
0
#!/usr/bin/env python3
# file : cal03.py
import calendar

calendar.setfirstweekday(6)  # 일요일을 첫 요일로..
calendar.prmonth(2012, 6)
Exemplo n.º 35
0
#showing a calender in python with ***Kelly***

#import calender built-in python libraries
import calendar
import dateime

#set the calendar to begin on a sunday
calendar.setfirstweekday(calendar.Sunday)

#shows the current year and month
print("----Python Calender---\n")
print(calendar.month(2020, 4), "\n")

#checks the current date in other system
current = datetime.datetime.now()

#this will indicate the current year,month, and give the day of the week
day_index = calendar.weekday(2020, 2, 7)
month_index = calendar.month(2020, 4)

#display full calendar

# %A is a full day
# %B is the full month name month
# %d is the day of the month
# &Y is the full year
print("Today is", current.strftime('%A %B %d %Y'))
Exemplo n.º 36
0
import calendar as cal
import matplotlib.pyplot as plt
import numpy as np

#I used code from https://stackoverflow.com/questions/42171990/create-a-one-month-calendar-with-events-on-it-in-python
#to create a calendar and modified it to meet the needs of this project.


cal.setfirstweekday(6)  # Setting Sunday as the first day
weekdays = 'Sun Mon Tues Wed Thurs Fri Sat'.split()
months = 'January February March April May June July August September October November December'.split()

class MyCalendar(object):

    particleCount = {}

    def __init__(self, year, month, fileName):

        temp = fileName.split('_')
        self.year = year
        self.month = month
        self.calendar = cal.monthcalendar(year, month)  #creates a list of lists for each week
        self.title = temp[0]

        data = open(fileName, "r")

        for line in data:
            word = line.split(' : ')
            day = word[0].split('/')
            self.particleCount.setdefault(int(day[1]), float(word[1]))
Exemplo n.º 37
0
def generateLogs(argv, printcmd, location="./"):
    # FIRST, figure out what days we are going to be printing logs for
    import calendar
    import datetime

    calendar.setfirstweekday(calendar.SUNDAY)

    if len(argv) < 4:
        printcmd("should be:\n\t%s <year> <month> <day> [number of days]\n" %
                 argv[0])
        return

    year = int(argv[1])
    month = int(argv[2])
    day = int(argv[3])
    today = datetime.datetime(year, month, day)

    numdays = 7
    try:
        numdays = int(argv[4])
    except IndexError:
        pass
    except ValueError:
        pass

    if today.weekday() != calendar.SUNDAY:
        printcmd(
            "This is supposed to start on a Sunday.  I assume you know what you're doing.\n"
        )

    dates = [today + datetime.timedelta(i) for i in xrange(numdays)]
    progEvents = dict([(date, []) for date in dates])
    opEvents = dict([(date, []) for date in dates])

    # SECOND, download the schedule
    # TODO: get rid of this and just talk to the database or whatever directly if
    #       that's at all possible!  This is a little silly!  If we're going to
    #       output things this way, we should put out an XML file!

    import urllib
    import codecs
    import model
    import json

    if True:
        printcmd("Downloading schedule...")
        sched_raw = unicode(
            urllib.urlopen(
                'http://www.wmbr.org/~lowe/templogs.php?start_year=%d&start_month=%d&start_day=%d&num_days=%d'
                % (year, month, day, numdays)).read(), "iso-8859-1")
        printcmd("Done.\n")
    else:
        printcmd("Using cached schedule (probably not what you want)...")
        sched_raw = "".join(
            codecs.open("templogs_sample", "r", "iso-8859-1").readlines())
        printcmd("Done.\n")

    timestrtodelta = lambda timestr: datetime.timedelta(
        0, sum(map(lambda x, y: int(x) * y, timestr.split(":"), [60 * 60, 60]))
    )

    printcmd("Adding shows...")

    schedule = json.loads(sched_raw)
    for date_str in schedule:
        year = int(date_str.split("-")[0])
        month = int(date_str.split("-")[1])
        day = int(date_str.split("-")[2])
        date = datetime.datetime(year, month, day)
        for show in schedule[date_str]:
            if show["type"] == "show":
                progEvents[date].append(
                    model.show(show["show_name"],
                               date + timestrtodelta(show["start_time"]),
                               date + timestrtodelta(show["end_time"]),
                               show["engineer"], show["producers"],
                               show["announcers"]))
            elif show["type"] == "signoff":
                opEvents[date].append((date + timestrtodelta(show["time"]),
                                       'TURN OFF TRANSMITTER'))
                progEvents[date].append(
                    model.signoff(date + timestrtodelta(show["time"])))
            elif show["type"] == "signon":
                opEvents[date].append(
                    (date + timestrtodelta(show["time"]),
                     'TEST EAS LIGHTS AND TURN ON TRANSMITTER'))
                progEvents[date].append(
                    model.signon(date + timestrtodelta(show["time"])))

    printcmd("Done.\n")

    # THIRD, compute other events that will occur on a particular day

    printcmd("Inserting FCC events (EAS tests, tower lights)...")

    import random

    # which dates should have an EAS test?
    easDays = [
        random.sample(dlist, 1)[0] for dlist in
        [[d for d in dates[i:i + 7] if d.strftime("%A") != "Sunday"]
         for i in xrange(len(dates) / 7)] if len(dlist) > 0
    ]

    # check the tower lights at civil twilight
    import twilight

    twilights = map(twilight.twilight, dates)
    for date in dates:
        twilightTime = twilight.twilight(date)
        opEvents[date].append((twilightTime, "CHECK TOWER LIGHTS: READING ="))

        # random EAS check once per week (taken from last version)
        # EAS tests must be conducted between 8:30 AM and twilight.
        # It is by WMBR convention that they are conducted at half
        # past an hour.  To be conservative, I also bring back the
        # late limit to half-past the previous hour from twilight,
        # thus avoiding any issues involving having the EAS test
        # and twilight too close together.
        if date in easDays:
            easDateTime = date + datetime.timedelta(
                0,
                random.randrange(8, twilightTime.hour) * 60 * 60 + 30 * 60)
            opEvents[date].append(
                (easDateTime, "CONDUCT REQUIRED WEEKLY EAS TEST"))

    printcmd("Done\n")

    # FOURTH, produce the pdf

    import os
    from reportlab.platypus import BaseDocTemplate, Frame, NextPageTemplate, PageBreak, PageTemplate, Table, TableStyle, Paragraph, flowables
    from reportlab.lib import colors
    from reportlab.lib.units import inch
    from reportlab.lib.pagesizes import letter
    from reportlab.lib.styles import getSampleStyleSheet
    from reportlab.rl_config import defaultPageSize
    import tablegen
    import progtablegen

    #letter paper
    PAGE_WIDTH, PAGE_HEIGHT = letter
    styles = getSampleStyleSheet()
    Elements = []

    def foot(title):
        def _foot(canvas, doc):
            today = datetime.date(doc.docEval("currentYear"),
                                  doc.docEval("currentMonth"),
                                  doc.docEval("currentDay"))
            canvas.saveState()
            canvas.setFont('Times-Roman', 20)
            canvas.drawString(0.3 * inch, PAGE_HEIGHT - 0.7 * inch, title)
            canvas.drawRightString(PAGE_WIDTH - 0.5 * inch,
                                   PAGE_HEIGHT - 0.7 * inch,
                                   today.strftime("%A, %b %d, %Y"))
            # this draws the page number on the outside corner of the log
            if doc.page % 2 == 0:
                canvas.drawString(0.3 * inch, 0.3 * inch,
                                  "Page %d" % (doc.page))
            else:
                canvas.drawRightString(PAGE_WIDTH - 0.5 * inch, 0.3 * inch,
                                       "Page %d" % (doc.page))
            canvas.restoreState()

        return _foot

    def title(title):
        def _title(canvas, doc):
            canvas.saveState()
            canvas.setFont('Times-Roman', 20)
            canvas.drawString(0.3 * inch, PAGE_HEIGHT - 0.7 * inch, title)
            canvas.drawRightString(
                PAGE_WIDTH - 0.5 * inch, PAGE_HEIGHT - 0.7 * inch,
                "%02d/%02d/%d — %02d/%02d/%d" %
                (dates[0].month, dates[0].day, dates[0].year, dates[-1].month,
                 dates[-1].day, dates[-1].year))
            canvas.restoreState()

        return _title

    def rulesPage():
        import op_title

        eltList = []
        paraPrefix = "<para"
        for elt in op_title.contents.split(paraPrefix):
            if len(elt.strip()) > 0:
                eltList.append(Paragraph(paraPrefix + elt, styles['Normal']))
        data = [["Henry Holtzman", "Home: 617-327-1298", "Work: 617-253-0319"],
                ["Ted Young", "Home: 617-776-7473", "Cell: 617-447-8439"]]
        eltList.append(Table(data, style=[('SIZE', (0, 0), (-1, -1), 12)]))
        return eltList

    def SigPage():
        data = [[
            "CUSTODIAN (print name)", "INITIALS", "TIME ON", "SIGNATURE",
            "TIME OFF", "SIGNATURE"
        ]] + [[None] * 6] * 22
        tableWidths = [2 * inch, None, None, 1.7 * inch, None, 1.7 * inch]
        tableHeights = [None] + [30] * 22
        t = Table(data, tableWidths, tableHeights)
        t.setStyle(
            TableStyle([
                ('VALIGN', (0, 0), (-1, 0), 'TOP'),
                ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                ('ALIGN', (3, 0), (3, 0), 'RIGHT'),
                ('ALIGN', (5, 0), (5, 0), 'RIGHT'),
                ('GRID', (0, 0), (1, -1), .6, colors.black),
                ('LINEABOVE', (2, 0), (3, -1), .6, colors.black),
                ('LINEAFTER', (3, 0), (3, -1), .6, colors.black),
                ('LINEABOVE', (4, 0), (5, -1), .6, colors.black),
                ('LINEAFTER', (5, 0), (5, -1), .6, colors.black),
                ('BOX', (0, 0), (-1, -1), 2, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
                ('VALIGN', (0, 1), (0, -1), 'MIDDLE'),
            ]))
        return t

    ## The operating log

    printcmd("Writing operating log...")

    doc = BaseDocTemplate(location + "oplog.pdf",
                          showBoundary=0,
                          allowSplitting=0,
                          leftMargin=0.5 * inch,
                          rightMargin=0.5 * inch,
                          topMargin=1.4 * inch,
                          bottomMargin=0.5 * inch)

    frameNormal = Frame(doc.leftMargin,
                        doc.bottomMargin,
                        doc.width,
                        doc.height,
                        id='normal')

    Elements.extend(rulesPage())

    for date in dates:
        Elements.append(flowables.DocAssign("currentYear", date.year))
        Elements.append(flowables.DocAssign("currentMonth", date.month))
        Elements.append(flowables.DocAssign("currentDay", date.day))
        tables = tablegen.make_day_tables(opEvents[date])
        Elements.append(NextPageTemplate('OTALogPage'))
        Elements.append(PageBreak())
        Elements.append(SigPage())
        for table in tables:
            Elements.append(NextPageTemplate('OpLogPage'))
            Elements.append(PageBreak())
            Elements.append(table)

    doc.addPageTemplates([
        PageTemplate(id='Title',
                     frames=frameNormal,
                     onPage=title("WMBR Operating Log"),
                     pagesize=letter),
        PageTemplate(id='OTALogPage',
                     frames=frameNormal,
                     onPage=foot("WMBR Operating Log"),
                     pagesize=letter),
        PageTemplate(id='OpLogPage',
                     frames=frameNormal,
                     onPage=foot("WMBR Operating Log"),
                     pagesize=letter)
    ])

    #start the construction of the pdf
    doc.build(Elements)

    printcmd("Done\n")

    ## The programming log

    printcmd("Writing programming log...")
    doc = BaseDocTemplate(location + "proglog.pdf",
                          showBoundary=0,
                          allowSplitting=0,
                          leftMargin=0.5 * inch,
                          rightMargin=0.5 * inch,
                          topMargin=1.4 * inch,
                          bottomMargin=0.5 * inch)

    frameNormal = Frame(doc.leftMargin,
                        doc.bottomMargin,
                        doc.width,
                        doc.height,
                        id='normal')

    Elements.extend(rulesPage())

    for date in dates:
        Elements.append(flowables.DocAssign("currentYear", date.year))
        Elements.append(flowables.DocAssign("currentMonth", date.month))
        Elements.append(flowables.DocAssign("currentDay", date.day))
        tables = progtablegen.make_day_tables(progEvents[date])
        Elements.append(NextPageTemplate('OTALogPage'))
        Elements.append(PageBreak())
        Elements.append(SigPage())
        Elements.append(NextPageTemplate('ProgLogPage'))
        Elements.append(PageBreak())
        Elements.extend(tables)

    doc.addPageTemplates([
        PageTemplate(id='Title',
                     frames=frameNormal,
                     onPage=title("WMBR Programming Log"),
                     pagesize=letter),
        PageTemplate(id='OTALogPage',
                     frames=frameNormal,
                     onPage=foot("WMBR Programming Log"),
                     pagesize=letter),
        PageTemplate(id='ProgLogPage',
                     frames=frameNormal,
                     onPage=foot("WMBR Programming Log"),
                     pagesize=letter)
    ])

    #start the construction of the pdf
    doc.build(Elements)
    printcmd("Done\n")
    printcmd("Finished.\n")
Exemplo n.º 38
0
import calendar

calendar.setfirstweekday(calendar.MONDAY)

dow = input('Enter day of week ')

dow_int = 0

if dow == 'Monday':
    dow_int = 0
elif dow == 'Tuesday':
    dow_int = 1
elif dow == 'Wednesday':
    dow_int = 2
elif dow == 'Thursday':
    dow_int = 3
elif dow == 'Friday':
    dow_int = 4
elif dow == 'Saturday':
    dow_int = 5
elif dow == 'Sunday':
    dow_int = 6

i = 11
for year in range(2018, 3000):
    for month in range(11, 100):
        if month % 12 == 0:
            m = 12
        else:
            m = month % 12
        if calendar.monthrange(year, m) == dow_int:
Exemplo n.º 39
0
print time.localtime(
)  # 接收时间辍(1970纪元后经过的浮点秒数)并返回当地时间下的时间元组t(t.tm_isdst可取0或1,取决于当地当时是不是夏令时)
#print time.mktime()# 接受时间元组并返回时间辍(1970纪元后经过的浮点秒数)。
# time.sleep(3000)#推迟线程的运行
# print time.strftime(format)#格式化时间,参见上面
print time.time()  # 返回当地时间戳
print "time.timezone: ", time.timezone
print "time.tzname: ", time.tzname

# 日历模块
print calendar.calendar(
    2017, w=2, l=1, c=6
)  #返回一个多行字符串格式的year年年历,3个月一行,间隔距离为c。 每日宽度间隔为w字符。每行长度为21* W+18+2* C。l是每星期行数。
print calendar.firstweekday()  # 返回当前每周起始日期的设置。默认情况下,首次载入caendar模块时返回0,即星期一。
print calendar.isleap(2017)  # 判断润年
print calendar.leapdays(1993, 2017)  #判断指定两个年份之间闰年的数
print calendar.month(2017, 9, w=2, l=1)  #返回指定年月的日历
print calendar.monthcalendar(
    2017, 12
)  #返回一个整数的单层嵌套列表。每个子列表装载代表一个星期的整数。Year年month月外的日期都设为0;范围内的日子都由该月第几日表示,从1开始。
print calendar.monthrange(2017, 11)
print calendar.prcal(2017, w=2, l=1, c=6)
print calendar.prmonth(2017, 10, w=2, l=1)
print calendar.setfirstweekday(3)  #设置每周起始日期码
print calendar.timegm(time.localtime())
print calendar.weekday(2017, 12, 25)  #返回星期码

#datetime
#pytz
#dateutil
Exemplo n.º 40
0
def generate_image():
    if middle_section == "inkycal_calendar" and internet_available() == True:
        try:
            clear_image('middle_section')
            print('Calendar module: Generating image...', end='')
            now = arrow.now(tz=get_tz())
            """Set up the Calendar template based on personal preferences"""
            if week_starts_on == "Monday":
                calendar.setfirstweekday(calendar.MONDAY)
                weekstart = now.replace(days=-now.weekday())
            else:
                calendar.setfirstweekday(calendar.SUNDAY)
                weekstart = now.replace(days=-now.isoweekday())
            """Write the name of the current month at the correct position"""
            write_text(main_area_width,
                       month_name_height,
                       str(now.format('MMMM', locale=language)),
                       (border_left, middle_section_offset),
                       autofit=True)
            """Set up weeknames in local language and add to main section"""
            weekday_names = [
                weekstart.replace(days=+_).format('ddd', locale=language)
                for _ in range(7)
            ]

            for _ in range(len(weekday_pos)):
                write_text(icon_width,
                           weekdays_height,
                           weekday_names[_],
                           weekday_pos[_],
                           autofit=True)
            """Create a calendar template and flatten (remove nestings)"""
            flatten = lambda z: [x for y in z for x in y]
            calendar_flat = flatten(calendar.monthcalendar(
                now.year, now.month))
            """Add the numbers on the correct positions"""
            for i in range(len(calendar_flat)):
                if calendar_flat[i] != 0:
                    write_text(icon_width, icon_height, str(calendar_flat[i]),
                               grid[i])
            """Draw a red/black circle with the current day of month in white"""
            icon = Image.new('RGBA', (icon_width, icon_height))
            current_day_pos = grid[calendar_flat.index(now.day)]
            x_circle, y_circle = int(icon_width / 2), int(icon_height / 2)
            radius = int(icon_width * 0.25)
            text_width, text_height = default.getsize(str(now.day))
            x_text = int((icon_width / 2) - (text_width / 2))
            y_text = int((icon_height / 2) - (text_height / 1.7))
            ImageDraw.Draw(icon).ellipse(
                (x_circle - radius, y_circle - radius, x_circle + radius,
                 y_circle + radius),
                fill='red' if three_colour_support == True else 'black',
                outline=None)
            ImageDraw.Draw(icon).text((x_text, y_text),
                                      str(now.day),
                                      fill='white',
                                      font=bold)
            image.paste(icon, current_day_pos, icon)
            """Create some reference points for the current month"""
            days_current_month = calendar.monthrange(now.year, now.month)[1]
            month_start = now.floor('month')
            month_end = now.ceil('month')

            if show_events == True:
                """Filter events which begin before the end of this month"""
                upcoming_events = fetch_events()

                calendar_events = [
                    events for events in upcoming_events
                    if month_start <= events.end <= month_end
                ]
                """Find days with events in the current month"""
                days_with_events = []
                for events in calendar_events:
                    if events.duration.days <= 1:
                        days_with_events.append(int(events.begin.format('D')))
                    else:
                        for day in range(events.duration.days):
                            days_with_events.append(
                                int(events.begin.replace(days=+i).format('D')))
                days_with_events = set(days_with_events)

                if event_icon == 'dot':
                    for days in days_with_events:
                        write_text(icon_width, int(icon_height * 0.2), '•',
                                   (grid[calendar_flat.index(days)][0],
                                    int(grid[calendar_flat.index(days)][1] +
                                        icon_height * 0.8)))

                if event_icon == 'square':
                    square_size = int(icon_width * 0.6)
                    center_x = int((icon_width - square_size) / 2)
                    center_y = int((icon_height - square_size) / 2)
                    for days in days_with_events:
                        draw_square((int(grid[calendar_flat.index(days)][0] +
                                         center_x),
                                     int(grid[calendar_flat.index(days)][1] +
                                         center_y)), 8, square_size,
                                    square_size)
                """Add a small section showing events of today and tomorrow"""
                event_list = [
                    '{0} {1} {2} : {3}'.format(
                        today_in_your_language, at_in_your_language,
                        event.begin.format('HH:mm' if hours ==
                                           24 else 'hh:mm'), event.name)
                    for event in calendar_events
                    if event.begin.day == now.day and now < event.end
                ]

                event_list += [
                    '{0} {1} {2} : {3}'.format(
                        tomorrow_in_your_language, at_in_your_language,
                        event.begin.format('HH:mm' if hours ==
                                           24 else 'hh:mm'), event.name)
                    for event in calendar_events
                    if event.begin.day == now.replace(days=1).day
                ]

                after_two_days = now.replace(days=2).floor('day')

                event_list += [
                    '{0} {1} {2} : {3}'.format(
                        event.begin.format('D MMM'), at_in_your_language,
                        event.begin.format('HH:mm' if hours ==
                                           24 else 'hh:mm'), event.name)
                    for event in upcoming_events if event.end > after_two_days
                ]

                del event_list[max_event_lines:]

            if event_list:
                for lines in event_list:
                    write_text(main_area_width,
                               int(events_height / max_event_lines),
                               lines,
                               event_lines[event_list.index(lines)],
                               alignment='left',
                               fill_height=0.7)
            else:
                write_text(main_area_width,
                           int(events_height / max_event_lines),
                           'No upcoming events.',
                           event_lines[0],
                           alignment='left',
                           fill_height=0.7)
            """Set print_events_to True to print all events in this month"""
            style = 'DD MMM YY HH:mm'
            if print_events == True and calendar_events:
                line_width = max(len(_.name) for _ in calendar_events)
                for events in calendar_events:
                    print(
                        '{0} {1} | {2} | {3} | All day ='.format(
                            events.name, ' ' * (line_width - len(events.name)),
                            events.begin.format(style),
                            events.end.format(style)), events.all_day)

            calendar_image = crop_image(image, 'middle_section')
            calendar_image.save(image_path + 'inkycal_calendar.png')

            print('Done')

        except Exception as e:
            """If something went wrong, print a Error message on the Terminal"""
            print('Failed!')
            print('Error in Calendar module!')
            print('Reason: ', e)
            pass
Exemplo n.º 41
0
 def tearDown(self):
     calendar.setfirstweekday(self.oldfirstweekday)
Exemplo n.º 42
0
#AFTERSHIP API STUFF
import aftership
AFTERSHIP_API_KEY = settings.AFTERSHIP_API_KEY  #DEFINED IN SETTINGS.PY
api = aftership.APIv4(AFTERSHIP_API_KEY)  #Defined in settings.py
couriers = api.couriers.all.get()

#################33
#THE FOLLOWING SHIT IS NEEDED FOR THE HOST AVAILABIITY CLANEDAR -- JESS EDITING ON 9/6/2015 E
#import new homebrew calendar
#NOTE - HOSTCONFLICTS_DATEVERSIO IS THE ONE CURRENTLY IN USE
from calendar_homebrew.models import HostConflicts_DateVersion, HostConflicts_DateVersion_OneTable, HostConflicts_OldVersion, HostConflicts_BooleanVersion, HostWeeklyDefaultSchedule
#Import the HostConflictsForm -- i just created this in calendar_homebrew.forms.py
from calendar_homebrew.forms import HostConflictsForm_DateVersion, HostConflictsForm_OldVersion, CalendarCheckBoxes
#Define lots of generic date fields that will be accessed by several functions - note that some of these may already be defined in core.views etc
import calendar
calendar.setfirstweekday(
    6)  #Set first weekday: 6 is sunday, 0 is monday, default is 0/monday
date_today = datetime.date.today()
datetime_now = datetime.datetime.now()
time = datetime.datetime.time(datetime_now)
thisyear = date_today.year
nextyear = date_today.year + 1
thisyear_isleap = calendar.isleap(thisyear)
nextyear_isleap = calendar.isleap(nextyear)
thismonth_num = date_today.month
if thismonth_num == 12:
    nextmonth_num = 1
    nextmonth_calendar_year = nextyear
else:
    nextmonth_num = date_today.month + 1
    nextmonth_calendar_year = thisyear
thismonth_calendar = calendar.monthcalendar(thisyear, thismonth_num)
Exemplo n.º 43
0
def localize():
    """Set program locale and first day of the week."""
    locale.setlocale(locale.LC_ALL, os.getenv('LC_ALL'))
    calendar.setfirstweekday(calendar.MONDAY)
from calendar import setfirstweekday, weekday, day_name
setfirstweekday(6)
MM, DD, YYYY = [int(i) for i in input().split()]
print(day_name[weekday(YYYY, MM, DD)].upper())
Exemplo n.º 45
0
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
""" CMFCalendar portal_calendar tool.

$Id$
"""

import calendar
calendar.setfirstweekday(6) #start day  Mon(0)-Sun(6)
from DateTime import DateTime

from Products.CMFCore.utils import UniqueObject
from OFS.SimpleItem import SimpleItem
from Globals import InitializeClass
from AccessControl import ClassSecurityInfo
from Products.CMFCore.CMFCorePermissions import ManagePortal
from Products.PageTemplates.PageTemplateFile import PageTemplateFile

class CalendarTool (UniqueObject, SimpleItem):
    """ a calendar tool for encapsualting how calendars work and are displayed """
    id = 'portal_calendar'
    meta_type= 'CMF Calendar Tool'
    security = ClassSecurityInfo()
    plone_tool = 1
Exemplo n.º 46
0
    def __init__(self, on_date_change, keybindings, on_press, firstweekday=0,
                 weeknumbers=False, monthdisplay='firstday', get_styles=None, initial=None):
        """
        :param on_date_change: a function that is called every time the selected
            date is changed with the newly selected date as a first (and only
            argument)
        :type on_date_change: function
        :param keybindings: bind keys to specific functionionality, keys are
            the available commands, values are lists of keys that should be
            bound to those commands. See below for the defaults.
            Available commands:
                'left', 'right', 'up', 'down': move cursor in direction
                'today': refocus on today
                'mark': toggles selection mode
        :type keybindings: dict
        :param on_press: dictonary of functions that are called when the key is
            pressed and is not already bound to one of the internal functionions
            via `keybindings`. These functions must accept two arguments, in
            normal mode the first argument is the currently selected date
            (datetime.date) and the second is `None`. When a date range is
            selected, the first argument is the earlier, the second argument
            is the later date. The function's return values are interpreted as
            pressed keys, which are handed to the widget containing the
            CalendarWidget.
        :type on_press: dict
        """
        if initial is None:
            self._initial = dt.date.today()
        else:
            self._initial = initial

        default_keybindings = {
            'left': ['left'], 'down': ['down'], 'right': ['right'], 'up': ['up'],
            'today': ['t'],
            'view': [],
            'mark': ['v'],
        }
        on_press = defaultdict(lambda: lambda x: x, on_press)
        default_keybindings.update(keybindings)
        calendar.setfirstweekday(firstweekday)

        try:
            mylocale = '.'.join(getlocale(LC_TIME))
        except TypeError:  # language code and encoding may be None
            mylocale = 'C'

        _calendar = calendar.LocaleTextCalendar(firstweekday, mylocale)
        weekheader = _calendar.formatweekheader(2)
        dnames = weekheader.split(' ')

        def _get_styles(date, focus):
            if focus:
                if date == dt.date.today():
                    return 'today focus'
                else:
                    return 'reveal focus'
            else:
                if date == dt.date.today():
                    return 'today'
                else:
                    return None
        if get_styles is None:
            get_styles = _get_styles

        if weeknumbers == 'right':
            dnames.append('#w')
        month_names_length = get_month_abbr_len()
        dnames = urwid.Columns(
            [(month_names_length, urwid.Text(' ' * month_names_length))] +
            [(2, urwid.AttrMap(urwid.Text(name), 'dayname')) for name in dnames],
            dividechars=1)
        self.walker = CalendarWalker(
            on_date_change, on_press, default_keybindings, firstweekday,
            weeknumbers, monthdisplay,
            get_styles, initial=self._initial)
        self.box = CListBox(self.walker)
        frame = urwid.Frame(self.box, header=dnames)
        urwid.WidgetWrap.__init__(self, frame)
        self.set_focus_date(self._initial)
Exemplo n.º 47
0
 def set_first_weekday(weekday):
     calendar.setfirstweekday(weekday)
Exemplo n.º 48
0
    def RenderMonthGrid(self, month, year):
        textheight = self.textheight

        calendar.setfirstweekday(calendar.SUNDAY)
        cal = calendar.monthcalendar(year, month)
        parent = self.year_g

        monthw = self.month_w
        monthh = self.month_h
        dayw = self.day_w
        dayh = self.day_h

        week_x = self.doc_w / 2 - self.options.week_width / 2
        week_y = self.pad

        #
        #   s m t w t f s
        #
        #

        txt_atts = {'id': 'month'}  #group for month day text
        self.month_g = inkex.etree.SubElement(parent, 'g', txt_atts)

        #horizontal lines
        y = week_y
        for week in range(self.numweeks):
            if week == 0:
                #Add initial horizontal at top
                path = "M " + str(week_x) + "," + str(week_y) + "L " + str(
                    week_x + self.options.week_width) + "," + str(week_y)
                line_atts = {
                    'style': simplestyle.formatStyle(self.line_style),
                    'd': path
                }
                inkex.etree.SubElement(parent, 'path', line_atts)

            #Add horizontal at bottom of each line
            path = "M " + str(week_x) + "," + str(y + self.day_h) + "L " + str(
                week_x + self.options.week_width) + "," + str(y + self.day_h)
            line_atts = {
                'style': simplestyle.formatStyle(self.line_style),
                'd': path
            }
            inkex.etree.SubElement(parent, 'path', line_atts)
            y = y + dayh

        #vertical lines
        x = week_x
        for c in range(8):
            path = "M " + str(x) + "," + str(week_y) + "L " + str(
                x) + "," + str(week_y + self.doc_h - 2 * self.pad)
            line_atts = {
                'style': simplestyle.formatStyle(self.line_style),
                'd': path
            }
            inkex.etree.SubElement(parent, 'path', line_atts)
            x += dayw

        #write year on top
        txt_atts = {
            'x': str(week_x),
            'y': str(week_y - textheight),
            'id': str(year),
            'text-anchor': "start"
        }
        inkex.etree.SubElement(self.month_g, 'text', txt_atts).text = str(year)

        very_first = True
        first_week = True
        make_month = True
        curweek = 0
        month = month - 1
        while week_y < self.doc_h - self.pad:
            if first_week and not very_first: first_week = False

            if make_month:
                make_month = False
                curweek = 0
                month = month + 1
                if month == 13:
                    month = 1
                    year = year + 1
                cal = calendar.monthcalendar(year, month)

            if curweek == len(cal):
                curweek = 0
                make_month = True
                continue

            week = cal[curweek]

            x = week_x + textheight / 4
            y = week_y
            i = 0
            while i < 7:
                day = week[i]

                i = i + 1
                if (day == 0 and first_week):
                    x += dayw
                    continue

                txt_atts = {
                    'x': str(x),
                    'y': str(week_y + textheight),
                    'id': str(year) + "_" + str(month) + '_' + str(day),
                    'text-anchor': "start"
                }
                if (i == 1 or i == 7):
                    txt_atts['style'] = simplestyle.formatStyle(
                        self.style_weekend)

                if day == 1 or very_first:
                    #write month then day
                    txt_atts = {
                        'x': str(x),
                        'y': str(week_y + textheight),
                        'font-size': str(self.textheight * .6),
                        'id': str(year) + "_" + str(month) + '_' + str(day),
                        'text-anchor': "start"
                    }
                    inkex.etree.SubElement(
                        self.month_g, 'text',
                        txt_atts).text = self.options.month_names[month - 1]

                    txt_atts = {
                        'x': str(x),
                        'y': str(week_y + 2 * textheight),
                        'id': str(year) + "_" + str(month) + '_' + str(day),
                        'text-anchor': "start"
                    }
                    inkex.etree.SubElement(self.month_g, 'text',
                                           txt_atts).text = str(day)
                    very_first = False

                else:
                    if day == 0:
                        if first_week:
                            x += dayw
                            continue
                        month = month + 1
                        curweek = 0
                        if month == 13:
                            month = 1
                            year = year + 1
                        cal = calendar.monthcalendar(year, month)
                        week = cal[0]
                        i -= 1
                        continue

                    #write day number only
                    inkex.etree.SubElement(self.month_g, 'text',
                                           txt_atts).text = str(day)

                x += dayw

            week_y += dayh
            curweek = curweek + 1
Exemplo n.º 49
0
import calendar

yy = int(input('Enter year '))
mm = int(input('Enter month '))

print(calendar.month(yy, mm))

calendar.setfirstweekday(firstweekday=6)
print(calendar.month(yy, mm))

print('*' * 12)
for i in range(12):
    print(calendar.month(yy, i + 1))
    print('*' * 12)
Exemplo n.º 50
0
import threading
import time
import logging
import calendar
calendar.setfirstweekday(0)  # Monday is the first day of the week
from Display import Display


class Calender:
    def __init__(self, display: Display):
        logging.basicConfig(level=logging.INFO, datefmt="%H:%M:%S")
        self.__display = display

        self.cal_width = 240
        # Calendar strings to be displayed
        self.weekday_name = None
        self.month_name = None
        self.day_of_the_month = None
        self.current_year = None
        self.month_cal = None
        self.calendar_month = None

        cal_reset_thread = threading.Thread(target=self.__reset, daemon=True)
        cal_reset_thread.start()

        self.fonts = self.__display.fonts
        logging.info("Calender  : Calender Setup correctly")

    def __reset(self):
        time_in_mins = 30
        time_in_seconds = time_in_mins * 60
Exemplo n.º 51
0
 def _getCalendar(self):
     """ Wrapper to ensure we set the first day of the week every time
     """
     calendar.setfirstweekday(self.getFirstWeekDay())
     return calendar
Exemplo n.º 52
0
        def get_context_data(self, **kwargs):
            context = ListView.get_context_data(self, **kwargs)
            ol = context['object_list']
            calendar.setfirstweekday(calendar.SUNDAY)

            try:
                m = int(self.request.GET.get('m', '0'))
            except:
                m = 0

            context['m_next'] = m + 1
            context['m_previous'] = m - 1

            now = datetime.now()
            mes_base = datetime(now.year, now.month, 15)
            mes_base = mes_base + timedelta(days=int(m) * 30)

            cal = calendar.monthcalendar(mes_base.year, mes_base.month)

            for i, semana in enumerate(cal):
                for j, dia in enumerate(semana):
                    if dia:
                        cal[i][j] = {
                            'data': datetime(mes_base.year, mes_base.month, dia),
                            'eventos': [],
                            'now': now.day == dia and mes_base.month == now.month,
                            'destaque': False
                        }

            for evento in ol.filter(
                    inicio__year=mes_base.year,
                    inicio__month=mes_base.month):
                ano = evento.inicio.year
                mes = evento.inicio.month
                dia = evento.inicio.day

                primeiro_dia = datetime(ano, mes, 1)
                dia_pos = dia + primeiro_dia.weekday()

                if evento.caracteristica == Evento.FERIADO:
                    cal[(dia_pos) // 7][(dia_pos) % 7]['destaque'] = True

                cal[(dia_pos) // 7][(dia_pos) % 7]['eventos'].insert(0, evento)

            linha_inicial = cal[0][::-1]
            for i, dia in enumerate(linha_inicial):
                if dia:
                    dia_pos = dia['data']
                else:
                    dia_pos = dia_pos - timedelta(days=1)
                    linha_inicial[i] = {
                        'data': dia_pos,
                        'eventos': None,
                        'now': False,
                        'destaque': False
                    }

            cal[0] = linha_inicial[::-1]

            linha_final = cal[-1]
            for i, dia in enumerate(linha_final):
                if dia:
                    dia_pos = dia['data']
                else:
                    dia_pos = dia_pos + timedelta(days=1)
                    linha_final[i] = {
                        'data': dia_pos,
                        'eventos': None,
                        'now': now.day == dia and mes_base.month == now.month,
                        'destaque': False
                    }

            cal[-1] = linha_final

            context['object_list'] = cal

            return context
Exemplo n.º 53
0
    def create_calendar(self):
        calendar.setfirstweekday(settings.FIRST_DAY_OF_WEEK)
        now = datetime.datetime(self.year, self.month, 1)

        if self.month == 12:
            self.next_month = now.replace(year=now.year+1, month=1)
            self.next_year = self.year+1
        else:
            self.next_month = now.replace(month=now.month+1)
            self.next_year = self.year

        if self.month == 1:
            self.last_month = now.replace(year=self.year-1, month=12)
            self.last_year = self.year-1
        else:
            self.last_month = now.replace(month=now.month-1)
            self.last_year = self.year

        self.week_day_labels = [x for x in calendar.weekheader(5).split(' ')
                                if x != '']
        self.current_month = datetime.datetime(self.year, self.month, 1)
        self.month_name = calendar.month_name[self.month]

        if self.month == 12:
            self.next_month = self.current_month.replace(
                year=self.year+1, month=1)
        else:
            self.next_month = self.current_month.replace(
                month=self.current_month.month+1)

        self.next_month_name = self.next_month.strftime('%B')

        if self.month == 1:
            self.last_month = self.current_month.replace(
                year=self.year-1, month=12)
        else:
            self.last_month = self.current_month.replace(
                month=self.current_month.month-1)

        self.last_month_name = self.last_month.strftime('%B')

        self.cal_weeks = calendar.monthcalendar(self.year, self.month)
        self.monthrange = calendar.monthrange(self.year, self.month)[1]

        self.cal_days = []

        items = self.calendar_items(self.month, self.monthrange)

        for week, day in [(week, day) for week
                          in xrange(0, len(self.cal_weeks))
                          for day in xrange(0, 7)]:
            imgCounter = dict()
            dsCounter = dict()
            prCounter = dict()
            imgCounter = 0
            dsCounter = 0
            prCounter = 0
            d = int(self.cal_weeks[week][day])
            if d > 0:
                t_items = {'image': [], 'dataset': [], 'project': []}
                for item in items.get(d):
                    if item.get('type') == 'ome.model.core.Image':
                        try:
                            t_items['image'].index(item.get('id'))
                        except:
                            imgCounter += 1
                            t_items['image'].append(item.get('id'))
                    elif item.get('type') == 'ome.model.containers.Dataset':
                        try:
                            t_items['dataset'].index(item.get('id'))
                        except:
                            dsCounter += 1
                            t_items['dataset'].append(item.get('id'))
                    elif item.get('type') == 'ome.model.containers.Project':
                        try:
                            t_items['project'].index(item.get('id'))
                        except:
                            prCounter += 1
                            t_items['project'].append(item.get('id'))
                self.cal_days.append({
                    'day': self.cal_weeks[week][day],
                    'counter': {'imgCounter': imgCounter,
                                'dsCounter': dsCounter,
                                'prCounter': prCounter}})
            else:
                self.cal_days.append({
                    'day': self.cal_weeks[week][day], 'counter': {}})
            self.cal_weeks[week][day] = {'cell': self.cal_days[-1]}
Exemplo n.º 54
0
    def __init__(self,
                 on_date_change,
                 keybindings,
                 on_press,
                 firstweekday=0,
                 weeknumbers=False,
                 get_styles=None):
        """
        on_date_change: a function that is called every time the selected date
                        is changed with the newly selected date as a first (and
                        only argument)
        keybindings: bind keys to specific functions, keys are commands (e.g.
                    movement commands, values are lists of keys that should be
                    bound to those commands. See below for the defaults.
                    Available commands:
                        'left', 'right', 'up', 'down': move cursor in direction
                        'today': refocus on today
                        'mark': toggles selection mode
        on_press: dict of functions that are called when the key is pressed.
            These functions must accept at least two argument. In the normal
            case the first argument is the currently selected date (datetime.date)
            and the second is *None*. When a date range is selected, the first
            argument is the earlier and the second argument is the later date.
            The function's return values are interpreted as pressed keys.
        """

        default_keybindings = {
            'left': ['left'],
            'down': ['down'],
            'right': ['right'],
            'up': ['up'],
            'today': ['t'],
            'view': [],
            'mark': ['v'],
        }
        from collections import defaultdict
        on_press = defaultdict(lambda: lambda x: x, on_press)

        default_keybindings.update(keybindings)
        calendar.setfirstweekday(firstweekday)

        weekheader = calendar.weekheader(2)
        # calendar.weekheader returns bytes for python2 and unicode for python3
        if compat.VERSION == 2:
            weekheader = weekheader.decode('utf-8')
        dnames = weekheader.split(' ')

        def _get_styles(date, focus):
            if focus:
                if date == date.today():
                    return 'today focus'
                else:
                    return 'reveal focus'
            else:
                if date == date.today():
                    return 'today'
                else:
                    return None

        if get_styles is None:
            get_styles = _get_styles

        if weeknumbers == 'right':
            dnames.append('#w')
        dnames = urwid.Columns([(4, urwid.Text('    '))] +
                               [(2, urwid.AttrMap(urwid.Text(name), 'dayname'))
                                for name in dnames],
                               dividechars=1)
        self.walker = CalendarWalker(on_date_change, on_press,
                                     default_keybindings, firstweekday,
                                     weeknumbers, get_styles)
        box = CListBox(self.walker)
        frame = urwid.Frame(box, header=dnames)
        urwid.WidgetWrap.__init__(self, frame)
Exemplo n.º 55
0
def main():
    global Debug_Mode
    Debug_Mode = 0
    global do_screen_update
    do_screen_update = 1
    global epd
    epd = epd7in5b.EPD()
    if Debug_Mode == 0:
        epd.init()
    else:
        print('-= Debug Mode =-')
    global todo_response
    todo_response = ''
    global cal_width
    cal_width = 240
    global line_start
    line_start = 48
    global weather_reponse
    global forecast_reponse

    # All fonts used in frames
    global font_cal
    font_cal = ImageFont.truetype(
        '/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 16)
    global font_day
    font_day = ImageFont.truetype('fonts/Roboto-Black.ttf', 110)
    global font_weather
    font_weather = ImageFont.truetype('fonts/Roboto-Black.ttf', 20)
    global font_day_str
    font_day_str = ImageFont.truetype('fonts/Roboto-Light.ttf', 35)
    global font_month_str
    font_month_str = ImageFont.truetype('fonts/Roboto-Light.ttf', 25)
    global font_weather_icons
    font_weather_icons = ImageFont.truetype('fonts/meteocons-webfont.ttf', 45)
    global font_tasks_list_title
    font_tasks_list_title = ImageFont.truetype('fonts/Roboto-Light.ttf', 30)
    global font_tasks_list
    font_tasks_list = ImageFont.truetype('fonts/tahoma.ttf', 12)
    global font_tasks_due_date
    font_tasks_due_date = ImageFont.truetype('fonts/tahoma.ttf', 11)
    global font_tasks_priority
    font_tasks_priority = ImageFont.truetype('fonts/tahoma.ttf', 9)
    global font_update_moment
    font_update_moment = ImageFont.truetype('fonts/tahoma.ttf', 9)
    global icons_list
    icons_list = {
        u'01d': u'B',
        u'01n': u'C',
        u'02d': u'H',
        u'02n': u'I',
        u'03d': u'N',
        u'03n': u'N',
        u'04d': u'Y',
        u'04n': u'Y',
        u'09d': u'R',
        u'09n': u'R',
        u'10d': u'R',
        u'10n': u'R',
        u'11d': u'P',
        u'11n': u'P',
        u'13d': u'W',
        u'13n': u'W',
        u'50d': u'M',
        u'50n': u'W'
    }

    calendar.setfirstweekday(0)  # Monday is the first day of the week

    global todo_wait
    todo_wait = 300
    global refresh_time
    refresh_time = 900
    start_time = time.time() + refresh_time

    while True:
        query_todo_list()
        if (do_screen_update == 1):
            do_screen_update = 0
            refresh_Screen()
            start_time = time.time() + refresh_time
        elif (time.time() - start_time) > 0:
            print('-= General Refresh =-')
            refresh_Screen()
            start_time = time.time() + refresh_time
        time.sleep(todo_wait)
Exemplo n.º 56
0
import calendar
from datetime import datetime, timedelta

"""    Display Full calendar for given Year    """
print(calendar.calendar(2018, 3, 2, 6))

"""    Display Starting weekday - Mon-Sun(0-6)    """
calendar.setfirstweekday(calendar.SUNDAY)
print("First Week day is :", calendar.firstweekday())

"""    Check if the given year is leap    """
print(calendar.isleap(2018))

"""    Counts total leap days between given year range    """
print("There are", calendar.leapdays(2012, 2021), "leap days from 2012 to 2021")

"""    Display full given month    """
print()
print(calendar.month(2018, 12, 2, 1))

"""    Give day name on Given date    """
day = calendar.day_name[calendar.weekday(2018, 12, 27)]
print("Weekday on 27th December, 2018 is", day)

"""    Counts occurrences of Weekday    """
c = calendar.Calendar()
date = datetime(2018, 12, 27)
a = 0
while date > datetime(2018, 12, 1):
    a += 1
    date -= timedelta(7)
Exemplo n.º 57
0
    try:
        for o, a in opts:
            if o in ("-h", "--help"): die_with_usage()
            elif o in ("-y", "--year"): fullyear = True
            elif o in ("-c", "--columns"): ncols = int(a)
            elif o in ("-s", "--separator"): sep = a
            elif o in ("-n", "--nohilight"): nohilight = True
            elif o in ("-t", "--today"):
                y, m, d = map(int, a.split("-"))
                today = datetime.date(y, m, d)
            elif o in ("-f", "--firstday"):
                d = int(lookup(Days, a.lower()))
                if not (1 <= d <= 7):
                    raise Exception("bad first day-of-week %s; "
                                    "must be 1 (Monday) to 7 (Sunday)" % d)
                calendar.setfirstweekday(d - 1)
            else:
                raise Exception("unhandled option")
    except Exception as err:
        die_with_usage(err, 3)

    Year, Month, Date = datetime.date.isoformat(today).split("-")[0:3]
    Date = Date.lstrip('0')

    ## compute the months to print
    months = []
    if len(args) == 0: args = [Month]
    for a in args:
        if fullyear: sy, sm, ey, em = int(a), 1, int(a), 12
        else:
            s, e = a, a