Exemple #1
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")
Exemple #2
0
def add_weekday_label(ax, horizontal: bool) -> None:
    if horizontal:
        ax.tick_params(axis="y", which="major", pad=8)
        ax.set_yticks([x + 0.5 for x in range(0, 7)])
        ax.set_yticklabels(calendar.weekheader(width=1).split(" "), )
    else:
        ax.tick_params(axis="x", which="major", pad=4)
        ax.set_xticks([x + 0.5 for x in range(0, 7)])
        ax.set_xticklabels(calendar.weekheader(width=1).split(" "), )
        ax.xaxis.tick_top()
    def display_calendar_man(self):

        # access info about current day, month, year
        self.day = datetime.datetime.now().day
        self.month = datetime.datetime.now().month
        self.month_name = calendar.month_name[self.month]
        self.year = datetime.datetime.now().year

        self.butt_all_days = [
            tk.Button(self.frame_display) for i in range(31)
        ]  # max 31 days in a month
        days_list = calendar.weekheader(3).split(" ")
        self.first_day, self.num_days_in_month = calendar.monthrange(
            2020, self.month)
        #print(self.first_day, self.num_days_in_month)
        #print(days_list[self.first_day])

        # displays month and year at top
        #print(self.day, self.month, self.year, calendar.month_name[self.month])
        self.label_month_year_title = tk.Label(self.frame_display,
                                               text=self.month_name + ", " +
                                               str(self.year),
                                               font="Consolas 25 bold")
        self.label_month_year_title.grid(row=0,
                                         column=0,
                                         columnspan=7,
                                         pady=10)

        # displays header of days of week
        for i in range(len(days_list)):
            self.label_day = tk.Label(self.frame_display,
                                      text=days_list[i],
                                      font="Consolas 18 bold")
            self.label_day.grid(row=1, column=i, pady=10, padx=10)

        # generates and draws buttons for each day
        row = 2

        for i in range(self.first_day,
                       self.num_days_in_month + self.first_day):

            # i goes from 6 to 35 - will help with gridding
            # i-self.first_day goes 0 to 29 and provides day of month
            # i%7 indicates num between 0 and 6 for day of week - helps with column
            # for rows, we need to know everytime i%7 == 0

            if (i % 7 == 0):
                row += 1

            self.butt_all_days[i - self.first_day].config(width=7,
                                                          height=2,
                                                          bg="#5ec98a",
                                                          text=i -
                                                          self.first_day + 1)
            self.butt_all_days[i - self.first_day].grid(row=row,
                                                        column=(i % 7))

            self.butt_all_days[i - self.first_day].config(
                command=lambda i=i: self.display_day_events(i - self.first_day
                                                            + 1))
Exemple #4
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
Exemple #5
0
 def __init__(self, fldname, dateval, action=None, *args, **kwargs):  #here
     ui.View.__init__(self, *args, **kwargs)  # here
     calendar.setfirstweekday(calendar.SUNDAY)
     self.days = calendar.weekheader(3).split()
     #self.width,self.height = ui.get_screen_size() #here
     cv = ui.View(name=fldname)
     cv.frame = (0, 95, self.width, 255)
     cv.background_color = 'yellow'
     cv.border_color = 'yellow'
     cv.border_width = 2
     self.view = cv
     self.action = action
     prv_mth = ui.Button(title='<')
     prv_mth.frame = (5, 5, 50, 25)
     prv_mth.action = self.prev_pressed
     self.day_color = prv_mth.tint_color
     self.view.add_subview(prv_mth)
     nxt_mth = ui.Button(title='>')
     nxt_mth.frame = (56, 5, 50, 25)
     nxt_mth.action = self.next_pressed
     self.view.add_subview(nxt_mth)
     label = ui.Label(name='caltitle')
     self.caldate = dateval  #dt.datetime.strptime(dateval,'%d/%m/%Y')
     self.curdate = curdate = dt.datetime.today()
     label.text = str(self.caldate.strftime('%B  %Y'))
     label.frame = (107, 5, 200, 25)
     label.alignment = ui.ALIGN_CENTER
     self.view.add_subview(label)
     today_btn = ui.Button(title='Today')
     today_btn.frame = (self.width - 60, 5, 50, 25)
     today_btn.action = self.today_pressed
     self.view.add_subview(today_btn)
     self.firstdate = dt.date(self.caldate.year, self.caldate.month, 1)
     self.create_buttons()
     self.draw_calendar()
Exemple #6
0
def cli(check):
    qal = calendar.Calendar(firstweekday=6)
    calendar.setfirstweekday(calendar.SUNDAY)
    initialize_db()
    y, m, today = datetime.datetime.now().year, datetime.datetime.now(
    ).month, datetime.datetime.now().day
    year = get_year(y)
    click.echo(calendar.weekheader(2))
    for day in qal.monthdayscalendar(y, m):

        def format_day(d, year):
            d = str(d)
            done = False
            try:
                done = year[str(m)][d]
            except KeyError:
                if not d == "0":
                    year[str(m)][d] = False
            if str(today) == d and check:
                year[str(m)][d] = True
                done = True
            if d == "0":
                d = '  '
            elif len(d) == 1:
                d = colored(f' {d}', 'red', attrs=['blink', 'bold'
                                                   ]) if done else f' {d}'
            return colored(d, 'red') if done else d

        click.echo(" ".join([format_day(x, year) for x in day]))
    update_month(y, m, year[str(m)])
Exemple #7
0
def genCalendar(date=mx.DateTime.now(), category=None, thispage=None, nohighlight=0):
    daylinks = [''] * 32
    for day in range(1, date.days_in_month+1):
        if len(tv.weblog.db.getItemsAtDay(mx.DateTime.DateTime(date.year, date.month, day), category)) > 0:
            daylinks[day] = getRelativePath(getDayPageUrl(mx.DateTime.DateTime(date.year, date.month, day)),
                                            filenameToUrl(thispage))
        else:
            daylinks[day] = ''

    previousmonth = tv.weblog.db.getPreviousMonthWithItems(date)
    nextmonth = tv.weblog.db.getNextMonthWithItems(date)

    calendarTemplate = templates.calendar.calendar(searchList=[
        {'weeklist': calendar.monthcalendar(date.year, date.month),
         'daynames': calendar.weekheader(2).split(' '),
         'date': dateNamespace(date),
         'daylinks': daylinks,
         'nohighlight': nohighlight,
         'monthpageurl': getRelativePath(getMonthPageUrl(date, category),
                                         filenameToUrl(thispage)),
         'previousmonthurl': getRelativePath(getMonthPageUrl(previousmonth),
                                             filenameToUrl(thispage)),
         'previousmonth': previousmonth,
         'nextmonthurl': getRelativePath(getMonthPageUrl(nextmonth),
                                         filenameToUrl(thispage)),
         'nextmonth': nextmonth,
         'thisday': date.day }])

    return str(calendarTemplate)
Exemple #8
0
 def makeHeader(self):
     PH = self.placeHolder
     headerList = ["|-"]
     for weekday in calendar.weekheader(3).split(" "):
         headerList.append(f"!{weekday}")
     headerStr = "\n".join(headerList)
     return headerStr
Exemple #9
0
    def printEventMonthCalendar(self, year, month, daysFlaggedForEvents):
        print '-' * DASH_AMNT
        print("")
        print("  " + calendar.month_abbr[month] + "  " + str(year))
        print("")
        print(calendar.weekheader(SET_WIDTH))

        monthMatrix = calendar.monthcalendar(year, month)

        for i in range(0, len(monthMatrix)):
            check = ""
            for j in range(0, len(monthMatrix[i])):
                dayNum = monthMatrix[i][j]

                if dayNum in daysFlaggedForEvents:
                    if (daysFlaggedForEvents[dayNum] == FLAGGED):

                        #Unflag the day numbers such that day numbers don't mistakenly get
                        # emphasized for other months
                        daysFlaggedForEvents[dayNum] = UNFLAGGED
                        check = check + '{0: <8}'.format(
                            self.formatDayNumToStrWithEmphasis(dayNum))
                    else:
                        check = check + '{0: <8}'.format(
                            self.formatDayNumToStrNormally(dayNum))
                else:
                    check = check + '{0: <8}'.format(
                        self.formatDayNumToStrNormally(dayNum))

            print check
        print("")
Exemple #10
0
def mifunction():
    print("Hola esto es una funcion")
    print(calendar.weekheader(8))
    print(calendar.firstweekday())
    print(calendar.month(2019, 8))
    print(calendar.monthcalendar(2019, 8))
    print(calendar.calendar(2019))
Exemple #11
0
def event_calendar(start=None, end=None):
    cal = calendar.Calendar(6)
    if not start:
        start = date.today()
    if not end:
        end = start
    days = cal.monthdatescalendar(start.year, start.month)
    today = date.today()

    def annotate(day):
        classes = []
        if day.month != start.month:
            classes.append('not_in_month')
        if day == today:
            classes.append('today')
        if end > day >= start:
            classes.append('active_day')
        return {'date': day, 'classes': classes, 'week': week}

    days = [map(annotate, week) for week in days]
    headers = calendar.weekheader(2).split()
    headers.insert(0, headers.pop())  # sneaky trick to put Sunday up front
    prev = start + relativedelta(months=-1)
    next = start + relativedelta(months=+1)
    return {
        'calendar': days,
        'headers': headers,
        'start': start,
        'today': date.today(),
        'prev': prev,
        'next': next,
    }
Exemple #12
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
Exemple #13
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(bstring('    ' + calendar.weekheader(2) + ' ' + w_number))
    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 = bstring(month_abbr(week[6].month).ljust(4))
            elif weeknumber == 'left':
                m_name = bstring(' {:2} '.format(getweeknumber(week[0])))
            else:
                m_name = '    '
            if weeknumber == 'right':
                w_number = bstring(' {}'.format(getweeknumber(week[0])))
            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
Exemple #14
0
def calendar_walker(view, firstweekday=0):
    """hopefully this will soon become a real "walker",
    loading new weeks as needed"""
    calendar.setfirstweekday(firstweekday)
    dnames = calendar.weekheader(2).split(" ")
    dnames = CColumns([(4, urwid.Text("    "))] + [(2, urwid.Text(name)) for name in dnames], dividechars=1)

    weeks = CalendarWalker(view=view, firstweekday=firstweekday)
    box = urwid.ListBox(weeks)
    frame = urwid.Frame(box, header=dnames)
    return frame
Exemple #15
0
    def show_week_header(self):
        week_header_pos_left = 0.74
        week_header_pos_top = 0.8
        week_header_scale = 0.01

        for name in calendar.weekheader(2).split():
            surface = self.font('regular', week_header_scale).render(name, True, self.color)
            position = surface.get_rect(left=self.width * week_header_pos_left,
                                        top=self.height * week_header_pos_top)
            self.new_data.append((surface, position))
            week_header_pos_left += 0.03
def get_week_str(starting_at_id):
    """Returns a list of 2 letter representation of days for this week,
    starting at the given input day of the form yyymmddhh"""
    num_chars = 2
    week_hdr = calendar.weekheader(num_chars)
    strt_dt = datetime.datetime.strptime(str(starting_at_id), DATETIME_ID_FORMAT)
    strt_idx = calendar.weekday(strt_dt.year,strt_dt.month,strt_dt.day)
    day_list = []
    for d in range(7):
        day_idx = (strt_idx + d) % 7
        day_list.append(week_hdr[day_idx*(num_chars+1) : day_idx*(num_chars+1) + num_chars])
    return day_list
Exemple #17
0
def buildCalendar(year, month):
    firstDayOfWeek = getfirstDayOfWeek()

    cal = calendar.Calendar(firstDayOfWeek)
    dt = datetime.date(year, month, 1)
    dateFormatter = utils.getdateFormatter()

    calendar.setfirstweekday(firstDayOfWeek)
    daysOfWeek = (calendar.weekheader(2)).split(' ')
    HTMLOUT = (
        """<!--LupinCalendarBegins--><div class="logseq-tools-calendar"><h2>{}</h2><table><thead><tr>"""
    ).format(dt.strftime("%B %Y"))
    for dayOfWeek in daysOfWeek:
        HTMLOUT += ("<th>{}</th>").format(dayOfWeek)
    HTMLOUT += "</tr></thead><tbody>"
    #<th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th><th>Sun</th></tr></thead><tbody>

    if (datetime.date.today().year == year
            and datetime.date.today().month == month):
        outofmonth = ""
    else:
        outofmonth = " outofmonth"

    dayClass = ""
    for week in cal.monthdays2calendar(year, month):
        HTMLOUT += "<tr>"
        for day in week:
            if (day[0]):
                calday = datetime.date(year, month, day[0])
                dateFormat = dtStylish(datetime.date(year, month, day[0]),
                                       dateFormatter)
                if (datetime.date.today() == datetime.date(
                        year, month, day[0])):
                    # print(datetime.date(year, month, day[0]))
                    dayClass = "page-ref today"
                    # HTMLOUT += ("""<td><a data-ref="{}" href="#/page/{}" class="page-ref today">{}</a></td>""").format(dateFormat, dateFormat, day[0])
                # elif utils.pageExists(calday.strftime("%Y_%m_%d")):
                elif utils.pageExists(dtStylish(calday, dateFormatter)):
                    dayClass += "page-ref page-exists" + outofmonth
                    # HTMLOUT += ("""<td><a data-ref="{}" href="#/page/{}" class="page-ref page-exists">{}</a></td>""").format(dateFormat, dateFormat, day[0])
                else:
                    dayClass = "page-ref" + outofmonth
                    # HTMLOUT += ("""<td><a data-ref="{}" href="#/page/{}" class="page-ref">{}</a></td>""").format(dateFormat, dateFormat, day[0])
                HTMLOUT += (
                    """<td><a data-ref="{}" href="#/page/{}" class="{}">{}</a></td>"""
                ).format(dateFormat, dateFormat, dayClass, day[0])
            else:
                HTMLOUT += "<td></td>"
        HTMLOUT += "</tr>"

    HTMLOUT += "</tbody></table></div><!--LupinCalendarEnds-->"

    return HTMLOUT
Exemple #18
0
 def createcal(self):
     cal.setfirstweekday(cal.SUNDAY)
     cm = [cal.monthcalendar(self.year,i+1) for i in range(12)]            
     monthy = self.month-1
     mo = [i for i in cal.month_name if i != '']
     monthdict = { i:d for i, d in zip(mo,cm)}
     days = cal.weekheader(3).split()
     df = pd.DataFrame(monthdict[mo[monthy]],
     index = [f'Week {i+1}' for i in range(len(monthdict[mo[monthy]]))],
     columns= days)
     df = df.replace(0, '   ')
     df.index.name = f'{mo[monthy]} {self.year}'
     return df
Exemple #19
0
def calendar_walker(view, firstweekday=0):
    """hopefully this will soon become a real "walker",
    loading new weeks as needed"""
    calendar.setfirstweekday(firstweekday)
    dnames = calendar.weekheader(2).split(' ')
    dnames = CColumns([(4, urwid.Text('    '))] + [(2, urwid.Text(name))
                                                   for name in dnames],
                      dividechars=1)

    weeks = CalendarWalker(view=view, firstweekday=firstweekday)
    box = urwid.ListBox(weeks)
    frame = urwid.Frame(box, header=dnames)
    return frame
Exemple #20
0
    def weekheader(cls):
        '''
        Return a week header.

        e.g.::

            CalendarFormatter.weekheader()
            # Mo\tTu\tWe\tTh\tFr\tSt\tSu

        :rtype: str
        :return: week header.
        '''
        return calendar.weekheader(2).replace(' ', '\t')
def calendar_html(year,month):
    import calendar
    import datetime

    date = datetime.date.today()
    year,month = int(year),int(month)
    calendar.setfirstweekday(6)
    chosen_month = calendar.monthcalendar(year, month)
#    weeks = [[day or '' for day in week] for week in chosen_month]

    weeks = [[]]
    i = 0

    for week in chosen_month:
        for day in week:
            events = announcements = current = False
            if day:
#                check = datetime.date(year,month,day)
#                events = event.objects.filter(start_date==check)
                events = event.objects.filter(start_date__year=year, start_date__month=month, start_date__day=day)
                announcements = announcement.objects.filter(expire_date__gt=datetime.date(year,month,day))
                if year == date.year and month == date.month and day == date.day:
                    current = True
            weeks[i].append((day,events,announcements,current))
        weeks.append([])
        i += 1


    next_month = month+1
    next_year = year
    if next_month == 13: 
        next_month = 1
        next_year = year+1

    prev_month = month-1
    prev_year = year
    if prev_month == 0:
        prev_month = 12
        prev_year = year-1

    return {      
            'month_name': calendar.month_name[month],
            'month': month,
            'year': year,
            'weeks': weeks,
            'daynames': calendar.weekheader(1).split(),#calendar.day_abbr,
            'next_month': next_month,
            'next_year': next_year,
            'prev_month': prev_month,
            'prev_year': prev_year,
            }
Exemple #22
0
        def displayWeek(Week):
	print()
	for day in Week.days:
		print(day.date.strftime('| %m/%d'), end = ' ')
	print()
	calendar.setfirstweekday(6)
	print(calendar.weekheader(7))

	for day in Week.days:
		if day.recordCheck:
			rc = 'X'
		else:
			rc = ' '
		print('  [{}]  '.format(rc), end = ' ')
def month(request, year, month):
    """Listing of days in `month`."""
    year, month = int(year), int(month)


    # init variables
    firstDay = request.user.usersettings.firstDayOfWeek;
    cal = calendar.Calendar(firstDay)
    month_days = cal.itermonthdays(year, month)
    lst = [[]]
    week = 0

    # make month lists containing list of days for each week
    # each day tuple will contain list of entries and 'current' indicator
    today = datetime.now()
    for day in month_days:
        entries = current = False   # are there entries for this day; current day?
        meals = []
        if day:
            #TODO: fix this to a get and a try
            n = date(year,month,day)
            entries = Meal.objects.filter(date=n, user=request.user)
            if(entries):
                for u in entries.all():
                    meals.append(u.recipe.name)
            entries = DayIngredient.objects.filter(date=n, user=request.user)
            if(entries):
                ingredientDesc = ""
                for u in entries.all():
                    ingredientDesc += '{0:.2g}'.format(u.quantity) + " " + u.unit + " of " + u.ingredient.name + ", "
                meals.append(ingredientDesc[:len(ingredientDesc)-2])
            if(today.year == year and today.month == month and today.day == day):
                current = True

        lst[week].append((day, current, meals))
        if len(lst[week]) == 7:
            lst.append([])
            week += 1
    wd = calendar.weekheader(3).split()
    week_days = [wd[x] for x in cal.iterweekdays()]
    context = {
        'user': request.user,
        'year': year,
        'month': month,
        'month_days': lst,
        'mname': mnames[month-1],
        'week_days': week_days,
        'first_day': firstDay + 1 % 7,
    }
    return render(request, "mealplanner/index.html", context)
Exemple #24
0
def calendar_walker(pane, firstweekday=0, weeknumbers=False):
    """creates a `Frame` filled with a `CalendarWalker`"""
    calendar.setfirstweekday(firstweekday)
    dnames = calendar.weekheader(2).split(' ')
    if weeknumbers == 'right':
        dnames.append('#w')
    dnames = CColumns([(4, urwid.Text('    '))] + [(2, urwid.Text(name))
                                                   for name in dnames],
                      dividechars=1)

    weeks = CalendarWalker(pane, firstweekday, weeknumbers)
    box = CListBox(weeks)
    frame = urwid.Frame(box, header=dnames)
    return frame
Exemple #25
0
    def _format_month_calendar(self, month, scores, max_length):
        """
            Format month and list o scores into a html table or txt block
        """
        #Start HTML and Txt headers
        month_table = """
                      <table>
                      <tr>
                        <th colspan="7" style="text-align: center;" >{}</th>
                      </tr>
                      """.format(month)
        txt_week_header = calendar.weekheader(max_length)
        week_header = '<tr>'+''.join(['<td>{}</td>'.format(week) for week in txt_week_header.split(' ')])+'</tr>'

        week_scores = '<tr>'
        for i, day in enumerate(scores):
            score, q_count = day
            score_color = 'black'
            #Color day as a 'bad' day if the added sum of the scores on that day is less or equal to
            #half the possible sum, detemrined by the number of questions on that day
            upper_bound = q_count * max(self._score_range)
            lower_bound = q_count * min(self._score_range)
            if upper_bound != 0:
                scalar = (max(self._scale) - min(self._scale)) / (upper_bound - lower_bound)
                score = int((score-lower_bound) * scalar)

                bad_score_limit =  max(self._scale) // 2
                good_score_limit =  bad_score_limit + (max(self._scale) // 4 )

                if score <= bad_score_limit:
                    score_color =  '#ff9900'
                elif score >= good_score_limit:
                    score_color =  '#00AF00'
                else:
                    'black'

            if i%7 == 0 and i != -0:
                week_scores += '</tr><tr>'

            if score > 0:
                week_scores += '<td style="color: {};">{:{w}}</td>'.format(score_color, score, w=max_length)
            elif score == 0:
                week_scores += '<td>{:{w}}</td>'.format('-', w=max_length)
            else:
                week_scores += '<td>{:{w}}</td>'.format(' ', w=max_length)

        week_scores += '</tr>'
        html = month_table+week_header+week_scores+'</table>'

        return html
Exemple #26
0
  def render(self, app):
    self.has_focus = app.contains_focus(self)
    cal_data = calendar.monthcalendar(self.value.year, self.value.month)
    cal_header = [[Display(t, fg=green) for t in calendar.weekheader(3).split(' ')]]

    assert(len(cal_data[0]) == len(cal_header[0]))

    cells = [[self._render_monthcell(cell) for cell in row]
             for row in cal_data]

    month_name = Display('%s, %s' % (self.value.strftime('%B'), self.value.year))
    grid = Grid(cal_header + cells, align_right=True)

    return Vertical([month_name, grid])
Exemple #27
0
 def afterInit(self):
     con = self.Form.Connection
     gs = self.Sizer = dGridSizer(MaxCols=7)
     self.bizStatic = biz.BizStatic(con)
     self.bizDaily = biz.BizDaily(con)
     header = calendar.weekheader(3).split()
     for x in header:
         gs.append(dLabel(self, Caption=x), alignment="center")
     for y in range(self._week_range):
         for x in range(7):
             gs.append(PnlDay(self, Pos=(x,y)), "expand")
             gs.setColExpand(True, x)
         gs.setRowExpand(True, y+1)
     self.setFocusToToday()
Exemple #28
0
 def afterInit(self):
     con = self.Form.Connection
     gs = self.Sizer = dGridSizer(MaxCols=7)
     self.bizStatic = biz.BizStatic(con)
     self.bizDaily = biz.BizDaily(con)
     header = calendar.weekheader(3).split()
     for x in header:
         gs.append(dLabel(self, Caption=x), alignment="center")
     for y in range(self._week_range):
         for x in range(7):
             gs.append(PnlDay(self, Pos=(x, y)), "expand")
             gs.setColExpand(True, x)
         gs.setRowExpand(True, y + 1)
     self.setFocusToToday()
Exemple #29
0
def calendar_walker(pane, firstweekday=0, weeknumbers=False):
    """creates a `Frame` filled with a `CalendarWalker`"""
    calendar.setfirstweekday(firstweekday)
    dnames = calendar.weekheader(2).split(' ')
    if weeknumbers == 'right':
        dnames.append('#w')
    dnames = CColumns(
        [(4, urwid.Text('    '))] + [(2, urwid.Text(name)) for name in dnames],
        dividechars=1)

    weeks = CalendarWalker(pane, firstweekday, weeknumbers)
    box = CListBox(weeks)
    frame = urwid.Frame(box, header=dnames)
    return frame
Exemple #30
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()
    :returns: calendar strings,  may also include some
              ANSI (color) escape strings
    :rtype: list() of str()

    >>> vertical_month(month=12, year=2011, today=datetime.date(2011,12,12))
    ['\\x1b[1m    Mo Tu We Th Fr Sa Su\\x1b[0m ', '\\x1b[1mDec \\x1b[0m28 29 30  1  2  3  4 ', '     5  6  7  8  9 10 11 ', '    \\x1b[7m12\\x1b[0m 13 14 15 16 17 18 ', '    19 20 21 22 23 24 25 ', '\\x1b[1mJan \\x1b[0m26 27 28 29 30 31  1 ', '     2  3  4  5  6  7  8 ', '     9 10 11 12 13 14 15 ', '    16 17 18 19 20 21 22 ', '    23 24 25 26 27 28 29 ', '\\x1b[1mFeb \\x1b[0m30 31  1  2  3  4  5 ', '     6  7  8  9 10 11 12 ', '    13 14 15 16 17 18 19 ', '    20 21 22 23 24 25 26 ', '\\x1b[1mMar \\x1b[0m27 28 29  1  2  3  4 ']

    """
    khal = list()
    w_number = '    ' if weeknumber else ''
    calendar.setfirstweekday(firstweekday)
    khal.append(bstring('    ' + calendar.weekheader(2) + ' ' + w_number))
    for _ in range(count):
        for week in calendar.Calendar(firstweekday).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 = bstring(calendar.month_abbr[week[6].month].ljust(4))
            else:
                m_name = '    '
            w_number = bstring(
                ' ' + str(getweeknumber(week[0]))) if weeknumber else ''
            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
Exemple #31
0
    def get_context_data(self, **kwargs):
        firstweekday = 0 + SHIFT_WEEKSTART
        while firstweekday < 0:
            firstweekday += 7
        while firstweekday > 6:
            firstweekday -= 7

        ctx = {}
        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)

        cal = calendar.Calendar()
        holiday=Holiday.objects.all().values_list('hdate', flat=True) 
        cal.setfirstweekday(firstweekday)
        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)
                days=date.weekday()
                tdate=date
                if date.date() == now().date():
                    current = True
                if tdate.date() in holiday or days > 4 :
                    hday=False
                else:
                    hday=True
                if tdate.date() in holiday and days > 4:
					print("I am")
					hday=True
                 
            else:
                days=''
                tdate=''
                hday=False
            month[week].append((day, current, days, tdate, hday))
            if len(month[week]) == 7:
                month.append([])
                week += 1
        calendar.setfirstweekday(firstweekday)
        weekdays = [_(header) for header in calendar.weekheader(10).split()]
        ctx.update({'month': month, 'date': date, 'weekdays': weekdays, 'holiday': holiday})
        return ctx
Exemple #32
0
    def __init__(self, on_date_change, keybindings, on_press,
                 firstweekday=0, weeknumbers=False):
        """
        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
        on_press: dict of functions that are called when the key is pressed,
                  getting the currently selected date as an argument. Their
                  return values are interpreted as pressed keys.
        """

        default_keybindings = {
            'left': ['left'], 'down': ['down'], 'right': ['right'], 'up': ['up'],
            'today': ['t'],
            'view': [],

        }
        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(' ')

        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)
        box = CListBox(self.walker)
        frame = urwid.Frame(box, header=dnames)
        urwid.WidgetWrap.__init__(self, frame)
Exemple #33
0
    def render(self, app):
        self.has_focus = app.contains_focus(self)
        cal_data = calendar.monthcalendar(self.value.year, self.value.month)
        cal_header = [[
            Display(t, fg=green) for t in calendar.weekheader(3).split(' ')
        ]]

        assert (len(cal_data[0]) == len(cal_header[0]))

        cells = [[self._render_monthcell(cell) for cell in row]
                 for row in cal_data]

        month_name = Display('%s, %s' %
                             (self.value.strftime('%B'), self.value.year))
        grid = Grid(cal_header + cells, align_right=True)

        return Vertical([month_name, grid])
Exemple #34
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()
    :returns: calendar strings,  may also include some
              ANSI (color) escape strings
    :rtype: list() of str()

    >>> vertical_month(month=12, year=2011, today=datetime.date(2011,12,12))
    ['\\x1b[1m    Mo Tu We Th Fr Sa Su\\x1b[0m ', '\\x1b[1mDec \\x1b[0m28 29 30  1  2  3  4 ', '     5  6  7  8  9 10 11 ', '    \\x1b[7m12\\x1b[0m 13 14 15 16 17 18 ', '    19 20 21 22 23 24 25 ', '\\x1b[1mJan \\x1b[0m26 27 28 29 30 31  1 ', '     2  3  4  5  6  7  8 ', '     9 10 11 12 13 14 15 ', '    16 17 18 19 20 21 22 ', '    23 24 25 26 27 28 29 ', '\\x1b[1mFeb \\x1b[0m30 31  1  2  3  4  5 ', '     6  7  8  9 10 11 12 ', '    13 14 15 16 17 18 19 ', '    20 21 22 23 24 25 26 ', '\\x1b[1mMar \\x1b[0m27 28 29  1  2  3  4 ']

    """
    khal = list()
    w_number = '    ' if weeknumber else ''
    calendar.setfirstweekday(firstweekday)
    khal.append(bstring('    ' + calendar.weekheader(2) + ' ' + w_number))
    for _ in range(count):
        for week in calendar.Calendar(firstweekday).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 = bstring(calendar.month_abbr[week[6].month].ljust(4))
            else:
                m_name = '    '
            w_number = bstring(' ' + str(getweeknumber(week[0]))) if weeknumber else ''
            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
Exemple #35
0
def updateCalendar(m=month, y=year):
    m = int(m)
    y = int(y)

    cal = calendar.monthcalendar(y, m)
    m_name = calendar.month_name[m]
    w_header = calendar.weekheader(2)

    str_calendar = ''
    str_calendar += (colorCal('494a5b') + '│' + str(y).center(20, ' ') + '│' + '\n')
    str_calendar += ('│' + m_name.center(20, ' ').upper() + '│' + '\n' )
    str_calendar += ('│' + w_header.upper() + '│' + colorCal() + '\n')
    str_calendar += (colorCal('494a5b', '├─ ┼  ┼  ┼  ┼  ┼  ┼ ─┤') + '\n')
    for rows, cols in enumerate(cal):
        l1 = []
        day = now.day
        current_date = [str(day), str(month), str(year)]
        for n in cols:
            n = '' if n==0 else n
            n_pad = str(n).rjust(2)
            for event in dblist:
                if not n:
                    break

                datel = parseDate(event['date'])
                if dateIndexParser(datel) < dateIndexParser(current_date):
                    n = colorCal('sienna', n_pad) if compareDates([n,m,y], datel) else n
                if dateIndexParser(datel) == dateIndexParser(current_date):
                    n = colorCal('sienna', 'X') if compareDates([n,m,y], datel) else n

                n = colorCal('darkcyan', n_pad) if compareDates([n,m,y], datel) else n
            n = colorCal('af2445', n_pad) if n==day and m==month and y==year else n
            n = str(n).rjust(2)
            l1.append(n)
        str_calendar += ( colorCal('494a5b') + '│' + colorCal() + ' '.join(map(str,l1)) + colorCal('494a5b') + '│' + colorCal() + '\n')

        if rows != (len(cal)-1):
            str_calendar += (colorCal('494a5b') + '├──┼──┼──┼──┼──┼──┼──┤' + colorCal() + '\n')

    str_calendar += (colorCal('494a5b') + '╰──┴──┴──┴──┴──┴──┴──╯' + colorCal() + '\n')

    if not _ignore_cache:
        with open('/tmp/calendar', 'w+') as calendar_stamp:
            calendar_stamp.write(str_calendar)
    print(str_calendar)
Exemple #36
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()
    :returns: calendar strings,  may also include some
              ANSI (color) escape strings
    :rtype: list() of str()
    """

    khal = list()
    w_number = '    ' if weeknumber else ''
    calendar.setfirstweekday(firstweekday)
    _calendar = calendar.Calendar(firstweekday)
    khal.append(bstring('    ' + calendar.weekheader(2) + ' ' + w_number))
    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 = bstring(calendar.month_abbr[week[6].month].ljust(4))
            else:
                m_name = '    '
            w_number = bstring(
                ' ' + str(getweeknumber(week[0]))) if weeknumber else ''
            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
Exemple #37
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()
    :returns: calendar strings,  may also include some
              ANSI (color) escape strings
    :rtype: list() of str()
    """

    khal = list()
    w_number = '    ' if weeknumber else ''
    calendar.setfirstweekday(firstweekday)
    _calendar = calendar.Calendar(firstweekday)
    khal.append(bstring('    ' + calendar.weekheader(2) + ' ' + w_number))
    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 = bstring(calendar.month_abbr[week[6].month].ljust(4))
            else:
                m_name = '    '
            w_number = bstring(
                ' ' + str(getweeknumber(week[0]))) if weeknumber else ''
            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
Exemple #38
0
    def get_context_data(self, **kwargs):
        firstweekday = 0 + SHIFT_WEEKSTART
        while firstweekday < 0:
            firstweekday += 7
        while firstweekday > 6:
            firstweekday -= 7

        ctx = self.get_category_context()
        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)

        all_occurrences = Event.objects.get_occurrences(
            start, end, ctx.get('current_category'))
        cal = calendar.Calendar()
        cal.setfirstweekday(firstweekday)

        req = get_request()        
        user_perm = req.user.get_all_permissions(obj=None)
        print(user_perm)
        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)
                occurrences = filter(
                    lambda occ, date=date: occ.start.replace(
                        hour=0, minute=0, second=0, microsecond=0) == date,
                    all_occurrences)
                if date.date() == now().date():
                    current = True
            else:
                occurrences = []
            month[week].append((day, occurrences, current))
            if len(month[week]) == 7:
                month.append([])
                week += 1
        calendar.setfirstweekday(firstweekday)
        weekdays = [_(header) for header in calendar.weekheader(10).split()]
        ctx.update({'month': month, 'date': date, 'weekdays': weekdays})
        return ctx
def meetup_day(year, month, day, interval):

    c = calendar.monthcalendar(year, month)
    first_week = c[0]
    second_week = c[1]
    third_week = c[2]
    fourth_week = c[3]
    fifth_week = c[4]

    week_dict = dict(zip(calendar.weekheader(9).split(), range(7)))

    week_day_numeric = week_dict[day]

    def is_a_teenth(date):
        return date >= 13 and date <= 19

    if interval == 'teenth':
        if is_a_teenth(second_week[week_day_numeric]):
            therightday = second_week[week_day_numeric]
        elif is_a_teenth(third_week[week_day_numeric]):
            therightday = third_week[week_day_numeric]
        else:
            therightday = fourth_week[week_day_numeric]

    elif interval == 'last':
        if fifth_week[week_day_numeric] != 0:
            therightday = fifth_week[week_day_numeric]
        else:
            therightday = fourth_week[week_day_numeric]

    elif interval[0].isdigit():
        nth_week = c[int(interval[0]) - 1]

        # Check to see if day exists in first week
        if first_week[week_day_numeric] == 0:
            next_week = c[int(interval[0])]
            therightday = next_week[week_day_numeric]
        else:
            therightday = nth_week[week_day_numeric]

    else:
        print "F**K, I shouldn't be here %s =" % (interval)

    return date(year, month, therightday)
Exemple #40
0
    def get_context_data(self, **kwargs):
        firstweekday = 0 + SHIFT_WEEKSTART
        while firstweekday < 0:
            firstweekday += 7
        while firstweekday > 6:
            firstweekday -= 7

        ctx = self.get_category_context()
        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)

        all_occurrences = Event.objects.get_occurrences(
            start, end, ctx.get('current_category'))
        cal = calendar.Calendar()
        cal.setfirstweekday(firstweekday)

        req = get_request()
        user_perm = req.user.get_all_permissions(obj=None)
        print(user_perm)
        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)
                occurrences = filter(lambda occ, date=date: occ.start.replace(
                    hour=0, minute=0, second=0, microsecond=0) == date,
                                     all_occurrences)
                if date.date() == now().date():
                    current = True
            else:
                occurrences = []
            month[week].append((day, occurrences, current))
            if len(month[week]) == 7:
                month.append([])
                week += 1
        calendar.setfirstweekday(firstweekday)
        weekdays = [_(header) for header in calendar.weekheader(10).split()]
        ctx.update({'month': month, 'date': date, 'weekdays': weekdays})
        return ctx
Exemple #41
0
def view_history():
    with open('data/sessionHistory.json', 'r') as file:
        sessions = json.load(file)
        sessions.sort(key=lambda s: datetime.strptime(s['timeStarted'],
                                                      DATETIME_FULL_FORMAT))
        sessions.reverse()

    state = 'LIST_VIEW'
    selection = None

    while True:
        click.clear()
        click.echo(BANNER)

        if state == 'LIST_VIEW':
            for i in range(len(sessions)):
                start_time = datetime.strptime(sessions[i]['timeStarted'],
                                               DATETIME_FULL_FORMAT)
                end_time = datetime.strptime(sessions[i]['timeFinished'],
                                             DATETIME_FULL_FORMAT)
                duration = end_time - start_time
                day_id = datetime.strptime(sessions[i]['timeStarted'],
                                           DATETIME_FULL_FORMAT).weekday()
                day_name = calendar.weekheader(5).split()[day_id].upper()
                click.echo(
                    '\t%d. %s %s (SCHED: %s) Duration: %s (%d)' %
                    (i + 1, day_name, sessions[i]['timeStarted'][:-2],
                     sessions[i]['timeScheduled'], '%s:%s' %
                     (int(duration.seconds / 60), duration.seconds % 60),
                     len(sessions[i]['completions'])))
            click.echo('\n\tView Session (ENTER=MENU | #): ', nl=False)
            recv = input()
            if recv.isdigit() and 0 < int(recv) <= len(sessions):
                selection = sessions[int(recv) - 1]
                state = 'SESSION_VIEW'
            elif recv == '':
                return

        elif state == 'SESSION_VIEW':
            click.echo(json.dumps(selection, indent=4))
            click.echo('\n\t<<< Press any key to return to list')
            click.getchar()
            selection = None
            state = 'LIST_VIEW'
Exemple #42
0
    def get_context_data(self, **kwargs):
        context = super(MonthView, self).get_context_data(**kwargs)
        context['today'] = datetime.date.today().strftime('%Y-%b-%d').split('-')
        context['month'] = context.get('month', context['today'][1])
        context['months'] = _months()[1:]
        context['daynames'] = calendar.weekheader(2).split(" ")
        context['days'] = calendar.monthcalendar(int(context['year']),
                                                 _months(context['month']))
        context['prev_year'] = int(context['year']) - 1
        context['next_year'] = int(context['year']) + 1

        view_date = '-'.join([context['year'], context['month']])
        prev_month = (parse(view_date) + delta(months=-1)).strftime('%Y/%b')
        next_month = (parse(view_date) + delta(months=+1)).strftime('%Y/%b')
        context['prev_month'] = prev_month.split('/')
        context['prev_month_s'] = prev_month
        context['next_month'] = next_month.split('/')
        context['next_month_s'] = next_month
        return context
Exemple #43
0
    def __init__(self,
                 date='2020-01-01',
                 interval=relativedelta(months=1),
                 config={}):
        # -----------------------------------------------
        # date: the init date;
        # interval: option of how long the interval is,
        #           self.next method uses it;
        # config: the local config object.
        if isinstance(config, dict):
            section = dict()
            logger.warning(
                'Config is not provided, using default initialization.')
        else:
            if config.has_section('Environment'):
                section = config['Environment']
            else:
                section = dict()
                logger.warning(
                    'Config has no "Environment" section, using default initialization.'
                )

        iD = [int(e) for e in section.get('initDate', date).split('-')]
        self.date = datetime(iD[0], iD[1], iD[2])

        interval = section.get('interval', interval)
        table = dict(monthly=relativedelta(months=1),
                     daily=relativedelta(days=1),
                     yearly=relativedelta(years=1))
        if interval in table:
            self.interval = table[interval]
        else:
            self.interval = interval

        # -----------------------------------------------
        # Generate weekdays and monthnames,
        # weekday: [Xxx] short name of weekday,
        # monthname: [Xxx] short name of month.
        self.weekdays = calendar.weekheader(4).split()
        self.monthnames = calendar.month_abbr

        logger.debug('Date initialized as date: {}, interval: {}'.format(
            self.string(), self.interval))
Exemple #44
0
def testB():
    print("\tCalendar")
    print(calendar.weekheader(3))
    print(calendar.firstweekday())
    print(calendar.month(2018, 4))
    print(calendar.calendar(2010))
    print(calendar.calendar(2011))
    print("Lunes vale: ", calendar.MONDAY)
    print("Martes vale: ", calendar.TUESDAY)
    print("Miercoles vale: ", calendar.WEDNESDAY)
    print("Jueves vale: ", calendar.THURSDAY)
    print("Viernes vale: ", calendar.FRIDAY)
    print("Sabado vale: ", calendar.SATURDAY)
    print("Domingo vale: ", calendar.SUNDAY)
    dia_de_la_semana = calendar.weekday(2011, 12, 18)
    print("Dia de la semana: ", dia_de_la_semana)
    print("Dia de la semana: ", get_dia_de_semana(dia_de_la_semana))
    is_leap = calendar.isleap(2011)
    bisiesto = "Fue año bisiesto" if is_leap == True else "No fue año bisiesto"
    print(bisiesto)
Exemple #45
0
def calendar_walker(view, firstweekday=0):
    """hopefully this will soon become a real "walker",
    loading new weeks as nedded"""
    lines = list()
    calendar.setfirstweekday(firstweekday)
    daynames = calendar.weekheader(2).split(' ')
    daynames = CColumns([(4, urwid.Text('    '))] + [(2, urwid.Text(name)) for name in daynames],
                        dividechars=1)
    lines = []
    focus_item = None
    for number, week in enumerate(week_list(firstweekday=firstweekday)):
        week, contains_today = construct_week(week, view)
        if contains_today:
            focus_item = number
        lines.append(week)

    weeks = CSimpleFocusListWalker(lines)
    weeks.set_focus(focus_item)
    weeks = urwid.ListBox(weeks)
    weeks = urwid.Frame(weeks, header=daynames)
    return weeks
Exemple #46
0
def nav_calendar(theyear, themonth, station=None):
    """Create a month calendar with links"""

    month = calendar.Calendar().monthdatescalendar(theyear, themonth)
    month_name = '%s %d' % (calendar.month_name[themonth], theyear)
    days_names = calendar.weekheader(3).split(' ')

    if station is None:
        days_with_data = (NetworkSummary.objects
                                        .filter(num_coincidences__isnull=False,
                                                date__year=theyear,
                                                date__month=themonth)
                                        .values_list('date', flat=True))
    else:
        days_with_data = (Summary.objects.filter(Q(num_events__isnull=False) |
                                                 Q(num_weather__isnull=False),
                                                 station=station,
                                                 date__year=theyear,
                                                 date__month=themonth)
                                         .values_list('date', flat=True))

    weeks = []
    for week in month:
        days = []
        for day in week:
            if day.month == themonth:
                if day in days_with_data:
                    if station is None:
                        link = (theyear, themonth, day.day)
                    else:
                        link = (station.number, theyear, themonth, day.day)
                else:
                    link = None
                days.append({'day': day.day, 'link': link})
            else:
                days.append('')
        weeks.append(days)

    return {'month': month_name, 'days': days_names, 'weeks': weeks}
Exemple #47
0
def nav_calendar(theyear, themonth, station=None):
    """Create a month calendar with links"""

    month = calendar.Calendar().monthdatescalendar(theyear, themonth)
    month_name = '%s %d' % (calendar.month_name[themonth], theyear)
    days_names = calendar.weekheader(3).split(' ')

    if station is None:
        days_with_data = (NetworkSummary.objects
                                        .filter(num_coincidences__isnull=False,
                                                date__year=theyear,
                                                date__month=themonth)
                                        .values_list('date', flat=True))
    else:
        days_with_data = (Summary.objects.filter(Q(num_events__isnull=False) |
                                                 Q(num_weather__isnull=False),
                                                 station=station,
                                                 date__year=theyear,
                                                 date__month=themonth)
                                         .values_list('date', flat=True))

    weeks = []
    for week in month:
        days = []
        for day in week:
            if day.month == themonth:
                if day in days_with_data:
                    if station is None:
                        link = (theyear, themonth, day.day)
                    else:
                        link = (station.number, theyear, themonth, day.day)
                else:
                    link = None
                days.append({'day': day.day, 'link': link})
            else:
                days.append('')
        weeks.append(days)

    return {'month': month_name, 'days': days_names, 'weeks': weeks}
Exemple #48
0
    def __str__(self):
        lines = []
        today = datetime.date.today()
        lines.append("{:23s}".format(calendar.weekheader(2)))
        for event in self.events:
            if event.calid in AGENDACOLORS:
                event.color = AGENDACOLORS[event.calid]
            else:
                event.color = COLORS[0]
                COLORS.rotate(-1)
                AGENDACOLORS[event.calid] = event.color

        for week in calendar.monthcalendar(self.first.year, self.first.month):
            days = []
            for day in week:
                color = COLOR_WHITE
                dayevents = []
                if day == 0:
                    days.append("  ")
                    continue
                date = datetime.date(self.first.year, self.first.month, day)
                dayevents = has_event(self.events, date)
                if dayevents:
                    for event in dayevents:
                        if not event.is_multiday():
                            color = event.color
                            break
                    else:
                        color = self.events[0].color
                if date.month == today.month and date.day == today.day:
                    color = [color + 10, COLOR_BLACK]

                days.append(color_format("{:2d}".format(day), color))
            days.append("  ")
            lines.append(" ".join(days))

        lines.append("")
        return "\n".join(lines)
Exemple #49
0
def event_calendar(start=None, end=None):
    cal = calendar.Calendar(6)
    if not start:
        start = date.today()
    if not end:
        end = start
    days = cal.monthdatescalendar(start.year, start.month)
    today = date.today()
    def annotate(day):
        classes = []
        if day.month != start.month:
            classes.append('not_in_month')
        if day == today:
            classes.append('today')
        if end  > day >= start:
            classes.append('active_day')
        return {'date': day, 'classes': classes, 'week': week}
    days = [map(annotate, week) for week in days]
    headers = calendar.weekheader(2).split()
    headers.insert(0, headers.pop()) # sneaky trick to put Sunday up front
    prev = start+relativedelta(months=-1)
    next = start+relativedelta(months=+1)
    return {'calendar': days, 'headers': headers, 'start': start, 'today': date.today(), 'prev': prev, 'next': next, }
def xtick_week_str(starting_at_id):
    """Returns a list for the x-axis labeling for plotting a week"""
    num_chars = 2
    hour_inc = 6 #broken into 6 hour increments
    week_hdr = calendar.weekheader(num_chars)
    start_dt = datetime.datetime.strptime(str(starting_at_id), DATETIME_ID_FORMAT)
    strt_idx = calendar.weekday(start_dt.year,start_dt.month,start_dt.day)
    # hour of starting_at_id sets the first element
    strt_hour = start_dt.hour
    day_list = []
    d = 0
    for x in range(7*hour_inc):
        hour = (strt_hour + x*hour_inc) % 24
        # Append name of day near noon
        if abs(hour - 12) <= 3: # if first element is 3, both 9 and 12 will be the day...
            day_idx = (strt_idx + d) % 7
            day_list.append(week_hdr[day_idx*(num_chars+1) : day_idx*(num_chars+1) + num_chars])
            if hour != 9:
                d = d + 1
        # Append time of day
        else:
            day_list.append(str(hour))
    return day_list
Exemple #51
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
Exemple #52
0
 def get_weekheader(self, p_week_day_len):
     """. return the days of week """
     l_result = []
     for l_day in string.split(calendar.weekheader(9)):
         l_result.append((l_day[:p_week_day_len], l_day))
     return l_result
Exemple #53
0
 def update(self, clear=True):
     calendar.setfirstweekday(self.firstWeekDay)
     if clear: self.clear()
     if self.hidden:
         self.clear()
         return False
     
     # Title line        
     if not self.value:
         _title_line = "No Value Set"
     else:
         year  = self.value.year
         month = self.value.month
         try:
             monthname = self.value.strftime('%B')
         except ValueError:
             monthname = "Month: %s" % self.value.month
         day   = self.value.day
         
         _title_line = "%s, %s" % (monthname, year)
     
     if isinstance(_title_line, bytes):
         _title_line = _title_line.decode(self.encoding, 'replace')
     
     if self.do_colors():
         title_attribute = self.parent.theme_manager.findPair(self)
     else:
         title_attribute = curses.A_NORMAL
     
     self.add_line(self.rely, self.relx, 
         _title_line,
         self.make_attributes_list(_title_line, title_attribute),
         self.width-1
     )
     
     
     if self.value:
         # Print the days themselves
         try:
             cal_data = calendar.monthcalendar(year, month)
             do_cal_print = True
         except OverflowError:
             do_cal_print = False
             self.parent.curses_pad.addstr(self.rely+1, self.relx, "Unable to display")
             self.parent.curses_pad.addstr(self.rely+2, self.relx, "calendar for date.")
         if do_cal_print:
             # Print the day names
             # weekheader puts an extra space at the end of each name
             
             cal_header = calendar.weekheader(self.__class__.DAY_FIELD_WIDTH - 1)
             if isinstance(cal_header, bytes):
                 cal_header = cal_header.decode(self.encoding, 'replace')
             
             if self.do_colors():
                 cal_title_attribute = self.parent.theme_manager.findPair(self, 'LABEL')
             else:
                 cal_title_attribute = curses.A_NORMAL
             self.add_line(self.rely+1, self.relx,
                 cal_header,
                 self.make_attributes_list(cal_header, cal_title_attribute),
                 self.width,
                 )
                 
             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")
Exemple #54
0
def calendar_day_view(request, year=datetime.now().year, month=datetime.now().month, day=datetime.now().day, blog_slug=None, page=1):
    """
    Shows a grid (similar in appearance to a physical calendar) of blogs for either entries in a specific blog or all entries.  Based on the GridOne layout originally developed for Calendars.
    """
    site = Site.objects.get_current()
    try:
        page = int(page)
        if year:
            year = int(year)
        if month:
            month = int(month)
    except ValueError:
        raise Http404

    blog = None
    blog_list = Blog.current.filter(section__publication__site=site).order_by('title')
    entries = Entry.get_published.filter(blog__section__publication__site=site)
    if blog_slug:
        blog = get_object_or_404(Blog, slug=blog_slug)
        entries = entries.filter(blog=blog)

    month_formatted = pycal.monthcalendar(year, month)

    month_minus = month - 1

    month_plus = month + 1

    month_name = pycal.month_name[month]

    weekday_header = pycal.weekheader(3).strip().split(" ")                                              

    year_minus = year - 1

    year_plus = year + 1

    today = datetime.now().day

    this_month = datetime.now().month

    this_year = datetime.now().year

    entry_list = entries.filter(pub_date__year=year).filter(pub_date__month=month).filter(pub_date__day=day).order_by('pub_date')
    page_name = "This is a test of the calendaring system."

    page = {
        'blog': blog,
        'blog_list': blog_list,
        'day': day,
        'entry_list': entry_list,
        'month': month,
        'month_formatted': month_formatted,
        'month_minus': month_minus,
        'month_name': month_name,
        'month_plus': month_plus,
        'page_name': page_name,
        'site': site,
        'this_month': this_month,
        'this_year': this_year,
        'today': today,
        'weekday_header': weekday_header,
        'year': year,
        'year_minus': year_minus,
        'year_plus': year_plus,
    }

    return render_to_response('blogs/calendarday.html', page, context_instance=RequestContext(request))
Exemple #55
0
 def getDays(self):
     """ Returns a list of days with the correct start day first """        
     return calendar.weekheader(2).split()
Exemple #56
0
def gencal(date = datetime.datetime.today(), cal_items=[]):
    """
    This will generate a calendar. It expects the year & month (in datetime format)
    and a list of dicts in the following format:

    cal_items = [{ 'day':datetime(2008,1,30), 'title':"Concert at Huckelberries", 'class':"concert",    'url':'/foo/2' },
                 { 'day':datetime(2008,2,4),  'title':"BBQ at Mom\'s house",      'class':"restaurant", 'url':'/restaurants/9' }]

    A listing of variables and their meanings:

    * day is the datetime of the day you'd like to reference
    * title is the text of the event that will be rendered
    * url is the url to the object you'd like to reference, it isn't necessary. If you don't wish to pass in a url, just pass it as None
    * class is a non-necessary field that will apply class="your_entry" to the list item

    My suggested urls.py file is:
    *Note: Its important to name your year/month url gencal or the backwards/forwards links won't work*;

    ::

        urlpatterns = patterns('',
            url(r'^(?P<year>\d{4})/(?P<month>\d+)/$', 'online_department.schedule.views.index', name='gencal'),
            (r'^$', 'online_department.schedule.views.index'),
        )

    The CSS I use to make it look good is:

    ::

        <style type="text/css">
        table.cal_month_calendar caption { text-align: center; text-size: 15px; background: none;}
        table.cal_month_calendar table { width: 455px;}
        table.cal_month_calendar th,td { width: 65px;}
        table.cal_month_calendar th { text-align: center; }
        table.cal_month_calendar td { height: 65px; position: relative;}
        table.cal_month_calendar td.cal_not_in_month { background-color: #ccc;}
        table.cal_month_calendar div.table_cell_contents { position: relative; height: 65px; width: 65px;}
        table.cal_month_calendar div.month_num { position: absolute; top: 1px; left: 1px; }
        table.cal_month_calendar ul.event_list { list-style-type: none; padding: 15px 0 0 0; margin: 0;}
        table.cal_month_calendar { border-collapse: collapse; }
        table.cal_month_calendar th { color: white; background: black;}
        table.cal_month_calendar td, th { border: 1px solid black; }
        </style>

    """
    # Iterator of all days to be shown in calendar given a year/month
    # includes possible stub of days at tail of previous month and possible
    # stub of days at head of next month to round out each week-list to 7 days.
    def get_iterable_days(year, month) :
        month_range = calendar.monthrange(year, month)
        days_in_month = month_range[1]
        first_day_of_month = datetime.date(year, month, 1)
        last_day_of_month = datetime.date(year, month, days_in_month)
    
        first_day_of_calendar = first_day_of_month - datetime.timedelta(first_day_of_month.weekday())
        head_days = first_day_of_month.weekday()
        tail_days = 6 - last_day_of_month.weekday()
        total_days_in_calendar = head_days + days_in_month + tail_days
        assert total_days_in_calendar%7 == 0
        for i in range(total_days_in_calendar):
            yield (first_day_of_calendar + datetime.timedelta(i))
        return

    # Calculate the 1st of previous and next months (for navigation in template)
    def get_prev_next_months(year, month) :
        lastmonth, nextmonth = month - 1, month + 1
        lastyear, nextyear = year, year
        if lastmonth == 0:
            lastmonth = 12
            lastyear -= 1
        elif nextmonth == 13:
            nextmonth = 1
            nextyear += 1 
        return (datetime.date(lastyear, lastmonth, 1), datetime.date(nextyear, nextmonth, 1))

    # Reduce cal_items to a day-keyed dictionary of lists of events
    def get_events_by_day(cal_items):
        events_by_day = defaultdict(list)
        for event in cal_items:
            d = event['day']
            d = datetime.date(d.year, d.month, d.day)
            events_by_day[d].append({'title':event['title'], 'url':event['url'], 'class':event['class'], 'timestamp':event['day'] })
        return events_by_day
    
    # Set the values pulled in from urls.py to integers from strings
    year, month = date.year, date.month
    
    events_by_day = get_events_by_day(cal_items)
    week, month_cal = [], []
    for day in get_iterable_days(year, month):
        cal_day = {'day': day, 'event': events_by_day[day], 'in_month': (day.month == month)}
        week.append(cal_day)        # Add the current day to the week
        if day.weekday() == 6:      # When Sunday comes, add the week to the calendar
            month_cal.append(week)
            week = []               # Reset the week

    week_headers = [header for header in calendar.weekheader(2).split(' ')]
    prev_date, next_date = get_prev_next_months(year, month)

    return {'month_cal': month_cal, 'headers': week_headers, 'date':date, 'prev_date':prev_date, 'next_date':next_date }
Exemple #57
0
 def getWeekHeader(self):
     """return a list of week header"""
     return calendar.weekheader(2).split()
Exemple #58
0
    nextmonth_calendar_year = nextyear
else:
    nextmonth_num = date_today.month + 1
    nextmonth_calendar_year = thisyear
thismonth_calendar = calendar.monthcalendar(thisyear, thismonth_num)
nextmonth_calendar = calendar.monthcalendar(thisyear, nextmonth_num)
thismonth = calendar.month_name[thismonth_num]
nextmonth = calendar.month_name[nextmonth_num]
monthrange_thismonth = calendar.monthrange(thisyear, thismonth_num)
monthrange_nextmonth = calendar.monthrange(thisyear, nextmonth_num)
days_in_thismonth = monthrange_thismonth[1]
days_in_nextmonth = monthrange_nextmonth[1]
firstweekday_num = calendar.firstweekday()
firstweekday = calendar.day_name[firstweekday_num]
weekheader_chars = 3
weekheaders = calendar.weekheader(weekheader_chars) #(n) specifies the width in characgters for one weekday 
today_dayofmonth_num = date_today.day
today_dayofweek_num = date_today.weekday()
today_dayofweek_name =  calendar.day_name[today_dayofweek_num] #day name is san array 
today_dayofweek_abbr = calendar.day_abbr[today_dayofweek_num] 

#Define get_item function
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

  
def facebook(request):
    enduser = request.user
    if request.is_ajax():
        ## access you data by playing around with the request.POST object
Exemple #59
0
    def update(self, clear=True):
        calendar.setfirstweekday(self.firstWeekDay)
        if clear: self.clear()
        if self.hidden:
            self.clear()
            return False

        # Title line
        if not self.value:
            _title_line = "No Value Set"
        else:
            year = self.value.year
            month = self.value.month
            try:
                monthname = self.value.strftime('%B')
            except ValueError:
                monthname = "Month: %s" % self.value.month
            day = self.value.day

            _title_line = "%s, %s" % (monthname, year)

        if isinstance(_title_line, bytes):
            _title_line = _title_line.decode(self.encoding, 'replace')

        if self.do_colors():
            title_attribute = self.parent.theme_manager.findPair(self)
        else:
            title_attribute = curses.A_NORMAL

        self.add_line(self.rely, self.relx, _title_line,
                      self.make_attributes_list(_title_line, title_attribute),
                      self.width - 1)

        if self.value:
            # Print the days themselves
            try:
                cal_data = calendar.monthcalendar(year, month)
                do_cal_print = True
            except OverflowError:
                do_cal_print = False
                self.parent.curses_pad.addstr(self.rely + 1, self.relx,
                                              "Unable to display")
                self.parent.curses_pad.addstr(self.rely + 2, self.relx,
                                              "calendar for date.")
            if do_cal_print:
                # Print the day names
                # weekheader puts an extra space at the end of each name

                cal_header = calendar.weekheader(
                    self.__class__.DAY_FIELD_WIDTH - 1)
                if isinstance(cal_header, bytes):
                    cal_header = cal_header.decode(self.encoding, 'replace')

                if self.do_colors():
                    cal_title_attribute = self.parent.theme_manager.findPair(
                        self, 'LABEL')
                else:
                    cal_title_attribute = curses.A_NORMAL
                self.add_line(
                    self.rely + 1,
                    self.relx,
                    cal_header,
                    self.make_attributes_list(cal_header, cal_title_attribute),
                    self.width,
                )

                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.allow_clear:
                key_help = "keys: dwmyDWMY t cq"
            else:
                key_help = "keys: dwmyDWMY t"

            if self.do_colors():
                self.parent.curses_pad.addstr(
                    self.rely + 9, self.relx, key_help,
                    self.parent.theme_manager.findPair(self, 'LABEL'))
            else:
                self.parent.curses_pad.addstr(self.rely + 9, self.relx,
                                              key_help)
Exemple #60
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

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

        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()
            rdCounter = dict()
            dsCounter = dict()
            prCounter = dict()
            imgCounter = 0
            rdCounter = 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]}