output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Returns the subject and session labels given the frequency and IDs of the items.
Here you have a function in Python 3, explain what it does def _get_item_labels(self, item, no_from_study=False): subject_id = self.inv_map_subject_id(item.subject_id) visit_id = self.inv_map_visit_id(item.visit_id) subj_label, sess_label = self._get_labels( item.frequency, subject_i...
As a python code expert, you are capable of creating scripts from specifications.
def _get_labels(self, frequency, subject_id=None, visit_id=None): """ Returns the labels for the XNAT subject and sessions given the frequency and provided IDs. """ if frequency == 'per_session': subj_label = '{}_{}'.format(self.project_id, ...
How would you implement a function in Python 3 that returns the labels for the XNAT subject and session given the frequency and provided IDs.
As a Python code composer, you craft elegant and concise scripts.
Turn on an output
Can you generate the documentation for the following Python 3 function def turn_on(self, time): self._elk.send(cn_encode(self._index, time))
As a Python code composer, you craft elegant and concise scripts.
Retrieve areas from ElkM1
How would you explain what the following Python 3 function does def sync(self): self.elk.send(cs_encode()) self.get_descriptions(TextDescriptions.OUTPUT.value)
As a Python code composer, you craft elegant and concise scripts.
Try to detect version of package from command help text.
How would you explain what the following Python 3 function does def detect_version_str(self): help_text = run_matlab_cmd("help('{}')".format(self.test_func)) if not help_text: raise ArcanaRequirementNotFoundError( "Did not find test function '{}' for {}" .form...
As a Python code translator, you convert algorithms and pseudocode into Python.
Return target heating level.
Make a summary of the following Python 3 code def target_heating_level(self): try: if self.side == 'left': level = self.device.device_data['leftTargetHeatingLevel'] elif self.side == 'right': level = self.device.device_data['rightTargetHeatingLevel'] ...
As a python code expert, you are capable of creating scripts from specifications.
Return a heating level from the past.
Can you generate the documentation for the following Python 3 function def past_heating_level(self, num): if num > 9: return 0 try: if self.side == 'left': level = self.device.device_data_history[ num]['leftHeatingLevel'] elif self...
You are a Python code analyst, evaluating scripts for potential improvements.
Return current heating state.
Can you generate the documentation for the following Python 3 function def now_heating(self): try: if self.side == 'left': heat = self.device.device_data['leftNowHeating'] elif self.side == 'right': heat = self.device.device_data['rightNowHeating'] ...
You are a Python code architect, reviewing and designing scalable and efficient code
def heating_remaining(self): """Return seconds of heat time remaining.""" try: if self.side == 'left': timerem = self.device.device_data['leftHeatingDuration'] elif self.side == 'right': timerem = self.device.device_data['rightHeatingDuration'] ...
Create a Python 3 function to return seconds of heat time remaining.
You are a Python code architect, reviewing and designing scalable and efficient code
def last_seen(self): """Return mattress last seen time.""" """ These values seem to be rarely updated correctly in the API. Don't expect accurate results from this property. """ try: if self.side == 'left': lastseen = self.device.device_data['l...
Implement a function in Python 3 to return last seen time.
As a Python code analyst, you investigate and solve complex coding mysteries
def heating_values(self): """Return a dict of all the current heating values.""" heating_dict = { 'level': self.heating_level, 'target': self.target_heating_level, 'active': self.now_heating, 'remaining': self.heating_remaining, 'last_seen': se...
Can you write a function in Python 3 where it returns a dict of all the current heating values.
You are a Python code architect, reviewing and designing scalable and efficient code
Return sleep stage for in - progress session.
Can you tell what is the following Python 3 function doing def current_sleep_stage(self): try: stages = self.intervals[0]['stages'] num_stages = len(stages) if num_stages == 0: return None # API now always has an awake state last in the dict ...
As a python code expert, you are capable of creating scripts from specifications.
Return durations of sleep stages for in - progress session.
Can you generate the documentation for the following Python 3 function def current_sleep_breakdown(self): try: stages = self.intervals[0]['stages'] breakdown = {'awake': 0, 'light': 0, 'deep': 0, 'rem': 0} for stage in stages: if stage['stage'] == 'awake': ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Return current bed temperature for in - progress session.
Here you have a function in Python 3, explain what it does def current_bed_temp(self): try: bedtemps = self.intervals[0]['timeseries']['tempBedC'] num_temps = len(bedtemps) if num_temps == 0: return None bedtemp = bedtemps[num_temps-1][1] ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def current_room_temp(self): """Return current room temperature for in-progress session.""" try: rmtemps = self.intervals[0]['timeseries']['tempRoomC'] num_temps = len(rmtemps) if num_temps == 0: return None rmtemp = rmtemps[num_temps-1][...
Can you create a Python 3 function that returns current room temperature for in - progress session.
As a Python code analyst, you investigate and solve complex coding mysteries
Return current respiratory rate for in - progress session.
Can you generate a brief explanation for the following Python 3 code def current_resp_rate(self): try: rates = self.intervals[0]['timeseries']['respiratoryRate'] num_rates = len(rates) if num_rates == 0: return None rate = rates[num_rates-1][1] ...
As a Python code composer, you craft elegant and concise scripts.
def current_heart_rate(self): """Return current heart rate for in-progress session.""" try: rates = self.intervals[0]['timeseries']['heartRate'] num_rates = len(rates) if num_rates == 0: return None rate = rates[num_rates-1][1] ex...
Write a Python 3 script for returning current heart rate for in - progress session.
You are a Python code architect, reviewing and designing scalable and efficient code
Return a dict of all the current parameters.
Explain what the following Python 3 code does def current_values(self): current_dict = { 'date': self.current_session_date, 'score': self.current_sleep_score, 'stage': self.current_sleep_stage, 'breakdown': self.current_sleep_breakdown, 'tnt': self.cur...
You are a Python code generator, capable of creating scripts from specifications.
def last_session_date(self): """Return date/time for start of last session data.""" try: date = self.intervals[1]['ts'] except KeyError: return None date_f = datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%fZ') now = time.time() offset = datetime.fromt...
Can you create a Python 3 function that returns date and time for start of last session data.
As a python code expert, you are capable of creating scripts from specifications.
def last_sleep_breakdown(self): """Return durations of sleep stages for last complete session.""" try: stages = self.intervals[1]['stages'] except KeyError: return None breakdown = {'awake': 0, 'light': 0, 'deep': 0, 'rem': 0} for stage in stages: ...
Implement a Python 3 function for returning durations of sleep stages for last complete session.
As a Python code translator, you convert algorithms and pseudocode into Python.
def last_bed_temp(self): """Return avg bed temperature for last session.""" try: bedtemps = self.intervals[1]['timeseries']['tempBedC'] except KeyError: return None tmp = 0 num_temps = len(bedtemps) if num_temps == 0: return None ...
Write a Python 3 script to return avg bed temperature for last session.
As a Python code composer, you craft elegant and concise scripts.
def last_room_temp(self): """Return avg room temperature for last session.""" try: rmtemps = self.intervals[1]['timeseries']['tempRoomC'] except KeyError: return None tmp = 0 num_temps = len(rmtemps) if num_temps == 0: return None ...
Implement a function in Python 3 to return avg room temperature for last session.
You are a Python code generator, capable of creating scripts from specifications.
def last_heart_rate(self): """Return avg heart rate for last session.""" try: rates = self.intervals[1]['timeseries']['heartRate'] except KeyError: return None tmp = 0 num_rates = len(rates) if num_rates == 0: return None for ...
Write a Python 3 script to return the average heart rate for last session.
You are a Python code analyst, evaluating scripts for potential improvements.
Return a dict of all the last parameters.
Can you generate a brief explanation for the following Python 3 code def last_values(self): last_dict = { 'date': self.last_session_date, 'score': self.last_sleep_score, 'breakdown': self.last_sleep_breakdown, 'tnt': self.last_tnt, 'bed_temp': self.las...
As a Python code translator, you convert algorithms and pseudocode into Python.
def heating_stats(self): """Calculate some heating data stats.""" local_5 = [] local_10 = [] for i in range(0, 10): level = self.past_heating_level(i) if level == 0: _LOGGER.debug('Cant calculate stats yet...') return i...
Can you write a function in Python 3 where it calculates some heating data stats.
You are a Python code architect, reviewing and designing scalable and efficient code
def dynamic_presence(self): """ Determine presence based on bed heating level and end presence time reported by the api. Idea originated from Alex Lee Yuk Cheung SmartThings Code. """ # self.heating_stats() if not self.presence: if self.heating_leve...
How would you implement a function in Python 3 that determines presence based on the heating level and end presence of the resource.
As a Python code composer, you craft elegant and concise scripts.
Update heating data json.
Can you tell what is the following Python 3 function doing async def set_heating_level(self, level, duration=0): url = '{}/devices/{}'.format(API_URL, self.device.deviceid) # Catch bad inputs level = 10 if level < 10 else level level = 100 if level > 100 else level if self.side...
As a Python code composer, you craft elegant and concise scripts.
Update trends data json for specified time period.
Can you generate the documentation for the following Python 3 function async def update_trend_data(self, startdate, enddate): url = '{}/users/{}/trends'.format(API_URL, self.userid) params = { 'tz': self.device.tzone, 'from': startdate, 'to': enddate } ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Update intervals data json for specified time period.
Can you generate a brief explanation for the following Python 3 code async def update_intervals_data(self): url = '{}/users/{}/intervals'.format(API_URL, self.userid) intervals = await self.device.api_get(url) if intervals is None: _LOGGER.error('Unable to fetch eight intervals data...
You are a Python code architect, reviewing and designing scalable and efficient code
Saves a deserialized model object.
Can you generate a brief explanation for the following Python 3 code def save(obj=None, m2m_data=None): m2m_data = {} if m2m_data is None else m2m_data obj.save_base(raw=True) for attr, values in m2m_data.items(): for value in values: getattr(obj, attr).add(value)
You are a Python code analyst, evaluating scripts for potential improvements.
Runs json_text thru custom parsers.
Explain what the following Python 3 code does def custom_parser(self, json_text=None): app_config = django_apps.get_app_config("django_collect_offline") for json_parser in app_config.custom_json_parsers: json_text = json_parser(json_text) return json_text
You are a Python code generator, capable of creating scripts from specifications.
def channel(self): """ channel lazy property """ # start shell, non-blocking channel chan = self.cli.invoke_shell(width=360, height=80) chan.setblocking(0) # set channel timeout chan.settimeout(10) # now waiting for shell prompt ('username@') result = "" ...
Can you create a Python 3 function that gets channel lazy property
You are a Python code analyst, evaluating scripts for potential improvements.
def disconnect(self): """ Close the connection """ if hasattr(self, '_lazy_sftp'): if self.sftp is not None: self.sftp.close() delattr(self, '_lazy_sftp') if hasattr(self, '_lazy_channel'): if self.channel is not None: ...
Write a Python 3 function that can disconnect from the internal state of the object.
You are a Python code analyst, evaluating scripts for potential improvements.
def exec_command(self, command, bufsize=-1, get_pty=False): """ Execute a command in the connection @param command: command to execute @type command: str @param bufsize: buffer size @type bufsize: int @param get_pty: get pty @type get_pty: bool ...
How would you code a function in Python 3 to execute a command in the connection and return the stdout and stderr of the command.
You are a Python code analyst, evaluating scripts for potential improvements.
def recv_exit_status(self, command, timeout=10, get_pty=False): """ Execute a command and get its return value @param command: command to execute @type command: str @param timeout: command execution timeout @type timeout: int @param get_pty: get pty @ty...
How would you implement a function in Python 3 that executes a command and get its return value
You are a Python code analyst, evaluating scripts for potential improvements.
Set the value of the current counter.
Make a summary of the following Python 3 code def set(self, value): self._elk.send(cx_encode(self._index, value))
As a Python code composer, you craft elegant and concise scripts.
Saves the provenance object to a JSON file optionally including checksums for inputs and outputs.
Can you generate the documentation for the following Python 3 function def save(self, path): with open(path, 'w') as f: try: json.dump(self.prov, f, indent=2) except TypeError: raise ArcanaError( "Could not serialise provenance record d...
You are a Python code analyst, evaluating scripts for potential improvements.
Loads a saved provenance object from a JSON file.
Can you generate the documentation for the following Python 3 function def load(cls, pipeline_name, frequency, subject_id, visit_id, from_study, path): """ Loads a saved provenance object from a JSON file Parameters ---------- path : str Path to the prov...
As a Python code composer, you craft elegant and concise scripts.
Compares two provenance objects and returns a dictionary of differences between those objects.
Can you tell what is the following Python 3 function doing def mismatches(self, other, include=None, exclude=None): if include is not None: include_res = [self._gen_prov_path_regex(p) for p in include] if exclude is not None: exclude_res = [self._gen_prov_path_regex(p) for p in e...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a method that returns a new method that calls the pipeline_getter with the given name_maps and returns the new method that returns the new instance of the class with the translated name_maps.
Given the following Python 3 function, write the documentation def translate(cls, substudy_name, pipeline_getter, auto_added=False): assert isinstance(substudy_name, basestring) assert isinstance(pipeline_getter, basestring) def translated_getter(self, **name_maps): substudy_spec = ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def auto_data_specs(self): """ Data specs in the sub-study class that are not explicitly provided in the name map """ for spec in self.study_class.data_specs(): if spec.name not in self._name_map: yield spec
Create a Python 3 function for returning an iterator over the data specs that are not explicitly provided by the name map.
You are a Python code architect, reviewing and designing scalable and efficient code
Cast generated nodes to Arcana Nodes
Can you generate the documentation for the following Python 3 function def _make_nodes(self, cwd=None): for i, node in NipypeMapNode._make_nodes(self, cwd=cwd): # "Cast" NiPype node to a Arcana Node and set Arcana Node # parameters node.__class__ = self.node_cls n...
As a Python code analyst, you investigate and solve complex coding mysteries
Find file matching query_name read and return query object
Given the following Python 3 function, write the documentation def get_query(query_name): query_file_match = list( filter(lambda i: query_name == i.stem, FLAT_QUERIES)) if not query_file_match: return None # TODO: Log warning if more than one match query_file = query_file_match[0] wi...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_result_set(query_name, **kwargs): """ Call get_query, then submit query from file to resultset module """ query = get_query(query_name) if not query: query = SimpleNamespace() query.error = f"No query found matching '{query_name}'" return query try: result_mod...
Write a Python 3 script to call get_query then submit query to resultset module
As a Python code composer, you craft elegant and concise scripts.
def results_to_csv(query_name, **kwargs): """ Generate CSV from result data """ query = get_result_set(query_name, **kwargs) result = query.result columns = list(result[0].keys()) data = [tuple(row.values()) for row in result] frame = tablib.Dataset() frame.headers = columns for row ...
Can you write a function in Python 3 where it generates CSV from result set
As a Python code analyst, you investigate and solve complex coding mysteries
def register(self, models=None, wrapper_cls=None): """Registers with app_label.modelname, wrapper_cls. """ self.loaded = True for model in models: model = model.lower() if model not in self.registry: self.registry.update({model: wrapper_cls or self...
Write a Python 3 script to register with app_label. modelname wrapper_cls.
As a Python code composer, you craft elegant and concise scripts.
Registers all models for this app_label.
Given the following Python 3 function, write the documentation def register_for_app( self, app_label=None, exclude_models=None, exclude_model_classes=None ): """Registers all models for this app_label. """ models = [] exclude_models = exclude_models or [] app_config =...
You are a Python code generator, capable of creating scripts from specifications.
def get_wrapped_instance(self, instance=None): """Returns a wrapped model instance. """ if instance._meta.label_lower not in self.registry: raise ModelNotRegistered(f"{repr(instance)} is not registered with {self}.") wrapper_cls = self.registry.get(instance._meta.label_lower)...
How would you implement a function in Python 3 that returns a wrapped model instance.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a dictionary of registered models.
How would you explain what the following Python 3 function does def site_models(self, app_label=None): site_models = {} app_configs = ( django_apps.get_app_configs() if app_label is None else [django_apps.get_app_config(app_label)] ) for app_config in ...
As a Python code analyst, you investigate and solve complex coding mysteries
Get the path of the fileset from the repository.
How would you explain what the following Python 3 function does def get_fileset(self, fileset): # Don't need to cache fileset as it is already local as long # as the path is set if fileset._path is None: primary_path = self.fileset_path(fileset) aux_files = fileset.format...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_field(self, field): """ Update the value of the field from the repository """ # Load fields JSON, locking to prevent read/write conflicts # Would be better if only checked if locked to allow # concurrent reads but not possible with multi-process # locks (i...
Write a Python 3 function for getting the value of the field from the repository
As a Python code translator, you convert algorithms and pseudocode into Python.
def put_fileset(self, fileset): """ Inserts or updates a fileset in the repository """ target_path = self.fileset_path(fileset) if op.isfile(fileset.path): shutil.copyfile(fileset.path, target_path) # Copy side car files into repository for aux...
Create a Python 3 function for inserting or updates a fileset in the repository.
As a python code expert, you are capable of creating scripts from specifications.
def put_field(self, field): """ Inserts or updates a field in the repository """ fpath = self.fields_json_path(field) # Open fields JSON, locking to prevent other processes # reading or writing with InterProcessLock(fpath + self.LOCK_SUFFIX, logger=logger): ...
Create a Python 3 function to insert or updates a field in the repository
As a Python code analyst, you investigate and solve complex coding mysteries
Find all data within a repository and return a list of all the filesets fields and provenance records.
Explain what the following Python 3 code does def find_data(self, subject_ids=None, visit_ids=None, **kwargs): all_filesets = [] all_fields = [] all_records = [] for session_path, dirs, files in os.walk(self.root_dir): relpath = op.relpath(session_path, self.root_dir) ...
As a Python code composer, you craft elegant and concise scripts.
def guess_depth(self, root_dir): """ Try to guess the depth of a directory repository (i.e. whether it has sub-folders for multiple subjects or visits, depending on where files and/or derived label files are found in the hierarchy of sub-directories under the root dir. P...
Implement a Python 3 function for trying to guess the depth of a directory repository.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_data_source(query): """ Get data source connection metadata based on config. Prefer, in order: - Query file frontmatter - `db.yaml` file in query subdirectory - DATABASE_URL in environment To allow for possible non-SQL sources to be contributed, we only return a config value...
How would you code a function in Python 3 to get the data source from the database.
As a python code expert, you are capable of creating scripts from specifications.
def item(self, subject_id=None, visit_id=None): """ Returns a particular fileset|field in the collection corresponding to the given subject and visit_ids. subject_id and visit_id must be provided for relevant frequencies. Note that subject_id/visit_id can also be provided for non...
Implement a Python 3 function for returning a particular fileset|field in the collection corresponding to the given subject and visit ids.
As a python code expert, you are capable of creating scripts from specifications.
Bind the study to the source and sink initiation.
Given the following Python 3 function, write the documentation def bind(self, study, **kwargs): # @UnusedVariable if self.frequency == 'per_subject': tree_subject_ids = list(study.tree.subject_ids) subject_ids = list(self._collection.keys()) if tree_subject_ids != subject_id...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the fileset with the given name produced by the given study or from the given spec.
Here you have a function in Python 3, explain what it does def fileset(self, name, from_study=None, format=None): # @ReservedAssignment @IgnorePep8 if isinstance(name, BaseFileset): if from_study is None and name.derived: from_study = name.study.name name = name.name ...
You are a Python code architect, reviewing and designing scalable and efficient code
def field(self, name, from_study=None): """ Gets the field named 'name' produced by the Study named 'study' if provided. If a spec is passed instead of a str to the name argument, then the study will be set from the spec iff it is derived Parameters ---------- na...
Can you create a Python 3 function that gets the field with the given name produced by the given study.
As a Python code composer, you craft elegant and concise scripts.
Returns the provenance record for a given pipeline and from_study.
Can you generate a brief explanation for the following Python 3 code def record(self, pipeline_name, from_study): try: return self._records[(pipeline_name, from_study)] except KeyError: found = [] for sname, pnames in groupby(sorted(self._records, ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a string that contains the string that contains the mismatch of two TreeNode objects.
Can you generate the documentation for the following Python 3 function def find_mismatch(self, other, indent=''): if self != other: mismatch = "\n{}{}".format(indent, type(self).__name__) else: mismatch = '' sub_indent = indent + ' ' if len(list(self.filesets)) !...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns an iterator over all nodes in the tree for the specified frequency.
Can you tell what is the following Python 3 function doing def nodes(self, frequency=None): if frequency is None: nodes = chain(*(self._nodes(f) for f in ('per_study', 'per_subject', 'per_visit', 'per_session'))) else: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Used in debugging unittests
Make a summary of the following Python 3 code def find_mismatch(self, other, indent=''): mismatch = super(Tree, self).find_mismatch(other, indent) sub_indent = indent + ' ' if len(list(self.subjects)) != len(list(other.subjects)): mismatch += ('\n{indent}mismatching subject lengths ...
You are a Python code analyst, evaluating scripts for potential improvements.
def _fill_empty_sessions(self, fill_subjects, fill_visits): """ Fill in tree with additional empty subjects and/or visits to allow the study to pull its inputs from external repositories """ if fill_subjects is None: fill_subjects = [s.id for s in self.subjects] ...
Write a Python 3 script to fill in tree with additional empty subjects and or visits to maintain order.
As a Python code composer, you craft elegant and concise scripts.
Constructs a new tree of all filesets fields and records and stores the summary for later tree of filesets and fields.
How would you explain what the following Python 3 function does def construct(cls, repository, filesets=(), fields=(), records=(), file_formats=(), **kwargs): """ Return the hierarchical tree of the filesets and fields stored in a repository Parameters --------...
You are a Python code analyst, evaluating scripts for potential improvements.
def nodes(self, frequency=None): """ Returns all nodes of the specified frequency that are related to the given Session Parameters ---------- frequency : str | None The frequency of the nodes to return Returns ------- nodes : iterable...
Write a Python 3 function for returning all nodes related to the Session for the specified frequency
You are a Python code generator, capable of creating scripts from specifications.
def write_data(self, data, response_required=None, timeout=5.0, raw=False): """Write data on the asyncio Protocol""" if self._transport is None: return if self._paused: return if self._waiting_for_response: LOG.debug("queueing write %s", data) ...
Implement a Python 3 function for writing data on the asyncio Protocol
As a Python code composer, you craft elegant and concise scripts.
Convert responder querystring params pulling values out of list
Here you have a function in Python 3, explain what it does def unwrap_querystring_lists(obj): new_dict = { key: (obj[key][0] if len(obj[key]) == 1 else obj[key]) for key in obj.keys() } return new_dict
You are a Python code generator, capable of creating scripts from specifications.
For duck - typing with *Spec types
How would you explain what the following Python 3 function does def pipeline_getter(self): "For duck-typing with *Spec types" if not self.derivable: raise ArcanaUsageError( "There is no pipeline getter for {} because it doesn't " "fallback to a derived spec".f...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a dictionary of all prerequisite names that are used in the pipeline.
How would you explain what the following Python 3 function does def prerequisites(self): # Loop through the inputs to the pipeline and add the instancemethods # for the pipelines to generate each of the processed inputs prereqs = defaultdict(set) for input in self.inputs: # @ReservedAss...
As a python code expert, you are capable of creating scripts from specifications.
Returns all inputs of the study used by the pipeline including inputs of prerequisites and inputs of prerequisites recursively.
Can you generate a brief explanation for the following Python 3 code def study_inputs(self): return set(chain( (i for i in self.inputs if not i.derived), *(self.study.pipeline(p, required_outputs=r).study_inputs for p, r in self.prerequisites.items())))
As a Python code composer, you craft elegant and concise scripts.
def add(self, name, interface, inputs=None, outputs=None, requirements=None, wall_time=None, annotations=None, **kwargs): """ Adds a processing Node to the pipeline Parameters ---------- name : str Name for the node interface : nipype.Interface ...
Write a Python 3 script to add a processing Node to the pipeline.
As a Python code composer, you craft elegant and concise scripts.
def connect_input(self, spec_name, node, node_input, format=None, **kwargs): # @ReservedAssignment @IgnorePep8 """ Connects a study fileset_spec as an input to the provided node Parameters ---------- spec_name : str Name of the study data spec (or one of the IDs fro...
How would you code a function in Python 3 to connect a study fileset_spec as an input to the provided node.
As a Python code composer, you craft elegant and concise scripts.
Connects an output from a study fileset to a specific node.
Can you generate a brief explanation for the following Python 3 code def connect_output(self, spec_name, node, node_output, format=None, # @ReservedAssignment @IgnorePep8 **kwargs): """ Connects an output to a study fileset spec Parameters ---------- spe...
As a python code expert, you are capable of creating scripts from specifications.
Maps a spec name to a new value based on the provided mapper
How would you explain what the following Python 3 function does def _map_name(self, name, mapper): if mapper is not None: if isinstance(mapper, basestring): name = mapper + name try: name = mapper[name] except KeyError: pass ...
As a Python code analyst, you investigate and solve complex coding mysteries
def requires_conversion(cls, fileset, file_format): """Checks whether the fileset matches the requested file format""" if file_format is None: return False try: filset_format = fileset.format except AttributeError: return False # Field input e...
Write a Python 3 function that can check whether the fileset matches the requested file format
As a Python code composer, you craft elegant and concise scripts.
Saves a graph of the pipeline to file fname.
Explain what the following Python 3 code does def save_graph(self, fname, style='flat', format='png', **kwargs): # @ReservedAssignment @IgnorePep8 fname = os.path.expanduser(fname) if not fname.endswith('.png'): fname += '.png' orig_dir = os.getcwd() tmpdir = tempfile.mkdtem...
As a python code expert, you are capable of creating scripts from specifications.
def iterators(self, frequency=None): """ Returns the iterators (i.e. subject_id, visit_id) that the pipeline iterates over Parameters ---------- frequency : str | None A selected data frequency to use to determine which iterators are required. If ...
Can you create a Python 3 function that returns the iterators that the pipeline contains for each input frequency.
You are a Python code analyst, evaluating scripts for potential improvements.
Unwraps potentially nested name - mapping dictionaries to get values for name input_map output_map and study.
Given the following Python 3 function, write the documentation def _unwrap_maps(self, name_maps, name, study=None, **inner_maps): # Set values of name and study name = name_maps.get('name', name) name = name_maps.get('prefix', '') + name study = name_maps.get('study', study) # Fl...
As a Python code analyst, you investigate and solve complex coding mysteries
def cap(self): """ "Caps" the construction of the pipeline, signifying that no more inputs and outputs are expected to be added and therefore the input and output nodes can be created along with the provenance. """ to_cap = (self._inputnodes, self._outputnodes, self._prov...
Can you write a function in Python 3 where it caps the construction of the pipeline.
You are a Python code architect, reviewing and designing scalable and efficient code
def _make_inputnode(self, frequency): """ Generates an input node for the given frequency. It also adds implicit file format conversion nodes to the pipeline. Parameters ---------- frequency : str The frequency (i.e. 'per_session', 'per_visit', 'per_subject' ...
How would you implement a function in Python 3 that creates an input node for the given frequency and adds it to the pipeline.
You are a Python code architect, reviewing and designing scalable and efficient code
Creates an output node for the given frequency.
Can you generate the documentation for the following Python 3 function def _make_outputnode(self, frequency): # Check to see whether there are any outputs for the given frequency outputs = list(self.frequency_outputs(frequency)) if not outputs: raise ArcanaError( "No ...
As a python code expert, you are capable of creating scripts from specifications.
def _gen_prov(self): """ Extracts provenance information from the pipeline into a PipelineProv object Returns ------- prov : dict[str, *] A dictionary containing the provenance information to record for the pipeline """ # Export wo...
Write a Python 3 function that can generate provenance information for the pipeline and returns a dictionary containing the provenance information for the pipeline and the pipeline itself.
As a Python code translator, you convert algorithms and pseudocode into Python.
def expected_record(self, node): """ Constructs the provenance record that would be saved in the given node if the pipeline was run on the current state of the repository Parameters ---------- node : arcana.repository.tree.TreeNode A node of the Tree represen...
Write a Python 3 function that can construct the provenance record that would be saved in the given node.
You are a Python code analyst, evaluating scripts for potential improvements.
def _joined_ids(self): """ Adds the subjects/visits used to generate the derivatives iff there are any joins over them in the pipeline """ joined_prov = {} if self.joins_subjects: joined_prov['subject_ids'] = list(self.study.subject_ids) if self.joins_...
Write a Python 3 script to add the subject and visit ids used to generate the derivatives iff there are any joins over them in the pipeline
As a Python code composer, you craft elegant and concise scripts.
Return the hierarchical tree of subject and session and fileset related to the given subject and visit IDs.
Make a summary of the following Python 3 code def tree(self, subject_ids=None, visit_ids=None, **kwargs): # Find all data present in the repository (filtered by the passed IDs) return Tree.construct( self, *self.find_data(subject_ids=subject_ids, visit_ids=v...
As a python code expert, you are capable of creating scripts from specifications.
def cached_tree(self, subject_ids=None, visit_ids=None, fill=False): """ Access the repository tree and caches it for subsequent accesses Parameters ---------- subject_ids : list(str) List of subject IDs with which to filter the tree with. If None...
Write a Python 3 function for returning the tree for the given subject and visit ID filters and the IDs that were actually returned by the tree.
You are a Python code generator, capable of creating scripts from specifications.
Returns a list of resource names for this format on a given repository type.
Can you generate the documentation for the following Python 3 function def resource_names(self, repo_type): try: names = self._resource_names[repo_type] except KeyError: names = [self.name, self.name.upper()] return names
You are a Python code analyst, evaluating scripts for potential improvements.
Get the default paths for auxiliary files relative to the path of the primary file
Can you tell what is the following Python 3 function doing def default_aux_file_paths(self, primary_path): return dict((n, primary_path[:-len(self.ext)] + ext) for n, ext in self.aux_files.items())
As a python code expert, you are capable of creating scripts from specifications.
Assorts candidate files into primary and auxiliary files.
How would you explain what the following Python 3 function does def assort_files(self, candidates): by_ext = defaultdict(list) for path in candidates: by_ext[split_extension(path)[1].lower()].append(path) try: primary_file = by_ext[self.ext] except KeyError: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Checks to see if the format matches the given fileset.
Given the following Python 3 function, write the documentation def matches(self, fileset): if fileset._resource_name is not None: return (fileset._resource_name in self.resource_names( fileset.repository.type)) elif self.directory: if op.isdir(fileset.path): ...
You are a Python code architect, reviewing and designing scalable and efficient code
Register a Converter and the FileFormat that it can convert from from
Can you generate a brief explanation for the following Python 3 code def set_converter(self, file_format, converter): self._converters[file_format.name] = (file_format, converter)
As a python code expert, you are capable of creating scripts from specifications.
Parse an Elk connection string into a tuple.
Can you generate the documentation for the following Python 3 function def parse_url(url): scheme, dest = url.split('://') host = None ssl_context = None if scheme == 'elk': host, port = dest.split(':') if ':' in dest else (dest, 2101) elif scheme == 'elks': host, port = dest.split('...
As a Python code composer, you craft elegant and concise scripts.
Make a constant pretty for printing in GUI
Can you tell what is the following Python 3 function doing def pretty_const(value): words = value.split('_') pretty = words[0].capitalize() for word in words[1:]: pretty += ' ' + word.lower() return pretty
As a Python code composer, you craft elegant and concise scripts.
def username(elk, user_number): """Return name of user.""" if user_number >= 0 and user_number < elk.users.max_elements: return elk.users[user_number].name if user_number == 201: return "*Program*" if user_number == 202: return "*Elk RP*" if user_number == 203: return...
How would you code a function in Python 3 to return name of user.
You are a Python code analyst, evaluating scripts for potential improvements.
async def _connect(self, connection_lost_callbk=None): """Asyncio connection to Elk.""" self.connection_lost_callbk = connection_lost_callbk url = self._config['url'] LOG.info("Connecting to ElkM1 at %s", url) scheme, dest, param, ssl_context = parse_url(url) conn = parti...
Write a Python 3 script to connect to the ElkM1.
You are a Python code generator, capable of creating scripts from specifications.
Login and sync the ElkM1 panel to memory.
Can you generate a brief explanation for the following Python 3 code def _connected(self, transport, conn): LOG.info("Connected to ElkM1") self._conn = conn self._transport = transport self._connection_retry_timer = 1 if url_scheme_is_secure(self._config['url']): self...
You are a Python code architect, reviewing and designing scalable and efficient code
def send(self, msg): """Send a message to Elk panel.""" if self._conn: self._conn.write_data(msg.message, msg.response_command)
Implement a function in Python 3 to send a message to the Elk panel.
As a Python code analyst, you investigate and solve complex coding mysteries
Retrieve zones from ElkM1
Make a summary of the following Python 3 code def sync(self): self.elk.send(az_encode()) self.elk.send(zd_encode()) self.elk.send(zp_encode()) self.elk.send(zs_encode()) self.get_descriptions(TextDescriptions.ZONE.value)
You are a Python code generator, capable of creating scripts from specifications.