text
stringlengths
81
112k
Adds cause error to error message def add_cause(self, error: Exception): '''Adds cause error to error message''' self.add_info('Cause error', '{0} - {1}'.format(type(error).__name__, error))
Process an Async task and execute the requested function. def process_async_task(headers, request_body): """Process an Async task and execute the requested function.""" async_options = json.loads(request_body) async = async_from_options(async_options) _log_task_info(headers, extra_t...
Processes the header from task requests to log analytical data. def _log_task_info(headers, extra_task_info=None): """Processes the header from task requests to log analytical data.""" ran_at = time.time() task_eta = float(headers.get('X-Appengine-Tasketa', 0.0)) task_info = { 'retry_count': he...
Update firmware version on device by loading provided image, performs following steps: 1. Copy bin file from remote tftp server. 2. Clear in run config boot system section. 3. Set downloaded bin file as boot file and then reboot device. 4. Check if firmware was successfu...
Parse ports string into the list :param str ports: :rtype: list[tuple[str, str]] def _parse_ports(self, ports): """Parse ports string into the list :param str ports: :rtype: list[tuple[str, str]] """ if not ports: return [] return [tuple(po...
SDN Controller enable trunk ports :rtype: list[tuple[str, str]] def add_trunk_ports(self): """SDN Controller enable trunk ports :rtype: list[tuple[str, str]] """ ports = self.attributes.get("{}Enable Full Trunk Ports".format(self.namespace_prefix), None) return self._p...
SDN Controller disable trunk ports :rtype: list[tuple[str, str]] def remove_trunk_ports(self): """SDN Controller disable trunk ports :rtype: list[tuple[str, str]] """ ports = self.attributes.get("{}Disable Full Trunk Ports".format(self.namespace_prefix), None) return s...
Will be run if the async task raises an unhandled exception. def handle_an_error(): """Will be run if the async task raises an unhandled exception.""" import os from furious.context import get_current_async async = get_current_async() async_exception = async.result.payload exc_info = async_ex...
Validate resource structure :param dict autoload_resource: :return correct autoload resource structure :rtype: dict def _validate_build_resource_structure(autoload_resource): """Validate resource structure :param dict autoload_resource: :return correct autoload resourc...
Build autoload details :param autoload_data: dict: :param relative_path: str: full relative path of current autoload resource def _build_autoload_details(self, autoload_data, relative_path=""): """ Build autoload details :param autoload_data: dict: :param relative_path: str: f...
Sets node attribute. Can be customized by attr_setter property def set_attr(self, key: str, value): """Sets node attribute. Can be customized by attr_setter property""" self.attr_setter(self, key, value)
Stores binding def add_binding(self, binding: Binding): """Stores binding""" binding.add_error_info = lambda error: error.add_view_info(self._xml_node.view_info) self._bindings.append(binding)
Destroys node def destroy(self): """Destroys node""" self.destroy_children() self.destroy_bindings() if self.on_destroy: self.on_destroy(self)
Sets value def set(self, value): """Sets value""" self._value = self._setter(self._node, value, self._value) if self._setter else value
Creates property for node def new(self, node: Node): """Creates property for node""" return Property(self.name, self._setter, node)
Histogram for correlation coefficients and its p-values (colored) Parameters: ----------- r : np.ndarray Correlation coefficient matrix. The upper triangular elements are extracted if a NxN is provided. Otherwise provide a plain vector. pval : np.ndarray NxN matrix with...
Create an instance of TrafficGeneratorVBladeResource from the given context :param cloudshell.shell.core.driver_context.ResourceCommandContext context: :param str shell_type: shell type :param str shell_name: shell name :rtype: TrafficGeneratorVChassisResource def from_context(cls, con...
Helper. Updates filter dict for a queryset. :param dict d: :param User|None user: :param int|None status: :return: def update_filter_dict(d, user, status): """Helper. Updates filter dict for a queryset. :param dict d: :param User|None user: :param int|None status: :return: """...
Returns a dictionary with flag objects associated with the given model classes (types). The dictionary is indexed by model classes. Each dict entry contains a list of associated flag objects. :param list mdl_classes: :param User user: :param int status: :param bool allow...
Returns a dictionary with flag objects associated with the given model objects. The dictionary is indexed by objects IDs. Each dict entry contains a list of associated flag objects. :param list, QuerySet objects_list: :param User user: :param int status: :rtype: dict de...
Returns flags for the object optionally filtered by status. :param User user: Optional user filter :param int status: Optional status filter :rtype: QuerySet def get_flags(self, user=None, status=None): """Returns flags for the object optionally filtered by status. :param User...
Flags the object. :param User user: :param str note: User-defined note for this flag. :param int status: Optional status integer (the meaning is defined by a developer). :return: def set_flag(self, user, note=None, status=None): """Flags the object. :param User user: ...
Removes flag(s) from the object. :param User user: Optional user filter :param int status: Optional status filter :return: def remove_flag(self, user=None, status=None): """Removes flag(s) from the object. :param User user: Optional user filter :param int status: Optio...
Returns boolean whether the objects is flagged by a user. :param User user: Optional user filter :param int status: Optional status filter :return: def is_flagged(self, user=None, status=None): """Returns boolean whether the objects is flagged by a user. :param User user: Opti...
Configure used database, so sqlpuzzle can generate queries which are needed. For now there is only support of MySQL and PostgreSQL. def set_backend(database): """ Configure used database, so sqlpuzzle can generate queries which are needed. For now there is only support of MySQL and PostgreSQL. """ ...
Verify that device is accessible over CLI by sending ENTER for cli session def health_check(self): """ Verify that device is accessible over CLI by sending ENTER for cli session """ api_response = 'Online' result = 'Health check on resource {}'.format(self._resource_name) try: ...
Convert as reference on column. table => "table" table.column => "table"."column" db.table.column => "db"."table"."column" table."col.umn" => "table"."col.umn" "table"."col.umn" => "table"."col.umn" def reference(cls, value): """ Convert as reference on column. ...
Convert a reference to a Python object to a string path. def reference_to_path(reference): """Convert a reference to a Python object to a string path.""" # Try to pop the options off whatever they passed in. if isinstance(reference, basestring): # This is an object path name in str form. im...
Convert an object path reference to a reference. def path_to_reference(path): """Convert an object path reference to a reference.""" # By default JSON decodes strings as unicode. The Python __import__ does # not like that choice. So we'll just cast all function paths to a string. # NOTE: that there is...
Encode callbacks to as a dict suitable for JSON encoding. def encode_callbacks(callbacks): """Encode callbacks to as a dict suitable for JSON encoding.""" from furious.async import Async if not callbacks: return encoded_callbacks = {} for event, callback in callbacks.iteritems(): ...
Decode the callbacks to an executable form. def decode_callbacks(encoded_callbacks): """Decode the callbacks to an executable form.""" from furious.async import Async callbacks = {} for event, callback in encoded_callbacks.iteritems(): if isinstance(callback, dict): async_type = As...
Prettifies a scope stack for use in error messages. :param list(str) stack: List of scopes. :param str current: The current scope. If specified, will be appended onto the stack before formatting. :returns: str def _format_stack(self, stack, current=None): """Prettifies a sc...
Resolve a fragment within the schema. If the resolved value contains a $ref, it will attempt to resolve that as well, until it gets something that is not a reference. Circular references will raise a SchemaError. :param str ref: URI to resolve. :param dict document: Optional sc...
Add support to load YAML files. This will attempt to load a YAML file first, and then go back to the default behavior. :param str uri: the URI to resolve :returns: the retrieved document def resolve_remote(self, uri): """Add support to load YAML files. This will attem...
Get a jsonschema validator. :param dict schema: A custom schema to validate against. :returns: an instance of jsonschema Draft4Validator. def get_validator(self, schema=None): """Get a jsonschema validator. :param dict schema: A custom schema to validate against. :returns: an ...
Resolve a ref within the schema. This is just a convenience method, since RefResolver returns both a URI and the resolved value, and we usually just need the resolved value. :param str ref: URI to resolve. :param dict document: Optional schema in which to resolve the URI. :retu...
jsonschema RefResolver object for the base schema. def resolver(self): """jsonschema RefResolver object for the base schema.""" if self._resolver is not None: return self._resolver if self._schema_path is not None: # the documentation for ref resolving # http...
Validates and returns the value. If the value does not validate against the schema, SchemaValidationError will be raised. :param value: A value to validate (usually a dict). :param validator: An instance of a jsonschema validator class, as created by Schema.get_validator()....
Validates and returns the parsed JSON string. If the value is not valid JSON, ParseError will be raised. If it is valid JSON, but does not validate against the schema, SchemaValidationError will be raised. :param str json_value: JSON value. :param validator: An instance of a js...
Create an instance from a YAML or JSON schema file. Any additional args or kwargs will be passed on when constructing the new schema instance (useful for subclasses). :param str schema_filepath: Path to the schema file. :returns: an instance of the class. :raises SchemaLoadingE...
Execute flow which run custom command on device :param custom_command: the command to execute on device :param is_config: if True then run command in configuration mode :return: command execution output def execute_flow(self, custom_command="", is_config=False): """ Execute flow which ...
Execute custom command in configuration mode on device :param custom_command: command :return: result of command execution def run_custom_config_command(self, custom_command): """ Execute custom command in configuration mode on device :param custom_command: command :return: re...
Parses a url like this rethinkdb://server1:port,server2:port/database/table Returns: tuple `(['server1:port', 'server2:port'], database, table)` `table` and `database` may be None Raises: ValueError if url cannot be parsed as a rethinkdb url There is some precedent for this kind o...
Deserialize an Async or Async subclass from an options dict. def async_from_options(options): """Deserialize an Async or Async subclass from an options dict.""" _type = options.pop('_type', 'furious.async.Async') _type = path_to_reference(_type) return _type.from_dict(options)
Encode Async options for JSON encoding. def encode_async_options(async): """Encode Async options for JSON encoding.""" options = copy.deepcopy(async._options) options['_type'] = reference_to_path(async.__class__) # JSON don't like datetimes. eta = options.get('task_args', {}).get('eta') if et...
Decode Async options from JSON decoding. def decode_async_options(options): """Decode Async options from JSON decoding.""" async_options = copy.deepcopy(options) # JSON don't like datetimes. eta = async_options.get('task_args', {}).get('eta') if eta: from datetime import datetime ...
Set default Async options on the function decorated. Note: you must pass the decorated function by reference, not as a "path.string.to.function" for this to have any effect. def defaults(**options): """Set default Async options on the function decorated. Note: you must pass the decorated function by ...
Store this Async's result in persistent storage. def _persist_result(self): """Store this Async's result in persistent storage.""" self._prepare_persistence_engine() return self._persistence_engine.store_async_result( self.id, self.result)
Ensure recursion info is initialized, if not, initialize it. def _initialize_recursion_depth(self): """Ensure recursion info is initialized, if not, initialize it.""" from furious.context import get_current_async recursion_options = self._options.get('_recursion', {}) current_depth = ...
Check recursion depth, raise AsyncRecursionError if too deep. def check_recursion_depth(self): """Check recursion depth, raise AsyncRecursionError if too deep.""" from furious.async import MAX_DEPTH recursion_options = self._options.get('_recursion', {}) max_depth = recursion_options.g...
Specify the function this async job is to execute when run. def _update_job(self, target, args, kwargs): """Specify the function this async job is to execute when run.""" target_path, options = get_function_path_and_options(target) assert isinstance(args, (tuple, list)) or args is None ...
Set the ExecutionContext this async is executing under. def set_execution_context(self, execution_context): """Set the ExecutionContext this async is executing under.""" if self._execution_context: raise errors.AlreadyInContextError self._execution_context = execution_context
Safely update this async job's configuration options. def update_options(self, **options): """Safely update this async job's configuration options.""" _check_options(options) if 'persistence_engine' in options: options['persistence_engine'] = reference_to_path( opt...
Return a task object representing this async job. def to_task(self): """Return a task object representing this async job.""" from google.appengine.api.taskqueue import Task from google.appengine.api.taskqueue import TaskRetryOptions self._increment_recursion_level() self.check_...
Insert the task into the requested queue, 'default' if non given. If a TransientError is hit the task will re-insert the task. If a TaskAlreadyExistsError or TombstonedTaskError is hit the task will silently fail. If the async flag is set, then the add will be done asynchronously and ...
Return an async job from a dict output by Async.to_dict. def from_dict(cls, async): """Return an async job from a dict output by Async.to_dict.""" async_options = decode_async_options(async) target, args, kwargs = async_options.pop('job') return cls(target, args, kwargs, **async_optio...
Load the specified persistence engine, or the default if none is set. def _prepare_persistence_engine(self): """Load the specified persistence engine, or the default if none is set. """ if self._persistence_engine: return persistence_engine = self._options.g...
If this async is in a context set the context id. def _get_context_id(self): """If this async is in a context set the context id.""" from furious.context import get_current_context context_id = self._options.get('context_id') if context_id: return context_id try:...
If this async is in within another async set that async id as the parent. def _get_parent_id(self): """If this async is in within another async set that async id as the parent. """ parent_id = self._options.get('parent_id') if parent_id: return parent_id ...
Return the full_id for this Async. Consists of the parent id, id and context id. def full_id(self): """Return the full_id for this Async. Consists of the parent id, id and context id. """ full_id = "" if self.parent_id: full_id = ":".join([self.parent_id, se...
Increment current_depth based on either defaults or the enclosing Async. def _increment_recursion_level(self): """Increment current_depth based on either defaults or the enclosing Async. """ # Update the recursion info. This is done so that if an async created # outside...
Return this Async's Context Id if it exists. def context_id(self): """Return this Async's Context Id if it exists.""" if not self._context_id: self._context_id = self._get_context_id() self.update_options(context_id=self._context_id) return self._context_id
When an error status the payload is holding an AsyncException that is converted to a serializable dict. def _payload_to_dict(self): """When an error status the payload is holding an AsyncException that is converted to a serializable dict. """ if self.status != self.ERROR or not ...
Returns a HTTPMethod instance to create a PUT route. :see: :class:`~doctor.routing.HTTPMethod` def put(func: Callable, allowed_exceptions: List = None, title: str = None, req_obj_type: Callable = None) -> HTTPMethod: """Returns a HTTPMethod instance to create a PUT route. :see: :class:`~doctor.ro...
Create a handler method to be used in a handler class. :param callable logic: The underlying function to execute with the parsed and validated parameters. :param str http_method: HTTP method this will handle. :param handle_http: The HTTP handler function that should be used to wrap the logi...
Gets the handler name. :param route: A Route instance. :param logic: The logic function. :returns: A handler class name. def get_handler_name(route: Route, logic: Callable) -> str: """Gets the handler name. :param route: A Route instance. :param logic: The logic function. :returns: A hand...
Creates handler routes from the provided routes. :param routes: A tuple containing the route and another tuple with all http methods allowed for the route. :param handle_http: The HTTP handler function that should be used to wrap the logic functions. :param default_base_handler_class: The d...
Parser of arguments. dict options { int min_items: Min of required items to fold one tuple. (default: 1) int max_items: Count of items in one tuple. Last `max_items-min_items` items is by default set to None. (default: 1) bool allow_dict: Flag allowing dictionary as first (and o...
Pick a number, if it is more than some cuttoff continue the chain. def simple_state_machine(): """Pick a number, if it is more than some cuttoff continue the chain.""" from random import random from furious.async import Async number = random() logging.info('Generating a number... %s', number) ...
Render HTML attributes, or return '' if no attributes needs to be rendered. def render_attrs(attrs): """ Render HTML attributes, or return '' if no attributes needs to be rendered. """ if attrs is not None: def parts(): for key, value in sorted(attrs.items()): if val...
Persist async marker and async the completion check def context_completion_checker(async): """Persist async marker and async the completion check""" store_async_marker(async.id, async.result.status if async.result else -1) logging.debug("Async check completion for: %s", async.context_id) current_queu...
Check if all Async jobs within a Context have been run. def _completion_checker(async_id, context_id): """Check if all Async jobs within a Context have been run.""" if not context_id: logging.debug("Context for async %s does not exist", async_id) return context = FuriousContext.from_id(co...
Returns a flag for markers being found for the task_ids. If all task ids have markers True will be returned. Otherwise it will return False as soon as a None result is hit. def _check_markers(task_ids, offset=10): """Returns a flag for markers being found for the task_ids. If all task ids have markers ...
Transactionally 'complete' the context. def _mark_context_complete(marker, context, has_errors): """Transactionally 'complete' the context.""" current = None if marker: current = marker.key.get() if not current: return False if current and current.complete: return False ...
Insert the event's asyncs and cleanup tasks. def _insert_post_complete_tasks(context): """Insert the event's asyncs and cleanup tasks.""" logging.debug("Context %s is complete.", context.id) # Async event handlers context.exec_event_handler('complete', transactional=True) # Insert cleanup tasks ...
Delete the FuriousAsyncMarker entities corresponding to ids. def _cleanup_markers(context_id, task_ids): """Delete the FuriousAsyncMarker entities corresponding to ids.""" logging.debug("Cleanup %d markers for Context %s", len(task_ids), context_id) # TODO: Handle exceptions and retries...
Persist a furious.context.Context object to the datastore by loading it into a FuriousContext ndb.Model. def store_context(context): """Persist a furious.context.Context object to the datastore by loading it into a FuriousContext ndb.Model. """ logging.debug("Attempting to store Context %s.", cont...
Persist the Async's result to the datastore. def store_async_result(async_id, async_result): """Persist the Async's result to the datastore.""" logging.debug("Storing result for %s", async_id) key = FuriousAsyncMarker( id=async_id, result=json.dumps(async_result.to_dict()), status=async_r...
Persist a marker indicating the Async ran to the datastore. def store_async_marker(async_id, status): """Persist a marker indicating the Async ran to the datastore.""" logging.debug("Attempting to mark Async %s complete.", async_id) # QUESTION: Do we trust if the marker had a flag result to just trust it...
Yield out the results found on the markers for the context task ids. def iter_context_results(context, batch_size=10, task_cache=None): """Yield out the results found on the markers for the context task ids.""" for futures in iget_batches(context.task_ids, batch_size=batch_size): for key, future in fu...
Yield out a map of the keys and futures in batches of the batch size passed in. def iget_batches(task_ids, batch_size=10): """Yield out a map of the keys and futures in batches of the batch size passed in. """ make_key = lambda _id: ndb.Key(FuriousAsyncMarker, _id) for keys in i_batch(imap(mak...
Generator that iteratively batches items to a max size and consumes the items as each batch is yielded. def i_batch(items, size): """Generator that iteratively batches items to a max size and consumes the items as each batch is yielded. """ for items_batch in iter(lambda: tuple(islice(items, size))...
Create a `cls` entity from a context. def from_context(cls, context): """Create a `cls` entity from a context.""" return cls(id=context.id, context=context.to_dict())
Load a `cls` entity and instantiate the Context it stores. def from_id(cls, id): """Load a `cls` entity and instantiate the Context it stores.""" from furious.context import Context # TODO: Handle exceptions and retries here. entity = cls.get_by_id(id) if not entity: ...
Yield the async reuslts for the context. def items(self): """Yield the async reuslts for the context.""" for key, task in self._tasks: if not (task and task.result): yield key, None else: yield key, json.loads(task.result)["payload"]
Yield the async reuslt values for the context. def values(self): """Yield the async reuslt values for the context.""" for _, task in self._tasks: if not (task and task.result): yield None else: yield json.loads(task.result)["payload"]
Display AiiDA data types in Jupyter notebooks. :param downloadable: If True, add link/button to download content of displayed AiiDA object. Defers to IPython.display.display for any objects it does not recognize. def aiidalab_display(obj, downloadable=True, **kwargs): """Display AiiDA data types in Jupyt...
ATTENTION: modifying the order of operations in this function can lead to unexpected problems def on_setup_ssh(self, b): """ATTENTION: modifying the order of operations in this function can lead to unexpected problems""" with self._setup_ssh_out: clear_output() self._ssh_keygen(...
Returning the password and immediately destroying it def __password(self): """Returning the password and immediately destroying it""" passwd = copy(self._inp_password.value) self._inp_password.value = '' return passwd
Returning the password and immediately destroying it def __proxy_password(self): """Returning the password and immediately destroying it""" passwd = copy(self._inp_proxy_password.value) self._inp_proxy_password.value = '' return passwd
Loking for username in user's input and config file def username(self): """Loking for username in user's input and config file""" if len(self._inp_username.value.strip()) == 0: # if username provided by user if not self.hostname is None: config = parse_sshconfig(self.hostnam...
create DbAuthInfo def _configure_computer(self): """create DbAuthInfo""" print("Configuring '{}'".format(self.name)) sshcfg = parse_sshconfig(self.hostname) authparams = { 'compress': True, 'gss_auth': False, 'gss_deleg_creds': False, 'gss...
Package setup def setup_package(): """Package setup""" setup( name='pyviews', version=_get_version(), description='Base package for xml views', long_description=_get_long_description(), long_description_content_type='text/markdown', url='https://github.com/eumis/...
Confusion Matrix - confusion matrix, error matrix, matching matrix (unsupervised) - is a special case: 2x2 contingency table (xtab, RxC table) - both dimensions are variables with the same classes/labels, i.e. actual and predicted variables are binary [0,1] Parameters: ----------- a : nd...
Retrieves a document from the database, by primary key. def load(cls, rr, pk): ''' Retrieves a document from the database, by primary key. ''' if pk is None: return None d = rr.table(cls.table).get(pk).run() if d is None: return None doc =...
Creates the table if it doesn't exist. def table_ensure(cls, rr): ''' Creates the table if it doesn't exist. ''' dbs = rr.db_list().run() if not rr.dbname in dbs: logging.info('creating rethinkdb database %s', repr(rr.dbname)) rr.db_create(rr.dbname).run(...
Name of the primary key field as retrieved from rethinkdb table metadata, 'id' by default. Should not be overridden. Override `table_create` if you want to use a nonstandard field as the primary key. def pk_field(self): ''' Name of the primary key field as retrieved from rethink...
Persist changes to rethinkdb. Updates only the fields that have changed. Performs insert rather than update if the document has no primary key or if the primary key is absent from the database. If there have been any changes to nested fields, updates the first level attribute. For examp...
Refresh the document from the database. def refresh(self): ''' Refresh the document from the database. ''' d = self.rr.table(self.table).get(self.pk_value).run() if d is None: raise KeyError for k in d: dict.__setitem__( self, ...
Parses xml file with xml_path and returns XmlNode def parse(self, xml_file, view_name=None) -> XmlNode: """Parses xml file with xml_path and returns XmlNode""" self._setup_parser() try: self._view_name = view_name self._parser.ParseFile(xml_file) except ExpatErro...