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 static_cdn_tag(path, cdn, cdn_only=False):
""" Return the URL of a static file, with handling of offline mode. Usage: ``{% %}`` """ |
clean_path = path.lstrip("/")
if getattr(settings, "OFFLINE", False):
return static_url(join("vendor", clean_path))
elif cdn_only:
return cdn
return urljoin(cdn, clean_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 on_get(resc, req, resp):
""" Get the models identified by query parameters We return an empty list if no models are found. """ |
signals.pre_req.send(resc.model)
signals.pre_req_search.send(resc.model)
models = goldman.sess.store.search(resc.rtype, **{
'filters': req.filters,
'pages': req.pages,
'sorts': req.sorts,
})
props = to_rest_models(models, includes=req.includes)
resp.serialize(props)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_post(resc, req, resp):
""" Deserialize the payload & create the new single item """ |
signals.pre_req.send(resc.model)
signals.pre_req_create.send(resc.model)
props = req.deserialize()
model = resc.model()
from_rest(model, props)
goldman.sess.store.create(model)
props = to_rest_model(model, includes=req.includes)
resp.last_modified = model.updated
resp.location =... |
<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_credentials(self, credentials):
""" Reads credentials from configuration parameters. Each section represents an individual CredentialParams :param crede... |
self._items.clear()
for key in credentials.get_key_names():
value = credentials.get_as_nullable_string(key)
self._items.append(CredentialParams.from_tuples([key, 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 store(self, correlation_id, key, credential):
""" Stores credential parameters into the store. :param correlation_id: (optional) transaction id to trace exec... |
if credential != None:
self._items.put(key, credential)
else:
self._items.remove(key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def CheckInputArgs(*interfaces):
"""Must provide at least one interface, the last one may be repeated. """ |
l = len(interfaces)
def wrapper(func):
def check_args(self, *args, **kw):
for i in range(len(args)):
if (l > i and interfaces[i].providedBy(args[i])) or interfaces[-1].providedBy(args[i]):
continue
if l > i: raise TypeError, 'arg %s does n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def group_by_key_func(iterable, key_func):
""" Create a dictionary from an iterable such that the keys are the result of evaluating a key function on elements of... |
result = defaultdict(list)
for item in iterable:
result[key_func(item)].append(item)
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 formatedTime(ms):
""" convert milliseconds in a human readable time '1m' '16m 40s' '2d 7h 33m 20.123s' """ |
if ms:
s = ms / 1000.0
m, s = divmod(s, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
out = ''
if d:
out += '%gd ' % d
if h:
out += '%gh ' % h
if m:
out += '%gm ' % m
if s:
out += '%gs ' % 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 _check_connectivity(self, err):
''' a method to check connectivity as source of error '''
try:
import requests
requests.get(self.uptime_ssl)
except:
from requests import Request
request_object = Request(method='GET', url=self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _request(self, **kwargs):
''' a helper method for processing all request types '''
response = None
error = ''
code = 0
# send request
from requests import request
try:
response = request(**kwargs)
# handle... |
<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_request(self, url, params=None, **kwargs):
''' a method to catch and report http get request connectivity errors '''
# construct request kwargs
request_kwargs = {
'method': 'GET',
'url': url,
'params': params
}
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _post_request(self, url, data=None, json=None, **kwargs):
''' a method to catch and report http post request connectivity errors '''
# construct request kwargs
request_kwargs = {
'method': 'POST',
'url': url,
'data': data,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _options_request(self, url, **kwargs):
''' a method to catch and report http options request connectivity errors '''
# construct request kwargs
request_kwargs = {
'method': 'OPTIONS',
'url': url
}
for key, value in kwargs.items()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def find_soft_selectors(ids_and_clean_visible, start_num_tokens='10',
max_num_tokens='20', filter_punctuation='0'):
'''External interface for dossier.models.soft_selectors.
This at scans through `num_tokens` values between
`start_num_tokens` and `max_num_tokens` and calls
`find_... |
<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_ngram_corpus(corpus_clean_visibles, num_tokens, filter_punctuation,
zoning_rules=False):
'''takes a list of clean_visible texts, such as from StreamItems or
FCs, tokenizes all the texts, and constructs n-grams using
`num_tokens` sized windows.
``corpus_clean_visibles`` --... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def ids_and_clean_visible_from_streamcorpus_chunk_path(corpus_path):
'''converts a streamcorpus.Chunk file into the structure that is
passed by the search engine to find_soft_selectors
'''
ch = clean_html(clean_html.default_config)
cv = clean_visible(clean_visible.default_config)
ids_and_clean_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pre_create(sender, model):
""" Callback before creating a new login Without a password during create we are forced to set the password to something random & ... |
if isinstance(model, Model) and not model.password:
model.password = random_str() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pre_save(sender, model):
""" Hash the password if being changed """ |
if isinstance(model, Model) and 'password' in model.dirty_fields:
model.salt, model.password = gen_salt_and_hash(model.password) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auth_creds(cls, username, password):
""" Validate a username & password A token is returned if auth is successful & can be used to authorize future requests ... |
store = goldman.sess.store
login = store.find(cls.RTYPE, 'username', username)
if not login:
msg = 'No login found by that username. Spelling error?'
raise AuthRejected(**{'detail': msg})
elif login.locked:
msg = 'The login account is currently lock... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auth_token(cls, token):
""" Callback method for OAuth 2.0 bearer token middleware """ |
store = goldman.sess.store
login = store.find(cls.RTYPE, 'token', token)
if not login:
msg = 'No login found with that token. It may have been revoked.'
raise AuthRejected(**{'detail': msg})
elif login.locked:
msg = 'The login account is currently l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_authenticate(self):
""" Update the login_date timestamp Initialize the thread local sess.login property with the authenticated login model. The login_da... |
goldman.sess.login = self
now = dt.now()
if not self.login_date:
self.login_date = now
else:
sec_since_updated = (now - self.login_date).seconds
min_since_updated = sec_since_updated / 60
if min_since_updated > 15:
self.... |
<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_username(self, data, value):
""" Ensure the username is unique If the login is being created then simply check if the username is in the store & fai... |
store = goldman.sess.store
existing = store.find(data['rtype'], 'username', value)
if existing:
if not data['rid'] or data['rid'] != existing.rid:
raise ValidationError('username is already taken') |
<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_log_level(value):
""" Converts numbers and strings to standard log level values. :param value: a value to be converted :return: converted log level """ |
if value == None:
return LogLevel.Info
value = str(value).upper()
if ("0" == value) or ("NOTHING" == value) or ("NONE" == value):
return LogLevel.Nothing
elif ("1" == value) or ("FATAL" == value):
return LogLevel.Fatal
elif ("2" == value) or ... |
<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_string(level):
""" Converts log level to a string. :param level: a log level to convert :return: log level name string. """ |
if level == LogLevel.Fatal:
return "FATAL"
if level == LogLevel.Error:
return "ERROR"
if level == LogLevel.Warn:
return "WARN"
if level == LogLevel.Info:
return "INFO"
if level == LogLevel.Debug:
return "DEBUG"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commit(message=COMMON_COMMIT_MESSAGE, capture=True):
""" git commit with common commit message when omit. """ |
env.warn_only = True
local(u'git commit -am"{}"'.format(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 get_filestore_instance(img_dir=None, data_dir=None):
"""Return an instance of FileStore.""" |
global _filestore_instances
key = "%s:%s" % (img_dir, data_dir)
try:
instance = _filestore_instances[key]
except KeyError:
instance = FileStore(
img_dir=img_dir, data_dir=data_dir
)
_filestore_instances[key] = instance
return 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_s3store_instance(bucket):
"""Return an instance of S3Store.""" |
global _s3store_instances
key = "%s" % bucket
try:
instance = _s3store_instances[key]
except KeyError:
instance = S3Store(
bucket=bucket
)
_s3store_instances[key] = instance
return 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 _compare_dict(new_dict, old_dict, change_list=None, root=None):
'''
a method for recursively listing changes made to a dictionary
:param new_dict: dictionary with new key-value pairs
:param old_dict: dictionary with old key-value pairs
:param change_list: list of differences between old an... |
<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_list(new_list, old_list, change_list=None, root=None):
'''
a method for recursively listing changes made to a list
:param new_list: list with new value
:param old_list: list with old values
:param change_list: list of differences between old and new
:param root: string with 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 _compare_set(new_set, old_set, change_list, root):
'''
a method for list changes made to a set
:param new_set: set with new values
:param old_set: set with old values
:param change_list: list of differences between old and new
:patam root: string with record of path to the root of the ... |
<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_mongo(qry):
"""Transform a simple query with one or more filter expressions into a MongoDB query expression. :param qry: Filter expression(s), see functio... |
rev = False # filters, not constraints
# special case for empty string/list
if qry == "" or qry == []:
return {}
# break input into groups of filters
unpar = lambda s: s.strip().strip('()')
if isinstance(qry, str):
groups = []
if _TOK_OR in qry:
groups = ... |
<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_expr(e):
"""Parse a single constraint expression. Legal expressions are defined by the regular expression `relation_re`. :param e: Expression :type e: ... |
m = relation_re.match(e)
if m is None:
raise ValueError("error parsing expression '{}'".format(e))
field, op, val = m.groups()
# Try different types
try:
# Integer
val_int = int(val)
val = val_int
except ValueError:
try:
# Float
va... |
<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_size_code(self):
"""Set the code for a size operation. """ |
if not self._op.startswith(self.SIZE):
self._size_code = None
return
if len(self._op) == len(self.SIZE):
self._size_code = self.SZ_EQ
else:
suffix = self._op[len(self.SIZE):]
self._size_code = self.SZ_MAPPING.get(suffix, None)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def passes(self, value):
"""Does the given value pass this constraint? :return: True,None if so; False,<expected> if not :rtype: tuple """ |
try:
if self._op.compare(value, self.value):
return True, None
else:
return False, self.value
except ValueError as err:
return False, str(err) |
<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_constraint(self, op, val):
"""Add new constraint. :param op: Constraint operator :type op: ConstraintOperator :param val: Constraint value :type val: str... |
if len(self.constraints) > 0:
if op.is_equality():
clist = ', '.join(map(str, self.constraints))
raise ValueError('Field {}: equality operator cannot be combined '
'with others: {}'.format(self._field.name, clist))
elif op... |
<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_conflicts(self):
"""Get conflicts in constraints, if any. :return: Description of each conflict, empty if none. :rtype: list(str) """ |
conflicts = []
if self._array and self._range:
conflicts.append('cannot use range expressions on arrays')
return conflicts |
<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_existence(self, rev):
"""Add existence constraint for the field. This is necessary because the normal meaning of 'x > 0' is: x > 0 and is present. Withou... |
if len(self.constraints) == 1 and (
# both 'exists' and strict equality don't require the extra clause
self.constraints[0].op.is_exists() or
self.constraints[0].op.is_equality()):
return
value = not rev # value is False if reversed, otherwise True
... |
<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, constraint, exists_main):
"""Create MongoDB query clause for a constraint. :param constraint: The constraint :type constraint: Constraint :para... |
c = constraint # alias
op = self._reverse_operator(c.op) if self._rev else c.op
mop = self._mongo_op_str(op)
# build the clause parts: location and expression
loc = MongoClause.LOC_MAIN # default location
if op.is_exists():
loc = MongoClause.LOC_MAIN2 if ex... |
<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_clause(self, clause):
"""Add a new clause to the existing query. :param clause: The clause to add :type clause: MongoClause :return: None """ |
if clause.query_loc == MongoClause.LOC_MAIN:
self._main.append(clause)
elif clause.query_loc == MongoClause.LOC_MAIN2:
self._main2.append(clause)
elif clause.query_loc == MongoClause.LOC_WHERE:
self._where.append(clause)
else:
raise Runtim... |
<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_mongo(self, disjunction=True):
"""Create from current state a valid MongoDB query expression. :return: MongoDB query expression :rtype: dict """ |
q = {}
# add all the main clauses to `q`
clauses = [e.expr for e in self._main]
if clauses:
if disjunction:
if len(clauses) + len(self._where) > 1:
q['$or'] = clauses
else:
# simplify 'or' of one thing
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def submit(self, call, *args, **kwargs):
""" Submit a call for future execution :return: future for the call execution :rtype: StoredFuture """ |
future = StoredFuture(call, *args, **kwargs)
self._queue.put(future)
self._ensure_worker()
return future |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dismiss_worker(self, worker):
"""Dismiss ``worker`` unless it is still required""" |
self._workers.remove(worker)
if len(self._workers) < self._min_workers:
self._workers.add(worker)
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ensure_worker(self):
"""Ensure there are enough workers available""" |
while len(self._workers) < self._min_workers or len(self._workers) < self._queue.qsize() < self._max_workers:
worker = threading.Thread(
target=self._execute_futures,
name=self.identifier + '_%d' % time.time(),
)
worker.daemon = True
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def s3_upload(acl, bucket, conn, content, content_type, path):
""" Store an object in our an S3 bucket. :param acl: S3 ACL for the object :param bucket: S3 bucke... |
# obj is the object that will be uploaded
obj = Key(conn.get_bucket(bucket))
obj.content_type = content_type
obj.key = path
obj.set_contents_from_string(content)
obj.set_acl(acl)
return gen_url(bucket, 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 to_image(self, filename='palette.png', band_width=1, length=60, max_width=0, vertical=True, alpha_channel=False):
""" Creates an image from the palette. Args... |
# max_width is approximate
# generate output pictures for documentation automatically
if max_width < 1:
pass
else:
band_width = int(max_width/len(self._colours))
image_width = band_width * len(self._colours)
if alpha_channel:
my_ima... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def blend(self, cycles=1):
""" Explands the existing Palette by inserting the blending colour between all Colours already in the Palette. Changes the Palette in-... |
for j in range(int(cycles)):
new_colours = []
for i, c in enumerate(self._colours):
if i != 0:
c2 = blend(c, self._colours[i-1])
new_colours.append(c2)
new_colours.append(c)
self._colours = new_colours |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def inject_init(init_path, readme_path, setup_kwargs):
'''
a method to add arguments to setup.py from module init file
:param init_path: string with path to module __init__ file
:param readme_path: string with path to module README.rst file
:param setup_kwargs: dictionary with existing setup ke... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bump(dev=False, patch=False, minor=False, major=False, nocommit=False):
"""Bump version number and commit change.""" |
if sum([int(x) for x in (patch, minor, major)]) > 1:
raise ValueError('Only one of patch, minor, major can be incremented.')
if check_staged():
raise EnvironmentError('There are staged changes, abort.')
with open(str(INIT_PATH)) as f:
lines = f.readlines()
for i, line in enum... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tag():
"""Tag current version.""" |
if check_unstaged():
raise EnvironmentError('There are staged changes, abort.')
with open(str(INIT_PATH)) as f:
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", f.read()))
version = metadata['version']
check_output(['git', 'tag', version, '-m', 'Release v{}'.format(version)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload():
"""Upload source to PyPI using twine.""" |
try:
o = check_output(['twine', 'upload'] + glob('dist/*'))
except CalledProcessError:
call(['twine', 'upload'] + glob('dist/*'))
raise
print(o.decode('utf-8')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def release():
"""Bump version, tag, build, gen docs.""" |
if check_staged():
raise EnvironmentError('There are staged changes, abort.')
if check_unstaged():
raise EnvironmentError('There are unstaged changes, abort.')
bump()
tag()
build()
doc_gen()
puts(colored.yellow("Remember to upload documentation and package:"))
with inden... |
<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_rid(model, rid):
""" Ensure the resource id is proper """ |
rid_field = getattr(model, model.rid_field)
if isinstance(rid_field, IntType):
try:
int(rid)
except (TypeError, ValueError):
abort(exceptions.InvalidURL(**{
'detail': 'The resource id {} in your request is not '
'syntactically ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find(model, rid):
""" Find a model from the store by resource id """ |
validate_rid(model, rid)
rid_field = model.rid_field
model = goldman.sess.store.find(model.RTYPE, rid_field, rid)
if not model:
abort(exceptions.DocumentNotFound)
return model |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _from_rest_blank(model, props):
""" Set empty strings to None where allowed This is done on fields with `allow_blank=True` which takes an incoming empty stri... |
blank = model.get_fields_by_prop('allow_blank', True)
for field in blank:
try:
if props[field] == '':
props[field] = None
except KeyError:
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 _from_rest_hide(model, props):
""" Purge fields not allowed during a REST deserialization This is done on fields with `from_rest=False`. """ |
hide = model.get_fields_by_prop('from_rest', False)
for field in hide:
try:
del props[field]
except KeyError:
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 _from_rest_ignore(model, props):
""" Purge fields that are completely unknown """ |
fields = model.all_fields
for prop in props.keys():
if prop not in fields:
del props[prop] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _from_rest_lower(model, props):
""" Lowercase fields requesting it during a REST deserialization """ |
for field in model.to_lower:
try:
props[field] = props[field].lower()
except (AttributeError, KeyError):
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 _from_rest_on_create(model, props):
""" Assign the default values when creating a model This is done on fields with `on_create=<value>`. """ |
fields = model.get_fields_with_prop('on_create')
for field in fields:
props[field[0]] = field[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 _from_rest_on_update(model, props):
""" Assign the default values when updating a model This is done on fields with `on_update=<value>`. """ |
fields = model.get_fields_with_prop('on_update')
for field in fields:
props[field[0]] = field[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 _from_rest_reject_update(model):
""" Reject any field updates not allowed on POST This is done on fields with `reject_update=True`. """ |
dirty = model.dirty_fields
fields = model.get_fields_by_prop('reject_update', True)
reject = []
for field in fields:
if field in dirty:
reject.append(field)
if reject:
mod_fail('These fields cannot be updated: %s' % ', '.join(reject)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_rest(model, props):
""" Map the REST data onto the model Additionally, perform the following tasks: * set all blank strings to None where needed * purge... |
req = goldman.sess.req
_from_rest_blank(model, props)
_from_rest_hide(model, props)
_from_rest_ignore(model, props)
_from_rest_lower(model, props)
if req.is_posting:
_from_rest_on_create(model, props)
elif req.is_patching:
_from_rest_on_update(model, props)
model.mer... |
<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_rest_hide(model, props):
""" Purge fields not allowed during a REST serialization This is done on fields with `to_rest=False`. """ |
hide = model.get_fields_by_prop('to_rest', False)
for field in hide:
try:
del props[field]
except KeyError:
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 _to_rest_includes(models, includes):
""" Fetch the models to be included The includes should follow a few basic rules: * the include MUST not already be an a... |
included = []
includes = includes or []
if not isinstance(models, list):
models = [models]
for include in includes:
for model in models:
rel = getattr(model, include)
if hasattr(rel, 'model') and rel.model:
rel_models = [rel.model]
... |
<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_rest_rels(model, props):
""" Move the relationships to appropriate location in the props All to_ones should be in a to_one key while all to_manys should ... |
props['to_many'] = {}
props['to_one'] = {}
for key in model.to_one:
try:
props['to_one'][key] = props.pop(key)
except KeyError:
continue
for key in model.to_many:
try:
props['to_many'][key] = props.pop(key)
except KeyError:
... |
<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_rest(model, includes=None):
""" Convert the model into a dict for serialization Notify schematics of the sparse fields requested while also forcing the r... |
includes = includes or []
sparse = goldman.sess.req.fields.get(model.rtype, [])
if sparse:
sparse += [model.rid_field, model.rtype_field]
sparse += includes
props = model.to_primitive(
load_rels=includes,
sparse_fields=sparse,
)
props['rid'] = props.pop(model... |
<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_rest_model(model, includes=None):
""" Convert the single model into a dict for serialization :return: dict """ |
props = {}
props['data'] = _to_rest(model, includes=includes)
props['included'] = _to_rest_includes(model, includes=includes)
return props |
<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_rest_models(models, includes=None):
""" Convert the models into a dict for serialization models should be an array of single model objects that will each ... |
props = {}
props['data'] = []
for model in models:
props['data'].append(_to_rest(model, includes=includes))
props['included'] = _to_rest_includes(models, includes=includes)
return props |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def collect_by_type(self, typ):
'''A more efficient way to collect nodes of a specified type than
collect_nodes.
'''
nodes = []
if isinstance(self, typ):
nodes.append(self)
for c in self:
nodes.extend(c.collect_by_type(typ))
return nodes |
<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_proxy(self, proxy, update=True):
""" Set proxy for chrome session """ |
update_web_driver = False
if self.current_proxy != proxy:
# Did we change proxies?
update_web_driver = True
self.current_proxy = proxy
if proxy is None:
# TODO: Need to be able to remove a proxy if one is set
pass
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 _header_extension(self, remove_headers=[], add_or_modify_headers={}):
"""Create modheaders extension Source: https://vimmaniac.com/blog/bangal/modify-and-add... |
import string
import zipfile
plugin_file = 'custom_headers_plugin.zip'
if remove_headers is None:
remove_headers = []
if add_or_modify_headers is None:
add_or_modify_headers = {}
if isinstance(remove_headers, list) is False:
logger... |
<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_template(self, template):
""" Sets template to be used when generating output :param template TEmplate instance :type instance of BasicTemplate """ |
if isinstance(template, templates.BasicTemplate):
self.template = template
else:
raise TypeError('converter#set_template:'
'Template must inherit from BasicTemplate') |
<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, filename=None):
""" Generates output and saves to given file :param filename File name :type str or unicode """ |
if filename is None:
raise IOError('Converter#save: Undefined filename')
cnt = self.output()
with (open(filename, 'wb+')) as f:
f.write(cnt.encode('utf-8')) |
<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_file(self, filename):
""" Read and adds given file's content to data array that will be used to generate output :param filename File name to add :type st... |
with (open(filename, 'rb')) as f:
data = f.read()
# below won't handle the same name files
# in different paths
fname = os.path.basename(filename)
self.files[fname] = base64.b64encode(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output(self):
""" Generates output from data array :returns Pythoned file :rtype str or unicode """ |
if len(self.files) < 1:
raise Exception('Converter#output: No files to convert')
return self.template.render(self.files) |
<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):
""" Update the screens contents in every loop. """ |
# this is not really neccesary because the surface is black after initializing
self.corners.fill(BLACK)
self.corners.draw_dot((0, 0), self.colors[0])
self.corners.draw_dot((self.screen.width - 1, 0), self.colors[0])
self.corners.draw_dot((self.screen.width - 1, self.screen.heigh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self):
""" Send the current screen content to Mate Light. """ |
self.screen.reset()
self.screen.blit(self.corners)
self.screen.blit(self.lines, (1, 1))
self.screen.blit(self.rects, (int(self.screen.width / 2) + 1, 1))
self.screen.blit(self.circle, (0, int(self.screen.height / 2) + 1))
self.screen.blit(self.filled, (int(self.screen.wi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_events(self):
""" Loop through all events. """ |
for event in pymlgame.get_events():
if event.type == E_NEWCTLR:
#print(datetime.now(), '### new player connected with uid', event.uid)
self.players[event.uid] = {'name': 'alien_{}'.format(event.uid), 'score': 0}
elif event.type == E_DISCONNECT:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gameloop(self):
""" A game loop that circles through the methods. """ |
try:
while True:
self.handle_events()
self.update()
self.render()
except KeyboardInterrupt:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, string):
"""The write method for a CalcpkgOutput object- print the string""" |
if ("" == string or '\n' == string or '\r' == string):
return
# Filter out any \r newlines.
string = string.replace("\r", "")
# if '\r\n' in string:
# string = util.replaceNewlines(string, '\r\n')
if self.printData:
print >> sys.__stdout__, string
if self.logData:
self.logWrite(string) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logWrite(self, string):
"""Only write text to the log file, do not print""" |
logFile = open(self.logFile, 'at')
logFile.write(string + '\n')
logFile.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setupLogFile(self):
"""Set up the logging file for a new session- include date and some whitespace""" |
self.logWrite("\n###############################################")
self.logWrite("calcpkg.py log from " + str(datetime.datetime.now()))
self.changeLogging(True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getLoggingLocation(self):
"""Return the path for the calcpkg.log file - at the moment, only use a Linux path since I don't know where Windows thinks logs s... |
if sys.platform == "win32":
modulePath = os.path.realpath(__file__)
modulePath = modulePath[:modulePath.rfind("/")]
return modulePath
else:
return "/tmp"
return "" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def twitter_timeline(screen_name, since_id=None):
""" Return relevant twitter timeline """ |
consumer_key = twitter_credential('consumer_key')
consumer_secret = twitter_credential('consumer_secret')
access_token = twitter_credential('access_token')
access_token_secret = twitter_credential('access_secret')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def twitter_credential(name):
""" Grab twitter credential from settings """ |
credential_name = 'TWITTER_' + name.upper()
if hasattr(settings, credential_name):
return getattr(settings, credential_name)
else:
raise AttributeError('Missing twitter credential in settings: ' + credential_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 modify_class(original_class, modifier_class, override=True):
""" Adds class methods from modifier_class to original_class. If override is True existing metho... |
# get members to add
modifier_methods = inspect.getmembers(modifier_class, inspect.ismethod)
# set methods
for method_tuple in modifier_methods:
name = method_tuple[0]
method = method_tuple[1]
if isinstance(method, types.UnboundMethodType):
if hasattr(original_c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resize_image(image, tuple_wh, preserve_aspect=True):
"""Resizes an instance of a PIL Image. In order to prevent un-intended side effects, this function alway... |
if preserve_aspect:
img_cpy = image.copy()
img_cpy.thumbnail(tuple_wh)
return img_cpy
else:
return image.resize(tuple_wh) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_datetime(date):
""" Convert datetime to UTC ISO 8601 """ |
# todo: test me
if date.utcoffset() is None:
return date.isoformat() + 'Z'
utc_offset_sec = date.utcoffset()
utc_date = date - utc_offset_sec
utc_date_without_offset = utc_date.replace(tzinfo=None)
return utc_date_without_offset.isoformat() + 'Z' |
<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(self, msg, error=False):
"""Log message helper.""" |
output = self.stdout
if error:
output = self.stderr
output.write(msg)
output.write('\n') |
<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_emails(self, email_filename, index=0):
"""Generator function that parse and extract emails from the file `email_filename` starting from the position `i... |
self.log("Parsing email dump: %s." % email_filename)
mbox = mailbox.mbox(email_filename, factory=CustomMessage)
# Get each email from mbox file
#
# The following implementation was used because the object
# mbox does not support slicing. Converting the object to a
... |
<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_emails(self, mailinglist_dir, all, exclude_lists):
"""Generator function that get the emails from each mailing list dump dirctory. If `all` is set to Tru... |
self.log("Getting emails dumps from: %s" % mailinglist_dir)
# Get the list of directories ending with .mbox
mailing_lists_mboxes = (mbox for mbox in os.listdir(mailinglist_dir)
if mbox.endswith('.mbox'))
# Get messages from each mbox
for mbox in... |
<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_thread(self, email, mailinglist):
"""Group messages by thread looking for similar subjects""" |
subject_slug = slugify(email.subject_clean)
thread = self.THREAD_CACHE.get(subject_slug, {}).get(mailinglist.id)
if thread is None:
thread = Thread.all_objects.get_or_create(
mailinglist=mailinglist,
subject_token=subject_slug
)[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 save_email(self, list_name, email_msg, index):
"""Save email message into the database.""" |
msg_id = email_msg.get('Message-ID')
if not msg_id:
return
# Update last imported message into the DB
mailinglist, created = MailingList.objects.get_or_create(
name=list_name
)
mailinglist.last_imported_index = index
if created:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_emails(self, archives_path, all, exclude_lists=None):
"""Get emails from the filesystem from the `archives_path` and store them into the database. If ... |
count = 0
email_generator = self.get_emails(archives_path, all, exclude_lists)
for mailinglist_name, msg, index in email_generator:
try:
self.save_email(mailinglist_name, msg, index)
except:
# This anti-pattern is needed to avoid the tran... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle(self, *args, **options):
"""Main command method.""" |
# Already running, so quit
if os.path.exists(self.lock_file):
self.log(("This script is already running. "
"(If your are sure it's not please "
"delete the lock file in {}')").format(self.lock_file))
sys.exit(0)
if not os.pat... |
<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_managers(sender, **kwargs):
""" Make sure all classes have the appropriate managers """ |
cls = sender
if issubclass(cls, ModelBase):
cls.add_to_class('permitted', PermittedManager()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vote_total(self):
""" Calculates vote total as total_upvotes - total_downvotes. We are adding a method here instead of relying on django-secretballot's addit... |
modelbase_obj = self.modelbase_obj
return modelbase_obj.votes.filter(vote=+1).count() - modelbase_obj.votes.filter(vote=-1).count() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comment_count(self):
""" Counts total number of comments on ModelBase object. Comments should always be recorded on ModelBase objects. """ |
# Get the comment model.
comment_model = comments.get_model()
modelbase_content_type = ContentType.objects.get(app_label="panya", model="modelbase")
# Create a qs filtered for the ModelBase or content_type objects.
qs = comment_model.objects.filter(
content_type__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 sync(collector):
"""Sync an environment""" |
amazon = collector.configuration['amazon']
aws_syncr = collector.configuration['aws_syncr']
# Convert everything before we try and sync anything
log.info("Converting configuration")
converted = {}
for thing in collector.configuration["__registered__"]:
if thing in collector.configurati... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deploy_lambda(collector):
"""Deploy a lambda function""" |
amazon = collector.configuration['amazon']
aws_syncr = collector.configuration['aws_syncr']
find_lambda_function(aws_syncr, collector.configuration).deploy(aws_syncr, amazon) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deploy_gateway(collector):
"""Deploy the apigateway to a particular stage""" |
configuration = collector.configuration
aws_syncr = configuration['aws_syncr']
aws_syncr, amazon, stage, gateway = find_gateway(aws_syncr, configuration)
gateway.deploy(aws_syncr, amazon, stage)
if not configuration['amazon'].changes:
log.info("No changes were made!!") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.