_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q250000 | display_queries | train | def display_queries(request, stats, queries):
"""
Generate a HttpResponse of SQL queries for a profiling run.
_stats_ should contain a pstats.Stats of a hotshot session.
_queries_ should contain a list of SQL queries.
"""
sort = request.REQUEST.get('sort_by', 'time')
sort_buttons = RadioBut... | python | {
"resource": ""
} |
q250001 | ProfileMiddleware.process_request | train | def process_request(self, request):
"""
Setup the profiler for a profiling run and clear the SQL query log.
If this is a resort of an existing profiling run, just return
the resorted list.
"""
def unpickle(params):
stats = unpickle_stats(b64decode(params.get(... | python | {
"resource": ""
} |
q250002 | ProfileMiddleware.process_view | train | def process_view(self, request, view_func, view_args, view_kwargs):
"""Run the profiler on _view_func_."""
profiler = getattr(request, 'profiler', None)
if profiler:
# Make sure profiler variables don't get passed into view_func
original_get = request.GET
requ... | python | {
"resource": ""
} |
q250003 | ProfileMiddleware.process_response | train | def process_response(self, request, response):
"""Finish profiling and render the results."""
profiler = getattr(request, 'profiler', None)
if profiler:
profiler.close()
params = request.REQUEST
stats = hotshot.stats.load(request.statsfile.name)
qu... | python | {
"resource": ""
} |
q250004 | ETL.items_to_extract | train | def items_to_extract(self, offset=0, length=None):
"""
Return an iterable of specific items to extract.
As a side-effect, set self.items_to_extract_length.
:param offset: where to start extracting
:param length: how many to extract
:return: An iterable of the specific
... | python | {
"resource": ""
} |
q250005 | dedupe_and_sort | train | def dedupe_and_sort(sequence, first=None, last=None):
"""
De-dupe and partially sort a sequence.
The `first` argument should contain all the items that might appear in
`sequence` and for which the order (relative to each other) is important.
The `last` argument is the same, but matching items will... | python | {
"resource": ""
} |
q250006 | slice_sequences | train | def slice_sequences(sequences, start, end, apply_slice=None):
"""
Performs a slice across multiple sequences.
Useful when paginating across chained collections.
:param sequences: an iterable of iterables, each nested iterable should contain
a sequence and its size
:param start: starting index... | python | {
"resource": ""
} |
q250007 | quote | train | def quote(key, value):
"""Certain options support string values. We want clients to be able to pass Python strings in
but we need them to be quoted in the output. Unfortunately some of those options also allow
numbers so we type check the value before wrapping it in quotes.
"""
if key in quoted_opt... | python | {
"resource": ""
} |
q250008 | scale_and_crop_with_ranges | train | def scale_and_crop_with_ranges(
im, size, size_range=None, crop=False, upscale=False, zoom=None, target=None, **kwargs):
"""
An easy_thumbnails processor that accepts a `size_range` tuple, which
indicates that one or both dimensions can give by a number of pixels in
order to minimize cropping.
"... | python | {
"resource": ""
} |
q250009 | check_settings | train | def check_settings(required_settings):
"""
Checks all settings required by a module have been set.
If a setting is required and it could not be found a
NotImplementedError will be raised informing which settings are
missing.
:param required_settings: List of settings names (as strings) that
... | python | {
"resource": ""
} |
q250010 | OccurrenceQueryset.available_on_day | train | def available_on_day(self, day):
"""
Return events that are available on a given day.
| python | {
"resource": ""
} |
q250011 | CronBaseCommand.cleanup | train | def cleanup(self):
"""
Performs clean-up after task is completed before it is executed again
in the next internal.
"""
# Closes connections to all | python | {
"resource": ""
} |
q250012 | PluginMount.get_plugins | train | def get_plugins(cls, *args, **kwargs):
"""
Return a list of plugin instances and pass through arguments.
"""
| python | {
"resource": ""
} |
q250013 | ICEkitSearchView.pre_facet_sqs | train | def pre_facet_sqs(self):
"""
Return the queryset used for generating facets, before any facets
are applied
"""
sqs = SearchQuerySet()
if self.query:
sqs = sqs.filter(
SQ(content=AutoQuery(self.query)) | # Search | python | {
"resource": ""
} |
q250014 | ICEkitSearchView.get | train | def get(self, request, *args, **kwargs):
"""User has conducted a search, or default state"""
form_class = self.get_form_class()
form = self.get_form(form_class)
top_value = self.get_top_level_facet_value()
subfacets = SEARCH_SUBFACETS.get(top_value, [])
self.active_face... | python | {
"resource": ""
} |
q250015 | index | train | def index(request):
"""
Listing page for event `Occurrence`s.
:param request: Django request object.
:param is_preview: Should the listing page be generated as a preview? This
will allow preview specific actions to be done in the
template such as turning of... | python | {
"resource": ""
} |
q250016 | get_assigned_to_user | train | def get_assigned_to_user(parser, token):
"""
Populates a template variable with the content with WorkflowState assignd
for the given criteria.
Usage::
{% get_assigned_to_user [limit] as [varname] for_user [context_var_containing_user_obj] %}
Examples::
{% get_assigned_to_user 10 ... | python | {
"resource": ""
} |
q250017 | forwards | train | def forwards(apps, schema_editor):
"""
Create initial recurrence rules.
"""
RecurrenceRule = apps.get_model('icekit_events', 'RecurrenceRule')
| python | {
"resource": ""
} |
q250018 | backwards | train | def backwards(apps, schema_editor):
"""
Delete initial recurrence rules.
"""
RecurrenceRule = apps.get_model('icekit_events', 'RecurrenceRule')
descriptions = [d | python | {
"resource": ""
} |
q250019 | environment | train | def environment(request=None):
"""
Return ``COMPRESS_ENABLED``, ``SITE_NAME``, and any settings listed
in ``ICEKIT_CONTEXT_PROCESSOR_SETTINGS`` as context.
"""
context = {
'COMPRESS_ENABLED': settings.COMPRESS_ENABLED,
'SITE_NAME': settings.SITE_NAME,
}
| python | {
"resource": ""
} |
q250020 | get_proxy_ancestor_classes | train | def get_proxy_ancestor_classes(klass):
"""
Return a set containing all the proxy model classes that are ancestors
of the given class.
NOTE: This implementation is for Django 1.7, it might need to work
differently for other versions especially | python | {
"resource": ""
} |
q250021 | PersonCreator.derive_and_set_name_fields_and_slug | train | def derive_and_set_name_fields_and_slug(
self, set_name_sort=True, set_slug=True
):
"""
Override this method from `CreatorBase` to handle additional name
fields for Person creators.
This method is called during `save()`
"""
super(PersonCreator, self).derive_a... | python | {
"resource": ""
} |
q250022 | LayoutQuerySet.for_model | train | def for_model(self, model, **kwargs):
"""
Return layouts that are allowed for the given model.
| python | {
"resource": ""
} |
q250023 | _order_by_pks | train | def _order_by_pks(qs, pks):
"""
Adjust the given queryset to order items according to the explicit ordering
of PKs provided.
This is a PostgreSQL-specific DB hack, based on:
blog.mathieu-leplatre.info/django-create-a-queryset-from-a-list-preserving-order.html
"""
pk_colname = '%s.%s' % (
... | python | {
"resource": ""
} |
q250024 | _queryset_iterator | train | def _queryset_iterator(qs):
"""
Override default iterator to wrap returned items in a publishing
sanity-checker "booby trap" to lazily raise an exception if DRAFT
items are mistakenly returned and mis-used in a public context
where only PUBLISHED items should be used.
This booby trap is added w... | python | {
"resource": ""
} |
q250025 | PublishingUrlNodeQuerySet.published | train | def published(self, for_user=UNSET, force_exchange=False):
"""
Apply additional filtering of published items over that done in
`PublishingQuerySet.published` to filter based on additional publising
date fields used by Fluent.
"""
if for_user is not UNSET:
retu... | python | {
"resource": ""
} |
q250026 | redis_from_url | train | def redis_from_url(url):
"""
Converts a redis URL used by celery into a `redis.Redis` object.
"""
# Makes sure that we only try to import redis when we need
# to use it
import redis
url = url or ""
parsed_url = urlparse(url)
if parsed_url.scheme != "redis":
return None
... | python | {
"resource": ""
} |
q250027 | ScoringContext.process_model_scores | train | def process_model_scores(self, model_names, root_cache,
include_features=False):
"""
Generates a score map for a set of models based on a `root_cache`.
This method performs no substantial IO, but may incur substantial CPU
usage.
:Parameters:
... | python | {
"resource": ""
} |
q250028 | ScoringContext._process_score | train | def _process_score(self, model_name, dependency_cache=None):
"""
Generates a score for a given model using the `dependency_cache`.
"""
version = self[model_name].version
start = time.time()
feature_values = self._solve_features(model_name, dependency_cache)
logge... | python | {
"resource": ""
} |
q250029 | ScoringContext.map_from_config | train | def map_from_config(cls, config, context_names,
section_key="scoring_contexts"):
"""
Loads a whole set of ScoringContext's from a configuration file
while maintaining a cache of model names. This aids in better memory
management and allows model aliases to be imp... | python | {
"resource": ""
} |
q250030 | build_event_set | train | def build_event_set(event):
"""
Turn an EventStream event into a set of event types that ORES
uses internally.
"""
event_set = set()
if re.match(r"([^\.]+.)?mediawiki\.revision-create$",
event['meta']['topic']):
event_set.add('edit')
user_groups = event.get('perf... | python | {
"resource": ""
} |
q250031 | build_precache_map | train | def build_precache_map(config):
"""
Build a mapping of contexts and models from the configuration
"""
precache_map = {}
ss_name = config['ores']['scoring_system']
for context in config['scoring_systems'][ss_name]['scoring_contexts']:
precache_map[context] = {}
for model in config... | python | {
"resource": ""
} |
q250032 | RevIdScorer.calculate_statistics | train | def calculate_statistics(self):
"Jam some data through to generate statistics"
rev_ids = range(0, 100, 1)
feature_values = zip(rev_ids, [0] * 100)
scores = [self.score(f) for f in feature_values]
labels = [s['prediction'] for s in | python | {
"resource": ""
} |
q250033 | read_hector_input | train | def read_hector_input(csv_file):
"""
Reads a Hector CSV file and returns it as a Pandas DataFrame.
| python | {
"resource": ""
} |
q250034 | write_hector_input | train | def write_hector_input(scenario, path=None):
"""
Writes a scenario DataFrame to a CSV emissions file as used in Hector.
Parameters
----------
scenario : DataFrame
DataFrame with emissions.
path: file-like object or path
Returns
-------
out : str
If no path is given ... | python | {
"resource": ""
} |
q250035 | read_hector_constraint | train | def read_hector_constraint(constraint_file):
"""
Reads a Hector contraint CSV file and returns it as a Pandas Series
""" | python | {
"resource": ""
} |
q250036 | read_hector_output | train | def read_hector_output(csv_file):
"""
Reads a Hector output stream CSV file and returns a wide DataFrame with
Hector output data.
"""
# Filter out spin-up values. In Hector 1.x RCP output streams years are
| python | {
"resource": ""
} |
q250037 | run | train | def run(scenario, config=None, base_config=None, outputs=None, return_config=False):
"""
Runs a scenario through the Hector climate model.
Parameters
----------
scenario : DataFrame
DataFrame with emissions. See ``pyhector.rcp26`` for an
example and :mod:`pyhector.units` for units o... | python | {
"resource": ""
} |
q250038 | Hector.config | train | def config(self, config):
"""Set config values from config dictionary."""
for section, data in config.items():
for variable, | python | {
"resource": ""
} |
q250039 | Hector.set_emissions | train | def set_emissions(self, scenario):
"""Set emissions from Pandas DataFrame."""
for section in emissions:
for source in emissions[section]:
if source not in scenario.columns:
| python | {
"resource": ""
} |
q250040 | requirements | train | def requirements(fname):
"""
Generator to parse requirements.txt file
Supports bits of extended pip format (git urls)
"""
with open(fname) as f:
for line in f:
match = re.search('#egg=(.*)$', line)
| python | {
"resource": ""
} |
q250041 | Session.score | train | def score(self, context, models, revids):
"""
Genetate scores for model applied to a sequence of revisions.
:Parameters:
context : str
The name of the context -- usually the database name of a wiki
models : `iterable`
The names of a models... | python | {
"resource": ""
} |
q250042 | principal_angle | train | def principal_angle(A,B):
"""
Find the principal angle between two subspaces
spanned by columns of A and B
"""
from numpy.linalg import qr, svd | python | {
"resource": ""
} |
q250043 | DiagonalRegression.resample | train | def resample(self, data, stats=None, mask=None, niter=None):
"""
Introduce a mask that allows for missing data
"""
stats = self._get_statistics(data, mask=mask) if | python | {
"resource": ""
} |
q250044 | sample_truncated_gaussian | train | def sample_truncated_gaussian(mu=0, sigma=1, lb=-np.Inf, ub=np.Inf):
"""
Sample a truncated normal with the specified params. This
is not the most stable way but it works as long as the
truncation region is not too far from the mean.
"""
# Broadcast arrays to be of the same shape
mu, sigma, ... | python | {
"resource": ""
} |
q250045 | CRPMixture.log_likelihood | train | def log_likelihood(self,x, K_extra=1):
"""
Estimate the log likelihood with samples from
the model. Draw k_extra components which were not populated by
the current model in order to create a truncated approximate
mixture model.
"""
x = np.asarray(x)
ks ... | python | {
"resource": ""
} |
q250046 | RingNode.debug_print | train | def debug_print(self):
"""
Prints the ring for debugging purposes.
"""
ring = self._fetch_all()
print('Hash ring "{key}" replicas:'.format(key=self.key))
now = time.time()
n_replicas = len(ring)
if ring:
print('{:10} {:6} {:7} {}'.format('St... | python | {
"resource": ""
} |
q250047 | RingNode.update | train | def update(self):
"""
Fetches the updated ring from Redis and updates the current ranges.
"""
ring = self._fetch()
n_replicas = len(ring)
replica_set = set([r[1] for r in self.replicas])
self.ranges = []
for n, (start, replica) in enumerate(ring):
... | python | {
"resource": ""
} |
q250048 | RingNode.contains | train | def contains(self, key):
"""
Returns a boolean indicating if this node is responsible for handling
the given key.
| python | {
"resource": ""
} |
q250049 | RingNode.gevent_start | train | def gevent_start(self):
"""
Helper method to start the node for gevent-based applications.
"""
import gevent
import gevent.select
| python | {
"resource": ""
} |
q250050 | RingNode.gevent_stop | train | def gevent_stop(self):
"""
Helper method to stop the node for gevent-based applications.
"""
import | python | {
"resource": ""
} |
q250051 | suggest_implied_attributes | train | def suggest_implied_attributes(prj):
"""
If given project contains what could be implied attributes, suggest that.
:param Iterable prj: Intent is a Project, but this could be any iterable
of strings to check for suitability of declaration as implied attr
:return list[str]: (likely empty) list o... | python | {
"resource": ""
} |
q250052 | check_bam | train | def check_bam(bam, o):
"""
Check reads in BAM file for read type and lengths.
:param str bam: BAM file path.
:param int o: Number of reads to look at for estimation.
"""
try:
p = sp.Popen(['samtools', 'view', bam], stdout=sp.PIPE)
# Count paired alignments
paired = 0
... | python | {
"resource": ""
} |
q250053 | grab_project_data | train | def grab_project_data(prj):
"""
From the given Project, grab Sample-independent data.
There are some aspects of a Project of which it's beneficial for a Sample
to be aware, particularly for post-hoc analysis. Since Sample objects
within a Project are mutually independent, though, each doesn't need ... | python | {
"resource": ""
} |
q250054 | import_from_source | train | def import_from_source(module_filepath):
"""
Import a module from a particular filesystem location.
:param str module_filepath: path to the file that constitutes the module
to import
:return module: module imported from the given location, named as indicated
:raises ValueError: if path prov... | python | {
"resource": ""
} |
q250055 | infer_delimiter | train | def infer_delimiter(filepath):
"""
From extension infer delimiter used in a separated values file.
:param str filepath: path to file about which to make inference
:return str | NoneType: extension if inference succeeded; else null | python | {
"resource": ""
} |
q250056 | is_null_like | train | def is_null_like(x):
"""
Determine whether an object is effectively null.
:param object x: Object for which null likeness is to be determined.
:return bool: Whether given object is effectively "null."
| python | {
"resource": ""
} |
q250057 | parse_ftype | train | def parse_ftype(input_file):
"""
Checks determine filetype from extension.
:param str input_file: String to check.
:return str: filetype (extension without dot prefix)
:raises TypeError: if file does not appear of a supported type
"""
if input_file.endswith(".bam"):
return "bam"
... | python | {
"resource": ""
} |
q250058 | parse_text_data | train | def parse_text_data(lines_or_path, delimiter=os.linesep):
"""
Interpret input argument as lines of data. This is intended to support
multiple input argument types to core model constructors.
:param str | collections.Iterable lines_or_path:
:param str delimiter: line separator used when parsing a ra... | python | {
"resource": ""
} |
q250059 | sample_folder | train | def sample_folder(prj, sample):
"""
Get the path to this Project's root folder for the given Sample.
:param attmap.PathExAttMap | Project prj: project with which sample is associated
| python | {
"resource": ""
} |
q250060 | standard_stream_redirector | train | def standard_stream_redirector(stream):
"""
Temporarily redirect stdout and stderr to another stream.
This can be useful for capturing messages for easier inspection, or
for rerouting and essentially ignoring them, with the destination as
something like an opened os.devnull.
:param FileIO[str]... | python | {
"resource": ""
} |
q250061 | Video.search | train | def search(
self,
q="yellow flower",
lang="en",
video_type="all",
category="",
min_width=0,
min_height=0,
editors_choice="false",
safesearch="false",
order="popular",
page=1,
p... | python | {
"resource": ""
} |
q250062 | quoted | train | def quoted(arg):
""" Given a string, return a quoted string as per RFC 3501, section 9.
Implementation copied from https://github.com/mjs/imapclient
(imapclient/imapclient.py), 3-clause BSD license
"""
if isinstance(arg, str):
arg = arg.replace('\\', '\\\\')
arg | python | {
"resource": ""
} |
q250063 | int2ap | train | def int2ap(num):
"""Convert integer to A-P string representation."""
val = ''
ap = 'ABCDEFGHIJKLMNOP'
num = int(abs(num))
while num:
| python | {
"resource": ""
} |
q250064 | time2internaldate | train | def time2internaldate(date_time):
"""Convert date_time to IMAP4 INTERNALDATE representation.
Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'. The
date_time argument can be a number (int or float) representing
seconds since epoch (as returned by time.time()), a 9-tuple
representing local time... | python | {
"resource": ""
} |
q250065 | _send_tasks_and_stop_queuing | train | def _send_tasks_and_stop_queuing(**kwargs):
"""Sends all delayed Celery tasks and stop queuing new ones for now."""
log.info('Stopping queueing tasks and sending already queued ones.')
_stop_queuing_tasks()
task_queue = _get_task_queue()
| python | {
"resource": ""
} |
q250066 | _append_task | train | def _append_task(t):
"""Append a task to the queue.
Expected argument is a tuple of the following form:
(task class, args, kwargs, extra kwargs).
This doesn't append to queue if the argument is already in the queue.
"""
task_queue = _get_task_queue()
if t not in task_queue:
| python | {
"resource": ""
} |
q250067 | Task.create_from_tuple | train | def create_from_tuple(cls, tube, the_tuple):
"""
Create task from tuple.
Returns `Task` instance.
"""
if the_tuple is None:
return
if not the_tuple.rowcount:
raise Queue.ZeroTupleException("Error creating task")
| python | {
"resource": ""
} |
q250068 | Task.update_from_tuple | train | def update_from_tuple(self, the_tuple):
"""
Update task from tuple.
"""
if not the_tuple.rowcount:
raise Queue.ZeroTupleException("Error updating task")
row = the_tuple[0]
if self.task_id != row[0]:
| python | {
"resource": ""
} |
q250069 | Task.peek | train | async def peek(self):
"""
Look at a task without changing its state.
Always returns `True`.
"""
| python | {
"resource": ""
} |
q250070 | Tube.cmd | train | def cmd(self, cmd_name):
"""
Returns tarantool queue command name for current tube.
"""
| python | {
"resource": ""
} |
q250071 | Queue.ack | train | async def ack(self, tube, task_id):
"""
Report task successful execution.
Ack is accepted only from the consumer, which took the task
for execution. If a consumer disconnects, | python | {
"resource": ""
} |
q250072 | Queue.tube | train | def tube(self, name):
"""
Create tube object, if not created before.
Returns `Tube` object.
"""
tube = self.tubes.get(name)
if tube is None:
| python | {
"resource": ""
} |
q250073 | RequestHandler.post | train | def post(self, endpoint='', url='', data=None, use_api_key=False, omit_api_version=False):
"""Perform a post to an API endpoint.
:param string endpoint: Target endpoint. (Optional).
:param string url: Override the endpoint and provide the full url (eg for pagination). (Optional).
:param... | python | {
"resource": ""
} |
q250074 | RequestHandler._request | train | def _request(self, request_method, endpoint='', url='', data=None, params=None, use_api_key=False, omit_api_version=False):
"""Perform a http request via the specified method to an API endpoint.
:param string request_method: Request method.
:param string endpoint: Target endpoint. (Optional).
... | python | {
"resource": ""
} |
q250075 | Client.change_participation_status | train | def change_participation_status(self, calendar_id, event_uid, status):
"""Changes the participation status for a calendar event
:param string calendar_id: The String Cronofy ID for the calendar to delete the event from.
:param string event_uid: A String uniquely identifying the event for your
... | python | {
"resource": ""
} |
q250076 | Client.create_notification_channel | train | def create_notification_channel(self, callback_url, calendar_ids=()):
"""Create a new channel for receiving push notifications.
:param string callback_url: The url that will receive push notifications.
Must not be longer than 128 characters and should be HTTPS.
:param tuple calendar_ids... | python | {
"resource": ""
} |
q250077 | Client.delete_all_events | train | def delete_all_events(self, calendar_ids=()):
"""Deletes all events managed through Cronofy from the all of the user's calendars.
:param tuple calendar_ids: List of calendar ids to delete events for. (Optional. Default empty tuple)
"""
params = {'delete_all': True}
| python | {
"resource": ""
} |
q250078 | Client.delete_event | train | def delete_event(self, calendar_id, event_id):
"""Delete an event from the specified calendar.
:param string calendar_id: ID of calendar to delete from.
:param string event_id: ID of event to delete.
"""
| python | {
"resource": ""
} |
q250079 | Client.delete_external_event | train | def delete_external_event(self, calendar_id, event_uid):
"""Delete an external event from the specified calendar.
:param string calendar_id: ID of | python | {
"resource": ""
} |
q250080 | Client.elevated_permissions | train | def elevated_permissions(self, permissions, redirect_uri=None):
"""Requests elevated permissions for a set of calendars.
:param tuple permissions - calendar permission dicts set each dict
must contain values for both `calendar_id` and `permission_level`
:param string redirect_uri - A u... | python | {
"resource": ""
} |
q250081 | Client.get_smart_invite | train | def get_smart_invite(self, smart_invite_id, recipient_email):
"""Gets the details for a smart invite.
:param string smart_invite_id: - A String uniquely identifying the event for your
application (note: this is NOT | python | {
"resource": ""
} |
q250082 | Client.application_calendar | train | def application_calendar(self, application_calendar_id):
"""Creates and Retrieves authorization for an application calendar
:param string application_calendar_id: The Id for this application calendar
:return: Dictionary containing auth tokens, expiration info, and response status.
:rtyp... | python | {
"resource": ""
} |
q250083 | Client.refresh_authorization | train | def refresh_authorization(self):
"""Refreshes the authorization tokens.
:return: Dictionary containing auth tokens, expiration info, and response status.
:rtype: ``dict``
"""
response = self.request_handler.post(
endpoint='oauth/token',
omit_api_version=T... | python | {
"resource": ""
} |
q250084 | Client.revoke_authorization | train | def revoke_authorization(self):
"""Revokes Oauth authorization."""
self.request_handler.post(
endpoint='oauth/token/revoke',
omit_api_version=True,
data={
'client_id': self.auth.client_id,
'client_secret': self.auth.client_secret,
| python | {
"resource": ""
} |
q250085 | Client.upsert_event | train | def upsert_event(self, calendar_id, event):
"""Inserts or updates an event for the specified calendar.
:param string calendar_id: ID of calendar to insert/update event into.
:param dict event: Dictionary of event data to send to cronofy.
"""
event['start'] = format_event_time(ev... | python | {
"resource": ""
} |
q250086 | Client.authorize_with_service_account | train | def authorize_with_service_account(self, email, scope, callback_url, state=None):
""" Attempts to authorize the email with impersonation from a service account
:param string email: the email address to impersonate
:param string callback_url: URL to callback with the OAuth code.
:param s... | python | {
"resource": ""
} |
q250087 | Client.real_time_scheduling | train | def real_time_scheduling(self, availability, oauth, event, target_calendars=()):
"""Generates an real time scheduling link to start the OAuth process with
an event to be automatically upserted
:param dict availability: - A dict describing the availability details for the event:
:pa... | python | {
"resource": ""
} |
q250088 | Client.real_time_sequencing | train | def real_time_sequencing(self, availability, oauth, event, target_calendars=()):
"""Generates an real time sequencing link to start the OAuth process with
an event to be automatically upserted
:param dict availability: - A dict describing the availability details for the event:
:s... | python | {
"resource": ""
} |
q250089 | Client.user_auth_link | train | def user_auth_link(self, redirect_uri, scope='', state='', avoid_linking=False):
"""Generates a URL to send the user for OAuth 2.0
:param string redirect_uri: URL to redirect the user to after auth.
:param string scope: The scope of the privileges you want the eventual access_token to grant.
... | python | {
"resource": ""
} |
q250090 | Client.validate | train | def validate(self, method, *args, **kwargs):
"""Validate authentication and values passed to the specified method.
Raises a PyCronofyValidationError on error. | python | {
"resource": ""
} |
q250091 | Pages.all | train | def all(self):
"""Return all results as a list by automatically fetching all pages.
:return: All results.
:rtype: ``list``
"""
results = self.data[self.data_type]
while self.current < self.total:
| python | {
"resource": ""
} |
q250092 | Pages.fetch_next_page | train | def fetch_next_page(self):
"""Retrieves the next page of data and refreshes Pages instance."""
result = self.request_handler.get(url=self.next_page_url).json()
| python | {
"resource": ""
} |
q250093 | check_datetime | train | def check_datetime(method, dictionary, fields, label=None):
"""Checks if the specified fields are formatted correctly if they have a value.
Throws an exception on incorrectly formatted fields.
:param dict dictionary: Dictionary to check.
:param typle fields: Fields to check.
:param string label: Di... | python | {
"resource": ""
} |
q250094 | validate | train | def validate(method, auth, *args, **kwargs):
"""Validate a method based on the METHOD_RULES above.
Raises a PyCronofyValidationError on error.
:param string method: Method being validated.
:param Auth auth: Auth instance.
:param *args: Positional arguments for method.
:param **kwargs: Keyword ... | python | {
"resource": ""
} |
q250095 | release | train | def release(part='patch'):
""" Automated software release workflow
* (Configurably) bumps the version number
* Tags the release
You can run it like::
$ fab release
which, by default, will create a 'patch' release (0.0.1 => 0.0.2).
You can also specify a patch level (patch, minor, ma... | python | {
"resource": ""
} |
q250096 | make_thumbnail_name | train | def make_thumbnail_name(image_name, extension):
"""Return name of the downloaded thumbnail, based on the extension."""
file_name, | python | {
"resource": ""
} |
q250097 | get_thumbnail_of_file | train | def get_thumbnail_of_file(image_name, width):
"""Return the file contents of the thumbnail of the given file."""
hdr = {'User-Agent': 'Python urllib2'}
url = make_thumb_url(image_name, width)
req = urllib2.Request(url, headers=hdr)
try:
logging.debug("Retrieving %s", url)
opened = ur... | python | {
"resource": ""
} |
q250098 | get_exception_based_on_api_message | train | def get_exception_based_on_api_message(message, image_name=""):
"""Return the exception matching the given API error message."""
msg_bigger_than_source = re.compile('Image was not scaled, is the requested width bigger than the source?')
msg_does_not_exist = re.compile('The source file .* does not exist')
... | python | {
"resource": ""
} |
q250099 | download_file | train | def download_file(image_name, output_path, width=DEFAULT_WIDTH):
"""Download a given Wikimedia Commons file."""
image_name = clean_up_filename(image_name)
logging.info("Downloading %s with width %s", image_name, width)
try:
contents, output_file_name = get_thumbnail_of_file(image_name, width)
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.