output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Return True if this path is a character device. | Explain what the following Python 3 code does
def is_char_device(self):
try:
return S_ISCHR(self.stat().st_mode)
except OSError as e:
if e.errno != ENOENT:
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitro... | You are a Python code architect, reviewing and designing scalable and efficient code |
def grid_coords_from_corners(upper_left_corner, lower_right_corner, size):
''' Points are the outer edges of the UL and LR pixels. Size is rows, columns.
GC projection type is taken from Points. '''
assert upper_left_corner.wkt == lower_right_corner.wkt
geotransform = np.array([upper_left_corner.lon, -(... | How would you implement a function in Python 3 that
returns a GridCoordinates object for the given upper left corner and lower right corner. | You are a Python code architect, reviewing and designing scalable and efficient code |
def intersects(self, other_grid_coordinates):
""" returns True if the GC's overlap. """
ogc = other_grid_coordinates # alias
# for explanation: http://stackoverflow.com/questions/306316/determine-if-two-rectangles-overlap-each-other
# Note the flipped y-coord in this coord system.
... | How would you code a function in Python 3 to
return True if the GC s overlap. | As a Python code translator, you convert algorithms and pseudocode into Python. |
A string that uniquely represents this object. | Explain what the following Python 3 code does
def unique_str(self):
unique_str = "_".join(["%.3f" % f for f in self.geotransform] +
["%d" % d for d in self.x_size, self.y_size]
)
if self.date is not None:
unique_str += '_' + str(se... | As a Python code composer, you craft elegant and concise scripts. |
def _get_x_axis(self):
"""See http://www.gdal.org/gdal_datamodel.html for details."""
# 0,0 is top/left top top/left pixel. Actual x/y coord of that pixel are (.5,.5).
x_centers = np.linspace(.5, self.x_size - .5, self.x_size)
y_centers = x_centers * 0
return (self.geotransform[0... | How would you implement a function in Python 3 that
gets the x axis of the image. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the y axis of the logarithmic data. | Here you have a function in Python 3, explain what it does
def _get_y_axis(self):
# 0,0 is top/left top top/left pixel. Actual x/y coord of that pixel are (.5,.5).
y_centers = np.linspace(.5, self.y_size - .5, self.y_size)
x_centers = y_centers * 0
return (self.geotransform[3]
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def raster_to_projection_coords(self, pixel_x, pixel_y):
""" Use pixel centers when appropriate.
See documentation for the GDAL function GetGeoTransform for details. """
h_px_py = np.array([1, pixel_x, pixel_y])
gt = np.array([[1, 0, 0], self.geotransform[0:3], self.geotransform[3:6]])
... | Write a Python 3 function for
converting pixel coordinates to projection coordinates. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns pixel centers.
See documentation for the GDAL function GetGeoTransform for details. | Can you generate a brief explanation for the following Python 3 code
def projection_to_raster_coords(self, lat, lon):
r_px_py = np.array([1, lon, lat])
tg = inv(np.array([[1, 0, 0], self.geotransform[0:3], self.geotransform[3:6]]))
return np.inner(tg, r_px_py)[1:] | As a Python code composer, you craft elegant and concise scripts. |
def inpaint(self):
""" Replace masked-out elements in an array using an iterative image inpainting algorithm. """
import inpaint
filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2)
self.raster_data = np.ma.masked_invalid(filled) | Create a Python 3 function to
replace masked - out elements in an array using an iterative image inpainting algorithm. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Interpolate the pixel value in the raster data. | Given the following Python 3 function, write the documentation
def interp_value(self, lat, lon, indexed=False):
(px, py) = self.grid_coordinates.projection_to_raster_coords(lat, lon)
if indexed:
return self.raster_data[round(py), round(px)]
else:
# from scipy.interpolate ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Gets a connected Client object. | Given the following Python 3 function, write the documentation
def get_connected_client(self):
if self.__sem is not None:
yield self.__sem.acquire()
client = None
newly_created, client = self._get_client_from_pool_or_make_it()
if newly_created:
res = yield client.... | You are a Python code generator, capable of creating scripts from specifications. |
Gets a Client object that is not yet available. | Can you generate the documentation for the following Python 3 function
def get_client_nowait(self):
if self.__sem is not None:
if self.__sem._value == 0:
return None
self.__sem.acquire()
_, client = self._get_client_from_pool_or_make_it()
return client | As a python code expert, you are capable of creating scripts from specifications. |
def connected_client(self):
"""Returns a ContextManagerFuture to be yielded in a with statement.
Returns:
A ContextManagerFuture object.
Examples:
>>> with (yield pool.connected_client()) as client:
# client is a connected tornadis.Client instance
... | Can you create a Python 3 function that
returns a ContextManagerFuture that is yielded in a with statement. | You are a Python code architect, reviewing and designing scalable and efficient code |
Releases a client object to the pool. | Make a summary of the following Python 3 code
def release_client(self, client):
if isinstance(client, Client):
if not self._is_expired_client(client):
LOG.debug('Client is not expired. Adding back to pool')
self.__pool.append(client)
elif client.is_connect... | As a python code expert, you are capable of creating scripts from specifications. |
def destroy(self):
"""Disconnects all pooled client objects."""
while True:
try:
client = self.__pool.popleft()
if isinstance(client, Client):
client.disconnect()
except IndexError:
break | Can you implement a function in Python 3 that
disconnects all pooled client objects. | You are a Python code architect, reviewing and designing scalable and efficient code |
Connects some or all redis clients inside the pool. | Can you generate a brief explanation for the following Python 3 code
def preconnect(self, size=-1):
if size == -1 and self.max_size == -1:
raise ClientError("size=-1 not allowed with pool max_size=-1")
limit = min(size, self.max_size) if size != -1 else self.max_size
clients = yield ... | As a python code expert, you are capable of creating scripts from specifications. |
Setup python search and add TASKS_VENDOR_DIR if available. | Make a summary of the following Python 3 code
def setup_path(invoke_minversion=None):
# print("INVOKE.tasks: setup_path")
if not os.path.isdir(TASKS_VENDOR_DIR):
print("SKIP: TASKS_VENDOR_DIR=%s is missing" % TASKS_VENDOR_DIR)
return
elif os.path.abspath(TASKS_VENDOR_DIR) in sys.path:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Ensures that the current version of invoke is less than min_version. | Can you tell what is the following Python 3 function doing
def require_invoke_minversion(min_version, verbose=False):
# -- REQUIRES: sys.path is setup and contains invoke
try:
import invoke
invoke_version = invoke.__version__
except ImportError:
invoke_version = "__NOT_INSTALLED"
... | As a Python code composer, you craft elegant and concise scripts. |
Decorator for SectionSchema classes to define the mapping between a config section schema class and one or more config sections with matching name. | Here you have a function in Python 3, explain what it does
def matches_section(section_name):
section_names = section_name
if isinstance(section_name, six.string_types):
section_names = [section_name]
elif not isinstance(section_name, (list, tuple)):
raise ValueError("%r (expected: string, s... | You are a Python code generator, capable of creating scripts from specifications. |
Class decorator to assign parameter names to instances of Param. | Make a summary of the following Python 3 code
def assign_param_names(cls=None, param_class=None):
if param_class is None:
param_class = Param
def decorate_class(cls):
for name, value in select_params_from_section_schema(cls, param_class,
... | As a Python code composer, you craft elegant and concise scripts. |
Selects the parameters of a config file section schema. | Can you generate a brief explanation for the following Python 3 code
def select_params_from_section_schema(section_schema, param_class=Param,
deep=False):
"""Selects the parameters of a config section schema.
:param section_schema: Configuration file section schema to use... | As a Python code composer, you craft elegant and concise scripts. |
Parse a config file section by using its schema and description. | Make a summary of the following Python 3 code
def parse_config_section(config_section, section_schema):
storage = {}
for name, param in select_params_from_section_schema(section_schema):
value = config_section.get(name, None)
if value is None:
if param.default is None:
... | You are a Python code generator, capable of creating scripts from specifications. |
def generate_configfile_names(config_files, config_searchpath=None):
"""Generates all configuration file name combinations to read.
.. sourcecode::
# -- ALGORITHM:
# First basenames/directories are prefered and override other files.
for config_path in reversed(config_searchpath):
... | Create a Python 3 function to
generate all available configuration file names. | As a python code expert, you are capable of creating scripts from specifications. |
Select a subset of the sections in a configuration file by using
a list of section names of list of section name patters
| Make a summary of the following Python 3 code
def select_config_sections(configfile_sections, desired_section_patterns):
for section_name in configfile_sections:
for desired_section_pattern in desired_section_patterns:
if fnmatch(section_name, desired_section_pattern):
yield sect... | As a Python code analyst, you investigate and solve complex coding mysteries |
Indicates if this schema can be applied to a config section. | Given the following Python 3 function, write the documentation
def matches_section(cls, section_name, supported_section_names=None):
if supported_section_names is None:
supported_section_names = getattr(cls, "section_names", None)
# pylint: disable=invalid-name
for supported_section... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def collect_config_sections_from_schemas(cls, config_section_schemas=None):
# pylint: disable=invalid-name
"""Derive support config section names from config section schemas.
If no :param:`config_section_schemas` are provided, the schemas from
this class are used (normally defined in the... | Can you create a Python 3 function that
derives support config section names from config section schemas. | You are a Python code generator, capable of creating scripts from specifications. |
def process_config_section(cls, config_section, storage):
"""Process the config section and store the extracted data in
the param:`storage` (as outgoing param).
"""
# -- CONCEPT:
# if not storage:
# # -- INIT DATA: With default parts.
# storage.update(dict... | Implement a Python 3 function for
processing the config section and store the extracted data in the param storage. | You are a Python code generator, capable of creating scripts from specifications. |
Select the config schema that matches the config section. | Can you tell what is the following Python 3 function doing
def select_config_schema_for(cls, section_name):
# pylint: disable=cell-var-from-loop, redefined-outer-name
for section_schema in cls.config_section_schemas:
schema_matches = getattr(section_schema, "matches_section", None)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def select_storage_for(cls, section_name, storage):
"""Selects the data storage for a config section within the
:param:`storage`. The primary config section is normally merged into
the :param:`storage`.
:param section_name: Config section (name) to process.
:param storage: ... | Write a Python 3 function for
selecting the data storage for a config section within the given storage. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def clean_all(ctx, dry_run=False):
"""Clean up everything, even the precious stuff.
NOTE: clean task is executed first.
"""
cleanup_dirs(ctx.clean_all.directories or [], dry_run=dry_run)
cleanup_dirs(ctx.clean_all.extra_directories or [], dry_run=dry_run)
cleanup_files(ctx.clean_all.files or [],... | Write a Python 3 script for
cleaning up all the files and directories in the current order. | You are a Python code architect, reviewing and designing scalable and efficient code |
def clean_python(ctx, dry_run=False):
"""Cleanup python related files/dirs: *.pyc, *.pyo, ..."""
# MAYBE NOT: "**/__pycache__"
cleanup_dirs(["build", "dist", "*.egg-info", "**/__pycache__"],
dry_run=dry_run)
if not dry_run:
ctx.run("py.cleanup")
cleanup_files(["**/*.pyc", "*... | Write a Python 3 function that can
clean python related files and directories. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def cleanup_files(patterns, dry_run=False, workdir="."):
"""Remove files or files selected by file patterns.
Skips removal if file does not exist.
:param patterns: File patterns, like "**/*.pyc" (as list).
:param dry_run: Dry-run mode indicator (as bool).
:param workdir: Current work dir... | Create a Python 3 function for
removing files or files selected by patterns. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Use pathlib for ant - like patterns like. py | Explain what the following Python 3 code does
def path_glob(pattern, current_dir=None):
if not current_dir:
current_dir = pathlib.Path.cwd()
elif not isinstance(current_dir, pathlib.Path):
# -- CASE: string, path.Path (string-like)
current_dir = pathlib.Path(str(current_dir))
for p ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Stack a redis command inside the object. | Can you generate a brief explanation for the following Python 3 code
def stack_call(self, *args):
self.pipelined_args.append(args)
self.number_of_stacked_calls = self.number_of_stacked_calls + 1 | You are a Python code analyst, evaluating scripts for potential improvements. |
Connects the object to the redis server. | Given the following Python 3 function, write the documentation
def connect(self):
if self.is_connected() or self.is_connecting():
raise tornado.gen.Return(True)
if self.unix_domain_socket is None:
self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if se... | As a python code expert, you are capable of creating scripts from specifications. |
Disconnects the object from the Redis server. | Can you generate the documentation for the following Python 3 function
def disconnect(self):
if not self.is_connected() and not self.is_connecting():
return
LOG.debug("disconnecting from %s...", self._redis_server())
self.__periodic_callback.stop()
try:
self._iolo... | As a python code expert, you are capable of creating scripts from specifications. |
def write(self, data):
"""Buffers some data to be sent to the host:port in a non blocking way.
So the data is always buffered and not sent on the socket in a
synchronous way.
You can give a WriteBuffer as parameter. The internal Connection
WriteBuffer will be extended with this... | Create a Python 3 function to
write some data to the internal connection. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Simulate the Python 3 surrogateescape handler but for Python 2 only. | How would you explain what the following Python 3 function does
def surrogate_escape(error):
chars = error.object[error.start:error.end]
assert len(chars) == 1
val = ord(chars)
val += 0xdc00
return __builtin__.unichr(val), error.end | As a Python code composer, you craft elegant and concise scripts. |
Ensure the path as retrieved from a Python API is a proper Unicode string. | Explain what the following Python 3 code does
def _always_unicode(cls, path):
if PY3 or isinstance(path, text_type):
return path
return path.decode(sys.getfilesystemencoding(), 'surrogateescape') | You are a Python code analyst, evaluating scripts for potential improvements. |
The same as name but with one file extension stripped off. | Here you have a function in Python 3, explain what it does
def namebase(self):
base, ext = self.module.splitext(self.name)
return base | As a Python code composer, you craft elegant and concise scripts. |
Returns a list of all directories in this directory. | Here you have a function in Python 3, explain what it does
def dirs(self, pattern=None):
return [p for p in self.listdir(pattern) if p.isdir()] | As a Python code composer, you craft elegant and concise scripts. |
D. files - > List of the files in this directory. | Given the following Python 3 function, write the documentation
def files(self, pattern=None):
return [p for p in self.listdir(pattern) if p.isfile()] | You are a Python code generator, capable of creating scripts from specifications. |
A generator function that iterates over all directories in the directory and returns only directories whose names match the pattern. | Make a summary of the following Python 3 code
def walkdirs(self, pattern=None, errors='strict'):
if errors not in ('strict', 'warn', 'ignore'):
raise ValueError("invalid errors parameter")
try:
dirs = self.dirs()
except Exception:
if errors == 'ignore':
... | As a Python code composer, you craft elegant and concise scripts. |
A generator function that returns all files in the directory and directories that match the pattern. | Can you generate a brief explanation for the following Python 3 code
def walkfiles(self, pattern=None, errors='strict'):
if errors not in ('strict', 'warn', 'ignore'):
raise ValueError("invalid errors parameter")
try:
childList = self.listdir()
except Exception:
... | As a Python code composer, you craft elegant and concise scripts. |
Open this file and return a corresponding file object. | Can you tell what is the following Python 3 function doing
def open(self, *args, **kwargs):
with io_error_compat():
return io.open(self, *args, **kwargs) | As a Python code analyst, you investigate and solve complex coding mysteries |
r Write the given lines of text to the file. | Can you generate the documentation for the following Python 3 function
def write_lines(self, lines, encoding=None, errors='strict',
linesep=os.linesep, append=False):
r""" Write the given lines of text to this file.
By default this overwrites any existing file at this path.
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def mkdir_p(self, mode=0o777):
""" Like :meth:`mkdir`, but does not raise an exception if the
directory already exists. """
try:
self.mkdir(mode)
except OSError:
_, e, _ = sys.exc_info()
if e.errno != errno.EEXIST:
raise
return ... | Write a Python 3 script for
liking mkdir but does not raise an exception. | You are a Python code analyst, evaluating scripts for potential improvements. |
Like makedirs but does not raise an exception. | Make a summary of the following Python 3 code
def makedirs_p(self, mode=0o777):
try:
self.makedirs(mode)
except OSError:
_, e, _ = sys.exc_info()
if e.errno != errno.EEXIST:
raise
return self | As a Python code analyst, you investigate and solve complex coding mysteries |
Like rmdir but does not raise an exception if the directory is not empty. | Explain what the following Python 3 code does
def rmdir_p(self):
try:
self.rmdir()
except OSError:
_, e, _ = sys.exc_info()
if e.errno != errno.ENOTEMPTY and e.errno != errno.EEXIST:
raise
return self | As a python code expert, you are capable of creating scripts from specifications. |
Like removedirs but does not raise an exception if the the
directory is not empty. | Can you generate the documentation for the following Python 3 function
def removedirs_p(self):
try:
self.removedirs()
except OSError:
_, e, _ = sys.exc_info()
if e.errno != errno.ENOTEMPTY and e.errno != errno.EEXIST:
raise
return self | You are a Python code architect, reviewing and designing scalable and efficient code |
Like remove but does not raise an exception if the the
file does not exist. | Can you generate a brief explanation for the following Python 3 code
def remove_p(self):
try:
self.unlink()
except OSError:
_, e, _ = sys.exc_info()
if e.errno != errno.ENOENT:
raise
return self | You are a Python code analyst, evaluating scripts for potential improvements. |
Like rmtree but does not raise an exception if the directory does not exist. | How would you explain what the following Python 3 function does
def rmtree_p(self):
try:
self.rmtree()
except OSError:
_, e, _ = sys.exc_info()
if e.errno != errno.ENOENT:
raise
return self | As a Python code analyst, you investigate and solve complex coding mysteries |
Copy all contents of self to dst overwriting existing
contents in dst. | Can you generate a brief explanation for the following Python 3 code
def merge_tree(self, dst, symlinks=False, *args, **kwargs):
update = kwargs.pop('update', False)
with tempdir() as _temp_dir:
# first copy the tree to a stage directory to support
# the parameters and behavior ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def connect(self):
"""Connects the client object to redis.
It's safe to use this method even if you are already connected.
Note: this method is useless with autoconnect mode (default).
Returns:
a Future object with True as result if the connection was ok.
"""
... | Write a Python 3 script for
connecting the client object to redis. | As a Python code analyst, you investigate and solve complex coding mysteries |
Callback called when redis closed the connection. | Can you generate a brief explanation for the following Python 3 code
def _close_callback(self):
while True:
try:
callback = self.__callback_queue.popleft()
callback(ConnectionError("closed connection"))
except IndexError:
break
if s... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Callback called when some data is read on the socket. | Can you tell what is the following Python 3 function doing
def _read_callback(self, data=None):
try:
if data is not None:
self.__reader.feed(data)
while True:
reply = self.__reader.gets()
if reply is not False:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Calls a redis command and returns a Future of the reply. | Can you generate the documentation for the following Python 3 function
def call(self, *args, **kwargs):
if not self.is_connected():
if self.autoconnect:
# We use this method only when we are not contected
# to void performance penaly due to gen.coroutine decorator
... | You are a Python code generator, capable of creating scripts from specifications. |
def async_call(self, *args, **kwargs):
"""Calls a redis command, waits for the reply and call a callback.
Following options are available (not part of the redis command itself):
- callback
Function called (with the result as argument) when the result
is available. If no... | How would you code a function in Python 3 to
call a redis command and waits for the reply and call a callback. | As a Python code composer, you craft elegant and concise scripts. |
def format_args_in_redis_protocol(*args):
"""Formats arguments into redis protocol...
This function makes and returns a string/buffer corresponding to
given arguments formated with the redis protocol.
integer, text, string or binary types are automatically converted
(using utf8 if necessary).
... | How would you implement a function in Python 3 that
formats arguments into the redis protocol | You are a Python code architect, reviewing and designing scalable and efficient code |
Internal done callback to set the result of the object. | Can you tell what is the following Python 3 function doing
def _done_callback(self, wrapped):
if wrapped.exception():
self.set_exception(wrapped.exception())
else:
self.set_result(wrapped.result()) | As a Python code composer, you craft elegant and concise scripts. |
def create_url(artist, song):
"""Create the URL in the LyricWikia format"""
return (__BASE_URL__ +
'/wiki/{artist}:{song}'.format(artist=urlize(artist),
song=urlize(song))) | Implement a function in Python 3 to
create the URL in the LyricWikia format | You are a Python code generator, capable of creating scripts from specifications. |
Retrieve the lyrics of the song and return the first one in case
multiple versions are available. | Here you have a function in Python 3, explain what it does
def get_lyrics(artist, song, linesep='\n', timeout=None):
return get_all_lyrics(artist, song, linesep, timeout)[0] | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_all_lyrics(artist, song, linesep='\n', timeout=None):
"""Retrieve a list of all the lyrics versions of a song."""
url = create_url(artist, song)
response = _requests.get(url, timeout=timeout)
soup = _BeautifulSoup(response.content, "html.parser")
lyricboxes = soup.findAll('div', {'class': 'l... | Can you write a function in Python 3 where it
retrieves a list of all the lyrics versions of a song. | As a Python code composer, you craft elegant and concise scripts. |
def open_file(name, mode=None, driver=None, libver=None, userblock_size=None, **kwargs):
"""Open an ARF file, creating as necessary.
Use this instead of h5py.File to ensure that root-level attributes and group
creation property lists are set correctly.
"""
import sys
import os
from h5py im... | Write a Python 3 script for
opening an ARF file creating as necessary. | As a python code expert, you are capable of creating scripts from specifications. |
def create_entry(group, name, timestamp, **attributes):
"""Create a new ARF entry under group, setting required attributes.
An entry is an abstract collection of data which all refer to the same time
frame. Data can include physiological recordings, sound recordings, and
derived data such as spike time... | Write a Python 3 script to
create a new ARF entry under a group. | You are a Python code generator, capable of creating scripts from specifications. |
Create an ARF dataset under the specified group. | Make a summary of the following Python 3 code
def create_dataset(group, name, data, units='', datatype=DataTypes.UNDEFINED,
chunks=True, maxshape=None, compression=None,
**attributes):
"""Create an ARF dataset under group, setting required attributes
Required arguments:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a new array dataset under group with compound datatype and maxshape = None. | Can you generate the documentation for the following Python 3 function
def create_table(group, name, dtype, **attributes):
dset = group.create_dataset(
name, shape=(0,), dtype=dtype, maxshape=(None,))
set_attributes(dset, **attributes)
return dset | As a Python code composer, you craft elegant and concise scripts. |
Append data to dset along axis 0. | Explain what the following Python 3 code does
def append_data(dset, data):
N = data.shape[0] if hasattr(data, 'shape') else 1
if N == 0:
return
oldlen = dset.shape[0]
newlen = oldlen + N
dset.resize(newlen, axis=0)
dset[oldlen:] = data | You are a Python code analyst, evaluating scripts for potential improvements. |
def check_file_version(file):
"""Check the ARF version attribute of file for compatibility.
Raises DeprecationWarning for backwards-incompatible files, FutureWarning
for (potentially) forwards-incompatible files, and UserWarning for files
that may not have been created by an ARF library.
Returns t... | Implement a function in Python 3 to
check the ARF version attribute of file for compatibility. | You are a Python code generator, capable of creating scripts from specifications. |
Set multiple attributes on a node. | Explain what the following Python 3 code does
def set_attributes(node, overwrite=True, **attributes):
aset = node.attrs
for k, v in attributes.items():
if not overwrite and k in aset:
pass
elif v is None:
if k in aset:
del aset[k]
else:
... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a sequence of links in group in order of creation. | Given the following Python 3 function, write the documentation
def keys_by_creation(group):
from h5py import h5
out = []
try:
group._id.links.iterate(
out.append, idx_type=h5.INDEX_CRT_ORDER, order=h5.ITER_INC)
except (AttributeError, RuntimeError):
# pre 2.2 shim
def... | As a Python code composer, you craft elegant and concise scripts. |
def convert_timestamp(obj):
"""Make an ARF timestamp from an object.
Argument can be a datetime.datetime object, a time.struct_time, an integer,
a float, or a tuple of integers. The returned value is a numpy array with
the integer number of seconds since the Epoch and any additional
microseconds.
... | Can you write a function in Python 3 where it
converts an ARF timestamp from an object to an ARF timestamp. | As a python code expert, you are capable of creating scripts from specifications. |
def timestamp_to_datetime(timestamp):
"""Convert an ARF timestamp to a datetime.datetime object (naive local time)"""
from datetime import datetime, timedelta
obj = datetime.fromtimestamp(timestamp[0])
return obj + timedelta(microseconds=int(timestamp[1])) | Create a Python 3 function for
converting an ARF timestamp to a datetime. datetime object | As a Python code translator, you convert algorithms and pseudocode into Python. |
Set the uuid attribute of an HDF5 object. | Make a summary of the following Python 3 code
def set_uuid(obj, uuid=None):
from uuid import uuid4, UUID
if uuid is None:
uuid = uuid4()
elif isinstance(uuid, bytes):
if len(uuid) == 16:
uuid = UUID(bytes=uuid)
else:
uuid = UUID(hex=uuid)
if "uuid" in obj... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the uuid for obj or null uuid if none is set | Can you tell what is the following Python 3 function doing
def get_uuid(obj):
# TODO: deprecate null uuid ret val
from uuid import UUID
try:
uuid = obj.attrs['uuid']
except KeyError:
return UUID(int=0)
# convert to unicode for python 3
try:
uuid = uuid.decode('ascii')
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the number of children of obj optionally restricting by class | How would you explain what the following Python 3 function does
def count_children(obj, type=None):
if type is None:
return len(obj)
else:
# there doesn't appear to be any hdf5 function for getting this
# information without inspecting each child, which makes this somewhat
# slow... | You are a Python code generator, capable of creating scripts from specifications. |
def _todict(cls):
""" generate a dict keyed by value """
return dict((getattr(cls, attr), attr) for attr in dir(cls) if not attr.startswith('_')) | How would you implement a function in Python 3 that
generates a dict keyed by value | As a Python code analyst, you investigate and solve complex coding mysteries |
get_template will return a template in the template folder with some substitutions | How would you explain what the following Python 3 function does
def get_template(template_name,fields=None):
'''get_template will return a template in the template folder,
with some substitutions (eg, {'{{ graph | safe }}':"fill this in!"}
'''
template = None
if not template_name.endswith('.html'):
... | You are a Python code generator, capable of creating scripts from specifications. |
container similarity_vector is similar to compare_packages but intended
to compare a container object. | Explain what the following Python 3 code does
def container_similarity_vector(container1=None,packages_set=None,by=None):
'''container similarity_vector is similar to compare_packages, but intended
to compare a container object (singularity image or singularity hub container)
to a list of packages. If packa... | You are a Python code generator, capable of creating scripts from specifications. |
This function will generate a data structure with common and unique files to
two images. | Make a summary of the following Python 3 code
def compare_containers(container1=None, container2=None):
'''compare_containers will generate a data structure with common and unique files to
two images. If environmental variable SINGULARITY_HUB is set, will use container
database objects.
:param containe... | You are a Python code analyst, evaluating scripts for potential improvements. |
compare lists is the lowest level that drives compare_containers and compare_packages. It returns a dict with the unique total and intersecting things between two lists
| Explain what the following Python 3 code does
def compare_lists(list1,list2):
'''compare lists is the lowest level that drives compare_containers and
compare_packages. It returns a comparison object (dict) with the unique,
total, and intersecting things between two lists
:param list1: the list for conta... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def package_node(root=None, name=None):
'''package node aims to package a (present working node) for a user into
a container. This assumes that the node is a single partition.
:param root: the root of the node to package, default is /
:param name: the name for the image. If not specified, will use ma... | How would you implement a function in Python 3 that
packages a node into a container | You are a Python code architect, reviewing and designing scalable and efficient code |
get_build template returns a string or file for a particular build template | Here you have a function in Python 3, explain what it does
def get_build_template(template_name,params=None,to_file=None):
'''get_build template returns a string or file for a particular build template, which is
intended to build a version of a Singularity image on a cloud resource.
:param template_name: th... | You are a Python code generator, capable of creating scripts from specifications. |
sniff_extension will attempt to determine the file type based on the extension and return the proper mimetype | How would you explain what the following Python 3 function does
def sniff_extension(file_path,verbose=True):
'''sniff_extension will attempt to determine the file type based on the extension,
and return the proper mimetype
:param file_path: the full path to the file to sniff
:param verbose: print stuff ... | As a python code expert, you are capable of creating scripts from specifications. |
This function will zip up some list of files into a single file in a folder. | How would you explain what the following Python 3 function does
def zip_up(file_list,zip_name,output_folder=None):
'''zip_up will zip up some list of files into a package (.zip)
:param file_list: a list of files to include in the zip.
:param output_folder: the output folder to create the zip in. If not
... | As a python code expert, you are capable of creating scripts from specifications. |
get_container_contents will return a list of folders or files
for a container | Here you have a function in Python 3, explain what it does
def get_container_contents(container, split_delim=None):
'''get_container_contents will return a list of folders and or files
for a container. The environmental variable SINGULARITY_HUB being set
means that container objects are referenced instead o... | As a Python code analyst, you investigate and solve complex coding mysteries |
get_image_hash will return an md5 hash of the file based on a criteria level | Given the following Python 3 function, write the documentation
def get_image_file_hash(image_path):
'''get_image_hash will return an md5 hash of the file based on a criteria level.
:param level: one of LOW, MEDIUM, HIGH
:param image_path: full path to the singularity image
'''
hasher = hashlib.md5()... | As a Python code composer, you craft elegant and concise scripts. |
container_difference will return a data structure to render an html
tree | Make a summary of the following Python 3 code
def container_difference(container=None,container_subtract=None,image_package=None,
image_package_subtract=None,comparison=None):
'''container_difference will return a data structure to render an html
tree (graph) of the differences between... | As a Python code composer, you craft elegant and concise scripts. |
container_sim will return a data structure to render an html tree
| Here you have a function in Python 3, explain what it does
def container_similarity(container1=None,container2=None,image_package1=None,
image_package2=None,comparison=None):
'''container_sim will return a data structure to render an html tree
(graph) of the intersection (commonalities... | You are a Python code architect, reviewing and designing scalable and efficient code |
will render an html tree of a container | Explain what the following Python 3 code does
def container_tree(container=None,image_package=None):
'''tree will render an html tree (graph) of a container
'''
guts = get_container_contents(container=container,
image_package=image_package,
... | As a python code expert, you are capable of creating scripts from specifications. |
This function will convert a list of folders and files into a json structure that represents a graph. | Can you generate a brief explanation for the following Python 3 code
def make_container_tree(folders,files,path_delim="/",parse_files=True):
'''make_container_tree will convert a list of folders and files into a json structure that represents a graph.
:param folders: a list of folders in the image
:param fi... | As a Python code composer, you craft elegant and concise scripts. |
make a package tree | Make a summary of the following Python 3 code
def make_package_tree(matrix=None,labels=None,width=25,height=10,title=None,font_size=None):
'''make package tree will make a dendrogram comparing a matrix of packages
:param matrix: a pandas df of packages, with names in index and columns
:param labels: a list ... | As a python code expert, you are capable of creating scripts from specifications. |
make an interactive tree | Explain what the following Python 3 code does
def make_interactive_tree(matrix=None,labels=None):
'''make interactive tree will return complete html for an interactive tree
:param title: a title for the plot, if not defined, will be left out.
'''
from scipy.cluster.hierarchy import (
dendrogram,... | You are a Python code analyst, evaluating scripts for potential improvements. |
add_node will add a node to it s parent
| Can you tell what is the following Python 3 function doing
def add_node(node, parent):
'''add_node will add a node to it's parent
'''
newNode = dict(node_id=node.id, children=[])
parent["children"].append(newNode)
if node.left: add_node(node.left, newNode)
if node.right: add_node(node.right, new... | As a Python code analyst, you investigate and solve complex coding mysteries |
label tree will recursively label the tree | Can you tell what is the following Python 3 function doing
def label_tree(n,lookup):
'''label tree will again recursively label the tree
:param n: the root node, usually d3['children'][0]
:param lookup: the node/id lookup
'''
if len(n["children"]) == 0:
leaves = [lookup[n["node_id"]]]
el... | As a Python code composer, you craft elegant and concise scripts. |
def extract_apps(image, app_names):
''' extract app will extract metadata for one or more apps
Parameters
==========
image: the absolute path to the image
app_name: the name of the app under /scif/apps
'''
apps = dict()
if isinstance(app_names, tuple):
app_names... | Implement a function in Python 3 to
extract app will extract metadata for one or more apps | As a Python code translator, you convert algorithms and pseudocode into Python. |
downloads the repo from the specified url to the specified destination | Can you generate the documentation for the following Python 3 function
def download_repo(repo_url, destination, commit=None):
'''download_repo
:param repo_url: the url of the repo to clone from
:param destination: the full path to the destination for the repo
'''
command = "git clone %s %s" % (repo_... | As a Python code composer, you craft elegant and concise scripts. |
def get_tags(container=None,
search_folders=None,
file_list=None,
return_unique=True):
'''get tags will return a list of tags that describe the software in an image,
meaning inside of a paricular folder. If search_folder is not defined, uses lib
:param container: if p... | Can you write a function in Python 3 where it
gets tags will return a list of tags that describe the software in an image | You are a Python code generator, capable of creating scripts from specifications. |
def file_counts(container=None,
patterns=None,
image_package=None,
file_list=None):
'''file counts will return a list of files that match one or more regular expressions.
if no patterns is defined, a default of readme is used. All patterns and files are made
... | Implement a Python 3 function for
filing counts will return a list of files that match one or more regular expressions. | As a Python code analyst, you investigate and solve complex coding mysteries |
returns a dictionary with counts of file extensions for a container and an image. | Can you generate the documentation for the following Python 3 function
def extension_counts(container=None, file_list=None, return_counts=True):
'''extension counts will return a dictionary with counts of file extensions for
an image.
:param container: if provided, will use container as image. Can also prov... | 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.