output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Dispatch execution over a pool of processors | Here you have a function in Python 3, explain what it does
def parallel_deblur(inputs, params,
pos_ref_db_fp, neg_ref_dp_fp, jobs_to_start=1):
"""Dispatch execution over a pool of processors
This code was adopted from the American Gut project:
https://github.com/biocore/American-Gut/blo... | You are a Python code architect, reviewing and designing scalable and efficient code |
def sequence_generator(input_fp):
"""Yield (id, sequence) from an input file
Parameters
----------
input_fp : filepath
A filepath, which can be any valid fasta or fastq file within the
limitations of scikit-bio's IO registry.
Notes
-----
The use of this method is a stopgap ... | Write a Python 3 script for
yielding (id, sequence) from an input file Parameters ---------- input_fp : filepath A filepath, which can be any valid fasta or fastq file within the limitations of scikit-bio's IO registry. Notes ----- The use of this method is a stopgap to replicate the existing `parse_fasta` functionalit... | As a Python code analyst, you investigate and solve complex coding mysteries |
Trim FASTA sequences to specified length. | Explain what the following Python 3 code does
def trim_seqs(input_seqs, trim_len, left_trim_len):
# counters for the number of trimmed and total sequences
logger = logging.getLogger(__name__)
okseqs = 0
totseqs = 0
if trim_len < -1:
raise ValueError("Invalid trim_len: %d" % trim_len)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def build_index_sortmerna(ref_fp, working_dir):
"""Build a SortMeRNA index for all reference databases.
Parameters
----------
ref_fp: tuple
filepaths to FASTA reference databases
working_dir: string
working directory path where to store the indexed database
Returns
-------
... | Create a Python 3 function to
build a SortMeRNA index for all reference databases. | You are a Python code analyst, evaluating scripts for potential improvements. |
def filter_minreads_samples_from_table(table, minreads=1, inplace=True):
"""Filter samples from biom table that have less than
minreads reads total
Paraneters
----------
table : biom.Table
the biom table to filter
minreads : int (optional)
the minimal number of reads in a sample... | Can you implement a function in Python 3 that
filters samples from a biom table that have less than minreads reads | As a Python code translator, you convert algorithms and pseudocode into Python. |
Save sequences from a biom table to a fasta file | Here you have a function in Python 3, explain what it does
def fasta_from_biom(table, fasta_file_name):
'''Save sequences from a biom table to a fasta file
Parameters
----------
table : biom.Table
The biom table containing the sequences
fasta_file_name : str
Name of the fasta output... | As a Python code analyst, you investigate and solve complex coding mysteries |
Remove artifacts from a biom table using SortMeRNA
| Can you generate a brief explanation for the following Python 3 code
def remove_artifacts_from_biom_table(table_filename,
fasta_filename,
ref_fp,
biom_table_dir,
ref_db_fp,... | As a Python code analyst, you investigate and solve complex coding mysteries |
def remove_artifacts_seqs(seqs_fp,
ref_fp,
working_dir,
ref_db_fp,
negate=False,
threads=1,
verbose=False,
sim_thresh=None,
... | Can you create a Python 3 function that
removes artifacts from a FASTA file using SortMeRNA. | You are a Python code architect, reviewing and designing scalable and efficient code |
Perform multiple sequence alignment on a FASTA file using MAFFT. | Can you generate a brief explanation for the following Python 3 code
def multiple_sequence_alignment(seqs_fp, threads=1):
logger = logging.getLogger(__name__)
logger.info('multiple_sequence_alignment seqs file %s' % seqs_fp)
# for mafft we use -1 to denote all threads and not 0
if threads == 0:
... | As a python code expert, you are capable of creating scripts from specifications. |
Remove chimeras de novo from a set of sequences. | Can you generate a brief explanation for the following Python 3 code
def remove_chimeras_denovo_from_seqs(seqs_fp, working_dir, threads=1):
logger = logging.getLogger(__name__)
logger.info('remove_chimeras_denovo_from_seqs seqs file %s'
'to working dir %s' % (seqs_fp, working_dir))
output_f... | You are a Python code architect, reviewing and designing scalable and efficient code |
def split_sequence_file_on_sample_ids_to_files(seqs,
outdir):
"""Split FASTA file on sample IDs.
Parameters
----------
seqs: file handler
file handler to demultiplexed FASTA file
outdir: string
dirpath to output split FASTA files
""... | Create a Python 3 function to
split FASTA file on sample IDs and store them in a dict of dicts. | As a Python code composer, you craft elegant and concise scripts. |
def write_biom_table(table, biom_fp):
"""Write BIOM table to file.
Parameters
----------
table: biom.table
an instance of a BIOM table
biom_fp: string
filepath to output BIOM table
"""
logger = logging.getLogger(__name__)
logger.debug('write_biom_table to file %s' % biom... | Can you implement a function in Python 3 that
writes a BIOM table to file. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get a list of files to add to the biom table | Here you have a function in Python 3, explain what it does
def get_files_for_table(input_dir,
file_end='.trim.derep.no_artifacts'
'.msa.deblur.no_chimeras'):
"""Get a list of files to add to the output table
Parameters:
-----------
input_dir : string
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def create_otu_table(output_fp, deblurred_list,
outputfasta_fp=None, minreads=0):
"""Create a biom table out of all files in a directory
Parameters
----------
output_fp : string
filepath to output BIOM table
deblurred_list : list of (str, str)
list of file names... | Create a Python 3 function for
creating a BIOM table out of all samples in a directory and a list of deblurred sample ids and a list of sequences in a directory. | You are a Python code architect, reviewing and designing scalable and efficient code |
def launch_workflow(seqs_fp, working_dir, mean_error, error_dist,
indel_prob, indel_max, trim_length, left_trim_length,
min_size, ref_fp, ref_db_fp, threads_per_sample=1,
sim_thresh=None, coverage_thresh=None):
"""Launch full deblur workflow for a single p... | Can you write a function in Python 3 where it
launches a full deblur workflow for a single post split - libraries fasta file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def start_log(level=logging.DEBUG, filename=None):
"""start the logger for the run
Parameters
----------
level : int, optional
logging.DEBUG, logging.INFO etc. for the log level (between 0-50).
filename : str, optional
name of the filename to save the log to or
None (default) to... | How would you code a function in Python 3 to
start the logger for the run | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _system_call(cmd, stdoutfilename=None):
"""Execute the command `cmd`
Parameters
----------
cmd : str
The string containing the command to be run.
stdoutfilename : str
Name of the file to save stdout to or None
(default) to not save to file
stderrfilename : str
... | Create a Python 3 function for
executing the command cmd and return the standard output and standard error and exist status of the command. | As a Python code composer, you craft elegant and concise scripts. |
Returns a list of Sequences
| Explain what the following Python 3 code does
def get_sequences(input_seqs):
try:
seqs = [Sequence(id, seq) for id, seq in input_seqs]
except Exception:
seqs = []
if len(seqs) == 0:
logger = logging.getLogger(__name__)
logger.warn('No sequences found in fasta file!')
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a string with the sequence in fasta format | Can you generate a brief explanation for the following Python 3 code
def to_fasta(self):
prefix, suffix = re.split('(?<=size=)\w+', self.label, maxsplit=1)
new_count = int(round(self.frequency))
new_label = "%s%d%s" % (prefix, new_count, suffix)
return ">%s\n%s\n" % (new_label, self.sequ... | You are a Python code generator, capable of creating scripts from specifications. |
def render_select2_options_code(self, options, id_):
"""Render options for select2."""
output = []
for key, value in options.items():
if isinstance(value, (dict, list)):
value = json.dumps(value)
output.append("data-{name}='{value}'".format(
... | Implement a Python 3 function for
rendering options for select2. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def render_js_code(self, id_, *args, **kwargs):
"""Render html container for Select2 widget with options."""
if id_:
options = self.render_select2_options_code(
dict(self.get_options()), id_)
return mark_safe(self.html.format(id=id_, options=options))
... | Create a Python 3 function for
rendering html container for Select2 widget with options. | As a Python code composer, you craft elegant and concise scripts. |
def render(self, name, value, attrs=None, **kwargs):
"""
Extend base class's `render` method by appending
javascript inline text to html output.
"""
output = super(Select2Mixin, self).render(
name, value, attrs=attrs, **kwargs)
id_ = attrs['id']
output... | How would you implement a function in Python 3 that
extends base class s render method by appending javascript inline text to html output. | As a Python code analyst, you investigate and solve complex coding mysteries |
def visit_console_html(self, node):
"""Generate HTML for the console directive."""
if self.builder.name in ('djangohtml', 'json') and node['win_console_text']:
# Put a mark on the document object signaling the fact the directive
# has been used on it.
self.document._console_directive_use... | How would you implement a function in Python 3 that
generates the console directive. | You are a Python code generator, capable of creating scripts from specifications. |
Returns a new meta class with Select2 - enabled widgets for fields
racket with kwargs | Can you generate the documentation for the following Python 3 function
def select2_modelform_meta(model,
meta_fields=None,
widgets=None,
attrs=None,
**kwargs):
"""
Return `Meta` class with Select2-enabled... | As a python code expert, you are capable of creating scripts from specifications. |
def select2_modelform(
model, attrs=None, form_class=es2_forms.FixedModelForm):
"""
Return ModelForm class for model with select2 widgets.
Arguments:
attrs: select2 widget attributes (width, for example) of type `dict`.
form_class: modelform base class, `forms.ModelForm` by default.... | Create a Python 3 function for
returning a modelform class for a model with select2 widgets. | You are a Python code analyst, evaluating scripts for potential improvements. |
def lex(self, text):
""" Yield (token_type, str_data) tokens.
The last token will be (EOF, None) where EOF is the singleton object
defined in this module.
"""
for match in self.regex.finditer(text):
for name, _ in self.lexicon:
m = match.group(name)
... | How would you implement a function in Python 3 that
yields (token_type, str_data) tokens. The last token will be (EOF, None) where EOF is the singleton object defined in this module. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def parse(self, text):
""" Parse a string of SVG transform="" data.
"""
gen = self.lexer.lex(text)
next_val_fn = partial(next, *(gen,))
commands = []
token = next_val_fn()
while token[0] is not EOF:
command, token = self.rule_svg_transform(next_val_fn... | Can you implement a function in Python 3 that
parses a string of SVG transform = " data. | You are a Python code analyst, evaluating scripts for potential improvements. |
def parse(self, text):
""" Parse a string of SVG <path> data.
"""
gen = self.lexer.lex(text)
next_val_fn = partial(next, *(gen,))
token = next_val_fn()
return self.rule_svg_path(next_val_fn, token) | Implement a Python 3 function for
parsing a string of SVG <path > data. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns all elements with id attributes | Can you generate the documentation for the following Python 3 function
def findElementsWithId(node, elems=None):
if elems is None:
elems = {}
id = node.getAttribute('id')
if id != '':
elems[id] = node
if node.hasChildNodes():
for child in node.childNodes:
# from http:... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def findReferencedElements(node, ids=None):
"""
Returns IDs of all referenced elements
- node is the node at which to start the search.
- returns a map which has the id as key and
each value is is a list of nodes
Currently looks at 'xlink:href' and all attributes in 'referencingProps'
"""... | Can you implement a function in Python 3 that
finds all elements that are referenced by a node. | As a Python code analyst, you investigate and solve complex coding mysteries |
def removeUnreferencedElements(doc, keepDefs):
"""
Removes all unreferenced elements except for <svg>, <font>, <metadata>, <title>, and <desc>.
Also vacuums the defs of any non-referenced renderable elements.
Returns the number of unreferenced elements removed from the document.
"""
global _num... | Implement a function in Python 3 to
remove all unreferenced elements from the document. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Shortens the IDs used in the document to have the given prefix. | Make a summary of the following Python 3 code
def shortenIDs(doc, prefix, unprotectedElements=None):
num = 0
identifiedElements = findElementsWithId(doc.documentElement)
if unprotectedElements is None:
unprotectedElements = identifiedElements
referencedIDs = findReferencedElements(doc.documentE... | As a Python code composer, you craft elegant and concise scripts. |
def intToID(idnum, prefix):
"""
Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z,
then from aa to az, ba to bz, etc., until zz.
"""
rid = ''
while idnum > 0:
idnum -= 1
rid = chr((idnum % 26) + ord('a')) + rid
idnum = int(idnum / 26)
... | Write a Python 3 script for
returning the ID name for the given ID number. | As a Python code composer, you craft elegant and concise scripts. |
def renameID(doc, idFrom, idTo, identifiedElements, referencedIDs):
"""
Changes the ID name from idFrom to idTo, on the declaring element
as well as all references in the document doc.
Updates identifiedElements and referencedIDs.
Does not handle the case where idTo is already the ID name
of an... | Write a Python 3 function for
renaming an ID name from idFrom to idTo on the declaring element identifiedElements and referencedIDs. | As a Python code translator, you convert algorithms and pseudocode into Python. |
u Returns a list of unprotected IDs within the document doc. | Given the following Python 3 function, write the documentation
def unprotected_ids(doc, options):
identifiedElements = findElementsWithId(doc.documentElement)
if not (options.protect_ids_noninkscape or
options.protect_ids_list or
options.protect_ids_prefix):
return identifiedElem... | As a Python code analyst, you investigate and solve complex coding mysteries |
Removes the unreferenced ID attributes from the identifiedElements. | Make a summary of the following Python 3 code
def removeUnreferencedIDs(referencedIDs, identifiedElements):
global _num_ids_removed
keepTags = ['font']
num = 0
for id in identifiedElements:
node = identifiedElements[id]
if id not in referencedIDs and node.nodeName not in keepTags:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def createGroupsForCommonAttributes(elem):
"""
Creates <g> elements to contain runs of 3 or more
consecutive child elements having at least one common attribute.
Common attributes are not promoted to the <g> by this function.
This is handled by moveCommonAttributesToParentGroup.
If all childre... | Write a Python 3 function that can
create a group of consecutive child elements with common attributes. | As a Python code analyst, you investigate and solve complex coding mysteries |
This function recursively calls this function on all children of the passed in and removes any unused attributes on the parent elem if none of the children inherit it. | Can you tell what is the following Python 3 function doing
def removeUnusedAttributesOnParent(elem):
num = 0
childElements = []
# recurse first into the children (depth-first)
for child in elem.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
childElements.append(child)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
u Returns the style attribute of a node as a dictionary. | Can you generate the documentation for the following Python 3 function
def _getStyle(node):
if node.nodeType == Node.ELEMENT_NODE and len(node.getAttribute('style')) > 0:
styleMap = {}
rawStyles = node.getAttribute('style').split(';')
for style in rawStyles:
propval = style.split... | As a Python code composer, you craft elegant and concise scripts. |
u Set the style attribute of a node to the dictionary styleMap. | Make a summary of the following Python 3 code
def _setStyle(node, styleMap):
fixedStyle = ';'.join([prop + ':' + styleMap[prop] for prop in styleMap])
if fixedStyle != '':
node.setAttribute('style', fixedStyle)
elif node.getAttribute('style'):
node.removeAttribute('style')
return node | As a Python code translator, you convert algorithms and pseudocode into Python. |
def styleInheritedFromParent(node, style):
"""
Returns the value of 'style' that is inherited from the parents of the passed-in node
Warning: This method only considers presentation attributes and inline styles,
any style sheets are ignored!
"""
parentNode = node.parentNode
# retu... | Can you create a Python 3 function that
returns the value of style that is inherited from the parents of the passed - in node. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns whether the passed - in node is inherited by any children of the passed - in node. | Can you tell what is the following Python 3 function doing
def styleInheritedByChild(node, style, nodeIsChild=False):
# Comment, text and CDATA nodes don't have attributes and aren't containers so they can't inherit attributes
if node.nodeType != Node.ELEMENT_NODE:
return False
if nodeIsChild:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns True if the passed - in node is probably a text element or at least
one of its descendants is probably a text element. | Here you have a function in Python 3, explain what it does
def mayContainTextNodes(node):
# Cached result of a prior call?
try:
return node.mayContainTextNodes
except AttributeError:
pass
result = True # Default value
# Comment, text and CDATA nodes don't have attributes and aren't... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Removes the DefaultAttribute attribute from node | Make a summary of the following Python 3 code
def removeDefaultAttributeValue(node, attribute):
if not node.hasAttribute(attribute.name):
return 0
# differentiate between text and numeric values
if isinstance(attribute.value, str):
if node.getAttribute(attribute.name) == attribute.value:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def removeDefaultAttributeValues(node, options, tainted=set()):
u"""'tainted' keeps a set of attributes defined in parent nodes.
For such attributes, we don't delete attributes with default values."""
num = 0
if node.nodeType != Node.ELEMENT_NODE:
return 0
# Conditionally remove all defaul... | Write a Python 3 script for
removing default values from the node. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Converts the input color string and returns a string containing the converted color. | How would you explain what the following Python 3 function does
def convertColor(value):
s = value
if s in colors:
s = colors[s]
rgbpMatch = rgbp.match(s)
if rgbpMatch is not None:
r = int(float(rgbpMatch.group(1)) * 255.0 / 100.0)
g = int(float(rgbpMatch.group(2)) * 255.0 / 10... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Cleans the path string of the element and returns a new empty tree structure. | Make a summary of the following Python 3 code
def cleanPath(element, options):
global _num_bytes_saved_in_path_data
global _num_path_segments_removed
# this gets the parser object from svg_regex.py
oldPathStr = element.getAttribute('d')
path = svg_parser.parse(oldPathStr)
style = _getStyle(elem... | You are a Python code analyst, evaluating scripts for potential improvements. |
Parse a string into a list of points. | Make a summary of the following Python 3 code
def parseListOfPoints(s):
i = 0
# (wsp)? comma-or-wsp-separated coordinate pairs (wsp)?
# coordinate-pair = coordinate comma-or-wsp coordinate
# coordinate = sign? integer
# comma-wsp: (wsp+ comma? wsp*) | (comma wsp*)
ws_nums = re.split(r"\s*[\s,]\... | As a python code expert, you are capable of creating scripts from specifications. |
Remove unnecessary closing point of polygon points attribute
| Can you tell what is the following Python 3 function doing
def cleanPolygon(elem, options):
global _num_points_removed_from_polygon
pts = parseListOfPoints(elem.getAttribute('points'))
N = len(pts) / 2
if N >= 2:
(startx, starty) = pts[:2]
(endx, endy) = pts[-2:]
if startx == en... | As a Python code composer, you craft elegant and concise scripts. |
Scour the polyline points attribute
| Make a summary of the following Python 3 code
def cleanPolyline(elem, options):
pts = parseListOfPoints(elem.getAttribute('points'))
elem.setAttribute('points', scourCoordinates(pts, options, True)) | You are a Python code analyst, evaluating scripts for potential improvements. |
def controlPoints(cmd, data):
"""
Checks if there are control points in the path data
Returns the indices of all values in the path data which are control points
"""
cmd = cmd.lower()
if cmd in ['c', 's', 'q']:
indices = range(len(data))
if cmd == 'c': # c: (x1 y1 x2 y2 x... | Implement a Python 3 function for
checking if there are control points in the path data | You are a Python code analyst, evaluating scripts for potential improvements. |
def flags(cmd, data):
"""
Checks if there are flags in the path data
Returns the indices of all values in the path data which are flags
"""
if cmd.lower() == 'a': # a: (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+
indices = range(len(data))
return [index for index in... | Implement a function in Python 3 to
check if there are flags in the path data | As a Python code analyst, you investigate and solve complex coding mysteries |
def serializePath(pathObj, options):
"""
Reserializes the path data with some cleanups.
"""
# elliptical arc commands must have comma/wsp separating the coordinates
# this fixes an issue outlined in Fix https://bugs.launchpad.net/scour/+bug/412754
return ''.join([cmd + scourCoordinates(data, ... | Create a Python 3 function to
serialize the path data with some cleanups. | You are a Python code generator, capable of creating scripts from specifications. |
Serializes the transform data with some cleanups. | Can you generate a brief explanation for the following Python 3 code
def serializeTransform(transformObj):
return ' '.join([command + '(' + ' '.join([scourUnitlessLength(number) for number in numbers]) + ')'
for command, numbers in transformObj]) | As a Python code composer, you craft elegant and concise scripts. |
def scourCoordinates(data, options, force_whitespace=False, control_points=[], flags=[]):
"""
Serializes coordinate data with some cleanups:
- removes all trailing zeros after the decimal
- integerize coordinates if possible
- removes extraneous whitespace
- adds space... | Implement a Python 3 function for
scouring the coordinates of the given data into a list of strings. | You are a Python code analyst, evaluating scripts for potential improvements. |
def scourLength(length):
"""
Scours a length. Accepts units.
"""
length = SVGLength(length)
return scourUnitlessLength(length.value) + Unit.str(length.units) | Can you write a function in Python 3 where it
scours a length. Accepts units. | As a python code expert, you are capable of creating scripts from specifications. |
def scourUnitlessLength(length, renderer_workaround=False, is_control_point=False): # length is of a numeric type
"""
Scours the numeric part of a length only. Does not accept units.
This is faster than scourLength on elements guaranteed not to
contain units.
"""
if not isinstance(length, Deci... | How would you implement a function in Python 3 that
scours the length of a single element and returns the length of the element. | As a Python code analyst, you investigate and solve complex coding mysteries |
def reducePrecision(element):
"""
Because opacities, letter spacings, stroke widths and all that don't need
to be preserved in SVG files with 9 digits of precision.
Takes all of these attributes, in the given element node and its children,
and reduces their precision to the current Decimal context'... | Write a Python 3 function that can
reduce the precision of the given element node and its children to the current Decimal context s precision. | As a Python code analyst, you investigate and solve complex coding mysteries |
This function is used to optimize the angle of a single - character system. | Can you generate the documentation for the following Python 3 function
def optimizeAngle(angle):
# First, we put the new angle in the range ]-360, 360[.
# The modulo operator yields results with the sign of the
# divisor, so for negative dividends, we preserve the sign
# of the angle.
if angle < 0:
... | As a Python code composer, you craft elegant and concise scripts. |
def optimizeTransform(transform):
"""
Optimises a series of transformations parsed from a single
transform="" attribute.
The transformation list is modified in-place.
"""
# FIXME: reordering these would optimize even more cases:
# first: Fold consecutive runs of the same transformation
... | Can you create a Python 3 function that
optimizes a series of transformations parsed from a single transform = transform attribute. | As a python code expert, you are capable of creating scripts from specifications. |
Optimize the transform specifications on the given node and its children. | Explain what the following Python 3 code does
def optimizeTransforms(element, options):
num = 0
for transformAttr in ['transform', 'patternTransform', 'gradientTransform']:
val = element.getAttribute(transformAttr)
if val != '':
transform = svg_transform_parser.parse(val)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def removeComments(element):
"""
Removes comments from the element and its children.
"""
global _num_bytes_saved_in_comments
num = 0
if isinstance(element, xml.dom.minidom.Comment):
_num_bytes_saved_in_comments += len(element.data)
element.parentNode.removeChild(element)
... | Can you write a function in Python 3 where it
removes comments from the element and its children. | You are a Python code analyst, evaluating scripts for potential improvements. |
def embedRasters(element, options):
import base64
"""
Converts raster references to inline images.
NOTE: there are size limits to base64-encoding handling in browsers
"""
global _num_rasters_embedded
href = element.getAttributeNS(NS['XLINK'], 'href')
# if xlink:href is set, then gr... | Write a Python 3 script for
converting raster references to inline images. NOTE: there are size limits to base64-encoding handling in browsers | As a Python code translator, you convert algorithms and pseudocode into Python. |
Find format schema in nerium format_files or nerium. schema. default | Can you tell what is the following Python 3 function doing
def get_format(format_):
format_path = os.getenv('FORMAT_PATH', 'format_files')
try:
spec = importlib.util.spec_from_file_location(
"format_mod", f"{format_path}/{format_}.py")
format_mod = importlib.util.module_from_spec(spe... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def set_property(self, key, value):
'''Set a new (or updating existing) key value pair.
Args:
key: A string containing the key namespace
value: A str, int, or bool value
Raises:
NotImplementedError: an unsupported value-type was provided
'''
... | Implement a function in Python 3 to
set a new key value pair. | You are a Python code architect, reviewing and designing scalable and efficient code |
Save current property list representation to the original file. | Can you generate the documentation for the following Python 3 function
def save(self):
'''Save current property list representation to the original file.'''
with open(self.filename, 'w') as plist_file:
plist_file.write(str(self.soup)) | As a python code expert, you are capable of creating scripts from specifications. |
Return the userid for the specified bed side. | Can you generate the documentation for the following Python 3 function
def fetch_userid(self, side):
for user in self.users:
obj = self.users[user]
if obj.side == side:
return user | You are a Python code generator, capable of creating scripts from specifications. |
async def fetch_token(self):
"""Fetch new session token from api."""
url = '{}/login'.format(API_URL)
payload = 'email={}&password={}'.format(self._email, self._password)
reg = await self.api_post(url, None, payload)
if reg is None:
_LOGGER.error('Unable to authentic... | Can you create a Python 3 function that
fetches new session token from api. | You are a Python code architect, reviewing and designing scalable and efficient code |
Fetch list of devices. | Explain what the following Python 3 code does
async def fetch_device_list(self):
url = '{}/users/me'.format(API_URL)
dlist = await self.api_get(url)
if dlist is None:
_LOGGER.error('Unable to fetch eight devices.')
else:
self._devices = dlist['user']['devices']
... | As a python code expert, you are capable of creating scripts from specifications. |
Assign users to the eight device. | Make a summary of the following Python 3 code
async def assign_users(self):
device = self._devices[0]
url = '{}/devices/{}?filter=ownerId,leftUserId,rightUserId' \
.format(API_URL, device)
data = await self.api_get(url)
if data is None:
_LOGGER.error('Unable to a... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return room temperature for both sides of bed. | Make a summary of the following Python 3 code
def room_temperature(self):
# Check which side is active, if both are return the average
tmp = None
tmp2 = None
for user in self.users:
obj = self.users[user]
if obj.current_values['processing']:
if tmp... | As a Python code analyst, you investigate and solve complex coding mysteries |
def handle_device_json(self, data):
"""Manage the device json list."""
self._device_json.insert(0, data)
self._device_json.pop() | Can you create a Python 3 function that
manages the device json list. | You are a Python code architect, reviewing and designing scalable and efficient code |
Update device data json. | Explain what the following Python 3 code does
async def update_device_data(self):
url = '{}/devices/{}?offlineView=true'.format(API_URL, self.deviceid)
# Check for access token expiration (every 15days)
exp_delta = datetime.strptime(self._expdate, '%Y-%m-%dT%H:%M:%S.%fZ') \
- dateti... | As a Python code analyst, you investigate and solve complex coding mysteries |
Make api fetch request. | Explain what the following Python 3 code does
async def api_get(self, url, params=None):
request = None
headers = DEFAULT_HEADERS.copy()
headers.update({'Session-Token': self._token})
try:
with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop):
re... | As a Python code analyst, you investigate and solve complex coding mysteries |
async def api_put(self, url, data=None):
"""Make api post request."""
put = None
headers = DEFAULT_HEADERS.copy()
headers.update({'Session-Token': self._token})
try:
with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop):
put = await self.... | Implement a Python 3 function for
making api post request. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a list of versions that satisfy the given requirements. | Can you tell what is the following Python 3 function doing
def satisfy(self, *requirements):
versions = []
for req_range in requirements:
try:
version = self._detected_versions[req_range.name]
except KeyError:
try:
version = req... | You are a Python code analyst, evaluating scripts for potential improvements. |
def housecode_to_index(housecode):
"""Convert a X10 housecode to a zero-based index"""
match = re.search(r'^([A-P])(\d{1,2})$', housecode.upper())
if match:
house_index = int(match.group(2))
if 1 <= house_index <= 16:
return (ord(match.group(1)) - ord('A')) * 16 + house_index - 1... | Create a Python 3 function for
converting a X10 housecode to a zero - based index | As a Python code composer, you craft elegant and concise scripts. |
def index_to_housecode(index):
"""Convert a zero-based index to a X10 housecode."""
if index < 0 or index > 255:
raise ValueError
quotient, remainder = divmod(index, 16)
return chr(quotient+ord('A')) + '{:02d}'.format(remainder+1) | Can you write a function in Python 3 where it
converts a zero - based index to a X10 housecode. | As a Python code analyst, you investigate and solve complex coding mysteries |
Ensure checksum in message is good. | Here you have a function in Python 3, explain what it does
def _check_checksum(msg):
checksum = int(msg[-2:], 16)
for char in msg[:-2]:
checksum += ord(char)
if (checksum % 256) != 0:
raise ValueError("Elk message checksum invalid") | You are a Python code architect, reviewing and designing scalable and efficient code |
def _check_message_valid(msg):
"""Check packet length valid and that checksum is good."""
try:
if int(msg[:2], 16) != (len(msg) - 2):
raise ValueError("Elk message length incorrect")
_check_checksum(msg)
except IndexError:
raise ValueError("Elk message length incorrect") | Create a Python 3 function for
checking that the message is valid and that checksum is good. | You are a Python code architect, reviewing and designing scalable and efficient code |
Encode a CWR message. | Given the following Python 3 function, write the documentation
def cw_encode(index, value, value_format):
if value_format == 2:
value = value[0] << 8 + value[1]
return MessageEncode('0Dcw{:02d}{:05d}00'.format(index+1, value), None) | You are a Python code analyst, evaluating scripts for potential improvements. |
dm - Display message on keypad. | Explain what the following Python 3 code does
def dm_encode(keypad_area, clear, beep, timeout, line1, line2):
return MessageEncode(
'2Edm{:1d}{:1d}{:1d}{:05d}{:^<16.16}{:^<16.16}00'
.format(keypad_area+1, clear, beep, timeout, line1, line2), None
) | You are a Python code architect, reviewing and designing scalable and efficient code |
zb - ZB encode | Can you tell what is the following Python 3 function doing
def zb_encode(zone, area, user_code):
if zone < 0:
zone = 0
elif zone > Max.ZONES.value:
zone = 999
else:
zone += 1
return MessageEncode('10zb{zone:03d}{area:1d}{code:06d}00'.format(
zone=zone, area=area+1, code=u... | You are a Python code architect, reviewing and designing scalable and efficient code |
Manage callbacks for message handlers. | Can you tell what is the following Python 3 function doing
def add_handler(self, message_type, handler):
if message_type not in self._handlers:
self._handlers[message_type] = []
if handler not in self._handlers[message_type]:
self._handlers[message_type].append(handler) | As a Python code analyst, you investigate and solve complex coding mysteries |
Decode an Elk message by passing to appropriate decoder | Explain what the following Python 3 code does
def decode(self, msg):
_check_message_valid(msg)
cmd = msg[2:4]
decoder = getattr(self, '_{}_decode'.format(cmd.lower()), None)
if not decoder:
cmd = 'unknown'
decoder = self._unknown_decode
decoded_msg = decod... | You are a Python code analyst, evaluating scripts for potential improvements. |
EE - > Entry / Exit timer report. | Can you generate the documentation for the following Python 3 function
def _ee_decode(self, msg):
return {'area': int(msg[4:5])-1, 'is_exit': msg[5:6] == '0',
'timer1': int(msg[6:9]), 'timer2': int(msg[9:12]),
'armed_status': msg[12:13]} | As a Python code translator, you convert algorithms and pseudocode into Python. |
IC: Send Valid Or Invalid User Code Format. | Given the following Python 3 function, write the documentation
def _ic_decode(self, msg):
code = msg[4:16]
if re.match(r'(0\d){6}', code):
code = re.sub(r'0(\d)', r'\1', code)
return {'code': code, 'user': int(msg[16:19])-1,
'keypad': int(msg[19:21])-1} | As a Python code analyst, you investigate and solve complex coding mysteries |
Decode a KA message. | Explain what the following Python 3 code does
def _ka_decode(self, msg):
return {'keypad_areas': [ord(x)-0x31 for x in msg[4:4+Max.KEYPADS.value]]} | As a Python code analyst, you investigate and solve complex coding mysteries |
def _lw_decode(self, msg):
"""LW: temperatures from all keypads and zones 1-16."""
keypad_temps = []
zone_temps = []
for i in range(16):
keypad_temps.append(int(msg[4+3*i:7+3*i]) - 40)
zone_temps.append(int(msg[52+3*i:55+3*i]) - 60)
return {'keypad_temps':... | Write a Python 3 function for
decoding the LW message into a dictionary. | You are a Python code architect, reviewing and designing scalable and efficient code |
SD : Description text. | How would you explain what the following Python 3 function does
def _sd_decode(self, msg):
desc_ch1 = msg[9]
show_on_keypad = ord(desc_ch1) >= 0x80
if show_on_keypad:
desc_ch1 = chr(ord(desc_ch1) & 0x7f)
return {'desc_type': int(msg[4:6]), 'unit': int(msg[6:9])-1,
... | As a Python code composer, you craft elegant and concise scripts. |
ST : Temperature update. | Can you generate a brief explanation for the following Python 3 code
def _st_decode(self, msg):
group = int(msg[4:5])
temperature = int(msg[7:10])
if group == 0:
temperature -= 60
elif group == 1:
temperature -= 40
return {'group': group, 'device': int(msg... | As a Python code composer, you craft elegant and concise scripts. |
def _vn_decode(self, msg):
"""VN: Version information."""
elkm1_version = "{}.{}.{}".format(int(msg[4:6], 16), int(msg[6:8], 16),
int(msg[8:10], 16))
xep_version = "{}.{}.{}".format(int(msg[10:12], 16), int(msg[12:14], 16),
... | Write a Python 3 script for
decoding the VN message into a dictionary. | You are a Python code analyst, evaluating scripts for potential improvements. |
ZP - > Zone partitions. | How would you explain what the following Python 3 function does
def _zp_decode(self, msg):
zone_partitions = [ord(x)-0x31 for x in msg[4:4+Max.ZONES.value]]
return {'zone_partitions': zone_partitions} | As a Python code composer, you craft elegant and concise scripts. |
ZS : Zone statuses. | Here you have a function in Python 3, explain what it does
def _zs_decode(self, msg):
status = [_status_decode(int(x, 16)) for x in msg[4:4+Max.ZONES.value]]
return {'zone_statuses': status} | As a Python code analyst, you investigate and solve complex coding mysteries |
Connects to the XNAT server. | Here you have a function in Python 3, explain what it does
def connect(self):
sess_kwargs = {}
if self._user is not None:
sess_kwargs['user'] = self._user
if self._password is not None:
sess_kwargs['password'] = self._password
self._login = xnat.connect(server=sel... | As a python code expert, you are capable of creating scripts from specifications. |
def get_fileset(self, fileset):
"""
Caches a single fileset (if the 'path' attribute is accessed
and it has not been previously cached for example
Parameters
----------
fileset : Fileset
The fileset to cache
prev_login : xnat.XNATSession
A... | Write a Python 3 script to
get a single file from the fileset and return a dict containing the information about the file. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_checksums(self, fileset):
"""
Downloads the MD5 digests associated with the files in the file-set.
These are saved with the downloaded files in the cache and used to
check if the files have been updated on the server
Parameters
----------
resource : xnat.... | How would you implement a function in Python 3 that
retrieves the MD5 digests associated with the files in the file - set and returns the checksums as a dictionary. | As a python code expert, you are capable of creating scripts from specifications. |
Find all filesets fields and provenance records within an XNAT project. | Can you generate a brief explanation for the following Python 3 code
def find_data(self, subject_ids=None, visit_ids=None, **kwargs):
subject_ids = self.convert_subject_ids(subject_ids)
# Add derived visit IDs to list of visit ids to filter
all_filesets = []
all_fields = []
all_r... | As a Python code analyst, you investigate and solve complex coding mysteries |
def convert_subject_ids(self, subject_ids):
"""
Convert subject ids to strings if they are integers
"""
# TODO: need to make this generalisable via a
# splitting+mapping function passed to the repository
if subject_ids is not None:
subject_ids = set(
... | Write a Python 3 script for
converting subject ids to strings if they are integers | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_xsession(self, item):
"""
Returns the XNAT session and cache dir corresponding to the
item.
"""
subj_label, sess_label = self._get_item_labels(item)
with self:
xproject = self._login.projects[self.project_id]
try:
xsubject =... | Implement a function in Python 3 to
return the XNAT session and cache dir corresponding to the item. | You are a Python code generator, capable of creating scripts from specifications. |