output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def search_reports(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
tags=None,
excluded_tags=None):
"""
Uses the |search_reports_page| method to create a generator th... | Can you write a function in Python 3 where it
searches for reports in the user s enclave. | As a python code expert, you are capable of creating scripts from specifications. |
Coerce a value to boolean. | Explain what the following Python 3 code does
def parse_boolean(value):
if value is None:
return None
if isinstance(value, bool):
return value
if isinstance(value, string_types):
value = value.lower()
if value == 'false':
return False
if value == 'true'... | You are a Python code generator, capable of creating scripts from specifications. |
Create a configuration dictionary from a config file. | Can you tell what is the following Python 3 function doing
def config_from_file(config_file_path, config_role):
# read config file depending on filetype, parse into dictionary
ext = os.path.splitext(config_file_path)[-1]
if ext in ['.conf', '.ini']:
config_parser = configparser.RawC... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the version number of the API. | Make a summary of the following Python 3 code
def get_version(self):
result = self._client.get("version").content
if isinstance(result, bytes):
result = result.decode('utf-8')
return result.strip('\n') | You are a Python code generator, capable of creating scripts from specifications. |
def get_user_enclaves(self):
"""
Gets the list of enclaves that the user has access to.
:return: A list of |EnclavePermissions| objects, each representing an enclave and whether the requesting user
has read, create, and update access to it.
"""
resp = self._client.g... | Can you create a Python 3 function that
gets the list of user enclaves that the user has access to. | You are a Python code generator, capable of creating scripts from specifications. |
Gets the request quotas for the user s company. | Can you tell what is the following Python 3 function doing
def get_request_quotas(self):
resp = self._client.get("request-quotas")
return [RequestQuota.from_dict(quota) for quota in resp.json()] | You are a Python code architect, reviewing and designing scalable and efficient code |
def configure_logging():
"""
Initialize logging configuration to defaults. If the environment variable DISABLE_TRUSTAR_LOGGING is set to true,
this will be ignored.
"""
if not parse_boolean(os.environ.get('DISABLE_TRUSTAR_LOGGING')):
# configure
dictConfig(DEFAULT_LOGGING_CONFIG)
... | Can you create a Python 3 function that
initializes logging configuration to defaults. | As a python code expert, you are capable of creating scripts from specifications. |
Create a enclave object from a dictionary. | Here you have a function in Python 3, explain what it does
def from_dict(cls, enclave):
return Enclave(id=enclave.get('id'),
name=enclave.get('name'),
type=EnclaveType.from_string(enclave.get('type'))) | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a dictionary representation of the object. | Can you generate the documentation for the following Python 3 function
def to_dict(self, remove_nones=False):
if remove_nones:
return super().to_dict(remove_nones=True)
return {
'id': self.id,
'name': self.name,
'type': self.type
} | As a Python code composer, you craft elegant and concise scripts. |
Create a enclave object from a dictionary. | Can you generate the documentation for the following Python 3 function
def from_dict(cls, d):
enclave = super(cls, EnclavePermissions).from_dict(d)
enclave_permissions = cls.from_enclave(enclave)
enclave_permissions.read = d.get('read')
enclave_permissions.create = d.get('create')
... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a dictionary representation of the enclave. | Can you tell what is the following Python 3 function doing
def to_dict(self, remove_nones=False):
d = super().to_dict(remove_nones=remove_nones)
d.update({
'read': self.read,
'create': self.create,
'update': self.update
})
return d | As a python code expert, you are capable of creating scripts from specifications. |
Create an |EnclavePermissions| object from an |Enclave| object. | Can you generate a brief explanation for the following Python 3 code
def from_enclave(cls, enclave):
return EnclavePermissions(id=enclave.id,
name=enclave.name,
type=enclave.type) | As a Python code composer, you craft elegant and concise scripts. |
def get_enclave_tags(self, report_id, id_type=None):
"""
Retrieves all enclave tags present in a specific report.
:param report_id: the ID of the report
:param id_type: indicates whether the ID internal or an external ID provided by the user
:return: A list of |Tag| objects.
... | Can you write a function in Python 3 where it
retrieves all enclave tags present in a specific report. | You are a Python code generator, capable of creating scripts from specifications. |
def add_enclave_tag(self, report_id, name, enclave_id, id_type=None):
"""
Adds a tag to a specific report, for a specific enclave.
:param report_id: The ID of the report
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will be added... | Write a Python 3 script for
adding a tag to a specific report for a specific enclave. | As a Python code composer, you craft elegant and concise scripts. |
Deletes a tag from a specific report in a specific enclave. | Can you tell what is the following Python 3 function doing
def delete_enclave_tag(self, report_id, tag_id, id_type=None):
params = {
'idType': id_type
}
self._client.delete("reports/%s/tags/%s" % (report_id, tag_id), params=params) | You are a Python code analyst, evaluating scripts for potential improvements. |
Retrieves all tags present in the given enclaves. | Can you generate a brief explanation for the following Python 3 code
def get_all_enclave_tags(self, enclave_ids=None):
params = {'enclaveIds': enclave_ids}
resp = self._client.get("reports/tags", params=params)
return [Tag.from_dict(indicator) for indicator in resp.json()] | As a Python code analyst, you investigate and solve complex coding mysteries |
Adds a tag to a specific indicator for a specific enclave. | Can you generate the documentation for the following Python 3 function
def add_indicator_tag(self, indicator_value, name, enclave_id):
data = {
'value': indicator_value,
'tag': {
'name': name,
'enclaveId': enclave_id
}
}
resp ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Deletes a tag from an indicator in a specific enclave. | Can you generate the documentation for the following Python 3 function
def delete_indicator_tag(self, indicator_value, tag_id):
params = {
'value': indicator_value
}
self._client.delete("indicators/tags/%s" % tag_id, params=params) | You are a Python code architect, reviewing and designing scalable and efficient code |
def from_dict(cls, tag):
"""
Create a tag object from a dictionary. This method is intended for internal use, to construct a
:class:`Tag` object from the body of a response json. It expects the keys of the dictionary to match those
of the json that would be found in a response to an AP... | Can you write a function in Python 3 where it
creates a Tag object from a dictionary. | As a python code expert, you are capable of creating scripts from specifications. |
Creates a dictionary representation of the tag. | Given the following Python 3 function, write the documentation
def to_dict(self, remove_nones=False):
if remove_nones:
d = super().to_dict(remove_nones=True)
else:
d = {
'name': self.name,
'id': self.id,
'enclaveId': self.enclave_i... | You are a Python code generator, capable of creating scripts from specifications. |
def infer_delimiter(filename, comment_char="#", n_lines=3):
"""
Given a file which contains data separated by one of the following:
- commas
- tabs
- spaces
Return the most likely separator by sniffing the first few lines
of the file's contents.
"""
lines = []
with op... | Write a Python 3 script to
infer the most likely delimiter from a file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Checks that all required columns are present in the given dataframe. | Here you have a function in Python 3, explain what it does
def check_required_columns(df, filename, required_columns):
available_columns = set(df.columns)
for column_name in required_columns:
if column_name not in available_columns:
raise ValueError("FPKM tracking file %s missing column '%s'... | You are a Python code generator, capable of creating scripts from specifications. |
Generate the MolecularViewer topology from the mdtraj. Trajectory object. | Can you tell what is the following Python 3 function doing
def topology_mdtraj(traj):
'''Generate topology spec for the MolecularViewer from mdtraj.
:param mdtraj.Trajectory traj: the trajectory
:return: A chemview-compatible dictionary corresponding to the topology defined in mdtraj.
'''
import m... | You are a Python code architect, reviewing and designing scalable and efficient code |
def encode_numpy(array):
'''Encode a numpy array as a base64 encoded string, to be JSON serialized.
:return: a dictionary containing the fields:
- *data*: the base64 string
- *type*: the array type
- *shape*: the array shape
'''
return {'data' : base64.... | Write a Python 3 function that can
encode a numpy array as a base64 encoded string to be JSON serialized. | As a Python code analyst, you investigate and solve complex coding mysteries |
def load_cufflinks_dataframe(
filename,
id_column=ID_COLUMN,
fpkm_column=FPKM_COLUMN,
status_column=STATUS_COLUMN,
locus_column=LOCUS_COLUMN,
gene_names_column=GENE_NAMES_COLUMN,
drop_failed=True,
drop_lowdata=False,
drop_hidata=True,
repla... | Can you write a function in Python 3 where it
loads a Cufflinks tracking file and returns a DataFrame containing the FPKM data. | You are a Python code architect, reviewing and designing scalable and efficient code |
def load_cufflinks_dict(*args, **kwargs):
"""
Returns dictionary mapping feature identifier (either transcript or gene ID)
to a DataFrame row with fields:
id : str
novel : bool
fpkm : float
chr : str
start : int
end : int
gene_names : str list
"""
... | Can you write a function in Python 3 where it
loads a Cufflinks table into a dictionary. | You are a Python code architect, reviewing and designing scalable and efficient code |
Load a Cufflinks FPKM expression value dictionary. | Here you have a function in Python 3, explain what it does
def load_cufflinks_fpkm_dict(*args, **kwargs):
return {
row.id: row.fpkm
for (_, row)
in load_cufflinks_dataframe(*args, **kwargs).iterrows()
} | You are a Python code analyst, evaluating scripts for potential improvements. |
Enable IPython notebook widgets to be displayed. | Can you tell what is the following Python 3 function doing
def enable_notebook(verbose=0):
libs = ['objexporter.js',
'ArcballControls.js', 'filesaver.js',
'base64-arraybuffer.js', 'context.js',
'chemview.js', 'three.min.js', 'jquery-ui.min.js',
'context.standalone.css... | As a Python code composer, you craft elegant and concise scripts. |
def extract_pdf(file_name):
"""
Extract text from a pdf file
:param file_name path to pdf to read
:return text from pdf
"""
rsrcmgr = pdfminer.pdfinterp.PDFResourceManager()
sio = StringIO()
laparams = LAParams()
device = TextConverter(rsrcmgr, sio, codec='utf-8', laparams=laparams)... | Create a Python 3 function to
extract text from a pdf file | As a python code expert, you are capable of creating scripts from specifications. |
def process_file(source_file):
"""
Extract text from a file (pdf, txt, eml, csv, json)
:param source_file path to file to read
:return text from file
"""
if source_file.endswith(('.pdf', '.PDF')):
txt = extract_pdf(source_file)
elif source_file.endswith(('.txt', '.eml', '.csv', '.jso... | Create a Python 3 function to
extract text from a file | As a python code expert, you are capable of creating scripts from specifications. |
Returns the value passed in as string. | Explain what the following Python 3 code does
def from_string(cls, string):
# find enum value
for attr in dir(cls):
value = getattr(cls, attr)
if value == string:
return value
# if not found, log warning and return the value passed in
logger.warn... | As a Python code composer, you craft elegant and concise scripts. |
def validate(self, value):
"""
Validate (and possibly typecast) the given parameter value value.
:param value: Parameter value
:return: Typecast parameter value
:raises ValidationErrors: if there were validation errors
"""
errors = []
value = self._valida... | Can you write a function in Python 3 where it
validates the given parameter value value. | As a python code expert, you are capable of creating scripts from specifications. |
Build a single parameter argument that can be used as a CLI string. | How would you explain what the following Python 3 function does
def format_cli(self, value):
if value is None or (self.type == 'flag' and not value):
return None
pass_as_bits = text_type(self.pass_as or self.default_pass_as).split()
env = dict(name=self.name, value=value, v=value)
... | You are a Python code generator, capable of creating scripts from specifications. |
def listify(value):
"""
Wrap the given value into a list, with the below provisions:
* If the value is a list or a tuple, it's coerced into a new list.
* If the value is None, an empty list is returned.
* Otherwise, a single-element list is returned, containing the value.
:param value: A value... | Write a Python 3 script for
wrapping the given value into a list. | You are a Python code analyst, evaluating scripts for potential improvements. |
def build_command(command, parameter_map):
"""
Build command line(s) using the given parameter map.
Even if the passed a single `command`, this function will return a list
of shell commands. It is the caller's responsibility to concatenate them,
likely using the semicolon or double ampersands.
... | Write a Python 3 script to
build a list of shell commands from a command line. | As a Python code composer, you craft elegant and concise scripts. |
Validate the given YAML document and return a list of errors encountered. | Explain what the following Python 3 code does
def validate(yaml, raise_exc=True):
data = read_yaml(yaml)
validator = get_validator()
# Nb: this uses a list instead of being a generator function in order to be
# easier to call correctly. (Were it a generator function, a plain
# `validate(..., raise_e... | You are a Python code analyst, evaluating scripts for potential improvements. |
def build_parameters(self):
"""
Build the CLI command line from the parameter values.
:return: list of CLI strings -- not escaped!
:rtype: list[str]
"""
param_bits = []
for name in self.parameters:
param_bits.extend(self.build_parameter_by_name(name) ... | Can you write a function in Python 3 where it
builds the CLI command line from the parameter values. | You are a Python code generator, capable of creating scripts from specifications. |
Parse a Config structure out of a Python dict. | Make a summary of the following Python 3 code
def parse(cls, data):
parsers = {
'step': ([], Step.parse),
'endpoint': ([], Endpoint.parse),
}
for datum in data:
assert isinstance(datum, dict)
for type, (items, parse) in parsers.items():
... | You are a Python code generator, capable of creating scripts from specifications. |
Get the first step that matches all the passed named arguments. | Can you tell what is the following Python 3 function doing
def get_step_by(self, **kwargs):
if not kwargs:
return None
for index, step in enumerate(self.steps.values()):
extended_step = dict(step.serialize(), index=index)
# check if kwargs is a subset of extended_step... | You are a Python code analyst, evaluating scripts for potential improvements. |
def parse(yaml, validate=True):
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param validate: Whether to validate the data before attempting to ... | Can you create a Python 3 function that
parses the given YAML data into a Config object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_parameter_defaults(self, include_flags=True):
"""
Get a dict mapping parameter names to their defaults (if set).
:rtype: dict[str, object]
"""
return {
name: parameter.default
for (name, parameter)
in self.parameters.items()
... | Write a Python 3 script to
get a dict mapping parameter names to their default values. | As a python code expert, you are capable of creating scripts from specifications. |
Builds a command for this step using the given parameter values. | Can you tell what is the following Python 3 function doing
def build_command(self, parameter_values, command=None):
command = (command or self.command)
# merge defaults with passed values
# ignore flag default values as they are special
# undefined flag will remain undefined regardless ... | As a python code expert, you are capable of creating scripts from specifications. |
def lint_file(file_path):
"""
Validate & lint `file_path` and return a LintResult.
:param file_path: YAML filename
:type file_path: str
:return: LintResult object
"""
with open(file_path, 'r') as yaml:
try:
return lint(yaml)
except Exception as e:
lr... | How would you code a function in Python 3 to
validate & lint file_path and return a LintResult object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Turn all capturing groups in a regular expression pattern into
non - capturing groups. | How would you explain what the following Python 3 function does
def _re_flatten(p):
''' Turn all capturing groups in a regular expression pattern into
non-capturing groups. '''
if '(' not in p: return p
return re.sub(r'(\\*)(\(\?P<[^>]+>|\((?!\?))',
lambda m: m.group(0) if len(m.group(1)) % ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def redirect(url, code=None):
""" Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. """
if not code:
code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302
res = response.copy(cls=HTTPResponse)
res.status = code
res.body = ""
... | Can you write a function in Python 3 where it
aborts execution and causes a 303 or 302 redirect. | You are a Python code architect, reviewing and designing scalable and efficient code |
Yields a range of bytes from a file. | How would you explain what the following Python 3 function does
def _file_iter_range(fp, offset, bytes, maxread=1024*1024):
''' Yield chunks from a range in a file. No chunk is bigger than maxread.'''
fp.seek(offset)
while bytes > 0:
part = fp.read(min(bytes, maxread))
if not part: break
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Open a file in a safe way and return a response object. | Explain what the following Python 3 code does
def static_file(filename, root, mimetype='auto', download=False, charset='UTF-8'):
root = os.path.abspath(root) + os.sep
filename = os.path.abspath(os.path.join(root, filename.strip('/\\')))
headers = dict()
if not filename.startswith(root):
return... | As a Python code analyst, you investigate and solve complex coding mysteries |
def debug(mode=True):
""" Change the debug level.
There is only one debug level supported at the moment."""
global DEBUG
if mode: warnings.simplefilter('default')
DEBUG = bool(mode) | Write a Python 3 script for
changing the debug level. | You are a Python code analyst, evaluating scripts for potential improvements. |
def parse_auth(header):
""" Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None"""
try:
method, data = header.split(None, 1)
if method.lower() == 'basic':
user, pwd = touni(base64.b64decode(tob(data))).split(':',1)
return user, pwd... | Implement a function in Python 3 to
parse RFC 2617 HTTP authentication header string and return user and pass tuple or None | You are a Python code generator, capable of creating scripts from specifications. |
def parse_range_header(header, maxlen=0):
''' Yield (start, end) ranges parsed from a HTTP Range header. Skip
unsatisfiable ranges. The end index is non-inclusive.'''
if not header or header[:6] != 'bytes=': return
ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r]
for start, ... | How would you implement a function in Python 3 that
parses a range header. | You are a Python code architect, reviewing and designing scalable and efficient code |
def add(self, rule, method, target, name=None):
''' Add a new rule or replace the target for an existing rule. '''
anons = 0 # Number of anonymous wildcards found
keys = [] # Names of keys
pattern = '' # Regular expression pattern with named groups
filters = [... | Can you write a function in Python 3 where it
adds a new rule or replace the target for an existing rule. | As a python code expert, you are capable of creating scripts from specifications. |
def build(self, _name, *anons, **query):
''' Build an URL by filling the wildcards in a rule. '''
builder = self.builder.get(_name)
if not builder: raise RouteBuildError("No route with that name.", _name)
try:
for i, value in enumerate(anons): query['anon%d'%i] = value
... | Write a Python 3 script to
build a URL by filling the wildcards in a rule. | As a python code expert, you are capable of creating scripts from specifications. |
Return a tuple of target url_agrs if the given path matches the current route. | Here you have a function in Python 3, explain what it does
def match(self, environ):
''' Return a (target, url_agrs) tuple or raise HTTPError(400/404/405). '''
verb = environ['REQUEST_METHOD'].upper()
path = environ['PATH_INFO'] or '/'
target = None
if verb == 'HEAD':
... | You are a Python code generator, capable of creating scripts from specifications. |
Return the original callback. If the callback is a decorated function try to
recover the original function. | Can you tell what is the following Python 3 function doing
def get_undecorated_callback(self):
''' Return the callback. If the callback is a decorated function, try to
recover the original function. '''
func = self.callback
func = getattr(func, '__func__' if py3k else 'im_func', func... | As a python code expert, you are capable of creating scripts from specifications. |
Attach a callback to a hook. | Here you have a function in Python 3, explain what it does
def add_hook(self, name, func):
''' Attach a callback to a hook. Three hooks are currently implemented:
before_request
Executed once before each request. The request context is
available, but no routing has h... | You are a Python code generator, capable of creating scripts from specifications. |
Remove a callback from a hook. | Given the following Python 3 function, write the documentation
def remove_hook(self, name, func):
''' Remove a callback from a hook. '''
if name in self._hooks and func in self._hooks[name]:
self._hooks[name].remove(func)
return True | You are a Python code analyst, evaluating scripts for potential improvements. |
def trigger_hook(self, __name, *args, **kwargs):
''' Trigger a hook and return a list of results. '''
return [hook(*args, **kwargs) for hook in self._hooks[__name][:]] | Can you create a Python 3 function that
triggers a hook and return a list of results. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a decorator that attaches a callback to a hook. See
. add_hook for details. | Can you tell what is the following Python 3 function doing
def hook(self, name):
def decorator(func):
self.add_hook(name, func)
return func
return decorator | As a Python code analyst, you investigate and solve complex coding mysteries |
Mount an application to a specific path prefix. | Make a summary of the following Python 3 code
def mount(self, prefix, app, **options):
''' Mount an application (:class:`Bottle` or plain WSGI) to a specific
URL prefix. Example::
root_app.mount('/admin/', admin_app)
:param prefix: path prefix or `mount-point`. If it en... | As a Python code composer, you craft elegant and concise scripts. |
def merge(self, routes):
''' Merge the routes of another :class:`Bottle` application or a list of
:class:`Route` objects into this application. The routes keep their
'owner', meaning that the :data:`Route.app` attribute is not
changed. '''
if isinstance(routes, Bottle... | Can you create a Python 3 function that
merges the routes of another Bottle application or a list of Bottle. | You are a Python code architect, reviewing and designing scalable and efficient code |
Reset all routes and clear all the caches. | Given the following Python 3 function, write the documentation
def reset(self, route=None):
''' Reset all routes (force plugins to be re-applied) and clear all
caches. If an ID or route object is given, only that specific route
is affected. '''
if route is None: routes = self.rou... | You are a Python code analyst, evaluating scripts for potential improvements. |
def add_route(self, route):
''' Add a route object, but do not change the :data:`Route.app`
attribute.'''
self.routes.append(route)
self.router.add(route.rule, route.method, route, name=route.name)
if DEBUG: route.prepare() | Create a Python 3 function for
adding a route object but do not change the : data : Route. app attribute. | You are a Python code architect, reviewing and designing scalable and efficient code |
Try to convert the output into something WSGI compatible and set
AttributeNames correct HTTP headers when possible. | Given the following Python 3 function, write the documentation
def _cast(self, out, peek=None):
# Empty output is done here
if not out:
if 'Content-Length' not in response:
response['Content-Length'] = 0
return []
# Join lists of byte or unicode strings. ... | As a Python code analyst, you investigate and solve complex coding mysteries |
The bottle WSGI - interface. | Can you generate the documentation for the following Python 3 function
def wsgi(self, environ, start_response):
try:
out = self._cast(self._handle(environ))
# rfc2616 section 4.3
if response._status_code in (100, 101, 204, 304)\
or environ['REQUEST_METHOD'] == 'HE... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a FormsDict containing all the form values parsed from an url - encoded POST or PUT request body. | Can you tell what is the following Python 3 function doing
def forms(self):
forms = FormsDict()
for name, item in self.POST.allitems():
if not isinstance(item, FileUpload):
forms[name] = item
return forms | You are a Python code architect, reviewing and designing scalable and efficient code |
A FormsDict with the combined values of query and forms. File uploads are stored in files. | Make a summary of the following Python 3 code
def params(self):
params = FormsDict()
for key, value in self.query.allitems():
params[key] = value
for key, value in self.forms.allitems():
params[key] = value
return params | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a FormsDict containing the files parsed from the POST or PUT
request body. | Given the following Python 3 function, write the documentation
def files(self):
files = FormsDict()
for name, item in self.POST.allitems():
if isinstance(item, FileUpload):
files[name] = item
return files | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the json object of the current object. | Make a summary of the following Python 3 code
def json(self):
''' If the ``Content-Type`` header is ``application/json``, this
property holds the parsed content of the request body. Only requests
smaller than :attr:`MEMFILE_MAX` are processed to avoid memory
exhaustion. '''
... | As a Python code composer, you craft elegant and concise scripts. |
def copy(self, cls=None):
''' Returns a copy of self. '''
cls = cls or BaseResponse
assert issubclass(cls, BaseResponse)
copy = cls()
copy.status = self.status
copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
if self._cookies:
copy._... | Can you create a Python 3 function that
returns a copy of self. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a new response header with the given name and value. | Can you generate a brief explanation for the following Python 3 code
def set_header(self, name, value):
''' Create a new response header, replacing any previously defined
headers with the same name. '''
self._headers[_hkey(name)] = [str(value)] | As a Python code analyst, you investigate and solve complex coding mysteries |
Return charset specified in the content - type header. | Given the following Python 3 function, write the documentation
def charset(self, default='UTF-8'):
if 'charset=' in self.content_type:
return self.content_type.split('charset=')[-1].split(';')[0].strip()
return default | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a new cookie or replace an old one. If the `secret` parameter is
set, create a `Signed Cookie` (described below).
:param name: the name of the cookie.
:param value: the value of the cookie.
:param secret: a signature key required for signed cookies.
A... | Explain what the following Python 3 code does
def set_cookie(self, name, value, secret=None, **options):
''' Create a new cookie or replace an old one. If the `secret` parameter is
set, create a `Signed Cookie` (described below).
:param name: the name of the cookie.
:param v... | You are a Python code architect, reviewing and designing scalable and efficient code |
def decode(self, encoding=None):
''' Returns a copy with all keys and values de- or recoded to match
:attr:`input_encoding`. Some libraries (e.g. WTForms) want a
unicode dictionary. '''
copy = FormsDict()
enc = copy.input_encoding = encoding or self.input_encoding
... | Can you implement a function in Python 3 that
returns a copy with all keys and values de - or recoded to match . | As a Python code composer, you craft elegant and concise scripts. |
Return the value as a unicode string or the default. | Explain what the following Python 3 code does
def getunicode(self, name, default=None, encoding=None):
''' Return the value as a unicode string, or the default. '''
try:
return self._fix(self[name], encoding)
except (UnicodeError, KeyError):
return default | As a Python code composer, you craft elegant and concise scripts. |
def load_config(self, filename):
''' Load values from an *.ini style config file.
If the config file contains sections, their names are used as
namespaces for the values within. The two special sections
``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix).
... | Can you create a Python 3 function that
loads values from an. ini style config file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Import values from a dictionary structure. Nesting can be used to represent namespaces. | Here you have a function in Python 3, explain what it does
def load_dict(self, source, namespace='', make_namespaces=False):
''' Import values from a dictionary structure. Nesting can be used to
represent namespaces.
>>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}})
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def meta_get(self, key, metafield, default=None):
''' Return the value of a meta field for a key. '''
return self._meta.get(key, {}).get(metafield, default) | How would you code a function in Python 3 to
return the value of a meta field for a key. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Set the meta field for a key to a new value. This triggers the the
on - change handler for existing keys. | Can you tell what is the following Python 3 function doing
def meta_set(self, key, metafield, value):
''' Set the meta field for a key to a new value. This triggers the
on-change handler for existing keys. '''
self._meta.setdefault(key, {})[metafield] = value
if key in self:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Search for a resource and return an absolute file path or None. | Explain what the following Python 3 code does
def lookup(self, name):
''' Search for a resource and return an absolute file path, or `None`.
The :attr:`path` list is searched in order. The first match is
returend. Symlinks are followed. The result is cached to speed up
futur... | You are a Python code architect, reviewing and designing scalable and efficient code |
def open(self, name, mode='r', *args, **kwargs):
''' Find a resource and return a file object, or raise IOError. '''
fname = self.lookup(name)
if not fname: raise IOError("Resource %r not found." % name)
return self.opener(fname, mode=mode, *args, **kwargs) | How would you implement a function in Python 3 that
finds a resource and return a file object. | As a python code expert, you are capable of creating scripts from specifications. |
def save(self, destination, overwrite=False, chunk_size=2**16):
''' Save file to disk or copy its content to an open file(-like) object.
If *destination* is a directory, :attr:`filename` is added to the
path. Existing files are not overwritten by default (IOError).
:param de... | Implement a Python 3 function for
saving file to disk or copy its content to an open file - like object. | You are a Python code architect, reviewing and designing scalable and efficient code |
def render(self, *args, **kwargs):
""" Render the template using keyword arguments as local variables. """
env = {}; stdout = []
for dictarg in args: env.update(dictarg)
env.update(kwargs)
self.execute(stdout, env)
return ''.join(stdout) | Write a Python 3 function that can
render the template using keyword arguments as local variables. | As a python code expert, you are capable of creating scripts from specifications. |
def convert_value(value, source_currency, target_currency):
"""Converts the price of a currency to another one using exchange rates
:param price: the price value
:param type: decimal
:param source_currency: source ISO-4217 currency code
:param type: str
:param target_currency: target ISO-4217... | Can you create a Python 3 function that
converts the price of a currency to another currency using exchange rates | You are a Python code analyst, evaluating scripts for potential improvements. |
imports and returns given class string. | Explain what the following Python 3 code does
def import_class(class_path):
try:
from django.utils.importlib import import_module
module_name = '.'.join(class_path.split(".")[:-1])
mod = import_module(module_name)
return getattr(mod, class_path.split(".")[-1])
except Exception, d... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def insert_many(objects, using="default"):
"""Insert list of Django objects in one SQL query. Objects must be
of the same Django model. Note that save is not called and signals
on the model are not raised.
Mostly from: http://people.iola.dk/olau/python/bulkops.py
"""
if not objects:
ret... | How would you implement a function in Python 3 that
inserts list of Django objects in one SQL query. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def update_many(objects, fields=[], using="default"):
"""Update list of Django objects in one SQL query, optionally only
overwrite the given fields (as names, e.g. fields=["foo"]).
Objects must be of the same Django model. Note that save is not
called and signals on the model are not raised.
Mostly... | Implement a Python 3 function for
updating a list of Django objects in one SQL query optionally only overwrite the given fields. | You are a Python code analyst, evaluating scripts for potential improvements. |
A decorator that caches the result of the function call with given args for until ttl seconds expires. | Make a summary of the following Python 3 code
def memoize(ttl=None):
def decorator(obj):
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
now = datetime.now()
key = str(args) + str(kwargs)
if key not in cache:
ca... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the duration between start_time and end_time rounded to 15 minutes. | How would you explain what the following Python 3 function does
def round_to_quarter(start_time, end_time):
# We don't care about the date (only about the time) but Python
# can substract only datetime objects, not time ones
today = datetime.date.today()
start_date = datetime.datetime.combine(today, sta... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _timesheets_callback(self, callback):
"""
Call a method on all the timesheets, aggregate the return values in a
list and return it.
"""
def call(*args, **kwargs):
return_values = []
for timesheet in self:
attr = getattr(timesheet, call... | Write a Python 3 script to
return a function that will be called on all the timesheets and aggregate the return values in a list and return it. | You are a Python code architect, reviewing and designing scalable and efficient code |
def load(cls, file_pattern, nb_previous_files=1, parser=None):
"""
Load a collection of timesheet from the given `file_pattern`. `file_pattern` is a path to a timesheet file that
will be expanded with :func:`datetime.date.strftime` and the current date. `nb_previous_files` is the number of
... | Implement a Python 3 function for
loading a collection of timesheets from the given file pattern. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_files(cls, file_pattern, nb_previous_files, from_date=None):
"""
Return an :class:`~taxi.utils.structures.OrderedSet` of file paths expanded from `filename`, with a maximum of
`nb_previous_files`. See :func:`taxi.utils.file.expand_date` for more information about filename expansion. If
... | Create a Python 3 function to
return an OrderedSet of file paths expanded from filename with a maximum of nb_previous_files. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_new_timesheets_contents(self):
"""
Return the initial text to be inserted in new timesheets.
"""
popular_aliases = self.get_popular_aliases()
template = ['# Recently used aliases:']
if popular_aliases:
contents = '\n'.join(template + ['# ' + entry for... | Can you write a function in Python 3 where it
returns the initial text to be inserted in new timesheets. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def entries(self):
"""
Return the entries (as a {date: entries} dict) of all timesheets in the
collection.
"""
entries_list = self._timesheets_callback('entries')()
return reduce(lambda x, y: x + y, entries_list) | Write a Python 3 function that can
return the entries of all timesheets in the the collection. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_popular_aliases(self, *args, **kwargs):
"""
Return the aggregated results of :meth:`Timesheet.get_popular_aliases`.
"""
aliases_count_total = defaultdict(int)
aliases_counts = self._timesheets_callback('get_popular_aliases')(*args, **kwargs)
for aliases_count in ... | Write a Python 3 script to
return the aggregated results of : meth : Timeheet. get_popular_aliases. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Show the contents of the base object. | Here you have a function in Python 3, explain what it does
def show(ctx, search):
matches = {'aliases': [], 'mappings': [], 'projects': []}
projects_db = ctx.obj['projects_db']
matches = get_alias_matches(search, matches)
matches = get_mapping_matches(search, matches, projects_db)
matches = get_pro... | You are a Python code generator, capable of creating scripts from specifications. |
def status(ctx, date, f, pushed):
"""
Shows the summary of what's going to be committed to the server.
"""
try:
timesheet_collection = get_timesheet_collection_for_context(ctx, f)
except ParseError as e:
ctx.obj['view'].err(e)
else:
ctx.obj['view'].show_status(
... | How would you implement a function in Python 3 that
shows the status of what s going to be committed to the server. | As a python code expert, you are capable of creating scripts from specifications. |
Edit a timesheet file in your favourite editor. | How would you explain what the following Python 3 function does
def edit(ctx, file_to_edit, previous_file):
timesheet_collection = None
autofill = not bool(file_to_edit) and previous_file == 0
if not file_to_edit:
file_to_edit = ctx.obj['settings'].get_entries_file_path(False)
# If the file was... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_reversed_aliases(self):
"""
Return the reversed aliases dict. Instead of being in the form
{'alias': mapping}, the dict is in the form {mapping: 'alias'}.
"""
return dict((v, k) for k, v in six.iteritems(self.aliases)) | Implement a Python 3 function for
returning the reversed aliases dict. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def filter_from_mapping(self, mapping, backend=None):
"""
Return mappings that either exactly correspond to the given `mapping`
tuple, or, if the second item of `mapping` is `None`, include mappings
that only match the first item of `mapping` (useful to show all
mappings for a gi... | Implement a Python 3 function for
returning a list of mappings that exactly correspond to the given mapping. | As a python code expert, you are capable of creating scripts from specifications. |
Return aliases that start with the given alias optionally filtered by backend. | Can you generate a brief explanation for the following Python 3 code
def filter_from_alias(self, alias, backend=None):
def alias_filter(key_item):
key, item = key_item
return ((alias is None or alias in key) and
(backend is None or item.backend == backend))
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.