text
stringlengths
81
112k
Generate documentation for the given object annotation. :param doctor.resource.ResourceAnnotation annotation: Annotation object for the associated handler method. :param str field: Sphinx field type to use (e.g. '<json'). :param list url_params: A list of url parameter strings. :param bool requ...
Generate documentation lines for the given annotation. This only documents schemas of type "object", or type "list" where each "item" is an object. Other types are ignored (but a warning is logged). :param doctor.resource.ResourceAnnotation annotation: Annotation object for the associated handler ...
Generate documentation lines for all collected resource objects. As API documentation is generated we keep a running list of objects used in request parameters and responses. This section will generate documentation for each object and provide an inline reference in the API documentation. :return...
Return a best guess at the qualified name for a class or function. :param value: A class or function object. :type value: class or function :returns str: def get_name(value) -> str: """Return a best guess at the qualified name for a class or function. :param value: A class or function object. ...
Strip some of the ugly regexp characters from the given pattern. >>> normalize_route('^/user/<user_id:int>/?$') u'/user/(user_id:int)/' def normalize_route(route: str) -> str: """Strip some of the ugly regexp characters from the given pattern. >>> normalize_route('^/user/<user_id:int>/?$') u'/use...
Add the prefix to each of the lines. >>> prefix_lines(['foo', 'bar'], ' ') [' foo', ' bar'] >>> prefix_lines('foo\\nbar', ' ') [' foo', ' bar'] :param list or str lines: A string or a list of strings. If a string is passed, the string is split using splitlines(). :param str prefi...
Converts a camel case class name to a resource name with spaces. >>> class_name_to_resource_name('FooBarObject') 'Foo Bar Object' :param class_name: The name to convert. :returns: The resource name. def class_name_to_resource_name(class_name: str) -> str: """Converts a camel case class name to a ...
Setup the document's environment, if necessary. def _prepare_env(self): # pragma: no cover """Setup the document's environment, if necessary.""" env = self.state.document.settings.env if not hasattr(env, self.directive_name): # Track places where we use this directive, so we can ch...
Render lines of reStructuredText for items yielded by :meth:`~doctor.docs.base.BaseHarness.iter_annotations`. def _render_rst(self): # pragma: no cover """Render lines of reStructuredText for items yielded by :meth:`~doctor.docs.base.BaseHarness.iter_annotations`. """ # Create ...
Called by Sphinx to generate documentation for this directive. def run(self): # pragma: no cover """Called by Sphinx to generate documentation for this directive.""" if self.directive_name is None: raise NotImplementedError('directive_name must be implemented by ' ...
Handler for Sphinx's env-get-outdated event. This handler gives a Sphinx extension a chance to indicate that some set of documents are out of date and need to be re-rendered. The implementation here is stupid, for now, and always says that anything that uses the directive needs to be re...
Handler for Sphinx's env-purge-doc event. This event is emitted when all traces of a source file should be cleaned from the environment (that is, if the source file is removed, or before it is freshly read). This is for extensions that keep their own caches in attributes of the environm...
Called by Sphinx to setup an extension. def setup(cls, app): # pragma: no cover """Called by Sphinx to setup an extension.""" if cls.directive_name is None: raise NotImplementedError('directive_name must be set by ' 'subclasses of BaseDirective') ...
Define header values for a given request. By default, header values are determined from the class attribute `headers`. But if you want to change the headers used in the documentation for a specific route, this method lets you do that. :param str http_method: An HTTP method, like "get"....
Define example values for a given request. By default, example values are determined from the example properties in the schema. But if you want to change the example used in the documentation for a specific route, and this method lets you do that. :param str http_method: An HTTP method...
Returns the heading text for an annotation. Attempts to get the name of the heading from the handler attribute `schematic_title` first. If `schematic_title` it is not present, it attempts to generate the title from the class path. This path: advertiser_api.handlers.foo_bar.FooL...
Gets headers for the provided route. :param route: The route to get example values for. :type route: werkzeug.routing.Rule for a flask api. :param annotation: Schema annotation for the method to be requested. :type annotation: doctor.resource.ResourceAnnotation :retruns: A dict ...
Gets example values for all properties in the annotation's schema. :param route: The route to get example values for. :type route: werkzeug.routing.Rule for a flask api. :param annotation: Schema annotation for the method to be requested. :type annotation: doctor.resource.ResourceAnnota...
Get device name by its SNMP sysObjectID property from the file map :param str file_name: :param str sys_obj_id: :param str delimiter: :rtype: str def get_device_name(file_name, sys_obj_id, delimiter=":"): """Get device name by its SNMP sysObjectID property from the file map :param str file_na...
Returns ``True`` if ``querypart_name`` with ``value`` is set. For example you can check if you already used condition by ``sql.has('where')``. If you want to check for more information, for example if that condition also contain ID, you can do this by ``sql.has('where', 'id')``. def has(self, ...
Default ordering is ``ASC``. ``group_by`` accept ``dict`` as you would expect, but note that ``dict`` does not have same order. Same for named arguments. .. code-block:: python >>> sqlpuzzle.select('c').from_('t').group_by('a', ('b', 'desc')) <Select: SELECT "c" FROM "...
Default ordering is ``ASC``. ``order_by`` accept ``dict`` as you would expect, but note that ``dict`` does not have same order. .. code-block:: python >>> sqlpuzzle.select('c').from_('t').order_by('a', ('b', 'desc')) <Select: SELECT "c" FROM "t" ORDER BY "a", "b" DESC>...
Log out that the context is complete. def context_complete(context_id): """Log out that the context is complete.""" logging.info('Context %s is.......... DONE.', context_id) from furious.context import get_current_async_with_context _, context = get_current_async_with_context() if not context: ...
Processes the messages pulled fromm a queue based off the tag passed in. Will insert another processor if any work was processed or the retry count is under the max retry count. Will update a aggregated stats object with the data in the payload of the messages processed. :param tag: :class: `str` Tag t...
Updates the stats with the value passed in. :param stats: :class: `dict` :param value: :class: `int` def set_stats(stats, value): """Updates the stats with the value passed in. :param stats: :class: `dict` :param value: :class: `int` """ stats["total_count"] += 1 stats["value"] += val...
Returns a :class: `dict` of the default stats structure. def get_default_stats(): """Returns a :class: `dict` of the default stats structure.""" default_stats = { "total_count": 0, "max": 0, "min": 0, "value": 0, "average": 0, "last_update": None, } ret...
Serializes output as JSON and writes it to console output wrapped with special prefix and suffix :param result: Result to return :param unpicklable: If True adds JSON can be deserialized as real object. When False will be deserialized as dictionary def serialize_to_json(result, unpickl...
Backup 'startup-config' or 'running-config' from device to provided file_system [ftp|tftp] Also possible to backup config to localhost :param folder_path: tftp/ftp server where file be saved :param configuration_type: type of configuration that will be saved (StartUp or Running) :param ...
Restore configuration on device from provided configuration file Restore configuration from local file system or ftp/tftp server into 'running-config' or 'startup-config'. :param path: relative path to the file on the remote host tftp://server/sourcefile :param configuration_type: the configurat...
Orchestration Save command :param mode: :param custom_params: json with all required action to configure or remove vlans from certain port :return Serialized OrchestrationSavedArtifact to json :rtype json def orchestration_save(self, mode="shallow", custom_params=None): """Orch...
Orchestration restore :param saved_artifact_info: json with all required data to restore configuration on the device :param custom_params: custom parameters def orchestration_restore(self, saved_artifact_info, custom_params=None): """Orchestration restore :param saved_artifact_info: j...
Validate incoming path, if path is empty, build it from resource attributes, If path is invalid - raise exception :param path: path to remote file storage :return: valid path or :raise Exception: def get_path(self, path=''): """ Validate incoming path, if path is empty, build i...
Validate configuration type :param configuration_type: configuration_type, should be Startup or Running :raise Exception: def _validate_configuration_type(self, configuration_type): """Validate configuration type :param configuration_type: configuration_type, should be Startup or Runn...
Validate OrchestrationSavedArtifactInfo object for key components :param OrchestrationSavedArtifactInfo saved_config: object to validate def _validate_artifact_info(self, saved_config): """Validate OrchestrationSavedArtifactInfo object for key components :param OrchestrationSavedArtifactInfo ...
Adds resolver to global container def register(key, initializer: callable, param=None): '''Adds resolver to global container''' get_current_scope().container.register(key, initializer, param)
Generates resolver to return singleton value and adds it to global container def register_single(key, value, param=None): '''Generates resolver to return singleton value and adds it to global container''' get_current_scope().container.register(key, lambda: value, param)
Wraps function with scope. If scope_name is None current scope is used def wrap_with_scope(func, scope_name=None): '''Wraps function with scope. If scope_name is None current scope is used''' if scope_name is None: scope_name = get_current_scope().name return lambda *args, scope=scope_name, **kwarg...
Resolves dependencies using global container and passed it with optional parameters def inject(*injections): '''Resolves dependencies using global container and passed it with optional parameters''' def _decorate(func): def _decorated(*args, **kwargs): args = list(args) keys_to_...
Add resolver to container def register(self, key, initializer: callable, param=None): '''Add resolver to container''' if not callable(initializer): raise DependencyError('Initializer {0} is not callable'.format(initializer)) if key not in self._initializers: self._initia...
Resolve dependecy def get(self, key, param=None): '''Resolve dependecy''' try: return self._initializers[key][param]() except KeyError: if key in self._factories: return self._factories[key](param) raise DependencyError('Dependency "{0}" is no...
Handle a Flask HTTP request :param handler: flask_restful.Resource: An instance of a Flask Restful resource class. :param tuple args: Any positional arguments passed to the wrapper method. :param dict kwargs: Any keyword arguments passed to the wrapper method. :param callable logic: The callabl...
A thin wrapper around create_routes that passes in flask specific values. :param routes: A tuple containing the route and another tuple with all http methods allowed for the route. :returns: A list of tuples containing the route and generated handler. def create_routes(routes: Tuple[Route]) -> List[Tu...
Convert the confusion matrix to the Matthews correlation coefficient Parameters: ----------- cm : ndarray 2x2 confusion matrix with np.array([[tn, fp], [fn, tp]]) tn, fp, fn, tp : float four scalar variables - tn : number of true negatives - fp : number of false positiv...
Matthews correlation Parameters ---------- x : ndarray dataset of binary [0,1] values axis : int, optional Variables as columns is the default (axis=0). If variables are in the rows use axis=1 autocorrect : bool, optional If all predictions are True or all are Fals...
Creates node from xml node using namespace as module and tag name as class name def create_node(xml_node: XmlNode, **init_args): '''Creates node from xml node using namespace as module and tag name as class name''' inst_type = get_inst_type(xml_node) init_args['xml_node'] = xml_node inst = create_inst(...
Returns type by xml node def get_inst_type(xml_node: XmlNode): '''Returns type by xml node''' (module_path, class_name) = (xml_node.namespace, xml_node.name) try: return import_module(module_path).__dict__[class_name] except (KeyError, ImportError, ModuleNotFoundError): message = 'Impor...
Creates class instance with args def create_inst(inst_type, **init_args): '''Creates class instance with args''' args, kwargs = get_init_args(inst_type, init_args) return inst_type(*args, **kwargs)
Returns tuple with args and kwargs to pass it to inst_type constructor def get_init_args(inst_type, init_args: dict, add_kwargs=False) -> Tuple[List, Dict]: '''Returns tuple with args and kwargs to pass it to inst_type constructor''' try: parameters = signature(inst_type).parameters.values() ar...
Wraps passed instance with InstanceNode def convert_to_node(instance, xml_node: XmlNode, node_globals: InheritedDict = None)\ -> InstanceNode: '''Wraps passed instance with InstanceNode''' return InstanceNode(instance, xml_node, node_globals)
Create QS Logger for command context AutoLoadCommandContext, ResourceCommandContext or ResourceRemoteCommandContext with thread name :param context: :return: def get_logger_with_thread_id(context): """ Create QS Logger for command context AutoLoadCommandContext, ResourceCommandContext or Resour...
:param ResourceCommandContext resource_config: command context :return: def get_snmp_parameters_from_command_context(resource_config, api, force_decrypt=False): """ :param ResourceCommandContext resource_config: command context :return: """ if '3' in resource_config.snmp_version: retur...
Add an Async job to this context. Like Context.add(): creates an Async and adds it to our list of tasks. but also calls _auto_insert_check() to add tasks to queues automatically. def add(self, target, args=None, kwargs=None, **options): """Add an Async job to this context. Lik...
Automatically insert tasks asynchronously. Depending on batch_size, insert or wait until next call. def _auto_insert_check(self): """Automatically insert tasks asynchronously. Depending on batch_size, insert or wait until next call. """ if not self.batch_size: retur...
Decorator for the instructions. The decorator contains the static information for the instructions, in particular the encoding parameters and the assembler mnemonic. :param mnemonic: Assembler mnemonic :param opcode: Opcode of this instruction :param funct3: 3 bit function code on bits 14 to 12 (R-, I-...
Get all Instructions. This is based on all known subclasses of `cls`. If non is given, all Instructions are returned. Only such instructions are returned that can be generated, i.e., that have a mnemonic, opcode, etc. So other classes in the hierarchy are not matched. :param cls: Base class to get list ...
Find instruction that matches the mnemonic. :param mnemonic: Mnemonic to match :return: :class:`Instruction` that matches or None def reverse_lookup(mnemonic: str): """ Find instruction that matches the mnemonic. :param mnemonic: Mnemonic to match :return: :class:`Instruction` that matches or...
Gets a value from a schema and definition. If the value has references it will recursively attempt to resolve them. :param ResourceSchema schema: The resource schema. :param dict definition: The definition dict from the schema. :param str key: The key to use to get the value from the schema. :para...
Returns the json and native python type based on the json_type input. If json_type is a list of types it will return the first non 'null' value. :param json_type: A json type or a list of json types. :returns: A tuple containing the json type and native python type. def get_types(json_type: StrOrList) ->...
Create a :class:`~doctor.types.JsonSchema` type. This function will automatically load the schema and set it as an attribute of the class along with the description and example. :param schema_file: The full path to the json schema file to load. :param kwargs: Can include any attribute defined in ...
Create a :class:`~doctor.types.String` type. :param description: A description of the type. :param kwargs: Can include any attribute defined in :class:`~doctor.types.String` def string(description: str, **kwargs) -> typing.Type: """Create a :class:`~doctor.types.String` type. :param descripti...
Create a :class:`~doctor.types.Integer` type. :param description: A description of the type. :param kwargs: Can include any attribute defined in :class:`~doctor.types.Integer` def integer(description, **kwargs) -> typing.Type: """Create a :class:`~doctor.types.Integer` type. :param descriptio...
Create a :class:`~doctor.types.Number` type. :param description: A description of the type. :param kwargs: Can include any attribute defined in :class:`~doctor.types.Number` def number(description, **kwargs) -> typing.Type: """Create a :class:`~doctor.types.Number` type. :param description: A...
Create a :class:`~doctor.types.Boolean` type. :param description: A description of the type. :param kwargs: Can include any attribute defined in :class:`~doctor.types.Boolean` def boolean(description, **kwargs) -> typing.Type: """Create a :class:`~doctor.types.Boolean` type. :param descriptio...
Create a :class:`~doctor.types.Enum` type. :param description: A description of the type. :param kwargs: Can include any attribute defined in :class:`~doctor.types.Enum` def enum(description, **kwargs) -> typing.Type: """Create a :class:`~doctor.types.Enum` type. :param description: A descrip...
Create a :class:`~doctor.types.Array` type. :param description: A description of the type. :param kwargs: Can include any attribute defined in :class:`~doctor.types.Array` def array(description, **kwargs) -> typing.Type: """Create a :class:`~doctor.types.Array` type. :param description: A des...
Create a user defined type. The new type will contain all attributes of the `cls` type passed in. Any attribute's value can be overwritten using kwargs. :param kwargs: Can include any attribute defined in the provided user defined type. def new_type(cls, **kwargs) -> typing.Type: """Create a ...
Returns an example value for the Dict type. If an example isn't a defined attribute on the class we return a dict of example values based on each property's annotation. def get_example(cls) -> dict: """Returns an example value for the Dict type. If an example isn't a defined attribute...
Returns an example value for the Array type. If an example isn't a defined attribute on the class we return a list of 1 item containing the example value of the `items` attribute. If `items` is None we simply return a `[1]`. def get_example(cls) -> list: """Returns an example value for...
Renders node from xml node def render_node(xml_node: XmlNode, **args) -> Node: """Renders node from xml node""" try: node = create_node(xml_node, **args) pipeline = get_pipeline(node) run_steps(node, pipeline, **args) return node except CoreError as error: error.add_...
Gets rendering pipeline for passed node def get_pipeline(node: Node) -> RenderingPipeline: """Gets rendering pipeline for passed node""" pipeline = _get_registered_pipeline(node) if pipeline is None: msg = _get_pipeline_registration_error_message(node) raise RenderingError(msg) return p...
Runs instance node rendering steps def run_steps(node: Node, pipeline: RenderingPipeline, **args): """Runs instance node rendering steps""" for step in pipeline.steps: result = step(node, pipeline=pipeline, **args) if isinstance(result, dict): args = {**args, **result}
Applies xml attributes to instance node and setups bindings def apply_attributes(node: Node, **_): """Applies xml attributes to instance node and setups bindings""" for attr in node.xml_node.attrs: apply_attribute(node, attr)
Maps xml attribute to instance node property and setups bindings def apply_attribute(node: Node, attr: XmlAttr): """Maps xml attribute to instance node property and setups bindings""" setter = get_setter(attr) stripped_value = attr.value.strip() if attr.value else '' if is_expression(stripped_value): ...
Calls node setter def call_set_attr(node: Node, key: str, value): """Calls node setter""" node.set_attr(key, value)
Render node children def render_children(node: Node, **child_args): """Render node children""" for xml_node in node.xml_node.children: child = render(xml_node, **child_args) node.add_child(child)
Return list of all columns. def all_columns(self): """Return list of all columns.""" columns = set() for values in self._parts: for value in values._parts: columns.add(value.column_name) return sorted(columns)
Find the _schema_annotation attribute for the given function. This will descend through decorators until it finds something that has the attribute. If it doesn't find it anywhere, it will return None. :param func fn: Find the attribute on this function. :returns: an instance of ...
Create a JSON schema for a request. :param list params: A list of keys specifying which definitions from the base schema should be allowed in the request. :param list required: A subset of the params that the requester must specify in the request. :returns: a JSON schema...
Update an existing note. def update_note(note_id: NoteId, body: Body=None, done: Done=None) -> Note: """Update an existing note.""" if note_id != 1: raise NotFoundError('Note does not exist') new_note = note.copy() if body is not None: new_note['body'] = body if done is not None: ...
Return a task object representing this message. def to_task(self): """Return a task object representing this message.""" from google.appengine.api.taskqueue import Task task_args = self.get_task_args().copy() payload = None if 'payload' in task_args: payload = task...
Insert the pull task into the requested queue, 'default' if non given. def insert(self): """Insert the pull task into the requested queue, 'default' if non given. """ from google.appengine.api.taskqueue import Queue task = self.to_task() Queue(name=self.get_que...
Return this message as a dict suitable for json encoding. def to_dict(self): """Return this message as a dict suitable for json encoding.""" import copy options = copy.deepcopy(self._options) # JSON don't like datetimes. eta = options.get('task_args', {}).get('eta') if...
If this message has no id, generate one. def _get_id(self): """If this message has no id, generate one.""" id = self._options.get('id') if id: return id id = uuid.uuid4().hex self.update_options(id=id) return id
Return an message from a dict output by Async.to_dict. def from_dict(cls, message): """Return an message from a dict output by Async.to_dict.""" message_options = message.copy() # JSON don't like datetimes. eta = message_options.get('task_args', {}).get('eta') if eta: ...
Return a task object representing this MessageProcessor job. def to_task(self): """Return a task object representing this MessageProcessor job.""" task_args = self.get_task_args() # check for name in task args name = task_args.get('name', MESSAGE_PROCESSOR_NAME) # if the count...
Return the batch id for the tag. :return: :class: `int` current batch id def current_batch(self): """Return the batch id for the tag. :return: :class: `int` current batch id """ current_batch = memcache.get(self.group_key) if not current_batch: memcache.ad...
Fetch messages from the specified pull-queue. This should only be called a single time by a given MessageIterator object. If the MessageIterator is iterated over again, it should return the originally leased messages. def fetch_messages(self): """Fetch messages from the specified pull...
Get the next batch of messages from the previously fetched messages. If there's no more messages, check if we should auto-delete the messages and raise StopIteration. def next(self): """Get the next batch of messages from the previously fetched messages. If there's no more messages, c...
Delete the messages previously leased. Unless otherwise directed, only the messages iterated over will be deleted. def delete_messages(self, only_processed=True): """Delete the messages previously leased. Unless otherwise directed, only the messages iterated over will be delet...
Returns a copy of a function. :param func: The function to copy. :returns: The copied function. def copy_func(func: Callable) -> Callable: """Returns a copy of a function. :param func: The function to copy. :returns: The copied function. """ copied = types.FunctionType( func.__cod...
Gets all parameters from a function signature. :param func: The function to inspect. :param signature: An inspect.Signature instance. :returns: A named tuple containing information about all, optional, required and logic function parameters. def get_params_from_func(func: Callable, signature: Sign...
Adds parameter annotations to a logic function. This adds additional required and/or optional parameters to the logic function that are not part of it's signature. It's intended to be used by decorators decorating logic functions or middleware. :param logic: The logic function to add the parameter an...
Get an attribute from a module. This uses exec to load the module with a private namespace, and then plucks and returns the given attribute from that module's namespace. Note that, while this method doesn't have any explicit unit tests, it is tested implicitly by the doctor's own documentation. The Sp...
Extract the description from the given docstring. This grabs everything up to the first occurrence of something that looks like a parameter description. The docstring will be dedented and cleaned up using the standard Sphinx methods. :param str docstring: The source docstring. :returns: list def ...
Return the given string converted so that it can be used for a class name Remove leading and trailing spaces; removes spaces and capitalizes each word; and remove anything that is not alphanumeric. Returns a pep8 compatible class name. :param s: The string to convert. :returns: The updated string...
Instantiate a new _ExecutionContext and store a reference to it in the global async context to make later retrieval easier. def execution_context_from_async(async): """Instantiate a new _ExecutionContext and store a reference to it in the global async context to make later retrieval easier. """ loc...
Use cli.get_session to open CLI connection and switch into required mode :param CommandMode command_mode: operation mode, can be default_mode/enable_mode/config_mode/etc. :return: created session in provided mode :rtype: CommandModeContextManager def get_cli_service(self, command_mode): ...
Function that identifies whether two crystals are equivalent def check_crystal_equivalence(crystal_a, crystal_b): """Function that identifies whether two crystals are equivalent""" # getting symmetry datasets for both crystals cryst_a = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_a), symprec=1e-5, ...
Adds view information to error message def add_view_info(self, view_info: ViewInfo): '''Adds view information to error message''' try: next(info for info in self._view_infos if info.view == view_info.view) except StopIteration: indent = len(self._view_infos) * '\t' ...
Adds "header: message" line to error message def add_info(self, header, message): '''Adds "header: message" line to error message''' current_message = self.args[0] message = current_message + self._format_info(header, message) self.args = (message,) + self.args[1:]