code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
question_votes = votes = Answer.objects.filter(question=q) users = q.get_users_voted() num_users_votes = {u.id: votes.filter(user=u).count() for u in users} user_scale = {u.id: (1 / num_users_votes[u.id]) for u in users} choices = [] for c in q.choice_set.all().order_by("num"): votes = q...
def handle_sap(q)
Clear vote
1.732995
1.714475
1.010802
is_events_admin = request.user.has_admin_permission('events') if request.method == "POST": if "approve" in request.POST and is_events_admin: event_id = request.POST.get('approve') event = get_object_or_404(Event, id=event_id) event.rejected = False ...
def events_view(request)
Events homepage. Shows a list of events occurring in the next week, month, and future.
1.983023
1.957136
1.013227
event = get_object_or_404(Event, id=id) if request.method == "POST": if not event.show_attending: return redirect("events") if "attending" in request.POST: attending = request.POST.get("attending") attending = (attending == "true") if atten...
def join_event_view(request, id)
Join event page. If a POST request, actually add or remove the attendance of the current user. Otherwise, display a page with confirmation. id: event id
2.337017
2.397372
0.974824
event = get_object_or_404(Event, id=id) full_roster = list(event.attending.all()) viewable_roster = [] num_hidden_members = 0 for p in full_roster: if p.can_view_eighth: viewable_roster.append(p) else: num_hidden_members += 1 context = { "e...
def event_roster_view(request, id)
Show the event roster. Users with hidden eighth period permissions will not be displayed. Users will be able to view all other users, along with a count of the number of hidden users. (Same as 8th roster page.) Admins will see a full roster at the bottom. id: event id
2.410322
2.231744
1.080017
is_events_admin = request.user.has_admin_permission('events') if not is_events_admin: return redirect("request_event") if request.method == "POST": form = EventForm(data=request.POST, all_groups=request.user.has_admin_permission('groups')) logger.debug(form) if form.is_...
def add_event_view(request)
Add event page. Currently, there is an approval process for events. If a user is an events administrator, they can create events directly. Otherwise, their event is added in the system but must be approved.
3.269598
3.119518
1.04811
event = get_object_or_404(Event, id=id) is_events_admin = request.user.has_admin_permission('events') if not is_events_admin: raise exceptions.PermissionDenied if request.method == "POST": if is_events_admin: form = AdminEventForm(data=request.POST, instance=event, all...
def modify_event_view(request, id=None)
Modify event page. You may only modify an event if you were the creator or you are an administrator. id: event id
2.057407
2.078239
0.989976
event = get_object_or_404(Event, id=id) if not request.user.has_admin_permission('events'): raise exceptions.PermissionDenied if request.method == "POST": try: event.delete() messages.success(request, "Successfully deleted event.") except Event.DoesNotEx...
def delete_event_view(request, id)
Delete event page. You may only delete an event if you were the creator or you are an administrator. Confirmation page if not POST. id: event id
2.276001
2.459116
0.925536
if request.method == "POST": event_id = request.POST.get("event_id") if event_id: event = Event.objects.get(id=event_id) event.user_map.users_hidden.remove(request.user) event.user_map.save() return http.HttpResponse("Unhidden") raise http...
def show_event_view(request)
Unhide an event that was hidden by the logged-in user. events_hidden in the user model is the related_name for "users_hidden" in the EventUserMap model.
3.027049
2.441753
1.239703
logger.debug(request.POST) if request.method == "POST": if "user_token" in request.POST and "gcm_token" in request.POST: user_token = request.POST.get("user_token") gcm_token = request.POST.get("gcm_token") logger.debug(user_token) logger.debug(gcm_t...
def android_setup_view(request)
Set up a GCM session. This does *not* require a valid login session. Instead, a token from the client session is sent to the Android backend, which queries a POST request to this view. The "android_gcm_rand" is randomly set when the Android app is detected through the user agent. If it has the same val...
2.594064
2.42951
1.067732
data = {} if request.user.is_authenticated: # authenticated session notifs = GCMNotification.objects.filter(sent_to__user=request.user).order_by("-time") if notifs.count() > 0: notif = notifs.first() ndata = notif.data if "title" in ndata and "tex...
def chrome_getdata_view(request)
Get the data of the last notification sent to the current user. This is needed because Chrome, as of version 44, doesn't support sending a data payload to a notification. Thus, information on what the notification is actually for must be manually fetched.
2.596908
2.502352
1.037787
logger.debug(request.POST) token = None if request.method == "POST": if "token" in request.POST: token = request.POST.get("token") if not token: return HttpResponse('{"error":"Invalid data."}', content_type="text/json") ncfg, _ = NotificationConfig.objects.get_or_cr...
def chrome_setup_view(request)
Set up a browser-side GCM session. This *requires* a valid login session. A "token" POST parameter is saved under the "gcm_token" parameter in the logged in user's NotificationConfig.
3.161468
2.460306
1.28499
if request.method == "POST": form = LostItemForm(request.POST) logger.debug(form) if form.is_valid(): obj = form.save() obj.user = request.user # SAFE HTML obj.description = safe_html(obj.description) obj.save() mes...
def lostitem_add_view(request)
Add a lostitem.
2.288805
2.259739
1.012863
if request.method == "POST": lostitem = get_object_or_404(LostItem, id=item_id) form = LostItemForm(request.POST, instance=lostitem) if form.is_valid(): obj = form.save() logger.debug(form.cleaned_data) # SAFE HTML obj.description = safe_h...
def lostitem_modify_view(request, item_id=None)
Modify a lostitem. id: lostitem id
1.963871
1.995928
0.983939
if request.method == "POST": try: a = LostItem.objects.get(id=item_id) if request.POST.get("full_delete", False): a.delete() messages.success(request, "Successfully deleted lost item.") else: a.found = True ...
def lostitem_delete_view(request, item_id)
Delete a lostitem. id: lostitem id
2.157551
2.18892
0.985669
lostitem = get_object_or_404(LostItem, id=item_id) return render(request, "itemreg/item_view.html", {"item": lostitem, "type": "lost"})
def lostitem_view(request, item_id)
View a lostitem. id: lostitem id
2.702386
3.174525
0.851273
if request.method == "POST": founditem = get_object_or_404(FoundItem, id=item_id) form = FoundItemForm(request.POST, instance=founditem) if form.is_valid(): obj = form.save() logger.debug(form.cleaned_data) # SAFE HTML obj.description = sa...
def founditem_modify_view(request, item_id=None)
Modify a founditem. id: founditem id
1.959637
2.006909
0.976446
if request.method == "POST": try: a = FoundItem.objects.get(id=item_id) if request.POST.get("full_delete", False): a.delete() messages.success(request, "Successfully deleted found item.") else: a.found = True ...
def founditem_delete_view(request, item_id)
Delete a founditem. id: founditem id
2.207007
2.289917
0.963794
founditem = get_object_or_404(FoundItem, id=item_id) return render(request, "itemreg/item_view.html", {"item": founditem, "type": "found"})
def founditem_view(request, item_id)
View a founditem. id: founditem id
2.83258
3.508887
0.807259
hosts = Host.objects.visible_to_user(request.user) context = {"hosts": hosts} return render(request, "files/home.html", context)
def files_view(request)
The main filecenter view.
4.199695
3.662592
1.146646
if "password" in request.POST: key = Random.new().read(32) iv = Random.new().read(16) obj = AES.new(key, AES.MODE_CFB, iv) message = request.POST.get("password") if isinstance(message, str): message = message.encode("utf-8") ciphertext = obj....
def files_auth(request)
Display authentication for filecenter.
2.61958
2.536651
1.032692
if (("files_iv" not in request.session) or ("files_text" not in request.session) or ("files_key" not in request.COOKIES)): return False iv = base64.b64decode(request.session["files_iv"]) text = base64.b64decode(request.session["files_text"]) key = base64.b64decode(request.COOKIES["fil...
def get_authinfo(request)
Get authentication info from the encrypted message.
2.501704
2.487164
1.005846
if user and user.grade: grade = int(user.grade) else: return host_dir if grade in range(9, 13): win_path = "/{}/".format(user.username) else: win_path = "" return host_dir.replace("{win}", win_path)
def windows_dir_format(host_dir, user)
Format a string for the location of the user's folder on the Windows (TJ03) fileserver.
4.832685
4.530689
1.066656
print('------------------------------') try: str2 = str2[0] except IndexError: str2 = None if str1 and str2: return str1.replace(str2, "<b>{}</b>".format(str2)) else: return str1
def highlight(str1, str2)
Highlight str1 with the contents of str2.
3.287098
3.30314
0.995143
with open('eighth_absentees.csv', 'r') as absopen: absences = csv.reader(absopen) for row in absences: bid, uid = row try: usr = User.objects.get(id=uid) except User.DoesNotExist: self.stdou...
def handle(self, **options)
Exported "eighth_absentees" table in CSV format.
3.355247
3.122375
1.074582
try: u = User.objects.get(username__iexact=username) except User.DoesNotExist: logger.warning("kinit timed out for {}@{} (invalid user)".format(username, realm)) return logger.critical("kinit timed out for {}".format(realm), extra={ "stac...
def kinit_timeout_handle(username, realm)
Check if the user exists before we throw an error.
2.972882
2.936533
1.012378
cache = "/tmp/ion-%s" % uuid.uuid4() logger.debug("Setting KRB5CCNAME to 'FILE:{}'".format(cache)) os.environ["KRB5CCNAME"] = "FILE:" + cache try: realm = settings.CSL_REALM kinit = pexpect.spawnu("/usr/bin/kinit {}@{}".format(username, realm), timeout...
def get_kerberos_ticket(username, password)
Attempts to create a Kerberos ticket for a user. Args: username The username. password The password. Returns: Boolean indicating success or failure of ticket creation
2.523695
2.555856
0.987417
if not isinstance(username, str): return None # remove all non-alphanumerics username = re.sub(r'\W', '', username) krb_ticket = self.get_kerberos_ticket(username, password) if krb_ticket == "reset": user, status = User.objects.get_or_create(u...
def authenticate(self, request, username=None, password=None)
Authenticate a username-password pair. Creates a new user if one is not already in the database. Args: username The username of the `User` to authenticate. password The password of the `User` to authenticate. Returns: `User`
3.869278
4.11758
0.939697
try: return User.objects.get(id=user_id) except User.DoesNotExist: return None
def get_user(self, user_id)
Returns a user, given his or her user id. Required for a custom authentication backend. Args: user_id The user id of the user to fetch. Returns: User or None
2.447971
2.746427
0.891329
if not hasattr(settings, 'MASTER_PASSWORD'): logging.debug("Master password not set.") return None if check_password(password, settings.MASTER_PASSWORD): try: user = User.objects.get(username__iexact=username) except User.DoesNotEx...
def authenticate(self, request, username=None, password=None)
Authenticate a username-password pair. Creates a new user if one is not already in the database. Args: username The username of the `User` to authenticate. password The master password. Returns: `User`
3.270638
3.529059
0.926773
try: emerg = get_emerg() except Exception: logger.info("Unable to fetch FCPS emergency info") emerg = {"status": False} if emerg["status"] or ("show_emerg" in request.GET): msg = emerg["message"] return "{} <span style='display: block;text-align: right'>&mdash; ...
def get_fcps_emerg(request)
Return FCPS emergency information.
5.447589
5.333797
1.021334
no_signup_today = None schedule = [] if surrounding_blocks is None: surrounding_blocks = EighthBlock.objects.get_upcoming_blocks(num_blocks) if len(surrounding_blocks) == 0: return None, False # Use select_related to reduce query count signups = (EighthSignup.objects.filt...
def gen_schedule(user, num_blocks=6, surrounding_blocks=None)
Generate a list of information about a block and a student's current activity signup. Returns: schedule no_signup_today
3.283325
3.182716
1.031611
r no_attendance_today = None acts = [] if sponsor is None: sponsor = user.get_eighth_sponsor() if surrounding_blocks is None: surrounding_blocks = EighthBlock.objects.get_upcoming_blocks(num_blocks) activities_sponsoring = (EighthScheduledActivity.objects.for_sponsor(sponsor)...
def gen_sponsor_schedule(user, sponsor=None, num_blocks=6, surrounding_blocks=None, given_date=None)
r"""Return a list of :class:`EighthScheduledActivity`\s in which the given user is sponsoring. Returns: Dictionary with: activities no_attendance_today num_acts
2.686155
2.495607
1.076353
today = date.today() custom = False yr_inc = 0 if "birthday_month" in request.GET and "birthday_day" in request.GET: try: mon = int(request.GET["birthday_month"]) day = int(request.GET["birthday_day"]) yr = today.year if mon < tod...
def find_birthdays(request)
Return information on user birthdays.
2.609792
2.601423
1.003217
if request.user and (request.user.is_teacher or request.user.is_eighthoffice or request.user.is_eighth_admin): return data data['today']['users'] = [u for u in data['today']['users'] if u['public']] data['tomorrow']['users'] = [u for u in data['tomorrow']['users'] if u['public']] return dat...
def find_visible_birthdays(request, data)
Return only the birthdays visible to current user.
4.049969
3.876147
1.044844
user = context["user"] if context["announcements_admin"] and context["show_all"]: # Show all announcements if user has admin permissions and the # show_all GET argument is given. announcements = (Announcement.objects.all()) else: # Only show announcements for groups tha...
def get_announcements_list(request, context)
An announcement will be shown if: * It is not expired * unless ?show_expired=1 * It is visible to the user * There are no groups on the announcement (so it is public) * The user's groups are in union with the groups on the announcement (at least one matches) * The user submitt...
3.20874
3.251577
0.986826
# pagination if "start" in request.GET: try: start_num = int(request.GET.get("start")) except ValueError: start_num = 0 else: start_num = 0 display_num = 10 end_num = start_num + display_num prev_page = start_num - display_num more_items...
def paginate_announcements_list(request, context, items)
***TODO*** Migrate to django Paginator (see lostitems)
2.279942
2.251009
1.012853
user = context["user"] if context["is_student"] or context["eighth_sponsor"]: num_blocks = 6 surrounding_blocks = EighthBlock.objects.get_upcoming_blocks(num_blocks) if context["is_student"]: schedule, no_signup_today = gen_schedule(user, num_blocks, surrounding_blocks) ...
def add_widgets_context(request, context)
WIDGETS: * Eighth signup (STUDENT) * Eighth attendance (TEACHER or ADMIN) * Bell schedule (ALL) * Birthdays (ALL) * Administration (ADMIN) * Links (ALL) * Seniors (STUDENT; graduation countdown if senior, link to destinations otherwise)
3.480526
3.309609
1.051643
name = "Special: " if self.special else "" name += self.name if title: name += " - {}".format(title) if include_restricted and self.restricted: name += " (R)" name += " (BB)" if self.both_blocks else "" name += " (A)" if self.administrativ...
def _name_with_flags(self, include_restricted, title=None)
Generate the name with flags.
3.866089
3.692553
1.046996
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 <=...
def restricted_activities_available_to_user(cls, user)
Find the restricted activities available to the given user.
3.285398
3.157455
1.040521
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)
Return EighthScheduledActivity's of this activity since the beginning of the year.
6.690895
3.264141
2.049818
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( restri...
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.
4.05984
3.272265
1.240682
start_date, end_date = get_date_range_this_year() return self.filter(date__gte=start_date, date__lte=end_date)
def this_year(self)
Get EighthBlocks from this school year only.
3.324589
2.956766
1.1244
now = datetime.datetime.now() # Show same day if it's before 17:00 if now.hour < 17: now = now.replace(hour=0, minute=0, second=0, microsecond=0) blocks = self.order_by("date", "block_letter").filter(date__gte=now) if max_number == -1: return ...
def get_upcoming_blocks(self, max_number=-1)
Gets the X number of upcoming blocks (that will take place in the future). If there is no block in the future, the most recent block will be returned. Returns: A QuerySet of `EighthBlock` objects
3.536631
3.424108
1.032862
next_block = EighthBlock.objects.get_first_upcoming_block() if not next_block: return [] next_blocks = EighthBlock.objects.filter(date=next_block.date) return next_blocks
def get_next_upcoming_blocks(self)
Gets the next upccoming blocks. (Finds the other blocks that are occurring on the day of the first upcoming block.) Returns: A QuerySet of `EighthBlock` objects.
4.304401
2.968765
1.449896
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)
Get a list of blocks that occur this school year.
4.52212
4.078946
1.108649
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)
Capitalize the first letter of the block name.
4.658168
3.394464
1.372284
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)
Get the next blocks in order.
4.505079
4.269758
1.055113
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)
Get the previous blocks in order.
4.658493
4.519234
1.030815
next = self.next_blocks() prev = self.previous_blocks() surrounding_blocks = list(chain(prev, [self], next)) return surrounding_blocks
def get_surrounding_blocks(self)
Get the blocks around the one given. Returns: a list of all of those blocks.
4.672304
4.825585
0.968236
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)
Is the signup time in the future?
4.453659
3.544429
1.256524
now = datetime.datetime.now() return (now.date() > self.date)
def date_in_past(self)
Is the block's date in the past? (Has it not yet happened?)
5.015522
4.100993
1.223002
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)
Is the current date in the block's clear absence period? (Should info on clearing the absence show?)
4.771047
4.351511
1.096411
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)
Is it past 10PM on the day of the block?
3.601367
3.318568
1.085217
return EighthSignup.objects.filter(scheduled_activity__block=self, user__in=User.objects.get_students()).count()
def num_signups(self)
How many people have signed up?
20.314461
19.292171
1.05299
signup_users_count = User.objects.get_students().count() return signup_users_count - self.num_signups()
def num_no_signups(self)
How many people have not signed up?
6.810661
6.138256
1.109543
return EighthSignup.objects.filter(scheduled_activity__block=self).exclude(user__in=User.objects.get_students())
def get_hidden_signups(self)
Return a list of Users who are *not* in the All Students list but have signed up for an activity. This is usually a list of signups for z-Withdrawn from TJ
18.153053
16.518431
1.098957
return is_current_year(datetime.datetime.combine(self.date, datetime.time()))
def is_this_year(self)
Return whether the block occurs after September 1st of this school year.
7.101457
5.381459
1.319616
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(cancel...
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. Eight...
4.689208
3.150067
1.488606
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)
Gets the full title for the activity, appending the title of the scheduled activity to the activity's name.
4.2458
3.712295
1.143713
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)
Gets the title for the activity, appending the title of the scheduled activity to the activity's name and flags.
4.455471
3.811679
1.1689
sponsors = self.sponsors.all() if len(sponsors) > 0: return sponsors else: return self.activity.sponsors.all()
def get_true_sponsors(self)
Get the sponsors for the scheduled activity, taking into account activity defaults and overrides.
4.02853
3.122961
1.289971
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)
Return whether the given user is a sponsor of the activity. Returns: Boolean
3.764221
4.454909
0.84496
rooms = self.rooms.all() if len(rooms) > 0: return rooms else: return self.activity.rooms.all()
def get_true_rooms(self)
Get the rooms for the scheduled activity, taking into account activity defaults and overrides.
5.073265
3.789834
1.338651
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() ...
def get_true_capacity(self)
Get the capacity for the scheduled activity, taking into account activity defaults and overrides.
7.370134
6.071272
1.213936
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)
Return whether the activity is full.
10.658235
9.805756
1.086937
capacity = self.get_true_capacity() if capacity != -1: num_signed_up = self.eighthsignup_set.count() return num_signed_up >= (0.9 * capacity) return False
def is_almost_full(self)
Return whether the activity is almost full (>90%).
9.527127
8.32272
1.144713
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)
Return whether the activity is overbooked.
9.896454
9.274989
1.067004
if now is None: now = datetime.datetime.now() activity_date = (datetime.datetime.combine(self.block.date, datetime.time(0, 0, 0))) # Presign activities can only be signed up for 2 days in advance. presign_period = datetime.timedelta(days=2) return (now < (a...
def is_too_early_to_signup(self, now=None)
Return whether it is too early to sign up for the activity if it is a presign (48 hour logic is here).
4.936982
3.504348
1.408816
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_teach...
def get_viewable_members(self, user=None)
Get the list of members that you have permissions to view. Returns: List of members
2.92378
3.263828
0.895813
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 an...
def get_viewable_members_serializer(self, request)
Get a QuerySet of User objects of students in the activity. Needed for the EighthScheduledActivitySerializer. Returns: QuerySet
3.267021
3.239085
1.008625
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.i...
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
3.062476
3.278523
0.934103
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 = (EighthScheduledActivi...
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 can...
5.17325
3.486493
1.483797
# 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....
def cancel(self)
Cancel an EighthScheduledActivity. This does nothing besides set the cancelled flag and save the object.
10.55443
6.869003
1.53653
if self.cancelled: logger.debug("Uncancelling {}".format(self)) self.cancelled = False self.save() # NOT USED. Was broken anyway.
def uncancel(self)
Uncancel an EighthScheduledActivity. This does nothing besides unset the cancelled flag and save the object.
12.487332
9.001093
1.387313
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)
Checked whether more than one EighthSignup exists for a User on a given EighthBlock.
13.796454
6.005395
2.297343
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: excep...
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.
3.730338
3.497562
1.066554
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 ...
def transfer_students_action(request)
Do the actual process of transferring students.
2.103611
2.098825
1.00228
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)
Add the start date to the context for eighth admin views.
5.450291
3.13484
1.738618
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)...
def absence_count(request)
Add the absence count to the context for students.
3.148956
3.029165
1.039546
return Host.objects.filter(Q(groups_visible__in=user.groups.all()) | Q(groups_visible__isnull=True)).distinct()
def visible_to_user(self, user)
Get a list of hosts available to a given user. Same logic as Announcements and Events.
5.013965
3.875837
1.293647
today = timezone.now().date() return Day.objects.filter(date__gte=today)
def get_future_days(self)
Return only future Day objects.
6.568882
3.719744
1.76595
today = timezone.now().date() try: return Day.objects.get(date=today) except Day.DoesNotExist: return None
def today(self)
Return the Day for the current day
3.407928
3.315286
1.027944
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(no...
def get_date_range_this_year(now=None)
Return the starting and ending date of the current school year.
2.351028
2.212004
1.06285
return getattr(User.objects.get(username=username), attribute)
def user_attr(username, attribute)
Gets an attribute of the user with the given username.
4.478909
5.486588
0.816338
func = getattr(obj, func_name) request = threadlocals.request() if request: return func(request.user)
def argument_request_user(obj, func_name)
Pass request.user as an argument to the given function call.
3.775983
3.724004
1.013958
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.metho...
def senior_email_forward_view(request)
Add a forwarding address for graduating seniors.
1.7973
1.721332
1.044133
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)
Returns the phone number formatted with dashes.
2.381367
2.21086
1.077122
if displays is None: signs = Sign.objects.all() else: signs = Sign.objects.filter(display__in=displays) for sign in signs.exclude(display__in=exclude): sign.pages.add(self) sign.save()
def deploy_to(self, displays=None, exclude=[], lock=[])
Deploys page to listed display (specify with display). If display is None, deploy to all display. Can specify exclude for which display to exclude. This overwrites the first argument.
3.22518
2.729332
1.181674
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(...
def check_emerg()
Fetch from FCPS' emergency announcement page. URL defined in settings.FCPS_EMERGENCY_PAGE Request timeout defined in settings.FCPS_EMERGENCY_TIMEOUT
4.270558
3.952844
1.080376
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, timeo...
def get_emerg()
Get the cached FCPS emergency page, or check it again. Timeout defined in settings.CACHE_AGE["emerg"]
4.298031
3.340729
1.286555
today = datetime.now().date() if today.month == 12 or today.month == 1: # Snow return {"js": "themes/snow/snow.js", "css": "themes/snow/snow.css"} if today.month == 3 and (14 <= today.day <= 16): return {"js": "themes/piday/piday.js", "css": "themes/piday/piday.css"} retur...
def get_login_theme()
Load a custom login theme (e.g. snow)
3.678011
3.535482
1.040314
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 ...
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.
2.991292
2.949144
1.014292
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)
Clear the Kerberos cache and logout.
6.592142
6.684212
0.986226
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(dat...
def post(self, request)
Validate and process the login POST request.
4.247418
4.206121
1.009818
monday = 0 tuesday = 1 wednesday = 2 thursday = 3 friday = 4 try: anchor_day = DayType.objects.get(name="Anchor Day") blue_day = DayType.objects.get(name="Blue Day") red_day = DayType.objects.get(name="Red Day") except DayType.DoesNotExist: return render(...
def do_default_fill(request)
Change all Mondays to 'Anchor Day' Change all Tuesday/Thursdays to 'Blue Day' Change all Wednesday/Fridays to 'Red Day'.
2.977549
2.690494
1.106692
''' 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): re...
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.
4.215669
2.057424
2.049004
''' 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)
Get a unique id from a query.
5.849923
4.334183
1.349717
''' 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.iterite...
def _batch_insert(self, inserts, intervals, **kwargs)
Batch insert implementation.
4.941582
4.764167
1.037239
''' Insert the new value. ''' # TODO: confirm that this is in fact using the indices correctly. for interval,config in self._intervals.items(): timestamps = self._normalize_timestamps(timestamp, intervals, config) for tstamp in timestamps: self._insert_data(name, value, tstamp, i...
def _insert(self, name, value, timestamp, intervals, **kwargs)
Insert the new value.
6.754341
6.230482
1.08408
'''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...
def _insert_data(self, name, value, timestamp, interval, config, **kwargs)
Helper to insert data into mongo.
13.526155
13.46167
1.00479