output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def has_offline_historical_manager_or_raise(self):
"""Raises an exception if model uses a history manager and
historical model history_id is not a UUIDField.
Note: expected to use edc_model.HistoricalRecords instead of
simple_history.HistoricalRecords.
"""
try:
... | Write a Python 3 function for
raising an exception if the model uses a history manager and historical model history_id is not a UUIDField. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the primary key field. | How would you explain what the following Python 3 function does
def primary_key_field(self):
return [field for field in self.instance._meta.fields if field.primary_key][0] | You are a Python code generator, capable of creating scripts from specifications. |
def to_outgoing_transaction(self, using, created=None, deleted=None):
""" Serialize the model instance to an AES encrypted json object
and saves the json object to the OutgoingTransaction model.
"""
OutgoingTransaction = django_apps.get_model(
"django_collect_offline", "Outgo... | Write a Python 3 script to
serialize the object to an OutgoingTransaction object and saves it to the OutgoingTransaction model. | You are a Python code generator, capable of creating scripts from specifications. |
Returns an encrypted json serialized from self.
| Here you have a function in Python 3, explain what it does
def encrypted_json(self):
json = serialize(objects=[self.instance])
encrypted_json = Cryptor().aes_encrypt(json, LOCAL_MODE)
return encrypted_json | As a python code expert, you are capable of creating scripts from specifications. |
Maps the name of an Requirement class to the name of the corresponding
module in the environment. | Can you tell what is the following Python 3 function doing
def map_req(self, requirement):
if isinstance(self._packages_map, dict):
local_name = self._packages_map.get(requirement, requirement.name)
else:
local_name = self._packages_map(requirement)
return local_name | As a python code expert, you are capable of creating scripts from specifications. |
Maps a local version name to one recognised by the Requirement class
| How would you explain what the following Python 3 function does
def map_version(self, requirement, local_version):
if isinstance(self._versions_map, dict):
version = self._versions_map.get(requirement, {}).get(
local_version, local_version)
else:
version = self._v... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Register the TagProcessors that are bundled with doxytag2zealdb. | Can you generate a brief explanation for the following Python 3 code
def init_tag_processors(self):
'''Register the TagProcessors that are bundled with doxytag2zealdb.'''
register = self.register_tag_processor
register('class', classTagProcessor(**self.opts))
register('file', fileTagPro... | As a python code expert, you are capable of creating scripts from specifications. |
Run all tag processors. | Can you tell what is the following Python 3 function doing
def process(self):
'''Run all tag processors.'''
for tag_proc in self.tag_procs:
before_count = self.entry_count
self.run_tag_processor(tag_proc)
after_count = self.entry_count
if self.verbose:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Run a tag processor. | Make a summary of the following Python 3 code
def run_tag_processor(self, tag_proc_name):
'''Run a tag processor.
Args:
tag_proc_name: A string key that maps to the TagProcessor to run.
'''
tag_processor = self.tag_procs[tag_proc_name]
for tag in tag_processor.find(... | You are a Python code generator, capable of creating scripts from specifications. |
Process a tag with a tag processor and insert a DB entry. | Can you generate the documentation for the following Python 3 function
def process_tag(self, tag_proc_name, tag):
'''Process a tag with a tag processor and insert a DB entry.
Args:
tag_proc_name: A string key that maps to the TagProcessor to use.
tag: A BeautifulSoup Tag to proc... | As a Python code composer, you craft elegant and concise scripts. |
def groupby(iterable, key=0, filter=None):
"""
wrapper to itertools.groupby that returns a list of each group, rather
than a generator and accepts integers or strings as the key and
automatically converts them to callables with itemgetter(key)
Arguments:
iterable: iterable
key: stri... | Implement a function in Python 3 to
wrap to itertools. groupby that returns a list of each group and returns a list of each group | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generator that yields n elements from iterable. | Here you have a function in Python 3, explain what it does
def groups_of(n, iterable):
args = [iter(iterable)] * n
for x in izip_longest(*args):
yield [v for v in x if v is not None] | As a python code expert, you are capable of creating scripts from specifications. |
Runs the given pipelines and returns the final report node which can be used to generate the next set of nodes. | Explain what the following Python 3 code does
def run(self, *pipelines, **kwargs):
if not pipelines:
raise ArcanaUsageError("No pipelines provided to {}.run"
.format(self))
# Get filter kwargs (NB: in Python 3 they could be in the kwarg list)
subje... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _connect_pipeline(self, pipeline, required_outputs, workflow,
subject_inds, visit_inds, filter_array, force=False):
"""
Connects a pipeline to a overarching workflow that sets up iterators
over subjects|visits present in the repository (if required) and
repo... | Can you implement a function in Python 3 that
connects a pipeline to an overarching workflow that sets up iterators over subjects and visits. | You are a Python code analyst, evaluating scripts for potential improvements. |
Generate nodes that iterate over subjects and visits in the study that need to be processed by the pipeline. | How would you explain what the following Python 3 function does
def _iterate(self, pipeline, to_process_array, subject_inds, visit_inds):
# Check to see whether the subject/visit IDs to process (as specified
# by the 'to_process' array) can be factorized into indepdent nodes,
# i.e. all subjects... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _to_process(self, pipeline, required_outputs, prqs_to_process_array,
to_skip_array, filter_array, subject_inds, visit_inds,
force):
"""
Check whether the outputs of the pipeline are present in all sessions
in the project repository and were generated w... | Implement a function in Python 3 to
check whether the outputs of the pipeline are present in all sessions in the project repository and were generated with matching provenance. Return an 2D boolean array (subjects: rows, visits: cols) with the sessions to process marked True. Parameters ---------- pipeline : Pipeline T... | As a python code expert, you are capable of creating scripts from specifications. |
Dialates a to_process array to include all subject and or visit for every unique entry in the set iterators. | Can you tell what is the following Python 3 function doing
def _dialate_array(self, array, iterators):
if not iterators:
return array
dialated = np.copy(array)
if self.study.SUBJECT_ID in iterators:
# If we join over subjects we should include all subjects for every
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Intercept calls to get template and return our own node - specific oneCOOKIE - set - key - value pairs template
- a node - id | Can you tell what is the following Python 3 function doing
def _get_args(self, node, keywords):
args = super(ArcanaSlurmGraphPlugin, self)._get_args(
node, keywords)
# Substitute the template arg with the node-specific one
new_args = []
for name, arg in zip(keywords, args):
... | You are a Python code generator, capable of creating scripts from specifications. |
Returns the wall time in the format required for the sbatch script. | Explain what the following Python 3 code does
def wall_time_str(self, wall_time):
days = int(wall_time // 1440)
hours = int((wall_time - days * 1440) // 60)
minutes = int(math.floor(wall_time - days * 1440 - hours * 60))
seconds = int((wall_time - math.floor(wall_time)) * 60)
ret... | As a Python code composer, you craft elegant and concise scripts. |
Retrieve panel information from ElkM1 | Make a summary of the following Python 3 code
def sync(self):
self._elk.add_handler('VN', self._vn_handler)
self._elk.add_handler('XK', self._xk_handler)
self._elk.add_handler('RP', self._rp_handler)
self._elk.add_handler('IE', self._elk.call_sync_handlers)
self._elk.add_handler(... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def set(self, element_to_set, value):
"""(Helper) Set thermostat"""
self._elk.send(ts_encode(self.index, value, element_to_set)) | Create a Python 3 function to
set the thermostat to the given value. | You are a Python code generator, capable of creating scripts from specifications. |
Duplicate the datum and rename it | Can you generate a brief explanation for the following Python 3 code
def renamed(self, name):
duplicate = copy(self)
duplicate._name = name
return duplicate | As a Python code translator, you convert algorithms and pseudocode into Python. |
Compares the version with another version. | Given the following Python 3 function, write the documentation
def compare(self, other):
if self._req != other._req:
raise ArcanaUsageError(
"Can't compare versions of different requirements {} and {}"
.format(self._req, other._req))
# Compare main sequence
... | You are a Python code generator, capable of creating scripts from specifications. |
def parse(self, version):
"""
Splits a typical version string (e.g. <MAJOR>.<MINOR>.<MICRO>)
into a tuple that can be sorted properly. Ignores all leading
and trailing characters by using a regex search (instead of match) so
as to pick the version string out of a block of text.
... | Write a Python 3 script to
parse a typical version string into a tuple that can be used to pick the version number and the version number of the version. | As a python code expert, you are capable of creating scripts from specifications. |
def within(self, version):
"""
A single version can also be interpreted as an open range (i.e. no
maximum version)
"""
if not isinstance(version, Version):
version = type(self._min_ver)(self._req, version)
return version >= self | Create a Python 3 function for
returning True if the current version is within the given version. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns either a single version or a version range depending on whether two arguments are supplied or one. | Here you have a function in Python 3, explain what it does
def v(self, version, max_version=None, **kwargs):
if not isinstance(version, Version):
version = self.version_cls(self, version, **kwargs)
# Return a version range instead of version
if max_version is not None:
if... | As a python code expert, you are capable of creating scripts from specifications. |
def open(self):
'''Open a connection to the database.
If a connection appears to be open already, transactions are committed
and it is closed before proceeding. After establishing the connection,
the searchIndex table is prepared (and dropped if it already exists).
'''
i... | Can you implement a function in Python 3 that
opens a connection to the database. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Insert an entry into the Zeal database. | Given the following Python 3 function, write the documentation
def insert(self, name, entry_type, filename):
'''Insert an entry into the Zeal database.
Args:
name: A string representing the name of the entry.
entry_type: A string representing the entry type.
filename... | As a Python code composer, you craft elegant and concise scripts. |
Returns the data for the given spec - related fileset or Field. | Can you generate the documentation for the following Python 3 function
def data(self, name, subject_ids=None, visit_ids=None, session_ids=None,
**kwargs):
"""
Returns the Fileset(s) or Field(s) associated with the provided spec
name(s), generating derived filesets as required. Multi... | You are a Python code architect, reviewing and designing scalable and efficient code |
def branch(self, name, values=None): # @UnusedVariable @IgnorePep8
"""
Checks whether the given switch matches the value provided
Parameters
----------
name : str
The name of the parameter to retrieve
value : str | None
The value(s) of the switch... | Can you implement a function in Python 3 that
checks whether the given switch matches the given value. | As a Python code analyst, you investigate and solve complex coding mysteries |
This method raises an exception if a pipeline doesn t handle a particular switch value | Explain what the following Python 3 code does
def unhandled_branch(self, name):
raise ArcanaDesignError(
"'{}' value of '{}' switch in {} is not handled"
.format(self._get_parameter(name), name,
self._param_error_location)) | You are a Python code architect, reviewing and designing scalable and efficient code |
Saves a graph of the workflow for the given spec_name to fname. | Make a summary of the following Python 3 code
def save_workflow_graph_for(self, spec_name, fname, full=False,
style='flat', **kwargs):
"""
Saves a graph of the workflow to generate the requested spec_name
Parameters
----------
spec_name : str
... | You are a Python code generator, capable of creating scripts from specifications. |
Returns either the input corresponding to a fileset or field or a spec or a parameter that has either been passed to the study as an input or can be derived. | Can you generate a brief explanation for the following Python 3 code
def spec(self, name):
# If the provided "name" is actually a data item or parameter then
# replace it with its name.
if isinstance(name, (BaseData, Parameter)):
name = name.name
# If name is a parameter than... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def bound_spec(self, name):
"""
Returns an input selector or derived spec bound to the study, i.e.
where the repository tree is checked for existing outputs
Parameters
----------
name : Str
A name of a fileset or field
"""
# If the provided "n... | Write a Python 3 script to
return an input selector or derived spec bound to the study i. e. the input selector or derived spec bound to the study i. e. the repository tree is checked for existing outputs | As a python code expert, you are capable of creating scripts from specifications. |
Returns the fileset_spec i. e. the template of the fileset expected to
be supplied or generated corresponding to the fileset_spec name. | Explain what the following Python 3 code does
def data_spec(cls, name):
# If the provided "name" is actually a data item or parameter then
# replace it with its name.
if isinstance(name, BaseData):
name = name.name
try:
return cls._data_specs[name]
except ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Runs the Study s repository source node for each of the inputs
of the study. | Can you generate a brief explanation for the following Python 3 code
def cache_inputs(self):
workflow = pe.Workflow(name='cache_download',
base_dir=self.processor.work_dir)
subjects = pe.Node(IdentityInterface(['subject_id']), name='subjects',
en... | You are a Python code analyst, evaluating scripts for potential improvements. |
Checks to see if the corresponding data spec was provided an explicit input. | Can you generate the documentation for the following Python 3 function
def provided(self, spec_name, default_okay=True):
try:
spec = self.bound_spec(spec_name)
except ArcanaMissingDataException:
return False
if isinstance(spec, BaseInputSpec):
return spec.defa... | As a python code expert, you are capable of creating scripts from specifications. |
def freq_from_iterators(cls, iterators):
"""
Returns the frequency corresponding to the given iterators
"""
return {
set(it): f for f, it in cls.FREQUENCIES.items()}[set(iterators)] | Implement a function in Python 3 to
return the frequency corresponding to the given iterators | You are a Python code analyst, evaluating scripts for potential improvements. |
Extracts the provenance information from the study for storage alongside
| Make a summary of the following Python 3 code
def prov(self):
# Get list of repositories where inputs to the study are stored
input_repos = list(set((i.repository for i in self.inputs)))
inputs = {}
for input in self.inputs: # @ReservedAssignment
inputs[input.name] = {
... | As a python code expert, you are capable of creating scripts from specifications. |
def arm(self, level, code):
"""(Helper) Arm system at specified level (away, vacation, etc)"""
self._elk.send(al_encode(level, self._index, code)) | Create a Python 3 function to
arm system at specified level. | You are a Python code analyst, evaluating scripts for potential improvements. |
def display_message(self, clear, beep, timeout, line1, line2):
"""Display a message on all of the keypads in this area."""
self._elk.send(
dm_encode(self._index, clear, beep, timeout, line1, line2)
) | How would you implement a function in Python 3 that
displays a message on all of the keypads in this area. | You are a Python code analyst, evaluating scripts for potential improvements. |
Retrieve areas from ElkM1 | Here you have a function in Python 3, explain what it does
def sync(self):
self.elk.send(as_encode())
self.get_descriptions(TextDescriptions.AREA.value) | You are a Python code architect, reviewing and designing scalable and efficient code |
(Helper) Set light to specified level | How would you explain what the following Python 3 function does
def level(self, level, time=0):
if level <= 0:
self._elk.send(pf_encode(self._index))
elif level >= 98:
self._elk.send(pn_encode(self._index))
else:
self._elk.send(pc_encode(self._index, 9, level,... | You are a Python code architect, reviewing and designing scalable and efficient code |
Retrieve lights from ElkM1 | Can you generate the documentation for the following Python 3 function
def sync(self):
for i in range(4):
self.elk.send(ps_encode(i))
self.get_descriptions(TextDescriptions.LIGHT.value) | You are a Python code generator, capable of creating scripts from specifications. |
Returns the modification time of all files in a directory. | Explain what the following Python 3 code does
def dir_modtime(dpath):
return max(os.path.getmtime(d) for d, _, _ in os.walk(dpath)) | You are a Python code architect, reviewing and designing scalable and efficient code |
Parses a single value from the Arcana database into a single value. | Can you generate a brief explanation for the following Python 3 code
def parse_single_value(value):
if isinstance(value, basestring):
try:
if value.startswith('"') and value.endswith('"'):
value = str(value[1:-1])
elif '.' in value:
value = float(value... | As a python code expert, you are capable of creating scripts from specifications. |
Checks whether all the provided items are containers. | Can you generate a brief explanation for the following Python 3 code
def iscontainer(*items):
return all(isinstance(i, Iterable) and not isinstance(i, basestring)
for i in items) | You are a Python code architect, reviewing and designing scalable and efficient code |
def find_mismatch(first, second, indent=''):
"""
Finds where two objects differ, iterating down into nested containers
(i.e. dicts, lists and tuples) They can be nested containers
any combination of primary dtypes, str, int, float, dict and lists
Parameters
----------
first : dict | list | ... | Can you implement a function in Python 3 that
finds where two objects differ in nested containers and returns a string that contains the mismatch. | You are a Python code architect, reviewing and designing scalable and efficient code |
def deserialize(json_text=None):
"""Returns a generator of deserialized objects.
Wraps django deserialize with defaults for JSON
and natural keys.
See https://docs.djangoproject.com/en/2.1/topics/serialization/
"""
return serializers.deserialize(
"json",
json_text,
ens... | Create a Python 3 function to
return a generator of deserialized objects. | As a Python code composer, you craft elegant and concise scripts. |
Create token when a user is created. | Make a summary of the following Python 3 code
def create_auth_token(sender, instance, raw, created, **kwargs):
if not raw:
if created:
sender.objects.create(user=instance) | As a Python code analyst, you investigate and solve complex coding mysteries |
def serialize_m2m_on_save(sender, action, instance, using, **kwargs):
""" Part of the serialize transaction process that ensures m2m are
serialized correctly.
Skip those not registered.
"""
if action == "post_add":
try:
wrapped_instance = site_offline_models.get_wrapped_instance... | Write a Python 3 script to
serialize the m2m of the given object. | As a python code expert, you are capable of creating scripts from specifications. |
def serialize_on_save(sender, instance, raw, created, using, **kwargs):
""" Serialize the model instance as an OutgoingTransaction.
Skip those not registered.
"""
if not raw:
if "historical" not in instance._meta.label_lower:
try:
wrapped_instance = site_offline_mode... | How would you implement a function in Python 3 that
serializes the model instance as an OutgoingTransaction. | You are a Python code generator, capable of creating scripts from specifications. |
def serialize_history_on_post_create(history_instance, using, **kwargs):
""" Serialize the history instance as an OutgoingTransaction.
Skip those not registered.
"""
try:
wrapped_instance = site_offline_models.get_wrapped_instance(history_instance)
except ModelNotRegistered:
pass
... | Implement a Python 3 function for
serializing the history instance as an OutgoingTransaction. | As a Python code analyst, you investigate and solve complex coding mysteries |
def serialize_on_post_delete(sender, instance, using, **kwargs):
"""Creates a serialized OutgoingTransaction when
a model instance is deleted.
Skip those not registered.
"""
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pas... | Can you create a Python 3 function that
serializes a serialized OutgoingTransaction when a model instance is deleted. | As a Python code translator, you convert algorithms and pseudocode into Python. |
(Helper) Set custom value. | Make a summary of the following Python 3 code
def set(self, value):
self._elk.send(cw_encode(self._index, value, self.value_format)) | As a python code expert, you are capable of creating scripts from specifications. |
Retrieve custom values from ElkM1 | Can you generate a brief explanation for the following Python 3 code
def sync(self):
self.elk.send(cp_encode())
self.get_descriptions(TextDescriptions.SETTING.value) | You are a Python code architect, reviewing and designing scalable and efficient code |
Iterates through all files in the set and returns a list of all paths in the set. | Make a summary of the following Python 3 code
def paths(self):
if self.format is None:
raise ArcanaFileFormatError(
"Cannot get paths of fileset ({}) that hasn't had its format "
"set".format(self))
if self.format.directory:
return chain(*((op.join... | You are a Python code generator, capable of creating scripts from specifications. |
Detects the format of the fileset from a list of possible file - formats. | Explain what the following Python 3 code does
def detect_format(self, candidates):
if self._format is not None:
raise ArcanaFileFormatError(
"Format has already been set for {}".format(self))
matches = [c for c in candidates if c.matches(self)]
if not matches:
... | As a Python code composer, you craft elegant and concise scripts. |
Tests the equality of the contents of this fileset with another fileset. | Make a summary of the following Python 3 code
def contents_equal(self, other, **kwargs):
if hasattr(self.format, 'contents_equal'):
equal = self.format.contents_equal(self, other, **kwargs)
else:
equal = (self.checksums == other.checksums)
return equal | As a Python code analyst, you investigate and solve complex coding mysteries |
def bind(self, study, **kwargs): # @UnusedVariable
"""
Returns a copy of the AcquiredSpec bound to the given study
Parameters
----------
study : Study
A study to bind the fileset spec to (should happen in the
study __init__)
"""
if self.d... | Create a Python 3 function to
return a copy of the AcquiredSpec bound to the given study. | You are a Python code generator, capable of creating scripts from specifications. |
def bind(self, study, **kwargs): # @UnusedVariable
"""
Returns a copy of the Spec bound to the given study
Parameters
----------
study : Study
A study to bind the fileset spec to (should happen in the
study __init__)
"""
if self._study is... | Write a Python 3 function that can
return a copy of the Spec bound to the given study | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the relevant nodes for the spec s frequency | How would you explain what the following Python 3 function does
def nodes(self, tree):
# Run the match against the tree
if self.frequency == 'per_session':
nodes = []
for subject in tree.subjects:
for sess in subject.sessions:
nodes.append(sess... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def derivable(self):
"""
Whether the spec (only valid for derived specs) can be derived
given the inputs and switches provided to the study
"""
try:
# Just need to iterate all study inputs and catch relevant
# exceptions
list(self.pipeline.stud... | Can you create a Python 3 function that
returns True if the spec can be derived from the study s base_specs and the study s inputs and switches provided to the study s base_specs. | As a Python code composer, you craft elegant and concise scripts. |
Re - establish connection to all instances | Can you generate a brief explanation for the following Python 3 code
def reconnect_all(self):
for role in self.Instances.keys():
for connection in self.Instances[role]:
connection.reconnect() | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add instance to the list of instances that are in the list of hosts that are connected to the specified role. | Can you tell what is the following Python 3 function doing
def add_instance(self,
role,
instance,
username='root',
key_filename=None,
output_shell=False):
"""
Add instance to the setup
@param rol... | You are a Python code architect, reviewing and designing scalable and efficient code |
Setup from yaml file | Explain what the following Python 3 code does
def setup_from_yamlfile(self, yamlfile, output_shell=False):
self.logger.debug('Loading config from ' + yamlfile)
with open(yamlfile, 'r') as yamlfd:
yamlconfig = yaml.load(yamlfd)
for instance in yamlconfig['Instances']:
... | As a Python code composer, you craft elegant and concise scripts. |
helper function to iterate over a process stdout and report error messages when done
| Can you tell what is the following Python 3 function doing
def process_iter(proc, cmd=""):
try:
for l in proc.stdout:
yield l
finally:
if proc.poll() is None:
# there was an exception
return
else:
proc.wait()
if proc.returncode ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def is_newer_b(a, bfiles):
"""
check that all b files have been modified more recently than a
"""
if isinstance(bfiles, basestring):
bfiles = [bfiles]
if not op.exists(a): return False
if not all(op.exists(b) for b in bfiles): return False
atime = os.stat(a).st_mtime # modification... | Can you implement a function in Python 3 that
checks that all b files have been modified more recently than a | You are a Python code analyst, evaluating scripts for potential improvements. |
Expect a list of expressions and associated return values | Can you generate the documentation for the following Python 3 function
def expect_list(connection, regexp_list, timeout=10):
'''
Expect a list of expressions
@param connection: Connection to the host
@type connection: L{Connection}
@param regexp_list: regular expressions and as... | As a python code expert, you are capable of creating scripts from specifications. |
def expect(connection, strexp, timeout=10):
'''
Expect one expression
@param connection: Connection to the host
@type connection: L{Connection}
@param strexp: string to convert to expression (.*string.*)
@type strexp: str
@param timeout: timeout for performing ... | How would you code a function in Python 3 to
expect one expression @param connection: Connection to the host @type connection: L{Connection} @param strexp: string to convert to expression (.*string.*) @type strexp: str @param timeout: timeout for performing expect operation @type timeout: int @return: True if succeeded... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Match against an expression and return the result. | Here you have a function in Python 3, explain what it does
def match(connection, regexp, grouplist=[1], timeout=10):
'''
Match against an expression
@param connection: Connection to the host
@type connection: L{Connection}
@param regexp: compiled regular expression
@typ... | As a python code expert, you are capable of creating scripts from specifications. |
Execute a command and wait for something to happen | Can you generate a brief explanation for the following Python 3 code
def ping_pong(connection, command, strexp, timeout=10):
'''
Enter a command and wait for something to happen (enter + expect
combined)
@param connection: connection to the host
@type connection: L{Connection}
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Run command and expect specified return value | Can you generate a brief explanation for the following Python 3 code
def expect_retval(connection, command, expected_status=0, timeout=10):
'''
Run command and expect specified return valud
@param connection: connection to the host
@type connection: L{Connection}
@param command... | As a Python code analyst, you investigate and solve complex coding mysteries |
def sync(self):
"""Retrieve areas from ElkM1"""
self.elk.send(ka_encode())
self.get_descriptions(TextDescriptions.KEYPAD.value) | How would you code a function in Python 3 to
retrieve areas from ElkM1 | As a python code expert, you are capable of creating scripts from specifications. |
Yield tags matching the tag criterion from a soup. | How would you explain what the following Python 3 function does
def find(self, soup):
'''Yield tags matching the tag criterion from a soup.
There is no need to override this if you are satisfied with finding
tags that match match_criterion.
Args:
soup: A BeautifulSoup to se... | You are a Python code generator, capable of creating scripts from specifications. |
def get_name(self, tag):
'''Extract and return a representative "name" from a tag.
Override as necessary. get_name's output can be controlled through
keyword arguments that are provided when initializing a
TagProcessor. For instance, a member of a class or namespace can have
its... | How would you code a function in Python 3 to
extract and return a representative name from a tag. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_filename(self, tag):
'''Extract and return a documentation filename from a tag.
Override as necessary, though this default implementation probably
covers all the cases of interest.
Args:
tag: A BeautifulSoup Tag that satisfies match_criterion.
Returns:
... | How would you implement a function in Python 3 that
extracts and return a documentation filename from a tag. | As a Python code analyst, you investigate and solve complex coding mysteries |
Override. Determine if a tag has the desired name and kind attribute
value. | Can you generate a brief explanation for the following Python 3 code
def match_criterion(self, tag):
'''Override. Determine if a tag has the desired name and kind attribute
value.
Args:
tag: A BeautifulSoup Tag.
Returns:
True if tag has the desired name and kind... | You are a Python code analyst, evaluating scripts for potential improvements. |
Override. Extract a representative name from a function tag. | Can you generate the documentation for the following Python 3 function
def get_name(self, tag):
'''Override. Extract a representative "name" from a function tag.
get_name's output can be controlled through keyword arguments that are
provided when initializing a functionTagProcessor. For instanc... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_entry_type(self, tag):
'''Override that returns u'Method' for class/struct methods.
Override as necessary.
Args:
tag: A BeautifulSoup Tag for a function.
Returns:
If this is a class/struct method, returns u'Method', otherwise
returns the val... | Implement a Python 3 function for
overriding that returns uMethod for class or struct methods. Override as necessary. | As a python code expert, you are capable of creating scripts from specifications. |
create a multiprocessing pool that responds to interrupts. | Explain what the following Python 3 code does
def pool(n=None, dummy=False):
if dummy:
from multiprocessing.dummy import Pool
else:
from multiprocessing import Pool
if n is None:
import multiprocessing
n = multiprocessing.cpu_count() - 1
return Pool(n) | As a python code expert, you are capable of creating scripts from specifications. |
def pmap(f, iterable, n=None, dummy=False, p=None):
"""
parallel map of a function to an iterable
if each item in iterable is itself an iterable, then
automatically call f(*item) instead of f(item)
Arguments:
f: function
iterable: any iterable where each item is sent to f
n: numbe... | Write a Python 3 script to
parallel map of a function to an iterable if each item in iterable is itself an iterable, then automatically call f(*item) instead of f(item) Arguments: f: function iterable: any iterable where each item is sent to f n: number of cpus (default is number on machine) dummy: use dummy pool. p: e... | As a python code expert, you are capable of creating scripts from specifications. |
def _call_callbacks(self):
"""Callbacks when attribute of element changes"""
for callback in self._callbacks:
callback(self, self._changeset)
self._changeset = {} | Write a Python 3 function that can
call all callbacks when attribute of element changes | You are a Python code architect, reviewing and designing scalable and efficient code |
def setattr(self, attr, new_value, close_the_changeset=True):
"""If attribute value has changed then set it and call the callbacks"""
existing_value = getattr(self, attr, None)
if existing_value != new_value:
setattr(self, attr, new_value)
self._changeset[attr] = new_valu... | Create a Python 3 function for
setting the attribute of the object to new_value. If the attribute value has changed then set it and call the callbacks. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def default_name(self, separator='-'):
"""Return a default name for based on class and index of element"""
return self.__class__.__name__ + '{}{:03d}'.format(
separator, self._index+1) | Can you write a function in Python 3 where it
returns a default name for based on class and index of element | As a Python code translator, you convert algorithms and pseudocode into Python. |
def as_dict(self):
"""Package up the public attributes as a dict."""
attrs = vars(self)
return {key: attrs[key] for key in attrs if not key.startswith('_')} | Can you create a Python 3 function that
packages up the public attributes as a dict. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_descriptions(self, description_type):
"""
Gets the descriptions for specified type.
When complete the callback is called with a list of descriptions
"""
(desc_type, max_units) = description_type
results = [None] * max_units
self.elk._descriptions_in_progre... | Create a Python 3 function to
get the descriptions for the specified type. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the canonical url of the page. | Here you have a function in Python 3, explain what it does
def page_url(self) -> str:
url = self.attributes['canonicalurl']
assert isinstance(url, str)
return url | You are a Python code analyst, evaluating scripts for potential improvements. |
Determine the normalized locale code string. | Given the following Python 3 function, write the documentation
def normalize_locale_code(locale: Union[Locale, str]) -> str:
if not isinstance(locale, Locale):
locale = Locale.parse(locale.replace('-', '_'))
return str(locale) | You are a Python code generator, capable of creating scripts from specifications. |
Get a Wikidata entity by its entity id. | Given the following Python 3 function, write the documentation
def get(self, entity_id: EntityId, load: bool = False) -> Entity:
try:
entity = self.identity_map[entity_id]
except KeyError:
entity = Entity(entity_id, self)
self.identity_map[entity_id] = entity
... | As a Python code composer, you craft elegant and concise scripts. |
def guess_entity_type(self, entity_id: EntityId) -> Optional[EntityType]:
r"""Guess :class:`~.entity.EntityType` from the given
:class:`~.entity.EntityId`. It could return :const:`None` when it
fails to guess.
.. note::
It always fails to guess when :attr:`entity_type_guess... | Create a Python 3 function to
guess the entity type from the given entity id. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Decode the given datavalue using the configured datavalue_decoder. | How would you explain what the following Python 3 function does
def decode_datavalue(self,
datatype: str,
datavalue: Mapping[str, object]) -> object:
"""Decode the given ``datavalue`` using the configured
:attr:`datavalue_decoder`.
.. versionadd... | You are a Python code architect, reviewing and designing scalable and efficient code |
def set(self, key: CacheKey, value: Optional[CacheValue]) -> None:
r"""Create or update a cache.
:param key: A key string to create or update.
:type key: :const:`CacheKey`
:param value: A value to cache. :const:`None` to remove cache.
:type value: :class:`~typing.Optional`\ [:c... | Write a Python 3 script to
create or update a cache. | As a Python code composer, you craft elegant and concise scripts. |
r Returns all values associated to the given key property
in sequence. | Here you have a function in Python 3, explain what it does
def getlist(self, key: 'Entity') -> Sequence[object]:
if not (isinstance(key, type(self)) and
key.type is EntityType.property):
return []
claims_map = self.attributes.get('claims') or {}
assert isinstance(clai... | You are a Python code generator, capable of creating scripts from specifications. |
def type(self) -> EntityType:
"""(:class:`EntityType`) The type of entity, :attr:`~EntityType.item`
or :attr:`~EntityType.property`.
.. versionadded:: 0.2.0
"""
if self.data is None:
guessed_type = self.client.guess_entity_type(self.id)
if guessed_type i... | Implement a Python 3 function for
returning the type of the entity. | As a Python code composer, you craft elegant and concise scripts. |
def make_user_role_table(table_name='user', id_column_name='id'):
"""
Create the user-role association table so that
it correctly references your own UserMixin subclass.
"""
return db.Table('fp_user_role',
db.Column(
'user_id', db.Integer, ... | Can you create a Python 3 function that
creates the user - role association table so that the user - role table correctly references your own UserMixin subclass. | You are a Python code architect, reviewing and designing scalable and efficient code |
def user_has(ability, get_user=import_user):
"""
Takes an ability (a string name of either a role or an ability) and returns the function if the user has that ability
"""
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
from .models import Ability
desir... | Write a Python 3 script to
take an ability (a string name of either a role or an ability) and returns the function if the user has that ability | As a Python code composer, you craft elegant and concise scripts. |
Decorator that returns a function if the user has the specified role | Can you generate a brief explanation for the following Python 3 code
def user_is(role, get_user=import_user):
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
from .models import Role
current_user = get_user()
if role in current_user.roles:
... | As a Python code composer, you craft elegant and concise scripts. |
def combo_serve(request, path, client):
"""
Handles generating a 'combo' file for the given path. This is similar to
what happens when we upload to S3. Processors are applied, and we get
the value that we would if we were serving from S3. This is a good way
to make sure combo files work as intended ... | Write a Python 3 script to
generate a combo file for the given path. | You are a Python code architect, reviewing and designing scalable and efficient code |
Given a URL path return a key that can be used for the URL path. | Can you tell what is the following Python 3 function doing
def _form_key_str(path):
if path.endswith('.css'):
media_path_prefix = msettings['CSS_PATH']
elif path.endswith('.js'):
media_path_prefix = msettings['JS_PATH']
else:
# This isn't a CSS/JS file, no combo for you.
retu... | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.