output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Split the string s using shell - like syntax. | Given the following Python 3 function, write the documentation
def split(s, posix=True):
if isinstance(s, six.binary_type):
s = s.decode("utf-8")
return shlex.split(s, posix=posix) | As a Python code analyst, you investigate and solve complex coding mysteries |
Recursive search function.
Args:
path (str): Path to search recursively
matcher (str or callable): String pattern to search for or function
that returns True/False for a file argument
dirs (bool): if True returns directories that match the pattern
files(bool): if True re... | Here you have a function in Python 3, explain what it does
def search(path, matcher="*", dirs=False, files=True):
if callable(matcher):
def fnmatcher(items):
return list(filter(matcher, items))
else:
def fnmatcher(items):
return fnmatch.filter(items, matcher)
for ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Change the current working directory. | How would you explain what the following Python 3 function does
def chdir(directory):
directory = os.path.abspath(directory)
logger.info("chdir -> %s" % directory)
try:
if not os.path.isdir(directory):
logger.error(
"chdir -> %s failed! Directory does not exist!", directo... | As a Python code analyst, you investigate and solve complex coding mysteries |
Make a directory.
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. This is recursive.
Args:
path (str): Directory to create
mode (int): Directory mode
... | Can you tell what is the following Python 3 function doing
def mkdir(path, mode=0o755, delete=False):
logger.info("mkdir: %s" % path)
if os.path.isdir(path):
if not delete:
return True
if not remove(path):
return False
try:
os.makedirs(path, mode)
retu... | You are a Python code architect, reviewing and designing scalable and efficient code |
def __copyfile(source, destination):
"""Copy data and mode bits ("cp source destination").
The destination may be a directory.
Args:
source (str): Source file (file to copy).
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation... | Write a Python 3 script to
copy a file to a new location. | You are a Python code generator, capable of creating scripts from specifications. |
def __copyfile2(source, destination):
"""Copy data and all stat info ("cp -p source destination").
The destination may be a directory.
Args:
source (str): Source file (file to copy).
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the o... | Create a Python 3 function for
copying data and all stat info from source to destination. | You are a Python code analyst, evaluating scripts for potential improvements. |
Copy a directory tree recursively using copy2. | Make a summary of the following Python 3 code
def __copytree(source, destination, symlinks=False):
logger.info("copytree: %s -> %s" % (source, destination))
try:
__create_destdir(destination)
shutil.copytree(source, destination, symlinks)
return True
except Exception as e:
lo... | As a python code expert, you are capable of creating scripts from specifications. |
def copy(source, destination):
"""Copy file or directory.
Args:
source (str): Source file or directory
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation is successful, False otherwise.
"""
if os.path.isdir(source):
... | How would you implement a function in Python 3 that
copies a file or directory to a new location. | As a Python code composer, you craft elegant and concise scripts. |
def gcopy(pattern, destination):
"""Copy all file found by glob.glob(pattern) to destination directory.
Args:
pattern (str): Glob pattern
destination (str): Path to the destination directory.
Returns:
bool: True if the operation is successful, False otherwise.
"""
for item ... | Can you create a Python 3 function that
copies all files found by glob. glob to destination directory. | As a Python code analyst, you investigate and solve complex coding mysteries |
def move(source, destination):
"""Move a file or directory (recursively) to another location.
If the destination is on our current file system, then simply use
rename. Otherwise, copy source to the destination and then remove
source.
Args:
source (str): Source file or directory (file or di... | Can you implement a function in Python 3 that
moves a file or directory recursively to another location. | As a Python code composer, you craft elegant and concise scripts. |
def gmove(pattern, destination):
"""Move all file found by glob.glob(pattern) to destination directory.
Args:
pattern (str): Glob pattern
destination (str): Path to the destination directory.
Returns:
bool: True if the operation is successful, False otherwise.
"""
for item ... | Write a Python 3 function for
moving all files found by glob. glob to destination directory. | You are a Python code analyst, evaluating scripts for potential improvements. |
def __rmfile(path):
"""Delete a file.
Args:
path (str): Path to the file that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise.
"""
logger.info("rmfile: %s" % path)
try:
os.remove(path)
return True
except Exception as ... | How would you implement a function in Python 3 that
deletes a file. Args: path (str): Path to the file that needs to be deleted. Returns: bool: True if the operation is successful, False otherwise. | As a Python code analyst, you investigate and solve complex coding mysteries |
def remove(path):
"""Delete a file or directory.
Args:
path (str): Path to the file or directory that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise.
"""
if os.path.isdir(path):
return __rmtree(path)
else:
return __rmfil... | Can you create a Python 3 function that
deletes a file or directory. | As a Python code composer, you craft elegant and concise scripts. |
Remove all files found by glob. glob. | Given the following Python 3 function, write the documentation
def gremove(pattern):
for item in glob.glob(pattern):
if not remove(item):
return False
return True | You are a Python code architect, reviewing and designing scalable and efficient code |
Read the content of the file. | How would you explain what the following Python 3 function does
def read(path, encoding="utf-8"):
try:
with io.open(path, encoding=encoding) as f:
return f.read()
except Exception as e:
logger.error("read: %s failed. Error: %s", path, e)
return "" | You are a Python code analyst, evaluating scripts for potential improvements. |
def touch(path, content="", encoding="utf-8", overwrite=False):
"""Create a file at the given path if it does not already exists.
Args:
path (str): Path to the file.
content (str): Optional content that will be written in the file.
encoding (str): Encoding in which to write the content.... | Write a Python 3 script to
create a file at the given path if it does not already exist. | As a python code expert, you are capable of creating scripts from specifications. |
def get_object(path="", obj=None):
"""Return an object from a dot path.
Path can either be a full path, in which case the `get_object` function
will try to import the modules in the path and follow it to the final
object. Or it can be a path relative to the object passed in as the second
argument.
... | Implement a Python 3 function for
returning an object from a dot path. | As a Python code composer, you craft elegant and concise scripts. |
Load all subclasses of a class from a list of modules. | Can you generate a brief explanation for the following Python 3 code
def load_subclasses(klass, modules=None):
if modules:
if isinstance(modules, six.string_types):
modules = [modules]
loader = Loader()
loader.load(*modules)
return klass.__subclasses__() | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_exception():
"""Return full formatted traceback as a string."""
trace = ""
exception = ""
exc_list = traceback.format_exception_only(
sys.exc_info()[0], sys.exc_info()[1]
)
for entry in exc_list:
exception += entry
tb_list = traceback.format_tb(sys.exc_info()[2])
... | Create a Python 3 function for
returning full formatted traceback as a string. | As a python code expert, you are capable of creating scripts from specifications. |
Load one or more modules. | Can you generate the documentation for the following Python 3 function
def load(self, *modules):
for module in modules:
if isinstance(module, six.string_types):
try:
module = get_object(module)
except Exception as e:
self.errors... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _product_filter(products) -> str:
"""Calculate the product filter."""
_filter = 0
for product in {PRODUCTS[p] for p in products}:
_filter += product
return format(_filter, "b")[::-1] | Create a Python 3 function to
calculate the product filter. | As a Python code composer, you craft elegant and concise scripts. |
Fetch data from rmv. de. | How would you explain what the following Python 3 function does
async def get_departures(
self,
station_id: str,
direction_id: Optional[str] = None,
max_journeys: int = 20,
products: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""Fetch data from rmv.de."""
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Pretty print travel times. | Explain what the following Python 3 code does
def output(self) -> None:
print("%s - %s" % (self.station, self.now))
print(self.products_filter)
for j in sorted(self.journeys, key=lambda k: k.real_departure)[
: self.max_journeys
]:
print("-------------")
... | As a python code expert, you are capable of creating scripts from specifications. |
def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
**kwargs):
"""
:param variable_path: a delimiter-separated path to a nested value
:para... | Write a Python 3 script to
get a nested value from the specified path. | You are a Python code analyst, evaluating scripts for potential improvements. |
Process a text file. | Given the following Python 3 function, write the documentation
def process_file(path, processor, encoding='utf-8', mode='rt', *args, **kwargs):
''' Process a text file's content. If the file name ends with .gz, read it as gzip file '''
if mode not in ('rU', 'rt', 'rb', 'r'):
raise Exception("Invalid fil... | You are a Python code generator, capable of creating scripts from specifications. |
Read text file content. | Given the following Python 3 function, write the documentation
def read_file(path, encoding='utf-8', *args, **kwargs):
''' Read text file content. If the file name ends with .gz, read it as gzip file.
If mode argument is provided as 'rb', content will be read as byte stream.
By default, content is read as s... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Write content to a file. | How would you explain what the following Python 3 function does
def write_file(path, content, mode=None, encoding='utf-8'):
''' Write content to a file. If the path ends with .gz, gzip will be used. '''
if not mode:
if isinstance(content, bytes):
mode = 'wb'
else:
mode = ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def iter_csv_stream(input_stream, fieldnames=None, sniff=False, *args, **kwargs):
''' Read CSV content as a table (list of lists) from an input stream '''
if 'dialect' not in kwargs and sniff:
kwargs['dialect'] = csv.Sniffer().sniff(input_stream.read(1024))
input_stream.seek(0)
if 'quoting' ... | Write a Python 3 script for
reading CSV content as a list of lists from an input stream | As a Python code composer, you craft elegant and concise scripts. |
def read_csv_iter(path, fieldnames=None, sniff=True, mode='rt', encoding='utf-8', *args, **kwargs):
''' Iterate through CSV rows in a file.
By default, csv.reader() will be used any output will be a list of lists.
If fieldnames is provided, DictReader will be used and output will be list of OrderedDict inst... | Can you write a function in Python 3 where it
iterates through CSV files in a file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def read_csv(path, fieldnames=None, sniff=True, encoding='utf-8', *args, **kwargs):
''' Read CSV rows as table from a file.
By default, csv.reader() will be used any output will be a list of lists.
If fieldnames is provided, DictReader will be used and output will be list of OrderedDict instead.
CSV sni... | Implement a function in Python 3 to
read CSV rows as list of lists. | You are a Python code generator, capable of creating scripts from specifications. |
def write_csv(path, rows, dialect='excel', fieldnames=None, quoting=csv.QUOTE_ALL, extrasaction='ignore', *args, **kwargs):
''' Write rows data to a CSV file (with or without fieldnames) '''
if not quoting:
quoting = csv.QUOTE_MINIMAL
if 'lineterminator' not in kwargs:
kw... | Write a Python 3 function that can
write rows data to a CSV file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Write rows data to a CSV file. | How would you explain what the following Python 3 function does
def write(file_name, rows, header=None, *args, **kwargs):
''' Write rows data to a CSV file (with or without header) '''
warnings.warn("chirptext.io.CSV is deprecated and will be removed in near future.", DeprecationWarning)
write_c... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a string suitable for RFC 2822 compliant Message - ID. | Explain what the following Python 3 code does
def make_msgid(idstring=None, utc=False):
if utc:
timestamp = time.gmtime()
else:
timestamp = time.localtime()
utcdate = time.strftime("%Y%m%d%H%M%S", timestamp)
try:
pid = os.getpid()
except AttributeError:
# No ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def forbid_multi_line_headers(name, val):
"""Forbid multi-line headers, to prevent header injection."""
val = smart_text(val)
if "\n" in val or "\r" in val:
raise BadHeaderError(
"Header values can't contain newlines "
"(got %r for header %r)" % (val, name)
)
... | Can you implement a function in Python 3 that
forbids multi - line headers to prevent header injection. | As a python code expert, you are capable of creating scripts from specifications. |
def send_mail(
subject,
sender,
to,
message,
html_message=None,
cc=None,
bcc=None,
attachments=None,
host=None,
port=None,
auth_user=None,
auth_password=None,
use_tls=False,
fail_silently=False,
):
"""Send a single email to a recipient list.
... | Write a Python 3 function that can
send an email to a list of recipients. | You are a Python code analyst, evaluating scripts for potential improvements. |
Send multiple emails to multiple recipients. | Can you tell what is the following Python 3 function doing
def send_mass_mail(
datatuple, fail_silently=False, auth_user=None, auth_password=None
):
"""Send multiple emails to multiple recipients.
Given a datatuple of (subject, message, sender, recipient_list), sends
each message to each recipien... | You are a Python code analyst, evaluating scripts for potential improvements. |
def open(self):
"""Ensure we have a connection to the email server.
Returns whether or not a new connection was required (True or False).
"""
if self.connection:
# Nothing to do if the connection is already open.
return False
try:
# I... | Create a Python 3 function to
open a new connection to the email server. | You are a Python code analyst, evaluating scripts for potential improvements. |
Close the connection to the email server. | Here you have a function in Python 3, explain what it does
def close(self):
try:
try:
self.connection.quit()
except socket.sslerror:
# This happens when calling quit() on a TLS connection
# sometimes.
self.connection.... | You are a Python code generator, capable of creating scripts from specifications. |
def send_messages(self, messages):
"""Send one or more EmailMessage objects.
Returns:
int: Number of email messages sent.
"""
if not messages:
return
new_conn_created = self.open()
if not self.connection:
# We failed silentl... | How would you code a function in Python 3 to
send one or more EmailMessage objects. | You are a Python code architect, reviewing and designing scalable and efficient code |
Send an email.
Helper method that does the actual sending. | Can you generate the documentation for the following Python 3 function
def _send(self, message):
if not message.recipients():
return False
try:
self.connection.sendmail(
message.sender,
message.recipients(),
message.message()... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Adds a file with the given filename and content to the message attachments. | Given the following Python 3 function, write the documentation
def attach(self, filename=None, content=None, mimetype=None):
if isinstance(filename, MIMEBase):
assert content is None and mimetype is None
self.attachments.append(filename)
elif content is None and os.path.isfil... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _create_attachment(self, filename, content, mimetype=None):
"""Convert the filename, content, mimetype triple to attachment."""
if mimetype is None:
mimetype, _ = mimetypes.guess_type(filename)
if mimetype is None:
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
... | How would you code a function in Python 3 to
convert the filename content mimetype triple to attachment. | As a python code expert, you are capable of creating scripts from specifications. |
Attach an alternative content representation. | How would you explain what the following Python 3 function does
def attach_alternative(self, content, mimetype=None):
self.attach(content=content, mimetype=mimetype) | You are a Python code architect, reviewing and designing scalable and efficient code |
Setup console logging. Info and below go to stdout, others go to stderr.
:param bool verbose: Print debug statements.
:param str logger: Which logger to set handlers to. Used for testing. | Can you generate a brief explanation for the following Python 3 code
def setup_logging(verbose=False, logger=None):
if not verbose:
logging.getLogger('requests').setLevel(logging.WARNING)
format_ = '%(asctime)s %(levelname)-8s %(name)-40s %(message)s' if verbose else '%(message)s'
level = logging.D... | You are a Python code generator, capable of creating scripts from specifications. |
Get command line arguments or values from environment variables. | Given the following Python 3 function, write the documentation
def get_arguments(argv=None, environ=None):
name = 'appveyor-artifacts'
environ = environ or os.environ
require = getattr(pkg_resources, 'require') # Stupid linting error.
commit, owner, pull_request, repo, tag = '', '', '', '', ''
# R... | You are a Python code analyst, evaluating scripts for potential improvements. |
def query_api(endpoint, log):
"""Query the AppVeyor API.
:raise HandledError: On non HTTP200 responses or invalid JSON response.
:param str endpoint: API endpoint to query (e.g. '/projects/Robpol86/appveyor-artifacts').
:param logging.Logger log: Logger for this function. Populated by with_log() decor... | Write a Python 3 function that can
query the AppVeyor API. | As a Python code analyst, you investigate and solve complex coding mysteries |
def validate(config, log):
"""Validate config values.
:raise HandledError: On invalid config values.
:param dict config: Dictionary from get_arguments().
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
"""
if config['always_job_dirs'] and config['no_job_... | Write a Python 3 function for
validating the config values. | As a Python code composer, you craft elegant and concise scripts. |
def query_build_version(config, log):
"""Find the build version we're looking for.
AppVeyor calls build IDs "versions" which is confusing but whatever. Job IDs aren't available in the history query,
only on latest, specific version, and deployment queries. Hence we need two queries to get a one-time status... | Write a Python 3 function for
querying AppVeyor for the build version we re looking for. | As a python code expert, you are capable of creating scripts from specifications. |
Query AppVeyor for one or more job IDs and their status associated with a build version. | Can you generate a brief explanation for the following Python 3 code
def query_job_ids(build_version, config, log):
url = '/projects/{0}/{1}/build/{2}'.format(config['owner'], config['repo'], build_version)
# Query version.
log.debug('Querying AppVeyor version API for %s/%s at %s...', config['owner'], conf... | You are a Python code analyst, evaluating scripts for potential improvements. |
def query_artifacts(job_ids, log):
"""Query API again for artifacts.
:param iter job_ids: List of AppVeyor jobIDs.
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
:return: List of tuples: (job ID, artifact file name, artifact file size).
:rtype: list
"""... | Write a Python 3 function that can
query API again for artifacts. | As a python code expert, you are capable of creating scripts from specifications. |
def artifacts_urls(config, jobs_artifacts, log):
"""Determine destination file paths for job artifacts.
:param dict config: Dictionary from get_arguments().
:param iter jobs_artifacts: List of job artifacts from query_artifacts().
:param logging.Logger log: Logger for this function. Populated by with_l... | Write a Python 3 function that can
determine the URLs for the artifacts and download them. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_urls(config, log):
"""Wait for AppVeyor job to finish and get all artifacts' URLs.
:param dict config: Dictionary from get_arguments().
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
:return: Paths and URLs from artifacts_urls.
:rtype: dict
"""
... | Implement a Python 3 function for
waiting for AppVeyor job to finish and get all artifacts URLs. | As a python code expert, you are capable of creating scripts from specifications. |
Download a file from the server. | Can you generate the documentation for the following Python 3 function
def download_file(config, local_path, url, expected_size, chunk_size, log):
if not os.path.exists(os.path.dirname(local_path)):
log.debug('Creating directory: %s', os.path.dirname(local_path))
os.makedirs(os.path.dirname(local_pa... | As a python code expert, you are capable of creating scripts from specifications. |
def mangle_coverage(local_path, log):
"""Edit .coverage file substituting Windows file paths to Linux paths.
:param str local_path: Destination path to save file to.
:param logging.Logger log: Logger for this function. Populated by with_log() decorator.
"""
# Read the file, or return if not a .cove... | Implement a Python 3 function for
editing coverage file substituting Windows file paths to Linux paths. | You are a Python code architect, reviewing and designing scalable and efficient code |
Entry - point from setuptools. | How would you explain what the following Python 3 function does
def entry_point():
signal.signal(signal.SIGINT, lambda *_: getattr(os, '_exit')(0)) # Properly handle Control+C
config = get_arguments()
setup_logging(config['verbose'])
try:
main(config)
except HandledError:
if config[... | You are a Python code architect, reviewing and designing scalable and efficient code |
Consume the receive buffer and return the messages. | Make a summary of the following Python 3 code
def incoming_messages(self) -> t.List[t.Tuple[float, bytes]]:
approximate_messages = self._receive_buffer.qsize()
messages = []
for _ in range(approximate_messages):
try:
messages.append(self._receive_buffer.get_nowait())
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def strip_callables(row):
"""Extract callable values from `row`.
Replace the callable values with the initial value (if specified) or
an empty string.
Parameters
----------
row : mapping
A data row. The keys are either a single column name or a tuple of
... | Create a Python 3 function to
extract callable values from a data row. | You are a Python code generator, capable of creating scripts from specifications. |
Build the style and fields for the current locale. | Explain what the following Python 3 code does
def build(self, columns):
self.columns = columns
default = dict(elements.default("default_"),
**_safe_get(self.init_style, "default_", {}))
self.style = elements.adopt({c: default for c in columns},
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _compose(self, name, attributes):
"""Construct a style taking `attributes` from the column styles.
Parameters
----------
name : str
Name of main style (e.g., "header_").
attributes : set of str
Adopt these elements from the column styles.
Ret... | Create a Python 3 function to
construct a composite style taking attributes from the column styles. | As a python code expert, you are capable of creating scripts from specifications. |
def _set_widths(self, row, proc_group):
"""Update auto-width Fields based on `row`.
Parameters
----------
row : dict
proc_group : {'default', 'override'}
Whether to consider 'default' or 'override' key for pre- and
post-format processors.
Returns... | Can you create a Python 3 function that
updates auto - width fields based on row. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return whether group is default or override. | Can you generate a brief explanation for the following Python 3 code
def _proc_group(self, style, adopt=True):
fields = self.fields
if style is not None:
if adopt:
style = elements.adopt(self.style, style)
elements.validate(style)
for column in self.c... | You are a Python code analyst, evaluating scripts for potential improvements. |
def render(self, row, style=None, adopt=True):
"""Render fields with values from `row`.
Parameters
----------
row : dict
A normalized row.
style : dict, optional
A style that follows the schema defined in pyout.elements. If
None, `self.style`... | How would you code a function in Python 3 to
render fields with values from row. | You are a Python code generator, capable of creating scripts from specifications. |
def get_config(self):
"""
Sets up the basic config from the variables passed in
all of these are from what Heroku gives you.
"""
self.create_ssl_certs()
config = {
"bootstrap_servers": self.get_brokers(),
"security_protocol": 'SSL',
"s... | Can you create a Python 3 function that
sets up the basic config from the variables passed in | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_brokers(self):
"""
Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects.
"""
return ['{}:{}'.format(parsedUrl.hostname, parsedUrl.port) for parsedUrl in
[urlparse(url) for url in self.kafka_url.split(',')]] | Create a Python 3 function for
parsing the KAKFA_URL and returns a list of hostname : port pairs in the format that kafka - python expects. | As a Python code composer, you craft elegant and concise scripts. |
def create_ssl_certs(self):
"""
Creates SSL cert files
"""
for key, file in self.ssl.items():
file["file"] = self.create_temp_file(file["suffix"], file["content"]) | Write a Python 3 script for
creating SSL cert files based on the current locale. | As a python code expert, you are capable of creating scripts from specifications. |
def create_temp_file(self, suffix, content):
"""
Creates file, because environment variables are by default escaped it
encodes and then decodes them before write so \n etc. work correctly.
"""
temp = tempfile.NamedTemporaryFile(suffix=suffix)
temp.write(content.encode('l... | Create a Python 3 function for
creating a temporary file with the given content. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Adds the topic_prefix to the topic list supplied by topics | Can you generate a brief explanation for the following Python 3 code
def prefix_topic(self, topics):
if not self.topic_prefix or not topics:
return topics
if not isinstance(topics, str) and isinstance(topics, collections.Iterable):
return [self.topic_prefix + topic for topic in ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def send(self, topic, *args, **kwargs):
"""
Appends the prefix to the topic before sendingf
"""
prefix_topic = self.heroku_kafka.prefix_topic(topic)
return super(HerokuKafkaProducer, self).send(prefix_topic, *args, **kwargs) | Write a Python 3 script for
sending a message to the given topic. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get a nested value from the specified path. | Here you have a function in Python 3, explain what it does
def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
**kwargs):
"""
Inherited method shou... | As a Python code composer, you craft elegant and concise scripts. |
Coerces a value to a type of val. | Given the following Python 3 function, write the documentation
def coerce(val: t.Any,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None) -> t.Any:
"""
Casts a type of ``val`` to ``coerce_type`` with ``coercer``.
If ``coerce_type`` is bo... | As a python code expert, you are capable of creating scripts from specifications. |
Lazy initialize and cache client. | Explain what the following Python 3 code does
def client(self):
if self._client is not None:
return self._client
self._client = self.get_client()
return self._client | You are a Python code analyst, evaluating scripts for potential improvements. |
Splice value at its center retaining a total of n characters. | Here you have a function in Python 3, explain what it does
def _splice(value, n):
if n <= 0:
raise ValueError("n must be positive")
value_len = len(value)
center = value_len // 2
left, right = value[:center], value[center:]
if n >= value_len:
return left, right
n_todrop = valu... | As a Python code analyst, you investigate and solve complex coding mysteries |
def write_uwsgi_ini_cfg(fp: t.IO, cfg: dict):
"""
Writes into IO stream the uwsgi.ini file content (actually it does smth strange, just look below).
uWSGI configs are likely to break INI (YAML, etc) specification (double key definition)
so it writes `cfg` object (dict) in "uWSGI Style".
>>> import... | Can you implement a function in Python 3 that
writes the uWSGI. ini file content into the IO stream. | As a python code expert, you are capable of creating scripts from specifications. |
Get a nested value from the client. | Explain what the following Python 3 code does
def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
**kwargs):
"""
:param variable_path: a delimiter-... | You are a Python code generator, capable of creating scripts from specifications. |
Translate iTunesSD bytes to tree object | Given the following Python 3 function, write the documentation
def itunessd_to_dics(itunessd):
# header
header_size = get_table_size(header_table)
header_chunk = itunessd[0:header_size]
header_dic = chunk_to_dic(header_chunk, header_table)
# tracks
tracks_header_dic, tracks_offsets = get_dic_s... | As a python code expert, you are capable of creating scripts from specifications. |
def dics_to_itunessd(header_dic, tracks_dics, playlists_dics_and_indexes):
"""
:param header_dic: dic of header_table
:param tracks_dics: list of all track_table's dics
:param playlists_dics_and_indexes: list of all playlists and all their track's indexes
:return: the whole iTunesSD bytes data
"... | Implement a Python 3 function for
converting dics to iTunesSD format | You are a Python code generator, capable of creating scripts from specifications. |
def add(self, kind, key, *values):
"""Add processor functions.
Any previous list of processors for `kind` and `key` will be
overwritten.
Parameters
----------
kind : {"pre", "post"}
key : str
A registered key. Add the functions (in order) to this ke... | Write a Python 3 script for
adding the functions to the list of processors for the given kind and key. | You are a Python code generator, capable of creating scripts from specifications. |
Wrap format call as a two - argument processor function. | Can you generate the documentation for the following Python 3 function
def _format(self, _, result):
return self._fmt.format(six.text_type(result)) | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a processor for a style s transform function. | Explain what the following Python 3 code does
def transform(function):
def transform_fn(_, result):
if isinstance(result, Nothing):
return result
lgr.debug("Transforming %r with %r", result, function)
try:
return function(result)
e... | You are a Python code analyst, evaluating scripts for potential improvements. |
def by_key(self, style_key, style_value):
"""Return a processor for a "simple" style value.
Parameters
----------
style_key : str
A style key.
style_value : bool or str
A "simple" style value that is either a style attribute (str) and a
boolea... | Can you write a function in Python 3 where it
returns a processor for a simple style value. | You are a Python code generator, capable of creating scripts from specifications. |
Return a processor that extracts the style from mapping. | Here you have a function in Python 3, explain what it does
def by_lookup(self, style_key, style_value):
style_attr = style_key if self.style_types[style_key] is bool else None
mapping = style_value["lookup"]
def proc(value, result):
try:
lookup_value = mapping[value]... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a processor for a re_lookup style value. | Can you tell what is the following Python 3 function doing
def by_re_lookup(self, style_key, style_value, re_flags=0):
style_attr = style_key if self.style_types[style_key] is bool else None
regexps = [(re.compile(r, flags=re_flags), v)
for r, v in style_value["re_lookup"]]
d... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a processor for an interval style value. | Can you generate a brief explanation for the following Python 3 code
def by_interval_lookup(self, style_key, style_value):
style_attr = style_key if self.style_types[style_key] is bool else None
intervals = style_value["interval"]
def proc(value, result):
try:
value ... | As a Python code composer, you craft elegant and concise scripts. |
Yield post - format processors based on column_style. | Make a summary of the following Python 3 code
def post_from_style(self, column_style):
flanks = Flanks()
yield flanks.split_flanks
fns = {"simple": self.by_key,
"lookup": self.by_lookup,
"re_lookup": self.by_re_lookup,
"interval": self.by_interval_lo... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return result with flanking whitespace. | Can you generate a brief explanation for the following Python 3 code
def split_flanks(self, _, result):
if not result.strip():
self.left, self.right = "", ""
return result
match = self.flank_re.match(result)
assert match, "This regexp should always match"
self.le... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_subscribers(self):
"""Get per-instance subscribers from the signal.
"""
data = self.signal.instance_subscribers
if self.instance not in data:
data[self.instance] = MethodAwareWeakList()
return data[self.instance] | Can you implement a function in Python 3 that
gets the subscribers of the current instance. | As a python code expert, you are capable of creating scripts from specifications. |
Like notify allows to pass more options to the underlying
Signal. prepare_notification method. | Make a summary of the following Python 3 code
def notify_prepared(self, args=None, kwargs=None, **opts):
if args is None:
args = ()
if kwargs is None:
kwargs = {}
loop = kwargs.pop('loop', self.loop)
return self.signal.prepare_notification(
subscribers... | As a Python code analyst, you investigate and solve complex coding mysteries |
Add a function or a method to the set of related objects. | Make a summary of the following Python 3 code
def connect(self, cback, subscribers=None, instance=None):
if subscribers is None:
subscribers = self.subscribers
# wrapper
if self._fconnect is not None:
def _connect(cback):
self._connect(subscribers, cback)
... | As a python code expert, you are capable of creating scripts from specifications. |
def disconnect(self, cback, subscribers=None, instance=None):
"""Remove a previously added function or method from the set of the
signal's handlers.
:param cback: the callback (or *handler*) to be added to the set
:returns: ``None`` or the value returned by the corresponding wrapper
... | Write a Python 3 script for
removing a previously added function or method from the set of signal s handlers. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Calls the external_signaller s publish_signal method to publish the internal event system. | Can you tell what is the following Python 3 function doing
def ext_publish(self, instance, loop, *args, **kwargs):
if self.external_signaller is not None:
# Assumes that the loop is managed by the external handler
return self.external_signaller.publish_signal(self, instance, loop,
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Prepares an Executor for notifications. | Can you tell what is the following Python 3 function doing
def prepare_notification(self, *, subscribers=None, instance=None,
loop=None, notify_external=True):
"""Sets up a and configures an `~.utils.Executor`:class: instance."""
# merge callbacks added to the class level wi... | As a Python code composer, you craft elegant and concise scripts. |
def configure_logging(
filename=None,
filemode="a",
datefmt=FMT_DATE,
fmt=FMT,
stdout_fmt=FMT_STDOUT,
level=logging.DEBUG,
stdout_level=logging.WARNING,
initial_file_message="",
max_size=1048576,
rotations_number=5,
remove_handlers=True,
):
"""Configure logging module.
... | Implement a function in Python 3 to
configure the logging module. | You are a Python code analyst, evaluating scripts for potential improvements. |
Create a new cluster tree based on the provided list of users and their uid. | Make a summary of the following Python 3 code
def create_plan(existing_users=None, proposed_users=None, purge_undefined=None, protected_users=None,
allow_non_unique_id=None, manage_home=True, manage_keys=True):
"""Determine what changes are required.
args:
existing_users (Users): List o... | You are a Python code analyst, evaluating scripts for potential improvements. |
Executes the command line for each user in the specified plan. | Can you generate a brief explanation for the following Python 3 code
def execute_plan(plan=None):
execution_result = list()
for task in plan:
action = task['action']
if action == 'delete':
command = generate_delete_user_command(username=task.get('username'), manage_home=task['manage_... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
**kwargs):
"""
Reads a value of ``variable_path`` from environment.
If ``coerce_type``... | Implement a Python 3 function for
reading a value of variable_path from environment and returns it. | As a Python code composer, you craft elegant and concise scripts. |
def unzip(archive, destination, filenames=None):
"""Unzip a zip archive into destination directory.
It unzips either the whole archive or specific file(s) from the archive.
Usage:
>>> output = os.path.join(os.getcwd(), 'output')
>>> # Archive can be an instance of a ZipFile class
>... | Can you implement a function in Python 3 that
unzips a zip archive into destination directory. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Recursively zip a directory and files. | Make a summary of the following Python 3 code
def mkzip(archive, items, mode="w", save_full_paths=False):
close = False
try:
if not isinstance(archive, zipfile.ZipFile):
archive = zipfile.ZipFile(archive, mode, allowZip64=True)
close = True
logger.info("mkdzip: Creating %... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def seven_zip(archive, items, self_extracting=False):
"""Create a 7z archive."""
if not isinstance(items, (list, tuple)):
items = [items]
if self_extracting:
return er(_get_sz(), "a", "-ssw", "-sfx", archive, *items)
else:
return er(_get_sz(), "a", "-ssw", archive, *items) | Implement a function in Python 3 to
create a 7z archive. | You are a Python code analyst, evaluating scripts for potential improvements. |
def ensure_caches_alive(max_retries: int = 100,
retry_timeout: int = 5,
exit_on_failure: bool = True) -> bool:
"""
Checks every cache backend alias in ``settings.CACHES`` until it becomes available. After ``max_retries``
attempts to reach any backend are faile... | Write a Python 3 function that can
ensure that all caches are available. | As a python code expert, you are capable of creating scripts from specifications. |
def ensure_databases_alive(max_retries: int = 100,
retry_timeout: int = 5,
exit_on_failure: bool = True) -> bool:
"""
Checks every database alias in ``settings.DATABASES`` until it becomes available. After ``max_retries``
attempts to reach any backend ar... | Can you create a Python 3 function that
checks all databases in settings. DATABASES and returns True if all backends are available. | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.