output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
r This method backpropagates a single object in a 3D manner. | Given the following Python 3 function, write the documentation
def backpropagate_3d(uSin, angles, res, nm, lD=0, coords=None,
weight_angles=True, onlyreal=False,
padding=(True, True), padfac=1.75, padval=None,
intp_order=2, dtype=None,
... | As a python code expert, you are capable of creating scripts from specifications. |
Compute the weights for each angle in the
. | Can you generate a brief explanation for the following Python 3 code
def compute_angle_weights_1d(angles):
# copy and modulo np.pi
# This is an array with values in [0, np.pi)
angles = (angles.flatten() - angles.min()) % (np.pi)
# sort the array
sortargs = np.argsort(angles)
sortangl = angles[so... | As a python code expert, you are capable of creating scripts from specifications. |
Calls initialize on all devices connected to the bus. | Make a summary of the following Python 3 code
def initialize(self):
Device.initialize(self)
for child in iter(self.children.values()):
child.initialize() | You are a Python code analyst, evaluating scripts for potential improvements. |
Writes a byte to an unaddressed register in a device. | Can you generate the documentation for the following Python 3 function
def write_byte(self, address, value):
LOGGER.debug("Writing byte %s to device %s!", bin(value), hex(address))
return self.driver.write_byte(address, value) | As a Python code analyst, you investigate and solve complex coding mysteries |
def read_byte(self, address):
"""Reads unadressed byte from a device. """
LOGGER.debug("Reading byte from device %s!", hex(address))
return self.driver.read_byte(address) | Create a Python 3 function to
read a single byte from a device. | You are a Python code generator, capable of creating scripts from specifications. |
def write_byte_data(self, address, register, value):
"""Write a byte value to a device's register. """
LOGGER.debug("Writing byte data %s to register %s on device %s",
bin(value), hex(register), hex(address))
return self.driver.write_byte_data(address, register, value) | Create a Python 3 function for
writing a byte value to a device s register. | You are a Python code analyst, evaluating scripts for potential improvements. |
def write_wdata(self, address, register, value):
"""Write a word (two bytes) value to a device's register. """
warnings.warn("write_wdata() is deprecated and will be removed in future versions replace with write_word_data()", DeprecationWarning)
LOGGER.debug("Writing word data %s to register %s ... | Write a Python 3 script to
write a word value to a device s register. | As a Python code analyst, you investigate and solve complex coding mysteries |
async def _raise_for_status(response):
"""Raise an appropriate error for a given response.
Arguments:
response (:py:class:`aiohttp.ClientResponse`): The API response.
Raises:
:py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate
error for the response's status.
This fu... | Create a Python 3 function for
raising an appropriate error for a given response. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generic Space-Track query coroutine.
The request class methods use this method internally; the public
API is as follows:
.. code-block:: python
st.tle_publish(*args, **st)
st.basicspacedata.tle_publish(*args, **st)
st.file(*args, **st)
st.filesh... | Can you generate a brief explanation for the following Python 3 code
async def generic_request(self, class_, iter_lines=False, iter_content=False,
controller=None, parse_types=False, **kwargs):
"""Generic Space-Track query coroutine.
The request class methods use this meth... | As a python code expert, you are capable of creating scripts from specifications. |
Get raw predicate information for given request class and cache for
subsequent calls. | Explain what the following Python 3 code does
async def _download_predicate_data(self, class_, controller):
await self.authenticate()
url = ('{0}{1}/modeldef/class/{2}'
.format(self.base_url, controller, class_))
resp = await self._ratelimited_get(url)
await _raise_for_... | As a python code expert, you are capable of creating scripts from specifications. |
parses string_value and returns only numeric - like part
| Given the following Python 3 function, write the documentation
def get_numeric_value(string_value):
num_chars = ['.', '+', '-']
number = ''
for c in string_value:
if c.isdigit() or c in num_chars:
number += c
return number | As a Python code composer, you craft elegant and concise scripts. |
def run(analysis, path=None, name=None, info=None, **kwargs):
"""Run a single analysis.
:param Analysis analysis: Analysis class to run.
:param str path: Path of analysis. Can be `__file__`.
:param str name: Name of the analysis.
:param dict info: Optional entries are ``version``, ``title``,
... | Can you create a Python 3 function that
runs a single analysis. | As a python code expert, you are capable of creating scripts from specifications. |
def _stringify_predicate_value(value):
"""Convert Python objects to Space-Track compatible strings
- Booleans (``True`` -> ``'true'``)
- Sequences (``[25544, 34602]`` -> ``'25544,34602'``)
- dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)
- ``None`` -> ``'null-val'``
"""
if isi... | Implement a function in Python 3 to
convert Python objects to Space - Track compatible strings | You are a Python code analyst, evaluating scripts for potential improvements. |
def args_repr(*args, **kwargs):
"""
Returns human-readable string representation of both positional and
keyword arguments passed to the function.
This function uses the built-in :func:`repr()` function to convert
individual arguments to string.
>>> args_repr("a", (1, 2), some_keyword = list("a... | Write a Python 3 function that can
return a human - readable string representation of both positional and keyword arguments passed to the function. | As a Python code composer, you craft elegant and concise scripts. |
Returns a human - readable string representation of an object given that it has been created by calling constructor with the specified positional and keyword arguments. | Can you generate a brief explanation for the following Python 3 code
def obj_repr(obj, *args, **kwargs):
cls_name = type(obj).__name__
return "%s(%s)" % (cls_name, args_repr(*args, **kwargs), ) | You are a Python code generator, capable of creating scripts from specifications. |
def decode_filter(text, encoding='utf-8'):
"""
decode a binary object to str and filter out non-printable characters
Parameters
----------
text: bytes
the binary object to be decoded
encoding: str
the encoding to be used
Returns
-------
str
the decoded a... | Write a Python 3 function for
decoding a binary object to str and filter out non - printable characters | As a Python code analyst, you investigate and solve complex coding mysteries |
def dictmerge(x, y):
"""
merge two dictionaries
"""
z = x.copy()
z.update(y)
return z | Write a Python 3 function for
merging two dictionaries together | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a list of lists with sub - lists or tuples that are not in list | Given the following Python 3 function, write the documentation
def dissolve(inlist):
out = []
for i in inlist:
i = list(i) if isinstance(i, tuple) else i
out.extend(dissolve(i)) if isinstance(i, list) else out.append(i)
return out | As a Python code composer, you craft elegant and concise scripts. |
function for finding files and folders in a directory and a list of directories and subdirectories. | How would you explain what the following Python 3 function does
def finder(target, matchlist, foldermode=0, regex=False, recursive=True):
if foldermode not in [0, 1, 2]:
raise ValueError("'foldermode' must be either 0, 1 or 2")
# match patterns
if isinstance(target, str):
patte... | As a Python code analyst, you investigate and solve complex coding mysteries |
Wrapper for the multicore function function. | Explain what the following Python 3 code does
def multicore(function, cores, multiargs, **singleargs):
tblib.pickling_support.install()
# compare the function arguments with the multi and single arguments and raise errors if mismatches occur
if sys.version_info >= (3, 0):
check = inspect.getful... | You are a Python code generator, capable of creating scripts from specifications. |
def parse_literal(x):
"""
return the smallest possible data type for a string or list of strings
Parameters
----------
x: str or list
a string to be parsed
Returns
-------
int, float or str
the parsing result
Examples
--------
>>> isinstance(parse_liter... | Can you write a function in Python 3 where it
returns the smallest possible data type for a string or list of strings Parameters ---------- x: str or list a string to be parsed Returns ------- int, float or str the parsing result Examples -------- >>> isinstance(parse_literal('1.5'), float) True >>> isinstance(parse_li... | You are a Python code architect, reviewing and designing scalable and efficient code |
rescale the values in a list between the new minimum and maximum | Make a summary of the following Python 3 code
def rescale(inlist, newrange=(0, 1)):
OldMax = max(inlist)
OldMin = min(inlist)
if OldMin == OldMax:
raise RuntimeError('list contains of only one unique value')
OldRange = OldMax - OldMin
NewRange = newrange[1] - newrange[0]
result... | You are a Python code architect, reviewing and designing scalable and efficient code |
def run(cmd, outdir=None, logfile=None, inlist=None, void=True, errorpass=False, env=None):
"""
| wrapper for subprocess execution including logfile writing and command prompt piping
| this is a convenience wrapper around the :mod:`subprocess` module and calls
its class :class:`~subprocess.Popen` inte... | Write a Python 3 function for
wrapping for subprocess execution including logfile writing and command prompt piping | As a Python code analyst, you investigate and solve complex coding mysteries |
def urlQueryParser(url, querydict):
"""
parse a url query
"""
address_parse = urlparse(url)
return urlunparse(address_parse._replace(query=urlencode(querydict))) | Write a Python 3 function that can
parse a url querydict | As a Python code analyst, you investigate and solve complex coding mysteries |
push a new item to the stack | Can you generate the documentation for the following Python 3 function
def push(self, x):
if isinstance(x, list):
for item in x:
self.stack.append(item)
else:
self.stack.append(x) | As a Python code composer, you craft elegant and concise scripts. |
pop the last element from the stack and return it | Make a summary of the following Python 3 code
def pop(self):
if not self.empty():
val = self.stack[-1]
del self.stack[-1]
return val | As a Python code composer, you craft elegant and concise scripts. |
def axes(self, offset = False):
"""returns measured value in miligauss"""
reg, self._scale = self.SCALES[self._gauss]
x = self.bus.read_int16_data(self.address, self.HMC5883L_DXRA)
if x == -4096: x = OVERFLOW
y = self.bus.read_int16_data(self.address, self.HMC5883L_DYRA)
... | How would you implement a function in Python 3 that
returns measured value in miligauss | As a Python code analyst, you investigate and solve complex coding mysteries |
dictionary - > list of pairs | Can you generate the documentation for the following Python 3 function
def _Pairs(data):
keys = sorted(data)
return [{'@key': k, '@value': data[k]} for k in keys] | You are a Python code generator, capable of creating scripts from specifications. |
def _StrftimeGm(value, unused_context, args):
"""Convert a timestamp in seconds to a string based on the format string.
Returns GM time.
"""
time_tuple = time.gmtime(value)
return _StrftimeHelper(args, time_tuple) | Can you create a Python 3 function that
converts a timestamp in seconds to a string based on the format string. Returns GM time. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _StrftimeLocal(value, unused_context, args):
"""Convert a timestamp in seconds to a string based on the format string.
Returns local time.
"""
time_tuple = time.localtime(value)
return _StrftimeHelper(args, time_tuple) | Write a Python 3 function for
converting a timestamp in seconds to a string based on the format string. Returns local time. | As a Python code composer, you craft elegant and concise scripts. |
Returns whether the given name is in the current Template s template group. | Can you generate a brief explanation for the following Python 3 code
def _TemplateExists(unused_value, context, args):
try:
name = args[0]
except IndexError:
raise EvaluationError('The "template" predicate requires an argument.')
return context.HasTemplate(name) | As a Python code composer, you craft elegant and concise scripts. |
Split and validate metacharacters.
| Can you generate a brief explanation for the following Python 3 code
def SplitMeta(meta):
n = len(meta)
if n % 2 == 1:
raise ConfigurationError(
'%r has an odd number of metacharacters' % meta)
return meta[:n // 2], meta[n // 2:] | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a compiled regular expression for tokenization. | Can you generate a brief explanation for the following Python 3 code
def MakeTokenRegex(meta_left, meta_right):
key = meta_left, meta_right
if key not in _token_re_cache:
# - Need () grouping for re.split
# - The first character must be a non-space. This allows us to ignore
# literals l... | As a python code expert, you are capable of creating scripts from specifications. |
Helper function for matching certain directives. | Can you generate the documentation for the following Python 3 function
def _MatchDirective(token):
# Tokens below must start with '.'
if token.startswith('.'):
token = token[1:]
else:
return None, None
if token == 'end':
return END_TOKEN, None
if token == 'alternate... | As a Python code composer, you craft elegant and concise scripts. |
def _Tokenize(template_str, meta_left, meta_right, whitespace):
"""Yields tokens, which are 2-tuples (TOKEN_TYPE, token_string)."""
trimlen = len(meta_left)
token_re = MakeTokenRegex(meta_left, meta_right)
do_strip = (whitespace == 'strip-line') # Do this outside loop
do_strip_part = False
... | Implement a Python 3 function for
yielding tokens which are 2 - tuples ( TOKEN_TYPE token_string | You are a Python code architect, reviewing and designing scalable and efficient code |
def _CompileTemplate(
template_str, builder, meta='{}', format_char='|', default_formatter='str',
whitespace='smart'):
"""Compile the template string, calling methods on the 'program builder'.
Args:
template_str: The template string. It should not have any compilation
options in the ... | Can you create a Python 3 function that
compiles the template string into a new base object. | You are a Python code generator, capable of creating scripts from specifications. |
def FromString(s, **kwargs):
"""Like FromFile, but takes a string."""
f = StringIO.StringIO(s)
return FromFile(f, **kwargs) | Can you write a function in Python 3 where it
likes FromFile but takes a string. | As a python code expert, you are capable of creating scripts from specifications. |
def FromFile(f, more_formatters=lambda x: None, more_predicates=lambda x: None,
_constructor=None):
"""Parse a template from a file, using a simple file format.
This is useful when you want to include template options in a data file,
rather than in the source code.
The format is similar to HTTP... | Write a Python 3 script to
parse a template from a file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Construct a dictinary template name - > Template instance from a parse tree. | Can you tell what is the following Python 3 function doing
def _MakeGroupFromRootSection(root_section, undefined_str):
group = {}
for statement in root_section.Statements():
if isinstance(statement, six.string_types):
continue
func, args = statement
# here the function acts a... | You are a Python code analyst, evaluating scripts for potential improvements. |
Join tokens into a single string. | Given the following Python 3 function, write the documentation
def JoinTokens(tokens):
try:
return ''.join(tokens)
except UnicodeDecodeError:
# This can still raise UnicodeDecodeError if that data isn't utf-8.
return ''.join(t.decode('utf-8') for t in tokens) | As a Python code composer, you craft elegant and concise scripts. |
def _DoRepeatedSection(args, context, callback, trace):
"""{.repeated section foo}"""
block = args
items = context.PushSection(block.section_name, block.pre_formatters)
if items:
if not isinstance(items, list):
raise EvaluationError('Expected a list; got %s' % type(items))
... | How would you implement a function in Python 3 that
executes the repeated section. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _DoSection(args, context, callback, trace):
"""{.section foo}"""
block = args
# If a section present and "true", push the dictionary onto the stack as the
# new context, and show it
if context.PushSection(block.section_name, block.pre_formatters):
_Execute(block.Statements(), context, ca... | Write a Python 3 script to
execute a section statement. | As a Python code analyst, you investigate and solve complex coding mysteries |
Execute the predicate clauses. | Can you generate the documentation for the following Python 3 function
def _DoPredicates(args, context, callback, trace):
block = args
value = context.Lookup('@')
for (predicate, args, func_type), statements in block.clauses:
if func_type == ENHANCED_FUNC:
do_clause = predicate(value, co... | You are a Python code architect, reviewing and designing scalable and efficient code |
Execute a bunch of template statements in a ScopedContext. | Can you tell what is the following Python 3 function doing
def _Execute(statements, context, callback, trace):
# Every time we call _Execute, increase this depth
if trace:
trace.exec_depth += 1
for i, statement in enumerate(statements):
if isinstance(statement, six.string_types):
... | You are a Python code generator, capable of creating scripts from specifications. |
def expand(template_str, dictionary, **kwargs):
"""Free function to expands a template string with a data dictionary.
This is useful for cases where you don't care about saving the result of
compilation (similar to re.match('.*', s) vs DOT_STAR.match(s))
"""
t = Template(template_str, **kwargs)
retur... | How would you code a function in Python 3 to
free function to expand a template string with a data dictionary. | As a Python code composer, you craft elegant and concise scripts. |
Flatten a nested list structure into a callback function. | Can you generate a brief explanation for the following Python 3 code
def _FlattenToCallback(tokens, callback):
for t in tokens:
if isinstance(t, six.string_types):
callback(t)
else:
_FlattenToCallback(t, callback) | As a Python code composer, you craft elegant and concise scripts. |
Execute a template with a style. | How would you explain what the following Python 3 function does
def execute_with_style_LEGACY(template, style, data, callback, body_subtree='body'):
try:
body_data = data[body_subtree]
except KeyError:
raise EvaluationError('Data dictionary has no subtree %r' % body_subtree)
tokens_body = []... | You are a Python code generator, capable of creating scripts from specifications. |
Expand a data dictionary with a template AND a style. | Make a summary of the following Python 3 code
def expand_with_style(template, style, data, body_subtree='body'):
if template.has_defines:
return template.expand(data, style=style)
else:
tokens = []
execute_with_style_LEGACY(template, style, data, tokens.append,
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns:
ref: Either a template instance (itself) or _TemplateRef | Can you generate a brief explanation for the following Python 3 code
def LookupWithType(self, user_str):
prefix = 'template '
ref = None # fail the lookup by default
if user_str.startswith(prefix):
name = user_str[len(prefix):]
if name == 'SELF':
# we can... | You are a Python code generator, capable of creating scripts from specifications. |
Get a formatter from a user s formatters list. | Can you generate a brief explanation for the following Python 3 code
def _GetFormatter(self, format_str):
formatter, args, func_type = self.formatters.LookupWithType(format_str)
if formatter:
return formatter, args, func_type
else:
raise BadFormatter('%r is not a valid fo... | As a Python code composer, you craft elegant and concise scripts. |
Get predicate from a string. | Given the following Python 3 function, write the documentation
def _GetPredicate(self, pred_str, test_attr=False):
predicate, args, func_type = self.predicates.LookupWithType(pred_str)
if predicate:
pred = predicate, args, func_type
else:
# Nicer syntax, {.debug?} is shor... | As a Python code composer, you craft elegant and concise scripts. |
For sections or repeated sections. | Given the following Python 3 function, write the documentation
def NewSection(self, token_type, section_name, pre_formatters):
pre_formatters = [self._GetFormatter(f) for f in pre_formatters]
# TODO: Consider getting rid of this dispatching, and turn _Do* into methods
if token_type == R... | You are a Python code analyst, evaluating scripts for potential improvements. |
def NewOrClause(self, pred_str):
"""
{.or ...} Can appear inside predicate blocks or section blocks, with
slightly different meaning.
"""
if pred_str:
pred = self._GetPredicate(pred_str, test_attr=False)
else:
pred = None
self.current_section.NewOrClau... | How would you code a function in Python 3 to
add an or clause to the current section. | You are a Python code architect, reviewing and designing scalable and efficient code |
def PushSection(self, name, pre_formatters):
"""Given a section name, push it on the top of the stack.
Returns:
The new section, or None if there is no such section.
"""
if name == '@':
value = self.stack[-1].context
else:
value = self.stack[-1].context.get... | Create a Python 3 function for
giving a section name push it on the top of the stack. | You are a Python code architect, reviewing and designing scalable and efficient code |
Advance to the next item in a repeated section. | Given the following Python 3 function, write the documentation
def Next(self):
stacktop = self.stack[-1]
# Now we're iterating -- push a new mutable object onto the stack
if stacktop.index == -1:
stacktop = _Frame(None, index=0)
self.stack.append(stacktop)
... | As a python code expert, you are capable of creating scripts from specifications. |
def _LookUpStack(self, name):
"""Look up the stack for the given name."""
i = len(self.stack) - 1
while 1:
frame = self.stack[i]
if name == '@index':
if frame.index != -1: # -1 is undefined
return frame.index # @index is 1-based
... | How would you implement a function in Python 3 that
looks up the stack for the given name. | As a python code expert, you are capable of creating scripts from specifications. |
def Lookup(self, name):
"""Get the value associated with a name in the current context.
The current context could be an dictionary in a list, or a dictionary
outside a list.
Args:
name: name to lookup, e.g. 'foo' or 'foo.bar.baz'
Returns:
The value, or self.undefined_str
Rais... | Write a Python 3 script to
look up the value associated with a name in the current context. | You are a Python code generator, capable of creating scripts from specifications. |
def execute(self, data_dict, callback, group=None, trace=None):
"""Low level method to expand the template piece by piece.
Args:
data_dict: The JSON data dictionary.
callback: A callback which should be called with each expanded token.
group: Dictionary of name -> Template instance (for s... | Write a Python 3 script for
executing the program and return the expanded token list. | You are a Python code architect, reviewing and designing scalable and efficient code |
Expands the template with the given data dictionary returning a string. | Can you generate a brief explanation for the following Python 3 code
def expand(self, *args, **kwargs):
if args:
if len(args) == 1:
data_dict = args[0]
trace = kwargs.get('trace')
style = kwargs.get('style')
else:
raise Type... | You are a Python code analyst, evaluating scripts for potential improvements. |
def tokenstream(self, data_dict):
"""Yields a list of tokens resulting from expansion.
This may be useful for WSGI apps. NOTE: In the current implementation, the
entire expanded template must be stored memory.
NOTE: This is a generator, but JavaScript doesn't have generators.
"""
toke... | Write a Python 3 function that can
yield a list of tokens resulting from expansion. | You are a Python code analyst, evaluating scripts for potential improvements. |
def align_unwrapped(sino):
"""Align an unwrapped phase array to zero-phase
All operations are performed in-place.
"""
samples = []
if len(sino.shape) == 2:
# 2D
# take 1D samples at beginning and end of array
samples.append(sino[:, 0])
samples.append(sino[:, 1])
... | How would you code a function in Python 3 to
align an unwrapped phase array to zero - phase array. | You are a Python code analyst, evaluating scripts for potential improvements. |
def divmod_neg(a, b):
"""Return divmod with closest result to zero"""
q, r = divmod(a, b)
# make sure r is close to zero
sr = np.sign(r)
if np.abs(r) > b/2:
q += sr
r -= b * sr
return q, r | Write a Python 3 function for
returning divmod with closest result to zero | As a Python code translator, you convert algorithms and pseudocode into Python. |
Default JSON encoder for more data types than the default JSON encoder. | Make a summary of the following Python 3 code
def json_encoder_default(obj):
if np is not None and hasattr(obj, 'size') and hasattr(obj, 'dtype'):
if obj.size == 1:
if np.issubdtype(obj.dtype, np.integer):
return int(obj)
elif np.issubdtype(obj.dtype, np.floating):
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert a matplotlib figure to an inline HTML image. | Can you generate a brief explanation for the following Python 3 code
def fig_to_src(figure, image_format='png', dpi=80):
if image_format == 'png':
f = io.BytesIO()
figure.savefig(f, format=image_format, dpi=dpi)
f.seek(0)
return png_to_src(f.read())
elif image_format == 'svg':
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Reset Axis and set default parameters for H - bridge | Can you tell what is the following Python 3 function doing
def Reset(self):
' Reset Axis and set default parameters for H-bridge '
spi.SPI_write(self.CS, [0xC0, 0x60]) # reset
# spi.SPI_write(self.CS, [0x14, 0x14]) # Stall Treshold setup
# spi.SPI_write(self.CS, [0xFF, 0xFF])
#... | As a Python code analyst, you investigate and solve complex coding mysteries |
Setup of maximum speed | Can you generate the documentation for the following Python 3 function
def MaxSpeed(self, speed):
' Setup of maximum speed '
spi.SPI_write(self.CS, [0x07, 0x07]) # Max Speed setup
spi.SPI_write(self.CS, [0x00, 0x00])
spi.SPI_write(self.CS, [speed, speed]) | As a Python code composer, you craft elegant and concise scripts. |
def ReleaseSW(self):
' Go away from Limit Switch '
while self.ReadStatusBit(2) == 1: # is Limit Switch ON ?
spi.SPI_write(self.CS, [0x92, 0x92] | (~self.Dir & 1)) # release SW
while self.IsBusy():
pass
self.MoveWait(10) | Can you implement a function in Python 3 that
goes away from Limit Switch | You are a Python code generator, capable of creating scripts from specifications. |
def Move(self, units):
' Move some distance units from current position '
steps = units * self.SPU # translate units to steps
if steps > 0: # look for direction
spi.SPI_write(self.CS, [0x40 | (~self.Dir & 1), 0x40 | (~self.Dir & 1)])
... | Create a Python 3 function for
moving some distance units from current position | As a Python code analyst, you investigate and solve complex coding mysteries |
Create a bounding box vector object from a dictionary of coordinates and coordinate reference system. | Explain what the following Python 3 code does
def bbox(coordinates, crs, outname=None, format='ESRI Shapefile', overwrite=True):
srs = crsConvert(crs, 'osr')
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(coordinates['xmin'], coordinates['ymin'])
ring.AddPoint(coordinates['xmin'], coordi... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def dissolve(infile, outfile, field, layername=None):
"""
dissolve the polygons of a vector file by an attribute field
Parameters
----------
infile: str
the input vector file
outfile: str
the output shapefile
field: str
the field name to merge the polygons by
laye... | Write a Python 3 script to
dissolve the polygons of a vector file by an attribute field Parameters ---------- infile: str the input vector file outfile: str the output shapefile field: str the field name to merge the polygons by layername: str the name of the output vector layer; If set to None the layername will be th... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def feature2vector(feature, ref, layername=None):
"""
create a Vector object from ogr features
Parameters
----------
feature: list of :osgeo:class:`ogr.Feature` or :osgeo:class:`ogr.Feature`
a single feature or a list of features
ref: Vector
a reference Vector object to retrieve... | How would you code a function in Python 3 to
create a Vector object from ogr features | You are a Python code architect, reviewing and designing scalable and efficient code |
def intersect(obj1, obj2):
"""
intersect two Vector objects
Parameters
----------
obj1: Vector
the first vector object; this object is reprojected to the CRS of obj2 if necessary
obj2: Vector
the second vector object
Returns
-------
Vector
the intersect of o... | Write a Python 3 function for
returning the intersection of two Vector objects | You are a Python code analyst, evaluating scripts for potential improvements. |
add a feature to the vector object from a geometry | Can you generate a brief explanation for the following Python 3 code
def addfeature(self, geometry, fields=None):
feature = ogr.Feature(self.layerdef)
feature.SetGeometry(geometry)
if fields is not None:
for fieldname, value in fields.items():
if fie... | You are a Python code analyst, evaluating scripts for potential improvements. |
add a field to the vector layer | Can you generate the documentation for the following Python 3 function
def addfield(self, name, type, width=10):
fieldDefn = ogr.FieldDefn(name, type)
if type == ogr.OFTString:
fieldDefn.SetWidth(width)
self.layer.CreateField(fieldDefn) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def addlayer(self, name, srs, geomType):
"""
add a layer to the vector layer
Parameters
----------
name: str
the layer name
srs: int, str or :osgeo:class:`osr.SpatialReference`
the spatial reference system. See :func:`spatialist.auxil.crsConvert` ... | Write a Python 3 function that can
add a layer to the vector layer | As a Python code translator, you convert algorithms and pseudocode into Python. |
def addvector(self, vec):
"""
add a vector object to the layer of the current Vector object
Parameters
----------
vec: Vector
the vector object to add
merge: bool
merge overlapping polygons?
Returns
-------
"""
ve... | Write a Python 3 function for
adding a vector object to the current Vector object | As a python code expert, you are capable of creating scripts from specifications. |
def bbox(self, outname=None, format='ESRI Shapefile', overwrite=True):
"""
create a bounding box from the extent of the Vector object
Parameters
----------
outname: str or None
the name of the vector file to be written; if None, a Vector object is returned
fo... | Can you implement a function in Python 3 that
creates a bounding box from the extent of the Vector object. | You are a Python code analyst, evaluating scripts for potential improvements. |
def convert2wkt(self, set3D=True):
"""
export the geometry of each feature as a wkt string
Parameters
----------
set3D: bool
keep the third (height) dimension?
Returns
-------
"""
features = self.getfeatures()
for feature in ... | Can you create a Python 3 function that
exports the geometry of each feature as a wkt string | You are a Python code analyst, evaluating scripts for potential improvements. |
def getFeatureByAttribute(self, fieldname, attribute):
"""
get features by field attribute
Parameters
----------
fieldname: str
the name of the queried field
attribute: int or str
the field value of interest
Returns
-------
... | Create a Python 3 function for
getting features by field attribute | You are a Python code analyst, evaluating scripts for potential improvements. |
get a feature by its index | Can you tell what is the following Python 3 function doing
def getFeatureByIndex(self, index):
feature = self.layer[index]
if feature is None:
feature = self.getfeatures()[index]
return feature | As a Python code translator, you convert algorithms and pseudocode into Python. |
initialize a layer object | Can you tell what is the following Python 3 function doing
def init_layer(self):
self.layer = self.vector.GetLayer()
self.__features = [None] * self.nfeatures | As a Python code analyst, you investigate and solve complex coding mysteries |
def load(self):
"""
load all feature into memory
Returns
-------
"""
self.layer.ResetReading()
for i in range(self.nfeatures):
if self.__features[i] is None:
self.__features[i] = self.layer[i] | How would you code a function in Python 3 to
load all features into memory | As a python code expert, you are capable of creating scripts from specifications. |
Reproject the object to the target CRS. | Can you generate the documentation for the following Python 3 function
def reproject(self, projection):
srs_out = crsConvert(projection, 'osr')
if self.srs.IsSame(srs_out) == 0:
# create the CoordinateTransformation
coordTrans = osr.CoordinateTransformation(... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This method is used to reset the spatial reference system of the vector object. | Here you have a function in Python 3, explain what it does
def setCRS(self, crs):
# try to convert the input crs to osr.SpatialReference
srs_out = crsConvert(crs, 'osr')
# save all relevant info from the existing vector object
layername = self.layername
geomType = self.g... | You are a Python code analyst, evaluating scripts for potential improvements. |
Writes the Vector object to a file. | How would you explain what the following Python 3 function does
def write(self, outfile, format='ESRI Shapefile', overwrite=True):
(outfilepath, outfilename) = os.path.split(outfile)
basename = os.path.splitext(outfilename)[0]
driver = ogr.GetDriverByName(format)
if os.... | You are a Python code architect, reviewing and designing scalable and efficient code |
Write a single byte to a designated register in a specific location. | Can you generate the documentation for the following Python 3 function
def write_byte_data(self, address, register, value):
return self.smbus.write_byte_data(address, register, value) | You are a Python code generator, capable of creating scripts from specifications. |
Write 2 bytes to a specified register in a specific location. | Explain what the following Python 3 code does
def write_word_data(self, address, register, value):
return self.smbus.write_word_data(address, register, value) | As a python code expert, you are capable of creating scripts from specifications. |
Write to a specific register in a specific SMBus device. | Here you have a function in Python 3, explain what it does
def write_block_data(self, address, register, value):
return self.smbus.write_block_data(address, register, value) | As a python code expert, you are capable of creating scripts from specifications. |
This function is used to send a block read call to the specified address and value. | Given the following Python 3 function, write the documentation
def block_process_call(self, address, register, value):
return self.smbus.block_process_call(address, register, value) | As a python code expert, you are capable of creating scripts from specifications. |
Write to a specific register in a specific I2C block. | Explain what the following Python 3 code does
def write_i2c_block_data(self, address, register, value):
return self.smbus.write_i2c_block_data(address, register, value) | As a python code expert, you are capable of creating scripts from specifications. |
Initialize the zmq messaging. | Can you generate a brief explanation for the following Python 3 code
def _init_zmq(self, port_publish, port_subscribe):
log.debug('kernel {} publishing on port {}'
''.format(self.analysis.id_, port_publish))
self.zmq_publish = zmq.Context().socket(zmq.PUB)
self.zmq_publish.con... | You are a Python code architect, reviewing and designing scalable and efficient code |
Executes an action in the analysis with the given message. | Explain what the following Python 3 code does
def run_process(self, analysis, action_name, message='__nomessagetoken__'):
# detect process_id
process_id = None
if isinstance(message, dict) and '__process_id' in message:
process_id = message['__process_id']
del message['_... | You are a Python code architect, reviewing and designing scalable and efficient code |
Emit a signal to main.
| Can you generate the documentation for the following Python 3 function
def emit(self, signal, message, analysis_id):
log.debug('kernel {} zmq send ({}): {}'
''.format(analysis_id, signal, message))
self.zmq_publish.send(json.dumps({
'analysis_id': analysis_id,
... | You are a Python code generator, capable of creating scripts from specifications. |
Writes specified value to the pins defined as output by config_ports() method. Writing to input pins has no effect. | Make a summary of the following Python 3 code
def set_ports(self, port0 = 0x00, port1 = 0x00):
'Writes specified value to the pins defined as output by config_ports() method. Writing to input pins has no effect.'
self.bus.write_byte_data(self.address, self.OUTPUT_PORT0, port0)
self.bus.write_byt... | You are a Python code architect, reviewing and designing scalable and efficient code |
Reads logical values at pins. | Make a summary of the following Python 3 code
def get_ports(self):
'Reads logical values at pins.'
return (self.bus.read_byte_data(self.address, self.STATUS_PORT0), self.bus.read_byte_data(self.address, self.STATUS_PORT1)); | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_config(self):
'Reads logical values at pins.'
return (self.bus.read_byte_data(self.address, self.CONTROL_PORT0), self.bus.read_byte_data(self.address, self.CONTROL_PORT1)); | Implement a function in Python 3 to
read logical values at pins. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sets INPUT 1 or OUTPUT 0 direction on pins. Inversion setting is applicable for input pins 1 - inverted 0 - noninverted input polarity. | How would you explain what the following Python 3 function does
def set_pullups(self, port0 = 0x00, port1 = 0x00):
'Sets INPUT (1) or OUTPUT (0) direction on pins. Inversion setting is applicable for input pins 1-inverted 0-noninverted input polarity.'
self.bus.write_byte_data(self.address, self.PULLUP... | As a Python code analyst, you investigate and solve complex coding mysteries |
Writes specified value to the pins defined as output by method. Writing to input pins has no effect. | Given the following Python 3 function, write the documentation
def set_ports(self, port0 = 0x00, port1 = 0x00):
'Writes specified value to the pins defined as output by method. Writing to input pins has no effect.'
self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port0)
self.bus.write_... | You are a Python code architect, reviewing and designing scalable and efficient code |
get a gffutils DB from a GTF file | How would you explain what the following Python 3 function does
def get_gtf_db(gtf, in_memory=False):
db_file = gtf + '.db'
if gtf.endswith('.gz'):
db_file = gtf[:-3] + '.db'
if file_exists(db_file):
return gffutils.FeatureDB(db_file)
db_file = ':memory:' if in_memory else db_file
if... | You are a Python code architect, reviewing and designing scalable and efficient code |
Convert GTF to BED file. | How would you explain what the following Python 3 function does
def gtf_to_bed(gtf, alt_out_dir=None):
out_file = os.path.splitext(gtf)[0] + '.bed'
if file_exists(out_file):
return out_file
if not os.access(os.path.dirname(out_file), os.W_OK | os.X_OK):
if not alt_out_dir:
raise ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.