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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
15,700 | tjcsl/ion | intranet/apps/eighth/models.py | EighthActivity.restricted_activities_available_to_user | def restricted_activities_available_to_user(cls, user):
"""Find the restricted activities available to the given user."""
if not user:
return []
activities = set(user.restricted_activity_set.values_list("id", flat=True))
if user and user.grade and user.grade.number and user.grade.name:
grade = user.grade
else:
grade = None
if grade is not None and 9 <= grade.number <= 12:
activities |= set(EighthActivity.objects.filter(**{'{}_allowed'.format(grade.name_plural): True}).values_list("id", flat=True))
for group in user.groups.all():
activities |= set(group.restricted_activity_set.values_list("id", flat=True))
return list(activities) | python | def restricted_activities_available_to_user(cls, user):
if not user:
return []
activities = set(user.restricted_activity_set.values_list("id", flat=True))
if user and user.grade and user.grade.number and user.grade.name:
grade = user.grade
else:
grade = None
if grade is not None and 9 <= grade.number <= 12:
activities |= set(EighthActivity.objects.filter(**{'{}_allowed'.format(grade.name_plural): True}).values_list("id", flat=True))
for group in user.groups.all():
activities |= set(group.restricted_activity_set.values_list("id", flat=True))
return list(activities) | [
"def",
"restricted_activities_available_to_user",
"(",
"cls",
",",
"user",
")",
":",
"if",
"not",
"user",
":",
"return",
"[",
"]",
"activities",
"=",
"set",
"(",
"user",
".",
"restricted_activity_set",
".",
"values_list",
"(",
"\"id\"",
",",
"flat",
"=",
"Tr... | Find the restricted activities available to the given user. | [
"Find",
"the",
"restricted",
"activities",
"available",
"to",
"the",
"given",
"user",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L304-L322 |
15,701 | tjcsl/ion | intranet/apps/eighth/models.py | EighthActivity.get_active_schedulings | def get_active_schedulings(self):
"""Return EighthScheduledActivity's of this activity since the beginning of the year."""
blocks = EighthBlock.objects.get_blocks_this_year()
scheduled_activities = EighthScheduledActivity.objects.filter(activity=self)
scheduled_activities = scheduled_activities.filter(block__in=blocks)
return scheduled_activities | python | def get_active_schedulings(self):
blocks = EighthBlock.objects.get_blocks_this_year()
scheduled_activities = EighthScheduledActivity.objects.filter(activity=self)
scheduled_activities = scheduled_activities.filter(block__in=blocks)
return scheduled_activities | [
"def",
"get_active_schedulings",
"(",
"self",
")",
":",
"blocks",
"=",
"EighthBlock",
".",
"objects",
".",
"get_blocks_this_year",
"(",
")",
"scheduled_activities",
"=",
"EighthScheduledActivity",
".",
"objects",
".",
"filter",
"(",
"activity",
"=",
"self",
")",
... | Return EighthScheduledActivity's of this activity since the beginning of the year. | [
"Return",
"EighthScheduledActivity",
"s",
"of",
"this",
"activity",
"since",
"the",
"beginning",
"of",
"the",
"year",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L342-L348 |
15,702 | tjcsl/ion | intranet/apps/eighth/models.py | EighthActivity.frequent_users | def frequent_users(self):
"""Return a QuerySet of user id's and counts that have signed up for this activity more than
`settings.SIMILAR_THRESHOLD` times. This is be used for suggesting activities to users."""
key = "eighthactivity_{}:frequent_users".format(self.id)
cached = cache.get(key)
if cached:
return cached
freq_users = self.eighthscheduledactivity_set.exclude(eighthsignup_set__user=None).exclude(administrative=True).exclude(special=True).exclude(
restricted=True).values('eighthsignup_set__user').annotate(count=Count('eighthsignup_set__user')).filter(
count__gte=settings.SIMILAR_THRESHOLD).order_by('-count')
cache.set(key, freq_users, timeout=60 * 60 * 24 * 7)
return freq_users | python | def frequent_users(self):
key = "eighthactivity_{}:frequent_users".format(self.id)
cached = cache.get(key)
if cached:
return cached
freq_users = self.eighthscheduledactivity_set.exclude(eighthsignup_set__user=None).exclude(administrative=True).exclude(special=True).exclude(
restricted=True).values('eighthsignup_set__user').annotate(count=Count('eighthsignup_set__user')).filter(
count__gte=settings.SIMILAR_THRESHOLD).order_by('-count')
cache.set(key, freq_users, timeout=60 * 60 * 24 * 7)
return freq_users | [
"def",
"frequent_users",
"(",
"self",
")",
":",
"key",
"=",
"\"eighthactivity_{}:frequent_users\"",
".",
"format",
"(",
"self",
".",
"id",
")",
"cached",
"=",
"cache",
".",
"get",
"(",
"key",
")",
"if",
"cached",
":",
"return",
"cached",
"freq_users",
"=",... | Return a QuerySet of user id's and counts that have signed up for this activity more than
`settings.SIMILAR_THRESHOLD` times. This is be used for suggesting activities to users. | [
"Return",
"a",
"QuerySet",
"of",
"user",
"id",
"s",
"and",
"counts",
"that",
"have",
"signed",
"up",
"for",
"this",
"activity",
"more",
"than",
"settings",
".",
"SIMILAR_THRESHOLD",
"times",
".",
"This",
"is",
"be",
"used",
"for",
"suggesting",
"activities",... | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L358-L369 |
15,703 | tjcsl/ion | intranet/apps/eighth/models.py | EighthBlockQuerySet.this_year | def this_year(self):
""" Get EighthBlocks from this school year only. """
start_date, end_date = get_date_range_this_year()
return self.filter(date__gte=start_date, date__lte=end_date) | python | def this_year(self):
start_date, end_date = get_date_range_this_year()
return self.filter(date__gte=start_date, date__lte=end_date) | [
"def",
"this_year",
"(",
"self",
")",
":",
"start_date",
",",
"end_date",
"=",
"get_date_range_this_year",
"(",
")",
"return",
"self",
".",
"filter",
"(",
"date__gte",
"=",
"start_date",
",",
"date__lte",
"=",
"end_date",
")"
] | Get EighthBlocks from this school year only. | [
"Get",
"EighthBlocks",
"from",
"this",
"school",
"year",
"only",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L384-L387 |
15,704 | tjcsl/ion | intranet/apps/eighth/models.py | EighthBlockManager.get_blocks_this_year | def get_blocks_this_year(self):
"""Get a list of blocks that occur this school year."""
date_start, date_end = get_date_range_this_year()
return EighthBlock.objects.filter(date__gte=date_start, date__lte=date_end) | python | def get_blocks_this_year(self):
date_start, date_end = get_date_range_this_year()
return EighthBlock.objects.filter(date__gte=date_start, date__lte=date_end) | [
"def",
"get_blocks_this_year",
"(",
"self",
")",
":",
"date_start",
",",
"date_end",
"=",
"get_date_range_this_year",
"(",
")",
"return",
"EighthBlock",
".",
"objects",
".",
"filter",
"(",
"date__gte",
"=",
"date_start",
",",
"date__lte",
"=",
"date_end",
")"
] | Get a list of blocks that occur this school year. | [
"Get",
"a",
"list",
"of",
"blocks",
"that",
"occur",
"this",
"school",
"year",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L453-L458 |
15,705 | tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.save | def save(self, *args, **kwargs):
"""Capitalize the first letter of the block name."""
letter = getattr(self, "block_letter", None)
if letter and len(letter) >= 1:
self.block_letter = letter[:1].upper() + letter[1:]
super(EighthBlock, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
letter = getattr(self, "block_letter", None)
if letter and len(letter) >= 1:
self.block_letter = letter[:1].upper() + letter[1:]
super(EighthBlock, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"letter",
"=",
"getattr",
"(",
"self",
",",
"\"block_letter\"",
",",
"None",
")",
"if",
"letter",
"and",
"len",
"(",
"letter",
")",
">=",
"1",
":",
"self",
".",
"blo... | Capitalize the first letter of the block name. | [
"Capitalize",
"the",
"first",
"letter",
"of",
"the",
"block",
"name",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L505-L511 |
15,706 | tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.next_blocks | def next_blocks(self, quantity=-1):
"""Get the next blocks in order."""
blocks = (EighthBlock.objects.get_blocks_this_year().order_by(
"date", "block_letter").filter(Q(date__gt=self.date) | (Q(date=self.date) & Q(block_letter__gt=self.block_letter))))
if quantity == -1:
return blocks
return blocks[:quantity] | python | def next_blocks(self, quantity=-1):
blocks = (EighthBlock.objects.get_blocks_this_year().order_by(
"date", "block_letter").filter(Q(date__gt=self.date) | (Q(date=self.date) & Q(block_letter__gt=self.block_letter))))
if quantity == -1:
return blocks
return blocks[:quantity] | [
"def",
"next_blocks",
"(",
"self",
",",
"quantity",
"=",
"-",
"1",
")",
":",
"blocks",
"=",
"(",
"EighthBlock",
".",
"objects",
".",
"get_blocks_this_year",
"(",
")",
".",
"order_by",
"(",
"\"date\"",
",",
"\"block_letter\"",
")",
".",
"filter",
"(",
"Q"... | Get the next blocks in order. | [
"Get",
"the",
"next",
"blocks",
"in",
"order",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L513-L519 |
15,707 | tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.previous_blocks | def previous_blocks(self, quantity=-1):
"""Get the previous blocks in order."""
blocks = (EighthBlock.objects.get_blocks_this_year().order_by(
"-date", "-block_letter").filter(Q(date__lt=self.date) | (Q(date=self.date) & Q(block_letter__lt=self.block_letter))))
if quantity == -1:
return reversed(blocks)
return reversed(blocks[:quantity]) | python | def previous_blocks(self, quantity=-1):
blocks = (EighthBlock.objects.get_blocks_this_year().order_by(
"-date", "-block_letter").filter(Q(date__lt=self.date) | (Q(date=self.date) & Q(block_letter__lt=self.block_letter))))
if quantity == -1:
return reversed(blocks)
return reversed(blocks[:quantity]) | [
"def",
"previous_blocks",
"(",
"self",
",",
"quantity",
"=",
"-",
"1",
")",
":",
"blocks",
"=",
"(",
"EighthBlock",
".",
"objects",
".",
"get_blocks_this_year",
"(",
")",
".",
"order_by",
"(",
"\"-date\"",
",",
"\"-block_letter\"",
")",
".",
"filter",
"(",... | Get the previous blocks in order. | [
"Get",
"the",
"previous",
"blocks",
"in",
"order",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L521-L527 |
15,708 | tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.get_surrounding_blocks | def get_surrounding_blocks(self):
"""Get the blocks around the one given.
Returns: a list of all of those blocks.
"""
next = self.next_blocks()
prev = self.previous_blocks()
surrounding_blocks = list(chain(prev, [self], next))
return surrounding_blocks | python | def get_surrounding_blocks(self):
next = self.next_blocks()
prev = self.previous_blocks()
surrounding_blocks = list(chain(prev, [self], next))
return surrounding_blocks | [
"def",
"get_surrounding_blocks",
"(",
"self",
")",
":",
"next",
"=",
"self",
".",
"next_blocks",
"(",
")",
"prev",
"=",
"self",
".",
"previous_blocks",
"(",
")",
"surrounding_blocks",
"=",
"list",
"(",
"chain",
"(",
"prev",
",",
"[",
"self",
"]",
",",
... | Get the blocks around the one given.
Returns: a list of all of those blocks. | [
"Get",
"the",
"blocks",
"around",
"the",
"one",
"given",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L529-L540 |
15,709 | tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.signup_time_future | def signup_time_future(self):
"""Is the signup time in the future?"""
now = datetime.datetime.now()
return (now.date() < self.date or (self.date == now.date() and self.signup_time > now.time())) | python | def signup_time_future(self):
now = datetime.datetime.now()
return (now.date() < self.date or (self.date == now.date() and self.signup_time > now.time())) | [
"def",
"signup_time_future",
"(",
"self",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"return",
"(",
"now",
".",
"date",
"(",
")",
"<",
"self",
".",
"date",
"or",
"(",
"self",
".",
"date",
"==",
"now",
".",
"date",
"(... | Is the signup time in the future? | [
"Is",
"the",
"signup",
"time",
"in",
"the",
"future?"
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L546-L549 |
15,710 | tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.date_in_past | def date_in_past(self):
"""Is the block's date in the past?
(Has it not yet happened?)
"""
now = datetime.datetime.now()
return (now.date() > self.date) | python | def date_in_past(self):
now = datetime.datetime.now()
return (now.date() > self.date) | [
"def",
"date_in_past",
"(",
"self",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"return",
"(",
"now",
".",
"date",
"(",
")",
">",
"self",
".",
"date",
")"
] | Is the block's date in the past?
(Has it not yet happened?) | [
"Is",
"the",
"block",
"s",
"date",
"in",
"the",
"past?"
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L551-L558 |
15,711 | tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.in_clear_absence_period | def in_clear_absence_period(self):
"""Is the current date in the block's clear absence period?
(Should info on clearing the absence show?)
"""
now = datetime.datetime.now()
two_weeks = self.date + datetime.timedelta(days=settings.CLEAR_ABSENCE_DAYS)
return now.date() <= two_weeks | python | def in_clear_absence_period(self):
now = datetime.datetime.now()
two_weeks = self.date + datetime.timedelta(days=settings.CLEAR_ABSENCE_DAYS)
return now.date() <= two_weeks | [
"def",
"in_clear_absence_period",
"(",
"self",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"two_weeks",
"=",
"self",
".",
"date",
"+",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"settings",
".",
"CLEAR_ABSENCE_DAYS",
")",
... | Is the current date in the block's clear absence period?
(Should info on clearing the absence show?) | [
"Is",
"the",
"current",
"date",
"in",
"the",
"block",
"s",
"clear",
"absence",
"period?"
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L560-L568 |
15,712 | tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.attendance_locked | def attendance_locked(self):
"""Is it past 10PM on the day of the block?"""
now = datetime.datetime.now()
return now.date() > self.date or (now.date() == self.date and now.time() > datetime.time(settings.ATTENDANCE_LOCK_HOUR, 0)) | python | def attendance_locked(self):
now = datetime.datetime.now()
return now.date() > self.date or (now.date() == self.date and now.time() > datetime.time(settings.ATTENDANCE_LOCK_HOUR, 0)) | [
"def",
"attendance_locked",
"(",
"self",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"return",
"now",
".",
"date",
"(",
")",
">",
"self",
".",
"date",
"or",
"(",
"now",
".",
"date",
"(",
")",
"==",
"self",
".",
"date"... | Is it past 10PM on the day of the block? | [
"Is",
"it",
"past",
"10PM",
"on",
"the",
"day",
"of",
"the",
"block?"
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L570-L573 |
15,713 | tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.num_signups | def num_signups(self):
"""How many people have signed up?"""
return EighthSignup.objects.filter(scheduled_activity__block=self, user__in=User.objects.get_students()).count() | python | def num_signups(self):
return EighthSignup.objects.filter(scheduled_activity__block=self, user__in=User.objects.get_students()).count() | [
"def",
"num_signups",
"(",
"self",
")",
":",
"return",
"EighthSignup",
".",
"objects",
".",
"filter",
"(",
"scheduled_activity__block",
"=",
"self",
",",
"user__in",
"=",
"User",
".",
"objects",
".",
"get_students",
"(",
")",
")",
".",
"count",
"(",
")"
] | How many people have signed up? | [
"How",
"many",
"people",
"have",
"signed",
"up?"
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L575-L577 |
15,714 | tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.num_no_signups | def num_no_signups(self):
"""How many people have not signed up?"""
signup_users_count = User.objects.get_students().count()
return signup_users_count - self.num_signups() | python | def num_no_signups(self):
signup_users_count = User.objects.get_students().count()
return signup_users_count - self.num_signups() | [
"def",
"num_no_signups",
"(",
"self",
")",
":",
"signup_users_count",
"=",
"User",
".",
"objects",
".",
"get_students",
"(",
")",
".",
"count",
"(",
")",
"return",
"signup_users_count",
"-",
"self",
".",
"num_signups",
"(",
")"
] | How many people have not signed up? | [
"How",
"many",
"people",
"have",
"not",
"signed",
"up?"
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L579-L582 |
15,715 | tjcsl/ion | intranet/apps/eighth/models.py | EighthBlock.is_this_year | def is_this_year(self):
"""Return whether the block occurs after September 1st of this school year."""
return is_current_year(datetime.datetime.combine(self.date, datetime.time())) | python | def is_this_year(self):
return is_current_year(datetime.datetime.combine(self.date, datetime.time())) | [
"def",
"is_this_year",
"(",
"self",
")",
":",
"return",
"is_current_year",
"(",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"self",
".",
"date",
",",
"datetime",
".",
"time",
"(",
")",
")",
")"
] | Return whether the block occurs after September 1st of this school year. | [
"Return",
"whether",
"the",
"block",
"occurs",
"after",
"September",
"1st",
"of",
"this",
"school",
"year",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L612-L614 |
15,716 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivityManager.for_sponsor | def for_sponsor(self, sponsor, include_cancelled=False):
"""Return a QueryList of EighthScheduledActivities where the given EighthSponsor is
sponsoring.
If a sponsorship is defined in an EighthActivity, it may be overridden
on a block by block basis in an EighthScheduledActivity. Sponsors from
the EighthActivity do not carry over.
EighthScheduledActivities that are deleted or cancelled are also not
counted.
"""
sponsoring_filter = (Q(sponsors=sponsor) | (Q(sponsors=None) & Q(activity__sponsors=sponsor)))
sched_acts = (EighthScheduledActivity.objects.exclude(activity__deleted=True).filter(sponsoring_filter).distinct())
if not include_cancelled:
sched_acts = sched_acts.exclude(cancelled=True)
return sched_acts | python | def for_sponsor(self, sponsor, include_cancelled=False):
sponsoring_filter = (Q(sponsors=sponsor) | (Q(sponsors=None) & Q(activity__sponsors=sponsor)))
sched_acts = (EighthScheduledActivity.objects.exclude(activity__deleted=True).filter(sponsoring_filter).distinct())
if not include_cancelled:
sched_acts = sched_acts.exclude(cancelled=True)
return sched_acts | [
"def",
"for_sponsor",
"(",
"self",
",",
"sponsor",
",",
"include_cancelled",
"=",
"False",
")",
":",
"sponsoring_filter",
"=",
"(",
"Q",
"(",
"sponsors",
"=",
"sponsor",
")",
"|",
"(",
"Q",
"(",
"sponsors",
"=",
"None",
")",
"&",
"Q",
"(",
"activity__s... | Return a QueryList of EighthScheduledActivities where the given EighthSponsor is
sponsoring.
If a sponsorship is defined in an EighthActivity, it may be overridden
on a block by block basis in an EighthScheduledActivity. Sponsors from
the EighthActivity do not carry over.
EighthScheduledActivities that are deleted or cancelled are also not
counted. | [
"Return",
"a",
"QueryList",
"of",
"EighthScheduledActivities",
"where",
"the",
"given",
"EighthSponsor",
"is",
"sponsoring",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L631-L648 |
15,717 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivity.full_title | def full_title(self):
"""Gets the full title for the activity, appending the title of the scheduled activity to
the activity's name."""
cancelled_str = " (Cancelled)" if self.cancelled else ""
act_name = self.activity.name + cancelled_str
if self.special and not self.activity.special:
act_name = "Special: " + act_name
return act_name if not self.title else "{} - {}".format(act_name, self.title) | python | def full_title(self):
cancelled_str = " (Cancelled)" if self.cancelled else ""
act_name = self.activity.name + cancelled_str
if self.special and not self.activity.special:
act_name = "Special: " + act_name
return act_name if not self.title else "{} - {}".format(act_name, self.title) | [
"def",
"full_title",
"(",
"self",
")",
":",
"cancelled_str",
"=",
"\" (Cancelled)\"",
"if",
"self",
".",
"cancelled",
"else",
"\"\"",
"act_name",
"=",
"self",
".",
"activity",
".",
"name",
"+",
"cancelled_str",
"if",
"self",
".",
"special",
"and",
"not",
"... | Gets the full title for the activity, appending the title of the scheduled activity to
the activity's name. | [
"Gets",
"the",
"full",
"title",
"for",
"the",
"activity",
"appending",
"the",
"title",
"of",
"the",
"scheduled",
"activity",
"to",
"the",
"activity",
"s",
"name",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L728-L735 |
15,718 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivity.title_with_flags | def title_with_flags(self):
"""Gets the title for the activity, appending the title of the scheduled activity to the
activity's name and flags."""
cancelled_str = " (Cancelled)" if self.cancelled else ""
name_with_flags = self.activity._name_with_flags(True, self.title) + cancelled_str
if self.special and not self.activity.special:
name_with_flags = "Special: " + name_with_flags
return name_with_flags | python | def title_with_flags(self):
cancelled_str = " (Cancelled)" if self.cancelled else ""
name_with_flags = self.activity._name_with_flags(True, self.title) + cancelled_str
if self.special and not self.activity.special:
name_with_flags = "Special: " + name_with_flags
return name_with_flags | [
"def",
"title_with_flags",
"(",
"self",
")",
":",
"cancelled_str",
"=",
"\" (Cancelled)\"",
"if",
"self",
".",
"cancelled",
"else",
"\"\"",
"name_with_flags",
"=",
"self",
".",
"activity",
".",
"_name_with_flags",
"(",
"True",
",",
"self",
".",
"title",
")",
... | Gets the title for the activity, appending the title of the scheduled activity to the
activity's name and flags. | [
"Gets",
"the",
"title",
"for",
"the",
"activity",
"appending",
"the",
"title",
"of",
"the",
"scheduled",
"activity",
"to",
"the",
"activity",
"s",
"name",
"and",
"flags",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L738-L745 |
15,719 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivity.get_true_sponsors | def get_true_sponsors(self):
"""Get the sponsors for the scheduled activity, taking into account activity defaults and
overrides."""
sponsors = self.sponsors.all()
if len(sponsors) > 0:
return sponsors
else:
return self.activity.sponsors.all() | python | def get_true_sponsors(self):
sponsors = self.sponsors.all()
if len(sponsors) > 0:
return sponsors
else:
return self.activity.sponsors.all() | [
"def",
"get_true_sponsors",
"(",
"self",
")",
":",
"sponsors",
"=",
"self",
".",
"sponsors",
".",
"all",
"(",
")",
"if",
"len",
"(",
"sponsors",
")",
">",
"0",
":",
"return",
"sponsors",
"else",
":",
"return",
"self",
".",
"activity",
".",
"sponsors",
... | Get the sponsors for the scheduled activity, taking into account activity defaults and
overrides. | [
"Get",
"the",
"sponsors",
"for",
"the",
"scheduled",
"activity",
"taking",
"into",
"account",
"activity",
"defaults",
"and",
"overrides",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L747-L755 |
15,720 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivity.user_is_sponsor | def user_is_sponsor(self, user):
"""Return whether the given user is a sponsor of the activity.
Returns:
Boolean
"""
sponsors = self.get_true_sponsors()
for sponsor in sponsors:
sp_user = sponsor.user
if sp_user == user:
return True
return False | python | def user_is_sponsor(self, user):
sponsors = self.get_true_sponsors()
for sponsor in sponsors:
sp_user = sponsor.user
if sp_user == user:
return True
return False | [
"def",
"user_is_sponsor",
"(",
"self",
",",
"user",
")",
":",
"sponsors",
"=",
"self",
".",
"get_true_sponsors",
"(",
")",
"for",
"sponsor",
"in",
"sponsors",
":",
"sp_user",
"=",
"sponsor",
".",
"user",
"if",
"sp_user",
"==",
"user",
":",
"return",
"Tru... | Return whether the given user is a sponsor of the activity.
Returns:
Boolean | [
"Return",
"whether",
"the",
"given",
"user",
"is",
"a",
"sponsor",
"of",
"the",
"activity",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L757-L770 |
15,721 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivity.get_true_rooms | def get_true_rooms(self):
"""Get the rooms for the scheduled activity, taking into account activity defaults and
overrides."""
rooms = self.rooms.all()
if len(rooms) > 0:
return rooms
else:
return self.activity.rooms.all() | python | def get_true_rooms(self):
rooms = self.rooms.all()
if len(rooms) > 0:
return rooms
else:
return self.activity.rooms.all() | [
"def",
"get_true_rooms",
"(",
"self",
")",
":",
"rooms",
"=",
"self",
".",
"rooms",
".",
"all",
"(",
")",
"if",
"len",
"(",
"rooms",
")",
">",
"0",
":",
"return",
"rooms",
"else",
":",
"return",
"self",
".",
"activity",
".",
"rooms",
".",
"all",
... | Get the rooms for the scheduled activity, taking into account activity defaults and
overrides. | [
"Get",
"the",
"rooms",
"for",
"the",
"scheduled",
"activity",
"taking",
"into",
"account",
"activity",
"defaults",
"and",
"overrides",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L772-L780 |
15,722 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivity.get_true_capacity | def get_true_capacity(self):
"""Get the capacity for the scheduled activity, taking into account activity defaults and
overrides."""
c = self.capacity
if c is not None:
return c
else:
if self.rooms.count() == 0 and self.activity.default_capacity:
# use activity-level override
return self.activity.default_capacity
rooms = self.get_true_rooms()
return EighthRoom.total_capacity_of_rooms(rooms) | python | def get_true_capacity(self):
c = self.capacity
if c is not None:
return c
else:
if self.rooms.count() == 0 and self.activity.default_capacity:
# use activity-level override
return self.activity.default_capacity
rooms = self.get_true_rooms()
return EighthRoom.total_capacity_of_rooms(rooms) | [
"def",
"get_true_capacity",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"capacity",
"if",
"c",
"is",
"not",
"None",
":",
"return",
"c",
"else",
":",
"if",
"self",
".",
"rooms",
".",
"count",
"(",
")",
"==",
"0",
"and",
"self",
".",
"activity",
... | Get the capacity for the scheduled activity, taking into account activity defaults and
overrides. | [
"Get",
"the",
"capacity",
"for",
"the",
"scheduled",
"activity",
"taking",
"into",
"account",
"activity",
"defaults",
"and",
"overrides",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L782-L795 |
15,723 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivity.is_full | def is_full(self):
"""Return whether the activity is full."""
capacity = self.get_true_capacity()
if capacity != -1:
num_signed_up = self.eighthsignup_set.count()
return num_signed_up >= capacity
return False | python | def is_full(self):
capacity = self.get_true_capacity()
if capacity != -1:
num_signed_up = self.eighthsignup_set.count()
return num_signed_up >= capacity
return False | [
"def",
"is_full",
"(",
"self",
")",
":",
"capacity",
"=",
"self",
".",
"get_true_capacity",
"(",
")",
"if",
"capacity",
"!=",
"-",
"1",
":",
"num_signed_up",
"=",
"self",
".",
"eighthsignup_set",
".",
"count",
"(",
")",
"return",
"num_signed_up",
">=",
"... | Return whether the activity is full. | [
"Return",
"whether",
"the",
"activity",
"is",
"full",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L838-L844 |
15,724 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivity.is_overbooked | def is_overbooked(self):
"""Return whether the activity is overbooked."""
capacity = self.get_true_capacity()
if capacity != -1:
num_signed_up = self.eighthsignup_set.count()
return num_signed_up > capacity
return False | python | def is_overbooked(self):
capacity = self.get_true_capacity()
if capacity != -1:
num_signed_up = self.eighthsignup_set.count()
return num_signed_up > capacity
return False | [
"def",
"is_overbooked",
"(",
"self",
")",
":",
"capacity",
"=",
"self",
".",
"get_true_capacity",
"(",
")",
"if",
"capacity",
"!=",
"-",
"1",
":",
"num_signed_up",
"=",
"self",
".",
"eighthsignup_set",
".",
"count",
"(",
")",
"return",
"num_signed_up",
">"... | Return whether the activity is overbooked. | [
"Return",
"whether",
"the",
"activity",
"is",
"overbooked",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L854-L860 |
15,725 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivity.get_viewable_members | def get_viewable_members(self, user=None):
"""Get the list of members that you have permissions to view.
Returns: List of members
"""
members = []
for member in self.members.all():
show = False
if member.can_view_eighth:
show = member.can_view_eighth
if not show and user and user.is_eighth_admin:
show = True
if not show and user and user.is_teacher:
show = True
if not show and member == user:
show = True
if show:
members.append(member)
return sorted(members, key=lambda u: (u.last_name, u.first_name)) | python | def get_viewable_members(self, user=None):
members = []
for member in self.members.all():
show = False
if member.can_view_eighth:
show = member.can_view_eighth
if not show and user and user.is_eighth_admin:
show = True
if not show and user and user.is_teacher:
show = True
if not show and member == user:
show = True
if show:
members.append(member)
return sorted(members, key=lambda u: (u.last_name, u.first_name)) | [
"def",
"get_viewable_members",
"(",
"self",
",",
"user",
"=",
"None",
")",
":",
"members",
"=",
"[",
"]",
"for",
"member",
"in",
"self",
".",
"members",
".",
"all",
"(",
")",
":",
"show",
"=",
"False",
"if",
"member",
".",
"can_view_eighth",
":",
"sh... | Get the list of members that you have permissions to view.
Returns: List of members | [
"Get",
"the",
"list",
"of",
"members",
"that",
"you",
"have",
"permissions",
"to",
"view",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L878-L900 |
15,726 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivity.get_viewable_members_serializer | def get_viewable_members_serializer(self, request):
"""Get a QuerySet of User objects of students in the activity. Needed for the
EighthScheduledActivitySerializer.
Returns: QuerySet
"""
ids = []
user = request.user
for member in self.members.all():
show = False
if member.can_view_eighth:
show = member.can_view_eighth
if not show and user and user.is_eighth_admin:
show = True
if not show and user and user.is_teacher:
show = True
if not show and member == user:
show = True
if show:
ids.append(member.id)
return User.objects.filter(id__in=ids) | python | def get_viewable_members_serializer(self, request):
ids = []
user = request.user
for member in self.members.all():
show = False
if member.can_view_eighth:
show = member.can_view_eighth
if not show and user and user.is_eighth_admin:
show = True
if not show and user and user.is_teacher:
show = True
if not show and member == user:
show = True
if show:
ids.append(member.id)
return User.objects.filter(id__in=ids) | [
"def",
"get_viewable_members_serializer",
"(",
"self",
",",
"request",
")",
":",
"ids",
"=",
"[",
"]",
"user",
"=",
"request",
".",
"user",
"for",
"member",
"in",
"self",
".",
"members",
".",
"all",
"(",
")",
":",
"show",
"=",
"False",
"if",
"member",
... | Get a QuerySet of User objects of students in the activity. Needed for the
EighthScheduledActivitySerializer.
Returns: QuerySet | [
"Get",
"a",
"QuerySet",
"of",
"User",
"objects",
"of",
"students",
"in",
"the",
"activity",
".",
"Needed",
"for",
"the",
"EighthScheduledActivitySerializer",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L902-L926 |
15,727 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivity.get_hidden_members | def get_hidden_members(self, user=None):
"""Get the members that you do not have permission to view.
Returns: List of members hidden based on their permission preferences
"""
hidden_members = []
for member in self.members.all():
show = False
if member.can_view_eighth:
show = member.can_view_eighth
if not show and user and user.is_eighth_admin:
show = True
if not show and user and user.is_teacher:
show = True
if not show and member == user:
show = True
if not show:
hidden_members.append(member)
return hidden_members | python | def get_hidden_members(self, user=None):
hidden_members = []
for member in self.members.all():
show = False
if member.can_view_eighth:
show = member.can_view_eighth
if not show and user and user.is_eighth_admin:
show = True
if not show and user and user.is_teacher:
show = True
if not show and member == user:
show = True
if not show:
hidden_members.append(member)
return hidden_members | [
"def",
"get_hidden_members",
"(",
"self",
",",
"user",
"=",
"None",
")",
":",
"hidden_members",
"=",
"[",
"]",
"for",
"member",
"in",
"self",
".",
"members",
".",
"all",
"(",
")",
":",
"show",
"=",
"False",
"if",
"member",
".",
"can_view_eighth",
":",
... | Get the members that you do not have permission to view.
Returns: List of members hidden based on their permission preferences | [
"Get",
"the",
"members",
"that",
"you",
"do",
"not",
"have",
"permission",
"to",
"view",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L928-L950 |
15,728 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivity.get_both_blocks_sibling | def get_both_blocks_sibling(self):
"""If this is a both-blocks activity, get the other EighthScheduledActivity
object that occurs on the other block.
both_blocks means A and B block, NOT all of the blocks on that day.
Returns:
EighthScheduledActivity object if found
None if the activity cannot have a sibling
False if not found
"""
if not self.is_both_blocks():
return None
if self.block.block_letter and self.block.block_letter.upper() not in ["A", "B"]:
# both_blocks is not currently implemented for blocks other than A and B
return None
other_instances = (EighthScheduledActivity.objects.filter(activity=self.activity, block__date=self.block.date))
for inst in other_instances:
if inst == self:
continue
if inst.block.block_letter in ["A", "B"]:
return inst
return None | python | def get_both_blocks_sibling(self):
if not self.is_both_blocks():
return None
if self.block.block_letter and self.block.block_letter.upper() not in ["A", "B"]:
# both_blocks is not currently implemented for blocks other than A and B
return None
other_instances = (EighthScheduledActivity.objects.filter(activity=self.activity, block__date=self.block.date))
for inst in other_instances:
if inst == self:
continue
if inst.block.block_letter in ["A", "B"]:
return inst
return None | [
"def",
"get_both_blocks_sibling",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_both_blocks",
"(",
")",
":",
"return",
"None",
"if",
"self",
".",
"block",
".",
"block_letter",
"and",
"self",
".",
"block",
".",
"block_letter",
".",
"upper",
"(",
")... | If this is a both-blocks activity, get the other EighthScheduledActivity
object that occurs on the other block.
both_blocks means A and B block, NOT all of the blocks on that day.
Returns:
EighthScheduledActivity object if found
None if the activity cannot have a sibling
False if not found | [
"If",
"this",
"is",
"a",
"both",
"-",
"blocks",
"activity",
"get",
"the",
"other",
"EighthScheduledActivity",
"object",
"that",
"occurs",
"on",
"the",
"other",
"block",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L952-L979 |
15,729 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivity.cancel | def cancel(self):
"""Cancel an EighthScheduledActivity.
This does nothing besides set the cancelled flag and save the
object.
"""
# super(EighthScheduledActivity, self).save(*args, **kwargs)
logger.debug("Running cancel hooks: {}".format(self))
if not self.cancelled:
logger.debug("Cancelling {}".format(self))
self.cancelled = True
self.save()
# NOT USED. Was broken anyway.
"""
cancelled_room = EighthRoom.objects.get_or_create(name="CANCELLED", capacity=0)[0]
cancelled_sponsor = EighthSponsor.objects.get_or_create(first_name="", last_name="CANCELLED")[0]
if cancelled_room not in list(self.rooms.all()):
self.rooms.all().delete()
self.rooms.add(cancelled_room)
if cancelled_sponsor not in list(self.sponsors.all()):
self.sponsors.all().delete()
self.sponsors.add(cancelled_sponsor)
self.save()
""" | python | def cancel(self):
# super(EighthScheduledActivity, self).save(*args, **kwargs)
logger.debug("Running cancel hooks: {}".format(self))
if not self.cancelled:
logger.debug("Cancelling {}".format(self))
self.cancelled = True
self.save()
# NOT USED. Was broken anyway.
"""
cancelled_room = EighthRoom.objects.get_or_create(name="CANCELLED", capacity=0)[0]
cancelled_sponsor = EighthSponsor.objects.get_or_create(first_name="", last_name="CANCELLED")[0]
if cancelled_room not in list(self.rooms.all()):
self.rooms.all().delete()
self.rooms.add(cancelled_room)
if cancelled_sponsor not in list(self.sponsors.all()):
self.sponsors.all().delete()
self.sponsors.add(cancelled_sponsor)
self.save()
""" | [
"def",
"cancel",
"(",
"self",
")",
":",
"# super(EighthScheduledActivity, self).save(*args, **kwargs)",
"logger",
".",
"debug",
"(",
"\"Running cancel hooks: {}\"",
".",
"format",
"(",
"self",
")",
")",
"if",
"not",
"self",
".",
"cancelled",
":",
"logger",
".",
"d... | Cancel an EighthScheduledActivity.
This does nothing besides set the cancelled flag and save the
object. | [
"Cancel",
"an",
"EighthScheduledActivity",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L1218-L1246 |
15,730 | tjcsl/ion | intranet/apps/eighth/models.py | EighthScheduledActivity.uncancel | def uncancel(self):
"""Uncancel an EighthScheduledActivity.
This does nothing besides unset the cancelled flag and save the
object.
"""
if self.cancelled:
logger.debug("Uncancelling {}".format(self))
self.cancelled = False
self.save()
# NOT USED. Was broken anyway.
"""
cancelled_room = EighthRoom.objects.get_or_create(name="CANCELLED", capacity=0)[0]
cancelled_sponsor = EighthSponsor.objects.get_or_create(first_name="", last_name="CANCELLED")[0]
if cancelled_room in list(self.rooms.all()):
self.rooms.filter(id=cancelled_room.id).delete()
if cancelled_sponsor in list(self.sponsors.all()):
self.sponsors.filter(id=cancelled_sponsor.id).delete()
self.save()
""" | python | def uncancel(self):
if self.cancelled:
logger.debug("Uncancelling {}".format(self))
self.cancelled = False
self.save()
# NOT USED. Was broken anyway.
"""
cancelled_room = EighthRoom.objects.get_or_create(name="CANCELLED", capacity=0)[0]
cancelled_sponsor = EighthSponsor.objects.get_or_create(first_name="", last_name="CANCELLED")[0]
if cancelled_room in list(self.rooms.all()):
self.rooms.filter(id=cancelled_room.id).delete()
if cancelled_sponsor in list(self.sponsors.all()):
self.sponsors.filter(id=cancelled_sponsor.id).delete()
self.save()
""" | [
"def",
"uncancel",
"(",
"self",
")",
":",
"if",
"self",
".",
"cancelled",
":",
"logger",
".",
"debug",
"(",
"\"Uncancelling {}\"",
".",
"format",
"(",
"self",
")",
")",
"self",
".",
"cancelled",
"=",
"False",
"self",
".",
"save",
"(",
")",
"# NOT USED.... | Uncancel an EighthScheduledActivity.
This does nothing besides unset the cancelled flag and save the
object. | [
"Uncancel",
"an",
"EighthScheduledActivity",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L1248-L1271 |
15,731 | tjcsl/ion | intranet/apps/eighth/models.py | EighthSignup.validate_unique | def validate_unique(self, *args, **kwargs):
"""Checked whether more than one EighthSignup exists for a User on a given EighthBlock."""
super(EighthSignup, self).validate_unique(*args, **kwargs)
if self.has_conflict():
raise ValidationError({NON_FIELD_ERRORS: ("EighthSignup already exists for the User and the EighthScheduledActivity's block",)}) | python | def validate_unique(self, *args, **kwargs):
super(EighthSignup, self).validate_unique(*args, **kwargs)
if self.has_conflict():
raise ValidationError({NON_FIELD_ERRORS: ("EighthSignup already exists for the User and the EighthScheduledActivity's block",)}) | [
"def",
"validate_unique",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"EighthSignup",
",",
"self",
")",
".",
"validate_unique",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"has_conflict",
"("... | Checked whether more than one EighthSignup exists for a User on a given EighthBlock. | [
"Checked",
"whether",
"more",
"than",
"one",
"EighthSignup",
"exists",
"for",
"a",
"User",
"on",
"a",
"given",
"EighthBlock",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L1355-L1360 |
15,732 | tjcsl/ion | intranet/apps/eighth/models.py | EighthSignup.remove_signup | def remove_signup(self, user=None, force=False, dont_run_waitlist=False):
"""Attempt to remove the EighthSignup if the user has permission to do so."""
exception = eighth_exceptions.SignupException()
if user is not None:
if user != self.user and not user.is_eighth_admin:
exception.SignupForbidden = True
# Check if the block has been locked
if self.scheduled_activity.block.locked:
exception.BlockLocked = True
# Check if the scheduled activity has been cancelled
if self.scheduled_activity.cancelled:
exception.ScheduledActivityCancelled = True
# Check if the activity has been deleted
if self.scheduled_activity.activity.deleted:
exception.ActivityDeleted = True
# Check if the user is already stickied into an activity
if self.scheduled_activity.activity and self.scheduled_activity.activity.sticky:
exception.Sticky = True
if len(exception.messages()) > 0 and not force:
raise exception
else:
block = self.scheduled_activity.block
self.delete()
if settings.ENABLE_WAITLIST and self.scheduled_activity.waitlist.all().exists() and not block.locked and not dont_run_waitlist:
if not self.scheduled_activity.is_full():
waitlists = EighthWaitlist.objects.get_next_waitlist(self.scheduled_activity)
self.scheduled_activity.notify_waitlist(waitlists, self.scheduled_activity)
return "Successfully removed signup for {}.".format(block) | python | def remove_signup(self, user=None, force=False, dont_run_waitlist=False):
exception = eighth_exceptions.SignupException()
if user is not None:
if user != self.user and not user.is_eighth_admin:
exception.SignupForbidden = True
# Check if the block has been locked
if self.scheduled_activity.block.locked:
exception.BlockLocked = True
# Check if the scheduled activity has been cancelled
if self.scheduled_activity.cancelled:
exception.ScheduledActivityCancelled = True
# Check if the activity has been deleted
if self.scheduled_activity.activity.deleted:
exception.ActivityDeleted = True
# Check if the user is already stickied into an activity
if self.scheduled_activity.activity and self.scheduled_activity.activity.sticky:
exception.Sticky = True
if len(exception.messages()) > 0 and not force:
raise exception
else:
block = self.scheduled_activity.block
self.delete()
if settings.ENABLE_WAITLIST and self.scheduled_activity.waitlist.all().exists() and not block.locked and not dont_run_waitlist:
if not self.scheduled_activity.is_full():
waitlists = EighthWaitlist.objects.get_next_waitlist(self.scheduled_activity)
self.scheduled_activity.notify_waitlist(waitlists, self.scheduled_activity)
return "Successfully removed signup for {}.".format(block) | [
"def",
"remove_signup",
"(",
"self",
",",
"user",
"=",
"None",
",",
"force",
"=",
"False",
",",
"dont_run_waitlist",
"=",
"False",
")",
":",
"exception",
"=",
"eighth_exceptions",
".",
"SignupException",
"(",
")",
"if",
"user",
"is",
"not",
"None",
":",
... | Attempt to remove the EighthSignup if the user has permission to do so. | [
"Attempt",
"to",
"remove",
"the",
"EighthSignup",
"if",
"the",
"user",
"has",
"permission",
"to",
"do",
"so",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L1367-L1401 |
15,733 | tjcsl/ion | intranet/apps/eighth/views/admin/scheduling.py | transfer_students_action | def transfer_students_action(request):
"""Do the actual process of transferring students."""
if "source_act" in request.GET:
source_act = EighthScheduledActivity.objects.get(id=request.GET.get("source_act"))
elif "source_act" in request.POST:
source_act = EighthScheduledActivity.objects.get(id=request.POST.get("source_act"))
else:
raise Http404
dest_act = None
dest_unsignup = False
if "dest_act" in request.GET:
dest_act = EighthScheduledActivity.objects.get(id=request.GET.get("dest_act"))
elif "dest_act" in request.POST:
dest_act = EighthScheduledActivity.objects.get(id=request.POST.get("dest_act"))
elif "dest_unsignup" in request.POST or "dest_unsignup" in request.GET:
dest_unsignup = True
else:
raise Http404
num = source_act.members.count()
context = {"admin_page_title": "Transfer Students", "source_act": source_act, "dest_act": dest_act, "dest_unsignup": dest_unsignup, "num": num}
if request.method == "POST":
if dest_unsignup and not dest_act:
source_act.eighthsignup_set.all().delete()
invalidate_obj(source_act)
messages.success(request, "Successfully removed signups for {} students.".format(num))
else:
source_act.eighthsignup_set.update(scheduled_activity=dest_act)
invalidate_obj(source_act)
invalidate_obj(dest_act)
messages.success(request, "Successfully transfered {} students.".format(num))
return redirect("eighth_admin_dashboard")
else:
return render(request, "eighth/admin/transfer_students.html", context) | python | def transfer_students_action(request):
if "source_act" in request.GET:
source_act = EighthScheduledActivity.objects.get(id=request.GET.get("source_act"))
elif "source_act" in request.POST:
source_act = EighthScheduledActivity.objects.get(id=request.POST.get("source_act"))
else:
raise Http404
dest_act = None
dest_unsignup = False
if "dest_act" in request.GET:
dest_act = EighthScheduledActivity.objects.get(id=request.GET.get("dest_act"))
elif "dest_act" in request.POST:
dest_act = EighthScheduledActivity.objects.get(id=request.POST.get("dest_act"))
elif "dest_unsignup" in request.POST or "dest_unsignup" in request.GET:
dest_unsignup = True
else:
raise Http404
num = source_act.members.count()
context = {"admin_page_title": "Transfer Students", "source_act": source_act, "dest_act": dest_act, "dest_unsignup": dest_unsignup, "num": num}
if request.method == "POST":
if dest_unsignup and not dest_act:
source_act.eighthsignup_set.all().delete()
invalidate_obj(source_act)
messages.success(request, "Successfully removed signups for {} students.".format(num))
else:
source_act.eighthsignup_set.update(scheduled_activity=dest_act)
invalidate_obj(source_act)
invalidate_obj(dest_act)
messages.success(request, "Successfully transfered {} students.".format(num))
return redirect("eighth_admin_dashboard")
else:
return render(request, "eighth/admin/transfer_students.html", context) | [
"def",
"transfer_students_action",
"(",
"request",
")",
":",
"if",
"\"source_act\"",
"in",
"request",
".",
"GET",
":",
"source_act",
"=",
"EighthScheduledActivity",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"source... | Do the actual process of transferring students. | [
"Do",
"the",
"actual",
"process",
"of",
"transferring",
"students",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/views/admin/scheduling.py#L369-L407 |
15,734 | tjcsl/ion | intranet/apps/eighth/context_processors.py | start_date | def start_date(request):
"""Add the start date to the context for eighth admin views."""
if request.user and request.user.is_authenticated and request.user.is_eighth_admin:
return {"admin_start_date": get_start_date(request)}
return {} | python | def start_date(request):
if request.user and request.user.is_authenticated and request.user.is_eighth_admin:
return {"admin_start_date": get_start_date(request)}
return {} | [
"def",
"start_date",
"(",
"request",
")",
":",
"if",
"request",
".",
"user",
"and",
"request",
".",
"user",
".",
"is_authenticated",
"and",
"request",
".",
"user",
".",
"is_eighth_admin",
":",
"return",
"{",
"\"admin_start_date\"",
":",
"get_start_date",
"(",
... | Add the start date to the context for eighth admin views. | [
"Add",
"the",
"start",
"date",
"to",
"the",
"context",
"for",
"eighth",
"admin",
"views",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/context_processors.py#L7-L13 |
15,735 | tjcsl/ion | intranet/apps/eighth/context_processors.py | absence_count | def absence_count(request):
"""Add the absence count to the context for students."""
if request.user and request.user.is_authenticated and request.user.is_student:
absence_info = request.user.absence_info()
num_absences = absence_info.count()
show_notif = False
if num_absences > 0:
notif_seen = request.session.get('eighth_absence_notif_seen', False)
if not notif_seen:
for signup in absence_info:
if signup.in_clear_absence_period():
show_notif = True
if show_notif:
request.session['eighth_absence_notif_seen'] = True
return {"eighth_absence_count": num_absences, "eighth_absence_notif": show_notif}
return {} | python | def absence_count(request):
if request.user and request.user.is_authenticated and request.user.is_student:
absence_info = request.user.absence_info()
num_absences = absence_info.count()
show_notif = False
if num_absences > 0:
notif_seen = request.session.get('eighth_absence_notif_seen', False)
if not notif_seen:
for signup in absence_info:
if signup.in_clear_absence_period():
show_notif = True
if show_notif:
request.session['eighth_absence_notif_seen'] = True
return {"eighth_absence_count": num_absences, "eighth_absence_notif": show_notif}
return {} | [
"def",
"absence_count",
"(",
"request",
")",
":",
"if",
"request",
".",
"user",
"and",
"request",
".",
"user",
".",
"is_authenticated",
"and",
"request",
".",
"user",
".",
"is_student",
":",
"absence_info",
"=",
"request",
".",
"user",
".",
"absence_info",
... | Add the absence count to the context for students. | [
"Add",
"the",
"absence",
"count",
"to",
"the",
"context",
"for",
"students",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/context_processors.py#L20-L39 |
15,736 | tjcsl/ion | intranet/apps/files/models.py | HostManager.visible_to_user | def visible_to_user(self, user):
"""Get a list of hosts available to a given user.
Same logic as Announcements and Events.
"""
return Host.objects.filter(Q(groups_visible__in=user.groups.all()) | Q(groups_visible__isnull=True)).distinct() | python | def visible_to_user(self, user):
return Host.objects.filter(Q(groups_visible__in=user.groups.all()) | Q(groups_visible__isnull=True)).distinct() | [
"def",
"visible_to_user",
"(",
"self",
",",
"user",
")",
":",
"return",
"Host",
".",
"objects",
".",
"filter",
"(",
"Q",
"(",
"groups_visible__in",
"=",
"user",
".",
"groups",
".",
"all",
"(",
")",
")",
"|",
"Q",
"(",
"groups_visible__isnull",
"=",
"Tr... | Get a list of hosts available to a given user.
Same logic as Announcements and Events. | [
"Get",
"a",
"list",
"of",
"hosts",
"available",
"to",
"a",
"given",
"user",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/files/models.py#L45-L52 |
15,737 | tjcsl/ion | intranet/apps/schedule/models.py | DayManager.get_future_days | def get_future_days(self):
"""Return only future Day objects."""
today = timezone.now().date()
return Day.objects.filter(date__gte=today) | python | def get_future_days(self):
today = timezone.now().date()
return Day.objects.filter(date__gte=today) | [
"def",
"get_future_days",
"(",
"self",
")",
":",
"today",
"=",
"timezone",
".",
"now",
"(",
")",
".",
"date",
"(",
")",
"return",
"Day",
".",
"objects",
".",
"filter",
"(",
"date__gte",
"=",
"today",
")"
] | Return only future Day objects. | [
"Return",
"only",
"future",
"Day",
"objects",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/schedule/models.py#L108-L112 |
15,738 | tjcsl/ion | intranet/apps/schedule/models.py | DayManager.today | def today(self):
"""Return the Day for the current day"""
today = timezone.now().date()
try:
return Day.objects.get(date=today)
except Day.DoesNotExist:
return None | python | def today(self):
today = timezone.now().date()
try:
return Day.objects.get(date=today)
except Day.DoesNotExist:
return None | [
"def",
"today",
"(",
"self",
")",
":",
"today",
"=",
"timezone",
".",
"now",
"(",
")",
".",
"date",
"(",
")",
"try",
":",
"return",
"Day",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"today",
")",
"except",
"Day",
".",
"DoesNotExist",
":",
"ret... | Return the Day for the current day | [
"Return",
"the",
"Day",
"for",
"the",
"current",
"day"
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/schedule/models.py#L114-L120 |
15,739 | tjcsl/ion | intranet/utils/date.py | get_date_range_this_year | def get_date_range_this_year(now=None):
"""Return the starting and ending date of the current school year."""
if now is None:
now = datetime.datetime.now().date()
if now.month <= settings.YEAR_TURNOVER_MONTH:
date_start = datetime.datetime(now.year - 1, 8, 1) # TODO; don't hardcode these values
date_end = datetime.datetime(now.year, 7, 1)
else:
date_start = datetime.datetime(now.year, 8, 1)
date_end = datetime.datetime(now.year + 1, 7, 1)
return timezone.make_aware(date_start), timezone.make_aware(date_end) | python | def get_date_range_this_year(now=None):
if now is None:
now = datetime.datetime.now().date()
if now.month <= settings.YEAR_TURNOVER_MONTH:
date_start = datetime.datetime(now.year - 1, 8, 1) # TODO; don't hardcode these values
date_end = datetime.datetime(now.year, 7, 1)
else:
date_start = datetime.datetime(now.year, 8, 1)
date_end = datetime.datetime(now.year + 1, 7, 1)
return timezone.make_aware(date_start), timezone.make_aware(date_end) | [
"def",
"get_date_range_this_year",
"(",
"now",
"=",
"None",
")",
":",
"if",
"now",
"is",
"None",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"date",
"(",
")",
"if",
"now",
".",
"month",
"<=",
"settings",
".",
"YEAR_TURNOV... | Return the starting and ending date of the current school year. | [
"Return",
"the",
"starting",
"and",
"ending",
"date",
"of",
"the",
"current",
"school",
"year",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/utils/date.py#L13-L23 |
15,740 | tjcsl/ion | intranet/apps/users/templatetags/users.py | user_attr | def user_attr(username, attribute):
"""Gets an attribute of the user with the given username."""
return getattr(User.objects.get(username=username), attribute) | python | def user_attr(username, attribute):
return getattr(User.objects.get(username=username), attribute) | [
"def",
"user_attr",
"(",
"username",
",",
"attribute",
")",
":",
"return",
"getattr",
"(",
"User",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"username",
")",
",",
"attribute",
")"
] | Gets an attribute of the user with the given username. | [
"Gets",
"an",
"attribute",
"of",
"the",
"user",
"with",
"the",
"given",
"username",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/templatetags/users.py#L15-L17 |
15,741 | tjcsl/ion | intranet/apps/users/templatetags/users.py | argument_request_user | def argument_request_user(obj, func_name):
"""Pass request.user as an argument to the given function call."""
func = getattr(obj, func_name)
request = threadlocals.request()
if request:
return func(request.user) | python | def argument_request_user(obj, func_name):
func = getattr(obj, func_name)
request = threadlocals.request()
if request:
return func(request.user) | [
"def",
"argument_request_user",
"(",
"obj",
",",
"func_name",
")",
":",
"func",
"=",
"getattr",
"(",
"obj",
",",
"func_name",
")",
"request",
"=",
"threadlocals",
".",
"request",
"(",
")",
"if",
"request",
":",
"return",
"func",
"(",
"request",
".",
"use... | Pass request.user as an argument to the given function call. | [
"Pass",
"request",
".",
"user",
"as",
"an",
"argument",
"to",
"the",
"given",
"function",
"call",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/templatetags/users.py#L21-L26 |
15,742 | tjcsl/ion | intranet/apps/emailfwd/views.py | senior_email_forward_view | def senior_email_forward_view(request):
"""Add a forwarding address for graduating seniors."""
if not request.user.is_senior:
messages.error(request, "Only seniors can set their forwarding address.")
return redirect("index")
try:
forward = SeniorEmailForward.objects.get(user=request.user)
except SeniorEmailForward.DoesNotExist:
forward = None
if request.method == "POST":
if forward:
form = SeniorEmailForwardForm(request.POST, instance=forward)
else:
form = SeniorEmailForwardForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save(commit=False)
obj.user = request.user
obj.save()
messages.success(request, "Successfully added forwarding address.")
return redirect("index")
else:
messages.error(request, "Error adding forwarding address.")
else:
if forward:
form = SeniorEmailForwardForm(instance=forward)
else:
form = SeniorEmailForwardForm()
return render(request, "emailfwd/senior_forward.html", {"form": form, "forward": forward}) | python | def senior_email_forward_view(request):
if not request.user.is_senior:
messages.error(request, "Only seniors can set their forwarding address.")
return redirect("index")
try:
forward = SeniorEmailForward.objects.get(user=request.user)
except SeniorEmailForward.DoesNotExist:
forward = None
if request.method == "POST":
if forward:
form = SeniorEmailForwardForm(request.POST, instance=forward)
else:
form = SeniorEmailForwardForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save(commit=False)
obj.user = request.user
obj.save()
messages.success(request, "Successfully added forwarding address.")
return redirect("index")
else:
messages.error(request, "Error adding forwarding address.")
else:
if forward:
form = SeniorEmailForwardForm(instance=forward)
else:
form = SeniorEmailForwardForm()
return render(request, "emailfwd/senior_forward.html", {"form": form, "forward": forward}) | [
"def",
"senior_email_forward_view",
"(",
"request",
")",
":",
"if",
"not",
"request",
".",
"user",
".",
"is_senior",
":",
"messages",
".",
"error",
"(",
"request",
",",
"\"Only seniors can set their forwarding address.\"",
")",
"return",
"redirect",
"(",
"\"index\""... | Add a forwarding address for graduating seniors. | [
"Add",
"a",
"forwarding",
"address",
"for",
"graduating",
"seniors",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/emailfwd/views.py#L14-L43 |
15,743 | tjcsl/ion | intranet/apps/users/templatetags/phone_numbers.py | dashes | def dashes(phone):
"""Returns the phone number formatted with dashes."""
if isinstance(phone, str):
if phone.startswith("+1"):
return "1-" + "-".join((phone[2:5], phone[5:8], phone[8:]))
elif len(phone) == 10:
return "-".join((phone[:3], phone[3:6], phone[6:]))
else:
return phone
else:
return phone | python | def dashes(phone):
if isinstance(phone, str):
if phone.startswith("+1"):
return "1-" + "-".join((phone[2:5], phone[5:8], phone[8:]))
elif len(phone) == 10:
return "-".join((phone[:3], phone[3:6], phone[6:]))
else:
return phone
else:
return phone | [
"def",
"dashes",
"(",
"phone",
")",
":",
"if",
"isinstance",
"(",
"phone",
",",
"str",
")",
":",
"if",
"phone",
".",
"startswith",
"(",
"\"+1\"",
")",
":",
"return",
"\"1-\"",
"+",
"\"-\"",
".",
"join",
"(",
"(",
"phone",
"[",
"2",
":",
"5",
"]",... | Returns the phone number formatted with dashes. | [
"Returns",
"the",
"phone",
"number",
"formatted",
"with",
"dashes",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/templatetags/phone_numbers.py#L9-L19 |
15,744 | tjcsl/ion | intranet/apps/emerg/views.py | check_emerg | def check_emerg():
"""Fetch from FCPS' emergency announcement page.
URL defined in settings.FCPS_EMERGENCY_PAGE
Request timeout defined in settings.FCPS_EMERGENCY_TIMEOUT
"""
status = True
message = None
if settings.EMERGENCY_MESSAGE:
return True, settings.EMERGENCY_MESSAGE
if not settings.FCPS_EMERGENCY_PAGE:
return None, None
timeout = settings.FCPS_EMERGENCY_TIMEOUT
r = requests.get("{}?{}".format(settings.FCPS_EMERGENCY_PAGE, int(time.time() // 60)), timeout=timeout)
res = r.text
if not res or len(res) < 1:
status = False
# Keep this list up to date with whatever wording FCPS decides to use each time...
bad_strings = [
"There are no emergency announcements at this time", "There are no emergency messages at this time",
"There are no emeregency annoncements at this time", "There are no major announcements at this time.",
"There are no major emergency announcements at this time.", "There are no emergencies at this time."
]
for b in bad_strings:
if b in res:
status = False
break
# emerg_split = '<p><a href="https://youtu.be/jo_8QFIEf64'
# message = res.split(emerg_split)[0]
soup = BeautifulSoup(res, "html.parser")
if soup.title:
title = soup.title.text
body = ""
for cd in soup.findAll(text=True):
if isinstance(cd, CData):
body += cd
message = "<h3>{}: </h3>{}".format(title, body)
message = message.strip()
else:
status = False
return status, message | python | def check_emerg():
status = True
message = None
if settings.EMERGENCY_MESSAGE:
return True, settings.EMERGENCY_MESSAGE
if not settings.FCPS_EMERGENCY_PAGE:
return None, None
timeout = settings.FCPS_EMERGENCY_TIMEOUT
r = requests.get("{}?{}".format(settings.FCPS_EMERGENCY_PAGE, int(time.time() // 60)), timeout=timeout)
res = r.text
if not res or len(res) < 1:
status = False
# Keep this list up to date with whatever wording FCPS decides to use each time...
bad_strings = [
"There are no emergency announcements at this time", "There are no emergency messages at this time",
"There are no emeregency annoncements at this time", "There are no major announcements at this time.",
"There are no major emergency announcements at this time.", "There are no emergencies at this time."
]
for b in bad_strings:
if b in res:
status = False
break
# emerg_split = '<p><a href="https://youtu.be/jo_8QFIEf64'
# message = res.split(emerg_split)[0]
soup = BeautifulSoup(res, "html.parser")
if soup.title:
title = soup.title.text
body = ""
for cd in soup.findAll(text=True):
if isinstance(cd, CData):
body += cd
message = "<h3>{}: </h3>{}".format(title, body)
message = message.strip()
else:
status = False
return status, message | [
"def",
"check_emerg",
"(",
")",
":",
"status",
"=",
"True",
"message",
"=",
"None",
"if",
"settings",
".",
"EMERGENCY_MESSAGE",
":",
"return",
"True",
",",
"settings",
".",
"EMERGENCY_MESSAGE",
"if",
"not",
"settings",
".",
"FCPS_EMERGENCY_PAGE",
":",
"return"... | Fetch from FCPS' emergency announcement page.
URL defined in settings.FCPS_EMERGENCY_PAGE
Request timeout defined in settings.FCPS_EMERGENCY_TIMEOUT | [
"Fetch",
"from",
"FCPS",
"emergency",
"announcement",
"page",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/emerg/views.py#L16-L63 |
15,745 | tjcsl/ion | intranet/apps/emerg/views.py | get_emerg | def get_emerg():
"""Get the cached FCPS emergency page, or check it again.
Timeout defined in settings.CACHE_AGE["emerg"]
"""
key = "emerg:{}".format(datetime.datetime.now().date())
cached = cache.get(key)
cached = None # Remove this for production
if cached:
logger.debug("Returning emergency info from cache")
return cached
else:
result = get_emerg_result()
cache.set(key, result, timeout=settings.CACHE_AGE["emerg"])
return result | python | def get_emerg():
key = "emerg:{}".format(datetime.datetime.now().date())
cached = cache.get(key)
cached = None # Remove this for production
if cached:
logger.debug("Returning emergency info from cache")
return cached
else:
result = get_emerg_result()
cache.set(key, result, timeout=settings.CACHE_AGE["emerg"])
return result | [
"def",
"get_emerg",
"(",
")",
":",
"key",
"=",
"\"emerg:{}\"",
".",
"format",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"date",
"(",
")",
")",
"cached",
"=",
"cache",
".",
"get",
"(",
"key",
")",
"cached",
"=",
"None",
"# Remove ... | Get the cached FCPS emergency page, or check it again.
Timeout defined in settings.CACHE_AGE["emerg"] | [
"Get",
"the",
"cached",
"FCPS",
"emergency",
"page",
"or",
"check",
"it",
"again",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/emerg/views.py#L73-L88 |
15,746 | tjcsl/ion | intranet/apps/auth/views.py | index_view | def index_view(request, auth_form=None, force_login=False, added_context=None):
"""Process and show the main login page or dashboard if logged in."""
if request.user.is_authenticated and not force_login:
return dashboard_view(request)
else:
auth_form = auth_form or AuthenticateForm()
request.session.set_test_cookie()
fcps_emerg = get_fcps_emerg(request)
try:
login_warning = settings.LOGIN_WARNING
except AttributeError:
login_warning = None
if fcps_emerg and not login_warning:
login_warning = fcps_emerg
ap_week = get_ap_week_warning(request)
if ap_week and not login_warning:
login_warning = ap_week
events = Event.objects.filter(time__gte=datetime.now(), time__lte=(datetime.now().date() + relativedelta(weeks=1)), public=True).this_year()
sports_events = events.filter(approved=True, category="sports").order_by('time')[:3]
school_events = events.filter(approved=True, category="school").order_by('time')[:3]
data = {
"auth_form": auth_form,
"request": request,
"git_info": settings.GIT,
"bg_pattern": get_bg_pattern(),
"theme": get_login_theme(),
"login_warning": login_warning,
"senior_graduation": settings.SENIOR_GRADUATION,
"senior_graduation_year": settings.SENIOR_GRADUATION_YEAR,
"sports_events": sports_events,
"school_events": school_events
}
schedule = schedule_context(request)
data.update(schedule)
if added_context is not None:
data.update(added_context)
return render(request, "auth/login.html", data) | python | def index_view(request, auth_form=None, force_login=False, added_context=None):
if request.user.is_authenticated and not force_login:
return dashboard_view(request)
else:
auth_form = auth_form or AuthenticateForm()
request.session.set_test_cookie()
fcps_emerg = get_fcps_emerg(request)
try:
login_warning = settings.LOGIN_WARNING
except AttributeError:
login_warning = None
if fcps_emerg and not login_warning:
login_warning = fcps_emerg
ap_week = get_ap_week_warning(request)
if ap_week and not login_warning:
login_warning = ap_week
events = Event.objects.filter(time__gte=datetime.now(), time__lte=(datetime.now().date() + relativedelta(weeks=1)), public=True).this_year()
sports_events = events.filter(approved=True, category="sports").order_by('time')[:3]
school_events = events.filter(approved=True, category="school").order_by('time')[:3]
data = {
"auth_form": auth_form,
"request": request,
"git_info": settings.GIT,
"bg_pattern": get_bg_pattern(),
"theme": get_login_theme(),
"login_warning": login_warning,
"senior_graduation": settings.SENIOR_GRADUATION,
"senior_graduation_year": settings.SENIOR_GRADUATION_YEAR,
"sports_events": sports_events,
"school_events": school_events
}
schedule = schedule_context(request)
data.update(schedule)
if added_context is not None:
data.update(added_context)
return render(request, "auth/login.html", data) | [
"def",
"index_view",
"(",
"request",
",",
"auth_form",
"=",
"None",
",",
"force_login",
"=",
"False",
",",
"added_context",
"=",
"None",
")",
":",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"and",
"not",
"force_login",
":",
"return",
"dashboard_v... | Process and show the main login page or dashboard if logged in. | [
"Process",
"and",
"show",
"the",
"main",
"login",
"page",
"or",
"dashboard",
"if",
"logged",
"in",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/auth/views.py#L110-L153 |
15,747 | tjcsl/ion | intranet/apps/auth/views.py | logout_view | def logout_view(request):
"""Clear the Kerberos cache and logout."""
do_logout(request)
app_redirects = {"collegerecs": "https://apps.tjhsst.edu/collegerecs/logout?ion_logout=1"}
app = request.GET.get("app", "")
if app and app in app_redirects:
return redirect(app_redirects[app])
return redirect("index") | python | def logout_view(request):
do_logout(request)
app_redirects = {"collegerecs": "https://apps.tjhsst.edu/collegerecs/logout?ion_logout=1"}
app = request.GET.get("app", "")
if app and app in app_redirects:
return redirect(app_redirects[app])
return redirect("index") | [
"def",
"logout_view",
"(",
"request",
")",
":",
"do_logout",
"(",
"request",
")",
"app_redirects",
"=",
"{",
"\"collegerecs\"",
":",
"\"https://apps.tjhsst.edu/collegerecs/logout?ion_logout=1\"",
"}",
"app",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"app\"",
... | Clear the Kerberos cache and logout. | [
"Clear",
"the",
"Kerberos",
"cache",
"and",
"logout",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/auth/views.py#L232-L241 |
15,748 | tjcsl/ion | intranet/apps/auth/views.py | LoginView.post | def post(self, request):
"""Validate and process the login POST request."""
"""Before September 1st, do not allow Class of [year+4] to log in."""
if request.POST.get("username", "").startswith(str(date.today().year + 4)) and date.today() < settings.SCHOOL_START_DATE:
return index_view(request, added_context={"auth_message": "Your account is not yet active for use with this application."})
form = AuthenticateForm(data=request.POST)
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
else:
logger.warning("No cookie support detected! This could cause problems.")
if form.is_valid():
reset_user, status = User.objects.get_or_create(username="RESET_PASSWORD", user_type="service", id=999999)
if form.get_user() == reset_user:
return redirect(reverse("reset_password") + "?expired=True")
login(request, form.get_user())
# Initial load into session
logger.info("Login succeeded as {}".format(request.POST.get("username", "unknown")))
logger.info("request.user: {}".format(request.user))
log_auth(request, "success{}".format(" - first login" if not request.user.first_login else ""))
default_next_page = "index"
if request.user.is_eighthoffice:
"""Default to eighth admin view (for eighthoffice)."""
default_next_page = "eighth_admin_dashboard"
# if request.user.is_eighthoffice:
# """Eighthoffice's session should (almost) never expire."""
# request.session.set_expiry(timezone.now() + timedelta(days=30))
if not request.user.first_login:
logger.info("First login")
request.user.first_login = make_aware(datetime.now())
request.user.save()
request.session["first_login"] = True
if request.user.is_student or request.user.is_teacher:
default_next_page = "welcome"
else:
pass # exclude eighth office/special accounts
# if the student has not seen the 8th agreement yet, redirect them
if request.user.is_student and not request.user.seen_welcome:
return redirect("welcome")
next_page = request.POST.get("next", request.GET.get("next", default_next_page))
return redirect(next_page)
else:
log_auth(request, "failed")
logger.info("Login failed as {}".format(request.POST.get("username", "unknown")))
return index_view(request, auth_form=form) | python | def post(self, request):
"""Before September 1st, do not allow Class of [year+4] to log in."""
if request.POST.get("username", "").startswith(str(date.today().year + 4)) and date.today() < settings.SCHOOL_START_DATE:
return index_view(request, added_context={"auth_message": "Your account is not yet active for use with this application."})
form = AuthenticateForm(data=request.POST)
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
else:
logger.warning("No cookie support detected! This could cause problems.")
if form.is_valid():
reset_user, status = User.objects.get_or_create(username="RESET_PASSWORD", user_type="service", id=999999)
if form.get_user() == reset_user:
return redirect(reverse("reset_password") + "?expired=True")
login(request, form.get_user())
# Initial load into session
logger.info("Login succeeded as {}".format(request.POST.get("username", "unknown")))
logger.info("request.user: {}".format(request.user))
log_auth(request, "success{}".format(" - first login" if not request.user.first_login else ""))
default_next_page = "index"
if request.user.is_eighthoffice:
"""Default to eighth admin view (for eighthoffice)."""
default_next_page = "eighth_admin_dashboard"
# if request.user.is_eighthoffice:
# """Eighthoffice's session should (almost) never expire."""
# request.session.set_expiry(timezone.now() + timedelta(days=30))
if not request.user.first_login:
logger.info("First login")
request.user.first_login = make_aware(datetime.now())
request.user.save()
request.session["first_login"] = True
if request.user.is_student or request.user.is_teacher:
default_next_page = "welcome"
else:
pass # exclude eighth office/special accounts
# if the student has not seen the 8th agreement yet, redirect them
if request.user.is_student and not request.user.seen_welcome:
return redirect("welcome")
next_page = request.POST.get("next", request.GET.get("next", default_next_page))
return redirect(next_page)
else:
log_auth(request, "failed")
logger.info("Login failed as {}".format(request.POST.get("username", "unknown")))
return index_view(request, auth_form=form) | [
"def",
"post",
"(",
"self",
",",
"request",
")",
":",
"\"\"\"Before September 1st, do not allow Class of [year+4] to log in.\"\"\"",
"if",
"request",
".",
"POST",
".",
"get",
"(",
"\"username\"",
",",
"\"\"",
")",
".",
"startswith",
"(",
"str",
"(",
"date",
".",
... | Validate and process the login POST request. | [
"Validate",
"and",
"process",
"the",
"login",
"POST",
"request",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/auth/views.py#L160-L214 |
15,749 | agoragames/kairos | kairos/mongo_backend.py | MongoBackend._unescape | def _unescape(self, value):
'''
Recursively unescape values. Though slower, this doesn't require the user to
know anything about the escaping when writing their own custom fetch functions.
'''
if isinstance(value, (str,unicode)):
return value.replace(self._escape_character, '.')
elif isinstance(value, dict):
return { self._unescape(k) : self._unescape(v) for k,v in value.items() }
elif isinstance(value, list):
return [ self._unescape(v) for v in value ]
return value | python | def _unescape(self, value):
'''
Recursively unescape values. Though slower, this doesn't require the user to
know anything about the escaping when writing their own custom fetch functions.
'''
if isinstance(value, (str,unicode)):
return value.replace(self._escape_character, '.')
elif isinstance(value, dict):
return { self._unescape(k) : self._unescape(v) for k,v in value.items() }
elif isinstance(value, list):
return [ self._unescape(v) for v in value ]
return value | [
"def",
"_unescape",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"return",
"value",
".",
"replace",
"(",
"self",
".",
"_escape_character",
",",
"'.'",
")",
"elif",
"isinstance",
... | Recursively unescape values. Though slower, this doesn't require the user to
know anything about the escaping when writing their own custom fetch functions. | [
"Recursively",
"unescape",
"values",
".",
"Though",
"slower",
"this",
"doesn",
"t",
"require",
"the",
"user",
"to",
"know",
"anything",
"about",
"the",
"escaping",
"when",
"writing",
"their",
"own",
"custom",
"fetch",
"functions",
"."
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/mongo_backend.py#L90-L101 |
15,750 | agoragames/kairos | kairos/mongo_backend.py | MongoBackend._batch_key | def _batch_key(self, query):
'''
Get a unique id from a query.
'''
return ''.join( ['%s%s'%(k,v) for k,v in sorted(query.items())] ) | python | def _batch_key(self, query):
'''
Get a unique id from a query.
'''
return ''.join( ['%s%s'%(k,v) for k,v in sorted(query.items())] ) | [
"def",
"_batch_key",
"(",
"self",
",",
"query",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"'%s%s'",
"%",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"query",
".",
"items",
"(",
")",
")",
"]",
")"
] | Get a unique id from a query. | [
"Get",
"a",
"unique",
"id",
"from",
"a",
"query",
"."
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/mongo_backend.py#L121-L125 |
15,751 | agoragames/kairos | kairos/mongo_backend.py | MongoBackend._batch_insert | def _batch_insert(self, inserts, intervals, **kwargs):
'''
Batch insert implementation.
'''
updates = {}
# TODO support flush interval
for interval,config in self._intervals.items():
for timestamp,names in inserts.iteritems():
timestamps = self._normalize_timestamps(timestamp, intervals, config)
for name,values in names.iteritems():
for value in values:
for tstamp in timestamps:
query,insert = self._insert_data(
name, value, tstamp, interval, config, dry_run=True)
batch_key = self._batch_key(query)
updates.setdefault(batch_key, {'query':query, 'interval':interval})
new_insert = self._batch(insert, updates[batch_key].get('insert'))
updates[batch_key]['insert'] = new_insert
# now that we've collected a bunch of updates, flush them out
for spec in updates.values():
self._client[ spec['interval'] ].update(
spec['query'], spec['insert'], upsert=True, check_keys=False ) | python | def _batch_insert(self, inserts, intervals, **kwargs):
'''
Batch insert implementation.
'''
updates = {}
# TODO support flush interval
for interval,config in self._intervals.items():
for timestamp,names in inserts.iteritems():
timestamps = self._normalize_timestamps(timestamp, intervals, config)
for name,values in names.iteritems():
for value in values:
for tstamp in timestamps:
query,insert = self._insert_data(
name, value, tstamp, interval, config, dry_run=True)
batch_key = self._batch_key(query)
updates.setdefault(batch_key, {'query':query, 'interval':interval})
new_insert = self._batch(insert, updates[batch_key].get('insert'))
updates[batch_key]['insert'] = new_insert
# now that we've collected a bunch of updates, flush them out
for spec in updates.values():
self._client[ spec['interval'] ].update(
spec['query'], spec['insert'], upsert=True, check_keys=False ) | [
"def",
"_batch_insert",
"(",
"self",
",",
"inserts",
",",
"intervals",
",",
"*",
"*",
"kwargs",
")",
":",
"updates",
"=",
"{",
"}",
"# TODO support flush interval",
"for",
"interval",
",",
"config",
"in",
"self",
".",
"_intervals",
".",
"items",
"(",
")",
... | Batch insert implementation. | [
"Batch",
"insert",
"implementation",
"."
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/mongo_backend.py#L127-L150 |
15,752 | agoragames/kairos | kairos/mongo_backend.py | MongoBackend._insert_data | def _insert_data(self, name, value, timestamp, interval, config, **kwargs):
'''Helper to insert data into mongo.'''
# Mongo does not allow mixing atomic modifiers and non-$set sets in the
# same update, so the choice is to either run the first upsert on
# {'_id':id} to ensure the record is in place followed by an atomic update
# based on the series type, or use $set for all of the keys to be used in
# creating the record, which then disallows setting our own _id because
# that "can't be updated". So the tradeoffs are:
# * 2 updates for every insert, maybe a local cache of known _ids and the
# associated memory overhead
# * Query by the 2 or 3 key tuple for this interval and the associated
# overhead of that index match vs. the presumably-faster match on _id
# * Yet another index for the would-be _id of i_key or r_key, where each
# index has a notable impact on write performance.
# For now, choosing to go with matching on the tuple until performance
# testing can be done. Even then, there may be a variety of factors which
# make the results situation-dependent.
insert = {'name':name, 'interval':config['i_calc'].to_bucket(timestamp)}
if not config['coarse']:
insert['resolution'] = config['r_calc'].to_bucket(timestamp)
# copy the query before expire_from as that is not indexed
query = insert.copy()
if config['expire']:
insert['expire_from'] = datetime.utcfromtimestamp( timestamp )
# switch to atomic updates
insert = {'$set':insert.copy()}
# need to hide the period of any values. best option seems to be to pick
# a character that "no one" uses.
if isinstance(value, (str,unicode)):
value = value.replace('.', self._escape_character)
elif isinstance(value, float):
value = str(value).replace('.', self._escape_character)
self._insert_type( insert, value )
# TODO: use write preference settings if we have them
if not kwargs.get('dry_run',False):
self._client[interval].update( query, insert, upsert=True, check_keys=False )
return query, insert | python | def _insert_data(self, name, value, timestamp, interval, config, **kwargs):
'''Helper to insert data into mongo.'''
# Mongo does not allow mixing atomic modifiers and non-$set sets in the
# same update, so the choice is to either run the first upsert on
# {'_id':id} to ensure the record is in place followed by an atomic update
# based on the series type, or use $set for all of the keys to be used in
# creating the record, which then disallows setting our own _id because
# that "can't be updated". So the tradeoffs are:
# * 2 updates for every insert, maybe a local cache of known _ids and the
# associated memory overhead
# * Query by the 2 or 3 key tuple for this interval and the associated
# overhead of that index match vs. the presumably-faster match on _id
# * Yet another index for the would-be _id of i_key or r_key, where each
# index has a notable impact on write performance.
# For now, choosing to go with matching on the tuple until performance
# testing can be done. Even then, there may be a variety of factors which
# make the results situation-dependent.
insert = {'name':name, 'interval':config['i_calc'].to_bucket(timestamp)}
if not config['coarse']:
insert['resolution'] = config['r_calc'].to_bucket(timestamp)
# copy the query before expire_from as that is not indexed
query = insert.copy()
if config['expire']:
insert['expire_from'] = datetime.utcfromtimestamp( timestamp )
# switch to atomic updates
insert = {'$set':insert.copy()}
# need to hide the period of any values. best option seems to be to pick
# a character that "no one" uses.
if isinstance(value, (str,unicode)):
value = value.replace('.', self._escape_character)
elif isinstance(value, float):
value = str(value).replace('.', self._escape_character)
self._insert_type( insert, value )
# TODO: use write preference settings if we have them
if not kwargs.get('dry_run',False):
self._client[interval].update( query, insert, upsert=True, check_keys=False )
return query, insert | [
"def",
"_insert_data",
"(",
"self",
",",
"name",
",",
"value",
",",
"timestamp",
",",
"interval",
",",
"config",
",",
"*",
"*",
"kwargs",
")",
":",
"# Mongo does not allow mixing atomic modifiers and non-$set sets in the",
"# same update, so the choice is to either run the ... | Helper to insert data into mongo. | [
"Helper",
"to",
"insert",
"data",
"into",
"mongo",
"."
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/mongo_backend.py#L162-L203 |
15,753 | tjcsl/ion | intranet/utils/helpers.py | debug_toolbar_callback | def debug_toolbar_callback(request):
"""Show the debug toolbar to those with the Django staff permission, excluding the Eighth Period
office."""
if request.is_ajax():
return False
if not hasattr(request, 'user'):
return False
if not request.user.is_authenticated:
return False
if not request.user.is_staff:
return False
if request.user.id == 9999:
return False
return "debug" in request.GET or settings.DEBUG | python | def debug_toolbar_callback(request):
if request.is_ajax():
return False
if not hasattr(request, 'user'):
return False
if not request.user.is_authenticated:
return False
if not request.user.is_staff:
return False
if request.user.id == 9999:
return False
return "debug" in request.GET or settings.DEBUG | [
"def",
"debug_toolbar_callback",
"(",
"request",
")",
":",
"if",
"request",
".",
"is_ajax",
"(",
")",
":",
"return",
"False",
"if",
"not",
"hasattr",
"(",
"request",
",",
"'user'",
")",
":",
"return",
"False",
"if",
"not",
"request",
".",
"user",
".",
... | Show the debug toolbar to those with the Django staff permission, excluding the Eighth Period
office. | [
"Show",
"the",
"debug",
"toolbar",
"to",
"those",
"with",
"the",
"Django",
"staff",
"permission",
"excluding",
"the",
"Eighth",
"Period",
"office",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/utils/helpers.py#L25-L41 |
15,754 | tjcsl/ion | intranet/apps/itemreg/views.py | register_calculator_view | def register_calculator_view(request):
"""Register a calculator."""
if request.method == "POST":
form = CalculatorRegistrationForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
obj.save()
messages.success(request, "Successfully added calculator.")
return redirect("itemreg")
else:
messages.error(request, "Error adding calculator.")
else:
form = CalculatorRegistrationForm()
return render(request, "itemreg/register_form.html", {"form": form, "action": "add", "type": "calculator", "form_route": "itemreg_calculator"}) | python | def register_calculator_view(request):
if request.method == "POST":
form = CalculatorRegistrationForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
obj.save()
messages.success(request, "Successfully added calculator.")
return redirect("itemreg")
else:
messages.error(request, "Error adding calculator.")
else:
form = CalculatorRegistrationForm()
return render(request, "itemreg/register_form.html", {"form": form, "action": "add", "type": "calculator", "form_route": "itemreg_calculator"}) | [
"def",
"register_calculator_view",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"form",
"=",
"CalculatorRegistrationForm",
"(",
"request",
".",
"POST",
")",
"logger",
".",
"debug",
"(",
"form",
")",
"if",
"form",
".",
"i... | Register a calculator. | [
"Register",
"a",
"calculator",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/itemreg/views.py#L154-L169 |
15,755 | tjcsl/ion | intranet/apps/itemreg/views.py | register_computer_view | def register_computer_view(request):
"""Register a computer."""
if request.method == "POST":
form = ComputerRegistrationForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
obj.save()
messages.success(request, "Successfully added computer.")
return redirect("itemreg")
else:
messages.error(request, "Error adding computer.")
else:
form = ComputerRegistrationForm()
return render(request, "itemreg/register_form.html", {"form": form, "action": "add", "type": "computer", "form_route": "itemreg_computer"}) | python | def register_computer_view(request):
if request.method == "POST":
form = ComputerRegistrationForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
obj.save()
messages.success(request, "Successfully added computer.")
return redirect("itemreg")
else:
messages.error(request, "Error adding computer.")
else:
form = ComputerRegistrationForm()
return render(request, "itemreg/register_form.html", {"form": form, "action": "add", "type": "computer", "form_route": "itemreg_computer"}) | [
"def",
"register_computer_view",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"form",
"=",
"ComputerRegistrationForm",
"(",
"request",
".",
"POST",
")",
"logger",
".",
"debug",
"(",
"form",
")",
"if",
"form",
".",
"is_va... | Register a computer. | [
"Register",
"a",
"computer",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/itemreg/views.py#L174-L189 |
15,756 | tjcsl/ion | intranet/apps/itemreg/views.py | register_phone_view | def register_phone_view(request):
"""Register a phone."""
if request.method == "POST":
form = PhoneRegistrationForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
obj.save()
messages.success(request, "Successfully added phone.")
return redirect("itemreg")
else:
messages.error(request, "Error adding phone.")
else:
form = PhoneRegistrationForm()
return render(request, "itemreg/register_form.html", {"form": form, "action": "add", "type": "phone", "form_route": "itemreg_phone"}) | python | def register_phone_view(request):
if request.method == "POST":
form = PhoneRegistrationForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
obj.save()
messages.success(request, "Successfully added phone.")
return redirect("itemreg")
else:
messages.error(request, "Error adding phone.")
else:
form = PhoneRegistrationForm()
return render(request, "itemreg/register_form.html", {"form": form, "action": "add", "type": "phone", "form_route": "itemreg_phone"}) | [
"def",
"register_phone_view",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"form",
"=",
"PhoneRegistrationForm",
"(",
"request",
".",
"POST",
")",
"logger",
".",
"debug",
"(",
"form",
")",
"if",
"form",
".",
"is_valid",
... | Register a phone. | [
"Register",
"a",
"phone",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/itemreg/views.py#L194-L209 |
15,757 | tjcsl/ion | docs/conf.py | setup | def setup(app):
"""Setup autodoc."""
# Fix for documenting models.FileField
from django.db.models.fields.files import FileDescriptor
FileDescriptor.__get__ = lambda self, *args, **kwargs: self
import django
django.setup()
app.connect('autodoc-skip-member', skip)
app.add_stylesheet('_static/custom.css') | python | def setup(app):
# Fix for documenting models.FileField
from django.db.models.fields.files import FileDescriptor
FileDescriptor.__get__ = lambda self, *args, **kwargs: self
import django
django.setup()
app.connect('autodoc-skip-member', skip)
app.add_stylesheet('_static/custom.css') | [
"def",
"setup",
"(",
"app",
")",
":",
"# Fix for documenting models.FileField",
"from",
"django",
".",
"db",
".",
"models",
".",
"fields",
".",
"files",
"import",
"FileDescriptor",
"FileDescriptor",
".",
"__get__",
"=",
"lambda",
"self",
",",
"*",
"args",
",",... | Setup autodoc. | [
"Setup",
"autodoc",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/docs/conf.py#L325-L333 |
15,758 | tjcsl/ion | intranet/apps/users/views.py | profile_view | def profile_view(request, user_id=None):
"""Displays a view of a user's profile.
Args:
user_id
The ID of the user whose profile is being viewed. If not
specified, show the user's own profile.
"""
if request.user.is_eighthoffice and "full" not in request.GET and user_id is not None:
return redirect("eighth_profile", user_id=user_id)
if user_id is not None:
try:
profile_user = User.objects.get(id=user_id)
if profile_user is None:
raise Http404
except User.DoesNotExist:
raise Http404
else:
profile_user = request.user
num_blocks = 6
eighth_schedule = []
start_block = EighthBlock.objects.get_first_upcoming_block()
blocks = []
if start_block:
blocks = [start_block] + list(start_block.next_blocks(num_blocks - 1))
for block in blocks:
sch = {"block": block}
try:
sch["signup"] = EighthSignup.objects.get(scheduled_activity__block=block, user=profile_user)
except EighthSignup.DoesNotExist:
sch["signup"] = None
except MultipleObjectsReturned:
client.captureException()
sch["signup"] = None
eighth_schedule.append(sch)
if profile_user.is_eighth_sponsor:
sponsor = EighthSponsor.objects.get(user=profile_user)
start_date = get_start_date(request)
eighth_sponsor_schedule = (EighthScheduledActivity.objects.for_sponsor(sponsor).filter(block__date__gte=start_date).order_by(
"block__date", "block__block_letter"))
eighth_sponsor_schedule = eighth_sponsor_schedule[:10]
else:
eighth_sponsor_schedule = None
admin_or_teacher = (request.user.is_eighth_admin or request.user.is_teacher)
can_view_eighth = (profile_user.can_view_eighth or request.user == profile_user)
eighth_restricted_msg = (not can_view_eighth and admin_or_teacher)
if not can_view_eighth and not request.user.is_eighth_admin and not request.user.is_teacher:
eighth_schedule = []
has_been_nominated = profile_user.username in [
u.nominee.username for u in request.user.nomination_votes.filter(position__position_name=settings.NOMINATION_POSITION)
]
context = {
"profile_user": profile_user,
"eighth_schedule": eighth_schedule,
"can_view_eighth": can_view_eighth,
"eighth_restricted_msg": eighth_restricted_msg,
"eighth_sponsor_schedule": eighth_sponsor_schedule,
"nominations_active": settings.NOMINATIONS_ACTIVE,
"nomination_position": settings.NOMINATION_POSITION,
"has_been_nominated": has_been_nominated
}
return render(request, "users/profile.html", context) | python | def profile_view(request, user_id=None):
if request.user.is_eighthoffice and "full" not in request.GET and user_id is not None:
return redirect("eighth_profile", user_id=user_id)
if user_id is not None:
try:
profile_user = User.objects.get(id=user_id)
if profile_user is None:
raise Http404
except User.DoesNotExist:
raise Http404
else:
profile_user = request.user
num_blocks = 6
eighth_schedule = []
start_block = EighthBlock.objects.get_first_upcoming_block()
blocks = []
if start_block:
blocks = [start_block] + list(start_block.next_blocks(num_blocks - 1))
for block in blocks:
sch = {"block": block}
try:
sch["signup"] = EighthSignup.objects.get(scheduled_activity__block=block, user=profile_user)
except EighthSignup.DoesNotExist:
sch["signup"] = None
except MultipleObjectsReturned:
client.captureException()
sch["signup"] = None
eighth_schedule.append(sch)
if profile_user.is_eighth_sponsor:
sponsor = EighthSponsor.objects.get(user=profile_user)
start_date = get_start_date(request)
eighth_sponsor_schedule = (EighthScheduledActivity.objects.for_sponsor(sponsor).filter(block__date__gte=start_date).order_by(
"block__date", "block__block_letter"))
eighth_sponsor_schedule = eighth_sponsor_schedule[:10]
else:
eighth_sponsor_schedule = None
admin_or_teacher = (request.user.is_eighth_admin or request.user.is_teacher)
can_view_eighth = (profile_user.can_view_eighth or request.user == profile_user)
eighth_restricted_msg = (not can_view_eighth and admin_or_teacher)
if not can_view_eighth and not request.user.is_eighth_admin and not request.user.is_teacher:
eighth_schedule = []
has_been_nominated = profile_user.username in [
u.nominee.username for u in request.user.nomination_votes.filter(position__position_name=settings.NOMINATION_POSITION)
]
context = {
"profile_user": profile_user,
"eighth_schedule": eighth_schedule,
"can_view_eighth": can_view_eighth,
"eighth_restricted_msg": eighth_restricted_msg,
"eighth_sponsor_schedule": eighth_sponsor_schedule,
"nominations_active": settings.NOMINATIONS_ACTIVE,
"nomination_position": settings.NOMINATION_POSITION,
"has_been_nominated": has_been_nominated
}
return render(request, "users/profile.html", context) | [
"def",
"profile_view",
"(",
"request",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"request",
".",
"user",
".",
"is_eighthoffice",
"and",
"\"full\"",
"not",
"in",
"request",
".",
"GET",
"and",
"user_id",
"is",
"not",
"None",
":",
"return",
"redirect",
"... | Displays a view of a user's profile.
Args:
user_id
The ID of the user whose profile is being viewed. If not
specified, show the user's own profile. | [
"Displays",
"a",
"view",
"of",
"a",
"user",
"s",
"profile",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/views.py#L24-L96 |
15,759 | tjcsl/ion | intranet/apps/users/views.py | picture_view | def picture_view(request, user_id, year=None):
"""Displays a view of a user's picture.
Args:
user_id
The ID of the user whose picture is being fetched.
year
The user's picture from this year is fetched. If not
specified, use the preferred picture.
"""
try:
user = User.objects.get(id=user_id)
except User.DoesNotExist:
raise Http404
default_image_path = os.path.join(settings.PROJECT_ROOT, "static/img/default_profile_pic.png")
if user is None:
raise Http404
else:
if year is None:
preferred = user.preferred_photo
if preferred is None:
data = user.default_photo
if data is None:
image_buffer = io.open(default_image_path, mode="rb")
else:
image_buffer = io.BytesIO(data)
# Exclude 'graduate' from names array
else:
data = preferred.binary
if data:
image_buffer = io.BytesIO(data)
else:
image_buffer = io.open(default_image_path, mode="rb")
else:
grade_number = Grade.number_from_name(year)
if user.photos.filter(grade_number=grade_number).exists():
data = user.photos.filter(grade_number=grade_number).first().binary
else:
data = None
if data:
image_buffer = io.BytesIO(data)
else:
image_buffer = io.open(default_image_path, mode="rb")
response = HttpResponse(content_type="image/jpeg")
response["Content-Disposition"] = "filename={}_{}.jpg".format(user_id, year or preferred)
try:
img = image_buffer.read()
except UnicodeDecodeError:
img = io.open(default_image_path, mode="rb").read()
image_buffer.close()
response.write(img)
return response | python | def picture_view(request, user_id, year=None):
try:
user = User.objects.get(id=user_id)
except User.DoesNotExist:
raise Http404
default_image_path = os.path.join(settings.PROJECT_ROOT, "static/img/default_profile_pic.png")
if user is None:
raise Http404
else:
if year is None:
preferred = user.preferred_photo
if preferred is None:
data = user.default_photo
if data is None:
image_buffer = io.open(default_image_path, mode="rb")
else:
image_buffer = io.BytesIO(data)
# Exclude 'graduate' from names array
else:
data = preferred.binary
if data:
image_buffer = io.BytesIO(data)
else:
image_buffer = io.open(default_image_path, mode="rb")
else:
grade_number = Grade.number_from_name(year)
if user.photos.filter(grade_number=grade_number).exists():
data = user.photos.filter(grade_number=grade_number).first().binary
else:
data = None
if data:
image_buffer = io.BytesIO(data)
else:
image_buffer = io.open(default_image_path, mode="rb")
response = HttpResponse(content_type="image/jpeg")
response["Content-Disposition"] = "filename={}_{}.jpg".format(user_id, year or preferred)
try:
img = image_buffer.read()
except UnicodeDecodeError:
img = io.open(default_image_path, mode="rb").read()
image_buffer.close()
response.write(img)
return response | [
"def",
"picture_view",
"(",
"request",
",",
"user_id",
",",
"year",
"=",
"None",
")",
":",
"try",
":",
"user",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"user_id",
")",
"except",
"User",
".",
"DoesNotExist",
":",
"raise",
"Http404",
"d... | Displays a view of a user's picture.
Args:
user_id
The ID of the user whose picture is being fetched.
year
The user's picture from this year is fetched. If not
specified, use the preferred picture. | [
"Displays",
"a",
"view",
"of",
"a",
"user",
"s",
"picture",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/users/views.py#L100-L158 |
15,760 | agoragames/kairos | kairos/sql_backend.py | SqlBackend.expire | def expire(self, name):
'''
Expire all the data.
'''
for interval,config in self._intervals.items():
if config['expire']:
# Because we're storing the bucket time, expiry has the same
# "skew" as whatever the buckets are.
expire_from = config['i_calc'].to_bucket(time.time() - config['expire'])
conn = self._client.connect()
conn.execute( self._table.delete().where(
and_(
self._table.c.name==name,
self._table.c.interval==interval,
self._table.c.i_time<=expire_from
)
)) | python | def expire(self, name):
'''
Expire all the data.
'''
for interval,config in self._intervals.items():
if config['expire']:
# Because we're storing the bucket time, expiry has the same
# "skew" as whatever the buckets are.
expire_from = config['i_calc'].to_bucket(time.time() - config['expire'])
conn = self._client.connect()
conn.execute( self._table.delete().where(
and_(
self._table.c.name==name,
self._table.c.interval==interval,
self._table.c.i_time<=expire_from
)
)) | [
"def",
"expire",
"(",
"self",
",",
"name",
")",
":",
"for",
"interval",
",",
"config",
"in",
"self",
".",
"_intervals",
".",
"items",
"(",
")",
":",
"if",
"config",
"[",
"'expire'",
"]",
":",
"# Because we're storing the bucket time, expiry has the same",
"# \... | Expire all the data. | [
"Expire",
"all",
"the",
"data",
"."
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/sql_backend.py#L161-L178 |
15,761 | agoragames/kairos | kairos/sql_backend.py | SqlGauge._update_data | def _update_data(self, name, value, timestamp, interval, config, conn):
'''Support function for insert. Should be called within a transaction'''
i_time = config['i_calc'].to_bucket(timestamp)
if not config['coarse']:
r_time = config['r_calc'].to_bucket(timestamp)
else:
r_time = None
stmt = self._table.update().where(
and_(
self._table.c.name==name,
self._table.c.interval==interval,
self._table.c.i_time==i_time,
self._table.c.r_time==r_time)
).values({self._table.c.value: value})
rval = conn.execute( stmt )
return rval.rowcount | python | def _update_data(self, name, value, timestamp, interval, config, conn):
'''Support function for insert. Should be called within a transaction'''
i_time = config['i_calc'].to_bucket(timestamp)
if not config['coarse']:
r_time = config['r_calc'].to_bucket(timestamp)
else:
r_time = None
stmt = self._table.update().where(
and_(
self._table.c.name==name,
self._table.c.interval==interval,
self._table.c.i_time==i_time,
self._table.c.r_time==r_time)
).values({self._table.c.value: value})
rval = conn.execute( stmt )
return rval.rowcount | [
"def",
"_update_data",
"(",
"self",
",",
"name",
",",
"value",
",",
"timestamp",
",",
"interval",
",",
"config",
",",
"conn",
")",
":",
"i_time",
"=",
"config",
"[",
"'i_calc'",
"]",
".",
"to_bucket",
"(",
"timestamp",
")",
"if",
"not",
"config",
"[",
... | Support function for insert. Should be called within a transaction | [
"Support",
"function",
"for",
"insert",
".",
"Should",
"be",
"called",
"within",
"a",
"transaction"
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/sql_backend.py#L528-L543 |
15,762 | tjcsl/ion | intranet/utils/urls.py | add_get_parameters | def add_get_parameters(url, parameters, percent_encode=True):
"""Utility function to add GET parameters to an existing URL.
Args:
parameters
A dictionary of the parameters that should be added.
percent_encode
Whether the query parameters should be percent encoded.
Returns:
The updated URL.
"""
url_parts = list(parse.urlparse(url))
query = dict(parse.parse_qs(url_parts[4]))
query.update(parameters)
if percent_encode:
url_parts[4] = parse.urlencode(query)
else:
url_parts[4] = "&".join([key + "=" + value for key, value in query.items()])
return parse.urlunparse(url_parts) | python | def add_get_parameters(url, parameters, percent_encode=True):
url_parts = list(parse.urlparse(url))
query = dict(parse.parse_qs(url_parts[4]))
query.update(parameters)
if percent_encode:
url_parts[4] = parse.urlencode(query)
else:
url_parts[4] = "&".join([key + "=" + value for key, value in query.items()])
return parse.urlunparse(url_parts) | [
"def",
"add_get_parameters",
"(",
"url",
",",
"parameters",
",",
"percent_encode",
"=",
"True",
")",
":",
"url_parts",
"=",
"list",
"(",
"parse",
".",
"urlparse",
"(",
"url",
")",
")",
"query",
"=",
"dict",
"(",
"parse",
".",
"parse_qs",
"(",
"url_parts"... | Utility function to add GET parameters to an existing URL.
Args:
parameters
A dictionary of the parameters that should be added.
percent_encode
Whether the query parameters should be percent encoded.
Returns:
The updated URL. | [
"Utility",
"function",
"to",
"add",
"GET",
"parameters",
"to",
"an",
"existing",
"URL",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/utils/urls.py#L6-L28 |
15,763 | tjcsl/ion | intranet/apps/context_processors.py | mobile_app | def mobile_app(request):
"""Determine if the site is being displayed in a WebView from a native application."""
ctx = {}
try:
ua = request.META.get('HTTP_USER_AGENT', '')
if "IonAndroid: gcmFrame" in ua:
logger.debug("IonAndroid %s", request.user)
ctx["is_android_client"] = True
registered = "appRegistered:False" in ua
ctx["android_client_registered"] = registered
if request.user and request.user.is_authenticated:
"""Add/update NotificationConfig object."""
import binascii
import os
from intranet.apps.notifications.models import NotificationConfig
from datetime import datetime
ncfg, _ = NotificationConfig.objects.get_or_create(user=request.user)
if not ncfg.android_gcm_rand:
rand = binascii.b2a_hex(os.urandom(32))
ncfg.android_gcm_rand = rand
else:
rand = ncfg.android_gcm_rand
ncfg.android_gcm_time = datetime.now()
logger.debug("GCM random token generated: %s", rand)
ncfg.save()
ctx["android_client_rand"] = rand
else:
ctx["is_android_client"] = False
ctx["android_client_register"] = False
except Exception:
ctx["is_android_client"] = False
ctx["android_client_register"] = False
return ctx | python | def mobile_app(request):
ctx = {}
try:
ua = request.META.get('HTTP_USER_AGENT', '')
if "IonAndroid: gcmFrame" in ua:
logger.debug("IonAndroid %s", request.user)
ctx["is_android_client"] = True
registered = "appRegistered:False" in ua
ctx["android_client_registered"] = registered
if request.user and request.user.is_authenticated:
"""Add/update NotificationConfig object."""
import binascii
import os
from intranet.apps.notifications.models import NotificationConfig
from datetime import datetime
ncfg, _ = NotificationConfig.objects.get_or_create(user=request.user)
if not ncfg.android_gcm_rand:
rand = binascii.b2a_hex(os.urandom(32))
ncfg.android_gcm_rand = rand
else:
rand = ncfg.android_gcm_rand
ncfg.android_gcm_time = datetime.now()
logger.debug("GCM random token generated: %s", rand)
ncfg.save()
ctx["android_client_rand"] = rand
else:
ctx["is_android_client"] = False
ctx["android_client_register"] = False
except Exception:
ctx["is_android_client"] = False
ctx["android_client_register"] = False
return ctx | [
"def",
"mobile_app",
"(",
"request",
")",
":",
"ctx",
"=",
"{",
"}",
"try",
":",
"ua",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_USER_AGENT'",
",",
"''",
")",
"if",
"\"IonAndroid: gcmFrame\"",
"in",
"ua",
":",
"logger",
".",
"debug",
"(",
... | Determine if the site is being displayed in a WebView from a native application. | [
"Determine",
"if",
"the",
"site",
"is",
"being",
"displayed",
"in",
"a",
"WebView",
"from",
"a",
"native",
"application",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/context_processors.py#L43-L83 |
15,764 | tjcsl/ion | intranet/apps/context_processors.py | global_custom_theme | def global_custom_theme(request):
"""Add custom theme javascript and css."""
today = datetime.datetime.now().date()
theme = {}
if today.month == 3 and (14 <= today.day <= 16):
theme = {"css": "themes/piday/piday.css"}
return {"theme": theme} | python | def global_custom_theme(request):
today = datetime.datetime.now().date()
theme = {}
if today.month == 3 and (14 <= today.day <= 16):
theme = {"css": "themes/piday/piday.css"}
return {"theme": theme} | [
"def",
"global_custom_theme",
"(",
"request",
")",
":",
"today",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"date",
"(",
")",
"theme",
"=",
"{",
"}",
"if",
"today",
".",
"month",
"==",
"3",
"and",
"(",
"14",
"<=",
"today",
".",
... | Add custom theme javascript and css. | [
"Add",
"custom",
"theme",
"javascript",
"and",
"css",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/context_processors.py#L86-L94 |
15,765 | tjcsl/ion | intranet/utils/admin_helpers.py | export_csv_action | def export_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True):
"""This function returns an export csv action.
'fields' and 'exclude' work like in django
ModelForm 'header' is whether or not to output the column names as the first row.
https://djangosnippets.org/snippets/2369/
"""
def export_as_csv(modeladmin, request, queryset):
"""Generic csv export admin action.
based on http://djangosnippets.org/snippets/1697/
"""
opts = modeladmin.model._meta
field_names = set([field.name for field in opts.fields])
if fields:
fieldset = set(fields)
field_names = field_names & fieldset
elif exclude:
excludeset = set(exclude)
field_names = field_names - excludeset
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_')
writer = csv.writer(response)
if header:
writer.writerow(list(field_names))
for obj in queryset:
writer.writerow([str(getattr(obj, field)) for field in field_names])
return response
export_as_csv.short_description = description
return export_as_csv | python | def export_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True):
def export_as_csv(modeladmin, request, queryset):
"""Generic csv export admin action.
based on http://djangosnippets.org/snippets/1697/
"""
opts = modeladmin.model._meta
field_names = set([field.name for field in opts.fields])
if fields:
fieldset = set(fields)
field_names = field_names & fieldset
elif exclude:
excludeset = set(exclude)
field_names = field_names - excludeset
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_')
writer = csv.writer(response)
if header:
writer.writerow(list(field_names))
for obj in queryset:
writer.writerow([str(getattr(obj, field)) for field in field_names])
return response
export_as_csv.short_description = description
return export_as_csv | [
"def",
"export_csv_action",
"(",
"description",
"=",
"\"Export selected objects as CSV file\"",
",",
"fields",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"header",
"=",
"True",
")",
":",
"def",
"export_as_csv",
"(",
"modeladmin",
",",
"request",
",",
"querys... | This function returns an export csv action.
'fields' and 'exclude' work like in django
ModelForm 'header' is whether or not to output the column names as the first row.
https://djangosnippets.org/snippets/2369/ | [
"This",
"function",
"returns",
"an",
"export",
"csv",
"action",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/utils/admin_helpers.py#L6-L43 |
15,766 | tjcsl/ion | intranet/apps/eighth/management/commands/import_permissions.py | Command.handle | def handle(self, **options):
"""Exported "eighth_activity_permissions" table in CSV format."""
perm_map = {}
with open('eighth_activity_permissions.csv', 'r') as absperms:
perms = csv.reader(absperms)
for row in perms:
aid, uid = row
try:
usr = User.objects.get(id=uid)
except User.DoesNotExist:
self.stdout.write("User {} doesn't exist, aid {}".format(uid, aid))
else:
if aid in perm_map:
perm_map[aid].append(usr)
else:
perm_map[aid] = [usr]
for aid in perm_map:
try:
act = EighthActivity.objects.get(id=aid)
except EighthActivity.DoesNotExist:
self.stdout.write("Activity {} doesn't exist".format(aid))
else:
self.stdout.write("{}: {}".format(aid, EighthActivity.objects.get(id=aid)))
grp, _ = Group.objects.get_or_create(name="{} -- Permissions".format("{}".format(act)[:55]))
users = perm_map[aid]
for u in users:
u.groups.add(grp)
u.save()
act.groups_allowed.add(grp)
act.save()
self.stdout.write("Done.") | python | def handle(self, **options):
perm_map = {}
with open('eighth_activity_permissions.csv', 'r') as absperms:
perms = csv.reader(absperms)
for row in perms:
aid, uid = row
try:
usr = User.objects.get(id=uid)
except User.DoesNotExist:
self.stdout.write("User {} doesn't exist, aid {}".format(uid, aid))
else:
if aid in perm_map:
perm_map[aid].append(usr)
else:
perm_map[aid] = [usr]
for aid in perm_map:
try:
act = EighthActivity.objects.get(id=aid)
except EighthActivity.DoesNotExist:
self.stdout.write("Activity {} doesn't exist".format(aid))
else:
self.stdout.write("{}: {}".format(aid, EighthActivity.objects.get(id=aid)))
grp, _ = Group.objects.get_or_create(name="{} -- Permissions".format("{}".format(act)[:55]))
users = perm_map[aid]
for u in users:
u.groups.add(grp)
u.save()
act.groups_allowed.add(grp)
act.save()
self.stdout.write("Done.") | [
"def",
"handle",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"perm_map",
"=",
"{",
"}",
"with",
"open",
"(",
"'eighth_activity_permissions.csv'",
",",
"'r'",
")",
"as",
"absperms",
":",
"perms",
"=",
"csv",
".",
"reader",
"(",
"absperms",
")",
"fo... | Exported "eighth_activity_permissions" table in CSV format. | [
"Exported",
"eighth_activity_permissions",
"table",
"in",
"CSV",
"format",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/management/commands/import_permissions.py#L15-L47 |
15,767 | tjcsl/ion | intranet/apps/printing/views.py | check_page_range | def check_page_range(page_range, max_pages):
"""Returns the number of pages in the range, or False if it is an invalid range."""
pages = 0
try:
for r in page_range.split(","): # check all ranges separated by commas
if "-" in r:
rr = r.split("-")
if len(rr) != 2: # make sure 2 values in range
return False
else:
rl = int(rr[0])
rh = int(rr[1])
# check in page range
if not 0 < rl < max_pages and not 0 < rh < max_pages:
return False
if rl > rh: # check lower bound <= upper bound
return False
pages += rh - rl + 1
else:
if not 0 < int(r) <= max_pages: # check in page range
return False
pages += 1
except ValueError: # catch int parse fail
return False
return pages | python | def check_page_range(page_range, max_pages):
pages = 0
try:
for r in page_range.split(","): # check all ranges separated by commas
if "-" in r:
rr = r.split("-")
if len(rr) != 2: # make sure 2 values in range
return False
else:
rl = int(rr[0])
rh = int(rr[1])
# check in page range
if not 0 < rl < max_pages and not 0 < rh < max_pages:
return False
if rl > rh: # check lower bound <= upper bound
return False
pages += rh - rl + 1
else:
if not 0 < int(r) <= max_pages: # check in page range
return False
pages += 1
except ValueError: # catch int parse fail
return False
return pages | [
"def",
"check_page_range",
"(",
"page_range",
",",
"max_pages",
")",
":",
"pages",
"=",
"0",
"try",
":",
"for",
"r",
"in",
"page_range",
".",
"split",
"(",
"\",\"",
")",
":",
"# check all ranges separated by commas",
"if",
"\"-\"",
"in",
"r",
":",
"rr",
"=... | Returns the number of pages in the range, or False if it is an invalid range. | [
"Returns",
"the",
"number",
"of",
"pages",
"in",
"the",
"range",
"or",
"False",
"if",
"it",
"is",
"an",
"invalid",
"range",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/printing/views.py#L128-L152 |
15,768 | tjcsl/ion | intranet/apps/announcements/notifications.py | request_announcement_email | def request_announcement_email(request, form, obj):
"""Send an announcement request email.
form: The announcement request form
obj: The announcement request object
"""
logger.debug(form.data)
teacher_ids = form.data["teachers_requested"]
if not isinstance(teacher_ids, list):
teacher_ids = [teacher_ids]
logger.debug(teacher_ids)
teachers = User.objects.filter(id__in=teacher_ids)
logger.debug(teachers)
subject = "News Post Confirmation Request from {}".format(request.user.full_name)
emails = []
for teacher in teachers:
emails.append(teacher.tj_email)
logger.debug(emails)
logger.info("%s: Announcement request to %s, %s", request.user, teachers, emails)
base_url = request.build_absolute_uri(reverse('index'))
data = {
"teachers": teachers,
"user": request.user,
"formdata": form.data,
"info_link": request.build_absolute_uri(reverse("approve_announcement", args=[obj.id])),
"base_url": base_url
}
logger.info("%s: Announcement request %s", request.user, data)
email_send("announcements/emails/teacher_approve.txt", "announcements/emails/teacher_approve.html", data, subject, emails) | python | def request_announcement_email(request, form, obj):
logger.debug(form.data)
teacher_ids = form.data["teachers_requested"]
if not isinstance(teacher_ids, list):
teacher_ids = [teacher_ids]
logger.debug(teacher_ids)
teachers = User.objects.filter(id__in=teacher_ids)
logger.debug(teachers)
subject = "News Post Confirmation Request from {}".format(request.user.full_name)
emails = []
for teacher in teachers:
emails.append(teacher.tj_email)
logger.debug(emails)
logger.info("%s: Announcement request to %s, %s", request.user, teachers, emails)
base_url = request.build_absolute_uri(reverse('index'))
data = {
"teachers": teachers,
"user": request.user,
"formdata": form.data,
"info_link": request.build_absolute_uri(reverse("approve_announcement", args=[obj.id])),
"base_url": base_url
}
logger.info("%s: Announcement request %s", request.user, data)
email_send("announcements/emails/teacher_approve.txt", "announcements/emails/teacher_approve.html", data, subject, emails) | [
"def",
"request_announcement_email",
"(",
"request",
",",
"form",
",",
"obj",
")",
":",
"logger",
".",
"debug",
"(",
"form",
".",
"data",
")",
"teacher_ids",
"=",
"form",
".",
"data",
"[",
"\"teachers_requested\"",
"]",
"if",
"not",
"isinstance",
"(",
"tea... | Send an announcement request email.
form: The announcement request form
obj: The announcement request object | [
"Send",
"an",
"announcement",
"request",
"email",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/notifications.py#L22-L53 |
15,769 | tjcsl/ion | intranet/apps/announcements/notifications.py | admin_request_announcement_email | def admin_request_announcement_email(request, form, obj):
"""Send an admin announcement request email.
form: The announcement request form
obj: The announcement request object
"""
subject = "News Post Approval Needed ({})".format(obj.title)
emails = [settings.APPROVAL_EMAIL]
base_url = request.build_absolute_uri(reverse('index'))
data = {
"req": obj,
"formdata": form.data,
"info_link": request.build_absolute_uri(reverse("admin_approve_announcement", args=[obj.id])),
"base_url": base_url
}
email_send("announcements/emails/admin_approve.txt", "announcements/emails/admin_approve.html", data, subject, emails) | python | def admin_request_announcement_email(request, form, obj):
subject = "News Post Approval Needed ({})".format(obj.title)
emails = [settings.APPROVAL_EMAIL]
base_url = request.build_absolute_uri(reverse('index'))
data = {
"req": obj,
"formdata": form.data,
"info_link": request.build_absolute_uri(reverse("admin_approve_announcement", args=[obj.id])),
"base_url": base_url
}
email_send("announcements/emails/admin_approve.txt", "announcements/emails/admin_approve.html", data, subject, emails) | [
"def",
"admin_request_announcement_email",
"(",
"request",
",",
"form",
",",
"obj",
")",
":",
"subject",
"=",
"\"News Post Approval Needed ({})\"",
".",
"format",
"(",
"obj",
".",
"title",
")",
"emails",
"=",
"[",
"settings",
".",
"APPROVAL_EMAIL",
"]",
"base_ur... | Send an admin announcement request email.
form: The announcement request form
obj: The announcement request object | [
"Send",
"an",
"admin",
"announcement",
"request",
"email",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/notifications.py#L56-L73 |
15,770 | tjcsl/ion | intranet/apps/announcements/notifications.py | announcement_approved_email | def announcement_approved_email(request, obj, req):
"""Email the requested teachers and submitter whenever an administrator approves an announcement
request.
obj: the Announcement object
req: the AnnouncementRequest object
"""
if not settings.PRODUCTION:
logger.debug("Not in production. Ignoring email for approved announcement.")
return
subject = "Announcement Approved: {}".format(obj.title)
""" Email to teachers who approved. """
teachers = req.teachers_approved.all()
teacher_emails = []
for u in teachers:
em = u.tj_email
if em:
teacher_emails.append(em)
base_url = request.build_absolute_uri(reverse('index'))
url = request.build_absolute_uri(reverse('view_announcement', args=[obj.id]))
if len(teacher_emails) > 0:
data = {"announcement": obj, "request": req, "info_link": url, "base_url": base_url, "role": "approved"}
email_send("announcements/emails/announcement_approved.txt", "announcements/emails/announcement_approved.html", data, subject, teacher_emails)
messages.success(request, "Sent teacher approved email to {} users".format(len(teacher_emails)))
""" Email to submitter. """
submitter = req.user
submitter_email = submitter.tj_email
if submitter_email:
submitter_emails = [submitter_email]
data = {"announcement": obj, "request": req, "info_link": url, "base_url": base_url, "role": "submitted"}
email_send("announcements/emails/announcement_approved.txt", "announcements/emails/announcement_approved.html", data, subject,
submitter_emails)
messages.success(request, "Sent teacher approved email to {} users".format(len(submitter_emails))) | python | def announcement_approved_email(request, obj, req):
if not settings.PRODUCTION:
logger.debug("Not in production. Ignoring email for approved announcement.")
return
subject = "Announcement Approved: {}".format(obj.title)
""" Email to teachers who approved. """
teachers = req.teachers_approved.all()
teacher_emails = []
for u in teachers:
em = u.tj_email
if em:
teacher_emails.append(em)
base_url = request.build_absolute_uri(reverse('index'))
url = request.build_absolute_uri(reverse('view_announcement', args=[obj.id]))
if len(teacher_emails) > 0:
data = {"announcement": obj, "request": req, "info_link": url, "base_url": base_url, "role": "approved"}
email_send("announcements/emails/announcement_approved.txt", "announcements/emails/announcement_approved.html", data, subject, teacher_emails)
messages.success(request, "Sent teacher approved email to {} users".format(len(teacher_emails)))
""" Email to submitter. """
submitter = req.user
submitter_email = submitter.tj_email
if submitter_email:
submitter_emails = [submitter_email]
data = {"announcement": obj, "request": req, "info_link": url, "base_url": base_url, "role": "submitted"}
email_send("announcements/emails/announcement_approved.txt", "announcements/emails/announcement_approved.html", data, subject,
submitter_emails)
messages.success(request, "Sent teacher approved email to {} users".format(len(submitter_emails))) | [
"def",
"announcement_approved_email",
"(",
"request",
",",
"obj",
",",
"req",
")",
":",
"if",
"not",
"settings",
".",
"PRODUCTION",
":",
"logger",
".",
"debug",
"(",
"\"Not in production. Ignoring email for approved announcement.\"",
")",
"return",
"subject",
"=",
"... | Email the requested teachers and submitter whenever an administrator approves an announcement
request.
obj: the Announcement object
req: the AnnouncementRequest object | [
"Email",
"the",
"requested",
"teachers",
"and",
"submitter",
"whenever",
"an",
"administrator",
"approves",
"an",
"announcement",
"request",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/notifications.py#L76-L113 |
15,771 | tjcsl/ion | intranet/apps/announcements/notifications.py | announcement_posted_email | def announcement_posted_email(request, obj, send_all=False):
"""Send a notification posted email.
obj: The announcement object
"""
if settings.EMAIL_ANNOUNCEMENTS:
subject = "Announcement: {}".format(obj.title)
if send_all:
users = User.objects.all()
else:
users = User.objects.filter(receive_news_emails=True)
send_groups = obj.groups.all()
emails = []
users_send = []
for u in users:
if len(send_groups) == 0:
# no groups, public.
em = u.emails.first() if u.emails.count() >= 1 else u.tj_email
if em:
emails.append(em)
users_send.append(u)
else:
# specific to a group
user_groups = u.groups.all()
if any(i in send_groups for i in user_groups):
# group intersection exists
em = u.emails.first() if u.emails.count() >= 1 else u.tj_email
if em:
emails.append(em)
users_send.append(u)
logger.debug(users_send)
logger.debug(emails)
if not settings.PRODUCTION and len(emails) > 3:
raise exceptions.PermissionDenied("You're about to email a lot of people, and you aren't in production!")
return
base_url = request.build_absolute_uri(reverse('index'))
url = request.build_absolute_uri(reverse('view_announcement', args=[obj.id]))
data = {"announcement": obj, "info_link": url, "base_url": base_url}
email_send_bcc("announcements/emails/announcement_posted.txt", "announcements/emails/announcement_posted.html", data, subject, emails)
messages.success(request, "Sent email to {} users".format(len(users_send)))
else:
logger.debug("Emailing announcements disabled") | python | def announcement_posted_email(request, obj, send_all=False):
if settings.EMAIL_ANNOUNCEMENTS:
subject = "Announcement: {}".format(obj.title)
if send_all:
users = User.objects.all()
else:
users = User.objects.filter(receive_news_emails=True)
send_groups = obj.groups.all()
emails = []
users_send = []
for u in users:
if len(send_groups) == 0:
# no groups, public.
em = u.emails.first() if u.emails.count() >= 1 else u.tj_email
if em:
emails.append(em)
users_send.append(u)
else:
# specific to a group
user_groups = u.groups.all()
if any(i in send_groups for i in user_groups):
# group intersection exists
em = u.emails.first() if u.emails.count() >= 1 else u.tj_email
if em:
emails.append(em)
users_send.append(u)
logger.debug(users_send)
logger.debug(emails)
if not settings.PRODUCTION and len(emails) > 3:
raise exceptions.PermissionDenied("You're about to email a lot of people, and you aren't in production!")
return
base_url = request.build_absolute_uri(reverse('index'))
url = request.build_absolute_uri(reverse('view_announcement', args=[obj.id]))
data = {"announcement": obj, "info_link": url, "base_url": base_url}
email_send_bcc("announcements/emails/announcement_posted.txt", "announcements/emails/announcement_posted.html", data, subject, emails)
messages.success(request, "Sent email to {} users".format(len(users_send)))
else:
logger.debug("Emailing announcements disabled") | [
"def",
"announcement_posted_email",
"(",
"request",
",",
"obj",
",",
"send_all",
"=",
"False",
")",
":",
"if",
"settings",
".",
"EMAIL_ANNOUNCEMENTS",
":",
"subject",
"=",
"\"Announcement: {}\"",
".",
"format",
"(",
"obj",
".",
"title",
")",
"if",
"send_all",
... | Send a notification posted email.
obj: The announcement object | [
"Send",
"a",
"notification",
"posted",
"email",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/notifications.py#L116-L163 |
15,772 | agoragames/kairos | kairos/cassandra_backend.py | scoped_connection | def scoped_connection(func):
'''
Decorator that gives out connections.
'''
def _with(series, *args, **kwargs):
connection = None
try:
connection = series._connection()
return func(series, connection, *args, **kwargs)
finally:
series._return( connection )
return _with | python | def scoped_connection(func):
'''
Decorator that gives out connections.
'''
def _with(series, *args, **kwargs):
connection = None
try:
connection = series._connection()
return func(series, connection, *args, **kwargs)
finally:
series._return( connection )
return _with | [
"def",
"scoped_connection",
"(",
"func",
")",
":",
"def",
"_with",
"(",
"series",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"connection",
"=",
"None",
"try",
":",
"connection",
"=",
"series",
".",
"_connection",
"(",
")",
"return",
"func",
... | Decorator that gives out connections. | [
"Decorator",
"that",
"gives",
"out",
"connections",
"."
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/cassandra_backend.py#L66-L77 |
15,773 | agoragames/kairos | kairos/cassandra_backend.py | CassandraBackend._connection | def _connection(self):
'''
Return a connection from the pool
'''
try:
return self._pool.get(False)
except Empty:
args = [
self._host, self._port, self._keyspace
]
kwargs = {
'user' : None,
'password' : None,
'cql_version' : self._cql_version,
'compression' : self._compression,
'consistency_level' : self._consistency_level,
'transport' : self._transport,
}
if self._credentials:
kwargs['user'] = self._credentials['user']
kwargs['password'] = self._credentials['password']
return cql.connect(*args, **kwargs) | python | def _connection(self):
'''
Return a connection from the pool
'''
try:
return self._pool.get(False)
except Empty:
args = [
self._host, self._port, self._keyspace
]
kwargs = {
'user' : None,
'password' : None,
'cql_version' : self._cql_version,
'compression' : self._compression,
'consistency_level' : self._consistency_level,
'transport' : self._transport,
}
if self._credentials:
kwargs['user'] = self._credentials['user']
kwargs['password'] = self._credentials['password']
return cql.connect(*args, **kwargs) | [
"def",
"_connection",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_pool",
".",
"get",
"(",
"False",
")",
"except",
"Empty",
":",
"args",
"=",
"[",
"self",
".",
"_host",
",",
"self",
".",
"_port",
",",
"self",
".",
"_keyspace",
"]",
... | Return a connection from the pool | [
"Return",
"a",
"connection",
"from",
"the",
"pool"
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/cassandra_backend.py#L145-L166 |
15,774 | agoragames/kairos | kairos/cassandra_backend.py | CassandraBackend._insert_data | def _insert_data(self, connection, name, value, timestamp, interval, config):
'''Helper to insert data into cql.'''
cursor = connection.cursor()
try:
stmt = self._insert_stmt(name, value, timestamp, interval, config)
if stmt:
cursor.execute(stmt)
finally:
cursor.close() | python | def _insert_data(self, connection, name, value, timestamp, interval, config):
'''Helper to insert data into cql.'''
cursor = connection.cursor()
try:
stmt = self._insert_stmt(name, value, timestamp, interval, config)
if stmt:
cursor.execute(stmt)
finally:
cursor.close() | [
"def",
"_insert_data",
"(",
"self",
",",
"connection",
",",
"name",
",",
"value",
",",
"timestamp",
",",
"interval",
",",
"config",
")",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"try",
":",
"stmt",
"=",
"self",
".",
"_insert_stmt",
"(... | Helper to insert data into cql. | [
"Helper",
"to",
"insert",
"data",
"into",
"cql",
"."
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/cassandra_backend.py#L188-L196 |
15,775 | tjcsl/ion | intranet/apps/events/models.py | Event.show_fuzzy_date | def show_fuzzy_date(self):
"""Return whether the event is in the next or previous 2 weeks.
Determines whether to display the fuzzy date.
"""
date = self.time.replace(tzinfo=None)
if date <= datetime.now():
diff = datetime.now() - date
if diff.days >= 14:
return False
else:
diff = date - datetime.now()
if diff.days >= 14:
return False
return True | python | def show_fuzzy_date(self):
date = self.time.replace(tzinfo=None)
if date <= datetime.now():
diff = datetime.now() - date
if diff.days >= 14:
return False
else:
diff = date - datetime.now()
if diff.days >= 14:
return False
return True | [
"def",
"show_fuzzy_date",
"(",
"self",
")",
":",
"date",
"=",
"self",
".",
"time",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"if",
"date",
"<=",
"datetime",
".",
"now",
"(",
")",
":",
"diff",
"=",
"datetime",
".",
"now",
"(",
")",
"-",
"da... | Return whether the event is in the next or previous 2 weeks.
Determines whether to display the fuzzy date. | [
"Return",
"whether",
"the",
"event",
"is",
"in",
"the",
"next",
"or",
"previous",
"2",
"weeks",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/events/models.py#L164-L180 |
15,776 | tjcsl/ion | intranet/apps/templatetags/dates.py | fuzzy_date | def fuzzy_date(date):
"""Formats a `datetime.datetime` object relative to the current time."""
date = date.replace(tzinfo=None)
if date <= datetime.now():
diff = datetime.now() - date
seconds = diff.total_seconds()
minutes = seconds // 60
hours = minutes // 60
if minutes <= 1:
return "moments ago"
elif minutes < 60:
return "{} minutes ago".format(int(seconds // 60))
elif hours < 24:
hrs = int(diff.seconds // (60 * 60))
return "{} hour{} ago".format(hrs, "s" if hrs != 1 else "")
elif diff.days == 1:
return "yesterday"
elif diff.days < 7:
return "{} days ago".format(int(seconds // (60 * 60 * 24)))
elif diff.days < 14:
return date.strftime("last %A")
else:
return date.strftime("%A, %B %d, %Y")
else:
diff = date - datetime.now()
seconds = diff.total_seconds()
minutes = seconds // 60
hours = minutes // 60
if minutes <= 1:
return "moments ago"
elif minutes < 60:
return "in {} minutes".format(int(seconds // 60))
elif hours < 24:
hrs = int(diff.seconds // (60 * 60))
return "in {} hour{}".format(hrs, "s" if hrs != 1 else "")
elif diff.days == 1:
return "tomorrow"
elif diff.days < 7:
return "in {} days".format(int(seconds // (60 * 60 * 24)))
elif diff.days < 14:
return date.strftime("next %A")
else:
return date.strftime("%A, %B %d, %Y") | python | def fuzzy_date(date):
date = date.replace(tzinfo=None)
if date <= datetime.now():
diff = datetime.now() - date
seconds = diff.total_seconds()
minutes = seconds // 60
hours = minutes // 60
if minutes <= 1:
return "moments ago"
elif minutes < 60:
return "{} minutes ago".format(int(seconds // 60))
elif hours < 24:
hrs = int(diff.seconds // (60 * 60))
return "{} hour{} ago".format(hrs, "s" if hrs != 1 else "")
elif diff.days == 1:
return "yesterday"
elif diff.days < 7:
return "{} days ago".format(int(seconds // (60 * 60 * 24)))
elif diff.days < 14:
return date.strftime("last %A")
else:
return date.strftime("%A, %B %d, %Y")
else:
diff = date - datetime.now()
seconds = diff.total_seconds()
minutes = seconds // 60
hours = minutes // 60
if minutes <= 1:
return "moments ago"
elif minutes < 60:
return "in {} minutes".format(int(seconds // 60))
elif hours < 24:
hrs = int(diff.seconds // (60 * 60))
return "in {} hour{}".format(hrs, "s" if hrs != 1 else "")
elif diff.days == 1:
return "tomorrow"
elif diff.days < 7:
return "in {} days".format(int(seconds // (60 * 60 * 24)))
elif diff.days < 14:
return date.strftime("next %A")
else:
return date.strftime("%A, %B %d, %Y") | [
"def",
"fuzzy_date",
"(",
"date",
")",
":",
"date",
"=",
"date",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"if",
"date",
"<=",
"datetime",
".",
"now",
"(",
")",
":",
"diff",
"=",
"datetime",
".",
"now",
"(",
")",
"-",
"date",
"seconds",
"=... | Formats a `datetime.datetime` object relative to the current time. | [
"Formats",
"a",
"datetime",
".",
"datetime",
"object",
"relative",
"to",
"the",
"current",
"time",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/templatetags/dates.py#L28-L76 |
15,777 | tjcsl/ion | intranet/apps/signage/templatetags/signage.py | render_page | def render_page(page, page_args):
""" Renders the template at page.template
"""
print(page_args)
template_name = page.template if page.template else page.name
template = "signage/pages/{}.html".format(template_name)
if page.function:
context_method = getattr(pages, page.function)
else:
context_method = getattr(pages, page.name)
sign, request = page_args
context = context_method(page, sign, request)
return render_to_string(template, context) | python | def render_page(page, page_args):
print(page_args)
template_name = page.template if page.template else page.name
template = "signage/pages/{}.html".format(template_name)
if page.function:
context_method = getattr(pages, page.function)
else:
context_method = getattr(pages, page.name)
sign, request = page_args
context = context_method(page, sign, request)
return render_to_string(template, context) | [
"def",
"render_page",
"(",
"page",
",",
"page_args",
")",
":",
"print",
"(",
"page_args",
")",
"template_name",
"=",
"page",
".",
"template",
"if",
"page",
".",
"template",
"else",
"page",
".",
"name",
"template",
"=",
"\"signage/pages/{}.html\"",
".",
"form... | Renders the template at page.template | [
"Renders",
"the",
"template",
"at",
"page",
".",
"template"
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/signage/templatetags/signage.py#L10-L22 |
15,778 | tjcsl/ion | intranet/apps/announcements/views.py | announcement_posted_hook | def announcement_posted_hook(request, obj):
"""Runs whenever a new announcement is created, or a request is approved and posted.
obj: The Announcement object
"""
logger.debug("Announcement posted")
if obj.notify_post:
logger.debug("Announcement notify on")
announcement_posted_twitter(request, obj)
try:
notify_all = obj.notify_email_all
except AttributeError:
notify_all = False
try:
if notify_all:
announcement_posted_email(request, obj, True)
else:
announcement_posted_email(request, obj)
except Exception as e:
logger.error("Exception when emailing announcement: {}".format(e))
messages.error(request, "Exception when emailing announcement: {}".format(e))
raise e
else:
logger.debug("Announcement notify off") | python | def announcement_posted_hook(request, obj):
logger.debug("Announcement posted")
if obj.notify_post:
logger.debug("Announcement notify on")
announcement_posted_twitter(request, obj)
try:
notify_all = obj.notify_email_all
except AttributeError:
notify_all = False
try:
if notify_all:
announcement_posted_email(request, obj, True)
else:
announcement_posted_email(request, obj)
except Exception as e:
logger.error("Exception when emailing announcement: {}".format(e))
messages.error(request, "Exception when emailing announcement: {}".format(e))
raise e
else:
logger.debug("Announcement notify off") | [
"def",
"announcement_posted_hook",
"(",
"request",
",",
"obj",
")",
":",
"logger",
".",
"debug",
"(",
"\"Announcement posted\"",
")",
"if",
"obj",
".",
"notify_post",
":",
"logger",
".",
"debug",
"(",
"\"Announcement notify on\"",
")",
"announcement_posted_twitter",... | Runs whenever a new announcement is created, or a request is approved and posted.
obj: The Announcement object | [
"Runs",
"whenever",
"a",
"new",
"announcement",
"is",
"created",
"or",
"a",
"request",
"is",
"approved",
"and",
"posted",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L40-L66 |
15,779 | tjcsl/ion | intranet/apps/announcements/views.py | request_announcement_view | def request_announcement_view(request):
"""The request announcement page."""
if request.method == "POST":
form = AnnouncementRequestForm(request.POST)
logger.debug(form)
logger.debug(form.data)
if form.is_valid():
teacher_objs = form.cleaned_data["teachers_requested"]
logger.debug("teacher objs:")
logger.debug(teacher_objs)
if len(teacher_objs) > 2:
messages.error(request, "Please select a maximum of 2 teachers to approve this post.")
else:
obj = form.save(commit=True)
obj.user = request.user
# SAFE HTML
obj.content = safe_html(obj.content)
obj.save()
ann = AnnouncementRequest.objects.get(id=obj.id)
logger.debug(teacher_objs)
approve_self = False
for teacher in teacher_objs:
ann.teachers_requested.add(teacher)
if teacher == request.user:
approve_self = True
ann.save()
if approve_self:
ann.teachers_approved.add(teacher)
ann.save()
if settings.SEND_ANNOUNCEMENT_APPROVAL:
admin_request_announcement_email(request, form, ann)
ann.admin_email_sent = True
ann.save()
return redirect("request_announcement_success_self")
else:
if settings.SEND_ANNOUNCEMENT_APPROVAL:
request_announcement_email(request, form, obj)
return redirect("request_announcement_success")
return redirect("index")
else:
messages.error(request, "Error adding announcement request")
else:
form = AnnouncementRequestForm()
return render(request, "announcements/request.html", {"form": form, "action": "add"}) | python | def request_announcement_view(request):
if request.method == "POST":
form = AnnouncementRequestForm(request.POST)
logger.debug(form)
logger.debug(form.data)
if form.is_valid():
teacher_objs = form.cleaned_data["teachers_requested"]
logger.debug("teacher objs:")
logger.debug(teacher_objs)
if len(teacher_objs) > 2:
messages.error(request, "Please select a maximum of 2 teachers to approve this post.")
else:
obj = form.save(commit=True)
obj.user = request.user
# SAFE HTML
obj.content = safe_html(obj.content)
obj.save()
ann = AnnouncementRequest.objects.get(id=obj.id)
logger.debug(teacher_objs)
approve_self = False
for teacher in teacher_objs:
ann.teachers_requested.add(teacher)
if teacher == request.user:
approve_self = True
ann.save()
if approve_self:
ann.teachers_approved.add(teacher)
ann.save()
if settings.SEND_ANNOUNCEMENT_APPROVAL:
admin_request_announcement_email(request, form, ann)
ann.admin_email_sent = True
ann.save()
return redirect("request_announcement_success_self")
else:
if settings.SEND_ANNOUNCEMENT_APPROVAL:
request_announcement_email(request, form, obj)
return redirect("request_announcement_success")
return redirect("index")
else:
messages.error(request, "Error adding announcement request")
else:
form = AnnouncementRequestForm()
return render(request, "announcements/request.html", {"form": form, "action": "add"}) | [
"def",
"request_announcement_view",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"form",
"=",
"AnnouncementRequestForm",
"(",
"request",
".",
"POST",
")",
"logger",
".",
"debug",
"(",
"form",
")",
"logger",
".",
"debug",
... | The request announcement page. | [
"The",
"request",
"announcement",
"page",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L81-L130 |
15,780 | tjcsl/ion | intranet/apps/announcements/views.py | approve_announcement_view | def approve_announcement_view(request, req_id):
"""The approve announcement page. Teachers will be linked to this page from an email.
req_id: The ID of the AnnouncementRequest
"""
req = get_object_or_404(AnnouncementRequest, id=req_id)
requested_teachers = req.teachers_requested.all()
logger.debug(requested_teachers)
if request.user not in requested_teachers:
messages.error(request, "You do not have permission to approve this announcement.")
return redirect("index")
if request.method == "POST":
form = AnnouncementRequestForm(request.POST, instance=req)
if form.is_valid():
obj = form.save(commit=True)
# SAFE HTML
obj.content = safe_html(obj.content)
obj.save()
if "approve" in request.POST:
obj.teachers_approved.add(request.user)
obj.save()
if not obj.admin_email_sent:
if settings.SEND_ANNOUNCEMENT_APPROVAL:
admin_request_announcement_email(request, form, obj)
obj.admin_email_sent = True
obj.save()
return redirect("approve_announcement_success")
else:
obj.save()
return redirect("approve_announcement_reject")
form = AnnouncementRequestForm(instance=req)
context = {"form": form, "req": req, "admin_approve": False}
return render(request, "announcements/approve.html", context) | python | def approve_announcement_view(request, req_id):
req = get_object_or_404(AnnouncementRequest, id=req_id)
requested_teachers = req.teachers_requested.all()
logger.debug(requested_teachers)
if request.user not in requested_teachers:
messages.error(request, "You do not have permission to approve this announcement.")
return redirect("index")
if request.method == "POST":
form = AnnouncementRequestForm(request.POST, instance=req)
if form.is_valid():
obj = form.save(commit=True)
# SAFE HTML
obj.content = safe_html(obj.content)
obj.save()
if "approve" in request.POST:
obj.teachers_approved.add(request.user)
obj.save()
if not obj.admin_email_sent:
if settings.SEND_ANNOUNCEMENT_APPROVAL:
admin_request_announcement_email(request, form, obj)
obj.admin_email_sent = True
obj.save()
return redirect("approve_announcement_success")
else:
obj.save()
return redirect("approve_announcement_reject")
form = AnnouncementRequestForm(instance=req)
context = {"form": form, "req": req, "admin_approve": False}
return render(request, "announcements/approve.html", context) | [
"def",
"approve_announcement_view",
"(",
"request",
",",
"req_id",
")",
":",
"req",
"=",
"get_object_or_404",
"(",
"AnnouncementRequest",
",",
"id",
"=",
"req_id",
")",
"requested_teachers",
"=",
"req",
".",
"teachers_requested",
".",
"all",
"(",
")",
"logger",
... | The approve announcement page. Teachers will be linked to this page from an email.
req_id: The ID of the AnnouncementRequest | [
"The",
"approve",
"announcement",
"page",
".",
"Teachers",
"will",
"be",
"linked",
"to",
"this",
"page",
"from",
"an",
"email",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L147-L184 |
15,781 | tjcsl/ion | intranet/apps/announcements/views.py | admin_approve_announcement_view | def admin_approve_announcement_view(request, req_id):
"""The administrator approval announcement request page. Admins will view this page through the
UI.
req_id: The ID of the AnnouncementRequest
"""
req = get_object_or_404(AnnouncementRequest, id=req_id)
requested_teachers = req.teachers_requested.all()
logger.debug(requested_teachers)
if request.method == "POST":
form = AnnouncementRequestForm(request.POST, instance=req)
if form.is_valid():
req = form.save(commit=True)
# SAFE HTML
req.content = safe_html(req.content)
if "approve" in request.POST:
groups = []
if "groups" in request.POST:
group_ids = request.POST.getlist("groups")
groups = Group.objects.filter(id__in=group_ids)
logger.debug(groups)
announcement = Announcement.objects.create(title=req.title, content=req.content, author=req.author, user=req.user,
expiration_date=req.expiration_date)
for g in groups:
announcement.groups.add(g)
announcement.save()
req.posted = announcement
req.posted_by = request.user
req.save()
announcement_approved_hook(request, announcement, req)
announcement_posted_hook(request, announcement)
messages.success(request, "Successfully approved announcement request. It has been posted.")
else:
req.rejected = True
req.rejected_by = request.user
req.save()
messages.success(request, "You did not approve this request. It will be hidden.")
return redirect("index")
form = AnnouncementRequestForm(instance=req)
all_groups = Group.objects.all()
context = {"form": form, "req": req, "admin_approve": True, "all_groups": all_groups}
return render(request, "announcements/approve.html", context) | python | def admin_approve_announcement_view(request, req_id):
req = get_object_or_404(AnnouncementRequest, id=req_id)
requested_teachers = req.teachers_requested.all()
logger.debug(requested_teachers)
if request.method == "POST":
form = AnnouncementRequestForm(request.POST, instance=req)
if form.is_valid():
req = form.save(commit=True)
# SAFE HTML
req.content = safe_html(req.content)
if "approve" in request.POST:
groups = []
if "groups" in request.POST:
group_ids = request.POST.getlist("groups")
groups = Group.objects.filter(id__in=group_ids)
logger.debug(groups)
announcement = Announcement.objects.create(title=req.title, content=req.content, author=req.author, user=req.user,
expiration_date=req.expiration_date)
for g in groups:
announcement.groups.add(g)
announcement.save()
req.posted = announcement
req.posted_by = request.user
req.save()
announcement_approved_hook(request, announcement, req)
announcement_posted_hook(request, announcement)
messages.success(request, "Successfully approved announcement request. It has been posted.")
else:
req.rejected = True
req.rejected_by = request.user
req.save()
messages.success(request, "You did not approve this request. It will be hidden.")
return redirect("index")
form = AnnouncementRequestForm(instance=req)
all_groups = Group.objects.all()
context = {"form": form, "req": req, "admin_approve": True, "all_groups": all_groups}
return render(request, "announcements/approve.html", context) | [
"def",
"admin_approve_announcement_view",
"(",
"request",
",",
"req_id",
")",
":",
"req",
"=",
"get_object_or_404",
"(",
"AnnouncementRequest",
",",
"id",
"=",
"req_id",
")",
"requested_teachers",
"=",
"req",
".",
"teachers_requested",
".",
"all",
"(",
")",
"log... | The administrator approval announcement request page. Admins will view this page through the
UI.
req_id: The ID of the AnnouncementRequest | [
"The",
"administrator",
"approval",
"announcement",
"request",
"page",
".",
"Admins",
"will",
"view",
"this",
"page",
"through",
"the",
"UI",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L201-L249 |
15,782 | tjcsl/ion | intranet/apps/announcements/views.py | add_announcement_view | def add_announcement_view(request):
"""Add an announcement."""
if request.method == "POST":
form = AnnouncementForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
# SAFE HTML
obj.content = safe_html(obj.content)
obj.save()
announcement_posted_hook(request, obj)
messages.success(request, "Successfully added announcement.")
return redirect("index")
else:
messages.error(request, "Error adding announcement")
else:
form = AnnouncementForm()
return render(request, "announcements/add_modify.html", {"form": form, "action": "add"}) | python | def add_announcement_view(request):
if request.method == "POST":
form = AnnouncementForm(request.POST)
logger.debug(form)
if form.is_valid():
obj = form.save()
obj.user = request.user
# SAFE HTML
obj.content = safe_html(obj.content)
obj.save()
announcement_posted_hook(request, obj)
messages.success(request, "Successfully added announcement.")
return redirect("index")
else:
messages.error(request, "Error adding announcement")
else:
form = AnnouncementForm()
return render(request, "announcements/add_modify.html", {"form": form, "action": "add"}) | [
"def",
"add_announcement_view",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"form",
"=",
"AnnouncementForm",
"(",
"request",
".",
"POST",
")",
"logger",
".",
"debug",
"(",
"form",
")",
"if",
"form",
".",
"is_valid",
"... | Add an announcement. | [
"Add",
"an",
"announcement",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L268-L286 |
15,783 | tjcsl/ion | intranet/apps/announcements/views.py | view_announcement_view | def view_announcement_view(request, id):
"""View an announcement.
id: announcement id
"""
announcement = get_object_or_404(Announcement, id=id)
return render(request, "announcements/view.html", {"announcement": announcement}) | python | def view_announcement_view(request, id):
announcement = get_object_or_404(Announcement, id=id)
return render(request, "announcements/view.html", {"announcement": announcement}) | [
"def",
"view_announcement_view",
"(",
"request",
",",
"id",
")",
":",
"announcement",
"=",
"get_object_or_404",
"(",
"Announcement",
",",
"id",
"=",
"id",
")",
"return",
"render",
"(",
"request",
",",
"\"announcements/view.html\"",
",",
"{",
"\"announcement\"",
... | View an announcement.
id: announcement id | [
"View",
"an",
"announcement",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L290-L298 |
15,784 | tjcsl/ion | intranet/apps/announcements/views.py | modify_announcement_view | def modify_announcement_view(request, id=None):
"""Modify an announcement.
id: announcement id
"""
if request.method == "POST":
announcement = get_object_or_404(Announcement, id=id)
form = AnnouncementForm(request.POST, instance=announcement)
if form.is_valid():
obj = form.save()
logger.debug(form.cleaned_data)
if "update_added_date" in form.cleaned_data and form.cleaned_data["update_added_date"]:
logger.debug("Update added date")
obj.added = timezone.now()
# SAFE HTML
obj.content = safe_html(obj.content)
obj.save()
messages.success(request, "Successfully modified announcement.")
return redirect("index")
else:
messages.error(request, "Error adding announcement")
else:
announcement = get_object_or_404(Announcement, id=id)
form = AnnouncementForm(instance=announcement)
context = {"form": form, "action": "modify", "id": id, "announcement": announcement}
return render(request, "announcements/add_modify.html", context) | python | def modify_announcement_view(request, id=None):
if request.method == "POST":
announcement = get_object_or_404(Announcement, id=id)
form = AnnouncementForm(request.POST, instance=announcement)
if form.is_valid():
obj = form.save()
logger.debug(form.cleaned_data)
if "update_added_date" in form.cleaned_data and form.cleaned_data["update_added_date"]:
logger.debug("Update added date")
obj.added = timezone.now()
# SAFE HTML
obj.content = safe_html(obj.content)
obj.save()
messages.success(request, "Successfully modified announcement.")
return redirect("index")
else:
messages.error(request, "Error adding announcement")
else:
announcement = get_object_or_404(Announcement, id=id)
form = AnnouncementForm(instance=announcement)
context = {"form": form, "action": "modify", "id": id, "announcement": announcement}
return render(request, "announcements/add_modify.html", context) | [
"def",
"modify_announcement_view",
"(",
"request",
",",
"id",
"=",
"None",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"announcement",
"=",
"get_object_or_404",
"(",
"Announcement",
",",
"id",
"=",
"id",
")",
"form",
"=",
"AnnouncementFo... | Modify an announcement.
id: announcement id | [
"Modify",
"an",
"announcement",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L303-L330 |
15,785 | tjcsl/ion | intranet/apps/announcements/views.py | delete_announcement_view | def delete_announcement_view(request, id):
"""Delete an announcement.
id: announcement id
"""
if request.method == "POST":
post_id = None
try:
post_id = request.POST["id"]
except AttributeError:
post_id = None
try:
a = Announcement.objects.get(id=post_id)
if request.POST.get("full_delete", False):
a.delete()
messages.success(request, "Successfully deleted announcement.")
else:
a.expiration_date = datetime.datetime.now()
a.save()
messages.success(request, "Successfully expired announcement.")
except Announcement.DoesNotExist:
pass
return redirect("index")
else:
announcement = get_object_or_404(Announcement, id=id)
return render(request, "announcements/delete.html", {"announcement": announcement}) | python | def delete_announcement_view(request, id):
if request.method == "POST":
post_id = None
try:
post_id = request.POST["id"]
except AttributeError:
post_id = None
try:
a = Announcement.objects.get(id=post_id)
if request.POST.get("full_delete", False):
a.delete()
messages.success(request, "Successfully deleted announcement.")
else:
a.expiration_date = datetime.datetime.now()
a.save()
messages.success(request, "Successfully expired announcement.")
except Announcement.DoesNotExist:
pass
return redirect("index")
else:
announcement = get_object_or_404(Announcement, id=id)
return render(request, "announcements/delete.html", {"announcement": announcement}) | [
"def",
"delete_announcement_view",
"(",
"request",
",",
"id",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"post_id",
"=",
"None",
"try",
":",
"post_id",
"=",
"request",
".",
"POST",
"[",
"\"id\"",
"]",
"except",
"AttributeError",
":",
... | Delete an announcement.
id: announcement id | [
"Delete",
"an",
"announcement",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L335-L362 |
15,786 | tjcsl/ion | intranet/apps/announcements/views.py | show_announcement_view | def show_announcement_view(request):
""" Unhide an announcement that was hidden by the logged-in user.
announcements_hidden in the user model is the related_name for
"users_hidden" in the announcement model.
"""
if request.method == "POST":
announcement_id = request.POST.get("announcement_id")
if announcement_id:
announcement = Announcement.objects.get(id=announcement_id)
announcement.user_map.users_hidden.remove(request.user)
announcement.user_map.save()
return http.HttpResponse("Unhidden")
raise http.Http404
else:
return http.HttpResponseNotAllowed(["POST"], "HTTP 405: METHOD NOT ALLOWED") | python | def show_announcement_view(request):
if request.method == "POST":
announcement_id = request.POST.get("announcement_id")
if announcement_id:
announcement = Announcement.objects.get(id=announcement_id)
announcement.user_map.users_hidden.remove(request.user)
announcement.user_map.save()
return http.HttpResponse("Unhidden")
raise http.Http404
else:
return http.HttpResponseNotAllowed(["POST"], "HTTP 405: METHOD NOT ALLOWED") | [
"def",
"show_announcement_view",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"announcement_id",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"\"announcement_id\"",
")",
"if",
"announcement_id",
":",
"announcement",
"=",
"A... | Unhide an announcement that was hidden by the logged-in user.
announcements_hidden in the user model is the related_name for
"users_hidden" in the announcement model. | [
"Unhide",
"an",
"announcement",
"that",
"was",
"hidden",
"by",
"the",
"logged",
"-",
"in",
"user",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L367-L382 |
15,787 | tjcsl/ion | intranet/apps/announcements/views.py | hide_announcement_view | def hide_announcement_view(request):
""" Hide an announcement for the logged-in user.
announcements_hidden in the user model is the related_name for
"users_hidden" in the announcement model.
"""
if request.method == "POST":
announcement_id = request.POST.get("announcement_id")
if announcement_id:
announcement = Announcement.objects.get(id=announcement_id)
try:
announcement.user_map.users_hidden.add(request.user)
announcement.user_map.save()
except IntegrityError:
logger.warning("Duplicate value when hiding announcement {} for {}.".format(announcement_id, request.user.username))
return http.HttpResponse("Hidden")
raise http.Http404
else:
return http.HttpResponseNotAllowed(["POST"], "HTTP 405: METHOD NOT ALLOWED") | python | def hide_announcement_view(request):
if request.method == "POST":
announcement_id = request.POST.get("announcement_id")
if announcement_id:
announcement = Announcement.objects.get(id=announcement_id)
try:
announcement.user_map.users_hidden.add(request.user)
announcement.user_map.save()
except IntegrityError:
logger.warning("Duplicate value when hiding announcement {} for {}.".format(announcement_id, request.user.username))
return http.HttpResponse("Hidden")
raise http.Http404
else:
return http.HttpResponseNotAllowed(["POST"], "HTTP 405: METHOD NOT ALLOWED") | [
"def",
"hide_announcement_view",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"announcement_id",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"\"announcement_id\"",
")",
"if",
"announcement_id",
":",
"announcement",
"=",
"A... | Hide an announcement for the logged-in user.
announcements_hidden in the user model is the related_name for
"users_hidden" in the announcement model. | [
"Hide",
"an",
"announcement",
"for",
"the",
"logged",
"-",
"in",
"user",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/announcements/views.py#L387-L405 |
15,788 | tjcsl/ion | intranet/apps/auth/forms.py | AuthenticateForm.is_valid | def is_valid(self):
"""Validates the username and password in the form."""
form = super(AuthenticateForm, self).is_valid()
for f, error in self.errors.items():
if f != "__all__":
self.fields[f].widget.attrs.update({"class": "error", "placeholder": ", ".join(list(error))})
else:
errors = list(error)
if "This account is inactive." in errors:
message = "Intranet access restricted"
else:
message = "Invalid password"
self.fields["password"].widget.attrs.update({"class": "error", "placeholder": message})
return form | python | def is_valid(self):
form = super(AuthenticateForm, self).is_valid()
for f, error in self.errors.items():
if f != "__all__":
self.fields[f].widget.attrs.update({"class": "error", "placeholder": ", ".join(list(error))})
else:
errors = list(error)
if "This account is inactive." in errors:
message = "Intranet access restricted"
else:
message = "Invalid password"
self.fields["password"].widget.attrs.update({"class": "error", "placeholder": message})
return form | [
"def",
"is_valid",
"(",
"self",
")",
":",
"form",
"=",
"super",
"(",
"AuthenticateForm",
",",
"self",
")",
".",
"is_valid",
"(",
")",
"for",
"f",
",",
"error",
"in",
"self",
".",
"errors",
".",
"items",
"(",
")",
":",
"if",
"f",
"!=",
"\"__all__\""... | Validates the username and password in the form. | [
"Validates",
"the",
"username",
"and",
"password",
"in",
"the",
"form",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/auth/forms.py#L37-L51 |
15,789 | agoragames/kairos | kairos/redis_backend.py | RedisBackend._calc_keys | def _calc_keys(self, config, name, timestamp):
'''
Calculate keys given a stat name and timestamp.
'''
i_bucket = config['i_calc'].to_bucket( timestamp )
r_bucket = config['r_calc'].to_bucket( timestamp )
i_key = '%s%s:%s:%s'%(self._prefix, name, config['interval'], i_bucket)
r_key = '%s:%s'%(i_key, r_bucket)
return i_bucket, r_bucket, i_key, r_key | python | def _calc_keys(self, config, name, timestamp):
'''
Calculate keys given a stat name and timestamp.
'''
i_bucket = config['i_calc'].to_bucket( timestamp )
r_bucket = config['r_calc'].to_bucket( timestamp )
i_key = '%s%s:%s:%s'%(self._prefix, name, config['interval'], i_bucket)
r_key = '%s:%s'%(i_key, r_bucket)
return i_bucket, r_bucket, i_key, r_key | [
"def",
"_calc_keys",
"(",
"self",
",",
"config",
",",
"name",
",",
"timestamp",
")",
":",
"i_bucket",
"=",
"config",
"[",
"'i_calc'",
"]",
".",
"to_bucket",
"(",
"timestamp",
")",
"r_bucket",
"=",
"config",
"[",
"'r_calc'",
"]",
".",
"to_bucket",
"(",
... | Calculate keys given a stat name and timestamp. | [
"Calculate",
"keys",
"given",
"a",
"stat",
"name",
"and",
"timestamp",
"."
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L51-L61 |
15,790 | agoragames/kairos | kairos/redis_backend.py | RedisBackend._batch_insert | def _batch_insert(self, inserts, intervals, **kwargs):
'''
Specialized batch insert
'''
if 'pipeline' in kwargs:
pipe = kwargs.get('pipeline')
own_pipe = False
else:
pipe = self._client.pipeline(transaction=False)
kwargs['pipeline'] = pipe
own_pipe = True
ttl_batch = set()
for timestamp,names in inserts.iteritems():
for name,values in names.iteritems():
for value in values:
# TODO: support config param to flush the pipe every X inserts
self._insert( name, value, timestamp, intervals, ttl_batch=ttl_batch, **kwargs )
for ttl_args in ttl_batch:
pipe.expire(*ttl_args)
if own_pipe:
kwargs['pipeline'].execute() | python | def _batch_insert(self, inserts, intervals, **kwargs):
'''
Specialized batch insert
'''
if 'pipeline' in kwargs:
pipe = kwargs.get('pipeline')
own_pipe = False
else:
pipe = self._client.pipeline(transaction=False)
kwargs['pipeline'] = pipe
own_pipe = True
ttl_batch = set()
for timestamp,names in inserts.iteritems():
for name,values in names.iteritems():
for value in values:
# TODO: support config param to flush the pipe every X inserts
self._insert( name, value, timestamp, intervals, ttl_batch=ttl_batch, **kwargs )
for ttl_args in ttl_batch:
pipe.expire(*ttl_args)
if own_pipe:
kwargs['pipeline'].execute() | [
"def",
"_batch_insert",
"(",
"self",
",",
"inserts",
",",
"intervals",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'pipeline'",
"in",
"kwargs",
":",
"pipe",
"=",
"kwargs",
".",
"get",
"(",
"'pipeline'",
")",
"own_pipe",
"=",
"False",
"else",
":",
"pipe",... | Specialized batch insert | [
"Specialized",
"batch",
"insert"
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L100-L123 |
15,791 | agoragames/kairos | kairos/redis_backend.py | RedisBackend._insert | def _insert(self, name, value, timestamp, intervals, **kwargs):
'''
Insert the value.
'''
if 'pipeline' in kwargs:
pipe = kwargs.get('pipeline')
else:
pipe = self._client.pipeline(transaction=False)
for interval,config in self._intervals.iteritems():
timestamps = self._normalize_timestamps(timestamp, intervals, config)
for tstamp in timestamps:
self._insert_data(name, value, tstamp, interval, config, pipe,
ttl_batch=kwargs.get('ttl_batch'))
if 'pipeline' not in kwargs:
pipe.execute() | python | def _insert(self, name, value, timestamp, intervals, **kwargs):
'''
Insert the value.
'''
if 'pipeline' in kwargs:
pipe = kwargs.get('pipeline')
else:
pipe = self._client.pipeline(transaction=False)
for interval,config in self._intervals.iteritems():
timestamps = self._normalize_timestamps(timestamp, intervals, config)
for tstamp in timestamps:
self._insert_data(name, value, tstamp, interval, config, pipe,
ttl_batch=kwargs.get('ttl_batch'))
if 'pipeline' not in kwargs:
pipe.execute() | [
"def",
"_insert",
"(",
"self",
",",
"name",
",",
"value",
",",
"timestamp",
",",
"intervals",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'pipeline'",
"in",
"kwargs",
":",
"pipe",
"=",
"kwargs",
".",
"get",
"(",
"'pipeline'",
")",
"else",
":",
"pipe",
... | Insert the value. | [
"Insert",
"the",
"value",
"."
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L125-L141 |
15,792 | agoragames/kairos | kairos/redis_backend.py | RedisBackend._insert_data | def _insert_data(self, name, value, timestamp, interval, config, pipe, ttl_batch=None):
'''Helper to insert data into redis'''
# Calculate the TTL and abort if inserting into the past
expire, ttl = config['expire'], config['ttl'](timestamp)
if expire and not ttl:
return
i_bucket, r_bucket, i_key, r_key = self._calc_keys(config, name, timestamp)
if config['coarse']:
self._type_insert(pipe, i_key, value)
else:
# Add the resolution bucket to the interval. This allows us to easily
# discover the resolution intervals within the larger interval, and
# if there is a cap on the number of steps, it will go out of scope
# along with the rest of the data
pipe.sadd(i_key, r_bucket)
self._type_insert(pipe, r_key, value)
if expire:
ttl_args = (i_key, ttl)
if ttl_batch is not None:
ttl_batch.add(ttl_args)
else:
pipe.expire(*ttl_args)
if not config['coarse']:
ttl_args = (r_key, ttl)
if ttl_batch is not None:
ttl_batch.add(ttl_args)
else:
pipe.expire(*ttl_args) | python | def _insert_data(self, name, value, timestamp, interval, config, pipe, ttl_batch=None):
'''Helper to insert data into redis'''
# Calculate the TTL and abort if inserting into the past
expire, ttl = config['expire'], config['ttl'](timestamp)
if expire and not ttl:
return
i_bucket, r_bucket, i_key, r_key = self._calc_keys(config, name, timestamp)
if config['coarse']:
self._type_insert(pipe, i_key, value)
else:
# Add the resolution bucket to the interval. This allows us to easily
# discover the resolution intervals within the larger interval, and
# if there is a cap on the number of steps, it will go out of scope
# along with the rest of the data
pipe.sadd(i_key, r_bucket)
self._type_insert(pipe, r_key, value)
if expire:
ttl_args = (i_key, ttl)
if ttl_batch is not None:
ttl_batch.add(ttl_args)
else:
pipe.expire(*ttl_args)
if not config['coarse']:
ttl_args = (r_key, ttl)
if ttl_batch is not None:
ttl_batch.add(ttl_args)
else:
pipe.expire(*ttl_args) | [
"def",
"_insert_data",
"(",
"self",
",",
"name",
",",
"value",
",",
"timestamp",
",",
"interval",
",",
"config",
",",
"pipe",
",",
"ttl_batch",
"=",
"None",
")",
":",
"# Calculate the TTL and abort if inserting into the past",
"expire",
",",
"ttl",
"=",
"config"... | Helper to insert data into redis | [
"Helper",
"to",
"insert",
"data",
"into",
"redis"
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L143-L173 |
15,793 | agoragames/kairos | kairos/redis_backend.py | RedisBackend.delete | def delete(self, name):
'''
Delete all the data in a named timeseries.
'''
keys = self._client.keys('%s%s:*'%(self._prefix,name))
pipe = self._client.pipeline(transaction=False)
for key in keys:
pipe.delete( key )
pipe.execute()
# Could be not technically the exact number of keys deleted, but is a close
# enough approximation
return len(keys) | python | def delete(self, name):
'''
Delete all the data in a named timeseries.
'''
keys = self._client.keys('%s%s:*'%(self._prefix,name))
pipe = self._client.pipeline(transaction=False)
for key in keys:
pipe.delete( key )
pipe.execute()
# Could be not technically the exact number of keys deleted, but is a close
# enough approximation
return len(keys) | [
"def",
"delete",
"(",
"self",
",",
"name",
")",
":",
"keys",
"=",
"self",
".",
"_client",
".",
"keys",
"(",
"'%s%s:*'",
"%",
"(",
"self",
".",
"_prefix",
",",
"name",
")",
")",
"pipe",
"=",
"self",
".",
"_client",
".",
"pipeline",
"(",
"transaction... | Delete all the data in a named timeseries. | [
"Delete",
"all",
"the",
"data",
"in",
"a",
"named",
"timeseries",
"."
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L175-L188 |
15,794 | agoragames/kairos | kairos/redis_backend.py | RedisBackend._get | def _get(self, name, interval, config, timestamp, **kws):
'''
Fetch a single interval from redis.
'''
i_bucket, r_bucket, i_key, r_key = self._calc_keys(config, name, timestamp)
fetch = kws.get('fetch') or self._type_get
process_row = kws.get('process_row') or self._process_row
rval = OrderedDict()
if config['coarse']:
data = process_row( fetch(self._client, i_key) )
rval[ config['i_calc'].from_bucket(i_bucket) ] = data
else:
# First fetch all of the resolution buckets for this set.
resolution_buckets = sorted(map(int,self._client.smembers(i_key)))
# Create a pipe and go fetch all the data for each.
# TODO: turn off transactions here?
pipe = self._client.pipeline(transaction=False)
for bucket in resolution_buckets:
r_key = '%s:%s'%(i_key, bucket) # TODO: make this the "resolution_bucket" closure?
fetch(pipe, r_key)
res = pipe.execute()
for idx,data in enumerate(res):
data = process_row(data)
rval[ config['r_calc'].from_bucket(resolution_buckets[idx]) ] = data
return rval | python | def _get(self, name, interval, config, timestamp, **kws):
'''
Fetch a single interval from redis.
'''
i_bucket, r_bucket, i_key, r_key = self._calc_keys(config, name, timestamp)
fetch = kws.get('fetch') or self._type_get
process_row = kws.get('process_row') or self._process_row
rval = OrderedDict()
if config['coarse']:
data = process_row( fetch(self._client, i_key) )
rval[ config['i_calc'].from_bucket(i_bucket) ] = data
else:
# First fetch all of the resolution buckets for this set.
resolution_buckets = sorted(map(int,self._client.smembers(i_key)))
# Create a pipe and go fetch all the data for each.
# TODO: turn off transactions here?
pipe = self._client.pipeline(transaction=False)
for bucket in resolution_buckets:
r_key = '%s:%s'%(i_key, bucket) # TODO: make this the "resolution_bucket" closure?
fetch(pipe, r_key)
res = pipe.execute()
for idx,data in enumerate(res):
data = process_row(data)
rval[ config['r_calc'].from_bucket(resolution_buckets[idx]) ] = data
return rval | [
"def",
"_get",
"(",
"self",
",",
"name",
",",
"interval",
",",
"config",
",",
"timestamp",
",",
"*",
"*",
"kws",
")",
":",
"i_bucket",
",",
"r_bucket",
",",
"i_key",
",",
"r_key",
"=",
"self",
".",
"_calc_keys",
"(",
"config",
",",
"name",
",",
"ti... | Fetch a single interval from redis. | [
"Fetch",
"a",
"single",
"interval",
"from",
"redis",
"."
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L190-L218 |
15,795 | agoragames/kairos | kairos/redis_backend.py | RedisCount._type_insert | def _type_insert(self, handle, key, value):
'''
Insert the value into the series.
'''
if value!=0:
if isinstance(value,float):
handle.incrbyfloat(key, value)
else:
handle.incr(key,value) | python | def _type_insert(self, handle, key, value):
'''
Insert the value into the series.
'''
if value!=0:
if isinstance(value,float):
handle.incrbyfloat(key, value)
else:
handle.incr(key,value) | [
"def",
"_type_insert",
"(",
"self",
",",
"handle",
",",
"key",
",",
"value",
")",
":",
"if",
"value",
"!=",
"0",
":",
"if",
"isinstance",
"(",
"value",
",",
"float",
")",
":",
"handle",
".",
"incrbyfloat",
"(",
"key",
",",
"value",
")",
"else",
":"... | Insert the value into the series. | [
"Insert",
"the",
"value",
"into",
"the",
"series",
"."
] | 0b062d543b0f4a46df460fa0eb6ec281232ab179 | https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/redis_backend.py#L293-L301 |
15,796 | tjcsl/ion | fabfile.py | _choose_from_list | def _choose_from_list(options, question):
"""Choose an item from a list."""
message = ""
for index, value in enumerate(options):
message += "[{}] {}\n".format(index, value)
message += "\n" + question
def valid(n):
if int(n) not in range(len(options)):
raise ValueError("Not a valid option.")
else:
return int(n)
prompt(message, validate=valid, key="answer")
return env.answer | python | def _choose_from_list(options, question):
message = ""
for index, value in enumerate(options):
message += "[{}] {}\n".format(index, value)
message += "\n" + question
def valid(n):
if int(n) not in range(len(options)):
raise ValueError("Not a valid option.")
else:
return int(n)
prompt(message, validate=valid, key="answer")
return env.answer | [
"def",
"_choose_from_list",
"(",
"options",
",",
"question",
")",
":",
"message",
"=",
"\"\"",
"for",
"index",
",",
"value",
"in",
"enumerate",
"(",
"options",
")",
":",
"message",
"+=",
"\"[{}] {}\\n\"",
".",
"format",
"(",
"index",
",",
"value",
")",
"... | Choose an item from a list. | [
"Choose",
"an",
"item",
"from",
"a",
"list",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/fabfile.py#L17-L31 |
15,797 | tjcsl/ion | fabfile.py | runserver | def runserver(port=8080, debug_toolbar="yes", werkzeug="no", dummy_cache="no", short_cache="no", template_warnings="no", log_level="DEBUG",
insecure="no"):
"""Clear compiled python files and start the Django dev server."""
if not port or (not isinstance(port, int) and not port.isdigit()):
abort("You must specify a port.")
# clean_pyc()
yes_or_no = ("debug_toolbar", "werkzeug", "dummy_cache", "short_cache", "template_warnings", "insecure")
for s in yes_or_no:
if locals()[s].lower() not in ("yes", "no"):
abort("Specify 'yes' or 'no' for {} option.".format(s))
_log_levels = ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL")
if log_level not in _log_levels:
abort("Invalid log level.")
with shell_env(SHOW_DEBUG_TOOLBAR=debug_toolbar.upper(), DUMMY_CACHE=dummy_cache.upper(), SHORT_CACHE=short_cache.upper(),
WARN_INVALID_TEMPLATE_VARS=template_warnings.upper(), LOG_LEVEL=log_level):
local("./manage.py runserver{} 0.0.0.0:{}{}".format("_plus" if werkzeug.lower() == "yes" else "", port, " --insecure"
if insecure.lower() == "yes" else "")) | python | def runserver(port=8080, debug_toolbar="yes", werkzeug="no", dummy_cache="no", short_cache="no", template_warnings="no", log_level="DEBUG",
insecure="no"):
if not port or (not isinstance(port, int) and not port.isdigit()):
abort("You must specify a port.")
# clean_pyc()
yes_or_no = ("debug_toolbar", "werkzeug", "dummy_cache", "short_cache", "template_warnings", "insecure")
for s in yes_or_no:
if locals()[s].lower() not in ("yes", "no"):
abort("Specify 'yes' or 'no' for {} option.".format(s))
_log_levels = ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL")
if log_level not in _log_levels:
abort("Invalid log level.")
with shell_env(SHOW_DEBUG_TOOLBAR=debug_toolbar.upper(), DUMMY_CACHE=dummy_cache.upper(), SHORT_CACHE=short_cache.upper(),
WARN_INVALID_TEMPLATE_VARS=template_warnings.upper(), LOG_LEVEL=log_level):
local("./manage.py runserver{} 0.0.0.0:{}{}".format("_plus" if werkzeug.lower() == "yes" else "", port, " --insecure"
if insecure.lower() == "yes" else "")) | [
"def",
"runserver",
"(",
"port",
"=",
"8080",
",",
"debug_toolbar",
"=",
"\"yes\"",
",",
"werkzeug",
"=",
"\"no\"",
",",
"dummy_cache",
"=",
"\"no\"",
",",
"short_cache",
"=",
"\"no\"",
",",
"template_warnings",
"=",
"\"no\"",
",",
"log_level",
"=",
"\"DEBUG... | Clear compiled python files and start the Django dev server. | [
"Clear",
"compiled",
"python",
"files",
"and",
"start",
"the",
"Django",
"dev",
"server",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/fabfile.py#L39-L58 |
15,798 | tjcsl/ion | fabfile.py | clear_sessions | def clear_sessions(venv=None):
"""Clear all sessions for all sandboxes or for production."""
if "VIRTUAL_ENV" in os.environ:
ve = os.path.basename(os.environ["VIRTUAL_ENV"])
else:
ve = ""
if venv is not None:
ve = venv
else:
ve = prompt("Enter the name of the "
"sandbox whose sessions you would like to delete, or "
"\"ion\" to clear production sessions:", default=ve)
c = "redis-cli -n {0} KEYS {1}:session:* | sed 's/\"^.*\")//g'"
keys_command = c.format(REDIS_SESSION_DB, ve)
keys = local(keys_command, capture=True)
count = 0 if keys.strip() == "" else keys.count("\n") + 1
if count == 0:
puts("No sessions to destroy.")
return 0
plural = "s" if count != 1 else ""
if not confirm("Are you sure you want to destroy {} {}" "session{}?".format(count, "production " if ve == "ion" else "", plural)):
return 0
if count > 0:
local("{0}| xargs redis-cli -n " "{1} DEL".format(keys_command, REDIS_SESSION_DB))
puts("Destroyed {} session{}.".format(count, plural)) | python | def clear_sessions(venv=None):
if "VIRTUAL_ENV" in os.environ:
ve = os.path.basename(os.environ["VIRTUAL_ENV"])
else:
ve = ""
if venv is not None:
ve = venv
else:
ve = prompt("Enter the name of the "
"sandbox whose sessions you would like to delete, or "
"\"ion\" to clear production sessions:", default=ve)
c = "redis-cli -n {0} KEYS {1}:session:* | sed 's/\"^.*\")//g'"
keys_command = c.format(REDIS_SESSION_DB, ve)
keys = local(keys_command, capture=True)
count = 0 if keys.strip() == "" else keys.count("\n") + 1
if count == 0:
puts("No sessions to destroy.")
return 0
plural = "s" if count != 1 else ""
if not confirm("Are you sure you want to destroy {} {}" "session{}?".format(count, "production " if ve == "ion" else "", plural)):
return 0
if count > 0:
local("{0}| xargs redis-cli -n " "{1} DEL".format(keys_command, REDIS_SESSION_DB))
puts("Destroyed {} session{}.".format(count, plural)) | [
"def",
"clear_sessions",
"(",
"venv",
"=",
"None",
")",
":",
"if",
"\"VIRTUAL_ENV\"",
"in",
"os",
".",
"environ",
":",
"ve",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"environ",
"[",
"\"VIRTUAL_ENV\"",
"]",
")",
"else",
":",
"ve",
"=",... | Clear all sessions for all sandboxes or for production. | [
"Clear",
"all",
"sessions",
"for",
"all",
"sandboxes",
"or",
"for",
"production",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/fabfile.py#L90-L122 |
15,799 | tjcsl/ion | fabfile.py | clear_cache | def clear_cache(input=None):
"""Clear the production or sandbox redis cache."""
if input is not None:
n = input
else:
n = _choose_from_list(["Production cache", "Sandbox cache"], "Which cache would you like to clear?")
if n == 0:
local("redis-cli -n {} FLUSHDB".format(REDIS_PRODUCTION_CACHE_DB))
else:
local("redis-cli -n {} FLUSHDB".format(REDIS_SANDBOX_CACHE_DB)) | python | def clear_cache(input=None):
if input is not None:
n = input
else:
n = _choose_from_list(["Production cache", "Sandbox cache"], "Which cache would you like to clear?")
if n == 0:
local("redis-cli -n {} FLUSHDB".format(REDIS_PRODUCTION_CACHE_DB))
else:
local("redis-cli -n {} FLUSHDB".format(REDIS_SANDBOX_CACHE_DB)) | [
"def",
"clear_cache",
"(",
"input",
"=",
"None",
")",
":",
"if",
"input",
"is",
"not",
"None",
":",
"n",
"=",
"input",
"else",
":",
"n",
"=",
"_choose_from_list",
"(",
"[",
"\"Production cache\"",
",",
"\"Sandbox cache\"",
"]",
",",
"\"Which cache would you ... | Clear the production or sandbox redis cache. | [
"Clear",
"the",
"production",
"or",
"sandbox",
"redis",
"cache",
"."
] | 5d722b0725d572039bb0929fd5715a4070c82c72 | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/fabfile.py#L125-L135 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.