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 diet(file, configuration, check):
"""Simple program that either print config customisations for your environment or compresses file FILE.""" |
config = process.read_yaml_configuration(configuration)
process.diet(file, config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def linspace2(a, b, n, dtype=None):
"""similar to numpy.linspace but excluding the boundaries this is the normal numpy.linspace: [ 0. 0.25 0.5 0.75 1. ] and this... |
a = linspace(a, b, n + 1, dtype=dtype)[:-1]
if len(a) > 1:
diff01 = ((a[1] - a[0]) / 2).astype(a.dtype)
a += diff01
return 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 send_mail(subject, text_content, from_email, to, html_content=None, attachments=[], cc=[], bcc=[]):
""" This function sends mail using EmailMultiAlternatives... |
msg = EmailMultiAlternatives(subject, text_content, from_email, to, cc=cc, bcc=bcc)
if html_content:
msg.attach_alternative(html_content, "text/html")
if attachments:
for att in attachments:
if att:
mimetype = mimetypes.guess_type(att)[0]
if 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 email_embed_image(email, img_content_id, img_data):
""" email is a django.core.mail.EmailMessage object """ |
img = MIMEImage(img_data)
img.add_header('Content-ID', '<%s>' % img_content_id)
img.add_header('Content-Disposition', 'inline')
email.attach(img) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def safe_mongocall(call):
""" Decorator for automatic handling of AutoReconnect-exceptions. """ |
def _safe_mongocall(*args, **kwargs):
for i in range(4):
try:
return call(*args, **kwargs)
except pymongo.errors.AutoReconnect:
print ('AutoReconnecting, try %d' % i)
time.sleep(pow(2, i))
# Try one more time, but this time, 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 get_username(self):
""" Gets the user name. The value can be stored in parameters "username" or "user". :return: the user name. """ |
username = self.get_as_nullable_string("username")
username = username if username != None else self.get_as_nullable_string("user")
return username |
<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_password(self):
""" Get the user password. The value can be stored in parameters "password" or "pass". :return: the user password. """ |
password = self.get_as_nullable_string("password")
password = password if password != None else self.get_as_nullable_string("pass")
return 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 get_access_id(self):
""" Gets the application access id. The value can be stored in parameters "access_id" pr "client_id" :return: the application access id.... |
access_id = self.get_as_nullable_string("access_id")
access_id = access_id if access_id != None else self.get_as_nullable_string("client_id")
return access_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 get_access_key(self):
""" Gets the application secret key. The value can be stored in parameters "access_key", "client_key" or "secret_key". :return: the app... |
access_key = self.get_as_nullable_string("access_key")
access_key = access_key if access_key != None else self.get_as_nullable_string("access_key")
return access_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 many_from_config(config):
""" Retrieves all CredentialParams from configuration parameters from "credentials" section. If "credential" section is present ins... |
result = []
# Try to get multiple credentials first
credentials = config.get_section("credentials")
if len(credentials) > 0:
sections_names = credentials.get_section_names()
for section in sections_names:
credential = credentials.get_section(sect... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def energy(q, v):
"""Compute the kinetic and potential energy of the planetary system""" |
# Number of points
N: int = len(q)
# Initialize arrays to zero of the correct size
T: np.ndarray = np.zeros(N)
U: np.ndarray = np.zeros(N)
# Add up kinetic energy of each body
for i in range(B):
# Kinetic energy is 1/2 mv^2
m = mass[i]
vi = v[:, sl... |
<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_force(q_vars, mass):
"""Fluxion with the potential energy of the eight planets sytem""" |
# Number of bodies
B: int = len(mass)
# Build the potential energy fluxion by iterating over distinct pairs of bodies
U = fl.Const(0.0)
for i in range(B):
for j in range(i+1, B):
U += U_ij(q_vars, mass, i, j)
# Varname arrays for both the coordinate system and U
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tweet(tweet_text_func):
'''
A decorator to make a function Tweet
Parameters
- `tweet_text_func` is a function that takes no parameters and returns a tweetable string
For example::
@tweet
def total_deposits_this_week():
# ...
@tweet
def not_an_inte... |
<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_perm_name(cls, action, full=True):
""" Return the name of the permission for a given model and action. By default it returns the full permission name `ap... |
codename = "{}_{}".format(action, cls.__name__.lower())
if full:
return "{}.{}".format(cls._meta.app_label, codename)
return codename |
<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(self, correlation_id, connection):
""" Registers the given connection in all referenced discovery services. This method can be used for dynamic serv... |
result = self._register_in_discovery(correlation_id, connection)
if result:
self._connections.append(connection) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sendPartialResponse(self):
""" Send a partial response without closing the connection. :return: <void> """ |
self.requestProtocol.requestResponse["code"] = (
self.responseCode
)
self.requestProtocol.requestResponse["content"] = (
self.responseContent
)
self.requestProtocol.requestResponse["errors"] = (
self.responseErrors
)
self.reque... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sendFinalResponse(self):
""" Send the final response and close the connection. :return: <void> """ |
self.requestProtocol.requestResponse["code"] = (
self.responseCode
)
self.requestProtocol.requestResponse["content"] = (
self.responseContent
)
self.requestProtocol.requestResponse["errors"] = (
self.responseErrors
)
self.reque... |
<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(self, value):
""" Add a value to the buffer. """ |
ind = int(self._ind % self.shape)
self._pos = self._ind % self.shape
self._values[ind] = value
if self._ind < self.shape:
self._ind += 1 # fast fill
else:
self._ind += self._splitValue
self._splitPos += self._splitValue
self._cached =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def array(self):
""" Returns a numpy array containing the last stored values. """ |
if self._ind < self.shape:
return self._values[:self._ind]
if not self._cached:
ind = int(self._ind % self.shape)
self._cache[:self.shape - ind] = self._values[ind:]
self._cache[self.shape - ind:] = self._values[:ind]
self._cached = 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 splitPos(self):
"""return the position of where to split the array to get the values in the right order""" |
if self._ind < self.shape:
return 0
v = int(self._splitPos)
if v >= 1:
self._splitPos = 0
return v |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort(polylines):
""" sort points within polyline """ |
for n, c in enumerate(polylines):
l = len(c)
if l > 2:
# DEFINE FIRST AND LAST INDEX A THOSE TWO POINTS THAT
# HAVE THE BIGGEST DIFFERENCE FROM A MIDDLE:
mid = c.mean(axis=0)
distV = (c - mid)
dists = norm(distV, axis=-1)
fir... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter(polylines, min_len=20):
""" filter polylines shorter than given min length """ |
filtered = []
for n in range(len(polylines) - 1, -1, -1):
if lengths(polylines[n]).sum() < min_len:
filtered.append(polylines.pop(n))
return filtered |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def separate(polylines, f_mx_dist=2, mn_group_len=4):
""" split polylines wherever crinkles are found """ |
s = []
for n in range(len(polylines) - 1, -1, -1):
c = polylines[n]
separated = False
start = 0
for m in range(mn_group_len, len(c) - 1):
if m - start < mn_group_len:
continue
m += 1
group = c[m - mn_group_len:m]
... |
<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(polylines, mx_dist=4):
""" point by line segment comparison merge polylines if points are close """ |
l = len(polylines)
to_remove = set()
for n in range(l - 1, -1, -1):
if n not in to_remove:
c = polylines[n]
for p0, p1 in zip(c[:-1], c[1:]):
# create a line from any subsegment:
l0 = p0[0], p0[1], p1[0], p1[1]
# for every oth... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def smooth(polylines):
""" smooth every polyline using spline interpolation """ |
for c in polylines:
if len(c) < 9:
# smoothing wouldn't make sense here
continue
x = c[:, 0]
y = c[:, 1]
t = np.arange(x.shape[0], dtype=float)
t /= t[-1]
x = UnivariateSpline(t, x)(t)
y = UnivariateSpline(t, y)(t)
c[:, 0] = 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 get_queryset(self):
"""Query for the most voted messages sorting by the sum of voted and after by date.""" |
queryset = super(MostVotedManager, self).get_queryset()
sql = """
SELECT
count(sav.id)
FROM
colab_superarchives_vote AS sav
WHERE
colab_superarchives_message.id = sav.message_id
"""
messages = queryse... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _conf_packages(args):
"""Runs custom configuration steps for the packages that ship with support in acorn. """ |
from acorn.config import config_dir
from os import path
from acorn.base import testmode
target = config_dir(True)
alternate = path.join(path.abspath(path.expanduser("~")), ".acorn")
if not testmode and target != alternate:# pragma: no cover
msg.err("Could not configure custom ~/.acorn d... |
<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_configure(subcmd, args):
"""Runs the configuration step for the specified sub-command. """ |
maps = {
"packages": _conf_packages
}
if subcmd in maps:
maps[subcmd](args)
else:
msg.warn("'configure' sub-command {} is not supported.".format(subcmd)) |
<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_for_legal_children(self, name, elt, mustqualify=1):
'''Check if all children of this node are elements or whitespace-only
text nodes.
'''
inheader = name == "Header"
for n in _children(elt):
t = n.nodeType
if t == _Node.COMMENT_NODE: 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 _check_for_pi_nodes(self, list, inheader):
'''Raise an exception if any of the list descendants are PI nodes.
'''
list = list[:]
while list:
elt = list.pop()
t = elt.nodeType
if t == _Node.PROCESSING_INSTRUCTION_NODE:
raise ParseExc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def GetElementNSdict(self, elt):
'''Get a dictionary of all the namespace attributes for the indicated
element. The dictionaries are cached, and we recurse up the tree
as necessary.
'''
d = self.ns_cache.get(id(elt))
if not d:
if elt != self.dom: d = self.Get... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def IsAFault(self):
'''Is this a fault message?
'''
e = self.body_root
if not e: return 0
return e.namespaceURI == SOAP.ENV and e.localName == 'Fault' |
<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(self, how):
'''Parse the message.
'''
if type(how) == types.ClassType: how = how.typecode
return how.parse(self.body_root, 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 WhatActorsArePresent(self):
'''Return a list of URI's of all the actor attributes found in
the header. The special actor "next" is ignored.
'''
results = []
for E in self.header_elements:
a = _find_actor(E)
if a not in [ None, SOAP.ACTOR_NEXT ]: resul... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _repr_html_(self):
""" Return HTML representation of VDOM object. HTML escaping is performed wherever necessary. """ |
# Use StringIO to avoid a large number of memory allocations with string concat
with io.StringIO() as out:
out.write('<{tag}'.format(tag=escape(self.tag_name)))
if self.style:
# Important values are in double quotes - cgi.escape only escapes double quotes, not si... |
<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_helper(filename, module_name, get_module, get_today_fn, hash_check=True, auth=None):
"""Deploys a file to the Artifactory BEL namespace cache :param ... |
path = ArtifactoryPath(
get_module(module_name),
auth=get_arty_auth() if auth is None else auth
)
path.mkdir(exist_ok=True)
if hash_check:
deployed_semantic_hashes = {
get_bel_resource_hash(subpath.as_posix())
for subpath in path
}
seman... |
<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_namespace(filename, module_name, hash_check=True, auth=None):
"""Deploy a file to the Artifactory BEL namespace cache. :param str filename: The physic... |
return _deploy_helper(
filename,
module_name,
get_namespace_module_url,
get_namespace_today,
hash_check=hash_check,
auth=auth
) |
<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_annotation(filename, module_name, hash_check=True, auth=None):
"""Deploy a file to the Artifactory BEL annotation cache. :param str filename: The phys... |
return _deploy_helper(
filename,
module_name,
get_annotation_module_url,
get_annotation_today,
hash_check=hash_check,
auth=auth
) |
<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_knowledge(filename, module_name, auth=None):
"""Deploy a file to the Artifactory BEL knowledge cache. :param str filename: The physical file path :par... |
return _deploy_helper(
filename,
module_name,
get_knowledge_module_url,
get_knowledge_today,
hash_check=False,
auth=auth
) |
<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_directory(directory, auth=None):
"""Deploy all files in a given directory. :param str directory: the path to a directory :param tuple[str] auth: A pai... |
for file in os.listdir(directory):
full_path = os.path.join(directory, file)
if file.endswith(BELANNO_EXTENSION):
name = file[:-len(BELANNO_EXTENSION)]
log.info('deploying annotation %s', full_path)
deploy_annotation(full_path, name, auth=auth)
elif fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export_tree(lookup, tree, path):
"""Exports the given tree object to path. :param lookup: Function to retrieve objects for SHA1 hashes. :param tree: Tree to ... |
FILE_PERM = S_IRWXU | S_IRWXG | S_IRWXO
for name, mode, hexsha in tree.iteritems():
dest = os.path.join(path, name)
if S_ISGITLINK(mode):
log.error('Ignored submodule {}; submodules are not yet supported.'
.format(name))
# raise ValueError('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 abook2vcf():
"""Command line tool to convert from Abook to vCard""" |
from argparse import ArgumentParser, FileType
from os.path import expanduser
from sys import stdout
parser = ArgumentParser(description='Converter from Abook to vCard syntax.')
parser.add_argument('infile', nargs='?', default=expanduser('~/.abook/addressbook'),
help='The Ab... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vcf2abook():
"""Command line tool to convert from vCard to Abook""" |
from argparse import ArgumentParser, FileType
from sys import stdin
parser = ArgumentParser(description='Converter from vCard to Abook syntax.')
parser.add_argument('infile', nargs='?', type=FileType('r'), default=stdin,
help='Input vCard file (default: stdin)')
parser.add_... |
<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 internal state.""" |
with self._lock:
if getmtime(self._filename) > self._last_modified:
self._last_modified = getmtime(self._filename)
self._book = ConfigParser(default_section='format')
self._book.read(self._filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _gen_addr(entry):
"""Generates a vCard Address object""" |
return Address(street=entry.get('address', ''),
extended=entry.get('address2', ''),
city=entry.get('city', ''),
region=entry.get('state', ''),
code=entry.get('zip', ''),
country=entry.get('country... |
<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_photo(self, card, name):
"""Tries to load a photo and add it to the vCard""" |
try:
photo_file = join(dirname(self._filename), 'photo/%s.jpeg' % name)
jpeg = open(photo_file, 'rb').read()
photo = card.add('photo')
photo.type_param = 'jpeg'
photo.encoding_param = 'b'
photo.value = jpeg
except 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 _to_vcard(self, entry):
"""Return a vCard of the Abook entry""" |
card = vCard()
card.add('uid').value = Abook._gen_uid(entry)
card.add('fn').value = entry['name']
card.add('n').value = Abook._gen_name(entry['name'])
if 'email' in entry:
for email in entry['email'].split(','):
card.add('email').value = email
... |
<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_vcards(self):
"""Return a list of vCards""" |
self._update()
return [self._to_vcard(self._book[entry]) for entry in self._book.sections()] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _conv_adr(adr, entry):
"""Converts to Abook address format""" |
if adr.value.street:
entry['address'] = adr.value.street
if adr.value.extended:
entry['address2'] = adr.value.extended
if adr.value.city:
entry['city'] = adr.value.city
if adr.value.region:
entry['state'] = adr.value.region
if adr.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _conv_tel_list(tel_list, entry):
"""Converts to Abook phone types""" |
for tel in tel_list:
if not hasattr(tel, 'TYPE_param'):
entry['other'] = tel.value
elif tel.TYPE_param.lower() == 'home':
entry['phone'] = tel.value
elif tel.TYPE_param.lower() == 'work':
entry['workphone'] = tel.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 to_abook(card, section, book, bookfile=None):
"""Converts a vCard to Abook""" |
book[section] = {}
book[section]['name'] = card.fn.value
if hasattr(card, 'email'):
book[section]['email'] = ','.join([e.value for e in card.email_list])
if hasattr(card, 'adr'):
Abook._conv_adr(card.adr, book[section])
if hasattr(card, 'tel_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 abook_file(vcard, bookfile):
"""Write a new Abook file with the given vcards""" |
book = ConfigParser(default_section='format')
book['format'] = {}
book['format']['program'] = 'abook'
book['format']['version'] = '0.6.1'
for (i, card) in enumerate(readComponents(vcard.read())):
Abook.to_abook(card, str(i), book, bookfile)
with open(bookfi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def positional_filter(positional_filters, title=''):
'''
a method to construct a conditional filter function to test positional arguments
:param positional_filters: dictionary or list of dictionaries with query criteria
:param title: string with name of function to use instead
:return: callab... |
<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_and_check(self, base_settings, prompt=None):
"""Load settings and check them. Loads the settings from ``base_settings``, then checks them. Returns: (mer... |
checker = Checker(self.file_name, self.section, self.registry, self.strategy_type, prompt)
settings = self.load(base_settings)
if checker.check(settings):
return settings, True
return None, False |
<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, base_settings):
"""Merge local settings from file with ``base_settings``. Returns a new settings dict containing the base settings and the loaded ... |
is_valid_key = lambda k: k.isupper() and not k.startswith('_')
# Base settings, including `LocalSetting`s, loaded from the
# Django settings module.
valid_keys = (k for k in base_settings if is_valid_key(k))
base_settings = DottedAccessDict((k, base_settings[k]) for k in valid_... |
<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(self, value, settings):
"""Inject ``settings`` into ``value``. Go through ``value`` looking for ``{{NAME}}`` groups and replace each group with the v... |
assert isinstance(value, string_types), 'Expected str; got {0.__class__}'.format(value)
begin, end = '{{', '}}'
if begin not in value:
return value, False
new_value = value
begin_pos, end_pos = 0, None
len_begin, len_end = len(begin), len(end)
len_... |
<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_reporoot():
"""Returns the absolute path to the repo root directory on the current system. """ |
from os import path
import acorn
medpath = path.abspath(acorn.__file__)
return path.dirname(path.dirname(medpath)) |
<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_and_exit(command_class):
'''A shortcut for reading from sys.argv and exiting the interpreter'''
cmd = command_class(sys.argv[1:])
if cmd.error:
print('error: {0}'.format(cmd.error))
sys.exit(1)
else:
sys.exit(cmd.run()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def registerParentFlag(self, optionName, value):
'''Register a flag of a parent command
:Parameters:
- `optionName`: String. Name of option
- `value`: Mixed. Value of parsed flag`
'''
self.parentFlags.update({optionName: value})
return 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 radialAverage(arr, center=None):
""" radial average a 2darray around a center if no center is given, take middle """ |
# taken from
# http://stackoverflow.com/questions/21242011/most-efficient-way-to-calculate-radial-profile
s0, s1 = arr.shape[:2]
if center is None:
center = s0/2, s1/2
y, x = np.indices((s0, s1))
r = np.sqrt((x - center[0])**2 + (y - center[1])**2)
r = r.astype(np.int)
tbin = np... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _convert(value, tzto, defaulttz):
"""Convert datetime.datetime object between timezones""" |
if not isinstance(value, datetime):
raise ValueError('value must be a datetime.datetime object')
if value.tzinfo is None:
value = value.replace(tzinfo=defaulttz)
return value.astimezone(tzto) |
<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_local(value, defaulttz=None):
"""Convert datetime.datetime time to local time zone If value doesn't have tzinfo, then defaulttz is set. Default value of d... |
if defaulttz is None:
defaulttz = tzutc()
return _convert(value, tzlocal(), defaulttz) |
<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_utc(value, defaulttz=None):
"""Convert datetime.datetime time to UTC If value doesn't have tzinfo, then defaulttz is set. Default value of defaulttz is lo... |
if defaulttz is None:
defaulttz = tzlocal()
return _convert(value, tzutc(), defaulttz) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def prettyPrintDictionary(d):
'''Pretty print a dictionary as simple keys and values'''
maxKeyLength = 0
maxValueLength = 0
for key, value in d.iteritems():
maxKeyLength = max(maxKeyLength, len(key))
maxValueLength = max(maxValueLength, len(key))
for key in sorted(d.keys()):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def label(self):
'''A human readable label'''
if self.__doc__ and self.__doc__.strip():
return self.__doc__.strip().splitlines()[0]
return humanize(self.__class__.__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 label_for(self, name):
'''Get a human readable label for a method given its name'''
method = getattr(self, name)
if method.__doc__ and method.__doc__.strip():
return method.__doc__.strip().splitlines()[0]
return humanize(name.replace(self._prefix, '')) |
<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(self):
'''
Collect all tests to run and run them.
Each method will be run :attr:`Benchmark.times`.
'''
tests = self._collect()
if not tests:
return
self.times
self.before_class()
for test in tests:
func = getattr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authorizer(self, schemes, resource, action, request_args):
"""Construct the Authorization header for a request. Args: schemes (list of str):
Authentication ... |
if not schemes:
return u'', u''
for scheme in schemes:
if scheme in self.schemes and self.has_auth_params(scheme):
cred = Context.format_auth_params(self.schemes[scheme][u'params'])
if hasattr(self, 'mfa_token'):
cred = '{}, mf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authorize(self, scheme, **params):
"""Store credentials required to satisfy a given auth scheme. Args: scheme (str):
The name of the Authentication scheme. ... |
if scheme not in self.schemes:
return False
for field, value in iteritems(params):
setattr(self, field, value)
if field in self.schemes[scheme][u'params'].keys() and value:
self.schemes[scheme][u'params'][field] = value
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 has_auth_params(self, scheme):
"""Check whether all information required for a given auth scheme have been supplied. Args: scheme (str):
Name of the authent... |
for k, v in iteritems(self.schemes[scheme][u'params']):
if not v: 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 format_auth_params(params):
"""Generate the format expected by HTTP Headers from parameters. Args: params (dict):
{key: value} to convert to key=value Retur... |
parts = []
for (key, value) in params.items():
if value:
parts.append('{}="{}"'.format(key, value))
return ", ".join(parts) |
<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_backend(backend_class=None):
""" Get backend instance If no `backend_class` is specified, the backend class is determined from the value of `settings.ROU... |
cache_name = '_backend_instance'
if not hasattr(get_backend, cache_name):
backend_class = backend_class or settings.ROUGHPAGES_BACKEND
if isinstance(backend_class, basestring):
module_path, class_name = backend_class.rsplit(".", 1)
module = import_module(module_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 find_faderport_input_name(number=0):
""" Find the MIDI input name for a connected FaderPort. NOTE! Untested for more than one FaderPort attached. :param numb... |
ins = [i for i in mido.get_input_names() if i.lower().startswith('faderport')]
if 0 <= number < len(ins):
return ins[number]
else:
return 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 find_faderport_output_name(number=0):
""" Find the MIDI output name for a connected FaderPort. NOTE! Untested for more than one FaderPort attached. :param nu... |
outs = [i for i in mido.get_output_names() if i.lower().startswith('faderport')]
if 0 <= number < len(outs):
return outs[number]
else:
return 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 _message_callback(self, msg):
"""Callback function to handle incoming MIDI messages.""" |
if msg.type == 'polytouch':
button = button_from_press(msg.note)
if button:
self.on_button(button, msg.value != 0)
elif msg.note == 127:
self.on_fader_touch(msg.value != 0)
elif msg.type == 'control_change' and msg.control == 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 fader(self, value: int):
"""Move the fader to a new position in the range 0 to 1023.""" |
self._fader = int(value) if 0 < value < 1024 else 0
self.outport.send(mido.Message('control_change', control=0,
value=self._fader >> 7))
self.outport.send(mido.Message('control_change', control=32,
value=self._fader &... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def light_on(self, button: Button):
"""Turn the light on for the given Button. NOTE! If yuo turn the "Off" button light on, the fader won't report value updates ... |
self.outport.send(mido.Message('polytouch', note=button.light, value=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 run(self):
"""Fetch remote code.""" |
link = self.content[0]
try:
r = requests.get(link)
r.raise_for_status()
self.content = [r.text]
return super(RemoteCodeBlock, self).run()
except Exception:
document = self.state.document
err = 'Unable to resolve ' + link
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setUp(self):
'''Look for WS-Address
'''
toplist = filter(lambda wsa: wsa.ADDRESS==self.wsAddressURI, WSA_LIST)
epr = 'EndpointReferenceType'
for WSA in toplist+WSA_LIST:
if (self.wsAddressURI is not None and self.wsAddressURI != WSA.ADDRESS) 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 setRequest(self, endPointReference, action):
'''Call For Request
'''
self._action = action
self.header_pyobjs = None
pyobjs = []
namespaceURI = self.wsAddressURI
addressTo = self._addressTo
messageID = self._messageID = "uuid:%s" %time.time()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def upsert(self, key, value, entry):
'''Update or Insert an entry into the list of dictionaries.
If a dictionary in the list is found where key matches the value, then
the FIRST matching list entry is replaced with entry
else
the entry is appended to the end of the 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 insert(self, new_entry):
'''Insert a new entry to the end of the list of dictionaries.
This entry retains the original index tracking but adds this
entry incrementally at the end.
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 },
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deleteByOrigIndex(self, index):
"""Removes a single entry from the list given the index reference. The index, in this instance, is a reference to the *origin... |
result = []
result_tracker = []
for counter, row in enumerate(self.table):
if self.index_track[counter] != index:
result.append(row)
result_tracker.append(self.index_track[counter])
self.table = result
self.index_track = result_tracker... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deleteByOrigIndexList(self, indexList):
"""Remove entries from the list given the index references. The index, in this instance, is a reference to the *origi... |
result = []
result_tracker = []
counter = 0
for row in self.table:
if not counter in indexList:
result.append(row)
result_tracker.append(self.index_track[counter])
counter += 1
self.table = result
self.index_track =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def renumber(self, key, start=1, increment=1, insert=False):
'''Incrementally number a key based on the current order of the list.
Please note that if an entry in the list does not have the specified
key, it is NOT created (unless insert=True is passed). The entry is,
however, still cou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sort(self, key, reverse=False, none_greater=False):
'''Sort the list in the order of the dictionary key.
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 },
... {"name": "Larry", "age": 18, "wigs": [3, 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 hasKey(self, key, notNone=False):
'''Return entries where the key is present.
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 },
... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]},
... {"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 returnString(self, limit=False, omitBrackets=False, executable=False, honorMissing=False):
'''Return a string containing the list of dictionaries in easy
human-readable read format.
Each entry is on one line. Key/value pairs are 'spaced' in such a way
as to have them all line up ver... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def returnIndexList(self, limit=False):
'''Return a list of integers that are list-index references to the
original list of dictionaries."
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "order": 2},
... {"name": "Larry", "age": 18, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def returnOneEntry(self, last=False):
'''Return the first entry in the current list. If 'last=True', then
the last entry is returned."
Returns None is the list is empty.
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "order": 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 returnValue(self, key, last=False):
'''Return the key's value for the first entry in the current list.
If 'last=True', then the last entry is referenced."
Returns None is the list is empty or the key is missing.
Example of use:
>>> test = [
... {"name": "Jim", ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def returnValueList(self, key_list, last=False):
'''Return a list of key values for the first entry in the current list.
If 'last=True', then the last entry is referenced."
Returns None is the list is empty. If a key is missing, then
that entry in the list is None.
Example of u... |
<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_queryset(self, request):
"""Limit to TenantGroups that this user can access.""" |
qs = super(TenantGroupAdmin, self).get_queryset(request)
if not request.user.is_superuser:
qs = qs.filter(tenantrole__user=request.user,
tenantrole__role=TenantRole.ROLE_GROUP_MANAGER)
return qs |
<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_queryset(self, request):
"""Limit to Tenants that this user can access.""" |
qs = super(TenantAdmin, self).get_queryset(request)
if not request.user.is_superuser:
tenants_by_group_manager_role = qs.filter(
group__tenantrole__user=request.user,
group__tenantrole__role=TenantRole.ROLE_GROUP_MANAGER
)
tenants_by_t... |
<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(self, stream, media_type=None, parser_context=None):
""" Parses the incoming bytestream as a URL encoded form, and returns the resulting QueryDict. """ |
parser_context = parser_context or {}
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
data = QueryDict(stream.read(), encoding=encoding)
return 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 parse(self, stream, media_type=None, parser_context=None):
""" Parses the incoming bytestream as a multipart encoded form, and returns a DataAndFiles object.... |
parser_context = parser_context or {}
request = parser_context['request']
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
meta = request.META.copy()
meta['CONTENT_TYPE'] = media_type
upload_handlers = request.upload_handlers
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 parse(self, stream, media_type=None, parser_context=None):
""" Treats the incoming bytestream as a raw file upload and returns a `DataAndFiles` object. `.dat... |
parser_context = parser_context or {}
request = parser_context['request']
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
meta = request.META
upload_handlers = request.upload_handlers
filename = self.get_filename(stream, media_type, parser_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 get_filename(self, stream, media_type, parser_context):
""" Detects the uploaded file name. First searches a 'filename' url kwarg. Then tries to parse Conten... |
try:
return parser_context['kwargs']['filename']
except KeyError:
pass
try:
meta = parser_context['request'].META
disposition = parse_header(meta['HTTP_CONTENT_DISPOSITION'].encode('utf-8'))
filename_parm = disposition[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 destandardize(self, estimates, se, **kwargs):
"""Revert the betas and variance components back to the original scale. """ |
pvalues = kwargs["pvalues"]
v = kwargs["v"]
nonmissing=kwargs["nonmissing"]
pheno = self.datasource.phenotype_data[self.idx][self.datasource.phenotype_data[self.idx] != PhenoCovar.missing_encoding]
covariates = []
mmx = []
ssx = []
a = [1,0]
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 tar(self, appname, appversion):
""" Given an app name and version to be used in the tarball name, create a tar.bz2 file with all of this folder's contents in... |
name_tmpl = '%(app)s-%(version)s-%(time)s.tar.bz2'
time = utc.now()
name = name_tmpl % {'app': appname,
'version': appversion,
'time': time.strftime('%Y-%m-%dT%H-%M')}
if not os.path.exists(TARBALL_HOME):
os.mkdir(TARB... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.