_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q42400 | BaseSR._yield_all | train | def _yield_all(self, l):
'''
Given a iterable like list or tuple the function yields each of its
items with _yield
'''
if l is not None:
if type(l) in [list, tuple]:
for f in l:
for x in self._yield(f): yield x
else:
... | python | {
"resource": ""
} |
q42401 | MoneyBird.post | train | def post(self, resource_path: str, data: dict, administration_id: int = None):
"""
Performs a POST request to the endpoint identified by the resource path. POST requests are usually used to add
new data.
Example:
>>> from moneybird import MoneyBird, TokenAuthentication
... | python | {
"resource": ""
} |
q42402 | MoneyBird.renew_session | train | def renew_session(self):
"""
Clears all session data and starts a new session using the same settings as before.
This method can be used to clear session data, e.g., cookies. Future requests will use a new session initiated
with the same settings and authentication method.
"""
... | python | {
"resource": ""
} |
q42403 | MoneyBird._get_url | train | def _get_url(cls, administration_id: int, resource_path: str):
"""
Builds the URL to the API endpoint specified by the given parameters.
:param administration_id: The ID of the administration (may be None).
:param resource_path: The path to the resource.
:return: The absolute UR... | python | {
"resource": ""
} |
q42404 | MoneyBird._process_response | train | def _process_response(response: requests.Response, expected: list = []) -> dict:
"""
Processes an API response. Raises an exception when appropriate.
The exception that will be raised is MoneyBird.APIError. This exception is subclassed so implementing programs
can easily react appropria... | python | {
"resource": ""
} |
q42405 | VideohubVideo.search_videohub | train | def search_videohub(cls, query, filters=None, status=None, sort=None, size=None, page=None):
"""searches the videohub given a query and applies given filters and other bits
:see: https://github.com/theonion/videohub/blob/master/docs/search/post.md
:see: https://github.com/theonion/videohub/blob... | python | {
"resource": ""
} |
q42406 | VideohubVideo.get_hub_url | train | def get_hub_url(self):
"""gets a canonical path to the detail page of the video on the hub
:return: the path to the consumer ui detail page of the video
:rtype: str
"""
url = getattr(settings, "VIDEOHUB_VIDEO_URL", self.DEFAULT_VIDEOHUB_VIDEO_URL)
# slugify needs ascii
... | python | {
"resource": ""
} |
q42407 | VideohubVideo.get_embed_url | train | def get_embed_url(self, targeting=None, recirc=None):
"""gets a canonical path to an embedded iframe of the video from the hub
:return: the path to create an embedded iframe of the video
:rtype: str
"""
url = getattr(settings, "VIDEOHUB_EMBED_URL", self.DEFAULT_VIDEOHUB_EMBED_UR... | python | {
"resource": ""
} |
q42408 | VideohubVideo.get_api_url | train | def get_api_url(self):
"""gets a canonical path to the api detail url of the video on the hub
:return: the path to the api detail of the video
:rtype: str
"""
url = getattr(settings, 'VIDEOHUB_API_URL', None)
# Support alternate setting (used by most client projects)
... | python | {
"resource": ""
} |
q42409 | OutcomeGroupsAPI.create_subgroup_global | train | def create_subgroup_global(self, id, title, description=None, vendor_guid=None):
"""
Create a subgroup.
Creates a new empty subgroup under the outcome group with the given title
and description.
"""
path = {}
data = {}
params = {}
# RE... | python | {
"resource": ""
} |
q42410 | GradingPeriodsAPI.update_single_grading_period | train | def update_single_grading_period(self, id, course_id, grading_periods_end_date, grading_periods_start_date, grading_periods_weight=None):
"""
Update a single grading period.
Update an existing grading period.
"""
path = {}
data = {}
params = {}
... | python | {
"resource": ""
} |
q42411 | AppointmentGroupsAPI.get_next_appointment | train | def get_next_appointment(self, appointment_group_ids=None):
"""
Get next appointment.
Return the next appointment available to sign up for. The appointment
is returned in a one-element array. If no future appointments are
available, an empty array is returned.
"""... | python | {
"resource": ""
} |
q42412 | Dataset.to_funset | train | def to_funset(self, discrete):
"""
Converts the dataset to a set of `gringo.Fun`_ instances
Parameters
----------
discrete : callable
A discretization function
Returns
-------
set
Representation of the dataset as a set of `gringo.... | python | {
"resource": ""
} |
q42413 | set_dump_directory | train | def set_dump_directory(base=None, sub_dir=None):
"""Create directory for dumping SQL commands."""
# Set current timestamp
timestamp = datetime.fromtimestamp(time()).strftime('%Y-%m-%d %H-%M-%S')
# Clean sub_dir
if sub_dir and '.' in sub_dir:
sub_dir = sub_dir.rsplit('.', 1)[0]
# Create... | python | {
"resource": ""
} |
q42414 | dump_commands | train | def dump_commands(commands, directory=None, sub_dir=None):
"""
Dump SQL commands to .sql files.
:param commands: List of SQL commands
:param directory: Directory to dump commands to
:param sub_dir: Sub directory
:return: Directory failed commands were dumped to
"""
print('\t' + str(len(... | python | {
"resource": ""
} |
q42415 | write_text | train | def write_text(_command, txt_file):
"""Dump SQL command to a text file."""
command = _command.strip()
with open(txt_file, 'w') as txt:
txt.writelines(command) | python | {
"resource": ""
} |
q42416 | get_commands_from_dir | train | def get_commands_from_dir(directory, zip_backup=True, remove_dir=True):
"""Traverse a directory and read contained SQL files."""
# Get SQL commands file paths
failed_scripts = sorted([os.path.join(directory, fn) for fn in os.listdir(directory) if fn.endswith('.sql')])
# Read each failed SQL file and ap... | python | {
"resource": ""
} |
q42417 | ParameterSet.blueprint | train | def blueprint(self):
"""
blueprint support, returns a partial dictionary
"""
blueprint = dict()
blueprint['type'] = "%s.%s" % (self.__module__, self.__class__.__name__)
# Fields
fields = dict()
# inspects the attributes of a parameter set and tries to v... | python | {
"resource": ""
} |
q42418 | ParameterSet.validate | train | def validate(self, request):
"""
validate method for %ParameterSet
Since the introduction of ResponseFieldListParser, the parameter _response_field_list
will be ignored, this is a prestans reserved parameter, and cannot be used by apps.
:param request: The request object to be ... | python | {
"resource": ""
} |
q42419 | preload_pages | train | def preload_pages():
"""Register all pages before the first application request."""
try:
_add_url_rule([page.url for page in Page.query.all()])
except Exception: # pragma: no cover
current_app.logger.warn('Pages were not loaded.')
raise | python | {
"resource": ""
} |
q42420 | render_page | train | def render_page(path):
"""Internal interface to the page view.
:param path: Page path.
:returns: The rendered template.
"""
try:
page = Page.get_by_url(request.path)
except NoResultFound:
abort(404)
return render_template(
[page.template_name, current_app.config['PA... | python | {
"resource": ""
} |
q42421 | handle_not_found | train | def handle_not_found(exception, **extra):
"""Custom blueprint exception handler."""
assert isinstance(exception, NotFound)
page = Page.query.filter(db.or_(Page.url == request.path,
Page.url == request.path + "/")).first()
if page:
_add_url_rule(page.url)
... | python | {
"resource": ""
} |
q42422 | _add_url_rule | train | def _add_url_rule(url_or_urls):
"""Register URL rule to application URL map."""
old = current_app._got_first_request
# This is bit of cheating to overcome @flask.app.setupmethod decorator.
current_app._got_first_request = False
if isinstance(url_or_urls, six.string_types):
url_or_urls = [url... | python | {
"resource": ""
} |
q42423 | CollaborationsAPI.list_members_of_collaboration | train | def list_members_of_collaboration(self, id, include=None):
"""
List members of a collaboration.
List the collaborators of a given collaboration
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
path["id"] = i... | python | {
"resource": ""
} |
q42424 | DiscussionTopicsAPI.list_discussion_topics_courses | train | def list_discussion_topics_courses(self, course_id, exclude_context_module_locked_topics=None, include=None, only_announcements=None, order_by=None, scope=None, search_term=None):
"""
List discussion topics.
Returns the paginated list of discussion topics for this course or group.
... | python | {
"resource": ""
} |
q42425 | DiscussionTopicsAPI.create_new_discussion_topic_courses | train | def create_new_discussion_topic_courses(self, course_id, allow_rating=None, assignment=None, attachment=None, delayed_post_at=None, discussion_type=None, group_category_id=None, is_announcement=None, lock_at=None, message=None, only_graders_can_rate=None, pinned=None, podcast_enabled=None, podcast_has_student_posts=Non... | python | {
"resource": ""
} |
q42426 | DiscussionTopicsAPI.delete_topic_groups | train | def delete_topic_groups(self, group_id, topic_id):
"""
Delete a topic.
Deletes the discussion topic. This will also delete the assignment, if it's
an assignment discussion.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_... | python | {
"resource": ""
} |
q42427 | DiscussionTopicsAPI.rate_entry_courses | train | def rate_entry_courses(self, topic_id, entry_id, course_id, rating=None):
"""
Rate entry.
Rate a discussion entry.
On success, the response will be 204 No Content with an empty body.
"""
path = {}
data = {}
params = {}
# REQU... | python | {
"resource": ""
} |
q42428 | cli | train | def cli(**settings):
"""Notify about new reviews in AppStore and Google Play in slack.
Launch command using supervisor or using screen/tmux/etc.
Reviews are fetched for multiple apps and languages in --beat=300 interval.
"""
setup_logging(settings)
settings = setup_languages(settings)
... | python | {
"resource": ""
} |
q42429 | Source.create_fa | train | def create_fa(self):
"""Create a FASTA file with extracted sequences.
"""
if self._seqs is None:
os.symlink(self._fa0_fn, self._fa_fn)
else:
in_seqs = pyfaidx.Fasta(self._fa0_fn)
with open(self._fa_fn, "w+") as g:
for seq_desc in self._seqs... | python | {
"resource": ""
} |
q42430 | Source.recode_sam_reads | train | def recode_sam_reads(
sam_fn,
fastq_rnf_fo,
fai_fo,
genome_id,
number_of_read_tuples=10**9,
simulator_name=None,
allow_unmapped=False,
):
"""Transform a SAM file to RNF-compatible FASTQ.
Args:
sam_fn (str): SAM/BAM file - file name.
fastq_rnf_... | python | {
"resource": ""
} |
q42431 | instantiate | train | def instantiate(config):
"""
instantiate all registered vodka applications
Args:
config (dict or MungeConfig): configuration object
"""
for handle, cfg in list(config["apps"].items()):
if not cfg.get("enabled", True):
continue
app = get_application(handle)
... | python | {
"resource": ""
} |
q42432 | compile_resource | train | def compile_resource(resource):
"""
Return compiled regex for resource matching
"""
return re.compile("^" + trim_resource(re.sub(r":(\w+)", r"(?P<\1>[\w-]+?)",
resource)) + r"(\?(?P<querystring>.*))?$") | python | {
"resource": ""
} |
q42433 | handle | train | def handle(data_type, data, data_id=None, caller=None):
"""
execute all data handlers on the specified data according to data type
Args:
data_type (str): data type handle
data (dict or list): data
Kwargs:
data_id (str): can be used to differentiate between different data
... | python | {
"resource": ""
} |
q42434 | ReadingListMixin.validate_query | train | def validate_query(self, query):
"""Confirm query exists given common filters."""
if query is None:
return query
query = self.update_reading_list(query)
return query | python | {
"resource": ""
} |
q42435 | ReadingListMixin.get_validated_augment_query | train | def get_validated_augment_query(self, augment_query=None):
"""
Common rules for reading list augmentation hierarchy.
1. Sponsored Content.
2. Video Content.
"""
augment_query = self.validate_query(augment_query)
# Given an invalid query, reach for a Sponsored qu... | python | {
"resource": ""
} |
q42436 | ReadingListMixin.augment_reading_list | train | def augment_reading_list(self, primary_query, augment_query=None, reverse_negate=False):
"""Apply injected logic for slicing reading lists with additional content."""
primary_query = self.validate_query(primary_query)
augment_query = self.get_validated_augment_query(augment_query=augment_query)
... | python | {
"resource": ""
} |
q42437 | ReadingListMixin.update_reading_list | train | def update_reading_list(self, reading_list):
"""Generic behaviors for reading lists before being rendered."""
# remove the current piece of content from the query.
reading_list = reading_list.filter(
~es_filter.Ids(values=[self.id])
)
# remove excluded document type... | python | {
"resource": ""
} |
q42438 | ReadingListMixin.get_reading_list_context | train | def get_reading_list_context(self, **kwargs):
"""Returns the context dictionary for a given reading list."""
reading_list = None
context = {
"name": "",
"content": reading_list,
"targeting": {},
"videos": []
}
if self.reading_list_... | python | {
"resource": ""
} |
q42439 | Frontmatter.read | train | def read(cls, string):
"""Returns dict with separated frontmatter from string.
Returned dict keys:
attributes -- extracted YAML attributes in dict form.
body -- string contents below the YAML separators
frontmatter -- string representation of YAML
"""
fmatter = "... | python | {
"resource": ""
} |
q42440 | _analyze_case | train | def _analyze_case(model_dir, bench_dir, config):
""" Generates statistics from the timing summaries """
model_timings = set(glob.glob(os.path.join(model_dir, "*" + config["timing_ext"])))
if bench_dir is not None:
bench_timings = set(glob.glob(os.path.join(bench_dir, "*" + config["timing_ext"])))
... | python | {
"resource": ""
} |
q42441 | generate_timing_stats | train | def generate_timing_stats(file_list, var_list):
"""
Parse all of the timing files, and generate some statistics
about the run.
Args:
file_list: A list of timing files to parse
var_list: A list of variables to look for in the timing file
Returns:
A dict containing values tha... | python | {
"resource": ""
} |
q42442 | weak_scaling | train | def weak_scaling(timing_stats, scaling_var, data_points):
"""
Generate data for plotting weak scaling. The data points keep
a constant amount of work per processor for each data point.
Args:
timing_stats: the result of the generate_timing_stats function
scaling_var: the variable to sel... | python | {
"resource": ""
} |
q42443 | generate_scaling_plot | train | def generate_scaling_plot(timing_data, title, ylabel, description, plot_file):
"""
Generate a scaling plot.
Args:
timing_data: data returned from a `*_scaling` method
title: the title of the plot
ylabel: the y-axis label of the plot
description: a description of the plot
... | python | {
"resource": ""
} |
q42444 | _InvenioPagesState.jinja_env | train | def jinja_env(self):
"""Create a sandboxed Jinja environment."""
if self._jinja_env is None:
self._jinja_env = SandboxedEnvironment(
extensions=[
'jinja2.ext.autoescape', 'jinja2.ext.with_', ],
autoescape=True,
)
sel... | python | {
"resource": ""
} |
q42445 | _InvenioPagesState.render_template | train | def render_template(self, source, **kwargs_context):
r"""Render a template string using sandboxed environment.
:param source: A string containing the page source.
:param \*\*kwargs_context: The context associated with the page.
:returns: The rendered template.
"""
return... | python | {
"resource": ""
} |
q42446 | InvenioPages.wrap_errorhandler | train | def wrap_errorhandler(app):
"""Wrap error handler.
:param app: The Flask application.
"""
try:
existing_handler = app.error_handler_spec[None][404][NotFound]
except (KeyError, TypeError):
existing_handler = None
if existing_handler:
a... | python | {
"resource": ""
} |
q42447 | ConferencesAPI.list_conferences_groups | train | def list_conferences_groups(self, group_id):
"""
List conferences.
Retrieve the list of conferences for this context
This API returns a JSON object containing the list of conferences,
the key for the list of conferences is "conferences"
"""
path... | python | {
"resource": ""
} |
q42448 | QuizAssignmentOverridesAPI.retrieve_assignment_overridden_dates_for_quizzes | train | def retrieve_assignment_overridden_dates_for_quizzes(self, course_id, quiz_assignment_overrides_0_quiz_ids=None):
"""
Retrieve assignment-overridden dates for quizzes.
Retrieve the actual due-at, unlock-at, and available-at dates for quizzes
based on the assignment overrides active... | python | {
"resource": ""
} |
q42449 | KNeighborsClassifier.fit | train | def fit(self, X, y):
"""Fit the model using X as training data and y as target values"""
self._data = X
self._classes = np.unique(y)
self._labels = y
self._is_fitted = True | python | {
"resource": ""
} |
q42450 | KNeighborsClassifier.predict | train | def predict(self, X):
"""Predict the class labels for the provided data
Parameters
----------
X : array-like, shape (n_query, n_features).
Test samples.
Returns
-------
y : array of shape [n_samples]
Class labels for each data sample.
... | python | {
"resource": ""
} |
q42451 | build_url | train | def build_url(component, filename, **values):
"""
search bower asset and build url
:param component: bower component (package)
:type component: str
:param filename: filename in bower component - can contain directories (like dist/jquery.js)
:type filename: str
:param values: additional url ... | python | {
"resource": ""
} |
q42452 | init_ixn | train | def init_ixn(api, logger, install_dir=None):
""" Create IXN object.
:param api: tcl/python/rest
:type api: trafficgenerator.tgn_utils.ApiType
:param logger: logger object
:param install_dir: IXN installation directory
:return: IXN object
"""
if api == ApiType.tcl:
api_wrapper =... | python | {
"resource": ""
} |
q42453 | IxnApp.disconnect | train | def disconnect(self):
""" Disconnect from chassis and server. """
if self.root.ref is not None:
self.api.disconnect()
self.root = None | python | {
"resource": ""
} |
q42454 | Timeout.start | train | def start(self):
"""Schedule the timeout. This is called on construction, so
it should not be called explicitly, unless the timer has been
canceled."""
assert not self._timer, '%r is already started; to restart it, cancel it first' % self
loop = evergreen.current.loop
cu... | python | {
"resource": ""
} |
q42455 | FqCreator.flush_read_tuple | train | def flush_read_tuple(self):
"""Flush the internal buffer of reads.
"""
if not self.is_empty():
suffix_comment_buffer = []
if self._info_simulator is not None:
suffix_comment_buffer.append(self._info_simulator)
if self._info_reads_in_tuple:
... | python | {
"resource": ""
} |
q42456 | BayesCategories.add_category | train | def add_category(self, name):
"""
Adds a bayes category that we can later train
:param name: name of the category
:type name: str
:return: the requested category
:rtype: BayesCategory
"""
category = BayesCategory(name)
self.categories[name] = cate... | python | {
"resource": ""
} |
q42457 | FilteredStream.line_is_interesting | train | def line_is_interesting(self, line):
"""Return True, False, or None.
True means always output, False means never output, None means output
only if there are interesting lines.
"""
if line.startswith('Name'):
return None
if line.startswith('--------'):
... | python | {
"resource": ""
} |
q42458 | Graph.predecessors | train | def predecessors(self, node, exclude_compressed=True):
"""
Returns the list of predecessors of a given node
Parameters
----------
node : str
The target node
exclude_compressed : boolean
If true, compressed nodes are excluded from the predecessors... | python | {
"resource": ""
} |
q42459 | Graph.successors | train | def successors(self, node, exclude_compressed=True):
"""
Returns the list of successors of a given node
Parameters
----------
node : str
The target node
exclude_compressed : boolean
If true, compressed nodes are excluded from the successors list
... | python | {
"resource": ""
} |
q42460 | Graph.compress | train | def compress(self, setup):
"""
Returns the compressed graph according to the given experimental setup
Parameters
----------
setup : :class:`caspo.core.setup.Setup`
Experimental setup used to compress the graph
Returns
-------
caspo.core.graph... | python | {
"resource": ""
} |
q42461 | RnfProfile.combine | train | def combine(*rnf_profiles):
"""Combine more profiles and set their maximal values.
Args:
*rnf_profiles (rnftools.rnfformat.RnfProfile): RNF profile.
"""
for rnf_profile in rnf_profiles:
self.prefix_width = max(self.prefix_width, rnf_profile.prefix_width)
self.read_tuple_... | python | {
"resource": ""
} |
q42462 | RnfProfile.load | train | def load(self, read_tuple_name):
"""Load RNF values from a read tuple name.
Args:
read_tuple_name (str): Read tuple name which the values are taken from.
"""
self.prefix_width = 0
self.read_tuple_id_width = 0
self.genome_id_width = 0
self.chr_id_width = 0
self.coo... | python | {
"resource": ""
} |
q42463 | RnfProfile.apply | train | def apply(self, read_tuple_name, read_tuple_id=None, synchronize_widths=True):
"""Apply profile on a read tuple name and update read tuple ID.
Args:
read_tuple_name (str): Read tuple name to be updated.
read_tuple_id (id): New read tuple ID.
synchronize_widths (bool): Update widths (in accordance to... | python | {
"resource": ""
} |
q42464 | RnfProfile.check | train | def check(self, read_tuple_name):
"""Check if the given read tuple name satisfies this profile.
Args:
read_tuple_name (str): Read tuple name.
"""
parts = read_tuple_name.split("__")
if len(parts[0]) != self.prefix_width or len(parts[1]) != self.read_tuple_id_width:
return F... | python | {
"resource": ""
} |
q42465 | Definition.get_column_definition_all | train | def get_column_definition_all(self, table):
"""Retrieve the column definition statement for all columns in a table."""
# Get complete table definition
col_defs = self.get_table_definition(table).split('\n')
# Return only column definitions
return [i[0:-1].strip().replace(',', ',... | python | {
"resource": ""
} |
q42466 | Definition.get_column_definition | train | def get_column_definition(self, table, column):
"""Retrieve the column definition statement for a column from a table."""
# Parse column definitions for match
for col in self.get_column_definition_all(table):
if col.strip('`').startswith(column):
return col.strip(',') | python | {
"resource": ""
} |
q42467 | original | train | def original(modname):
""" This returns an unpatched version of a module."""
# note that it's not necessary to temporarily install unpatched
# versions of all patchable modules during the import of the
# module; this is because none of them import each other, except
# for threading which imports thr... | python | {
"resource": ""
} |
q42468 | patch | train | def patch(**on):
"""Globally patches certain system modules to be 'cooperaive'.
The keyword arguments afford some control over which modules are patched.
If no keyword arguments are supplied, all possible modules are patched.
If keywords are set to True, only the specified modules are patched. E.g.,
... | python | {
"resource": ""
} |
q42469 | SysModulesSaver.save | train | def save(self, *module_names):
"""Saves the named modules to the object."""
for modname in module_names:
self._saved[modname] = sys.modules.get(modname, None) | python | {
"resource": ""
} |
q42470 | SysModulesSaver.restore | train | def restore(self):
"""Restores the modules that the saver knows about into
sys.modules.
"""
try:
for modname, mod in self._saved.items():
if mod is not None:
sys.modules[modname] = mod
else:
try:
... | python | {
"resource": ""
} |
q42471 | LIVVDict.nested_insert | train | def nested_insert(self, item_list):
""" Create a series of nested LIVVDicts given a list """
if len(item_list) == 1:
self[item_list[0]] = LIVVDict()
elif len(item_list) > 1:
if item_list[0] not in self:
self[item_list[0]] = LIVVDict()
self[item... | python | {
"resource": ""
} |
q42472 | LIVVDict.nested_assign | train | def nested_assign(self, key_list, value):
""" Set the value of nested LIVVDicts given a list """
if len(key_list) == 1:
self[key_list[0]] = value
elif len(key_list) > 1:
if key_list[0] not in self:
self[key_list[0]] = LIVVDict()
self[key_list[0... | python | {
"resource": ""
} |
q42473 | post_save | train | def post_save(sender, instance, created, **kwargs):
"""
After save create order instance for sending instance for orderable models.
"""
# Only create order model instances for
# those modules specified in settings.
model_label = '.'.join([sender._meta.app_label, sender._meta.object_name])
la... | python | {
"resource": ""
} |
q42474 | parse_children | train | def parse_children(parent):
"""Recursively parse child tags until match is found"""
components = []
for tag in parent.children:
matched = parse_tag(tag)
if matched:
components.append(matched)
elif hasattr(tag, 'contents'):
components += parse_children(tag)
... | python | {
"resource": ""
} |
q42475 | DataURLFile.save | train | def save(self, path):
"""
Writes file to a particular location
This won't work for cloud environments like Google's App Engine, use with caution
ensure to catch exceptions so you can provide informed feedback.
prestans does not mask File IO exceptions so your handler can respon... | python | {
"resource": ""
} |
q42476 | GradeChangeLogAPI.query_by_assignment | train | def query_by_assignment(self, assignment_id, end_time=None, start_time=None):
"""
Query by assignment.
List grade change events for a given assignment.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - assignment_id
"""ID"""
... | python | {
"resource": ""
} |
q42477 | GradeChangeLogAPI.query_by_student | train | def query_by_student(self, student_id, end_time=None, start_time=None):
"""
Query by student.
List grade change events for a given student.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - student_id
"""ID"""
path["stud... | python | {
"resource": ""
} |
q42478 | GradeChangeLogAPI.query_by_grader | train | def query_by_grader(self, grader_id, end_time=None, start_time=None):
"""
Query by grader.
List grade change events for a given grader.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - grader_id
"""ID"""
path["grader_id... | python | {
"resource": ""
} |
q42479 | Response.register_serializers | train | def register_serializers(self, serializers):
"""
Adds extra serializers; generally registered during the handler lifecycle
"""
for new_serializer in serializers:
if not isinstance(new_serializer, serializer.Base):
msg = "registered serializer %s.%s does not i... | python | {
"resource": ""
} |
q42480 | ContributorReport.is_valid | train | def is_valid(self):
"""returns `True` if the report should be sent."""
if not self.total:
return False
if not self.contributor.freelanceprofile.is_freelance:
return False
return True | python | {
"resource": ""
} |
q42481 | ContributorReport.contributions | train | def contributions(self):
"""Apply a datetime filter against the contributor's contribution queryset."""
if self._contributions is None:
self._contributions = self.contributor.contributions.filter(
content__published__gte=self.start,
content__published__lt=self... | python | {
"resource": ""
} |
q42482 | ContributorReport.line_items | train | def line_items(self):
"""Apply a datetime filter against the contributors's line item queryset."""
if self._line_items is None:
self._line_items = self.contributor.line_items.filter(
payment_date__range=(self.start, self.end)
)
return self._line_items | python | {
"resource": ""
} |
q42483 | ContributorReport.deadline | train | def deadline(self):
"""Return next day as deadline if no deadline provided."""
if not self._deadline:
self._deadline = self.now + timezone.timedelta(days=1)
return self._deadline | python | {
"resource": ""
} |
q42484 | EmailReport.send_contributor_email | train | def send_contributor_email(self, contributor):
"""Send an EmailMessage object for a given contributor."""
ContributorReport(
contributor,
month=self.month,
year=self.year,
deadline=self._deadline,
start=self._start,
end=self._end
... | python | {
"resource": ""
} |
q42485 | EmailReport.send_mass_contributor_emails | train | def send_mass_contributor_emails(self):
"""Send report email to all relevant contributors."""
# If the report configuration is not active we only send to the debugging user.
for contributor in self.contributors:
if contributor.email not in EMAIL_SETTINGS.get("EXCLUDED", []):
... | python | {
"resource": ""
} |
q42486 | EmailReport.contributors | train | def contributors(self):
"""Property to retrieve or access the list of contributors."""
if not self._contributors:
self._contributors = self.get_contributors()
return self._contributors | python | {
"resource": ""
} |
q42487 | CrawlElement.xpath_pick_one | train | def xpath_pick_one(self, xpaths):
"""
Try each of the xpaths successively until
a single element is found. If no xpath succeeds
then raise the last UnexpectedContentException caught.
"""
for xpathi, xpath in enumerate(xpaths):
try:
return self.xpath(xpath, [1, 1])[0]
except UnexpectedCont... | python | {
"resource": ""
} |
q42488 | _PZoneOperationSerializer.get_content_title | train | def get_content_title(self, obj):
"""Get content's title."""
return Content.objects.get(id=obj.content.id).title | python | {
"resource": ""
} |
q42489 | Dates.is_date | train | def is_date(self):
"""Determine if a data record is of type DATE."""
dt = DATA_TYPES['date']
if type(self.data) is dt['type'] and '-' in str(self.data) and str(self.data).count('-') == 2:
# Separate year, month and day
date_split = str(self.data).split('-')
y,... | python | {
"resource": ""
} |
q42490 | Dates.is_time | train | def is_time(self):
"""Determine if a data record is of type TIME."""
dt = DATA_TYPES['time']
if type(self.data) is dt['type'] and ':' in str(self.data) and str(self.data).count(':') == 2:
# Separate hour, month, second
date_split = str(self.data).split(':')
h,... | python | {
"resource": ""
} |
q42491 | Dates.is_year | train | def is_year(self):
"""Determine if a data record is of type YEAR."""
dt = DATA_TYPES['year']
if dt['min'] and dt['max']:
if type(self.data) is dt['type'] and dt['min'] < self.data < dt['max']:
self.type = 'year'.upper()
self.len = None
... | python | {
"resource": ""
} |
q42492 | Dates._is_date_data | train | def _is_date_data(self, data_type):
"""Private method for determining if a data record is of type DATE."""
dt = DATA_TYPES[data_type]
if isinstance(self.data, dt['type']):
self.type = data_type.upper()
self.len = None
return True | python | {
"resource": ""
} |
q42493 | Barrier.wait | train | def wait(self, timeout=None):
"""Wait for the barrier.
When the specified number of threads have started waiting, they are all
simultaneously awoken. If an 'action' was provided for the barrier, one
of the threads will have executed that callback prior to returning.
Returns an i... | python | {
"resource": ""
} |
q42494 | Barrier.reset | train | def reset(self):
"""Reset the barrier to the initial state.
Any threads currently waiting will get the BrokenBarrier exception
raised.
"""
with self._cond:
if self._count > 0:
if self._state == 0:
#reset the barrier, waking up thr... | python | {
"resource": ""
} |
q42495 | BaseContentDetailView.get | train | def get(self, request, *args, **kwargs):
"""Override default get function to use token if there is one to retrieve object. If a
subclass should use their own GET implementation, token_from_kwargs should be called if
that detail view should be accessible via token."""
self.object = self.... | python | {
"resource": ""
} |
q42496 | host | train | def host(value):
""" Validates that the value is a valid network location """
if not value:
return (True, "")
try:
host,port = value.split(":")
except ValueError as _:
return (False, "value needs to be <host>:<port>")
try:
int(port)
except ValueError as _:
... | python | {
"resource": ""
} |
q42497 | QuizReportsAPI.retrieve_all_quiz_reports | train | def retrieve_all_quiz_reports(self, quiz_id, course_id, includes_all_versions=None):
"""
Retrieve all quiz reports.
Returns a list of all available reports.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
... | python | {
"resource": ""
} |
q42498 | Setup.clampings_iter | train | def clampings_iter(self, cues=None):
"""
Iterates over all possible clampings of this experimental setup
Parameters
----------
cues : Optional[iterable]
If given, restricts clampings over given species names
Yields
------
caspo.core.clamping... | python | {
"resource": ""
} |
q42499 | Setup.to_funset | train | def to_funset(self):
"""
Converts the experimental setup to a set of `gringo.Fun`_ object instances
Returns
-------
set
The set of `gringo.Fun`_ object instances
.. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun
"""
fs = set((g... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.