text
stringlengths
81
112k
Return avg room temperature for last session. 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) ...
Return avg heart rate for last session. 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 ==...
Return a dict of all the 'last' parameters. def last_values(self): """Return a dict of all the 'last' parameters.""" last_dict = { 'date': self.last_session_date, 'score': self.last_sleep_score, 'breakdown': self.last_sleep_breakdown, 'tnt': self.last_tnt...
Calculate some heating data stats. 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...') ...
Determine presence based on bed heating level and end presence time reported by the api. Idea originated from Alex Lee Yuk Cheung SmartThings Code. def dynamic_presence(self): """ Determine presence based on bed heating level and end presence time reported by the api. ...
Update heating data json. async def set_heating_level(self, level, duration=0): """Update heating data json.""" 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 s...
Update trends data json for specified time period. async def update_trend_data(self, startdate, enddate): """Update trends data json for specified time period.""" url = '{}/users/{}/trends'.format(API_URL, self.userid) params = { 'tz': self.device.tzone, 'from': startdat...
Update intervals data json for specified time period. async def update_intervals_data(self): """Update intervals data json for specified time period.""" url = '{}/users/{}/intervals'.format(API_URL, self.userid) intervals = await self.device.api_get(url) if intervals is None: ...
Saves a deserialized model object. Uses save_base to avoid running code in model.save() and to avoid triggering signals (if raw=True). def save(obj=None, m2m_data=None): """Saves a deserialized model object. Uses save_base to avoid running code in model.save() and to avoid triggering signals (if ...
Deserializes the encrypted serialized model instances, tx, in a queryset of transactions. Note: each transaction instance contains encrypted JSON text that represents just ONE model instance. def deserialize_transactions(self, transactions=None, deserialize_only=None): """Deserializes ...
Runs json_text thru custom parsers. def custom_parser(self, json_text=None): """Runs json_text thru custom parsers. """ 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) ...
cli lazy property def cli(self): """ cli lazy property """ client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname=self.private_hostname, username=self.username, key_filename=self.k...
channel lazy property 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@'...
Plumbum lazy property def pbm(self): """ Plumbum lazy property """ if not self.disable_rpyc: from plumbum import SshMachine return SshMachine(host=self.private_hostname, user=self.username, keyfile=self.key_filename, ss...
RPyC lazy property def rpyc(self): """ RPyC lazy property """ if not self.disable_rpyc: try: import rpyc devnull_fd = open("/dev/null", "w") rpyc_dirname = os.path.dirname(rpyc.__file__) rnd_id = ''.join(random.choice(string.a...
Close the connection 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 ...
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 @return: the stdin, stdout, and stderr of the executing command @rtype:...
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 @type get_pty: bool @return: the exit code of the process or None in case of t...
(Helper) Set counter to value def set(self, value): """(Helper) Set counter to value""" self._elk.send(cx_encode(self._index, value))
Saves the provenance object to a JSON file, optionally including checksums for inputs and outputs (which are initially produced mid- run) to insert during the write Parameters ---------- path : str Path to save the generated JSON file inputs : dict[str, str |...
Loads a saved provenance object from a JSON file Parameters ---------- path : str Path to the provenance file frequency : str The frequency of the record subject_id : str | None The subject ID of the provenance record visit_id : str | ...
Compares information stored within provenance objects with the exception of version information to see if they match. Matches are constrained to the paths passed to the 'include' kwarg, with the exception of sub-paths passed to the 'exclude' kwarg Parameters ---------- o...
A method for translating pipeline constructors from a sub-study to the namespace of a multi-study. Returns a new method that calls the sub-study pipeline constructor with appropriate keyword arguments Parameters ---------- substudy_name : str Name of the sub-study ...
Data specs in the sub-study class that are not explicitly provided in the name map 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 no...
Parameter pecs in the sub-study class that are not explicitly provided in the name map def auto_param_specs(self): """ Parameter pecs in the sub-study class that are not explicitly provided in the name map """ for spec in self.study_class.parameter_specs(): i...
Cast generated nodes to be Arcana nodes def _make_nodes(self, cwd=None): """ Cast generated nodes to be Arcana nodes """ for i, node in NipypeMapNode._make_nodes(self, cwd=cwd): # "Cast" NiPype node to a Arcana Node and set Arcana Node # parameters no...
Find file matching query_name, read and return query object def get_query(query_name): """Find file matching query_name, read and return query object """ query_file_match = list( filter(lambda i: query_name == i.stem, FLAT_QUERIES)) if not query_file_match: return None # TODO: Log w...
Call get_query, then submit query from file to resultset module 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...
Generate CSV from result data 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...
Registers with app_label.modelname, wrapper_cls. 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: ...
Registers all models for this app_label. 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 = django_apps.get_app_...
Returns a wrapped model instance. 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.regis...
Returns a dictionary of registered models. def site_models(self, app_label=None): """Returns a dictionary of registered models. """ site_models = {} app_configs = ( django_apps.get_app_configs() if app_label is None else [django_apps.get_app_config(ap...
Set the path of the fileset from the repository def get_fileset(self, fileset): """ Set the path of the fileset from the repository """ # 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 = ...
Update the value of the field from the repository 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...
Inserts or updates a fileset in the repository 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 si...
Inserts or updates a field in the repository 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(fp...
Find all data within a repository, registering filesets, fields and provenance with the found_fileset, found_field and found_provenance methods, respectively Parameters ---------- subject_ids : list(str) List of subject IDs with which to filter the tree with. If ...
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. Parameters ---------- root_dir : str ...
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 here, and leave connecting to concr...
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-relevant frequencies, they will just be ignored. P...
Used for duck typing Collection objects with Spec and Match in source and sink initiation. Checks IDs match sessions in study. def bind(self, study, **kwargs): # @UnusedVariable """ Used for duck typing Collection objects with Spec and Match in source and sink initiation. Checks IDs ma...
Gets the fileset 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 ---------- name : str | FilesetSpec The name of the fileset...
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 ---------- name : str | BaseField The name of the field or a ...
Returns the provenance record for a given pipeline Parameters ---------- pipeline_name : str The name of the pipeline that generated the record from_study : str The name of the study that the pipeline was generated from Returns ------- re...
Highlights where two nodes differ in a human-readable form Parameters ---------- other : TreeNode The node to compare indent : str The white-space with which to indent output string Returns ------- mismatch : str The human-rea...
Returns an iterator over all nodes in the tree for the specified frequency. If no frequency is specified then all nodes are returned Parameters ---------- frequency : str | None The frequency of the nodes to iterate over. If None all frequencies are returned ...
Used in debugging unittests def find_mismatch(self, other, indent=''): """ Used in debugging unittests """ mismatch = super(Tree, self).find_mismatch(other, indent) sub_indent = indent + ' ' if len(list(self.subjects)) != len(list(other.subjects)): mismatch ...
Fill in tree with additional empty subjects and/or visits to allow the study to pull its inputs from external repositories 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...
Return the hierarchical tree of the filesets and fields stored in a repository Parameters ---------- respository : Repository The repository that the tree comes from filesets : list[Fileset] List of all filesets in the tree fields : list[Field] ...
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[TreeNode] All nodes related to the Sessi...
Write data on the asyncio Protocol 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.deb...
Convert responder querystring params, pulling values out of list if there's only one. def unwrap_querystring_lists(obj): """Convert responder querystring params, pulling values out of list if there's only one. """ new_dict = { key: (obj[key][0] if len(obj[key]) == 1 else obj[k...
For duck-typing with *Spec types 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".format(self)) return se...
Iterates through the inputs of the pipelinen and determines the all prerequisite pipelines def prerequisites(self): """ Iterates through the inputs of the pipelinen and determines the all prerequisite pipelines """ # Loop through the inputs to the pipeline and add the in...
Returns all inputs of the study used by the pipeline, including inputs of prerequisites (and their prerequisites recursively) def study_inputs(self): """ Returns all inputs of the study used by the pipeline, including inputs of prerequisites (and their prerequisites recursively) ...
Adds a processing Node to the pipeline Parameters ---------- name : str Name for the node interface : nipype.Interface The interface to use for the node inputs : dict[str, (str, FileFormat) | (Node, str)] Connections from inputs of the pipelin...
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 from the iterator nodes, 'subject_id' or 'visit_id') to connect to the node node : arcana.Node The node...
Connects an output to a study fileset spec Parameters ---------- spec_name : str Name of the study fileset spec to connect to node : arcana.Node The node to connect the output from node_output : str Name of the output on the node to connect to...
Maps a spec name to a new value based on the provided mapper def _map_name(self, name, mapper): """ Maps a spec name to a new value based on the provided mapper """ if mapper is not None: if isinstance(mapper, basestring): name = mapper + name try...
Checks whether the fileset matches the requested file format 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 Att...
Saves a graph of the pipeline to file Parameters ---------- fname : str The filename for the saved graph style : str The style of the graph, can be one of can be one of 'orig', 'flat', 'exec', 'hierarchical' plot : bool Whether to ...
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 None, all input frequencies of the pipeline are ...
Unwraps potentially nested name-mapping dictionaries to get values for name, input_map, output_map and study. Unsed in __init__. Parameters ---------- name_maps : dict A dictionary containing the name_maps to apply to the values name : str Name passed fro...
"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. def cap(self): """ "Caps" the construction of the pipeline, signifying that no more inputs ...
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' or 'per_study') of the input node to retrieve ...
Generates an output 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' or 'per_study') of the output node to retriev...
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 def _gen_prov(self): """ Extracts provenance informatio...
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 representation of the study data stored in the re...
Adds the subjects/visits used to generate the derivatives iff there are any joins over them in the pipeline 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 = {} ...
Return the tree of subject and sessions information within a project in the XNAT repository Parameters ---------- subject_ids : list(str) List of subject IDs with which to filter the tree with. If None all are returned visit_ids : list(str) Li...
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 all are returned visit_ids : list(str) List of visit IDs with which ...
Names of resources used to store the format on a given repository type. Defaults to the name of the name of the format def resource_names(self, repo_type): """ Names of resources used to store the format on a given repository type. Defaults to the name of the name of the format ...
Get the default paths for auxiliary files relative to the path of the primary file, i.e. the same name as the primary path with a different extension Parameters ---------- primary_path : str Path to the primary file in the fileset Returns ------- ...
Assorts candidate files into primary and auxiliary (and ignored) files corresponding to the format by their file extensions. Can be overridden in specialised subclasses to assort files based on other characteristics Parameters ---------- candidates : list[str] ...
Checks to see whether the format matches the given fileset Parameters ---------- fileset : Fileset The fileset to check def matches(self, fileset): """ Checks to see whether the format matches the given fileset Parameters ---------- fileset ...
Register a Converter and the FileFormat that it is able to convert from Parameters ---------- converter : Converter The converter to register file_format : FileFormat The file format that can be converted into this format def set_converter(self, file_format, con...
Parse a Elk connection string def parse_url(url): """Parse a Elk connection string """ 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(...
Make a constant pretty for printing in GUI def pretty_const(value): """Make a constant pretty for printing in GUI""" words = value.split('_') pretty = words[0].capitalize() for word in words[1:]: pretty += ' ' + word.lower() return pretty
Return name of user. 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 ...
Asyncio connection to Elk. 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_u...
Login and sync the ElkM1 panel to memory. def _connected(self, transport, conn): """Login and sync the ElkM1 panel to memory.""" LOG.info("Connected to ElkM1") self._conn = conn self._transport = transport self._connection_retry_timer = 1 if url_scheme_is_secure(self._co...
Text description def _sd_handler(self, desc_type, unit, desc, show_on_keypad): """Text description""" if desc_type not in self._descriptions_in_progress: LOG.debug("Text description response ignored for " + str(desc_type)) return (max_units, results, callback) = self._d...
Send a message to Elk panel. def send(self, msg): """Send a message to Elk panel.""" if self._conn: self._conn.write_data(msg.message, msg.response_command)
Retrieve zones from ElkM1 def sync(self): """Retrieve zones from ElkM1""" 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)
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. def has_offline_historical_manager_or_raise(self): """Raises an exception if model uses...
Return the primary key field. Is `id` in most cases. Is `history_id` for Historical models. def primary_key_field(self): """Return the primary key field. Is `id` in most cases. Is `history_id` for Historical models. """ return [field for field in self.instance._meta.fields if ...
Serialize the model instance to an AES encrypted json object and saves the json object to the OutgoingTransaction model. 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 Outgoi...
Returns an encrypted json serialized from self. def encrypted_json(self): """Returns an encrypted json serialized from self. """ json = serialize(objects=[self.instance]) encrypted_json = Cryptor().aes_encrypt(json, LOCAL_MODE) return encrypted_json
Maps the name of an Requirement class to the name of the corresponding module in the environment Parameters ---------- requirement : Requirement The requirement to map to the name of a module on the system def map_req(self, requirement): """ Maps the name of...
Maps a local version name to one recognised by the Requirement class Parameters ---------- requirement : str Name of the requirement version : str version string def map_version(self, requirement, local_version): """ Maps a local version name to ...
Register the TagProcessors that are bundled with doxytag2zealdb. 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', fileTagProces...
Run all tag processors. 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: print('Inserted %d e...
Run a tag processor. Args: tag_proc_name: A string key that maps to the TagProcessor to run. 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 = ...
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 process. def process_tag(self, tag_proc_name, tag): '''Process a tag with a tag processor and insert a DB entry. ...
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: string, int or callable that tells how to group Return...
>>> groups_of(2, range(5)) def groups_of(n, iterable): """ >>> groups_of(2, range(5)) """ args = [iter(iterable)] * n for x in izip_longest(*args): yield [v for v in x if v is not None]
Connects all pipelines to that study's repository and runs them in the same NiPype workflow Parameters ---------- pipeline(s) : Pipeline, ... The pipeline to connect to repository required_outputs : list[set[str]] A set of required outputs for each pipeli...
Connects a pipeline to a overarching workflow that sets up iterators over subjects|visits present in the repository (if required) and repository source and sink nodes Parameters ---------- pipeline : Pipeline The pipeline to connect required_outputs : set[str...
Generate nodes that iterate over subjects and visits in the study that need to be processed by the pipeline Parameters ---------- pipeline : Pipeline The pipeline to add iter_nodes for to_process_array : 2-D numpy.array[bool] A two-dimensional boolean arr...