_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q16700 | PayuManifest.make_link | train | def make_link(self, filepath):
"""
Payu integration function for creating symlinks in work directories
which point back to the original file.
"""
# Check file exists. It may have been deleted but still in manifest
if not os.path.exists(self.fullpath(filepath)):
... | python | {
"resource": ""
} |
q16701 | Manifest.add_filepath | train | def add_filepath(self, manifest, filepath, fullpath, copy=False):
"""
Wrapper to the add_filepath function in PayuManifest. Prevents outside
code from directly calling anything in PayuManifest.
"""
filepath = os.path.normpath(filepath)
if self.manifests[manifest].add_file... | python | {
"resource": ""
} |
q16702 | commit_hash | train | def commit_hash(dir='.'):
"""
Return commit hash for HEAD of checked out branch of the
specified directory.
"""
cmd = ['git', 'rev-parse', 'HEAD']
try:
with open(os.devnull, 'w') as devnull:
revision_hash = subprocess.check_output(
cmd,
cwd=d... | python | {
"resource": ""
} |
q16703 | Runlog.create_manifest | train | def create_manifest(self):
"""Construct the list of files to be tracked by the runlog."""
config_path = os.path.join(self.expt.control_path,
DEFAULT_CONFIG_FNAME)
self.manifest = []
if os.path.isfile(config_path):
self.manifest.append(conf... | python | {
"resource": ""
} |
q16704 | Runlog.push | train | def push(self):
"""Push the changes to the remote repository.
Usage: payu push
This command pushes local runlog changes to the remote runlog
repository, currently named `payu`, using the SSH key associated with
this experiment.
For an experiment `test`, it is equivalen... | python | {
"resource": ""
} |
q16705 | add_expiration_postfix | train | def add_expiration_postfix(expiration):
""" Formats the expiration version and adds a version postfix if needed.
:param expiration: the expiration version string.
:return: the modified expiration string.
"""
if re.match(r'^[1-9][0-9]*$', expiration):
return expiration + ".0a1"
if re.ma... | python | {
"resource": ""
} |
q16706 | load_yaml_file | train | def load_yaml_file(filename):
""" Load a YAML file from disk, throw a ParserError on failure."""
try:
with open(filename, 'r') as f:
return yaml.safe_load(f)
except IOError as e:
raise ParserError('Error opening ' + filename + ': ' + e.message)
except ValueError as e:
... | python | {
"resource": ""
} |
q16707 | StringTable.writeDefinition | train | def writeDefinition(self, f, name):
"""Writes the string table to a file as a C const char array.
This writes out the string table as one single C char array for memory
size reasons, separating the individual strings with '\0' characters.
This way we can index directly into the string a... | python | {
"resource": ""
} |
q16708 | comments | train | def comments(context, obj):
""" Render comments for obj. """
content_type = ContentType.objects.get_for_model(obj.__class__)
comment_list = LogEntry.objects.filter(
content_type=content_type,
object_id=obj.pk,
action_flag=COMMENT
)
return {
'obj': obj,
'commen... | python | {
"resource": ""
} |
q16709 | get_disk_quota | train | def get_disk_quota(username, machine_name=None):
"""
Returns disk quota for username in KB
"""
try:
ua = Account.objects.get(
username=username,
date_deleted__isnull=True)
except Account.DoesNotExist:
return 'Account not found'
result = ua.get_disk_quota... | python | {
"resource": ""
} |
q16710 | snap_to_beginning_of_week | train | 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.
"""
... | python | {
"resource": ""
} |
q16711 | get_last_week_range | train | 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... | python | {
"resource": ""
} |
q16712 | get_last_month_range | train | 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.
"""
today = date.today()
# Get the last day for the previous month.
... | python | {
"resource": ""
} |
q16713 | read_main_summary | train | 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, optional... | python | {
"resource": ""
} |
q16714 | sampler | train | 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 mu... | python | {
"resource": ""
} |
q16715 | progress | train | def progress(request):
""" Check status of task. """
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(
... | python | {
"resource": ""
} |
q16716 | synchronise | train | def synchronise(func):
""" If task already queued, running, or finished, don't restart. """
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):
... | python | {
"resource": ""
} |
q16717 | _group_by_size_greedy | train | 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... | python | {
"resource": ""
} |
q16718 | _group_by_equal_size | train | 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_lis... | python | {
"resource": ""
} |
q16719 | Dataset.select | train | 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: JME... | python | {
"resource": ""
} |
q16720 | Dataset.where | train | 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 va... | python | {
"resource": ""
} |
q16721 | Dataset.summaries | train | 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 numb... | python | {
"resource": ""
} |
q16722 | Dataset.records | train | 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 retriev... | python | {
"resource": ""
} |
q16723 | Dataset.dataframe | train | 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 obje... | python | {
"resource": ""
} |
q16724 | Dataset.from_source | train | 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')... | python | {
"resource": ""
} |
q16725 | send_bounced_warning | train | def send_bounced_warning(person, leader_list):
"""Sends an email to each project leader for person
informing them that person's email has bounced"""
context = CONTEXT.copy()
context['person'] = person
for lp in leader_list:
leader = lp['leader']
context['project'] = lp['project']
... | python | {
"resource": ""
} |
q16726 | send_reset_password_email | train | def send_reset_password_email(person):
"""Sends an email to user allowing them to set their password."""
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,... | python | {
"resource": ""
} |
q16727 | send_confirm_password_email | train | def send_confirm_password_email(person):
"""Sends an email to user allowing them to confirm their password."""
url = '%s/profile/login/%s/' % (
settings.REGISTRATION_BASE_URL, person.username)
context = CONTEXT.copy()
context.update({
'url': url,
'receiver': person,
})
... | python | {
"resource": ""
} |
q16728 | StateWaitingForApproval.check_can_approve | train | def check_can_approve(self, request, application, roles):
""" Check the person's authorization. """
try:
authorised_persons = self.get_authorised_persons(application)
authorised_persons.get(pk=request.user.pk)
return True
except Person.DoesNotExist:
... | python | {
"resource": ""
} |
q16729 | StateWaitingForApproval.enter_state | train | def enter_state(self, request, application):
""" This is becoming the new current state. """
authorised_persons = self.get_email_persons(application)
link, is_secret = self.get_request_email_link(application)
emails.send_request_email(
self.authorised_text,
self.a... | python | {
"resource": ""
} |
q16730 | StateWithSteps.add_step | train | def add_step(self, step, step_id):
""" Add a step to the list. The first step added becomes the initial
step. """
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... | python | {
"resource": ""
} |
q16731 | _init_datastores | train | def _init_datastores():
""" Initialize all datastores. """
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_CATEG... | python | {
"resource": ""
} |
q16732 | get_group_details | train | def get_group_details(group):
""" Get group details. """
result = []
for datastore in _get_datastores():
value = datastore.get_group_details(group)
value['datastore'] = datastore.config['DESCRIPTION']
result.append(value)
return result | python | {
"resource": ""
} |
q16733 | set_project_pid | train | def set_project_pid(project, old_pid, new_pid):
""" Project's PID was changed. """
for datastore in _get_datastores():
datastore.save_project(project)
datastore.set_project_pid(project, old_pid, new_pid) | python | {
"resource": ""
} |
q16734 | add_accounts_to_group | train | def add_accounts_to_group(accounts_query, group):
""" Add accounts to group. """
query = accounts_query.filter(date_deleted__isnull=True)
for account in query:
add_account_to_group(account, group) | python | {
"resource": ""
} |
q16735 | remove_accounts_from_group | train | def remove_accounts_from_group(accounts_query, group):
""" Remove accounts from group. """
query = accounts_query.filter(date_deleted__isnull=True)
for account in query:
remove_account_from_group(account, group) | python | {
"resource": ""
} |
q16736 | add_accounts_to_project | train | def add_accounts_to_project(accounts_query, project):
""" Add accounts to project. """
query = accounts_query.filter(date_deleted__isnull=True)
for account in query:
add_account_to_project(account, project) | python | {
"resource": ""
} |
q16737 | remove_accounts_from_project | train | def remove_accounts_from_project(accounts_query, project):
""" Remove accounts from project. """
query = accounts_query.filter(date_deleted__isnull=True)
for account in query:
remove_account_from_project(account, project) | python | {
"resource": ""
} |
q16738 | add_accounts_to_institute | train | def add_accounts_to_institute(accounts_query, institute):
""" Add accounts to institute. """
query = accounts_query.filter(date_deleted__isnull=True)
for account in query:
add_account_to_institute(account, institute) | python | {
"resource": ""
} |
q16739 | remove_accounts_from_institute | train | def remove_accounts_from_institute(accounts_query, institute):
""" Remove accounts from institute. """
query = accounts_query.filter(date_deleted__isnull=True)
for account in query:
remove_account_from_institute(account, institute) | python | {
"resource": ""
} |
q16740 | MamDataStoreBase._filter_string | train | def _filter_string(value):
""" Filter the string so MAM doesn't have heart failure."""
if value is None:
value = ""
# replace whitespace with space
value = value.replace("\n", " ")
value = value.replace("\t", " ")
# CSV seperator
value = value.replac... | python | {
"resource": ""
} |
q16741 | MamDataStoreBase.get_user | train | def get_user(self, username):
""" Get the user details from MAM. """
cmd = ["glsuser", "-u", username, "--raw"]
results = self._read_output(cmd)
if len(results) == 0:
return None
elif len(results) > 1:
logger.error(
"Command returned multi... | python | {
"resource": ""
} |
q16742 | MamDataStoreBase.get_user_balance | train | def get_user_balance(self, username):
""" Get the user balance details from MAM. """
cmd = ["gbalance", "-u", username, "--raw"]
results = self._read_output(cmd)
if len(results) == 0:
return None
return results | python | {
"resource": ""
} |
q16743 | MamDataStoreBase.get_users_in_project | train | def get_users_in_project(self, projectname):
""" Get list of users in project from MAM. """
ds_project = self.get_project(projectname)
if ds_project is None:
logger.error(
"Project '%s' does not exist in MAM" % projectname)
raise RuntimeError(
... | python | {
"resource": ""
} |
q16744 | MamDataStoreBase.get_projects_in_user | train | def get_projects_in_user(self, username):
""" Get list of projects in user from MAM. """
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... | python | {
"resource": ""
} |
q16745 | MamDataStoreBase.get_account_details | train | def get_account_details(self, account):
""" Get the account details """
result = self.get_user(account.username)
if result is None:
result = {}
return result | python | {
"resource": ""
} |
q16746 | MamDataStoreBase.get_project_details | train | def get_project_details(self, project):
""" Get the project details. """
result = self.get_project(project.pid)
if result is None:
result = {}
return result | python | {
"resource": ""
} |
q16747 | MamDataStoreBase.delete_institute | train | def delete_institute(self, institute):
""" Called when institute is deleted. """
name = institute.name
logger.debug("institute_deleted '%s'" % name)
# institute deleted
self._call(["goldsh", "Organization", "Delete", "Name==%s" % name])
logger.debug("returning")
... | python | {
"resource": ""
} |
q16748 | MamDataStore71.add_account_to_project | train | def add_account_to_project(self, account, project):
""" Add account to project. """
username = account.username
projectname = project.pid
self._call([
"gchproject",
"--add-user", username,
"-p", projectname],
ignore_errors=[74]) | python | {
"resource": ""
} |
q16749 | show | train | 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.fig... | python | {
"resource": ""
} |
q16750 | default_hub | train | 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
E... | python | {
"resource": ""
} |
q16751 | from_files | train | def from_files(filenames, strict_type_checks=True):
"""Return an iterator that provides a sequence of Histograms for
the histograms defined in filenames.
"""
if strict_type_checks:
load_whitelist()
all_histograms = OrderedDict()
for filename in filenames:
parser = FILENAME_PARSERS[o... | python | {
"resource": ""
} |
q16752 | Histogram.ranges | train | def ranges(self):
"""Return an array of lower bounds for each bucket in the histogram."""
bucket_fns = {
'boolean': linear_buckets,
'flag': linear_buckets,
'count': linear_buckets,
'enumerated': linear_buckets,
'categorical': linear_buckets,
... | python | {
"resource": ""
} |
q16753 | apply_extra_context | train | 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.
"""
for key, value in six.iteritems(extra_context):
if callable(value):
context[key]... | python | {
"resource": ""
} |
q16754 | get_model_and_form_class | train | 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 ... | python | {
"resource": ""
} |
q16755 | redirect | train | 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 returne... | python | {
"resource": ""
} |
q16756 | lookup_object | train | 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.
"... | python | {
"resource": ""
} |
q16757 | create_object | train | 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``
... | python | {
"resource": ""
} |
q16758 | update_object | train | 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):
"""
... | python | {
"resource": ""
} |
q16759 | delete_object | train | 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... | python | {
"resource": ""
} |
q16760 | get_url | train | def get_url(request, application, roles, label=None):
""" Retrieve a link that will work for the current user. """
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 secre... | python | {
"resource": ""
} |
q16761 | get_admin_email_link | train | def get_admin_email_link(application):
""" Retrieve a link that can be emailed to the administrator. """
url = '%s/applications/%d/' % (settings.ADMIN_BASE_URL, application.pk)
is_secret = False
return url, is_secret | python | {
"resource": ""
} |
q16762 | get_registration_email_link | train | def get_registration_email_link(application):
""" Retrieve a link that can be emailed to the logged other users. """
url = '%s/applications/%d/' % (
settings.REGISTRATION_BASE_URL, application.pk)
is_secret = False
return url, is_secret | python | {
"resource": ""
} |
q16763 | get_email_link | train | def get_email_link(application):
""" Retrieve a link that can be emailed to the applicant. """
# 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.... | python | {
"resource": ""
} |
q16764 | StateMachine.start | train | def start(self, request, application, extra_roles=None):
""" Continue the state machine at first state. """
# 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)
# ... | python | {
"resource": ""
} |
q16765 | StateMachine.process | train | def process(
self, request, application,
expected_state, label, extra_roles=None):
""" Process the view request at the current state. """
# Get the authentication of the current user
roles = self._get_roles_for_request(request, application)
if extra_roles is not ... | python | {
"resource": ""
} |
q16766 | StateMachine._get_roles_for_request | train | def _get_roles_for_request(request, application):
""" Check the authentication of the current user. """
roles = application.get_roles_for_person(request.user)
if common.is_admin(request):
roles.add("is_admin")
roles.add('is_authorised')
return roles | python | {
"resource": ""
} |
q16767 | StateMachine._next | train | def _next(self, request, application, roles, next_config):
""" Continue the state machine at given state. """
# we only support state changes for POST requests
if request.method == "POST":
key = None
# If next state is a transition, process it
while True:
... | python | {
"resource": ""
} |
q16768 | State.get_next_action | train | def get_next_action(self, request, application, label, roles):
""" Django view method. We provide a default detail view for
applications. """
# We only provide a view for when no label provided
if label is not None:
return HttpResponseBadRequest("<h1>Bad Request</h1>")
... | python | {
"resource": ""
} |
q16769 | Histogram.get_value | train | 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 ... | python | {
"resource": ""
} |
q16770 | Histogram.percentile | train | def percentile(self, percentile):
""" Returns the nth percentile of the histogram. """
assert(percentile >= 0 and percentile <= 100)
assert(self.kind in ["exponential", "linear", "enumerated", "boolean"])
fraction = percentile / 100
to_count = fraction * self.buckets.sum()
... | python | {
"resource": ""
} |
q16771 | BaseTrack.tracktype | train | def tracktype(self, tracktype):
"""
When setting the track type, the valid parameters for this track type
need to be set as well.
"""
self._tracktype = tracktype
if tracktype is not None:
if 'bed' in tracktype.lower():
tracktype = 'bigBed'
... | python | {
"resource": ""
} |
q16772 | BaseTrack.add_subgroups | train | def add_subgroups(self, subgroups):
"""
Update the subgroups for this track.
Note that in contrast to :meth:`CompositeTrack`, which takes a list of
:class:`SubGroupDefinition` objects representing the allowed subgroups,
this method takes a single dictionary indicating the partic... | python | {
"resource": ""
} |
q16773 | BaseTrack._str_subgroups | train | def _str_subgroups(self):
"""
helper function to render subgroups as a string
"""
if not self.subgroups:
return ""
return ['subGroups %s'
% ' '.join(['%s=%s' % (k, v) for (k, v) in
self.subgroups.items()])] | python | {
"resource": ""
} |
q16774 | CompositeTrack.add_subgroups | train | def add_subgroups(self, subgroups):
"""
Add a list of SubGroupDefinition objects to this composite.
Note that in contrast to :meth:`BaseTrack`, which takes a single
dictionary indicating the particular subgroups for the track, this
method takes a list of :class:`SubGroupDefiniti... | python | {
"resource": ""
} |
q16775 | CompositeTrack.add_view | train | def add_view(self, view):
"""
Add a ViewTrack object to this composite.
:param view:
A ViewTrack object.
"""
self.add_child(view)
self.views.append(view) | python | {
"resource": ""
} |
q16776 | CompositeTrack._str_subgroups | train | def _str_subgroups(self):
"""
renders subgroups to a list of strings
"""
s = []
i = 0
# if there are any views, there must be a subGroup1 view View tag=val
# as the first one. So create it automatically here
if len(self.views) > 0:
mapping =... | python | {
"resource": ""
} |
q16777 | ViewTrack.add_tracks | train | def add_tracks(self, subtracks):
"""
Add one or more tracks to this view.
subtracks : Track or iterable of Tracks
A single Track instance or an iterable of them.
"""
if isinstance(subtracks, Track):
subtracks = [subtracks]
for subtrack in subtrack... | python | {
"resource": ""
} |
q16778 | SuperTrack.add_tracks | train | def add_tracks(self, subtracks):
"""
Add one or more tracks.
subtrack : Track or iterable of Tracks
"""
if isinstance(subtracks, BaseTrack):
subtracks = [subtracks]
for subtrack in subtracks:
self.add_child(subtrack)
self.subtracks.app... | python | {
"resource": ""
} |
q16779 | load_scalars | train | def load_scalars(filename, strict_type_checks=True):
"""Parses a YAML file containing the scalar definition.
:param filename: the YAML file containing the scalars definition.
:raises ParserError: if the scalar file cannot be opened or parsed.
"""
# Parse the scalar definitions from the YAML file.
... | python | {
"resource": ""
} |
q16780 | ScalarType.validate_values | train | def validate_values(self, definition):
"""This function checks that the fields have the correct values.
:param definition: the dictionary containing the scalar properties.
:raises ParserError: if a scalar definition field contains an unexpected value.
"""
if not self._strict_ty... | python | {
"resource": ""
} |
q16781 | HubComponent.add_child | train | def add_child(self, child):
"""
Adds self as parent to child, and then adds child.
"""
child.parent = self
self.children.append(child)
return child | python | {
"resource": ""
} |
q16782 | HubComponent.add_parent | train | def add_parent(self, parent):
"""
Adds self as child of parent, then adds parent.
"""
parent.add_child(self)
self.parent = parent
return parent | python | {
"resource": ""
} |
q16783 | HubComponent.root | train | def root(self, cls=None, level=0):
"""
Returns the top-most HubComponent in the hierarchy.
If `cls` is not None, then return the top-most attribute HubComponent
that is an instance of class `cls`.
For a fully-constructed track hub (and `cls=None`), this should return
a ... | python | {
"resource": ""
} |
q16784 | HubComponent.leaves | train | def leaves(self, cls, level=0, intermediate=False):
"""
Returns an iterator of the HubComponent leaves that are of class `cls`.
If `intermediate` is True, then return any intermediate classes as
well.
"""
if intermediate:
if isinstance(self, cls):
... | python | {
"resource": ""
} |
q16785 | HubComponent.render | train | def render(self, staging=None):
"""
Renders the object to file, returning a list of created files.
Calls validation code, and, as long as each child is also a subclass of
:class:`HubComponent`, the rendering is recursive.
"""
self.validate()
created_files = Order... | python | {
"resource": ""
} |
q16786 | send_request_email | train | def send_request_email(
authorised_text, authorised_role, authorised_persons, application,
link, is_secret):
"""Sends an email to admin asking to approve user application"""
context = CONTEXT.copy()
context['requester'] = application.applicant
context['link'] = link
context['is_secre... | python | {
"resource": ""
} |
q16787 | send_invite_email | train | def send_invite_email(application, link, is_secret):
""" Sends an email inviting someone to create an account"""
if not application.applicant.email:
return
context = CONTEXT.copy()
context['receiver'] = application.applicant
context['application'] = application
context['link'] = link
... | python | {
"resource": ""
} |
q16788 | send_approved_email | train | def send_approved_email(
application, created_person, created_account, link, is_secret):
"""Sends an email informing person application is approved"""
if not application.applicant.email:
return
context = CONTEXT.copy()
context['receiver'] = application.applicant
context['application... | python | {
"resource": ""
} |
q16789 | _add_person_to_group | train | def _add_person_to_group(person, group):
""" Call datastores after adding a person to a group. """
from karaage.datastores import add_accounts_to_group
from karaage.datastores import add_accounts_to_project
from karaage.datastores import add_accounts_to_institute
a_list = person.account_set
add... | python | {
"resource": ""
} |
q16790 | _remove_person_from_group | train | def _remove_person_from_group(person, group):
""" Call datastores after removing a person from a group. """
from karaage.datastores import remove_accounts_from_group
from karaage.datastores import remove_accounts_from_project
from karaage.datastores import remove_accounts_from_institute
a_list = pe... | python | {
"resource": ""
} |
q16791 | dimensions_from_subgroups | train | def dimensions_from_subgroups(s):
"""
Given a sorted list of subgroups, return a string appropriate to provide as
a composite track's `dimensions` arg.
Parameters
----------
s : list of SubGroup objects (or anything with a `name` attribute)
"""
letters = 'XYABCDEFGHIJKLMNOPQRSTUVWZ'
... | python | {
"resource": ""
} |
q16792 | filter_composite_from_subgroups | train | def filter_composite_from_subgroups(s):
"""
Given a sorted list of subgroups, return a string appropriate to provide as
the a composite track's `filterComposite` argument
>>> import trackhub
>>> trackhub.helpers.filter_composite_from_subgroups(['cell', 'ab', 'lab', 'knockdown'])
'dimA dimB'
... | python | {
"resource": ""
} |
q16793 | hex2rgb | train | def hex2rgb(h):
"""
Convert hex colors to RGB tuples
Parameters
----------
h : str
String hex color value
>>> hex2rgb("#ff0033")
'255,0,51'
"""
if not h.startswith('#') or len(h) != 7:
raise ValueError("Does not look like a hex color: '{0}'".format(h))
return ',... | python | {
"resource": ""
} |
q16794 | sanitize | train | def sanitize(s, strict=True):
"""
Sanitize a string.
Spaces are converted to underscore; if strict=True they are then removed.
Parameters
----------
s : str
String to sanitize
strict : bool
If True, only alphanumeric characters are allowed. If False, a limited
set ... | python | {
"resource": ""
} |
q16795 | auto_track_url | train | def auto_track_url(track):
"""
Automatically sets the bigDataUrl for `track`.
Requirements:
* the track must be fully connected, such that its root is a Hub object
* the root Hub object must have the Hub.url attribute set
* the track must have the `source` attribute set
"""
... | python | {
"resource": ""
} |
q16796 | print_rendered_results | train | def print_rendered_results(results_dict):
"""
Pretty-prints the rendered results dictionary.
Rendered results can be multiply-nested dictionaries; this uses JSON
serialization to print a nice representation.
"""
class _HubComponentEncoder(json.JSONEncoder):
def default(self, o):
... | python | {
"resource": ""
} |
q16797 | example_bigbeds | train | def example_bigbeds():
"""
Returns list of example bigBed files
"""
hits = []
d = data_dir()
for fn in os.listdir(d):
fn = os.path.join(d, fn)
if os.path.splitext(fn)[-1] == '.bigBed':
hits.append(os.path.abspath(fn))
return hits | python | {
"resource": ""
} |
q16798 | get_colour | train | def get_colour(index):
""" get color number index. """
colours = [
'red', 'blue', 'green', 'pink',
'yellow', 'magenta', 'orange', 'cyan',
]
default_colour = 'purple'
if index < len(colours):
return colours[index]
else:
return default_colour | python | {
"resource": ""
} |
q16799 | get_project_trend_graph_url | train | def get_project_trend_graph_url(project, start, end):
"""Generates a bar graph for a project. """
filename = get_project_trend_graph_filename(project, start, end)
urls = {
'graph_url': urlparse.urljoin(GRAPH_URL, filename + ".png"),
'data_url': urlparse.urljoin(GRAPH_URL, filename + ".csv")... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.