INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
:return: int | def channels_to_byte(self, channels):
"""
:return: int
"""
# pylint: disable-msg=R0201
assert isinstance(channels, list)
result = 0
for offset in range(0, 8):
if offset + 1 in channels:
result = result + (1 << offset)
... |
:return: int | def byte_to_channel(self, byte):
"""
:return: int
"""
assert isinstance(byte, int)
channels = self.byte_to_channels(byte)
self.needs_one_channel(channels)
return channels[0] |
:return: None | def needs_valid_channel(self, channel, maximum):
"""
:return: None
"""
assert isinstance(channel, int)
assert isinstance(maximum, int)
if channel < 1 and channel > maximum:
self.parser_error("needs valid channel in channel byte") |
:return: None | def needs_low_priority(self, priority):
"""
:return: None
"""
assert isinstance(priority, int)
if priority != velbus.LOW_PRIORITY:
self.parser_error("needs low priority set") |
:return: None | def needs_high_priority(self, priority):
"""
:return: None
"""
assert isinstance(priority, int)
if priority != velbus.HIGH_PRIORITY:
self.parser_error("needs high priority set") |
:return: None | def needs_firmware_priority(self, priority):
"""
:return: None
"""
assert isinstance(priority, int)
if priority != velbus.FIRMWARE_PRIORITY:
self.parser_error("needs firmware priority set") |
:return: None | def needs_data(self, data, length):
"""
:return: None
"""
assert isinstance(data, bytes)
if len(data) < length:
self.parser_error("needs " + str(length) + " bytes of data have " + str(len(data))) |
:return: None | def needs_fixed_byte(self, byte, value):
"""
:return: None
"""
assert isinstance(byte, int)
assert isinstance(value, int)
assert byte >= 0 and value >= 0
assert byte <= 0xff and value <= 0xff
if byte != value:
self.parser_error("expect... |
:return: None | def needs_one_channel(self, channels):
"""
:return: None
"""
assert isinstance(channels, list)
if len(channels) != 1 or not isinstance(channels[0], int) or \
not channels[0] > 0 or not channels[0] <= 8:
self.parser_error("needs exactly one bit s... |
Tracking Protection shield.
Returns:
bool: True or False if the Tracking Shield is displayed. | def is_tracking_shield_displayed(self):
"""Tracking Protection shield.
Returns:
bool: True or False if the Tracking Shield is displayed.
"""
with self.selenium.context(self.selenium.CONTEXT_CHROME):
if self.window.firefox_version >= 63: # Bug 1471713, 1476218
... |
Checks if the device + username have already been registered with the
bridge. | def validate_registration(self):
'''
Checks if the device + username have already been registered with the
bridge.
'''
url = '/api/%s' % self.username
response = self.make_request('GET', url)
if 'error' in response:
return False
return True |
Registers a new device + username with the bridge | def connect(self):
'''
Registers a new device + username with the bridge
'''
# Don't try to register if we already have
if self.validate_registration():
return True
body = {
'devicetype': self.device_type,
'username': self.username,
... |
Lists all available lights on the bridge. | def get_lights(self):
'''
Lists all available lights on the bridge.
'''
url = '/api/%s/lights' % self.username
response = self.make_request('GET', url)
lights = []
# Did we get a success response back?
# error responses look like:
# [{'error': {'ad... |
Sets state on the light, can be used like this:
.. code-block:: python
set_state(1, xy=[1,2]) | def set_state(self, light_id, **kwargs):
'''
Sets state on the light, can be used like this:
.. code-block:: python
set_state(1, xy=[1,2])
'''
light = self.get_light(light_id)
url = '/api/%s/lights/%s/state' % (self.username, light.light_id)
response... |
This will set the light color based on a hex value | def set_color(self, light_id, hex_value, brightness=None):
'''
This will set the light color based on a hex value
'''
light = self.get_light(light_id)
xy = get_xy_from_hex(hex_value)
data = {
'xy': [xy.x, xy.y],
}
if brightness is not None:
... |
This functions computes the fft of a signal, returning the frequency
and their magnitude values.
Parameters
----------
s: array-like
the input signal.
fmax: int
the sampling frequency.
doplot: boolean
a variable to indicate whether the plot is done or not.
Returns
---... | def plotfft(s, fmax, doplot=False):
""" This functions computes the fft of a signal, returning the frequency
and their magnitude values.
Parameters
----------
s: array-like
the input signal.
fmax: int
the sampling frequency.
doplot: boolean
a variable to indicate whether t... |
@brief This function loads a file from the current directory and saves
the cached file to later executions. It's also possible to make a recache
or a subsampling of the signal and choose only a few columns of the signal,
to accelerate the opening process.
@param file String: the name of the file to ope... | def load_with_cache(file_, recache=False, sampling=1,
columns=None, temp_dir='.', data_type='int16'):
"""@brief This function loads a file from the current directory and saves
the cached file to later executions. It's also possible to make a recache
or a subsampling of the signal and cho... |
:rtype : numpy matrix | def load_data(filename):
"""
:rtype : numpy matrix
"""
data = pandas.read_csv(filename, header=None, delimiter='\t', skiprows=9)
return data.as_matrix() |
:return: None | def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_low_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 7)
self.set_attributes(priority, address, rtr)
self.channel = self... |
:return: str | def to_json(self):
"""
:return: str
"""
json_dict = self.to_json_basic()
json_dict['channel'] = self.channel
json_dict['timeout'] = self.timeout
json_dict['status'] = self.status
json_dict['led_status'] = self.led_status
json_dict['blind_position']... |
:return: bytes | def data_to_binary(self):
"""
:return: bytes
"""
return bytes([
COMMAND_CODE,
self.channels_to_byte([self.channel]),
self.timeout,
self.status,
self.led_status,
self.blind_position,
self.locked_inhibit_fo... |
Discovers services on a network using the SSDP Protocol. | def discover(service, timeout=5, retries=5):
'''
Discovers services on a network using the SSDP Protocol.
'''
group = ('239.255.255.250', 1900)
message = '\r\n'.join([
'M-SEARCH * HTTP/1.1',
'HOST: {0}:{1}',
'MAN: "ssdp:discover"',
'ST: {st}', 'MX: 3', '', ''])
so... |
Checks if the specified model instance matches the class model.
By default this method will raise a `ValueError` if the model is not of
expected type.
Args:
model (Model) : The instance to be type checked
raise_error (bool) : Flag to specify whether to raise error on
... | def _isinstance(self, model, raise_error=True):
"""Checks if the specified model instance matches the class model.
By default this method will raise a `ValueError` if the model is not of
expected type.
Args:
model (Model) : The instance to be type checked
raise... |
Returns a preprocessed dictionary of parameters.
Use this to filter the kwargs passed to `new`, `create`,
`build` methods.
Args:
**kwargs: a dictionary of parameters | def _preprocess_params(cls, kwargs):
"""Returns a preprocessed dictionary of parameters.
Use this to filter the kwargs passed to `new`, `create`,
`build` methods.
Args:
**kwargs: a dictionary of parameters
"""
# kwargs.pop('csrf_token', None)
for att... |
Updates an instance.
Args:
**kwargs : Arbitrary keyword arguments. Column names are
keywords and their new values are the values.
Examples:
>>> customer.update(email="newemail@x.com", name="new") | def update(self, **kwargs):
"""Updates an instance.
Args:
**kwargs : Arbitrary keyword arguments. Column names are
keywords and their new values are the values.
Examples:
>>> customer.update(email="newemail@x.com", name="new")
"""
kwa... |
Same as SQLAlchemy's filter_by. Additionally this accepts
two special keyword arguments `limit` and `reverse` for limiting
the results and reversing the order respectively.
Args:
**kwargs: filter parameters
Examples:
>>> user = User.filter_by(email="new@x.com"... | def filter_by(cls, **kwargs):
"""Same as SQLAlchemy's filter_by. Additionally this accepts
two special keyword arguments `limit` and `reverse` for limiting
the results and reversing the order respectively.
Args:
**kwargs: filter parameters
Examples:
>>... |
Returns a count of the instances meeting the specified
filter criterion and kwargs.
Examples:
>>> User.count()
500
>>> User.count(country="India")
300
>>> User.count(User.age > 50, country="India")
39 | def count(cls, *criterion, **kwargs):
"""Returns a count of the instances meeting the specified
filter criterion and kwargs.
Examples:
>>> User.count()
500
>>> User.count(country="India")
300
>>> User.count(User.age > 50, country="I... |
Returns the last instance matching the criterion and/or
keyword arguments.
Examples:
last_male_user = User.last(gender="male") | def last(cls, *criterion, **kwargs):
"""Returns the last instance matching the criterion and/or
keyword arguments.
Examples:
last_male_user = User.last(gender="male")
"""
kwargs['reverse'] = True
return cls.first(*criterion, **kwargs) |
Returns a new, unsaved instance of the model class. | def new(cls, **kwargs):
"""Returns a new, unsaved instance of the model class.
"""
kwargs = cls.preprocess_kwargs_before_new(kwargs)
if cls.__mapper__.polymorphic_on is not None:
discriminator_key = cls.__mapper__.polymorphic_on.name
discriminator_val = kwargs.ge... |
Adds a model instance to session and commits the
transaction.
Args:
model: The instance to add.
Examples:
>>> customer = Customer.new(name="hari", email="hari@gmail.com")
>>> Customer.add(customer)
hari@gmail.com | def add(cls, model, commit=True):
"""Adds a model instance to session and commits the
transaction.
Args:
model: The instance to add.
Examples:
>>> customer = Customer.new(name="hari", email="hari@gmail.com")
>>> Customer.add(customer)
... |
Batch method for adding a list of model instances
to the db in one get_or_404.
Args:
models (list): A list of the instances to add.
commit (bool, optional): Defaults to True. If False, the
transaction won't get committed.
check_type (bool, optional) ... | def add_all(cls, models, commit=True, check_type=False):
"""Batch method for adding a list of model instances
to the db in one get_or_404.
Args:
models (list): A list of the instances to add.
commit (bool, optional): Defaults to True. If False, the
trans... |
Fetches a single instance which has value `keyval`
for the attribute `key`.
Args:
keyval: The value of the attribute.
key (str, optional): The attribute to search by. By default,
it is 'id'.
Returns:
A model instance if found. Else None.
... | def get(cls, keyval, key='id', user_id=None):
"""Fetches a single instance which has value `keyval`
for the attribute `key`.
Args:
keyval: The value of the attribute.
key (str, optional): The attribute to search by. By default,
it is 'id'.
Ret... |
Works like a map function from keyvals to instances.
Args:
keyvals(list): The list of values of the attribute.
key (str, optional): The attribute to search by. By default, it is
'id'.
Returns:
list: A list of model instances, in the same order ... | def get_all(cls, keyvals, key='id', user_id=None):
"""Works like a map function from keyvals to instances.
Args:
keyvals(list): The list of values of the attribute.
key (str, optional): The attribute to search by. By default, it is
'id'.
Returns:
... |
Initializes a new instance, adds it to the db and commits
the transaction.
Args:
**kwargs: The keyword arguments for the init constructor.
Examples:
>>> user = User.create(name="Vicky", email="vicky@h.com")
>>> user.id
35 | def create(cls, **kwargs):
"""Initializes a new instance, adds it to the db and commits
the transaction.
Args:
**kwargs: The keyword arguments for the init constructor.
Examples:
>>> user = User.create(name="Vicky", email="vicky@h.com")
>>> user.id... |
Checks if an instance already exists by filtering with the
kwargs. If yes, returns that instance. If not, creates a new
instance with kwargs and returns it
Args:
**kwargs: The keyword arguments which are used for filtering
and initialization.
keys(list, ... | def find_or_create(cls, **kwargs):
"""Checks if an instance already exists by filtering with the
kwargs. If yes, returns that instance. If not, creates a new
instance with kwargs and returns it
Args:
**kwargs: The keyword arguments which are used for filtering
... |
Checks if an instance already exists by filtering with the
kwargs. If yes, updates the instance with new kwargs and
returns that instance. If not, creates a new
instance with kwargs and returns it.
Args:
**kwargs: The keyword arguments which are used for filtering
... | def update_or_create(cls, **kwargs):
"""Checks if an instance already exists by filtering with the
kwargs. If yes, updates the instance with new kwargs and
returns that instance. If not, creates a new
instance with kwargs and returns it.
Args:
**kwargs: The keyword ... |
Batch method for creating a list of instances
Args:
list_of_kwargs(list of dicts): hereA list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately
Examples:
>>> Customer.create_all([
.... | def create_all(cls, list_of_kwargs):
"""Batch method for creating a list of instances
Args:
list_of_kwargs(list of dicts): hereA list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately
Examples:
... |
Batch method for querying for a list of instances and
creating them if required
Args:
list_of_kwargs(list of dicts): A list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately
keys (list, optional... | def find_or_create_all(cls, list_of_kwargs, keys=[]):
"""Batch method for querying for a list of instances and
creating them if required
Args:
list_of_kwargs(list of dicts): A list of dicts where
each dict denotes the keyword args that you would pass
... |
Batch method for updating a list of instances and
creating them if required
Args:
list_of_kwargs(list of dicts): A list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately
keys (list, optional): A... | def update_or_create_all(cls, list_of_kwargs, keys=[]):
"""Batch method for updating a list of instances and
creating them if required
Args:
list_of_kwargs(list of dicts): A list of dicts where
each dict denotes the keyword args that you would pass
to... |
Similar to create. But the transaction is not committed
Args:
**kwargs : The keyword arguments for the constructor
Returns:
A model instance which has been added to db session. But session
transaction has not been committed yet. | def build(cls, **kwargs):
"""Similar to create. But the transaction is not committed
Args:
**kwargs : The keyword arguments for the constructor
Returns:
A model instance which has been added to db session. But session
transaction has not been committed yet... |
Checks if an instance already exists in db with these kwargs else
returns a new, saved instance of the service's model class.
Args:
**kwargs: instance parameters | def find_or_build(cls, **kwargs):
"""Checks if an instance already exists in db with these kwargs else
returns a new, saved instance of the service's model class.
Args:
**kwargs: instance parameters
"""
keys = kwargs.pop('keys') if 'keys' in kwargs else []
re... |
Similar to `create_all`. But transaction is not committed. | def build_all(cls, list_of_kwargs):
"""Similar to `create_all`. But transaction is not committed.
"""
return cls.add_all([
cls.new(**kwargs) for kwargs in list_of_kwargs], commit=False) |
Similar to `find_or_create_all`. But transaction is not committed. | def find_or_build_all(cls, list_of_kwargs):
"""Similar to `find_or_create_all`. But transaction is not committed.
"""
return cls.add_all([cls.first(**kwargs) or cls.new(**kwargs)
for kwargs in list_of_kwargs], commit=False) |
Batch method for updating all instances obeying the criterion
Args:
*criterion: SQLAlchemy query criterion for filtering what
instances to update
**kwargs: The parameters to be updated
Examples:
>>> User.update_all(active=True)
>>> Cust... | def update_all(cls, *criterion, **kwargs):
"""Batch method for updating all instances obeying the criterion
Args:
*criterion: SQLAlchemy query criterion for filtering what
instances to update
**kwargs: The parameters to be updated
Examples:
... |
Returns an updated instance of the service's model class.
Args:
model: the model to update
**kwargs: update parameters | def get_and_update(cls, id, **kwargs):
"""Returns an updated instance of the service's model class.
Args:
model: the model to update
**kwargs: update parameters
"""
model = cls.get(id)
for k, v in cls._preprocess_params(kwargs).items():
setatt... |
Returns an updated instance of the service's model class.
Args:
model: the model to update
**kwargs: update parameters | def get_and_setattr(cls, id, **kwargs):
"""Returns an updated instance of the service's model class.
Args:
model: the model to update
**kwargs: update parameters
"""
model = cls.get(id)
for k, v in cls._preprocess_params(kwargs).items():
setat... |
Returns two arrays
function [maxtab, mintab]=peakdelta(v, delta, x)
%PEAKDET Detect peaks in a vector
% [MAXTAB, MINTAB] = peakdelta(V, DELTA) finds the local
% maxima and minima ("peaks") in the vector V.
% MAXTAB and MINTAB consists of two columns. Column 1
% conta... | def peakdelta(v, delta, x=None):
"""
Returns two arrays
function [maxtab, mintab]=peakdelta(v, delta, x)
%PEAKDET Detect peaks in a vector
% [MAXTAB, MINTAB] = peakdelta(V, DELTA) finds the local
% maxima and minima ("peaks") in the vector V.
% MAXTAB and MINTAB consist... |
:return: None | def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_high_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 4)
self.set_attributes(priority, address, rtr)
self.relay_channel... |
:return: bytes | def data_to_binary(self):
"""
:return: bytes
"""
return bytes([
COMMAND_CODE,
self.channels_to_byte(self.relay_channels)]) + \
struct.pack('>L', self.delay_time)[-3:] |
Callback to execute on status of update of channel | def on_status_update(self, channel, callback):
"""
Callback to execute on status of update of channel
"""
if channel not in self._callbacks:
self._callbacks[channel] = []
self._callbacks[channel].append(callback) |
:return: bytes | def data_to_binary(self):
"""
:return: bytes
"""
return bytes([
COMMAND_CODE,
self.high_address,
self.low_address
]) + self.data |
Create and return a temporary directory which you can use as a context manager.
When you are out of the context the temprorary disk gets erased.
.. versionadded:: 2.3
:param cwd: path to change working directory back to path when out of context
:type cwd: basestring or None
:return: in context a ... | def temp_chdir(cwd=None):
"""
Create and return a temporary directory which you can use as a context manager.
When you are out of the context the temprorary disk gets erased.
.. versionadded:: 2.3
:param cwd: path to change working directory back to path when out of context
:type cwd: basestr... |
Convert datetime string to datetime object.
Helper function to convert a datetime string found in json responses to a datetime object with timezone information.
The server is storing all datetime strings as UTC (ZULU time). This function supports time zone offsets. When
the input contains one, the output u... | def parse_datetime(value):
"""
Convert datetime string to datetime object.
Helper function to convert a datetime string found in json responses to a datetime object with timezone information.
The server is storing all datetime strings as UTC (ZULU time). This function supports time zone offsets. When
... |
Save the complete customization to the activity.
:param widgets: The complete set of widgets to be customized | def _save_customization(self, widgets):
"""
Save the complete customization to the activity.
:param widgets: The complete set of widgets to be customized
"""
if len(widgets) > 0:
# Get the current customization and only replace the 'ext' part of it
custom... |
Add a widget to the customization.
Will save the widget to KE-chain.
:param widget: The widget (specific json dict) to be added
:type widget: dict | def _add_widget(self, widget):
"""
Add a widget to the customization.
Will save the widget to KE-chain.
:param widget: The widget (specific json dict) to be added
:type widget: dict
"""
widgets = self.widgets()
widgets += [widget]
self._save_cust... |
Get the Ext JS specific customization from the activity.
:return: The Ext JS specific customization in `list(dict)` form | def widgets(self):
"""
Get the Ext JS specific customization from the activity.
:return: The Ext JS specific customization in `list(dict)` form
"""
customization = self.activity._json_data.get('customization')
if customization and "ext" in customization.keys():
... |
Delete widgets by index.
The widgets are saved to KE-chain.
:param index: The index of the widget to be deleted in the self.widgets
:type index: int
:raises ValueError: if the customization has no widgets | def delete_widget(self, index):
"""
Delete widgets by index.
The widgets are saved to KE-chain.
:param index: The index of the widget to be deleted in the self.widgets
:type index: int
:raises ValueError: if the customization has no widgets
"""
widgets =... |
Add an Ext Json Widget to the customization.
The configuration json provided must be interpretable by KE-chain. The json will be validated
against the widget json schema.
The widget will be saved to KE-chain.
:param config: The json configuration of the widget
:type config: di... | def add_json_widget(self, config):
"""
Add an Ext Json Widget to the customization.
The configuration json provided must be interpretable by KE-chain. The json will be validated
against the widget json schema.
The widget will be saved to KE-chain.
:param config: The js... |
Add a KE-chain Property Grid widget to the customization.
The widget will be saved to KE-chain.
:param part_instance: The part instance on which the property grid will be based
:type part_instance: :class:`Part` or UUID
:param max_height: The max height of the property grid in pixels
... | def add_property_grid_widget(self, part_instance, max_height=None, custom_title=False, show_headers=True,
show_columns=None):
"""
Add a KE-chain Property Grid widget to the customization.
The widget will be saved to KE-chain.
:param part_instance: The p... |
Add a KE-chain Text widget to the customization.
The widget will be saved to KE-chain.
:param text: The text that will be shown by the widget.
:type text: basestring or None
:param custom_title: A custom title for the text panel::
* None (default): No title
* St... | def add_text_widget(self, text=None, custom_title=None, collapsible=True, collapsed=False):
"""
Add a KE-chain Text widget to the customization.
The widget will be saved to KE-chain.
:param text: The text that will be shown by the widget.
:type text: basestring or None
... |
Add a KE-chain paginatedGrid (e.g. paginated table widget) to the customization.
The widget will be saved to KE-chain.
:param emphasize_new_instance: Emphasize the New instance button (default True)
:type emphasize_new_instance: bool
:param emphasize_edit: Emphasize the Edit button (de... | def add_paginated_grid_widget(self, part_model, delete=False, edit=True, export=True, clone=True,
new_instance=False, parent_part_instance=None, max_height=None, custom_title=False,
emphasize_edit=False, emphasize_clone=False, emphasize_new_instance=Tr... |
Add a KE-chain Script (e.g. script widget) to the customization.
The widget will be saved to KE-chain.
:param script: The Script to which the button will be coupled and will be ran when the button is pressed.
:type script: :class:`Service` or UUID
:param custom_title: A custom title fo... | def add_script_widget(self, script, custom_title=False, custom_button_text=False, emphasize_run=True,
download_log=False):
"""
Add a KE-chain Script (e.g. script widget) to the customization.
The widget will be saved to KE-chain.
:param script: The Script to w... |
Add a KE-chain Notebook (e.g. notebook widget) to the customization.
The widget will be saved to KE-chain.
:param notebook: The Notebook to which the button will be coupled and will start when the button is pressed.
:type notebook: :class:`Service` or UUID
:param custom_title: A custom... | def add_notebook_widget(self, notebook, custom_title=False, height=None):
"""
Add a KE-chain Notebook (e.g. notebook widget) to the customization.
The widget will be saved to KE-chain.
:param notebook: The Notebook to which the button will be coupled and will start when the button is p... |
Add a KE-chain Attachment Viewer (e.g. attachment viewer widget) to the customization.
The widget will be saved to KE-chain.
:param attachment_property: The Attachment Property to which the Viewer will be connected to.
:type attachment_property: :class:`Property` or UUID
:param custom_... | def add_attachment_viewer_widget(self, attachment_property, custom_title=False, height=None):
"""
Add a KE-chain Attachment Viewer (e.g. attachment viewer widget) to the customization.
The widget will be saved to KE-chain.
:param attachment_property: The Attachment Property to which th... |
:return: None | def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_low_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 3)
self.transmit_error_counter = data[0]
self.receive_error_counte... |
:return: bytes | def data_to_binary(self):
"""
:return: bytes
"""
return bytes([COMMAND_CODE, self.transmit_error_counter,
self.receive_error_counter, self.bus_off_counter]) |
Monkey-patch the multiprocessing.Process class with our own CrashReportingProcess.
Any subsequent imports of multiprocessing.Process will reference CrashReportingProcess instead.
This function must be called before any imports to mulitprocessing in order for the monkey-patching to work. | def enable_mp_crash_reporting():
"""
Monkey-patch the multiprocessing.Process class with our own CrashReportingProcess.
Any subsequent imports of multiprocessing.Process will reference CrashReportingProcess instead.
This function must be called before any imports to mulitprocessing in order for the mon... |
Add new incoming data to buffer and try to process | def feed(self, data):
"""
Add new incoming data to buffer and try to process
"""
self.buffer += data
while len(self.buffer) >= 6:
self.next_packet() |
Check if a valid header is waiting in buffer | def valid_header_waiting(self):
"""
Check if a valid header is waiting in buffer
"""
if len(self.buffer) < 4:
self.logger.debug("Buffer does not yet contain full header")
result = False
else:
result = True
result = result and self.b... |
Check if a valid body is waiting in buffer | def valid_body_waiting(self):
"""
Check if a valid body is waiting in buffer
"""
# 0f f8 be 04 00 08 00 00 2f 04
packet_size = velbus.MINIMUM_MESSAGE_SIZE + \
(self.buffer[3] & 0x0F)
if len(self.buffer) < packet_size:
self.logger.debug("Buffer does... |
Process next packet if present | def next_packet(self):
"""
Process next packet if present
"""
try:
start_byte_index = self.buffer.index(velbus.START_BYTE)
except ValueError:
self.buffer = bytes([])
return
if start_byte_index >= 0:
self.buffer = self.buffer... |
Extract packet from buffer | def extract_packet(self):
"""
Extract packet from buffer
"""
packet_size = velbus.MINIMUM_MESSAGE_SIZE + \
(self.buffer[3] & 0x0F)
packet = self.buffer[0:packet_size]
return packet |
:return: None | def parse(self, data):
"""
:return: None
"""
# pylint: disable-msg=R0911,C1801
assert isinstance(data, bytes)
assert len(data) > 0
assert len(data) >= velbus.MINIMUM_MESSAGE_SIZE
assert data[0] == velbus.START_BYTE
self.logger.debug("Processing mes... |
Helper function for extract_values,
figures out string length from format string. | def _get_number_from_fmt(fmt):
"""
Helper function for extract_values,
figures out string length from format string.
"""
if '%' in fmt:
# its datetime
return len(("{0:" + fmt + "}").format(dt.datetime.now()))
else:
# its something else
fmt = fmt.lstrip('0')
... |
Convert the string *stri* to the given conversion definition *convdef*. | def _convert(convdef, stri):
"""Convert the string *stri* to the given conversion definition *convdef*."""
if '%' in convdef:
result = dt.datetime.strptime(stri, convdef)
elif 'd' in convdef or 's' in convdef:
regex_match = fmt_spec_regex.match(convdef)
match_dict = regex_match.group... |
Retrieve parse definition from the format string `fmt`. | def get_convert_dict(fmt):
"""Retrieve parse definition from the format string `fmt`."""
convdef = {}
for literal_text, field_name, format_spec, conversion in formatter.parse(fmt):
if field_name is None:
continue
# XXX: Do I need to include 'conversion'?
convdef[field_nam... |
Parse keys and corresponding values from *stri* using format described in *fmt* string. | def parse(fmt, stri):
"""Parse keys and corresponding values from *stri* using format described in *fmt* string."""
convdef = get_convert_dict(fmt)
keyvals = regex_formatter.extract_values(fmt, stri)
for key in convdef.keys():
keyvals[key] = _convert(convdef[key], keyvals[key])
return keyva... |
Generate a fake data dictionary to fill in the provided format string. | def _generate_data_for_format(fmt):
"""Generate a fake data dictionary to fill in the provided format string."""
# finally try some data, create some random data for the fmt.
data = {}
# keep track of how many "free_size" (wildcard) parameters we have
# if we get two in a row then we know the patter... |
Runs a check to evaluate if the format string has a
one to one correspondence. I.e. that successive composing and
parsing opperations will result in the original data.
In other words, that input data maps to a string,
which then maps back to the original data without any change
or loss in informati... | def is_one2one(fmt):
"""
Runs a check to evaluate if the format string has a
one to one correspondence. I.e. that successive composing and
parsing opperations will result in the original data.
In other words, that input data maps to a string,
which then maps back to the original data without an... |
Apply conversions mentioned above. | def convert_field(self, value, conversion):
"""Apply conversions mentioned above."""
func = self.CONV_FUNCS.get(conversion)
if func is not None:
value = getattr(value, func)()
elif conversion not in ['R']:
# default conversion ('r', 's')
return super(S... |
Escape bad characters for regular expressions.
Similar to `re.escape` but allows '%' to pass through. | def _escape(self, s):
"""Escape bad characters for regular expressions.
Similar to `re.escape` but allows '%' to pass through.
"""
for ch, r_ch in self.ESCAPE_SETS:
s = s.replace(ch, r_ch)
return s |
Make an attempt at converting a format spec to a regular expression. | def format_spec_to_regex(field_name, format_spec):
"""Make an attempt at converting a format spec to a regular expression."""
# NOTE: remove escaped backslashes so regex matches
regex_match = fmt_spec_regex.match(format_spec.replace('\\', ''))
if regex_match is None:
raise Va... |
@brief This function prints in the screen the difference between
the time saved with function tic.py and current time.
@param label String: if something is desired to print (default = '').
@see also tic() | def tac(label=''):
"""@brief This function prints in the screen the difference between
the time saved with function tic.py and current time.
@param label String: if something is desired to print (default = '').
@see also tic()
"""
global _tic
delta_t = time.time() - _tic
if label !=... |
Feed parser with new data
:return: None | def feed_parser(self, data):
"""
Feed parser with new data
:return: None
"""
assert isinstance(data, bytes)
self.parser.feed(data) |
Scan the bus and call the callback when a new module is discovered
:return: None | def scan(self, callback=None):
"""
Scan the bus and call the callback when a new module is discovered
:return: None
"""
def scan_finished():
"""
Callback when scan is finished
"""
time.sleep(3)
logging.info('Scan finish... |
:return: None | def send_binary(self, binary_message, callback=None):
"""
:return: None
"""
assert isinstance(binary_message, str)
message = self.parser.parse(binary_message)
if isinstance(message, velbus.Message):
self.send(message, callback) |
:return: None | def new_message(self, message):
"""
:return: None
"""
self.logger.info("New message: " + str(message))
if isinstance(message, velbus.BusActiveMessage):
self.logger.info("Velbus active message received")
if isinstance(message, velbus.ReceiveReadyMessage):
... |
This will send all the needed messages to sync the cloc | def sync_clock(self):
"""
This will send all the needed messages to sync the cloc
"""
self.send(velbus.SetRealtimeClock())
self.send(velbus.SetDate())
self.send(velbus.SetDaylightSaving()) |
Look up the value of an object in a traceback by a dot-lookup string.
ie. "self.crashreporter.application_name"
Returns ValueError if value was not found in the scope of the traceback.
:param tb: traceback
:param s: lookup string
:return: value of the | def string_variable_lookup(tb, s):
"""
Look up the value of an object in a traceback by a dot-lookup string.
ie. "self.crashreporter.application_name"
Returns ValueError if value was not found in the scope of the traceback.
:param tb: traceback
:param s: lookup string
:return: value of the... |
Find the values of referenced attributes of objects within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value) | def get_object_references(tb, source, max_string_length=1000):
"""
Find the values of referenced attributes of objects within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value)
"""
global obj_ref_regex
referenced_attr = set()
for line in ... |
Find the values of the local variables within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value) | def get_local_references(tb, max_string_length=1000):
"""
Find the values of the local variables within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value)
"""
if 'self' in tb.tb_frame.f_locals:
_locals = [('self', repr(tb.tb_frame.f_local... |
Converts an object / value into a string representation to pass along in the payload
:param ref: object or value
:param max_string_length: maximum number of characters to represent the object
:return: | def format_reference(ref, max_string_length=1000):
"""
Converts an object / value into a string representation to pass along in the payload
:param ref: object or value
:param max_string_length: maximum number of characters to represent the object
:return:
"""
_pass = lambda *args: None
_... |
Extract trace back information into a list of dictionaries.
:param tb: traceback
:return: list of dicts containing filepath, line, module, code, traceback level and source code for tracebacks | def analyze_traceback(tb, inspection_level=None, limit=None):
"""
Extract trace back information into a list of dictionaries.
:param tb: traceback
:return: list of dicts containing filepath, line, module, code, traceback level and source code for tracebacks
"""
info = []
tb_level = tb
e... |
-----
Brief
-----
Function for generation of Poincaré Plot (Heart rate variability analysis).
-----------
Description
-----------
ECG signals measure the electric potential in the heart of the subject. In normal conditions, it is expeted that the
the electric potential to be similar in ... | def poincare(data, sample_rate, signal=False, in_seconds=False):
"""
-----
Brief
-----
Function for generation of Poincaré Plot (Heart rate variability analysis).
-----------
Description
-----------
ECG signals measure the electric potential in the heart of the subject. In normal co... |
-----
Brief
-----
Smooth the data using a window with requested size.
-----------
Description
-----------
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends ... | def smooth(input_signal, window_len=10, window='hanning'):
"""
-----
Brief
-----
Smooth the data using a window with requested size.
-----------
Description
-----------
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by introduc... |
-----
Brief
-----
This functions computes the Fast Fourier Transform of a signal, returning the frequency and magnitude values.
-----------
Description
-----------
Fast Fourier Transform (FFT) is a method to computationally calculate the Fourier Transform of discrete finite
signals. Thi... | def plotfft(s, fmax, doplot=False):
"""
-----
Brief
-----
This functions computes the Fast Fourier Transform of a signal, returning the frequency and magnitude values.
-----------
Description
-----------
Fast Fourier Transform (FFT) is a method to computationally calculate the Fouri... |
-----
Brief
-----
For a given signal s passes the frequencies within a certain range (between f1 and f2) and rejects (attenuates) the
frequencies outside that range by applying a Butterworth digital filter.
-----------
Description
-----------
Signals may have frequency components of mul... | def bandpass(s, f1, f2, order=2, fs=1000.0, use_filtfilt=False):
"""
-----
Brief
-----
For a given signal s passes the frequencies within a certain range (between f1 and f2) and rejects (attenuates) the
frequencies outside that range by applying a Butterworth digital filter.
-----------
... |
Log the read configs if debug is enabled. | def log_configs(self):
"""Log the read configs if debug is enabled."""
for sec in self.config.sections():
LOG.debug(' %s: %s', sec, self.config.options(sec)) |
Read some environment variables and set them on the config.
If no environment variable is found and the config section/key is
empty, then set some default values. | def set_env_or_defaults(self):
"""Read some environment variables and set them on the config.
If no environment variable is found and the config section/key is
empty, then set some default values.
"""
option = namedtuple('Option', ['section', 'name', 'env_var',
... |
Create a empty config file. | def check_sections(config):
"""Create a empty config file."""
default_sections = ['global', 'auth', 'napps', 'kytos']
for section in default_sections:
if not config.has_section(section):
config.add_section(section) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.