INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Calculates AMR and ACR using CAN - ID as parameter. | def create_filter(extended, from_id, to_id, rtr_only, rtr_too):
"""
Calculates AMR and ACR using CAN-ID as parameter.
:param bool extended:
if True parameters from_id and to_id contains 29-bit CAN-ID
:param int from_id:
first CAN-ID which should be received
... |
Shuts down all CAN interfaces and hardware interface. | def shutdown(self):
"""
Shuts down all CAN interfaces and hardware interface.
"""
try:
self._ucan.shutdown()
except Exception as ex:
log.error(ex) |
Loads configuration from file with following content:: | def load_file_config(path=None, section=None):
"""
Loads configuration from file with following content::
[default]
interface = socketcan
channel = can0
:param path:
path to config file. If not specified, several sensible
default locations are tried depending on pla... |
Loads config dict from environmental variables ( if set ): | def load_environment_config():
"""
Loads config dict from environmental variables (if set):
* CAN_INTERFACE
* CAN_CHANNEL
* CAN_BITRATE
"""
mapper = {
'interface': 'CAN_INTERFACE',
'channel': 'CAN_CHANNEL',
'bitrate': 'CAN_BITRATE',
}
return dict(
(k... |
Returns a dict with configuration details which is loaded from ( in this order ): | def load_config(path=None, config=None, context=None):
"""
Returns a dict with configuration details which is loaded from (in this order):
- config
- can.rc
- Environment variables CAN_INTERFACE, CAN_CHANNEL, CAN_BITRATE
- Config files ``/etc/can.conf`` or ``~/.can`` or ``~/.canrc``
where... |
Set the logging level for the can logger. Expects one of: critical error warning info debug subdebug | def set_logging_level(level_name=None):
"""Set the logging level for the "can" logger.
Expects one of: 'critical', 'error', 'warning', 'info', 'debug', 'subdebug'
"""
can_logger = logging.getLogger('can')
try:
can_logger.setLevel(getattr(logging, level_name.upper()))
except AttributeErr... |
Calculate the DLC from data length. | def len2dlc(length):
"""Calculate the DLC from data length.
:param int length: Length in number of bytes (0-64)
:returns: DLC (0-15)
:rtype: int
"""
if length <= 8:
return length
for dlc, nof_bytes in enumerate(CAN_FD_DLC):
if nof_bytes >= length:
return dlc
... |
Try to convert the channel to an integer. | def channel2int(channel):
"""Try to convert the channel to an integer.
:param channel:
Channel string (e.g. can0, CAN1) or integer
:returns: Channel integer or `None` if unsuccessful
:rtype: int
"""
if channel is None:
return None
if isinstance(channel, int):
re... |
Block waiting for a message from the Bus. | def recv(self, timeout=None):
"""Block waiting for a message from the Bus.
:type timeout: float or None
:param timeout:
seconds to wait for a message or None to wait indefinitely
:rtype: can.Message or None
:return:
None on timeout or a :class:`can.Messa... |
Start sending a message at a given period on this bus. | def send_periodic(self, msg, period, duration=None, store_task=True):
"""Start sending a message at a given period on this bus.
The task will be active until one of the following conditions are met:
- the (optional) duration expires
- the Bus instance goes out of scope
- the Bu... |
Default implementation of periodic message sending using threading. | def _send_periodic_internal(self, msg, period, duration=None):
"""Default implementation of periodic message sending using threading.
Override this method to enable a more efficient backend specific approach.
:param can.Message msg:
Message to transmit
:param float period:
... |
Stop sending any messages that were started using bus. send_periodic | def stop_all_periodic_tasks(self, remove_tasks=True):
"""Stop sending any messages that were started using bus.send_periodic
:param bool remove_tasks:
Stop tracking the stopped tasks.
"""
for task in self._periodic_tasks:
task.stop(remove_task=remove_tasks) |
Apply filtering to all messages received by this Bus. | def set_filters(self, filters=None):
"""Apply filtering to all messages received by this Bus.
All messages that match at least one filter are returned.
If `filters` is `None` or a zero length sequence, all
messages are matched.
Calling without passing any filters will reset the... |
Checks whether the given message matches at least one of the current filters. See: meth: ~can. BusABC. set_filters for details on how the filters work. | def _matches_filters(self, msg):
"""Checks whether the given message matches at least one of the
current filters. See :meth:`~can.BusABC.set_filters` for details
on how the filters work.
This method should not be overridden.
:param can.Message msg:
the message to ch... |
Checks if function: meth: UcanServer. read_can_msg returns a valid CAN message. | def check_valid_rx_can_msg(result):
"""
Checks if function :meth:`UcanServer.read_can_msg` returns a valid CAN message.
:param ReturnCode result: Error code of the function.
:return: True if a valid CAN messages was received, otherwise False.
:rtype: bool
"""
return (result.value == ReturnC... |
Checks if function: meth: UcanServer. write_can_msg successfully wrote CAN message ( s ). | def check_tx_ok(result):
"""
Checks if function :meth:`UcanServer.write_can_msg` successfully wrote CAN message(s).
While using :meth:`UcanServer.write_can_msg_ex` the number of sent CAN messages can be less than
the number of CAN messages which should be sent.
:param ReturnCode result: Error code... |
Checks if any function returns an error from USB - CAN - library. | def check_error(result):
"""
Checks if any function returns an error from USB-CAN-library.
:param ReturnCode result: Error code of the function.
:return: True if a function returned error, otherwise False.
:rtype: bool
"""
return (result.value != ReturnCode.SUCCESSFUL) and (result.value < R... |
Checks if any function returns an error from firmware in USB - CANmodul. | def check_error_cmd(result):
"""
Checks if any function returns an error from firmware in USB-CANmodul.
:param ReturnCode result: Error code of the function.
:return: True if a function returned error from firmware, otherwise False.
:rtype: bool
"""
return (result.value >= ReturnCode.ERRCMD... |
Initializes the device with the corresponding serial or device number. | def init_hardware(self, serial=None, device_number=ANY_MODULE):
"""
Initializes the device with the corresponding serial or device number.
:param int or None serial: Serial number of the USB-CANmodul.
:param int device_number: Device number (0 – 254, or :const:`ANY_MODULE` for the first... |
Initializes a specific CAN channel of a device. | def init_can(self, channel=Channel.CHANNEL_CH0, BTR=Baudrate.BAUD_1MBit, baudrate=BaudrateEx.BAUDEX_USE_BTR01,
AMR=AMR_ALL, ACR=ACR_ALL, mode=Mode.MODE_NORMAL, OCR=OutputControl.OCR_DEFAULT,
rx_buffer_entries=DEFAULT_BUFFER_ENTRIES, tx_buffer_entries=DEFAULT_BUFFER_ENTRIES):
""... |
Reads one or more CAN - messages from the buffer of the specified CAN channel. | def read_can_msg(self, channel, count):
"""
Reads one or more CAN-messages from the buffer of the specified CAN channel.
:param int channel:
CAN channel to read from (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1`,
:data:`Channel.CHANNEL_ANY`).
:param i... |
Transmits one ore more CAN messages through the specified CAN channel of the device. | def write_can_msg(self, channel, can_msg):
"""
Transmits one ore more CAN messages through the specified CAN channel of the device.
:param int channel:
CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param list(CanMsg) can_msg:... |
This function is used to configure the baud rate of specific CAN channel of a device. | def set_baudrate(self, channel, BTR, baudarate):
"""
This function is used to configure the baud rate of specific CAN channel of a device.
:param int channel:
CAN channel, which is to be configured (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int BTR:... |
This function is used to change the acceptance filter values for a specific CAN channel on a device. | def set_acceptance(self, channel=Channel.CHANNEL_CH0, AMR=AMR_ALL, ACR=ACR_ALL):
"""
This function is used to change the acceptance filter values for a specific CAN channel on a device.
:param int channel:
CAN channel, which is to be configured (:data:`Channel.CHANNEL_CH0` or :data:... |
Returns the error status of a specific CAN channel. | def get_status(self, channel=Channel.CHANNEL_CH0):
"""
Returns the error status of a specific CAN channel.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:return: Tuple with CAN and USB status (see structure :class:`Status`).
... |
Reads the message counters of the specified CAN channel. | def get_msg_count_info(self, channel=Channel.CHANNEL_CH0):
"""
Reads the message counters of the specified CAN channel.
:param int channel:
CAN channel, which is to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:return: Tuple with number of CAN messag... |
Resets a CAN channel of a device ( hardware reset empty buffer and so on ). | def reset_can(self, channel=Channel.CHANNEL_CH0, flags=ResetFlags.RESET_ALL):
"""
Resets a CAN channel of a device (hardware reset, empty buffer, and so on).
:param int channel: CAN channel, to be reset (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int flags: Flag... |
Returns the extended hardware information of a device. With multi - channel USB - CANmoduls the information for both CAN channels are returned separately. | def get_hardware_info(self):
"""
Returns the extended hardware information of a device. With multi-channel USB-CANmoduls the information for
both CAN channels are returned separately.
:return:
Tuple with extended hardware information structure (see structure :class:`Hardware... |
Defines a list of CAN messages for automatic transmission. | def define_cyclic_can_msg(self, channel, can_msg=None):
"""
Defines a list of CAN messages for automatic transmission.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param list(CanMsg) can_msg:
List of CAN messages ... |
Reads back the list of CAN messages for automatically sending. | def read_cyclic_can_msg(self, channel, count):
"""
Reads back the list of CAN messages for automatically sending.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int count: The number of cyclic CAN messages to be received.... |
Returns the number of pending CAN messages. | def get_msg_pending(self, channel, flags):
"""
Returns the number of pending CAN messages.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int flags: Flags specifies which buffers should be checked (see enum :class:`Pendin... |
Reads the current value of the error counters within the CAN controller. | def get_can_error_counter(self, channel):
"""
Reads the current value of the error counters within the CAN controller.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:return: Tuple with the TX and RX error counter.
:rtyp... |
Sets the transmission timeout. | def set_tx_timeout(self, channel, timeout):
"""
Sets the transmission timeout.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param float timeout: Transmit timeout in seconds (value 0 disables this feature).
"""
... |
Shuts down all CAN interfaces and/ or the hardware interface. | def shutdown(self, channel=Channel.CHANNEL_ALL, shutdown_hardware=True):
"""
Shuts down all CAN interfaces and/or the hardware interface.
:param int channel:
CAN channel, to be used (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1` or
:data:`Channel.CHANNEL_ALL`)... |
Converts a given CAN status value to the appropriate message string. | def get_can_status_message(can_status):
"""
Converts a given CAN status value to the appropriate message string.
:param can_status: CAN status value from method :meth:`get_status` (see enum :class:`CanStatus`)
:return: Status message string.
:rtype: str
"""
statu... |
Converts a given baud rate value for GW - 001/ GW - 002 to the appropriate message string. | def get_baudrate_message(baudrate):
"""
Converts a given baud rate value for GW-001/GW-002 to the appropriate message string.
:param Baudrate baudrate:
Bus Timing Registers, BTR0 in high order byte and BTR1 in low order byte
(see enum :class:`Baudrate`)
:return: ... |
Converts a given baud rate value for systec USB - CANmoduls to the appropriate message string. | def get_baudrate_ex_message(baudrate_ex):
"""
Converts a given baud rate value for systec USB-CANmoduls to the appropriate message string.
:param BaudrateEx baudrate_ex: Bus Timing Registers (see enum :class:`BaudrateEx`)
:return: Baud rate message string.
:rtype: str
""... |
Checks if the version is equal or higher than a specified value. | def check_version_is_equal_or_higher(cls, version, cmp_major, cmp_minor):
"""
Checks if the version is equal or higher than a specified value.
:param int version: Version number to be checked.
:param int cmp_major: Major version to be compared with.
:param int cmp_minor: Minor v... |
Checks whether the module supports automatically transmission of cyclic CAN messages. | def check_support_cyclic_msg(cls, hw_info_ex):
"""
Checks whether the module supports automatically transmission of cyclic CAN messages.
:param HardwareInfoEx hw_info_ex:
Extended hardware information structure (see method :meth:`get_hardware_info`).
:return: True when the m... |
Checks whether the module supports a user I/ O port. | def check_support_user_port(cls, hw_info_ex):
"""
Checks whether the module supports a user I/O port.
:param HardwareInfoEx hw_info_ex:
Extended hardware information structure (see method :meth:`get_hardware_info`).
:return: True when the module supports a user I/O port, oth... |
Checks whether the module supports the usage of USB - CANnetwork driver. | def check_support_ucannet(cls, hw_info_ex):
"""
Checks whether the module supports the usage of USB-CANnetwork driver.
:param HardwareInfoEx hw_info_ex:
Extended hardware information structure (see method :meth:`get_hardware_info`).
:return: True when the module does support... |
Calculates AMR using CAN - ID range as parameter. | def calculate_amr(cls, is_extended, from_id, to_id, rtr_only=False, rtr_too=True):
"""
Calculates AMR using CAN-ID range as parameter.
:param bool is_extended: If True parameters from_id and to_id contains 29-bit CAN-ID.
:param int from_id: First CAN-ID which should be received.
... |
Is the actual callback function for: meth: init_hw_connect_control_ex. | def _connect_control(self, event, param, arg):
"""
Is the actual callback function for :meth:`init_hw_connect_control_ex`.
:param event:
Event (:data:`CbEvent.EVENT_CONNECT`, :data:`CbEvent.EVENT_DISCONNECT` or
:data:`CbEvent.EVENT_FATALDISCON`).
:param param: Ad... |
Is called if a working event occurred. | def _callback(self, handle, event, channel, arg):
"""
Is called if a working event occurred.
:param int handle: USB-CAN-Handle returned by the function :meth:`init_hardware`.
:param int event: Event type.
:param int channel:
CAN channel (:data:`Channel.CHANNEL_CH0`, ... |
Colors API using schema This example is using marshmallow schemas | def get(self, palette):
"""
Colors API using schema
This example is using marshmallow schemas
"""
all_colors = {
'cmyk': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
if palette == 'all':
result = all... |
Custom validation function which drops parameter _id if present in data | def drop_id_validate(data, schema):
"""
Custom validation function which drops parameter '_id' if present
in data
"""
jsonschema.validate(data, schema)
if data.get('_id') is not None:
del data['_id'] |
Custom validation function which inserts a timestamp for when the validation occurred | def timestamping_validate(data, schema):
"""
Custom validation function which inserts a timestamp for when the
validation occurred
"""
jsonschema.validate(data, schema)
data['timestamp'] = str(time.time()) |
Custom validation function which inserts an special flag depending on the cat s name | def special_validate(data, schema):
"""
Custom validation function which inserts an special flag depending
on the cat's name
"""
jsonschema.validate(data, schema)
data['special'] = str(data['name'] == 'Garfield').lower() |
Custom validation error handler which produces 404 Bad Request response in case validation fails and returns the error | def validation_error_inform_error(err, data, schema):
"""
Custom validation error handler which produces 404 Bad Request
response in case validation fails and returns the error
"""
abort(Response(
json.dumps({'error': str(err), 'data': data, 'schema': schema}),
status=HTTPStatus.BAD_... |
Custom validation error handler which attempts alternative validation | def validation_error_try_to_accept(err, data, schema):
"""
Custom validation error handler which attempts alternative
validation
"""
if not isinstance(err, ValidationError):
abort(Response(err, status=HTTPStatus.BAD_REQUEST))
alernative_schema = dict(schema)
alernative_schema['prope... |
Convert Marshmallow schemas to dict definitions | def convert_schemas(d, definitions=None):
"""
Convert Marshmallow schemas to dict definitions
Also updates the optional definitions argument with any definitions
entries contained within the schema.
"""
if Schema is None:
raise RuntimeError('Please install marshmallow and apispec')
... |
Converts APISpec dict to flasgger suitable dict also adds definitions and paths ( optional ) | def to_flasgger(self, app=None, definitions=None, paths=None):
"""
Converts APISpec dict to flasgger suitable dict
also adds definitions and paths (optional)
"""
if Schema is None:
raise RuntimeError('Please install marshmallow and apispec')
return flasgger.u... |
If validation = True perform validation | def dispatch_request(self, *args, **kwargs):
"""
If validation=True perform validation
"""
if self.validation:
specs = {}
attrs = flasgger.constants.OPTIONAL_FIELDS + [
'parameters', 'definitions', 'responses',
'summary', 'descripti... |
Update target dictionary with values from the source recursively. List items will be merged. | def merge_specs(target, source):
"""
Update target dictionary with values from the source, recursively.
List items will be merged.
"""
for key, value in source.items():
if isinstance(value, dict):
node = target.setdefault(key, {})
merge_specs(node, value)
eli... |
Takes a filename. yml a dictionary or object and loads swagger specs. | def swag_from(
specs=None, filetype=None, endpoint=None, methods=None,
validation=False, schema_id=None, data=None, definition=None,
validation_function=None, validation_error_handler=None):
"""
Takes a filename.yml, a dictionary or object and loads swagger specs.
:param specs: a fi... |
This method is available to use YAML swagger definitions file or specs ( dict or object ) to validate data against its jsonschema. | def validate(
data=None, schema_id=None, filepath=None, root=None, definition=None,
specs=None, validation_function=None, validation_error_handler=None):
"""
This method is available to use YAML swagger definitions file
or specs (dict or object) to validate data against its jsonschema.
... |
Converts apispec object in to flasgger definitions template: param app: Current app: param spec: apispec. APISpec: param definitions: a list of [ Schema.. ] or [ ( Name Schema ).. ]: param paths: A list of flask views | def apispec_to_template(app, spec, definitions=None, paths=None):
"""
Converts apispec object in to flasgger definitions template
:param app: Current app
:param spec: apispec.APISpec
:param definitions: a list of [Schema, ..] or [('Name', Schema), ..]
:param paths: A list of flask views
"""
... |
Converts inner OrderedDict to bare dict | def ordered_dict_to_dict(d):
"""
Converts inner OrderedDict to bare dict
"""
ret = {}
new_d = deepcopy(d)
for k, v in new_d.items():
if isinstance(v, OrderedDict):
v = dict(v)
if isinstance(v, dict):
v = ordered_dict_to_dict(v)
ret[k] = v
retur... |
* nix to python module path | def pathify(basenames, examples_dir="examples/"): # pragma: no cover
"""*nix to python module path"""
example = examples_dir.replace("/", ".")
return [example + basename for basename in basenames] |
All example modules | def get_examples(examples_dir="examples/"): # pragma: no cover
"""All example modules"""
all_files = os.listdir(examples_dir)
python_files = [f for f in all_files if is_python_file(f)]
basenames = [remove_suffix(f) for f in python_files]
modules = [import_module(module) for module in pathify(basena... |
If file: is provided import the file. | def get_path_from_doc(full_doc):
"""
If `file:` is provided import the file.
"""
swag_path = full_doc.replace('file:', '').strip()
swag_type = swag_path.split('.')[-1]
return swag_path, swag_type |
Load specs from YAML file | def load_from_file(swag_path, swag_type='yml', root_path=None):
"""
Load specs from YAML file
"""
if swag_type not in ('yaml', 'yml'):
raise AttributeError("Currently only yaml or yml supported")
# TODO: support JSON
try:
enc = detect_by_bom(swag_path)
with codecs.op... |
Gets swag data for method/ view docstring | def parse_docstring(obj, process_doc, endpoint=None, verb=None):
"""
Gets swag data for method/view docstring
"""
first_line, other_lines, swag = None, None, None
full_doc = None
swag_path = getattr(obj, 'swag_path', None)
swag_type = getattr(obj, 'swag_type', 'yml')
swag_paths = getatt... |
Get file path for object and returns its dirname | def get_root_path(obj):
"""
Get file path for object and returns its dirname
"""
try:
filename = os.path.abspath(obj.__globals__['__file__'])
except (KeyError, AttributeError):
if getattr(obj, '__wrapped__', None):
# decorator package has been used in view
ret... |
Gets swag data from docstring for class based definitions | def parse_definition_docstring(obj, process_doc):
"""
Gets swag data from docstring for class based definitions
"""
doc_lines, swag = None, None
full_doc = None
swag_path = getattr(obj, 'swag_path', None)
swag_type = getattr(obj, 'swag_type', 'yml')
if swag_path is not None:
fu... |
Supports import: otherfile. yml in docstring specs | def parse_imports(full_doc, root_path=None):
"""
Supports `import: otherfile.yml` in docstring specs
"""
regex = re.compile('import: "(.*)"')
import_prop = regex.search(full_doc)
if import_prop:
start = import_prop.start()
spaces_num = start - full_doc.rfind('\n', 0, start) - 1
... |
Since we couldn t be bothered to register models elsewhere our definitions need to be extracted from the parameters. We require an id field for the schema to be correctly added to the definitions list. | def extract_definitions(alist, level=None, endpoint=None, verb=None,
prefix_ids=False):
"""
Since we couldn't be bothered to register models elsewhere
our definitions need to be extracted from the parameters.
We require an 'id' field for the schema to be correctly
added to th... |
Return True if dispatch_request is swaggable | def has_valid_dispatch_view_docs(endpoint):
"""
Return True if dispatch_request is swaggable
"""
klass = endpoint.__dict__.get('view_class', None)
return klass and hasattr(klass, 'dispatch_request') \
and hasattr(endpoint, 'methods') \
and getattr(klass, 'dispatch_request').__doc__ |
Return True if obj is MethodView | def is_valid_method_view(endpoint):
"""
Return True if obj is MethodView
"""
klass = endpoint.__dict__.get('view_class', None)
try:
return issubclass(klass, MethodView)
except TypeError:
return False |
Identify vendor extension fields and extract them into a new dictionary. Examples: >>> get_vendor_extension_fields ( { test: 1 } ) {} >>> get_vendor_extension_fields ( { test: 1 x - test: 2 } ) { x - test: 2 } | def get_vendor_extension_fields(mapping):
"""
Identify vendor extension fields and extract them into a new dictionary.
Examples:
>>> get_vendor_extension_fields({'test': 1})
{}
>>> get_vendor_extension_fields({'test': 1, 'x-test': 2})
{'x-test': 2}
"""
return {k: v fo... |
User authenticate method. --- description: Authenticate user with supplied credentials. parameters: - name: username in: formData type: string required: true - name: password in: formData type: string required: true responses: 200: description: User successfully logged in. 400: description: User login failed. | def login():
"""
User authenticate method.
---
description: Authenticate user with supplied credentials.
parameters:
- name: username
in: formData
type: string
required: true
- name: password
in: formData
type: string
required: true
res... |
The data under/ apidocs json or Swagger UI | def get(self):
"""
The data under /apidocs
json or Swagger UI
"""
base_endpoint = self.config.get('endpoint', 'flasgger')
specs = [
{
"url": url_for(".".join((base_endpoint, spec['endpoint']))),
"title": spec.get('title', 'API S... |
Initialize the app with Swagger plugin | def init_app(self, app, decorators=None):
"""
Initialize the app with Swagger plugin
"""
self.decorators = decorators or self.decorators
self.app = app
self.load_config(app)
# self.load_apispec(app)
if self.template_file is not None:
self.temp... |
Returns all werkzeug rules | def get_url_mappings(self, rule_filter=None):
"""
Returns all werkzeug rules
"""
rule_filter = rule_filter or (lambda rule: True)
app_rules = [
rule for rule in current_app.url_map.iter_rules()
if rule_filter(rule)
]
return app_rules |
Used for class based definitions | def get_def_models(self, definition_filter=None):
"""
Used for class based definitions
"""
model_filter = definition_filter or (lambda tag: True)
return {
definition.name: definition.obj
for definition in self.definition_models
if model_filter(... |
Decorator to add class based definitions | def definition(self, name, tags=None):
"""
Decorator to add class based definitions
"""
def wrapper(obj):
self.definition_models.append(SwaggerDefinition(name, obj,
tags=tags))
return obj
return w... |
Register Flasgger views | def register_views(self, app):
"""
Register Flasgger views
"""
# Wrap the views in an arbitrary number of decorators.
def wrap_view(view):
if self.decorators:
for decorator in self.decorators:
view = decorator(view)
ret... |
Inject headers after request | def add_headers(self, app):
"""
Inject headers after request
"""
@app.after_request
def after_request(response): # noqa
for header, value in self.config.get('headers'):
response.headers[header] = value
return response |
A decorator that is used to validate incoming requests data against a schema | def validate(
self, schema_id, validation_function=None,
validation_error_handler=None):
"""
A decorator that is used to validate incoming requests data
against a schema
swagger = Swagger(app)
@app.route('/pets', methods=['POST'])
@sw... |
This method finds a schema known to Flasgger and returns it. | def get_schema(self, schema_id):
"""
This method finds a schema known to Flasgger and returns it.
:raise KeyError: when the specified :param schema_id: is not
found by Flasgger
:param schema_id: the id of the desired schema
"""
schema_specs = get_schema_specs(sc... |
This is an example --- tags: - restful parameters: - in: body name: body schema: $ref: #/ definitions/ Task - in: path name: todo_id required: true description: The ID of the task try 42! type: string responses: 201: description: The task has been updated schema: $ref: #/ definitions/ Task | def put(self, todo_id):
"""
This is an example
---
tags:
- restful
parameters:
- in: body
name: body
schema:
$ref: '#/definitions/Task'
- in: path
name: todo_id
required: true
... |
This is an example --- tags: - restful parameters: - in: body name: body schema: $ref: #/ definitions/ Task responses: 201: description: The task has been created schema: $ref: #/ definitions/ Task | def post(self):
"""
This is an example
---
tags:
- restful
parameters:
- in: body
name: body
schema:
$ref: '#/definitions/Task'
responses:
201:
description: The task has been created
... |
Example endpoint return a list of colors by palette This is using docstring for specifications --- tags: - colors parameters: - name: palette in: path type: string enum: [ all rgb cmyk ] required: true default: all description: Which palette to filter? operationId: get_colors consumes: - application/ json produces: - a... | def colors(palette):
"""Example endpoint return a list of colors by palette
This is using docstring for specifications
---
tags:
- colors
parameters:
- name: palette
in: path
type: string
enum: ['all', 'rgb', 'cmyk']
required: true
default: all
... |
Decorator to require HTTP Basic Auth for your endpoint. | def requires_basic_auth(f):
"""Decorator to require HTTP Basic Auth for your endpoint."""
def check_auth(username, password):
return username == "guest" and password == "secret"
def authenticate():
return Response(
"Authentication required.", 401,
{"WWW-Authenticate... |
Scales the image to a given scale.: param image:: param scale:: return: | def __scale_image(image, scale: float):
"""
Scales the image to a given scale.
:param image:
:param scale:
:return:
"""
height, width, _ = image.shape
width_scaled = int(np.ceil(width * scale))
height_scaled = int(np.ceil(height * scale))
... |
Non Maximum Suppression. | def __nms(boxes, threshold, method):
"""
Non Maximum Suppression.
:param boxes: np array with bounding boxes.
:param threshold:
:param method: NMS method to apply. Available values ('Min', 'Union')
:return:
"""
if boxes.size == 0:
return np.em... |
Detects bounding boxes from the specified image.: param img: image to process: return: list containing all the bounding boxes detected with their keypoints. | def detect_faces(self, img) -> list:
"""
Detects bounding boxes from the specified image.
:param img: image to process
:return: list containing all the bounding boxes detected with their keypoints.
"""
if img is None or not hasattr(img, "shape"):
raise Invalid... |
First stage of the MTCNN.: param image:: param scales:: param stage_status:: return: | def __stage1(self, image, scales: list, stage_status: StageStatus):
"""
First stage of the MTCNN.
:param image:
:param scales:
:param stage_status:
:return:
"""
total_boxes = np.empty((0, 9))
status = stage_status
for scale in scales:
... |
Second stage of the MTCNN.: param img:: param total_boxes:: param stage_status:: return: | def __stage2(self, img, total_boxes, stage_status:StageStatus):
"""
Second stage of the MTCNN.
:param img:
:param total_boxes:
:param stage_status:
:return:
"""
num_boxes = total_boxes.shape[0]
if num_boxes == 0:
return total_boxes, st... |
Third stage of the MTCNN. | def __stage3(self, img, total_boxes, stage_status: StageStatus):
"""
Third stage of the MTCNN.
:param img:
:param total_boxes:
:param stage_status:
:return:
"""
num_boxes = total_boxes.shape[0]
if num_boxes == 0:
return total_boxes, np... |
Creates a tensorflow variable with the given name and shape.: param name: name to set for the variable.: param shape: list defining the shape of the variable.: return: created TF variable. | def __make_var(self, name: str, shape: list):
"""
Creates a tensorflow variable with the given name and shape.
:param name: name to set for the variable.
:param shape: list defining the shape of the variable.
:return: created TF variable.
"""
return tf.get_variabl... |
Creates a feed layer. This is usually the first layer in the network.: param name: name of the layer: return: | def new_feed(self, name: str, layer_shape: tuple):
"""
Creates a feed layer. This is usually the first layer in the network.
:param name: name of the layer
:return:
"""
feed_data = tf.placeholder(tf.float32, layer_shape, 'input')
self.__network.add_layer(name, la... |
Creates a convolution layer for the network.: param name: name for the layer: param kernel_size: tuple containing the size of the kernel ( Width Height ): param channels_output: ¿? Perhaps number of channels in the output? it is used as the bias size.: param stride_size: tuple containing the size of the stride ( Width ... | def new_conv(self, name: str, kernel_size: tuple, channels_output: int,
stride_size: tuple, padding: str='SAME',
group: int=1, biased: bool=True, relu: bool=True, input_layer_name: str=None):
"""
Creates a convolution layer for the network.
:param name: name for... |
Creates a new prelu layer with the given name and input.: param name: name for this layer.: param input_layer_name: name of the layer that serves as input for this one. | def new_prelu(self, name: str, input_layer_name: str=None):
"""
Creates a new prelu layer with the given name and input.
:param name: name for this layer.
:param input_layer_name: name of the layer that serves as input for this one.
"""
input_layer = self.__network.get_la... |
Creates a new max pooling layer.: param name: name for the layer.: param kernel_size: tuple containing the size of the kernel ( Width Height ): param stride_size: tuple containing the size of the stride ( Width Height ): param padding: Type of padding. Available values are: ( SAME VALID ): param input_layer_name: name ... | def new_max_pool(self, name:str, kernel_size: tuple, stride_size: tuple, padding='SAME',
input_layer_name: str=None):
"""
Creates a new max pooling layer.
:param name: name for the layer.
:param kernel_size: tuple containing the size of the kernel (Width, Height)
... |
Creates a new fully connected layer. | def new_fully_connected(self, name: str, output_count: int, relu=True, input_layer_name: str=None):
"""
Creates a new fully connected layer.
:param name: name for the layer.
:param output_count: number of outputs of the fully connected layer.
:param relu: boolean flag to set if ... |
Creates a new softmax layer: param name: name to set for the layer: param axis:: param input_layer_name: name of the input layer for this layer. If None it will take the last added layer of the network. | def new_softmax(self, name, axis, input_layer_name: str=None):
"""
Creates a new softmax layer
:param name: name to set for the layer
:param axis:
:param input_layer_name: name of the input layer for this layer. If None, it will take the last added layer of
the network.
... |
Adds a layer to the network.: param name: name of the layer to add: param layer_output: output layer. | def add_layer(self, name: str, layer_output):
"""
Adds a layer to the network.
:param name: name of the layer to add
:param layer_output: output layer.
"""
self.__layers[name] = layer_output
self.__last_layer_name = name |
Retrieves the layer by its name.: param name: name of the layer to retrieve. If name is None it will retrieve the last added layer to the network.: return: layer output | def get_layer(self, name: str=None):
"""
Retrieves the layer by its name.
:param name: name of the layer to retrieve. If name is None, it will retrieve the last added layer to the
network.
:return: layer output
"""
if name is None:
name = self.__last_l... |
Sets the weights values of the network.: param weights_values: dictionary with weights for each layer | def set_weights(self, weights_values: dict, ignore_missing=False):
"""
Sets the weights values of the network.
:param weights_values: dictionary with weights for each layer
"""
network_name = self.__class__.__name__.lower()
with tf.variable_scope(network_name):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.