text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def length(
cls, request,
vector: (Ptypes.body,
Vector('The vector to analyse.'))) -> [
(200, 'Ok', Float),
(400, 'Wrong vector format')]:
'''Return the modulo of a vector.'''
log.info('Computing the length of vector {}'.format(vector)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def place(slot_name, dttime):
""" Set a timer to be published at the specified minute. """ |
dttime = datetime.strptime(dttime, '%Y-%m-%d %H:%M:%S')
dttime = dttime.replace(second=0, microsecond=0)
try:
area.context['timers'][dttime].add(slot_name)
except KeyError:
area.context['timers'][dttime] = {slot_name}
area.publish({'status': 'placed'}, slot=slot_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_table(table_name):
"""Return True if table exists, False otherwise.""" |
return db.engine.dialect.has_table(
db.engine.connect(),
table_name
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_migration_ctx(**kwargs):
"""Create an alembic migration context.""" |
env = EnvironmentContext(Config(), None)
env.configure(
connection=db.engine.connect(),
sqlalchemy_module_prefix='db.',
**kwargs
)
return env.get_context() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_operations(ctx=None, **kwargs):
"""Create an alembic operations object.""" |
if ctx is None:
ctx = create_migration_ctx(**kwargs)
operations = Operations(ctx)
operations.has_table = has_table
return operations |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def produce_upgrade_operations( ctx=None, metadata=None, include_symbol=None, include_object=None, **kwargs):
"""Produce a list of upgrade statements.""" |
if metadata is None:
# Note, all SQLAlchemy models must have been loaded to produce
# accurate results.
metadata = db.metadata
if ctx is None:
ctx = create_migration_ctx(target_metadata=metadata, **kwargs)
template_args = {}
imports = set()
_produce_migration_diffs... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handleArgs(self, event):
"""Nose2 hook for the handling the command line args""" |
# settings resolution order:
# command line > cfg file > environ
if self.djsettings:
os.environ['DJANGO_SETTINGS_MODULE'] = self.djsettings
if self.djconfig:
os.environ['DJANGO_CONFIGURATION'] = self.djconfig
# test for django-configurations package
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_signature(signature, private_key, full_path, payload):
""" Checks signature received and verifies that we are able to re-create it from the private key... |
if isinstance(private_key, bytes):
private_key = private_key.decode("ascii")
if isinstance(payload, bytes):
payload = payload.decode()
url_to_check = _strip_signature_from_url(signature, full_path)
computed_signature = apysigner.get_signature(private_key, url_to_check, payload)
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_param(key):
""" Parse the query param looking for filters Determine the field to filter on & the operator to be used when filtering. :param key: The q... |
regex = re.compile(r'filter\[([A-Za-z0-9_./]+)\]')
match = regex.match(key)
if match:
field_and_oper = match.groups()[0].split('__')
if len(field_and_oper) == 1:
return field_and_oper[0], 'eq'
elif len(field_and_oper) == 2:
return tuple(field_and_oper)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_field(param, fields):
""" Ensure the field exists on the model """ |
if '/' not in param.field and param.field not in fields:
raise InvalidQueryParams(**{
'detail': 'The filter query param of "%s" is not possible. The '
'resource requested does not have a "%s" field. Please '
'modify your request & retry.' % (param, p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_rel(param, rels):
""" Validate relationship based filters We don't support nested filters currently. FIX: Ensure the relationship filter field exis... |
if param.field.count('/') > 1:
raise InvalidQueryParams(**{
'detail': 'The filter query param of "%s" is attempting to '
'filter on a nested relationship which is not '
'currently supported.' % param,
'links': LINK,
'parameter... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_param(param):
# pylint: disable=too-many-branches """ Ensure the filter cast properly according to the operator """ |
detail = None
if param.oper not in goldman.config.QUERY_FILTERS:
detail = 'The query filter {} is not a supported ' \
'operator. Please change {} & retry your ' \
'request'.format(param.oper, param)
elif param.oper in goldman.config.GEO_FILTERS:
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(req, model):
""" Return an array of Filter objects. """ |
fields = model.all_fields
rels = model.relationships
params = []
for key, val in req.params.items():
try:
field, oper = _parse_param(key)
except (TypeError, ValueError):
continue
try:
local_field, foreign_filter = field.split('/')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def git_check():
"""Check for uncomitted changes""" |
git_status = subprocess.check_output(['git', 'status', '--porcelain'])
if len(git_status) is 0:
print(Fore.GREEN + 'All changes committed' + Style.RESET_ALL)
else:
exit(Fore.RED + 'Please commit all files to continue') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_version_number(update_level='patch'):
"""Update version number Returns a semantic_version object""" |
"""Find current version"""
temp_file = version_file().parent / ("~" + version_file().name)
with open(str(temp_file), 'w') as g:
with open(str(version_file()), 'r') as f:
for line in f:
version_matches = bare_version_re.match(line)
if version_matches:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_release_to_changelog(version):
"""Add release line at the top of the first list it finds Assumes your changelog in managed with `releases`""" |
temp_file = changelog_file().parent / ("~" + changelog_file().name)
now = datetime.today()
release_added = False
with open(str(temp_file), 'w') as g:
with open(str(changelog_file()), 'r') as f:
for line in f:
list_match = list_match_re.match(line)
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_sphinx():
"""Runs Sphinx via it's `make html` command""" |
old_dir = here_directory()
os.chdir(str(doc_directory()))
doc_status = subprocess.check_call(['make', 'html'], shell=True)
os.chdir(str(old_dir)) # go back to former working directory
if doc_status is not 0:
exit(Fore.RED + 'Something broke generating your documentation...') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_tasks(target=None):
"""Returns a list of all the projects and tasks available in the `acorn` database directory. Args: target (str):
directory to list ... |
from os import getcwd, chdir
from glob import glob
original = getcwd()
if target is None:# pragma: no cover
target = _dbdir()
chdir(target)
result = {}
for filename in glob("*.*.json"):
project, task = filename.split('.')[0:2]
if project not in result:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_task(project_, task_):
"""Sets the active project and task. All subsequent logging will be saved to the database with that project and task. Args: projec... |
global project, task
project = project_
task = task_
msg.okay("Set project name to {}.{}".format(project, task), 2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup():
"""Saves all the open databases to JSON so that the kernel can be shut down without losing in-memory collections. """ |
failed = {}
success = []
for dbname, db in dbs.items():
try:
#Force the database save, even if the time hasn't elapsed yet.
db.save(True)
success.append(dbname)
except: # pragma: no cover
import sys, traceback
xcls, xerr = sys.exc_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dbdir():
"""Returns the path to the directory where acorn DBs are stored. """ |
global dbdir
from os import mkdir, path, getcwd, chdir
if dbdir is None:
from acorn.config import settings
config = settings("acorn")
if (config.has_section("database") and
config.has_option("database", "folder")):
dbdir = config.get("database", "folder"... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _json_clean(d):
"""Cleans the specified python `dict` by converting any tuple keys to strings so that they can be serialized by JSON. Args: d (dict):
python... |
result = {}
compkeys = {}
for k, v in d.items():
if not isinstance(k, tuple):
result[k] = v
else:
#v is a list of entries for instance methods/constructors on the
#UUID of the key. Instead of using the composite tuple keys, we
#switch them for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_image(byteio, imgfmt):
"""Saves the specified image to disk. Args: byteio (bytes):
image bytes to save to disk. imgfmt (str):
used as the extension of... |
from os import path, mkdir
ptdir = "{}.{}".format(project, task)
uuid = str(uuid4())
#Save the image within the project/task specific folder.
idir = path.join(dbdir, ptdir)
if not path.isdir(idir):
mkdir(idir)
ipath = path.join(idir, "{}.{}".format(uuid, imgfmt))
with ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_uuid(self, uuid):
"""Logs the object with the specified `uuid` to `self.uuids` if possible. Args: uuid (str):
string value of :meth:`uuid.uuid4` value f... |
#We only need to try and describe an object once; if it is already in
#our database, then just move along.
if uuid not in self.uuids and uuid in uuids:
self.uuids[uuid] = uuids[uuid].describe() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_option(option, default=None, cast=None):
"""Returns the option value for the specified acorn database option. """ |
from acorn.config import settings
config = settings("acorn")
if (config.has_section("database") and
config.has_option("database", option)):
result = config.get("database", option)
if cast is not None:
result = cast(result)
else... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self):
"""Deserializes the database from disk. """ |
#We load the database even when it is not configured to be
#writable. After all, the user may decide part-way through a session to
#begin writing again, and then we would want a history up to that point
#to be valid.
from os import path
if path.isfile(self.dbpath):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, force=False):
"""Serializes the database file to disk. Args: force (bool):
when True, the elapsed time since last save is ignored and the databas... |
from time import time
# Since the DBs can get rather large, we don't want to save them every
# single time a method is called. Instead, we only save them at the
# frequency specified in the global settings file.
from datetime import datetime
savefreq = TaskDB.get_option... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe(self):
"""Returns a dictionary describing the object based on its type. """ |
result = {}
#Because we created an Instance object, we already know that this object
#is not one of the regular built-in types (except, perhaps, for list,
#dict and set objects that can have their tracking turned on).
#For objects that are instantiated by the user in __main__, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def load_module(name, filename):
'''Load a module into name given its filename'''
if sys.version_info < (3, 5):
import imp
import warnings
with warnings.catch_warnings(): # Required for Python 2.7
warnings.simplefilter("ignore", RuntimeWarning)
return imp.load_so... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_code(function_index=1, function_name=None):
""" This will return the code of the calling function function_index of 2 will give the parent of the caller... |
info = function_info(function_index + 1, function_name)
with open(info['file'], 'r') as fn:
return fn.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relevant_kwargs(function, exclude_keys='self', exclude_values=None, extra_values=None):
""" This will return a dictionary of local variables that are paramet... |
args = function_args(function)
locals_values = function_kwargs(function_index=2, exclude_keys=exclude_keys)
if extra_values:
locals_values.update(extra_values)
return {k: v for k, v in locals_values.items() if k in args} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_feature(fc):
'''Builds a new `StringCounter` from the many `StringCounters` in the
input `fc`. This StringCounter will define one of the targets for
the `MultinomialNB` classifier.
This crucial function decides the relative importance of features
extracted by the ETL pipeline. This is es... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rx_int_extra(rxmatch):
""" We didn't just match an int but the int is what we need. """ |
rxmatch = re.search("\d+", rxmatch.group(0))
return int(rxmatch.group(0)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_filename_decorator(fn):
""" A decorator of `prepare_filename` method 1. It automatically assign `settings.ROUGHPAGES_INDEX_FILENAME` if the `normaliz... |
@wraps(fn)
def inner(self, normalized_url, request):
ext = settings.ROUGHPAGES_TEMPLATE_FILE_EXT
if not normalized_url:
normalized_url = settings.ROUGHPAGES_INDEX_FILENAME
filenames = fn(self, normalized_url, request)
filenames = [x + ext for x in filenames if x]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def smart_query_string(parser, token):
""" Outputs current GET query string with additions appended. Additions are provided in token pairs. """ |
args = token.split_contents()
additions = args[1:]
addition_pairs = []
while additions:
addition_pairs.append(additions[0:2])
additions = additions[2:]
return SmartQueryStringNode(addition_pairs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_thread(self, target, args=(), kwargs=None, priority=0):
""" To make sure applications work with the old name """ |
return self.add_task(target, args, kwargs, priority) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_projects(folders, folder = None, user = None):
'''List all folders or all subfolders of a folder.
If folder is provided, this method will output a list of subfolders
contained by it. Otherwise, a list of all top-level folders is produced.
:param folders: reference to folder.Folders instance
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_supervisor(func: types.AnyFunction) -> types.Supervisor: """Get the appropriate supervisor to use and pre-apply the function. Args: func: A function. """ |
if not callable(func):
raise TypeError("func is not callable")
if asyncio.iscoroutinefunction(func):
supervisor = _async_supervisor
else:
supervisor = _sync_supervisor
return functools.partial(supervisor, func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def _async_supervisor(func, animation_, step, *args, **kwargs):
"""Supervisor for running an animation with an asynchronous function. Args: func: A functio... |
with ThreadPoolExecutor(max_workers=2) as pool:
with _terminating_event() as event:
pool.submit(animate_cli, animation_, step, event)
result = await func(*args, **kwargs)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def concatechain(*generators: types.FrameGenerator, separator: str = ''):
"""Return a generator that in each iteration takes one value from each of the supplied ... |
while True:
try:
next_ = [next(gen) for gen in generators]
yield separator.join(next_)
except StopIteration as exc:
return exc.value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare(self, control_result, experimental_result):
_compare = getattr(self, '_compare', lambda x, y: x == y) """ Return true if the results match. """ |
return (
# Mismatch if only one of the results returned an error, or if
# different types of errors were returned.
type(control_result.error) is type(experimental_result.error) and
_compare(control_result.value, experimental_result.value)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_inst_id(self):
""" Fetches the institute id of the RU """ |
try:
for d in msgpack.unpack(urllib2.urlopen(
"%s/list/institutes?format=msgpack" % self.url)):
if d['name'] == 'Radboud Universiteit Nijmegen':
return d['id']
except IOError, e: # urllib2 exceptions are a subclass of IOError
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_ip(source='aws'):
''' a method to get current public ip address of machine '''
if source == 'aws':
source_url = 'http://checkip.amazonaws.com/'
else:
raise Exception('get_ip currently only supports queries to aws')
import requests
try:
response = reques... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_parameter(samples, sample_period):
"""Create a HTK Parameter object from an array of samples and a samples period :param samples (list of lists or arr... |
parm_kind_str = 'USER'
parm_kind = _htk_str_to_param(parm_kind_str)
parm_kind_base, parm_kind_opts = _htk_str_to_param(parm_kind_str)
meta = ParameterMeta(n_samples=len(samples),
samp_period=sample_period,
samp_size=len(samples[0]) * 4, # size in byt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_mlf(filename, utf8_normalization=None):
"""Load an HTK Master Label File. :param filename: The filename of the MLF file. :param utf8_normalization: None... |
with codecs.open(filename, 'r', 'string_escape') as f:
data = f.read().decode('utf8')
if utf8_normalization:
data = unicodedata.normalize(utf8_normalization, data)
mlfs = {}
for mlf_object in HTK_MLF_RE.finditer(data):
mlfs[mlf_object.group('file')] = [[Label(**mo.group... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_mlf(mlf, output_filename):
"""Save an HTK Master Label File. :param mlf: MLF dictionary containing a mapping from file to list of annotations. :param ou... |
with codecs.open(output_filename, 'w', 'utf-8') as f:
f.write(u'#!MLF!#\n')
for k, v in mlf.items():
f.write(u'"{}"\n'.format(k))
for labels in v:
for label in labels:
line = u'{start} {end} {symbol} ' \
u'{logli... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Test code called from commandline""" |
model = load_model('../data/hmmdefs')
hmm = model.hmms['r-We']
for state_name in hmm.state_names:
print(state_name)
state = model.states[state_name]
print(state.means_)
print(model)
model2 = load_model('../data/prior.hmm1mixSI.rate32')
print(model2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_lower(cls):
# NOQA """ Return a list of all the fields that should be lowercased This is done on fields with `lower=True`. """ |
email = cls.get_fields_by_class(EmailType)
lower = cls.get_fields_by_prop('lower', True) + email
return list(set(email + lower)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_fields_by_class(cls, field_class):
""" Return a list of field names matching a field class :param field_class: field class object :return: list """ |
ret = []
for key, val in getattr(cls, '_fields').items():
if isinstance(val, field_class):
ret.append(key)
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_fields_with_prop(cls, prop_key):
""" Return a list of fields with a prop key defined Each list item will be a tuple of field name containing the prop key... |
ret = []
for key, val in getattr(cls, '_fields').items():
if hasattr(val, prop_key):
ret.append((key, getattr(val, prop_key)))
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_exceptions(cls, errors):
""" Convert the validation errors into ValidationFailure exc's Transform native schematics validation errors into a goldman Valid... |
ret = []
for key, val in errors.items():
if key in cls.relationships:
attr = '/data/relationships/%s' % key
else:
attr = '/data/attributes/%s' % key
for error in val:
ret.append(ValidationFailure(attr, detail=error))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dirty_fields(self):
""" Return an array of field names that are dirty Dirty means if a model was hydrated first from the store & then had field values change... |
dirty_fields = []
for field in self.all_fields:
if field not in self._original:
dirty_fields.append(field)
elif self._original[field] != getattr(self, field):
dirty_fields.append(field)
return dirty_fields |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(self, data, clean=False, validate=False):
""" Merge a dict with the model This is needed because schematics doesn't auto cast values when assigned. Thi... |
try:
model = self.__class__(data)
except ConversionError as errors:
abort(self.to_exceptions(errors.messages))
for key, val in model.to_native().items():
if key in data:
setattr(self, key, val)
if validate:
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_primitive(self, load_rels=None, sparse_fields=None, *args, **kwargs):
""" Override the schematics native to_primitive method :param loads_rels: List of fi... |
if load_rels:
for rel in load_rels:
getattr(self, rel).load()
data = super(Model, self).to_primitive(*args, **kwargs)
if sparse_fields:
for key in data.keys():
if key not in sparse_fields:
del data[key]
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stash_split(fqdn, result, *argl, **argd):
"""Stashes the split between training and testing sets so that it can be used later for automatic scoring of the mo... |
global _splits
if fqdn == "sklearn.cross_validation.train_test_split":
key = id(result[1])
_splits[key] = result
#We don't actually want to return anything for the analysis; we are using it
#as a hook to save pointers to the dataset split so that we can easily
#analyze performance ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _machine_fqdn(machine):
"""Returns the FQDN of the given learning machine. """ |
from acorn.logging.decoration import _fqdn
if hasattr(machine, "__class__"):
return _fqdn(machine.__class__, False)
else: # pragma: no cover
#See what FQDN can get out of the class instance.
return _fqdn(machine) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit(fqdn, result, *argl, **argd):
"""Analyzes the result of a generic fit operation performed by `sklearn`. Args: fqdn (str):
full-qualified name of the met... |
#Check the arguments to see what kind of data we are working with, then
#choose the appropriate function below to return the analysis dictionary.
#The first positional argument will be the instance of the machine that was
#used. Check its name against a list.
global _machines
out = None
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def predict(fqdn, result, *argl, **argd):
"""Analyzes the result of a generic predict operation performed by `sklearn`. Args: fqdn (str):
full-qualified name of... |
#Check the arguments to see what kind of data we are working with, then
#choose the appropriate function below to return the analysis dictionary.
out = None
if len(argl) > 0:
machine = argl[0]
if isclassifier(machine):
out = classify_predict(fqdn, result, None, *argl, **argd... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_auto_predict(machine, X, *args):
"""Performs an automatic prediction for the specified machine and returns the predicted values. """ |
if auto_predict and hasattr(machine, "predict"):
return machine.predict(X) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generic_fit(fqdn, result, scorer, yP=None, *argl, **argd):
"""Performs the generic fit tests that are common to both classifier and regressor; uses `scorer`... |
out = None
if len(argl) > 0:
machine = argl[0]
out = {}
if hasattr(machine, "best_score_"):
out["score"] = machine.best_score_
#With fitting it is often useful to know how well the fitting set was
#matched (by trying to predict a score on it). We... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _percent_match(result, out, yP=None, *argl):
"""Returns the percent match for the specified prediction call; requires that the data was split before using an... |
if len(argl) > 1:
if yP is None:
Xt = argl[1]
key = id(Xt)
if key in _splits:
yP = _splits[key][3]
if yP is not None:
import math
out["%"] = round(1.-sum(abs(yP - result))/float(len(result)), 3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def path(self):
"""Getter property for the URL path to this Task. :rtype: string :returns: The URL path to this task. """ |
if not self.id:
raise ValueError('Cannot determine path without a task id.')
return self.path_helper(self.taskqueue.path, self.id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, client=None):
"""Deletes a task from Task Queue. :type client: :class:`gcloud.taskqueue.client.Client` or ``NoneType`` :param client: Optional. ... |
return self.taskqueue.delete_task(self.id, client=client) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, new_lease_time, client=None):
"""Update the duration of a task lease :type new_lease_time: int :param new_lease_time: the new lease time in seco... |
return self.taskqueue.update_task(self.id, new_lease_time=new_lease_time, client=client) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def description(self):
"""The description for this task. See: https://cloud.google.com/appengine/docs/python/taskqueue/rest/tasks :rtype: string :returns: The de... |
if self._description is None:
if 'payloadBase64' not in self._properties:
self._properties = self.taskqueue.get_task(id=self.id)._properties
self._description = base64.b64decode(self._properties.get('payloadBase64', b'')).decode("ascii")
return self._description |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def time_enqueued(self):
"""Retrieve the timestamp at which the task was enqueued. See: https://cloud.google.com/appengine/docs/python/taskqueue/rest/tasks :rtyp... |
value = self._properties.get('enqueueTimestamp')
if value is not None:
return _datetime_from_microseconds(int(value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conv2d(self, x_in: Connection, w_in: Connection, receptive_field_size, filters_number, stride=1, padding=1, name=""):
""" Computes a 2-D convolution given 4-... |
x_cols = self.tensor_3d_to_cols(x_in, receptive_field_size, stride=stride, padding=padding)
mul = self.transpose(self.matrix_multiply(x_cols, w_in), 0, 2, 1)
#output_width = self.sum(self.div(self.sum(self.sum(self.shape(x_in, 2), self.constant(-1 * receptive_field_size)),
# ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, hcont, value, score = None):
""" If sort_field is specified, score must be None. If sort_field is not specified, score is mandatory. """ |
assert (score is None) != (self.field.sort_field is None)
if score is None:
score = getattr(value, self.field.sort_field.name)
ContainerFieldWriter.append(self, hcont, value, score) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_file(aws_access_key_id, aws_secret_access_key, bucket_name, file, s3_folder):
""" copies file to bucket s3_folder """ |
# Connect to the bucket
bucket = s3_bucket(aws_access_key_id, aws_secret_access_key, bucket_name)
key = boto.s3.key.Key(bucket)
if s3_folder:
target_name = '%s/%s' % (s3_folder, os.path.basename(file))
else:
target_name = os.path.basename(file)
key.key = target_name
pri... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
""" We here demostrate the basic functionality of barrett. We use a global scan of scalar dark matter as an example. The details aren't really import... |
dataset = 'RD'
observables = ['log(<\sigma v>)', '\Omega_{\chi}h^2', 'log(\sigma_p^{SI})']
var = ['log(m_{\chi})']
var += ['log(C_1)', 'log(C_2)', 'log(C_3)', 'log(C_4)', 'log(C_5)', 'log(C_6)']
var += observables
plot_vs_mass(dataset, observables, 'mass_vs_observables.png')
plot_oneD(da... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pairplot(dataset, vars, filename, bins=60):
""" Plot a matrix of the specified variables with all the 2D pdfs and 1D pdfs. """ |
n = len(vars)
fig, axes = plt.subplots(nrows=n, ncols=n)
plt.subplots_adjust(wspace=0.1, hspace=0.1)
for i, x in enumerate(vars):
for j, y in enumerate(vars):
print(((x, y), (i, j)))
ax = axes[j,i]
if j < i:
ax.axis('off')
co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_vs_mass(dataset, vars, filename, bins=60):
""" Plot 2D marginalised posteriors of the 'vars' vs the dark matter mass. We plot the one sigma, and two sig... |
n = len(vars)
fig, axes = plt.subplots(nrows=n,
ncols=1,
sharex='col',
sharey=False)
plt.subplots_adjust(wspace=0, hspace=0)
m = 'log(m_{\chi})'
for i, y in enumerate(vars):
ax = axes[i]
P = p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_oneD(dataset, vars, filename, bins=60):
""" Plot 1D marginalised posteriors for the 'vars' of interest.""" |
n = len(vars)
fig, axes = plt.subplots(nrows=n,
ncols=1,
sharex=False,
sharey=False)
for i, x in enumerate(vars):
ax = axes[i]
P = posterior.oneD(dataset+'.h5', x, limits=limits(x), bins=bins)
P... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_logger(self):
""" Enables the root logger and configures extra loggers. """ |
level = self.real_level(self.level)
logging.basicConfig(level=level)
self.set_logger(self.name, self.level)
config.dictConfig(self.config)
self.logger = logging.getLogger(self.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_logger(self, logger_name, level, handler=None):
""" Sets the level of a logger """ |
if 'loggers' not in self.config:
self.config['loggers'] = {}
real_level = self.real_level(level)
self.config['loggers'][logger_name] = {'level': real_level}
if handler:
self.config['loggers'][logger_name]['handlers'] = [handler] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_event(self, event_name, event_level, message):
""" Registers an event so that it can be logged later. """ |
self.events[event_name] = (event_level, message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_iso8601(dt, tz=None):
""" Returns an ISO-8601 representation of a given datetime instance. '2014-10-01T23:21:33.718508Z' :param dt: a :class:`~datetime.da... |
if tz is not None:
dt = dt.replace(tzinfo=tz)
iso8601 = dt.isoformat()
# Naive datetime objects usually don't have info about timezone.
# Let's assume it's UTC and add Z to the end.
if re.match(r'.*(Z|[+-]\d{2}:\d{2})$', iso8601) is None:
iso8601 += 'Z'
return iso8601 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_dst(dt):
""" Returns True if a given datetime object represents a time with DST shift. """ |
# we can't use `dt.timestamp()` here since it requires a `utcoffset`
# and we don't want to get into a recursive loop
localtime = time.localtime(time.mktime((
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dst(self, dt):
""" Returns a difference in seconds between standard offset and dst offset. """ |
if not self._is_dst(dt):
return datetime.timedelta(0)
offset = time.timezone - time.altzone
return datetime.timedelta(seconds=-offset) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _to_camelcase(input_string):
''' a helper method to convert python to camelcase'''
camel_string = ''
for i in range(len(input_string)):
if input_string[i] == '_':
pass
elif not camel_string:
camel_string += input_string[i].upper()
elif input_string[i-1] ==... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _to_python(input_string):
''' a helper method to convert camelcase to python'''
python_string = ''
for i in range(len(input_string)):
if not python_string:
python_string += input_string[i].lower()
elif input_string[i].isupper():
python_string += '_%s' % input_stri... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, callback_url):
"""Register a new Subscription on this collection's parent object. Args: callback_url (str):
URI of an active endpoint which can... |
resource = self.resource.create({'subscribed_to': 'address',
'callback_url': callback_url})
subscription = self.wrap(resource)
self.add(subscription)
return subscription |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def match(self, seq, **kwargs):
'''If the schema matches seq, returns a list of the matched objects.
Otherwise, returns MatchFailure instance.
'''
strict = kwargs.get('strict', False)
top_level = kwargs.get('top_level', True)
match = kwargs.get('match', list())
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def downloads_per_year(collection, code, raw=False):
""" This method retrieve the total of downloads per year. arguments collection: SciELO 3 letters Acronym cod... |
tc = ThriftClient()
body = {"query": {"filtered": {}}}
fltr = {}
query = {
"query": {
"bool": {
"must": [
{
"match": {
"collection": collection
}
}... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def word_wrap(self, text, width=1023):
""" A simple word wrapping greedy algorithm that puts as many words into a single string as possible. """ |
substrings = []
string = text
while len(string) > width:
index = width - 1
while not string[index].isspace():
index = index - 1
line = string[0:index]
substrings.append(line)
string = string[index + 1:]
subs... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def speak(self, text):
""" The main function to convert text into speech. """ |
if not self.is_valid_string(text):
raise Exception("%s is not ISO-8859-1 compatible." % (text))
# Maximum allowable 1023 characters per message
if len(text) > 1023:
lines = self.word_wrap(text, width=1023)
for line in lines:
self.queue.put("S... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_site(self, url, headers, cookies, timeout, driver_args, driver_kwargs):
""" Try and return page content in the requested format using selenium """ |
try:
# **TODO**: Find what exception this will throw and catch it and call
# self.driver.execute_script("window.stop()")
# Then still try and get the source from the page
self.driver.set_page_load_timeout(timeout)
self.driver.get(url)
h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_one(self, aws_syncr, amazon, key):
"""Make sure this key is as defined""" |
key_info = amazon.kms.key_info(key.name, key.location)
if not key_info:
amazon.kms.create_key(key.name, key.description, key.location, key.grant, key.policy.document)
else:
amazon.kms.modify_key(key_info, key.name, key.description, key.location, key.grant, key.policy.doc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _walk(self, root_path=''):
''' an iterator method which walks the file structure of the dropbox collection '''
title = '%s._walk' % self.__class__.__name__
if root_path:
root_path = '/%s' % root_path
try:
response = self.dropbox.files_list_folder(path=ro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_stdin():
""" Generator for reading from standard input in nonblocking mode. Other ways of reading from ``stdin`` in python waits, until the buffer is b... |
line = sys.stdin.readline()
while line:
yield line
line = sys.stdin.readline() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_line(line):
""" Convert one line from the extended log to dict. Args: line (str):
Line which will be converted. Returns: dict: dict with ``timestamp`... |
line, timestamp = line.rsplit(",", 1)
line, command = line.rsplit(",", 1)
path, username = line.rsplit(",", 1)
return {
"timestamp": timestamp.strip(),
"command": command.strip(),
"username": username.strip(),
"path": path,
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_log(file_iterator):
""" Process the extended ProFTPD log. Args: file_iterator (file):
any file-like iterator for reading the log or stdin (see :func... |
for line in file_iterator:
if "," not in line:
continue
parsed = _parse_line(line)
if not parsed["command"].upper() in ["DELE", "DEL"]:
continue
# don't react to anything else, than trigger in form of deleted
# "lock" file
if os.path.basena... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(filename):
""" Open `filename` and start processing it line by line. If `filename` is none, process lines from `stdin`. """ |
if filename:
if not os.path.exists(filename):
logger.error("'%s' doesn't exists!" % filename)
sys.stderr.write("'%s' doesn't exists!\n" % filename)
sys.exit(1)
logger.info("Processing '%s'" % filename)
for ir in process_log(sh.tail("-f", filename, _iter=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(self, data):
""" Invoke the serializer These are common things for all serializers. Mostly, stuff to do with managing headers. The data passed in m... |
if not self.resp.content_type:
self.resp.set_header('Content-Type', getattr(self, 'MIMETYPE')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def printData(self, output = sys.stdout):
"""Output all the file data to be written to any writable output""" |
self.printDatum("Name : ", self.fileName, output)
self.printDatum("Author : ", self.author, output)
self.printDatum("Repository : ", self.repository, output)
self.printDatum("Category : ", self.category, output)
self.printDatum("Downloads : ", self.downloads, output)
self.printD... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raise_errors_on_nested_writes(method_name, serializer, validated_data):
""" Give explicit errors when users attempt to pass writable nested data. If we don't... |
# Ensure we don't have a writable nested field. For example:
#
# class UserSerializer(ModelSerializer):
# ...
# profile = ProfileSerializer()
assert not any(
isinstance(field, BaseSerializer) and
(key in validated_data) and
isinstance(validated_data[key], (list,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def many_init(cls, *args, **kwargs):
""" This method implements the creation of a `ListSerializer` parent class when `many=True` is used. You can customize it if... |
allow_empty = kwargs.pop('allow_empty', None)
child_serializer = cls(*args, **kwargs)
list_kwargs = {
'child': child_serializer,
}
if allow_empty is not None:
list_kwargs['allow_empty'] = allow_empty
list_kwargs.update({
key: value for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_value(self, dictionary):
""" Given the input dictionary, return the field value. """ |
# We override the default field access in order to support
# lists in HTML forms.
if html.is_html_input(dictionary):
return html.parse_html_list(dictionary, prefix=self.field_name)
return dictionary.get(self.field_name, empty) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_field_names(self, declared_fields, info):
""" Returns the list of all field names that should be created when instantiating this serializer class. This i... |
fields = getattr(self.Meta, 'fields', None)
exclude = getattr(self.Meta, 'exclude', None)
if fields and fields != ALL_FIELDS and not isinstance(fields, (list, tuple)):
raise TypeError(
'The `fields` option must be a list or tuple or "__all__". '
'Got... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_standard_field(self, field_name, model_field):
""" Create regular model fields. """ |
field_mapping = ClassLookupDict(self.serializer_field_mapping)
field_class = field_mapping[model_field]
field_kwargs = get_field_kwargs(field_name, model_field)
if 'choices' in field_kwargs:
# Fields with choices get coerced into `ChoiceField`
# instead of usin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.