output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
MNStorage.update(session, pid, object, newPid, sysmeta) → Identifier. | Explain what the following Python 3 code does
def put_object(request, old_pid):
if django.conf.settings.REQUIRE_WHITELIST_FOR_UPDATE:
d1_gmn.app.auth.assert_create_update_delete_permission(request)
d1_gmn.app.util.coerce_put_post(request)
d1_gmn.app.views.assert_db.post_has_mime_parts(
reque... | As a Python code composer, you craft elegant and concise scripts. |
Generate identifier for the current post. | Explain what the following Python 3 code does
def post_generate_identifier(request):
d1_gmn.app.views.assert_db.post_has_mime_parts(request, (('field', 'scheme'),))
if request.POST['scheme'] != 'UUID':
raise d1_common.types.exceptions.InvalidRequest(
0, 'Only the UUID scheme is currently sup... | As a Python code analyst, you investigate and solve complex coding mysteries |
MNReplication. replicate - Replicates the sourceNode. | Explain what the following Python 3 code does
def post_replicate(request):
d1_gmn.app.views.assert_db.post_has_mime_parts(
request, (('field', 'sourceNode'), ('file', 'sysmeta'))
)
sysmeta_pyxb = d1_gmn.app.sysmeta.deserialize(request.FILES['sysmeta'])
d1_gmn.app.local_replica.assert_request_com... | As a Python code analyst, you investigate and solve complex coding mysteries |
def contribute_to_class(self, process, fields, name):
"""Register this field with a specific process.
:param process: Process descriptor instance
:param fields: Fields registry to use
:param name: Field name
"""
self.name = name
self.process = process
fie... | Can you write a function in Python 3 where it
registers this field with a specific process. | As a Python code composer, you craft elegant and concise scripts. |
def to_schema(self):
"""Return field schema for this field."""
if not self.name or not self.process:
raise ValueError("field is not registered with process")
schema = {
'name': self.name,
'type': self.get_field_type(),
}
if self.required is no... | Can you create a Python 3 function that
returns a dictionary that represents this field. | As a Python code composer, you craft elegant and concise scripts. |
Run validators and return the clean value. | Given the following Python 3 function, write the documentation
def clean(self, value):
if value is None:
value = self.default
try:
value = self.to_python(value)
self.validate(value)
except ValidationError as error:
raise ValidationError("invalid v... | As a python code expert, you are capable of creating scripts from specifications. |
Convert value to process output format. | Given the following Python 3 function, write the documentation
def to_output(self, value):
return json.loads(resolwe_runtime_utils.save(self.name, str(value))) | As a Python code composer, you craft elegant and concise scripts. |
def to_python(self, value):
"""Convert value if needed."""
if isinstance(value, str):
return value
elif isinstance(value, dict):
try:
value = value['url']
except KeyError:
raise ValidationError("dictionary must contain an 'url' ... | Can you write a function in Python 3 where it
converts value if needed. | You are a Python code generator, capable of creating scripts from specifications. |
def import_file(self, imported_format=None, progress_from=0.0, progress_to=None):
"""Import field source file to working directory.
:param imported_format: Import file format (extracted, compressed or both)
:param progress_from: Initial progress value
:param progress_to: Final progress ... | Can you write a function in Python 3 where it
imports the file into the working directory. | As a python code expert, you are capable of creating scripts from specifications. |
def to_python(self, value):
"""Convert value if needed."""
if isinstance(value, FileDescriptor):
return value
elif isinstance(value, str):
return FileDescriptor(value)
elif isinstance(value, dict):
try:
path = value['file']
... | Implement a function in Python 3 to
convert value if needed. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def to_output(self, value):
"""Convert value to process output format."""
return json.loads(resolwe_runtime_utils.save_file(self.name, value.path, *value.refs)) | Write a Python 3 script to
convert value to process output format. | As a Python code composer, you craft elegant and concise scripts. |
def to_python(self, value):
"""Convert value if needed."""
if isinstance(value, DirDescriptor):
return value
elif isinstance(value, str):
return DirDescriptor(value)
elif isinstance(value, dict):
try:
path = value['dir']
exc... | How would you implement a function in Python 3 that
converts value if needed. | You are a Python code analyst, evaluating scripts for potential improvements. |
def contribute_to_class(self, process, fields, name):
"""Register this field with a specific process.
:param process: Process descriptor instance
:param fields: Fields registry to use
:param name: Field name
"""
super().contribute_to_class(process, fields, name)
... | Can you write a function in Python 3 where it
registers this field with a specific process. | You are a Python code analyst, evaluating scripts for potential improvements. |
def to_output(self, value):
"""Convert value to process output format."""
return {self.name: [self.inner.to_output(v)[self.name] for v in value]} | Can you write a function in Python 3 where it
converts value to process output format. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return given key from cache. | Given the following Python 3 function, write the documentation
def _get(self, key):
self._populate_cache()
if key not in self._cache:
raise AttributeError("DataField has no member {}".format(key))
return self._cache[key] | As a Python code analyst, you investigate and solve complex coding mysteries |
def to_python(self, value):
"""Convert value if needed."""
cache = None
if value is None:
return None
if isinstance(value, DataDescriptor):
return value
elif isinstance(value, dict):
# Allow pre-hydrated data objects.
cache = value... | Write a Python 3 script for
converting value if needed. | You are a Python code analyst, evaluating scripts for potential improvements. |
Register this field with a specific process. | How would you explain what the following Python 3 function does
def contribute_to_class(self, process, fields, name):
# Use order-preserving definition namespace (__dict__) to respect the
# order of GroupField's fields definition.
for field_name in self.field_group.__dict__:
if field... | You are a Python code architect, reviewing and designing scalable and efficient code |
def to_python(self, value):
"""Convert value if needed."""
if isinstance(value, GroupDescriptor):
value = value._value # pylint: disable=protected-access
result = {}
for name, field in self.fields.items():
result[name] = field.to_python(value.get(name, None))
... | Create a Python 3 function to
convert value if needed. | As a Python code composer, you craft elegant and concise scripts. |
Return field schema for this field. | How would you explain what the following Python 3 function does
def to_schema(self):
schema = super().to_schema()
if self.disabled is not None:
schema['disabled'] = self.disabled
if self.collapsed is not None:
schema['collapsed'] = self.collapsed
group = []
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Recreate channel name constants with changed settings. | Given the following Python 3 function, write the documentation
def update_constants():
global MANAGER_CONTROL_CHANNEL, MANAGER_EXECUTOR_CHANNELS # pylint: disable=global-statement
global MANAGER_LISTENER_STATS, MANAGER_STATE_PREFIX # pylint: disable=global-statement
redis_prefix = getattr(settings, 'FLOW_... | As a python code expert, you are capable of creating scripts from specifications. |
Destroy Redis channels managed by this state instance. | Can you tell what is the following Python 3 function doing
def destroy_channels(self):
for item_name in dir(self):
item = getattr(self, item_name)
if isinstance(item, self.RedisAtomicBase):
self.redis.delete(item.item_name) | You are a Python code architect, reviewing and designing scalable and efficient code |
Render the SubjectInfo to an image file. | Here you have a function in Python 3, explain what it does
def render_to_image_file(
self, image_out_path, width_pixels=None, height_pixels=None, dpi=90
):
"""Render the SubjectInfo to an image file.
Args:
image_out_path : str
Path to where image image will be wr... | As a python code expert, you are capable of creating scripts from specifications. |
def browse_in_qt5_ui(self):
"""Browse and edit the SubjectInfo in a simple Qt5 based UI."""
self._render_type = "browse"
self._tree.show(tree_style=self._get_tree_style()) | Implement a Python 3 function for
browsing and edit the SubjectInfo in a simple Qt5 based UI. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _gen_etetoolkit_tree(self, node, subject_info_tree):
"""Copy SubjectInfoTree to a ETE Tree."""
for si_node in subject_info_tree.child_list:
if si_node.type_str == TYPE_NODE_TAG:
child = self._add_type_node(node, si_node.label_str)
elif si_node.type_str == SUBJ... | How would you implement a function in Python 3 that
copies SubjectInfoTree to a ETE Tree. | You are a Python code architect, reviewing and designing scalable and efficient code |
Add a node representing a SubjectInfo type. | Can you generate a brief explanation for the following Python 3 code
def _add_type_node(self, node, label):
child = node.add_child(name=label)
child.add_feature(TYPE_NODE_TAG, True)
return child | As a Python code composer, you craft elegant and concise scripts. |
def _add_subject_node(self, node, subj_str):
"""Add a node containing a subject string."""
child = node.add_child(name=subj_str)
child.add_feature(SUBJECT_NODE_TAG, True)
return child | Can you write a function in Python 3 where it
adds a node containing a subject string. | As a Python code composer, you craft elegant and concise scripts. |
def _get_node_path(self, node):
"""Return the path from the root to ``node`` as a list of node names."""
path = []
while node.up:
path.append(node.name)
node = node.up
return list(reversed(path)) | Can you create a Python 3 function that
returns the path from the root to node as a list of node names. | You are a Python code generator, capable of creating scripts from specifications. |
This method renders the node in the ETE file. | Can you generate a brief explanation for the following Python 3 code
def _layout(self, node):
def set_edge_style():
"""Set the style for edges and make the node invisible."""
node_style = ete3.NodeStyle()
node_style["vt_line_color"] = EDGE_COLOR
node_style["hz_li... | You are a Python code generator, capable of creating scripts from specifications. |
Prevent processes requiring access to secrets from being run. | Explain what the following Python 3 code does
def extend_settings(self, data_id, files, secrets):
process = Data.objects.get(pk=data_id).process
if process.requirements.get('resources', {}).get('secrets', False):
raise PermissionDenied(
"Process which requires access to secre... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get a process finder. | Can you tell what is the following Python 3 function doing
def get_finder(import_path):
finder_class = import_string(import_path)
if not issubclass(finder_class, BaseProcessesFinder):
raise ImproperlyConfigured(
'Finder "{}" is not a subclass of "{}"'.format(finder_class, BaseProcessesFinder... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _find_folders(self, folder_name):
"""Return a list of sub-directories."""
found_folders = []
for app_config in apps.get_app_configs():
folder_path = os.path.join(app_config.path, folder_name)
if os.path.isdir(folder_path):
found_folders.append(folder_p... | How would you code a function in Python 3 to
return a list of sub - directories. | You are a Python code analyst, evaluating scripts for potential improvements. |
Check that sysmeta_pyxb is suitable for creating a new object and matches the
uploaded sciobj bytes. | Here you have a function in Python 3, explain what it does
def sanity(request, sysmeta_pyxb):
_does_not_contain_replica_sections(sysmeta_pyxb)
_is_not_archived(sysmeta_pyxb)
_obsoleted_by_not_specified(sysmeta_pyxb)
if 'HTTP_VENDOR_GMN_REMOTE_URL' in request.META:
return
_has_correct_file_si... | As a Python code analyst, you investigate and solve complex coding mysteries |
Assert that any SID in sysmeta_pyxb can be assigned to a new standalone
object. | Can you generate a brief explanation for the following Python 3 code
def is_valid_sid_for_new_standalone(sysmeta_pyxb):
sid = d1_common.xml.get_opt_val(sysmeta_pyxb, 'seriesId')
if not d1_gmn.app.did.is_valid_sid_for_new_standalone(sid):
raise d1_common.types.exceptions.IdentifierNotUnique(
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Assert that a SID can be assigned to the single object or to the chain. | Can you generate a brief explanation for the following Python 3 code
def is_valid_sid_for_chain(pid, sid):
if not d1_gmn.app.did.is_valid_sid_for_chain(pid, sid):
existing_sid = d1_gmn.app.revision.get_sid_by_pid(pid)
raise d1_common.types.exceptions.IdentifierNotUnique(
0,
'... | You are a Python code generator, capable of creating scripts from specifications. |
Assert that sysmeta_pyxb does not contain any replica information. | Here you have a function in Python 3, explain what it does
def _does_not_contain_replica_sections(sysmeta_pyxb):
if len(getattr(sysmeta_pyxb, 'replica', [])):
raise d1_common.types.exceptions.InvalidSystemMetadata(
0,
'A replica section was included. A new object object created via '... | As a Python code composer, you craft elegant and concise scripts. |
Assert that sysmeta_pyxb does not have the archived flag set. | Given the following Python 3 function, write the documentation
def _is_not_archived(sysmeta_pyxb):
if _is_archived(sysmeta_pyxb):
raise d1_common.types.exceptions.InvalidSystemMetadata(
0,
'Archived flag was set. A new object created via create() or update() '
'cannot alr... | You are a Python code generator, capable of creating scripts from specifications. |
Given the BaseURL for a CN return the DataONE environment dict for the CN s
environemnt. | Can you generate a brief explanation for the following Python 3 code
def get_d1_env_by_base_url(cn_base_url):
for k, v in D1_ENV_DICT:
if v['base_url'].startswith(cn_base_url):
return D1_ENV_DICT[k] | You are a Python code generator, capable of creating scripts from specifications. |
Match the SMEFT Warsaw basis onto the WET JMS basis. | Can you tell what is the following Python 3 function doing
def match_all(d_SMEFT, parameters=None):
p = default_parameters.copy()
if parameters is not None:
# if parameters are passed in, overwrite the default values
p.update(parameters)
C = wilson.util.smeftutil.wcxf2arrays_symmetrized(d_SM... | As a python code expert, you are capable of creating scripts from specifications. |
def _debug_mode_responses(self, request, response):
"""Extra functionality available in debug mode.
- If pretty printed output was requested, force the content type to text. This
causes the browser to not try to format the output in any way.
- If SQL profiling is turned on, return a p... | Implement a function in Python 3 to
return a list of HTTP responses for the debug mode. | As a python code expert, you are capable of creating scripts from specifications. |
Query the ISO for the specified resource set. | Explain what the following Python 3 code does
def queryResponse(
self, queryEngine, query_str, vendorSpecific=None, do_post=False, **kwargs
):
"""CNRead.query(session, queryEngine, query) → OctetStream
https://releases.dataone.org/online/api-
documentation-v2.0.1/apis/CN_APIs.html#CN... | You are a Python code generator, capable of creating scripts from specifications. |
def query(
self, queryEngine, query_str, vendorSpecific=None, do_post=False, **kwargs
):
"""See Also: queryResponse()
Args:
queryEngine:
query_str:
vendorSpecific:
do_post:
**kwargs:
Returns:
"""
response = self.que... | How would you code a function in Python 3 to
see Also : queryResponse | As a Python code composer, you craft elegant and concise scripts. |
CNRead.getQueryEngineDescription(session, queryEngine) →
QueryEngineDescription https://releases.dataone.org/online/api-
documentation-v2.0.1/apis/CN_APIs.html#CNRead.getQueryEngineDescription
MNQuery.getQueryEngineDescription(session, queryEngine) → QueryEngineDescription
http://jenkins... | Given the following Python 3 function, write the documentation
def getQueryEngineDescriptionResponse(self, queryEngine, vendorSpecific=None, **kwargs):
return self.GET(['query', queryEngine], query=kwargs, headers=vendorSpecific) | As a Python code composer, you craft elegant and concise scripts. |
def getQueryEngineDescription(self, queryEngine, **kwargs):
"""See Also: getQueryEngineDescriptionResponse()
Args:
queryEngine:
**kwargs:
Returns:
"""
response = self.getQueryEngineDescriptionResponse(queryEngine, **kwargs)
return self._read_dataone... | Write a Python 3 function for
seeing Also : getQueryEngineDescriptionResponse | As a python code expert, you are capable of creating scripts from specifications. |
def _get_cache_key(self, obj):
"""Derive cache key for given object."""
if obj is not None:
# Make sure that key is REALLY unique.
return '{}-{}'.format(id(self), obj.pk)
return "{}-None".format(id(self)) | Create a Python 3 function for
deriving cache key for given object. | You are a Python code architect, reviewing and designing scalable and efficient code |
Set the cached value for the object. | Can you generate a brief explanation for the following Python 3 code
def set(self, obj, build_kwargs):
if build_kwargs is None:
build_kwargs = {}
cached = {}
if 'queryset' in build_kwargs:
cached = {
'model': build_kwargs['queryset'].model,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def take(self, obj):
"""Get cached value and clean cache."""
cached = self._thread_local.cache[self._get_cache_key(obj)]
build_kwargs = {}
if 'model' in cached and 'pks' in cached:
build_kwargs['queryset'] = cached['model'].objects.filter(pk__in=cached['pks'])
elif ... | Can you implement a function in Python 3 that
gets cached value and clean cache. | As a Python code composer, you craft elegant and concise scripts. |
Connect a specific signal type to this receiver. | Here you have a function in Python 3, explain what it does
def connect(self, signal, **kwargs):
signal.connect(self, **kwargs)
self.connections.append((signal, kwargs)) | You are a Python code generator, capable of creating scripts from specifications. |
def disconnect(self):
"""Disconnect all connected signal types from this receiver."""
for signal, kwargs in self.connections:
signal.disconnect(self, **kwargs) | Write a Python 3 function for
disconnecting all connected signal types from this receiver. | You are a Python code analyst, evaluating scripts for potential improvements. |
def connect(self, index):
"""Connect signals needed for dependency updates.
Pre- and post-delete signals have to be handled separately, as:
* in the pre-delete signal we have the information which
objects to rebuild, but affected relations are still
presented, so rebu... | Implement a Python 3 function for
connecting signals needed for dependency updates. | You are a Python code analyst, evaluating scripts for potential improvements. |
Connect signals needed for dependency updates. | Explain what the following Python 3 code does
def connect(self, index):
# Determine which model is the target model as either side of the relation
# may be passed as `field`.
if index.object_type == self.field.rel.model:
self.model = self.field.rel.related_model
self.acce... | You are a Python code generator, capable of creating scripts from specifications. |
def _filter(self, objects, **kwargs):
"""Determine if dependent object should be processed."""
for obj in objects:
if self.filter(obj, **kwargs) is False:
return False
return True | Can you create a Python 3 function that
determines if dependent object should be processed. | As a Python code composer, you craft elegant and concise scripts. |
Prepare arguments for rebuilding indices. | Make a summary of the following Python 3 code
def _get_build_kwargs(self, obj, pk_set=None, action=None, update_fields=None, reverse=None, **kwargs):
if action is None:
# Check filter before rebuilding index.
if not self._filter([obj], update_fields=update_fields):
return... | As a python code expert, you are capable of creating scripts from specifications. |
def process_predelete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs):
"""Render the queryset of influenced objects and cache it."""
build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs)
self.delete_cache.set(obj, build_kwargs) | How would you code a function in Python 3 to
render the queryset of influenced objects and cache it. | You are a Python code architect, reviewing and designing scalable and efficient code |
def process_delete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs):
"""Recreate queryset from the index and rebuild the index."""
build_kwargs = self.delete_cache.take(obj)
if build_kwargs:
self.index.build(**build_kwargs) | Write a Python 3 function that can
recreate queryset from the index and rebuild the index. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def process_m2m(self, obj, pk_set=None, action=None, update_fields=None, cache_key=None, **kwargs):
"""Process signals from dependencies.
Remove signal is processed in two parts. For details see:
:func:`~Dependency.connect`
"""
if action not in (None, 'post_add', 'pre_remove', '... | Create a Python 3 function for
processing signals from dependencies. m2m add signal is processed in two parts. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _process_m2m_through(self, obj, action):
"""Process custom M2M through model actions."""
source = getattr(obj, self.field.rel.field.m2m_field_name())
target = getattr(obj, self.field.rel.field.m2m_reverse_field_name())
pk_set = set()
if target:
pk_set.add(target.... | Write a Python 3 function for
processing custom M2M through model actions. | You are a Python code architect, reviewing and designing scalable and efficient code |
def process_m2m_through_save(self, obj, created=False, **kwargs):
"""Process M2M post save for custom through model."""
# We are only interested in signals that establish relations.
if not created:
return
self._process_m2m_through(obj, 'post_add') | Can you write a function in Python 3 where it
processes M2M through model post save for custom through model. | As a python code expert, you are capable of creating scripts from specifications. |
def process(self, obj, pk_set=None, action=None, update_fields=None, **kwargs):
"""Process signals from dependencies."""
build_kwargs = self._get_build_kwargs(obj, pk_set, action, update_fields, **kwargs)
if build_kwargs:
self.index.build(**build_kwargs) | Can you write a function in Python 3 where it
processes signals from dependencies. | As a Python code composer, you craft elegant and concise scripts. |
Connect signals for building indexes. | Here you have a function in Python 3, explain what it does
def _connect_signal(self, index):
post_save_signal = ElasticSignal(index, 'build')
post_save_signal.connect(post_save, sender=index.object_type)
self.signals.append(post_save_signal)
post_delete_signal = ElasticSignal(index, 're... | As a python code expert, you are capable of creating scripts from specifications. |
Register signals for all indexes. | How would you explain what the following Python 3 function does
def register_signals(self):
for index in self.indexes:
if index.object_type:
self._connect_signal(index) | As a Python code composer, you craft elegant and concise scripts. |
Find all indexes and add them to the _index_builders attribute. | Can you generate a brief explanation for the following Python 3 code
def discover_indexes(self):
self.indexes = []
for app_config in apps.get_app_configs():
indexes_path = '{}.elastic_indexes'.format(app_config.name)
try:
indexes_module = import_module(indexes_pa... | You are a Python code analyst, evaluating scripts for potential improvements. |
Trigger building of the indexes. | Explain what the following Python 3 code does
def build(self, obj=None, queryset=None, push=True):
for index in self.indexes:
index.build(obj, queryset, push) | You are a Python code architect, reviewing and designing scalable and efficient code |
def push(self, index=None):
"""Push built documents to ElasticSearch.
If ``index`` is specified, only that index will be pushed.
"""
for ind in self.indexes:
if index and not isinstance(ind, index):
continue
ind.push() | Write a Python 3 script for
pushing built documents to ElasticSearch. | You are a Python code analyst, evaluating scripts for potential improvements. |
def delete(self, skip_mapping=False):
"""Delete all entries from ElasticSearch."""
for index in self.indexes:
index.destroy()
if not skip_mapping:
index.create_mapping() | Implement a function in Python 3 to
delete all entries from ElasticSearch. | You are a Python code architect, reviewing and designing scalable and efficient code |
def destroy(self):
"""Delete all indexes from Elasticsearch and index builder."""
self.unregister_signals()
for index in self.indexes:
index.destroy()
self.indexes = [] | Implement a Python 3 function for
deleting all indexes from Elasticsearch and index builder. | As a Python code composer, you craft elegant and concise scripts. |
Set the initial values for parameters and Wilson coefficients at
the scale scale_in. | Make a summary of the following Python 3 code
def _set_initial(self, C_in, scale_in):
self.C_in = C_in
self.scale_in = scale_in | As a Python code analyst, you investigate and solve complex coding mysteries |
Load the initial values for the Wilson coefficients from a Wilson coefficients object. | Can you tell what is the following Python 3 function doing
def _set_initial_wcxf(self, wc, get_smpar=True):
if wc.eft != 'SMEFT':
raise ValueError("Wilson coefficients use wrong EFT.")
if wc.basis != 'Warsaw':
raise ValueError("Wilson coefficients use wrong basis.")
self.... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the Wilson coefficients C_out as a wcxf. WC instance. | Explain what the following Python 3 code does
def _to_wcxf(self, C_out, scale_out):
C = self._rotate_defaultbasis(C_out)
d = wilson.util.smeftutil.arrays2wcxf_nonred(C)
basis = wcxf.Basis['SMEFT', 'Warsaw']
all_wcs = set(basis.all_wcs) # to speed up lookup
d = {k: v for k, v in ... | As a Python code composer, you craft elegant and concise scripts. |
Solve the SMEFT RGEs from the initial scale to scale_out. | Make a summary of the following Python 3 code
def _rgevolve(self, scale_out, **kwargs):
self._check_initial()
return rge.smeft_evolve(C_in=self.C_in,
scale_in=self.scale_in,
scale_out=scale_out,
**kwargs) | You are a Python code generator, capable of creating scripts from specifications. |
def _rgevolve_leadinglog(self, scale_out):
"""Compute the leading logarithmic approximation to the solution
of the SMEFT RGEs from the initial scale to `scale_out`.
Returns a dictionary with parameters and Wilson coefficients.
Much faster but less precise that `rgevolve`.
"""
... | Create a Python 3 function for
computing the leading logarithmic approximation to the solution of the SMEFT RGEs from the initial scale to scale_out. | You are a Python code generator, capable of creating scripts from specifications. |
Get the SM parameters at the EW scale using an estimate C_out and run them to the
input scale. | How would you explain what the following Python 3 function does
def _run_sm_scale_in(self, C_out, scale_sm=91.1876):
# initialize an empty SMEFT instance
smeft_sm = SMEFT(wc=None)
C_in_sm = smeftutil.C_array2dict(np.zeros(9999))
# set the SM parameters to the values obtained from smpar.s... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_smpar(self, accuracy='integrate', scale_sm=91.1876):
"""Compute the SM MS-bar parameters at the electroweak scale.
This method can be used to validate the accuracy of the iterative
extraction of SM parameters. If successful, the values returned by this
method should agree with t... | Create a Python 3 function for
computing the SM - bar parameters at the electroweak scale. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _get_sm_scale_in(self, scale_sm=91.1876):
"""Get an estimate of the SM parameters at the input scale by running
them from the EW scale using constant values for the Wilson coefficients
(corresponding to their leading log approximated values at the EW
scale).
Note that this i... | Write a Python 3 script for
running the SM up and return the SM parameters at the input scale. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the Wilson coefficients evolved to the specified scale. | Make a summary of the following Python 3 code
def run(self, scale, accuracy='integrate', **kwargs):
if accuracy == 'integrate':
C_out = self._rgevolve(scale, **kwargs)
elif accuracy == 'leadinglog':
C_out = self._rgevolve_leadinglog(scale)
else:
raise ValueErr... | As a Python code composer, you craft elegant and concise scripts. |
def run_continuous(self, scale):
"""Return a continuous solution to the RGE as `RGsolution` instance."""
if scale == self.scale_in:
raise ValueError("The scale must be different from the input scale")
elif scale < self.scale_in:
scale_min = scale
scale_max = s... | Can you write a function in Python 3 where it
returns a continuous solution to the RGE as RGsolution instance. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _get_unique_constraints(self, instance):
"""Return SQL filter for filtering by fields in ``unique_with`` attribute.
Filter is returned as tuple of two elements where first one is
placeholder which is safe to insert into SQL query and second
one may include potentially dangerous valu... | How would you implement a function in Python 3 that
returns SQL filter for filtering by fields in unique_with attribute. | As a python code expert, you are capable of creating scripts from specifications. |
Get the value from populate_from attribute. | Here you have a function in Python 3, explain what it does
def _get_populate_from_value(self, instance):
if hasattr(self.populate_from, '__call__'):
# ResolweSlugField(populate_from=lambda instance: ...)
return self.populate_from(instance)
else:
# ResolweSlugField(pop... | You are a Python code architect, reviewing and designing scalable and efficient code |
def pre_save(self, instance, add):
"""Ensure slug uniqunes before save."""
slug = self.value_from_object(instance)
# We don't want to change slug defined by user.
predefined_slug = bool(slug)
if not slug and self.populate_from:
slug = self._get_populate_from_value(i... | Can you create a Python 3 function that
ensures slug uniqunes before save. | As a Python code analyst, you investigate and solve complex coding mysteries |
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(('.yml', '.yaml')):
... | How would you code a function in Python 3 to
perform process discovery in given path. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Recursively evaluate expressions in a dictionary of values. | Given the following Python 3 function, write the documentation
def _evaluate_expressions(self, expression_engine, step_id, values, context):
if expression_engine is None:
return values
processed = {}
for name, value in values.items():
if isinstance(value, str):
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def evaluate(self, data):
"""Evaluate the code needed to compute a given Data object."""
expression_engine = data.process.requirements.get('expression-engine', None)
if expression_engine is not None:
expression_engine = self.get_expression_engine(expression_engine)
# Parse s... | Can you write a function in Python 3 where it
evaluates the code needed to compute a given Data object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
async def init():
"""Create a connection to the Redis server."""
global redis_conn # pylint: disable=global-statement,invalid-name
conn = await aioredis.create_connection(
'redis://{}:{}'.format(
SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('host', 'localhost'),
... | How would you implement a function in Python 3 that
creates a connection to the Redis server. | You are a Python code architect, reviewing and designing scalable and efficient code |
Send a properly formatted command to the manager. | Can you generate the documentation for the following Python 3 function
async def send_manager_command(cmd, expect_reply=True, extra_fields={}):
packet = {
ExecutorProtocol.DATA_ID: DATA['id'],
ExecutorProtocol.COMMAND: cmd,
}
packet.update(extra_fields)
logger.debug("Sending command to ... | You are a Python code generator, capable of creating scripts from specifications. |
def extract_values_query(query, field_list, out_stream=None):
"""Get list of dicts where each dict holds values from one SciObj.
Args:
field_list: list of str
List of field names for which to return values. Must be strings from
FIELD_NAME_TO_generate_dict.keys().
If... | How would you implement a function in Python 3 that
extracts values from one SciObj. | As a python code expert, you are capable of creating scripts from specifications. |
Extract values from one SciObj. | Explain what the following Python 3 code does
def extract_values(field_list=None, filter_arg_dict=None, out_stream=None):
lookup_dict, generate_dict = _split_field_list(field_list)
query, annotate_key_list = _create_query(filter_arg_dict, generate_dict)
lookup_list = [v["lookup_str"] for k, v in lookup_dic... | You are a Python code generator, capable of creating scripts from specifications. |
def assert_invalid_field_list(field_list):
"""raise d1_common.types.exceptions.InvalidRequest() if ``field_list`` contains any
invalid field names. A list of the invalid fields is included in the exception.
- Implicitly called by ``extract_values()``.
"""
if field_list is not None:
invalid... | Write a Python 3 script to
raise an exception if the given list contains invalid field names. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _annotate_query(query, generate_dict):
"""Add annotations to the query to retrieve values required by field value generate
functions."""
annotate_key_list = []
for field_name, annotate_dict in generate_dict.items():
for annotate_name, annotate_func in annotate_dict["annotate_dict"].items():
... | Implement a Python 3 function for
adding annotations to the query to retrieve values required by field value generate functions. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _value_list_to_sciobj_dict(
sciobj_value_list, lookup_list, lookup_dict, generate_dict
):
"""Create a dict where the keys are the requested field names, from the values
returned by Django."""
sciobj_dict = {}
# for sciobj_value, lookup_str in zip(sciobj_value_list, lookup_list):
lookup_to_... | Write a Python 3 script for
creating a dict where the keys are the requested field names from the values returned by Django. | As a Python code composer, you craft elegant and concise scripts. |
Split the list of fields for which to extract values into lists by extraction
methods. | Make a summary of the following Python 3 code
def _split_field_list(field_list):
lookup_dict = {}
generate_dict = {}
for field_name in field_list or FIELD_NAME_TO_EXTRACT_DICT.keys():
try:
extract_dict = FIELD_NAME_TO_EXTRACT_DICT[field_name]
except KeyError:
assert_... | You are a Python code analyst, evaluating scripts for potential improvements. |
def dataoneTypes(request):
"""Return the PyXB binding to use when handling a request."""
if is_v1_api(request):
return d1_common.types.dataoneTypes_v1_1
elif is_v2_api(request) or is_diag_api(request):
return d1_common.types.dataoneTypes_v2_0
else:
raise d1_common.types.exception... | Create a Python 3 function for
returning the PyXB binding to use when handling a request. | As a Python code analyst, you investigate and solve complex coding mysteries |
def parse_and_normalize_url_date(date_str):
"""Parse a ISO 8601 date-time with optional timezone.
- Return as datetime with timezone adjusted to UTC.
- Return naive date-time set to UTC.
"""
if date_str is None:
return None
try:
return d1_common.date_time.dt_from_iso8601_str(da... | Write a Python 3 script for
parsing a ISO 8601 date - time and return a datetime with timezone adjusted to UTC. | As a Python code composer, you craft elegant and concise scripts. |
def get(self, doc_id):
"""Retrieve the specified document."""
resp_dict = self._get_query(q='id:{}'.format(doc_id))
if resp_dict['response']['numFound'] > 0:
return resp_dict['response']['docs'][0] | Write a Python 3 script for
retrieving the specified document. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_ids(self, start=0, rows=1000, **query_dict):
"""Retrieve a list of identifiers for documents matching the query."""
resp_dict = self._get_query(start=start, rows=rows, **query_dict)
return {
'matches': resp_dict['response']['numFound'],
'start': start,
... | Write a Python 3 function that can
retrieve a list of identifiers for documents matching the query. | As a python code expert, you are capable of creating scripts from specifications. |
def count(self, **query_dict):
"""Return the number of entries that match query."""
param_dict = query_dict.copy()
param_dict['count'] = 0
resp_dict = self._get_query(**param_dict)
return resp_dict['response']['numFound'] | How would you code a function in Python 3 to
return the number of entries that match query_dict. | As a Python code analyst, you investigate and solve complex coding mysteries |
Retrieve the unique values for a field. | Can you generate a brief explanation for the following Python 3 code
def get_field_values(self, name, maxvalues=-1, sort=True, **query_dict):
param_dict = query_dict.copy()
param_dict.update(
{
'rows': '0',
'facet': 'true',
'facet.field': name,... | As a python code expert, you are capable of creating scripts from specifications. |
Generates a histogram of values from a string field. | Can you generate a brief explanation for the following Python 3 code
def field_alpha_histogram(
self, name, n_bins=10, include_queries=True, **query_dict
):
"""Generates a histogram of values from a string field.
Output is: [[low, high, count, query], ... ]. Bin edges is determined by equal... | As a Python code composer, you craft elegant and concise scripts. |
docs is a list of fields that are a dictionary of name : value for a record. | Make a summary of the following Python 3 code
def add_docs(self, docs):
return self.query(
'solr',
'<add>{}</add>'.format(
''.join([self._format_add(fields) for fields in docs])
),
do_post=True,
) | As a Python code composer, you craft elegant and concise scripts. |
Coerce the value into the Solr field type. | How would you explain what the following Python 3 function does
def _coerce_type(self, field_type, value):
if value is None:
return None
if field_type == 'string':
return str(value)
elif field_type == 'text':
return str(value)
elif field_type == 'int':... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the Solr type of the specified field name. | Can you generate a brief explanation for the following Python 3 code
def _get_solr_type(self, field):
field_type = 'string'
try:
field_type = FIELD_TYPE_CONVERSION_MAP[field]
return field_type
except:
pass
fta = field.split('_')
if len(fta) > 1... | You are a Python code generator, capable of creating scripts from specifications. |
Perform a GET query against Solr and return the response as a Python dict. | Can you generate a brief explanation for the following Python 3 code
def _get_query(self, **query_dict):
param_dict = query_dict.copy()
return self._send_query(do_post=False, **param_dict) | 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.