_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q15700
EighthActivity.restricted_activities_available_to_user
train
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:
python
{ "resource": "" }
q15701
EighthActivity.get_active_schedulings
train
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
python
{ "resource": "" }
q15702
EighthActivity.frequent_users
train
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(
python
{ "resource": "" }
q15703
EighthBlockQuerySet.this_year
train
def this_year(self): """ Get EighthBlocks from this school year only. """
python
{ "resource": "" }
q15704
EighthBlockManager.get_blocks_this_year
train
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()
python
{ "resource": "" }
q15705
EighthBlock.save
train
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:
python
{ "resource": "" }
q15706
EighthBlock.next_blocks
train
def next_blocks(self, quantity=-1): """Get the next blocks in order.""" blocks = (EighthBlock.objects.get_blocks_this_year().order_by(
python
{ "resource": "" }
q15707
EighthBlock.previous_blocks
train
def previous_blocks(self, quantity=-1): """Get the previous blocks in order.""" blocks = (EighthBlock.objects.get_blocks_this_year().order_by(
python
{ "resource": "" }
q15708
EighthBlock.get_surrounding_blocks
train
def get_surrounding_blocks(self): """Get the blocks around the one given. Returns: a list of all of those blocks.
python
{ "resource": "" }
q15709
EighthBlock.signup_time_future
train
def signup_time_future(self): """Is the signup time in the future?""" now = datetime.datetime.now()
python
{ "resource": "" }
q15710
EighthBlock.date_in_past
train
def date_in_past(self): """Is the block's date in the past? (Has it not yet happened?) """
python
{ "resource": "" }
q15711
EighthBlock.in_clear_absence_period
train
def in_clear_absence_period(self): """Is the current date in the block's clear absence period? (Should info on clearing the absence
python
{ "resource": "" }
q15712
EighthBlock.attendance_locked
train
def attendance_locked(self): """Is it past 10PM on the day of the block?""" now = datetime.datetime.now()
python
{ "resource": "" }
q15713
EighthBlock.num_signups
train
def num_signups(self): """How many people have signed up?""" return
python
{ "resource": "" }
q15714
EighthBlock.num_no_signups
train
def num_no_signups(self): """How many people have not signed up?"""
python
{ "resource": "" }
q15715
EighthBlock.is_this_year
train
def is_this_year(self): """Return whether the block occurs after September 1st of this school year."""
python
{ "resource": "" }
q15716
EighthScheduledActivityManager.for_sponsor
train
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
python
{ "resource": "" }
q15717
EighthScheduledActivity.full_title
train
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
python
{ "resource": "" }
q15718
EighthScheduledActivity.title_with_flags
train
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)
python
{ "resource": "" }
q15719
EighthScheduledActivity.get_true_sponsors
train
def get_true_sponsors(self): """Get the sponsors for the scheduled activity, taking into account activity defaults and
python
{ "resource": "" }
q15720
EighthScheduledActivity.user_is_sponsor
train
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:
python
{ "resource": "" }
q15721
EighthScheduledActivity.get_true_rooms
train
def get_true_rooms(self): """Get the rooms for the scheduled activity, taking into account activity defaults and
python
{ "resource": "" }
q15722
EighthScheduledActivity.get_true_capacity
train
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:
python
{ "resource": "" }
q15723
EighthScheduledActivity.is_full
train
def is_full(self): """Return whether the activity is full.""" capacity = self.get_true_capacity() if capacity != -1:
python
{ "resource": "" }
q15724
EighthScheduledActivity.is_overbooked
train
def is_overbooked(self): """Return whether the activity is overbooked.""" capacity = self.get_true_capacity() if capacity != -1:
python
{ "resource": "" }
q15725
EighthScheduledActivity.get_viewable_members
train
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
python
{ "resource": "" }
q15726
EighthScheduledActivity.get_viewable_members_serializer
train
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:
python
{ "resource": "" }
q15727
EighthScheduledActivity.get_hidden_members
train
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
python
{ "resource": "" }
q15728
EighthScheduledActivity.get_both_blocks_sibling
train
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
python
{ "resource": "" }
q15729
EighthScheduledActivity.cancel
train
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
python
{ "resource": "" }
q15730
EighthScheduledActivity.uncancel
train
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]
python
{ "resource": "" }
q15731
EighthSignup.validate_unique
train
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():
python
{ "resource": "" }
q15732
EighthSignup.remove_signup
train
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
python
{ "resource": "" }
q15733
transfer_students_action
train
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":
python
{ "resource": "" }
q15734
start_date
train
def start_date(request): """Add the start date to the context for eighth admin views.""" if request.user
python
{ "resource": "" }
q15735
absence_count
train
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:
python
{ "resource": "" }
q15736
HostManager.visible_to_user
train
def visible_to_user(self, user): """Get a list of hosts available to a given user. Same logic as Announcements and Events. """
python
{ "resource": "" }
q15737
DayManager.get_future_days
train
def get_future_days(self): """Return only future Day objects.""" today
python
{ "resource": "" }
q15738
DayManager.today
train
def today(self): """Return the Day for the current day""" today = timezone.now().date() try:
python
{ "resource": "" }
q15739
get_date_range_this_year
train
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)
python
{ "resource": "" }
q15740
user_attr
train
def user_attr(username, attribute): """Gets an attribute of the user with the given username."""
python
{ "resource": "" }
q15741
argument_request_user
train
def argument_request_user(obj, func_name): """Pass request.user as an argument to the given function
python
{ "resource": "" }
q15742
senior_email_forward_view
train
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 =
python
{ "resource": "" }
q15743
dashes
train
def dashes(phone): """Returns the phone number formatted with dashes.""" if isinstance(phone, str): if phone.startswith("+1"):
python
{ "resource": "" }
q15744
check_emerg
train
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...
python
{ "resource": "" }
q15745
get_emerg
train
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")
python
{ "resource": "" }
q15746
index_view
train
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 = {
python
{ "resource": "" }
q15747
logout_view
train
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", "")
python
{ "resource": "" }
q15748
LoginView.post
train
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
python
{ "resource": "" }
q15749
MongoBackend._unescape
train
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. '''
python
{ "resource": "" }
q15750
MongoBackend._batch_key
train
def _batch_key(self, query): ''' Get a unique id from a query. '''
python
{ "resource": "" }
q15751
MongoBackend._batch_insert
train
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)
python
{ "resource": "" }
q15752
MongoBackend._insert_data
train
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
python
{ "resource": "" }
q15753
debug_toolbar_callback
train
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
python
{ "resource": "" }
q15754
register_calculator_view
train
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
python
{ "resource": "" }
q15755
register_computer_view
train
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
python
{ "resource": "" }
q15756
register_phone_view
train
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
python
{ "resource": "" }
q15757
setup
train
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
python
{ "resource": "" }
q15758
profile_view
train
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
python
{ "resource": "" }
q15759
picture_view
train
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)
python
{ "resource": "" }
q15760
SqlBackend.expire
train
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()
python
{ "resource": "" }
q15761
SqlGauge._update_data
train
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_(
python
{ "resource": "" }
q15762
add_get_parameters
train
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))
python
{ "resource": "" }
q15763
mobile_app
train
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
python
{ "resource": "" }
q15764
global_custom_theme
train
def global_custom_theme(request): """Add custom theme javascript and css.""" today = datetime.datetime.now().date() theme = {} if today.month == 3 and (14
python
{ "resource": "" }
q15765
export_csv_action
train
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
python
{ "resource": "" }
q15766
Command.handle
train
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:
python
{ "resource": "" }
q15767
check_page_range
train
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
python
{ "resource": "" }
q15768
request_announcement_email
train
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,
python
{ "resource": "" }
q15769
admin_request_announcement_email
train
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,
python
{ "resource": "" }
q15770
announcement_approved_email
train
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
python
{ "resource": "" }
q15771
announcement_posted_email
train
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:
python
{ "resource": "" }
q15772
scoped_connection
train
def scoped_connection(func): ''' Decorator that gives out connections. ''' def _with(series, *args, **kwargs): connection = None try: connection = series._connection()
python
{ "resource": "" }
q15773
CassandraBackend._connection
train
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'
python
{ "resource": "" }
q15774
CassandraBackend._insert_data
train
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,
python
{ "resource": "" }
q15775
Event.show_fuzzy_date
train
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
python
{ "resource": "" }
q15776
fuzzy_date
train
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
python
{ "resource": "" }
q15777
render_page
train
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)
python
{ "resource": "" }
q15778
announcement_posted_hook
train
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)
python
{ "resource": "" }
q15779
request_announcement_view
train
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)
python
{ "resource": "" }
q15780
approve_announcement_view
train
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:
python
{ "resource": "" }
q15781
admin_approve_announcement_view
train
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)
python
{ "resource": "" }
q15782
add_announcement_view
train
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
python
{ "resource": "" }
q15783
view_announcement_view
train
def view_announcement_view(request, id): """View an announcement. id: announcement id """
python
{ "resource": "" }
q15784
modify_announcement_view
train
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"]:
python
{ "resource": "" }
q15785
delete_announcement_view
train
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()
python
{ "resource": "" }
q15786
show_announcement_view
train
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)
python
{ "resource": "" }
q15787
hide_announcement_view
train
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:
python
{ "resource": "" }
q15788
AuthenticateForm.is_valid
train
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:
python
{ "resource": "" }
q15789
RedisBackend._calc_keys
train
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 =
python
{ "resource": "" }
q15790
RedisBackend._batch_insert
train
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():
python
{ "resource": "" }
q15791
RedisBackend._insert
train
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)
python
{ "resource": "" }
q15792
RedisBackend._insert_data
train
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
python
{ "resource": "" }
q15793
RedisBackend.delete
train
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 )
python
{ "resource": "" }
q15794
RedisBackend._get
train
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 =
python
{ "resource": "" }
q15795
RedisCount._type_insert
train
def _type_insert(self, handle, key, value): ''' Insert the value into the series. ''' if value!=0: if isinstance(value,float):
python
{ "resource": "" }
q15796
_choose_from_list
train
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)):
python
{ "resource": "" }
q15797
runserver
train
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.")
python
{ "resource": "" }
q15798
clear_sessions
train
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.")
python
{ "resource": "" }
q15799
clear_cache
train
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 ==
python
{ "resource": "" }