INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Function that specifies the interaction with a: class:. ResourceQueue upon departure.
def queue_action(self, queue, *args, **kwargs): """Function that specifies the interaction with a :class:`.ResourceQueue` upon departure. When departuring from a :class:`.ResourceQueue` (or a :class:`.QueueServer`), this method is called. If the agent does not already have a res...
Simulates the queue forward one event.
def next_event(self): """Simulates the queue forward one event. This method behaves identically to a :class:`.LossQueue` if the arriving/departing agent is anything other than a :class:`.ResourceAgent`. The differences are; Arriving: * If the :class:`.ResourceAgent` ha...
Returns the number of elements in the set that s belongs to.
def size(self, s): """Returns the number of elements in the set that ``s`` belongs to. Parameters ---------- s : object An object Returns ------- out : int The number of elements in the set that ``s`` belongs to. """ leade...
Locates the leader of the set to which the element s belongs.
def find(self, s): """Locates the leader of the set to which the element ``s`` belongs. Parameters ---------- s : object An object that the ``UnionFind`` contains. Returns ------- object The leader of the set that contains ``s``. ...
Merges the set that contains a with the set that contains b.
def union(self, a, b): """Merges the set that contains ``a`` with the set that contains ``b``. Parameters ---------- a, b : objects Two objects whose sets are to be merged. """ s1, s2 = self.find(a), self.find(b) if s1 != s2: r1, r2 = sel...
Generates a random transition matrix for the graph g.
def generate_transition_matrix(g, seed=None): """Generates a random transition matrix for the graph ``g``. Parameters ---------- g : :any:`networkx.DiGraph`, :class:`numpy.ndarray`, dict, etc. Any object that :any:`DiGraph<networkx.DiGraph>` accepts. seed : int (optional) An integer...
Creates a random graph where the edges have different types.
def generate_random_graph(num_vertices=250, prob_loop=0.5, **kwargs): """Creates a random graph where the edges have different types. This method calls :func:`.minimal_random_graph`, and then adds a loop to each vertex with ``prob_loop`` probability. It then calls :func:`.set_types_random` on the resul...
Creates a random graph where the vertex types are selected using their pagerank.
def generate_pagerank_graph(num_vertices=250, **kwargs): """Creates a random graph where the vertex types are selected using their pagerank. Calls :func:`.minimal_random_graph` and then :func:`.set_types_rank` where the ``rank`` keyword argument is given by :func:`networkx.pagerank`. Parameter...
Creates a connected graph with random vertex locations.
def minimal_random_graph(num_vertices, seed=None, **kwargs): """Creates a connected graph with random vertex locations. Parameters ---------- num_vertices : int The number of vertices in the graph. seed : int (optional) An integer used to initialize numpy's psuedorandom number ...
Randomly sets edge_type ( edge type ) properties of the graph.
def set_types_random(g, proportions=None, loop_proportions=None, seed=None, **kwargs): """Randomly sets ``edge_type`` (edge type) properties of the graph. This function randomly assigns each edge a type. The probability of an edge being a specific type is proscribed in the ``propor...
Creates a stylized graph. Sets edge and types using pagerank _.
def set_types_rank(g, rank, pType2=0.1, pType3=0.1, seed=None, **kwargs): """Creates a stylized graph. Sets edge and types using `pagerank`_. This function sets the edge types of a graph to be either 1, 2, or 3. It sets the vertices to type 2 by selecting the top ``pType2 * g.number_of_nodes()`` vertic...
Strip # markers at the front of a block of comment text.
def strip_comment_marker(text): """ Strip # markers at the front of a block of comment text. """ lines = [] for line in text.splitlines(): lines.append(line.lstrip('#')) text = textwrap.dedent('\n'.join(lines)) return text
Yield all of the documentation for trait definitions on a class object.
def get_class_traits(klass): """ Yield all of the documentation for trait definitions on a class object. """ # FIXME: gracefully handle errors here or in the caller? source = inspect.getsource(klass) cb = CommentBlocker() cb.process_file(StringIO(source)) mod_ast = compiler.parse(source) ...
Add lines to the block.
def add(self, string, start, end, line): """ Add lines to the block. """ if string.strip(): # Only add if not entirely whitespace. self.start_lineno = min(self.start_lineno, start[0]) self.end_lineno = max(self.end_lineno, end[0])
Process a file object.
def process_file(self, file): """ Process a file object. """ if sys.version_info[0] >= 3: nxt = file.__next__ else: nxt = file.next for token in tokenize.generate_tokens(nxt): self.process_token(*token) self.make_index()
Process a single token.
def process_token(self, kind, string, start, end, line): """ Process a single token. """ if self.current_block.is_comment: if kind == tokenize.COMMENT: self.current_block.add(string, start, end, line) else: self.new_noncomment(start[0], end...
We are transitioning from a noncomment to a comment.
def new_noncomment(self, start_lineno, end_lineno): """ We are transitioning from a noncomment to a comment. """ block = NonComment(start_lineno, end_lineno) self.blocks.append(block) self.current_block = block
Possibly add a new comment.
def new_comment(self, string, start, end, line): """ Possibly add a new comment. Only adds a new comment if this comment is the only thing on the line. Otherwise, it extends the noncomment block. """ prefix = line[:start[1]] if prefix.strip(): # Oops! Trailin...
Make the index mapping lines of actual code to their associated prefix comments.
def make_index(self): """ Make the index mapping lines of actual code to their associated prefix comments. """ for prev, block in zip(self.blocks[:-1], self.blocks[1:]): if not block.is_comment: self.index[block.start_lineno] = prev
Find the comment block just before the given line number.
def search_for_comment(self, lineno, default=None): """ Find the comment block just before the given line number. Returns None (or the specified default) if there is no such block. """ if not self.index: self.make_index() block = self.index.get(lineno, None) ...
Adds configuration files to tarfile instance.
def _generate_contents(self, tar): """ Adds configuration files to tarfile instance. :param tar: tarfile instance :returns: None """ uci = self.render(files=False) # create a list with all the packages (and remove empty entries) packages = packages_patter...
Loads config from string or dict
def _load(self, config): """ Loads config from string or dict """ if isinstance(config, six.string_types): try: config = json.loads(config) except ValueError: pass if not isinstance(config, dict): raise TypeError...
Merges config with templates
def _merge_config(self, config, templates): """ Merges config with templates """ if not templates: return config # type check if not isinstance(templates, list): raise TypeError('templates argument must be an instance of list') # merge temp...
Renders additional files specified in self. config [ files ]
def _render_files(self): """ Renders additional files specified in ``self.config['files']`` """ output = '' # render files files = self.config.get('files', []) # add delimiter if files: output += '\n{0}\n\n'.format(self.FILE_SECTION_DELIMITER) ...
Converts the configuration dictionary into the corresponding configuration format
def render(self, files=True): """ Converts the configuration dictionary into the corresponding configuration format :param files: whether to include "additional files" in the output or not; defaults to ``True`` :returns: string with output """ self....
returns a string formatted as ** NetJSON DeviceConfiguration ** ; performs validation before returning output ;
def json(self, validate=True, *args, **kwargs): """ returns a string formatted as **NetJSON DeviceConfiguration**; performs validation before returning output; ``*args`` and ``*kwargs`` will be passed to ``json.dumps``; :returns: string """ if validate: ...
Returns a BytesIO instance representing an in - memory tar. gz archive containing the native router configuration.
def generate(self): """ Returns a ``BytesIO`` instance representing an in-memory tar.gz archive containing the native router configuration. :returns: in-memory tar.gz archive, instance of ``BytesIO`` """ tar_bytes = BytesIO() tar = tarfile.open(fileobj=tar_bytes,...
Like generate but writes to disk.
def write(self, name, path='./'): """ Like ``generate`` but writes to disk. :param name: file name, the tar.gz extension will be added automatically :param path: directory where the file will be written to, defaults to ``./`` :returns: None """ byte_object = self...
Adds files specified in self. config [ files ] to tarfile instance.
def _process_files(self, tar): """ Adds files specified in self.config['files'] to tarfile instance. :param tar: tarfile instance :returns: None """ # insert additional files for file_item in self.config.get('files', []): path = file_item['path'] ...
Adds a single file in tarfile instance.
def _add_file(self, tar, name, contents, mode=DEFAULT_FILE_MODE): """ Adds a single file in tarfile instance. :param tar: tarfile instance :param name: string representing filename or path :param contents: string representing file contents :param mode: string representin...
Converts the NetJSON configuration dictionary ( self. config ) to the intermediate data structure ( self. intermediate_data ) that will be then used by the renderer class to generate the router configuration
def to_intermediate(self): """ Converts the NetJSON configuration dictionary (self.config) to the intermediate data structure (self.intermediate_data) that will be then used by the renderer class to generate the router configuration """ self.validate() self.interm...
Parses a native configuration and converts it to a NetJSON configuration dictionary
def parse(self, native): """ Parses a native configuration and converts it to a NetJSON configuration dictionary """ if not hasattr(self, 'parser') or not self.parser: raise NotImplementedError('Parser class not specified') parser = self.parser(native) ...
Converts the intermediate data structure ( self. intermediate_data ) to the NetJSON configuration dictionary ( self. config )
def to_netjson(self): """ Converts the intermediate data structure (self.intermediate_data) to the NetJSON configuration dictionary (self.config) """ self.__backup_intermediate_data() self.config = OrderedDict() for converter_class in self.converters: ...
Merges config on top of template.
def merge_config(template, config, list_identifiers=None): """ Merges ``config`` on top of ``template``. Conflicting keys are handled in the following way: * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will overwrite the ones in ``template`` * values of type ``list`` i...
Merges list2 on top of list1.
def merge_list(list1, list2, identifiers=None): """ Merges ``list2`` on top of ``list1``. If both lists contain dictionaries which have keys specified in ``identifiers`` which have equal values, those dicts will be merged (dicts in ``list2`` will override dicts in ``list1``). The remaining elem...
Evaluates variables in data
def evaluate_vars(data, context=None): """ Evaluates variables in ``data`` :param data: data structure containing variables, may be ``str``, ``dict`` or ``list`` :param context: ``dict`` containing variables :returns: modified data structure """ context = context or {} ...
Looks for a key in a dictionary if found returns a deepcopied value otherwise returns default value
def get_copy(dict_, key, default=None): """ Looks for a key in a dictionary, if found returns a deepcopied value, otherwise returns default value """ value = dict_.get(key, default) if value: return deepcopy(value) return value
Loops over item and performs type casting according to supplied schema fragment
def type_cast(self, item, schema=None): """ Loops over item and performs type casting according to supplied schema fragment """ if schema is None: schema = self._schema properties = schema['properties'] for key, value in item.items(): if ke...
Converts the NetJSON configuration dictionary ( self. config ) to intermediate data structure ( self. intermediate_datra )
def to_intermediate(self): """ Converts the NetJSON configuration dictionary (``self.config``) to intermediate data structure (``self.intermediate_datra``) """ result = OrderedDict() # copy netjson dictionary netjson = get_copy(self.netjson, self.netjson_key) ...
Converts the intermediate data structure ( self. intermediate_datra ) to a NetJSON configuration dictionary ( self. config )
def to_netjson(self, remove_block=True): """ Converts the intermediate data structure (``self.intermediate_datra``) to a NetJSON configuration dictionary (``self.config``) """ result = OrderedDict() # copy list intermediate_data = list(self.intermediate_data[self....
adds a file in self. config [ files ] only if not present already
def _add_unique_file(self, item): """ adds a file in self.config['files'] only if not present already """ if item not in self.config['files']: self.config['files'].append(item)
returns the template context for install. sh and uninstall. sh
def _get_install_context(self): """ returns the template context for install.sh and uninstall.sh """ config = self.config # layer2 VPN list l2vpn = [] for vpn in self.config.get('openvpn', []): if vpn.get('dev_type') != 'tap': continue ...
generates install. sh and adds it to included files
def _add_install(self, context): """ generates install.sh and adds it to included files """ contents = self._render_template('install.sh', context) self.config.setdefault('files', []) # file list might be empty # add install.sh to list of included files self._add...
generates uninstall. sh and adds it to included files
def _add_uninstall(self, context): """ generates uninstall.sh and adds it to included files """ contents = self._render_template('uninstall.sh', context) self.config.setdefault('files', []) # file list might be empty # add uninstall.sh to list of included files s...
generates tc_script. sh and adds it to included files
def _add_tc_script(self): """ generates tc_script.sh and adds it to included files """ # fill context context = dict(tc_options=self.config.get('tc_options', [])) # import pdb; pdb.set_trace() contents = self._render_template('tc_script.sh', context) self....
Adds configuration files to tarfile instance.
def _generate_contents(self, tar): """ Adds configuration files to tarfile instance. :param tar: tarfile instance :returns: None """ uci = self.render(files=False) # create a list with all the packages (and remove empty entries) packages = re.split('packa...
Renders configuration by using the jinja2 templating engine
def render(self): """ Renders configuration by using the jinja2 templating engine """ # get jinja2 template template_name = '{0}.jinja2'.format(self.get_name()) template = self.template_env.get_template(template_name) # render template and cleanup context ...
converts NetJSON address to UCI intermediate data structure
def __intermediate_addresses(self, interface): """ converts NetJSON address to UCI intermediate data structure """ address_list = self.get_copy(interface, 'addresses') # do not ignore interfaces if they do not contain any address if not address_list: r...
converts NetJSON interface to UCI intermediate data structure
def __intermediate_interface(self, interface, uci_name): """ converts NetJSON interface to UCI intermediate data structure """ interface.update({ '.type': 'interface', '.name': uci_name, 'ifname': interface.pop('name') }) if 'ne...
deletes NetJSON address keys
def __intermediate_address(self, address): """ deletes NetJSON address keys """ for key in self._address_keys: if key in address: del address[key] return address
converts NetJSON bridge to UCI intermediate data structure
def __intermediate_bridge(self, interface, i): """ converts NetJSON bridge to UCI intermediate data structure """ # ensure type "bridge" is only given to one logical interface if interface['type'] == 'bridge' and i < 2: bridge_members = ' '.join(interface.pop(...
determines UCI interface proto option
def __intermediate_proto(self, interface, address): """ determines UCI interface "proto" option """ # proto defaults to static address_proto = address.pop('proto', 'static') if 'proto' not in interface: return address_proto else: # allow ov...
determines UCI interface dns option
def __intermediate_dns_servers(self, uci, address): """ determines UCI interface "dns" option """ # allow override if 'dns' in uci: return uci['dns'] # ignore if using DHCP or if "proto" is none if address['proto'] in ['dhcp', 'dhcpv6', 'none']: ...
determines UCI interface dns_search option
def __intermediate_dns_search(self, uci, address): """ determines UCI interface "dns_search" option """ # allow override if 'dns_search' in uci: return uci['dns_search'] # ignore if "proto" is none if address['proto'] == 'none': return None...
Returns a list of violated schema fragments and related error messages: param e: jsonschema. exceptions. ValidationError instance
def _list_errors(e): """ Returns a list of violated schema fragments and related error messages :param e: ``jsonschema.exceptions.ValidationError`` instance """ error_list = [] for value, error in zip(e.validator_value, e.context): error_list.append((value, error.message)) if err...
possible return values are: 11a 11b 11g
def __intermediate_hwmode(self, radio): """ possible return values are: 11a, 11b, 11g """ protocol = radio['protocol'] if protocol in ['802.11a', '802.11b', '802.11g']: # return 11a, 11b or 11g return protocol[4:] # determine hwmode depending on ch...
only for mac80211 driver
def __intermediate_htmode(self, radio): """ only for mac80211 driver """ protocol = radio.pop('protocol') channel_width = radio.pop('channel_width') # allow overriding htmode if 'htmode' in radio: return radio['htmode'] if protocol == '802.11n'...
determines NetJSON protocol radio attribute
def __netjson_protocol(self, radio): """ determines NetJSON protocol radio attribute """ htmode = radio.get('htmode') hwmode = radio.get('hwmode', None) if htmode.startswith('HT'): return '802.11n' elif htmode.startswith('VHT'): return '802...
determines NetJSON channel_width radio attribute
def __netjson_channel_width(self, radio): """ determines NetJSON channel_width radio attribute """ htmode = radio.pop('htmode') if htmode == 'NONE': return 20 channel_width = htmode.replace('VHT', '').replace('HT', '') # we need to override htmode ...
Generates consistent OpenWRT/ LEDE UCI output
def cleanup(self, output): """ Generates consistent OpenWRT/LEDE UCI output """ # correct indentation output = output.replace(' ', '')\ .replace('\noption', '\n\toption')\ .replace('\nlist', '\n\tlist') # convert True to 1 ...
Adds configuration files to tarfile instance.
def _generate_contents(self, tar): """ Adds configuration files to tarfile instance. :param tar: tarfile instance :returns: None """ text = self.render(files=False) # create a list with all the packages (and remove empty entries) vpn_instances = vpn_patte...
Returns a configuration dictionary representing an OpenVPN client configuration that is compatible with the passed server configuration.
def auto_client(cls, host, server, ca_path=None, ca_contents=None, cert_path=None, cert_contents=None, key_path=None, key_contents=None): """ Returns a configuration dictionary representing an OpenVPN client configuration that is compatible with the passed...
returns a list of NetJSON extra files for automatically generated clients produces side effects in client dictionary
def _auto_client_files(cls, client, ca_path=None, ca_contents=None, cert_path=None, cert_contents=None, key_path=None, key_contents=None): """ returns a list of NetJSON extra files for automatically generated clients produces side effects in ``client`` dictionary ...
parse requirements. txt ignore links exclude comments
def get_install_requires(): """ parse requirements.txt, ignore links, exclude comments """ requirements = [] for line in open('requirements.txt').readlines(): # skip to next iteration if comment or empty line if line.startswith('#') or line == '' or line.startswith('http') or line.st...
Get all events for this report. Additional arguments may also be specified that will be passed to the query function.
def events(self, **kwargs): """Get all events for this report. Additional arguments may also be specified that will be passed to the query function. """ return self.__api.events(query=EqualsOperator("report", self.hash_), **kwargs)
Get all facts of this node. Additional arguments may also be specified that will be passed to the query function.
def facts(self, **kwargs): """Get all facts of this node. Additional arguments may also be specified that will be passed to the query function. """ return self.__api.facts(query=EqualsOperator("certname", self.name), **kwargs)
Get a single fact from this node.
def fact(self, name): """Get a single fact from this node.""" facts = self.facts(name=name) return next(fact for fact in facts)
Get all resources of this node or all resources of the specified type. Additional arguments may also be specified that will be passed to the query function.
def resources(self, type_=None, title=None, **kwargs): """Get all resources of this node or all resources of the specified type. Additional arguments may also be specified that will be passed to the query function. """ if type_ is None: resources = self.__api.resource...
Get a resource matching the supplied type and title. Additional arguments may also be specified that will be passed to the query function.
def resource(self, type_, title, **kwargs): """Get a resource matching the supplied type and title. Additional arguments may also be specified that will be passed to the query function. """ resources = self.__api.resources( type_=type_, title=title, ...
Get all reports for this node. Additional arguments may also be specified that will be passed to the query function.
def reports(self, **kwargs): """Get all reports for this node. Additional arguments may also be specified that will be passed to the query function. """ return self.__api.reports( query=EqualsOperator("certname", self.name), **kwargs)
A base_url that will be used to construct the final URL we re going to query against.
def base_url(self): """A base_url that will be used to construct the final URL we're going to query against. :returns: A URL of the form: ``proto://host:port``. :rtype: :obj:`string` """ return '{proto}://{host}:{port}{url_path}'.format( proto=self.protocol, ...
The complete URL we will end up querying. Depending on the endpoint we pass in this will result in different URL s with different prefixes.
def _url(self, endpoint, path=None): """The complete URL we will end up querying. Depending on the endpoint we pass in this will result in different URL's with different prefixes. :param endpoint: The PuppetDB API endpoint we want to query. :type endpoint: :obj:`string` ...
This method actually querries PuppetDB. Provided an endpoint and an optional path and/ or query it will fire a request at PuppetDB. If PuppetDB can be reached and answers within the timeout we ll decode the response and give it back or raise for the HTTP Status Code PuppetDB gave back.
def _query(self, endpoint, path=None, query=None, order_by=None, limit=None, offset=None, include_total=False, summarize_by=None, count_by=None, count_filter=None, request_method='GET'): """This method actually querries PuppetDB. Provided an endpoint and an o...
Query for nodes by either name or query. If both aren t provided this will return a list of all nodes. This method also fetches the nodes status and event counts of the latest report from puppetdb.
def nodes(self, unreported=2, with_status=False, **kwargs): """Query for nodes by either name or query. If both aren't provided this will return a list of all nodes. This method also fetches the nodes status and event counts of the latest report from puppetdb. :param with_status...
Gets a single node from PuppetDB.
def node(self, name): """Gets a single node from PuppetDB. :param name: The name of the node search. :type name: :obj:`string` :return: An instance of Node :rtype: :class:`pypuppetdb.types.Node` """ nodes = self.nodes(path=name) return next(node for node...
Get the known catalog edges formed between two resources.
def edges(self, **kwargs): """Get the known catalog edges, formed between two resources. :param \*\*kwargs: The rest of the keyword arguments are passed to the _query function. :returns: A generating yielding Edges. :rtype: :class:`pypuppetdb.types.Edge` ...
Query for facts limited by either name value and/ or query.
def facts(self, name=None, value=None, **kwargs): """Query for facts limited by either name, value and/or query. :param name: (Optional) Only return facts that match this name. :type name: :obj:`string` :param value: (Optional) Only return facts of `name` that\ match this va...
Query for resources limited by either type and/ or title or query. This will yield a Resources object for every returned resource.
def resources(self, type_=None, title=None, **kwargs): """Query for resources limited by either type and/or title or query. This will yield a Resources object for every returned resource. :param type_: (Optional) The resource type. This can be any resource type referenced in\ ...
Get the available catalog for a given node.
def catalog(self, node): """Get the available catalog for a given node. :param node: (Required) The name of the PuppetDB node. :type: :obj:`string` :returns: An instance of Catalog :rtype: :class:`pypuppetdb.types.Catalog` """ catalogs = self.catalogs(path=node)...
Get the catalog information from the infrastructure based on path and/ or query results. It is strongly recommended to include query and/ or paging parameters for this endpoint to prevent large result sets or PuppetDB performance bottlenecks.
def catalogs(self, **kwargs): """Get the catalog information from the infrastructure based on path and/or query results. It is strongly recommended to include query and/or paging parameters for this endpoint to prevent large result sets or PuppetDB performance bottlenecks. :para...
A report is made up of events which can be queried either individually or based on their associated report hash. It is strongly recommended to include query and/ or paging parameters for this endpoint to prevent large result sets or PuppetDB performance bottlenecks.
def events(self, **kwargs): """A report is made up of events which can be queried either individually or based on their associated report hash. It is strongly recommended to include query and/or paging parameters for this endpoint to prevent large result sets or PuppetDB performance ...
Get event counts from puppetdb aggregated into a single map.
def aggregate_event_counts(self, summarize_by, query=None, count_by=None, count_filter=None): """Get event counts from puppetdb aggregated into a single map. :param summarize_by: (Required) The object type to be counted on. Valid values are 'c...
Get reports for our infrastructure. It is strongly recommended to include query and/ or paging parameters for this endpoint to prevent large result sets and potential PuppetDB performance bottlenecks.
def reports(self, **kwargs): """Get reports for our infrastructure. It is strongly recommended to include query and/or paging parameters for this endpoint to prevent large result sets and potential PuppetDB performance bottlenecks. :param \*\*kwargs: The rest of the keyword argu...
Get Node and Fact information with an alternative query syntax for structured facts instead of using the facts fact - contents and factsets endpoints for many fact - related queries.
def inventory(self, **kwargs): """Get Node and Fact information with an alternative query syntax for structured facts instead of using the facts, fact-contents and factsets endpoints for many fact-related queries. :param \*\*kwargs: The rest of the keyword arguments are passed ...
Compares two objects x and y and returns an integer according to the outcome. The return value is negative if x < y zero if x == y and positive if x > y.
def versioncmp(v1, v2): """Compares two objects, x and y, and returns an integer according to the outcome. The return value is negative if x < y, zero if x == y and positive if x > y. :param v1: The first object to compare. :param v2: The second object to compare. :returns: -1, 0 or 1. :rt...
Connect with PuppetDB. This will return an object allowing you to query the API through its methods.
def connect(host='localhost', port=8080, ssl_verify=False, ssl_key=None, ssl_cert=None, timeout=10, protocol=None, url_path='/', username=None, password=None, token=None): """Connect with PuppetDB. This will return an object allowing you to query the API through its methods. :param ...
: type result: opendnp3. CommandPointResult
def collection_callback(result=None): """ :type result: opendnp3.CommandPointResult """ print("Header: {0} | Index: {1} | State: {2} | Status: {3}".format( result.headerIndex, result.index, opendnp3.CommandPointStateToString(result.state), opendnp3.CommandStatusToString...
: type result: opendnp3. ICommandTaskResult
def command_callback(result=None): """ :type result: opendnp3.ICommandTaskResult """ print("Received command result with summary: {}".format(opendnp3.TaskCompletionToString(result.summary))) result.ForeachItem(collection_callback)
The Master has been started from the command line. Execute ad - hoc tests if desired.
def main(): """The Master has been started from the command line. Execute ad-hoc tests if desired.""" # app = MyMaster() app = MyMaster(log_handler=MyLogger(), listener=AppChannelListener(), soe_handler=SOEHandler(), master_application=MasterApplicati...
Direct operate a single command
def send_direct_operate_command(self, command, index, callback=asiodnp3.PrintingCommandCallback.Get(), config=opendnp3.TaskConfig().Default()): """ Direct operate a single command :param command: command to operate :param index: index of the comma...
Direct operate a set of commands
def send_direct_operate_command_set(self, command_set, callback=asiodnp3.PrintingCommandCallback.Get(), config=opendnp3.TaskConfig().Default()): """ Direct operate a set of commands :param command_set: set of command headers :param callback: c...
Select and operate a single command
def send_select_and_operate_command(self, command, index, callback=asiodnp3.PrintingCommandCallback.Get(), config=opendnp3.TaskConfig().Default()): """ Select and operate a single command :param command: command to operate :param index: index ...
Select and operate a set of commands
def send_select_and_operate_command_set(self, command_set, callback=asiodnp3.PrintingCommandCallback.Get(), config=opendnp3.TaskConfig().Default()): """ Select and operate a set of commands :param command_set: set of command headers :param...
Process measurement data.
def Process(self, info, values): """ Process measurement data. :param info: HeaderInfo :param values: A collection of values received from the Outstation (various data types are possible). """ visitor_class_types = { opendnp3.ICollectionIndexedBinary: Vis...
The Outstation has been started from the command line. Execute ad - hoc tests if desired.
def main(): """The Outstation has been started from the command line. Execute ad-hoc tests if desired.""" app = OutstationApplication() _log.debug('Initialization complete. In command loop.') # Ad-hoc tests can be inserted here if desired. See outstation_cmd.py for examples. app.shutdown() _log....
Set up the OpenDNP3 configuration.
def configure_stack(): """Set up the OpenDNP3 configuration.""" stack_config = asiodnp3.OutstationStackConfig(opendnp3.DatabaseSizes.AllTypes(10)) stack_config.outstation.eventBufferConfig = opendnp3.EventBufferConfig().AllTypes(10) stack_config.outstation.params.allowUnsolicited = True ...
Configure the Outstation s database of input point definitions.
def configure_database(db_config): """ Configure the Outstation's database of input point definitions. Configure two Analog points (group/variation 30.1) at indexes 1 and 2. Configure two Binary points (group/variation 1.2) at indexes 1 and 2. """ db_config.a...
Return the application - controlled IIN field.
def GetApplicationIIN(self): """Return the application-controlled IIN field.""" application_iin = opendnp3.ApplicationIIN() application_iin.configCorrupt = False application_iin.deviceTrouble = False application_iin.localControl = False application_iin.needTime = False ...
A PointValue was received from the Master. Process its payload.
def process_point_value(cls, command_type, command, index, op_type): """ A PointValue was received from the Master. Process its payload. :param command_type: (string) Either 'Select' or 'Operate'. :param command: A ControlRelayOutputBlock or else a wrapped data value (AnalogOutputIn...
Record an opendnp3 data value ( Analog Binary etc. ) in the outstation s database.
def apply_update(self, value, index): """ Record an opendnp3 data value (Analog, Binary, etc.) in the outstation's database. The data value gets sent to the Master as a side-effect. :param value: An instance of Analog, Binary, or another opendnp3 data value. :param inde...