Ejemplo n.º 1
0
def month_year_picker(request):
    """Adds localized date info for the month-year picker widget."""
    locale = current_locale()

    return {
        'mypicker_months_short': get_month_names('abbreviated', locale=locale),
        'mypicker_months_long': get_month_names('wide', locale=locale)
    }
Ejemplo n.º 2
0
def month_year_picker(request):
    """Adds localized date info for the month-year picker widget."""
    locale = current_locale()

    return {
        "mypicker_months_short": get_month_names("abbreviated", locale=locale),
        "mypicker_months_long": get_month_names("wide", locale=locale),
    }
Ejemplo n.º 3
0
def getMonthNames(locale=None):
    """TODO
    
    :param locale: the current locale (e.g: en, en_us, it)"""
    locale = (locale or DEFAULT_LOCALE).replace('-', '_')
    d = dict([(v.lower(), k) for k, v in dates.get_month_names(width='wide', locale=locale).items()])
    d.update([(v.lower(), k) for k, v in dates.get_month_names(width='abbreviated', locale=locale).items()])
    return d
Ejemplo n.º 4
0
def getMonthNames(locale=None):
    """add???
    
    :param locale: ???add. Default value is ``None``
    :returns: add???
    """
    locale = (locale or DEFAULT_LOCALE).replace('-', '_')
    d = dict([(v.lower(), k) for k, v in dates.get_month_names(width='wide', locale=locale).items()])
    d.update([(v.lower(), k) for k, v in dates.get_month_names(width='abbreviated', locale=locale).items()])
    return d
Ejemplo n.º 5
0
def update_month(query_date, lang, project):
    year = query_date.year
    month = query_date.month
    month_name = get_month_names(locale=lang)
    weekdays = get_day_names(locale=lang)
    data = {'dir_depth': '../' * 4,
            'month_name': month_name[month],
            'project': project.capitalize(),
            'full_lang': LOCAL_LANG_MAP[lang],
            'prev_month': check_month(query_date, 1, lang, project),
            'next_month': check_month(query_date, -1, lang, project),
            'year': year,
            'meta': {'generated': datetime.utcnow().isoformat()},
            'weekdays': {'mon': weekdays[0],
                         'tues': weekdays[1],
                         'wed': weekdays[2],
                         'thurs': weekdays[3],
                         'fri': weekdays[4],
                         'sat': weekdays[5],
                         'sun': weekdays[6]}}
    data['dates'] = monthly_calendar(year, month, lang, project)
    month_index_path = MONTH_INDEX_PATH.format(lang=lang,
                                               project=project,
                                               year=year,
                                               month=month)
    month_index = pjoin(month_index_path, 'index.html')
    month_template = choose_template(template=MONTH_INDEX_TMPL,
                                     lang=lang)
    save_rendered(month_index, month_template, data)
    return data
Ejemplo n.º 6
0
def yearly_calendar(year, lang, project):
    ret = []
    year_path = YEAR_PATH.format(year=year,
                                 lang=lang,
                                 project=project)
    for root, dirs, files in os.walk(year_path):
        for month in sorted(dirs, key=int):
            month = int(month)
            month_name = get_month_names(locale=lang)
            weekdays = get_day_names(locale=lang)
            mname = month_name[month]
            mdata = {'month_name': mname,
                     'month': month,
                     'year': year,
                     'local_year': int_to_local_str(year, locale=lang),
                     'weekdays': {'mon': weekdays[0],
                                  'tues': weekdays[1],
                                  'wed': weekdays[2],
                                  'thurs': weekdays[3],
                                  'fri': weekdays[4],
                                  'sat': weekdays[5],
                                  'sun': weekdays[6]}}
            mdata['dates'] = monthly_calendar(year, month, lang, project)
            ret.append(mdata)
    ret.reverse()
    return ret
Ejemplo n.º 7
0
def update_month(query_date, lang, project):
    year = query_date.year
    month = query_date.month
    month_name = get_month_names(locale=lang)
    weekdays = get_day_names(locale=lang)
    data = {
        "dir_depth": "../" * 4,
        "month_name": month_name[month],
        "project": project.capitalize(),
        "full_lang": LOCAL_LANG_MAP[lang],
        "prev_month": check_month(query_date, 1, lang, project),
        "next_month": check_month(query_date, -1, lang, project),
        "year": year,
        "meta": {"generated": datetime.utcnow().isoformat()},
        "weekdays": {
            "mon": weekdays[0],
            "tues": weekdays[1],
            "wed": weekdays[2],
            "thurs": weekdays[3],
            "fri": weekdays[4],
            "sat": weekdays[5],
            "sun": weekdays[6],
        },
    }
    data["dates"] = monthly_calendar(year, month, lang, project)
    month_index_path = MONTH_INDEX_PATH.format(lang=lang, project=project, year=year, month=month)
    month_index = pjoin(month_index_path, "index.html")
    month_template = choose_template(template=MONTH_INDEX_TMPL, lang=lang)
    save_rendered(month_index, month_template, data)
    return data
Ejemplo n.º 8
0
def _i18n_parse_date_pattern(locale):
    format_keys = {
        'y': ('y', 'Y'),
        'M': ('M',),
        'd': ('d',),
        'h': ('h', 'H'),
        'm': ('m',),
        's': ('s',),
    }
    regexp = [r'[0-9]+']

    date_format = get_date_format('medium', locale=locale)
    time_format = get_time_format('medium', locale=locale)
    datetime_format = get_datetime_format('medium', locale=locale)
    formats = (
        datetime_format.replace('{0}', time_format.format) \
                       .replace('{1}', date_format.format),
        date_format.format)

    orders = []
    for format in formats:
        order = []
        for key, chars in format_keys.iteritems():
            for char in chars:
                idx = format.find('%(' + char)
                if idx != -1:
                    order.append((idx, key))
                    break
        order.sort()
        order = dict((key, idx) for idx, (_, key) in enumerate(order))
        orders.append(order)

    month_names = {
        'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
        'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12,
    }
    if formats[0].find('%(MMM)s') != -1:
        for width in ('wide', 'abbreviated'):
            names = get_month_names(width, locale=locale)
            for num, name in names.iteritems():
                name = name.lower()
                month_names[name] = num
    regexp.extend(month_names.iterkeys())

    period_names = {'am': 'am', 'pm': 'pm'}
    if formats[0].find('%(a)s') != -1:
        names = get_period_names(locale=locale)
        for period, name in names.iteritems():
            if period in ('am', 'pm'):
                name = name.lower()
                period_names[name] = period
    regexp.extend(period_names.iterkeys())

    return {
        'orders': orders,
        'regexp': re.compile('(%s)' % '|'.join(regexp),
                             re.IGNORECASE | re.UNICODE),
        'month_names': month_names,
        'period_names': period_names,
    }
Ejemplo n.º 9
0
def yearly_calendar(year, lang, project):
    ret = []
    year_path = YEAR_PATH.format(year=year, lang=lang, project=project)
    for month in next(os.walk(year_path))[1]:
        month = int(month)
        month_name = get_month_names(locale=lang)
        weekdays = get_day_names(locale=lang)
        mname = month_name[month]
        mdata = {
            "month_name": mname,
            "month": month,
            "year": year,
            "weekdays": {
                "mon": weekdays[0],
                "tues": weekdays[1],
                "wed": weekdays[2],
                "thurs": weekdays[3],
                "fri": weekdays[4],
                "sat": weekdays[5],
                "sun": weekdays[6],
            },
        }
        mdata["dates"] = monthly_calendar(year, month, lang, project)
        ret.append(mdata)
    ret.reverse()
    return ret
Ejemplo n.º 10
0
 def expires_header(self, when):
     # FIXME: strftime returns localized month and day names but here we should use C locale
     # it's not possible to change locale for only this operation so we need our own lookup
     # table here
     return when.strftime("%(day)s, %%d %(month)s %%Y %%H:%%M:%%S GMT" % \
         {
             'day': get_day_names('abbreviated', locale='en_US')[when.weekday()].encode('utf-8'), 
             'month': get_month_names('abbreviated', locale='en_US')[when.month].encode('utf-8')
         })
Ejemplo n.º 11
0
def dashboard(request, template, context=None):
    """
    Performs common operations needed by pages using the 'dashboard' template.
    """
    if context is None:
        context = {}

    locale = Locale.parse(get_language(), sep='-')

    # Set context variables needed by all dashboard pages
    context['newsitem'] = NewsItem.objects.current()
    context['user_has_created_badges'] = request.user.has_created_badges()

    if context['user_has_created_badges']:
        clicks_total = (ClickStats.objects
                        .total(badge_instance__user=request.user))
        context['user_clicks_total'] = format_number(clicks_total,
                                                     locale=locale)

        # Statistics Summary
        months_short = get_month_names('abbreviated', locale=locale)
        months_full = get_month_names('wide', locale=locale)
        months_short_list = [name for k, name in months_short.items()]
        months_full_list = [name for k, name in months_full.items()]

        context['months_short'] = months_short.items()
        context['months_full_list_json'] = json.dumps(months_full_list)
        context['months_short_list_json'] = json.dumps(months_short_list)

        # Leaderboard
        try:
            context['show_leaderboard'] = True
            context['leaderboard'] = (Leaderboard.objects
                                      .top_users(settings.LEADERBOARD_SIZE))
            context['user_standing'] = (Leaderboard.objects
                                        .get(user=request.user))
        except Leaderboard.DoesNotExist:
            context['show_leaderboard'] = False

    return jingo.render(request, template, context)
Ejemplo n.º 12
0
def monthsFromDateRange(date_start=None,date_end=None,locale=None):
    curr_date = datetime.date(date_start.year,date_start.month,1)
    result = []
    if locale and '-' in locale:
        locale = locale.split('-')[0]
    months = dates.get_month_names(width='wide', locale=locale)
    while curr_date<=date_end:
        m = curr_date.month
        y = curr_date.year
        result.append('%s %s' %(months[m].capitalize(),y))
        m += 1
        if m>12:
            y += 1
            m = 1
        curr_date = datetime.date(y,m,1)
    return result
Ejemplo n.º 13
0
    def get_month_names(self, width='wide', context='format'):
        """Return the month names for the specified format

        >>> Locale('en', 'US').get_month_names('wide')[1]
        u'January'
        >>> Locale('es').get_month_names('abbreviated')[1]
        u'ene'
        >>> Locale('de', 'DE').get_month_names('narrow', context='stand-alone')[1]
        u'J'

        In:
          - ``width`` -- 'wide', 'abbreviated' or 'narrow'
          - ``context`` -- either 'format' or 'stand-alone'

        Return:
          - the month names
        """
        return dates.get_month_names(width, context, self)
Ejemplo n.º 14
0
def get_month_names_jquery_ui(req):
    """Get the month names for the jQuery UI datepicker library"""
    locale = req.lc_time
    if locale == 'iso8601':
        locale = req.locale
    if babel and locale:
        month_names = {}
        for width in ('wide', 'abbreviated'):
            names = get_month_names(width, locale=locale)
            month_names[width] = [names[i + 1] for i in xrange(12)]
        return month_names

    return {
        'wide':
        ('January', 'February', 'March', 'April', 'May', 'June', 'July',
         'August', 'September', 'October', 'November', 'December'),
        'abbreviated': ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
                        'Sep', 'Oct', 'Nov', 'Dec'),
    }
Ejemplo n.º 15
0
def get_month_names_jquery_ui(req):
    """Get the month names for the jQuery UI datepicker library"""
    locale = req.lc_time
    if locale == 'iso8601':
        locale = req.locale
    if babel and locale:
        month_names = {}
        for width in ('wide', 'abbreviated'):
            names = get_month_names(width, locale=locale)
            month_names[width] = [names[i + 1] for i in xrange(12)]
        return month_names

    return {
        'wide': (
            'January', 'February', 'March', 'April', 'May', 'June', 'July',
            'August', 'September', 'October', 'November', 'December'),
        'abbreviated': (
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
            'Oct', 'Nov', 'Dec'),
    }
Ejemplo n.º 16
0
def collect():
    articles = {}
    articles['sorted-list'] = []
    articles_dir = os.path.join(app.template_folder, ARTICLES_DIR)
    _, _, article_files = next(os.walk(articles_dir))
    for article_file in sorted(article_files, reverse=True):
        article_path = os.path.join(articles_dir, article_file)
        articles['sorted-list'].append(Article(article_path))

    articles['by-year'] = {}
    for year, articles_by_year in groupby(articles['sorted-list'],
                                          lambda a: a.date.year):
        articles_by_year = list(articles_by_year)
        articles['by-year'][year] = {}
        articles['by-year'][year]['sorted-list'] = articles_by_year
        articles['by-year'][year]['by-month'] = {}
        articles['by-year'][year]['by-month-name'] = {}

        month_names = get_month_names('wide', locale='sr_Latn_RS')
        for month, articles_by_month in groupby(articles_by_year,
                                                lambda a: a.date.month):
            articles_by_month = list(articles_by_month)

            articles['by-year'][year]['by-month'][month] = {}
            articles['by-year'][year]['by-month'][month][
                'sorted-list'] = articles_by_month
            articles['by-year'][year]['by-month'][month]['by-slug'] = \
                {article.slug: article for article in articles_by_month}

            month_name = month_names[month]
            articles['by-year'][year]['by-month-name'][month_name] = {}
            articles['by-year'][year]['by-month-name'][month_name]['sorted-list'] = \
                articles['by-year'][year]['by-month'][month]['sorted-list']
            articles['by-year'][year]['by-month-name'][month_name]['by-slug'] = \
                articles['by-year'][year]['by-month'][month]['by-slug']

    return articles
Ejemplo n.º 17
0
def update_month(query_date, lang, project):
    year = query_date.year
    month = query_date.month
    month_name = get_month_names(locale=lang)
    weekdays = get_day_names(locale=lang)
    data = {
        'dir_depth': '../' * 4,
        'month_name': month_name[month],
        'project': project.capitalize(),
        'full_lang': LOCAL_LANG_MAP[lang],
        'prev_month': check_month(query_date, 1, lang, project),
        'next_month': check_month(query_date, -1, lang, project),
        'year': year,
        'local_year': int_to_local_str(year, locale=lang),
        'meta': {
            'generated': datetime.utcnow().isoformat()
        },
        'weekdays': {
            'mon': weekdays[0],
            'tues': weekdays[1],
            'wed': weekdays[2],
            'thurs': weekdays[3],
            'fri': weekdays[4],
            'sat': weekdays[5],
            'sun': weekdays[6]
        }
    }
    data['dates'] = monthly_calendar(year, month, lang, project)
    month_index_path = MONTH_INDEX_PATH.format(lang=lang,
                                               project=project,
                                               year=year,
                                               month=month)
    month_index = pjoin(month_index_path, 'index.html')
    month_template = choose_template(template=MONTH_INDEX_TMPL, lang=lang)
    save_rendered(month_index, month_template, data)
    return data
Ejemplo n.º 18
0
def yearly_calendar(year, lang, project):
    ret = []
    year_path = YEAR_PATH.format(year=year,
                                 lang=lang,
                                 project=project)
    for month in next(os.walk(year_path))[1]:
        month = int(month)
        month_name = get_month_names(locale=lang)
        weekdays = get_day_names(locale=lang)
        mname = month_name[month]
        mdata = {'month_name': mname,
                 'month': month,
                 'year': year,
                 'weekdays': {'mon': weekdays[0],
                              'tues': weekdays[1],
                              'wed': weekdays[2],
                              'thurs': weekdays[3],
                              'fri': weekdays[4],
                              'sat': weekdays[5],
                              'sun': weekdays[6]}}
        mdata['dates'] = monthly_calendar(year, month, lang, project)
        ret.append(mdata)
    ret.reverse()
    return ret
Ejemplo n.º 19
0
def test_get_month_names():
    assert dates.get_month_names('wide', locale='en_US')[1] == u'January'
    assert dates.get_month_names('abbreviated', locale='es')[1] == u'ene.'
    de = dates.get_month_names('narrow', context='stand-alone', locale='de_DE')
    assert de[1] == u'J'
Ejemplo n.º 20
0
    def by(self, by, values):
        if by == 'bysetpos':
            before = [-v for v in reversed(values) if v < 0]
            after = [v for v in values if v > 0]
            parts = []
            t = 0
            if after:
                if len(after) == 1 and after[0] == 1:
                    parts.append('the first')
                    t += 1
                else:
                    parts.append(
                        'the %s first' %
                        self.join_list([self.nth(val) for val in after]))
                    t += 2
            if before:
                if len(before) == 1 and before[0] == 1:
                    parts.append('the last')
                    t += 1
                else:
                    parts.append(
                        'the %s last' %
                        self.join_list([self.nth(val) for val in before]))
                    t += 2

            return ' and '.join(parts) + ' occurence%s' % ('s'
                                                           if t != 1 else '')

        if by == 'bymonth':
            return 'on %s' % self.join_list([
                get_month_names(locale=self.__class__.__name__)[month]
                for month in values
            ])

        if by == 'bymonthday':
            return 'the %s of month' % self.join_list(values)

        if by == 'byyearday':
            return 'the %s of year' % self.join_list(values)

        if by == 'byweekno':
            return 'the week%s n°%s' % ('s' if len(values) > 1 else '',
                                        self.join_list(values))

        if by == 'byweekday':
            dow = get_day_names(locale=self.__class__.__name__)

            return 'on %s' % self.join_list([dow[val] for val in values])

        if by == 'byeaster':
            before = [-v for v in reversed(values) if v < 0]
            after = [v for v in values if v > 0]
            parts = []
            if before:
                if len(before) == 1 and before[0] == 1:
                    parts.append('1 day before Easter')
                else:
                    parts.append('%s days before Easter' %
                                 self.join_list(before))
            if after:
                if len(after) == 1 and before[0] == 1:
                    parts.append('1 day after Easter')
                else:
                    parts.append('%s days after Easter' %
                                 self.join_list(after))

            return ' and '.join(parts)
Ejemplo n.º 21
0
    def __init__(self, master=None, **kw):
        """
        Construct a Calendar with parent master.

        STANDARD OPTIONS

            cursor, font, borderwidth, state

        WIDGET-SPECIFIC OPTIONS

            year, month: initially displayed month, default is current month
            day: initially selected day, if month or year is given but not
                day, no initial selection, otherwise, default is today
            locale: locale to use, e.g. 'fr_FR'
            selectmode: "none" or "day" (default) define whether the user
                        can change the selected day with a mouse click
            showweeknumbers: boolean (default is True) to show/hide week numbers
            textvariable: StringVar that will contain the currently selected date as str
            background: background color of calendar border and month/year name
            foreground: foreground color of month/year name
            bordercolor: day border color
            selectbackground: background color of selected day
            selectforeground: foreground color of selected day
            disabledselectbackground: background color of selected day in disabled state
            disabledselectforeground: foreground color of selected day in disabled state
            normalbackground: background color of normal week days
            normalforeground: foreground color of normal week days
            othermonthforeground: foreground color of normal week days
                                  belonging to the previous/next month
            othermonthbackground: background color of normal week days
                                  belonging to the previous/next month
            othermonthweforeground: foreground color of week-end days
                                    belonging to the previous/next month
            othermonthwebackground: background color of week-end days
                                    belonging to the previous/next month
            weekendbackground: background color of week-end days
            weekendforeground: foreground color of week-end days
            headersbackground: background color of day names and week numbers
            headersforeground: foreground color of day names and week numbers
            disableddaybackground: background color of days in disabled state
            disableddayforeground: foreground color of days in disabled state

        VIRTUAL EVENTS

            A <<CalendarSelected>> event is generated each time the user
            selects a day with the mouse.
        """

        curs = kw.pop("cursor", "")
        font = kw.pop("font", "Liberation\ Sans 9")
        classname = kw.pop('class_', "Calendar")
        name = kw.pop('name', None)
        ttk.Frame.__init__(self, master, class_=classname, cursor=curs, name=name)
        self._style_prefixe = str(self)
        ttk.Frame.configure(self, style='main.%s.TFrame' % self._style_prefixe)

        self._textvariable = kw.pop("textvariable", None)

        self._font = Font(self, font)
        prop = self._font.actual()
        prop["size"] += 1
        self._header_font = Font(self, **prop)

        # state
        state = kw.get('state', 'normal')

        try:
            bd = int(kw.pop('borderwidth', 2))
        except ValueError:
            raise ValueError('expected integer for the borderwidth option.')

        self._cal = calendar.TextCalendar(calendar.MONDAY)

        # --- locale
        locale = kw.pop("locale", getdefaultlocale()[0])
        self._day_names = get_day_names('abbreviated', locale=locale)
        self._month_names = get_month_names('wide', locale=locale)

        # --- date
        today = self.date.today()

        if (("month" in kw) or ("year" in kw)) and ("day" not in kw):
            month = kw.pop("month", today.month)
            year = kw.pop('year', today.year)
            self._sel_date = None  # selected day
        else:
            day = kw.pop('day', today.day)
            month = kw.pop("month", today.month)
            year = kw.pop('year', today.year)
            try:
                self._sel_date = self.date(year, month, day)  # selected day
                if self._textvariable is not None:
                    self._textvariable.set(format_date(self._sel_date, 'short', locale))
            except ValueError:
                self._sel_date = None

        self._date = self.date(year, month, 1)  # (year, month) displayed by the calendar

        # --- selectmode
        selectmode = kw.pop("selectmode", "day")
        if selectmode not in ("none", "day"):
            raise ValueError("'selectmode' option should be 'none' or 'day'.")
        # --- show week numbers
        showweeknumbers = kw.pop('showweeknumbers', True)

        # --- style
        self.style = ttk.Style(self)
        active_bg = self.style.lookup('TEntry', 'selectbackground', ('focus',))
        dis_active_bg = self.style.lookup('TEntry', 'selectbackground', ('disabled',))
        dis_bg = self.style.lookup('TLabel', 'background', ('disabled',))
        dis_fg = self.style.lookup('TLabel', 'foreground', ('disabled',))

        # --- properties
        options = ['cursor',
                   'font',
                   'borderwidth',
                   'state',
                   'selectmode',
                   'textvariable',
                   'locale',
                   'showweeknumbers',
                   'selectbackground',
                   'selectforeground',
                   'disabledselectbackground',
                   'disabledselectforeground',
                   'normalbackground',
                   'normalforeground',
                   'background',
                   'foreground',
                   'bordercolor',
                   'othermonthforeground',
                   'othermonthbackground',
                   'othermonthweforeground',
                   'othermonthwebackground',
                   'weekendbackground',
                   'weekendforeground',
                   'headersbackground',
                   'headersforeground',
                   'disableddaybackground',
                   'disableddayforeground']

        keys = list(kw.keys())
        for option in keys:
            if option not in options:
                del(kw[option])

        self._properties = {"cursor": curs,
                            "font": font,
                            "borderwidth": bd,
                            "state": state,
                            "locale": locale,
                            "selectmode": selectmode,
                            'textvariable': self._textvariable,
                            'showweeknumbers': showweeknumbers,
                            'selectbackground': active_bg,
                            'selectforeground': 'white',
                            'disabledselectbackground': dis_active_bg,
                            'disabledselectforeground': 'white',
                            'normalbackground': 'white',
                            'normalforeground': 'black',
                            'background': 'gray30',
                            'foreground': 'white',
                            'bordercolor': 'gray70',
                            'othermonthforeground': 'gray45',
                            'othermonthbackground': 'gray93',
                            'othermonthweforeground': 'gray45',
                            'othermonthwebackground': 'gray75',
                            'weekendbackground': 'gray80',
                            'weekendforeground': 'gray30',
                            'headersbackground': 'gray70',
                            'headersforeground': 'black',
                            'disableddaybackground': dis_bg,
                            'disableddayforeground': dis_fg}
        self._properties.update(kw)

        # --- init calendar
        # --- *-- header: month - year
        header = ttk.Frame(self, style='main.%s.TFrame' % self._style_prefixe)

        f_month = ttk.Frame(header,
                            style='main.%s.TFrame' % self._style_prefixe)
        self._l_month = ttk.Button(f_month,
                                   style='L.%s.TButton' % self._style_prefixe,
                                   command=self._prev_month)
        self._header_month = ttk.Label(f_month, width=10, anchor='center',
                                       style='main.%s.TLabel' % self._style_prefixe, font=self._header_font)
        self._r_month = ttk.Button(f_month,
                                   style='R.%s.TButton' % self._style_prefixe,
                                   command=self._next_month)
        self._l_month.pack(side='left', fill="y")
        self._header_month.pack(side='left', padx=4)
        self._r_month.pack(side='left', fill="y")

        f_year = ttk.Frame(header, style='main.%s.TFrame' % self._style_prefixe)
        self._l_year = ttk.Button(f_year, style='L.%s.TButton' % self._style_prefixe,
                                  command=self._prev_year)
        self._header_year = ttk.Label(f_year, width=4, anchor='center',
                                      style='main.%s.TLabel' % self._style_prefixe, font=self._header_font)
        self._r_year = ttk.Button(f_year, style='R.%s.TButton' % self._style_prefixe,
                                  command=self._next_year)
        self._l_year.pack(side='left', fill="y")
        self._header_year.pack(side='left', padx=4)
        self._r_year.pack(side='left', fill="y")

        f_month.pack(side='left', fill='x')
        f_year.pack(side='right')

        # --- *-- calendar
        self._cal_frame = ttk.Frame(self,
                                    style='cal.%s.TFrame' % self._style_prefixe)

        ttk.Label(self._cal_frame,
                  style='headers.%s.TLabel' % self._style_prefixe).grid(row=0,
                                                                        column=0,
                                                                        sticky="eswn")

        for i in range(7):
            d = self._day_names[i]
            self._cal_frame.columnconfigure(i + 1, weight=1)
            ttk.Label(self._cal_frame,
                      font=self._font,
                      style='headers.%s.TLabel' % self._style_prefixe,
                      anchor="center",
                      text=d, width=4).grid(row=0, column=i + 1,
                                            sticky="ew", pady=(0, 1))
        self._week_nbs = []
        self._calendar = []
        for i in range(1, 7):
            self._cal_frame.rowconfigure(i, weight=1)
            wlabel = ttk.Label(self._cal_frame, style='headers.%s.TLabel' % self._style_prefixe,
                               font=self._font, padding=2,
                               anchor="e", width=2)
            self._week_nbs.append(wlabel)
            wlabel.grid(row=i, column=0, sticky="esnw", padx=(0, 1))
            if not showweeknumbers:
                wlabel.grid_remove()
            self._calendar.append([])
            for j in range(1, 8):
                label = ttk.Label(self._cal_frame, style='normal.%s.TLabel' % self._style_prefixe,
                                  font=self._font, anchor="center")
                self._calendar[-1].append(label)
                label.grid(row=i, column=j, padx=(0, 1), pady=(0, 1), sticky="nsew")
                if selectmode is "day":
                    label.bind("<1>", self._on_click)

        # --- *-- pack main elements
        header.pack(fill="x", padx=2, pady=2)
        self._cal_frame.pack(fill="both", expand=True, padx=bd, pady=bd)

        self.config(state=state)

        # --- bindings
        self.bind('<<ThemeChanged>>', self._setup_style)

        self._setup_style()
        self._display_calendar()

        if self._textvariable is not None:
            try:
                self._textvariable_trace_id = self._textvariable.trace_add('write', self._textvariable_trace)
            except AttributeError:
                self._textvariable_trace_id = self._textvariable.trace('w', self._textvariable_trace)
Ejemplo n.º 22
0
from indico.modules.rb.models.reservation_occurrences import ReservationOccurrence
from indico.modules.rb.models.reservations import RepeatMapping, Reservation
from indico.modules.rb.models.room_attributes import RoomAttributeAssociation, RoomAttribute
from indico.modules.rb.models.room_bookable_hours import BookableHours
from indico.modules.rb.models.equipment import EquipmentType
from indico.modules.rb.models.room_nonbookable_periods import NonBookablePeriod
from indico.modules.rb.models.rooms import Room
from indico.util.console import cformat, verbose_iterator
from indico.util.date_time import as_utc
from indico.util.string import safe_upper, is_valid_mail
from indico_zodbimport import Importer, convert_to_unicode, convert_principal_list
from indico_zodbimport.util import UnbreakingDB, get_storage

french_month_names = [
    (str(i), name[:3].encode('utf-8').lower())
    for i, name in dates.get_month_names(locale='fr_FR').iteritems()
]

attribute_map = {
    'Simba List': 'Manager Group',
    'Booking Simba List': 'Allowed Booking Group'
}


def generate_name(old_room):
    return '{}-{}-{}'.format(old_room.building, old_room.floor,
                             old_room.roomNr)


def get_canonical_name_of(old_room):
    return '{}-{}'.format(old_room._locationName, generate_name(old_room))
Ejemplo n.º 23
0
from indico.modules.rb.models.reservation_occurrences import ReservationOccurrence
from indico.modules.rb.models.reservations import RepeatMapping, Reservation
from indico.modules.rb.models.room_attributes import RoomAttributeAssociation, RoomAttribute
from indico.modules.rb.models.room_bookable_hours import BookableHours
from indico.modules.rb.models.equipment import EquipmentType
from indico.modules.rb.models.room_nonbookable_periods import NonBookablePeriod
from indico.modules.rb.models.rooms import Room
from indico.util.console import cformat, verbose_iterator
from indico.util.date_time import as_utc
from indico.util.string import safe_upper, is_valid_mail
from indico_zodbimport import Importer, convert_to_unicode, convert_principal_list
from indico_zodbimport.util import UnbreakingDB, get_storage


french_month_names = [
    (str(i), name[:3].encode("utf-8").lower()) for i, name in dates.get_month_names(locale="fr_FR").iteritems()
]

attribute_map = {"Simba List": "Manager Group", "Booking Simba List": "Allowed Booking Group"}


def generate_name(old_room):
    return "{}-{}-{}".format(old_room.building, old_room.floor, old_room.roomNr)


def get_canonical_name_of(old_room):
    return "{}-{}".format(old_room._locationName, generate_name(old_room))


def get_room_id(guid):
    return int(guid.split("|")[1].strip())
Ejemplo n.º 24
0
def _i18n_parse_date_pattern(locale):
    format_keys = {
        'y': ('y', 'Y'),
        'M': ('M',),
        'd': ('d',),
        'h': ('h', 'H'),
        'm': ('m',),
        's': ('s',),
    }

    if locale is None:
        formats = (_libc_get_datetime_format_hint(format=True),
                   _libc_get_date_format_hint(format=True))
    else:
        date_format = get_date_format('medium', locale=locale)
        time_format = get_time_format('medium', locale=locale)
        datetime_format = get_datetime_format('medium', locale=locale)
        formats = (datetime_format.replace('{0}', time_format.format) \
                                  .replace('{1}', date_format.format),
                   date_format.format)

    orders = []
    for format in formats:
        order = []
        for key, chars in format_keys.iteritems():
            for char in chars:
                idx = format.find('%(' + char)
                if idx != -1:
                    order.append((idx, key))
                    break
        order.sort()
        orders.append(dict((key, idx) for idx, (_, key) in enumerate(order)))

    # always allow using English names regardless of locale
    month_names = dict(zip(('jan', 'feb', 'mar', 'apr', 'may', 'jun',
                            'jul', 'aug', 'sep', 'oct', 'nov', 'dec',),
                           xrange(1, 13)))
    period_names = {'am': 'am', 'pm': 'pm'}

    if locale is None:
        for num in xrange(1, 13):
            t = datetime(1999, num, 1, tzinfo=utc)
            names = format_date(t, '%b\t%B', utc).split('\t')
            month_names.update((name.lower(), num) for name in names
                               if str(num) not in name)
        for num, period in ((11, 'am'), (23, 'pm')):
            t = datetime(1999, 1, 1, num, tzinfo=utc)
            name = format_datetime(t, '%p', utc)
            if name:
                period_names[name.lower()] = period
    else:
        if formats[0].find('%(MMM)s') != -1:
            for width in ('wide', 'abbreviated'):
                names = get_month_names(width, locale=locale)
                month_names.update((name.lower(), num)
                                   for num, name in names.iteritems())
        if formats[0].find('%(a)s') != -1:
            names = get_period_names(locale=locale)
            period_names.update((name.lower(), period)
                                for period, name in names.iteritems()
                                if period in ('am', 'pm'))

    regexp = ['[0-9]+']
    regexp.extend(re.escape(name) for name in month_names)
    regexp.extend(re.escape(name) for name in period_names)

    return {
        'orders': orders,
        'regexp': re.compile('(%s)' % '|'.join(regexp), re.IGNORECASE),
        'month_names': month_names,
        'period_names': period_names,
    }
Ejemplo n.º 25
0
from indico.modules.rb.models.reservation_occurrences import ReservationOccurrence
from indico.modules.rb.models.reservations import RepeatMapping, Reservation
from indico.modules.rb.models.room_attributes import RoomAttributeAssociation, RoomAttribute
from indico.modules.rb.models.room_bookable_hours import BookableHours
from indico.modules.rb.models.equipment import EquipmentType
from indico.modules.rb.models.room_nonbookable_periods import NonBookablePeriod
from indico.modules.rb.models.rooms import Room
from indico.util.console import cformat, verbose_iterator
from indico.util.date_time import as_utc
from indico.util.string import safe_upper, is_valid_mail
from indico_zodbimport import Importer, convert_to_unicode, convert_principal_list
from indico_zodbimport.util import UnbreakingDB, get_storage


french_month_names = [(str(i), name[:3].encode('utf-8').lower())
                      for i, name in dates.get_month_names(locale='fr_FR').iteritems()]

attribute_map = {
    'Simba List': 'Manager Group',
    'Booking Simba List': 'Allowed Booking Group'
}


def generate_name(old_room):
    return '{}-{}-{}'.format(old_room.building, old_room.floor, old_room.roomNr)


def get_canonical_name_of(old_room):
    return '{}-{}'.format(old_room._locationName, generate_name(old_room))

Ejemplo n.º 26
0
    def by(self, by, values):
        if by == 'bysetpos':
            before = [-v for v in reversed(values) if v < 0]
            after = [v for v in values if v > 0]
            parts = []
            t = 0
            if after:
                if len(after) == 1:
                    parts.append('la %s' % self.nth(after[0], self.FEMININ))
                    t += 1
                else:
                    t += 2
                    parts.append(
                        'les %s premières' %
                        self.join_list([self.nth(val) for val in after]))
            if before:
                if len(before) == 1:
                    if before[0] == 1:
                        parts.append('la dernière')
                    else:
                        parts.append('l’%sdernière' % ('avant-' *
                                                       (before[0] - 1)))
                    t += 1
                else:
                    t += 2
                    parts.append(
                        'les %s dernières' %
                        self.join_list([self.nth(val) for val in before]))

            return ' et '.join(parts) + ' occurence%s' % ('s'
                                                          if t != 1 else '')

        if by == 'bymonth':
            return 'en %s' % self.join_list([
                get_month_names(locale=self.__class__.__name__)[month]
                for month in values
            ])
        if by == 'bymonthday':
            if len(values) == 1:
                return 'le %s jour du mois' % self.nth(val)
            return 'les %s jours du mois' % self.join_list(
                [self.nth(val) for val in values])

        if by == 'byyearday':
            if len(values) == 1:
                return 'le %s jour de l’année' % self.nth(val)
            return 'les %s jours de l’année' % self.join_list(
                [self.nth(val) for val in values])

        if by == 'byweekno':
            if len(values) == 1:
                return 'la semaine n°%d' % values[0]
            return 'les semaines n°%s' % self.join_list(values)

        if by == 'byweekday':
            dow = get_day_names(locale=self.__class__.__name__)

            return 'le %s' % self.join_list([dow[val] for val in values])

        if by == 'byeaster':
            before = [-v for v in reversed(values) if v < 0]
            after = [v for v in values if v > 0]
            parts = []
            if before:
                if len(before) == 1 and before[0] == 1:
                    parts.append('la veille de Pâques')
                else:
                    parts.append('%s jours avant Pâques' %
                                 self.join_list(before))
            if after:
                if len(after) == 1 and after[0] == 1:
                    parts.append('le lendemain de Pâques')
                else:
                    parts.append('%s jours après Pâques' %
                                 self.join_list(after))

            return ' et '.join(parts)
Ejemplo n.º 27
0
def _i18n_parse_date_patterns():
    if not babel:
        return {}

    format_keys = {
        'y': ('y', 'Y'),
        'M': ('M', ),
        'd': ('d', ),
        'h': ('h', 'H'),
        'm': ('m', ),
        's': ('s', ),
    }
    patterns = {}

    for locale in get_available_locales():
        regexp = [r'[0-9]+']

        date_format = get_date_format('medium', locale=locale)
        time_format = get_time_format('medium', locale=locale)
        datetime_format = get_datetime_format('medium', locale=locale)

        formats = (
            datetime_format.replace('{0}', time_format.format) \
                           .replace('{1}', date_format.format),
            date_format.format)

        orders = []
        for format in formats:
            order = []
            for key, chars in format_keys.iteritems():
                for char in chars:
                    idx = format.find('%(' + char)
                    if idx != -1:
                        order.append((idx, key))
                        break
            order.sort()
            order = dict((key, idx) for idx, (_, key) in enumerate(order))
            orders.append(order)

        month_names = {
            'jan': 1,
            'feb': 2,
            'mar': 3,
            'apr': 4,
            'may': 5,
            'jun': 6,
            'jul': 7,
            'aug': 8,
            'sep': 9,
            'oct': 10,
            'nov': 11,
            'dec': 12,
        }
        if formats[0].find('%(MMM)s') != -1:
            for width in ('wide', 'abbreviated'):
                names = get_month_names(width, locale=locale)
                for num, name in names.iteritems():
                    name = name.lower()
                    month_names[name] = num
        regexp.extend(month_names.iterkeys())

        period_names = {'am': 'am', 'pm': 'pm'}
        if formats[0].find('%(a)s') != -1:
            names = get_period_names(locale=locale)
            for period, name in names.iteritems():
                name = name.lower()
                period_names[name] = period
        regexp.extend(period_names.iterkeys())

        patterns[locale] = {
            'orders':
            orders,
            'regexp':
            re.compile('(%s)' % '|'.join(regexp), re.IGNORECASE | re.UNICODE),
            'month_names':
            month_names,
            'period_names':
            period_names,
        }

    return patterns
Ejemplo n.º 28
0
def _get_month_name(date, loc):
    m = date.month
    return get_month_names('wide', locale=loc)[m]
Ejemplo n.º 29
0
def get_abbr_month_names(locale=LC_TIME):
    """Get list of abbreviated month names, starting with Jan."""
    return get_month_names(width='abbreviated', locale=locale)
def get_month_selection_field(validate_with):
    month_names = get_month_names(locale=get_locale())
    month_choices = [('', _('Select month'))] + [(str(key), month_names[key]) for key in range(1, 13)]
    return SelectField(choices=month_choices, default='', validators=validate_with)
Ejemplo n.º 31
0
    def prepare_figure(
            cls,
            max_index,
            x_label='',
            y_label='',
            width=12,
            height=3,
            month_names=False,
            language='en',
            title='',
    ):

        fig, ax = plt.subplots(1, 1)
        fig.set_figwidth(width)
        fig.set_figheight(height)
        fig.subplots_adjust(left=0.06, bottom=0.1, right=0.94, top=0.92)

        fig.text(
            0.5,
            0.01,
            x_label.decode('utf-8'),
            horizontalalignment='center',
            fontsize=12
        )

        fig.text(
            0.5,
            0.95,
            title.decode('utf-8'),
            horizontalalignment='center',
            fontsize=16,
            style='oblique',
        )

        fig.text(
            0.01,
            0.5,
            y_label.decode('utf-8'),
            verticalalignment='center',
            fontsize=12,
            rotation=90
        )

        # nr_bars = self.y.maxindex
        nr_bars = max_index

        if month_names:
            monthly_labels_pos = [
                p * nr_bars / 12.0 + (0.0416667 * nr_bars - 0.5) for p in range(0, 12)
            ]
            ax.set_xticks(monthly_labels_pos)
            ax.set_xticklabels(
                get_month_names(width='abbreviated', locale=language).itervalues())

            monthly_dividers = [
                p * nr_bars / 12.0 + (0.0416667 * nr_bars - 0.5) - 1.5 for p in range(0, 13)
            ]
            ax.set_xticks(monthly_dividers, minor=True)
        else:
            monthly_labels_pos = [
                p * nr_bars / nr_bars for p in range(0, nr_bars)
            ]
            ax.set_xticks(monthly_labels_pos)
            labels = [str(x + 1) for x in range(max_index)]
            max_labels_shown = 15
            skip = len(labels) // max_labels_shown
            if skip:
                for i in range(len(labels)):
                    if i % skip:
                        labels[i] = ''
            ax.set_xticklabels(labels)

        ax.grid(True, which="minor", axis="x", color="black", linestyle='--')
        ax.tick_params(axis="x", which="major", length=0)
        return fig, ax
Ejemplo n.º 32
0
    def plot_ts_comparison(cls, x_data, y_data, frequency, language='en', encoded=True):

        if frequency == 'fiveday':
            rows, columns = 12, 6
            left = 0.06
            bottom = 0.08
            right = 0.94
            top = 0.92
            wspace = 0.4
            hspace = 0.8
            figsize = (11, 14)
        if frequency == 'decade':
            rows, columns = 6, 6
            left = 0.06
            bottom = 0.08
            right = 0.94
            top = 0.92
            wspace = 0.4
            hspace = 0.8
            figsize = (11, 7)
        elif frequency == 'monthly':
            rows, columns = 4, 3
            left = 0.06
            bottom = 0.08
            right = 0.94
            top = 0.92
            wspace = 0.2
            hspace = 0.4
            figsize = (11, 7)

        fig, axes = plt.subplots(rows, columns, figsize=figsize)
        fig.subplots_adjust(left=left, bottom=bottom, right=right, top=top, wspace=wspace, hspace=hspace)

        fig.text(
            0.5,
            0.01,
            r'${}\ [m^3/s]$'.format(_('Observed')).decode('utf-8'),
            horizontalalignment='center',
            fontsize=12
        )
        fig.text(
            0.01,
            0.5,
            r'${}\ [m^3/s]$'.format(_('Predicted')).decode('utf-8'),
            verticalalignment='center',
            fontsize=12,
            rotation=90
        )

        for row_num, row in enumerate(axes):
            for ax_num, ax in enumerate(row):
                # get period
                period = row_num * len(row) + ax_num + 1
                month, day = cls.get_month_day(frequency, period)
                like_str = "-{:02d}-{:02d}".format(month, day)

                x_sub_data = x_data.filter(like=like_str)
                y_sub_data = y_data.filter(like=like_str)

                # draw points
                ax.scatter(x_sub_data, y_sub_data, s=20, facecolors='none', edgecolors='black')
                # set period label
                ax.xaxis.set_label_position('top')

                if frequency == 'fiveday':
                    x_label = '{pentade} {period}'.format(
                        pentade=_('pentade').capitalize(),
                        period=period
                    ).decode('utf-8')

                elif frequency == 'decade':
                    x_label = '{decade} {period}'.format(
                        decade=_('decade').capitalize(),
                        period=period
                    ).decode('utf-8')

                elif frequency == 'monthly':
                    x_label = get_month_names(
                        width='wide',
                        locale=language
                    )[period]

                ax.set_xlabel(x_label, fontweight='bold')

                # rotate y tick labels
                ax.tick_params(axis='y', labelrotation=90)

                # set only min and max values for ticks
                ax.set_xticks([round(x, 1) for x in ax.get_xlim()])
                ax.set_yticks([round(y, 1) for y in ax.get_ylim()])

                # "zoom out"
                x_range = ax.get_xlim()[1] - ax.get_xlim()[0]
                y_range = ax.get_ylim()[1] - ax.get_ylim()[0]
                x_out = x_range * 0.1
                y_out = y_range * 0.1
                ax.set_xlim([ax.get_xlim()[0] - x_out, ax.get_xlim()[1] + x_out])
                ax.set_ylim([ax.get_ylim()[0] - y_out, ax.get_ylim()[1] + y_out])

                if not x_sub_data.empty:
                    a, b = cls.get_line_points(x_sub_data, y_sub_data)
                    ax.plot(a, b, color='red')  # predicted

        return cls.encode_figure(fig) if encoded else fig
Ejemplo n.º 33
0
 def __deepcopy__(self, memo):
     res = forms.ChoiceField.__deepcopy__(self, memo)
     res.choices = dates.get_month_names(width=self.width, locale=get_request().locale).items()
     return res
Ejemplo n.º 34
0
def _i18n_parse_date_pattern(locale):
    format_keys = {
        'y': ('y', 'Y'),
        'M': ('M', ),
        'd': ('d', ),
        'h': ('h', 'H'),
        'm': ('m', ),
        's': ('s', ),
    }

    if locale is None:
        formats = (_libc_get_datetime_format_hint(format=True),
                   _libc_get_date_format_hint(format=True))
    else:
        date_format = get_date_format('medium', locale=locale)
        time_format = get_time_format('medium', locale=locale)
        datetime_format = get_datetime_format('medium', locale=locale)
        formats = (datetime_format.replace('{0}', time_format.format).replace(
            '{1}', date_format.format), date_format.format)

    orders = []
    for format in formats:
        order = []
        for key, chars in format_keys.iteritems():
            for char in chars:
                idx = format.find('%(' + char)
                if idx != -1:
                    order.append((idx, key))
                    break
        order.sort()
        orders.append({key: idx for idx, (_, key) in enumerate(order)})

    # always allow using English names regardless of locale
    month_names = dict(
        zip((
            'jan',
            'feb',
            'mar',
            'apr',
            'may',
            'jun',
            'jul',
            'aug',
            'sep',
            'oct',
            'nov',
            'dec',
        ), xrange(1, 13)))
    period_names = {'am': 'am', 'pm': 'pm'}

    if locale is None:
        for num in xrange(1, 13):
            t = datetime(1999, num, 1, tzinfo=utc)
            names = format_date(t, '%b\t%B', utc).split('\t')
            month_names.update(
                (name.lower(), num) for name in names if str(num) not in name)
        for num, period in ((11, 'am'), (23, 'pm')):
            t = datetime(1999, 1, 1, num, tzinfo=utc)
            name = format_datetime(t, '%p', utc)
            if name:
                period_names[name.lower()] = period
    else:
        if formats[0].find('%(MMM)s') != -1:
            for width in ('wide', 'abbreviated'):
                names = get_month_names(width, locale=locale)
                month_names.update(
                    (name.lower(), num) for num, name in names.iteritems())
        if formats[0].find('%(a)s') != -1:
            names = get_period_names(locale=locale)
            period_names.update((name.lower(), period)
                                for period, name in names.iteritems()
                                if period in ('am', 'pm'))

    regexp = ['[0-9]+']
    regexp.extend(re.escape(name) for name in month_names)
    regexp.extend(re.escape(name) for name in period_names)

    return {
        'orders': orders,
        'regexp': re.compile('(%s)' % '|'.join(regexp), re.IGNORECASE),
        'month_names': month_names,
        'period_names': period_names,
    }
Ejemplo n.º 35
0
def test_get_month_names():
    assert dates.get_month_names('wide', locale='en_US')[1] == u'January'
    assert dates.get_month_names('abbreviated', locale='es')[1] == u'ene.'
    de = dates.get_month_names('narrow', context='stand-alone', locale='de_DE')
    assert de[1] == u'J'
Ejemplo n.º 36
0
def _get_month_name(date, loc):
    m = date.month
    return get_month_names('wide', locale=loc)[m]