output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def normalize_datetime_to_utc(dt):
"""Adjust datetime to UTC.
Apply the timezone offset to the datetime and set the timezone to UTC.
This is a no-op if the datetime is already in UTC.
Args:
dt : datetime
- tz-aware: Used in the formatted string.
- tz-naive: Assumed to be in UTC.... | Can you write a function in Python 3 where it
adjusts the datetime to UTC. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def cast_naive_datetime_to_tz(dt, tz=UTC()):
"""If datetime is tz-naive, set it to ``tz``. If datetime is tz-aware, return it
unmodified.
Args:
dt : datetime
tz-naive or tz-aware datetime.
tz : datetime.tzinfo
The timezone to which to adjust tz-naive datetime.
Returns:
... | Can you implement a function in Python 3 that
casts a naive datetime to a tz - aware datetime. | As a Python code composer, you craft elegant and concise scripts. |
Round datetime up or down to nearest divisor. | Can you tell what is the following Python 3 function doing
def round_to_nearest(dt, n_round_sec=1.0):
ts = ts_from_dt(strip_timezone(dt)) + n_round_sec / 2.0
res = dt_from_ts(ts - (ts % n_round_sec))
return res.replace(tzinfo=dt.tzinfo) | You are a Python code analyst, evaluating scripts for potential improvements. |
def submit(self, data, runtime_dir, argv):
"""Run process with SLURM.
For details, see
:meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`.
"""
limits = data.process.get_resource_limits()
logger.debug(__(
"Connector '{}' running for D... | How would you code a function in Python 3 to
submit a new process with SLURM. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_purge_files(root, output, output_schema, descriptor, descriptor_schema):
"""Get files to purge."""
def remove_file(fn, paths):
"""From paths remove fn and dirs before fn in dir tree."""
while fn:
for i in range(len(paths) - 1, -1, -1):
if fn == paths[i]:
... | Can you write a function in Python 3 where it
gets the list of files to purge. | You are a Python code generator, capable of creating scripts from specifications. |
def location_purge(location_id, delete=False, verbosity=0):
"""Print and conditionally delete files not referenced by meta data.
:param location_id: Id of the
:class:`~resolwe.flow.models.DataLocation` model that data
objects reference to.
:param delete: If ``True``, then delete unreference... | Create a Python 3 function to
purge all files referenced by meta data. | You are a Python code generator, capable of creating scripts from specifications. |
Purge all data locations. | Can you generate a brief explanation for the following Python 3 code
def _location_purge_all(delete=False, verbosity=0):
if DataLocation.objects.exists():
for location in DataLocation.objects.filter(Q(purged=False) | Q(data=None)):
location_purge(location.id, delete, verbosity)
else:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def purge_all(delete=False, verbosity=0):
"""Purge all data locations."""
_location_purge_all(delete, verbosity)
_storage_purge_all(delete, verbosity) | How would you implement a function in Python 3 that
purges all data locations and storage. | As a python code expert, you are capable of creating scripts from specifications. |
def get_value(self, node):
"""Convert value from an AST node."""
if not isinstance(node, ast.Str):
raise TypeError("must be a string literal")
return node.s | How would you implement a function in Python 3 that
converts value from an AST node. | You are a Python code generator, capable of creating scripts from specifications. |
def get_value(self, node):
"""Convert value from an AST node."""
if not isinstance(node, ast.Attribute):
raise TypeError("must be an attribute")
if node.value.id != self.choices.__name__:
raise TypeError("must be an attribute of {}".format(self.choices.__name__))
... | How would you code a function in Python 3 to
convert value from an AST node. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_value(self, node):
"""Convert value from an AST node."""
if not isinstance(node, ast.Dict):
raise TypeError("must be a dictionary")
evaluator = SafeEvaluator()
try:
value = evaluator.run(node)
except Exception as ex:
# TODO: Handle err... | Can you create a Python 3 function that
converts value from an AST node. | You are a Python code generator, capable of creating scripts from specifications. |
def visit_field_class(self, item, descriptor=None, fields=None):
"""Visit a class node containing a list of field definitions."""
discovered_fields = collections.OrderedDict()
field_groups = {}
for node in item.body:
if isinstance(node, ast.ClassDef):
field_gr... | Write a Python 3 function that can
visit a class node containing a list of field definitions. | You are a Python code architect, reviewing and designing scalable and efficient code |
Visit the class definition node. | Can you tell what is the following Python 3 function doing
def visit_ClassDef(self, node): # pylint: disable=invalid-name
# Resolve everything as root scope contains everything from the process module.
for base in node.bases:
# Cover `from resolwe.process import ...`.
if isinsta... | You are a Python code analyst, evaluating scripts for potential improvements. |
Parse process.
:return: A list of discovered process descriptors | Explain what the following Python 3 code does
def parse(self):
root = ast.parse(self._source)
visitor = ProcessVisitor(source=self._source)
visitor.visit(root)
return visitor.processes | You are a Python code architect, reviewing and designing scalable and efficient code |
Load and cache permissions class. | Can you tell what is the following Python 3 function doing
def get_permissions_class(permissions_name=None):
def load_permissions(permissions_name):
"""Look for a fully qualified flow permissions class."""
try:
return import_module('{}'.format(permissions_name)).ResolwePermissions
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get set of identifiers that provide revision context for SciObj. | Here you have a function in Python 3, explain what it does
def get_identifiers(sysmeta_pyxb):
pid = d1_common.xml.get_opt_val(sysmeta_pyxb, 'identifier')
sid = d1_common.xml.get_opt_val(sysmeta_pyxb, 'seriesId')
obsoletes_pid = d1_common.xml.get_opt_val(sysmeta_pyxb, 'obsoletes')
obsoleted_by_pid = d1_c... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def topological_sort(unsorted_dict):
"""Sort objects by dependency.
Sort a dict of obsoleting PID to obsoleted PID to a list of PIDs in order of
obsolescence.
Args:
unsorted_dict : dict
Dict that holds obsolescence information. Each ``key/value`` pair establishes
that the PID in ... | Write a Python 3 function that can
sort objects by dependency. | As a Python code composer, you craft elegant and concise scripts. |
def get_pids_in_revision_chain(client, did):
"""Args: client: d1_client.cnclient.CoordinatingNodeClient or
d1_client.mnclient.MemberNodeClient.
did : str
SID or a PID of any object in a revision chain.
Returns:
list of str:
All PIDs in the chain. The returned list is in the sam... | How would you implement a function in Python 3 that
returns a list of all PIDs in the revision chain. | As a Python code analyst, you investigate and solve complex coding mysteries |
This function is called by the command line interface to remove unused imports Unsafe!
Only tested on our codebase which uses simple absolute imports on the form import
a. b. c. | Make a summary of the following Python 3 code
def main():
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("path", nargs="+", help="File or directory path")
parser.add_argument("--exclude", nargs="+", help="Exclude ... | As a python code expert, you are capable of creating scripts from specifications. |
Find all triple - quoted docstrings in module. | Explain what the following Python 3 code does
def get_docstr_list(red):
docstr_list = []
for n in red.find_all("string"):
if n.value.startswith('"""'):
docstr_list.append(n)
return docstr_list | You are a Python code architect, reviewing and designing scalable and efficient code |
def unwrap(s, node_indent):
"""Group lines of a docstring to blocks.
For now, only groups markdown list sections.
A block designates a list of consequtive lines that all start at the same
indentation level.
The lines of the docstring are iterated top to bottom. Each line is added to
`block_li... | Can you create a Python 3 function that
unwraps a string into a list of consequtive blocks. | As a Python code composer, you craft elegant and concise scripts. |
def wrap(indent_int, unwrap_str):
"""Wrap a single line to one or more lines that start at indent_int and end at the
last word that will fit before WRAP_MARGIN_INT.
If there are no word breaks (spaces) before WRAP_MARGIN_INT, force a break at
WRAP_MARGIN_INT.
"""
with io.StringIO() as str_buf:... | Write a Python 3 function that can
wrap a single line to one or more lines that start at indent_int and end at indent_int and force a break at the end of the last word that will fit before WRAP_MARGIN_INT. | You are a Python code architect, reviewing and designing scalable and efficient code |
def createSimpleResourceMap(ore_pid, scimeta_pid, sciobj_pid_list):
"""Create a simple OAI-ORE Resource Map with one Science Metadata document and any
number of Science Data objects.
This creates a document that establishes an association between a Science Metadata
object and any number of Science Data... | Can you write a function in Python 3 where it
creates a simple OAI -ORE Resource Map with one Science Metadata document and any number of Science Data objects. | You are a Python code analyst, evaluating scripts for potential improvements. |
def createResourceMapFromStream(in_stream, base_url=d1_common.const.URL_DATAONE_ROOT):
"""Create a simple OAI-ORE Resource Map with one Science Metadata document and any
number of Science Data objects, using a stream of PIDs.
Args:
in_stream:
The first non-blank line is the PID of the resourc... | Can you write a function in Python 3 where it
creates a simple OAI -ORE Resource Map from a stream of PIDs. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create the basic ORE document structure. | How would you explain what the following Python 3 function does
def initialize(self, pid, ore_software_id=d1_common.const.ORE_SOFTWARE_ID):
# Set nice prefixes for the namespaces
for k in list(d1_common.const.ORE_NAMESPACE_DICT.keys()):
self.bind(k, d1_common.const.ORE_NAMESPACE_DICT[k])
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Serialize to UTF - 8 encoded XML document. | Can you generate a brief explanation for the following Python 3 code
def serialize_to_transport(self, doc_format="xml", *args, **kwargs):
return super(ResourceMap, self).serialize(
format=doc_format, encoding="utf-8", *args, **kwargs
) | As a Python code analyst, you investigate and solve complex coding mysteries |
def serialize_to_display(self, doc_format="pretty-xml", *args, **kwargs):
"""Serialize ResourceMap to an XML doc that is pretty printed for display.
Args:
doc_format: str
One of: ``xml``, ``n3``, ``turtle``, ``nt``, ``pretty-xml``, ``trix``,
``trig`` and ``nquads``.
... | Implement a function in Python 3 to
serialize ResourceMap to an XML doc that is pretty printed for display. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def getAggregation(self):
"""Returns:
str : URIRef of the Aggregation entity
"""
self._check_initialized()
return [
o for o in self.subjects(predicate=rdflib.RDF.type, object=ORE.Aggregation)
][0] | Create a Python 3 function to
return the URIRef of the Aggregation entity | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the object identified by pid. | Explain what the following Python 3 code does
def getObjectByPid(self, pid):
self._check_initialized()
opid = rdflib.term.Literal(pid)
res = [o for o in self.subjects(predicate=DCTERMS.identifier, object=opid)]
return res[0] | As a Python code composer, you craft elegant and concise scripts. |
Add a resource to the Resource Map. | Explain what the following Python 3 code does
def addResource(self, pid):
self._check_initialized()
try:
# is entry already in place?
self.getObjectByPid(pid)
return
except IndexError:
pass
# Entry not present, add it to the graph
o... | You are a Python code generator, capable of creating scripts from specifications. |
Add a CiTO the Citation Typing Ontology triple asserting that
documenting_pid documents documented_pid | Here you have a function in Python 3, explain what it does
def setDocuments(self, documenting_pid, documented_pid):
self._check_initialized()
documenting_id = self.getObjectByPid(documenting_pid)
documented_id = self.getObjectByPid(documented_pid)
self.add((documenting_id, CITO.documents... | As a python code expert, you are capable of creating scripts from specifications. |
Add a CiTO the Citation Typing Ontology triple asserting that documented_pid is documenting_pid. | Explain what the following Python 3 code does
def setDocumentedBy(self, documented_pid, documenting_pid):
self._check_initialized()
documented_id = self.getObjectByPid(documented_pid)
documenting_id = self.getObjectByPid(documenting_pid)
self.add((documented_id, CITO.isDocumentedBy, docu... | As a Python code analyst, you investigate and solve complex coding mysteries |
def addDataDocuments(self, scidata_pid_list, scimeta_pid=None):
"""Add Science Data object(s)
Args:
scidata_pid_list : list of str
List of one or more PIDs of Science Data objects
scimeta_pid: str
PID of a Science Metadata object that documents the Science D... | Write a Python 3 script for
adding a list of PIDs of Science Data objects to the list of Science Data objects that documents the Science Data objects. | As a Python code analyst, you investigate and solve complex coding mysteries |
def getResourceMapPid(self):
"""Returns:
str : PID of the Resource Map itself.
"""
ore = [
o for o in self.subjects(predicate=rdflib.RDF.type, object=ORE.ResourceMap)
][0]
pid = [str(o) for o in self.objects(predicate=DCTERMS.identifier, subject=ore)][
... | Create a Python 3 function to
return the PID of the Resource Map itself. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a list of tuples containing a subject predicate object. | Here you have a function in Python 3, explain what it does
def getAllTriples(self):
return [(str(s), str(p), str(o)) for s, p, o in self] | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a list of subject and object tuples that match the predicate. | How would you explain what the following Python 3 function does
def getSubjectObjectsByPredicate(self, predicate):
return sorted(
set(
[
(str(s), str(o))
for s, o in self.subject_objects(rdflib.term.URIRef(predicate))
]
... | As a Python code composer, you craft elegant and concise scripts. |
def parseDoc(self, doc_str, format="xml"):
"""Parse a OAI-ORE Resource Maps document.
See Also: ``rdflib.ConjunctiveGraph.parse`` for documentation on arguments.
"""
self.parse(data=doc_str, format=format)
self._ore_initialized = True
return self | How would you code a function in Python 3 to
parse a OAI -ORE resource maps document. | You are a Python code architect, reviewing and designing scalable and efficient code |
Converts a pid to a URI that can be used as an OAI -ORE identifier. | Explain what the following Python 3 code does
def _pid_to_id(self, pid):
return d1_common.url.joinPathElements(
self._base_url,
self._version_tag,
"resolve",
d1_common.url.encodePathElement(pid),
) | You are a Python code analyst, evaluating scripts for potential improvements. |
def make_checksum_validation_script(stats_list):
"""Make batch files required for checking checksums from another machine."""
if not os.path.exists('./hash_check'):
os.mkdir('./hash_check')
with open('./hash_check/curl.sh', 'w') as curl_f, open(
'./hash_check/md5.txt', 'w'
) as md5_f, o... | Write a Python 3 function for
making the script required for checking checksums from another machine. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a formfield with max_value 90 and min_value - 90. | How would you explain what the following Python 3 function does
def formfield(self, **kwargs):
kwargs.update({
'max_value': 90,
'min_value': -90,
})
return super(LatitudeField, self).formfield(**kwargs) | As a python code expert, you are capable of creating scripts from specifications. |
Returns a formfield with max_value 180 and min_value - 180. | Given the following Python 3 function, write the documentation
def formfield(self, **kwargs):
kwargs.update({
'max_value': 180,
'min_value': -180,
})
return super(LongitudeField, self).formfield(**kwargs) | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a new OSMFormField with the specified kwargs. | Can you generate a brief explanation for the following Python 3 code
def formfield(self, **kwargs):
widget_kwargs = {
'lat_field': self.latitude_field_name,
'lon_field': self.longitude_field_name,
}
if self.data_field_name:
widget_kwargs['data_field'] = self.... | As a Python code composer, you craft elegant and concise scripts. |
The name of the related : class : LongitudeField. | Can you tell what is the following Python 3 function doing
def longitude_field_name(self):
if self._lon_field_name is None:
self._lon_field_name = self.name + '_lon'
return self._lon_field_name | As a Python code composer, you craft elegant and concise scripts. |
Update historical dependency kinds as they may be wrong. | Can you generate a brief explanation for the following Python 3 code
def update_dependency_kinds(apps, schema_editor):
DataDependency = apps.get_model('flow', 'DataDependency')
for dependency in DataDependency.objects.all():
# Assume dependency is of subprocess kind.
dependency.kind = 'subproces... | You are a Python code architect, reviewing and designing scalable and efficient code |
Wrap a function to propagate exceptions as undefined values filter. | Given the following Python 3 function, write the documentation
def _wrap_jinja_filter(self, function):
def wrapper(*args, **kwargs):
"""Filter wrapper."""
try:
return function(*args, **kwargs)
except Exception: # pylint: disable=broad-except
r... | As a python code expert, you are capable of creating scripts from specifications. |
Register any custom filter modules. | Explain what the following Python 3 code does
def _register_custom_filters(self):
custom_filters = self.settings.get('CUSTOM_FILTERS', [])
if not isinstance(custom_filters, list):
raise KeyError("`CUSTOM_FILTERS` setting must be a list.")
for filter_module_name in custom_filters:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _evaluation_context(self, escape, safe_wrapper):
"""Configure the evaluation context."""
self._escape = escape
self._safe_wrapper = safe_wrapper
try:
yield
finally:
self._escape = None
self._safe_wrapper = None | Implement a Python 3 function for
configuring the evaluation context. | You are a Python code generator, capable of creating scripts from specifications. |
def evaluate_block(self, template, context=None, escape=None, safe_wrapper=None):
"""Evaluate a template block."""
if context is None:
context = {}
try:
with self._evaluation_context(escape, safe_wrapper):
template = self._environment.from_string(template... | Write a Python 3 function for
evaluating a template block. | As a Python code analyst, you investigate and solve complex coding mysteries |
Evaluate an inline expression. | Given the following Python 3 function, write the documentation
def evaluate_inline(self, expression, context=None, escape=None, safe_wrapper=None):
if context is None:
context = {}
try:
with self._evaluation_context(escape, safe_wrapper):
compiled = self._environ... | As a python code expert, you are capable of creating scripts from specifications. |
Update the module_path with the contents of the tree. | Explain what the following Python 3 code does
def update_module_file(redbaron_tree, module_path, show_diff=False, dry_run=False):
with tempfile.NamedTemporaryFile() as tmp_file:
tmp_file.write(redbaron_tree_to_module_str(redbaron_tree))
tmp_file.seek(0)
if are_files_equal(module_path, tmp_fi... | You are a Python code generator, capable of creating scripts from specifications. |
Given a path to an item in a git repository find the root of the repository. | Given the following Python 3 function, write the documentation
def find_repo_root_by_path(path):
repo = git.Repo(path, search_parent_directories=True)
repo_path = repo.git.rev_parse('--show-toplevel')
logging.info('Repository: {}'.format(repo_path))
return repo_path | As a Python code translator, you convert algorithms and pseudocode into Python. |
Format the value of the key in the operation. | Can you generate a brief explanation for the following Python 3 code
def _format_value(self, operation, key, indent):
v = self._find_value(operation, key)
if v == "NOT_FOUND":
return []
if not isinstance(v, list):
v = [v]
if not len(v):
v = [None]
... | As a Python code composer, you craft elegant and concise scripts. |
Add CORS headers to response. | Given the following Python 3 function, write the documentation
def add_cors_headers(response, request):
opt_method_list = ",".join(request.allowed_method_list + ["OPTIONS"])
response["Allow"] = opt_method_list
response["Access-Control-Allow-Methods"] = opt_method_list
response["Access-Control-Allow-Orig... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Run a new process from a running process. | Can you generate the documentation for the following Python 3 function
def run_process(self, slug, inputs):
def export_files(value):
"""Export input files of spawned process."""
if isinstance(value, str) and os.path.isfile(value):
# TODO: Use the protocol to export files ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_data_id_by_slug(self, slug):
"""Find data object ID for given slug.
This method queries the Resolwe API and requires network access.
"""
resolwe_host = os.environ.get('RESOLWE_HOST_URL')
url = urllib.parse.urljoin(resolwe_host, '/api/data?slug={}&fields=id'.format(slug))... | Create a Python 3 function to
find data object ID for given slug. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def requirements(self):
"""Process requirements."""
class dotdict(dict): # pylint: disable=invalid-name
"""Dot notation access to dictionary attributes."""
def __getattr__(self, attr):
value = self.get(attr)
return dotdict(value) if isinstance(va... | Implement a function in Python 3 to
return a dictionary of the requirements of the current object. | As a python code expert, you are capable of creating scripts from specifications. |
Start the process.
:param inputs: An instance of `Inputs` describing the process inputs
:return: An instance of `Outputs` describing the process outputs | Explain what the following Python 3 code does
def start(self, inputs):
self.logger.info("Process is starting")
outputs = Outputs(self._meta.outputs)
self.logger.info("Process is running")
try:
self.run(inputs.freeze(), outputs)
return outputs.freeze()
ex... | As a Python code composer, you craft elegant and concise scripts. |
def discover_process(self, path):
"""Perform process discovery in given path.
This method will be called during process registration and
should return a list of dictionaries with discovered process
schemas.
"""
if not path.lower().endswith('.py'):
return []
... | Write a Python 3 function that can
perform process discovery in given path and return a list of process schemas. | As a Python code analyst, you investigate and solve complex coding mysteries |
def evaluate(self, data):
"""Evaluate the code needed to compute a given Data object."""
return 'PYTHONPATH="{runtime}" python3 -u -m resolwe.process {program} --slug {slug} --inputs {inputs}'.format(
runtime=PYTHON_RUNTIME_VOLUME,
program=PYTHON_PROGRAM_VOLUME,
slug=... | Create a Python 3 function to
evaluate the code needed to compute a given Data object. | You are a Python code architect, reviewing and designing scalable and efficient code |
Prepare the runtime directory for the current process. | Given the following Python 3 function, write the documentation
def prepare_runtime(self, runtime_dir, data):
# Copy over Python process runtime (resolwe.process).
import resolwe.process as runtime_package
src_dir = os.path.dirname(inspect.getsourcefile(runtime_package))
dest_package_dir... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_subject_with_local_validation(jwt_bu64, cert_obj):
"""Validate the JWT and return the subject it contains.
- The JWT is validated by checking that it was signed with a CN certificate.
- The returned subject can be trusted for authz and authn operations.
- Possible validation errors include:
... | Create a Python 3 function to
validate the JWT and return the subject it contains. | As a Python code composer, you craft elegant and concise scripts. |
Same as get_subject_with_local_validation except that the signing certificate is downloaded from the CN and the certificate is downloaded from the root CN and the certificate is downloaded from the root CN. | Can you tell what is the following Python 3 function doing
def get_subject_with_remote_validation(jwt_bu64, base_url):
cert_obj = d1_common.cert.x509.download_as_obj(base_url)
return get_subject_with_local_validation(jwt_bu64, cert_obj) | As a Python code composer, you craft elegant and concise scripts. |
Same as get_subject_with_local_validation except that the signing certificate
is read from a local PEM file. | Can you generate the documentation for the following Python 3 function
def get_subject_with_file_validation(jwt_bu64, cert_path):
cert_obj = d1_common.cert.x509.deserialize_pem_file(cert_path)
return get_subject_with_local_validation(jwt_bu64, cert_obj) | You are a Python code generator, capable of creating scripts from specifications. |
Extract subject from the JWT without validating the JWT. | Can you tell what is the following Python 3 function doing
def get_subject_without_validation(jwt_bu64):
try:
jwt_dict = get_jwt_dict(jwt_bu64)
except JwtException as e:
return log_jwt_bu64_info(logging.error, str(e), jwt_bu64)
try:
return jwt_dict['sub']
except LookupError:
... | You are a Python code generator, capable of creating scripts from specifications. |
Parse Base64 encoded JWT and return as a dict. | Given the following Python 3 function, write the documentation
def get_jwt_dict(jwt_bu64):
jwt_tup = get_jwt_tup(jwt_bu64)
try:
jwt_dict = json.loads(jwt_tup[0].decode('utf-8'))
jwt_dict.update(json.loads(jwt_tup[1].decode('utf-8')))
jwt_dict['_sig_sha1'] = hashlib.sha1(jwt_tup[2]).hexdi... | You are a Python code architect, reviewing and designing scalable and efficient code |
Validate the JWT and return as a dict. | Make a summary of the following Python 3 code
def validate_and_decode(jwt_bu64, cert_obj):
try:
return jwt.decode(
jwt_bu64.strip(), cert_obj.public_key(), algorithms=['RS256'], verify=True
)
except jwt.InvalidTokenError as e:
raise JwtException('Signature is invalid. error="... | As a python code expert, you are capable of creating scripts from specifications. |
Dump the JWT dictionary to log. | Make a summary of the following Python 3 code
def log_jwt_dict_info(log, msg_str, jwt_dict):
d = ts_to_str(jwt_dict)
# Log known items in specific order, then the rest just sorted
log_list = [(b, d.pop(a)) for a, b, c in CLAIM_LIST if a in d] + [
(k, d[k]) for k in sorted(d)
]
list(
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def ts_to_str(jwt_dict):
"""Convert timestamps in JWT to human readable dates.
Args:
jwt_dict: dict
JWT with some keys containing timestamps.
Returns:
dict: Copy of input dict where timestamps have been replaced with human readable
dates.
"""
d = ts_to_dt(jwt_dict)
f... | Write a Python 3 script for
converting timestamps in JWT to human readable dates. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def ts_to_dt(jwt_dict):
"""Convert timestamps in JWT to datetime objects.
Args:
jwt_dict: dict
JWT with some keys containing timestamps.
Returns:
dict: Copy of input dict where timestamps have been replaced with
datetime.datetime() objects.
"""
d = jwt_dict.copy()
fo... | How would you implement a function in Python 3 that
converts timestamps in JWT to datetime objects. | You are a Python code generator, capable of creating scripts from specifications. |
Encode bytes to a URL safe Base64 used by JWTs. | Can you tell what is the following Python 3 function doing
def encode_bu64(b):
s = base64.standard_b64encode(b)
s = s.rstrip('=')
s = s.replace('+', '-')
s = s.replace('/', '_')
return s | You are a Python code generator, capable of creating scripts from specifications. |
Encode bytes to a URL safe flavor of Base64 used by JWTs. | Make a summary of the following Python 3 code
def decode_bu64(b):
s = b
s = s.replace(b'-', b'+')
s = s.replace(b'_', b'/')
p = len(s) % 4
if p == 0:
pass
elif p == 2:
s += b'=='
elif p == 3:
s += b'='
else:
raise ValueError('Illegal Base64url string')
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def evaluate(self, data):
"""Evaluate the code needed to compute a given Data object."""
try:
inputs = copy.deepcopy(data.input)
hydrate_input_references(inputs, data.process.input_schema)
hydrate_input_uploads(inputs, data.process.input_schema)
# Include... | Write a Python 3 script to
evaluate the code needed to compute a given Data object. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _escape(self, value):
"""Escape given value unless it is safe."""
if isinstance(value, SafeString):
return value
return shellescape.quote(value) | Write a Python 3 function that can
escape given value unless it is safe. | As a Python code analyst, you investigate and solve complex coding mysteries |
Open the file containing the Science Object bytes of pid in the default SciObj store. | Explain what the following Python 3 code does
def open_sciobj_file_by_pid_ctx(pid, write=False):
abs_path = get_abs_sciobj_file_path_by_pid(pid)
with open_sciobj_file_by_path_ctx(abs_path, write) as sciobj_file:
yield sciobj_file | As a python code expert, you are capable of creating scripts from specifications. |
def open_sciobj_file_by_path_ctx(abs_path, write=False):
"""Open the file containing the Science Object bytes at the custom location
``abs_path`` in the local filesystem.
If ``write`` is True, the file is opened for writing and any missing directores are
created. Return the file handle and file_url wit... | Can you write a function in Python 3 where it
opens the file containing the Science Object bytes at the custom locationabs_path in the local filesystem and return the file handle and file_url. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def open_sciobj_file_by_pid(pid, write=False):
"""Open the file containing the Science Object bytes at the custom location
``abs_path`` in the local filesystem for read."""
abs_path = get_abs_sciobj_file_path_by_pid(pid)
if write:
d1_common.utils.filesystem.create_missing_directories_for_file(ab... | Can you implement a function in Python 3 that
opens the Science Object file containing the Science Object bytes at the custom location . | As a python code expert, you are capable of creating scripts from specifications. |
Open a SciObj file for read or write. | Given the following Python 3 function, write the documentation
def open_sciobj_file_by_path(abs_path, write=False):
if write:
d1_common.utils.filesystem.create_missing_directories_for_file(abs_path)
return open(abs_path, 'wb' if write else 'rb') | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_rel_sciobj_file_path(pid):
"""Get the relative local path to the file holding an object's bytes.
- The path is relative to settings.OBJECT_STORE_PATH
- There is a one-to-one mapping between pid and path
- The path is based on a SHA1 hash. It's now possible to craft SHA1 collisions, but
it... | How would you code a function in Python 3 to
get the relative local path to the file holding an object. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get the absolute path to the file holding an object s bytes. | Make a summary of the following Python 3 code
def get_abs_sciobj_file_path_by_url(file_url):
assert_sciobj_store_exists()
m = re.match(r'file://(.*?)/(.*)', file_url, re.IGNORECASE)
if m.group(1) == RELATIVE_PATH_MAGIC_HOST_STR:
return os.path.join(get_abs_sciobj_store_path(), m.group(2))
assert... | As a python code expert, you are capable of creating scripts from specifications. |
Return the version currently running on a GMN instance. | How would you explain what the following Python 3 function does
def get_gmn_version(base_url):
home_url = d1_common.url.joinPathElements(base_url, 'home')
try:
response = requests.get(home_url, verify=False)
except requests.exceptions.ConnectionError as e:
return False, str(e)
if not re... | You are a Python code architect, reviewing and designing scalable and efficient code |
Extract a set of authenticated subjects from a SubjectInfo XML document and primary subject. | Can you generate the documentation for the following Python 3 function
def extract_subjects(subject_info_xml, primary_str):
subject_info_pyxb = deserialize_subject_info(subject_info_xml)
subject_info_tree = gen_subject_info_tree(subject_info_pyxb, primary_str)
return subject_info_tree.get_subject_set() | As a Python code translator, you convert algorithms and pseudocode into Python. |
Deserialize SubjectInfo XML doc to native object. | How would you explain what the following Python 3 function does
def deserialize_subject_info(subject_info_xml):
try:
return d1_common.xml.deserialize(subject_info_xml)
except ValueError as e:
raise d1_common.types.exceptions.InvalidToken(
0,
'Could not deserialize Subject... | As a Python code composer, you craft elegant and concise scripts. |
def gen_subject_info_tree(subject_info_pyxb, authn_subj, include_duplicates=False):
"""Convert the flat, self referential lists in the SubjectInfo to a tree structure.
Args:
subject_info_pyxb: SubjectInfo PyXB object
authn_subj: str
The authenticated subject that becomes the root s... | Implement a Python 3 function for
converting the flat self referential lists in the SubjectInfo PyXB object to a tree structure. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Trim empty leaf nodes from the tree. | Can you tell what is the following Python 3 function doing
def _trim_tree(state):
for n in list(state.tree.leaf_node_gen):
if n.type_str == TYPE_NODE_TAG:
n.parent.child_list.remove(n)
return _trim_tree(state) | As a python code expert, you are capable of creating scripts from specifications. |
Add a child node. | Can you generate a brief explanation for the following Python 3 code
def add_child(self, label_str, type_str):
child_node = SubjectInfoNode(label_str, type_str)
child_node.parent = self
self.child_list.append(child_node)
return child_node | You are a Python code generator, capable of creating scripts from specifications. |
def get_path_str(self, sep=os.path.sep, type_str=None):
"""Get path from root to this node.
Args:
sep: str
One or more characters to insert between each element in the path.
Defaults to "/" on Unix and "\" on Windows.
type_str:
SU... | Implement a Python 3 function for
getting path from root to this node. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get paths for all leaf nodes for the tree rooted at this node. | Here you have a function in Python 3, explain what it does
def get_leaf_node_path_list(self, sep=os.path.sep, type_str=None):
return [v.get_path_str(sep, type_str) for v in self.leaf_node_gen] | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_path_list(self, type_str=None):
"""Get list of the labels of the nodes leading up to this node from the root.
Args:
type_str:
SUBJECT_NODE_TAG, TYPE_NODE_TAG or None. If set, only include
information from nodes of that type.
Returns:
... | Can you implement a function in Python 3 that
gets list of the labels of the nodes leading up to this node from the root. | You are a Python code generator, capable of creating scripts from specifications. |
Returns a set of label_str for the tree rooted at this node. | Can you tell what is the following Python 3 function doing
def get_label_set(self, type_str=None):
return {v.label_str for v in self.node_gen if type_str in (None, v.type_str)} | You are a Python code architect, reviewing and designing scalable and efficient code |
Called when about to start processing a new type of task. | Can you generate the documentation for the following Python 3 function
def start_task_type(self, task_type_str, total_task_count):
assert (
task_type_str not in self._task_dict
), "Task type has already been started"
self._task_dict[task_type_str] = {
"start_time": time.t... | You are a Python code architect, reviewing and designing scalable and efficient code |
Called when processing of all tasks of the given type is complete. | Given the following Python 3 function, write the documentation
def end_task_type(self, task_type_str):
assert (
task_type_str in self._task_dict
), "Task type has not been started yet: {}".format(task_type_str)
self._log_progress()
del self._task_dict[task_type_str] | You are a Python code analyst, evaluating scripts for potential improvements. |
def start_task(self, task_type_str, current_task_index=None):
"""Call when processing is about to start on a single task of the given task
type, typically at the top inside of the loop that processes the tasks.
Args:
task_type_str (str):
The name of the task, used as... | Create a Python 3 function for
calling when processing is about to start on a single task of the given type. | You are a Python code generator, capable of creating scripts from specifications. |
def event(self, event_name):
"""Register an event that occurred during processing of a task of the given
type.
Args: event_name: str A name for a type of events. Events of the
same type are displayed as a single entry and a total count of
occurences.
... | How would you code a function in Python 3 to
register an event that occurred during processing of a task of the given type. | You are a Python code analyst, evaluating scripts for potential improvements. |
r Returns a list of sectors that are permitted to use in the given class. | Explain what the following Python 3 code does
def get_permissible_wcs(classname, f):
# these are the problematic sectors
classes = ['cu', 'db', 'sb', 'sd', 'mue', 'mutau', 'taue', 'dF0']
if classname not in classes or f == 5:
# for 5-flavour WET, nothing to do.
# Neither for other classes (I... | As a Python code composer, you craft elegant and concise scripts. |
Compute the eigenvalues and eigenvectors for a QCD anomalous dimension
matrix that is defined in adm. adm_s_X where X is the name of the sector. Output analogous to np. linalg. eigenvectors. | Can you generate the documentation for the following Python 3 function
def admeig(classname, f, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau):
args = f, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau
A = getattr(adm, 'adm_s_' + classname)(*args)
perm_keys = get_permissible_wcs(classname, f)
if perm_keys != 'all... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the QCD evolution matrix. | Explain what the following Python 3 code does
def getUs(classname, eta_s, f, alpha_s, alpha_e, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau):
w, v = admeig(classname, f, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau)
b0s = 11 - 2 * f / 3
a = w / (2 * b0s)
return v @ np.diag(eta_s**a) @ np.linalg.inv(v) | You are a Python code architect, reviewing and designing scalable and efficient code |
def getUe(classname, eta_s, f, alpha_s, alpha_e, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau):
"""Get the QCD evolution matrix."""
args = f, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau
A = getattr(adm, 'adm_e_' + classname)(*args)
perm_keys = get_permissible_wcs(classname, f)
if perm_keys != 'all':
... | Can you create a Python 3 function that
gets the QCD evolution matrix. | You are a Python code architect, reviewing and designing scalable and efficient code |
r Solve the WET RGE for a specific sector. | Here you have a function in Python 3, explain what it does
def run_sector(sector, C_in, eta_s, f, p_in, p_out, qed_order=1, qcd_order=1):
Cdictout = OrderedDict()
classname = sectors[sector]
keylist = coeffs[sector]
if sector == 'dF=0':
perm_keys = get_permissible_wcs('dF0', f)
else:
... | As a Python code composer, you craft elegant and concise scripts. |
Merge the tree of files in one tree into another tree. | How would you explain what the following Python 3 function does
def _merge_region_trees(self, dst_tree, src_tree, pid):
for k, v in list(src_tree.items()):
# Prepend an underscore to the administrative area names, to make them
# sort separately from the identifiers.
# k = '_'... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _get_region_tree_item_and_unconsumed_path(
self, region_tree, path, parent_key=''
):
"""Return the region_tree item specified by path. An item can be a a folder
(represented by a dictionary) or a PID (represented by None).
This function is also used for determining which section... | Create a Python 3 function for
returning the region_tree item specified by path. An item can be a a folder (represented by a dictionary) or a PID (represented by None). This function is also used for determining which section of a path is within the region tree and which section should be passed to the next resolver. T... | As a python code expert, you are 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.