output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Move entities from source to destination collection. | How would you explain what the following Python 3 function does
def move_to_collection(self, source_collection, destination_collection):
for entity in self:
entity.move_to_collection(source_collection, destination_collection) | You are a Python code architect, reviewing and designing scalable and efficient code |
def duplicate(self, contributor=None, inherit_collections=False):
"""Duplicate (make a copy)."""
duplicate = Entity.objects.get(id=self.id)
duplicate.pk = None
duplicate.slug = None
duplicate.name = 'Copy of {}'.format(self.name)
duplicate.duplicated = now()
if co... | How would you code a function in Python 3 to
duplicate (make a copy). | As a python code expert, you are capable of creating scripts from specifications. |
Move entity from source to destination collection. | Given the following Python 3 function, write the documentation
def move_to_collection(self, source_collection, destination_collection):
# Remove from collection.
self.collections.remove(source_collection) # pylint: disable=no-member
source_collection.data.remove(*self.data.all()) # pylint: dis... | You are a Python code architect, reviewing and designing scalable and efficient code |
Pass in a dictionary that has unsafe characters as the keys and percent
encoded value as the value. | How would you explain what the following Python 3 function does
def quote(s, unsafe='/'):
res = s.replace('%', '%25')
for c in unsafe:
res = res.replace(c, '%' + (hex(ord(c)).upper())[2:])
return res | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_dependencies(self):
"""Return dependencies, which should trigger updates of this model."""
# pylint: disable=no-member
return super().get_dependencies() + [
Data.collection_set,
Data.entity_set,
Data.parents,
] | Write a Python 3 script for
returning dependencies which should trigger updates of this model. | You are a Python code generator, capable of creating scripts from specifications. |
3 - loop computation of alpha_s for f flavours
| Here you have a function in Python 3, explain what it does
def alpha_s(scale, f, alphasMZ=0.1185, loop=3):
if scale == MZ and f == 5:
return alphasMZ # nothing to do
_sane(scale, f)
crd = rundec.CRunDec()
if f == 5:
return_value = crd.AlphasExact(alphasMZ, MZ, scale, f, loop)
elif f... | You are a Python code generator, capable of creating scripts from specifications. |
r Return the running b quark mass in the MSbar scheme at the scale scale. | Can you generate the documentation for the following Python 3 function
def m_b(mbmb, scale, f, alphasMZ=0.1185, loop=3):
if scale == mbmb and f == 5:
return mbmb # nothing to do
_sane(scale, f)
alphas_mb = alpha_s(mbmb, 5, alphasMZ=alphasMZ, loop=loop)
crd = rundec.CRunDec()
if f == 5:
... | You are a Python code generator, capable of creating scripts from specifications. |
r Returns the running c quark mass in the MSbar scheme at the scale scale. | Can you generate a brief explanation for the following Python 3 code
def m_c(mcmc, scale, f, alphasMZ=0.1185, loop=3):
if scale == mcmc:
return mcmc # nothing to do
_sane(scale, f)
crd = rundec.CRunDec()
alphas_mc = alpha_s(mcmc, 4, alphasMZ=alphasMZ, loop=loop)
if f == 4:
alphas_sc... | You are a Python code generator, capable of creating scripts from specifications. |
r Returns the running s quark mass in the MSbar scheme at the scale scale. | Here you have a function in Python 3, explain what it does
def m_s(ms2, scale, f, alphasMZ=0.1185, loop=3):
if scale == 2 and f == 3:
return ms2 # nothing to do
_sane(scale, f)
crd = rundec.CRunDec()
alphas_2 = alpha_s(2, 3, alphasMZ=alphasMZ, loop=loop)
if f == 3:
alphas_scale = al... | As a python code expert, you are capable of creating scripts from specifications. |
Get user confirmation to proceed. | Given the following Python 3 function, write the documentation
def get_confirmation(self):
if self.clear:
action = 'This will DELETE ALL FILES in this location!'
else:
action = 'This will overwrite existing files!'
message = (
"\n"
"You have reque... | You are a Python code analyst, evaluating scripts for potential improvements. |
def clear_dir(self):
"""Delete contents of the directory on the given path."""
self.stdout.write("Deleting contents of '{}'.".format(self.destination_path))
for filename in os.listdir(self.destination_path):
if os.path.isfile(filename) or os.path.islink(filename):
os... | How would you code a function in Python 3 to
delete contents of the directory on the given path. | As a Python code analyst, you investigate and solve complex coding mysteries |
def change_path_prefix(self, path, old_prefix, new_prefix, app_name):
"""Change path prefix and include app name."""
relative_path = os.path.relpath(path, old_prefix)
return os.path.join(new_prefix, app_name, relative_path) | Write a Python 3 function that can
change path prefix and include app name. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get tools locations and copy them to a single location. | How would you explain what the following Python 3 function does
def collect(self):
for app_name, tools_path in get_apps_tools().items():
self.stdout.write("Copying files from '{}'.".format(tools_path))
app_name = app_name.replace('.', '_')
app_destination_path = os.path.joi... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_data_checksum(proc_input, proc_slug, proc_version):
"""Compute checksum of processor inputs, name and version."""
checksum = hashlib.sha256()
checksum.update(json.dumps(proc_input, sort_keys=True).encode('utf-8'))
checksum.update(proc_slug.encode('utf-8'))
checksum.update(str(proc_version).e... | Create a Python 3 function to
compute checksum of processor inputs name and version. | You are a Python code analyst, evaluating scripts for potential improvements. |
def dict_dot(d, k, val=None, default=None):
"""Get or set value using a dot-notation key in a multilevel dict."""
if val is None and k == '':
return d
def set_default(dict_or_model, key, default_value):
"""Set default field value."""
if isinstance(dict_or_model, models.Model):
... | Create a Python 3 function to
get or set value using a dot - notation key in a multilevel dict. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_apps_tools():
"""Get applications' tools and their paths.
Return a dict with application names as keys and paths to tools'
directories as values. Applications without tools are omitted.
"""
tools_paths = {}
for app_config in apps.get_app_configs():
proc_path = os.path.join(app_... | How would you implement a function in Python 3 that
gets applications tools and their paths. | As a python code expert, you are capable of creating scripts from specifications. |
Rewire inputs of provided data objects. | Can you generate a brief explanation for the following Python 3 code
def rewire_inputs(data_list):
if len(data_list) < 2:
return data_list
mapped_ids = {bundle['original'].id: bundle['copy'].id for bundle in data_list}
for bundle in data_list:
updated = False
copy = bundle['copy']
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def CreateFromDocument(xml_text, default_namespace=None, location_base=None):
"""Parse the given XML and use the document element to create a Python instance.
@param xml_text An XML document. This should be data (Python 2
str or Python 3 bytes), or a text (Python 2 unicode or Python 3
str) in the L{py... | How would you implement a function in Python 3 that
parses the given XML and use the XML element to create a Python object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def CreateFromDOM(node, default_namespace=None):
"""Create a Python instance from the given DOM node. The node tag must correspond to
an element declaration in this module.
@deprecated: Forcing use of DOM interface is unnecessary; use L{CreateFromDocument}.
"""
if default_namespace is None:
... | Create a Python 3 function for
creating a Python instance from the given DOM node. | As a python code expert, you are capable of creating scripts from specifications. |
Take care of any unfinished business. | Can you tell what is the following Python 3 function doing
def postloop(self):
cmd.Cmd.postloop(self) # Clean up command completion
d1_cli.impl.util.print_info("Exiting...") | You are a Python code architect, reviewing and designing scalable and efficient code |
Called on an input line when the command prefix is not recognized. | Make a summary of the following Python 3 code
def default(self, line):
args = self._split_args(line, 0, 99)
d1_cli.impl.util.print_error("Unknown command: {}".format(args[0])) | As a Python code composer, you craft elegant and concise scripts. |
Get help on commands help or "?" with no arguments displays a list_objects
of commands which help is available | Make a summary of the following Python 3 code
def do_help(self, line):
command, = self._split_args(line, 0, 1)
if command is None:
return self._print_help()
cmd.Cmd.do_help(self, line) | As a Python code composer, you craft elegant and concise scripts. |
history Display a list of commands that have been entered. | How would you explain what the following Python 3 function does
def do_history(self, line):
self._split_args(line, 0, 0)
for idx, item in enumerate(self._history):
d1_cli.impl.util.print_info("{0: 3d} {1}".format(idx, item)) | You are a Python code analyst, evaluating scripts for potential improvements. |
def do_exit(self, line):
"""exit Exit from the CLI."""
n_remaining_operations = len(self._command_processor.get_operation_queue())
if n_remaining_operations:
d1_cli.impl.util.print_warn(
"""There are {} unperformed operations in the write operation queue. These will
b... | Implement a Python 3 function for
exiting Exit from the CLI. | As a python code expert, you are capable of creating scripts from specifications. |
def do_eof(self, line):
"""Exit on system EOF character."""
d1_cli.impl.util.print_info("")
self.do_exit(line) | Write a Python 3 function for
exiting on system EOF character. | As a Python code analyst, you investigate and solve complex coding mysteries |
\ x1b [ 1mNAME \ x1b [ 0m set - Set the value of the allCOOKIE_NAME \ x1b [ 0m session_parameter - Name of the parameter. | Can you tell what is the following Python 3 function doing
def do_set(self, line):
session_parameter, value = self._split_args(line, 0, 2)
if value is None:
self._command_processor.get_session().print_variable(session_parameter)
else:
self._command_processor.get_session()... | As a Python code composer, you craft elegant and concise scripts. |
Load a session from file | Can you generate a brief explanation for the following Python 3 code
def do_load(self, line):
config_file = self._split_args(line, 0, 1)[0]
self._command_processor.get_session().load(config_file)
if config_file is None:
config_file = (
self._command_processor.get_sess... | You are a Python code analyst, evaluating scripts for potential improvements. |
def do_save(self, line):
"""save [config_file] Save session variables to file save (without parameters):
Save session to default file ~/.dataone_cli.conf save.
<file>: Save session to specified file.
"""
config_file = self._split_args(line, 0, 1)[0]
self._command_proces... | Write a Python 3 script for
saving session variables to file save. | As a python code expert, you are capable of creating scripts from specifications. |
def do_reset(self, line):
"""reset Set all session variables to their default values."""
self._split_args(line, 0, 0)
self._command_processor.get_session().reset()
self._print_info_if_verbose("Successfully reset session variables") | Can you create a Python 3 function that
resets Reset all session variables to their default values. | As a Python code analyst, you investigate and solve complex coding mysteries |
allowaccess - Set the access level for subject Access
level is read write or changePermission. | Can you generate the documentation for the following Python 3 function
def do_allowaccess(self, line):
subject, permission = self._split_args(line, 1, 1)
self._command_processor.get_session().get_access_control().add_allowed_subject(
subject, permission
)
self._print_info_if_... | You are a Python code generator, capable of creating scripts from specifications. |
allowrep Allow new objects to be replicated | Given the following Python 3 function, write the documentation
def do_allowrep(self, line):
self._split_args(line, 0, 0)
self._command_processor.get_session().get_replication_policy().set_replication_allowed(
True
)
self._print_info_if_verbose("Set replication policy to allow... | As a python code expert, you are capable of creating scripts from specifications. |
denyrep Prevent new objects from being replicated | How would you explain what the following Python 3 function does
def do_denyrep(self, line):
self._split_args(line, 0, 0)
self._command_processor.get_session().get_replication_policy().set_replication_allowed(
False
)
self._print_info_if_verbose("Set replication policy to deny... | As a Python code translator, you convert algorithms and pseudocode into Python. |
blockrep | blockrep | node name | | | Make a summary of the following Python 3 code
def do_blockrep(self, line):
mns = self._split_args(line, 1, -1)
self._command_processor.get_session().get_replication_policy().add_blocked(mns)
self._print_info_if_verbose(
"Set {} as blocked replication target(s)".format(", ".join(mns))... | You are a Python code generator, capable of creating scripts from specifications. |
removerep remove one or more Member Nodes
from replication policy | Can you tell what is the following Python 3 function doing
def do_removerep(self, line):
mns = self._split_args(line, 1, -1)
self._command_processor.get_session().get_replication_policy().repremove(mns)
self._print_info_if_verbose(
"Removed {} from replication policy".format(", ".joi... | You are a Python code generator, capable of creating scripts from specifications. |
numberrep <number of replicas > Set preferred number of replicas for new
objects. | Can you tell what is the following Python 3 function doing
def do_numberrep(self, line):
n_replicas = self._split_args(line, 1, 0)[0]
self._command_processor.get_session().get_replication_policy().set_number_of_replicas(
n_replicas
)
self._print_info_if_verbose("Set number of... | You are a Python code architect, reviewing and designing scalable and efficient code |
get - Get an object from a Member Node. | Can you generate the documentation for the following Python 3 function
def do_get(self, line):
pid, output_file = self._split_args(line, 2, 0)
self._command_processor.science_object_get(pid, output_file)
self._print_info_if_verbose(
'Downloaded "{}" to file: {}'.format(pid, output_fi... | You are a Python code analyst, evaluating scripts for potential improvements. |
\ x1b [ 1mNAME \ x1b [ 0m meta - Gets the System Metadata that is associated with the Science Object. | Can you generate the documentation for the following Python 3 function
def do_meta(self, line):
pid, output_file = self._split_args(line, 1, 1)
self._command_processor.system_metadata_get(pid, output_file)
if output_file is not None:
self._print_info_if_verbose(
'Down... | You are a Python code generator, capable of creating scripts from specifications. |
def do_list(self, line):
"""list [path] Retrieve a list of available Science Data Objects from Member
Node The response is filtered by the from-date, to-date, search, start and count
session variables.
See also: search
"""
path = self._split_args(line, 0, 1, pad=False)
... | Write a Python 3 script for
listing a list of Science Data Objects from Member Node | As a Python code translator, you convert algorithms and pseudocode into Python. |
log [ path ] Retrieve event log from Member Node The response is filtered by from - date to - date start and count session parameters | Explain what the following Python 3 code does
def do_log(self, line):
path = self._split_args(line, 0, 1, pad=False)
if len(path):
path = path[0]
self._command_processor.log(path) | As a Python code translator, you convert algorithms and pseudocode into Python. |
resolve <identifier > Find all locations from which the given Science Object
can be downloaded. | Can you generate a brief explanation for the following Python 3 code
def do_resolve(self, line):
pid, = self._split_args(line, 1, 0)
self._command_processor.resolve(pid) | As a Python code translator, you convert algorithms and pseudocode into Python. |
create - Create a new Science Object on a Member Node. | Explain what the following Python 3 code does
def do_create(self, line):
pid, sciobj_path = self._split_args(line, 2, 0)
self._command_processor.science_object_create(pid, sciobj_path)
self._print_info_if_verbose(
'Added create operation for identifier "{}" to write queue'.format(pid... | As a Python code analyst, you investigate and solve complex coding mysteries |
update - update a.
. pid | Explain what the following Python 3 code does
def do_update(self, line):
curr_pid, pid_new, input_file = self._split_args(line, 3, 0)
self._command_processor.science_object_update(curr_pid, input_file, pid_new)
self._print_info_if_verbose(
'Added update operation for identifier "{}" ... | As a Python code analyst, you investigate and solve complex coding mysteries |
\ x1b [ 1mNAME \ x1b [ 0m package - Create a simple OAI -ORE Resource Map on a Member Node. | Make a summary of the following Python 3 code
def do_package(self, line):
pids = self._split_args(line, 3, -1, pad=False)
self._command_processor.create_package(pids)
self._print_info_if_verbose(
'Added package create operation for identifier "{}" to write queue'.format(
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def do_archive(self, line):
"""archive <identifier> [identifier ...] Mark one or more existing Science
Objects as archived."""
pids = self._split_args(line, 1, -1)
self._command_processor.science_object_archive(pids)
self._print_info_if_verbose(
"Added archive operati... | How would you code a function in Python 3 to
archive - Add one or more existing Science Objects as archived. | As a Python code translator, you convert algorithms and pseudocode into Python. |
updateaccess <identifier> [identifier ...] Update the Access Policy on one or
more existing Science Data Objects. | Can you generate a brief explanation for the following Python 3 code
def do_updateaccess(self, line):
pids = self._split_args(line, 1, -1)
self._command_processor.update_access_policy(pids)
self._print_info_if_verbose(
"Added access policy update operation for identifiers {} to write... | As a python code expert, you are capable of creating scripts from specifications. |
def do_search(self, line):
"""search [query] Comprehensive search for Science Data Objects across all
available MNs.
See https://releases.dataone.org/online/api-
documentation-v2.0.1/design/SearchMetadata.html for the available search terms.
"""
args = self._split_args(... | Write a Python 3 script to
search [ query ] Comprehensive search for Science Data Objects across all available MNs. | You are a Python code generator, capable of creating scripts from specifications. |
ping - Ping the CN and MN of the current session. | Make a summary of the following Python 3 code
def do_ping(self, line):
hosts = self._split_args(line, 0, 99, pad=False)
self._command_processor.ping(hosts) | You are a Python code architect, reviewing and designing scalable and efficient code |
def do_queue(self, line):
"""queue Print the queue of write operations."""
self._split_args(line, 0, 0)
self._command_processor.get_operation_queue().display() | Can you create a Python 3 function that
queues Print the queue of write operations. | As a python code expert, you are capable of creating scripts from specifications. |
run Perform each operation in the queue of write operations. | Can you tell what is the following Python 3 function doing
def do_run(self, line):
self._split_args(line, 0, 0)
self._command_processor.get_operation_queue().execute()
self._print_info_if_verbose(
"All operations in the write queue were successfully executed"
) | As a Python code analyst, you investigate and solve complex coding mysteries |
edit Edit the queue of write operations. | Make a summary of the following Python 3 code
def do_edit(self, line):
self._split_args(line, 0, 0)
self._command_processor.get_operation_queue().edit()
self._print_info_if_verbose("The write operation queue was successfully edited") | As a Python code analyst, you investigate and solve complex coding mysteries |
Print help message to group commands by functionality. | Can you tell what is the following Python 3 function doing
def _print_help(self):
msg = """Commands (type help <command> for details)
CLI: help history exit quit
Session, General: set load save reset
Session, Access Control: allowaccess denyaccess clearaccess
Session, Replication: ... | As a python code expert, you are capable of creating scripts from specifications. |
Return queryset of all Groups with any object permissions for the given object. | Explain what the following Python 3 code does
def get_groups_with_perms(obj, attach_perms=False):
ctype = get_content_type(obj)
group_model = get_group_obj_perms_model(obj)
if not attach_perms:
# It's much easier without attached perms so we do it first if that is the case
group_rel_name = ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _group_groups(perm_list):
"""Group permissions by group.
Input is list of tuples of length 3, where each tuple is in
following format::
(<group_id>, <group_name>, <single_permission>)
Permissions are regrouped and returned in such way that there is
only one tuple for each group::
... | Can you implement a function in Python 3 that
groups permissions by group. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_user_group_perms(user_or_group, obj):
"""Get permissins for user groups.
Based on guardian.core.ObjectPermissionChecker.
"""
user, group = get_identity(user_or_group)
if user and not user.is_active:
return [], []
user_model = get_user_model()
ctype = ContentType.objects.ge... | Create a Python 3 function to
get permissins for user groups. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns list of permissions for given object in Resolwe specific format. | Can you tell what is the following Python 3 function doing
def get_object_perms(obj, user=None):
def format_permissions(perms):
"""Remove model name from permission."""
ctype = ContentType.objects.get_for_model(obj)
return [perm.replace('_{}'.format(ctype.name), '') for perm in perms]
p... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_objects_for_user(user, perms, klass=None, use_groups=True, any_perm=False,
with_superuser=True, accept_global_perms=True, perms_filter='pk__in'):
"""Return queryset with required permissions."""
if isinstance(perms, str):
perms = [perms]
ctype = None
app_label =... | Write a Python 3 script to
return a queryset with required permissions. | As a python code expert, you are capable of creating scripts from specifications. |
Return users with specific permission on object. | Can you tell what is the following Python 3 function doing
def get_users_with_permission(obj, permission):
user_model = get_user_model()
return user_model.objects.filter(
userobjectpermission__object_pk=obj.pk,
userobjectpermission__permission__codename=permission,
).distinct() | You are a Python code generator, capable of creating scripts from specifications. |
def purge_run(self, event):
"""Run purge for the object with ``location_id`` specified in ``event`` argument."""
location_id = event['location_id']
verbosity = event['verbosity']
try:
logger.info(__("Running purge for location id {}.", location_id))
location_purg... | Write a Python 3 script to
run purge for the object with location_id specified in event argument. | As a python code expert, you are capable of creating scripts from specifications. |
def get_resource_limits(self):
"""Get the core count and memory usage limits for this process.
:return: A dictionary with the resource limits, containing the
following keys:
- ``memory``: Memory usage limit, in MB. Defaults to 4096 if
not otherwise specified in th... | Write a Python 3 function for
getting the core count and memory usage limits for this process. | As a python code expert, you are capable of creating scripts from specifications. |
Ensure no unsupported query params were used. | Explain what the following Python 3 code does
def validate_query_params(self):
allowed_params = set(self.get_filters().keys())
allowed_params.update(self.get_always_allowed_arguments())
unallowed = set(self.request.query_params.keys()) - allowed_params
if unallowed:
msg = '... | As a Python code composer, you craft elegant and concise scripts. |
def set_default_option(cls, key, value):
"""Class method. Set the default value of the option `key` (string)
to `value` for all future instances of the class.
Note that this does not affect existing instances or the instance
called from."""
cls._default_options.update(cls._optio... | How would you implement a function in Python 3 that
classes method. Set the default value of the option key to value for all future instances of the class. | As a python code expert, you are capable of creating scripts from specifications. |
Set the option key to value. | Here you have a function in Python 3, explain what it does
def set_option(self, key, value):
self._options.update(self._option_schema({key: value}))
self.clear_cache() | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_option(self, key):
"""Return the current value of the option `key` (string).
Instance method, only refers to current instance."""
return self._options.get(key, self._default_options[key]) | Create a Python 3 function for
returning the current value of the option key ( string. Instance method only refers to current instance. | You are a Python code analyst, evaluating scripts for potential improvements. |
def from_wc(cls, wc):
"""Return a `Wilson` instance initialized by a `wcxf.WC` instance"""
return cls(wcdict=wc.dict, scale=wc.scale, eft=wc.eft, basis=wc.basis) | Can you implement a function in Python 3 that
returns a Wilson instance initialized by a wcxf. WC instance | You are a Python code analyst, evaluating scripts for potential improvements. |
def load_wc(cls, stream):
"""Return a `Wilson` instance initialized by a WCxf file-like object"""
wc = wcxf.WC.load(stream)
return cls.from_wc(wc) | Create a Python 3 function for
returning a Wilson instance initialized by a WCxf file - like object | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the Wilson coefficients to a different scale and EFT and basis. | Can you tell what is the following Python 3 function doing
def match_run(self, scale, eft, basis, sectors='all'):
cached = self._get_from_cache(sector=sectors, scale=scale, eft=eft, basis=basis)
if cached is not None:
return cached
if sectors == 'all':
# the default valu... | You are a Python code architect, reviewing and designing scalable and efficient code |
Try to load a set of Wilson coefficients from the cache else return None. | Can you generate a brief explanation for the following Python 3 code
def _get_from_cache(self, sector, scale, eft, basis):
try:
return self._cache[eft][scale][basis][sector]
except KeyError:
return None | As a Python code composer, you craft elegant and concise scripts. |
Return a tuple of arrays x y that can be fed to plt. plot | Given the following Python 3 function, write the documentation
def plotdata(self, key, part='re', scale='log', steps=50):
if scale == 'log':
x = np.logspace(log(self.scale_min),
log(self.scale_max),
steps,
base=e)
... | As a Python code composer, you craft elegant and concise scripts. |
Plot the RG evolution of parameter key. | Given the following Python 3 function, write the documentation
def plot(self, key, part='re', scale='log', steps=50, legend=True, plotargs={}):
try:
import matplotlib.pyplot as plt
except ImportError:
raise ImportError("Please install matplotlib if you want to use the plot method... | You are a Python code architect, reviewing and designing scalable and efficient code |
Run the consumer until it finishes processing messages. | Here you have a function in Python 3, explain what it does
async def run_consumer(timeout=None, dry_run=False):
channel = state.MANAGER_CONTROL_CHANNEL
scope = {
'type': 'control_event',
'channel': channel,
}
app = ApplicationCommunicator(ManagerConsumer, scope)
channel_layer = get... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the class path for a given class. | Can you generate a brief explanation for the following Python 3 code
def _get_class_path(self, klass_or_instance):
if inspect.isclass(klass_or_instance):
klass = '{}.{}'.format(klass_or_instance.__module__, klass_or_instance.__name__)
elif not isinstance(klass_or_instance, str):
... | As a Python code composer, you craft elegant and concise scripts. |
def add_extension(self, klass, extension):
"""Register an extension for a class.
:param klass: Class to register an extension for
:param extension: Extension (arbitrary type)
"""
klass = self._get_class_path(klass)
# TODO: Take order into account.
self._extensio... | Write a Python 3 script for
registering an extension for a class. | You are a Python code generator, capable of creating scripts from specifications. |
Return all registered extensions of a given class. | Can you generate the documentation for the following Python 3 function
def get_extensions(self, klass):
self.discover_extensions()
return self._extensions.get(self._get_class_path(klass), []) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _get_running_parameters(self, scale, f, loop=3):
"""Get the running parameters (e.g. quark masses and the strong
coupling at a given scale."""
p = {}
p['alpha_s'] = qcd.alpha_s(scale, self.f, self.parameters['alpha_s'], loop=loop)
p['m_b'] = qcd.m_b(self.parameters['m_b'], sc... | Write a Python 3 function for
getting the running parameters for the given scale. | As a Python code composer, you craft elegant and concise scripts. |
def run(self, scale_out, sectors='all'):
"""Evolve the Wilson coefficients to the scale `scale_out`.
Parameters:
- scale_out: output scale
- sectors: optional. If provided, must be a tuple of strings
corresponding to WCxf sector names. Only Wilson coefficients
belon... | Can you create a Python 3 function that
evolves the Wilson coefficients to the scale scale_out. | As a Python code analyst, you investigate and solve complex coding mysteries |
def size(self):
"""Returns:
int : The total number of bytes that will be returned by the iterator.
"""
if hasattr(self._stream, 'len'):
return len(self._stream)
elif hasattr(self._stream, 'fileno'):
return os.fstat(self._stream.fileno()).st_size
el... | How would you code a function in Python 3 to
return the total number of bytes that will be returned by the iterator. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get the public TLS X.509 certificate from the root CN of the DataONE
environment. | Make a summary of the following Python 3 code
def _get_cn_cert():
try:
cert_obj = django.core.cache.cache.cn_cert_obj
d1_common.cert.x509.log_cert_info(
logging.debug, 'Using cached CN cert for JWT validation', cert_obj
)
return cert_obj
except AttributeError:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Takes a user s API key string which applies content settings. | Can you tell what is the following Python 3 function doing
def key(self, key=""):
params = join_params(self.parameters, {"key": key})
return self.__class__(**params) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a new object with the given q | Make a summary of the following Python 3 code
def query(self, *q):
params = join_params(self.parameters, {"q": q})
return self.__class__(**params) | As a python code expert, you are capable of creating scripts from specifications. |
def sort_by(self, sf):
"""
Determines how to sort search results. Available sorting methods are
sort.SCORE, sort.COMMENTS, sort.HEIGHT, sort.RELEVANCE, sort.CREATED_AT,
and sort.RANDOM; default is sort.CREATED_AT.
"""
params = join_params(self.parameters, {"sf": sf})
return self.__class__(*... | Implement a Python 3 function for
returning a new object with the sort parameters set to sf. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a new object with the specified limit. | Explain what the following Python 3 code does
def limit(self, limit):
params = join_params(self.parameters, {"limit": limit})
return self.__class__(**params) | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a new object with the current filter ID. | Here you have a function in Python 3, explain what it does
def filter(self, filter_id=""):
params = join_params(self.parameters, {"filter_id": filter_id})
return self.__class__(**params) | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a new object with the specified option applied to all users. | Make a summary of the following Python 3 code
def faves(self, option):
params = join_params(self.parameters, {"faves": option})
return self.__class__(**params) | As a python code expert, you are capable of creating scripts from specifications. |
Sets whether to filter by a user s uploads list. Options available are user. ONLY user. NOT user. ONLY user. NOT user. ONLY user. NOT user. ONLY user. NOT user. ONLY user. NOT user. ONLY user. NOT user. ONLY user. NOT user. ONLY user. NOT user. ONLY user. NOT user. ONLY user. NOT user. None is used. | How would you explain what the following Python 3 function does
def uploads(self, option):
params = join_params(self.parameters, {"uploads": option})
return self.__class__(**params) | You are a Python code analyst, evaluating scripts for potential improvements. |
Define contributor by adding it to request. data. | Can you generate a brief explanation for the following Python 3 code
def define_contributor(self, request):
request.data['contributor'] = self.resolve_user(request.user).pk | As a Python code composer, you craft elegant and concise scripts. |
def slug_exists(self, request):
"""Check if given url slug exists.
Check if slug given in query parameter ``name`` exists. Return
``True`` if slug already exists and ``False`` otherwise.
"""
if not request.user.is_authenticated:
return Response(status=status.HTTP_40... | Implement a Python 3 function for
checking if given url slug exists. Return True if slug exists and False otherwise. | As a Python code composer, you craft elegant and concise scripts. |
Extract a list of integers from request data. | Can you tell what is the following Python 3 function doing
def get_ids(self, request_data, parameter_name='ids'):
if parameter_name not in request_data:
raise ParseError("`{}` parameter is required".format(parameter_name))
ids = request_data.get(parameter_name)
if not isinstance(ids... | You are a Python code generator, capable of creating scripts from specifications. |
Extract an integer from request data. | Explain what the following Python 3 code does
def get_id(self, request_data, parameter_name='id'):
if parameter_name not in request_data:
raise ParseError("`{}` parameter is required".format(parameter_name))
id_parameter = request_data.get(parameter_name, None)
if not isinstance(id_... | You are a Python code architect, reviewing and designing scalable and efficient code |
Deserialize a DataONE Exception from a dictionary of HTTP headers. | Can you generate the documentation for the following Python 3 function
def deserialize_from_headers(headers):
return create_exception_by_name(
_get_header(headers, 'DataONE-Exception-Name'),
_get_header(headers, 'DataONE-Exception-DetailCode'),
_get_header(headers, 'DataONE-Exception-Descrip... | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a DataONE Exception based object by name. | How would you explain what the following Python 3 function does
def create_exception_by_name(
name,
detailCode='0',
description='',
traceInformation=None,
identifier=None,
nodeId=None,
):
"""Create a DataONEException based object by name.
Args:
name: str
The type name of a... | As a Python code composer, you craft elegant and concise scripts. |
def create_exception_by_error_code(
errorCode,
detailCode='0',
description='',
traceInformation=None,
identifier=None,
nodeId=None,
):
"""Create a DataONE Exception object by errorCode.
See Also: For args, see: ``DataONEException()``
"""
try:
dataone_exception = ERROR... | Create a Python 3 function for
creating a DataONE Exception object by errorCode. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _fmt(self, tag, msg):
"""Format a string for inclusion in the exception's string representation.
If msg is None, format to empty string. If msg has a single line, format to:
tag: msg If msg has multiple lines, format to: tag: line 1 line 2 Msg is
truncated to 1024 chars.
... | Create a Python 3 function to
format a string for inclusion in the exception s string representation. | You are a Python code generator, capable of creating scripts from specifications. |
def friendly_format(self):
"""Serialize to a format more suitable for displaying to end users."""
if self.description is not None:
msg = self.description
else:
msg = 'errorCode: {} / detailCode: {}'.format(
self.errorCode, self.detailCode
)
... | Write a Python 3 script to
serialize to a format more suitable for displaying to end users. | You are a Python code architect, reviewing and designing scalable and efficient code |
Serialize to XML bytes with prolog. | How would you explain what the following Python 3 function does
def serialize_to_transport(self, encoding='utf-8', xslt_url=None):
assert encoding in ('utf-8', 'UTF-8')
dataone_exception_pyxb = self.get_pyxb()
return d1_common.xml.serialize_for_transport(
dataone_exception_pyxb, xslt... | As a python code expert, you are capable of creating scripts from specifications. |
Serialize to a pretty printed Unicode str suitable for display. | Can you generate a brief explanation for the following Python 3 code
def serialize_to_display(self, xslt_url=None):
return d1_common.xml.serialize_to_xml_str(
self.get_pyxb(), pretty=True, xslt_url=xslt_url
) | As a python code expert, you are capable of creating scripts from specifications. |
Serialize to a dict of HTTP headers. | Can you generate a brief explanation for the following Python 3 code
def serialize_to_headers(self):
return {
'DataONE-Exception-Name': self.__class__.__name__,
'DataONE-Exception-ErrorCode': self._format_header(self.errorCode),
'DataONE-Exception-DetailCode': self._format_he... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_pyxb(self):
"""Generate a DataONE Exception PyXB object.
The PyXB object supports directly reading and writing the individual values that
may be included in a DataONE Exception.
"""
dataone_exception_pyxb = dataoneErrors.error()
dataone_exception_pyxb.name = sel... | Can you implement a function in Python 3 that
generates a DataONE Exception PyXB object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Recreate empty dependency relation if parent has been deleted. | Can you generate the documentation for the following Python 3 function
def recreate_parent_dependencies(apps, schema_editor):
Data = apps.get_model('flow', 'Data')
DataDependency = apps.get_model('flow', 'DataDependency')
def process_dependency(data, parent):
if not Data.objects.filter(pk=parent).e... | As a python code expert, you are capable of creating scripts from specifications. |
def add_access_policy_filter(request, query, column_name):
"""Filter records that do not have ``read`` or better access for one or more of the
active subjects.
Since ``read`` is the lowest access level that a subject can have, this method only
has to filter on the presence of the subject.
"""
... | How would you implement a function in Python 3 that
adds a filter to the query that only has read or better access for one or more active subjects. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add redact annotation to LogEntry records that require unredacted IP and subject fields to be returned to the client. | Explain what the following Python 3 code does
def add_redact_annotation(request, query):
return query.annotate(
redact=django.db.models.Exists(
d1_gmn.app.models.Permission.objects.filter(
sciobj=django.db.models.OuterRef('sciobj'),
subject__subject__in=request.al... | 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.