code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if daynum is None: return None try: daycount = int(daynum) except ValueError: return None if daycount > max_days: # Using default: some time in the 48th century, clearly bogus. daycount = max_days return date(1970, 1, 1) + timedelta(daycount)
def daynum_to_date(daynum, max_days=1000000)
Convert a number of days to a date. If it's out of range, default to a max date. If it is not a number (or a numeric string), return None. Using a max_days of more than 2932896 (9999-12-31) will throw an exception if the specified daynum exceeds the max. :param daynum: A number of days since Jan 1, 1970
4.69396
5.029387
0.933307
target_day_date = datetime.strptime(target_day, date_format) # Compute activity over `past_days` days leading up to target_day min_activity_date = target_day_date - timedelta(past_days) min_activity = unix_time_nanos(min_activity_date) max_activity = unix_time_nanos(target_day_date + timedelta...
def mau(dataframe, target_day, past_days=28, future_days=10, date_format="%Y%m%d")
Compute Monthly Active Users (MAU) from the Executive Summary dataset. See https://bugzilla.mozilla.org/show_bug.cgi?id=1240849
3.551221
3.429773
1.03541
delta_days = ((day.weekday() + 1) % 7) if weekday_start is "Sunday" else day.weekday() return day - timedelta(days=delta_days)
def snap_to_beginning_of_week(day, weekday_start="Sunday")
Get the first day of the current week. :param day: The input date to snap. :param weekday_start: Either "Monday" or "Sunday", indicating the first day of the week. :returns: A date representing the first day of the current week.
3.227523
3.642044
0.886185
today = date.today() # Get the first day of the past complete week. start_of_week = snap_to_beginning_of_week(today, weekday_start) - timedelta(weeks=1) end_of_week = start_of_week + timedelta(days=6) return (start_of_week, end_of_week)
def get_last_week_range(weekday_start="Sunday")
Gets the date for the first and the last day of the previous complete week. :param weekday_start: Either "Monday" or "Sunday", indicating the first day of the week. :returns: A tuple containing two date objects, for the first and the last day of the week respectively.
3.1646
3.090706
1.023908
today = date.today() # Get the last day for the previous month. end_of_last_month = snap_to_beginning_of_month(today) - timedelta(days=1) start_of_last_month = snap_to_beginning_of_month(end_of_last_month) return (start_of_last_month, end_of_last_month)
def get_last_month_range()
Gets the date for the first and the last day of the previous complete month. :returns: A tuple containing two date objects, for the first and the last day of the month respectively.
2.50426
2.580172
0.970579
base_path = path # Specifying basePath retains the partition fields even # if we read a bunch of paths separately. reader = spark.read.option("basePath", base_path) if mergeSchema: reader = reader.option("mergeSchema", "true") if submission_date_s3 is not None and sample_id is Non...
def read_main_summary(spark, submission_date_s3=None, sample_id=None, mergeSchema=True, path='s3://telemetry-parquet/main_summary/v4')
Efficiently read main_summary parquet data. Read data from the given path, optionally filtering to a specified set of partition values first. This can save a time, particularly if `mergeSchema` is True. Args: spark: Spark session submission_date_s3: Optional list of values to filter th...
3.130224
3.110915
1.006207
return dataframe \ .withColumn( "sampler", udf(lambda key: (crc32(key or "") & 0xffffffff) % modulo)(column), ).where("sampler = %s" % sample_id).drop("sampler")
def sampler(dataframe, modulo, column="client_id", sample_id=42)
Collect a sample of clients given an input column Filter dataframe based on the modulus of the CRC32 of a given string column matching a given sample_id. if dataframe has already been filtered by sample_id, then modulo should be a multiple of 100, column should be "client_id", and the given sample_id s...
6.379107
7.058437
0.903756
if 'delete' in request.GET: models.MachineCache.objects.all().delete() models.InstituteCache.objects.all().delete() models.PersonCache.objects.all().delete() models.ProjectCache.objects.all().delete() return render( template_name='main.html', cont...
def progress(request)
Check status of task.
3.102523
3.029329
1.024162
def inner(request, *args): lock_id = '%s-%s-built-%s' % ( datetime.date.today(), func.__name__, ",".join([str(a) for a in args])) if cache.add(lock_id, 'true', LOCK_EXPIRE): result = func(request, *args) cache.set(lock_id, result.task_id) ...
def synchronise(func)
If task already queued, running, or finished, don't restart.
3.445159
3.584586
0.961104
sorted_list = sorted(obj_list, key=lambda x: x['size'], reverse=True) groups = [[] for _ in range(tot_groups)] for index, obj in enumerate(sorted_list): current_group = groups[index % len(groups)] current_group.append(obj) return groups
def _group_by_size_greedy(obj_list, tot_groups)
Partition a list of objects in even buckets The idea is to choose the bucket for an object in a round-robin fashion. The list of objects is sorted to also try to keep the total size in bytes as balanced as possible. :param obj_list: a list of dict-like objects with a 'size' property :param tot_grou...
2.042919
2.313663
0.88298
sorted_obj_list = sorted([(obj['size'], obj) for obj in obj_list], reverse=True) groups = [(random.random(), []) for _ in range(tot_groups)] if tot_groups <= 1: groups = _group_by_size_greedy(obj_list, tot_groups) return groups heapq.heapify(groups) for obj in sorted_obj_list: ...
def _group_by_equal_size(obj_list, tot_groups, threshold=pow(2, 32))
Partition a list of objects evenly and by file size Files are placed according to largest file in the smallest bucket. If the file is larger than the given threshold, then it is placed in a new bucket by itself. :param obj_list: a list of dict-like objects with a 'size' property :param tot_groups: ...
2.403015
2.345761
1.024407
if not (properties or aliased_properties): return self merged_properties = dict(zip(properties, properties)) merged_properties.update(aliased_properties) for prop_name in (merged_properties.keys()): if prop_name in self.selection: raise E...
def select(self, *properties, **aliased_properties)
Specify which properties of the dataset must be returned Property extraction is based on `JMESPath <http://jmespath.org>`_ expressions. This method returns a new Dataset narrowed down by the given selection. :param properties: JMESPath to use for the property extraction. ...
2.878233
3.055767
0.941902
clauses = copy(self.clauses) for dimension, condition in kwargs.items(): if dimension in self.clauses: raise Exception('There should be only one clause for {}'.format(dimension)) if dimension not in self.schema: raise Exception('The dimens...
def where(self, **kwargs)
Return a new Dataset refined using the given condition :param kwargs: a map of `dimension` => `condition` to filter the elements of the dataset. `condition` can either be an exact value or a callable returning a boolean value. If `condition` is a value, it is converted to a ...
4.463199
4.105113
1.087229
clauses = copy(self.clauses) schema = self.schema if self.prefix: schema = ['prefix'] + schema # Add a clause for the prefix that always returns True, in case # the output is not filtered at all (so that we do a scan/filter # on the prefi...
def summaries(self, sc, limit=None)
Summary of the files contained in the current dataset Every item in the summary is a dict containing a key name and the corresponding size of the key item in bytes, e.g.:: {'key': 'full/path/to/my/key', 'size': 200} :param limit: Max number of objects to retrieve :return: An it...
8.289002
7.919995
1.046592
decode = decode or message_parser.parse_heka_message summaries = summaries or self.summaries(sc, limit) # Calculate the sample if summaries is not empty and limit is not set if summaries and limit is None and sample != 1: if sample < 0 or sample > 1: ...
def records(self, sc, group_by='greedy', limit=None, sample=1, seed=42, decode=None, summaries=None)
Retrieve the elements of a Dataset :param sc: a SparkContext object :param group_by: specifies a partition strategy for the objects :param limit: maximum number of objects to retrieve :param decode: an optional transformation to apply to the objects retrieved :param sample: perc...
4.452113
4.523128
0.9843
rdd = self.records(spark.sparkContext, group_by, limit, sample, seed, decode, summaries) if not schema: df = rdd.map(lambda d: Row(**d)).toDF() else: df = spark.createDataFrame(rdd, schema=schema) if table_name: df.createOrReplaceTempView(tabl...
def dataframe(self, spark, group_by='greedy', limit=None, sample=1, seed=42, decode=None, summaries=None, schema=None, table_name=None)
Convert RDD returned from records function to a dataframe :param spark: a SparkSession object :param group_by: specifies a paritition strategy for the objects :param limit: maximum number of objects to retrieve :param decode: an optional transformation to apply to the objects retrieved ...
2.365294
2.307108
1.02522
meta_bucket = 'net-mozaws-prod-us-west-2-pipeline-metadata' store = S3Store(meta_bucket) try: source = json.loads(store.get_key('sources.json').read().decode('utf-8'))[source_name] except KeyError: raise Exception('Unknown source {}'.format(source_name))...
def from_source(source_name)
Create a Dataset configured for the given source_name This is particularly convenient when the user doesn't know the list of dimensions or the bucket name, but only the source name. Usage example:: records = Dataset.from_source('telemetry').where( docType='main', ...
4.61199
4.479352
1.029611
application.reopen() link, is_secret = base.get_email_link(application) emails.send_invite_email(application, link, is_secret) messages.success( request, "Sent an invitation to %s." % application.applicant.email) return 'success'
def get_next_action(self, request, application, roles)
Retrieve the next state.
7.1569
7.321252
0.977551
# Check for serious errors in submission. # Should only happen in rare circumstances. errors = application.check_valid() if len(errors) > 0: for error in errors: messages.error(request, error) return 'error' # mark as submitted ...
def get_next_action(self, request, application, roles)
Retrieve the next state.
5.817771
5.8749
0.990276
# Check for serious errors in submission. # Should only happen in rare circumstances. errors = application.check_valid() if len(errors) > 0: for error in errors: messages.error(request, error) return 'error' # approve application ...
def get_next_action(self, request, application, roles)
Retrieve the next state.
5.747974
5.690089
1.010173
context = CONTEXT.copy() context['person'] = person for lp in leader_list: leader = lp['leader'] context['project'] = lp['project'] context['receiver'] = leader to_email = leader.email subject = render_to_string( 'karaage/people/emails/bounced_emai...
def send_bounced_warning(person, leader_list)
Sends an email to each project leader for person informing them that person's email has bounced
3.993962
3.830463
1.042684
uid = urlsafe_base64_encode(force_bytes(person.pk)).decode("ascii") token = default_token_generator.make_token(person) url = '%s/persons/reset/%s/%s/' % ( settings.REGISTRATION_BASE_URL, uid, token) context = CONTEXT.copy() context.update({ 'url': url, 'receiver': perso...
def send_reset_password_email(person)
Sends an email to user allowing them to set their password.
2.754282
2.78622
0.988537
url = '%s/profile/login/%s/' % ( settings.REGISTRATION_BASE_URL, person.username) context = CONTEXT.copy() context.update({ 'url': url, 'receiver': person, }) to_email = person.email subject, body = render_email('confirm_password', context) send_mail(subject, ...
def send_confirm_password_email(person)
Sends an email to user allowing them to confirm their password.
3.774283
3.712901
1.016532
try: authorised_persons = self.get_authorised_persons(application) authorised_persons.get(pk=request.user.pk) return True except Person.DoesNotExist: return False
def check_can_approve(self, request, application, roles)
Check the person's authorization.
4.022116
3.354771
1.198924
authorised_persons = self.get_email_persons(application) link, is_secret = self.get_request_email_link(application) emails.send_request_email( self.authorised_text, self.authorised_role, authorised_persons, application, link, i...
def enter_state(self, request, application)
This is becoming the new current state.
7.634563
7.702968
0.99112
actions = self.get_actions(request, application, roles) if label == "approve" and 'approve' in actions: application_form = self.get_approve_form( request, application, roles) form = application_form(request.POST or None, instance=application) ...
def get_next_action(self, request, application, label, roles)
Django view method.
2.580814
2.575269
1.002153
actions = self.get_actions(request, application, roles) if label is None and 'is_applicant' in roles: assert application.content_type.model == 'person' if application.applicant.has_usable_password(): form = forms.PersonVerifyPassword( ...
def get_next_action(self, request, application, label, roles)
Django view method.
3.555031
3.552015
1.000849
actions = self.get_actions(request, application, roles) if label is None and \ 'is_applicant' in roles and 'is_admin' not in roles: # applicant, admin, leader can reopen an application for action in actions: if action in request.POST: ...
def get_next_action(self, request, application, label, roles)
Django view method.
5.129138
5.294881
0.968698
assert step_id not in self._steps assert step_id not in self._order assert isinstance(step, Step) self._steps[step_id] = step self._order.append(step_id)
def add_step(self, step, step_id)
Add a step to the list. The first step added becomes the initial step.
2.613456
2.589551
1.009231
actions = self.get_actions(request, application, roles) # if the user is not the applicant, the steps don't apply. if 'is_applicant' not in roles: return super(StateWithSteps, self).get_next_action( request, application, label, roles) # was label su...
def get_next_action(self, request, application, label, roles)
Process the get_next_action request at the current step.
2.969851
2.971716
0.999372
actions = self.get_actions(request, application, roles) if label is None and \ 'is_applicant' in roles and 'is_admin' not in roles: for action in actions: if action in request.POST: return action link, is_secret = base....
def get_next_action(self, request, application, label, roles)
Django get_next_action method.
4.71068
4.806142
0.980137
global _DATASTORES array = settings.DATASTORES for config in array: cls = _lookup(config['ENGINE']) ds = _get_datastore(cls, DataStore, config) _DATASTORES.append(ds) legacy_settings = getattr(settings, 'MACHINE_CATEGORY_DATASTORES', None) if legacy_settings is not None:...
def _init_datastores()
Initialize all datastores.
3.454866
3.425854
1.008469
for datastore in _get_datastores(): datastore.set_account_username(account, old_username, new_username)
def set_account_username(account, old_username, new_username)
Account's username was changed.
3.63568
3.988141
0.911623
result = [] for datastore in _get_datastores(): value = datastore.get_account_details(account) value['datastore'] = datastore.config['DESCRIPTION'] result.append(value) return result
def get_account_details(account)
Get the account details.
5.154035
5.012274
1.028283
for datastore in _get_datastores(): datastore.set_group_name(group, old_name, new_name)
def set_group_name(group, old_name, new_name)
Group was renamed.
3.74323
3.896836
0.960582
result = [] for datastore in _get_datastores(): value = datastore.get_group_details(group) value['datastore'] = datastore.config['DESCRIPTION'] result.append(value) return result
def get_group_details(group)
Get group details.
5.061508
4.967289
1.018968
result = [] for datastore in _get_datastores(): value = datastore.get_project_details(project) value['datastore'] = datastore.config['DESCRIPTION'] result.append(value) return result
def get_project_details(project)
Get details for this user.
5.262213
4.987798
1.055017
for datastore in _get_datastores(): datastore.save_project(project) datastore.set_project_pid(project, old_pid, new_pid)
def set_project_pid(project, old_pid, new_pid)
Project's PID was changed.
3.781592
3.852005
0.981721
result = [] for datastore in _get_datastores(): value = datastore.get_institute_details(institute) value['datastore'] = datastore.config['DESCRIPTION'] result.append(value) return result
def get_institute_details(institute)
Get details for this user.
5.282612
5.172475
1.021293
query = accounts_query.filter(date_deleted__isnull=True) for account in query: add_account_to_group(account, group)
def add_accounts_to_group(accounts_query, group)
Add accounts to group.
4.130945
3.918875
1.054115
query = accounts_query.filter(date_deleted__isnull=True) for account in query: remove_account_from_group(account, group)
def remove_accounts_from_group(accounts_query, group)
Remove accounts from group.
4.065225
4.02835
1.009154
query = accounts_query.filter(date_deleted__isnull=True) for account in query: add_account_to_project(account, project)
def add_accounts_to_project(accounts_query, project)
Add accounts to project.
4.173965
3.88287
1.074969
query = accounts_query.filter(date_deleted__isnull=True) for account in query: remove_account_from_project(account, project)
def remove_accounts_from_project(accounts_query, project)
Remove accounts from project.
4.007971
3.912637
1.024366
query = accounts_query.filter(date_deleted__isnull=True) for account in query: add_account_to_institute(account, institute)
def add_accounts_to_institute(accounts_query, institute)
Add accounts to institute.
4.252379
3.956775
1.074708
query = accounts_query.filter(date_deleted__isnull=True) for account in query: remove_account_from_institute(account, institute)
def remove_accounts_from_institute(accounts_query, institute)
Remove accounts from institute.
4.126776
3.906324
1.056435
status = None applicant = application.applicant attrs = [] saml_session = saml.is_saml_session(request) # certain actions are supported regardless of what else happens if 'cancel' in request.POST: return "cancel" if 'prev' in request.POST: ...
def view(self, request, application, label, roles, actions)
Django view method.
3.746727
3.74094
1.001547
# Get the appropriate form status = None form = None if application.content_type.model != 'applicant': status = "You are already registered in the system." elif application.content_type.model == 'applicant': if application.applicant.saml_id is no...
def view(self, request, application, label, roles, actions)
Django view method.
3.794319
3.781347
1.003431
if 'ajax' in request.POST: resp = self.handle_ajax(request, application) return HttpResponse( json.dumps(resp), content_type="application/json") form_models = { 'common': forms.CommonApplicationForm, 'new': forms.NewProjectApplica...
def view(self, request, application, label, roles, actions)
Django view method.
2.81203
2.801774
1.003661
if application.content_type.model == 'applicant': if not application.applicant.email_verified: application.applicant.email_verified = True application.applicant.save() for action in actions: if action in request.POST: retur...
def view(self, request, application, label, roles, actions)
Django get_next_action method.
5.298023
5.268657
1.005574
# if user is logged and and not applicant, steal the # application if 'is_applicant' in roles: # if we got this far, then we either we are logged in as applicant, # or we know the secret for this application. new_person = None reason = N...
def get_next_action(self, request, application, label, roles)
Process the get_next_action request at the current step.
4.416718
4.464361
0.989328
if value is None: value = "" # replace whitespace with space value = value.replace("\n", " ") value = value.replace("\t", " ") # CSV seperator value = value.replace("|", " ") # remove leading/trailing whitespace value = value.strip(...
def _filter_string(value)
Filter the string so MAM doesn't have heart failure.
4.723532
4.181101
1.129734
length = int(arg) if value is None: value = "" if len(value) > length: return value[:length] + "..." else: return value
def _truncate(value, arg)
Truncates a string after a given number of chars Argument: Number of chars to _truncate after
2.706641
2.916084
0.928176
if ignore_errors is None: ignore_errors = [] command = self._get_command(command) logger.debug("Cmd %s" % command) null = open('/dev/null', 'w') retcode = subprocess.call(command, stdout=null, stderr=null) null.close() if retcode in ignore_e...
def _call(self, command, ignore_errors=None)
Call remote command with logging.
2.601331
2.55262
1.019083
cmd = ["glsuser", "-u", username, "--raw"] results = self._read_output(cmd) if len(results) == 0: return None elif len(results) > 1: logger.error( "Command returned multiple results for '%s'." % username) raise RuntimeError( ...
def get_user(self, username)
Get the user details from MAM.
2.735298
2.701616
1.012467
cmd = ["gbalance", "-u", username, "--raw"] results = self._read_output(cmd) if len(results) == 0: return None return results
def get_user_balance(self, username)
Get the user balance details from MAM.
7.029948
7.281066
0.965511
ds_project = self.get_project(projectname) if ds_project is None: logger.error( "Project '%s' does not exist in MAM" % projectname) raise RuntimeError( "Project '%s' does not exist in MAM" % projectname) user_list = [] if ...
def get_users_in_project(self, projectname)
Get list of users in project from MAM.
3.073046
2.644537
1.162035
ds_balance = self.get_user_balance(username) if ds_balance is None: return [] project_list = [] for bal in ds_balance: project_list.append(bal["Name"]) return project_list
def get_projects_in_user(self, username)
Get list of projects in user from MAM.
4.244335
3.883008
1.093053
# retrieve default project, or use null project if none default_project_name = self._null_project if account.default_project is not None: default_project_name = account.default_project.pid # account created # account updated ds_user = self.get_user...
def _save_account(self, account, username)
Called when account is created/updated. With username override.
4.421744
4.39222
1.006722
# account deleted ds_user = self.get_user(username) if ds_user is not None: self._call(["grmuser", "-u", username], ignore_errors=[8]) return
def _delete_account(self, account, username)
Called when account is deleted. With username override.
12.738533
12.436432
1.024292
self._delete_account(account, old_username) self._save_account(account, new_username)
def set_account_username(self, account, old_username, new_username)
Account's username was changed.
3.330949
3.245698
1.026266
result = self.get_user(account.username) if result is None: result = {} return result
def get_account_details(self, account)
Get the account details
6.230832
6.409808
0.972078
pid = project.pid # project created # project updated if project.is_active: # project is not deleted logger.debug("project is active") ds_project = self.get_project(pid) if ds_project is None: self._create_project...
def save_project(self, project)
Called when project is saved/updated.
3.683806
3.565391
1.033213
pid = project.pid # project deleted ds_project = self.get_project(pid) if ds_project is not None: self._delete_project(pid) return
def delete_project(self, project)
Called when project is deleted.
6.459061
5.751119
1.123096
result = self.get_project(project.pid) if result is None: result = {} return result
def get_project_details(self, project)
Get the project details.
6.476202
5.509205
1.175524
name = institute.name logger.debug("save_institute '%s'" % name) # institute created # institute updated if institute.is_active: # date_deleted is not set, user should exist logger.debug("institute is active") self._call( ...
def save_institute(self, institute)
Called when institute is created/updated.
6.789681
6.612779
1.026752
name = institute.name logger.debug("institute_deleted '%s'" % name) # institute deleted self._call(["goldsh", "Organization", "Delete", "Name==%s" % name]) logger.debug("returning") return
def delete_institute(self, institute)
Called when institute is deleted.
13.885927
12.401295
1.119716
username = account.username projectname = project.pid self._call([ "gchproject", "--add-user", username, "-p", projectname], ignore_errors=[74])
def add_account_to_project(self, account, project)
Add account to project.
10.7485
10.181634
1.055675
img = StringIO() fig.savefig(img, format='svg') img.seek(0) print("%html <div style='width:{}px'>{}</div>".format(width, img.buf))
def show(fig, width=600)
Renders a Matplotlib figure in Zeppelin. :param fig: a Matplotlib figure :param width: the width in pixel of the rendered figure, defaults to 600 Usage example:: import matplotlib.pyplot as plt from moztelemetry.zeppelin import show fig = plt.figure() plt.plot([1, 2, 3]) ...
5.788017
6.304012
0.918148
if short_label is None: short_label = hub_name if long_label is None: long_label = short_label hub = Hub( hub=hub_name, short_label=short_label, long_label=long_label, email=email) genome = Genome(genome) genomes_file = GenomesFile() trackdb...
def default_hub(hub_name, genome, email, short_label=None, long_label=None)
Returns a fully-connected set of hub components using default filenames. Parameters ---------- hub_name : str Name of the hub genome : str Assembly name (hg38, dm6, etc) email : str Email to include with hub. short_label : str Short label for the hub. If None...
2.20307
2.504105
0.879784
assert machine.name == machine_name year, month, day = date.split('-') date = datetime.date(int(year), int(month), int(day)) return parse_logs(usage, date, machine_name, log_type)
def parse_usage(machine, usage, date, machine_name, log_type)
Parses usage
2.727144
2.883681
0.945716
if strict_type_checks: load_whitelist() all_histograms = OrderedDict() for filename in filenames: parser = FILENAME_PARSERS[os.path.basename(filename)] histograms = parser(filename, strict_type_checks) # OrderedDicts are important, because then the iteration order over...
def from_files(filenames, strict_type_checks=True)
Return an iterator that provides a sequence of Histograms for the histograms defined in filenames.
3.708221
3.660244
1.013108
bucket_fns = { 'boolean': linear_buckets, 'flag': linear_buckets, 'count': linear_buckets, 'enumerated': linear_buckets, 'categorical': linear_buckets, 'linear': linear_buckets, 'exponential': exponential_buckets, ...
def ranges(self)
Return an array of lower bounds for each bucket in the histogram.
4.009372
3.656266
1.096575
number = '0001' prefix = 'p%s' % institute.name.replace(' ', '')[:4] found = True while found: try: Project.objects.get(pid=prefix + number) number = str(int(number) + 1) if len(number) == 1: number = '000' + number elif len(n...
def get_new_pid(institute)
Return a new Project ID Keyword arguments: institute_id -- Institute id
2.1608
2.326231
0.928885
for key, value in six.iteritems(extra_context): if callable(value): context[key] = value() else: context[key] = value
def apply_extra_context(extra_context, context)
Adds items from extra_context dict to context. If a value in extra_context is callable, then it is called and the result is added to context.
2.140525
2.004549
1.067834
if form_class: return form_class._meta.model, form_class if model: # The inner Meta class fails if model = model is used for some reason. tmp_model = model # TODO: we should be able to construct a ModelForm without creating # and passing in a temporary inner class. ...
def get_model_and_form_class(model, form_class)
Returns a model and form class based on the model and form_class parameters that were passed to the generic view. If ``form_class`` is given then its associated model will be returned along with ``form_class`` itself. Otherwise, if ``model`` is given, ``model`` itself will be returned along with a ``M...
5.466657
5.219431
1.047366
if post_save_redirect: return HttpResponseRedirect(post_save_redirect % obj.__dict__) elif hasattr(obj, 'get_absolute_url'): return HttpResponseRedirect(obj.get_absolute_url()) else: raise ImproperlyConfigured( "No URL to redirect to. Either pass a post_save_redirec...
def redirect(post_save_redirect, obj)
Returns a HttpResponseRedirect to ``post_save_redirect``. ``post_save_redirect`` should be a string, and can contain named string- substitution place holders of ``obj`` field names. If ``post_save_redirect`` is None, then redirect to ``obj``'s URL returned by ``get_absolute_url()``. If ``obj`` has no...
2.480356
2.484176
0.998462
lookup_kwargs = {} if object_id: lookup_kwargs['%s__exact' % model._meta.pk.name] = object_id elif slug and slug_field: lookup_kwargs['%s__exact' % slug_field] = slug else: raise GenericViewError( "Generic view must be called with either an object_id or a" ...
def lookup_object(model, object_id, slug, slug_field)
Return the ``model`` object with the passed ``object_id``. If ``object_id`` is None, then return the object whose ``slug_field`` equals the passed ``slug``. If ``slug`` and ``slug_field`` are not passed, then raise Http404 exception.
2.186583
2.172728
1.006377
if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated: return redirect_to_login(request.path) model, form_class = get_model_and_form_class(model, form_class) if request.method == 'POST': form = form_class(request.POST, request....
def create_object( request, model=None, template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, form_class=None)
Generic object-creation function. Templates: ``<app_label>/<model_name>_form.html`` Context: form the form for the object
1.92048
1.970511
0.97461
if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated: return redirect_to_login(request.path) model, form_class = get_model_and_form_class(model, form_class) obj = lookup_object(model, object_id, slug, slug_field) if request.metho...
def update_object( request, model=None, object_id=None, slug=None, slug_field='slug', template_name=None, template_loader=loader, extra_context=None, post_save_redirect=None, login_required=False, context_processors=None, template_object_name='object', form_class=None)
Generic object-update function. Templates: ``<app_label>/<model_name>_form.html`` Context: form the form for the object object the original object being edited
1.740685
1.791243
0.971775
if extra_context is None: extra_context = {} if login_required and not request.user.is_authenticated: return redirect_to_login(request.path) obj = lookup_object(model, object_id, slug, slug_field) if request.method == 'POST': obj.delete() msg = ugettext("The %(verb...
def delete_object( request, model, post_delete_redirect, object_id=None, slug=None, slug_field='slug', template_name=None, template_loader=loader, extra_context=None, login_required=False, context_processors=None, template_object_name='object')
Generic object-delete function. The given template will be used to confirm deletetion if this view is fetched using GET; for safty, deletion will only be performed if this view is POSTed. Templates: ``<app_label>/<model_name>_confirm_delete.html`` Context: object the original o...
1.850918
1.999486
0.925697
for k, v in kw.items(): if k not in self.params: raise ValidationError( '"%s" is not a valid parameter for %s' % (k, self.__class__.__name__)) self.params[k].validate(v) self._orig_kwargs.update(kw) self.kw...
def add_params(self, **kw)
Add [possibly many] parameters to the Assembly. Parameters will be checked against known UCSC parameters and their supported formats.
2.838918
2.954912
0.960746
for a in args: self._orig_kwargs.pop(a) self.kwargs = self._orig_kwargs.copy()
def remove_params(self, *args)
Remove [possibly many] parameters from the Assembly. E.g., remove_params('color', 'visibility')
5.214046
8.07528
0.64568
if action == "post_remove": if not reverse: group = instance for person in model.objects.filter(pk__in=pk_set): _remove_group(group, person) else: person = instance for group in model.objects.filter(pk__in=pk_set): ...
def _members_changed( sender, instance, action, reverse, model, pk_set, **kwargs)
Hook that executes whenever the group members are changed.
2.404257
2.476063
0.971
# Check username looks ok if not username.islower(): raise UsernameInvalid(six.u('Username must be all lowercase')) if len(username) < 2: raise UsernameInvalid(six.u('Username must be at least 2 characters')) if not username_re.search(username): raise UsernameInvalid(setti...
def validate_username(username)
Validate the new username. If the username is invalid, raises :py:exc:`UsernameInvalid`. :param username: Username to validate.
4.153903
4.0955
1.01426
# is the username valid? validate_username(username) # Check for existing people count = Person.objects.filter(username__exact=username).count() if count >= 1: raise UsernameTaken(six.u( 'The username is already taken. Please choose another. ' 'If this was th...
def validate_username_for_new_person(username)
Validate the new username for a new person. If the username is invalid or in use, raises :py:exc:`UsernameInvalid` or :py:exc:`UsernameTaken`. :param username: Username to validate.
4.299368
4.257079
1.009934
# This is much the same as validate_username_for_new_person, except # we don't care if the username is used by the person owning the account # is the username valid? validate_username(username) # Check for existing people query = Person.objects.filter(username__exact=username) coun...
def validate_username_for_new_account(person, username)
Validate the new username for a new account. If the username is invalid or in use, raises :py:exc:`UsernameInvalid` or :py:exc:`UsernameTaken`. :param person: Owner of new account. :param username: Username to validate.
4.051078
4.070564
0.995213
query = Account.objects.filter( username__exact=username, date_deleted__isnull=True) if query.count() > 0: raise UsernameTaken( six.u('Username already in use.') ) if account_exists(username): raise UsernameTaken( six.u('Username is alr...
def check_username_for_new_account(person, username)
Check the new username for a new account. If the username is in use, raises :py:exc:`UsernameTaken`. :param person: Owner of new account. :param username: Username to validate.
5.012465
5.019757
0.998547
# is the username valid? validate_username(username) # Check for existing people count = Person.objects.filter(username__exact=username) \ .exclude(pk=person.pk).count() if count >= 1: raise UsernameTaken( six.u('The username is already taken by an existing perso...
def validate_username_for_rename_person(username, person)
Validate the new username to rename a person. If the username is invalid or in use, raises :py:exc:`UsernameInvalid` or :py:exc:`UsernameTaken`. :param username: Username to validate. :param person: We exclude this person when checking for duplicates.
4.174518
4.073938
1.024689
args = [] if label is not None: args.append(label) # don't use secret_token unless we have to if 'is_admin' in roles: # Administrators can access anything without secrets require_secret = False elif 'is_applicant' not in roles: # we never give secrets to anybody...
def get_url(request, application, roles, label=None)
Retrieve a link that will work for the current user.
5.541098
5.432573
1.019977
url = '%s/applications/%d/' % (settings.ADMIN_BASE_URL, application.pk) is_secret = False return url, is_secret
def get_admin_email_link(application)
Retrieve a link that can be emailed to the administrator.
5.623045
5.074729
1.108048
url = '%s/applications/%d/' % ( settings.REGISTRATION_BASE_URL, application.pk) is_secret = False return url, is_secret
def get_registration_email_link(application)
Retrieve a link that can be emailed to the logged other users.
6.046971
5.669547
1.06657
# don't use secret_token unless we have to if (application.content_type.model == 'person' and application.applicant.has_usable_password()): url = '%s/applications/%d/' % ( settings.REGISTRATION_BASE_URL, application.pk) is_secret = False else: url = '%s/a...
def get_email_link(application)
Retrieve a link that can be emailed to the applicant.
4.042095
3.948942
1.023589
# Get the authentication of the current user roles = self._get_roles_for_request(request, application) if extra_roles is not None: roles.update(extra_roles) # Ensure current user is authenticated. If user isn't applicant, # leader, delegate or admin, they pr...
def start(self, request, application, extra_roles=None)
Continue the state machine at first state.
5.585286
5.181215
1.077988
# Get the authentication of the current user roles = self._get_roles_for_request(request, application) if extra_roles is not None: roles.update(extra_roles) # Ensure current user is authenticated. If user isn't applicant, # leader, delegate or admin, they p...
def process( self, request, application, expected_state, label, extra_roles=None)
Process the view request at the current state.
4.778763
4.778389
1.000078
roles = application.get_roles_for_person(request.user) if common.is_admin(request): roles.add("is_admin") roles.add('is_authorised') return roles
def _get_roles_for_request(request, application)
Check the authentication of the current user.
6.434752
5.509366
1.167966
# we only support state changes for POST requests if request.method == "POST": key = None # If next state is a transition, process it while True: # We do not expect to get a direct state transition here. assert next_config['ty...
def _next(self, request, application, roles, next_config)
Continue the state machine at given state.
5.01686
4.99499
1.004378
# We only provide a view for when no label provided if label is not None: return HttpResponseBadRequest("<h1>Bad Request</h1>") # only certain actions make sense for default view actions = self.get_actions(request, application, roles) # process the request...
def get_next_action(self, request, application, label, roles)
Django view method. We provide a default detail view for applications.
4.642588
4.473961
1.037691
if not request.user.is_authenticated: raise PermissionDenied if not is_admin(request): raise PermissionDenied
def check_auth(self, request)
to ensure that nobody can get your data via json simply by knowing the URL. public facing forms should write a custom LookupChannel to implement as you wish. also you could choose to return HttpResponseForbidden("who are you?") instead of raising PermissionDenied (401 response)
3.938124
3.393795
1.160389
return Institute.objects.filter( Q(name__icontains=q) )
def get_query(self, q, request)
return a query set searching for the query string q either implement this method yourself or set the search_field in the LookupChannel class definition
7.137414
6.090198
1.171951
if not autocast: return self.buckets if self.kind in ["exponential", "linear", "enumerated", "boolean"]: return float(self.percentile(50)) if only_median else self.buckets elif self.kind == "categorical" and not only_median: return self.buckets ...
def get_value(self, only_median=False, autocast=True)
Returns a scalar for flag and count histograms. Otherwise it returns either the raw histogram represented as a pandas Series or just the median if only_median is True. If autocast is disabled the underlying pandas series is always returned as is.
4.318466
3.802747
1.135617