code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if redirect_to is None: redirect_to = get_static_url('img/sitemessage/blank.png') return _generic_view( 'handle_mark_read_request', sig_mark_read_failed, request, message_id, dispatch_id, hashed, redirect_to=redirect_to )
def mark_read(request, message_id, dispatch_id, hashed, redirect_to=None)
Handles mark message as read request. :param Request request: :param int message_id: :param int dispatch_id: :param str hashed: :param str redirect_to: :return:
6.100733
7.048919
0.865485
if not is_iterable(messages): messages = (messages,) results = [] for message in messages: if isinstance(message, six.string_types): message = PlainTextMessage(message) resulting_priority = message.priority if priority is not None: resulting_pri...
def schedule_messages(messages, recipients=None, sender=None, priority=None)
Schedules a message or messages. :param MessageBase|str|list messages: str or MessageBase heir or list - use str to create PlainTextMessage. :param list|None recipients: recipients addresses or Django User model heir instances If `None` Dispatches should be created before send using `prepare_dispatches...
2.548276
2.80781
0.907567
dispatches_by_messengers = Dispatch.group_by_messengers(Dispatch.get_unsent(priority=priority)) for messenger_id, messages in dispatches_by_messengers.items(): try: messenger_obj = get_registered_messenger_object(messenger_id) messenger_obj._process_messages(messages, ignor...
def send_scheduled_messages(priority=None, ignore_unknown_messengers=False, ignore_unknown_message_types=False)
Sends scheduled messages. :param int, None priority: number to limit sending message by this priority. :param bool ignore_unknown_messengers: to silence UnknownMessengerError :param bool ignore_unknown_message_types: to silence UnknownMessageTypeError :raises UnknownMessengerError: :raises UnknownM...
2.988808
3.414203
0.875404
failed_count = Dispatch.objects.filter(dispatch_status=Dispatch.DISPATCH_STATUS_FAILED).count() if failed_count: from sitemessage.shortcuts import schedule_email from sitemessage.messages.email import EmailTextMessage if to is None: admins = settings.ADMINS ...
def check_undelivered(to=None)
Sends a notification email if any undelivered dispatches. Returns undelivered (failed) dispatches count. :param str|unicode to: Recipient address. If not set Django ADMINS setting is used. :rtype: int
5.312885
4.804151
1.105895
filter_kwargs = { 'dispatch_status': Dispatch.DISPATCH_STATUS_SENT, } objects = Dispatch.objects if ago: filter_kwargs['time_dispatched__lte'] = timezone.now() - timedelta(days=int(ago)) dispatch_map = dict(objects.filter(**filter_kwargs).values_list('pk', 'message_id')) ...
def cleanup_sent_messages(ago=None, dispatches_only=False)
Cleans up DB : removes delivered dispatches (and messages). :param int ago: Days. Allows cleanup messages sent X days ago. Defaults to None (cleanup all sent). :param bool dispatches_only: Remove dispatches only (messages objects will stay intact).
2.906027
2.918885
0.995595
dispatches = [] target_messages = Message.get_without_dispatches() cache = {} for message_model in target_messages: if message_model.cls not in cache: message_cls = get_registered_message_type(message_model.cls) subscribers = message_cls.get_subscribers() ...
def prepare_dispatches()
Automatically creates dispatches for messages without them. :return: list of Dispatch :rtype: list
3.236133
3.158318
1.024638
if new_messengers_titles is None: new_messengers_titles = {} msgr_to_msg = defaultdict(set) msg_titles = OrderedDict() msgr_titles = OrderedDict() for msgr in get_registered_messenger_objects().values(): if not (messenger_filter is None or messenger_filter(msgr)) or not msgr.a...
def get_user_preferences_for_ui(user, message_filter=None, messenger_filter=None, new_messengers_titles=None)
Returns a two element tuple with user subscription preferences to render in UI. Message types with the same titles are merged into one row. First element: A list of messengers titles. Second element: User preferences dictionary indexed by message type titles. Preferences (dictiona...
2.651136
2.580328
1.027442
prefs = [] for pref in request.POST.getlist(_PREF_POST_KEY): message_alias, messenger_alias = pref.split(_ALIAS_SEP) try: get_registered_message_type(message_alias) get_registered_messenger_object(messenger_alias) except (UnknownMessengerError, UnknownMess...
def set_user_preferences_from_request(request)
Sets user subscription preferences using data from a request. Expects data sent by form built with `sitemessage_prefs_table` template tag. :param request: :rtype: bool :return: Flag, whether prefs were found in the request.
5.041342
4.976198
1.013091
url_unsubscribe = url( r'^messages/unsubscribe/(?P<message_id>\d+)/(?P<dispatch_id>\d+)/(?P<hashed>[^/]+)/$', unsubscribe, name='sitemessage_unsubscribe' ) url_mark_read = url( r'^messages/ping/(?P<message_id>\d+)/(?P<dispatch_id>\d+)/(?P<hashed>[^/]+)/$', mark_...
def get_sitemessage_urls()
Returns sitemessage urlpatterns, that can be attached to urlpatterns of a project: # Example from urls.py. from sitemessage.toolbox import get_sitemessage_urls urlpatterns = patterns('', # Your URL Patterns belongs here. ) + get_sitemessage_urls() # Now attaching additio...
2.762075
2.720555
1.015261
''' Determine the list of gradings in this scheme as rendered string. TODO: Use nice little icons instead of (p) / (f) marking. ''' result = [] for grading in gradingScheme.gradings.all(): if grading.means_passed: result.append(str(grading) + " (pass)") else: ...
def gradings(gradingScheme)
Determine the list of gradings in this scheme as rendered string. TODO: Use nice little icons instead of (p) / (f) marking.
7.151882
2.971658
2.406698
''' Offer only gradings that are not used by other schemes, which means they are used by this scheme or not at all.''' if db_field.name == "gradings": request=kwargs['request'] try: #TODO: MockRequst object from unit test does not contain path information, so an ...
def formfield_for_dbfield(self, db_field, **kwargs)
Offer only gradings that are not used by other schemes, which means they are used by this scheme or not at all.
8.631203
5.361492
1.609851
''' Part of the Python Social Auth Pipeline. Stores the result service URL reported by the LMS / LTI tool consumer so that we can use it later. ''' if backend.name is 'lti': assignment_pk = response.get('assignment_pk', None) assignment = get_object_or_404(Assignment, pk=assignment_p...
def store_report_link(backend, user, response, *args, **kwargs)
Part of the Python Social Auth Pipeline. Stores the result service URL reported by the LMS / LTI tool consumer so that we can use it later.
3.826881
2.376084
1.610583
'''builds the list of BAM tags to be added to output BAMs''' #pylint: disable=unused-argument def _combine_filters(fam, paired_align, align): filters = [x.filter_value for x in [fam, align] if x and x.filter_value] if filters: return ";".join(filters).replace('; ', ';') r...
def build_bam_tags()
builds the list of BAM tags to be added to output BAMs
5.541258
5.454205
1.015961
result = {} livechat = LiveChat.chat_finder.get_current_live_chat() if livechat: result['live_chat'] = {} result['live_chat']['current_live_chat'] = livechat can_comment, reason_code = livechat.can_comment(request) result['live_chat']['can_render_comment_form'] = can_com...
def current_livechat(request)
Checks if a live chat is currently on the go, and add it to the request context. This is to allow the AskMAMA URL in the top-navigation to be redirected to the live chat object view consistently, and to make it available to the views and tags that depends on it.
3.429287
3.373574
1.016514
''' Sanitize the user-provided file name, add timestamp for uniqness. ''' filename = filename.replace(" ", "_") filename = unicodedata.normalize('NFKD', filename).lower() return os.path.join(str(timezone.now().date().isoformat()), filename)
def upload_path(instance, filename)
Sanitize the user-provided file name, add timestamp for uniqness.
7.476447
3.988382
1.874556
''' Calculate the checksum of the file upload. For binary files (e.g. PDFs), the MD5 of the file itself is used. Archives are unpacked and the MD5 is generated from the sanitized textfiles in the archive. This is done with some smartness: - Whitespace...
def attachment_md5(self)
Calculate the checksum of the file upload. For binary files (e.g. PDFs), the MD5 of the file itself is used. Archives are unpacked and the MD5 is generated from the sanitized textfiles in the archive. This is done with some smartness: - Whitespace and tabs are removed be...
2.904536
1.835392
1.582516
''' Determines if the attachment is an archive. ''' try: if zipfile.is_zipfile(self.attachment.path) or tarfile.is_tarfile(self.attachment.path): return True except Exception: pass return False
def is_archive(self)
Determines if the attachment is an archive.
4.140087
3.133792
1.321111
''' Return preview on archive file / single file content as dictionary. In order to avoid browser and web server trashing by the students, there is a size limit for the single files shown. ''' MAX_PREVIEW_SIZE = 1000000 def sanitize(bytes): ...
def previews(self)
Return preview on archive file / single file content as dictionary. In order to avoid browser and web server trashing by the students, there is a size limit for the single files shown.
2.546185
1.970085
1.292424
if SESSION_VAR not in self.strategy.request.session: # This is the only protection layer when people # go directly to the passthrough login view. logger.warn("Auth data for passthrough provider not found in session. Raising 404.") raise PermissionDenied ...
def auth_complete(self, *args, **kwargs)
Completes loging process, must return user instance
6.367208
6.671727
0.954357
result = { 'id': response['id'], 'username': response.get('username', None), 'email': response.get('email', None), 'first_name': response.get('first_name', None), 'last_name': response.get('last_name', None) } if result['first_...
def get_user_details(self, response)
Complete with additional information from session, as available.
1.771523
1.720911
1.02941
'''Given a BAM file, return a generator that yields filtered, paired reads''' total_aligns = pysamwrapper.total_align_count(args.input_bam) bamfile_generator = _bamfile_generator(args.input_bam) return _paired_reader(args.umt_length, bamfile_generator, ...
def paired_reader_from_bamfile(args, log, usage_logger, annotated_writer)
Given a BAM file, return a generator that yields filtered, paired reads
5.445723
4.339128
1.255027
'''Returns count of all mapped alignments in input BAM (based on index)''' count = 0 for line in idxstats(bam_filepath): if line: chrom, _, mapped, unmapped = line.strip().split('\t') if chrom != '*': count += int(mapped) + int(unmapped) return count
def total_align_count(bam_filepath)
Returns count of all mapped alignments in input BAM (based on index)
4.752951
3.150852
1.508465
'''given collection of random {aligns}, returns alternating forward/reverse strands up to {total_aligns}; will return smaller of forward/reverse collection if less than total_aligns''' predicate=lambda align: align.is_reverse gen1, gen2 = itertools.tee((predicate(align), align) for align in base_ali...
def _balanced_strand_gen(base_aligns, limit)
given collection of random {aligns}, returns alternating forward/reverse strands up to {total_aligns}; will return smaller of forward/reverse collection if less than total_aligns
5.186046
2.579629
2.010385
''' Determine our own IP adress. This seems to be far more complicated than you would think: ''' try: import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("gmail.com", 80)) result = s.getsockname()[0] s.close() return result ...
def ipaddress()
Determine our own IP adress. This seems to be far more complicated than you would think:
3.688428
2.037436
1.810328
''' Determine some system information about the installed OpenCL device. ''' result = [] try: import pyopencl as ocl for plt in ocl.get_platforms(): result.append("Platform: " + platform.name) for device in plt.get_devices(): result.append(...
def opencl()
Determine some system information about the installed OpenCL device.
3.870873
3.284754
1.178436
''' Summarize all host information. ''' output = [] output.append(["Operating system", os()]) output.append(["CPUID information", cpu()]) output.append(["CC information", compiler()]) output.append(["JDK information", from_cmd("java -version")]) output.append(["MPI information", ...
def all_host_infos()
Summarize all host information.
4.427554
4.082797
1.084441
'''returns one or more families whose end < rightmost boundary''' in_progress = self._right_coords_in_progress[reference_name] while len(in_progress): right_coord = in_progress[0] if right_coord < rightmost_boundary: in_progress.pop(0) left...
def _completed_families(self, reference_name, rightmost_boundary)
returns one or more families whose end < rightmost boundary
4.716764
4.087163
1.154044
'''Given a stream of paired aligns, return a list of pairs that share same coordinates (coordinate family). Flushes families in progress when any of: a) incoming right start > family end b) incoming chrom != current chrom c) incoming align stream is exhausted''' ...
def build_coordinate_families(self, paired_aligns)
Given a stream of paired aligns, return a list of pairs that share same coordinates (coordinate family). Flushes families in progress when any of: a) incoming right start > family end b) incoming chrom != current chrom c) incoming align stream is exhausted
4.53244
2.326119
1.948499
'''Return a method that logs progress/mem usage.''' def _log_usage(): log.debug("{}mb peak memory", peak_memory()) log.debug("{} pending alignment pairs; {} peak pairs", self.pending_pair_count, self.pending_pair_peak_count) ret...
def build_usage_logger(self, log)
Return a method that logs progress/mem usage.
13.089083
8.653175
1.512633
''' Create an email message for the student, based on the given submission state. Sending eMails on validation completion does not work, since this may have been triggered by the admin. ''' details_url = request.build_absolute_uri(reverse('details', args=(submission.pk,))) if state...
def inform_student(submission, request, state)
Create an email message for the student, based on the given submission state. Sending eMails on validation completion does not work, since this may have been triggered by the admin.
3.638702
2.659073
1.36841
''' Queryset for the graded submissions, which are worth closing. ''' qs = self._valid_submissions().filter(state__in=[Submission.GRADED]) return qs
def graded_submissions(self)
Queryset for the graded submissions, which are worth closing.
13.307584
5.653765
2.353756
''' Queryset for all distinct authors this course had so far. Important for statistics. Note that this may be different from the list of people being registered for the course, f.e. when they submit something and the leave the course. ''' qs = self._valid_subm...
def authors(self)
Queryset for all distinct authors this course had so far. Important for statistics. Note that this may be different from the list of people being registered for the course, f.e. when they submit something and the leave the course.
19.840069
2.771955
7.157427
taf_header_pattern = metar_header_pattern = header_taf = re.match(taf_header_pattern, string, re.VERBOSE) header_metar = re.match(metar_header_pattern, string, re.VERBOSE) # The difference between a METAR and TAF header isn't that big # so it's likely to ge...
def _init_header(self, string)
Extracts header part from TAF/METAR string and populates header dict Args: TAF/METAR report string Raises: MalformedTAF: An error parsing the report Returns: Header dictionary
4.031645
3.554403
1.134268
taf_group_pattern = group_list = [] groups = re.findall(taf_group_pattern, string, re.VERBOSE) if not groups: raise MalformedTAF("No valid groups found") for group in groups: group_list.append(group) return(group_list)
def _init_groups(self, string)
Extracts weather groups (FM, PROB etc.) and populates group list Args: TAF report string Raises: MalformedTAF: Group decoding error
4.667024
3.231524
1.444218
logger.debug("Running post-processing for user login.") # Users created by social login or admins have no profile. # We fix that during their first login. try: with transaction.atomic(): profile, created = UserProfile.objects.get_or_create(user=user) if created: ...
def post_user_login(sender, request, user, **kwargs)
Create a profile for the user, when missing. Make sure that all neccessary user groups exist and have the right permissions. We need that automatism for people not calling the configure tool, admin rights for admins after the first login, and similar cases.
5.536835
5.179462
1.068998
''' Update MD5 field for newly uploaded files. ''' if created: logger.debug("Running post-processing for new submission file.") instance.md5 = instance.attachment_md5() instance.save()
def submissionfile_post_save(sender, instance, signal, created, **kwargs)
Update MD5 field for newly uploaded files.
9.927071
5.90554
1.680976
''' Several sanity checks after we got a valid submission object.''' logger.debug("Running post-processing for submission") # Make the submitter an author if instance.submitter not in instance.authors.all(): instance.authors.add(instance.submitter) instance.save() # Mark all existing...
def submission_post_save(sender, instance, **kwargs)
Several sanity checks after we got a valid submission object.
12.066751
10.396079
1.160702
if priority is None: priority = self.priority self._message_model, self._dispatch_models = Message.create( self.get_alias(), self.get_context(), recipients=recipients, sender=sender, priority=priority ) return self._message_model, self._dispatch_models
def schedule(self, recipients=None, sender=None, priority=None)
Schedules message for a delivery. Puts message (and dispatches if any) data into DB. :param list|None recipients: recipient (or a list) or None. If `None` Dispatches should be created before send using `prepare_dispatches()`. :param User|None sender: Django User model heir instance ...
4.948332
3.760011
1.316042
subscribers_raw = Subscription.get_for_message_cls(cls.alias) subscribers = [] for subscriber in subscribers_raw: messenger_cls = subscriber.messenger_cls address = subscriber.address recipient = subscriber.recipient # Do not send messag...
def get_subscribers(cls, active_only=True)
Returns a list of Recipient objects subscribed for this message type. :param bool active_only: Flag whether :return:
4.059417
4.346036
0.93405
global APP_URLS_ATTACHED url = '' if dispatch_model is None: return url if APP_URLS_ATTACHED != False: # sic! hashed = cls.get_dispatch_hash(dispatch_model.id, message_model.id) try: url = reverse(name, args=[message_mode...
def _get_url(cls, name, message_model, dispatch_model)
Returns a common pattern sitemessage URL. :param str name: URL name :param Message message_model: :param Dispatch|None dispatch_model: :return:
3.996526
4.245692
0.941313
if hash_is_valid: Subscription.cancel( dispatch.recipient_id or dispatch.address, cls.alias, dispatch.messenger ) signal = sig_unsubscribe_success else: signal = sig_unsubscribe_failed signal.send(cls, request=request, me...
def handle_unsubscribe_request(cls, request, message, dispatch, hash_is_valid, redirect_to)
Handles user subscription cancelling request. :param Request request: Request instance :param Message message: Message model instance :param Dispatch dispatch: Dispatch model instance :param bool hash_is_valid: Flag indicating that user supplied request signature is correct :par...
5.768471
5.628853
1.024804
if hash_is_valid: dispatch.mark_read() dispatch.save() signal = sig_mark_read_success else: signal = sig_mark_read_failed signal.send(cls, request=request, message=message, dispatch=dispatch) return redirect(redirect_to)
def handle_mark_read_request(cls, request, message, dispatch, hash_is_valid, redirect_to)
Handles a request to mark a message as read. :param Request request: Request instance :param Message message: Message model instance :param Dispatch dispatch: Dispatch model instance :param bool hash_is_valid: Flag indicating that user supplied request signature is correct :para...
3.079124
2.950988
1.043422
template = message.context.get('tpl', None) if template: # Template name is taken from message context. return template if cls.template is None: cls.template = 'sitemessage/messages/%s__%s.%s' % ( cls.get_alias(), messenger.get_alias(), cls.tem...
def get_template(cls, message, messenger)
Get a template path to compile a message. 1. `tpl` field of message context; 2. `template` field of message class; 3. deduced from message, messenger data and `template_ext` message type field (e.g. `sitemessage/messages/plain__smtp.txt` for `plain` message type). :param Mes...
5.782238
4.013268
1.44078
if message.context.get('use_tpl', False): context = message.context context.update({ 'SITE_URL': get_site_url(), 'directive_unsubscribe': cls.get_unsubscribe_directive(message, dispatch), 'directive_mark_read': cls.get_mark_read_di...
def compile(cls, message, messenger, dispatch=None)
Compiles and returns a message text. Considers `use_tpl` field from message context to decide whether template compilation is used. Otherwise a SIMPLE_TEXT_ID field from message context is used as message contents. :param Message message: model instance :param MessengerBase me...
4.471539
3.348683
1.335313
if isinstance(str_or_dict, dict): base_context.update(str_or_dict) base_context['use_tpl'] = True else: base_context[cls.SIMPLE_TEXT_ID] = str_or_dict if cls.SIMPLE_TEXT_ID in str_or_dict: base_context['use_tpl'] = False base_con...
def update_context(cls, base_context, str_or_dict, template_path=None)
Helper method to structure initial message context data. NOTE: updates `base_context` inplace. :param dict base_context: context dict to update :param dict, str str_or_dict: text representing a message, or a dict to be placed into message context. :param str template_path: template pat...
2.776076
3.125786
0.888121
return Dispatch.create(message, recipients or cls.get_subscribers())
def prepare_dispatches(cls, message, recipients=None)
Creates Dispatch models for a given message and return them. :param Message message: Message model instance :param list|None recipients: A list or Recipient objects :return: list of created Dispatch models :rtype: list
12.517513
25.930361
0.482736
url_extend = ( self._url_base + '/oauth/access_token?grant_type=fb_exchange_token&' 'client_id=%(app_id)s&client_secret=%(app_secret)s&fb_exchange_token=%(user_token)s') response = self.lib.get(url_extend % {'app_id': app_id, 'app_secret': app_secret, '...
def get_page_access_token(self, app_id, app_secret, user_token)
Returns a dictionary of never expired page token indexed by page names. :param str app_id: Application ID :param str app_secret: Application secret :param str user_token: User short-lived token :rtype: dict
2.674198
2.666468
1.002899
''' Create a fresh temporary directory, based on the fiven prefix. Returns the new path. ''' # Fetch base directory from executor configuration basepath = config.get("Execution", "directory") if not prefix: prefix = 'opensubmit' finalpath = tempfile.mkdtemp(prefix=prefi...
def create_working_dir(config, prefix)
Create a fresh temporary directory, based on the fiven prefix. Returns the new path.
6.226892
4.47147
1.392583
''' Based on two downloaded files in the working directory, the student submission and the validation package, the working directory is prepared. We unpack student submission first, so that teacher files overwrite them in case. When the student submission is a single directory, we change t...
def prepare_working_directory(job, submission_path, validator_path)
Based on two downloaded files in the working directory, the student submission and the validation package, the working directory is prepared. We unpack student submission first, so that teacher files overwrite them in case. When the student submission is a single directory, we change the worki...
3.944133
2.880636
1.369188
''' Run something like it would be done through Django's manage.py. ''' from django.core.management import execute_from_command_line from django.core.exceptions import ImproperlyConfigured os.environ.setdefault("DJANGO_SETTINGS_MODULE", "opensubmit.settings") try: execute_from_co...
def django_admin(args)
Run something like it would be done through Django's manage.py.
3.302058
2.303104
1.433742
''' Generate a valid Apache configuration file, based on the given settings. ''' if os.path.exists(outputfile): os.rename(outputfile, outputfile + ".old") print("Renamed existing Apache config file to " + outputfile + ".old") from django.conf import settings f = open(outputf...
def apache_config(config, outputfile)
Generate a valid Apache configuration file, based on the given settings.
3.052192
2.842589
1.073737
''' Checks if the directories for this path exist, and creates them in case. ''' directory = os.path.dirname(file_path) if directory != '': if not os.path.exists(directory): os.makedirs(directory, 0o775)
def check_path(file_path)
Checks if the directories for this path exist, and creates them in case.
4.079909
2.302824
1.771698
''' - Checks if the parent directories for this path exist. - Checks that the file exists. - Donates the file to the web server user. TODO: This is Debian / Ubuntu specific. ''' check_path(filepath) if not os.path.exists(filepath): print("WARNING: File does not e...
def check_file(filepath)
- Checks if the parent directories for this path exist. - Checks that the file exists. - Donates the file to the web server user. TODO: This is Debian / Ubuntu specific.
4.405588
2.719823
1.619807
''' Check the web application config file for consistency. ''' login_conf_deps = { 'LOGIN_TWITTER_OAUTH_KEY': ['LOGIN_TWITTER_OAUTH_SECRET'], 'LOGIN_GOOGLE_OAUTH_KEY': ['LOGIN_GOOGLE_OAUTH_SECRET'], 'LOGIN_GITHUB_OAUTH_KEY': ['LOGIN_GITHUB_OAUTH_SECRET'], 'LOGIN_GITLA...
def check_web_config_consistency(config)
Check the web application config file for consistency.
2.871835
2.808906
1.022404
''' Try to load the Django settings. If this does not work, than settings file does not exist. Returns: Loaded configuration, or None. ''' print("Looking for config file at {0} ...".format(config_fname)) config = RawConfigParser() try: config.readfp(open(...
def check_web_config(config_fname)
Try to load the Django settings. If this does not work, than settings file does not exist. Returns: Loaded configuration, or None.
7.100444
4.252797
1.669594
if url.startswith('/'): url = url[1:] if url.endswith('/'): url = url[:-1] return url
def normalize_url(url: str) -> str
Remove leading and trailing slashes from a URL :param url: URL :return: URL with no leading and trailing slashes :private:
3.345656
2.66665
1.254629
curr_parts = variable_parts var_any = [] while curr_parts: curr_parts, (var_type, part) = curr_parts if var_type == Routes._VAR_ANY_NODE: var_any.append(part) continue if var_type == Routes._VAR_ANY_BREAK: if var_any: yield ...
def _unwrap(variable_parts: VariablePartsType)
Yield URL parts. The given parts are usually in reverse order.
2.946405
2.674953
1.101479
# The unwrapped variable parts are in reverse order. # Instead of reversing those we reverse the key parts # and avoid the O(n) space required for reversing the vars return dict(zip(reversed(key_parts), _unwrap(variable_parts)))
def make_params( key_parts: Sequence[str], variable_parts: VariablePartsType) -> Dict[str, Union[str, Tuple[str]]]
Map keys to variables. This map\ URL-pattern variables to\ a URL related parts :param key_parts: A list of URL parts :param variable_parts: A linked-list\ (ala nested tuples) of URL parts :return: The param dict with the values\ assigned to the keys :private:
10.566777
12.414512
0.851163
parts = url.split('/', self._max_depth + 1) if depth_of(parts) > self._max_depth: raise RouteError('No match') return parts
def _deconstruct_url(self, url: str) -> List[str]
Split a regular URL into parts :param url: A normalized URL :return: Parts of the URL :raises kua.routes.RouteError: \ If the depth of the URL exceeds\ the max depth of the deepest\ registered pattern :private:
8.228587
5.032887
1.634963
route_match = None # type: RouteResolved route_variable_parts = tuple() # type: VariablePartsType # (route_partial, variable_parts, depth) to_visit = [(self._routes, tuple(), 0)] # type: List[Tuple[dict, tuple, int]] # Walk through the graph, # keep track of ...
def _match(self, parts: Sequence[str]) -> RouteResolved
Match URL parts to a registered pattern. This function is basically where all\ the CPU-heavy work is done. :param parts: URL parts :return: Matched route :raises kua.routes.RouteError: If there is no match :private:
2.688084
2.720095
0.988231
url = normalize_url(url) parts = self._deconstruct_url(url) return self._match(parts)
def match(self, url: str) -> RouteResolved
Match a URL to a registered pattern. :param url: URL :return: Matched route :raises kua.RouteError: If there is no match
6.301042
10.677954
0.590098
url = normalize_url(url) parts = url.split('/') curr_partial_routes = self._routes curr_key_parts = [] for part in parts: if part.startswith(':*'): curr_key_parts.append(part[2:]) part = self._VAR_ANY_NODE self...
def add(self, url: str, anything: Any) -> None
Register a URL pattern into\ the routes for later matching. It's possible to attach any kind of\ object to the pattern for later\ retrieving. A dict with methods and callbacks,\ for example. Anything really. Registration order does not matter.\ Adding a URL firs...
3.729233
3.877468
0.96177
site_url = getattr(_THREAD_LOCAL, _THREAD_SITE_URL, None) if site_url is None: site_url = SITE_URL or get_site_url_() setattr(_THREAD_LOCAL, _THREAD_SITE_URL, site_url) return site_url
def get_site_url()
Returns a URL for current site. :rtype: str|unicode
2.932315
3.343352
0.877058
message_type = default_message_type_alias try: message_type = _MESSAGES_FOR_APPS[app_name][message_type] except KeyError: pass return get_registered_message_type(message_type)
def get_message_type_for_app(app_name, default_message_type_alias)
Returns a registered message type object for a given application. Supposed to be used by reusable applications authors, to get message type objects which may be overridden by project authors using `override_message_type_for_app`. :param str|unicode app_name: :param str|unicode default_message_type...
3.110266
3.896771
0.798165
if isinstance(messenger, six.string_types): messenger = get_registered_messenger_object(messenger) return messenger._structure_recipients_data(addresses)
def recipients(messenger, addresses)
Structures recipients data. :param str|unicode, MessageBase messenger: MessengerBase heir :param list[str|unicode]|str|unicode addresses: recipients addresses or Django User model heir instances (NOTE: if supported by a messenger) :return: list of Recipient :rtype: list[Recipient]
6.68993
6.451454
1.036965
chat = None now = datetime.now() lcqs = self.get_query_set() lcqs = lcqs.filter( chat_ends_at__gte=now).order_by('-chat_starts_at') try: if settings.LIVECHAT_PRIMARY_CATEGORY: lcqs = lcqs.filter( primary_categ...
def upcoming_live_chat(self)
Find any upcoming or current live chat to advertise on the home page or live chat page. These are LiveChat's with primary category of 'ask-mama' and category of 'live-chat'. The Chat date must be less than 5 days away, or happening now.
2.693777
2.481704
1.085454
now = datetime.now() chat = self.upcoming_live_chat() if chat and chat.is_in_progress(): return chat return None
def get_current_live_chat(self)
Check if there is a live chat on the go, so that we should take over the AskMAMA page with the live chat.
6.95789
6.235309
1.115885
now = datetime.now() lcqs = self.get_query_set() lcqs = lcqs.filter( chat_ends_at__lte=now, ).order_by('-chat_ends_at') for itm in lcqs: if itm.chat_ends_at + timedelta(days=3) > now: return itm return None
def get_last_live_chat(self)
Check if there is a live chat that ended in the last 3 days, and return it. We will display a link to it on the articles page.
4.013341
3.553595
1.129375
ct = ContentType.objects.get_for_model(self.__class__) qs = Comment.objects.filter( content_type=ct, object_pk=self.pk) qs = qs.exclude(is_removed=True) qs = qs.order_by('-submit_date') return qs
def comment_set(self)
Get the comments that have been submitted for the chat
2.447324
2.508581
0.975581
dispatches = Dispatch.objects.prefetch_related('message').filter( **filter_kwargs ).order_by('-message__time_created') return list(dispatches)
def _get_dispatches(filter_kwargs)
Simplified version. Not distributed friendly.
5.378394
4.585018
1.173036
dispatches = Dispatch.objects.prefetch_related('message').filter( **filter_kwargs ).select_for_update( **GET_DISPATCHES_ARGS[1] ).order_by('-message__time_created') try: dispatches = list(dispatches) except NotSupportedError: return None except Database...
def _get_dispatches_for_update(filter_kwargs)
Distributed friendly version using ``select for update``.
6.777604
6.160403
1.100188
''' A filtering of the given Submission queryset for all submissions that were successfully validated. This includes the following cases: - The submission was submitted and there are no tests. - The submission was successfully validity-tested, regardless of the full test sta...
def qs_valid(qs)
A filtering of the given Submission queryset for all submissions that were successfully validated. This includes the following cases: - The submission was submitted and there are no tests. - The submission was successfully validity-tested, regardless of the full test status (not existent / fail...
11.626765
1.887982
6.158305
''' A filtering of the given Submission queryset for all submissions that are gradeable. This includes the following cases: - The submission was submitted and there are no tests. - The submission was successfully validity-tested, regardless of the full test status (not exist...
def qs_tobegraded(qs)
A filtering of the given Submission queryset for all submissions that are gradeable. This includes the following cases: - The submission was submitted and there are no tests. - The submission was successfully validity-tested, regardless of the full test status (not existent / failed / success)....
13.974486
1.949554
7.168043
''' The list of authors als text, for admin submission list overview.''' author_list = [self.submitter] + \ [author for author in self.authors.all().exclude(pk=self.submitter.pk)] return ",\n".join([author.get_full_name() for author in author_list])
def author_list(self)
The list of authors als text, for admin submission list overview.
7.465595
3.402938
2.193867
''' A rendering of the grading that is an answer on the question "Is grading finished?". Used in duplicate view and submission list on the teacher backend. ''' if self.assignment.is_graded(): if self.is_grading_finished(): return str('Yes ({0})...
def grading_status_text(self)
A rendering of the grading that is an answer on the question "Is grading finished?". Used in duplicate view and submission list on the teacher backend.
10.42761
2.588547
4.028364
''' A rendering of the grading that is an answer to the question "What is the grade?". ''' if self.assignment.is_graded(): if self.is_grading_finished(): return str(self.grading) else: return str('pending') else: ...
def grading_value_text(self)
A rendering of the grading that is an answer to the question "What is the grade?".
5.145079
3.000663
1.714647
''' Information if the given grading means passed. Non-graded assignments are always passed. ''' if self.assignment.is_graded(): if self.grading and self.grading.means_passed: return True else: return False else: ...
def grading_means_passed(self)
Information if the given grading means passed. Non-graded assignments are always passed.
5.922006
2.783666
2.127413
# The user must be authorized to commit these actions. if user and not self.user_can_modify(user): #self.log('DEBUG', "Submission cannot be modified, user is not an authorized user ({!r} not in {!r})", user, self.authorized_users) return False # Modification of...
def can_modify(self, user=None)
Determines whether the submission can be modified. Returns a boolean value. The 'user' parameter is optional and additionally checks whether the given user is authorized to perform these actions. This function checks the submission states and assignment deadlines.
4.392282
4.235172
1.037096
# Re-uploads are allowed only when test executions have failed. if self.state not in (self.TEST_VALIDITY_FAILED, self.TEST_FULL_FAILED): return False # It must be allowed to modify the submission. if not self.can_modify(user=user): return False ...
def can_reupload(self, user=None)
Determines whether a submission can be re-uploaded. Returns a boolean value. Requires: can_modify. Re-uploads are allowed only when test executions have failed.
8.130594
4.551229
1.786461
''' Return first state for this submission after upload, which depends on the kind of assignment. ''' if not self.assignment.attachment_is_tested(): return Submission.SUBMITTED else: if self.assignment.attachment_test_validity: ...
def get_initial_state(self)
Return first state for this submission after upload, which depends on the kind of assignment.
8.847024
4.177786
2.117634
''' Prepares an open temporary file with information about the submission. Closing it will delete it, which must be considered by the caller. This file is not readable, since the tempfile library wants either readable or writable files. ''' info = tempfile.Nam...
def info_file(self, delete=True)
Prepares an open temporary file with information about the submission. Closing it will delete it, which must be considered by the caller. This file is not readable, since the tempfile library wants either readable or writable files.
3.241313
2.232923
1.451601
''' Copies the currently valid file upload into the given directory. If possible, the content is un-archived in the target directory. ''' assert(self.file_upload) # unpack student data to temporary directory # os.chroot is not working with tarfile support ...
def copy_file_upload(self, targetdir)
Copies the currently valid file upload into the given directory. If possible, the content is un-archived in the target directory.
3.067022
2.539584
1.207687
updates = self.get_updates() chat_ids = [] if updates: for update in updates: message = update['message'] if message['text'] == '/start': chat_ids.append(message['chat']['id']) return list(set(chat_ids))
def get_chat_ids(self)
Returns unique chat IDs from `/start` command messages sent to our bot by users. Those chat IDs can be used to send messages to chats. :rtype: list
2.395213
2.392079
1.00131
try: response = self.lib.post(self._tpl_url % {'token': self.auth_token, 'method': method_name}, data=data) json = response.json() if not json['ok']: raise TelegramMessengerException(json['description']) return json['result'] ex...
def _send_command(self, method_name, data=None)
Sends a command to API. :param str method_name: :param dict data: :return:
4.107848
4.369093
0.940206
''' Restrict the listed submission files for the current user.''' qs = super(SubmissionFileAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: return qs.filter(Q(submissions__assignment__course__tutors__pk=request.user.pk) | Q(submissi...
def get_queryset(self, request)
Restrict the listed submission files for the current user.
4.708488
3.154532
1.492611
from .plain import PlainTextMessage from .email import EmailTextMessage, EmailHtmlMessage register_message_types(PlainTextMessage, EmailTextMessage, EmailHtmlMessage)
def register_builtin_message_types()
Registers the built-in message types.
4.442304
4.41177
1.006921
''' Link to performance data and duplicate overview.''' result=format_html('') result+=format_html('<a href="%s" style="white-space: nowrap">Show duplicates</a><br/>'%reverse('duplicates', args=(obj.pk,))) result+=format_html('<a href="%s" style="white-space: nowrap">Show submissions</a><br/>'%obj.gradi...
def view_links(obj)
Link to performance data and duplicate overview.
5.200989
4.198365
1.238813
''' Check if such an assignment configuration makes sense, and reject it otherwise. This mainly relates to interdependencies between the different fields, since single field constraints are already clatified by the Django model configuration. ''' super(Assignm...
def clean(self)
Check if such an assignment configuration makes sense, and reject it otherwise. This mainly relates to interdependencies between the different fields, since single field constraints are already clatified by the Django model configuration.
4.824719
3.11102
1.550848
''' Restrict the listed assignments for the current user.''' qs = super(AssignmentAdmin, self).get_queryset(request) if not request.user.is_superuser: qs = qs.filter(course__active=True).filter(Q(course__tutors__pk=request.user.pk) | Q(course__owner=request.user)).distinct() ...
def get_queryset(self, request)
Restrict the listed assignments for the current user.
3.968415
2.874454
1.380581
if self.ENV_USERNAME in os.environ: response = os.environ elif type(self.strategy).__name__ == "DjangoStrategy" and self.ENV_USERNAME in self.strategy.request.META: # Looks like the Django strategy. In this case, it might by mod_wsgi, which stores # authentic...
def auth_complete(self, *args, **kwargs)
Completes loging process, must return user instance
5.942438
5.8206
1.020932
result = { 'username': response[self.ENV_USERNAME], 'email': response.get(self.ENV_EMAIL, None), 'first_name': response.get(self.ENV_FIRST_NAME, None), 'last_name': response.get(self.ENV_LAST_NAME, None) } if result['first_name'] and resul...
def get_user_details(self, response)
Complete with additional information from environment, as available.
2.129076
1.958761
1.08695
''' Renders the link to the student upload file. ''' sfile = instance.file_upload if not sfile: return mark_safe('No file submitted by student.') else: return mark_safe('<a href="%s">%s</a><br/>(<a href="%s" target="_new">Preview</a>)' % (sfile...
def file_link(self, instance)
Renders the link to the student upload file.
4.491199
3.424154
1.311623
''' Restrict the listed submission for the current user.''' qs = super(SubmissionAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: return qs.filter(Q(assignment__course__tutors__pk=request.user.pk) | Q(assignment__course__owner=reque...
def get_queryset(self, request)
Restrict the listed submission for the current user.
4.404382
2.981147
1.477412
''' Offer grading choices from the assignment definition as potential form field values for 'grading'. When no object is given in the form, the this is a new manual submission ''' if db_field.name == "grading": submurl = kwargs['request'].path try:...
def formfield_for_dbfield(self, db_field, **kwargs)
Offer grading choices from the assignment definition as potential form field values for 'grading'. When no object is given in the form, the this is a new manual submission
9.653019
4.70385
2.052153
''' Our custom addition to the view adds an easy radio button choice for the new state. This is meant to be for tutors. We need to peel this choice from the form data and set the state accordingly. The radio buttons have no default, so that we can keep the existing state ...
def save_model(self, request, obj, form, change)
Our custom addition to the view adds an easy radio button choice for the new state. This is meant to be for tutors. We need to peel this choice from the form data and set the state accordingly. The radio buttons have no default, so that we can keep the existing state if t...
11.118242
1.900963
5.848743
''' Set all marked submissions to "grading not finished". This is intended to support grading corrections on a larger scale. ''' for subm in queryset: subm.state = Submission.GRADING_IN_PROGRESS subm.save()
def setGradingNotFinishedStateAction(self, request, queryset)
Set all marked submissions to "grading not finished". This is intended to support grading corrections on a larger scale.
8.37188
2.700182
3.100487
''' Set all marked submissions to "grading finished". This is intended to support grading corrections on a larger scale. ''' for subm in queryset: subm.state = Submission.GRADED subm.save()
def setGradingFinishedStateAction(self, request, queryset)
Set all marked submissions to "grading finished". This is intended to support grading corrections on a larger scale.
9.561483
2.791228
3.425548
''' Close all submissions were the tutor sayed that the grading is finished, and inform the student. CLosing only graded submissions is a safeguard, since backend users tend to checkbox-mark all submissions without thinking. ''' mails = [] qs = queryset.filter(Q(s...
def closeAndNotifyAction(self, request, queryset)
Close all submissions were the tutor sayed that the grading is finished, and inform the student. CLosing only graded submissions is a safeguard, since backend users tend to checkbox-mark all submissions without thinking.
8.791234
3.241848
2.711798
''' Download selected submissions as archive, for targeted correction. ''' output = io.BytesIO() z = zipfile.ZipFile(output, 'w') for sub in queryset: sub.add_to_zipfile(z) z.close() # go back to start in ZIP file so that Django can deliver i...
def downloadArchiveAction(self, request, queryset)
Download selected submissions as archive, for targeted correction.
4.574571
3.165106
1.445313
''' The assignment name in a format that is suitable for a directory name. ''' coursename = self.course.directory_name() assignmentname = self.title.replace(" ", "_").replace("\\", "_").replace(",","").lower() return coursename + os.sep + assignmentname
def directory_name_with_course(self)
The assignment name in a format that is suitable for a directory name.
7.12721
4.766875
1.495154