id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
6,500
linuxsoftware/ls.joyous
ls/joyous/utils/weeks.py
_ssweek_to_gregorian
def _ssweek_to_gregorian(ssweek_year, ssweek_week, ssweek_day): "Gregorian calendar date for the given Sundaystarting-week year, week and day" year_start = _ssweek_year_start(ssweek_year) return year_start + dt.timedelta(days=ssweek_day-1, weeks=ssweek_week-1)
python
def _ssweek_to_gregorian(ssweek_year, ssweek_week, ssweek_day): "Gregorian calendar date for the given Sundaystarting-week year, week and day" year_start = _ssweek_year_start(ssweek_year) return year_start + dt.timedelta(days=ssweek_day-1, weeks=ssweek_week-1)
[ "def", "_ssweek_to_gregorian", "(", "ssweek_year", ",", "ssweek_week", ",", "ssweek_day", ")", ":", "year_start", "=", "_ssweek_year_start", "(", "ssweek_year", ")", "return", "year_start", "+", "dt", ".", "timedelta", "(", "days", "=", "ssweek_day", "-", "1", ",", "weeks", "=", "ssweek_week", "-", "1", ")" ]
Gregorian calendar date for the given Sundaystarting-week year, week and day
[ "Gregorian", "calendar", "date", "for", "the", "given", "Sundaystarting", "-", "week", "year", "week", "and", "day" ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/weeks.py#L66-L69
6,501
linuxsoftware/ls.joyous
ls/joyous/utils/weeks.py
_ssweek_num_weeks
def _ssweek_num_weeks(ssweek_year): "Get the number of Sundaystarting-weeks in this year" year_start = _ssweek_year_start(ssweek_year) next_year_start = _ssweek_year_start(ssweek_year+1) year_num_weeks = ((next_year_start - year_start).days) // 7 return year_num_weeks
python
def _ssweek_num_weeks(ssweek_year): "Get the number of Sundaystarting-weeks in this year" year_start = _ssweek_year_start(ssweek_year) next_year_start = _ssweek_year_start(ssweek_year+1) year_num_weeks = ((next_year_start - year_start).days) // 7 return year_num_weeks
[ "def", "_ssweek_num_weeks", "(", "ssweek_year", ")", ":", "year_start", "=", "_ssweek_year_start", "(", "ssweek_year", ")", "next_year_start", "=", "_ssweek_year_start", "(", "ssweek_year", "+", "1", ")", "year_num_weeks", "=", "(", "(", "next_year_start", "-", "year_start", ")", ".", "days", ")", "//", "7", "return", "year_num_weeks" ]
Get the number of Sundaystarting-weeks in this year
[ "Get", "the", "number", "of", "Sundaystarting", "-", "weeks", "in", "this", "year" ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/weeks.py#L71-L76
6,502
linuxsoftware/ls.joyous
ls/joyous/utils/weeks.py
_ssweek_info
def _ssweek_info(ssweek_year, ssweek_week): "Give all the ssweek info we need from one calculation" prev_year_start = _ssweek_year_start(ssweek_year-1) year_start = _ssweek_year_start(ssweek_year) next_year_start = _ssweek_year_start(ssweek_year+1) first_day = year_start + dt.timedelta(weeks=ssweek_week-1) last_day = first_day + dt.timedelta(days=6) prev_year_num_weeks = ((year_start - prev_year_start).days) // 7 year_num_weeks = ((next_year_start - year_start).days) // 7 return (first_day, last_day, prev_year_num_weeks, year_num_weeks)
python
def _ssweek_info(ssweek_year, ssweek_week): "Give all the ssweek info we need from one calculation" prev_year_start = _ssweek_year_start(ssweek_year-1) year_start = _ssweek_year_start(ssweek_year) next_year_start = _ssweek_year_start(ssweek_year+1) first_day = year_start + dt.timedelta(weeks=ssweek_week-1) last_day = first_day + dt.timedelta(days=6) prev_year_num_weeks = ((year_start - prev_year_start).days) // 7 year_num_weeks = ((next_year_start - year_start).days) // 7 return (first_day, last_day, prev_year_num_weeks, year_num_weeks)
[ "def", "_ssweek_info", "(", "ssweek_year", ",", "ssweek_week", ")", ":", "prev_year_start", "=", "_ssweek_year_start", "(", "ssweek_year", "-", "1", ")", "year_start", "=", "_ssweek_year_start", "(", "ssweek_year", ")", "next_year_start", "=", "_ssweek_year_start", "(", "ssweek_year", "+", "1", ")", "first_day", "=", "year_start", "+", "dt", ".", "timedelta", "(", "weeks", "=", "ssweek_week", "-", "1", ")", "last_day", "=", "first_day", "+", "dt", ".", "timedelta", "(", "days", "=", "6", ")", "prev_year_num_weeks", "=", "(", "(", "year_start", "-", "prev_year_start", ")", ".", "days", ")", "//", "7", "year_num_weeks", "=", "(", "(", "next_year_start", "-", "year_start", ")", ".", "days", ")", "//", "7", "return", "(", "first_day", ",", "last_day", ",", "prev_year_num_weeks", ",", "year_num_weeks", ")" ]
Give all the ssweek info we need from one calculation
[ "Give", "all", "the", "ssweek", "info", "we", "need", "from", "one", "calculation" ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/weeks.py#L78-L87
6,503
linuxsoftware/ls.joyous
ls/joyous/utils/weeks.py
_gregorian_to_ssweek
def _gregorian_to_ssweek(date_value): "Sundaystarting-week year, week and day for the given Gregorian calendar date" yearStart = _ssweek_year_start(date_value.year) weekNum = ((date_value - yearStart).days) // 7 + 1 dayOfWeek = date_value.weekday()+1 return (date_value.year, weekNum, dayOfWeek)
python
def _gregorian_to_ssweek(date_value): "Sundaystarting-week year, week and day for the given Gregorian calendar date" yearStart = _ssweek_year_start(date_value.year) weekNum = ((date_value - yearStart).days) // 7 + 1 dayOfWeek = date_value.weekday()+1 return (date_value.year, weekNum, dayOfWeek)
[ "def", "_gregorian_to_ssweek", "(", "date_value", ")", ":", "yearStart", "=", "_ssweek_year_start", "(", "date_value", ".", "year", ")", "weekNum", "=", "(", "(", "date_value", "-", "yearStart", ")", ".", "days", ")", "//", "7", "+", "1", "dayOfWeek", "=", "date_value", ".", "weekday", "(", ")", "+", "1", "return", "(", "date_value", ".", "year", ",", "weekNum", ",", "dayOfWeek", ")" ]
Sundaystarting-week year, week and day for the given Gregorian calendar date
[ "Sundaystarting", "-", "week", "year", "week", "and", "day", "for", "the", "given", "Gregorian", "calendar", "date" ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/weeks.py#L89-L94
6,504
linuxsoftware/ls.joyous
ls/joyous/utils/weeks.py
_ssweek_of_month
def _ssweek_of_month(date_value): "0-starting index which Sundaystarting-week in the month this date is" weekday_of_first = (date_value.replace(day=1).weekday() + 1) % 7 return (date_value.day + weekday_of_first - 1) // 7
python
def _ssweek_of_month(date_value): "0-starting index which Sundaystarting-week in the month this date is" weekday_of_first = (date_value.replace(day=1).weekday() + 1) % 7 return (date_value.day + weekday_of_first - 1) // 7
[ "def", "_ssweek_of_month", "(", "date_value", ")", ":", "weekday_of_first", "=", "(", "date_value", ".", "replace", "(", "day", "=", "1", ")", ".", "weekday", "(", ")", "+", "1", ")", "%", "7", "return", "(", "date_value", ".", "day", "+", "weekday_of_first", "-", "1", ")", "//", "7" ]
0-starting index which Sundaystarting-week in the month this date is
[ "0", "-", "starting", "index", "which", "Sundaystarting", "-", "week", "in", "the", "month", "this", "date", "is" ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/weeks.py#L96-L99
6,505
linuxsoftware/ls.joyous
ls/joyous/utils/recurrence.py
Recurrence.byweekday
def byweekday(self): """ The weekdays where the recurrence will be applied. In RFC5545 this is called BYDAY, but is renamed by dateutil to avoid ambiguity. """ retval = [] if self.rule._byweekday: retval += [Weekday(day) for day in self.rule._byweekday] if self.rule._bynweekday: retval += [Weekday(day, n) for day, n in self.rule._bynweekday] return retval
python
def byweekday(self): """ The weekdays where the recurrence will be applied. In RFC5545 this is called BYDAY, but is renamed by dateutil to avoid ambiguity. """ retval = [] if self.rule._byweekday: retval += [Weekday(day) for day in self.rule._byweekday] if self.rule._bynweekday: retval += [Weekday(day, n) for day, n in self.rule._bynweekday] return retval
[ "def", "byweekday", "(", "self", ")", ":", "retval", "=", "[", "]", "if", "self", ".", "rule", ".", "_byweekday", ":", "retval", "+=", "[", "Weekday", "(", "day", ")", "for", "day", "in", "self", ".", "rule", ".", "_byweekday", "]", "if", "self", ".", "rule", ".", "_bynweekday", ":", "retval", "+=", "[", "Weekday", "(", "day", ",", "n", ")", "for", "day", ",", "n", "in", "self", ".", "rule", ".", "_bynweekday", "]", "return", "retval" ]
The weekdays where the recurrence will be applied. In RFC5545 this is called BYDAY, but is renamed by dateutil to avoid ambiguity.
[ "The", "weekdays", "where", "the", "recurrence", "will", "be", "applied", ".", "In", "RFC5545", "this", "is", "called", "BYDAY", "but", "is", "renamed", "by", "dateutil", "to", "avoid", "ambiguity", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/recurrence.py#L151-L161
6,506
linuxsoftware/ls.joyous
ls/joyous/utils/recurrence.py
Recurrence.bymonthday
def bymonthday(self): """ The month days where the recurrence will be applied. """ retval = [] if self.rule._bymonthday: retval += self.rule._bymonthday if self.rule._bynmonthday: retval += self.rule._bynmonthday return retval
python
def bymonthday(self): """ The month days where the recurrence will be applied. """ retval = [] if self.rule._bymonthday: retval += self.rule._bymonthday if self.rule._bynmonthday: retval += self.rule._bynmonthday return retval
[ "def", "bymonthday", "(", "self", ")", ":", "retval", "=", "[", "]", "if", "self", ".", "rule", ".", "_bymonthday", ":", "retval", "+=", "self", ".", "rule", ".", "_bymonthday", "if", "self", ".", "rule", ".", "_bynmonthday", ":", "retval", "+=", "self", ".", "rule", ".", "_bynmonthday", "return", "retval" ]
The month days where the recurrence will be applied.
[ "The", "month", "days", "where", "the", "recurrence", "will", "be", "applied", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/recurrence.py#L164-L173
6,507
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage.routeDefault
def routeDefault(self, request, year=None): """Route a request to the default calendar view.""" eventsView = request.GET.get('view', self.default_view) if eventsView in ("L", "list"): return self.serveUpcoming(request) elif eventsView in ("W", "weekly"): return self.serveWeek(request, year) else: return self.serveMonth(request, year)
python
def routeDefault(self, request, year=None): """Route a request to the default calendar view.""" eventsView = request.GET.get('view', self.default_view) if eventsView in ("L", "list"): return self.serveUpcoming(request) elif eventsView in ("W", "weekly"): return self.serveWeek(request, year) else: return self.serveMonth(request, year)
[ "def", "routeDefault", "(", "self", ",", "request", ",", "year", "=", "None", ")", ":", "eventsView", "=", "request", ".", "GET", ".", "get", "(", "'view'", ",", "self", ".", "default_view", ")", "if", "eventsView", "in", "(", "\"L\"", ",", "\"list\"", ")", ":", "return", "self", ".", "serveUpcoming", "(", "request", ")", "elif", "eventsView", "in", "(", "\"W\"", ",", "\"weekly\"", ")", ":", "return", "self", ".", "serveWeek", "(", "request", ",", "year", ")", "else", ":", "return", "self", ".", "serveMonth", "(", "request", ",", "year", ")" ]
Route a request to the default calendar view.
[ "Route", "a", "request", "to", "the", "default", "calendar", "view", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L148-L156
6,508
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage.routeByMonthAbbr
def routeByMonthAbbr(self, request, year, monthAbbr): """Route a request with a month abbreviation to the monthly view.""" month = (DatePictures['Mon'].index(monthAbbr.lower()) // 4) + 1 return self.serveMonth(request, year, month)
python
def routeByMonthAbbr(self, request, year, monthAbbr): """Route a request with a month abbreviation to the monthly view.""" month = (DatePictures['Mon'].index(monthAbbr.lower()) // 4) + 1 return self.serveMonth(request, year, month)
[ "def", "routeByMonthAbbr", "(", "self", ",", "request", ",", "year", ",", "monthAbbr", ")", ":", "month", "=", "(", "DatePictures", "[", "'Mon'", "]", ".", "index", "(", "monthAbbr", ".", "lower", "(", ")", ")", "//", "4", ")", "+", "1", "return", "self", ".", "serveMonth", "(", "request", ",", "year", ",", "month", ")" ]
Route a request with a month abbreviation to the monthly view.
[ "Route", "a", "request", "with", "a", "month", "abbreviation", "to", "the", "monthly", "view", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L159-L162
6,509
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage.serveMonth
def serveMonth(self, request, year=None, month=None): """Monthly calendar view.""" myurl = self.get_url(request) def myUrl(urlYear, urlMonth): if 1900 <= urlYear <= 2099: return myurl + self.reverse_subpage('serveMonth', args=[urlYear, urlMonth]) today = timezone.localdate() if year is None: year = today.year if month is None: month = today.month year = int(year) month = int(month) if year == today.year and month == today.month: weekNum = gregorian_to_week_date(today)[1] else: weekNum = gregorian_to_week_date(dt.date(year, month, 7))[1] weeklyUrl = myurl + self.reverse_subpage('serveWeek', args=[year, weekNum]) listUrl = myurl + self.reverse_subpage('serveUpcoming') prevMonth = month - 1 prevMonthYear = year if prevMonth == 0: prevMonth = 12 prevMonthYear -= 1 nextMonth = month + 1 nextMonthYear = year if nextMonth == 13: nextMonth = 1 nextMonthYear += 1 # TODO Consider changing to a TemplateResponse # https://stackoverflow.com/questions/38838601 return render(request, "joyous/calendar_month.html", {'self': self, 'page': self, 'version': __version__, 'year': year, 'month': month, 'today': today, 'yesterday': today - dt.timedelta(1), 'lastweek': today - dt.timedelta(7), 'prevMonthUrl': myUrl(prevMonthYear, prevMonth), 'nextMonthUrl': myUrl(nextMonthYear, nextMonth), 'prevYearUrl': myUrl(year - 1, month), 'nextYearUrl': myUrl(year + 1, month), 'weeklyUrl': weeklyUrl, 'listUrl': listUrl, 'thisMonthUrl': myUrl(today.year, today.month), 'monthName': MONTH_NAMES[month], 'weekdayAbbr': weekday_abbr, 'events': self._getEventsByWeek(request, year, month)})
python
def serveMonth(self, request, year=None, month=None): """Monthly calendar view.""" myurl = self.get_url(request) def myUrl(urlYear, urlMonth): if 1900 <= urlYear <= 2099: return myurl + self.reverse_subpage('serveMonth', args=[urlYear, urlMonth]) today = timezone.localdate() if year is None: year = today.year if month is None: month = today.month year = int(year) month = int(month) if year == today.year and month == today.month: weekNum = gregorian_to_week_date(today)[1] else: weekNum = gregorian_to_week_date(dt.date(year, month, 7))[1] weeklyUrl = myurl + self.reverse_subpage('serveWeek', args=[year, weekNum]) listUrl = myurl + self.reverse_subpage('serveUpcoming') prevMonth = month - 1 prevMonthYear = year if prevMonth == 0: prevMonth = 12 prevMonthYear -= 1 nextMonth = month + 1 nextMonthYear = year if nextMonth == 13: nextMonth = 1 nextMonthYear += 1 # TODO Consider changing to a TemplateResponse # https://stackoverflow.com/questions/38838601 return render(request, "joyous/calendar_month.html", {'self': self, 'page': self, 'version': __version__, 'year': year, 'month': month, 'today': today, 'yesterday': today - dt.timedelta(1), 'lastweek': today - dt.timedelta(7), 'prevMonthUrl': myUrl(prevMonthYear, prevMonth), 'nextMonthUrl': myUrl(nextMonthYear, nextMonth), 'prevYearUrl': myUrl(year - 1, month), 'nextYearUrl': myUrl(year + 1, month), 'weeklyUrl': weeklyUrl, 'listUrl': listUrl, 'thisMonthUrl': myUrl(today.year, today.month), 'monthName': MONTH_NAMES[month], 'weekdayAbbr': weekday_abbr, 'events': self._getEventsByWeek(request, year, month)})
[ "def", "serveMonth", "(", "self", ",", "request", ",", "year", "=", "None", ",", "month", "=", "None", ")", ":", "myurl", "=", "self", ".", "get_url", "(", "request", ")", "def", "myUrl", "(", "urlYear", ",", "urlMonth", ")", ":", "if", "1900", "<=", "urlYear", "<=", "2099", ":", "return", "myurl", "+", "self", ".", "reverse_subpage", "(", "'serveMonth'", ",", "args", "=", "[", "urlYear", ",", "urlMonth", "]", ")", "today", "=", "timezone", ".", "localdate", "(", ")", "if", "year", "is", "None", ":", "year", "=", "today", ".", "year", "if", "month", "is", "None", ":", "month", "=", "today", ".", "month", "year", "=", "int", "(", "year", ")", "month", "=", "int", "(", "month", ")", "if", "year", "==", "today", ".", "year", "and", "month", "==", "today", ".", "month", ":", "weekNum", "=", "gregorian_to_week_date", "(", "today", ")", "[", "1", "]", "else", ":", "weekNum", "=", "gregorian_to_week_date", "(", "dt", ".", "date", "(", "year", ",", "month", ",", "7", ")", ")", "[", "1", "]", "weeklyUrl", "=", "myurl", "+", "self", ".", "reverse_subpage", "(", "'serveWeek'", ",", "args", "=", "[", "year", ",", "weekNum", "]", ")", "listUrl", "=", "myurl", "+", "self", ".", "reverse_subpage", "(", "'serveUpcoming'", ")", "prevMonth", "=", "month", "-", "1", "prevMonthYear", "=", "year", "if", "prevMonth", "==", "0", ":", "prevMonth", "=", "12", "prevMonthYear", "-=", "1", "nextMonth", "=", "month", "+", "1", "nextMonthYear", "=", "year", "if", "nextMonth", "==", "13", ":", "nextMonth", "=", "1", "nextMonthYear", "+=", "1", "# TODO Consider changing to a TemplateResponse", "# https://stackoverflow.com/questions/38838601", "return", "render", "(", "request", ",", "\"joyous/calendar_month.html\"", ",", "{", "'self'", ":", "self", ",", "'page'", ":", "self", ",", "'version'", ":", "__version__", ",", "'year'", ":", "year", ",", "'month'", ":", "month", ",", "'today'", ":", "today", ",", "'yesterday'", ":", "today", "-", "dt", ".", "timedelta", "(", "1", ")", ",", "'lastweek'", ":", "today", "-", "dt", ".", "timedelta", "(", "7", ")", ",", "'prevMonthUrl'", ":", "myUrl", "(", "prevMonthYear", ",", "prevMonth", ")", ",", "'nextMonthUrl'", ":", "myUrl", "(", "nextMonthYear", ",", "nextMonth", ")", ",", "'prevYearUrl'", ":", "myUrl", "(", "year", "-", "1", ",", "month", ")", ",", "'nextYearUrl'", ":", "myUrl", "(", "year", "+", "1", ",", "month", ")", ",", "'weeklyUrl'", ":", "weeklyUrl", ",", "'listUrl'", ":", "listUrl", ",", "'thisMonthUrl'", ":", "myUrl", "(", "today", ".", "year", ",", "today", ".", "month", ")", ",", "'monthName'", ":", "MONTH_NAMES", "[", "month", "]", ",", "'weekdayAbbr'", ":", "weekday_abbr", ",", "'events'", ":", "self", ".", "_getEventsByWeek", "(", "request", ",", "year", ",", "month", ")", "}", ")" ]
Monthly calendar view.
[ "Monthly", "calendar", "view", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L166-L219
6,510
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage.serveWeek
def serveWeek(self, request, year=None, week=None): """Weekly calendar view.""" myurl = self.get_url(request) def myUrl(urlYear, urlWeek): if (urlYear < 1900 or urlYear > 2099 or urlYear == 2099 and urlWeek == 53): return None if urlWeek == 53 and num_weeks_in_year(urlYear) == 52: urlWeek = 52 return myurl + self.reverse_subpage('serveWeek', args=[urlYear, urlWeek]) today = timezone.localdate() thisYear, thisWeekNum, dow = gregorian_to_week_date(today) if year is None: year = thisYear if week is None: week = thisWeekNum year = int(year) week = int(week) firstDay, lastDay, prevYearNumWeeks, yearNumWeeks = week_info(year, week) if week == 53 and yearNumWeeks == 52: raise Http404("Only 52 weeks in {}".format(year)) eventsInWeek = self._getEventsByDay(request, firstDay, lastDay) if firstDay.year >= 1900: monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[firstDay.year, firstDay.month]) else: monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[1900, 1]) listUrl = myurl + self.reverse_subpage('serveUpcoming') prevWeek = week - 1 prevWeekYear = year if prevWeek == 0: prevWeek = prevYearNumWeeks prevWeekYear -= 1 nextWeek = week + 1 nextWeekYear = year if nextWeek > yearNumWeeks: nextWeek = 1 nextWeekYear += 1 # TODO Consider changing to a TemplateResponse # https://stackoverflow.com/questions/38838601 return render(request, "joyous/calendar_week.html", {'self': self, 'page': self, 'version': __version__, 'year': year, 'week': week, 'today': today, 'yesterday': today - dt.timedelta(1), 'prevWeekUrl': myUrl(prevWeekYear, prevWeek), 'nextWeekUrl': myUrl(nextWeekYear, nextWeek), 'prevYearUrl': myUrl(year - 1, week), 'nextYearUrl': myUrl(year + 1, week), 'thisWeekUrl': myUrl(thisYear, thisWeekNum), 'monthlyUrl': monthlyUrl, 'listUrl': listUrl, 'weekName': _("Week {weekNum}").format(weekNum=week), 'weekdayAbbr': weekday_abbr, 'events': [eventsInWeek]})
python
def serveWeek(self, request, year=None, week=None): """Weekly calendar view.""" myurl = self.get_url(request) def myUrl(urlYear, urlWeek): if (urlYear < 1900 or urlYear > 2099 or urlYear == 2099 and urlWeek == 53): return None if urlWeek == 53 and num_weeks_in_year(urlYear) == 52: urlWeek = 52 return myurl + self.reverse_subpage('serveWeek', args=[urlYear, urlWeek]) today = timezone.localdate() thisYear, thisWeekNum, dow = gregorian_to_week_date(today) if year is None: year = thisYear if week is None: week = thisWeekNum year = int(year) week = int(week) firstDay, lastDay, prevYearNumWeeks, yearNumWeeks = week_info(year, week) if week == 53 and yearNumWeeks == 52: raise Http404("Only 52 weeks in {}".format(year)) eventsInWeek = self._getEventsByDay(request, firstDay, lastDay) if firstDay.year >= 1900: monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[firstDay.year, firstDay.month]) else: monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[1900, 1]) listUrl = myurl + self.reverse_subpage('serveUpcoming') prevWeek = week - 1 prevWeekYear = year if prevWeek == 0: prevWeek = prevYearNumWeeks prevWeekYear -= 1 nextWeek = week + 1 nextWeekYear = year if nextWeek > yearNumWeeks: nextWeek = 1 nextWeekYear += 1 # TODO Consider changing to a TemplateResponse # https://stackoverflow.com/questions/38838601 return render(request, "joyous/calendar_week.html", {'self': self, 'page': self, 'version': __version__, 'year': year, 'week': week, 'today': today, 'yesterday': today - dt.timedelta(1), 'prevWeekUrl': myUrl(prevWeekYear, prevWeek), 'nextWeekUrl': myUrl(nextWeekYear, nextWeek), 'prevYearUrl': myUrl(year - 1, week), 'nextYearUrl': myUrl(year + 1, week), 'thisWeekUrl': myUrl(thisYear, thisWeekNum), 'monthlyUrl': monthlyUrl, 'listUrl': listUrl, 'weekName': _("Week {weekNum}").format(weekNum=week), 'weekdayAbbr': weekday_abbr, 'events': [eventsInWeek]})
[ "def", "serveWeek", "(", "self", ",", "request", ",", "year", "=", "None", ",", "week", "=", "None", ")", ":", "myurl", "=", "self", ".", "get_url", "(", "request", ")", "def", "myUrl", "(", "urlYear", ",", "urlWeek", ")", ":", "if", "(", "urlYear", "<", "1900", "or", "urlYear", ">", "2099", "or", "urlYear", "==", "2099", "and", "urlWeek", "==", "53", ")", ":", "return", "None", "if", "urlWeek", "==", "53", "and", "num_weeks_in_year", "(", "urlYear", ")", "==", "52", ":", "urlWeek", "=", "52", "return", "myurl", "+", "self", ".", "reverse_subpage", "(", "'serveWeek'", ",", "args", "=", "[", "urlYear", ",", "urlWeek", "]", ")", "today", "=", "timezone", ".", "localdate", "(", ")", "thisYear", ",", "thisWeekNum", ",", "dow", "=", "gregorian_to_week_date", "(", "today", ")", "if", "year", "is", "None", ":", "year", "=", "thisYear", "if", "week", "is", "None", ":", "week", "=", "thisWeekNum", "year", "=", "int", "(", "year", ")", "week", "=", "int", "(", "week", ")", "firstDay", ",", "lastDay", ",", "prevYearNumWeeks", ",", "yearNumWeeks", "=", "week_info", "(", "year", ",", "week", ")", "if", "week", "==", "53", "and", "yearNumWeeks", "==", "52", ":", "raise", "Http404", "(", "\"Only 52 weeks in {}\"", ".", "format", "(", "year", ")", ")", "eventsInWeek", "=", "self", ".", "_getEventsByDay", "(", "request", ",", "firstDay", ",", "lastDay", ")", "if", "firstDay", ".", "year", ">=", "1900", ":", "monthlyUrl", "=", "myurl", "+", "self", ".", "reverse_subpage", "(", "'serveMonth'", ",", "args", "=", "[", "firstDay", ".", "year", ",", "firstDay", ".", "month", "]", ")", "else", ":", "monthlyUrl", "=", "myurl", "+", "self", ".", "reverse_subpage", "(", "'serveMonth'", ",", "args", "=", "[", "1900", ",", "1", "]", ")", "listUrl", "=", "myurl", "+", "self", ".", "reverse_subpage", "(", "'serveUpcoming'", ")", "prevWeek", "=", "week", "-", "1", "prevWeekYear", "=", "year", "if", "prevWeek", "==", "0", ":", "prevWeek", "=", "prevYearNumWeeks", "prevWeekYear", "-=", "1", "nextWeek", "=", "week", "+", "1", "nextWeekYear", "=", "year", "if", "nextWeek", ">", "yearNumWeeks", ":", "nextWeek", "=", "1", "nextWeekYear", "+=", "1", "# TODO Consider changing to a TemplateResponse", "# https://stackoverflow.com/questions/38838601", "return", "render", "(", "request", ",", "\"joyous/calendar_week.html\"", ",", "{", "'self'", ":", "self", ",", "'page'", ":", "self", ",", "'version'", ":", "__version__", ",", "'year'", ":", "year", ",", "'week'", ":", "week", ",", "'today'", ":", "today", ",", "'yesterday'", ":", "today", "-", "dt", ".", "timedelta", "(", "1", ")", ",", "'prevWeekUrl'", ":", "myUrl", "(", "prevWeekYear", ",", "prevWeek", ")", ",", "'nextWeekUrl'", ":", "myUrl", "(", "nextWeekYear", ",", "nextWeek", ")", ",", "'prevYearUrl'", ":", "myUrl", "(", "year", "-", "1", ",", "week", ")", ",", "'nextYearUrl'", ":", "myUrl", "(", "year", "+", "1", ",", "week", ")", ",", "'thisWeekUrl'", ":", "myUrl", "(", "thisYear", ",", "thisWeekNum", ")", ",", "'monthlyUrl'", ":", "monthlyUrl", ",", "'listUrl'", ":", "listUrl", ",", "'weekName'", ":", "_", "(", "\"Week {weekNum}\"", ")", ".", "format", "(", "weekNum", "=", "week", ")", ",", "'weekdayAbbr'", ":", "weekday_abbr", ",", "'events'", ":", "[", "eventsInWeek", "]", "}", ")" ]
Weekly calendar view.
[ "Weekly", "calendar", "view", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L223-L285
6,511
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage.serveDay
def serveDay(self, request, year=None, month=None, dom=None): """The events of the day list view.""" myurl = self.get_url(request) today = timezone.localdate() if year is None: year = today.year if month is None: month = today.month if dom is None: dom = today.day year = int(year) month = int(month) dom = int(dom) day = dt.date(year, month, dom) eventsOnDay = self._getEventsOnDay(request, day) if len(eventsOnDay.all_events) == 1: event = eventsOnDay.all_events[0].page return redirect(event.get_url(request)) monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[year, month]) weekNum = gregorian_to_week_date(today)[1] weeklyUrl = myurl + self.reverse_subpage('serveWeek', args=[year, weekNum]) listUrl = myurl + self.reverse_subpage('serveUpcoming') # TODO Consider changing to a TemplateResponse # https://stackoverflow.com/questions/38838601 return render(request, "joyous/calendar_list_day.html", {'self': self, 'page': self, 'version': __version__, 'year': year, 'month': month, 'dom': dom, 'day': day, 'monthlyUrl': monthlyUrl, 'weeklyUrl': weeklyUrl, 'listUrl': listUrl, 'monthName': MONTH_NAMES[month], 'weekdayName': WEEKDAY_NAMES[day.weekday()], 'events': eventsOnDay})
python
def serveDay(self, request, year=None, month=None, dom=None): """The events of the day list view.""" myurl = self.get_url(request) today = timezone.localdate() if year is None: year = today.year if month is None: month = today.month if dom is None: dom = today.day year = int(year) month = int(month) dom = int(dom) day = dt.date(year, month, dom) eventsOnDay = self._getEventsOnDay(request, day) if len(eventsOnDay.all_events) == 1: event = eventsOnDay.all_events[0].page return redirect(event.get_url(request)) monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[year, month]) weekNum = gregorian_to_week_date(today)[1] weeklyUrl = myurl + self.reverse_subpage('serveWeek', args=[year, weekNum]) listUrl = myurl + self.reverse_subpage('serveUpcoming') # TODO Consider changing to a TemplateResponse # https://stackoverflow.com/questions/38838601 return render(request, "joyous/calendar_list_day.html", {'self': self, 'page': self, 'version': __version__, 'year': year, 'month': month, 'dom': dom, 'day': day, 'monthlyUrl': monthlyUrl, 'weeklyUrl': weeklyUrl, 'listUrl': listUrl, 'monthName': MONTH_NAMES[month], 'weekdayName': WEEKDAY_NAMES[day.weekday()], 'events': eventsOnDay})
[ "def", "serveDay", "(", "self", ",", "request", ",", "year", "=", "None", ",", "month", "=", "None", ",", "dom", "=", "None", ")", ":", "myurl", "=", "self", ".", "get_url", "(", "request", ")", "today", "=", "timezone", ".", "localdate", "(", ")", "if", "year", "is", "None", ":", "year", "=", "today", ".", "year", "if", "month", "is", "None", ":", "month", "=", "today", ".", "month", "if", "dom", "is", "None", ":", "dom", "=", "today", ".", "day", "year", "=", "int", "(", "year", ")", "month", "=", "int", "(", "month", ")", "dom", "=", "int", "(", "dom", ")", "day", "=", "dt", ".", "date", "(", "year", ",", "month", ",", "dom", ")", "eventsOnDay", "=", "self", ".", "_getEventsOnDay", "(", "request", ",", "day", ")", "if", "len", "(", "eventsOnDay", ".", "all_events", ")", "==", "1", ":", "event", "=", "eventsOnDay", ".", "all_events", "[", "0", "]", ".", "page", "return", "redirect", "(", "event", ".", "get_url", "(", "request", ")", ")", "monthlyUrl", "=", "myurl", "+", "self", ".", "reverse_subpage", "(", "'serveMonth'", ",", "args", "=", "[", "year", ",", "month", "]", ")", "weekNum", "=", "gregorian_to_week_date", "(", "today", ")", "[", "1", "]", "weeklyUrl", "=", "myurl", "+", "self", ".", "reverse_subpage", "(", "'serveWeek'", ",", "args", "=", "[", "year", ",", "weekNum", "]", ")", "listUrl", "=", "myurl", "+", "self", ".", "reverse_subpage", "(", "'serveUpcoming'", ")", "# TODO Consider changing to a TemplateResponse", "# https://stackoverflow.com/questions/38838601", "return", "render", "(", "request", ",", "\"joyous/calendar_list_day.html\"", ",", "{", "'self'", ":", "self", ",", "'page'", ":", "self", ",", "'version'", ":", "__version__", ",", "'year'", ":", "year", ",", "'month'", ":", "month", ",", "'dom'", ":", "dom", ",", "'day'", ":", "day", ",", "'monthlyUrl'", ":", "monthlyUrl", ",", "'weeklyUrl'", ":", "weeklyUrl", ",", "'listUrl'", ":", "listUrl", ",", "'monthName'", ":", "MONTH_NAMES", "[", "month", "]", ",", "'weekdayName'", ":", "WEEKDAY_NAMES", "[", "day", ".", "weekday", "(", ")", "]", ",", "'events'", ":", "eventsOnDay", "}", ")" ]
The events of the day list view.
[ "The", "events", "of", "the", "day", "list", "view", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L289-L328
6,512
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage.serveUpcoming
def serveUpcoming(self, request): """Upcoming events list view.""" myurl = self.get_url(request) today = timezone.localdate() monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[today.year, today.month]) weekNum = gregorian_to_week_date(today)[1] weeklyUrl = myurl + self.reverse_subpage('serveWeek', args=[today.year, weekNum]) listUrl = myurl + self.reverse_subpage('servePast') upcomingEvents = self._getUpcomingEvents(request) paginator = Paginator(upcomingEvents, self.EventsPerPage) try: eventsPage = paginator.page(request.GET.get('page')) except PageNotAnInteger: eventsPage = paginator.page(1) except EmptyPage: eventsPage = paginator.page(paginator.num_pages) # TODO Consider changing to a TemplateResponse # https://stackoverflow.com/questions/38838601 return render(request, "joyous/calendar_list_upcoming.html", {'self': self, 'page': self, 'version': __version__, 'today': today, 'weeklyUrl': weeklyUrl, 'monthlyUrl': monthlyUrl, 'listUrl': listUrl, 'events': eventsPage})
python
def serveUpcoming(self, request): """Upcoming events list view.""" myurl = self.get_url(request) today = timezone.localdate() monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[today.year, today.month]) weekNum = gregorian_to_week_date(today)[1] weeklyUrl = myurl + self.reverse_subpage('serveWeek', args=[today.year, weekNum]) listUrl = myurl + self.reverse_subpage('servePast') upcomingEvents = self._getUpcomingEvents(request) paginator = Paginator(upcomingEvents, self.EventsPerPage) try: eventsPage = paginator.page(request.GET.get('page')) except PageNotAnInteger: eventsPage = paginator.page(1) except EmptyPage: eventsPage = paginator.page(paginator.num_pages) # TODO Consider changing to a TemplateResponse # https://stackoverflow.com/questions/38838601 return render(request, "joyous/calendar_list_upcoming.html", {'self': self, 'page': self, 'version': __version__, 'today': today, 'weeklyUrl': weeklyUrl, 'monthlyUrl': monthlyUrl, 'listUrl': listUrl, 'events': eventsPage})
[ "def", "serveUpcoming", "(", "self", ",", "request", ")", ":", "myurl", "=", "self", ".", "get_url", "(", "request", ")", "today", "=", "timezone", ".", "localdate", "(", ")", "monthlyUrl", "=", "myurl", "+", "self", ".", "reverse_subpage", "(", "'serveMonth'", ",", "args", "=", "[", "today", ".", "year", ",", "today", ".", "month", "]", ")", "weekNum", "=", "gregorian_to_week_date", "(", "today", ")", "[", "1", "]", "weeklyUrl", "=", "myurl", "+", "self", ".", "reverse_subpage", "(", "'serveWeek'", ",", "args", "=", "[", "today", ".", "year", ",", "weekNum", "]", ")", "listUrl", "=", "myurl", "+", "self", ".", "reverse_subpage", "(", "'servePast'", ")", "upcomingEvents", "=", "self", ".", "_getUpcomingEvents", "(", "request", ")", "paginator", "=", "Paginator", "(", "upcomingEvents", ",", "self", ".", "EventsPerPage", ")", "try", ":", "eventsPage", "=", "paginator", ".", "page", "(", "request", ".", "GET", ".", "get", "(", "'page'", ")", ")", "except", "PageNotAnInteger", ":", "eventsPage", "=", "paginator", ".", "page", "(", "1", ")", "except", "EmptyPage", ":", "eventsPage", "=", "paginator", ".", "page", "(", "paginator", ".", "num_pages", ")", "# TODO Consider changing to a TemplateResponse", "# https://stackoverflow.com/questions/38838601", "return", "render", "(", "request", ",", "\"joyous/calendar_list_upcoming.html\"", ",", "{", "'self'", ":", "self", ",", "'page'", ":", "self", ",", "'version'", ":", "__version__", ",", "'today'", ":", "today", ",", "'weeklyUrl'", ":", "weeklyUrl", ",", "'monthlyUrl'", ":", "monthlyUrl", ",", "'listUrl'", ":", "listUrl", ",", "'events'", ":", "eventsPage", "}", ")" ]
Upcoming events list view.
[ "Upcoming", "events", "list", "view", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L331-L360
6,513
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage.serveMiniMonth
def serveMiniMonth(self, request, year=None, month=None): """Serve data for the MiniMonth template tag.""" if not request.is_ajax(): raise Http404("/mini/ is for ajax requests only") today = timezone.localdate() if year is None: year = today.year if month is None: month = today.month year = int(year) month = int(month) # TODO Consider changing to a TemplateResponse # https://stackoverflow.com/questions/38838601 return render(request, "joyous/includes/minicalendar.html", {'self': self, 'page': self, 'version': __version__, 'today': today, 'year': year, 'month': month, 'calendarUrl': self.get_url(request), 'monthName': MONTH_NAMES[month], 'weekdayInfo': zip(weekday_abbr, weekday_name), 'events': self._getEventsByWeek(request, year, month)})
python
def serveMiniMonth(self, request, year=None, month=None): """Serve data for the MiniMonth template tag.""" if not request.is_ajax(): raise Http404("/mini/ is for ajax requests only") today = timezone.localdate() if year is None: year = today.year if month is None: month = today.month year = int(year) month = int(month) # TODO Consider changing to a TemplateResponse # https://stackoverflow.com/questions/38838601 return render(request, "joyous/includes/minicalendar.html", {'self': self, 'page': self, 'version': __version__, 'today': today, 'year': year, 'month': month, 'calendarUrl': self.get_url(request), 'monthName': MONTH_NAMES[month], 'weekdayInfo': zip(weekday_abbr, weekday_name), 'events': self._getEventsByWeek(request, year, month)})
[ "def", "serveMiniMonth", "(", "self", ",", "request", ",", "year", "=", "None", ",", "month", "=", "None", ")", ":", "if", "not", "request", ".", "is_ajax", "(", ")", ":", "raise", "Http404", "(", "\"/mini/ is for ajax requests only\"", ")", "today", "=", "timezone", ".", "localdate", "(", ")", "if", "year", "is", "None", ":", "year", "=", "today", ".", "year", "if", "month", "is", "None", ":", "month", "=", "today", ".", "month", "year", "=", "int", "(", "year", ")", "month", "=", "int", "(", "month", ")", "# TODO Consider changing to a TemplateResponse", "# https://stackoverflow.com/questions/38838601", "return", "render", "(", "request", ",", "\"joyous/includes/minicalendar.html\"", ",", "{", "'self'", ":", "self", ",", "'page'", ":", "self", ",", "'version'", ":", "__version__", ",", "'today'", ":", "today", ",", "'year'", ":", "year", ",", "'month'", ":", "month", ",", "'calendarUrl'", ":", "self", ".", "get_url", "(", "request", ")", ",", "'monthName'", ":", "MONTH_NAMES", "[", "month", "]", ",", "'weekdayInfo'", ":", "zip", "(", "weekday_abbr", ",", "weekday_name", ")", ",", "'events'", ":", "self", ".", "_getEventsByWeek", "(", "request", ",", "year", ",", "month", ")", "}", ")" ]
Serve data for the MiniMonth template tag.
[ "Serve", "data", "for", "the", "MiniMonth", "template", "tag", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L395-L418
6,514
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage._allowAnotherAt
def _allowAnotherAt(cls, parent): """You can only create one of these pages per site.""" site = parent.get_site() if site is None: return False return not cls.peers().descendant_of(site.root_page).exists()
python
def _allowAnotherAt(cls, parent): """You can only create one of these pages per site.""" site = parent.get_site() if site is None: return False return not cls.peers().descendant_of(site.root_page).exists()
[ "def", "_allowAnotherAt", "(", "cls", ",", "parent", ")", ":", "site", "=", "parent", ".", "get_site", "(", ")", "if", "site", "is", "None", ":", "return", "False", "return", "not", "cls", ".", "peers", "(", ")", ".", "descendant_of", "(", "site", ".", "root_page", ")", ".", "exists", "(", ")" ]
You can only create one of these pages per site.
[ "You", "can", "only", "create", "one", "of", "these", "pages", "per", "site", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L425-L430
6,515
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage.peers
def peers(cls): """Return others of the same concrete type.""" contentType = ContentType.objects.get_for_model(cls) return cls.objects.filter(content_type=contentType)
python
def peers(cls): """Return others of the same concrete type.""" contentType = ContentType.objects.get_for_model(cls) return cls.objects.filter(content_type=contentType)
[ "def", "peers", "(", "cls", ")", ":", "contentType", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "cls", ")", "return", "cls", ".", "objects", ".", "filter", "(", "content_type", "=", "contentType", ")" ]
Return others of the same concrete type.
[ "Return", "others", "of", "the", "same", "concrete", "type", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L433-L436
6,516
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage._getEventsOnDay
def _getEventsOnDay(self, request, day): """Return all the events in this site for a given day.""" home = request.site.root_page return getAllEventsByDay(request, day, day, home=home)[0]
python
def _getEventsOnDay(self, request, day): """Return all the events in this site for a given day.""" home = request.site.root_page return getAllEventsByDay(request, day, day, home=home)[0]
[ "def", "_getEventsOnDay", "(", "self", ",", "request", ",", "day", ")", ":", "home", "=", "request", ".", "site", ".", "root_page", "return", "getAllEventsByDay", "(", "request", ",", "day", ",", "day", ",", "home", "=", "home", ")", "[", "0", "]" ]
Return all the events in this site for a given day.
[ "Return", "all", "the", "events", "in", "this", "site", "for", "a", "given", "day", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L438-L441
6,517
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage._getEventsByDay
def _getEventsByDay(self, request, firstDay, lastDay): """ Return the events in this site for the dates given, grouped by day. """ home = request.site.root_page return getAllEventsByDay(request, firstDay, lastDay, home=home)
python
def _getEventsByDay(self, request, firstDay, lastDay): """ Return the events in this site for the dates given, grouped by day. """ home = request.site.root_page return getAllEventsByDay(request, firstDay, lastDay, home=home)
[ "def", "_getEventsByDay", "(", "self", ",", "request", ",", "firstDay", ",", "lastDay", ")", ":", "home", "=", "request", ".", "site", ".", "root_page", "return", "getAllEventsByDay", "(", "request", ",", "firstDay", ",", "lastDay", ",", "home", "=", "home", ")" ]
Return the events in this site for the dates given, grouped by day.
[ "Return", "the", "events", "in", "this", "site", "for", "the", "dates", "given", "grouped", "by", "day", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L443-L448
6,518
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage._getEventsByWeek
def _getEventsByWeek(self, request, year, month): """ Return the events in this site for the given month grouped by week. """ home = request.site.root_page return getAllEventsByWeek(request, year, month, home=home)
python
def _getEventsByWeek(self, request, year, month): """ Return the events in this site for the given month grouped by week. """ home = request.site.root_page return getAllEventsByWeek(request, year, month, home=home)
[ "def", "_getEventsByWeek", "(", "self", ",", "request", ",", "year", ",", "month", ")", ":", "home", "=", "request", ".", "site", ".", "root_page", "return", "getAllEventsByWeek", "(", "request", ",", "year", ",", "month", ",", "home", "=", "home", ")" ]
Return the events in this site for the given month grouped by week.
[ "Return", "the", "events", "in", "this", "site", "for", "the", "given", "month", "grouped", "by", "week", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L450-L455
6,519
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage._getUpcomingEvents
def _getUpcomingEvents(self, request): """Return the upcoming events in this site.""" home = request.site.root_page return getAllUpcomingEvents(request, home=home)
python
def _getUpcomingEvents(self, request): """Return the upcoming events in this site.""" home = request.site.root_page return getAllUpcomingEvents(request, home=home)
[ "def", "_getUpcomingEvents", "(", "self", ",", "request", ")", ":", "home", "=", "request", ".", "site", ".", "root_page", "return", "getAllUpcomingEvents", "(", "request", ",", "home", "=", "home", ")" ]
Return the upcoming events in this site.
[ "Return", "the", "upcoming", "events", "in", "this", "site", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L457-L460
6,520
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage._getPastEvents
def _getPastEvents(self, request): """Return the past events in this site.""" home = request.site.root_page return getAllPastEvents(request, home=home)
python
def _getPastEvents(self, request): """Return the past events in this site.""" home = request.site.root_page return getAllPastEvents(request, home=home)
[ "def", "_getPastEvents", "(", "self", ",", "request", ")", ":", "home", "=", "request", ".", "site", ".", "root_page", "return", "getAllPastEvents", "(", "request", ",", "home", "=", "home", ")" ]
Return the past events in this site.
[ "Return", "the", "past", "events", "in", "this", "site", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L462-L465
6,521
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage._getEventFromUid
def _getEventFromUid(self, request, uid): """Try and find an event with the given UID in this site.""" event = getEventFromUid(request, uid) # might raise ObjectDoesNotExist home = request.site.root_page if event.get_ancestors().filter(id=home.id).exists(): # only return event if it is in the same site return event
python
def _getEventFromUid(self, request, uid): """Try and find an event with the given UID in this site.""" event = getEventFromUid(request, uid) # might raise ObjectDoesNotExist home = request.site.root_page if event.get_ancestors().filter(id=home.id).exists(): # only return event if it is in the same site return event
[ "def", "_getEventFromUid", "(", "self", ",", "request", ",", "uid", ")", ":", "event", "=", "getEventFromUid", "(", "request", ",", "uid", ")", "# might raise ObjectDoesNotExist", "home", "=", "request", ".", "site", ".", "root_page", "if", "event", ".", "get_ancestors", "(", ")", ".", "filter", "(", "id", "=", "home", ".", "id", ")", ".", "exists", "(", ")", ":", "# only return event if it is in the same site", "return", "event" ]
Try and find an event with the given UID in this site.
[ "Try", "and", "find", "an", "event", "with", "the", "given", "UID", "in", "this", "site", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L467-L473
6,522
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
CalendarPage._getAllEvents
def _getAllEvents(self, request): """Return all the events in this site.""" home = request.site.root_page return getAllEvents(request, home=home)
python
def _getAllEvents(self, request): """Return all the events in this site.""" home = request.site.root_page return getAllEvents(request, home=home)
[ "def", "_getAllEvents", "(", "self", ",", "request", ")", ":", "home", "=", "request", ".", "site", ".", "root_page", "return", "getAllEvents", "(", "request", ",", "home", "=", "home", ")" ]
Return all the events in this site.
[ "Return", "all", "the", "events", "in", "this", "site", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L475-L478
6,523
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
SpecificCalendarPage._getEventsOnDay
def _getEventsOnDay(self, request, day): """Return my child events for a given day.""" return getAllEventsByDay(request, day, day, home=self)[0]
python
def _getEventsOnDay(self, request, day): """Return my child events for a given day.""" return getAllEventsByDay(request, day, day, home=self)[0]
[ "def", "_getEventsOnDay", "(", "self", ",", "request", ",", "day", ")", ":", "return", "getAllEventsByDay", "(", "request", ",", "day", ",", "day", ",", "home", "=", "self", ")", "[", "0", "]" ]
Return my child events for a given day.
[ "Return", "my", "child", "events", "for", "a", "given", "day", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L496-L498
6,524
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
SpecificCalendarPage._getEventsByDay
def _getEventsByDay(self, request, firstDay, lastDay): """ Return my child events for the dates given, grouped by day. """ return getAllEventsByDay(request, firstDay, lastDay, home=self)
python
def _getEventsByDay(self, request, firstDay, lastDay): """ Return my child events for the dates given, grouped by day. """ return getAllEventsByDay(request, firstDay, lastDay, home=self)
[ "def", "_getEventsByDay", "(", "self", ",", "request", ",", "firstDay", ",", "lastDay", ")", ":", "return", "getAllEventsByDay", "(", "request", ",", "firstDay", ",", "lastDay", ",", "home", "=", "self", ")" ]
Return my child events for the dates given, grouped by day.
[ "Return", "my", "child", "events", "for", "the", "dates", "given", "grouped", "by", "day", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L500-L504
6,525
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
SpecificCalendarPage._getEventsByWeek
def _getEventsByWeek(self, request, year, month): """Return my child events for the given month grouped by week.""" return getAllEventsByWeek(request, year, month, home=self)
python
def _getEventsByWeek(self, request, year, month): """Return my child events for the given month grouped by week.""" return getAllEventsByWeek(request, year, month, home=self)
[ "def", "_getEventsByWeek", "(", "self", ",", "request", ",", "year", ",", "month", ")", ":", "return", "getAllEventsByWeek", "(", "request", ",", "year", ",", "month", ",", "home", "=", "self", ")" ]
Return my child events for the given month grouped by week.
[ "Return", "my", "child", "events", "for", "the", "given", "month", "grouped", "by", "week", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L506-L508
6,526
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
SpecificCalendarPage._getEventFromUid
def _getEventFromUid(self, request, uid): """Try and find a child event with the given UID.""" event = getEventFromUid(request, uid) if event.get_ancestors().filter(id=self.id).exists(): # only return event if it is a descendant return event
python
def _getEventFromUid(self, request, uid): """Try and find a child event with the given UID.""" event = getEventFromUid(request, uid) if event.get_ancestors().filter(id=self.id).exists(): # only return event if it is a descendant return event
[ "def", "_getEventFromUid", "(", "self", ",", "request", ",", "uid", ")", ":", "event", "=", "getEventFromUid", "(", "request", ",", "uid", ")", "if", "event", ".", "get_ancestors", "(", ")", ".", "filter", "(", "id", "=", "self", ".", "id", ")", ".", "exists", "(", ")", ":", "# only return event if it is a descendant", "return", "event" ]
Try and find a child event with the given UID.
[ "Try", "and", "find", "a", "child", "event", "with", "the", "given", "UID", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L518-L523
6,527
linuxsoftware/ls.joyous
ls/joyous/templatetags/joyous_tags.py
events_this_week
def events_this_week(context): """ Displays a week's worth of events. Starts week with Monday, unless today is Sunday. """ request = context['request'] home = request.site.root_page cal = CalendarPage.objects.live().descendant_of(home).first() calUrl = cal.get_url(request) if cal else None calName = cal.title if cal else None today = dt.date.today() beginOrd = today.toordinal() if today.weekday() != 6: # Start week with Monday, unless today is Sunday beginOrd -= today.weekday() endOrd = beginOrd + 6 dateFrom = dt.date.fromordinal(beginOrd) dateTo = dt.date.fromordinal(endOrd) if cal: events = cal._getEventsByDay(request, dateFrom, dateTo) else: events = getAllEventsByDay(request, dateFrom, dateTo) return {'request': request, 'today': today, 'calendarUrl': calUrl, 'calendarName': calName, 'events': events }
python
def events_this_week(context): """ Displays a week's worth of events. Starts week with Monday, unless today is Sunday. """ request = context['request'] home = request.site.root_page cal = CalendarPage.objects.live().descendant_of(home).first() calUrl = cal.get_url(request) if cal else None calName = cal.title if cal else None today = dt.date.today() beginOrd = today.toordinal() if today.weekday() != 6: # Start week with Monday, unless today is Sunday beginOrd -= today.weekday() endOrd = beginOrd + 6 dateFrom = dt.date.fromordinal(beginOrd) dateTo = dt.date.fromordinal(endOrd) if cal: events = cal._getEventsByDay(request, dateFrom, dateTo) else: events = getAllEventsByDay(request, dateFrom, dateTo) return {'request': request, 'today': today, 'calendarUrl': calUrl, 'calendarName': calName, 'events': events }
[ "def", "events_this_week", "(", "context", ")", ":", "request", "=", "context", "[", "'request'", "]", "home", "=", "request", ".", "site", ".", "root_page", "cal", "=", "CalendarPage", ".", "objects", ".", "live", "(", ")", ".", "descendant_of", "(", "home", ")", ".", "first", "(", ")", "calUrl", "=", "cal", ".", "get_url", "(", "request", ")", "if", "cal", "else", "None", "calName", "=", "cal", ".", "title", "if", "cal", "else", "None", "today", "=", "dt", ".", "date", ".", "today", "(", ")", "beginOrd", "=", "today", ".", "toordinal", "(", ")", "if", "today", ".", "weekday", "(", ")", "!=", "6", ":", "# Start week with Monday, unless today is Sunday", "beginOrd", "-=", "today", ".", "weekday", "(", ")", "endOrd", "=", "beginOrd", "+", "6", "dateFrom", "=", "dt", ".", "date", ".", "fromordinal", "(", "beginOrd", ")", "dateTo", "=", "dt", ".", "date", ".", "fromordinal", "(", "endOrd", ")", "if", "cal", ":", "events", "=", "cal", ".", "_getEventsByDay", "(", "request", ",", "dateFrom", ",", "dateTo", ")", "else", ":", "events", "=", "getAllEventsByDay", "(", "request", ",", "dateFrom", ",", "dateTo", ")", "return", "{", "'request'", ":", "request", ",", "'today'", ":", "today", ",", "'calendarUrl'", ":", "calUrl", ",", "'calendarName'", ":", "calName", ",", "'events'", ":", "events", "}" ]
Displays a week's worth of events. Starts week with Monday, unless today is Sunday.
[ "Displays", "a", "week", "s", "worth", "of", "events", ".", "Starts", "week", "with", "Monday", "unless", "today", "is", "Sunday", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/templatetags/joyous_tags.py#L20-L45
6,528
linuxsoftware/ls.joyous
ls/joyous/templatetags/joyous_tags.py
minicalendar
def minicalendar(context): """ Displays a little ajax version of the calendar. """ today = dt.date.today() request = context['request'] home = request.site.root_page cal = CalendarPage.objects.live().descendant_of(home).first() calUrl = cal.get_url(request) if cal else None if cal: events = cal._getEventsByWeek(request, today.year, today.month) else: events = getAllEventsByWeek(request, today.year, today.month) return {'request': request, 'today': today, 'year': today.year, 'month': today.month, 'calendarUrl': calUrl, 'monthName': calendar.month_name[today.month], 'weekdayInfo': zip(weekday_abbr, weekday_name), 'events': events}
python
def minicalendar(context): """ Displays a little ajax version of the calendar. """ today = dt.date.today() request = context['request'] home = request.site.root_page cal = CalendarPage.objects.live().descendant_of(home).first() calUrl = cal.get_url(request) if cal else None if cal: events = cal._getEventsByWeek(request, today.year, today.month) else: events = getAllEventsByWeek(request, today.year, today.month) return {'request': request, 'today': today, 'year': today.year, 'month': today.month, 'calendarUrl': calUrl, 'monthName': calendar.month_name[today.month], 'weekdayInfo': zip(weekday_abbr, weekday_name), 'events': events}
[ "def", "minicalendar", "(", "context", ")", ":", "today", "=", "dt", ".", "date", ".", "today", "(", ")", "request", "=", "context", "[", "'request'", "]", "home", "=", "request", ".", "site", ".", "root_page", "cal", "=", "CalendarPage", ".", "objects", ".", "live", "(", ")", ".", "descendant_of", "(", "home", ")", ".", "first", "(", ")", "calUrl", "=", "cal", ".", "get_url", "(", "request", ")", "if", "cal", "else", "None", "if", "cal", ":", "events", "=", "cal", ".", "_getEventsByWeek", "(", "request", ",", "today", ".", "year", ",", "today", ".", "month", ")", "else", ":", "events", "=", "getAllEventsByWeek", "(", "request", ",", "today", ".", "year", ",", "today", ".", "month", ")", "return", "{", "'request'", ":", "request", ",", "'today'", ":", "today", ",", "'year'", ":", "today", ".", "year", ",", "'month'", ":", "today", ".", "month", ",", "'calendarUrl'", ":", "calUrl", ",", "'monthName'", ":", "calendar", ".", "month_name", "[", "today", ".", "month", "]", ",", "'weekdayInfo'", ":", "zip", "(", "weekday_abbr", ",", "weekday_name", ")", ",", "'events'", ":", "events", "}" ]
Displays a little ajax version of the calendar.
[ "Displays", "a", "little", "ajax", "version", "of", "the", "calendar", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/templatetags/joyous_tags.py#L49-L69
6,529
linuxsoftware/ls.joyous
ls/joyous/templatetags/joyous_tags.py
subsite_upcoming_events
def subsite_upcoming_events(context): """ Displays a list of all upcoming events in this site. """ request = context['request'] home = request.site.root_page return {'request': request, 'events': getAllUpcomingEvents(request, home=home)}
python
def subsite_upcoming_events(context): """ Displays a list of all upcoming events in this site. """ request = context['request'] home = request.site.root_page return {'request': request, 'events': getAllUpcomingEvents(request, home=home)}
[ "def", "subsite_upcoming_events", "(", "context", ")", ":", "request", "=", "context", "[", "'request'", "]", "home", "=", "request", ".", "site", ".", "root_page", "return", "{", "'request'", ":", "request", ",", "'events'", ":", "getAllUpcomingEvents", "(", "request", ",", "home", "=", "home", ")", "}" ]
Displays a list of all upcoming events in this site.
[ "Displays", "a", "list", "of", "all", "upcoming", "events", "in", "this", "site", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/templatetags/joyous_tags.py#L83-L90
6,530
linuxsoftware/ls.joyous
ls/joyous/templatetags/joyous_tags.py
group_upcoming_events
def group_upcoming_events(context, group=None): """ Displays a list of all upcoming events that are assigned to a specific group. If the group is not specified it is assumed to be the current page. """ request = context.get('request') if group is None: group = context.get('page') if group: events = getGroupUpcomingEvents(request, group) else: events = [] return {'request': request, 'events': events}
python
def group_upcoming_events(context, group=None): """ Displays a list of all upcoming events that are assigned to a specific group. If the group is not specified it is assumed to be the current page. """ request = context.get('request') if group is None: group = context.get('page') if group: events = getGroupUpcomingEvents(request, group) else: events = [] return {'request': request, 'events': events}
[ "def", "group_upcoming_events", "(", "context", ",", "group", "=", "None", ")", ":", "request", "=", "context", ".", "get", "(", "'request'", ")", "if", "group", "is", "None", ":", "group", "=", "context", ".", "get", "(", "'page'", ")", "if", "group", ":", "events", "=", "getGroupUpcomingEvents", "(", "request", ",", "group", ")", "else", ":", "events", "=", "[", "]", "return", "{", "'request'", ":", "request", ",", "'events'", ":", "events", "}" ]
Displays a list of all upcoming events that are assigned to a specific group. If the group is not specified it is assumed to be the current page.
[ "Displays", "a", "list", "of", "all", "upcoming", "events", "that", "are", "assigned", "to", "a", "specific", "group", ".", "If", "the", "group", "is", "not", "specified", "it", "is", "assumed", "to", "be", "the", "current", "page", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/templatetags/joyous_tags.py#L94-L107
6,531
linuxsoftware/ls.joyous
ls/joyous/templatetags/joyous_tags.py
next_on
def next_on(context, rrevent=None): """ Displays when the next occurence of a recurring event will be. If the recurring event is not specified it is assumed to be the current page. """ request = context['request'] if rrevent is None: rrevent = context.get('page') eventNextOn = getattr(rrevent, '_nextOn', lambda _:None) return eventNextOn(request)
python
def next_on(context, rrevent=None): """ Displays when the next occurence of a recurring event will be. If the recurring event is not specified it is assumed to be the current page. """ request = context['request'] if rrevent is None: rrevent = context.get('page') eventNextOn = getattr(rrevent, '_nextOn', lambda _:None) return eventNextOn(request)
[ "def", "next_on", "(", "context", ",", "rrevent", "=", "None", ")", ":", "request", "=", "context", "[", "'request'", "]", "if", "rrevent", "is", "None", ":", "rrevent", "=", "context", ".", "get", "(", "'page'", ")", "eventNextOn", "=", "getattr", "(", "rrevent", ",", "'_nextOn'", ",", "lambda", "_", ":", "None", ")", "return", "eventNextOn", "(", "request", ")" ]
Displays when the next occurence of a recurring event will be. If the recurring event is not specified it is assumed to be the current page.
[ "Displays", "when", "the", "next", "occurence", "of", "a", "recurring", "event", "will", "be", ".", "If", "the", "recurring", "event", "is", "not", "specified", "it", "is", "assumed", "to", "be", "the", "current", "page", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/templatetags/joyous_tags.py#L128-L137
6,532
linuxsoftware/ls.joyous
ls/joyous/templatetags/joyous_tags.py
location_gmap
def location_gmap(context, location): """Display a link to Google maps iff we are using WagtailGMaps""" gmapq = None if getattr(MapFieldPanel, "UsingWagtailGMaps", False): gmapq = location return {'gmapq': gmapq}
python
def location_gmap(context, location): """Display a link to Google maps iff we are using WagtailGMaps""" gmapq = None if getattr(MapFieldPanel, "UsingWagtailGMaps", False): gmapq = location return {'gmapq': gmapq}
[ "def", "location_gmap", "(", "context", ",", "location", ")", ":", "gmapq", "=", "None", "if", "getattr", "(", "MapFieldPanel", ",", "\"UsingWagtailGMaps\"", ",", "False", ")", ":", "gmapq", "=", "location", "return", "{", "'gmapq'", ":", "gmapq", "}" ]
Display a link to Google maps iff we are using WagtailGMaps
[ "Display", "a", "link", "to", "Google", "maps", "iff", "we", "are", "using", "WagtailGMaps" ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/templatetags/joyous_tags.py#L143-L148
6,533
linuxsoftware/ls.joyous
ls/joyous/models/events.py
getGroupUpcomingEvents
def getGroupUpcomingEvents(request, group): """ Return all the upcoming events that are assigned to the specified group. :param request: Django request object :param group: for this group page :rtype: list of the namedtuple ThisEvent (title, page, url) """ # Get events that are a child of a group page, or a postponement or extra # info a child of the recurring event child of the group rrEvents = RecurringEventPage.events(request).exclude(group_page=group) \ .upcoming().child_of(group).this() qrys = [SimpleEventPage.events(request).exclude(group_page=group) .upcoming().child_of(group).this(), MultidayEventPage.events(request).exclude(group_page=group) .upcoming().child_of(group).this(), rrEvents] for rrEvent in rrEvents: qrys += [PostponementPage.events(request).child_of(rrEvent.page) .upcoming().this(), ExtraInfoPage.events(request).exclude(extra_title="") .child_of(rrEvent.page).upcoming().this()] # Get events that are linked to a group page, or a postponement or extra # info a child of the recurring event linked to a group rrEvents = group.recurringeventpage_set(manager='events').auth(request) \ .upcoming().this() qrys += [group.simpleeventpage_set(manager='events').auth(request) .upcoming().this(), group.multidayeventpage_set(manager='events').auth(request) .upcoming().this(), rrEvents] for rrEvent in rrEvents: qrys += [PostponementPage.events(request).child_of(rrEvent.page) .upcoming().this(), ExtraInfoPage.events(request).exclude(extra_title="") .child_of(rrEvent.page).upcoming().this()] events = sorted(chain.from_iterable(qrys), key=attrgetter('page._upcoming_datetime_from')) return events
python
def getGroupUpcomingEvents(request, group): """ Return all the upcoming events that are assigned to the specified group. :param request: Django request object :param group: for this group page :rtype: list of the namedtuple ThisEvent (title, page, url) """ # Get events that are a child of a group page, or a postponement or extra # info a child of the recurring event child of the group rrEvents = RecurringEventPage.events(request).exclude(group_page=group) \ .upcoming().child_of(group).this() qrys = [SimpleEventPage.events(request).exclude(group_page=group) .upcoming().child_of(group).this(), MultidayEventPage.events(request).exclude(group_page=group) .upcoming().child_of(group).this(), rrEvents] for rrEvent in rrEvents: qrys += [PostponementPage.events(request).child_of(rrEvent.page) .upcoming().this(), ExtraInfoPage.events(request).exclude(extra_title="") .child_of(rrEvent.page).upcoming().this()] # Get events that are linked to a group page, or a postponement or extra # info a child of the recurring event linked to a group rrEvents = group.recurringeventpage_set(manager='events').auth(request) \ .upcoming().this() qrys += [group.simpleeventpage_set(manager='events').auth(request) .upcoming().this(), group.multidayeventpage_set(manager='events').auth(request) .upcoming().this(), rrEvents] for rrEvent in rrEvents: qrys += [PostponementPage.events(request).child_of(rrEvent.page) .upcoming().this(), ExtraInfoPage.events(request).exclude(extra_title="") .child_of(rrEvent.page).upcoming().this()] events = sorted(chain.from_iterable(qrys), key=attrgetter('page._upcoming_datetime_from')) return events
[ "def", "getGroupUpcomingEvents", "(", "request", ",", "group", ")", ":", "# Get events that are a child of a group page, or a postponement or extra", "# info a child of the recurring event child of the group", "rrEvents", "=", "RecurringEventPage", ".", "events", "(", "request", ")", ".", "exclude", "(", "group_page", "=", "group", ")", ".", "upcoming", "(", ")", ".", "child_of", "(", "group", ")", ".", "this", "(", ")", "qrys", "=", "[", "SimpleEventPage", ".", "events", "(", "request", ")", ".", "exclude", "(", "group_page", "=", "group", ")", ".", "upcoming", "(", ")", ".", "child_of", "(", "group", ")", ".", "this", "(", ")", ",", "MultidayEventPage", ".", "events", "(", "request", ")", ".", "exclude", "(", "group_page", "=", "group", ")", ".", "upcoming", "(", ")", ".", "child_of", "(", "group", ")", ".", "this", "(", ")", ",", "rrEvents", "]", "for", "rrEvent", "in", "rrEvents", ":", "qrys", "+=", "[", "PostponementPage", ".", "events", "(", "request", ")", ".", "child_of", "(", "rrEvent", ".", "page", ")", ".", "upcoming", "(", ")", ".", "this", "(", ")", ",", "ExtraInfoPage", ".", "events", "(", "request", ")", ".", "exclude", "(", "extra_title", "=", "\"\"", ")", ".", "child_of", "(", "rrEvent", ".", "page", ")", ".", "upcoming", "(", ")", ".", "this", "(", ")", "]", "# Get events that are linked to a group page, or a postponement or extra", "# info a child of the recurring event linked to a group", "rrEvents", "=", "group", ".", "recurringeventpage_set", "(", "manager", "=", "'events'", ")", ".", "auth", "(", "request", ")", ".", "upcoming", "(", ")", ".", "this", "(", ")", "qrys", "+=", "[", "group", ".", "simpleeventpage_set", "(", "manager", "=", "'events'", ")", ".", "auth", "(", "request", ")", ".", "upcoming", "(", ")", ".", "this", "(", ")", ",", "group", ".", "multidayeventpage_set", "(", "manager", "=", "'events'", ")", ".", "auth", "(", "request", ")", ".", "upcoming", "(", ")", ".", "this", "(", ")", ",", "rrEvents", "]", "for", "rrEvent", "in", "rrEvents", ":", "qrys", "+=", "[", "PostponementPage", ".", "events", "(", "request", ")", ".", "child_of", "(", "rrEvent", ".", "page", ")", ".", "upcoming", "(", ")", ".", "this", "(", ")", ",", "ExtraInfoPage", ".", "events", "(", "request", ")", ".", "exclude", "(", "extra_title", "=", "\"\"", ")", ".", "child_of", "(", "rrEvent", ".", "page", ")", ".", "upcoming", "(", ")", ".", "this", "(", ")", "]", "events", "=", "sorted", "(", "chain", ".", "from_iterable", "(", "qrys", ")", ",", "key", "=", "attrgetter", "(", "'page._upcoming_datetime_from'", ")", ")", "return", "events" ]
Return all the upcoming events that are assigned to the specified group. :param request: Django request object :param group: for this group page :rtype: list of the namedtuple ThisEvent (title, page, url)
[ "Return", "all", "the", "upcoming", "events", "that", "are", "assigned", "to", "the", "specified", "group", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L109-L148
6,534
linuxsoftware/ls.joyous
ls/joyous/models/events.py
EventBase.group
def group(self): """ The group this event belongs to. Adding the event as a child of a group automatically assigns the event to that group. """ retval = None parent = self.get_parent() Group = get_group_model() if issubclass(parent.specific_class, Group): retval = parent.specific if retval is None: retval = self.group_page return retval
python
def group(self): """ The group this event belongs to. Adding the event as a child of a group automatically assigns the event to that group. """ retval = None parent = self.get_parent() Group = get_group_model() if issubclass(parent.specific_class, Group): retval = parent.specific if retval is None: retval = self.group_page return retval
[ "def", "group", "(", "self", ")", ":", "retval", "=", "None", "parent", "=", "self", ".", "get_parent", "(", ")", "Group", "=", "get_group_model", "(", ")", "if", "issubclass", "(", "parent", ".", "specific_class", ",", "Group", ")", ":", "retval", "=", "parent", ".", "specific", "if", "retval", "is", "None", ":", "retval", "=", "self", ".", "group_page", "return", "retval" ]
The group this event belongs to. Adding the event as a child of a group automatically assigns the event to that group.
[ "The", "group", "this", "event", "belongs", "to", ".", "Adding", "the", "event", "as", "a", "child", "of", "a", "group", "automatically", "assigns", "the", "event", "to", "that", "group", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L492-L504
6,535
linuxsoftware/ls.joyous
ls/joyous/models/events.py
EventBase.isAuthorized
def isAuthorized(self, request): """ Is the user authorized for the requested action with this event? """ restrictions = self.get_view_restrictions() if restrictions and request is None: return False else: return all(restriction.accept_request(request) for restriction in restrictions)
python
def isAuthorized(self, request): """ Is the user authorized for the requested action with this event? """ restrictions = self.get_view_restrictions() if restrictions and request is None: return False else: return all(restriction.accept_request(request) for restriction in restrictions)
[ "def", "isAuthorized", "(", "self", ",", "request", ")", ":", "restrictions", "=", "self", ".", "get_view_restrictions", "(", ")", "if", "restrictions", "and", "request", "is", "None", ":", "return", "False", "else", ":", "return", "all", "(", "restriction", ".", "accept_request", "(", "request", ")", "for", "restriction", "in", "restrictions", ")" ]
Is the user authorized for the requested action with this event?
[ "Is", "the", "user", "authorized", "for", "the", "requested", "action", "with", "this", "event?" ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L562-L571
6,536
linuxsoftware/ls.joyous
ls/joyous/models/events.py
RecurringEventPage._upcoming_datetime_from
def _upcoming_datetime_from(self): """ The datetime this event next starts in the local time zone, or None if it is finished. """ nextDt = self.__localAfter(timezone.localtime(), dt.time.max, excludeCancellations=True, excludeExtraInfo=True) return nextDt
python
def _upcoming_datetime_from(self): """ The datetime this event next starts in the local time zone, or None if it is finished. """ nextDt = self.__localAfter(timezone.localtime(), dt.time.max, excludeCancellations=True, excludeExtraInfo=True) return nextDt
[ "def", "_upcoming_datetime_from", "(", "self", ")", ":", "nextDt", "=", "self", ".", "__localAfter", "(", "timezone", ".", "localtime", "(", ")", ",", "dt", ".", "time", ".", "max", ",", "excludeCancellations", "=", "True", ",", "excludeExtraInfo", "=", "True", ")", "return", "nextDt" ]
The datetime this event next starts in the local time zone, or None if it is finished.
[ "The", "datetime", "this", "event", "next", "starts", "in", "the", "local", "time", "zone", "or", "None", "if", "it", "is", "finished", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L961-L969
6,537
linuxsoftware/ls.joyous
ls/joyous/models/events.py
RecurringEventPage._past_datetime_from
def _past_datetime_from(self): """ The datetime this event previously started in the local time zone, or None if it never did. """ prevDt = self.__localBefore(timezone.localtime(), dt.time.max, excludeCancellations=True, excludeExtraInfo=True) return prevDt
python
def _past_datetime_from(self): """ The datetime this event previously started in the local time zone, or None if it never did. """ prevDt = self.__localBefore(timezone.localtime(), dt.time.max, excludeCancellations=True, excludeExtraInfo=True) return prevDt
[ "def", "_past_datetime_from", "(", "self", ")", ":", "prevDt", "=", "self", ".", "__localBefore", "(", "timezone", ".", "localtime", "(", ")", ",", "dt", ".", "time", ".", "max", ",", "excludeCancellations", "=", "True", ",", "excludeExtraInfo", "=", "True", ")", "return", "prevDt" ]
The datetime this event previously started in the local time zone, or None if it never did.
[ "The", "datetime", "this", "event", "previously", "started", "in", "the", "local", "time", "zone", "or", "None", "if", "it", "never", "did", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L982-L990
6,538
linuxsoftware/ls.joyous
ls/joyous/models/events.py
RecurringEventPage._first_datetime_from
def _first_datetime_from(self): """ The datetime this event first started in the local time zone, or None if it never did. """ myFromDt = self._getMyFirstDatetimeFrom() localTZ = timezone.get_current_timezone() return myFromDt.astimezone(localTZ)
python
def _first_datetime_from(self): """ The datetime this event first started in the local time zone, or None if it never did. """ myFromDt = self._getMyFirstDatetimeFrom() localTZ = timezone.get_current_timezone() return myFromDt.astimezone(localTZ)
[ "def", "_first_datetime_from", "(", "self", ")", ":", "myFromDt", "=", "self", ".", "_getMyFirstDatetimeFrom", "(", ")", "localTZ", "=", "timezone", ".", "get_current_timezone", "(", ")", "return", "myFromDt", ".", "astimezone", "(", "localTZ", ")" ]
The datetime this event first started in the local time zone, or None if it never did.
[ "The", "datetime", "this", "event", "first", "started", "in", "the", "local", "time", "zone", "or", "None", "if", "it", "never", "did", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L993-L1000
6,539
linuxsoftware/ls.joyous
ls/joyous/models/events.py
RecurringEventPage._getFromTime
def _getFromTime(self, atDate=None): """ What was the time of this event? Due to time zones that depends what day we are talking about. If no day is given, assume today. """ if atDate is None: atDate = timezone.localdate(timezone=self.tz) return getLocalTime(atDate, self.time_from, self.tz)
python
def _getFromTime(self, atDate=None): """ What was the time of this event? Due to time zones that depends what day we are talking about. If no day is given, assume today. """ if atDate is None: atDate = timezone.localdate(timezone=self.tz) return getLocalTime(atDate, self.time_from, self.tz)
[ "def", "_getFromTime", "(", "self", ",", "atDate", "=", "None", ")", ":", "if", "atDate", "is", "None", ":", "atDate", "=", "timezone", ".", "localdate", "(", "timezone", "=", "self", ".", "tz", ")", "return", "getLocalTime", "(", "atDate", ",", "self", ".", "time_from", ",", "self", ".", "tz", ")" ]
What was the time of this event? Due to time zones that depends what day we are talking about. If no day is given, assume today.
[ "What", "was", "the", "time", "of", "this", "event?", "Due", "to", "time", "zones", "that", "depends", "what", "day", "we", "are", "talking", "about", ".", "If", "no", "day", "is", "given", "assume", "today", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L1074-L1081
6,540
linuxsoftware/ls.joyous
ls/joyous/models/events.py
RecurringEventPage._getFromDt
def _getFromDt(self): """ Get the datetime of the next event after or before now. """ myNow = timezone.localtime(timezone=self.tz) return self.__after(myNow) or self.__before(myNow)
python
def _getFromDt(self): """ Get the datetime of the next event after or before now. """ myNow = timezone.localtime(timezone=self.tz) return self.__after(myNow) or self.__before(myNow)
[ "def", "_getFromDt", "(", "self", ")", ":", "myNow", "=", "timezone", ".", "localtime", "(", "timezone", "=", "self", ".", "tz", ")", "return", "self", ".", "__after", "(", "myNow", ")", "or", "self", ".", "__before", "(", "myNow", ")" ]
Get the datetime of the next event after or before now.
[ "Get", "the", "datetime", "of", "the", "next", "event", "after", "or", "before", "now", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L1083-L1088
6,541
linuxsoftware/ls.joyous
ls/joyous/models/events.py
RecurringEventPage._futureExceptions
def _futureExceptions(self, request): """ Returns all future extra info, cancellations and postponements created for this recurring event """ retval = [] # We know all future exception dates are in the parent time zone myToday = timezone.localdate(timezone=self.tz) for extraInfo in ExtraInfoPage.events(request).child_of(self) \ .filter(except_date__gte=myToday): retval.append(extraInfo) for cancellation in CancellationPage.events(request).child_of(self) \ .filter(except_date__gte=myToday): postponement = getattr(cancellation, "postponementpage", None) if postponement: retval.append(postponement) else: retval.append(cancellation) retval.sort(key=attrgetter('except_date')) # notice these are events not ThisEvents return retval
python
def _futureExceptions(self, request): """ Returns all future extra info, cancellations and postponements created for this recurring event """ retval = [] # We know all future exception dates are in the parent time zone myToday = timezone.localdate(timezone=self.tz) for extraInfo in ExtraInfoPage.events(request).child_of(self) \ .filter(except_date__gte=myToday): retval.append(extraInfo) for cancellation in CancellationPage.events(request).child_of(self) \ .filter(except_date__gte=myToday): postponement = getattr(cancellation, "postponementpage", None) if postponement: retval.append(postponement) else: retval.append(cancellation) retval.sort(key=attrgetter('except_date')) # notice these are events not ThisEvents return retval
[ "def", "_futureExceptions", "(", "self", ",", "request", ")", ":", "retval", "=", "[", "]", "# We know all future exception dates are in the parent time zone", "myToday", "=", "timezone", ".", "localdate", "(", "timezone", "=", "self", ".", "tz", ")", "for", "extraInfo", "in", "ExtraInfoPage", ".", "events", "(", "request", ")", ".", "child_of", "(", "self", ")", ".", "filter", "(", "except_date__gte", "=", "myToday", ")", ":", "retval", ".", "append", "(", "extraInfo", ")", "for", "cancellation", "in", "CancellationPage", ".", "events", "(", "request", ")", ".", "child_of", "(", "self", ")", ".", "filter", "(", "except_date__gte", "=", "myToday", ")", ":", "postponement", "=", "getattr", "(", "cancellation", ",", "\"postponementpage\"", ",", "None", ")", "if", "postponement", ":", "retval", ".", "append", "(", "postponement", ")", "else", ":", "retval", ".", "append", "(", "cancellation", ")", "retval", ".", "sort", "(", "key", "=", "attrgetter", "(", "'except_date'", ")", ")", "# notice these are events not ThisEvents", "return", "retval" ]
Returns all future extra info, cancellations and postponements created for this recurring event
[ "Returns", "all", "future", "extra", "info", "cancellations", "and", "postponements", "created", "for", "this", "recurring", "event" ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L1090-L1111
6,542
linuxsoftware/ls.joyous
ls/joyous/models/events.py
RecurringEventPage._getMyFirstDatetimeFrom
def _getMyFirstDatetimeFrom(self): """ The datetime this event first started, or None if it never did. """ myStartDt = getAwareDatetime(self.repeat.dtstart, None, self.tz, dt.time.min) return self.__after(myStartDt, excludeCancellations=False)
python
def _getMyFirstDatetimeFrom(self): """ The datetime this event first started, or None if it never did. """ myStartDt = getAwareDatetime(self.repeat.dtstart, None, self.tz, dt.time.min) return self.__after(myStartDt, excludeCancellations=False)
[ "def", "_getMyFirstDatetimeFrom", "(", "self", ")", ":", "myStartDt", "=", "getAwareDatetime", "(", "self", ".", "repeat", ".", "dtstart", ",", "None", ",", "self", ".", "tz", ",", "dt", ".", "time", ".", "min", ")", "return", "self", ".", "__after", "(", "myStartDt", ",", "excludeCancellations", "=", "False", ")" ]
The datetime this event first started, or None if it never did.
[ "The", "datetime", "this", "event", "first", "started", "or", "None", "if", "it", "never", "did", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L1145-L1151
6,543
linuxsoftware/ls.joyous
ls/joyous/models/events.py
RecurringEventPage._getMyFirstDatetimeTo
def _getMyFirstDatetimeTo(self): """ The datetime this event first finished, or None if it never did. """ myFirstDt = self._getMyFirstDatetimeFrom() if myFirstDt is not None: daysDelta = dt.timedelta(days=self.num_days - 1) return getAwareDatetime(myFirstDt.date() + daysDelta, self.time_to, self.tz, dt.time.max)
python
def _getMyFirstDatetimeTo(self): """ The datetime this event first finished, or None if it never did. """ myFirstDt = self._getMyFirstDatetimeFrom() if myFirstDt is not None: daysDelta = dt.timedelta(days=self.num_days - 1) return getAwareDatetime(myFirstDt.date() + daysDelta, self.time_to, self.tz, dt.time.max)
[ "def", "_getMyFirstDatetimeTo", "(", "self", ")", ":", "myFirstDt", "=", "self", ".", "_getMyFirstDatetimeFrom", "(", ")", "if", "myFirstDt", "is", "not", "None", ":", "daysDelta", "=", "dt", ".", "timedelta", "(", "days", "=", "self", ".", "num_days", "-", "1", ")", "return", "getAwareDatetime", "(", "myFirstDt", ".", "date", "(", ")", "+", "daysDelta", ",", "self", ".", "time_to", ",", "self", ".", "tz", ",", "dt", ".", "time", ".", "max", ")" ]
The datetime this event first finished, or None if it never did.
[ "The", "datetime", "this", "event", "first", "finished", "or", "None", "if", "it", "never", "did", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L1153-L1162
6,544
linuxsoftware/ls.joyous
ls/joyous/models/events.py
EventExceptionBase.local_title
def local_title(self): """ Localised version of the human-readable title of the page. """ name = self.title.partition(" for ")[0] exceptDate = getLocalDate(self.except_date, self.time_from, self.tz) title = _("{exception} for {date}").format(exception=_(name), date=dateFormat(exceptDate)) return title
python
def local_title(self): """ Localised version of the human-readable title of the page. """ name = self.title.partition(" for ")[0] exceptDate = getLocalDate(self.except_date, self.time_from, self.tz) title = _("{exception} for {date}").format(exception=_(name), date=dateFormat(exceptDate)) return title
[ "def", "local_title", "(", "self", ")", ":", "name", "=", "self", ".", "title", ".", "partition", "(", "\" for \"", ")", "[", "0", "]", "exceptDate", "=", "getLocalDate", "(", "self", ".", "except_date", ",", "self", ".", "time_from", ",", "self", ".", "tz", ")", "title", "=", "_", "(", "\"{exception} for {date}\"", ")", ".", "format", "(", "exception", "=", "_", "(", "name", ")", ",", "date", "=", "dateFormat", "(", "exceptDate", ")", ")", "return", "title" ]
Localised version of the human-readable title of the page.
[ "Localised", "version", "of", "the", "human", "-", "readable", "title", "of", "the", "page", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L1338-L1346
6,545
linuxsoftware/ls.joyous
ls/joyous/models/events.py
EventExceptionBase.full_clean
def full_clean(self, *args, **kwargs): """ Apply fixups that need to happen before per-field validation occurs. Sets the page's title. """ name = getattr(self, 'name', self.slugName.title()) self.title = "{} for {}".format(name, dateFormat(self.except_date)) self.slug = "{}-{}".format(self.except_date, self.slugName) super().full_clean(*args, **kwargs)
python
def full_clean(self, *args, **kwargs): """ Apply fixups that need to happen before per-field validation occurs. Sets the page's title. """ name = getattr(self, 'name', self.slugName.title()) self.title = "{} for {}".format(name, dateFormat(self.except_date)) self.slug = "{}-{}".format(self.except_date, self.slugName) super().full_clean(*args, **kwargs)
[ "def", "full_clean", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "getattr", "(", "self", ",", "'name'", ",", "self", ".", "slugName", ".", "title", "(", ")", ")", "self", ".", "title", "=", "\"{} for {}\"", ".", "format", "(", "name", ",", "dateFormat", "(", "self", ".", "except_date", ")", ")", "self", ".", "slug", "=", "\"{}-{}\"", ".", "format", "(", "self", ".", "except_date", ",", "self", ".", "slugName", ")", "super", "(", ")", ".", "full_clean", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Apply fixups that need to happen before per-field validation occurs. Sets the page's title.
[ "Apply", "fixups", "that", "need", "to", "happen", "before", "per", "-", "field", "validation", "occurs", ".", "Sets", "the", "page", "s", "title", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L1403-L1411
6,546
linuxsoftware/ls.joyous
ls/joyous/models/events.py
PostponementPage.what
def what(self): """ May return a 'postponed' or 'rescheduled' string depending what the start and finish time of the event has been changed to. """ originalFromDt = dt.datetime.combine(self.except_date, timeFrom(self.overrides.time_from)) changedFromDt = dt.datetime.combine(self.date, timeFrom(self.time_from)) originalDaysDelta = dt.timedelta(days=self.overrides.num_days - 1) originalToDt = getAwareDatetime(self.except_date + originalDaysDelta, self.overrides.time_to, self.tz) changedDaysDelta = dt.timedelta(days=self.num_days - 1) changedToDt = getAwareDatetime(self.except_date + changedDaysDelta, self.time_to, self.tz) if originalFromDt < changedFromDt: return _("Postponed") elif originalFromDt > changedFromDt or originalToDt != changedToDt: return _("Rescheduled") else: return None
python
def what(self): """ May return a 'postponed' or 'rescheduled' string depending what the start and finish time of the event has been changed to. """ originalFromDt = dt.datetime.combine(self.except_date, timeFrom(self.overrides.time_from)) changedFromDt = dt.datetime.combine(self.date, timeFrom(self.time_from)) originalDaysDelta = dt.timedelta(days=self.overrides.num_days - 1) originalToDt = getAwareDatetime(self.except_date + originalDaysDelta, self.overrides.time_to, self.tz) changedDaysDelta = dt.timedelta(days=self.num_days - 1) changedToDt = getAwareDatetime(self.except_date + changedDaysDelta, self.time_to, self.tz) if originalFromDt < changedFromDt: return _("Postponed") elif originalFromDt > changedFromDt or originalToDt != changedToDt: return _("Rescheduled") else: return None
[ "def", "what", "(", "self", ")", ":", "originalFromDt", "=", "dt", ".", "datetime", ".", "combine", "(", "self", ".", "except_date", ",", "timeFrom", "(", "self", ".", "overrides", ".", "time_from", ")", ")", "changedFromDt", "=", "dt", ".", "datetime", ".", "combine", "(", "self", ".", "date", ",", "timeFrom", "(", "self", ".", "time_from", ")", ")", "originalDaysDelta", "=", "dt", ".", "timedelta", "(", "days", "=", "self", ".", "overrides", ".", "num_days", "-", "1", ")", "originalToDt", "=", "getAwareDatetime", "(", "self", ".", "except_date", "+", "originalDaysDelta", ",", "self", ".", "overrides", ".", "time_to", ",", "self", ".", "tz", ")", "changedDaysDelta", "=", "dt", ".", "timedelta", "(", "days", "=", "self", ".", "num_days", "-", "1", ")", "changedToDt", "=", "getAwareDatetime", "(", "self", ".", "except_date", "+", "changedDaysDelta", ",", "self", ".", "time_to", ",", "self", ".", "tz", ")", "if", "originalFromDt", "<", "changedFromDt", ":", "return", "_", "(", "\"Postponed\"", ")", "elif", "originalFromDt", ">", "changedFromDt", "or", "originalToDt", "!=", "changedToDt", ":", "return", "_", "(", "\"Rescheduled\"", ")", "else", ":", "return", "None" ]
May return a 'postponed' or 'rescheduled' string depending what the start and finish time of the event has been changed to.
[ "May", "return", "a", "postponed", "or", "rescheduled", "string", "depending", "what", "the", "start", "and", "finish", "time", "of", "the", "event", "has", "been", "changed", "to", "." ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L1750-L1769
6,547
linuxsoftware/ls.joyous
ls/joyous/formats/ical.py
VEvent._convertTZ
def _convertTZ(self): """Will convert UTC datetimes to the current local timezone""" tz = timezone.get_current_timezone() dtstart = self['DTSTART'] dtend = self['DTEND'] if dtstart.zone() == "UTC": dtstart.dt = dtstart.dt.astimezone(tz) if dtend.zone() == "UTC": dtend.dt = dtend.dt.astimezone(tz)
python
def _convertTZ(self): """Will convert UTC datetimes to the current local timezone""" tz = timezone.get_current_timezone() dtstart = self['DTSTART'] dtend = self['DTEND'] if dtstart.zone() == "UTC": dtstart.dt = dtstart.dt.astimezone(tz) if dtend.zone() == "UTC": dtend.dt = dtend.dt.astimezone(tz)
[ "def", "_convertTZ", "(", "self", ")", ":", "tz", "=", "timezone", ".", "get_current_timezone", "(", ")", "dtstart", "=", "self", "[", "'DTSTART'", "]", "dtend", "=", "self", "[", "'DTEND'", "]", "if", "dtstart", ".", "zone", "(", ")", "==", "\"UTC\"", ":", "dtstart", ".", "dt", "=", "dtstart", ".", "dt", ".", "astimezone", "(", "tz", ")", "if", "dtend", ".", "zone", "(", ")", "==", "\"UTC\"", ":", "dtend", ".", "dt", "=", "dtend", ".", "dt", ".", "astimezone", "(", "tz", ")" ]
Will convert UTC datetimes to the current local timezone
[ "Will", "convert", "UTC", "datetimes", "to", "the", "current", "local", "timezone" ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/formats/ical.py#L518-L526
6,548
linuxsoftware/ls.joyous
ls/joyous/formats/vtimezone.py
to_naive_utc
def to_naive_utc(dtime): """convert a datetime object to UTC and than remove the tzinfo, if datetime is naive already, return it """ if not hasattr(dtime, 'tzinfo') or dtime.tzinfo is None: return dtime dtime_utc = dtime.astimezone(pytz.UTC) dtime_naive = dtime_utc.replace(tzinfo=None) return dtime_naive
python
def to_naive_utc(dtime): """convert a datetime object to UTC and than remove the tzinfo, if datetime is naive already, return it """ if not hasattr(dtime, 'tzinfo') or dtime.tzinfo is None: return dtime dtime_utc = dtime.astimezone(pytz.UTC) dtime_naive = dtime_utc.replace(tzinfo=None) return dtime_naive
[ "def", "to_naive_utc", "(", "dtime", ")", ":", "if", "not", "hasattr", "(", "dtime", ",", "'tzinfo'", ")", "or", "dtime", ".", "tzinfo", "is", "None", ":", "return", "dtime", "dtime_utc", "=", "dtime", ".", "astimezone", "(", "pytz", ".", "UTC", ")", "dtime_naive", "=", "dtime_utc", ".", "replace", "(", "tzinfo", "=", "None", ")", "return", "dtime_naive" ]
convert a datetime object to UTC and than remove the tzinfo, if datetime is naive already, return it
[ "convert", "a", "datetime", "object", "to", "UTC", "and", "than", "remove", "the", "tzinfo", "if", "datetime", "is", "naive", "already", "return", "it" ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/formats/vtimezone.py#L29-L38
6,549
linuxsoftware/ls.joyous
ls/joyous/formats/vtimezone.py
create_timezone
def create_timezone(tz, first_date=None, last_date=None): """ create an icalendar vtimezone from a pytz.tzinfo object :param tz: the timezone :type tz: pytz.tzinfo :param first_date: the very first datetime that needs to be included in the transition times, typically the DTSTART value of the (first recurring) event :type first_date: datetime.datetime :param last_date: the last datetime that needs to included, typically the end of the (very last) event (of a recursion set) :returns: timezone information :rtype: icalendar.Timezone() we currently have a problem here: pytz.timezones only carry the absolute dates of time zone transitions, not their RRULEs. This will a) make for rather bloated VTIMEZONE components, especially for long recurring events, b) we'll need to specify for which time range this VTIMEZONE should be generated and c) will not be valid for recurring events that go into eternity. Possible Solutions: As this information is not provided by pytz at all, there is no easy solution, we'd really need to ship another version of the OLSON DB. """ if isinstance(tz, pytz.tzinfo.StaticTzInfo): return _create_timezone_static(tz) # TODO last_date = None, recurring to infinity first_date = dt.datetime.today() if not first_date else to_naive_utc(first_date) last_date = dt.datetime.today() if not last_date else to_naive_utc(last_date) timezone = icalendar.Timezone() timezone.add('TZID', tz) # This is not a reliable way of determining if a transition is for # daylight savings. # From 1927 to 1941 New Zealand had GMT+11:30 (NZ Mean Time) as standard # and GMT+12:00 (NZ Summer Time) as daylight savings time. # From 1941 GMT+12:00 (NZ Standard Time) became standard time. # So NZST (NZ Summer/Standard Time) can refer to standard or daylight # savings time. And this code depends on the random order the _tzinfos # are returned. # dst = { # one[2]: 'DST' in two.__repr__() # for one, two in iter(tz._tzinfos.items()) # } # bst = { # one[2]: 'BST' in two.__repr__() # for one, two in iter(tz._tzinfos.items()) # } # ... # if dst[name] or bst[name]: # looking for the first and last transition time we need to include first_num, last_num = 0, len(tz._utc_transition_times) - 1 first_tt = tz._utc_transition_times[0] last_tt = tz._utc_transition_times[-1] for num, transtime in enumerate(tz._utc_transition_times): if transtime > first_tt and transtime < first_date: first_num = num first_tt = transtime if transtime < last_tt and transtime > last_date: last_num = num last_tt = transtime timezones = dict() for num in range(first_num, last_num + 1): name = tz._transition_info[num][2] if name in timezones: ttime = tz.fromutc(tz._utc_transition_times[num]).replace(tzinfo=None) if 'RDATE' in timezones[name]: timezones[name]['RDATE'].dts.append( icalendar.prop.vDDDTypes(ttime)) else: timezones[name].add('RDATE', ttime) continue if tz._transition_info[num][1]: subcomp = icalendar.TimezoneDaylight() else: subcomp = icalendar.TimezoneStandard() subcomp.add('TZNAME', tz._transition_info[num][2]) subcomp.add( 'DTSTART', tz.fromutc(tz._utc_transition_times[num]).replace(tzinfo=None)) subcomp.add('TZOFFSETTO', tz._transition_info[num][0]) subcomp.add('TZOFFSETFROM', tz._transition_info[num - 1][0]) timezones[name] = subcomp for subcomp in timezones.values(): timezone.add_component(subcomp) return timezone
python
def create_timezone(tz, first_date=None, last_date=None): """ create an icalendar vtimezone from a pytz.tzinfo object :param tz: the timezone :type tz: pytz.tzinfo :param first_date: the very first datetime that needs to be included in the transition times, typically the DTSTART value of the (first recurring) event :type first_date: datetime.datetime :param last_date: the last datetime that needs to included, typically the end of the (very last) event (of a recursion set) :returns: timezone information :rtype: icalendar.Timezone() we currently have a problem here: pytz.timezones only carry the absolute dates of time zone transitions, not their RRULEs. This will a) make for rather bloated VTIMEZONE components, especially for long recurring events, b) we'll need to specify for which time range this VTIMEZONE should be generated and c) will not be valid for recurring events that go into eternity. Possible Solutions: As this information is not provided by pytz at all, there is no easy solution, we'd really need to ship another version of the OLSON DB. """ if isinstance(tz, pytz.tzinfo.StaticTzInfo): return _create_timezone_static(tz) # TODO last_date = None, recurring to infinity first_date = dt.datetime.today() if not first_date else to_naive_utc(first_date) last_date = dt.datetime.today() if not last_date else to_naive_utc(last_date) timezone = icalendar.Timezone() timezone.add('TZID', tz) # This is not a reliable way of determining if a transition is for # daylight savings. # From 1927 to 1941 New Zealand had GMT+11:30 (NZ Mean Time) as standard # and GMT+12:00 (NZ Summer Time) as daylight savings time. # From 1941 GMT+12:00 (NZ Standard Time) became standard time. # So NZST (NZ Summer/Standard Time) can refer to standard or daylight # savings time. And this code depends on the random order the _tzinfos # are returned. # dst = { # one[2]: 'DST' in two.__repr__() # for one, two in iter(tz._tzinfos.items()) # } # bst = { # one[2]: 'BST' in two.__repr__() # for one, two in iter(tz._tzinfos.items()) # } # ... # if dst[name] or bst[name]: # looking for the first and last transition time we need to include first_num, last_num = 0, len(tz._utc_transition_times) - 1 first_tt = tz._utc_transition_times[0] last_tt = tz._utc_transition_times[-1] for num, transtime in enumerate(tz._utc_transition_times): if transtime > first_tt and transtime < first_date: first_num = num first_tt = transtime if transtime < last_tt and transtime > last_date: last_num = num last_tt = transtime timezones = dict() for num in range(first_num, last_num + 1): name = tz._transition_info[num][2] if name in timezones: ttime = tz.fromutc(tz._utc_transition_times[num]).replace(tzinfo=None) if 'RDATE' in timezones[name]: timezones[name]['RDATE'].dts.append( icalendar.prop.vDDDTypes(ttime)) else: timezones[name].add('RDATE', ttime) continue if tz._transition_info[num][1]: subcomp = icalendar.TimezoneDaylight() else: subcomp = icalendar.TimezoneStandard() subcomp.add('TZNAME', tz._transition_info[num][2]) subcomp.add( 'DTSTART', tz.fromutc(tz._utc_transition_times[num]).replace(tzinfo=None)) subcomp.add('TZOFFSETTO', tz._transition_info[num][0]) subcomp.add('TZOFFSETFROM', tz._transition_info[num - 1][0]) timezones[name] = subcomp for subcomp in timezones.values(): timezone.add_component(subcomp) return timezone
[ "def", "create_timezone", "(", "tz", ",", "first_date", "=", "None", ",", "last_date", "=", "None", ")", ":", "if", "isinstance", "(", "tz", ",", "pytz", ".", "tzinfo", ".", "StaticTzInfo", ")", ":", "return", "_create_timezone_static", "(", "tz", ")", "# TODO last_date = None, recurring to infinity", "first_date", "=", "dt", ".", "datetime", ".", "today", "(", ")", "if", "not", "first_date", "else", "to_naive_utc", "(", "first_date", ")", "last_date", "=", "dt", ".", "datetime", ".", "today", "(", ")", "if", "not", "last_date", "else", "to_naive_utc", "(", "last_date", ")", "timezone", "=", "icalendar", ".", "Timezone", "(", ")", "timezone", ".", "add", "(", "'TZID'", ",", "tz", ")", "# This is not a reliable way of determining if a transition is for", "# daylight savings.", "# From 1927 to 1941 New Zealand had GMT+11:30 (NZ Mean Time) as standard", "# and GMT+12:00 (NZ Summer Time) as daylight savings time.", "# From 1941 GMT+12:00 (NZ Standard Time) became standard time.", "# So NZST (NZ Summer/Standard Time) can refer to standard or daylight", "# savings time. And this code depends on the random order the _tzinfos", "# are returned.", "# dst = {", "# one[2]: 'DST' in two.__repr__()", "# for one, two in iter(tz._tzinfos.items())", "# }", "# bst = {", "# one[2]: 'BST' in two.__repr__()", "# for one, two in iter(tz._tzinfos.items())", "# }", "# ...", "# if dst[name] or bst[name]:", "# looking for the first and last transition time we need to include", "first_num", ",", "last_num", "=", "0", ",", "len", "(", "tz", ".", "_utc_transition_times", ")", "-", "1", "first_tt", "=", "tz", ".", "_utc_transition_times", "[", "0", "]", "last_tt", "=", "tz", ".", "_utc_transition_times", "[", "-", "1", "]", "for", "num", ",", "transtime", "in", "enumerate", "(", "tz", ".", "_utc_transition_times", ")", ":", "if", "transtime", ">", "first_tt", "and", "transtime", "<", "first_date", ":", "first_num", "=", "num", "first_tt", "=", "transtime", "if", "transtime", "<", "last_tt", "and", "transtime", ">", "last_date", ":", "last_num", "=", "num", "last_tt", "=", "transtime", "timezones", "=", "dict", "(", ")", "for", "num", "in", "range", "(", "first_num", ",", "last_num", "+", "1", ")", ":", "name", "=", "tz", ".", "_transition_info", "[", "num", "]", "[", "2", "]", "if", "name", "in", "timezones", ":", "ttime", "=", "tz", ".", "fromutc", "(", "tz", ".", "_utc_transition_times", "[", "num", "]", ")", ".", "replace", "(", "tzinfo", "=", "None", ")", "if", "'RDATE'", "in", "timezones", "[", "name", "]", ":", "timezones", "[", "name", "]", "[", "'RDATE'", "]", ".", "dts", ".", "append", "(", "icalendar", ".", "prop", ".", "vDDDTypes", "(", "ttime", ")", ")", "else", ":", "timezones", "[", "name", "]", ".", "add", "(", "'RDATE'", ",", "ttime", ")", "continue", "if", "tz", ".", "_transition_info", "[", "num", "]", "[", "1", "]", ":", "subcomp", "=", "icalendar", ".", "TimezoneDaylight", "(", ")", "else", ":", "subcomp", "=", "icalendar", ".", "TimezoneStandard", "(", ")", "subcomp", ".", "add", "(", "'TZNAME'", ",", "tz", ".", "_transition_info", "[", "num", "]", "[", "2", "]", ")", "subcomp", ".", "add", "(", "'DTSTART'", ",", "tz", ".", "fromutc", "(", "tz", ".", "_utc_transition_times", "[", "num", "]", ")", ".", "replace", "(", "tzinfo", "=", "None", ")", ")", "subcomp", ".", "add", "(", "'TZOFFSETTO'", ",", "tz", ".", "_transition_info", "[", "num", "]", "[", "0", "]", ")", "subcomp", ".", "add", "(", "'TZOFFSETFROM'", ",", "tz", ".", "_transition_info", "[", "num", "-", "1", "]", "[", "0", "]", ")", "timezones", "[", "name", "]", "=", "subcomp", "for", "subcomp", "in", "timezones", ".", "values", "(", ")", ":", "timezone", ".", "add_component", "(", "subcomp", ")", "return", "timezone" ]
create an icalendar vtimezone from a pytz.tzinfo object :param tz: the timezone :type tz: pytz.tzinfo :param first_date: the very first datetime that needs to be included in the transition times, typically the DTSTART value of the (first recurring) event :type first_date: datetime.datetime :param last_date: the last datetime that needs to included, typically the end of the (very last) event (of a recursion set) :returns: timezone information :rtype: icalendar.Timezone() we currently have a problem here: pytz.timezones only carry the absolute dates of time zone transitions, not their RRULEs. This will a) make for rather bloated VTIMEZONE components, especially for long recurring events, b) we'll need to specify for which time range this VTIMEZONE should be generated and c) will not be valid for recurring events that go into eternity. Possible Solutions: As this information is not provided by pytz at all, there is no easy solution, we'd really need to ship another version of the OLSON DB.
[ "create", "an", "icalendar", "vtimezone", "from", "a", "pytz", ".", "tzinfo", "object" ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/formats/vtimezone.py#L40-L138
6,550
linuxsoftware/ls.joyous
ls/joyous/formats/vtimezone.py
_create_timezone_static
def _create_timezone_static(tz): """create an icalendar vtimezone from a pytz.tzinfo.StaticTzInfo :param tz: the timezone :type tz: pytz.tzinfo.StaticTzInfo :returns: timezone information :rtype: icalendar.Timezone() """ timezone = icalendar.Timezone() timezone.add('TZID', tz) subcomp = icalendar.TimezoneStandard() subcomp.add('TZNAME', tz) subcomp.add('DTSTART', dt.datetime(1601, 1, 1)) subcomp.add('RDATE', dt.datetime(1601, 1, 1)) subcomp.add('TZOFFSETTO', tz._utcoffset) subcomp.add('TZOFFSETFROM', tz._utcoffset) timezone.add_component(subcomp) return timezone
python
def _create_timezone_static(tz): """create an icalendar vtimezone from a pytz.tzinfo.StaticTzInfo :param tz: the timezone :type tz: pytz.tzinfo.StaticTzInfo :returns: timezone information :rtype: icalendar.Timezone() """ timezone = icalendar.Timezone() timezone.add('TZID', tz) subcomp = icalendar.TimezoneStandard() subcomp.add('TZNAME', tz) subcomp.add('DTSTART', dt.datetime(1601, 1, 1)) subcomp.add('RDATE', dt.datetime(1601, 1, 1)) subcomp.add('TZOFFSETTO', tz._utcoffset) subcomp.add('TZOFFSETFROM', tz._utcoffset) timezone.add_component(subcomp) return timezone
[ "def", "_create_timezone_static", "(", "tz", ")", ":", "timezone", "=", "icalendar", ".", "Timezone", "(", ")", "timezone", ".", "add", "(", "'TZID'", ",", "tz", ")", "subcomp", "=", "icalendar", ".", "TimezoneStandard", "(", ")", "subcomp", ".", "add", "(", "'TZNAME'", ",", "tz", ")", "subcomp", ".", "add", "(", "'DTSTART'", ",", "dt", ".", "datetime", "(", "1601", ",", "1", ",", "1", ")", ")", "subcomp", ".", "add", "(", "'RDATE'", ",", "dt", ".", "datetime", "(", "1601", ",", "1", ",", "1", ")", ")", "subcomp", ".", "add", "(", "'TZOFFSETTO'", ",", "tz", ".", "_utcoffset", ")", "subcomp", ".", "add", "(", "'TZOFFSETFROM'", ",", "tz", ".", "_utcoffset", ")", "timezone", ".", "add_component", "(", "subcomp", ")", "return", "timezone" ]
create an icalendar vtimezone from a pytz.tzinfo.StaticTzInfo :param tz: the timezone :type tz: pytz.tzinfo.StaticTzInfo :returns: timezone information :rtype: icalendar.Timezone()
[ "create", "an", "icalendar", "vtimezone", "from", "a", "pytz", ".", "tzinfo", ".", "StaticTzInfo" ]
316283140ca5171a68ad3170a5964fdc89be0b56
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/formats/vtimezone.py#L141-L158
6,551
Onyo/jsonbender
jsonbender/core.py
bend
def bend(mapping, source, context=None): """ The main bending function. mapping: the map of benders source: a dict to be bent returns a new dict according to the provided map. """ context = {} if context is None else context transport = Transport(source, context) return _bend(mapping, transport)
python
def bend(mapping, source, context=None): """ The main bending function. mapping: the map of benders source: a dict to be bent returns a new dict according to the provided map. """ context = {} if context is None else context transport = Transport(source, context) return _bend(mapping, transport)
[ "def", "bend", "(", "mapping", ",", "source", ",", "context", "=", "None", ")", ":", "context", "=", "{", "}", "if", "context", "is", "None", "else", "context", "transport", "=", "Transport", "(", "source", ",", "context", ")", "return", "_bend", "(", "mapping", ",", "transport", ")" ]
The main bending function. mapping: the map of benders source: a dict to be bent returns a new dict according to the provided map.
[ "The", "main", "bending", "function", "." ]
df85ec444be3185d346db894402ca6eaa38dd947
https://github.com/Onyo/jsonbender/blob/df85ec444be3185d346db894402ca6eaa38dd947/jsonbender/core.py#L216-L227
6,552
Onyo/jsonbender
jsonbender/selectors.py
F.protect
def protect(self, protect_against=None): """ Return a ProtectedF with the same parameters and with the given `protect_against`. """ return ProtectedF(self._func, *self._args, protect_against=protect_against, **self._kwargs)
python
def protect(self, protect_against=None): """ Return a ProtectedF with the same parameters and with the given `protect_against`. """ return ProtectedF(self._func, *self._args, protect_against=protect_against, **self._kwargs)
[ "def", "protect", "(", "self", ",", "protect_against", "=", "None", ")", ":", "return", "ProtectedF", "(", "self", ".", "_func", ",", "*", "self", ".", "_args", ",", "protect_against", "=", "protect_against", ",", "*", "*", "self", ".", "_kwargs", ")" ]
Return a ProtectedF with the same parameters and with the given `protect_against`.
[ "Return", "a", "ProtectedF", "with", "the", "same", "parameters", "and", "with", "the", "given", "protect_against", "." ]
df85ec444be3185d346db894402ca6eaa38dd947
https://github.com/Onyo/jsonbender/blob/df85ec444be3185d346db894402ca6eaa38dd947/jsonbender/selectors.py#L83-L91
6,553
wdecoster/NanoPlot
nanoplot/utils.py
init_logs
def init_logs(args, tool="NanoPlot"): """Initiate log file and log arguments.""" start_time = dt.fromtimestamp(time()).strftime('%Y%m%d_%H%M') logname = os.path.join(args.outdir, args.prefix + tool + "_" + start_time + ".log") handlers = [logging.FileHandler(logname)] if args.verbose: handlers.append(logging.StreamHandler()) logging.basicConfig( format='%(asctime)s %(message)s', handlers=handlers, level=logging.INFO) logging.info('{} {} started with arguments {}'.format(tool, __version__, args)) logging.info('Python version is: {}'.format(sys.version.replace('\n', ' '))) return logname
python
def init_logs(args, tool="NanoPlot"): """Initiate log file and log arguments.""" start_time = dt.fromtimestamp(time()).strftime('%Y%m%d_%H%M') logname = os.path.join(args.outdir, args.prefix + tool + "_" + start_time + ".log") handlers = [logging.FileHandler(logname)] if args.verbose: handlers.append(logging.StreamHandler()) logging.basicConfig( format='%(asctime)s %(message)s', handlers=handlers, level=logging.INFO) logging.info('{} {} started with arguments {}'.format(tool, __version__, args)) logging.info('Python version is: {}'.format(sys.version.replace('\n', ' '))) return logname
[ "def", "init_logs", "(", "args", ",", "tool", "=", "\"NanoPlot\"", ")", ":", "start_time", "=", "dt", ".", "fromtimestamp", "(", "time", "(", ")", ")", ".", "strftime", "(", "'%Y%m%d_%H%M'", ")", "logname", "=", "os", ".", "path", ".", "join", "(", "args", ".", "outdir", ",", "args", ".", "prefix", "+", "tool", "+", "\"_\"", "+", "start_time", "+", "\".log\"", ")", "handlers", "=", "[", "logging", ".", "FileHandler", "(", "logname", ")", "]", "if", "args", ".", "verbose", ":", "handlers", ".", "append", "(", "logging", ".", "StreamHandler", "(", ")", ")", "logging", ".", "basicConfig", "(", "format", "=", "'%(asctime)s %(message)s'", ",", "handlers", "=", "handlers", ",", "level", "=", "logging", ".", "INFO", ")", "logging", ".", "info", "(", "'{} {} started with arguments {}'", ".", "format", "(", "tool", ",", "__version__", ",", "args", ")", ")", "logging", ".", "info", "(", "'Python version is: {}'", ".", "format", "(", "sys", ".", "version", ".", "replace", "(", "'\\n'", ",", "' '", ")", ")", ")", "return", "logname" ]
Initiate log file and log arguments.
[ "Initiate", "log", "file", "and", "log", "arguments", "." ]
d1601076731df2a07020316bd159b544f497a606
https://github.com/wdecoster/NanoPlot/blob/d1601076731df2a07020316bd159b544f497a606/nanoplot/utils.py#L61-L74
6,554
wdecoster/NanoPlot
nanoplot/filteroptions.py
flag_length_outliers
def flag_length_outliers(df, columnname): """Return index of records with length-outliers above 3 standard deviations from the median.""" return df[columnname] > (np.median(df[columnname]) + 3 * np.std(df[columnname]))
python
def flag_length_outliers(df, columnname): """Return index of records with length-outliers above 3 standard deviations from the median.""" return df[columnname] > (np.median(df[columnname]) + 3 * np.std(df[columnname]))
[ "def", "flag_length_outliers", "(", "df", ",", "columnname", ")", ":", "return", "df", "[", "columnname", "]", ">", "(", "np", ".", "median", "(", "df", "[", "columnname", "]", ")", "+", "3", "*", "np", ".", "std", "(", "df", "[", "columnname", "]", ")", ")" ]
Return index of records with length-outliers above 3 standard deviations from the median.
[ "Return", "index", "of", "records", "with", "length", "-", "outliers", "above", "3", "standard", "deviations", "from", "the", "median", "." ]
d1601076731df2a07020316bd159b544f497a606
https://github.com/wdecoster/NanoPlot/blob/d1601076731df2a07020316bd159b544f497a606/nanoplot/filteroptions.py#L6-L8
6,555
xmunoz/sodapy
sodapy/__init__.py
_raise_for_status
def _raise_for_status(response): ''' Custom raise_for_status with more appropriate error message. ''' http_error_msg = "" if 400 <= response.status_code < 500: http_error_msg = "{0} Client Error: {1}".format(response.status_code, response.reason) elif 500 <= response.status_code < 600: http_error_msg = "{0} Server Error: {1}".format(response.status_code, response.reason) if http_error_msg: try: more_info = response.json().get("message") except ValueError: more_info = None if more_info and more_info.lower() != response.reason.lower(): http_error_msg += ".\n\t{0}".format(more_info) raise requests.exceptions.HTTPError(http_error_msg, response=response)
python
def _raise_for_status(response): ''' Custom raise_for_status with more appropriate error message. ''' http_error_msg = "" if 400 <= response.status_code < 500: http_error_msg = "{0} Client Error: {1}".format(response.status_code, response.reason) elif 500 <= response.status_code < 600: http_error_msg = "{0} Server Error: {1}".format(response.status_code, response.reason) if http_error_msg: try: more_info = response.json().get("message") except ValueError: more_info = None if more_info and more_info.lower() != response.reason.lower(): http_error_msg += ".\n\t{0}".format(more_info) raise requests.exceptions.HTTPError(http_error_msg, response=response)
[ "def", "_raise_for_status", "(", "response", ")", ":", "http_error_msg", "=", "\"\"", "if", "400", "<=", "response", ".", "status_code", "<", "500", ":", "http_error_msg", "=", "\"{0} Client Error: {1}\"", ".", "format", "(", "response", ".", "status_code", ",", "response", ".", "reason", ")", "elif", "500", "<=", "response", ".", "status_code", "<", "600", ":", "http_error_msg", "=", "\"{0} Server Error: {1}\"", ".", "format", "(", "response", ".", "status_code", ",", "response", ".", "reason", ")", "if", "http_error_msg", ":", "try", ":", "more_info", "=", "response", ".", "json", "(", ")", ".", "get", "(", "\"message\"", ")", "except", "ValueError", ":", "more_info", "=", "None", "if", "more_info", "and", "more_info", ".", "lower", "(", ")", "!=", "response", ".", "reason", ".", "lower", "(", ")", ":", "http_error_msg", "+=", "\".\\n\\t{0}\"", ".", "format", "(", "more_info", ")", "raise", "requests", ".", "exceptions", ".", "HTTPError", "(", "http_error_msg", ",", "response", "=", "response", ")" ]
Custom raise_for_status with more appropriate error message.
[ "Custom", "raise_for_status", "with", "more", "appropriate", "error", "message", "." ]
dad2ca9560cde0acb03bdb4423260e891ca40d7b
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L510-L531
6,556
xmunoz/sodapy
sodapy/__init__.py
_clear_empty_values
def _clear_empty_values(args): ''' Scrap junk data from a dict. ''' result = {} for param in args: if args[param] is not None: result[param] = args[param] return result
python
def _clear_empty_values(args): ''' Scrap junk data from a dict. ''' result = {} for param in args: if args[param] is not None: result[param] = args[param] return result
[ "def", "_clear_empty_values", "(", "args", ")", ":", "result", "=", "{", "}", "for", "param", "in", "args", ":", "if", "args", "[", "param", "]", "is", "not", "None", ":", "result", "[", "param", "]", "=", "args", "[", "param", "]", "return", "result" ]
Scrap junk data from a dict.
[ "Scrap", "junk", "data", "from", "a", "dict", "." ]
dad2ca9560cde0acb03bdb4423260e891ca40d7b
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L534-L542
6,557
xmunoz/sodapy
sodapy/__init__.py
authentication_validation
def authentication_validation(username, password, access_token): ''' Only accept one form of authentication. ''' if bool(username) is not bool(password): raise Exception("Basic authentication requires a username AND" " password.") if (username and access_token) or (password and access_token): raise Exception("Cannot use both Basic Authentication and" " OAuth2.0. Please use only one authentication" " method.")
python
def authentication_validation(username, password, access_token): ''' Only accept one form of authentication. ''' if bool(username) is not bool(password): raise Exception("Basic authentication requires a username AND" " password.") if (username and access_token) or (password and access_token): raise Exception("Cannot use both Basic Authentication and" " OAuth2.0. Please use only one authentication" " method.")
[ "def", "authentication_validation", "(", "username", ",", "password", ",", "access_token", ")", ":", "if", "bool", "(", "username", ")", "is", "not", "bool", "(", "password", ")", ":", "raise", "Exception", "(", "\"Basic authentication requires a username AND\"", "\" password.\"", ")", "if", "(", "username", "and", "access_token", ")", "or", "(", "password", "and", "access_token", ")", ":", "raise", "Exception", "(", "\"Cannot use both Basic Authentication and\"", "\" OAuth2.0. Please use only one authentication\"", "\" method.\"", ")" ]
Only accept one form of authentication.
[ "Only", "accept", "one", "form", "of", "authentication", "." ]
dad2ca9560cde0acb03bdb4423260e891ca40d7b
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L570-L580
6,558
xmunoz/sodapy
sodapy/__init__.py
_download_file
def _download_file(url, local_filename): ''' Utility function that downloads a chunked response from the specified url to a local path. This method is suitable for larger downloads. ''' response = requests.get(url, stream=True) with open(local_filename, 'wb') as outfile: for chunk in response.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks outfile.write(chunk)
python
def _download_file(url, local_filename): ''' Utility function that downloads a chunked response from the specified url to a local path. This method is suitable for larger downloads. ''' response = requests.get(url, stream=True) with open(local_filename, 'wb') as outfile: for chunk in response.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks outfile.write(chunk)
[ "def", "_download_file", "(", "url", ",", "local_filename", ")", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "with", "open", "(", "local_filename", ",", "'wb'", ")", "as", "outfile", ":", "for", "chunk", "in", "response", ".", "iter_content", "(", "chunk_size", "=", "1024", ")", ":", "if", "chunk", ":", "# filter out keep-alive new chunks", "outfile", ".", "write", "(", "chunk", ")" ]
Utility function that downloads a chunked response from the specified url to a local path. This method is suitable for larger downloads.
[ "Utility", "function", "that", "downloads", "a", "chunked", "response", "from", "the", "specified", "url", "to", "a", "local", "path", ".", "This", "method", "is", "suitable", "for", "larger", "downloads", "." ]
dad2ca9560cde0acb03bdb4423260e891ca40d7b
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L583-L592
6,559
xmunoz/sodapy
sodapy/__init__.py
Socrata.set_permission
def set_permission(self, dataset_identifier, permission="private", content_type="json"): ''' Set a dataset's permissions to private or public Options are private, public ''' resource = _format_old_api_request(dataid=dataset_identifier, content_type=content_type) params = { "method": "setPermission", "value": "public.read" if permission == "public" else permission } return self._perform_request("put", resource, params=params)
python
def set_permission(self, dataset_identifier, permission="private", content_type="json"): ''' Set a dataset's permissions to private or public Options are private, public ''' resource = _format_old_api_request(dataid=dataset_identifier, content_type=content_type) params = { "method": "setPermission", "value": "public.read" if permission == "public" else permission } return self._perform_request("put", resource, params=params)
[ "def", "set_permission", "(", "self", ",", "dataset_identifier", ",", "permission", "=", "\"private\"", ",", "content_type", "=", "\"json\"", ")", ":", "resource", "=", "_format_old_api_request", "(", "dataid", "=", "dataset_identifier", ",", "content_type", "=", "content_type", ")", "params", "=", "{", "\"method\"", ":", "\"setPermission\"", ",", "\"value\"", ":", "\"public.read\"", "if", "permission", "==", "\"public\"", "else", "permission", "}", "return", "self", ".", "_perform_request", "(", "\"put\"", ",", "resource", ",", "params", "=", "params", ")" ]
Set a dataset's permissions to private or public Options are private, public
[ "Set", "a", "dataset", "s", "permissions", "to", "private", "or", "public", "Options", "are", "private", "public" ]
dad2ca9560cde0acb03bdb4423260e891ca40d7b
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L236-L249
6,560
xmunoz/sodapy
sodapy/__init__.py
Socrata.get_metadata
def get_metadata(self, dataset_identifier, content_type="json"): ''' Retrieve the metadata for a particular dataset. ''' resource = _format_old_api_request(dataid=dataset_identifier, content_type=content_type) return self._perform_request("get", resource)
python
def get_metadata(self, dataset_identifier, content_type="json"): ''' Retrieve the metadata for a particular dataset. ''' resource = _format_old_api_request(dataid=dataset_identifier, content_type=content_type) return self._perform_request("get", resource)
[ "def", "get_metadata", "(", "self", ",", "dataset_identifier", ",", "content_type", "=", "\"json\"", ")", ":", "resource", "=", "_format_old_api_request", "(", "dataid", "=", "dataset_identifier", ",", "content_type", "=", "content_type", ")", "return", "self", ".", "_perform_request", "(", "\"get\"", ",", "resource", ")" ]
Retrieve the metadata for a particular dataset.
[ "Retrieve", "the", "metadata", "for", "a", "particular", "dataset", "." ]
dad2ca9560cde0acb03bdb4423260e891ca40d7b
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L251-L256
6,561
xmunoz/sodapy
sodapy/__init__.py
Socrata.download_attachments
def download_attachments(self, dataset_identifier, content_type="json", download_dir="~/sodapy_downloads"): ''' Download all of the attachments associated with a dataset. Return the paths of downloaded files. ''' metadata = self.get_metadata(dataset_identifier, content_type=content_type) files = [] attachments = metadata['metadata'].get("attachments") if not attachments: logging.info("No attachments were found or downloaded.") return files download_dir = os.path.join(os.path.expanduser(download_dir), dataset_identifier) if not os.path.exists(download_dir): os.makedirs(download_dir) for attachment in attachments: file_path = os.path.join(download_dir, attachment["filename"]) has_assetid = attachment.get("assetId", False) if has_assetid: base = _format_old_api_request(dataid=dataset_identifier) assetid = attachment["assetId"] resource = "{0}/files/{1}?download=true&filename={2}"\ .format(base, assetid, attachment["filename"]) else: base = "/api/assets" assetid = attachment["blobId"] resource = "{0}/{1}?download=true".format(base, assetid) uri = "{0}{1}{2}".format(self.uri_prefix, self.domain, resource) _download_file(uri, file_path) files.append(file_path) logging.info("The following files were downloaded:\n\t{0}".format("\n\t".join(files))) return files
python
def download_attachments(self, dataset_identifier, content_type="json", download_dir="~/sodapy_downloads"): ''' Download all of the attachments associated with a dataset. Return the paths of downloaded files. ''' metadata = self.get_metadata(dataset_identifier, content_type=content_type) files = [] attachments = metadata['metadata'].get("attachments") if not attachments: logging.info("No attachments were found or downloaded.") return files download_dir = os.path.join(os.path.expanduser(download_dir), dataset_identifier) if not os.path.exists(download_dir): os.makedirs(download_dir) for attachment in attachments: file_path = os.path.join(download_dir, attachment["filename"]) has_assetid = attachment.get("assetId", False) if has_assetid: base = _format_old_api_request(dataid=dataset_identifier) assetid = attachment["assetId"] resource = "{0}/files/{1}?download=true&filename={2}"\ .format(base, assetid, attachment["filename"]) else: base = "/api/assets" assetid = attachment["blobId"] resource = "{0}/{1}?download=true".format(base, assetid) uri = "{0}{1}{2}".format(self.uri_prefix, self.domain, resource) _download_file(uri, file_path) files.append(file_path) logging.info("The following files were downloaded:\n\t{0}".format("\n\t".join(files))) return files
[ "def", "download_attachments", "(", "self", ",", "dataset_identifier", ",", "content_type", "=", "\"json\"", ",", "download_dir", "=", "\"~/sodapy_downloads\"", ")", ":", "metadata", "=", "self", ".", "get_metadata", "(", "dataset_identifier", ",", "content_type", "=", "content_type", ")", "files", "=", "[", "]", "attachments", "=", "metadata", "[", "'metadata'", "]", ".", "get", "(", "\"attachments\"", ")", "if", "not", "attachments", ":", "logging", ".", "info", "(", "\"No attachments were found or downloaded.\"", ")", "return", "files", "download_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "download_dir", ")", ",", "dataset_identifier", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "download_dir", ")", ":", "os", ".", "makedirs", "(", "download_dir", ")", "for", "attachment", "in", "attachments", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "download_dir", ",", "attachment", "[", "\"filename\"", "]", ")", "has_assetid", "=", "attachment", ".", "get", "(", "\"assetId\"", ",", "False", ")", "if", "has_assetid", ":", "base", "=", "_format_old_api_request", "(", "dataid", "=", "dataset_identifier", ")", "assetid", "=", "attachment", "[", "\"assetId\"", "]", "resource", "=", "\"{0}/files/{1}?download=true&filename={2}\"", ".", "format", "(", "base", ",", "assetid", ",", "attachment", "[", "\"filename\"", "]", ")", "else", ":", "base", "=", "\"/api/assets\"", "assetid", "=", "attachment", "[", "\"blobId\"", "]", "resource", "=", "\"{0}/{1}?download=true\"", ".", "format", "(", "base", ",", "assetid", ")", "uri", "=", "\"{0}{1}{2}\"", ".", "format", "(", "self", ".", "uri_prefix", ",", "self", ".", "domain", ",", "resource", ")", "_download_file", "(", "uri", ",", "file_path", ")", "files", ".", "append", "(", "file_path", ")", "logging", ".", "info", "(", "\"The following files were downloaded:\\n\\t{0}\"", ".", "format", "(", "\"\\n\\t\"", ".", "join", "(", "files", ")", ")", ")", "return", "files" ]
Download all of the attachments associated with a dataset. Return the paths of downloaded files.
[ "Download", "all", "of", "the", "attachments", "associated", "with", "a", "dataset", ".", "Return", "the", "paths", "of", "downloaded", "files", "." ]
dad2ca9560cde0acb03bdb4423260e891ca40d7b
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L269-L304
6,562
xmunoz/sodapy
sodapy/__init__.py
Socrata.replace_non_data_file
def replace_non_data_file(self, dataset_identifier, params, file_data): ''' Same as create_non_data_file, but replaces a file that already exists in a file-based dataset. WARNING: a table-based dataset cannot be replaced by a file-based dataset. Use create_non_data_file in order to replace. ''' resource = _format_old_api_request(dataid=dataset_identifier, content_type="txt") if not params.get('method', None): params['method'] = 'replaceBlob' params['id'] = dataset_identifier return self._perform_request("post", resource, params=params, files=file_data)
python
def replace_non_data_file(self, dataset_identifier, params, file_data): ''' Same as create_non_data_file, but replaces a file that already exists in a file-based dataset. WARNING: a table-based dataset cannot be replaced by a file-based dataset. Use create_non_data_file in order to replace. ''' resource = _format_old_api_request(dataid=dataset_identifier, content_type="txt") if not params.get('method', None): params['method'] = 'replaceBlob' params['id'] = dataset_identifier return self._perform_request("post", resource, params=params, files=file_data)
[ "def", "replace_non_data_file", "(", "self", ",", "dataset_identifier", ",", "params", ",", "file_data", ")", ":", "resource", "=", "_format_old_api_request", "(", "dataid", "=", "dataset_identifier", ",", "content_type", "=", "\"txt\"", ")", "if", "not", "params", ".", "get", "(", "'method'", ",", "None", ")", ":", "params", "[", "'method'", "]", "=", "'replaceBlob'", "params", "[", "'id'", "]", "=", "dataset_identifier", "return", "self", ".", "_perform_request", "(", "\"post\"", ",", "resource", ",", "params", "=", "params", ",", "files", "=", "file_data", ")" ]
Same as create_non_data_file, but replaces a file that already exists in a file-based dataset. WARNING: a table-based dataset cannot be replaced by a file-based dataset. Use create_non_data_file in order to replace.
[ "Same", "as", "create_non_data_file", "but", "replaces", "a", "file", "that", "already", "exists", "in", "a", "file", "-", "based", "dataset", "." ]
dad2ca9560cde0acb03bdb4423260e891ca40d7b
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L400-L415
6,563
xmunoz/sodapy
sodapy/__init__.py
Socrata._perform_update
def _perform_update(self, method, resource, payload): ''' Execute the update task. ''' # python2/3 compatibility wizardry try: file_type = file except NameError: file_type = IOBase if isinstance(payload, (dict, list)): response = self._perform_request(method, resource, data=json.dumps(payload)) elif isinstance(payload, file_type): headers = { "content-type": "text/csv", } response = self._perform_request(method, resource, data=payload, headers=headers) else: raise Exception("Unrecognized payload {0}. Currently only list-, dictionary-," " and file-types are supported.".format(type(payload))) return response
python
def _perform_update(self, method, resource, payload): ''' Execute the update task. ''' # python2/3 compatibility wizardry try: file_type = file except NameError: file_type = IOBase if isinstance(payload, (dict, list)): response = self._perform_request(method, resource, data=json.dumps(payload)) elif isinstance(payload, file_type): headers = { "content-type": "text/csv", } response = self._perform_request(method, resource, data=payload, headers=headers) else: raise Exception("Unrecognized payload {0}. Currently only list-, dictionary-," " and file-types are supported.".format(type(payload))) return response
[ "def", "_perform_update", "(", "self", ",", "method", ",", "resource", ",", "payload", ")", ":", "# python2/3 compatibility wizardry", "try", ":", "file_type", "=", "file", "except", "NameError", ":", "file_type", "=", "IOBase", "if", "isinstance", "(", "payload", ",", "(", "dict", ",", "list", ")", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "method", ",", "resource", ",", "data", "=", "json", ".", "dumps", "(", "payload", ")", ")", "elif", "isinstance", "(", "payload", ",", "file_type", ")", ":", "headers", "=", "{", "\"content-type\"", ":", "\"text/csv\"", ",", "}", "response", "=", "self", ".", "_perform_request", "(", "method", ",", "resource", ",", "data", "=", "payload", ",", "headers", "=", "headers", ")", "else", ":", "raise", "Exception", "(", "\"Unrecognized payload {0}. Currently only list-, dictionary-,\"", "\" and file-types are supported.\"", ".", "format", "(", "type", "(", "payload", ")", ")", ")", "return", "response" ]
Execute the update task.
[ "Execute", "the", "update", "task", "." ]
dad2ca9560cde0acb03bdb4423260e891ca40d7b
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L417-L441
6,564
xmunoz/sodapy
sodapy/__init__.py
Socrata._perform_request
def _perform_request(self, request_type, resource, **kwargs): ''' Utility method that performs all requests. ''' request_type_methods = set(["get", "post", "put", "delete"]) if request_type not in request_type_methods: raise Exception("Unknown request type. Supported request types are" ": {0}".format(", ".join(request_type_methods))) uri = "{0}{1}{2}".format(self.uri_prefix, self.domain, resource) # set a timeout, just to be safe kwargs["timeout"] = self.timeout response = getattr(self.session, request_type)(uri, **kwargs) # handle errors if response.status_code not in (200, 202): _raise_for_status(response) # when responses have no content body (ie. delete, set_permission), # simply return the whole response if not response.text: return response # for other request types, return most useful data content_type = response.headers.get('content-type').strip().lower() if re.match(r'application\/json', content_type): return response.json() elif re.match(r'text\/csv', content_type): csv_stream = StringIO(response.text) return [line for line in csv.reader(csv_stream)] elif re.match(r'application\/rdf\+xml', content_type): return response.content elif re.match(r'text\/plain', content_type): try: return json.loads(response.text) except ValueError: return response.text else: raise Exception("Unknown response format: {0}" .format(content_type))
python
def _perform_request(self, request_type, resource, **kwargs): ''' Utility method that performs all requests. ''' request_type_methods = set(["get", "post", "put", "delete"]) if request_type not in request_type_methods: raise Exception("Unknown request type. Supported request types are" ": {0}".format(", ".join(request_type_methods))) uri = "{0}{1}{2}".format(self.uri_prefix, self.domain, resource) # set a timeout, just to be safe kwargs["timeout"] = self.timeout response = getattr(self.session, request_type)(uri, **kwargs) # handle errors if response.status_code not in (200, 202): _raise_for_status(response) # when responses have no content body (ie. delete, set_permission), # simply return the whole response if not response.text: return response # for other request types, return most useful data content_type = response.headers.get('content-type').strip().lower() if re.match(r'application\/json', content_type): return response.json() elif re.match(r'text\/csv', content_type): csv_stream = StringIO(response.text) return [line for line in csv.reader(csv_stream)] elif re.match(r'application\/rdf\+xml', content_type): return response.content elif re.match(r'text\/plain', content_type): try: return json.loads(response.text) except ValueError: return response.text else: raise Exception("Unknown response format: {0}" .format(content_type))
[ "def", "_perform_request", "(", "self", ",", "request_type", ",", "resource", ",", "*", "*", "kwargs", ")", ":", "request_type_methods", "=", "set", "(", "[", "\"get\"", ",", "\"post\"", ",", "\"put\"", ",", "\"delete\"", "]", ")", "if", "request_type", "not", "in", "request_type_methods", ":", "raise", "Exception", "(", "\"Unknown request type. Supported request types are\"", "\": {0}\"", ".", "format", "(", "\", \"", ".", "join", "(", "request_type_methods", ")", ")", ")", "uri", "=", "\"{0}{1}{2}\"", ".", "format", "(", "self", ".", "uri_prefix", ",", "self", ".", "domain", ",", "resource", ")", "# set a timeout, just to be safe", "kwargs", "[", "\"timeout\"", "]", "=", "self", ".", "timeout", "response", "=", "getattr", "(", "self", ".", "session", ",", "request_type", ")", "(", "uri", ",", "*", "*", "kwargs", ")", "# handle errors", "if", "response", ".", "status_code", "not", "in", "(", "200", ",", "202", ")", ":", "_raise_for_status", "(", "response", ")", "# when responses have no content body (ie. delete, set_permission),", "# simply return the whole response", "if", "not", "response", ".", "text", ":", "return", "response", "# for other request types, return most useful data", "content_type", "=", "response", ".", "headers", ".", "get", "(", "'content-type'", ")", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "re", ".", "match", "(", "r'application\\/json'", ",", "content_type", ")", ":", "return", "response", ".", "json", "(", ")", "elif", "re", ".", "match", "(", "r'text\\/csv'", ",", "content_type", ")", ":", "csv_stream", "=", "StringIO", "(", "response", ".", "text", ")", "return", "[", "line", "for", "line", "in", "csv", ".", "reader", "(", "csv_stream", ")", "]", "elif", "re", ".", "match", "(", "r'application\\/rdf\\+xml'", ",", "content_type", ")", ":", "return", "response", ".", "content", "elif", "re", ".", "match", "(", "r'text\\/plain'", ",", "content_type", ")", ":", "try", ":", "return", "json", ".", "loads", "(", "response", ".", "text", ")", "except", "ValueError", ":", "return", "response", ".", "text", "else", ":", "raise", "Exception", "(", "\"Unknown response format: {0}\"", ".", "format", "(", "content_type", ")", ")" ]
Utility method that performs all requests.
[ "Utility", "method", "that", "performs", "all", "requests", "." ]
dad2ca9560cde0acb03bdb4423260e891ca40d7b
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L459-L500
6,565
ElsevierDev/elsapy
elsapy/elsclient.py
ElsClient.exec_request
def exec_request(self, URL): """Sends the actual request; returns response.""" ## Throttle request, if need be interval = time.time() - self.__ts_last_req if (interval < self.__min_req_interval): time.sleep( self.__min_req_interval - interval ) ## Construct and execute request headers = { "X-ELS-APIKey" : self.api_key, "User-Agent" : self.__user_agent, "Accept" : 'application/json' } if self.inst_token: headers["X-ELS-Insttoken"] = self.inst_token logger.info('Sending GET request to ' + URL) r = requests.get( URL, headers = headers ) self.__ts_last_req = time.time() self._status_code=r.status_code if r.status_code == 200: self._status_msg='data retrieved' return json.loads(r.text) else: self._status_msg="HTTP " + str(r.status_code) + " Error from " + URL + " and using headers " + str(headers) + ": " + r.text raise requests.HTTPError("HTTP " + str(r.status_code) + " Error from " + URL + "\nand using headers " + str(headers) + ":\n" + r.text)
python
def exec_request(self, URL): """Sends the actual request; returns response.""" ## Throttle request, if need be interval = time.time() - self.__ts_last_req if (interval < self.__min_req_interval): time.sleep( self.__min_req_interval - interval ) ## Construct and execute request headers = { "X-ELS-APIKey" : self.api_key, "User-Agent" : self.__user_agent, "Accept" : 'application/json' } if self.inst_token: headers["X-ELS-Insttoken"] = self.inst_token logger.info('Sending GET request to ' + URL) r = requests.get( URL, headers = headers ) self.__ts_last_req = time.time() self._status_code=r.status_code if r.status_code == 200: self._status_msg='data retrieved' return json.loads(r.text) else: self._status_msg="HTTP " + str(r.status_code) + " Error from " + URL + " and using headers " + str(headers) + ": " + r.text raise requests.HTTPError("HTTP " + str(r.status_code) + " Error from " + URL + "\nand using headers " + str(headers) + ":\n" + r.text)
[ "def", "exec_request", "(", "self", ",", "URL", ")", ":", "## Throttle request, if need be", "interval", "=", "time", ".", "time", "(", ")", "-", "self", ".", "__ts_last_req", "if", "(", "interval", "<", "self", ".", "__min_req_interval", ")", ":", "time", ".", "sleep", "(", "self", ".", "__min_req_interval", "-", "interval", ")", "## Construct and execute request", "headers", "=", "{", "\"X-ELS-APIKey\"", ":", "self", ".", "api_key", ",", "\"User-Agent\"", ":", "self", ".", "__user_agent", ",", "\"Accept\"", ":", "'application/json'", "}", "if", "self", ".", "inst_token", ":", "headers", "[", "\"X-ELS-Insttoken\"", "]", "=", "self", ".", "inst_token", "logger", ".", "info", "(", "'Sending GET request to '", "+", "URL", ")", "r", "=", "requests", ".", "get", "(", "URL", ",", "headers", "=", "headers", ")", "self", ".", "__ts_last_req", "=", "time", ".", "time", "(", ")", "self", ".", "_status_code", "=", "r", ".", "status_code", "if", "r", ".", "status_code", "==", "200", ":", "self", ".", "_status_msg", "=", "'data retrieved'", "return", "json", ".", "loads", "(", "r", ".", "text", ")", "else", ":", "self", ".", "_status_msg", "=", "\"HTTP \"", "+", "str", "(", "r", ".", "status_code", ")", "+", "\" Error from \"", "+", "URL", "+", "\" and using headers \"", "+", "str", "(", "headers", ")", "+", "\": \"", "+", "r", ".", "text", "raise", "requests", ".", "HTTPError", "(", "\"HTTP \"", "+", "str", "(", "r", ".", "status_code", ")", "+", "\" Error from \"", "+", "URL", "+", "\"\\nand using headers \"", "+", "str", "(", "headers", ")", "+", "\":\\n\"", "+", "r", ".", "text", ")" ]
Sends the actual request; returns response.
[ "Sends", "the", "actual", "request", ";", "returns", "response", "." ]
a8a8b043816441e3ed0c834e792f7089231092da
https://github.com/ElsevierDev/elsapy/blob/a8a8b043816441e3ed0c834e792f7089231092da/elsapy/elsclient.py#L91-L119
6,566
ElsevierDev/elsapy
elsapy/elsentity.py
ElsEntity.write
def write(self): """If data exists for the entity, writes it to disk as a .JSON file with the url-encoded URI as the filename and returns True. Else, returns False.""" if (self.data): dataPath = self.client.local_dir / (urllib.parse.quote_plus(self.uri)+'.json') with dataPath.open(mode='w') as dump_file: json.dump(self.data, dump_file) dump_file.close() logger.info('Wrote ' + self.uri + ' to file') return True else: logger.warning('No data to write for ' + self.uri) return False
python
def write(self): """If data exists for the entity, writes it to disk as a .JSON file with the url-encoded URI as the filename and returns True. Else, returns False.""" if (self.data): dataPath = self.client.local_dir / (urllib.parse.quote_plus(self.uri)+'.json') with dataPath.open(mode='w') as dump_file: json.dump(self.data, dump_file) dump_file.close() logger.info('Wrote ' + self.uri + ' to file') return True else: logger.warning('No data to write for ' + self.uri) return False
[ "def", "write", "(", "self", ")", ":", "if", "(", "self", ".", "data", ")", ":", "dataPath", "=", "self", ".", "client", ".", "local_dir", "/", "(", "urllib", ".", "parse", ".", "quote_plus", "(", "self", ".", "uri", ")", "+", "'.json'", ")", "with", "dataPath", ".", "open", "(", "mode", "=", "'w'", ")", "as", "dump_file", ":", "json", ".", "dump", "(", "self", ".", "data", ",", "dump_file", ")", "dump_file", ".", "close", "(", ")", "logger", ".", "info", "(", "'Wrote '", "+", "self", ".", "uri", "+", "' to file'", ")", "return", "True", "else", ":", "logger", ".", "warning", "(", "'No data to write for '", "+", "self", ".", "uri", ")", "return", "False" ]
If data exists for the entity, writes it to disk as a .JSON file with the url-encoded URI as the filename and returns True. Else, returns False.
[ "If", "data", "exists", "for", "the", "entity", "writes", "it", "to", "disk", "as", "a", ".", "JSON", "file", "with", "the", "url", "-", "encoded", "URI", "as", "the", "filename", "and", "returns", "True", ".", "Else", "returns", "False", "." ]
a8a8b043816441e3ed0c834e792f7089231092da
https://github.com/ElsevierDev/elsapy/blob/a8a8b043816441e3ed0c834e792f7089231092da/elsapy/elsentity.py#L84-L97
6,567
ElsevierDev/elsapy
elsapy/elsprofile.py
ElsProfile.write_docs
def write_docs(self): """If a doclist exists for the entity, writes it to disk as a .JSON file with the url-encoded URI as the filename and returns True. Else, returns False.""" if self.doc_list: dataPath = self.client.local_dir dump_file = open('data/' + urllib.parse.quote_plus(self.uri+'?view=documents') + '.json', mode='w' ) dump_file.write('[' + json.dumps(self.doc_list[0])) for i in range (1, len(self.doc_list)): dump_file.write(',' + json.dumps(self.doc_list[i])) dump_file.write(']') dump_file.close() logger.info('Wrote ' + self.uri + '?view=documents to file') return True else: logger.warning('No doclist to write for ' + self.uri) return False
python
def write_docs(self): """If a doclist exists for the entity, writes it to disk as a .JSON file with the url-encoded URI as the filename and returns True. Else, returns False.""" if self.doc_list: dataPath = self.client.local_dir dump_file = open('data/' + urllib.parse.quote_plus(self.uri+'?view=documents') + '.json', mode='w' ) dump_file.write('[' + json.dumps(self.doc_list[0])) for i in range (1, len(self.doc_list)): dump_file.write(',' + json.dumps(self.doc_list[i])) dump_file.write(']') dump_file.close() logger.info('Wrote ' + self.uri + '?view=documents to file') return True else: logger.warning('No doclist to write for ' + self.uri) return False
[ "def", "write_docs", "(", "self", ")", ":", "if", "self", ".", "doc_list", ":", "dataPath", "=", "self", ".", "client", ".", "local_dir", "dump_file", "=", "open", "(", "'data/'", "+", "urllib", ".", "parse", ".", "quote_plus", "(", "self", ".", "uri", "+", "'?view=documents'", ")", "+", "'.json'", ",", "mode", "=", "'w'", ")", "dump_file", ".", "write", "(", "'['", "+", "json", ".", "dumps", "(", "self", ".", "doc_list", "[", "0", "]", ")", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "self", ".", "doc_list", ")", ")", ":", "dump_file", ".", "write", "(", "','", "+", "json", ".", "dumps", "(", "self", ".", "doc_list", "[", "i", "]", ")", ")", "dump_file", ".", "write", "(", "']'", ")", "dump_file", ".", "close", "(", ")", "logger", ".", "info", "(", "'Wrote '", "+", "self", ".", "uri", "+", "'?view=documents to file'", ")", "return", "True", "else", ":", "logger", ".", "warning", "(", "'No doclist to write for '", "+", "self", ".", "uri", ")", "return", "False" ]
If a doclist exists for the entity, writes it to disk as a .JSON file with the url-encoded URI as the filename and returns True. Else, returns False.
[ "If", "a", "doclist", "exists", "for", "the", "entity", "writes", "it", "to", "disk", "as", "a", ".", "JSON", "file", "with", "the", "url", "-", "encoded", "URI", "as", "the", "filename", "and", "returns", "True", ".", "Else", "returns", "False", "." ]
a8a8b043816441e3ed0c834e792f7089231092da
https://github.com/ElsevierDev/elsapy/blob/a8a8b043816441e3ed0c834e792f7089231092da/elsapy/elsprofile.py#L66-L85
6,568
ElsevierDev/elsapy
elsapy/elsprofile.py
ElsAuthor.read
def read(self, els_client = None): """Reads the JSON representation of the author from ELSAPI. Returns True if successful; else, False.""" if ElsProfile.read(self, self.__payload_type, els_client): return True else: return False
python
def read(self, els_client = None): """Reads the JSON representation of the author from ELSAPI. Returns True if successful; else, False.""" if ElsProfile.read(self, self.__payload_type, els_client): return True else: return False
[ "def", "read", "(", "self", ",", "els_client", "=", "None", ")", ":", "if", "ElsProfile", ".", "read", "(", "self", ",", "self", ".", "__payload_type", ",", "els_client", ")", ":", "return", "True", "else", ":", "return", "False" ]
Reads the JSON representation of the author from ELSAPI. Returns True if successful; else, False.
[ "Reads", "the", "JSON", "representation", "of", "the", "author", "from", "ELSAPI", ".", "Returns", "True", "if", "successful", ";", "else", "False", "." ]
a8a8b043816441e3ed0c834e792f7089231092da
https://github.com/ElsevierDev/elsapy/blob/a8a8b043816441e3ed0c834e792f7089231092da/elsapy/elsprofile.py#L124-L130
6,569
ElsevierDev/elsapy
elsapy/elsdoc.py
FullDoc.read
def read(self, els_client = None): """Reads the JSON representation of the document from ELSAPI. Returns True if successful; else, False.""" if super().read(self.__payload_type, els_client): return True else: return False
python
def read(self, els_client = None): """Reads the JSON representation of the document from ELSAPI. Returns True if successful; else, False.""" if super().read(self.__payload_type, els_client): return True else: return False
[ "def", "read", "(", "self", ",", "els_client", "=", "None", ")", ":", "if", "super", "(", ")", ".", "read", "(", "self", ".", "__payload_type", ",", "els_client", ")", ":", "return", "True", "else", ":", "return", "False" ]
Reads the JSON representation of the document from ELSAPI. Returns True if successful; else, False.
[ "Reads", "the", "JSON", "representation", "of", "the", "document", "from", "ELSAPI", ".", "Returns", "True", "if", "successful", ";", "else", "False", "." ]
a8a8b043816441e3ed0c834e792f7089231092da
https://github.com/ElsevierDev/elsapy/blob/a8a8b043816441e3ed0c834e792f7089231092da/elsapy/elsdoc.py#L44-L50
6,570
althonos/pronto
pronto/parser/owl.py
OwlXMLParser._extract_obo_synonyms
def _extract_obo_synonyms(rawterm): """Extract the synonyms defined in the rawterm. """ synonyms = set() # keys in rawterm that define a synonym keys = set(owl_synonyms).intersection(rawterm.keys()) for k in keys: for s in rawterm[k]: synonyms.add(Synonym(s, owl_synonyms[k])) return synonyms
python
def _extract_obo_synonyms(rawterm): """Extract the synonyms defined in the rawterm. """ synonyms = set() # keys in rawterm that define a synonym keys = set(owl_synonyms).intersection(rawterm.keys()) for k in keys: for s in rawterm[k]: synonyms.add(Synonym(s, owl_synonyms[k])) return synonyms
[ "def", "_extract_obo_synonyms", "(", "rawterm", ")", ":", "synonyms", "=", "set", "(", ")", "# keys in rawterm that define a synonym", "keys", "=", "set", "(", "owl_synonyms", ")", ".", "intersection", "(", "rawterm", ".", "keys", "(", ")", ")", "for", "k", "in", "keys", ":", "for", "s", "in", "rawterm", "[", "k", "]", ":", "synonyms", ".", "add", "(", "Synonym", "(", "s", ",", "owl_synonyms", "[", "k", "]", ")", ")", "return", "synonyms" ]
Extract the synonyms defined in the rawterm.
[ "Extract", "the", "synonyms", "defined", "in", "the", "rawterm", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/parser/owl.py#L152-L161
6,571
althonos/pronto
pronto/parser/owl.py
OwlXMLParser._extract_obo_relation
def _extract_obo_relation(cls, rawterm): """Extract the relationships defined in the rawterm. """ relations = {} if 'subClassOf' in rawterm: relations[Relationship('is_a')] = l = [] l.extend(map(cls._get_id_from_url, rawterm.pop('subClassOf'))) return relations
python
def _extract_obo_relation(cls, rawterm): """Extract the relationships defined in the rawterm. """ relations = {} if 'subClassOf' in rawterm: relations[Relationship('is_a')] = l = [] l.extend(map(cls._get_id_from_url, rawterm.pop('subClassOf'))) return relations
[ "def", "_extract_obo_relation", "(", "cls", ",", "rawterm", ")", ":", "relations", "=", "{", "}", "if", "'subClassOf'", "in", "rawterm", ":", "relations", "[", "Relationship", "(", "'is_a'", ")", "]", "=", "l", "=", "[", "]", "l", ".", "extend", "(", "map", "(", "cls", ".", "_get_id_from_url", ",", "rawterm", ".", "pop", "(", "'subClassOf'", ")", ")", ")", "return", "relations" ]
Extract the relationships defined in the rawterm.
[ "Extract", "the", "relationships", "defined", "in", "the", "rawterm", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/parser/owl.py#L164-L171
6,572
althonos/pronto
pronto/parser/owl.py
OwlXMLParser._relabel_to_obo
def _relabel_to_obo(d): """Change the keys of ``d`` to use Obo labels. """ return { owl_to_obo.get(old_k, old_k): old_v for old_k, old_v in six.iteritems(d) }
python
def _relabel_to_obo(d): """Change the keys of ``d`` to use Obo labels. """ return { owl_to_obo.get(old_k, old_k): old_v for old_k, old_v in six.iteritems(d) }
[ "def", "_relabel_to_obo", "(", "d", ")", ":", "return", "{", "owl_to_obo", ".", "get", "(", "old_k", ",", "old_k", ")", ":", "old_v", "for", "old_k", ",", "old_v", "in", "six", ".", "iteritems", "(", "d", ")", "}" ]
Change the keys of ``d`` to use Obo labels.
[ "Change", "the", "keys", "of", "d", "to", "use", "Obo", "labels", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/parser/owl.py#L174-L180
6,573
althonos/pronto
pronto/relationship.py
Relationship.complement
def complement(self): """Return the complementary relationship of self. Raises: ValueError: if the relationship has a complementary which was not defined. Returns: complementary (Relationship): the complementary relationship. Example: >>> from pronto.relationship import Relationship >>> print(Relationship('has_part').complement()) Relationship('part_of') >>> print(Relationship('has_units').complement()) None """ if self.complementary: #if self.complementary in self._instances.keys(): try: return self._instances[self.complementary] except KeyError: raise ValueError('{} has a complementary but it was not defined !') else: return None
python
def complement(self): """Return the complementary relationship of self. Raises: ValueError: if the relationship has a complementary which was not defined. Returns: complementary (Relationship): the complementary relationship. Example: >>> from pronto.relationship import Relationship >>> print(Relationship('has_part').complement()) Relationship('part_of') >>> print(Relationship('has_units').complement()) None """ if self.complementary: #if self.complementary in self._instances.keys(): try: return self._instances[self.complementary] except KeyError: raise ValueError('{} has a complementary but it was not defined !') else: return None
[ "def", "complement", "(", "self", ")", ":", "if", "self", ".", "complementary", ":", "#if self.complementary in self._instances.keys():", "try", ":", "return", "self", ".", "_instances", "[", "self", ".", "complementary", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'{} has a complementary but it was not defined !'", ")", "else", ":", "return", "None" ]
Return the complementary relationship of self. Raises: ValueError: if the relationship has a complementary which was not defined. Returns: complementary (Relationship): the complementary relationship. Example: >>> from pronto.relationship import Relationship >>> print(Relationship('has_part').complement()) Relationship('part_of') >>> print(Relationship('has_units').complement()) None
[ "Return", "the", "complementary", "relationship", "of", "self", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/relationship.py#L113-L141
6,574
althonos/pronto
pronto/relationship.py
Relationship.topdown
def topdown(cls): """Get all topdown `Relationship` instances. Returns: :obj:`generator` Example: >>> from pronto import Relationship >>> for r in Relationship.topdown(): ... print(r) Relationship('can_be') Relationship('has_part') """ return tuple(unique_everseen(r for r in cls._instances.values() if r.direction=='topdown'))
python
def topdown(cls): """Get all topdown `Relationship` instances. Returns: :obj:`generator` Example: >>> from pronto import Relationship >>> for r in Relationship.topdown(): ... print(r) Relationship('can_be') Relationship('has_part') """ return tuple(unique_everseen(r for r in cls._instances.values() if r.direction=='topdown'))
[ "def", "topdown", "(", "cls", ")", ":", "return", "tuple", "(", "unique_everseen", "(", "r", "for", "r", "in", "cls", ".", "_instances", ".", "values", "(", ")", "if", "r", ".", "direction", "==", "'topdown'", ")", ")" ]
Get all topdown `Relationship` instances. Returns: :obj:`generator` Example: >>> from pronto import Relationship >>> for r in Relationship.topdown(): ... print(r) Relationship('can_be') Relationship('has_part')
[ "Get", "all", "topdown", "Relationship", "instances", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/relationship.py#L174-L189
6,575
althonos/pronto
pronto/relationship.py
Relationship.bottomup
def bottomup(cls): """Get all bottomup `Relationship` instances. Example: >>> from pronto import Relationship >>> for r in Relationship.bottomup(): ... print(r) Relationship('is_a') Relationship('part_of') Relationship('develops_from') """ return tuple(unique_everseen(r for r in cls._instances.values() if r.direction=='bottomup'))
python
def bottomup(cls): """Get all bottomup `Relationship` instances. Example: >>> from pronto import Relationship >>> for r in Relationship.bottomup(): ... print(r) Relationship('is_a') Relationship('part_of') Relationship('develops_from') """ return tuple(unique_everseen(r for r in cls._instances.values() if r.direction=='bottomup'))
[ "def", "bottomup", "(", "cls", ")", ":", "return", "tuple", "(", "unique_everseen", "(", "r", "for", "r", "in", "cls", ".", "_instances", ".", "values", "(", ")", "if", "r", ".", "direction", "==", "'bottomup'", ")", ")" ]
Get all bottomup `Relationship` instances. Example: >>> from pronto import Relationship >>> for r in Relationship.bottomup(): ... print(r) Relationship('is_a') Relationship('part_of') Relationship('develops_from')
[ "Get", "all", "bottomup", "Relationship", "instances", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/relationship.py#L192-L205
6,576
althonos/pronto
pronto/utils.py
unique_everseen
def unique_everseen(iterable): """List unique elements, preserving order. Remember all elements ever seen.""" # unique_everseen('AAAABBBCCDAABBB') --> A B C D seen = set() seen_add = seen.add for element in six.moves.filterfalse(seen.__contains__, iterable): seen_add(element) yield element
python
def unique_everseen(iterable): """List unique elements, preserving order. Remember all elements ever seen.""" # unique_everseen('AAAABBBCCDAABBB') --> A B C D seen = set() seen_add = seen.add for element in six.moves.filterfalse(seen.__contains__, iterable): seen_add(element) yield element
[ "def", "unique_everseen", "(", "iterable", ")", ":", "# unique_everseen('AAAABBBCCDAABBB') --> A B C D", "seen", "=", "set", "(", ")", "seen_add", "=", "seen", ".", "add", "for", "element", "in", "six", ".", "moves", ".", "filterfalse", "(", "seen", ".", "__contains__", ",", "iterable", ")", ":", "seen_add", "(", "element", ")", "yield", "element" ]
List unique elements, preserving order. Remember all elements ever seen.
[ "List", "unique", "elements", "preserving", "order", ".", "Remember", "all", "elements", "ever", "seen", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/utils.py#L30-L38
6,577
althonos/pronto
pronto/utils.py
output_str
def output_str(f): """Create a function that always return instances of `str`. This decorator is useful when the returned string is to be used with libraries that do not support ̀`unicode` in Python 2, but work fine with Python 3 `str` objects. """ if six.PY2: #@functools.wraps(f) def new_f(*args, **kwargs): return f(*args, **kwargs).encode("utf-8") else: new_f = f return new_f
python
def output_str(f): """Create a function that always return instances of `str`. This decorator is useful when the returned string is to be used with libraries that do not support ̀`unicode` in Python 2, but work fine with Python 3 `str` objects. """ if six.PY2: #@functools.wraps(f) def new_f(*args, **kwargs): return f(*args, **kwargs).encode("utf-8") else: new_f = f return new_f
[ "def", "output_str", "(", "f", ")", ":", "if", "six", ".", "PY2", ":", "#@functools.wraps(f)", "def", "new_f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ".", "encode", "(", "\"utf-8\"", ")", "else", ":", "new_f", "=", "f", "return", "new_f" ]
Create a function that always return instances of `str`. This decorator is useful when the returned string is to be used with libraries that do not support ̀`unicode` in Python 2, but work fine with Python 3 `str` objects.
[ "Create", "a", "function", "that", "always", "return", "instances", "of", "str", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/utils.py#L40-L53
6,578
althonos/pronto
pronto/utils.py
nowarnings
def nowarnings(func): """Create a function wrapped in a context that ignores warnings. """ @functools.wraps(func) def new_func(*args, **kwargs): with warnings.catch_warnings(): warnings.simplefilter('ignore') return func(*args, **kwargs) return new_func
python
def nowarnings(func): """Create a function wrapped in a context that ignores warnings. """ @functools.wraps(func) def new_func(*args, **kwargs): with warnings.catch_warnings(): warnings.simplefilter('ignore') return func(*args, **kwargs) return new_func
[ "def", "nowarnings", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "'ignore'", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_func" ]
Create a function wrapped in a context that ignores warnings.
[ "Create", "a", "function", "wrapped", "in", "a", "context", "that", "ignores", "warnings", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/utils.py#L55-L63
6,579
althonos/pronto
pronto/ontology.py
Ontology.parse
def parse(self, stream, parser=None): """Parse the given file using available `BaseParser` instances. Raises: TypeError: when the parser argument is not a string or None. ValueError: when the parser argument is a string that does not name a `BaseParser`. """ force, parsers = self._get_parsers(parser) try: stream.seek(0) lookup = stream.read(1024) stream.seek(0) except (io.UnsupportedOperation, AttributeError): lookup = None for p in parsers: if p.hook(path=self.path, force=force, lookup=lookup): self.meta, self.terms, self.imports, self.typedefs = p.parse(stream) self._parsed_by = p.__name__ break
python
def parse(self, stream, parser=None): """Parse the given file using available `BaseParser` instances. Raises: TypeError: when the parser argument is not a string or None. ValueError: when the parser argument is a string that does not name a `BaseParser`. """ force, parsers = self._get_parsers(parser) try: stream.seek(0) lookup = stream.read(1024) stream.seek(0) except (io.UnsupportedOperation, AttributeError): lookup = None for p in parsers: if p.hook(path=self.path, force=force, lookup=lookup): self.meta, self.terms, self.imports, self.typedefs = p.parse(stream) self._parsed_by = p.__name__ break
[ "def", "parse", "(", "self", ",", "stream", ",", "parser", "=", "None", ")", ":", "force", ",", "parsers", "=", "self", ".", "_get_parsers", "(", "parser", ")", "try", ":", "stream", ".", "seek", "(", "0", ")", "lookup", "=", "stream", ".", "read", "(", "1024", ")", "stream", ".", "seek", "(", "0", ")", "except", "(", "io", ".", "UnsupportedOperation", ",", "AttributeError", ")", ":", "lookup", "=", "None", "for", "p", "in", "parsers", ":", "if", "p", ".", "hook", "(", "path", "=", "self", ".", "path", ",", "force", "=", "force", ",", "lookup", "=", "lookup", ")", ":", "self", ".", "meta", ",", "self", ".", "terms", ",", "self", ".", "imports", ",", "self", ".", "typedefs", "=", "p", ".", "parse", "(", "stream", ")", "self", ".", "_parsed_by", "=", "p", ".", "__name__", "break" ]
Parse the given file using available `BaseParser` instances. Raises: TypeError: when the parser argument is not a string or None. ValueError: when the parser argument is a string that does not name a `BaseParser`.
[ "Parse", "the", "given", "file", "using", "available", "BaseParser", "instances", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/ontology.py#L204-L226
6,580
althonos/pronto
pronto/ontology.py
Ontology._get_parsers
def _get_parsers(self, name): """Return the appropriate parser asked by the user. Todo: Change `Ontology._get_parsers` behaviour to look for parsers through a setuptools entrypoint instead of mere subclasses. """ parserlist = BaseParser.__subclasses__() forced = name is None if isinstance(name, (six.text_type, six.binary_type)): parserlist = [p for p in parserlist if p.__name__ == name] if not parserlist: raise ValueError("could not find parser: {}".format(name)) elif name is not None: raise TypeError("parser must be {types} or None, not {actual}".format( types=" or ".join([six.text_type.__name__, six.binary_type.__name__]), actual=type(parser).__name__, )) return not forced, parserlist
python
def _get_parsers(self, name): """Return the appropriate parser asked by the user. Todo: Change `Ontology._get_parsers` behaviour to look for parsers through a setuptools entrypoint instead of mere subclasses. """ parserlist = BaseParser.__subclasses__() forced = name is None if isinstance(name, (six.text_type, six.binary_type)): parserlist = [p for p in parserlist if p.__name__ == name] if not parserlist: raise ValueError("could not find parser: {}".format(name)) elif name is not None: raise TypeError("parser must be {types} or None, not {actual}".format( types=" or ".join([six.text_type.__name__, six.binary_type.__name__]), actual=type(parser).__name__, )) return not forced, parserlist
[ "def", "_get_parsers", "(", "self", ",", "name", ")", ":", "parserlist", "=", "BaseParser", ".", "__subclasses__", "(", ")", "forced", "=", "name", "is", "None", "if", "isinstance", "(", "name", ",", "(", "six", ".", "text_type", ",", "six", ".", "binary_type", ")", ")", ":", "parserlist", "=", "[", "p", "for", "p", "in", "parserlist", "if", "p", ".", "__name__", "==", "name", "]", "if", "not", "parserlist", ":", "raise", "ValueError", "(", "\"could not find parser: {}\"", ".", "format", "(", "name", ")", ")", "elif", "name", "is", "not", "None", ":", "raise", "TypeError", "(", "\"parser must be {types} or None, not {actual}\"", ".", "format", "(", "types", "=", "\" or \"", ".", "join", "(", "[", "six", ".", "text_type", ".", "__name__", ",", "six", ".", "binary_type", ".", "__name__", "]", ")", ",", "actual", "=", "type", "(", "parser", ")", ".", "__name__", ",", ")", ")", "return", "not", "forced", ",", "parserlist" ]
Return the appropriate parser asked by the user. Todo: Change `Ontology._get_parsers` behaviour to look for parsers through a setuptools entrypoint instead of mere subclasses.
[ "Return", "the", "appropriate", "parser", "asked", "by", "the", "user", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/ontology.py#L228-L250
6,581
althonos/pronto
pronto/ontology.py
Ontology.adopt
def adopt(self): """Make terms aware of their children. This is done automatically when using the `~Ontology.merge` and `~Ontology.include` methods as well as the `~Ontology.__init__` method, but it should be called in case of manual editing of the parents or children of a `Term`. """ valid_relationships = set(Relationship._instances.keys()) relationships = [ (parent, relation.complement(), term.id) for term in six.itervalues(self.terms) for relation in term.relations for parent in term.relations[relation] if relation.complementary and relation.complementary in valid_relationships ] relationships.sort(key=operator.itemgetter(2)) for parent, rel, child in relationships: if rel is None: break try: parent = parent.id except AttributeError: pass if parent in self.terms: try: if child not in self.terms[parent].relations[rel]: self.terms[parent].relations[rel].append(child) except KeyError: self[parent].relations[rel] = [child] del relationships
python
def adopt(self): """Make terms aware of their children. This is done automatically when using the `~Ontology.merge` and `~Ontology.include` methods as well as the `~Ontology.__init__` method, but it should be called in case of manual editing of the parents or children of a `Term`. """ valid_relationships = set(Relationship._instances.keys()) relationships = [ (parent, relation.complement(), term.id) for term in six.itervalues(self.terms) for relation in term.relations for parent in term.relations[relation] if relation.complementary and relation.complementary in valid_relationships ] relationships.sort(key=operator.itemgetter(2)) for parent, rel, child in relationships: if rel is None: break try: parent = parent.id except AttributeError: pass if parent in self.terms: try: if child not in self.terms[parent].relations[rel]: self.terms[parent].relations[rel].append(child) except KeyError: self[parent].relations[rel] = [child] del relationships
[ "def", "adopt", "(", "self", ")", ":", "valid_relationships", "=", "set", "(", "Relationship", ".", "_instances", ".", "keys", "(", ")", ")", "relationships", "=", "[", "(", "parent", ",", "relation", ".", "complement", "(", ")", ",", "term", ".", "id", ")", "for", "term", "in", "six", ".", "itervalues", "(", "self", ".", "terms", ")", "for", "relation", "in", "term", ".", "relations", "for", "parent", "in", "term", ".", "relations", "[", "relation", "]", "if", "relation", ".", "complementary", "and", "relation", ".", "complementary", "in", "valid_relationships", "]", "relationships", ".", "sort", "(", "key", "=", "operator", ".", "itemgetter", "(", "2", ")", ")", "for", "parent", ",", "rel", ",", "child", "in", "relationships", ":", "if", "rel", "is", "None", ":", "break", "try", ":", "parent", "=", "parent", ".", "id", "except", "AttributeError", ":", "pass", "if", "parent", "in", "self", ".", "terms", ":", "try", ":", "if", "child", "not", "in", "self", ".", "terms", "[", "parent", "]", ".", "relations", "[", "rel", "]", ":", "self", ".", "terms", "[", "parent", "]", ".", "relations", "[", "rel", "]", ".", "append", "(", "child", ")", "except", "KeyError", ":", "self", "[", "parent", "]", ".", "relations", "[", "rel", "]", "=", "[", "child", "]", "del", "relationships" ]
Make terms aware of their children. This is done automatically when using the `~Ontology.merge` and `~Ontology.include` methods as well as the `~Ontology.__init__` method, but it should be called in case of manual editing of the parents or children of a `Term`.
[ "Make", "terms", "aware", "of", "their", "children", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/ontology.py#L253-L292
6,582
althonos/pronto
pronto/ontology.py
Ontology.reference
def reference(self): """Make relations point to ontology terms instead of term ids. This is done automatically when using the :obj:`merge` and :obj:`include` methods as well as the :obj:`__init__` method, but it should be called in case of manual changes of the relationships of a Term. """ for termkey, termval in six.iteritems(self.terms): termval.relations.update( (relkey, TermList( (self.terms.get(x) or Term(x, '', '') if not isinstance(x, Term) else x) for x in relval )) for relkey, relval in six.iteritems(termval.relations) )
python
def reference(self): """Make relations point to ontology terms instead of term ids. This is done automatically when using the :obj:`merge` and :obj:`include` methods as well as the :obj:`__init__` method, but it should be called in case of manual changes of the relationships of a Term. """ for termkey, termval in six.iteritems(self.terms): termval.relations.update( (relkey, TermList( (self.terms.get(x) or Term(x, '', '') if not isinstance(x, Term) else x) for x in relval )) for relkey, relval in six.iteritems(termval.relations) )
[ "def", "reference", "(", "self", ")", ":", "for", "termkey", ",", "termval", "in", "six", ".", "iteritems", "(", "self", ".", "terms", ")", ":", "termval", ".", "relations", ".", "update", "(", "(", "relkey", ",", "TermList", "(", "(", "self", ".", "terms", ".", "get", "(", "x", ")", "or", "Term", "(", "x", ",", "''", ",", "''", ")", "if", "not", "isinstance", "(", "x", ",", "Term", ")", "else", "x", ")", "for", "x", "in", "relval", ")", ")", "for", "relkey", ",", "relval", "in", "six", ".", "iteritems", "(", "termval", ".", "relations", ")", ")" ]
Make relations point to ontology terms instead of term ids. This is done automatically when using the :obj:`merge` and :obj:`include` methods as well as the :obj:`__init__` method, but it should be called in case of manual changes of the relationships of a Term.
[ "Make", "relations", "point", "to", "ontology", "terms", "instead", "of", "term", "ids", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/ontology.py#L294-L307
6,583
althonos/pronto
pronto/ontology.py
Ontology.resolve_imports
def resolve_imports(self, imports, import_depth, parser=None): """Import required ontologies. """ if imports and import_depth: for i in list(self.imports): try: if os.path.exists(i) or i.startswith(('http', 'ftp')): self.merge(Ontology(i, import_depth=import_depth-1, parser=parser)) else: # try to look at neighbouring ontologies self.merge(Ontology( os.path.join(os.path.dirname(self.path), i), import_depth=import_depth-1, parser=parser)) except (IOError, OSError, URLError, HTTPError, _etree.ParseError) as e: warnings.warn("{} occured during import of " "{}".format(type(e).__name__, i), ProntoWarning)
python
def resolve_imports(self, imports, import_depth, parser=None): """Import required ontologies. """ if imports and import_depth: for i in list(self.imports): try: if os.path.exists(i) or i.startswith(('http', 'ftp')): self.merge(Ontology(i, import_depth=import_depth-1, parser=parser)) else: # try to look at neighbouring ontologies self.merge(Ontology( os.path.join(os.path.dirname(self.path), i), import_depth=import_depth-1, parser=parser)) except (IOError, OSError, URLError, HTTPError, _etree.ParseError) as e: warnings.warn("{} occured during import of " "{}".format(type(e).__name__, i), ProntoWarning)
[ "def", "resolve_imports", "(", "self", ",", "imports", ",", "import_depth", ",", "parser", "=", "None", ")", ":", "if", "imports", "and", "import_depth", ":", "for", "i", "in", "list", "(", "self", ".", "imports", ")", ":", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "i", ")", "or", "i", ".", "startswith", "(", "(", "'http'", ",", "'ftp'", ")", ")", ":", "self", ".", "merge", "(", "Ontology", "(", "i", ",", "import_depth", "=", "import_depth", "-", "1", ",", "parser", "=", "parser", ")", ")", "else", ":", "# try to look at neighbouring ontologies", "self", ".", "merge", "(", "Ontology", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "path", ")", ",", "i", ")", ",", "import_depth", "=", "import_depth", "-", "1", ",", "parser", "=", "parser", ")", ")", "except", "(", "IOError", ",", "OSError", ",", "URLError", ",", "HTTPError", ",", "_etree", ".", "ParseError", ")", "as", "e", ":", "warnings", ".", "warn", "(", "\"{} occured during import of \"", "\"{}\"", ".", "format", "(", "type", "(", "e", ")", ".", "__name__", ",", "i", ")", ",", "ProntoWarning", ")" ]
Import required ontologies.
[ "Import", "required", "ontologies", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/ontology.py#L309-L326
6,584
althonos/pronto
pronto/ontology.py
Ontology.include
def include(self, *terms): """Add new terms to the current ontology. Raises: TypeError: when the arguments is (are) neither a TermList nor a Term. Note: This will also recursively include terms in the term's relations dictionnary, but it is considered bad practice to do so. If you want to create your own ontology, you should only add an ID (such as 'ONT:001') to your terms relations, and let the Ontology link terms with each other. Examples: Create a new ontology from scratch >>> from pronto import Term, Relationship >>> t1 = Term('ONT:001','my 1st term', ... 'this is my first term') >>> t2 = Term('ONT:002', 'my 2nd term', ... 'this is my second term', ... {Relationship('part_of'): ['ONT:001']}) >>> ont = Ontology() >>> ont.include(t1, t2) >>> >>> 'ONT:002' in ont True >>> ont['ONT:001'].children [<ONT:002: my 2nd term>] """ ref_needed = False for term in terms: if isinstance(term, TermList): ref_needed = ref_needed or self._include_term_list(term) elif isinstance(term, Term): ref_needed = ref_needed or self._include_term(term) else: raise TypeError('include only accepts <Term> or <TermList> as arguments') self.adopt() self.reference()
python
def include(self, *terms): """Add new terms to the current ontology. Raises: TypeError: when the arguments is (are) neither a TermList nor a Term. Note: This will also recursively include terms in the term's relations dictionnary, but it is considered bad practice to do so. If you want to create your own ontology, you should only add an ID (such as 'ONT:001') to your terms relations, and let the Ontology link terms with each other. Examples: Create a new ontology from scratch >>> from pronto import Term, Relationship >>> t1 = Term('ONT:001','my 1st term', ... 'this is my first term') >>> t2 = Term('ONT:002', 'my 2nd term', ... 'this is my second term', ... {Relationship('part_of'): ['ONT:001']}) >>> ont = Ontology() >>> ont.include(t1, t2) >>> >>> 'ONT:002' in ont True >>> ont['ONT:001'].children [<ONT:002: my 2nd term>] """ ref_needed = False for term in terms: if isinstance(term, TermList): ref_needed = ref_needed or self._include_term_list(term) elif isinstance(term, Term): ref_needed = ref_needed or self._include_term(term) else: raise TypeError('include only accepts <Term> or <TermList> as arguments') self.adopt() self.reference()
[ "def", "include", "(", "self", ",", "*", "terms", ")", ":", "ref_needed", "=", "False", "for", "term", "in", "terms", ":", "if", "isinstance", "(", "term", ",", "TermList", ")", ":", "ref_needed", "=", "ref_needed", "or", "self", ".", "_include_term_list", "(", "term", ")", "elif", "isinstance", "(", "term", ",", "Term", ")", ":", "ref_needed", "=", "ref_needed", "or", "self", ".", "_include_term", "(", "term", ")", "else", ":", "raise", "TypeError", "(", "'include only accepts <Term> or <TermList> as arguments'", ")", "self", ".", "adopt", "(", ")", "self", ".", "reference", "(", ")" ]
Add new terms to the current ontology. Raises: TypeError: when the arguments is (are) neither a TermList nor a Term. Note: This will also recursively include terms in the term's relations dictionnary, but it is considered bad practice to do so. If you want to create your own ontology, you should only add an ID (such as 'ONT:001') to your terms relations, and let the Ontology link terms with each other. Examples: Create a new ontology from scratch >>> from pronto import Term, Relationship >>> t1 = Term('ONT:001','my 1st term', ... 'this is my first term') >>> t2 = Term('ONT:002', 'my 2nd term', ... 'this is my second term', ... {Relationship('part_of'): ['ONT:001']}) >>> ont = Ontology() >>> ont.include(t1, t2) >>> >>> 'ONT:002' in ont True >>> ont['ONT:001'].children [<ONT:002: my 2nd term>]
[ "Add", "new", "terms", "to", "the", "current", "ontology", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/ontology.py#L328-L371
6,585
althonos/pronto
pronto/ontology.py
Ontology.merge
def merge(self, other): """Merge another ontology into the current one. Raises: TypeError: When argument is not an Ontology object. Example: >>> from pronto import Ontology >>> nmr = Ontology('tests/resources/nmrCV.owl', False) >>> po = Ontology('tests/resources/po.obo.gz', False) >>> 'NMR:1000271' in nmr True >>> 'NMR:1000271' in po False >>> po.merge(nmr) >>> 'NMR:1000271' in po True """ if not isinstance(other, Ontology): raise TypeError("'merge' requires an Ontology as argument," " not {}".format(type(other))) self.terms.update(other.terms) self._empty_cache() self.adopt() self.reference()
python
def merge(self, other): """Merge another ontology into the current one. Raises: TypeError: When argument is not an Ontology object. Example: >>> from pronto import Ontology >>> nmr = Ontology('tests/resources/nmrCV.owl', False) >>> po = Ontology('tests/resources/po.obo.gz', False) >>> 'NMR:1000271' in nmr True >>> 'NMR:1000271' in po False >>> po.merge(nmr) >>> 'NMR:1000271' in po True """ if not isinstance(other, Ontology): raise TypeError("'merge' requires an Ontology as argument," " not {}".format(type(other))) self.terms.update(other.terms) self._empty_cache() self.adopt() self.reference()
[ "def", "merge", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Ontology", ")", ":", "raise", "TypeError", "(", "\"'merge' requires an Ontology as argument,\"", "\" not {}\"", ".", "format", "(", "type", "(", "other", ")", ")", ")", "self", ".", "terms", ".", "update", "(", "other", ".", "terms", ")", "self", ".", "_empty_cache", "(", ")", "self", ".", "adopt", "(", ")", "self", ".", "reference", "(", ")" ]
Merge another ontology into the current one. Raises: TypeError: When argument is not an Ontology object. Example: >>> from pronto import Ontology >>> nmr = Ontology('tests/resources/nmrCV.owl', False) >>> po = Ontology('tests/resources/po.obo.gz', False) >>> 'NMR:1000271' in nmr True >>> 'NMR:1000271' in po False >>> po.merge(nmr) >>> 'NMR:1000271' in po True
[ "Merge", "another", "ontology", "into", "the", "current", "one", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/ontology.py#L373-L399
6,586
althonos/pronto
pronto/ontology.py
Ontology._include_term_list
def _include_term_list(self, termlist): """Add terms from a TermList to the ontology. """ ref_needed = False for term in termlist: ref_needed = ref_needed or self._include_term(term) return ref_needed
python
def _include_term_list(self, termlist): """Add terms from a TermList to the ontology. """ ref_needed = False for term in termlist: ref_needed = ref_needed or self._include_term(term) return ref_needed
[ "def", "_include_term_list", "(", "self", ",", "termlist", ")", ":", "ref_needed", "=", "False", "for", "term", "in", "termlist", ":", "ref_needed", "=", "ref_needed", "or", "self", ".", "_include_term", "(", "term", ")", "return", "ref_needed" ]
Add terms from a TermList to the ontology.
[ "Add", "terms", "from", "a", "TermList", "to", "the", "ontology", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/ontology.py#L427-L433
6,587
althonos/pronto
pronto/ontology.py
Ontology._include_term
def _include_term(self, term): """Add a single term to the current ontology. It is needed to dereference any term in the term's relationship and then to build the reference again to make sure the other terms referenced in the term's relations are the one contained in the ontology (to make sure changes to one term in the ontology will be applied to every other term related to that term). """ ref_needed = False if term.relations: for k,v in six.iteritems(term.relations): for i,t in enumerate(v): #if isinstance(t, Term): try: if t.id not in self: self._include_term(t) v[i] = t.id except AttributeError: pass ref_needed = True self.terms[term.id] = term return ref_needed
python
def _include_term(self, term): """Add a single term to the current ontology. It is needed to dereference any term in the term's relationship and then to build the reference again to make sure the other terms referenced in the term's relations are the one contained in the ontology (to make sure changes to one term in the ontology will be applied to every other term related to that term). """ ref_needed = False if term.relations: for k,v in six.iteritems(term.relations): for i,t in enumerate(v): #if isinstance(t, Term): try: if t.id not in self: self._include_term(t) v[i] = t.id except AttributeError: pass ref_needed = True self.terms[term.id] = term return ref_needed
[ "def", "_include_term", "(", "self", ",", "term", ")", ":", "ref_needed", "=", "False", "if", "term", ".", "relations", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "term", ".", "relations", ")", ":", "for", "i", ",", "t", "in", "enumerate", "(", "v", ")", ":", "#if isinstance(t, Term):", "try", ":", "if", "t", ".", "id", "not", "in", "self", ":", "self", ".", "_include_term", "(", "t", ")", "v", "[", "i", "]", "=", "t", ".", "id", "except", "AttributeError", ":", "pass", "ref_needed", "=", "True", "self", ".", "terms", "[", "term", ".", "id", "]", "=", "term", "return", "ref_needed" ]
Add a single term to the current ontology. It is needed to dereference any term in the term's relationship and then to build the reference again to make sure the other terms referenced in the term's relations are the one contained in the ontology (to make sure changes to one term in the ontology will be applied to every other term related to that term).
[ "Add", "a", "single", "term", "to", "the", "current", "ontology", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/ontology.py#L435-L465
6,588
althonos/pronto
pronto/ontology.py
Ontology._empty_cache
def _empty_cache(self, termlist=None): """Empty the cache associated with each `Term` instance. This method is called when merging Ontologies or including new terms in the Ontology to make sure the cache of each term is cleaned and avoid returning wrong memoized values (such as Term.rchildren() TermLists, which get memoized for performance concerns) """ if termlist is None: for term in six.itervalues(self.terms): term._empty_cache() else: for term in termlist: try: self.terms[term.id]._empty_cache() except AttributeError: self.terms[term]._empty_cache()
python
def _empty_cache(self, termlist=None): """Empty the cache associated with each `Term` instance. This method is called when merging Ontologies or including new terms in the Ontology to make sure the cache of each term is cleaned and avoid returning wrong memoized values (such as Term.rchildren() TermLists, which get memoized for performance concerns) """ if termlist is None: for term in six.itervalues(self.terms): term._empty_cache() else: for term in termlist: try: self.terms[term.id]._empty_cache() except AttributeError: self.terms[term]._empty_cache()
[ "def", "_empty_cache", "(", "self", ",", "termlist", "=", "None", ")", ":", "if", "termlist", "is", "None", ":", "for", "term", "in", "six", ".", "itervalues", "(", "self", ".", "terms", ")", ":", "term", ".", "_empty_cache", "(", ")", "else", ":", "for", "term", "in", "termlist", ":", "try", ":", "self", ".", "terms", "[", "term", ".", "id", "]", ".", "_empty_cache", "(", ")", "except", "AttributeError", ":", "self", ".", "terms", "[", "term", "]", ".", "_empty_cache", "(", ")" ]
Empty the cache associated with each `Term` instance. This method is called when merging Ontologies or including new terms in the Ontology to make sure the cache of each term is cleaned and avoid returning wrong memoized values (such as Term.rchildren() TermLists, which get memoized for performance concerns)
[ "Empty", "the", "cache", "associated", "with", "each", "Term", "instance", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/ontology.py#L467-L484
6,589
althonos/pronto
pronto/ontology.py
Ontology._obo_meta
def _obo_meta(self): """Generate the obo metadata header and updates metadata. When called, this method will create appropriate values for the ``auto-generated-by`` and ``date`` fields. Note: Generated following specs of the unofficial format guide: ftp://ftp.geneontology.org/pub/go/www/GO.format.obo-1_4.shtml """ metatags = ( "format-version", "data-version", "date", "saved-by", "auto-generated-by", "import", "subsetdef", "synonymtypedef", "default-namespace", "namespace-id-rule", "idspace", "treat-xrefs-as-equivalent", "treat-xrefs-as-genus-differentia", "treat-xrefs-as-is_a", "remark", "ontology" ) meta = self.meta.copy() meta['auto-generated-by'] = ['pronto v{}'.format(__version__)] meta['date'] = [datetime.datetime.now().strftime('%d:%m:%Y %H:%M')] obo_meta = "\n".join( [ # official obo tags x.obo if hasattr(x, 'obo') \ else "{}: {}".format(k,x) for k in metatags[:-1] for x in meta.get(k, ()) ] + [ # eventual other metadata added to remarksmock.patch in production code "remark: {}: {}".format(k, x) for k,v in sorted(six.iteritems(meta), key=operator.itemgetter(0)) for x in v if k not in metatags ] + ( ["ontology: {}".format(x) for x in meta["ontology"]] if "ontology" in meta else ["ontology: {}".format(meta["namespace"][0].lower())] if "namespace" in meta else []) ) return obo_meta
python
def _obo_meta(self): """Generate the obo metadata header and updates metadata. When called, this method will create appropriate values for the ``auto-generated-by`` and ``date`` fields. Note: Generated following specs of the unofficial format guide: ftp://ftp.geneontology.org/pub/go/www/GO.format.obo-1_4.shtml """ metatags = ( "format-version", "data-version", "date", "saved-by", "auto-generated-by", "import", "subsetdef", "synonymtypedef", "default-namespace", "namespace-id-rule", "idspace", "treat-xrefs-as-equivalent", "treat-xrefs-as-genus-differentia", "treat-xrefs-as-is_a", "remark", "ontology" ) meta = self.meta.copy() meta['auto-generated-by'] = ['pronto v{}'.format(__version__)] meta['date'] = [datetime.datetime.now().strftime('%d:%m:%Y %H:%M')] obo_meta = "\n".join( [ # official obo tags x.obo if hasattr(x, 'obo') \ else "{}: {}".format(k,x) for k in metatags[:-1] for x in meta.get(k, ()) ] + [ # eventual other metadata added to remarksmock.patch in production code "remark: {}: {}".format(k, x) for k,v in sorted(six.iteritems(meta), key=operator.itemgetter(0)) for x in v if k not in metatags ] + ( ["ontology: {}".format(x) for x in meta["ontology"]] if "ontology" in meta else ["ontology: {}".format(meta["namespace"][0].lower())] if "namespace" in meta else []) ) return obo_meta
[ "def", "_obo_meta", "(", "self", ")", ":", "metatags", "=", "(", "\"format-version\"", ",", "\"data-version\"", ",", "\"date\"", ",", "\"saved-by\"", ",", "\"auto-generated-by\"", ",", "\"import\"", ",", "\"subsetdef\"", ",", "\"synonymtypedef\"", ",", "\"default-namespace\"", ",", "\"namespace-id-rule\"", ",", "\"idspace\"", ",", "\"treat-xrefs-as-equivalent\"", ",", "\"treat-xrefs-as-genus-differentia\"", ",", "\"treat-xrefs-as-is_a\"", ",", "\"remark\"", ",", "\"ontology\"", ")", "meta", "=", "self", ".", "meta", ".", "copy", "(", ")", "meta", "[", "'auto-generated-by'", "]", "=", "[", "'pronto v{}'", ".", "format", "(", "__version__", ")", "]", "meta", "[", "'date'", "]", "=", "[", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%d:%m:%Y %H:%M'", ")", "]", "obo_meta", "=", "\"\\n\"", ".", "join", "(", "[", "# official obo tags", "x", ".", "obo", "if", "hasattr", "(", "x", ",", "'obo'", ")", "else", "\"{}: {}\"", ".", "format", "(", "k", ",", "x", ")", "for", "k", "in", "metatags", "[", ":", "-", "1", "]", "for", "x", "in", "meta", ".", "get", "(", "k", ",", "(", ")", ")", "]", "+", "[", "# eventual other metadata added to remarksmock.patch in production code", "\"remark: {}: {}\"", ".", "format", "(", "k", ",", "x", ")", "for", "k", ",", "v", "in", "sorted", "(", "six", ".", "iteritems", "(", "meta", ")", ",", "key", "=", "operator", ".", "itemgetter", "(", "0", ")", ")", "for", "x", "in", "v", "if", "k", "not", "in", "metatags", "]", "+", "(", "[", "\"ontology: {}\"", ".", "format", "(", "x", ")", "for", "x", "in", "meta", "[", "\"ontology\"", "]", "]", "if", "\"ontology\"", "in", "meta", "else", "[", "\"ontology: {}\"", ".", "format", "(", "meta", "[", "\"namespace\"", "]", "[", "0", "]", ".", "lower", "(", ")", ")", "]", "if", "\"namespace\"", "in", "meta", "else", "[", "]", ")", ")", "return", "obo_meta" ]
Generate the obo metadata header and updates metadata. When called, this method will create appropriate values for the ``auto-generated-by`` and ``date`` fields. Note: Generated following specs of the unofficial format guide: ftp://ftp.geneontology.org/pub/go/www/GO.format.obo-1_4.shtml
[ "Generate", "the", "obo", "metadata", "header", "and", "updates", "metadata", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/ontology.py#L487-L529
6,590
althonos/pronto
pronto/term.py
Term._empty_cache
def _empty_cache(self): """Empty the cache of the Term's memoized functions. """ self._children, self._parents = None, None self._rchildren, self._rparents = {}, {}
python
def _empty_cache(self): """Empty the cache of the Term's memoized functions. """ self._children, self._parents = None, None self._rchildren, self._rparents = {}, {}
[ "def", "_empty_cache", "(", "self", ")", ":", "self", ".", "_children", ",", "self", ".", "_parents", "=", "None", ",", "None", "self", ".", "_rchildren", ",", "self", ".", "_rparents", "=", "{", "}", ",", "{", "}" ]
Empty the cache of the Term's memoized functions.
[ "Empty", "the", "cache", "of", "the", "Term", "s", "memoized", "functions", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/term.py#L250-L254
6,591
althonos/pronto
pronto/parser/obo.py
OboParser._check_section
def _check_section(line, section): """Update the section being parsed. The parser starts in the `OboSection.meta` section but once it reaches the first ``[Typedef]``, it will enter the `OboSection.typedef` section, and/or when it reaches the first ``[Term]``, it will enter the `OboSection.term` section. """ if "[Term]" in line: section = OboSection.term elif "[Typedef]" in line: section = OboSection.typedef return section
python
def _check_section(line, section): """Update the section being parsed. The parser starts in the `OboSection.meta` section but once it reaches the first ``[Typedef]``, it will enter the `OboSection.typedef` section, and/or when it reaches the first ``[Term]``, it will enter the `OboSection.term` section. """ if "[Term]" in line: section = OboSection.term elif "[Typedef]" in line: section = OboSection.typedef return section
[ "def", "_check_section", "(", "line", ",", "section", ")", ":", "if", "\"[Term]\"", "in", "line", ":", "section", "=", "OboSection", ".", "term", "elif", "\"[Typedef]\"", "in", "line", ":", "section", "=", "OboSection", ".", "typedef", "return", "section" ]
Update the section being parsed. The parser starts in the `OboSection.meta` section but once it reaches the first ``[Typedef]``, it will enter the `OboSection.typedef` section, and/or when it reaches the first ``[Term]``, it will enter the `OboSection.term` section.
[ "Update", "the", "section", "being", "parsed", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/parser/obo.py#L86-L99
6,592
althonos/pronto
pronto/parser/obo.py
OboParser._parse_metadata
def _parse_metadata(cls, line, meta, parse_remarks=True): """Parse a metadata line. The metadata is organized as a ``key: value`` statement which is split into the proper key and the proper value. Arguments: line (str): the line containing the metadata parse_remarks(bool, optional): set to `False` to avoid parsing the remarks. Note: If the line follows the following schema: ``remark: key: value``, the function will attempt to extract the proper key/value instead of leaving everything inside the remark key. This may cause issues when the line is identified as such even though the remark is simply a sentence containing a colon, such as ``remark: 090506 "Attribute"`` in Term deleted and new entries: Scan Type [...]" (found in imagingMS.obo). To prevent the splitting from happening, the text on the left of the colon must be less that *20 chars long*. """ key, value = line.split(':', 1) key, value = key.strip(), value.strip() if parse_remarks and "remark" in key: # Checking that the ':' is not if 0<value.find(': ')<20: # not too far avoid parsing a sentence try: # containing a ':' as a key: value cls._parse_metadata(value, meta, parse_remarks) # obo statement nested in a remark except ValueError: # (20 is arbitrary, it may require pass # tweaking) else: meta[key].append(value) try: syn_type_def = [] for m in meta['synonymtypedef']: if not isinstance(m, SynonymType): x = SynonymType.from_obo(m) syn_type_def.append(x) else: syn_type_def.append(m) except KeyError: pass else: meta['synonymtypedef'] = syn_type_def
python
def _parse_metadata(cls, line, meta, parse_remarks=True): """Parse a metadata line. The metadata is organized as a ``key: value`` statement which is split into the proper key and the proper value. Arguments: line (str): the line containing the metadata parse_remarks(bool, optional): set to `False` to avoid parsing the remarks. Note: If the line follows the following schema: ``remark: key: value``, the function will attempt to extract the proper key/value instead of leaving everything inside the remark key. This may cause issues when the line is identified as such even though the remark is simply a sentence containing a colon, such as ``remark: 090506 "Attribute"`` in Term deleted and new entries: Scan Type [...]" (found in imagingMS.obo). To prevent the splitting from happening, the text on the left of the colon must be less that *20 chars long*. """ key, value = line.split(':', 1) key, value = key.strip(), value.strip() if parse_remarks and "remark" in key: # Checking that the ':' is not if 0<value.find(': ')<20: # not too far avoid parsing a sentence try: # containing a ':' as a key: value cls._parse_metadata(value, meta, parse_remarks) # obo statement nested in a remark except ValueError: # (20 is arbitrary, it may require pass # tweaking) else: meta[key].append(value) try: syn_type_def = [] for m in meta['synonymtypedef']: if not isinstance(m, SynonymType): x = SynonymType.from_obo(m) syn_type_def.append(x) else: syn_type_def.append(m) except KeyError: pass else: meta['synonymtypedef'] = syn_type_def
[ "def", "_parse_metadata", "(", "cls", ",", "line", ",", "meta", ",", "parse_remarks", "=", "True", ")", ":", "key", ",", "value", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "key", ",", "value", "=", "key", ".", "strip", "(", ")", ",", "value", ".", "strip", "(", ")", "if", "parse_remarks", "and", "\"remark\"", "in", "key", ":", "# Checking that the ':' is not", "if", "0", "<", "value", ".", "find", "(", "': '", ")", "<", "20", ":", "# not too far avoid parsing a sentence", "try", ":", "# containing a ':' as a key: value", "cls", ".", "_parse_metadata", "(", "value", ",", "meta", ",", "parse_remarks", ")", "# obo statement nested in a remark", "except", "ValueError", ":", "# (20 is arbitrary, it may require", "pass", "# tweaking)", "else", ":", "meta", "[", "key", "]", ".", "append", "(", "value", ")", "try", ":", "syn_type_def", "=", "[", "]", "for", "m", "in", "meta", "[", "'synonymtypedef'", "]", ":", "if", "not", "isinstance", "(", "m", ",", "SynonymType", ")", ":", "x", "=", "SynonymType", ".", "from_obo", "(", "m", ")", "syn_type_def", ".", "append", "(", "x", ")", "else", ":", "syn_type_def", ".", "append", "(", "m", ")", "except", "KeyError", ":", "pass", "else", ":", "meta", "[", "'synonymtypedef'", "]", "=", "syn_type_def" ]
Parse a metadata line. The metadata is organized as a ``key: value`` statement which is split into the proper key and the proper value. Arguments: line (str): the line containing the metadata parse_remarks(bool, optional): set to `False` to avoid parsing the remarks. Note: If the line follows the following schema: ``remark: key: value``, the function will attempt to extract the proper key/value instead of leaving everything inside the remark key. This may cause issues when the line is identified as such even though the remark is simply a sentence containing a colon, such as ``remark: 090506 "Attribute"`` in Term deleted and new entries: Scan Type [...]" (found in imagingMS.obo). To prevent the splitting from happening, the text on the left of the colon must be less that *20 chars long*.
[ "Parse", "a", "metadata", "line", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/parser/obo.py#L102-L149
6,593
althonos/pronto
pronto/parser/obo.py
OboParser._parse_typedef
def _parse_typedef(line, _rawtypedef): """Parse a typedef line. The typedef is organized as a succesion of ``key:value`` pairs that are extracted into the same dictionnary until a new header is encountered Arguments: line (str): the line containing a typedef statement """ if "[Typedef]" in line: _rawtypedef.append(collections.defaultdict(list)) else: key, value = line.split(':', 1) _rawtypedef[-1][key.strip()].append(value.strip())
python
def _parse_typedef(line, _rawtypedef): """Parse a typedef line. The typedef is organized as a succesion of ``key:value`` pairs that are extracted into the same dictionnary until a new header is encountered Arguments: line (str): the line containing a typedef statement """ if "[Typedef]" in line: _rawtypedef.append(collections.defaultdict(list)) else: key, value = line.split(':', 1) _rawtypedef[-1][key.strip()].append(value.strip())
[ "def", "_parse_typedef", "(", "line", ",", "_rawtypedef", ")", ":", "if", "\"[Typedef]\"", "in", "line", ":", "_rawtypedef", ".", "append", "(", "collections", ".", "defaultdict", "(", "list", ")", ")", "else", ":", "key", ",", "value", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "_rawtypedef", "[", "-", "1", "]", "[", "key", ".", "strip", "(", ")", "]", ".", "append", "(", "value", ".", "strip", "(", ")", ")" ]
Parse a typedef line. The typedef is organized as a succesion of ``key:value`` pairs that are extracted into the same dictionnary until a new header is encountered Arguments: line (str): the line containing a typedef statement
[ "Parse", "a", "typedef", "line", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/parser/obo.py#L152-L166
6,594
althonos/pronto
pronto/parser/obo.py
OboParser._parse_term
def _parse_term(_rawterms): """Parse a term line. The term is organized as a succesion of ``key:value`` pairs that are extracted into the same dictionnary until a new header is encountered Arguments: line (str): the line containing a term statement """ line = yield _rawterms.append(collections.defaultdict(list)) while True: line = yield if "[Term]" in line: _rawterms.append(collections.defaultdict(list)) else: key, value = line.split(':', 1) _rawterms[-1][key.strip()].append(value.strip())
python
def _parse_term(_rawterms): """Parse a term line. The term is organized as a succesion of ``key:value`` pairs that are extracted into the same dictionnary until a new header is encountered Arguments: line (str): the line containing a term statement """ line = yield _rawterms.append(collections.defaultdict(list)) while True: line = yield if "[Term]" in line: _rawterms.append(collections.defaultdict(list)) else: key, value = line.split(':', 1) _rawterms[-1][key.strip()].append(value.strip())
[ "def", "_parse_term", "(", "_rawterms", ")", ":", "line", "=", "yield", "_rawterms", ".", "append", "(", "collections", ".", "defaultdict", "(", "list", ")", ")", "while", "True", ":", "line", "=", "yield", "if", "\"[Term]\"", "in", "line", ":", "_rawterms", ".", "append", "(", "collections", ".", "defaultdict", "(", "list", ")", ")", "else", ":", "key", ",", "value", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "_rawterms", "[", "-", "1", "]", "[", "key", ".", "strip", "(", ")", "]", ".", "append", "(", "value", ".", "strip", "(", ")", ")" ]
Parse a term line. The term is organized as a succesion of ``key:value`` pairs that are extracted into the same dictionnary until a new header is encountered Arguments: line (str): the line containing a term statement
[ "Parse", "a", "term", "line", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/parser/obo.py#L170-L188
6,595
althonos/pronto
pronto/parser/obo.py
OboParser._classify
def _classify(_rawtypedef, _rawterms): """Create proper objects out of extracted dictionnaries. New Relationship objects are instantiated with the help of the `Relationship._from_obo_dict` alternate constructor. New `Term` objects are instantiated by manually extracting id, name, desc and relationships out of the ``_rawterm`` dictionnary, and then calling the default constructor. """ terms = collections.OrderedDict() _cached_synonyms = {} typedefs = [ Relationship._from_obo_dict( # instantiate a new Relationship {k:v for k,lv in six.iteritems(_typedef) for v in lv} ) for _typedef in _rawtypedef ] for _term in _rawterms: synonyms = set() _id = _term['id'][0] _name = _term.pop('name', ('',))[0] _desc = _term.pop('def', ('',))[0] _relations = collections.defaultdict(list) try: for other in _term.get('is_a', ()): _relations[Relationship('is_a')].append(other.split('!')[0].strip()) except IndexError: pass try: for relname, other in ( x.split(' ', 1) for x in _term.pop('relationship', ())): _relations[Relationship(relname)].append(other.split('!')[0].strip()) except IndexError: pass for key, scope in six.iteritems(_obo_synonyms_map): for obo_header in _term.pop(key, ()): try: s = _cached_synonyms[obo_header] except KeyError: s = Synonym.from_obo(obo_header, scope) _cached_synonyms[obo_header] = s finally: synonyms.add(s) desc = Description.from_obo(_desc) if _desc else Description("") terms[_id] = Term(_id, _name, desc, dict(_relations), synonyms, dict(_term)) return terms, typedefs
python
def _classify(_rawtypedef, _rawterms): """Create proper objects out of extracted dictionnaries. New Relationship objects are instantiated with the help of the `Relationship._from_obo_dict` alternate constructor. New `Term` objects are instantiated by manually extracting id, name, desc and relationships out of the ``_rawterm`` dictionnary, and then calling the default constructor. """ terms = collections.OrderedDict() _cached_synonyms = {} typedefs = [ Relationship._from_obo_dict( # instantiate a new Relationship {k:v for k,lv in six.iteritems(_typedef) for v in lv} ) for _typedef in _rawtypedef ] for _term in _rawterms: synonyms = set() _id = _term['id'][0] _name = _term.pop('name', ('',))[0] _desc = _term.pop('def', ('',))[0] _relations = collections.defaultdict(list) try: for other in _term.get('is_a', ()): _relations[Relationship('is_a')].append(other.split('!')[0].strip()) except IndexError: pass try: for relname, other in ( x.split(' ', 1) for x in _term.pop('relationship', ())): _relations[Relationship(relname)].append(other.split('!')[0].strip()) except IndexError: pass for key, scope in six.iteritems(_obo_synonyms_map): for obo_header in _term.pop(key, ()): try: s = _cached_synonyms[obo_header] except KeyError: s = Synonym.from_obo(obo_header, scope) _cached_synonyms[obo_header] = s finally: synonyms.add(s) desc = Description.from_obo(_desc) if _desc else Description("") terms[_id] = Term(_id, _name, desc, dict(_relations), synonyms, dict(_term)) return terms, typedefs
[ "def", "_classify", "(", "_rawtypedef", ",", "_rawterms", ")", ":", "terms", "=", "collections", ".", "OrderedDict", "(", ")", "_cached_synonyms", "=", "{", "}", "typedefs", "=", "[", "Relationship", ".", "_from_obo_dict", "(", "# instantiate a new Relationship", "{", "k", ":", "v", "for", "k", ",", "lv", "in", "six", ".", "iteritems", "(", "_typedef", ")", "for", "v", "in", "lv", "}", ")", "for", "_typedef", "in", "_rawtypedef", "]", "for", "_term", "in", "_rawterms", ":", "synonyms", "=", "set", "(", ")", "_id", "=", "_term", "[", "'id'", "]", "[", "0", "]", "_name", "=", "_term", ".", "pop", "(", "'name'", ",", "(", "''", ",", ")", ")", "[", "0", "]", "_desc", "=", "_term", ".", "pop", "(", "'def'", ",", "(", "''", ",", ")", ")", "[", "0", "]", "_relations", "=", "collections", ".", "defaultdict", "(", "list", ")", "try", ":", "for", "other", "in", "_term", ".", "get", "(", "'is_a'", ",", "(", ")", ")", ":", "_relations", "[", "Relationship", "(", "'is_a'", ")", "]", ".", "append", "(", "other", ".", "split", "(", "'!'", ")", "[", "0", "]", ".", "strip", "(", ")", ")", "except", "IndexError", ":", "pass", "try", ":", "for", "relname", ",", "other", "in", "(", "x", ".", "split", "(", "' '", ",", "1", ")", "for", "x", "in", "_term", ".", "pop", "(", "'relationship'", ",", "(", ")", ")", ")", ":", "_relations", "[", "Relationship", "(", "relname", ")", "]", ".", "append", "(", "other", ".", "split", "(", "'!'", ")", "[", "0", "]", ".", "strip", "(", ")", ")", "except", "IndexError", ":", "pass", "for", "key", ",", "scope", "in", "six", ".", "iteritems", "(", "_obo_synonyms_map", ")", ":", "for", "obo_header", "in", "_term", ".", "pop", "(", "key", ",", "(", ")", ")", ":", "try", ":", "s", "=", "_cached_synonyms", "[", "obo_header", "]", "except", "KeyError", ":", "s", "=", "Synonym", ".", "from_obo", "(", "obo_header", ",", "scope", ")", "_cached_synonyms", "[", "obo_header", "]", "=", "s", "finally", ":", "synonyms", ".", "add", "(", "s", ")", "desc", "=", "Description", ".", "from_obo", "(", "_desc", ")", "if", "_desc", "else", "Description", "(", "\"\"", ")", "terms", "[", "_id", "]", "=", "Term", "(", "_id", ",", "_name", ",", "desc", ",", "dict", "(", "_relations", ")", ",", "synonyms", ",", "dict", "(", "_term", ")", ")", "return", "terms", ",", "typedefs" ]
Create proper objects out of extracted dictionnaries. New Relationship objects are instantiated with the help of the `Relationship._from_obo_dict` alternate constructor. New `Term` objects are instantiated by manually extracting id, name, desc and relationships out of the ``_rawterm`` dictionnary, and then calling the default constructor.
[ "Create", "proper", "objects", "out", "of", "extracted", "dictionnaries", "." ]
a768adcba19fb34f26f67cde4a03d317f932c274
https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/parser/obo.py#L192-L244
6,596
matheuscas/pycpfcnpj
pycpfcnpj/calculation.py
calculate_first_digit
def calculate_first_digit(number): """ This function calculates the first check digit of a cpf or cnpj. :param number: cpf (length 9) or cnpf (length 12) string to check the first digit. Only numbers. :type number: string :returns: string -- the first digit """ sum = 0 if len(number) == 9: weights = CPF_WEIGHTS[0] else: weights = CNPJ_WEIGHTS[0] for i in range(len(number)): sum = sum + int(number[i]) * weights[i] rest_division = sum % DIVISOR if rest_division < 2: return '0' return str(11 - rest_division)
python
def calculate_first_digit(number): """ This function calculates the first check digit of a cpf or cnpj. :param number: cpf (length 9) or cnpf (length 12) string to check the first digit. Only numbers. :type number: string :returns: string -- the first digit """ sum = 0 if len(number) == 9: weights = CPF_WEIGHTS[0] else: weights = CNPJ_WEIGHTS[0] for i in range(len(number)): sum = sum + int(number[i]) * weights[i] rest_division = sum % DIVISOR if rest_division < 2: return '0' return str(11 - rest_division)
[ "def", "calculate_first_digit", "(", "number", ")", ":", "sum", "=", "0", "if", "len", "(", "number", ")", "==", "9", ":", "weights", "=", "CPF_WEIGHTS", "[", "0", "]", "else", ":", "weights", "=", "CNPJ_WEIGHTS", "[", "0", "]", "for", "i", "in", "range", "(", "len", "(", "number", ")", ")", ":", "sum", "=", "sum", "+", "int", "(", "number", "[", "i", "]", ")", "*", "weights", "[", "i", "]", "rest_division", "=", "sum", "%", "DIVISOR", "if", "rest_division", "<", "2", ":", "return", "'0'", "return", "str", "(", "11", "-", "rest_division", ")" ]
This function calculates the first check digit of a cpf or cnpj. :param number: cpf (length 9) or cnpf (length 12) string to check the first digit. Only numbers. :type number: string :returns: string -- the first digit
[ "This", "function", "calculates", "the", "first", "check", "digit", "of", "a", "cpf", "or", "cnpj", "." ]
42f7db466280042af10e0e555cb8d2f5bb9865ee
https://github.com/matheuscas/pycpfcnpj/blob/42f7db466280042af10e0e555cb8d2f5bb9865ee/pycpfcnpj/calculation.py#L10-L32
6,597
matheuscas/pycpfcnpj
pycpfcnpj/cpfcnpj.py
validate
def validate(number): """This functions acts like a Facade to the other modules cpf and cnpj and validates either CPF and CNPJ numbers. Feel free to use this or the other modules directly. :param number: a CPF or CNPJ number. Clear number to have only numbers. :type number: string :return: Bool -- True if number is a valid CPF or CNPJ number. False if it is not or do not complain with the right size of these numbers. """ clean_number = clear_punctuation(number) if len(clean_number) == 11: return cpf.validate(clean_number) elif len(clean_number) == 14: return cnpj.validate(clean_number) return False
python
def validate(number): """This functions acts like a Facade to the other modules cpf and cnpj and validates either CPF and CNPJ numbers. Feel free to use this or the other modules directly. :param number: a CPF or CNPJ number. Clear number to have only numbers. :type number: string :return: Bool -- True if number is a valid CPF or CNPJ number. False if it is not or do not complain with the right size of these numbers. """ clean_number = clear_punctuation(number) if len(clean_number) == 11: return cpf.validate(clean_number) elif len(clean_number) == 14: return cnpj.validate(clean_number) return False
[ "def", "validate", "(", "number", ")", ":", "clean_number", "=", "clear_punctuation", "(", "number", ")", "if", "len", "(", "clean_number", ")", "==", "11", ":", "return", "cpf", ".", "validate", "(", "clean_number", ")", "elif", "len", "(", "clean_number", ")", "==", "14", ":", "return", "cnpj", ".", "validate", "(", "clean_number", ")", "return", "False" ]
This functions acts like a Facade to the other modules cpf and cnpj and validates either CPF and CNPJ numbers. Feel free to use this or the other modules directly. :param number: a CPF or CNPJ number. Clear number to have only numbers. :type number: string :return: Bool -- True if number is a valid CPF or CNPJ number. False if it is not or do not complain with the right size of these numbers.
[ "This", "functions", "acts", "like", "a", "Facade", "to", "the", "other", "modules", "cpf", "and", "cnpj", "and", "validates", "either", "CPF", "and", "CNPJ", "numbers", ".", "Feel", "free", "to", "use", "this", "or", "the", "other", "modules", "directly", "." ]
42f7db466280042af10e0e555cb8d2f5bb9865ee
https://github.com/matheuscas/pycpfcnpj/blob/42f7db466280042af10e0e555cb8d2f5bb9865ee/pycpfcnpj/cpfcnpj.py#L7-L25
6,598
matheuscas/pycpfcnpj
pycpfcnpj/cpf.py
validate
def validate(cpf_number): """This function validates a CPF number. This function uses calculation package to calculate both digits and then validates the number. :param cpf_number: a CPF number to be validated. Only numbers. :type cpf_number: string :return: Bool -- True for a valid number, False otherwise. """ _cpf = compat.clear_punctuation(cpf_number) if (len(_cpf) != 11 or len(set(_cpf)) == 1): return False first_part = _cpf[:9] second_part = _cpf[:10] first_digit = _cpf[9] second_digit = _cpf[10] if (first_digit == calc.calculate_first_digit(first_part) and second_digit == calc.calculate_second_digit(second_part)): return True return False
python
def validate(cpf_number): """This function validates a CPF number. This function uses calculation package to calculate both digits and then validates the number. :param cpf_number: a CPF number to be validated. Only numbers. :type cpf_number: string :return: Bool -- True for a valid number, False otherwise. """ _cpf = compat.clear_punctuation(cpf_number) if (len(_cpf) != 11 or len(set(_cpf)) == 1): return False first_part = _cpf[:9] second_part = _cpf[:10] first_digit = _cpf[9] second_digit = _cpf[10] if (first_digit == calc.calculate_first_digit(first_part) and second_digit == calc.calculate_second_digit(second_part)): return True return False
[ "def", "validate", "(", "cpf_number", ")", ":", "_cpf", "=", "compat", ".", "clear_punctuation", "(", "cpf_number", ")", "if", "(", "len", "(", "_cpf", ")", "!=", "11", "or", "len", "(", "set", "(", "_cpf", ")", ")", "==", "1", ")", ":", "return", "False", "first_part", "=", "_cpf", "[", ":", "9", "]", "second_part", "=", "_cpf", "[", ":", "10", "]", "first_digit", "=", "_cpf", "[", "9", "]", "second_digit", "=", "_cpf", "[", "10", "]", "if", "(", "first_digit", "==", "calc", ".", "calculate_first_digit", "(", "first_part", ")", "and", "second_digit", "==", "calc", ".", "calculate_second_digit", "(", "second_part", ")", ")", ":", "return", "True", "return", "False" ]
This function validates a CPF number. This function uses calculation package to calculate both digits and then validates the number. :param cpf_number: a CPF number to be validated. Only numbers. :type cpf_number: string :return: Bool -- True for a valid number, False otherwise.
[ "This", "function", "validates", "a", "CPF", "number", "." ]
42f7db466280042af10e0e555cb8d2f5bb9865ee
https://github.com/matheuscas/pycpfcnpj/blob/42f7db466280042af10e0e555cb8d2f5bb9865ee/pycpfcnpj/cpf.py#L5-L32
6,599
matheuscas/pycpfcnpj
pycpfcnpj/cnpj.py
validate
def validate(cnpj_number): """This function validates a CNPJ number. This function uses calculation package to calculate both digits and then validates the number. :param cnpj_number: a CNPJ number to be validated. Only numbers. :type cnpj_number: string :return: Bool -- True for a valid number, False otherwise. """ _cnpj = compat.clear_punctuation(cnpj_number) if (len(_cnpj) != 14 or len(set(_cnpj)) == 1): return False first_part = _cnpj[:12] second_part = _cnpj[:13] first_digit = _cnpj[12] second_digit = _cnpj[13] if (first_digit == calc.calculate_first_digit(first_part) and second_digit == calc.calculate_second_digit(second_part)): return True return False
python
def validate(cnpj_number): """This function validates a CNPJ number. This function uses calculation package to calculate both digits and then validates the number. :param cnpj_number: a CNPJ number to be validated. Only numbers. :type cnpj_number: string :return: Bool -- True for a valid number, False otherwise. """ _cnpj = compat.clear_punctuation(cnpj_number) if (len(_cnpj) != 14 or len(set(_cnpj)) == 1): return False first_part = _cnpj[:12] second_part = _cnpj[:13] first_digit = _cnpj[12] second_digit = _cnpj[13] if (first_digit == calc.calculate_first_digit(first_part) and second_digit == calc.calculate_second_digit(second_part)): return True return False
[ "def", "validate", "(", "cnpj_number", ")", ":", "_cnpj", "=", "compat", ".", "clear_punctuation", "(", "cnpj_number", ")", "if", "(", "len", "(", "_cnpj", ")", "!=", "14", "or", "len", "(", "set", "(", "_cnpj", ")", ")", "==", "1", ")", ":", "return", "False", "first_part", "=", "_cnpj", "[", ":", "12", "]", "second_part", "=", "_cnpj", "[", ":", "13", "]", "first_digit", "=", "_cnpj", "[", "12", "]", "second_digit", "=", "_cnpj", "[", "13", "]", "if", "(", "first_digit", "==", "calc", ".", "calculate_first_digit", "(", "first_part", ")", "and", "second_digit", "==", "calc", ".", "calculate_second_digit", "(", "second_part", ")", ")", ":", "return", "True", "return", "False" ]
This function validates a CNPJ number. This function uses calculation package to calculate both digits and then validates the number. :param cnpj_number: a CNPJ number to be validated. Only numbers. :type cnpj_number: string :return: Bool -- True for a valid number, False otherwise.
[ "This", "function", "validates", "a", "CNPJ", "number", "." ]
42f7db466280042af10e0e555cb8d2f5bb9865ee
https://github.com/matheuscas/pycpfcnpj/blob/42f7db466280042af10e0e555cb8d2f5bb9865ee/pycpfcnpj/cnpj.py#L5-L32