output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def _post_query(self, **query_dict):
"""Perform a POST query against Solr and return the response as a Python
dict."""
param_dict = query_dict.copy()
return self._send_query(do_post=True, **param_dict) | Can you implement a function in Python 3 that
performs a POST query against Solr and return the response as a Python dict. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _send_query(self, do_post=False, **query_dict):
"""Perform a query against Solr and return the response as a Python dict."""
# self._prepare_query_term()
param_dict = query_dict.copy()
param_dict.setdefault('wt', 'json')
param_dict.setdefault('q', '*.*')
param_dict.se... | Implement a Python 3 function for
performing a query against Solr and return the response as a Python dict. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Prepare a query term for inclusion in a query. | Can you generate a brief explanation for the following Python 3 code
def _prepare_query_term(self, field, term):
if term == "*":
return term
add_star = False
if term[len(term) - 1] == '*':
add_star = True
term = term[0 : len(term) - 1]
term = self._esc... | You are a Python code generator, capable of creating scripts from specifications. |
def _escape_query_term(self, term):
"""Escape a query term for inclusion in a query.
- Also see: prepare_query_term().
"""
term = term.replace('\\', '\\\\')
for c in RESERVED_CHAR_LIST:
term = term.replace(c, r'\{}'.format(c))
return term | Create a Python 3 function to
escape a query term for inclusion in a query. | As a Python code composer, you craft elegant and concise scripts. |
def _next_page(self, offset):
"""Retrieves the next set of results from the service."""
self._log.debug("Iterator c_record={}".format(self.c_record))
page_size = self.page_size
if (offset + page_size) > self.max_records:
page_size = self.max_records - offset
param_dic... | Can you implement a function in Python 3 that
retrieves the next page of results from the service. | You are a Python code generator, capable of creating scripts from specifications. |
def _next_page(self, offset):
"""Retrieves the next set of results from the service."""
self._log.debug("Iterator c_record={}".format(self.c_record))
param_dict = self.query_dict.copy()
param_dict.update(
{
'rows': '0',
'facet': 'true',
... | How would you implement a function in Python 3 that
retrieves the next page of results from the service. | As a python code expert, you are capable of creating scripts from specifications. |
def migrate_flow_collection(apps, schema_editor):
"""Migrate 'flow_collection' field to 'entity_type'."""
Process = apps.get_model('flow', 'Process')
DescriptorSchema = apps.get_model('flow', 'DescriptorSchema')
for process in Process.objects.all():
process.entity_type = process.flow_collection... | Create a Python 3 function for
migrating flow_collection field to entity_type. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_pyxb_binding_by_api_version(api_major, api_minor=0):
"""Map DataONE API version tag to PyXB binding.
Given a DataONE API major version number, return PyXB binding that can
serialize and deserialize DataONE XML docs of that version.
Args:
api_major, api_minor: str or int
DataONE A... | How would you code a function in Python 3 to
map a DataONE API version tag to a PyXB binding. | You are a Python code analyst, evaluating scripts for potential improvements. |
def extract_version_tag_from_url(url):
"""Extract a DataONE API version tag from a MN or CN service endpoint URL.
Args:
url : str
Service endpoint URL. E.g.: ``https://mn.example.org/path/v2/object/pid``.
Returns:
str : Valid version tags are currently ``v1`` or ``v2``.
"""
m ... | Write a Python 3 script to
extract a DataONE API version tag from a MN or CN service endpoint URL. | You are a Python code architect, reviewing and designing scalable and efficient code |
Convert a API v2 XML doc to v1 XML doc. | Here you have a function in Python 3, explain what it does
def str_to_v1_str(xml_str):
if str_is_v1(xml_str):
return xml_str
etree_obj = str_to_etree(xml_str)
strip_v2_elements(etree_obj)
etree_replace_namespace(etree_obj, d1_common.types.dataoneTypes_v1.Namespace)
return etree_to_str(etree_... | As a Python code composer, you craft elegant and concise scripts. |
def str_to_v2_str(xml_str):
"""Convert a API v1 XML doc to v2 XML doc.
All v1 elements are valid for v2, so only changes namespace.
Args:
xml_str : str
API v1 XML doc. E.g.: ``SystemMetadata v1``.
Returns:
str : API v2 XML doc. E.g.: ``SystemMetadata v2``.
"""
if str_is_v... | Write a Python 3 script for
converting a API v1 XML doc to v2 XML doc. | As a Python code analyst, you investigate and solve complex coding mysteries |
def str_is_well_formed(xml_str):
"""
Args:
xml_str : str
DataONE API XML doc.
Returns:
bool: **True** if XML doc is well formed.
"""
try:
str_to_etree(xml_str)
except xml.etree.ElementTree.ParseError:
return False
else:
return True | Can you write a function in Python 3 where it
checks if the XML string is well formed. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns True if pyxb_obj holds an API v1 type. | Explain what the following Python 3 code does
def pyxb_is_v1(pyxb_obj):
# TODO: Will not detect v1.2 as v1.
return (
pyxb_obj._element().name().namespace()
== d1_common.types.dataoneTypes_v1.Namespace
) | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns True if pyxb_obj holds an API v2 type. | Given the following Python 3 function, write the documentation
def pyxb_is_v2(pyxb_obj):
return (
pyxb_obj._element().name().namespace()
== d1_common.types.dataoneTypes_v2_0.Namespace
) | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert XML tag names with namespace on the form ore : ResourceMap tag name with prefix. | Can you tell what is the following Python 3 function doing
def replace_namespace_with_prefix(tag_str, ns_reverse_dict=None):
ns_reverse_dict = ns_reverse_dict or NS_REVERSE_DICT
for namespace_str, prefix_str in ns_reverse_dict.items():
tag_str = tag_str.replace(
'{{{}}}'.format(namespace_str... | As a Python code composer, you craft elegant and concise scripts. |
In - place remove elements and attributes that are only valid in v2 types from v1SystemMetadata. | Can you generate the documentation for the following Python 3 function
def strip_system_metadata(etree_obj):
for series_id_el in etree_obj.findall('seriesId'):
etree_obj.remove(series_id_el)
for media_type_el in etree_obj.findall('mediaType'):
etree_obj.remove(media_type_el)
for file_name_el... | You are a Python code generator, capable of creating scripts from specifications. |
def _create_replica(self, sysmeta_pyxb, sciobj_bytestream):
"""GMN handles replicas differently from native objects, with the main
differences being related to handling of restrictions related to revision chains
and SIDs.
So this create sequence differs significantly from the regular on... | Create a Python 3 function for
creating a new replica from a sysmeta. pyxb and a sciobj bytestream. | As a Python code analyst, you investigate and solve complex coding mysteries |
async def restricted_import(self, async_client, node_type):
"""Import only the Science Objects specified by a text file.
The file must be UTF-8 encoded and contain one PIDs or SIDs per line.
"""
item_task_name = "Importing objects"
pid_path = self.options['pid_path']
i... | Implement a Python 3 function for
importing only the Science Objects specified by a text file. The file must be UTF-8 encoded and contain one PIDs or SIDs per line. | You are a Python code analyst, evaluating scripts for potential improvements. |
Imports the SciObj at pid. | Make a summary of the following Python 3 code
async def import_aggregated(self, async_client, pid):
self._logger.info('Importing: {}'.format(pid))
task_set = set()
object_info_pyxb = d1_common.types.dataoneTypes.ObjectInfo()
object_info_pyxb.identifier = pid
task_set.add(self.i... | As a Python code composer, you craft elegant and concise scripts. |
async def get_object_proxy_location(self, client, pid):
"""If object is proxied, return the proxy location URL.
If object is local, return None.
"""
try:
return (await client.describe(pid)).get("DataONE-Proxy")
except d1_common.types.exceptions.DataONEException:
... | Create a Python 3 function to
get the proxy location URL for an object. | You are a Python code generator, capable of creating scripts from specifications. |
def get_list_objects_arg_dict(self, node_type):
"""Create a dict of arguments that will be passed to listObjects().
If {node_type} is a CN, add filtering to include only objects from this GMN
instance in the ObjectList returned by CNCore.listObjects().
"""
arg_dict = {
... | Write a Python 3 script for
creating a dict of arguments that will be passed to listObjects. | As a Python code composer, you craft elegant and concise scripts. |
Create a dict of arguments that will be passed to getLogRecords. | Can you generate the documentation for the following Python 3 function
def get_log_records_arg_dict(self, node_type):
arg_dict = {
# Restrict query for faster debugging
# "fromDate": datetime.datetime(2017, 1, 1),
# "toDate": datetime.datetime(2017, 1, 3),
}
i... | You are a Python code generator, capable of creating scripts from specifications. |
async def is_cn(self, client):
"""Return True if node at {base_url} is a CN, False if it is an MN.
Raise a DataONEException if it's not a functional CN or MN.
"""
node_pyxb = await client.get_capabilities()
return d1_common.type_conversions.pyxb_get_type_name(node_pyxb) == "Nod... | Can you create a Python 3 function that
returns True if node at base_url is a CN False otherwise Raise a DataONEException | You are a Python code analyst, evaluating scripts for potential improvements. |
Determine if import source node is a CN or MN and which major version API to
use. | Explain what the following Python 3 code does
async def probe_node_type_major(self, client):
try:
node_pyxb = await self.get_node_doc(client)
except d1_common.types.exceptions.DataONEException as e:
raise django.core.management.base.CommandError(
"Could not find a... | As a python code expert, you are capable of creating scripts from specifications. |
Search NodeList for Node that has base_url.
Return matching Node or None | Given the following Python 3 function, write the documentation
def find_node(self, node_list_pyxb, base_url):
for node_pyxb in node_list_pyxb.node:
if node_pyxb.baseURL == base_url:
return node_pyxb | As a Python code analyst, you investigate and solve complex coding mysteries |
def find_node_api_version(self, node_pyxb):
"""Find the highest API major version supported by node."""
max_major = 0
for s in node_pyxb.services.service:
max_major = max(max_major, int(s.version[1:]))
return max_major | Implement a Python 3 function for
finding the highest API major version supported by node. | As a Python code composer, you craft elegant and concise scripts. |
def find_node_by_id(self, node_list_pyxb, node_id):
"""Search NodeList for Node with {node_id}.
Return matching Node or None
"""
for node_pyxb in node_list_pyxb.node:
# if node_pyxb.baseURL == base_url:
if d1_common.xml.get_req_val(node_pyxb.identifier) == node_... | Write a Python 3 script to
search NodeList for Node with id. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def celery_run(data_id, runtime_dir, argv):
"""Run process executor.
:param data_id: The id of the :class:`~resolwe.flow.models.Data`
object to be processed.
:param runtime_dir: The directory from which to run the executor.
:param argv: The argument vector used to run the executor.
:param v... | Create a Python 3 function for
running the celery process executor. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Set the status of an object to archived. | Can you generate the documentation for the following Python 3 function
def archive_sciobj(pid):
sciobj_model = d1_gmn.app.model_util.get_sci_model(pid)
sciobj_model.is_archived = True
sciobj_model.save()
_update_modified_timestamp(sciobj_model) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def create_or_update(sysmeta_pyxb, sciobj_url=None):
"""Create or update database representation of a System Metadata object and closely
related internal state.
- If ``sciobj_url`` is not passed on create, storage in the internal sciobj store
is assumed
- If ``sciobj_url`` is passed on create, it... | Can you create a Python 3 function that
creates or update a System Metadata object and closely related internal state. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _access_policy_pyxb_to_model(sci_model, sysmeta_pyxb):
"""Create or update the database representation of the sysmeta_pyxb access policy.
If called without an access policy, any existing permissions on the object
are removed and the access policy for the rights holder is recreated.
Preconditions:
... | Write a Python 3 script for
creating or update the database representation of sysmeta_pyxb access policy. | You are a Python code generator, capable of creating scripts from specifications. |
Adds command line arguments to the given parser. | How would you explain what the following Python 3 function does
def add_arguments(self, parser):
parser.description = __doc__
parser.formatter_class = argparse.RawDescriptionHelpFormatter
parser.add_argument("--debug", action="store_true", help="Debug level logging")
parser.add_argument(... | As a python code expert, you are capable of creating scripts from specifications. |
Create a log entry from a log record. | How would you explain what the following Python 3 function does
def _create_log_entry(self, log_record_pyxb):
event_log_model = d1_gmn.app.event_log.create_log_entry(
d1_gmn.app.model_util.get_sci_model(
d1_common.xml.get_req_val(log_record_pyxb.identifier)
),
... | You are a Python code generator, capable of creating scripts from specifications. |
def _download_source_sciobj_bytes_to_store(self, client, pid):
"""Args:
client: pid:
"""
if d1_gmn.app.sciobj_store.is_existing_sciobj_file(pid):
self._events.log_and_count(
"Skipped download of existing sciobj bytes", 'pid="{}"'.format(pid)
)
... | Write a Python 3 script for
downloading bytes from the source Science Object store to the store. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Checks that the path is a directory. | How would you explain what the following Python 3 function does
def _assert_path_is_dir(self, dir_path):
if not os.path.isdir(dir_path):
raise django.core.management.base.CommandError(
'Invalid dir path. path="{}"'.format(dir_path)
) | You are a Python code analyst, evaluating scripts for potential improvements. |
Send a HEAD request. See requests. request for optional parameters. | Make a summary of the following Python 3 code
def HEAD(self, rest_path_list, **kwargs):
kwargs.setdefault("allow_redirects", False)
return self._request("HEAD", rest_path_list, **kwargs) | You are a Python code analyst, evaluating scripts for potential improvements. |
def POST(self, rest_path_list, **kwargs):
"""Send a POST request with optional streaming multipart encoding. See
requests.sessions.request for optional parameters. To post regular data, pass a
string, iterator or generator as the ``data`` argument. To post a multipart
stream, pass a dict... | Write a Python 3 script for
sending a POST request to the specified path list. | As a Python code analyst, you investigate and solve complex coding mysteries |
Send a PUT request with optional streaming multipart encoding. See post for optional parameters. | Can you generate the documentation for the following Python 3 function
def PUT(self, rest_path_list, **kwargs):
fields = kwargs.pop("fields", None)
if fields is not None:
return self._send_mmp_stream("PUT", rest_path_list, fields, **kwargs)
else:
return self._request("PUT... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_curl_command_line(self, method, url, **kwargs):
"""Get request as cURL command line for debugging."""
if kwargs.get("query"):
url = "{}?{}".format(url, d1_common.url.urlencode(kwargs["query"]))
curl_list = ["curl"]
if method.lower() == "head":
curl_list.ap... | Can you create a Python 3 function that
gets request as cURL command line for debugging. | You are a Python code architect, reviewing and designing scalable and efficient code |
def dump_request_and_response(self, response):
"""Return a string containing a nicely formatted representation of the request
and response objects for logging and debugging.
- Note: Does not work if the request or response body is a MultipartEncoder
object.
"""
if res... | Write a Python 3 script to
dump the request and response objects for logging and debugging. | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert timeout to float. | Can you generate the documentation for the following Python 3 function
def _timeout_to_float(self, timeout):
if timeout is not None:
try:
timeout_float = float(timeout)
except ValueError:
raise ValueError(
'timeout_sec must be a valid n... | You are a Python code analyst, evaluating scripts for potential improvements. |
def main():
"""Print the RedBaron syntax tree for a Python module."""
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("path", help="Python module path")
args = parser.parse_args()
r = d1_dev.util.redbaron_... | Write a Python 3 script for
printing the RedBaron syntax tree for a Python module. | As a Python code analyst, you investigate and solve complex coding mysteries |
def abs_path_from_base(base_path, rel_path):
"""Join a base and a relative path and return an absolute path to the resulting
location.
Args:
base_path: str
Relative or absolute path to prepend to ``rel_path``.
rel_path: str
Path relative to the location of the module file from ... | How would you implement a function in Python 3 that
joins a base and a relative path and return an absolute path to the resulting location. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def abs_path(rel_path):
"""Convert a path that is relative to the module from which this function is called,
to an absolute path.
Args:
rel_path: str
Path relative to the location of the module file from which this function is called.
Returns:
str : Absolute path to the location ... | Can you write a function in Python 3 where it
converts a path that is relative to the module file from which this function is called to an absolute path. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_xml(self, encoding='unicode'):
"""Returns:
str : Current state of the wrapper as XML
"""
return xml.etree.ElementTree.tostring(self._root_el, encoding) | Write a Python 3 script to
return the current state of the wrapper as XML | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the current state of the wrapper as a pretty printed XML string. | Explain what the following Python 3 code does
def get_pretty_xml(self, encoding='unicode'):
return d1_common.xml.reformat_to_pretty_xml(
xml.etree.ElementTree.tostring(self._root_el, encoding)
) | You are a Python code generator, capable of creating scripts from specifications. |
Returns the XML fragment rooted at el_name below el_idx. | Can you generate a brief explanation for the following Python 3 code
def get_xml_below_element(self, el_name, el_idx=0, encoding='unicode'):
return xml.etree.ElementTree.tostring(
self.get_element_by_name(el_name, el_idx), encoding
) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the list of elements matching xpath_str. | Explain what the following Python 3 code does
def get_element_by_xpath(self, xpath_str, namespaces=None):
try:
return self._root_el.findall('.' + xpath_str, namespaces)
except (ValueError, xml.etree.ElementTree.ParseError) as e:
raise SimpleXMLWrapperException(
'X... | You are a Python code generator, capable of creating scripts from specifications. |
Returns the element with the specified name. | Given the following Python 3 function, write the documentation
def get_element_by_name(self, el_name, el_idx=0):
el_list = self.get_element_list_by_name(el_name)
try:
return el_list[el_idx]
except IndexError:
raise SimpleXMLWrapperException(
'Element not f... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the element with the specified attribute key. | Can you tell what is the following Python 3 function doing
def get_element_by_attr_key(self, attr_key, el_idx=0):
el_list = self.get_element_list_by_attr_key(attr_key)
try:
return el_list[el_idx]
except IndexError:
raise SimpleXMLWrapperException(
'Element... | You are a Python code architect, reviewing and designing scalable and efficient code |
def set_element_text(self, el_name, el_text, el_idx=0):
"""
Args:
el_name : str
Name of element to update.
el_text : str
Text to set for element.
el_idx : int
Index of element to use in the event that there are multiple sibling
elements with the same name.... | Implement a Python 3 function for
updating the text of the element with the given name. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def set_element_text_by_attr_key(self, attr_key, el_text, el_idx=0):
"""
Args:
attr_key : str
Name of attribute for which to search
el_text : str
Text to set for element.
el_idx : int
Index of element to use in the event that there are multiple sibling
ele... | Create a Python 3 function for
setting the text of the element with the given attribute key. | You are a Python code generator, capable of creating scripts from specifications. |
Return the value of the selected attribute in the selected element. | Can you tell what is the following Python 3 function doing
def get_attr_value(self, attr_key, el_idx=0):
return self.get_element_by_attr_key(attr_key, el_idx).attrib[attr_key] | As a python code expert, you are capable of creating scripts from specifications. |
Set the value of the selected attribute of the selected element. | Can you generate the documentation for the following Python 3 function
def set_attr_text(self, attr_key, attr_val, el_idx=0):
self.get_element_by_attr_key(attr_key, el_idx).attrib[attr_key] = attr_val | As a Python code composer, you craft elegant and concise scripts. |
def get_element_dt(self, el_name, tz=None, el_idx=0):
"""Return the text of the selected element as a ``datetime.datetime`` object.
The element text must be a ISO8601 formatted datetime
Args:
el_name : str
Name of element to use.
tz : datetime.tzinfo
... | Implement a function in Python 3 to
return the text of the selected element as a datetime. datetime object. | You are a Python code analyst, evaluating scripts for potential improvements. |
def set_element_dt(self, el_name, dt, tz=None, el_idx=0):
"""Set the text of the selected element to an ISO8601 formatted datetime.
Args:
el_name : str
Name of element to update.
dt : datetime.datetime
Date and time to set
tz : datetime.tzinfo
... | Can you implement a function in Python 3 that
sets the text of the selected element to an ISO8601 formatted datetime. | As a python code expert, you are capable of creating scripts from specifications. |
def replace_by_etree(self, root_el, el_idx=0):
"""Replace element.
Select element that has the same name as ``root_el``, then replace the selected
element with ``root_el``
``root_el`` can be a single element or the root of an element tree.
Args:
root_el : element
... | Create a Python 3 function to
replace element. with a new element with the root_el. | As a Python code analyst, you investigate and solve complex coding mysteries |
Replace element.
Arc with xml_str | Here you have a function in Python 3, explain what it does
def replace_by_xml(self, xml_str, el_idx=0):
root_el = self.parse_xml(xml_str)
self.replace_by_etree(root_el, el_idx) | You are a Python code generator, capable of creating scripts from specifications. |
def as_sql(self, compiler, connection): # pylint: disable=arguments-differ
"""Compile SQL for this function."""
sql, params = super().as_sql(compiler, connection)
params.append(self.path)
return sql, params | Implement a function in Python 3 to
compile SQL for this function. | You are a Python code analyst, evaluating scripts for potential improvements. |
Annotate Storage objects with a specific JSON path. | Make a summary of the following Python 3 code
def with_json_path(self, path, field=None):
if field is None:
field = '_'.join(['json'] + json_path_components(path))
kwargs = {field: JsonGetPath('json', path)}
return self.defer('json').annotate(**kwargs) | As a Python code analyst, you investigate and solve complex coding mysteries |
Return only a specific JSON path of the object. | Can you tell what is the following Python 3 function doing
def get_json_path(self, path):
return self.with_json_path(path, field='result').values_list('result', flat=True) | You are a Python code analyst, evaluating scripts for potential improvements. |
def _get_storage(self):
"""Load `json` field from `Storage` object."""
if self._json is None:
self._json = Storage.objects.get(**self._kwargs).json | Can you implement a function in Python 3 that
loads json field from Storage object. | You are a Python code analyst, evaluating scripts for potential improvements. |
def migrate_process_schema(self, process, schema, from_state):
"""Migrate process schema.
:param process: Process instance
:param schema: Process schema to migrate
:param from_state: Database model state
:return: True if the process was migrated, False otherwise
"""
... | Write a Python 3 function for
migrating process schema. :param process: Process instance :param schema: Process schema to migrate :param from_state: Database model state :return: True if the process was migrated, False otherwise | You are a Python code architect, reviewing and designing scalable and efficient code |
Migrate data objects.
:param data: Queryset containing all data objects that need
to be migrated
:param from_state: Database model state | How would you explain what the following Python 3 function does
def migrate_data(self, data, from_state):
if not self.default:
return
self.default.prepare(data, from_state)
for instance in data:
value = self.default.get_default_for(instance, from_state)
if no... | As a Python code analyst, you investigate and solve complex coding mysteries |
Migrate the process schema. | Given the following Python 3 function, write the documentation
def migrate_process_schema(self, process, schema, from_state):
container = dict_dot(schema, '.'.join(self.field[:-1]), default=list)
# Ignore processes, which already contain the target field.
migrate = False
for field in co... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Migrate data objects.
:param data: Queryset containing all data objects that need
to be migrated
:param from_state: Database model state | Here you have a function in Python 3, explain what it does
def migrate_data(self, data, from_state):
for instance in data:
if instance.status == 'ER':
continue
container = getattr(instance, self.schema_type, {})
schema = container.pop(self.field[-1])
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Migrate process instance to new schema. | Can you tell what is the following Python 3 function doing
def migrate_process_schema(self, process, schema, from_state):
if process.type == self.new_type:
return False
process.type = self.new_type
return True | You are a Python code analyst, evaluating scripts for potential improvements. |
def home(request):
"""Home page.
Root of web server should redirect to here.
"""
if request.path.endswith('/'):
return django.http.HttpResponseRedirect(request.path[:-1])
return django.http.HttpResponse(
generate_status_xml(), d1_common.const.CONTENT_TYPE_XML
) | Can you write a function in Python 3 where it
homes page. Root of web server should redirect to here. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Handle 404s outside of the valid API URL endpoints. | Given the following Python 3 function, write the documentation
def error_404(request, exception):
return django.http.HttpResponseNotFound(
d1_common.types.exceptions.NotFound(
0,
'Invalid API endpoint',
# Include the regexes the URL was tested against
# traceI... | As a Python code composer, you craft elegant and concise scripts. |
def get_obj_store_free_space_bytes():
"""Return total free space available on the disk on which the object storage resides
(in bytes)"""
obj_store_path = django.conf.settings.OBJECT_STORE_PATH
if platform.system() == 'Windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.Ge... | Can you create a Python 3 function that
returns the total free space on the object storage on which the object storage resides ( in bytes | As a python code expert, you are capable of creating scripts from specifications. |
Function to numerically determine the physical Higgs VEV and mass
given the parameters of the Higgs potential. | Can you tell what is the following Python 3 function doing
def m2Lambda_to_vMh2(m2, Lambda, C):
try:
v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) /
(sqrt(2) * Lambda**(5 / 2)) * C['phi'])
except ValueError:
v = 0
Mh2 = 2 * m2 * (1 - m2 / Lambda * (3 * C['phi'] - 4 * Lambda * C['... | You are a Python code analyst, evaluating scripts for potential improvements. |
def vMh2_to_m2Lambda(v, Mh2, C):
"""Function to numerically determine the parameters of the Higgs potential
given the physical Higgs VEV and mass."""
if C['phi'] == 0 and C['phiBox'] == 0 and C['phiD'] == 0:
return _vMh2_to_m2Lambda_SM(v, Mh2)
else:
def f0(x): # we want the root of this... | Write a Python 3 script for
functioning to numerically determine the parameters of the Higgs potential given the physical Higgs VEV and mass. | As a python code expert, you are capable of creating scripts from specifications. |
Get the running parameters in SMEFT. | How would you explain what the following Python 3 function does
def smeftpar(scale, C, basis):
# start with a zero dict and update it with the input values
MW = p['m_W']
# MZ = p['m_Z']
GF = p['GF']
Mh = p['m_h']
vb = sqrt(1 / sqrt(2) / GF)
v = vb # TODO
_d = vMh2_to_m2Lambda(v=v, Mh2=M... | As a Python code composer, you craft elegant and concise scripts. |
def smpar(C):
"""Get the running effective SM parameters."""
m2 = C['m2'].real
Lambda = C['Lambda'].real
v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) /
(sqrt(2) * Lambda**(5 / 2)) * C['phi'])
GF = 1 / (sqrt(2) * v**2) # TODO
Mh2 = 2 * m2 * (1 - m2 / Lambda * (3 * C['phi'] - 4 * Lambda ... | Write a Python 3 script for
returning the running effective SM parameters. | You are a Python code generator, capable of creating scripts from specifications. |
Translations necessary for class - 8 coefficients
to go from a basis with only non - redundant WCxf
operators to a basis where the Wilson coefficients are symmetrized like
the operators are not symmetric | Can you generate a brief explanation for the following Python 3 code
def scale_8(b):
a = np.array(b, copy=True, dtype=complex)
for i in range(3):
a[0, 0, 1, i] = 1/2 * b[0, 0, 1, i]
a[0, 0, 2, i] = 1/2 * b[0, 0, 2, i]
a[0, 1, 1, i] = 1/2 * b[0, 1, 1, i]
a[0, 1, 2, i] = 2/3 * b[0,... | As a python code expert, you are capable of creating scripts from specifications. |
def arrays2wcxf(C):
"""Convert a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values to a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values. This is needed for the output in WCxf format."""
d = {}
... | Write a Python 3 script for
converting a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values to a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values. This is needed for the output in WCxf format. | As a python code expert, you are capable of creating scripts from specifications. |
Convert a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as arrays as values. This is needed for parsing a Wilson coefficient tree in WCxf format. | Can you generate the documentation for the following Python 3 function
def wcxf2arrays(d):
C = {}
for k, v in d.items():
name = k.split('_')[0]
s = C_keys_shape[name]
if s == 1:
C[k] = v
else:
ind = k.split('_')[-1]
if name not in C:
... | You are a Python code generator, capable of creating scripts from specifications. |
def add_missing(C):
"""Add arrays with zeros for missing Wilson coefficient keys"""
C_out = C.copy()
for k in (set(WC_keys) - set(C.keys())):
C_out[k] = np.zeros(C_keys_shape[k])
return C_out | How would you code a function in Python 3 to
add arrays with zeros for missing Wilson coefficient keys | You are a Python code generator, capable of creating scripts from specifications. |
def C_array2dict(C):
"""Convert a 1D array containing C values to a dictionary."""
d = OrderedDict()
i=0
for k in C_keys:
s = C_keys_shape[k]
if s == 1:
j = i+1
d[k] = C[i]
else:
j = i \
+ reduce(operator.mul, s, 1)
d[k] = C[i... | Write a Python 3 script to
convert a 1D array containing C values to a dictionary. | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert an OrderedDict containing C values to a 1D array. | Given the following Python 3 function, write the documentation
def C_dict2array(C):
return np.hstack([np.asarray(C[k]).ravel() for k in C_keys]) | You are a Python code architect, reviewing and designing scalable and efficient code |
This function takes into account the symmetry factors
that occur when transitioning from a basis with only non - redundant operators and the Wilson coefficients are symmetrized
. | Make a summary of the following Python 3 code
def symmetrize_nonred(C):
C_symm = {}
for i, v in C.items():
if i in C_symm_keys[0]:
C_symm[i] = v.real
elif i in C_symm_keys[1] + C_symm_keys[3]:
C_symm[i] = v # nothing to do
elif i in C_symm_keys[2]:
C_s... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Undo the scaling applied in scale_dict. | Given the following Python 3 function, write the documentation
def unscale_dict(C):
C_out = {k: _scale_dict[k] * v for k, v in C.items()}
for k in C_symm_keys[8]:
C_out['qqql'] = unscale_8(C_out['qqql'])
return C_out | As a python code expert, you are capable of creating scripts from specifications. |
Convert a dictionary with a Wilson coefficient name followed by underscore numeric indices as keys and numbers as values and numpy arrays as values. | Explain what the following Python 3 code does
def wcxf2arrays_symmetrized(d):
C = wcxf2arrays(d)
C = symmetrize_nonred(C)
C = add_missing(C)
return C | You are a Python code architect, reviewing and designing scalable and efficient code |
def commit_signal(data_id):
"""Nudge manager at the end of every Data object save event."""
if not getattr(settings, 'FLOW_MANAGER_DISABLE_AUTO_CALLS', False):
immediate = getattr(settings, 'FLOW_MANAGER_SYNC_AUTO_CALLS', False)
async_to_sync(manager.communicate)(data_id=data_id, save_settings=F... | Implement a Python 3 function for
nudging manager at the end of every Data object save event. | You are a Python code analyst, evaluating scripts for potential improvements. |
def manager_post_save_handler(sender, instance, created, **kwargs):
"""Run newly created (spawned) processes."""
if instance.status == Data.STATUS_DONE or instance.status == Data.STATUS_ERROR or created:
# Run manager at the end of the potential transaction. Otherwise
# tasks are send to workers... | How would you implement a function in Python 3 that
calls when a new process is created. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def delete_entity(sender, instance, **kwargs):
"""Delete Entity when last Data object is deleted."""
# 1 means that the last Data object is going to be deleted.
Entity.objects.annotate(num_data=Count('data')).filter(data=instance, num_data=1).delete() | Create a Python 3 function to
delete Entity when last Data object is deleted. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Delete the relation when the last Entity is removed. | Here you have a function in Python 3, explain what it does
def delete_relation(sender, instance, **kwargs):
def process_signal(relation_id):
"""Get the relation and delete it if it has no entities left."""
try:
relation = Relation.objects.get(pk=relation_id)
except Relation.DoesN... | As a Python code translator, you convert algorithms and pseudocode into Python. |
async def run_executor():
"""Start the actual execution; instantiate the executor and run."""
parser = argparse.ArgumentParser(description="Run the specified executor.")
parser.add_argument('module', help="The module from which to instantiate the concrete executor.")
args = parser.parse_args()
modu... | Create a Python 3 function to
start the actual execution ; instantiate the executor and run. | As a Python code composer, you craft elegant and concise scripts. |
def assert_valid(sysmeta_pyxb, pid):
"""Validate file at {sciobj_path} against schema selected via formatId and raise
InvalidRequest if invalid.
Validation is only performed when:
- SciMeta validation is enabled
- and Object size is below size limit for validation
- and formatId designates obj... | How would you code a function in Python 3 to
validate file at sysmeta_pyxb against schema selected via formatId and raise InvalidRequest if invalid. | As a Python code analyst, you investigate and solve complex coding mysteries |
def to_internal_value(self, data):
"""Convert to internal value."""
user = getattr(self.context.get('request'), 'user')
queryset = self.get_queryset()
permission = get_full_perm('view', queryset.model)
try:
return get_objects_for_user(
user,
... | Can you write a function in Python 3 where it
converts to internal value. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Dump the dict to DynamoDB format. | Here you have a function in Python 3, explain what it does
def dumps(dct, as_dict=False, **kwargs):
result_ = TypeSerializer().serialize(json.loads(json.dumps(dct, default=json_serial),
use_decimal=True))
if as_dict:
return next(six.iteritems(result_)... | As a Python code analyst, you investigate and solve complex coding mysteries |
def loads(s, as_dict=False, *args, **kwargs):
""" Loads dynamodb json format to a python dict.
:param s - the json string or dict (with the as_dict variable set to True) to convert
:returns python dict object
"""
if as_dict or (not isinstance(s, six.string_types)):
s = json.dumps(s)
... | Can you implement a function in Python 3 that
loads dynamodb json format to a python dict | You are a Python code analyst, evaluating scripts for potential improvements. |
def tileSize(self, zoom):
"Returns the size (in meters) of a tile"
assert zoom in range(0, len(self.RESOLUTIONS))
return self.tileSizePx * self.RESOLUTIONS[int(zoom)] | Write a Python 3 function for
returning the size ( in meters ) of a tile | As a Python code composer, you craft elegant and concise scripts. |
def tileBounds(self, zoom, tileCol, tileRow):
"Returns the bounds of a tile in LV03 (EPSG:21781)"
assert zoom in range(0, len(self.RESOLUTIONS))
# 0,0 at top left: y axis down and x axis right
tileSize = self.tileSize(zoom)
minX = self.MINX + tileCol * tileSize
maxX = se... | Write a Python 3 script for
returning the bounds of a tile in LV03 ( EPSG : 21781 ) | You are a Python code analyst, evaluating scripts for potential improvements. |
def tileAddress(self, zoom, point):
"Returns a tile address based on a zoom level and \
a point in the tile"
[x, y] = point
assert x <= self.MAXX and x >= self.MINX
assert y <= self.MAXY and y >= self.MINY
assert zoom in range(0, len(self.RESOLUTIONS))
tileS = se... | Can you create a Python 3 function that
returns a tile address based on a zoom level and \ a point in the tile | You are a Python code architect, reviewing and designing scalable and efficient code |
def intersectsExtent(self, extent):
"Determine if an extent intersects this instance extent"
return \
self.extent[0] <= extent[2] and self.extent[2] >= extent[0] and \
self.extent[1] <= extent[3] and self.extent[3] >= extent[1] | Create a Python 3 function for
determining if an extent intersects this instance extent | You are a Python code architect, reviewing and designing scalable and efficient code |
def iterGrid(self, minZoom, maxZoom):
"Yields the tileBounds, zoom, tileCol and tileRow"
assert minZoom in range(0, len(self.RESOLUTIONS))
assert maxZoom in range(0, len(self.RESOLUTIONS))
assert minZoom <= maxZoom
for zoom in xrange(minZoom, maxZoom + 1):
[minRow, m... | Create a Python 3 function to
yield the tileBounds zoom tileCol and tileRow | As a Python code translator, you convert algorithms and pseudocode into Python. |
def numberOfXTilesAtZoom(self, zoom):
"Returns the number of tiles over x at a given zoom level"
[minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom)
return maxCol - minCol + 1 | Can you implement a function in Python 3 that
returns the number of tiles over x at a given zoom level | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the total number of tile at a given zoom level | Here you have a function in Python 3, explain what it does
def numberOfTilesAtZoom(self, zoom):
"Returns the total number of tile at a given zoom level"
[minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom)
return (maxCol - minCol + 1) * (maxRow - minRow + 1) | As a python code expert, you are capable of creating scripts from specifications. |
def totalNumberOfTiles(self, minZoom=None, maxZoom=None):
"Return the total number of tiles for this instance extent"
nbTiles = 0
minZoom = minZoom or 0
if maxZoom:
maxZoom = maxZoom + 1
else:
maxZoom = len(self.RESOLUTIONS)
for zoom in xrange(minZ... | Can you write a function in Python 3 where it
returns the total number of tiles for this instance extent | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.