output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict | Explain what the following Python 3 code does
def _list_locators(self):
with _handle_oss_error():
response = _oss.Service(
self.client, endpoint=self._endpoint).list_buckets()
for bucket in response.buckets:
yield bucket.name, self._model_to_dict(bucket, ('name',... | As a Python code composer, you craft elegant and concise scripts. |
A generator function that returns objects from the specified path. | Can you generate the documentation for the following Python 3 function
def _list_objects(self, client_kwargs, path, max_request_entries):
kwargs = dict()
if max_request_entries:
kwargs['max_keys'] = max_request_entries
bucket = self._get_bucket(client_kwargs)
while True:
... | You are a Python code generator, capable of creating scripts from specifications. |
Read a range of bytes in stream. | Can you generate the documentation for the following Python 3 function
def _read_range(self, start, end=0):
if start >= self._size:
# EOF. Do not detect using 416 (Out of range) error, 200 returned.
return bytes()
# Get object bytes range
with _handle_oss_error():
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Read and return all the bytes from the stream until EOF. | Make a summary of the following Python 3 code
def _readall(self):
with _handle_oss_error():
return self._bucket.get_object(key=self._key).read() | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _flush(self, buffer):
"""
Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
"""
with _handle_oss_error():
self._bucket.put_object(key=self._key, data=buffer.tobytes()) | Implement a Python 3 function for
flushing the write buffers of the stream if applicable. | You are a Python code generator, capable of creating scripts from specifications. |
def _flush(self):
"""
Flush the write buffers of the stream.
"""
# Initialize multipart upload
if self._upload_id is None:
with _handle_oss_error():
self._upload_id = self._bucket.init_multipart_upload(
self._key).upload_id
... | Write a Python 3 script for
flushing the write buffers of the stream. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Close the object in write mode. | Explain what the following Python 3 code does
def _close_writable(self):
# Wait parts upload completion
parts = [_PartInfo(part_number=future['part_number'],
etag=future['response'].result().etag)
for future in self._write_futures]
# Complete multipar... | As a Python code composer, you craft elegant and concise scripts. |
def cos_open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, storage=None, storage_parameters=None, unsecure=None,
**kwargs):
"""
Open file and return a corresponding file object.
Equivalent to "io.open" or builtin "open".
File can also be binary opene... | Write a Python 3 function for
functioning that opens a file and returns a corresponding file - like object. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _text_io_wrapper(stream, mode, encoding, errors, newline):
"""Wrap a binary stream to Text stream.
Args:
stream (file-like object): binary stream.
mode (str): Open mode.
encoding (str): Stream encoding.
errors (str): Decoding error handling.
newline (str): Universal ... | Write a Python 3 script to
wrap a binary stream to a Text stream. | As a Python code composer, you craft elegant and concise scripts. |
Returns a random model identifier by class name. | Can you generate a brief explanation for the following Python 3 code
def random_model(ctx, model_class_name):
model_identifiers = ctx['model_identifiers'][model_class_name]
if not model_identifiers:
return 'None'
idx = random.randrange(0, len(model_identifiers))
return '"%s(%s)"' % (model_class_... | As a Python code analyst, you investigate and solve complex coding mysteries |
def random_models(ctx, model_class_name, min_count=0, max_count=3):
"""
Get a random model identifier by class name. Example usage::
# db/fixtures/Tag.yml
{% for i in range(0, 10) %}
tag{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
... | Write a Python 3 function for
returning a random model identifier by class name. | As a python code expert, you are capable of creating scripts from specifications. |
def list_objects(self, path='', relative=False, first_level=False,
max_request_entries=None):
"""
List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only fi... | How would you code a function in Python 3 to
list objects. Args: path (str): Path or URL. relative (bool): Path is relative to current root. first_level (bool): It True, returns only first level objects. Else, returns full tree. max_request_entries (int): If specified, maximum entries returned by request. Returns: gene... | As a Python code analyst, you investigate and solve complex coding mysteries |
def hash_key(self, key):
""" "Hash" all keys in a timerange to the same value. """
for i, destination_key in enumerate(self._dict):
if key < destination_key:
return destination_key
return key | Can you implement a function in Python 3 that
hashes all keys in a timerange to the same value. | You are a Python code analyst, evaluating scripts for potential improvements. |
Creates all the models in the fixture files in the fixtures_dir. | Can you tell what is the following Python 3 function doing
def create_all(self, progress_callback: Optional[callable] = None) -> Dict[str, object]:
if not self._loaded:
self._load_data()
# build up a directed acyclic graph to determine the model instantiation order
dag = nx.DiGraph(... | You are a Python code architect, reviewing and designing scalable and efficient code |
def convert_identifiers(self, identifiers: Union[Identifier, List[Identifier]]):
"""
Convert an individual :class:`Identifier` to a model instance,
or a list of Identifiers to a list of model instances.
"""
if not identifiers:
return identifiers
def _create_o... | Write a Python 3 script to
convert an individual : class : Identifier to a list of model instances or a list of model instances. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _load_data(self):
"""
Load all fixtures from :attr:`fixtures_dir`
"""
filenames = []
model_identifiers = defaultdict(list)
# attempt to load fixture files from given directories (first pass)
# for each valid model fixture file, read it into the cache and get ... | How would you code a function in Python 3 to
load all fixtures from given directories and store them in the self. _cache. | You are a Python code generator, capable of creating scripts from specifications. |
Load fixtures from the given yaml file. | Can you generate a brief explanation for the following Python 3 code
def _load_from_yaml(self, filename: str, model_identifiers: Dict[str, List[str]]):
class_name = filename[:filename.rfind('.')]
rendered_yaml = self.env.get_template(filename).render(
model_identifiers=model_identifiers)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _post_process_yaml_data(self,
fixture_data: Dict[str, Dict[str, Any]],
relationship_columns: Set[str],
) -> Tuple[Dict[str, Dict[str, Any]], List[str]]:
"""
Convert and normalize identifier strings to Ide... | Implement a Python 3 function for
converting and normalize identifier strings to Identifiers and determine the class relationships. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _ensure_env(self, env: Union[jinja2.Environment, None]):
"""
Make sure the jinja environment is minimally configured.
"""
if not env:
env = jinja2.Environment()
if not env.loader:
env.loader = jinja2.FunctionLoader(lambda filename: self._cache[filename... | Can you implement a function in Python 3 that
makes sure the jinja environment is minimally configured. | You are a Python code architect, reviewing and designing scalable and efficient code |
A context manager that preloads the environment variables for the object. | Can you generate the documentation for the following Python 3 function
def _preloading_env(self):
ctx = self.env.globals
try:
ctx['random_model'] = lambda *a, **kw: None
ctx['random_models'] = lambda *a, **kw: None
yield self.env
finally:
ctx['rand... | You are a Python code generator, capable of creating scripts from specifications. |
Get a cloud object storage instance. | Can you generate a brief explanation for the following Python 3 code
def get_instance(name, cls='system', storage=None, storage_parameters=None,
unsecure=None, *args, **kwargs):
"""
Get a cloud object storage instance.
Args:
name (str): File name, path or URL.
cls (str): Ty... | As a Python code analyst, you investigate and solve complex coding mysteries |
def mount(storage=None, name='', storage_parameters=None,
unsecure=None, extra_root=None):
"""
Mount a new storage.
Args:
storage (str): Storage name.
name (str): File URL. If storage is not specified,
URL scheme will be used as storage value.
storage_parameter... | Write a Python 3 script for
mounting a new storage at a new location. | You are a Python code generator, capable of creating scripts from specifications. |
def _system_parameters(**kwargs):
"""
Returns system keyword arguments removing Nones.
Args:
kwargs: system keyword arguments.
Returns:
dict: system keyword arguments.
"""
return {key: value for key, value in kwargs.items()
if (value is not None or value == {})} | Write a Python 3 function that can
return system keyword arguments removing Nones. | You are a Python code analyst, evaluating scripts for potential improvements. |
sadness because argparse doesn t quite do what we want. | Can you generate a brief explanation for the following Python 3 code
def manual_argument_parsing(argv):
# Special case these for a better error message
if not argv or argv == ['-h'] or argv == ['--help']:
print_help_and_exit()
try:
dashdash_index = argv.index('--')
except ValueError:
... | As a Python code composer, you craft elegant and concise scripts. |
def make_entry_point(patches, original_entry_point):
"""Use this to make a console_script entry point for your application
which applies patches.
:param patches: iterable of pymonkey patches to apply. Ex: ('my-patch,)
:param original_entry_point: Such as 'pip'
"""
def entry(argv=None):
... | Write a Python 3 function that can
create a console_script entry point for your application. | You are a Python code generator, capable of creating scripts from specifications. |
def client(self):
"""
Storage client
Returns:
client
"""
if self._client is None:
self._client = self._get_client()
return self._client | Implement a function in Python 3 to
return the client object for this storage instance. | As a Python code composer, you craft elegant and concise scripts. |
Check if a file exists in the object store. | Given the following Python 3 function, write the documentation
def exists(self, path=None, client_kwargs=None, assume_exists=None):
try:
self.head(path, client_kwargs)
except ObjectNotFoundError:
return False
except ObjectPermissionError:
if assume_exists is N... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the creation time of path. | Here you have a function in Python 3, explain what it does
def getctime(self, path=None, client_kwargs=None, header=None):
return self._getctime_from_header(
self.head(path, client_kwargs, header)) | You are a Python code architect, reviewing and designing scalable and efficient code |
def getmtime(self, path=None, client_kwargs=None, header=None):
"""
Return the time of last access of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The numb... | Create a Python 3 function for
returning the time of last access of path. | As a Python code composer, you craft elegant and concise scripts. |
def _get_time(header, keys, name):
"""
Get time from header
Args:
header (dict): Object header.
keys (tuple of str): Header keys.
name (str): Method name.
Returns:
float: The number of seconds since the epoch
"""
for key i... | How would you code a function in Python 3 to
get time from header | As a Python code composer, you craft elegant and concise scripts. |
Returns the size in bytes of the object at path. | Explain what the following Python 3 code does
def getsize(self, path=None, client_kwargs=None, header=None):
return self._getsize_from_header(self.head(path, client_kwargs, header)) | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the size in bytes from the header. | Can you generate the documentation for the following Python 3 function
def _getsize_from_header(self, header):
# By default, assumes that information are in a standard HTTP header
for key in self._SIZE_KEYS:
try:
return int(header.pop(key))
except KeyError:
... | As a python code expert, you are capable of creating scripts from specifications. |
def isdir(self, path=None, client_kwargs=None, virtual_dir=True,
assume_exists=None):
"""
Return True if path is an existing directory.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
virtual_dir (bool): If True, checks if... | Write a Python 3 function for
checking if a path is an existing directory. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def isfile(self, path=None, client_kwargs=None, assume_exists=None):
"""
Return True if path is an existing regular file.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to retur... | Create a Python 3 function to
check if a file exists. | You are a Python code generator, capable of creating scripts from specifications. |
def head(self, path=None, client_kwargs=None, header=None):
"""
Returns object HTTP header.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
dict: HTTP header.
"""
... | Write a Python 3 function for
returning object HTTP header. | You are a Python code analyst, evaluating scripts for potential improvements. |
def relpath(self, path):
"""
Get path relative to storage.
args:
path (str): Absolute path or URL.
Returns:
str: relative path.
"""
for root in self.roots:
# Root is regex, convert to matching root string
if isinstance(roo... | Write a Python 3 function that can
get path relative to storage. | You are a Python code generator, capable of creating scripts from specifications. |
def is_locator(self, path, relative=False):
"""
Returns True if path refer to a locator.
Depending the storage, locator may be a bucket or container name,
a hostname, ...
args:
path (str): path or URL.
relative (bool): Path is relative to current root.
... | Write a Python 3 function for
returning True if path refer to a locator. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def split_locator(self, path):
"""
Split the path into a pair (locator, path).
args:
path (str): Absolute path or URL.
Returns:
tuple of str: locator, path.
"""
relative = self.relpath(path)
try:
locator, tail = relative.split... | How would you implement a function in Python 3 that
splits the path into a pair of locator and tail. | As a Python code composer, you craft elegant and concise scripts. |
Make a directory.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root. | Here you have a function in Python 3, explain what it does
def make_dir(self, path, relative=False):
if not relative:
path = self.relpath(path)
self._make_dir(self.get_client_kwargs(self.ensure_dir_path(
path, relative=True))) | You are a Python code analyst, evaluating scripts for potential improvements. |
Remove an object from the cache. | How would you explain what the following Python 3 function does
def remove(self, path, relative=False):
if not relative:
path = self.relpath(path)
self._remove(self.get_client_kwargs(path)) | As a Python code analyst, you investigate and solve complex coding mysteries |
def ensure_dir_path(self, path, relative=False):
"""
Ensure the path is a dir path.
Should end with '/' except for schemes and locators.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
Returns:
path: dir pat... | How would you code a function in Python 3 to
ensure the path is a dir path. | You are a Python code generator, capable of creating scripts from specifications. |
A generator function that returns all objects in the specified path. | How would you explain what the following Python 3 function does
def list_objects(self, path='', relative=False, first_level=False,
max_request_entries=None):
"""
List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to curren... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns os. stat_result object. | Can you tell what is the following Python 3 function doing
def stat(self, path=None, client_kwargs=None, header=None):
# Should contain at least the strict minimum of os.stat_result
stat = OrderedDict((
("st_mode", 0), ("st_ino", 0), ("st_dev", 0), ("st_nlink", 0),
("st_uid", 0),... | As a Python code composer, you craft elegant and concise scripts. |
def init(uri=None, alembic_ini=None, engine=None, create=False):
""" Initialize a connection. Create tables if requested."""
if uri and engine:
raise ValueError("uri and engine cannot both be specified")
if uri is None and not engine:
uri = 'sqlite:////tmp/datanommer.db'
log.warni... | Implement a Python 3 function for
initializing a connection. Create tables if requested. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add(envelope):
""" Take a dict-like fedmsg envelope and store the headers and message
in the table.
"""
message = envelope['body']
timestamp = message.get('timestamp', None)
try:
if timestamp:
timestamp = datetime.datetime.utcfromtimestamp(timestamp)
else:
... | Can you write a function in Python 3 where it
takes a dict - like fedmsg envelope and store the headers and message in the table. | As a python code expert, you are capable of creating scripts from specifications. |
Get the instance of the class with the specified name. If it doesn t exist create it. | Given the following Python 3 function, write the documentation
def get_or_create(cls, name):
obj = cls.query.filter_by(name=name).one_or_none()
if obj:
return obj
try:
with session.begin_nested():
obj = cls(name=name)
session.add(obj)
... | As a Python code composer, you craft elegant and concise scripts. |
Returns True if path is an existing directory. | Explain what the following Python 3 code does
def isdir(path):
system = get_instance(path)
# User may use directory path without trailing '/'
# like on standard file systems
return system.isdir(system.ensure_dir_path(path)) | As a Python code composer, you craft elegant and concise scripts. |
Returns a relative file path to path either from the current directory or from a start directory. | Make a summary of the following Python 3 code
def relpath(path, start=None):
relative = get_instance(path).relpath(path)
if start:
# Storage relative path
# Replaces "\" by "/" for Windows.
return os_path_relpath(relative, start=start).replace('\\', '/')
return relative | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns True if both pathname arguments refer to the same file or directory. | Can you generate a brief explanation for the following Python 3 code
def samefile(path1, path2):
# Handles path-like objects and checks if storage
path1, path1_is_storage = format_and_is_storage(path1)
path2, path2_is_storage = format_and_is_storage(path2)
# Local files: Redirects to "os.path.samefile"... | As a Python code composer, you craft elegant and concise scripts. |
def splitdrive(path):
"""
Split the path into a pair (drive, tail) where drive is either a
mount point or the empty string. On systems which do not use drive
specifications, drive will always be the empty string.
In all cases, drive + tail will be the same as path.
Equivalent to "os.path.split... | Create a Python 3 function to
split the path into a pair of drive tail. | You are a Python code architect, reviewing and designing scalable and efficient code |
def handle_os_exceptions():
"""
Handles pycosio exceptions and raise standard OS exceptions.
"""
try:
yield
# Convert pycosio exception to equivalent OSError
except ObjectException:
exc_type, exc_value, _ = exc_info()
raise _OS_EXCEPTIONS.get(exc_type, OSError)(exc_value... | Can you implement a function in Python 3 that
handles pycosio exceptions and raises standard OS exceptions. | As a python code expert, you are capable of creating scripts from specifications. |
def listdir(path='.'):
"""
Return a list containing the names of the entries in the directory given by
path.
Equivalent to "os.listdir".
Args:
path (path-like object): Path or URL.
Returns:
list of str: Entries names.
"""
return [name.rstrip('/') for name, _ in
... | Implement a function in Python 3 to
return a list containing the names of the entries in the directory given by path. | You are a Python code analyst, evaluating scripts for potential improvements. |
def makedirs(name, mode=0o777, exist_ok=False):
"""
Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment
(not just the rightmost) will be created if it does not exist.
Equivalent to "os.makedirs".
Args:
name (path-l... | Create a Python 3 function for
creating a directory and all intermediate ones. | As a Python code analyst, you investigate and solve complex coding mysteries |
Creates a directory named path with numeric mode mode. | Can you tell what is the following Python 3 function doing
def mkdir(path, mode=0o777, dir_fd=None):
system = get_instance(path)
relative = system.relpath(path)
# Checks if parent directory exists
parent_dir = dirname(relative.rstrip('/'))
if parent_dir:
parent = path.rsplit(relative, 1)[0]... | As a Python code analyst, you investigate and solve complex coding mysteries |
def remove(path, dir_fd=None):
"""
Remove a file.
Equivalent to "os.remove" and "os.unlink".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage obje... | Write a Python 3 script to
remove a file. Equivalent to "os.remove" and "os.unlink". Args: path (path-like object): Path or URL. dir_fd: directory descriptors; see the os.remove() description for how it is interpreted. Not supported on cloud storage objects. | You are a Python code analyst, evaluating scripts for potential improvements. |
def rmdir(path, dir_fd=None):
"""
Remove a directory.
Equivalent to "os.rmdir".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.rmdir() description for how it is interpreted.
Not supported on cloud storage objects.
"""
... | Can you create a Python 3 function that
removes a directory. Equivalent to "os.rmdir". Args: path (path-like object): Path or URL. dir_fd: directory descriptors; see the os.rmdir() description for how it is interpreted. Not supported on cloud storage objects. | As a python code expert, you are capable of creating scripts from specifications. |
def scandir(path='.'):
"""
Return an iterator of os.DirEntry objects corresponding to the entries in
the directory given by path. The entries are yielded in arbitrary order,
and the special entries '.' and '..' are not included.
Equivalent to "os.scandir".
Args:
path (path-like object)... | Implement a function in Python 3 to
return an iterator of os. DirEntry objects corresponding to the entries in the directory given by path. | As a python code expert, you are capable of creating scripts from specifications. |
def name(self):
"""
The entry’s base filename, relative to the scandir() path argument.
Returns:
str: name.
"""
name = self._name.rstrip('/')
if self._bytes_path:
name = fsencode(name)
return name | Implement a function in Python 3 to
return the base filename of the entry. | You are a Python code architect, reviewing and designing scalable and efficient code |
def path(self):
"""
The entry’s full path name:
equivalent to os.path.join(scandir_path, entry.name)
where scandir_path is the scandir() path argument.
The path is only absolute if the scandir() path argument was absolute.
Returns:
str: name.
"""
... | Create a Python 3 function for
returning the full path name of the entry. | You are a Python code generator, capable of creating scripts from specifications. |
def is_file(self, follow_symlinks=True):
"""
Return True if this entry is a file or a symbolic link pointing to a
file; return False if the entry is or points to a directory or other
non-file entry, or if it doesn’t exist anymore.
The result is cached on the os.DirEntry object.
... | Create a Python 3 function to
return True if this entry is a file. | As a Python code composer, you craft elegant and concise scripts. |
Return a stat_result object for this entry. | Explain what the following Python 3 code does
def stat(self, follow_symlinks=True):
return self._system.stat(
path=self._path, client_kwargs=self._client_kwargs,
header=self._header) | As a Python code composer, you craft elegant and concise scripts. |
Flush the write buffers of the stream if applicable and
close the object. | Can you generate the documentation for the following Python 3 function
def close(self):
if self._writable and not self._closed:
self._closed = True
with self._seek_lock:
self._flush_raw_or_buffered()
if self._seek:
with handle_os_exceptions():
... | As a python code expert, you are capable of creating scripts from specifications. |
Flush the write buffers of the stream if applicable. | Can you tell what is the following Python 3 function doing
def flush(self):
if self._writable:
with self._seek_lock:
self._flush_raw_or_buffered()
# Clear the buffer
self._write_buffer = bytearray(self._buffer_size)
self._buffer_seek =... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _flush_raw_or_buffered(self):
"""
Flush using raw of buffered methods.
"""
# Flush only if bytes written
# This avoid no required process/thread
# creation and network call.
# This step is performed by raw stream.
if self._buffer_seek and self._seek:
... | Write a Python 3 script to
flush raw or buffered data. | You are a Python code generator, capable of creating scripts from specifications. |
Reads the next size bytes from the stream without advancing the position. | Here you have a function in Python 3, explain what it does
def peek(self, size=-1):
if not self._readable:
raise UnsupportedOperation('read')
with self._seek_lock:
self._raw.seek(self._seek)
return self._raw._peek(size) | As a Python code analyst, you investigate and solve complex coding mysteries |
def read(self, size=-1):
"""
Read and return up to size bytes,
with at most one call to the underlying raw stream’s.
Use at most one call to the underlying raw stream’s read method.
Args:
size (int): Number of bytes to read. -1 to read the
stream unt... | Write a Python 3 function for
reading up to size bytes from the underlying raw stream and returns up to size bytes. | You are a Python code architect, reviewing and designing scalable and efficient code |
Reads bytes into a pre - allocated writable bytes - like object b and returns the number of bytes read. | Can you tell what is the following Python 3 function doing
def readinto(self, b):
if not self._readable:
raise UnsupportedOperation('read')
with self._seek_lock:
# Gets seek
seek = self._seek
# Initializes queue
queue = self._read_queue
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Change the stream position to the given byte offset. | Here you have a function in Python 3, explain what it does
def seek(self, offset, whence=SEEK_SET):
if not self._seekable:
raise UnsupportedOperation('seek')
# Only read mode is seekable
with self._seek_lock:
# Set seek using raw method and
# sync buffered se... | As a python code expert, you are capable of creating scripts from specifications. |
def write(self, b):
"""
Write the given bytes-like object, b, to the underlying raw stream,
and return the number of bytes written.
Args:
b (bytes-like object): Bytes to write.
Returns:
int: The number of bytes written.
"""
if not self._w... | Write a Python 3 function for
writing the given bytes - like object b to the underlying raw stream and returns the number of bytes written. | As a python code expert, you are capable of creating scripts from specifications. |
This function creates a new QR code. | Explain what the following Python 3 code does
def create(content, error='H', version=None, mode=None, encoding=None):
return QRCode(content, error, version, mode, encoding) | As a Python code analyst, you investigate and solve complex coding mysteries |
Displays this QR code. | Here you have a function in Python 3, explain what it does
def show(self, wait=1.2, scale=10, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4):
"""Displays this QR code.
This method is mainly intended for debugging purposes.
This method saves the output o... | You are a Python code analyst, evaluating scripts for potential improvements. |
This method uses the png render and returns the PNG image encoded as base64 string. | Make a summary of the following Python 3 code
def png_as_base64_str(self, scale=1, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4):
"""This method uses the png render and returns the PNG image encoded as
base64 string. This can be useful for creating... | You are a Python code generator, capable of creating scripts from specifications. |
def xbm(self, scale=1, quiet_zone=4):
"""Returns a string representing an XBM image of the QR code.
The XBM format is a black and white image format that looks like a
C header file.
Because displaying QR codes in Tkinter is the
primary use case for this renderer, this m... | How would you code a function in Python 3 to
return a string representing an XBM image of the QR code. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This method returns a text based representation of the QR code. | Make a summary of the following Python 3 code
def _text(code, quiet_zone=4):
buf = io.StringIO()
border_row = '0' * (len(code[0]) + (quiet_zone*2))
#Every QR code start with a quiet zone at the top
for b in range(quiet_zone):
buf.write(border_row)
buf.write('\n')
for row in code:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
This function will format the QR code as a X BitMap. | Explain what the following Python 3 code does
def _xbm(code, scale=1, quiet_zone=4):
try:
str = unicode # Python 2
except NameError:
str = __builtins__['str']
buf = io.StringIO()
# Calculate the width in pixels
pixel_width = (len(code[0]) + quiet_zone * 2) * scale
... | You are a Python code generator, capable of creating scripts from specifications. |
This function writes the QR code out as an SVG document. | Can you tell what is the following Python 3 function doing
def _svg(code, version, file, scale=1, module_color='#000', background=None,
quiet_zone=4, xmldecl=True, svgns=True, title=None, svgclass='pyqrcode',
lineclass='pyqrline', omithw=False, debug=False):
"""This function writes the QR code out... | You are a Python code architect, reviewing and designing scalable and efficient code |
Helper function to convert a color provided in hexadecimal format
as RGB triple. | Given the following Python 3 function, write the documentation
def _hex_to_rgb(color):
if color[0] == '#':
color = color[1:]
if len(color) == 3:
color = color[0] * 2 + color[1] * 2 + color[2] * 2
if len(color) != 6:
raise ValueError('Input #{0} is not in #RRGGBB format'.format(color)... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This generator yields a set of tuples where the iterable is evenly sized and fillvalue will be appended to the last tuple. | Make a summary of the following Python 3 code
def grouper(self, n, iterable, fillvalue=None):
args = [iter(iterable)] * n
if hasattr(itertools, 'zip_longest'):
return itertools.zip_longest(*args, fillvalue=fillvalue)
return itertools.izip_longest(*args, fillvalue=fillvalue) | As a python code expert, you are capable of creating scripts from specifications. |
This method encodes the data into a binary string using the appropriate algorithm specified by the mode. | How would you explain what the following Python 3 function does
def encode(self):
if self.mode == tables.modes['alphanumeric']:
encoded = self.encode_alphanumeric()
elif self.mode == tables.modes['numeric']:
encoded = self.encode_numeric()
elif self.mode == tables.modes['... | You are a Python code generator, capable of creating scripts from specifications. |
This method encodes the QR code s data if its mode is
numeric. It returns the data encoded as a binary string. | Here you have a function in Python 3, explain what it does
def encode_numeric(self):
with io.StringIO() as buf:
#Break the number into groups of three digits
for triplet in self.grouper(3, self.data):
number = ''
for digit in triplet:
i... | As a python code expert, you are capable of creating scripts from specifications. |
This method encodes the QR code s data into a kanji encoded binary string. It returns the data encoded as a binary string. | Given the following Python 3 function, write the documentation
def encode_kanji(self):
def two_bytes(data):
"""Output two byte character code as a single integer."""
def next_byte(b):
"""Make sure that character code is an int. Python 2 and
3 compatibility... | You are a Python code analyst, evaluating scripts for potential improvements. |
This function properly constructs a QR code s data string. It takes the data and returns the data string. | Can you tell what is the following Python 3 function doing
def add_data(self):
#Encode the data into a QR code
self.buffer.write(self.binary_string(self.mode, 4))
self.buffer.write(self.get_data_length())
self.buffer.write(self.encode())
#Converts the buffer into "code word" int... | As a Python code composer, you craft elegant and concise scripts. |
def add_words(self):
"""The data block must fill the entire data capacity of the QR code.
If we fall short, then we must add bytes to the end of the encoded
data field. The value of these bytes are specified in the standard.
"""
data_blocks = len(self.buffer.getvalue()) // 8
... | Write a Python 3 script for
adding words to the data block of the QR code. | As a Python code analyst, you investigate and solve complex coding mysteries |
This method adds the detection patterns to the QR code. | How would you explain what the following Python 3 function does
def add_detection_pattern(self, m):
#Draw outer black box
for i in range(7):
inv = -(i+1)
for j in [0,6,-1,-7]:
m[j][i] = 1
m[i][j] = 1
m[inv][j] = 1
m... | As a python code expert, you are capable of creating scripts from specifications. |
This method draws the position adjustment patterns onto the QR code code. | Can you tell what is the following Python 3 function doing
def add_position_pattern(self, m):
#Version 1 does not have a position adjustment pattern
if self.version == 1:
return
#Get the coordinates for where to place the boxes
coordinates = tables.position_adjustment[self.v... | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_version_pattern(self, m):
"""For QR codes with a version 7 or higher, a special pattern
specifying the code's version is required.
For further information see:
http://www.thonky.com/qr-code-tutorial/format-version-information/#example-of-version-7-information-string
"""
... | How would you code a function in Python 3 to
add the version pattern to the internal table m. | You are a Python code architect, reviewing and designing scalable and efficient code |
split a list of closed issues into non - PR Issues and Pull Requests | Can you generate the documentation for the following Python 3 function
def split_pulls(all_issues, project="arokem/python-matlab-bridge"):
pulls = []
issues = []
for i in all_issues:
if is_pull_request(i):
pull = get_pull_request(project, i['number'], auth=True)
pulls.append(... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get all issues closed since a particular point in time. | How would you explain what the following Python 3 function does
def issues_closed_since(period=timedelta(days=365), project="arokem/python-matlab-bridge", pulls=False):
which = 'pulls' if pulls else 'issues'
if isinstance(period, timedelta):
since = round_hour(datetime.utcnow() - period)
else:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a list of issues sorted by field. | Explain what the following Python 3 code does
def sorted_by_field(issues, field='closed_at', reverse=False):
return sorted(issues, key = lambda i:i[field], reverse=reverse) | You are a Python code generator, capable of creating scripts from specifications. |
Summary report about a list of issues printing number and title. | Can you generate a brief explanation for the following Python 3 code
def report(issues, show_urls=False):
# titles may have unicode in them, so we must encode everything below
if show_urls:
for i in issues:
print(u'#%d: %s' % (i['number'],
i['title'].rep... | You are a Python code generator, capable of creating scripts from specifications. |
def encode_ndarray(obj):
"""Write a numpy array and its shape to base64 buffers"""
shape = obj.shape
if len(shape) == 1:
shape = (1, obj.shape[0])
if obj.flags.c_contiguous:
obj = obj.T
elif not obj.flags.f_contiguous:
obj = asfortranarray(obj.T)
else:
obj = obj.T... | Implement a Python 3 function for
writing a numpy array and its shape to base64 buffers | You are a Python code analyst, evaluating scripts for potential improvements. |
def decode_arr(data):
"""Extract a numpy array from a base64 buffer"""
data = data.encode('utf-8')
return frombuffer(base64.b64decode(data), float64) | Write a Python 3 script for
extracting a numpy array from a base64 buffer | As a Python code translator, you convert algorithms and pseudocode into Python. |
Run a function in Matlab and return the result. | How would you explain what the following Python 3 function does
def run_func(self, func_path, *func_args, **kwargs):
if not self.started:
raise ValueError('Session not started, use start()')
nargout = kwargs.pop('nargout', 1)
func_args += tuple(item for pair in zip(kwargs.keys(), kw... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _bind_method(self, name, unconditionally=False):
"""Generate a Matlab function and bind it to the instance
This is where the magic happens. When an unknown attribute of the
Matlab class is requested, it is assumed to be a call to a
Matlab function, and is generated and bound to the ... | Can you write a function in Python 3 where it
binds a Matlab function to the instance of the named attribute. | As a Python code analyst, you investigate and solve complex coding mysteries |
def format_line(line):
"""
Format a line of Matlab into either a markdown line or a code line.
Parameters
----------
line : str
The line of code to be formatted. Formatting occurs according to the
following rules:
- If the line starts with (at least) two %% signs, a new cel... | Can you write a function in Python 3 where it
formats a line of Matlab into a markdown line or a code line. | You are a Python code generator, capable of creating scripts from specifications. |
def lines_to_notebook(lines, name=None):
"""
Convert the lines of an m file into an IPython notebook
Parameters
----------
lines : list
A list of strings. Each element is a line in the m file
Returns
-------
notebook : an IPython NotebookNode class instance, containing the
... | Create a Python 3 function to
convert the lines of an m file into an IPython notebooknode. | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert a Matlab m - file into a Matlab notebook in ipynb format | Can you generate the documentation for the following Python 3 function
def convert_mfile(mfile, outfile=None):
lines = mfile_to_lines(mfile)
nb = lines_to_notebook(lines)
if outfile is None:
outfile = mfile.split('.m')[0] + '.ipynb'
with open(outfile, 'w') as fid:
nbwrite(nb, fid) | As a Python code composer, you craft elegant and concise scripts. |
Load the extension in IPython. | Explain what the following Python 3 code does
def load_ipython_extension(ip, **kwargs):
global _loaded
if not _loaded:
ip.register_magics(MatlabMagics(ip, **kwargs))
_loaded = True | As a Python code translator, you convert algorithms and pseudocode into Python. |
Post some text to a Gist and return the URL. | How would you explain what the following Python 3 function does
def post_gist(content, description='', filename='file', auth=False):
post_data = json.dumps({
"description": description,
"public": True,
"files": {
filename: {
"content": content
}
}
}).encode('utf... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_pull_request(project, num, auth=False):
"""get pull request info by number
"""
url = "https://api.github.com/repos/{project}/pulls/{num}".format(project=project, num=num)
if auth:
header = make_auth_header()
else:
header = None
response = requests.get(url, headers=header... | Write a Python 3 script for
getting pull request info by number | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.