code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
Get the interval.
'''
i_bucket = config['i_calc'].to_bucket(timestamp)
fetch = kws.get('fetch')
process_row = kws.get('process_row') or self._process_row
rval = OrderedDict()
query = {'name':name, 'interval':i_bucket}
if config['coarse']:
if fetch:
record = fetch( self._client[interval], spec=query, method='find_one' )
else:
record = self._client[interval].find_one( query )
if record:
data = process_row( self._unescape(record['value']) )
rval[ config['i_calc'].from_bucket(i_bucket) ] = data
else:
rval[ config['i_calc'].from_bucket(i_bucket) ] = self._type_no_value()
else:
sort = [('interval', ASCENDING), ('resolution', ASCENDING) ]
if fetch:
cursor = fetch( self._client[interval], spec=query, sort=sort, method='find' )
else:
cursor = self._client[interval].find( spec=query, sort=sort )
idx = 0
for record in cursor:
rval[ config['r_calc'].from_bucket(record['resolution']) ] = \
process_row(record['value'])
return rval | def _get(self, name, interval, config, timestamp, **kws) | Get the interval. | 3.831485 | 3.690951 | 1.038075 |
'''
Fetch a series of buckets.
'''
# make a copy of the buckets because we're going to mutate it
buckets = list(buckets)
rval = OrderedDict()
step = config['step']
resolution = config.get('resolution',step)
fetch = kws.get('fetch')
process_row = kws.get('process_row', self._process_row)
query = { 'name':name, 'interval':{'$gte':buckets[0], '$lte':buckets[-1]} }
sort = [('interval', ASCENDING)]
if not config['coarse']:
sort.append( ('resolution', ASCENDING) )
if fetch:
cursor = fetch( self._client[interval], spec=query, sort=sort, method='find' )
else:
cursor = self._client[interval].find( spec=query, sort=sort )
for record in cursor:
while buckets and buckets[0] < record['interval']:
rval[ config['i_calc'].from_bucket(buckets.pop(0)) ] = self._type_no_value()
if buckets and buckets[0]==record['interval']:
buckets.pop(0)
i_key = config['i_calc'].from_bucket(record['interval'])
data = process_row( record['value'] )
if config['coarse']:
rval[ i_key ] = data
else:
rval.setdefault( i_key, OrderedDict() )
rval[ i_key ][ config['r_calc'].from_bucket(record['resolution']) ] = data
# are there buckets at the end for which we received no data?
while buckets:
rval[ config['i_calc'].from_bucket(buckets.pop(0)) ] = self._type_no_value()
return rval | def _series(self, name, interval, config, buckets, **kws) | Fetch a series of buckets. | 3.630885 | 3.523831 | 1.03038 |
'''
Delete time series by name across all intervals. Returns the number of
records deleted.
'''
# TODO: confirm that this does not use the combo index and determine
# performance implications.
num_deleted = 0
for interval,config in self._intervals.items():
# TODO: use write preference settings if we have them
num_deleted += self._client[interval].remove( {'name':name} )['n']
return num_deleted | def delete(self, name) | Delete time series by name across all intervals. Returns the number of
records deleted. | 11.156181 | 8.186248 | 1.362795 |
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) | Show the debug toolbar to those with the Django staff permission, excluding the Eighth Period
office. | 2.799552 | 2.723675 | 1.027858 |
return Announcement.objects.filter(
Q(groups__in=user.groups.all()) | Q(groups__isnull=True) | Q(announcementrequest__teachers_requested=user) |
Q(announcementrequest__user=user) | Q(user=user)).distinct() | def visible_to_user(self, user) | Get a list of visible announcements for a given user (usually request.user).
These visible announcements will be those that either have no
groups assigned to them (and are therefore public) or those in
which the user is a member.
Apparently this .filter() call occasionally returns duplicates, hence the .distinct()... | 5.091147 | 3.506516 | 1.45191 |
ids = user.announcements_hidden.all().values_list("announcement__id")
return Announcement.objects.filter(id__in=ids) | def hidden_announcements(self, user) | Get a list of announcements marked as hidden for a given user (usually request.user).
These are all announcements visible to the user -- they have just decided to
hide them. | 4.359414 | 4.019605 | 1.084538 |
start_date, end_date = get_date_range_this_year()
return Announcement.objects.filter(added__gte=start_date, added__lte=end_date) | def this_year(self) | Get AnnouncementRequests from this school year only. | 4.288083 | 3.18933 | 1.344509 |
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) | Register a calculator. | 2.536345 | 2.507692 | 1.011426 |
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) | Register a computer. | 2.589406 | 2.569836 | 1.007616 |
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) | Register a phone. | 2.599176 | 2.548756 | 1.019782 |
# 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) | Setup autodoc. | 4.501891 | 4.402749 | 1.022518 |
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) | 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. | 2.695166 | 2.738291 | 0.984251 |
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) | 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. | 2.470236 | 2.435435 | 1.01429 |
if not (request.user.is_eighth_admin or request.user.is_teacher):
return render(request, "error/403.html", {"reason": "You do not have permission to view statistics for this activity."}, status=403)
activity = get_object_or_404(EighthActivity, id=activity_id)
if request.GET.get("print", False):
response = HttpResponse(content_type="application/pdf")
buf = generate_statistics_pdf([activity], year=int(request.GET.get("year", 0)) or None)
response.write(buf.getvalue())
buf.close()
return response
current_year = current_school_year()
if EighthBlock.objects.count() == 0:
earliest_year = current_year
else:
earliest_year = EighthBlock.objects.order_by("date").first().date.year
if request.GET.get("year", False):
year = int(request.GET.get("year"))
else:
year = None
future = request.GET.get("future", False)
context = {"activity": activity, "years": list(reversed(range(earliest_year, current_year + 1))), "year": year, "future": future}
if year:
context.update(calculate_statistics(activity, year=year, future=future))
else:
context.update(calculate_statistics(activity, get_start_date(request), future=future))
return render(request, "eighth/statistics.html", context) | def stats_view(request, activity_id=None) | If a the GET parameter `year` is set, it uses stats from given year
with the following caveats:
- If it's the current year and start_date is set, start_date is ignored
- If it's the current year, stats will only show up to today - they won't
go into the future.
`all_years` (obviously) displays all years. | 2.595032 | 2.58023 | 1.005737 |
'''
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) | Expire all the data. | 8.111815 | 7.637103 | 1.062159 |
'''
Get the interval.
'''
i_bucket = config['i_calc'].to_bucket(timestamp)
fetch = kws.get('fetch')
process_row = kws.get('process_row') or self._process_row
rval = OrderedDict()
if fetch:
data = fetch( self._client.connect(), self._table, name, interval, i_bucket )
else:
data = self._type_get(name, interval, i_bucket)
if config['coarse']:
if data:
rval[ config['i_calc'].from_bucket(i_bucket) ] = process_row(data.values()[0][None])
else:
rval[ config['i_calc'].from_bucket(i_bucket) ] = self._type_no_value()
else:
for r_bucket,row_data in data.values()[0].items():
rval[ config['r_calc'].from_bucket(r_bucket) ] = process_row(row_data)
return rval | def _get(self, name, interval, config, timestamp, **kws) | Get the interval. | 4.27075 | 4.087893 | 1.044731 |
'''
Delete time series by name across all intervals. Returns the number of
records deleted.
'''
conn = self._client.connect()
conn.execute( self._table.delete().where(self._table.c.name==name) ) | def delete(self, name) | Delete time series by name across all intervals. Returns the number of
records deleted. | 7.304821 | 4.24768 | 1.71972 |
'''Helper to insert data into sql.'''
kwargs = {
'name' : name,
'interval' : interval,
'insert_time' : time.time(),
'i_time' : config['i_calc'].to_bucket(timestamp),
'value' : value
}
if not config['coarse']:
kwargs['r_time'] = config['r_calc'].to_bucket(timestamp)
stmt = self._table.insert().values(**kwargs)
conn = self._client.connect()
result = conn.execute(stmt) | def _insert_data(self, name, value, timestamp, interval, config, **kwargs) | Helper to insert data into sql. | 4.768992 | 4.506093 | 1.058343 |
'''Helper to insert data into sql.'''
conn = self._client.connect()
if not self._update_data(name, value, timestamp, interval, config, conn):
try:
kwargs = {
'name' : name,
'interval' : interval,
'i_time' : config['i_calc'].to_bucket(timestamp),
'value' : value
}
if not config['coarse']:
kwargs['r_time'] = config['r_calc'].to_bucket(timestamp)
stmt = self._table.insert().values(**kwargs)
result = conn.execute(stmt)
except:
# TODO: only catch IntegrityError
if not self._update_data(name, value, timestamp, interval, config, conn):
raise | def _insert_data(self, name, value, timestamp, interval, config, **kwargs) | Helper to insert data into sql. | 4.153696 | 4.009569 | 1.035946 |
'''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) | Support function for insert. Should be called within a transaction | 3.881883 | 3.279669 | 1.18362 |
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) | 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. | 1.675819 | 1.901115 | 0.881492 |
categories = [(r"^/$", "dashboard"), (r"^/announcements", "dashboard"), (r"^/eighth/admin", "eighth_admin"), (r"^/eighth", "eighth"),
(r"^/events", "events"), (r"^/files", "files"), (r"^/printing", "printing"), (r"^/groups", "groups"), (r"^/polls", "polls"),
(r"^/board", "board"), (r"/bus", "bus")]
for pattern, category in categories:
p = re.compile(pattern)
if p.match(request.path):
return {"nav_category": category}
return {"nav_category": ""} | def nav_categorizer(request) | Determine which top-level nav category (left nav) a request
falls under | 3.300526 | 3.177298 | 1.038784 |
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:
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) | Determine if the site is being displayed in a WebView from a native application. | 3.642903 | 3.639427 | 1.000955 |
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) | Add custom theme javascript and css. | 6.648963 | 6.715431 | 0.990102 |
return {'show_homecoming': settings.HOCO_START_DATE < datetime.date.today() and datetime.date.today() < settings.HOCO_END_DATE} | def show_homecoming(request) | Show homecoming ribbon / scores | 5.594386 | 5.544635 | 1.008973 |
def export_as_csv(modeladmin, request, queryset):
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) | 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/ | 1.708978 | 1.673699 | 1.021079 |
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) | Exported "eighth_activity_permissions" table in CSV format. | 2.800086 | 2.455642 | 1.140266 |
start_date, end_date = get_date_range_this_year()
return self.filter(start_time__gte=start_date, start_time__lte=end_date) | def this_year(self) | Get AnnouncementRequests from this school year only. | 3.441342 | 2.837542 | 1.21279 |
return Poll.objects.filter(Q(groups__in=user.groups.all()) | Q(groups__isnull=True)) | def visible_to_user(self, user) | Get a list of visible polls for a given user (usually request.user).
These visible polls will be those that either have no groups
assigned to them (and are therefore public) or those in which
the user is a member. | 5.738325 | 3.18837 | 1.799767 |
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) | Returns the number of pages in the range, or False if it is an invalid range. | 2.860061 | 2.673702 | 1.069701 |
if not request.user.is_student:
return redirect("index")
# context = {"first_login": request.session["first_login"] if "first_login" in request.session else False}
# return render(request, "welcome/old_student.html", context)
return dashboard_view(request, show_welcome=True) | def student_welcome_view(request) | Welcome/first run page for students. | 3.84794 | 3.909785 | 0.984182 |
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) | Send an announcement request email.
form: The announcement request form
obj: The announcement request object | 3.015193 | 2.979177 | 1.012089 |
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) | Send an admin announcement request email.
form: The announcement request form
obj: The announcement request object | 4.215709 | 4.30416 | 0.97945 |
if not settings.PRODUCTION:
logger.debug("Not in production. Ignoring email for approved announcement.")
return
subject = "Announcement Approved: {}".format(obj.title)
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)))
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) | Email the requested teachers and submitter whenever an administrator approves an announcement
request.
obj: the Announcement object
req: the AnnouncementRequest object | 2.594965 | 2.501858 | 1.037215 |
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) | Send a notification posted email.
obj: The announcement object | 3.082051 | 3.105877 | 0.992329 |
text = get_template(text_template)
html = get_template(html_template)
text_content = text.render(data)
html_content = html.render(data)
subject = settings.EMAIL_SUBJECT_PREFIX + subject
headers = {} if headers is None else headers
msg = EmailMultiAlternatives(subject, text_content, settings.EMAIL_FROM, emails, headers=headers)
msg.attach_alternative(html_content, "text/html")
logger.debug("Emailing {} to {}".format(subject, emails))
msg.send()
return msg | def email_send(text_template, html_template, data, subject, emails, headers=None) | Send an HTML/Plaintext email with the following fields.
text_template: URL to a Django template for the text email's contents
html_template: URL to a Django tempalte for the HTML email's contents
data: The context to pass to the templates
subject: The subject of the email
emails: The addresses to send the email to
headers: A dict of additional headers to send to the message | 2.00558 | 2.065724 | 0.970885 |
try:
field = self.fields[name]
except KeyError:
raise KeyError("Key %r not found in '%s'" % (name, self.__class__.__name__))
return BoundField(self, field, name) | def field_(self, name) | From https://github.com/halfnibble/django-underscore-filters
Get a form field starting with _.
Taken near directly from Django > forms.
Returns a BoundField with the given name. | 3.387937 | 2.906827 | 1.16551 |
'''
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) | Decorator that gives out connections. | 6.446458 | 4.399168 | 1.465381 |
'''
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) | Return a connection from the pool | 2.855349 | 2.57977 | 1.106823 |
'''
Insert the new value.
'''
if self._value_type in QUOTE_TYPES and not QUOTE_MATCH.match(value):
value = "'%s'"%(value)
for interval,config in self._intervals.items():
timestamps = self._normalize_timestamps(timestamp, intervals, config)
for tstamp in timestamps:
self._insert_data(name, value, tstamp, interval, config, **kwargs) | def _insert(self, name, value, timestamp, intervals, **kwargs) | Insert the new value. | 5.22236 | 4.90844 | 1.063955 |
'''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) | Helper to insert data into cql. | 4.115893 | 3.169132 | 1.298745 |
'''
Fetch a series of buckets.
'''
fetch = kws.get('fetch')
process_row = kws.get('process_row') or self._process_row
rval = OrderedDict()
if fetch:
data = fetch( connection, self._table, name, interval, buckets )
else:
data = self._type_get(name, interval, buckets[0], buckets[-1])
if config['coarse']:
for i_bucket in buckets:
i_key = config['i_calc'].from_bucket(i_bucket)
i_data = data.get( i_bucket )
if i_data:
rval[ i_key ] = process_row( i_data[None] )
else:
rval[ i_key ] = self._type_no_value()
else:
if data:
for i_bucket, i_data in data.items():
i_key = config['i_calc'].from_bucket(i_bucket)
rval[i_key] = OrderedDict()
for r_bucket, r_data in i_data.items():
r_key = config['r_calc'].from_bucket(r_bucket)
if r_data:
rval[i_key][r_key] = process_row(r_data)
else:
rval[i_key][r_key] = self._type_no_value()
return rval | def _series(self, connection, name, interval, config, buckets, **kws) | Fetch a series of buckets. | 2.866827 | 2.73692 | 1.047464 |
'''Helper to generate the insert statement.'''
# Calculate the TTL and abort if inserting into the past
expire, ttl = config['expire'], config['ttl'](timestamp)
if expire and not ttl:
return None
i_time = config['i_calc'].to_bucket(timestamp)
if not config['coarse']:
r_time = config['r_calc'].to_bucket(timestamp)
else:
r_time = -1
# TODO: figure out escaping rules of CQL
stmt = '''INSERT INTO %s (name, interval, i_time, r_time, value)
VALUES ('%s', '%s', %s, %s, %s)'''%(self._table, name, interval, i_time, r_time, value)
expire = config['expire']
if ttl:
stmt += " USING TTL %s"%(ttl)
return stmt | def _insert_stmt(self, name, value, timestamp, interval, config) | Helper to generate the insert statement. | 5.150522 | 4.986388 | 1.032916 |
return (Event.objects.filter(approved=True).filter(Q(groups__in=user.groups.all()) | Q(groups__isnull=True) | Q(user=user))) | def visible_to_user(self, user) | Get a list of visible events for a given user (usually request.user).
These visible events will be those that either have no groups
assigned to them (and are therefore public) or those in which
the user is a member. | 5.08454 | 3.369342 | 1.50906 |
ids = user.events_hidden.all().values_list("event__id")
return Event.objects.filter(id__in=ids) | def hidden_events(self, user) | Get a list of events marked as hidden for a given user (usually request.user).
These are all events visible to the user -- they have just decided to
hide them. | 4.462564 | 4.562928 | 0.978004 |
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) | Return whether the event is in the next or previous 2 weeks.
Determines whether to display the fuzzy date. | 2.952812 | 2.675376 | 1.1037 |
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) | Formats a `datetime.datetime` object relative to the current time. | 1.581689 | 1.554592 | 1.01743 |
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) | Renders the template at page.template | 3.874441 | 3.739832 | 1.035993 |
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) | Runs whenever a new announcement is created, or a request is approved and posted.
obj: The Announcement object | 2.972195 | 3.141587 | 0.946081 |
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) | The request announcement page. | 2.846394 | 2.849417 | 0.998939 |
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) | The approve announcement page. Teachers will be linked to this page from an email.
req_id: The ID of the AnnouncementRequest | 2.549066 | 2.534003 | 1.005944 |
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) | The administrator approval announcement request page. Admins will view this page through the
UI.
req_id: The ID of the AnnouncementRequest | 2.499067 | 2.524252 | 0.990022 |
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) | Add an announcement. | 2.587851 | 2.519349 | 1.02719 |
announcement = get_object_or_404(Announcement, id=id)
return render(request, "announcements/view.html", {"announcement": announcement}) | def view_announcement_view(request, id) | View an announcement.
id: announcement id | 1.980157 | 2.250952 | 0.879698 |
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) | Modify an announcement.
id: announcement id | 2.059318 | 2.086924 | 0.986772 |
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) | Delete an announcement.
id: announcement id | 2.091582 | 2.119523 | 0.986817 |
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) | 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. | 2.896885 | 2.544947 | 1.138289 |
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) | 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. | 2.820324 | 2.737162 | 1.030383 |
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) | Validates the username and password in the form. | 3.924408 | 3.642652 | 1.077349 |
'''
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) | Calculate keys given a stat name and timestamp. | 4.242075 | 3.522103 | 1.204415 |
'''
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) | Specialized batch insert | 4.998303 | 4.806277 | 1.039953 |
'''
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) | Insert the value. | 4.4439 | 4.262599 | 1.042533 |
'''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) | Helper to insert data into redis | 4.726976 | 4.773969 | 0.990157 |
'''
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) | Delete all the data in a named timeseries. | 6.644253 | 5.381636 | 1.234616 |
'''
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) | Fetch a single interval from redis. | 5.248916 | 4.884436 | 1.074621 |
'''
Fetch a series of buckets.
'''
pipe = self._client.pipeline(transaction=False)
step = config['step']
resolution = config.get('resolution',step)
fetch = kws.get('fetch') or self._type_get
process_row = kws.get('process_row') or self._process_row
rval = OrderedDict()
for interval_bucket in buckets:
i_key = '%s%s:%s:%s'%(self._prefix, name, interval, interval_bucket)
if config['coarse']:
fetch(pipe, i_key)
else:
pipe.smembers(i_key)
res = pipe.execute()
# TODO: a memory efficient way to use a single pipeline for this.
for idx,data in enumerate(res):
# TODO: use closures on the config for generating this interval key
interval_bucket = buckets[idx] #start_bucket + idx
interval_key = '%s%s:%s:%s'%(self._prefix, name, interval, interval_bucket)
if config['coarse']:
data = process_row( data )
rval[ config['i_calc'].from_bucket(interval_bucket) ] = data
else:
rval[ config['i_calc'].from_bucket(interval_bucket) ] = OrderedDict()
pipe = self._client.pipeline(transaction=False)
resolution_buckets = sorted(map(int,data))
for bucket in resolution_buckets:
# TODO: use closures on the config for generating this resolution key
resolution_key = '%s:%s'%(interval_key, bucket)
fetch(pipe, resolution_key)
resolution_res = pipe.execute()
for x,data in enumerate(resolution_res):
i_t = config['i_calc'].from_bucket(interval_bucket)
r_t = config['r_calc'].from_bucket(resolution_buckets[x])
rval[ i_t ][ r_t ] = process_row(data)
return rval | def _series(self, name, interval, config, buckets, **kws) | Fetch a series of buckets. | 3.729472 | 3.621986 | 1.029676 |
'''
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) | Insert the value into the series. | 6.539765 | 5.167148 | 1.265643 |
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) | Choose an item from a list. | 4.113002 | 3.9517 | 1.040819 |
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",
insecure="no") | Clear compiled python files and start the Django dev server. | 3.076589 | 3.054615 | 1.007193 |
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) | Clear all sessions for all sandboxes or for production. | 4.789537 | 4.439146 | 1.078932 |
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) | Clear the production or sandbox redis cache. | 3.919778 | 3.121404 | 1.255774 |
if local("pwd", capture=True) == PRODUCTION_DOCUMENT_ROOT:
abort("Refusing to automatically load fixtures into production database!")
if not confirm("Are you sure you want to load all fixtures? This could have unintended consequences if the database is not empty."):
abort("Aborted.")
files = [
"fixtures/users/users.json", "fixtures/eighth/sponsors.json", "fixtures/eighth/rooms.json", "fixtures/eighth/blocks.json",
"fixtures/eighth/activities.json", "fixtures/eighth/scheduled_activities.json", "fixtures/eighth/signups.json",
"fixtures/announcements/announcements.json"
]
for f in files:
local("./manage.py loaddata " + f) | def load_fixtures() | Populate a database with data from fixtures. | 4.384126 | 4.384146 | 0.999995 |
_require_root()
if not confirm("This will apply any available migrations to the database. Has the database been backed up?"):
abort("Aborted.")
if not confirm("Are you sure you want to deploy?"):
abort("Aborted.")
with lcd(PRODUCTION_DOCUMENT_ROOT):
with shell_env(PRODUCTION="TRUE"):
local("git pull")
with open("requirements.txt", "r") as req_file:
requirements = req_file.read().strip().split()
try:
pkg_resources.require(requirements)
except pkg_resources.DistributionNotFound:
local("pip install -r requirements.txt")
except Exception:
traceback.format_exc()
local("pip install -r requirements.txt")
else:
puts("Python requirements already satisfied.")
with prefix("source /usr/local/virtualenvs/ion/bin/activate"):
local("./manage.py collectstatic --noinput", shell="/bin/bash")
local("./manage.py migrate", shell="/bin/bash")
restart_production_gunicorn(skip=True)
puts("Deploy complete.") | def deploy() | Deploy to production. | 4.353025 | 4.230963 | 1.02885 |
if app is None:
abort("No app name given.")
local("./manage.py migrate {} --fake".format(app))
local("./manage.py migrate {}".format(app)) | def forcemigrate(app=None) | Force migrations to apply for a given app. | 6.282579 | 5.400341 | 1.163367 |
results = User.objects.filter(student_id=student_id)
if len(results) == 1:
return results.first()
return None | def user_with_student_id(self, student_id) | Get a unique user object by FCPS student ID. (Ex. 1624472) | 2.865819 | 2.576452 | 1.112312 |
if isinstance(student_id, str) and not student_id.isdigit():
return None
results = User.objects.filter(id=student_id)
if len(results) == 1:
return results.first()
return None | def user_with_ion_id(self, student_id) | Get a unique user object by Ion ID. (Ex. 489) | 2.888205 | 2.614371 | 1.104742 |
results = []
if sn and not given_name:
results = User.objects.filter(last_name=sn)
elif given_name:
query = {'first_name': given_name}
if sn:
query['last_name'] = sn
results = User.objects.filter(**query)
if len(results) == 0:
# Try their first name as a nickname
del query['first_name']
query['nickname'] = given_name
results = User.objects.filter(**query)
if len(results) == 1:
return results.first()
return None | def user_with_name(self, given_name=None, sn=None) | Get a unique user object by given name (first/nickname and last). | 2.587249 | 2.459547 | 1.051921 |
users = User.objects.filter(properties___birthday__month=month, properties___birthday__day=day)
results = []
for user in users:
# TODO: permissions system
results.append(user)
return results | def users_with_birthday(self, month, day) | Return a list of user objects who have a birthday on a given date. | 4.96335 | 4.453869 | 1.114391 |
users = User.objects.filter(user_type="student", graduation_year__gte=settings.SENIOR_GRADUATION_YEAR)
users = users.exclude(id__in=EXTRA)
return users | def get_students(self) | Get user objects that are students (quickly). | 7.044644 | 6.063632 | 1.161786 |
users = User.objects.filter(user_type="teacher")
users = users.exclude(id__in=EXTRA)
# Add possible exceptions handling here
users = users | User.objects.filter(id__in=[31863, 32327, 32103, 33228])
return users | def get_teachers(self) | Get user objects that are teachers (quickly). | 7.654307 | 7.124785 | 1.074321 |
teachers = self.get_teachers()
teachers = [(u.last_name, u.first_name, u.id) for u in teachers]
for t in teachers:
if t is None or t[0] is None or t[1] is None or t[2] is None:
teachers.remove(t)
for t in teachers:
if t[0] is None or len(t[0]) <= 1:
teachers.remove(t)
teachers.sort(key=lambda u: (u[0], u[1]))
# Hack to return QuerySet in given order
id_list = [t[2] for t in teachers]
clauses = ' '.join(['WHEN id=%s THEN %s' % (pk, i) for i, pk in enumerate(id_list)])
ordering = 'CASE %s END' % clauses
queryset = User.objects.filter(id__in=id_list).extra(select={'ordering': ordering}, order_by=('ordering',))
return queryset | def get_teachers_sorted(self) | Get teachers sorted by last name.
This is used for the announcement request page. | 2.58558 | 2.561136 | 1.009544 |
if isinstance(group, Group):
group = group.name
return self.groups.filter(name=group).exists() | def member_of(self, group) | Returns whether a user is a member of a certain group.
Args:
group
The name of a group (string) or a group object
Returns:
Boolean | 3.852734 | 4.886926 | 0.788376 |
return "{}, {} ".format(self.last_name, self.first_name) + ("({})".format(self.nickname) if self.nickname else "") | def last_first(self) | Return a name in the format of:
Lastname, Firstname [(Nickname)] | 4.572806 | 2.944182 | 1.553167 |
return ("{}{} ".format(self.last_name, ", " + self.first_name if self.first_name else "") + ("({}) ".format(self.nickname)
if self.nickname else "") +
("({})".format(self.student_id if self.is_student and self.student_id else self.username))) | def last_first_id(self) | Return a name in the format of:
Lastname, Firstname [(Nickname)] (Student ID/ID/Username) | 5.077783 | 3.390174 | 1.497794 |
return ("{}{} ".format(self.last_name, ", " + self.first_name[:1] + "." if self.first_name else "") + ("({}) ".format(self.nickname)
if self.nickname else "")) | def last_first_initial(self) | Return a name in the format of:
Lastname, F [(Nickname)] | 5.900945 | 4.102404 | 1.438412 |
for email in self.emails.all():
if email.address.endswith(("@fcps.edu", "@tjhsst.edu")):
return email
if self.is_teacher:
domain = "fcps.edu"
else:
domain = "tjhsst.edu"
return "{}@{}".format(self.username, domain) | def tj_email(self) | Get (or guess) a user's TJ email.
If a fcps.edu or tjhsst.edu email is specified in their email
list, use that. Otherwise, append the user's username to the
proper email suffix, depending on whether they are a student or
teacher. | 4.997909 | 2.806064 | 1.78111 |
preferred = self.preferred_photo
if preferred is not None:
return preferred.binary
if preferred is None:
if self.user_type == "teacher":
current_grade = 12
else:
current_grade = int(self.grade)
if current_grade > 12:
current_grade = 12
for i in reversed(range(9, current_grade + 1)):
data = None
if self.photos.filter(grade_number=i).exists():
data = self.photos.filter(grade_number=i).first().binary
if data:
return data | def default_photo(self) | Returns default photo (in binary) that should be used
Returns:
Binary data | 3.787372 | 3.686406 | 1.027389 |
# TODO: optimize this, it's kind of a bad solution for listing a mostly
# static set of files.
# We could either add a permissions dict as an attribute or cache this
# in some way. Creating a dict would be another place we have to define
# the permission, so I'm not a huge fan, but it would definitely be the
# easier option.
permissions_dict = {"self": {}, "parent": {}}
for field in self.properties._meta.get_fields():
split_field = field.name.split('_', 1)
if len(split_field) <= 0 or split_field[0] not in ['self', 'parent']:
continue
permissions_dict[split_field[0]][split_field[1]] = getattr(self.properties, field.name)
return permissions_dict | def permissions(self) | Dynamically generate dictionary of privacy options | 7.195666 | 6.937486 | 1.037215 |
try:
# threadlocals is a module, not an actual thread locals object
request = threadlocals.request()
if request is None:
return False
requesting_user = request.user
if isinstance(requesting_user, AnonymousUser) or not requesting_user.is_authenticated:
return False
can_view_anyway = requesting_user and (requesting_user.is_teacher or requesting_user.is_eighthoffice or requesting_user.is_eighth_admin)
except (AttributeError, KeyError) as e:
logger.error("Could not check teacher/eighth override: {}".format(e))
can_view_anyway = False
return can_view_anyway | def _current_user_override(self) | Return whether the currently logged in user is a teacher, and can view all of a student's
information regardless of their privacy settings. | 4.932723 | 4.42706 | 1.114221 |
date = datetime.today().date()
b = self.birthday
if b:
return int((date - b).days / 365)
return None | def age(self) | Returns a user's age, based on their birthday.
Returns:
integer | 5.445366 | 6.308296 | 0.863207 |
# FIXME: remove recursive dep
from ..eighth.models import EighthSponsor
return EighthSponsor.objects.filter(user=self).exists() | def is_eighth_sponsor(self) | Determine whether the given user is associated with an.
:class:`intranet.apps.eighth.models.EighthSponsor` and, therefore, should view activity
sponsoring information. | 10.267078 | 6.462948 | 1.588606 |
key = "{}:frequent_signups".format(self.username)
cached = cache.get(key)
if cached:
return cached
freq_signups = self.eighthsignup_set.exclude(scheduled_activity__activity__administrative=True).exclude(
scheduled_activity__activity__special=True).exclude(scheduled_activity__activity__restricted=True).exclude(
scheduled_activity__activity__deleted=True).values('scheduled_activity__activity').annotate(
count=Count('scheduled_activity__activity')).filter(count__gte=settings.SIMILAR_THRESHOLD).order_by('-count')
cache.set(key, freq_signups, timeout=60 * 60 * 24 * 7)
return freq_signups | def frequent_signups(self) | Return a QuerySet of activity id's and counts for the activities that a given user
has signed up for more than `settings.SIMILAR_THRESHOLD` times | 3.436193 | 2.860965 | 1.201061 |
# FIXME: remove recursive dep
from ..eighth.models import EighthSponsor
try:
sp = EighthSponsor.objects.get(user=self)
except EighthSponsor.DoesNotExist:
return False
return sp | def get_eighth_sponsor(self) | Return the :class:`intranet.apps.eighth.models.EighthSponsor` that a given user is
associated with. | 6.191461 | 4.344767 | 1.425039 |
# FIXME: remove recursive dep
from ..eighth.models import EighthSignup
return EighthSignup.objects.filter(user=self, was_absent=True, scheduled_activity__attendance_taken=True).count() | def absence_count(self) | Return the user's absence count.
If the user has no absences
or is not a signup user, returns 0. | 17.940636 | 14.637687 | 1.225647 |
# FIXME: remove recursive dep
from ..eighth.models import EighthSignup
return EighthSignup.objects.filter(user=self, was_absent=True, scheduled_activity__attendance_taken=True) | def absence_info(self) | Return information about the user's absences. | 21.744503 | 20.108152 | 1.081377 |
from intranet.apps.eighth.models import EighthScheduledActivity
EighthScheduledActivity.objects.filter(eighthsignup_set__user=self).update(
archived_member_count=F('archived_member_count')+1) | def handle_delete(self) | Handle a graduated user being deleted. | 9.617333 | 7.775703 | 1.236844 |
try:
if not getattr(self, 'parent_{}'.format(permission)) and not parent and not admin:
return False
level = 'parent' if parent else 'self'
setattr(self, '{}_{}'.format(level, permission), value)
# Set student permission to false if parent sets permission to false.
if parent and not value:
setattr(self, 'self_{}'.format(permission), False)
self.save()
return True
except Exception as e:
logger.error("Error occurred setting permission {} to {}: {}".format(permission, value, e))
return False | def set_permission(self, permission, value, parent=False, admin=False) | Sets permission for personal information.
Returns False silently if unable to set permission.
Returns True if successful. | 3.394343 | 3.358478 | 1.010679 |
try:
# threadlocals is a module, not an actual thread locals object
request = threadlocals.request()
if request and request.user and request.user.is_authenticated:
requesting_user_id = request.user.id
return str(requesting_user_id) == str(self.user.id)
except (AttributeError, KeyError) as e:
logger.error("Could not check request sender: {}".format(e))
return False
return False | def is_http_request_sender(self) | Checks if a user the HTTP request sender (accessing own info)
Used primarily to load private personal information from the
cache. (A student should see all info on his or her own profile
regardless of how the permissions are set.)
Returns:
Boolean | 4.27975 | 4.380775 | 0.976939 |
try:
parent = getattr(self, "parent_{}".format(permission))
student = getattr(self, "self_{}".format(permission))
return (parent and student) or (self.is_http_request_sender() or self._current_user_override())
except Exception:
logger.error("Could not retrieve permissions for {}".format(permission)) | def attribute_is_visible(self, permission) | Checks privacy options to see if an attribute is visible to public | 7.272315 | 7.033591 | 1.033941 |
try:
parent = getattr(self, "parent_{}".format(permission))
student = getattr(self, "self_{}".format(permission))
return (parent and student)
except Exception:
logger.error("Could not retrieve permissions for {}".format(permission)) | def attribute_is_public(self, permission) | Checks if attribute is visible to public (regardless of admins status) | 5.265708 | 4.97392 | 1.058664 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.