output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Runs Django migrate command. | Explain what the following Python 3 code does
def migrate(*argv) -> bool:
wf('Applying migrations... ', False)
execute_from_command_line(['./manage.py', 'migrate'] + list(argv))
wf('[+]\n')
return True | You are a Python code analyst, evaluating scripts for potential improvements. |
Formats a response from a WSGI app to handle any RDF graphs that are not already serialized | How would you explain what the following Python 3 function does
def output(self, output, accepts, set_http_code, set_content_type):
graph = Decorator._get_graph(output)
if graph is not None:
# decide the format
output_mimetype, output_format = self.format_selector.decide(accepts, graph.context_aware)
# re... | You are a Python code analyst, evaluating scripts for potential improvements. |
def decorate(self, app):
""" Wraps a WSGI application to return formatted RDF graphs
Uses content negotiation to serialize the graph to the client-preferred format
Passes other content through unmodified
"""
from functools import wraps
@wraps(app)
def decorated(environ, start_response):
# capt... | Write a Python 3 script for
decorating a WSGI application to return formatted RDF graphs | As a python code expert, you are capable of creating scripts from specifications. |
Detect an handler and return its wanted signal name and config. | How would you explain what the following Python 3 function does
def is_handler(cls, name, value):
signal_name = False
config = None
if callable(value) and hasattr(value, SPEC_CONTAINER_MEMBER_NAME):
spec = getattr(value, SPEC_CONTAINER_MEMBER_NAME)
if spec['kind']... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _build_instance_handler_mapping(cls, instance, handle_d):
"""For every unbound handler, get the bound version."""
res = {}
for member_name, sig_name in handle_d.items():
if sig_name in res:
sig_handlers = res[sig_name]
else:
sig_handler... | Implement a function in Python 3 to
build a mapping from member names to instance handler names. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _check_local_handlers(cls, signals, handlers, namespace, configs):
"""For every marked handler, see if there is a suitable signal. If
not, raise an error."""
for aname, sig_name in handlers.items():
# WARN: this code doesn't take in account the case where a new
# meth... | Write a Python 3 script to
check if there are any local handlers that can be used in the class. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _find_local_signals(cls, signals, namespace):
"""Add name info to every "local" (present in the body of this class)
signal and add it to the mapping. Also complete signal
initialization as member of the class by injecting its name.
"""
from . import Signal
signaller... | Create a Python 3 function to
find all local signals in the namespace. | As a Python code analyst, you investigate and solve complex coding mysteries |
Find all local handlers and add them to the handlers dict. | Explain what the following Python 3 code does
def _find_local_handlers(cls, handlers, namespace, configs):
for aname, avalue in namespace.items():
sig_name, config = cls._is_handler(aname, avalue)
if sig_name:
configs[aname] = config
handlers[aname] = sig... | You are a Python code generator, capable of creating scripts from specifications. |
Returns the class level handlers registered at class level. | How would you explain what the following Python 3 function does
def _get_class_handlers(cls, signal_name, instance):
handlers = cls._signal_handlers_sorted[signal_name]
return [getattr(instance, hname) for hname in handlers] | You are a Python code analyst, evaluating scripts for potential improvements. |
def _sort_handlers(cls, signals, handlers, configs):
"""Sort class defined handlers to give precedence to those declared at
lower level. ``config`` can contain two keys ``begin`` or ``end`` that
will further reposition the handler at the two extremes.
"""
def macro_precedence_sor... | Implement a function in Python 3 to
sort class defined handlers to give precedence to those declared at lower level. | You are a Python code generator, capable of creating scripts from specifications. |
Calculate per - instance signals and handlers. | Make a summary of the following Python 3 code
def instance_signals_and_handlers(cls, instance):
isignals = cls._signals.copy()
ihandlers = cls._build_instance_handler_mapping(
instance,
cls._signal_handlers
)
return isignals, ihandlers | You are a Python code architect, reviewing and designing scalable and efficient code |
def add(self, src):
"""
:param src: file path
:return: checksum value
"""
checksum = get_checksum(src)
filename = self.get_filename(checksum)
if not filename:
new_name = self._get_new_name()
new_realpath = self._storage_dir + '/' + new_... | Implement a Python 3 function for
adding a file to the log file. | You are a Python code generator, capable of creating scripts from specifications. |
def get_filename(self, checksum):
"""
:param checksum: checksum
:return: filename no storage base part
"""
filename = None
for _filename, metadata in self._log.items():
if metadata['checksum'] == checksum:
filename = _filename
b... | Implement a function in Python 3 to
return the filename of the current log entry with the given checksum | You are a Python code generator, capable of creating scripts from specifications. |
Retrieve a specific file from cache | Here you have a function in Python 3, explain what it does
def __retrieve(self, key):
''' Retrieve file location from cache DB
'''
with self.get_conn() as conn:
try:
c = conn.cursor()
if key is None:
c.execute("SELECT value FROM cac... | As a Python code analyst, you investigate and solve complex coding mysteries |
Insert a new key to database. | Explain what the following Python 3 code does
def __insert(self, key, value):
'''
Insert a new key to database
'''
if key in self:
getLogger().warning("Cache entry exists, cannot insert a new entry with key='{key}'".format(key=key))
return False
with self.... | As a python code expert, you are capable of creating scripts from specifications. |
Delete a file key from database | How would you explain what the following Python 3 function does
def __delete(self, key):
''' Delete file key from database
'''
with self.get_conn() as conn:
try:
c = conn.cursor()
c.execute("DELETE FROM cache_entries WHERE key = ?", (key,))
... | As a python code expert, you are capable of creating scripts from specifications. |
This method will insert internal blob data into blob table
| Can you generate a brief explanation for the following Python 3 code
def __insert_internal_blob(self, key, blob, compressed=True):
''' This method will insert blob data to blob table
'''
with self.get_conn() as conn:
conn.isolation_level = None
c = conn.cursor()
... | As a python code expert, you are capable of creating scripts from specifications. |
This method will delete the internal blob from the blob table. | Can you generate the documentation for the following Python 3 function
def __delete_internal_blob(self, key):
''' This method will insert blob data to blob table
'''
with self.get_conn() as conn:
conn.isolation_level = None
try:
c = conn.cursor()
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def __retrieve_internal_blob(self, key):
''' Retrieve file location from cache DB
'''
logger = getLogger()
with self.get_conn() as conn:
try:
c = conn.cursor()
if key is None:
c.execute("SELECT compressed, blob_data FROM blo... | Create a Python 3 function to
retrieve the internal blob from the cache. | As a python code expert, you are capable of creating scripts from specifications. |
Retrieve a blob in binary format or string format. | Can you generate a brief explanation for the following Python 3 code
def retrieve_blob(self, key, encoding=None):
''' Retrieve blob in binary format (or string format if encoding is provided) '''
blob_key = self.__retrieve(key)
if blob_key is None:
return None
if not blob_key... | As a Python code composer, you craft elegant and concise scripts. |
def summarize(self, rows):
"""Return summary rows for `rows`.
Parameters
----------
rows : list of dicts
Normalized rows to summarize.
Returns
-------
A list of summary rows. Each row is a tuple where the first item is
the data and the secon... | Can you write a function in Python 3 where it
returns a list of summary rows for rows. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _init(self, style, streamer, processors=None):
"""Do writer-specific setup.
Parameters
----------
style : dict
Style, as passed to __init__.
streamer : interface.Stream
A stream interface that takes __init__'s `stream` and `interactive`
ar... | Create a Python 3 function to
do basic initialization of the object. | You are a Python code generator, capable of creating scripts from specifications. |
A list of unique IDs used to identify a row. | Explain what the following Python 3 code does
def ids(self):
if self._ids is None:
if self._columns:
if isinstance(self._columns, OrderedDict):
return [list(self._columns.keys())[0]]
return [self._columns[0]]
else:
return self._... | You are a Python code architect, reviewing and designing scalable and efficient code |
def wait(self):
"""Wait for asynchronous calls to return.
"""
if self._pool is None:
return
self._pool.close()
self._pool.join() | How would you code a function in Python 3 to
wait for asynchronous calls to return. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _write_lock(self):
"""Acquire and release the lock around output calls.
This should allow multiple threads or processes to write output
reliably. Code that modifies the `_content` attribute should also do
so within this context.
"""
if self._lock:
lgr.de... | Implement a function in Python 3 to
acquire and release the lock around output calls. This should allow multiple threads or processes to write output reliably. Code that modifies the `_content` attribute should also do so within this context. | You are a Python code architect, reviewing and designing scalable and efficient code |
Start running callables asynchronously. | Can you tell what is the following Python 3 function doing
def _start_callables(self, row, callables):
id_vals = {c: row[c] for c in self.ids}
def callback(tab, cols, result):
if isinstance(result, Mapping):
pass
elif isinstance(result, tuple):
re... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get a listing of all non - system schemas that exist in the database. | Here you have a function in Python 3, explain what it does
def schemas(self):
sql = """SELECT schema_name FROM information_schema.schemata
ORDER BY schema_name"""
schemas = self.query(sql).fetchall()
return [s[0] for s in schemas if s[0][:3] != "pg_"] | As a python code expert, you are capable of creating scripts from specifications. |
Get a listing of all tables in the database with schema
prefixes | Can you tell what is the following Python 3 function doing
def tables(self):
if self.schema:
return self.tables_in_schema(self.schema)
else:
tables = []
for schema in self.schemas:
tables = tables + [
schema + "." + t for t in self.... | As a Python code composer, you craft elegant and concise scripts. |
Check if the table name is obviously invalid. | Can you tell what is the following Python 3 function doing
def _valid_table_name(self, table):
if table is None or not len(table.strip()):
raise ValueError("Invalid table name: %r" % table)
return table.strip() | You are a Python code analyst, evaluating scripts for potential improvements. |
def build_query(self, sql, lookup):
"""
Modify table and field name variables in a sql string with a dict.
This seems to be discouraged by psycopg2 docs but it makes small
adjustments to large sql strings much easier, making prepped queries
much more versatile.
USAGE
... | Write a Python 3 function that can
build the sql string for the select statement | As a python code expert, you are capable of creating scripts from specifications. |
Get a listing of all tables in given schema | Can you generate the documentation for the following Python 3 function
def tables_in_schema(self, schema):
sql = """SELECT table_name
FROM information_schema.tables
WHERE table_schema = %s"""
return [t[0] for t in self.query(sql, (schema,)).fetchall()] | You are a Python code analyst, evaluating scripts for potential improvements. |
def parse_table_name(self, table):
"""Parse schema qualified table name
"""
if "." in table:
schema, table = table.split(".")
else:
schema = None
return (schema, table) | Create a Python 3 function to
parse schema qualified table name. | You are a Python code analyst, evaluating scripts for potential improvements. |
Loads a table. Returns None if the table does not exist in db
. | Can you generate the documentation for the following Python 3 function
def load_table(self, table):
table = self._valid_table_name(table)
schema, table = self.parse_table_name(table)
if not schema:
schema = self.schema
tables = self.tables
else:
tables... | You are a Python code generator, capable of creating scripts from specifications. |
Return the query string with parameters added
| Here you have a function in Python 3, explain what it does
def mogrify(self, sql, params):
conn = self.engine.raw_connection()
cursor = conn.cursor()
return cursor.mogrify(sql, params) | As a Python code analyst, you investigate and solve complex coding mysteries |
Just a pointer to engine. execute
| Can you tell what is the following Python 3 function doing
def execute(self, sql, params=None):
# wrap in a transaction to ensure things are committed
# https://github.com/smnorris/pgdata/issues/3
with self.engine.begin() as conn:
result = conn.execute(sql, params)
return res... | You are a Python code generator, capable of creating scripts from specifications. |
Grab just one record
| Can you tell what is the following Python 3 function doing
def query_one(self, sql, params=None):
r = self.engine.execute(sql, params)
return r.fetchone() | You are a Python code generator, capable of creating scripts from specifications. |
Create specified schema if it does not already exist. | Here you have a function in Python 3, explain what it does
def create_schema(self, schema):
if schema not in self.schemas:
sql = "CREATE SCHEMA " + schema
self.execute(sql) | As a python code expert, you are capable of creating scripts from specifications. |
Drop specified schema from the database. | Here you have a function in Python 3, explain what it does
def drop_schema(self, schema, cascade=False):
if schema in self.schemas:
sql = "DROP SCHEMA " + schema
if cascade:
sql = sql + " CASCADE"
self.execute(sql) | You are a Python code generator, capable of creating scripts from specifications. |
def create_table(self, table, columns):
"""Creates a table
"""
schema, table = self.parse_table_name(table)
table = self._valid_table_name(table)
if not schema:
schema = self.schema
if table in self.tables:
return Table(self, schema, table)
... | How would you implement a function in Python 3 that
creates a table with the given name and columns. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def ogr2pg(
self,
in_file,
in_layer=None,
out_layer=None,
schema="public",
s_srs=None,
t_srs="EPSG:3005",
sql=None,
dim=2,
cmd_only=False,
index=True
):
"""
Load a layer to provided pgdata database connection usi... | Create a Python 3 function to
load a record from a OGR2OGR database connection using the OGR2OGR command line interface. | You are a Python code architect, reviewing and designing scalable and efficient code |
def pg2ogr(
self,
sql,
driver,
outfile,
outlayer=None,
column_remap=None,
s_srs="EPSG:3005",
t_srs=None,
geom_type=None,
append=False,
):
"""
A wrapper around ogr2ogr, for quickly dumping a postgis query to file.
... | Implement a function in Python 3 to
wrap around ogr2ogr to convert a postgis query to an OGR file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def setup_logging(filename, log_dir=None, force_setup=False):
''' Try to load logging configuration from a file. Set level to INFO if failed.
'''
if not force_setup and ChirpCLI.SETUP_COMPLETED:
logging.debug("Master logging has been setup. This call will be ignored.")
return
if log_dir ... | Write a Python 3 script for
loading logging configuration from a file. Set level to INFO if failed. | As a python code expert, you are capable of creating scripts from specifications. |
Override root logger s level | Can you tell what is the following Python 3 function doing
def config_logging(args):
''' Override root logger's level '''
if args.quiet:
logging.getLogger().setLevel(logging.CRITICAL)
elif args.verbose:
logging.getLogger().setLevel(logging.DEBUG) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add_task(self, task, func=None, **kwargs):
''' Add a task parser '''
if not self.__tasks:
raise Exception("Tasks subparsers is disabled")
if 'help' not in kwargs:
if func.__doc__:
kwargs['help'] = func.__doc__
task_parser = self.__tasks.add_par... | Create a Python 3 function to
add a task parser | You are a Python code analyst, evaluating scripts for potential improvements. |
Add verbose & quiet options to the parser. | Can you generate a brief explanation for the following Python 3 code
def add_vq(self, parser):
''' Add verbose & quiet options '''
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_tr... | You are a Python code generator, capable of creating scripts from specifications. |
Enable - V to show version information | Explain what the following Python 3 code does
def add_version_func(self, show_version):
''' Enable --version and -V to show version information '''
if callable(show_version):
self.__show_version_func = show_version
else:
self.__show_version_func = lambda cli, args: print(... | As a Python code composer, you craft elegant and concise scripts. |
def header(*msg, level='h1', separator=" ", print_out=print):
''' Print header block in text mode
'''
out_string = separator.join(str(x) for x in msg)
if level == 'h0':
# box_len = 80 if len(msg) < 80 else len(msg)
box_len = 80
print_out('+' + '-' * (box_len + 2))
print_o... | Write a Python 3 script to
print a header block in text mode | As a Python code composer, you craft elegant and concise scripts. |
def fetch(self, value_obj=None):
''' Fetch the next two values '''
val = None
try:
val = next(self.__iterable)
except StopIteration:
return None
if value_obj is None:
value_obj = Value(value=val)
else:
value_obj.value = val
... | Create a Python 3 function for
fetching the next two values from the list. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a list of the report items in order of priority. | Here you have a function in Python 3, explain what it does
def get_report_order(self):
''' Keys are sorted based on report order (i.e. some keys to be shown first)
Related: see sorted_by_count
'''
order_list = []
for x in self.__priority:
order_list.append([x, sel... | You are a Python code analyst, evaluating scripts for potential improvements. |
def content(self):
''' Return report content as a string if mode == STRINGIO else an empty string '''
if isinstance(self.__report_file, io.StringIO):
return self.__report_file.getvalue()
else:
return '' | Write a Python 3 script to
return report content as a string if mode == STRINGIO else an empty string | As a python code expert, you are capable of creating scripts from specifications. |
Format table to print out
| Make a summary of the following Python 3 code
def format(self):
''' Format table to print out
'''
self.max_lengths = []
for row in self.rows:
if len(self.max_lengths) < len(row):
self.max_lengths += [0] * (len(row) - len(self.max_lengths))
for idx,... | As a python code expert, you are capable of creating scripts from specifications. |
def getfullfilename(file_path):
''' Get full filename (with extension)
'''
warnings.warn("getfullfilename() is deprecated and will be removed in near future. Use chirptext.io.write_file() instead", DeprecationWarning)
if file_path:
return os.path.basename(file_path)
e... | Implement a function in Python 3 to
get full filename of the chirptext. io file. | You are a Python code generator, capable of creating scripts from specifications. |
def replace_ext(file_path, ext):
''' Change extension of a file_path to something else (provide None to remove) '''
if not file_path:
raise Exception("File path cannot be empty")
dirname = os.path.dirname(file_path)
filename = FileHelper.getfilename(file_path)
if ext:... | Can you write a function in Python 3 where it
changes extension of a file_path to something else | As a Python code composer, you craft elegant and concise scripts. |
def replace_name(file_path, new_name):
''' Change the file name in a path but keep the extension '''
if not file_path:
raise Exception("File path cannot be empty")
elif not new_name:
raise Exception("New name cannot be empty")
dirname = os.path.dirname(file_path)
... | Create a Python 3 function to
change the file name in a path but keep the extension | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_child_folders(path):
''' Get all child folders of a folder '''
path = FileHelper.abspath(path)
return [dirname for dirname in os.listdir(path) if os.path.isdir(os.path.join(path, dirname))] | Can you create a Python 3 function that
gets all child folders of a folder | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_child_files(path):
''' Get all child files of a folder '''
path = FileHelper.abspath(path)
return [filename for filename in os.listdir(path) if os.path.isfile(os.path.join(path, filename))] | Create a Python 3 function for
getting all child files of a folder | As a Python code translator, you convert algorithms and pseudocode into Python. |
Delete a file from the cache. | Here you have a function in Python 3, explain what it does
def remove_file(filepath):
''' Delete a file '''
try:
os.remove(os.path.abspath(os.path.expanduser(filepath)))
except OSError as e:
if e.errno != errno.ENOENT:
raise | You are a Python code generator, capable of creating scripts from specifications. |
Add a potential config file pattern | Make a summary of the following Python 3 code
def add_potential(self, *patterns):
''' Add a potential config file pattern '''
for ptn in patterns:
self.__potential.extend(self._ptn2fn(ptn)) | You are a Python code architect, reviewing and designing scalable and efficient code |
Read config automatically if required | Here you have a function in Python 3, explain what it does
def config(self):
''' Read config automatically if required '''
if self.__config is None:
config_path = self.locate_config()
if config_path:
self.__config = self.read_file(config_path)
self... | You are a Python code generator, capable of creating scripts from specifications. |
Read a configuration file and return a configuration data dict | Can you tell what is the following Python 3 function doing
def read_file(self, file_path):
''' Read a configuration file and return configuration data '''
getLogger().info("Loading app config from {} file: {}".format(self.__mode, file_path))
if self.__mode == AppConfig.JSON:
return j... | As a Python code composer, you craft elegant and concise scripts. |
def load(self, file_path):
''' Load configuration from a specific file '''
self.clear()
self.__config = self.read_file(file_path) | Write a Python 3 function that can
load configuration from a specific file | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_processes(sort_by_name=True):
"""Retrieve a list of processes sorted by name.
Args:
sort_by_name (bool): Sort the list by name or by process ID's.
Returns:
list of (int, str) or list of (int, str, str): List of process id,
process name and optional cmdline tuple... | Write a Python 3 script to
return a list of processes sorted by name or by process ID s. | As a python code expert, you are capable of creating scripts from specifications. |
Find a process by name or by argument in command line. | Here you have a function in Python 3, explain what it does
def find(name, arg=None):
for p in get_processes():
if p.name.lower().find(name.lower()) != -1:
if arg is not None:
for a in p.cmdline or []:
if a.lower().find(arg.lower()) != -1:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def execute(command, *args, **kwargs):
"""Execute a command with arguments and wait for output.
Arguments should not be quoted!
Keyword arguments:
env (dict): Dictionary of additional environment variables.
wait (bool): Wait for the process to finish.
Example::
>>>... | Write a Python 3 function for
executing a command with arguments and wait for output. | You are a Python code generator, capable of creating scripts from specifications. |
def execute_and_report(command, *args, **kwargs):
"""Execute a command with arguments and wait for output.
If execution was successful function will return True,
if not, it will log the output using standard logging and return False.
"""
logging.info("Execute: %s %s" % (command, " ".join(args... | Write a Python 3 function that can
execute a command and reports the output to the console. | You are a Python code generator, capable of creating scripts from specifications. |
def read_authorized_keys(username=None):
"""Read public keys from specified user's authorized_keys file.
args:
username (str): username.
returns:
list: Authorised keys for the specified user.
"""
authorized_keys_path = '{0}/.ssh/authorized_keys'.format(os.path.expanduser('~{0}'.for... | How would you code a function in Python 3 to
read public keys from specified user s authorized_keys file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def write_authorized_keys(user=None):
"""Write public keys back to authorized_keys file. Create keys directory if it doesn't already exist.
args:
user (User): Instance of User containing keys.
returns:
list: Authorised keys for the specified user.
"""
authorized_keys = list()
a... | Create a Python 3 function for
writing public keys to authorized_keys file. Create keys directory if it doesn t exist. | As a Python code composer, you craft elegant and concise scripts. |
Return a base64 encoding of the public key. | Given the following Python 3 function, write the documentation
def b64encoded(self):
if self._b64encoded:
return text_type(self._b64encoded).strip("\r\n")
else:
return base64encode(self.raw) | As a python code expert, you are capable of creating scripts from specifications. |
Return raw key.
returns:
str: raw key | How would you explain what the following Python 3 function does
def raw(self):
if self._raw:
return text_type(self._raw).strip("\r\n")
else:
return text_type(base64decode(self._b64encoded)).strip("\r\n") | As a Python code analyst, you investigate and solve complex coding mysteries |
def inner_parser(self) -> BaseParser:
"""
Prepares inner config parser for config stored at ``endpoint``.
:return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser`
:raises config.exceptions.KVStorageKeyDoestNotExist: if specified ``endpoint`` does not exis... | Create a Python 3 function to
return an instance of self. inner_parser_class with the config stored at self. endpoint. | 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):
"""
Reads a value of ``variable_path`` from consul kv storage.
:param varia... | Create a Python 3 function for
reading a value from consul kv storage. | As a Python code composer, you craft elegant and concise scripts. |
def add_format(mimetype, format, requires_context=False):
""" Registers a new format to be used in a graph's serialize call
If you've installed an rdflib serializer plugin, use this
to add it to the content negotiation system
Set requires_context=True if this format requires a context-aware graph
"""
... | How would you implement a function in Python 3 that
adds a format to be used in a graph s serialize call | You are a Python code architect, reviewing and designing scalable and efficient code |
Adds a format to be used in a graph s serialize | Explain what the following Python 3 code does
def add_format(self, mimetype, format, requires_context=False):
self.formats[mimetype] = format
if not requires_context:
self.ctxless_mimetypes.append(mimetype)
self.all_mimetypes.append(mimetype) | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_default_mimetype(self):
""" Returns the default mimetype """
mimetype = self.default_mimetype
if mimetype is None: # class inherits from module default
mimetype = DEFAULT_MIMETYPE
if mimetype is None: # module is set to None?
mimetype = 'application/rdf+xml'
return mimetype | Implement a Python 3 function for
returning the default mimetype | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the mimetype if the client sends a wildcard mimetype | Explain what the following Python 3 code does
def get_wildcard_mimetype(self):
mimetype = self.wildcard_mimetype
if mimetype is None: # class inherits from module default
mimetype = WILDCARD_MIMETYPE
if mimetype is None: # module is set to None?
mimetype = 'application/rdf+xml'
return mimetype | As a Python code analyst, you investigate and solve complex coding mysteries |
def decide_mimetype(self, accepts, context_aware = False):
""" Returns what mimetype the client wants to receive
Parses the given Accept header and returns the best one that
we know how to output
An empty Accept will default to application/rdf+xml
An Accept with */* use rdf+xml unless a better... | Write a Python 3 function that can
return what mimetype the client wants to receive | As a python code expert, you are capable of creating scripts from specifications. |
Get the serialization format for the given mimetype | Can you generate a brief explanation for the following Python 3 code
def get_serialize_format(self, mimetype):
format = self.formats.get(mimetype, None)
if format is None:
format = formats.get(mimetype, None)
return format | You are a Python code architect, reviewing and designing scalable and efficient code |
def decide(self, accepts, context_aware=False):
""" Returns what (mimetype,format) the client wants to receive
Parses the given Accept header and picks the best one that
we know how to output
Returns (mimetype, format)
An empty Accept will default to rdf+xml
An Accept with */* use rdf+xm... | Write a Python 3 script for
deciding what mimetype to serialize | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns whether this client s Accept header indicates
that the client wants to receive RDF
| Make a summary of the following Python 3 code
def wants_rdf(self, accepts):
mimetype = mimeparse.best_match(all_mimetypes + self.all_mimetypes + [WILDCARD], accepts)
return mimetype and mimetype != WILDCARD | As a Python code composer, you craft elegant and concise scripts. |
Send an HTTP request to the specified URL. | Can you generate a brief explanation for the following Python 3 code
async def send_http(session, method, url, *,
retries=1,
interval=1,
backoff=2,
http_status_codes_to_retry=HTTP_STATUS_CODES_TO_RETRY,
fn=lambda x:x,
... | As a Python code composer, you craft elegant and concise scripts. |
Generates the sitemap file and the stylesheet file and puts them into the content dir. | Can you tell what is the following Python 3 function doing
def generate_output(self, writer):
# write xml stylesheet
with codecs_open(os.path.join(os.path.dirname(__file__), 'sitemap-stylesheet.xsl'), 'r', encoding='utf-8') as fd_origin:
with codecs_open(os.path.join(self.path_output, 'sitem... | You are a Python code generator, capable of creating scripts from specifications. |
Returns the URL for the given DIRECT_TEMPLATE name. | Given the following Python 3 function, write the documentation
def __get_direct_template_url(self, name):
url = self.pelican_settings.get('{}_SAVE_AS'.format(name.upper()))
if url is None:
url = self.settings.get('{}_URL'.format(name.upper()), '{}.html'.format(name))
return urljoin(s... | As a Python code composer, you craft elegant and concise scripts. |
Processes the list of url wrapper elements into HTML. | How would you explain what the following Python 3 function does
def __process_url_wrapper_elements(self, elements):
urls = ''
for url_wrapper, articles in elements:
urls += self.__create_url_node_for_content(
url_wrapper,
'others',
url=urljoin(... | As a Python code composer, you craft elegant and concise scripts. |
def __create_url_node_for_content(self, content, content_type, url=None, modification_time=None):
"""
Creates the required <url> node for the sitemap xml.
:param content: the content class to handle
:type content: pelican.contents.Content | None
:param content_type: the type of t... | Write a Python 3 script for
creating the required url node for the given content. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_missing_commands(_platform):
"""Check I can identify the necessary commands for managing users."""
missing = list()
if _platform in ('Linux', 'OpenBSD'):
if not LINUX_CMD_USERADD:
missing.append('useradd')
if not LINUX_CMD_USERMOD:
missing.append('usermod')
... | Can you implement a function in Python 3 that
checks I can identify the necessary commands for managing users. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def execute_command(command=None):
"""Execute a command and return the stdout and stderr."""
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stdin = process.communicate()
process.wait()
return (stdout, stdin), process.returncode | Can you implement a function in Python 3 that
executes a command and return the stdout and stderr. | You are a Python code generator, capable of creating scripts from specifications. |
def base64encode(_input=None):
"""Return base64 encoded representation of a string."""
if PY2: # pragma: no cover
return base64.b64encode(_input)
elif PY3: # pragma: no cover
if isinstance(_input, bytes):
return base64.b64encode(_input).decode('UTF-8')
elif isinstance(_... | Write a Python 3 script to
return base64 encoded representation of a string. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Take a base64 encoded string and return the decoded string. | Can you generate a brief explanation for the following Python 3 code
def base64decode(_input=None):
missing_padding = 4 - len(_input) % 4
if missing_padding:
_input += '=' * missing_padding
if PY2: # pragma: no cover
return base64.decodestring(_input)
elif PY3: # pragma: no cover
... | As a Python code composer, you craft elegant and concise scripts. |
def read_sudoers():
""" Read the sudoers entry for the specified user.
args:
username (str): username.
returns:`r
str: sudoers entry for the specified user.
"""
sudoers_path = '/etc/sudoers'
rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH)
tmp_sudoers_path = '/tmp/s... | Implement a Python 3 function for
reading the sudoers entry for the specified user. | You are a Python code architect, reviewing and designing scalable and efficient code |
def write_sudoers_entry(username=None, sudoers_entry=None):
"""Write sudoers entry.
args:
user (User): Instance of User containing sudoers entry.
returns:
str: sudoers entry for the specified user.
"""
sudoers_path = '/etc/sudoers'
rnd_chars = random_string(length=RANDOM_FILE_... | Write a Python 3 function that can
write sudoers entry for the specified user. | As a python code expert, you are capable of creating scripts from specifications. |
def get_sudoers_entry(username=None, sudoers_entries=None):
""" Find the sudoers entry in the sudoers file for the specified user.
args:
username (str): username.
sudoers_entries (list): list of lines from the sudoers file.
returns:`r
str: sudoers entry for the specified user.
... | How would you implement a function in Python 3 that
finds the sudoers entry for the specified user. | As a python code expert, you are capable of creating scripts from specifications. |
Creates a superuser from a specified dict or object bundle located at user_config_path. | Can you tell what is the following Python 3 function doing
def create_admin(user_config_path: str = 'CONFIG.superuser') -> bool:
from django.conf import settings
wf('Creating superuser... ', False)
username, email, password = [
dot_path(settings, '{0}.{1}'.format(user_config_path, 'username')),
... | As a python code expert, you are capable of creating scripts from specifications. |
Runs gunicorn with a specified config module. | Given the following Python 3 function, write the documentation
def run_gunicorn(application: WSGIHandler, gunicorn_module_name: str = 'gunicorn_prod'):
from gunicorn.app.base import Application
class DjangoApplication(Application):
def init(self, parser, opts, args):
cfg = self.get_config_f... | You are a Python code generator, capable of creating scripts from specifications. |
Set the console color. | How would you explain what the following Python 3 function does
def set_color(
fg=Color.normal,
bg=Color.normal,
fg_dark=False,
bg_dark=False,
underlined=False,
):
"""Set the console color.
>>> set_color(Color.red, Color.blue)
>>> set_color('red', 'blue')
>>> set_color() ... | As a python code expert, you are capable of creating scripts from specifications. |
Print string in to stdout using colored font. | Explain what the following Python 3 code does
def cprint(
text,
fg=Color.normal,
bg=Color.normal,
fg_dark=False,
bg_dark=False,
underlined=False,
parse=False,
):
"""Print string in to stdout using colored font.
See L{set_color} for more details about colors.
Args:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Print a single line to console with ability to colorize parts of it. | Make a summary of the following Python 3 code
def _colorize_single_line(line, regexp, color_def):
match = regexp.match(line)
groupdict = match.groupdict()
groups = match.groups()
if not groupdict:
# no named groups, just colorize whole line
color = color_def[0]
dark = colo... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Clear last N lines of terminal output. | Can you generate the documentation for the following Python 3 function
def clear_last_lines(self, n):
self.term.stream.write(
self.term.move_up * n + self.term.clear_eos)
self.term.stream.flush() | You are a Python code analyst, evaluating scripts for potential improvements. |
Move back N lines and overwrite line with text. | Given the following Python 3 function, write the documentation
def overwrite_line(self, n, text):
with self._moveback(n):
self.term.stream.write(text) | As a Python code composer, you craft elegant and concise scripts. |
Move back N lines in terminal. | Given the following Python 3 function, write the documentation
def move_to(self, n):
self.term.stream.write(self.term.move_up * n) | You are a Python code generator, capable of creating scripts from specifications. |
Reads a value from all of the parsers that contain a specified path. | Given the following Python 3 function, write the documentation
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,
required: bool = False,
**kwargs):
... | 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.