text stringlengths 81 112k |
|---|
Return sensor value based on sensor_uri.
def read_sensor(self, device_id, sensor_uri):
"""Return sensor value based on sensor_uri."""
url = MINUT_DEVICES_URL + "/{device_id}/{sensor_uri}".format(
device_id=device_id, sensor_uri=sensor_uri)
res = self._request(url, request_type='GET'... |
Register webhook.
def _register_webhook(self, webhook_url, events):
"""Register webhook."""
response = self._request(
MINUT_WEBHOOKS_URL,
request_type='POST',
json={
'url': webhook_url,
'events': events,
},
)
... |
Remove webhook.
def remove_webhook(self):
"""Remove webhook."""
if self._webhook.get('hook_id'):
self._request(
"{}/{}".format(MINUT_WEBHOOKS_URL, self._webhook['hook_id']),
request_type='DELETE',
) |
Register webhook (if it doesn't exit).
def update_webhook(self, webhook_url, webhook_id, events=None):
"""Register webhook (if it doesn't exit)."""
hooks = self._request(MINUT_WEBHOOKS_URL, request_type='GET')['hooks']
try:
self._webhook = next(
hook for hook in hook... |
Update all devices from server.
def update(self):
"""Update all devices from server."""
with self._lock:
devices = self._request_devices(MINUT_DEVICES_URL, 'devices')
if devices:
self._state = {
device['device_id']: device
... |
Set alarm satus.
def _set_alarm(self, status, home_id):
"""Set alarm satus."""
response = self._request(
MINUT_HOMES_URL + "/{}".format(home_id),
request_type='PUT',
json={'alarm_status': status})
return response.get('alarm_status', '') == status |
Update and return sensor value.
def sensor(self, sensor_type):
"""Update and return sensor value."""
_LOGGER.debug("Reading %s sensor.", sensor_type)
return self._session.read_sensor(self.device_id, sensor_type) |
Info about device.
def device_info(self):
"""Info about device."""
return {
'connections': {('mac', self.device['device_mac'])},
'identifieres': self.device['device_id'],
'manufacturer': 'Minut',
'model': 'Point v{}'.format(self.device['hardware_version']... |
Status of device.
def device_status(self):
"""Status of device."""
return {
'active': self.device['active'],
'offline': self.device['offline'],
'last_update': self.last_update,
'battery_level': self.battery_level,
} |
Template tag which renders the glitter CSS and JavaScript. Any resources
which need to be loaded should be added here. This is only shown to users
with permission to edit the page.
def glitter_head(context):
"""
Template tag which renders the glitter CSS and JavaScript. Any resources
which need to ... |
Template tag which renders the glitter overlay and sidebar. This is only
shown to users with permission to edit the page.
def glitter_startbody(context):
"""
Template tag which renders the glitter overlay and sidebar. This is only
shown to users with permission to edit the page.
"""
user = cont... |
Replace all special characters found in assertion_value
by quoted notation.
escape_mode
If 0 only special chars mentioned in RFC 4515 are escaped.
If 1 all NON-ASCII chars are escaped.
If 2 all chars are escaped.
def escape_filter_chars(assertion_value, escape_mode=0):
"""
Repl... |
filter_template
String containing %s as placeholder for assertion values.
assertion_values
List or tuple of assertion values. Length must match
count of %s in filter_template.
def filter_format(filter_template, assertion_values):
"""
filter_template
String containing... |
Args:
checker_cls: Class performing the check to be passed back to
flake8.
def to_flake8(self, checker_cls: type) -> Flake8Error:
"""
Args:
checker_cls: Class performing the check to be passed back to
flake8.
"""
return Flake8Error... |
:param chassis: chassis object
def add_chassis(self, chassis):
"""
:param chassis: chassis object
"""
res = self._request(RestMethod.post, self.user_url, params={'ip': chassis.ip, 'port': chassis.port})
assert(res.status_code == 201) |
Send command with no output.
:param obj: requested object.
:param command: command to send.
:param arguments: list of command arguments.
def send_command(self, obj, command, *arguments):
""" Send command with no output.
:param obj: requested object.
:param command: com... |
Send command with single line output.
:param obj: requested object.
:param command: command to send.
:param arguments: list of command arguments.
:return: command output.
def send_command_return(self, obj, command, *arguments):
""" Send command with single line output.
... |
Send command with no output.
:param obj: requested object.
:param command: command to send.
:param arguments: list of command arguments.
:return: list of command output lines.
:rtype: list(str)
def send_command_return_multilines(self, obj, command, *arguments):
""" Send... |
Get all object's attributes.
Sends multi-parameter info/config queries and returns the result as dictionary.
:param obj: requested object.
:returns: dictionary of <name, value> of all attributes returned by the query.
:rtype: dict of (str, str)
def get_attributes(self, obj):
"... |
Set attributes.
:param obj: requested object.
:param attributes: dictionary of {attribute: value} to set
def set_attributes(self, obj, **attributes):
""" Set attributes.
:param obj: requested object.
:param attributes: dictionary of {attribute: value} to set
"""
... |
Send CLI command that returns list of integer counters.
:param obj: requested object.
:param stat_name: statistics command name.
:return: list of counters.
:rtype: list(int)
def get_stats(self, obj, stat_name):
""" Send CLI command that returns list of integer counters.
... |
Initialize common service,
When 'zone_name' is defined " at $zone_name" is added to service names
:param bool with_cloud_account:
:param str zone_name:
:return: OR tuple(Workflow, Vault), OR tuple(Workflow, Vault, CloudAccount) with services
def init_common_services(self, with_cloud_acc... |
:param name: new env name
:rtype: Environment
def clone(self, name=None):
"""
:param name: new env name
:rtype: Environment
"""
resp = self._router.post_env_clone(env_id=self.environmentId, json=dict(name=name) if name else {}).json()
return Environment(self.orga... |
Returns environment marked as default.
When Zone is set marked default makes no sense, special env with proper Zone is returned.
def default(self):
"""
Returns environment marked as default.
When Zone is set marked default makes no sense, special env with proper Zone is retu... |
Builds a mapping of class paths to URLs.
def build_urls(self: NodeVisitor, node: inheritance_diagram) -> Mapping[str, str]:
"""
Builds a mapping of class paths to URLs.
"""
current_filename = self.builder.current_docname + self.builder.out_suffix
urls = {}
for child in node:
# Another d... |
Builds HTML output from an :py:class:`~uqbar.sphinx.inheritance.inheritance_diagram` node.
def html_visit_inheritance_diagram(
self: NodeVisitor, node: inheritance_diagram
) -> None:
"""
Builds HTML output from an :py:class:`~uqbar.sphinx.inheritance.inheritance_diagram` node.
"""
inheritance_graph... |
Builds LaTeX output from an :py:class:`~uqbar.sphinx.inheritance.inheritance_diagram` node.
def latex_visit_inheritance_diagram(
self: NodeVisitor, node: inheritance_diagram
) -> None:
"""
Builds LaTeX output from an :py:class:`~uqbar.sphinx.inheritance.inheritance_diagram` node.
"""
inheritance_gr... |
Sets up Sphinx extension.
def setup(app) -> Dict[str, Any]:
"""
Sets up Sphinx extension.
"""
app.setup_extension("sphinx.ext.graphviz")
app.add_node(
inheritance_diagram,
html=(html_visit_inheritance_diagram, None),
latex=(latex_visit_inheritance_diagram, None),
man... |
Run the daemon and all its services
def run(configuration: str, level: str, target: str, short_format: bool):
"""Run the daemon and all its services"""
initialise_logging(level=level, target=target, short_format=short_format)
logger = logging.getLogger(__package__)
logger.info('COBalD %s', cobald.__abo... |
Run the daemon from a command line interface
def cli_run():
"""Run the daemon from a command line interface"""
options = CLI.parse_args()
run(options.CONFIGURATION, options.log_level, options.log_target, options.log_journal) |
Note:
Return type is probably ``-> List[AN]``, but can't get it to pass.
def build_body(cls: Type[AN], body: List[ast.stmt]) -> List:
"""
Note:
Return type is probably ``-> List[AN]``, but can't get it to pass.
"""
act_nodes = [] # type: List[ActNode]
fo... |
Starting at this ``node``, check if it's an act node. If it's a context
manager, recurse into child nodes.
Returns:
List of all act nodes found.
def build(cls: Type[AN], node: ast.stmt) -> List[AN]:
"""
Starting at this ``node``, check if it's an act node. If it's a context... |
Checks if organization properly created.
Note: New organization must have 'default' environment and two default services
running there. Cannot use DEFAULT_ENV_NAME, because zone could be added there.
:rtype: bool
def ready(self):
"""
Checks if organization properly created.
... |
Creates application and returns Application object.
def create_application(self, name=None, manifest=None):
""" Creates application and returns Application object.
"""
if not manifest:
raise exceptions.NotEnoughParams('Manifest not set')
if not name:
name = 'auto... |
Get application object by name or id.
def get_application(self, id=None, name=None):
""" Get application object by name or id.
"""
log.info("Picking application: %s (%s)" % (name, id))
return self.applications[id or name] |
Get application by id or name.
If not found: create with given or generated parameters
def get_or_create_application(self, id=None, manifest=None, name=None):
""" Get application by id or name.
If not found: create with given or generated parameters
"""
if id:
return... |
Smart method. Creates, picks or modifies application.
If application found by name or id and manifest not changed: return app.
If app found by id, but other parameters differs: change them.
If no application found, create.
def application(self, id=None, manifest=None, name=None):
""" Sm... |
Launches instance in application and returns Instance object.
def create_instance(self, application, revision=None, environment=None, name=None, parameters=None, submodules=None,
destroyInterval=None, manifestVersion=None):
""" Launches instance in application and returns Instance objec... |
Get instance object by name or id.
If application set, search within the application.
def get_instance(self, id=None, name=None):
""" Get instance object by name or id.
If application set, search within the application.
"""
log.info("Picking instance: %s (%s)" % (name, id))
... |
Get list of instances in json format converted to list
def list_instances_json(self, application=None, show_only_destroyed=False):
""" Get list of instances in json format converted to list"""
# todo: application should not be parameter here. Application should do its own list, just in sake of code reu... |
Get instance by id or name.
If not found: create with given parameters
def get_or_create_instance(self, id=None, application=None, revision=None, environment=None, name=None, parameters=None, submodules=None,
destroyInterval=None):
""" Get instance by id or name.
... |
Smart method. It does everything, to return Instance with given parameters within the application.
If instance found running and given parameters are actual: return it.
If instance found, but parameters differs - reconfigure instance with new parameters.
If instance not found: launch instance wi... |
Creates environment and returns Environment object.
def create_environment(self, name, default=False, zone=None):
""" Creates environment and returns Environment object.
"""
from qubell.api.private.environment import Environment
return Environment.new(organization=self, name=name, zone_... |
Get environment object by name or id.
def get_environment(self, id=None, name=None):
""" Get environment object by name or id.
"""
log.info("Picking environment: %s (%s)" % (name, id))
return self.environments[id or name] |
Get environment by id or name.
If not found: create with given or generated parameters
def get_or_create_environment(self, id=None, name=None, zone=None, default=False):
""" Get environment by id or name.
If not found: create with given or generated parameters
"""
if id:
... |
Smart method. Creates, picks or modifies environment.
If environment found by name or id parameters not changed: return env.
If env found by id, but other parameters differs: change them.
If no environment found, create with given parameters.
def environment(self, id=None, name=None, zone=None,... |
Get zone object by name or id.
def get_zone(self, id=None, name=None):
""" Get zone object by name or id.
"""
log.info("Picking zone: %s (%s)" % (name, id))
return self.zones[id or name] |
Creates role
def create_role(self, name=None, permissions=""):
""" Creates role """
name = name or "autocreated-role"
from qubell.api.private.role import Role
return Role.new(self._router, organization=self, name=name, permissions=permissions) |
Get role object by name or id.
def get_role(self, id=None, name=None):
""" Get role object by name or id.
"""
log.info("Picking role: %s (%s)" % (name, id))
return self.roles[id or name] |
Get user object by email or id.
def get_user(self, id=None, name=None, email=None):
""" Get user object by email or id.
"""
log.info("Picking user: %s (%s) (%s)" % (name, email, id))
from qubell.api.private.user import User
if email:
user = User.get(self._router, org... |
Send invitation to email with a list of roles
:param email:
:param roles: None or "ALL" or list of role_names
:return:
def invite(self, email, roles=None):
"""
Send invitation to email with a list of roles
:param email:
:param roles: None or "ALL" or list of role... |
Mimics wizard's environment preparation
def init(self, access_key=None, secret_key=None):
"""
Mimics wizard's environment preparation
"""
if not access_key and not secret_key:
self._router.post_init(org_id=self.organizationId, data='{"initCloudAccount": true}')
else:... |
Parses meta and update or create each application
:param str metadata: path or url to meta.yml
:param list[str] exclude: List of application names, to exclude from meta.
This might be need when you use meta as list of dependencies
def set_applications_from_meta(self, m... |
Mimics get starter-kit and wizard functionality to create components
Note: may create component duplicates, not idempotent
:type metadata: str
:type category: Category
:param metadata: url to meta.yml
:param category: category
def upload_applications(self, metadata, category=Non... |
Commits and leaves transaction management.
def process_response(self, request, response):
"""Commits and leaves transaction management."""
if tldap.transaction.is_managed():
tldap.transaction.commit()
tldap.transaction.leave_transaction_management()
return response |
Format a report as per InfluxDB line protocol
:param name: name of the report
:param tags: tags identifying the specific report
:param fields: measurements of the report
:param timestamp: when the measurement was taken, in **seconds** since the epoch
def line_protocol(name, tags: dict = None, fields: ... |
This gets display on the block header.
def block_type(self):
""" This gets display on the block header. """
return capfirst(force_text(
self.content_block.content_type.model_class()._meta.verbose_name
)) |
Return a list of column default block tuples (URL, verbose name).
Used for quick add block buttons.
def get_default_blocks(self, top=False):
"""
Return a list of column default block tuples (URL, verbose name).
Used for quick add block buttons.
"""
default_blocks = []
... |
Return a select widget for blocks which can be added to this column.
def add_block_widget(self, top=False):
"""
Return a select widget for blocks which can be added to this column.
"""
widget = AddBlockSelect(attrs={
'class': 'glitter-add-block-select',
}, choices=se... |
Return a list of URLs and titles for blocks which can be added to this column.
All available blocks are grouped by block category.
def add_block_options(self, top):
"""
Return a list of URLs and titles for blocks which can be added to this column.
All available blocks are grouped by b... |
Return a list of default block tuples (appname.ModelName, verbose name).
Next to the dropdown list of block types, a small number of common blocks which are
frequently used can be added immediately to a column with one click. This method defines
the list of default blocks.
def default_blocks(s... |
Returns a boolean if the current user has permission to add another object of the same
type which is being viewed/edited.
def has_add_permission(self):
"""
Returns a boolean if the current user has permission to add another object of the same
type which is being viewed/edited.
"... |
Returns a boolean if the current user has permission to change the current object being
viewed/edited.
def has_change_permission(self):
"""
Returns a boolean if the current user has permission to change the current object being
viewed/edited.
"""
has_permission = False
... |
Get correct embed url for Youtube or Vimeo.
def get_embed_url(self):
""" Get correct embed url for Youtube or Vimeo. """
embed_url = None
youtube_embed_url = 'https://www.youtube.com/embed/{}'
vimeo_embed_url = 'https://player.vimeo.com/video/{}'
# Get video ID from url.
... |
Set html field with correct iframe.
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
""" Set html field with correct iframe. """
if self.url:
iframe_html = '<iframe src="{}" frameborder="0" title="{}" allowfullscreen></iframe>'
self.html = ... |
Get IP address for the docker host
def _get_ip():
"""Get IP address for the docker host
"""
cmd_netstat = ['netstat', '-nr']
p1 = subprocess.Popen(cmd_netstat, stdout=subprocess.PIPE)
cmd_grep = ['grep', '^0\.0\.0\.0']
p2 = subprocess.Popen(cmd_grep, stdin=p1.stdout, stdout=subprocess.PIPE)
... |
Given access to the configuration dict that galaxy passed us, we try and connect to galaxy's API.
First we try connecting to galaxy directly, using an IP address given
us by docker (since the galaxy host is the default gateway for docker).
Using additional information collected by galaxy like th... |
Given filename[s] of any file accessible to the docker instance, this
function will upload that file[s] to galaxy using the current history.
Does not return anything.
def put(filenames, file_type='auto', history_id=None):
"""
Given filename[s] of any file accessible to the docker instance, ... |
Given the history_id that is displayed to the user, this function will
download the file[s] from the history and stores them under /import/
Return value[s] are the path[s] to the dataset[s] stored under /import/
def get(datasets_identifiers, identifier_type='hid', history_id=None):
"""
Give... |
Get all visible dataset infos of user history.
Return a list of dict of each dataset.
def get_user_history (history_id=None):
"""
Get all visible dataset infos of user history.
Return a list of dict of each dataset.
"""
history_id = history_id or os.environ['HISTORY_ID']
gi = get_... |
Act block is a single node - either the act node itself, or the node
that wraps the act node.
def build_act(cls: Type[_Block], node: ast.stmt, test_func_node: ast.FunctionDef) -> _Block:
"""
Act block is a single node - either the act node itself, or the node
that wraps the act node.
... |
Arrange block is all non-pass and non-docstring nodes before the Act
block start.
def build_arrange(cls: Type[_Block], nodes: List[ast.stmt], max_line_number: int) -> _Block:
"""
Arrange block is all non-pass and non-docstring nodes before the Act
block start.
"""
return... |
Assert block is all nodes that are after the Act node.
Note:
The filtering is *still* running off the line number of the Act
node, when instead it should be using the last line of the Act
block.
def build_assert(cls: Type[_Block], nodes: List[ast.stmt], min_line_number: int... |
Raises:
EmptyBlock: when block has no nodes
def get_span(self, first_line_no: int) -> Tuple[int, int]:
"""
Raises:
EmptyBlock: when block has no nodes
"""
if not self.nodes:
raise EmptyBlock('span requested from {} block with no nodes'.format(self.lin... |
r"""Developer script aliases.
def cli_aliases(self):
r"""Developer script aliases.
"""
scripting_groups = []
aliases = {}
for cli_class in self.cli_classes:
instance = cli_class()
if getattr(instance, "alias", None):
scripting_group = geta... |
r"""Developer script program names.
def cli_program_names(self):
r"""Developer script program names.
"""
program_names = {}
for cli_class in self.cli_classes:
instance = cli_class()
program_names[instance.program_name] = cli_class
return program_names |
:return: statistics as flat table {port/strea,/tpld name {group_stat name: value}}
def get_flat_stats(self):
"""
:return: statistics as flat table {port/strea,/tpld name {group_stat name: value}}
"""
flat_stats = OrderedDict()
for obj, port_stats in self.statistics.items():
... |
Read current ports statistics from chassis.
:return: dictionary {port name {group name, {stat name: stat value}}}
def read_stats(self):
""" Read current ports statistics from chassis.
:return: dictionary {port name {group name, {stat name: stat value}}}
"""
self.statistics = ... |
Read current statistics from chassis.
:return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}}
def read_stats(self):
""" Read current statistics from chassis.
:return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat... |
Read current statistics from chassis.
:return: dictionary {tpld full index {group name {stat name: stat value}}}
def read_stats(self):
""" Read current statistics from chassis.
:return: dictionary {tpld full index {group name {stat name: stat value}}}
"""
self.statistics = Tg... |
Find all user sets.
def get_user_sets(client_id, user_id):
"""Find all user sets."""
data = api_call('get', 'users/{}/sets'.format(user_id), client_id=client_id)
return [WordSet.from_dict(wordset) for wordset in data] |
Print all user sets by title. If 'print_terms', also prints all terms of all user sets.
:param wordsets: List of WordSet.
:param print_terms: If True, also prints all terms of all user sets.
def print_user_sets(wordsets, print_terms):
"""Print all user sets by title. If 'print_terms', also prints all terms... |
Get all term duplicates across all user word sets as a list of
(title of first word set, title of second word set, set of terms) tuples.
def get_common_terms(*api_envs):
"""Get all term duplicates across all user word sets as a list of
(title of first word set, title of second word set, set of terms) tuple... |
Print common terms for each pair of word sets.
:param common_terms: Output of get_common_terms().
def print_common_terms(common_terms):
"""Print common terms for each pair of word sets.
:param common_terms: Output of get_common_terms().
"""
if not common_terms:
print('No duplicates')
el... |
Delete the given term.
def delete_term(set_id, term_id, access_token):
"""Delete the given term."""
api_call('delete', 'sets/{}/terms/{}'.format(set_id, term_id), access_token=access_token) |
Add the given term to the given set.
:param term: Instance of Term.
def add_term(set_id, term, access_token):
"""Add the given term to the given set.
:param term: Instance of Term.
"""
api_call('post', 'sets/{}/terms'.format(set_id), term.to_dict(), access_token=access_token) |
Reset the stats of a term by deleting and re-creating it.
def reset_term_stats(set_id, term_id, client_id, user_id, access_token):
"""Reset the stats of a term by deleting and re-creating it."""
found_sets = [user_set for user_set in get_user_sets(client_id, user_id)
if user_set.set_id == set... |
Function createController
Create a controller node
@param key: The host name or ID
@param attributes:The payload of the host creation
@param printer: - False for no creation progression message
- True to get creation progression printed on STDOUT
... |
Function waitPuppetCatalogToBeApplied
Wait for puppet catalog to be applied
@param key: The host name or ID
@return RETURN: None
def waitPuppetCatalogToBeApplied(self, key, sleepTime=5):
""" Function waitPuppetCatalogToBeApplied
Wait for puppet catalog to be applied
@p... |
Function createVM
Create a Virtual Machine
The creation of a VM with libVirt is a bit complexe.
We first create the element in foreman, the ask to start before
the result of the creation.
To do so, we make async calls to the API and check the results
@param key: The hos... |
:rtype: User
def get(router, organization, email):
"""
:rtype: User
"""
log.info("Getting user: %s" % email)
resp = router.get_users(org_id=organization.id).json()
ids = [x['id'] for x in resp if x['email'] == email]
if len(ids):
user = User(organizat... |
Construct an object from a mapping
:param mapping: the constructor definition, with ``__type__`` name and keyword arguments
:param kwargs: additional keyword arguments to pass to the constructor
def construct(self, mapping: dict, **kwargs):
"""
Construct an object from a mapping
... |
Load an object based on an absolute, dotted name
def load_name(absolute_name: str):
"""Load an object based on an absolute, dotted name"""
path = absolute_name.split('.')
try:
__import__(absolute_name)
except ImportError:
try:
obj = sys.modules[pa... |
Set specified value to yaml path.
Example:
patch('application/components/child/configuration/__locator.application-id','777')
Will change child app ID to 777
def patch(self, path, value=None):
""" Set specified value to yaml path.
Example:
patch('application/components/c... |
Async component of _run
async def _await_all(self):
"""Async component of _run"""
delay = 0.0
# we run a top-level nursery that automatically reaps/cancels for us
async with trio.open_nursery() as nursery:
while self.running.is_set():
await self._start_payloa... |
Start all queued payloads
async def _start_payloads(self, nursery):
"""Start all queued payloads"""
with self._lock:
for coroutine in self._payloads:
nursery.start_soon(coroutine)
self._payloads.clear()
await trio.sleep(0) |
Check if longer list starts with shorter list
def contains_list(longer, shorter):
"""Check if longer list starts with shorter list"""
if len(longer) <= len(shorter):
return False
for a, b in zip(shorter, longer):
if a != b:
return False
return True |
Load and parse toml from a file object
An additional argument `dict_` is used to specify the output type
def load(f, dict_=dict):
"""Load and parse toml from a file object
An additional argument `dict_` is used to specify the output type
"""
if not f.read:
raise ValueError('The first parame... |
Parse a toml string
An additional argument `dict_` is used to specify the output type
def loads(content, dict_=dict):
"""Parse a toml string
An additional argument `dict_` is used to specify the output type
"""
if not isinstance(content, basestring):
raise ValueError('The first parameter ne... |
Read the line content and return the converted value
:param line: the line to feed to converter
:param is_end: if set to True, will raise an error if
the line has something remaining.
def convert(self, line=None, is_end=True):
"""Read the line content and return the converted value
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.