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 drilldown_tree(self, session=None, json=False, json_fields=None):
""" This method generate a branch from a tree, begining with current node. For example: nod... |
if not session:
session = object_session(self)
return self.get_tree(
session,
json=json,
json_fields=json_fields,
query=self._drilldown_query
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def path_to_root(self, session=None, order=desc):
"""Generate path from a leaf or intermediate node to the root. For example: node11.path_to_root() .. code:: lev... |
table = self.__class__
query = self._base_query_obj(session=session)
query = query.filter(table.is_ancestor_of(self, inclusive=True))
return self._base_order(query, order=order) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rebuild_tree(cls, session, tree_id):
""" This method rebuid tree. Args: session (:mod:`sqlalchemy.orm.session.Session`):
SQLAlchemy session tree_id (int or ... |
session.query(cls).filter_by(tree_id=tree_id)\
.update({cls.left: 0, cls.right: 0, cls.level: 0})
top = session.query(cls).filter_by(parent_id=None)\
.filter_by(tree_id=tree_id).one()
top.left = left = 1
top.right = right = 2
top.level = level = cls.get_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 rebuild(cls, session, tree_id=None):
""" This function rebuid tree. Args: session (:mod:`sqlalchemy.orm.session.Session`):
SQLAlchemy session Kwargs: tree_i... |
trees = session.query(cls).filter_by(parent_id=None)
if tree_id:
trees = trees.filter_by(tree_id=tree_id)
for tree in trees:
cls.rebuild_tree(session, tree.tree_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 dx(mt, x):
""" Returns the number of dying at begining of age x """ |
end_x_val = mt.lx.index(0)
if x < end_x_val:
return mt.lx[x] - mt.lx[x + 1]
else:
return 0.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 Sx(mt, x):
""" Return the Sx """ |
n = len(mt.Nx)
sum1 = 0
for j in range(x, n):
k = mt.Nx[j]
sum1 += k
return sum1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Cx(mt, x):
""" Return the Cx """ |
return ((1 / (1 + mt.i)) ** (x + 1)) * mt.dx[x] * ((1 + mt.i) ** 0.5) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Mx(mt, x):
""" Return the Mx """ |
n = len(mt.Cx)
sum1 = 0
for j in range(x, n):
k = mt.Cx[j]
sum1 += k
return sum1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qAx(mt, x, q):
""" This function evaluates the APV of a geometrically increasing annual annuity-due """ |
q = float(q)
j = (mt.i - q) / (1 + q)
mtj = Actuarial(nt=mt.nt, i=j)
return Ax(mtj, 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 _meanvalueattr(self,v):
""" find new position of vertex v according to adjacency in prevlayer. position is given by the mean value of adjacent positions. exp... |
sug = self.layout
if not self.prevlayer(): return sug.grx[v].bar
bars = [sug.grx[x].bar for x in self._neighbors(v)]
return sug.grx[v].bar if len(bars)==0 else float(sum(bars))/len(bars) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw(self,N=1.5):
"""compute every node coordinates after converging to optimal ordering by N rounds, and finally perform the edge routing. """ |
while N>0.5:
for (l,mvmt) in self.ordering_step():
pass
N = N-1
if N>0:
for (l,mvmt) in self.ordering_step(oneway=True):
pass
self.setxy()
self.draw_edges() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setrank(self,v):
"""set rank value for vertex v and add it to the corresponding layer. The Layer is created if it is the first vertex with this rank. """ |
assert self.dag
r=max([self.grx[x].rank for x in v.N(-1)]+[-1])+1
self.grx[v].rank=r
# add it to its layer:
try:
self.layers[r].append(v)
except IndexError:
assert r==len(self.layers)
self.layers.append(Layer([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 dummyctrl(self,r,ctrl):
"""creates a DummyVertex at rank r inserted in the ctrl dict of the associated edge and layer. Arguments: r (int):
rank value ctrl (... |
dv = DummyVertex(r)
dv.view.w,dv.view.h=self.dw,self.dh
self.grx[dv] = dv
dv.ctrl = ctrl
ctrl[r] = dv
self.layers[r].append(dv)
return dv |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setdummies(self,e):
"""creates and defines all needed dummy vertices for edge e. """ |
v0,v1 = e.v
r0,r1 = self.grx[v0].rank,self.grx[v1].rank
if r0>r1:
assert e in self.alt_e
v0,v1 = v1,v0
r0,r1 = r1,r0
if (r1-r0)>1:
# "dummy vertices" are stored in the edge ctrl dict,
# keyed by their rank in layers.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _coord_vertical_alignment(self):
"""performs vertical alignment according to current dirvh internal state. """ |
dirh,dirv = self.dirh,self.dirv
g = self.grx
for l in self.layers[::-dirv]:
if not l.prevlayer(): continue
r=None
for vk in l[::dirh]:
for m in l._medianindex(vk):
# take the median node in dirv layer:
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 load_png(varNumVol, strPathPng, tplVslSpcSze=(200, 200), varStrtIdx=0, varZfill=3):
""" Load PNGs with stimulus information for pRF model creation. Parameter... |
# Create list of png files to load:
lstPngPaths = [None] * varNumVol
for idx01 in range(0, varNumVol):
lstPngPaths[idx01] = (strPathPng +
str(idx01 + varStrtIdx).zfill(varZfill) +
'.png')
# The png data will be saved in a numpy array ... |
<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_ev_txt(strPthEv):
"""Load information from event text file. Parameters input1 : str Path to event text file Returns ------- aryEvTxt : 2d numpy array, s... |
aryEvTxt = np.loadtxt(strPthEv, dtype='float', comments='#', delimiter=' ',
skiprows=0, usecols=(0, 1, 2))
return aryEvTxt |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adjust_status(info: dict) -> dict: """Apply status mapping to a raw API result.""" |
modified_info = deepcopy(info)
modified_info.update({
'level':
get_nearest_by_numeric_key(STATUS_MAP, int(info['level'])),
'level2':
STATUS_MAP[99] if info['level2'] is None else
get_nearest_by_numeric_key(STATUS_MAP, int(info['level2']))
})
return m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def status_by_state(self, state: str) -> dict: """Return the CDC status for the specified state.""" |
data = await self.raw_cdc_data()
try:
info = next((v for k, v in data.items() if state in k))
except StopIteration:
return {}
return adjust_status(info) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def brief_exception_text(exception, secret_values):
""" Returns the Exception class and the message of the exception as string. :param exception: The exception t... |
exception_text = _hide_secret_values(str(exception), secret_values)
return '[{}]\n{}'.format(type(exception).__name__, exception_text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_exception(exception, secret_values=None):
""" Prints the exception message and the name of the exception class to stderr. :param exception: The excepti... |
print(brief_exception_text(exception, secret_values), file=sys.stderr) |
<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, **kwargs):
""" Saves the Document to the database if it is valid. Returns errors otherwise. """ |
if self.is_valid:
before = self.before_insert()
if before:
return before
try:
self._document['_id'] = self.insert_one(self._document)
self.after_insert()
return self._document
except PyMongoExcept... |
<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, **kwargs):
""" Updates the document with the given _id saved in the collection if it is valid. Returns errors otherwise. """ |
if self.is_valid:
if '_id' in self._document:
to_update = self.find_one({'_id': self._id})
if to_update:
before = self.before_update(old=to_update)
if before:
return before
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 delete(self, **kwargs):
""" Deletes the document if it is saved in the collection. """ |
if self.is_valid:
if '_id' in self._document:
to_delete = self.find_one({'_id': self._id})
if to_delete:
before = self.before_delete()
if before:
return before
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 find_one(cls, filter=None, *args, **kwargs):
""" Returns one document dict if one passes the filter. Returns None otherwise. """ |
return cls.collection.find_one(filter, *args, **kwargs) |
<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(cls, *args, **kwargs):
""" Returns all document dicts that pass the filter """ |
return list(cls.collection.find(*args, **kwargs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aggregate(cls, pipeline=None, **kwargs):
""" Returns the document dicts returned from the Aggregation Pipeline """ |
return list(cls.collection.aggregate(pipeline or [], **kwargs)) |
<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_many(cls, documents, ordered=True):
""" Inserts a list of documents into the Collection and returns their _ids """ |
return cls.collection.insert_many(documents, ordered).inserted_ids |
<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_one(cls, filter, update, upsert=False):
""" Updates a document that passes the filter with the update value Will upsert a new document if upsert=True ... |
return cls.collection.update_one(filter, update, upsert).raw_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 update_many(cls, filter, update, upsert=False):
""" Updates all documents that pass the filter with the update value Will upsert a new document if upsert=Tru... |
return cls.collection.update_many(filter, update, upsert).raw_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 replace_one(cls, filter, replacement, upsert=False):
""" Replaces a document that passes the filter. Will upsert a new document if upsert=True and no documen... |
return cls.collection.replace_one(
filter, replacement, upsert
).raw_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 get(cls, filter=None, **kwargs):
""" Returns a Document if any document is filtered, returns None otherwise """ |
document = cls(cls.find_one(filter, **kwargs))
return document if document.document else 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 documents(cls, filter=None, **kwargs):
""" Returns a list of Documents if any document is filtered """ |
documents = [cls(document) for document in cls.find(filter, **kwargs)]
return [document for document in documents if document.document] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def in_file(self, fn: str) -> Iterator[Statement]: """ Returns an iterator over all of the statements belonging to a file. """ |
yield from self.__file_to_statements.get(fn, []) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def at_line(self, line: FileLine) -> Iterator[Statement]: """ Returns an iterator over all of the statements located at a given line. """ |
num = line.num
for stmt in self.in_file(line.filename):
if stmt.location.start.line == num:
yield stmt |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap(text, width=70, **kwargs):
"""Wrap multiple paragraphs of text, returning a list of wrapped lines. Reformat the multiple paragraphs 'text' so they fit i... |
w = ParagraphWrapper(width=width, **kwargs)
return w.wrap(text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fill(text, width=70, **kwargs):
"""Fill multiple paragraphs of text, returning a new string. Reformat multiple paragraphs in 'text' to fit in lines of no mor... |
w = ParagraphWrapper(width=width, **kwargs)
return w.fill(text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_outdir(outdir):
""" Creates the output directory if not existing. If outdir is None or if no output_files are provided nothing happens. :param outdir... |
if outdir:
outdir = os.path.expanduser(outdir)
if not os.path.isdir(outdir):
try:
os.makedirs(outdir)
except os.error as e:
raise JobExecutionError('Failed to create outdir "{}".\n{}'.format(outdir, str(e))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def model_node(**kwargs):
""" Decorates a ``schematics.Model`` class to add it as a field of type ``schematic.types.ModelType``. Keyword arguments are passed to ... |
kwargs.setdefault('default', {})
def decorator(model):
return types.ModelType(model, **kwargs)
return decorator |
<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_file_read_only(file_path):
""" Removes the write permissions for the given file for owner, groups and others. :param file_path: The file whose privilege... |
old_permissions = os.stat(file_path).st_mode
os.chmod(file_path, old_permissions & ~WRITE_PERMISSIONS) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def status_by_zip(self, zip_code: str) -> dict: """Get symptom data for the provided ZIP code.""" |
try:
location = next((
d for d in await self.user_reports()
if d['zip'] == zip_code))
except StopIteration:
return {}
return await self.status_by_coordinates(
float(location['latitude']), float(location['longitude'])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_request(request):
""" Prints a prepared request to give the user info as to what they're sending :param request.PreparedRequest request: PreparedReques... |
print('{}\n{}\n{}\n\n{}'.format(
'-----------START-----------',
request.method + ' ' + request.url,
'\n'.join('{}: {}'.format(k, v) for k, v in request.headers.items()),
request.body,
)) |
<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_validate_schemas(get_response, params):
""" This filter validates input data against the resource's ``request_schema`` and fill the request's ``valida... |
request_schema = params.get('request_schema')
if request_schema is None:
return get_response
def _convert_params(schema, data):
for sc in schema.fields.values():
name = sc.serialized_name or sc.name
val = data.getlist(name)
if val is 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 make_EPUB(parsed_article, output_directory, input_path, image_directory, config_module=None, epub_version=None, batch=False):
""" Standard workflow for creat... |
#command_log.info('Creating {0}.epub'.format(output_directory))
if config_module is None:
config_module = openaccess_epub.utils.load_config_module()
if epub_version not in (None, 2, 3):
log.error('Invalid EPUB version: {0}'.format(epub_version))
raise ValueError('Invalid EPUB versi... |
<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_epub_base(location):
""" Creates the base structure for an EPUB file in a specified location. This function creates constant components for the structur... |
log.info('Making EPUB base files in {0}'.format(location))
with open(os.path.join(location, 'mimetype'), 'w') as out: # mimetype file
out.write('application/epub+zip')
#Create EPUB and META-INF directorys
os.mkdir(os.path.join(location, 'META-INF'))
os.mkdir(os.path.join(location, 'EPUB')... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def epub_zip(outdirect):
""" Zips up the input file directory into an EPUB file. """ |
def recursive_zip(zipf, directory, folder=None):
if folder is None:
folder = ''
for item in os.listdir(directory):
if os.path.isfile(os.path.join(directory, item)):
zipf.write(os.path.join(directory, item),
os.path.join(directory, ... |
<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_int(fname, data, append=True):
"""Write data to CSV file with validation.""" |
# pylint: disable=W0705
data_ex = pexdoc.exh.addex(ValueError, "There is no data to save to file")
fos_ex = pexdoc.exh.addex(
OSError, "File *[fname]* could not be created: *[reason]*"
)
data_ex((len(data) == 0) or ((len(data) == 1) and (len(data[0]) == 0)))
try:
pmisc.make_dir(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _input_directory_description(input_identifier, arg_item, input_dir):
""" Produces a directory description. A directory description is a dictionary containing... |
description = {
'path': None,
'found': False,
'debugInfo': None,
'listing': None,
'basename': None
}
try:
path = location(input_identifier, arg_item)
if input_dir and not os.path.isabs(path):
path = os.path.join(os.path.expanduser(input_... |
<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_input_directory_listing(base_directory, listing):
""" Raises an DirectoryError if files or directories, given in the listing, could not be found in th... |
for sub in listing:
path = os.path.join(base_directory, sub['basename'])
if sub['class'] == 'File':
if not os.path.isfile(path):
raise DirectoryError('File \'{}\' not found but specified in listing.'.format(path))
if sub['class'] == 'Directory':
if 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_cwl_type(cwl_type_string):
""" Parses cwl type information from a cwl type string. Examples: - "File[]" -> {'type': 'File', 'isArray': True, 'isOptiona... |
is_optional = cwl_type_string.endswith('?')
if is_optional:
cwl_type_string = cwl_type_string[:-1]
is_array = cwl_type_string.endswith('[]')
if is_array:
cwl_type_string = cwl_type_string[:-2]
return {'type': cwl_type_string, 'isArray': is_array, 'isOptional': is_optional} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cwl_input_directories(cwl_data, job_data, input_dir=None):
""" Searches for Directories and in the cwl data and produces a dictionary containing input file i... |
results = {}
for input_identifier, input_data in cwl_data['inputs'].items():
cwl_type = parse_cwl_type(input_data['type'])
(is_optional, is_array, cwl_type) = itemgetter('isOptional', 'isArray', 'type')(cwl_type)
if cwl_type == 'Directory':
result = {
'is... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cwl_output_files(cwl_data, inputs_to_reference, output_dir=None):
""" Returns a dictionary containing information about the output files given in cwl_data. :... |
results = {}
for key, val in cwl_data['outputs'].items():
cwl_type = parse_cwl_type(val['type'])
(is_optional, is_array, cwl_type) = itemgetter('isOptional', 'isArray', 'type')(cwl_type)
if not cwl_type == 'File':
continue
result = {
'isOptional': is_o... |
<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(self, length=-1):
""" Reads from the FIFO. Reads as much data as possible from the FIFO up to the specified length. If the length argument is negative o... |
if 0 <= length < len(self):
newpos = self.pos + length
data = self.buf[self.pos:newpos]
self.pos = newpos
self.__discard()
return data
data = self.buf[self.pos:]
self.clear()
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 readuntil(self, token, size=0):
""" Reads data from the FIFO until a token is encountered. If no token is encountered as much data is read from the FIFO as p... |
self.__append()
i = self.buf.find(token, self.pos)
if i < 0:
index = max(len(token) - 1, size)
newpos = max(len(self.buf) - index, self.pos)
data = self.buf[self.pos:newpos]
self.pos = newpos
self.__discard()
return 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 peekline(self):
""" Peeks a line into the FIFO. Perfroms the same function as readline() without removing data from the FIFO. See readline() for further info... |
self.__append()
i = self.buf.find(self.eol, self.pos)
if i < 0:
return ''
newpos = i + len(self.eol)
return self.buf[self.pos:newpos] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def peekuntil(self, token, size=0):
""" Peeks for token into the FIFO. Performs the same function as readuntil() without removing data from the FIFO. See readunt... |
self.__append()
i = self.buf.find(token, self.pos)
if i < 0:
index = max(len(token) - 1, size)
newpos = max(len(self.buf) - index, self.pos)
return False, self.buf[self.pos:newpos]
newpos = i + len(token)
return True, self.buf[self.pos:newpo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def revdocs2reverts(rev_docs, radius=defaults.RADIUS, use_sha1=False, resort=False, verbose=False):
""" Converts a sequence of page-partitioned revision document... |
page_rev_docs = groupby(rev_docs, lambda rd: rd.get('page'))
for page_doc, rev_docs in page_rev_docs:
if verbose:
sys.stderr.write(page_doc.get('title') + ": ")
sys.stderr.flush()
if resort:
if verbose:
sys.stderr.write("(sorting) ")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spm_hrf_compat(t, peak_delay=6, under_delay=16, peak_disp=1, under_disp=1, p_u_ratio=6, normalize=True, ):
""" SPM HRF function from sum of two gamma PDFs Th... |
if len([v for v in [peak_delay, peak_disp, under_delay, under_disp]
if v <= 0]):
raise ValueError("delays and dispersions must be > 0")
# gamma.pdf only defined for t > 0
hrf = np.zeros(t.shape, dtype=np.float)
pos_t = t[t > 0]
peak = sps.gamma.pdf(pos_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 dsort(fname, order, has_header=True, frow=0, ofname=None):
r""" Sort file data. :param fname: Name of the comma-separated values file to sort :type fname: Fi... |
ofname = fname if ofname is None else ofname
obj = CsvFile(fname=fname, has_header=has_header, frow=frow)
obj.dsort(order)
obj.write(fname=ofname, header=has_header, append=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 call(cls, method, params=None, timeout=600):
""" Makes a Call to the LBRY API :param str method: Method to call from the LBRY API. See the full list of metho... |
params = [] if params is None else params
return cls.make_request(SERVER_ADDRESS, method, params, timeout=timeout) |
<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_document(self, titlestring):
""" This method may be used to create a new document for writing as xml to the OPS subdirectory of the ePub structure. """ |
#root = etree.XML('''<?xml version="1.0"?>\
#<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.1//EN' 'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'>\
#<html xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml" xmlns:ops="http://www.idpf.org/2007/ops">\
#</html>''')
root = etree.XML('''<?xml version="1.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 write_document(self, name, document):
""" This function will write a document to an XML file. """ |
with open(name, 'wb') as out:
out.write(etree.tostring(document,
encoding='utf-8',
pretty_print=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_date_string(self, date_tuple):
""" Receives a date_tuple object, and outputs a string for placement in the article content. """ |
months = ['', 'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December']
date_string = ''
if date_tuple.season:
return '{0}, {1}'.format(date_tuple.season, date_tuple.year)
else:
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_out_of_flow_tables(self):
""" Returns True if the article has out-of-flow tables, indicates separate tables document. This method is used to indicate whe... |
if self.article.body is None:
return False
for table_wrap in self.article.body.findall('.//table-wrap'):
graphic = table_wrap.xpath('./graphic | ./alternatives/graphic')
table = table_wrap.xpath('./table | ./alternatives/table')
if graphic and table:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self, article):
""" Ingests an Article to create navigation structures and parse global metadata. """ |
if self.article is not None and not self.collection:
log.warning('Could not process additional article. Navigation only \
handles one article unless collection mode is set.')
return False
if article.publisher is None:
log.error('''Navigation cannot be generated 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 map_navigation(self):
""" This is a wrapper for depth-first recursive analysis of the article """ |
#All articles should have titles
title_id = 'titlepage-{0}'.format(self.article_doi)
title_label = self.article.publisher.nav_title()
title_source = 'main.{0}.xhtml#title'.format(self.article_doi)
title_navpoint = navpoint(title_id, title_label, self.play_order,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recursive_article_navmap(self, src_element, depth=0, first=True):
""" This function recursively traverses the content of an input article to add the correct ... |
if depth > self.nav_depth:
self.nav_depth = depth
navpoints = []
tagnames = ['sec', 'fig', 'table-wrap']
for child in src_element:
try:
tagname = child.tag
except AttributeError:
continue
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 funcConvPar(aryDm, vecHrf, varNumVol):
""" Function for convolution of pixel-wise 'design matrix' with HRF model. """ |
# In order to avoid an artefact at the end of the time series, we have to
# concatenate an empty array to both the design matrix and the HRF model
# before convolution.
aryDm = np.concatenate((aryDm, np.zeros((aryDm.shape[0], 100))), axis=1)
vecHrf = np.concatenate((vecHrf, np.zeros((100,))))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def funcNrlTcMotPred(idxPrc, varPixX, varPixY, NrlMdlChunk, varNumTP, aryBoxCar, # aryCond path, varNumNrlMdls, varNumMtDrctn, varPar, queOut):
""" Function for ... |
# # if hd5 method is used: open file for reading
# filename = 'aryBoxCar' + str(idxPrc) + '.hdf5'
# hdf5_path = os.path.join(path, filename)
# fileH = tables.openFile(hdf5_path, mode='r')
# Output array with pRF model time courses at all modelled standard
# deviations for current pixel position:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def funcFindPrf(idxPrc, aryFuncChnk, aryPrfTc, aryMdls, queOut):
""" Function for finding best pRF model for voxel time course. This function should be used if t... |
# Number of voxels to be fitted in this chunk:
varNumVoxChnk = aryFuncChnk.shape[0]
# Number of volumes:
varNumVol = aryFuncChnk.shape[1]
# Vectors for pRF finding results [number-of-voxels times one]:
vecBstXpos = np.zeros(varNumVoxChnk)
vecBstYpos = np.zeros(varNumVoxChnk)
vecBstSd... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def concatenate( fname1, fname2, dfilter1=None, dfilter2=None, has_header1=True, has_header2=True, frow1=0, frow2=0, ofname=None, ocols=None, ):
r""" Concatenate... |
# pylint: disable=R0913,R0914
iro = pexdoc.exh.addex(RuntimeError, "Files have different number of columns")
iom = pexdoc.exh.addex(
RuntimeError, "Number of columns in data files and output columns are different"
)
# Read and validate file 1
obj1 = CsvFile(fname=fname1, dfilter=dfilter... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_images_to_cache(source, destination):
""" Handles the movement of images to the cache. Must be helpful if it finds that the folder for this article alre... |
if os.path.isdir(destination):
log.debug('Cached images for this article already exist')
return
else:
log.debug('Cache location: {0}'.format(destination))
try:
shutil.copytree(source, destination)
except:
log.exception('Images could not be moved 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 explicit_images(images, image_destination, rootname, config):
""" The method used to handle an explicitly defined image directory by the user as a parsed arg... |
log.info('Explicit image directory specified: {0}'.format(images))
if '*' in images:
images = images.replace('*', rootname)
log.debug('Wildcard expansion for image directory: {0}'.format(images))
try:
shutil.copytree(images, image_destination)
except:
#The following is b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def input_relative_images(input_path, image_destination, rootname, config):
""" The method used to handle Input-Relative image inclusion. """ |
log.debug('Looking for input relative images')
input_dirname = os.path.dirname(input_path)
for path in config.input_relative_images:
if '*' in path:
path = path.replace('*', rootname)
log.debug('Wildcard expansion for image directory: {0}'.format(path))
images = os.p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_images(output_directory, explicit, input_path, config, parsed_article):
""" Main logic controller for the placement of images into the output directory C... |
#Split the DOI
journal_doi, article_doi = parsed_article.doi.split('/')
log.debug('journal-doi : {0}'.format(journal_doi))
log.debug('article-doi : {0}'.format(article_doi))
#Get the rootname for wildcard expansion
rootname = utils.file_root_name(input_path)
#Specify where to place the im... |
<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_image_cache(img_cache):
""" Initiates the image cache if it does not exist """ |
log.info('Initiating the image cache at {0}'.format(img_cache))
if not os.path.isdir(img_cache):
utils.mkdir_p(img_cache)
utils.mkdir_p(os.path.join(img_cache, '10.1371'))
utils.mkdir_p(os.path.join(img_cache, '10.3389')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_plos_images(article_doi, output_dir, document):
""" Fetch the images for a PLoS article from the internet. PLoS images are known through the inspection... |
log.info('Processing images for {0}...'.format(article_doi))
#A dict of URLs for PLoS subjournals
journal_urls = {'pgen': 'http://www.plosgenetics.org/article/{0}',
'pcbi': 'http://www.ploscompbiol.org/article/{0}',
'ppat': 'http://www.plospathogens.org/article/{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 get_nearest_by_numeric_key(data: dict, key: int) -> Any: """Return the dict element whose numeric key is closest to a target.""" |
return data.get(key, data[min(data.keys(), key=lambda k: abs(k - 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 resource(self, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, stream=False, version=None, name=None, **kwargs):
""" Create a blueprint reso... |
if strict_slashes is None:
strict_slashes = self.strict_slashes
def decorator(handler):
self.resources.append((
FutureRoute(handler, uri, methods, host, strict_slashes,
stream, version, name),
kwargs))
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_resource(self, handler, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, version=None, name=None, **kwargs):
""" Create a blueprint resou... |
self.resource(uri=uri, methods=methods, host=host,
strict_slashes=strict_slashes, version=version,
name=name, **kwargs)(handler) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_db():
""" Returns the connection to the database using the settings. This function should not be called outside of this file. Use db instead. """ |
from .settings import settings
mongo = settings.MONGODB
if 'URI' in mongo and mongo['URI']:
uri = mongo['URI']
else:
uri = 'mongodb://'
if all(mongo.get(key) for key in ('USERNAME', 'PASSWORD')):
uri += '{0}:{1}@'.format(mongo['USERNAME'], mongo['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 plos_doi_to_xmlurl(doi_string):
""" Attempts to resolve a PLoS DOI into a URL path to the XML file. """ |
#Create URL to request DOI resolution from http://dx.doi.org
doi_url = 'http://dx.doi.org/{0}'.format(doi_string)
log.debug('DOI URL: {0}'.format(doi_url))
#Open the page, follow the redirect
try:
resolved_page = urllib.request.urlopen(doi_url)
except urllib.error.URLError as 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 doi_input(doi_string, download=True):
""" This method accepts a DOI string and attempts to download the appropriate xml file. If successful, it returns a pat... |
log.debug('DOI Input - {0}'.format(doi_string))
doi_string = doi_string[4:]
if '10.1371' in doi_string: # Corresponds to PLoS
log.debug('DOI string shows PLoS')
xml_url = plos_doi_to_xmlurl(doi_string)
else:
log.critical('DOI input for this publisher is not supported')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url_input(url_string, download=True):
""" This method expects a direct URL link to an xml file. It will apply no modifications to the received URL string, so... |
log.debug('URL Input - {0}'.format(url_string))
try:
open_xml = urllib.request.urlopen(url_string)
except urllib.error.URLError as err:
print('utils.input.url_input received a bad URL, or could not connect')
raise err
else:
#Employ a quick check on the mimetype of the li... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def frontiersZipInput(zip_path, output_prefix, download=None):
""" This method provides support for Frontiers production using base zipfiles as the input for ePu... |
log.debug('frontiersZipInput called')
#If there is a problem with the input, it should clearly describe the issue
pathname, pathext = os.path.splitext(zip_path)
path, name = os.path.split(pathname)
if not pathext == '.zip': # Checks for a path to zipfile
log.error('Pathname provided 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 _red_listing_validation(key, listing):
""" Raises an RedValidationError, if the given listing does not comply with cwl_job_listing_schema. If listing is None... |
if listing:
try:
jsonschema.validate(listing, cwl_job_listing_schema)
except ValidationError as e:
raise RedValidationError('REDFILE listing of input "{}" does not comply with jsonschema: {}'
.format(key, e.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 red_get_mount_connectors(red_data, ignore_outputs):
""" Returns a list of mounting connectors :param red_data: The red data to be searched :param ignore_outp... |
keys = []
batches = red_data.get('batches')
inputs = red_data.get('inputs')
if batches:
for batch in batches:
keys.extend(red_get_mount_connectors_from_inputs(batch['inputs']))
elif inputs:
keys.extend(red_get_mount_connectors_from_inputs(inputs))
if not ignore_ou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup(connector_manager, red_data, tmp_dir):
""" Invokes the cleanup functions for all inputs. """ |
for key, arg in red_data['inputs'].items():
val = arg
if isinstance(arg, list):
for index, i in enumerate(arg):
if not isinstance(i, dict):
continue
# connector_class should be one of 'File' or 'Directory'
connector_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 _execute_connector(connector_command, top_level_argument, *file_contents, listing=None):
""" Executes a connector by executing the given connector_command. T... |
# create temp_files for every file_content
temp_files = []
for file_content in file_contents:
if file_content is None:
continue
tmp_file = tempfile.NamedTemporaryFile('w')
json.dump(file_content, tmp_file)
tmp_file.flush()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def directory_listing_content_check(directory_path, listing):
""" Checks if a given listing is present under the given directory path. :param directory_path: The... |
if listing:
for sub in listing:
path = os.path.join(directory_path, sub['basename'])
if sub['class'] == 'File':
if not os.path.isfile(path):
return 'listing contains "{}" but this file could not be found on disk.'.format(pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match_gpus(available_devices, requirements):
""" Determines sufficient GPUs for the given requirements and returns a list of GPUDevices. If there aren't suff... |
if not requirements:
return []
if not available_devices:
raise InsufficientGPUError("No GPU devices available, but {} devices required.".format(len(requirements)))
available_devices = available_devices.copy()
used_devices = []
for req in requirements:
dev = search_devic... |
<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_gpu_requirements(gpus_reqs):
""" Extracts the GPU from a dictionary requirements as list of GPURequirements. :return: A list of GPURequirements """ |
requirements = []
if gpus_reqs:
if type(gpus_reqs) is dict:
count = gpus_reqs.get('count')
if count:
for i in range(count):
requirements.append(GPURequirement())
elif type(gpus_reqs) is list:
for gpu_req in gpus_reqs:
... |
<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_nvidia_environment_variables(environment, gpu_ids):
""" Updates a dictionary containing environment variables to setup Nvidia-GPUs. :param environment: T... |
if gpu_ids:
nvidia_visible_devices = ""
for gpu_id in gpu_ids:
nvidia_visible_devices += "{},".format(gpu_id)
environment["NVIDIA_VISIBLE_DEVICES"] = nvidia_visible_devices |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_sufficient(self, device):
""" Returns whether the device is sufficient for this requirement. :param device: A GPUDevice instance. :type device: GPUDevice ... |
sufficient = True
if (self.min_vram is not None) and (device.vram < self.min_vram):
sufficient = False
return sufficient |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def cache_location():
'''Cross-platform placement of cached files'''
plat = platform.platform()
log.debug('Platform read as: {0}'.format(plat))
if plat.startswith('Windows'):
log.debug('Windows platform detected')
return os.path.join(os.environ['APPDATA'], 'OpenAccess_EPUB')
elif pla... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate_relative_path(working=os.getcwd(), relative=''):
""" This function receives two strings representing system paths. The first is the working director... |
return os.path.normpath(os.path.join(working, relative)) |
<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_absolute_path(some_path):
""" This function will return an appropriate absolute path for the path it is given. If the input is absolute, it will return u... |
if os.path.isabs(some_path):
return some_path
else:
return evaluate_relative_path(os.getcwd(), some_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 file_root_name(name):
""" Returns the root name of a file from a full file path. It will not raise an error if the result is empty, but an warning will be is... |
base = os.path.basename(name)
root = os.path.splitext(base)[0]
if not root:
warning = 'file_root_name returned an empty root name from \"{0}\"'
log.warning(warning.format(name))
return root |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def files_with_ext(extension, directory='.', recursive=False):
""" Generator function that will iterate over all files in the specified directory and return a pa... |
if recursive:
log.info('Recursively searching {0} for files with extension "{1}"'.format(directory, extension))
for dirname, subdirnames, filenames in os.walk(directory):
for filename in filenames:
filepath = os.path.join(dirname, filename)
_root, ext = o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def epubcheck(epubname, config=None):
""" This method takes the name of an epub file as an argument. This name is the input for the java execution of a locally i... |
if config is None:
config = load_config_module()
r, e = os.path.splitext(epubname)
if not e:
log.warning('Missing file extension, appending ".epub"')
e = '.epub'
epubname = r + e
elif not e == '.epub':
log.warning('File does not have ".epub" extension, appending ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.