INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Save the token on the config file.
def save_token(self, user, token): """Save the token on the config file.""" self.config.set('auth', 'user', user) self.config.set('auth', 'token', token) # allow_no_value=True is used to keep the comments on the config file. new_config = ConfigParser(allow_no_value=True) ...
Clear Token information on config file.
def clear_token(self): """Clear Token information on config file.""" # allow_no_value=True is used to keep the comments on the config file. new_config = ConfigParser(allow_no_value=True) # Parse the config file. If no config file was found, then create some # default sections on...
Move the `Part` model to target parent. .. versionadded:: 2.3 :param part: `Part` object to be moved :type part: :class:`Part` :param target_parent: `Part` object under which the desired `Part` is moved :type target_parent: :class:`Part` :param name: how the moved top-level `Part` should be ca...
def relocate_model(part, target_parent, name=None, include_children=True): """ Move the `Part` model to target parent. .. versionadded:: 2.3 :param part: `Part` object to be moved :type part: :class:`Part` :param target_parent: `Part` object under which the desired `Part` is moved :type ta...
Retrieve the illegal parent parts where `Part` can be moved/copied. :param part: `Part` to be moved/copied. :type part: :class:`Part` :param include: `Set` object with id's to be avoided as target parent `Part` :type include: set :return: `List` object of illegal id's :rtype: list
def get_illegal_targets(part, include): """ Retrieve the illegal parent parts where `Part` can be moved/copied. :param part: `Part` to be moved/copied. :type part: :class:`Part` :param include: `Set` object with id's to be avoided as target parent `Part` :type include: set :return: `List` o...
Move the `Part` instance to target parent. .. versionadded:: 2.3 :param part: `Part` object to be moved :type part: :class:`Part` :param target_parent: `Part` object under which the desired `Part` is moved :type target_parent: :class:`Part` :param name: how the moved top-level `Part` should be...
def relocate_instance(part, target_parent, name=None, include_children=True): """ Move the `Part` instance to target parent. .. versionadded:: 2.3 :param part: `Part` object to be moved :type part: :class:`Part` :param target_parent: `Part` object under which the desired `Part` is moved :t...
Move the `Part` instance to target parent and updates the properties based on the original part instance. .. versionadded:: 2.3 :param part_instance: `Part` object to be moved :type part_instance: :class:`Part` :param part_model: `Part` object representing the model of part_instance :type part_mod...
def move_part_instance(part_instance, target_parent, part_model, name=None, include_children=True): """ Move the `Part` instance to target parent and updates the properties based on the original part instance. .. versionadded:: 2.3 :param part_instance: `Part` object to be moved :type part_instanc...
Update the newly created part and its properties based on the original one. :param part_instance: `Part` object to be copied :type part_instance: :class:`Part` :param moved_instance: `Part` object copied :type moved_instance: :class:`Part` :param name: Name of the updated part :type name: bases...
def update_part_with_properties(part_instance, moved_instance, name=None): """ Update the newly created part and its properties based on the original one. :param part_instance: `Part` object to be copied :type part_instance: :class:`Part` :param moved_instance: `Part` object copied :type moved_...
Map the id of the original part with the `Part` object of the newly created one. Updated the singleton `mapping dictionary` with the new mapping table values. :param original_part: `Part` object to be copied/moved :type original_part: :class:`Part` :param new_part: `Part` object copied/moved :type...
def map_property_instances(original_part, new_part): """ Map the id of the original part with the `Part` object of the newly created one. Updated the singleton `mapping dictionary` with the new mapping table values. :param original_part: `Part` object to be copied/moved :type original_part: :class...
Register a new user. This method will ask for user attributes and create the user in Napps server, when All required fields is filled. Returns: result(string): Response of user registration process.
def register(self): """Register a new user. This method will ask for user attributes and create the user in Napps server, when All required fields is filled. Returns: result(string): Response of user registration process. """ user = {} print('-----...
Ask a question and get the input values. This method will validade the input values. Args: field_name(string): Field name used to ask for input value. pattern(tuple): Pattern to validate the input value. is_required(bool): Boolean value if the input value is required...
def ask_question(self, field_name, pattern=NAME_PATTERN, is_required=False, password=False): """Ask a question and get the input values. This method will validade the input values. Args: field_name(string): Field name used to ask for input value. pat...
Static asset management in python. Called with no arguments grablib will download, then build. You can also choose to only download or build. See `grablib -h` and https://github.com/samuelcolvin/grablib for more help.
def cli(action, config_file, debug, verbose): """ Static asset management in python. Called with no arguments grablib will download, then build. You can also choose to only download or build. See `grablib -h` and https://github.com/samuelcolvin/grablib for more help. """ if verbose is True: ...
----- Brief ----- Function for extracting HRV parameters from time and frequency domains. ----------- Description ----------- ECG signals require specific processing due to their cyclic nature. For example, it is expected that in similar conditions the RR peak interval to be similar, wh...
def hrv_parameters(data, sample_rate, signal=False, in_seconds=False): """ ----- Brief ----- Function for extracting HRV parameters from time and frequency domains. ----------- Description ----------- ECG signals require specific processing due to their cyclic nature. For example, i...
----- Brief ----- Function for removing ectopic beats. ----------- Description ----------- Ectopic beats are beats that are originated in cells that do not correspond to the expected pacemaker cells. These beats are identifiable in ECG signals by abnormal rhythms. This function all...
def remove_ectopy(tachogram_data, tachogram_time): """ ----- Brief ----- Function for removing ectopic beats. ----------- Description ----------- Ectopic beats are beats that are originated in cells that do not correspond to the expected pacemaker cells. These beats are identifi...
----- Brief ----- Determination of the Power Spectral Density Function (Fourier Domain) ----------- Description ----------- The Power Spectral Density Function allows to perceive the behavior of a given signal in terms of its frequency. This procedure costs the time resolution of the si...
def psd(tachogram_time, tachogram_data): """ ----- Brief ----- Determination of the Power Spectral Density Function (Fourier Domain) ----------- Description ----------- The Power Spectral Density Function allows to perceive the behavior of a given signal in terms of its frequency. ...
----- Brief ----- Function for extracting EMG parameters from time and frequency domains. ----------- Description ----------- EMG signals have specific properties that are different from other biosignals. For example, it is not periodic, contrary to ECG signals. This type of biosign...
def emg_parameters(data, sample_rate, raw_to_mv=True, device="biosignalsplux", resolution=16): """ ----- Brief ----- Function for extracting EMG parameters from time and frequency domains. ----------- Description ----------- EMG signals have specific properties that are different fr...
----- Brief ----- Returns the evolution time series of EMG median frequency along the acquisition, based on a sliding window mechanism. ----------- Description ----------- The median frequency of activation events in EMG signal is particularly important in fatigue evaluation methods. ...
def fatigue_eval_med_freq(data, sample_rate, time_units=True, raw_to_mv=True, device="biosignalsplux", resolution=16, show_plot=False): """ ----- Brief ----- Returns the evolution time series of EMG median frequency along the acquisition, based on a sliding window mecha...
Retrieve the part that holds this Property. :returns: The :class:`Part` associated to this property :raises APIError: if the `Part` is not found
def part(self): """Retrieve the part that holds this Property. :returns: The :class:`Part` associated to this property :raises APIError: if the `Part` is not found """ part_id = self._json_data['part'] return self._client.part(pk=part_id, category=self._json_data['categ...
Delete this property. :return: None :raises APIError: if delete was not successful
def delete(self): # type () -> () """Delete this property. :return: None :raises APIError: if delete was not successful """ r = self._client._request('DELETE', self._client._build_url('property', property_id=self.id)) if r.status_code != requests.codes.no_conten...
Create a property based on the json data. This method will attach the right class to a property, enabling the use of type-specific methods. It does not create a property object in KE-chain. But a pseudo :class:`Property` object. :param json: the json from which the :class:`Property` object to...
def create(cls, json, **kwargs): # type: (dict, **Any) -> Property """Create a property based on the json data. This method will attach the right class to a property, enabling the use of type-specific methods. It does not create a property object in KE-chain. But a pseudo :class:`Prope...
Edit the details of a property (model). :param name: (optional) new name of the property to edit :type name: basestring or None :param description: (optional) new description of the property :type description: basestring or None :param unit: (optional) new unit of the property ...
def edit(self, name=None, description=None, unit=None, options=None, **kwargs): """ Edit the details of a property (model). :param name: (optional) new name of the property to edit :type name: basestring or None :param description: (optional) new description of the property ...
Parse the validator in the options to validators.
def __parse_validators(self): """Parse the validator in the options to validators.""" self._validators = [] validators_json = self._options.get('validators') for validator_json in validators_json: self._validators.append(PropertyValidator.parse(json=validator_json))
Dump the validators as json inside the _options dictionary with the key `validators`.
def __dump_validators(self): """Dump the validators as json inside the _options dictionary with the key `validators`.""" if hasattr(self, '_validators'): validators_json = [] for validator in self._validators: if isinstance(validator, PropertyValidator): ...
Determine if the value in the property is valid. If the value of the property is validated as 'valid', than returns a True, otherwise a False. When no validators are configured, returns a None. It checks against all configured validators and returns a single boolean outcome. :returns: ...
def is_valid(self): # type: () -> Union[bool, None] """Determine if the value in the property is valid. If the value of the property is validated as 'valid', than returns a True, otherwise a False. When no validators are configured, returns a None. It checks against all configured valid...
Return the validation results and include an (optional) reason. If reason keyword is true, the validation is returned for each validation the [(<result: bool>, <reason:str>), ...]. If reason is False, only a single list of validation results for each configured validator is returned. :...
def validate(self, reason=True): # type: (bool) -> list """Return the validation results and include an (optional) reason. If reason keyword is true, the validation is returned for each validation the [(<result: bool>, <reason:str>), ...]. If reason is False, only a single list of valid...
This is a convenience function for getting the zdesk configuration from an ini file without the need to decorate and call your own function. Handy when using zdesk and zdeskcfg from the interactive prompt.
def get_ini_config(config=os.path.join(os.path.expanduser('~'), '.zdeskcfg'), default_section=None, section=None): """This is a convenience function for getting the zdesk configuration from an ini file without the need to decorate and call your own function. Handy when using zdesk and zdeskcfg from ...
This method provides a way for decorated functions to get the four new configuration parameters *after* it has been called. If no section is specified, then the fully resolved zdesk config will be returned. That is defaults, zdesk ini section, command line options. If a section...
def getconfig(self, section=None): """ This method provides a way for decorated functions to get the four new configuration parameters *after* it has been called. If no section is specified, then the fully resolved zdesk config will be returned. That is defaults, zdesk ini secti...
----- Brief ----- Python implementation of R peak detection algorithm (proposed by Raja Selvaraj). ----------- Description ----------- Pan-Tompkins algorithm is one of the gold-standard algorithms in R-peak detection on ECG due to its low computational complexity, which allows for real-...
def detect_r_peaks(ecg_signal, sample_rate, time_units=False, volts=False, resolution=None, device="biosignalsplux", plot_result=False): """ ----- Brief ----- Python implementation of R peak detection algorithm (proposed by Raja Selvaraj). ----------- Description ----...
----- Brief ----- Python implementation of Burst detection algorithm using Teager Kaiser Energy Operator. ----------- Description ----------- Activation events in EMG readings correspond to an increase of muscular activity, namely, from inaction to action. These events are characterised...
def detect_emg_activations(emg_signal, sample_rate, smooth_level=20, threshold_level=10, time_units=False, volts=False, resolution=None, device="biosignalsplux", plot_result=False): """ ----- Brief ----- Python implementation of Burst detection a...
Bandpass filter with a bandpass setting of 5 to 15 Hz ---------- Parameters ---------- data : list List with the ECG signal samples. sample_rate : int Sampling rate at which the acquisition took place. Returns ------- out : list Filtered signal.
def _ecg_band_pass_filter(data, sample_rate): """ Bandpass filter with a bandpass setting of 5 to 15 Hz ---------- Parameters ---------- data : list List with the ECG signal samples. sample_rate : int Sampling rate at which the acquisition took place. Returns ------...
Moving window integration. N is the number of samples in the width of the integration window ---------- Parameters ---------- data : ndarray Samples of the signal where a moving window integration will be applied. sample_rate : int Sampling rate at which the acquisition took pla...
def _integration(data, sample_rate): """ Moving window integration. N is the number of samples in the width of the integration window ---------- Parameters ---------- data : ndarray Samples of the signal where a moving window integration will be applied. sample_rate : int ...
Initializes the buffer with eight 1s intervals ---------- Parameters ---------- data : ndarray Pre-processed ECG signal samples. sample_rate : int Sampling rate at which the acquisition took place. Returns ------- rr_buffer : list Data structure that stores eigh...
def _buffer_ini(data, sample_rate): """ Initializes the buffer with eight 1s intervals ---------- Parameters ---------- data : ndarray Pre-processed ECG signal samples. sample_rate : int Sampling rate at which the acquisition took place. Returns ------- rr_buffe...
Detects peaks from local maximum ---------- Parameters ---------- ecg_integrated : ndarray Array that contains the samples of the integrated signal. sample_rate : int Sampling rate at which the acquisition took place. Returns ------- choosen_peaks : list List of...
def _detects_peaks(ecg_integrated, sample_rate): """ Detects peaks from local maximum ---------- Parameters ---------- ecg_integrated : ndarray Array that contains the samples of the integrated signal. sample_rate : int Sampling rate at which the acquisition took place. ...
Check each peak according to thresholds ---------- Parameters ---------- peaks : list List of local maximums that pass the first stage of conditions needed to be considered as an R peak. ecg_integrated : ndarray Array that contains the samples of the integrated signal. s...
def _checkup(peaks, ecg_integrated, sample_rate, rr_buffer, spk1, npk1, threshold): """ Check each peak according to thresholds ---------- Parameters ---------- peaks : list List of local maximums that pass the first stage of conditions needed to be considered as an R peak. ...
Private function intended to insert a new RR interval in the buffer. ---------- Parameters ---------- peak : int Sample where the peak under analysis is located. amp : int Amplitude of the peak under analysis. definitive_peaks : list List with the definitive_peaks stored...
def _acceptpeak(peak, amp, definitive_peaks, spk1, rr_buffer): """ Private function intended to insert a new RR interval in the buffer. ---------- Parameters ---------- peak : int Sample where the peak under analysis is located. amp : int Amplitude of the peak under analysis...
Function for generation of ECG Tachogram. ---------- Parameters ---------- data : list ECG signal or R peak list. When the input is a raw signal the input flag signal should be True. sample_rate : int Sampling frequency. signal : boolean If True, then the data ...
def tachogram(data, sample_rate, signal=False, in_seconds=False, out_seconds=False): """ Function for generation of ECG Tachogram. ---------- Parameters ---------- data : list ECG signal or R peak list. When the input is a raw signal the input flag signal should be True. sa...
Regression function that with a percent input gives an absolute value of the threshold level (used in the muscular activation detection algorithm). Converts a relative threshold level to an absolute value. ---------- Parameters ---------- threshold_level : int Percentage value that defi...
def _thres_norm_reg(threshold_level, signal, pre_smooth_signal): """ Regression function that with a percent input gives an absolute value of the threshold level (used in the muscular activation detection algorithm). Converts a relative threshold level to an absolute value. ---------- Parameter...
Close serial port.
def stop(self): """Close serial port.""" self.logger.warning("Stop executed") try: self._reader.close() except serial.serialutil.SerialException: self.logger.error("Error while closing device") raise VelbusException("Error while closing device") ...
Parse received message.
def feed_parser(self, data): """Parse received message.""" assert isinstance(data, bytes) self.controller.feed_parser(data)
Add message to write queue.
def send(self, message, callback=None): """Add message to write queue.""" assert isinstance(message, velbus.Message) self._write_queue.put_nowait((message, callback))
Write thread.
def write_daemon(self): """Write thread.""" while True: (message, callback) = self._write_queue.get(block=True) self.logger.info("Sending message on USB bus: %s", str(message)) self.logger.debug("Sending binary message: %s", str(message.to_binary())) self...
Set path locations from kytosd API. It should not be called directly, but from properties that require a running kytosd instance.
def __require_kytos_config(self): """Set path locations from kytosd API. It should not be called directly, but from properties that require a running kytosd instance. """ if self.__enabled is None: uri = self._kytos_api + 'api/kytos/core/config/' try: ...
Set info about NApp. Args: user (str): NApps Server username. napp (str): NApp name. version (str): NApp version.
def set_napp(self, user, napp, version=None): """Set info about NApp. Args: user (str): NApps Server username. napp (str): NApp name. version (str): NApp version. """ self.user = user self.napp = napp self.version = version or 'latest'
List of (username, napp_name) found in ``napps_dir``.
def _get_napps(napps_dir): """List of (username, napp_name) found in ``napps_dir``.""" jsons = napps_dir.glob('*/*/kytos.json') return sorted(j.parts[-3:-1] for j in jsons)
Sorted list of (username, napp_name) of disabled napps. The difference of installed and enabled.
def get_disabled(self): """Sorted list of (username, napp_name) of disabled napps. The difference of installed and enabled. """ installed = set(self.get_installed()) enabled = set(self.get_enabled()) return sorted(installed - enabled)
Get napp_dependencies from install NApp. Args: user(string) A Username. napp(string): A NApp name. Returns: napps(list): List with tuples with Username and NApp name. e.g. [('kytos'/'of_core'), ('kytos/of_l2ls')]
def dependencies(self, user=None, napp=None): """Get napp_dependencies from install NApp. Args: user(string) A Username. napp(string): A NApp name. Returns: napps(list): List with tuples with Username and NApp name. e.g. [('kytos'/'o...
Return a value from kytos.json. Args: user (string): A Username. napp (string): A NApp name key (string): Key used to get the value within kytos.json. Returns: meta (object): Value stored in kytos.json.
def _get_napp_key(self, key, user=None, napp=None): """Return a value from kytos.json. Args: user (string): A Username. napp (string): A NApp name key (string): Key used to get the value within kytos.json. Returns: meta (object): Value stored in ...
Disable a NApp if it is enabled.
def disable(self): """Disable a NApp if it is enabled.""" core_napps_manager = CoreNAppsManager(base_path=self._enabled) core_napps_manager.disable(self.user, self.napp)
Enable a NApp if not already enabled. Raises: FileNotFoundError: If NApp is not installed. PermissionError: No filesystem permission to enable NApp.
def enable(self): """Enable a NApp if not already enabled. Raises: FileNotFoundError: If NApp is not installed. PermissionError: No filesystem permission to enable NApp. """ core_napps_manager = CoreNAppsManager(base_path=self._enabled) core_napps_manage...
Delete code inside NApp directory, if existent.
def uninstall(self): """Delete code inside NApp directory, if existent.""" if self.is_installed(): installed = self.installed_dir() if installed.is_symlink(): installed.unlink() else: shutil.rmtree(str(installed))
Render Jinja2 template for a NApp structure.
def render_template(templates_path, template_filename, context): """Render Jinja2 template for a NApp structure.""" template_env = Environment( autoescape=False, trim_blocks=False, loader=FileSystemLoader(str(templates_path))) return template_env.get_template(str(template...
Search all server NApps matching pattern. Args: pattern (str): Python regular expression.
def search(pattern): """Search all server NApps matching pattern. Args: pattern (str): Python regular expression. """ def match(napp): """Whether a NApp metadata matches the pattern.""" # WARNING: This will change for future versions, when 'author' wi...
Make a symlink in install folder to a local NApp. Raises: FileNotFoundError: If NApp is not found.
def install_local(self): """Make a symlink in install folder to a local NApp. Raises: FileNotFoundError: If NApp is not found. """ folder = self._get_local_folder() installed = self.installed_dir() self._check_module(installed.parent) installed.symli...
Return local NApp root folder. Search for kytos.json in _./_ folder and _./user/napp_. Args: root (pathlib.Path): Where to begin searching. Return: pathlib.Path: NApp root folder. Raises: FileNotFoundError: If there is no such local NApp.
def _get_local_folder(self, root=None): """Return local NApp root folder. Search for kytos.json in _./_ folder and _./user/napp_. Args: root (pathlib.Path): Where to begin searching. Return: pathlib.Path: NApp root folder. Raises: FileNotFo...
Download, extract and install NApp.
def install_remote(self): """Download, extract and install NApp.""" package, pkg_folder = None, None try: package = self._download() pkg_folder = self._extract(package) napp_folder = self._get_local_folder(pkg_folder) dst = self._installed / self.u...
Download NApp package from server. Return: str: Downloaded temp filename. Raises: urllib.error.HTTPError: If download is not successful.
def _download(self): """Download NApp package from server. Return: str: Downloaded temp filename. Raises: urllib.error.HTTPError: If download is not successful. """ repo = self._config.get('napps', 'repo') napp_id = '{}/{}-{}.napp'.format(self.u...
Extract package to a temporary folder. Return: pathlib.Path: Temp dir with package contents.
def _extract(filename): """Extract package to a temporary folder. Return: pathlib.Path: Temp dir with package contents. """ random_string = '{:0d}'.format(randint(0, 10**6)) tmp = '/tmp/kytos-napp-' + Path(filename).stem + '-' + random_string os.mkdir(tmp) ...
Bootstrap a basic NApp structure for you to develop your NApp. This will create, on the current folder, a clean structure of a NAPP, filling some contents on this structure.
def create_napp(cls, meta_package=False): """Bootstrap a basic NApp structure for you to develop your NApp. This will create, on the current folder, a clean structure of a NAPP, filling some contents on this structure. """ templates_path = SKEL_PATH / 'napp-structure/username/na...
Create the ui directory structure.
def create_ui_structure(cls, username, napp_name, ui_templates_path, context): """Create the ui directory structure.""" for section in ['k-info-panel', 'k-toolbar', 'k-action-menu']: os.makedirs(os.path.join(username, napp_name, 'ui', section)) templates ...
Create module folder with empty __init__.py if it doesn't exist. Args: folder (pathlib.Path): Module path.
def _check_module(folder): """Create module folder with empty __init__.py if it doesn't exist. Args: folder (pathlib.Path): Module path. """ if not folder.exists(): folder.mkdir(parents=True, exist_ok=True, mode=0o755) (folder / '__init__.py').touch()
Build the .napp file to be sent to the napps server. Args: napp_identifier (str): Identifier formatted as <username>/<napp_name> Return: file_payload (binary): The binary representation of the napp package that will be POSTed to the napp server.
def build_napp_package(napp_name): """Build the .napp file to be sent to the napps server. Args: napp_identifier (str): Identifier formatted as <username>/<napp_name> Return: file_payload (binary): The binary representation of the napp pa...
Generate the metadata to send the napp package.
def create_metadata(*args, **kwargs): # pylint: disable=unused-argument """Generate the metadata to send the napp package.""" json_filename = kwargs.get('json_filename', 'kytos.json') readme_filename = kwargs.get('readme_filename', 'README.rst') ignore_json = kwargs.get('ignore_json', F...
Create package and upload it to NApps Server. Raises: FileNotFoundError: If kytos.json is not found.
def upload(self, *args, **kwargs): """Create package and upload it to NApps Server. Raises: FileNotFoundError: If kytos.json is not found. """ self.prepare() metadata = self.create_metadata(*args, **kwargs) package = self.build_napp_package(metadata.get('nam...
Delete a NApp. Raises: requests.HTTPError: When there's a server error.
def delete(self): """Delete a NApp. Raises: requests.HTTPError: When there's a server error. """ client = NAppsClient(self._config) client.delete(self.user, self.napp)
Return whether we should create a (new) skeleton.
def _ask_openapi(): """Return whether we should create a (new) skeleton.""" if Path('openapi.yml').exists(): question = 'Override local openapi.yml with a new skeleton? (y/N) ' default = False else: question = 'Do you have REST endpoints and wish to create an ...
Prepare NApp to be uploaded by creating openAPI skeleton.
def prepare(cls): """Prepare NApp to be uploaded by creating openAPI skeleton.""" if cls._ask_openapi(): napp_path = Path() tpl_path = SKEL_PATH / 'napp-structure/username/napp' OpenAPI(napp_path, tpl_path).render_template() print('Please, update your open...
Reload a NApp or all NApps. Args: napps (list): NApp list to be reloaded. Raises: requests.HTTPError: When there's a server error.
def reload(self, napps=None): """Reload a NApp or all NApps. Args: napps (list): NApp list to be reloaded. Raises: requests.HTTPError: When there's a server error. """ client = NAppsClient(self._config) client.reload_napps(napps)
data bytes (high + low) 1 + 2 = current temp 3 + 4 = min temp 5 + 6 = max temp :return: None
def populate(self, priority, address, rtr, data): """ data bytes (high + low) 1 + 2 = current temp 3 + 4 = min temp 5 + 6 = max temp :return: None """ assert isinstance(data, bytes) self.needs_no_rtr(rtr) self.needs_data(d...
:return: str
def to_json(self): """ :return: str """ json_dict = self.to_json_basic() json_dict['rain'] = self.rain json_dict['light'] = self.light json_dict['wind'] = self.wind return json.dumps(json_dict)
Given a large image, return the thumbnail url
def _get_thumbnail_url(image): """ Given a large image, return the thumbnail url """ lhs, rhs = splitext(image.url) lhs += THUMB_EXT thumb_url = f'{lhs}{rhs}' return thumb_url
Create a client from environment variable settings. :param basestring env_filename: filename of the environment file, defaults to '.env' in the local dir (or parent dir) :return: :class:`pykechain.Client` Example ------- Initiates the py...
def from_env(cls, env_filename=None): # type: (Optional[str]) -> Client """Create a client from environment variable settings. :param basestring env_filename: filename of the environment file, defaults to '.env' in the local dir (or parent dir) :r...
Login into KE-chain with either username/password or token. :param basestring username: username for your user from KE-chain :param basestring password: password for your user from KE-chain :param basestring token: user authentication token retrieved from KE-chain Examples ----...
def login(self, username=None, password=None, token=None): # type: (Optional[str], Optional[str], Optional[str]) -> None """Login into KE-chain with either username/password or token. :param basestring username: username for your user from KE-chain :param basestring password: password f...
Build the correct API url.
def _build_url(self, resource, **kwargs): # type: (str, **str) -> str """Build the correct API url.""" return urljoin(self.api_root, API_PATH[resource].format(**kwargs))
Retrieve user objects of the entire administration. :return: list of dictionary with users information :rtype: list(dict) -------
def _retrieve_users(self): """ Retrieve user objects of the entire administration. :return: list of dictionary with users information :rtype: list(dict) ------- """ users_url = self._build_url('users') response = self._request('GET', users_url) u...
Perform the request on the API.
def _request(self, method, url, **kwargs): # type: (str, str, **Any) -> requests.Response """Perform the request on the API.""" self.last_request = None self.last_response = self.session.request(method, url, auth=self.auth, headers=self.headers, **kwargs) self.last_request = self...
List of the versions of the internal KE-chain 'app' modules.
def app_versions(self): """List of the versions of the internal KE-chain 'app' modules.""" if not self._app_versions: app_versions_url = self._build_url('versions') response = self._request('GET', app_versions_url) if response.status_code == requests.codes.not_found...
Match app version against a semantic version string. Checks if a KE-chain app matches a version comparison. Uses the `semver` matcher to check. `match("2.0.0", ">=1.0.0")` => `True` `match("1.0.0", ">1.0.0")` => `False` Examples -------- >>> client.match_app_version(la...
def match_app_version(self, app=None, label=None, version=None, default=False): """Match app version against a semantic version string. Checks if a KE-chain app matches a version comparison. Uses the `semver` matcher to check. `match("2.0.0", ">=1.0.0")` => `True` `match("1.0.0", ">1.0...
Reload an object from server. This method is immutable and will return a new object. :param obj: object to reload :type obj: :py:obj:`obj` :param extra_params: additional object specific extra query string params (eg for activity) :type extra_params: dict :return: a new object ...
def reload(self, obj, extra_params=None): """Reload an object from server. This method is immutable and will return a new object. :param obj: object to reload :type obj: :py:obj:`obj` :param extra_params: additional object specific extra query string params (eg for activity) :ty...
Return all scopes visible / accessible for the logged in user. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional query parameters. :param name: if provided, filter the search for...
def scopes(self, name=None, pk=None, status=ScopeStatus.ACTIVE, **kwargs): # type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Scope] """Return all scopes visible / accessible for the logged in user. If additional `keyword=value` arguments are provided, these are added to the r...
Return a single scope based on the provided name. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional query parameters. :return: a single :class:`models.Scope` :raises NotF...
def scope(self, *args, **kwargs): # type: (*Any, **Any) -> Scope """Return a single scope based on the provided name. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional que...
Search for activities with optional name, pk and scope filter. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional query parameters. :param pk: id (primary key) of the activity to ...
def activities(self, name=None, pk=None, scope=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Activity] """Search for activities with optional name, pk and scope filter. If additional `keyword=value` arguments are provided, these are added to the request p...
Search for a single activity. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional query parameters. :param pk: id (primary key) of the activity to retrieve :type pk: basest...
def activity(self, *args, **kwargs): # type: (*Any, **Any) -> Activity """Search for a single activity. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional query parameters....
Retrieve multiple KE-chain parts. If no parameters are provided, all parts are retrieved. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional query parameters. :param name...
def parts(self, name=None, # type: Optional[str] pk=None, # type: Optional[str] model=None, # type: Optional[Part] category=Category.INSTANCE, # type: Optional[str] bucket=None, # type: Optional[str] parent=None, # type: Optional[...
Retrieve single KE-chain part. Uses the same interface as the :func:`parts` method but returns only a single pykechain :class:`models.Part` instance. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of th...
def part(self, *args, **kwargs): # type: (*Any, **Any) -> Part """Retrieve single KE-chain part. Uses the same interface as the :func:`parts` method but returns only a single pykechain :class:`models.Part` instance. If additional `keyword=value` arguments are provided, these ar...
Retrieve single KE-chain part model. Uses the same interface as the :func:`part` method but returns only a single pykechain :class:`models.Part` instance of category `MODEL`. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer t...
def model(self, *args, **kwargs): # type: (*Any, **Any) -> Part """Retrieve single KE-chain part model. Uses the same interface as the :func:`part` method but returns only a single pykechain :class:`models.Part` instance of category `MODEL`. If additional `keyword=value` argume...
Retrieve single KE-chain Property. Uses the same interface as the :func:`properties` method but returns only a single pykechain :class: `models.Property` instance. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the docum...
def property(self, *args, **kwargs): # type: (*Any, **Any) -> Property """Retrieve single KE-chain Property. Uses the same interface as the :func:`properties` method but returns only a single pykechain :class: `models.Property` instance. If additional `keyword=value` arguments ...
Retrieve properties. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional query parameters. :param name: name to limit the search for. :type name: basestring or None ...
def properties(self, name=None, pk=None, category=Category.INSTANCE, **kwargs): # type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Property] """Retrieve properties. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please ...
Retrieve Services. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional query parameters. :param name: (optional) name to limit the search for :type name: basestring or None...
def services(self, name=None, pk=None, scope=None, **kwargs): """ Retrieve Services. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional query parameters. :param na...
Retrieve single KE-chain Service. Uses the same interface as the :func:`services` method but returns only a single pykechain :class:`models.Service` instance. :param name: (optional) name to limit the search for :type name: basestring or None :param pk: (optional) primary key o...
def service(self, name=None, pk=None, scope=None, **kwargs): """ Retrieve single KE-chain Service. Uses the same interface as the :func:`services` method but returns only a single pykechain :class:`models.Service` instance. :param name: (optional) name to limit the search for ...
Retrieve Service Executions. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional query parameters. :param name: (optional) name to limit the search for :type name: basestri...
def service_executions(self, name=None, pk=None, scope=None, service=None, **kwargs): """ Retrieve Service Executions. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please refer to the documentation of the KE-chain API for additional qu...
Retrieve single KE-chain ServiceExecution. Uses the same interface as the :func:`service_executions` method but returns only a single pykechain :class:`models.ServiceExecution` instance. If additional `keyword=value` arguments are provided, these are added to the request parameters. Please ...
def service_execution(self, name=None, pk=None, scope=None, service=None, **kwargs): """ Retrieve single KE-chain ServiceExecution. Uses the same interface as the :func:`service_executions` method but returns only a single pykechain :class:`models.ServiceExecution` instance. If...
User of KE-chain. Provides single user of :class:`User` of KE-chain. You can filter on username or id or an advanced filter. :param username: (optional) username to filter :type username: basestring or None :param pk: (optional) id of the user to filter :type pk: basestring or ...
def user(self, username=None, pk=None, **kwargs): """ User of KE-chain. Provides single user of :class:`User` of KE-chain. You can filter on username or id or an advanced filter. :param username: (optional) username to filter :type username: basestring or None :param pk...
Users of KE-chain. Provide a list of :class:`User`s of KE-chain. You can filter on username or id or any other advanced filter. :param username: (optional) username to filter :type username: basestring or None :param pk: (optional) id of the user to filter :type pk: basestring ...
def users(self, username=None, pk=None, **kwargs): """ Users of KE-chain. Provide a list of :class:`User`s of KE-chain. You can filter on username or id or any other advanced filter. :param username: (optional) username to filter :type username: basestring or None :para...
Team of KE-chain. Provides a team of :class:`Team` of KE-chain. You can filter on team name or provide id. :param name: (optional) team name to filter :type name: basestring or None :param id: (optional) id of the user to filter :type id: basestring or None :param is_hi...
def team(self, name=None, id=None, is_hidden=False, **kwargs): """ Team of KE-chain. Provides a team of :class:`Team` of KE-chain. You can filter on team name or provide id. :param name: (optional) team name to filter :type name: basestring or None :param id: (optional)...
Teams of KE-chain. Provide a list of :class:`Team`s of KE-chain. You can filter on teamname or id or any other advanced filter. :param name: (optional) teamname to filter :type name: basestring or None :param id: (optional) id of the team to filter :type id: basestring or None ...
def teams(self, name=None, id=None, is_hidden=False, **kwargs): """ Teams of KE-chain. Provide a list of :class:`Team`s of KE-chain. You can filter on teamname or id or any other advanced filter. :param name: (optional) teamname to filter :type name: basestring or None ...
Create a new activity. .. important:: This is a shim function that based on the implementation of KE-chain will determine to create the activity using the legacy WIM API (KE-chain < 2.9.0) or the newer WIM2 API (KE-chain >= 2.9.0). It will either return a :class:`Activity` o...
def create_activity(self, *args, **kwargs): """ Create a new activity. .. important:: This is a shim function that based on the implementation of KE-chain will determine to create the activity using the legacy WIM API (KE-chain < 2.9.0) or the newer WIM2 API (KE-chain >=...
Create a new activity. :param process: parent process id :type process: basestring :param name: new activity name :type name: basestring :param activity_class: type of activity: UserTask (default) or Subprocess :type activity_class: basestring :return: the create...
def _create_activity1(self, process, name, activity_class="UserTask"): """Create a new activity. :param process: parent process id :type process: basestring :param name: new activity name :type name: basestring :param activity_class: type of activity: UserTask (default) ...
Create a new activity. .. important:: This function creates activities for KE-chain versions later than 2.9.0-135 In effect where the module 'wim' has version '>=2.0.0'. The version of 'wim' in KE-chain can be found in the property :attr:`Client.app_versions` In WIM...
def _create_activity2(self, parent, name, activity_type=ActivityType.TASK): """Create a new activity. .. important:: This function creates activities for KE-chain versions later than 2.9.0-135 In effect where the module 'wim' has version '>=2.0.0'. The version of 'wi...
Create a part internal core function.
def _create_part(self, action, data, **kwargs): """Create a part internal core function.""" # suppress_kevents should be in the data (not the query_params) if 'suppress_kevents' in kwargs: data['suppress_kevents'] = kwargs.pop('suppress_kevents') # prepare url query paramete...
Create a new part instance from a given model under a given parent. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve performance of the backend against a trade-off that someone l...
def create_part(self, parent, model, name=None, **kwargs): """Create a new part instance from a given model under a given parent. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve...
Create a new child model under a given parent. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve performance of the backend against a trade-off that someone looking at the fronten...
def create_model(self, parent, name, multiplicity='ZERO_MANY', **kwargs): """Create a new child model under a given parent. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve perfo...