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(1))
act_col = dataframe.activityTimestamp
min_submission = datetime.strftime(min_activity_date, date_format)
max_submission_date = target_day_date + timedelta(future_days)
max_submission = datetime.strftime(max_submission_date, date_format)
sub_col = dataframe.submission_date_s3
filtered = filter_date_range(dataframe, act_col, min_activity, max_activity,
sub_col, min_submission, max_submission)
return count_distinct_clientids(filtered) | 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 None:
paths = ["{}/submission_date_s3={}/".format(base_path, s) for s in submission_date_s3]
return reader.parquet(*paths)
if submission_date_s3 is not None and sample_id is not None:
paths = []
for sd in submission_date_s3:
for si in sample_id:
paths.append("{}/submission_date_s3={}/sample_id={}/".format(
base_path, sd, si))
return reader.parquet(*paths)
if submission_date_s3 is None and sample_id is not None:
# Ugh, why? We would have to iterate the entire path to identify
# all the submission_date_s3 partitions, which may end up being
# slower.
data = reader.parquet(base_path)
sids = ["{}".format(s) for s in sample_id]
criteria = "sample_id IN ({})".format(",".join(sids))
return data.where(criteria)
# Neither partition is filtered.
return reader.parquet(base_path) | 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 the
`submission_date_s3` partition. Default is to read all
partitions. Each value should be in the form `YYYYMMDD`.
sample_id: Optional list of values to filter the `sample_id`
partition. Default is to read all partitions.
mergeSchema (bool): Determines whether or not to merge the
schemas of the resulting parquet files (ie. whether to
support schema evolution or not). Default is to merge
schemas.
path (str): Location (disk or S3) from which to read data.
Default is to read from the "production" location on S3.
Returns:
A DataFrame loaded from the specified partitions. | 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 should match the value previously
used, optionally plus multiples of 100.
Args:
dataframe: A Dataframe to be sampled
modulo (int): selects a 1/modulo sampling of dataframe
column (str): name of a string column to sample on
sample_id (int): modulus result to select for sampling
Returns:
A DataFrame sampled on the given inputs. | 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',
context={'content': 'Deleted'},
request=request)
if request.method == 'POST':
if 'task_id' in request.POST:
result = Task.AsyncResult(request.POST['task_id'])
if result.failed():
value = {
'info': {},
'ready': result.ready(),
}
else:
value = {
'info': result.info,
'ready': result.ready(),
}
return HttpResponse(
json.dumps(value), content_type="application/json")
return None | 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)
else:
task_id = cache.get(lock_id)
if not task_id:
return None
cache.set(lock_id, "")
result = Task.AsyncResult(task_id)
if result.ready():
result.forget()
return None
return result
return inner | 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_groups: number of partitions to split the data into.
:return: a list of lists, one for each partition. | 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:
if obj[0] > threshold:
heapq.heappush(groups, (obj[0], [obj[1]]))
else:
size, files = heapq.heappop(groups)
size += obj[0]
files.append(obj[1])
heapq.heappush(groups, (size, files))
groups = [group[1] for group in groups]
return groups | 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: number of partitions to split the data
:param threshold: the maximum size of each bucket
:return: a list of lists, one for each partition | 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 Exception('The property {} has already been selected'.format(prop_name))
new_selection = self.selection.copy()
new_selection.update(merged_properties)
return self._copy(selection=new_selection) | 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.
The JMESPath string will be used as a key in the output dictionary.
:param aliased_properties: Same as properties, but the output dictionary will contain
the parameter name instead of the JMESPath string. | 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 dimension {} doesn\'t exist'.format(dimension))
if isfunction(condition) or isinstance(condition, functools.partial):
clauses[dimension] = condition
else:
clauses[dimension] = functools.partial((lambda x, y: x == y), self._sanitize_dimension(str(condition)))
return self._copy(clauses=clauses) | 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 string, then sanitized. If `condition` is a callable, note that it will
be passed sanitized values -- i.e., characters outside [a-zA-Z0-9_.] are converted
to `_`. | 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 prefix directory)
clauses['prefix'] = lambda x: True
with futures.ThreadPoolExecutor(self.max_concurrency) as executor:
scanned = self._scan(schema, [self.prefix], clauses, executor)
keys = sc.parallelize(scanned).flatMap(self.store.list_keys)
return keys.take(limit) if limit else keys.collect() | 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 iterable of summaries | 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:
raise ValueError('sample must be between 0 and 1')
print(
"WARNING: THIS IS NOT A REPRESENTATIVE SAMPLE.\n"
"This 'sampling' is based on s3 files and is highly\n"
"susceptible to skew. Use only for quicker performance\n"
"while prototyping."
)
# We want this sample to be reproducible.
# See https://bugzilla.mozilla.org/show_bug.cgi?id=1318681
seed_state = random.getstate()
try:
random.seed(seed)
summaries = random.sample(summaries,
int(len(summaries) * sample))
finally:
random.setstate(seed_state)
# Obtain size in MB
total_size = functools.reduce(lambda acc, item: acc + item['size'], summaries, 0)
total_size_mb = total_size / float(1 << 20)
print("fetching %.5fMB in %s files..." % (total_size_mb, len(summaries)))
if group_by == 'equal_size':
groups = _group_by_equal_size(summaries, 10*sc.defaultParallelism)
elif group_by == 'greedy':
groups = _group_by_size_greedy(summaries, 10*sc.defaultParallelism)
else:
raise Exception("group_by specification is invalid")
self._compile_selection()
keys = (
sc.parallelize(groups, len(groups))
.flatMap(lambda x: x)
.map(lambda x: x['key'])
)
file_handles = keys.map(self.store.get_key)
# decode(fp: file-object) -> list[dict]
data = file_handles.flatMap(decode)
return data.map(self._apply_selection) | 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: percentage of results to return. Useful to return a sample
of the dataset. This parameter is ignored when `limit` is set.
:param seed: initialize internal state of the random number generator (42 by default).
This is used to make the dataset sampling reproducible. It can be set to None to obtain
different samples.
:param summaries: an iterable containing a summary for each item in the dataset. If None,
it will computed calling the summaries dataset.
:return: a Spark rdd containing the elements retrieved | 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(table_name)
return df | 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
:param sample: percentage of results to return. Useful to return a sample
of the dataset. This parameter is ignored when 'limit' is set.
:param seed: initialize internal state of the random number generator (42 by default).
This is used to make the dataset sampling reproducible. It an be set to None to obtain
different samples.
:param summaries: an iterable containing the summary for each item in the dataset. If None, it
will compute calling the summaries dataset.
:param schema: a Spark schema that overrides automatic conversion to a dataframe
:param table_name: allows resulting dataframe to easily be queried using SparkSQL
:return: a Spark DataFrame | 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))
schema = store.get_key('{}/schema.json'.format(source['metadata_prefix'])).read().decode('utf-8')
dimensions = [f['field_name'] for f in json.loads(schema)['dimensions']]
return Dataset(source['bucket'], dimensions, prefix=source['prefix']) | 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',
submissionDate='20160701',
appUpdateChannel='nightly'
) | 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
application.submit()
return 'success' | 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
approved_by = request.user
created_person, created_account = application.approve(approved_by)
# send email
application.extend()
link, is_secret = base.get_email_link(application)
emails.send_approved_email(
application, created_person, created_account, link, is_secret)
if created_person or created_account:
return 'password_needed'
else:
return 'password_ok' | 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_email_subject.txt', context)
body = render_to_string(
'karaage/people/emails/bounced_email_body.txt', context)
send_mail(
subject.replace('\n', ''), body,
settings.ACCOUNTS_EMAIL, [to_email])
log.change(
leader,
'Sent email about bounced emails from %s' % person) | 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': person,
})
to_email = person.email
subject, body = render_email('reset_password', context)
send_mail(subject, body, settings.ACCOUNTS_EMAIL, [to_email]) | 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, body, settings.ACCOUNTS_EMAIL, [to_email]) | 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, is_secret) | 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)
if request.method == 'POST':
if 'back' in request.POST:
url = base.get_url(request, application, roles)
return HttpResponseRedirect(url)
if 'approve' in request.POST and form.is_valid():
form.save()
return "approve"
return render(
template_name=self.template_approve,
context={
'application': application,
'form': form,
'authorised_text': self.authorised_text,
'actions': self.get_actions(request, application, roles),
'roles': roles
},
request=request)
elif label == "cancel" and 'cancel' in actions:
if request.method == 'POST':
form = EmailForm(request.POST)
if 'back' in request.POST:
url = base.get_url(request, application, roles)
return HttpResponseRedirect(url)
if 'cancel' in request.POST and form.is_valid():
to_email = application.applicant.email
subject, body = form.get_data()
emails.send_mail(
subject, body,
settings.ACCOUNTS_EMAIL, [to_email])
return "cancel"
else:
link, is_secret = base.get_email_link(application)
subject, body = emails.render_email(
'common_declined',
{'receiver': application.applicant,
'authorised_text': self.authorised_text,
'application': application,
'link': link, 'is_secret': is_secret})
initial_data = {'body': body, 'subject': subject}
form = EmailForm(initial=initial_data)
return render(
template_name=self.template_decline,
context={
'application': application,
'form': form,
'authorised_text': self.authorised_text,
'actions': self.get_actions(request, application, roles),
'roles': roles
},
request=request)
elif request.method == "POST":
for action in ['approve', 'cancel']:
if action in request.POST:
url = base.get_url(request, application, roles, action)
return HttpResponseRedirect(url)
# Not parent class method will do the same thing, however this makes it
# explicit.
if label is not None:
return HttpResponseBadRequest("<h1>Bad Request</h1>")
self.context = {
'authorised_text': self.authorised_text,
}
return super(StateWaitingForApproval, self).get_next_action(
request, application, label, roles) | 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(
data=request.POST or None, person=application.applicant)
form_type = "verify"
else:
form = forms.PersonSetPassword(
data=request.POST or None, person=application.applicant)
form_type = "set"
if request.method == 'POST':
if 'cancel' in request.POST:
return 'cancel'
if form.is_valid():
form.save()
messages.success(
request, 'Password updated. New accounts activated.')
for action in actions:
if action in request.POST:
return action
return HttpResponseBadRequest("<h1>Bad Request</h1>")
return render(
template_name='kgapplications/common_password.html',
context={
'application': application,
'form': form,
'actions': actions,
'roles': roles,
'type': form_type
},
request=request)
return super(StatePassword, self).get_next_action(request, application, label, roles) | 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:
return action
return render(
template_name='kgapplications/common_declined.html',
context={
'application': application,
'actions': actions,
'roles': roles
},
request=request)
return super(StateDeclined, self).get_next_action(
request, application, label, roles) | 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 supplied?
if label is None:
# no label given, find first step and redirect to it.
this_id = self._order[0]
url = base.get_url(request, application, roles, this_id)
return HttpResponseRedirect(url)
else:
# label was given, get the step position and id for it
this_id = label
if this_id not in self._steps:
return HttpResponseBadRequest("<h1>Bad Request</h1>")
position = self._order.index(this_id)
# get the step given the label
this_step = self._steps[this_id]
# define list of allowed actions for step
step_actions = {}
if 'cancel' in actions:
step_actions['cancel'] = "state:cancel"
if 'submit' in actions and position == len(self._order) - 1:
step_actions['submit'] = "state:submit"
if position > 0:
step_actions['prev'] = self._order[position - 1]
if position < len(self._order) - 1:
step_actions['next'] = self._order[position + 1]
# process the request
if request.method == "GET":
# if GET request, state changes are not allowed
response = this_step.view(
request, application, this_id, roles, step_actions.keys())
assert isinstance(response, HttpResponse)
return response
elif request.method == "POST":
# if POST request, state changes are allowed
response = this_step.view(
request, application, this_id, roles, step_actions.keys())
assert response is not None
# If it was a HttpResponse, just return it
if isinstance(response, HttpResponse):
return response
else:
# try to lookup the response
if response not in step_actions:
raise RuntimeError(
"Invalid response '%s' from step '%s'"
% (response, this_step))
action = step_actions[response]
# process the required action
if action.startswith("state:"):
return action[6:]
else:
url = base.get_url(request, application, roles, action)
return HttpResponseRedirect(url)
# Something went wrong.
return HttpResponseBadRequest("<h1>Bad Request</h1>") | 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.get_email_link(application)
return render(
template_name='kgapplications/software_introduction.html',
context={
'actions': actions,
'application': application,
'roles': roles,
'link': link,
'is_secret': is_secret
},
request=request)
return super(StateIntroduction, self).get_next_action(
request, application, label, roles) | 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:
warnings.warn(
"MACHINE_CATEGORY_DATASTORES is deprecated, "
"please change to use DATASTORES",
)
for name in ['ldap']:
array = settings.MACHINE_CATEGORY_DATASTORES.get(name, [])
for config in array:
cls = _lookup(config['ENGINE'])
ds = _get_datastore(cls, DataStore, config)
_DATASTORES.append(ds) | 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:
return 'prev'
# test for conditions where shibboleth registration not required
if applicant.saml_id is not None:
status = "You have already registered a shibboleth id."
form = None
done = True
elif application.content_type.model != 'applicant':
status = "You are already registered in the system."
form = None
done = True
elif (applicant.institute is not None
and applicant.institute.saml_entityid is None):
status = "Your institute does not have shibboleth registered."
form = None
done = True
elif Institute.objects.filter(
saml_entityid__isnull=False).count() == 0:
status = "No institutes support shibboleth here."
form = None
done = True
else:
# shibboleth registration is required
# Do construct the form
form = saml.SAMLInstituteForm(
request.POST or None,
initial={'institute': applicant.institute})
done = False
status = None
# Was it a POST request?
if request.method == 'POST':
# Did the login form get posted?
if 'login' in request.POST and form.is_valid():
institute = form.cleaned_data['institute']
applicant.institute = institute
applicant.save()
# We do not set application.insitute here, that happens
# when application, if it is a ProjectApplication, is
# submitted
# if institute supports shibboleth, redirect back here via
# shibboleth, otherwise redirect directly back he.
url = base.get_url(request, application, roles, label)
if institute.saml_entityid is not None:
url = saml.build_shib_url(
request, url, institute.saml_entityid)
return HttpResponseRedirect(url)
# Did we get a logout request?
elif 'logout' in request.POST:
if saml_session:
url = saml.logout_url(request)
return HttpResponseRedirect(url)
else:
return HttpResponseBadRequest("<h1>Bad Request</h1>")
# did we get a shib session yet?
if saml_session:
attrs, _ = saml.parse_attributes(request)
saml_session = True
# if we are done, we can proceed to next state
if request.method == 'POST':
if 'cancel' in request.POST:
return "cancel"
if 'prev' in request.POST:
return 'prev'
if not done:
if saml_session:
applicant = _get_applicant_from_saml(request)
if applicant is not None:
application.applicant = applicant
application.save()
else:
applicant = application.applicant
applicant = saml.add_saml_data(
applicant, request)
applicant.save()
done = True
else:
status = "Please login to SAML before proceeding."
if request.method == 'POST' and done:
for action in actions:
if action in request.POST:
return action
return HttpResponseBadRequest("<h1>Bad Request</h1>")
# render the page
return render(
template_name='kgapplications/project_aed_shibboleth.html',
context={
'form': form,
'done': done,
'status': status,
'actions': actions,
'roles': roles,
'application': application,
'attrs': attrs,
'saml_session': saml_session,
},
request=request) | 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 not None:
form = forms.SAMLApplicantForm(
request.POST or None,
instance=application.applicant)
else:
form = forms.UserApplicantForm(
request.POST or None,
instance=application.applicant)
# Process the form, if there is one
if form is not None and request.method == 'POST':
if form.is_valid():
form.save(commit=True)
for action in actions:
if action in request.POST:
return action
return HttpResponseBadRequest("<h1>Bad Request</h1>")
else:
# if form didn't validate and we want to go back or cancel,
# then just do it.
if 'cancel' in request.POST:
return "cancel"
if 'prev' in request.POST:
return 'prev'
# If we don't have a form, we can just process the actions here
if form is None:
for action in actions:
if action in request.POST:
return action
# Render the response
return render(
template_name='kgapplications/project_aed_applicant.html',
context={
'form': form,
'application': application,
'status': status, 'actions': actions, 'roles': roles,
},
request=request) | 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.NewProjectApplicationForm,
'existing': forms.ExistingProjectApplicationForm,
}
project_forms = {}
for key, form in six.iteritems(form_models):
project_forms[key] = form(
request.POST or None, instance=application)
if application.project is not None:
project_forms["common"].initial = {'application_type': 'U'}
elif application.name != "":
project_forms["common"].initial = {'application_type': 'P'}
if 'application_type' in request.POST:
at = request.POST['application_type']
valid = True
if at == 'U':
# existing project
if project_forms['common'].is_valid():
project_forms['common'].save(commit=False)
else:
valid = False
if project_forms['existing'].is_valid():
project_forms['existing'].save(commit=False)
else:
valid = False
elif at == 'P':
# new project
if project_forms['common'].is_valid():
project_forms['common'].save(commit=False)
else:
valid = False
if project_forms['new'].is_valid():
project_forms['new'].save(commit=False)
else:
valid = False
application.institute = application.applicant.institute
else:
return HttpResponseBadRequest("<h1>Bad Request</h1>")
# reset hidden forms
if at != 'U':
# existing project form was not displayed
project_forms["existing"] = (
form_models["existing"](instance=application))
application.project = None
if at != 'P':
# new project form was not displayed
project_forms["new"] = form_models["new"](instance=application)
application.name = ""
application.institute = None
application.description = None
application.additional_req = None
application.machine_categories = []
application.pid = None
# save the values
application.save()
if project_forms['new'].is_valid() and at == 'P':
project_forms["new"].save_m2m()
# we still need to process cancel and prev even if form were
# invalid
if 'cancel' in request.POST:
return "cancel"
if 'prev' in request.POST:
return 'prev'
# if forms were valid, jump to next state
if valid:
for action in actions:
if action in request.POST:
return action
return HttpResponseBadRequest("<h1>Bad Request</h1>")
else:
# we still need to process cancel, prev even if application type
# not given
if 'cancel' in request.POST:
return "cancel"
if 'prev' in request.POST:
return 'prev'
# lookup the project based on the form data
project_id = project_forms['existing']['project'].value()
project = None
if project_id:
try:
project = Project.objects.get(pk=project_id)
except Project.DoesNotExist:
pass
# render the response
return render(
template_name='kgapplications/project_aed_project.html',
context={
'forms': project_forms,
'project': project,
'actions': actions,
'roles': roles,
'application': application,
},
request=request) | 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:
return action
link, is_secret = base.get_email_link(application)
return render(
template_name='kgapplications/project_aed_introduction.html',
context={
'actions': actions,
'application': application, 'roles': roles,
'link': link, 'is_secret': is_secret,
},
request=request) | 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 = None
details = None
attrs, _ = saml.parse_attributes(request)
saml_id = attrs['persistent_id']
if saml_id is not None:
query = Person.objects.filter(saml_id=saml_id)
if application.content_type.model == "person":
query = query.exclude(pk=application.applicant.pk)
if query.count() > 0:
new_person = Person.objects.get(saml_id=saml_id)
reason = "SAML id is already in use by existing person."
details = (
"It is not possible to continue this application "
+ "as is because the saml identity already exists "
+ "as a registered user.")
del query
if request.user.is_authenticated:
new_person = request.user
reason = "%s was logged in " \
"and accessed the secret URL." % new_person
details = (
"If you want to access this application "
+ "as %s " % application.applicant
+ "without %s stealing it, " % new_person
+ "you will have to ensure %s is " % new_person
+ "logged out first.")
if new_person is not None:
if application.applicant != new_person:
if 'steal' in request.POST:
old_applicant = application.applicant
application.applicant = new_person
application.save()
log.change(
application.application_ptr,
"Stolen application from %s" % old_applicant)
messages.success(
request,
"Stolen application from %s" % old_applicant)
url = base.get_url(request, application, roles, label)
return HttpResponseRedirect(url)
else:
return render(
template_name='kgapplications'
'/project_aed_steal.html',
context={
'application': application,
'person': new_person,
'reason': reason,
'details': details,
},
request=request)
# if the user is the leader, show him the leader specific page.
if ('is_leader' in roles or 'is_delegate' in roles) \
and 'is_admin' not in roles \
and 'is_applicant' not in roles:
actions = ['reopen']
if 'reopen' in request.POST:
return 'reopen'
return render(
template_name='kgapplications/project_aed_for_leader.html',
context={'application': application,
'actions': actions, 'roles': roles, },
request=request)
# otherwise do the default behaviour for StateWithSteps
return super(StateApplicantEnteringDetails, self) \
.get_next_action(request, application, label, roles) | 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()
# hack because MAM doesn't quote sql correctly
value = value.replace("\\", "")
# Used for stripping non-ascii characters
value = ''.join(c for c in value if 31 < ord(c) < 127)
return value | 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_errors:
logger.debug(
"<-- Cmd %s returned %d (ignored)" % (command, retcode))
return
if retcode:
logger.error(
"<-- Cmd %s returned: %d (error)" % (command, retcode))
raise subprocess.CalledProcessError(retcode, command)
logger.debug("<-- Returned %d (good)" % retcode)
return | 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(
"Command returned multiple results for '%s'." % username)
the_result = results[0]
the_name = the_result["Name"]
if username.lower() != the_name.lower():
logger.error(
"We expected username '%s' but got username '%s'."
% (username, the_name))
raise RuntimeError(
"We expected username '%s' but got username '%s'."
% (username, the_name))
return the_result | 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 ds_project["Users"] != "":
user_list = ds_project["Users"].lower().split(",")
return user_list | 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(username)
if account.date_deleted is None:
# date_deleted is not set, user should exist
logger.debug("account is active")
if ds_user is None:
# create user if doesn't exist
self._create_user(username, default_project_name)
else:
# or just set default project
self._set_user_default_project(username, default_project_name)
# update user meta information
self._call([
"gchuser",
"-n", self._filter_string(account.person.get_full_name()),
"-u", username])
self._call([
"gchuser",
"-E", self._filter_string(account.person.email),
"-u", username])
# add rest of projects user belongs to
mam_projects = self.get_projects_in_user(username)
for project in account.person.projects.all():
if project.pid not in mam_projects:
self.add_account_to_project(account, project)
else:
# date_deleted is not set, user should not exist
logger.debug("account is not active")
if ds_user is not None:
# delete MAM user if account marked as deleted
self._call(["grmuser", "-u", username], ignore_errors=[8])
return | 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(pid)
# update project meta information
name = self._truncate(project.name, 40)
self._set_project(pid, name, project.institute)
else:
# project is deleted
logger.debug("project is not active")
ds_project = self.get_project(pid)
if ds_project is not None:
self._delete_project(pid)
return | 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(
["goldsh", "Organization", "Create", "Name=%s" % name],
ignore_errors=[185])
else:
# date_deleted is not set, user should not exist
logger.debug("institute is not active")
# delete MAM organisation if institute marked as deleted
self._call(["goldsh", "Organization", "Delete", "Name==%s" % name])
logger.debug("returning")
return | 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])
show(fig) | 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 = TrackDb()
hub.add_genomes_file(genomes_file)
genomes_file.add_genome(genome)
genome.add_trackdb(trackdb)
return hub, genomes_file, genome, 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, defaults to the value of `hub_name`
long_label : str
Long label for the hub. If None, defaults to the value of `short_label`. | 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
# the parsed histograms is stable, which makes the insertion into
# all_histograms stable, which makes ordering in generated files
# stable, which makes builds more deterministic.
if not isinstance(histograms, OrderedDict):
raise ParserError("Histogram parser did not provide an OrderedDict.")
for name, definition in iteritems(histograms):
if name in all_histograms:
raise ParserError('Duplicate histogram name "%s".' % name)
all_histograms[name] = definition
# We require that all USE_COUNTER2_* histograms be defined in a contiguous
# block.
use_counter_indices = filter(lambda x: x[1].startswith("USE_COUNTER2_"),
enumerate(iterkeys(all_histograms)))
if use_counter_indices:
lower_bound = use_counter_indices[0][0]
upper_bound = use_counter_indices[-1][0]
n_counters = upper_bound - lower_bound + 1
if n_counters != len(use_counter_indices):
raise ParserError("Use counter histograms must be defined in a contiguous block.")
# Check that histograms that were removed from Histograms.json etc.
# are also removed from the whitelists.
if whitelists is not None:
all_whitelist_entries = itertools.chain.from_iterable(whitelists.itervalues())
orphaned = set(all_whitelist_entries) - set(iterkeys(all_histograms))
if len(orphaned) > 0:
msg = 'The following entries are orphaned and should be removed from ' \
'histogram-whitelists.json:\n%s'
raise ParserError(msg % (', '.join(sorted(orphaned))))
for name, definition in iteritems(all_histograms):
yield Histogram(name, definition, strict_type_checks=strict_type_checks) | 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,
}
if self._kind not in bucket_fns:
raise ParserError('Unknown kind "%s" for histogram "%s".' % (self._kind, self._name))
fn = bucket_fns[self._kind]
return fn(self.low(), self.high(), self.n_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(number) == 2:
number = '00' + number
elif len(number) == 3:
number = '0' + number
except Project.DoesNotExist:
found = False
return prefix + number | 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.
class Meta:
model = tmp_model
class_name = model.__name__ + 'Form'
form_class = ModelFormMetaclass(
class_name, (ModelForm,), {'Meta': Meta})
return model, form_class
raise GenericViewError("Generic view must be called with either a model or"
" form_class argument.") | 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 ``ModelForm`` class created from
``model``. | 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_redirect"
" parameter to the generic view or define a get_absolute_url"
" method on the Model.") | 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 ``get_absolute_url`` method,
then raise ImproperlyConfigured.
This function is meant to handle the post_save_redirect parameter to the
``create_object`` and ``update_object`` views. | 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"
" slug/slug_field.")
try:
return model.objects.get(**lookup_kwargs)
except ObjectDoesNotExist:
raise Http404("No %s found for %s"
% (model._meta.verbose_name, lookup_kwargs)) | 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.FILES)
if form.is_valid():
new_object = form.save()
msg = ugettext("The %(verbose_name)s was created successfully.") %\
{"verbose_name": model._meta.verbose_name}
messages.success(request, msg, fail_silently=True)
return redirect(post_save_redirect, new_object)
else:
form = form_class()
# Create the template, context, response
if not template_name:
template_name = "%s/%s_form.html" % (
model._meta.app_label, model._meta.object_name.lower())
t = template_loader.get_template(template_name)
c = {
'form': form,
}
apply_extra_context(extra_context, c)
return HttpResponse(t.render(context=c, request=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.method == 'POST':
form = form_class(request.POST, request.FILES, instance=obj)
if form.is_valid():
obj = form.save()
msg = ugettext("The %(verbose_name)s was updated successfully.") %\
{"verbose_name": model._meta.verbose_name}
messages.success(request, msg, fail_silently=True)
return redirect(post_save_redirect, obj)
else:
form = form_class(instance=obj)
if not template_name:
template_name = "%s/%s_form.html" % (
model._meta.app_label, model._meta.object_name.lower())
t = template_loader.get_template(template_name)
c = {
'form': form,
template_object_name: obj,
}
apply_extra_context(extra_context, c)
response = HttpResponse(t.render(context=c, request=request))
return response | 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 %(verbose_name)s was deleted.") %\
{"verbose_name": model._meta.verbose_name}
messages.success(request, msg, fail_silently=True)
return HttpResponseRedirect(post_delete_redirect)
else:
if not template_name:
template_name = "%s/%s_confirm_delete.html" % (
model._meta.app_label, model._meta.object_name.lower())
t = template_loader.get_template(template_name)
c = {
template_object_name: obj,
}
apply_extra_context(extra_context, c)
response = HttpResponse(t.render(context=c, request=request))
return response | 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 object being deleted | 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.kwargs = self._orig_kwargs.copy() | 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):
_remove_group(group, person)
elif action == "pre_clear":
# This has to occur in pre_clear, not post_clear, as otherwise
# we won't see what groups need to be removed.
if not reverse:
group = instance
for person in group.members.all():
_remove_group(group, person)
else:
person = instance
for group in person.groups.all():
_remove_group(group, person) | 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(settings.USERNAME_VALIDATION_ERROR_MSG)
return username | 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 the name of your old account please email %s')
% settings.ACCOUNTS_EMAIL)
# Check for existing accounts
count = Account.objects.filter(username__exact=username).count()
if count >= 1:
raise UsernameTaken(six.u(
'The username is already taken. Please choose another. '
'If this was the name of your old account please email %s')
% settings.ACCOUNTS_EMAIL)
# Check account datastore, in case username created outside Karaage.
if account_exists(username):
raise UsernameTaken(
six.u('Username is already in external account datastore.'))
return username | 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)
count = query.exclude(pk=person.pk).count()
if count >= 1:
raise UsernameTaken(six.u(
'The username is already taken. Please choose another. '
'If this was the name of your old account please email %s')
% settings.ACCOUNTS_EMAIL)
# Check for existing accounts not belonging to this person
query = Account.objects.filter(username__exact=username)
count = query.exclude(person__pk=person.pk).count()
if count >= 1:
raise UsernameTaken(six.u(
'The username is already taken. Please choose another. '
'If this was the name of your old account please email %s')
% settings.ACCOUNTS_EMAIL)
# Check datastore, in case username created outside Karaage.
# Make sure we don't count the entry for person.
query = Person.objects.filter(username__exact=username)
count = query.filter(pk=person.pk).count()
if count == 0 and account_exists(username):
raise UsernameTaken(
six.u('Username is already in external personal datastore.')) | 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 already in datastore.')
)
return username | 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 person.'))
# Check for existing accounts not owned by person.
# If there is a conflicting account owned by person it doesn't matter.
count = Account.objects.filter(username__exact=username) \
.exclude(person=person).count()
if count >= 1:
raise UsernameTaken(
six.u('The username is already taken by an existing account.'))
# Check datastore, in case username created outside Karaage.
count = Account.objects.filter(
username__exact=username,
person=person,
date_deleted__isnull=True).count()
if count == 0 and account_exists(username):
raise UsernameTaken(
six.u('Username is already in external account datastore.')) | 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 but the applicant
require_secret = False
elif not request.user.is_authenticated:
# If applicant is not logged in, we redirect them to secret URL
require_secret = True
elif request.user != application.applicant:
# If logged in as different person, we redirect them to secret
# URL. This could happen if the application was open with a different
# email address, and the applicant is logged in when accessing it.
require_secret = True
else:
# otherwise redirect them to URL that requires correct login.
require_secret = False
# return required url
if not require_secret:
url = reverse(
'kg_application_detail',
args=[application.pk, application.state] + args)
else:
url = reverse(
'kg_application_unauthenticated',
args=[application.secret_token, application.state] + args)
return url | 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/applications/%s/' % (
settings.REGISTRATION_BASE_URL, application.secret_token)
is_secret = True
return url, is_secret | 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 probably shouldn't be here.
if 'is_authorised' not in roles:
return HttpResponseForbidden('<h1>Access Denied</h1>')
# Go to first state.
return self._next(request, application, roles, self._first_state) | 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 probably shouldn't be here.
if 'is_authorised' not in roles:
return HttpResponseForbidden('<h1>Access Denied</h1>')
# If user didn't supply state on URL, redirect to full URL.
if expected_state is None:
url = get_url(request, application, roles, label)
return HttpResponseRedirect(url)
# Check that the current state is valid.
if application.state not in self._config:
raise RuntimeError("Invalid current state '%s'" % application.state)
# If state user expected is different to state we are in, warn user
# and jump to expected state.
if expected_state != application.state:
# post data will be lost
if request.method == "POST":
messages.warning(
request,
"Discarding request and jumping to current state.")
# note we discard the label, it probably isn't relevant for new
# state
url = get_url(request, application, roles)
return HttpResponseRedirect(url)
# Get the current state for this application
state_config = self._config[application.state]
# Finally do something
instance = load_state_instance(state_config)
if request.method == "GET":
# if method is GET, state does not ever change.
response = instance.get_next_config(request, application, label, roles)
assert isinstance(response, HttpResponse)
return response
elif request.method == "POST":
# if method is POST, it can return a HttpResponse or a string
response = instance.get_next_config(request, application, label, roles)
if isinstance(response, HttpResponse):
# If it returned a HttpResponse, state not changed, just
# display
return response
else:
# If it returned a string, lookit up in the actions for this
# state
next_config = response
# Go to the next state
return self._next(request, application, roles, next_config)
else:
# Shouldn't happen, user did something weird
return HttpResponseBadRequest("<h1>Bad Request</h1>") | 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['type'] in ['goto', 'transition']
while next_config['type'] == 'goto':
key = next_config['key']
next_config = self._config[key]
instance = load_instance(next_config)
if not isinstance(instance, Transition):
break
next_config = instance.get_next_config(request, application, roles)
# lookup next state
assert key is not None
state_key = key
# enter that state
instance.enter_state(request, application)
application.state = state_key
application.save()
# log details
log.change(application.application_ptr, "state: %s" % instance.name)
# redirect to this new state
url = get_url(request, application, roles)
return HttpResponseRedirect(url)
else:
return HttpResponseBadRequest("<h1>Bad Request</h1>") | 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 in default view
if request.method == "GET":
context = self.context
context.update({
'application': application,
'actions': actions,
'state': self.name,
'roles': roles})
return render(
template_name='kgapplications/common_detail.html',
context=context,
request=request)
elif request.method == "POST":
for action in actions:
if action in request.POST:
return action
# we don't know how to handle this request.
return HttpResponseBadRequest("<h1>Bad Request</h1>") | 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
elif self.kind == "count":
return int(self.buckets[0])
elif self.kind == "flag":
return self.buckets[1] == 1
else:
assert(False) | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.