text
stringlengths
81
112k
Produces a list of files and and formats it for Files class. Requires fixed_width filename Parameters ---------- data_path : string Top level directory to search files for. This directory is provided by pysat to the instrument_module.list_files ...
Adds metadata variables to self that are in other but not in self. Parameters ---------- other : pysat.Meta def merge(self, other): """Adds metadata variables to self that are in other but not in self. Parameters ---------- other : pysat.Meta ...
Drops variables (names) from metadata. def drop(self, names): """Drops variables (names) from metadata.""" # drop lower dimension data self._data = self._data.drop(names, axis=0) # drop higher dimension data for name in names: if name in self._ho_data: ...
Keeps variables (keep_names) while dropping other parameters def keep(self, keep_names): """Keeps variables (keep_names) while dropping other parameters""" current_names = self._data.columns drop_names = [] for name in current_names: if name not in keep_names: ...
Applies labels for default meta labels from self onto other. Parameters ---------- other : Meta Meta object to have default labels applied Returns ------- Meta def apply_default_labels(self, other): """Applies labels for default meta...
Applies labels for default meta labels from other onto self. Parameters ---------- other : Meta Meta object to take default labels from Returns ------- Meta def accept_default_labels(self, other): """Applies labels for default meta l...
Generalized setter of default meta attributes Parameters ---------- new_label : str New label to use in the Meta object current_label : str The hidden attribute to be updated that actually stores metadata default : Deafult setting to ...
Provides stored name (case preserved) for case insensitive input If name is not found (case-insensitive check) then name is returned, as input. This function is intended to be used to help ensure the case of a given variable name is the same across the Meta object. Para...
Returns boolean indicating presence of given attribute name Case-insensitive check Notes ----- Does not check higher order meta objects Parameters ---------- name : str name of variable to get stored case form ...
Returns preserved case name for case insensitive value of name. Checks first within standard attributes. If not found there, checks attributes for higher order data structures. If not found, returns supplied name as it is available for use. Intended to be used to help ensure tha...
Concats two metadata objects together. Parameters ---------- other : Meta Meta object to be concatenated strict : bool if True, ensure there are no duplicate variable names Notes ----- Uses units and name label of self if other is differe...
Remove and return metadata about variable Parameters ---------- name : str variable name Returns ------- pandas.Series Series of metadata for variable def pop(self, name): """Remove and return metadata about variable Parameters ...
Transfer non-standard attributes in Meta to Instrument object. Pysat's load_netCDF and similar routines are only able to attach netCDF4 attributes to a Meta object. This routine identifies these attributes and removes them from the Meta object. Intent is to support simple transfers to ...
Create instrument metadata object from csv. Parameters ---------- name : string absolute filename for csv file or name of file stored in pandas instruments location col_names : list-like collection of strings column names in csv and resultant meta obj...
Routine to return C/NOFS IVM data cleaned to the specified level Parameters ----------- inst : (pysat.Instrument) Instrument class object, whose attribute clean_level is used to return the desired level of data selectivity. Returns -------- Void : (NoneType) data in ins...
A signal receiver decorator that fetch the complete instance from db when it's passed as raw def nonraw_instance(receiver): """ A signal receiver decorator that fetch the complete instance from db when it's passed as raw """ @wraps(receiver) def wrapper(sender, instance, raw, using, **kwarg...
This is used to pass data required for deletion to the post_delete signal that is no more available thereafter. def base_definition_pre_delete(sender, instance, **kwargs): """ This is used to pass data required for deletion to the post_delete signal that is no more available thereafter. """ # s...
Make sure to delete fields inherited from an abstract model base. def base_definition_post_delete(sender, instance, **kwargs): """ Make sure to delete fields inherited from an abstract model base. """ if hasattr(instance._state, '_deletion'): # Make sure to flatten abstract bases since Django ...
When proxy field definitions are loaded from a fixture they're not passing through the `field_definition_post_save` signal. Make sure they are. def raw_field_definition_proxy_post_save(sender, instance, raw, **kwargs): """ When proxy field definitions are loaded from a fixture they're not passing t...
This signal is connected by all FieldDefinition subclasses see comment in FieldDefinitionBase for more details def field_definition_post_save(sender, instance, created, raw, **kwargs): """ This signal is connected by all FieldDefinition subclasses see comment in FieldDefinitionBase for more details ...
Useful for retrieving an object attr and removing it if it's part of it's dict while allowing retrieving from subclass. i.e. class A: a = 'a' class B(A): b = 'b' >>> popattr(B, 'a', None) 'a' >>> A.a 'a' def popattr(obj, attr, default=NOT_PROVIDED): """ Useful fo...
An helper that correctly deepcopy model cache state def _app_cache_deepcopy(obj): """ An helper that correctly deepcopy model cache state """ if isinstance(obj, defaultdict): return deepcopy(obj) elif isinstance(obj, dict): return type(obj)((_app_cache_deepcopy(key), _app_cache_deep...
A context manager that restore model cache state as it was before entering context. def app_cache_restorer(): """ A context manager that restore model cache state as it was before entering context. """ state = _app_cache_deepcopy(apps.__dict__) try: yield state finally: ...
Custom on_delete handler which sets _cascade_deletion_origin on the _state of the all relating objects that will deleted. We use this handler on ModelDefinitionAttribute.model_def, so when we delete a ModelDefinition we can skip field_definition_post_delete and base_definition_post_delete and avoid an...
Make sure all related model class are created and marked as dependency when a mutable model class is prepared def mutable_model_prepared(signal, sender, definition, existing_model_class, **kwargs): """ Make sure all related model class are created and marked as dependency whe...
Helper used to unpickle MutableModel model class from their definition pk. def _model_class_from_pk(definition_cls, definition_pk): """ Helper used to unpickle MutableModel model class from their definition pk. """ try: return definition_cls.objects.get(pk=definition_pk).model_class() ...
Make sure the lookup makes sense def clean(self): """ Make sure the lookup makes sense """ if self.lookup == '?': # Randomly sort return else: lookups = self.lookup.split(LOOKUP_SEP) opts = self.model_def.model_class()._meta valid...
Compute the time-derivative of a Lorentz system. def lorentz_deriv((x, y, z), t0, sigma=10., beta=8./3, rho=28.0): """Compute the time-derivative of a Lorentz system.""" return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]
Builds the parser for reading the command line arguments def buildParser(): ''' Builds the parser for reading the command line arguments''' parser = argparse.ArgumentParser(description='Bagfile reader') parser.add_argument('-b', '--bag', help='Bag file to read', required=True, type=...
Return which topics and which field keys need to be examined for plotting def parse_series_args(topics, fields): '''Return which topics and which field keys need to be examined for plotting''' keys = {} for field in fields: for topic in topics: if field.startswith(topic): ...
Read in a rosbag file and create a pandas data frame that is indexed by the time the message was recorded in the bag. :bag_name: String name for the bag file :include: None, String, or List Topics to include in the dataframe if None all topics added, if string it is used as regular ...
Find the length (# of rows) in the created dataframe def get_length(topics, yaml_info): ''' Find the length (# of rows) in the created dataframe ''' total = 0 info = yaml_info['topics'] for topic in topics: for t in info: if t['topic'] == topic: total = total...
Create a data map for usage when parsing the bag def create_data_map(msgs_to_read): ''' Create a data map for usage when parsing the bag ''' dmap = {} for topic in msgs_to_read.keys(): base_name = get_key_name(topic) + '__' fields = {} for f in msgs_to_read[topic]: ...
prune the topics. If include is None add all to the set of topics to use if include is a string regex match that string, if it is a list use the list If exclude is None do nothing, if string remove the topics with regex, if it is a list remove those topics def prune_topics(bag_topics, i...
Get info from all of the messages about what they contain and will be added to the dataframe def get_msg_info(yaml_info, topics, parse_header=True): ''' Get info from all of the messages about what they contain and will be added to the dataframe ''' topic_info = yaml_info['topics'] msgs = {...
Get uamle dict of the bag information by calling the subprocess -- used to create correct sized arrays def get_bag_info(bag_file): '''Get uamle dict of the bag information by calling the subprocess -- used to create correct sized arrays''' # Get the info on the bag bag_info = yaml.load(subp...
Returns the names of all of the topics in the bag, and prints them to stdout if requested def get_topics(yaml_info): ''' Returns the names of all of the topics in the bag, and prints them to stdout if requested ''' # Pull out the topic info names = [] # Store all of the topics in a ...
function to get the full names of every message field in the message def get_base_fields(msg, prefix='', parse_header=True): '''function to get the full names of every message field in the message''' slots = msg.__slots__ ret_val = [] msg_types = dict() for i in slots: slot_msg = getattr(ms...
get the datapoint from the dot delimited message field key e.g. translation.x looks up translation than x and returns the value found in x def get_message_data(msg, key): '''get the datapoint from the dot delimited message field key e.g. translation.x looks up translation than x and returns the value f...
Builds the parser for reading the command line arguments def buildParser(): ''' Builds the parser for reading the command line arguments''' parser = argparse.ArgumentParser( description='Script to parse bagfile to csv file') parser.add_argument('bag', help='Bag file to read', ...
Dump the payload to JSON def jsonify_payload(self): """ Dump the payload to JSON """ # Assume already json serialized if isinstance(self.payload, string_types): return self.payload return json.dumps(self.payload, cls=StandardJSONEncoder)
Send the webhook method def _send(self): """ Send the webhook method """ payload = self.payload sending_metadata = {'success': False} post_attributes = {'timeout': self.timeout} if self.custom_headers: post_attributes['headers'] = self.custom_headers if not...
:type signatureKey: ECPublicKey def verifySignature(self, signatureKey): """ :type signatureKey: ECPublicKey """ try: parts = ByteUtil.split(self.serialized, len(self.serialized) - self.__class__.SIGNATURE_LENGTH, ...
:type signatureKey: ECPrivateKey :type serialized: bytearray def getSignature(self, signatureKey, serialized): """ :type signatureKey: ECPrivateKey :type serialized: bytearray """ try: return Curve.calculateSignature(signatureKey, serialized) except I...
:param sessionRecord: :param message: :type message: PreKeyWhisperMessage def process(self, sessionRecord, message): """ :param sessionRecord: :param message: :type message: PreKeyWhisperMessage """ messageVersion = message.getMessageVersion() th...
:type sessionRecord: SessionRecord :type message: PreKeyWhisperMessage def processV2(self, sessionRecord, message): """ :type sessionRecord: SessionRecord :type message: PreKeyWhisperMessage """ if message.getPreKeyId() is None: raise InvalidKeyIdException("...
:param sessionRecord: :param message: :type message: PreKeyWhisperMessage :return: def processV3(self, sessionRecord, message): """ :param sessionRecord: :param message: :type message: PreKeyWhisperMessage :return: """ if sessionRecord.ha...
:type preKey: PreKeyBundle def processPreKeyBundle(self, preKey): """ :type preKey: PreKeyBundle """ if not self.identityKeyStore.isTrustedIdentity(self.recipientId, preKey.getIdentityKey()): raise UntrustedIdentityException(self.recipientId, preKey.getIdentityKey()) ...
:type senderKeyName: SenderKeyName :type senderKeyDistributionMessage: SenderKeyDistributionMessage def process(self, senderKeyName, senderKeyDistributionMessage): """ :type senderKeyName: SenderKeyName :type senderKeyDistributionMessage: SenderKeyDistributionMessage """ ...
:type senderKeyName: SenderKeyName def create(self, senderKeyName): """ :type senderKeyName: SenderKeyName """ try: senderKeyRecord = self.senderKeyStore.loadSenderKey(senderKeyName); if senderKeyRecord.isEmpty() : senderKeyRecord.setSenderKeySta...
:type sessionState: SessionState :type sessionVersion: int :type parameters: SymmetricAxolotlParameters def initializeSession(sessionState, sessionVersion, parameters): """ :type sessionState: SessionState :type sessionVersion: int :type parameters: SymmetricAxolotlParam...
:type sessionState: SessionState :type sessionVersion: int :type parameters: AliceAxolotlParameters def initializeSessionAsAlice(sessionState, sessionVersion, parameters): """ :type sessionState: SessionState :type sessionVersion: int :type parameters: AliceAxolotlParame...
:type sessionState: SessionState :type sessionVersion: int :type parameters: BobAxolotlParameters def initializeSessionAsBob(sessionState, sessionVersion, parameters): """ :type sessionState: SessionState :type sessionVersion: int :type parameters: BobAxolotlParameters ...
:type id: int :type iteration: int :type chainKey: bytearray :type signatureKey: ECPublicKey def addSenderKeyState(self, id, iteration, chainKey, signatureKey): """ :type id: int :type iteration: int :type chainKey: bytearray :type signatureKey: ECPublicK...
:type id: int :type iteration: int :type chainKey: bytearray :type signatureKey: ECKeyPair def setSenderKeyState(self, id, iteration, chainKey, signatureKey): """ :type id: int :type iteration: int :type chainKey: bytearray :type signatureKey: ECKeyPair ...
:type paddedMessage: str def encrypt(self, paddedMessage): """ :type paddedMessage: str """ # TODO: make this less ugly and python 2 and 3 compatible # paddedMessage = bytearray(paddedMessage.encode() if (sys.version_info >= (3, 0) and not type(paddedMessage) in (bytes, bytearra...
:type ciphertext: WhisperMessage :type textMsg: Bool set this to False if you are decrypting bytes instead of string def decryptMsg(self, ciphertext, textMsg=True): """ :type ciphertext: WhisperMessage :type textMsg: Bool set this to False if you are decrypting by...
:type ciphertext: PreKeyWhisperMessage def decryptPkmsg(self, ciphertext, textMsg=True): """ :type ciphertext: PreKeyWhisperMessage """ sessionRecord = self.sessionStore.loadSession(self.recipientId, self.deviceId) unsignedPreKeyId = self.sessionBuilder.process(sessionRecord, ci...
:type sessionRecord: SessionRecord :type cipherText: WhisperMessage def decryptWithSessionRecord(self, sessionRecord, cipherText): """ :type sessionRecord: SessionRecord :type cipherText: WhisperMessage """ previousStates = sessionRecord.getPreviousSessionStates() ...
:type version: int :type messageKeys: MessageKeys :type plainText: bytearray def getCiphertext(self, version, messageKeys, plainText): """ :type version: int :type messageKeys: MessageKeys :type plainText: bytearray """ cipher = None if version ...
:type publicKey: ECPublicKey :type privateKey: ECPrivateKey def calculateAgreement(publicKey, privateKey): """ :type publicKey: ECPublicKey :type privateKey: ECPrivateKey """ if publicKey.getType() != privateKey.getType(): raise InvalidKeyException("Public an...
:type ecPublicSigningKey: ECPublicKey :type message: bytearray :type signature: bytearray def verifySignature(ecPublicSigningKey, message, signature): """ :type ecPublicSigningKey: ECPublicKey :type message: bytearray :type signature: bytearray """ if ec...
:type privateSigningKey: ECPrivateKey :type message: bytearray def calculateSignature(privateSigningKey, message): """ :type privateSigningKey: ECPrivateKey :type message: bytearray """ if privateSigningKey.getType() == Curve.DJB_TYPE: rand = os.urandom(64)...
:type paddedPlaintext: str def encrypt(self, paddedPlaintext): """ :type paddedPlaintext: str """ # TODO: make this less ugly and python 2 and 3 compatible # paddedMessage = bytearray(paddedMessage.encode() if (sys.version_info >= (3, 0) and not type(paddedMessage) in (bytes, by...
:type senderKeyMessageBytes: bytearray def decrypt(self, senderKeyMessageBytes): """ :type senderKeyMessageBytes: bytearray """ try: record = self.senderKeyStore.loadSenderKey(self.senderKeyName) if record.isEmpty(): raise NoSessionException("No s...
:type iv: bytearray :type key: bytearray :type ciphertext: bytearray def getPlainText(self, iv, key, ciphertext): """ :type iv: bytearray :type key: bytearray :type ciphertext: bytearray """ try: cipher = AESCipher(key, iv) plainte...
:type iv: bytearray :type key: bytearray :type plaintext: bytearray def getCipherText(self, iv, key, plaintext): """ :type iv: bytearray :type key: bytearray :type plaintext: bytearray """ cipher = AESCipher(key, iv) return cipher.encrypt(bytes(pl...
:type sequence: int :type ourBaseKey: ECKeyPair :type ourRatchetKey: ECKeyPair :type ourIdentityKey: IdentityKeyPair def setPendingKeyExchange(self, sequence, ourBaseKey, ourRatchetKey, ourIdentityKey): """ :type sequence: int :type ourBaseKey: ECKeyPair :type o...
:type preKeyId: int :type signedPreKeyId: int :type baseKey: ECPublicKey def setUnacknowledgedPreKeyMessage(self, preKeyId, signedPreKeyId, baseKey): """ :type preKeyId: int :type signedPreKeyId: int :type baseKey: ECPublicKey """ self.sessionStructure.pe...
Generate an identity key pair. Clients should only do this once, at install time. @return the generated IdentityKeyPair. def generateIdentityKeyPair(): """ Generate an identity key pair. Clients should only do this once, at install time. @return the generated IdentityK...
Generate a list of PreKeys. Clients should do this at install time, and subsequently any time the list of PreKeys stored on the server runs low. PreKey IDs are shorts, so they will eventually be repeated. Clients should store PreKeys in a circular buffer, so that they are repeated as infreque...
Choices for Enum :return: List of tuples (<value>, <human-readable value>) :rtype: list def choices(cls, blank=False): """ Choices for Enum :return: List of tuples (<value>, <human-readable value>) :rtype: list """ choices = sorted([(key, value) for key, value in...
Get Enum.Value object matching the value argument. :param name_or_numeric: Integer value or attribute name :type name_or_numeric: int or str :rtype: Enum.Value def get(cls, name_or_numeric): """ Get Enum.Value object matching the value argument. :param name_or_numeric: Integer v...
:return: List of tuples consisting of every enum value in the form [('NAME', value), ...] :rtype: list def items(cls): """ :return: List of tuples consisting of every enum value in the form [('NAME', value), ...] :rtype: list """ items = [(value.name, key) for key, value...
Will check if to_value is a valid transition from from_value. Returns true if it is a valid transition. :param from_value: Start transition point :param to_value: End transition point :type from_value: int :type to_value: int :return: Success flag :rtype: bool def is_val...
User a customer setter for the field to validate new value against the old one. The current value is set as '_enum_[att_name]' on the model instance. def _setup_validation(self, sender, **kwargs): """ User a customer setter for the field to validate new value against the old one. The cu...
Validate that to_value is a valid choice and that to_value is a valid transition from from_value. def validate_valid_transition(enum, from_value, to_value): """ Validate that to_value is a valid choice and that to_value is a valid transition from from_value. """ validate_available_choice(enum, to_value...
Validate that to_value is defined as a value in enum. def validate_available_choice(enum, to_value): """ Validate that to_value is defined as a value in enum. """ if to_value is None: return if type(to_value) is not int: try: to_value = int(to_value) except Valu...
Get a diff between running config and a proposed file. def _get_diff(self, cp_file): """Get a diff between running config and a proposed file.""" diff = [] self._create_sot_file() diff_out = self.device.show( 'show diff rollback-patch file {0} file {1}'.format( ...
Save the current running config to the given file. def _save_config(self, filename): """Save the current running config to the given file.""" self.device.show('checkpoint file {}'.format(filename), raw_text=True)
Open the connection wit the device. def open(self): """Open the connection wit the device.""" try: self.device.open() except ConnectTimeoutError as cte: raise ConnectionException(cte.message) self.device.timeout = self.timeout self.device._conn._session.t...
Lock the config DB. def _lock(self): """Lock the config DB.""" if not self.locked: self.device.cu.lock() self.locked = True
Unlock the config DB. def _unlock(self): """Unlock the config DB.""" if self.locked: self.device.cu.unlock() self.locked = False
Compare candidate config with running. def compare_config(self): """Compare candidate config with running.""" diff = self.device.cu.diff() if diff is None: return '' else: return diff.strip()
Commit configuration. def commit_config(self): """Commit configuration.""" self.device.cu.commit(ignore_warning=self.ignore_warning) if not self.config_lock: self._unlock()
Discard changes (rollback 0). def discard_config(self): """Discard changes (rollback 0).""" self.device.cu.rollback(rb_id=0) if not self.config_lock: self._unlock()
Return facts of the device. def get_facts(self): """Return facts of the device.""" output = self.device.facts uptime = self.device.uptime or -1 interfaces = junos_views.junos_iface_table(self.device) interfaces.get() interface_list = interfaces.keys() return {...
Return interfaces details. def get_interfaces(self): """Return interfaces details.""" result = {} interfaces = junos_views.junos_iface_table(self.device) interfaces.get() # convert all the tuples to our pre-defined dict structure for iface in interfaces.keys(): ...
Function to derive address family from a junos table name. :params table: The name of the routing table :returns: address family def _get_address_family(table): """ Function to derive address family from a junos table name. :params table: The name of the routing table ...
Return BGP neighbors details. def get_bgp_neighbors(self): """Return BGP neighbors details.""" bgp_neighbor_data = {} default_neighbor_details = { 'local_as': 0, 'remote_as': 0, 'remote_id': '', 'is_up': False, 'is_enabled': False, ...
Return LLDP neighbors details. def get_lldp_neighbors(self): """Return LLDP neighbors details.""" lldp = junos_views.junos_lldp_table(self.device) try: lldp.get() except RpcError as rpcerr: # this assumes the library runs in an environment # able to h...
Detailed view of the LLDP neighbors. def get_lldp_neighbors_detail(self, interface=''): """Detailed view of the LLDP neighbors.""" lldp_neighbors = {} lldp_table = junos_views.junos_lldp_neighbors_detail_table(self.device) try: lldp_table.get() except RpcError as rp...
Return the ARP table. def get_arp_table(self): """Return the ARP table.""" # could use ArpTable # from jnpr.junos.op.phyport import ArpTable # and simply use it # but # we need: # - filters # - group by VLAN ID # - hostname & TTE fields as w...
Return the NTP peers configured on the device. def get_ntp_peers(self): """Return the NTP peers configured on the device.""" ntp_table = junos_views.junos_ntp_peers_config_table(self.device) ntp_table.get() ntp_peers = ntp_table.items() if not ntp_peers: return {} ...
Return the NTP servers configured on the device. def get_ntp_servers(self): """Return the NTP servers configured on the device.""" ntp_table = junos_views.junos_ntp_servers_config_table(self.device) ntp_table.get() ntp_servers = ntp_table.items() if not ntp_servers: ...
Return NTP stats (associations). def get_ntp_stats(self): """Return NTP stats (associations).""" # NTP Peers does not have XML RPC defined # thus we need to retrieve raw text and parse... # :( ntp_stats = [] REGEX = ( '^\s?(\+|\*|x|-)?([a-zA-Z0-9\.+-:]+)' ...
Return the MAC address table. def get_mac_address_table(self): """Return the MAC address table.""" mac_address_table = [] if self.device.facts.get('personality', '') in ['SWITCH']: # for EX & QFX devices if self.device.facts.get('switch_style', '') in ['VLAN_L2NG']: # for L2NG de...
Return the configuration of the RPM probes. def get_probes_config(self): """Return the configuration of the RPM probes.""" probes = {} probes_table = junos_views.junos_rpm_probes_config_table(self.device) probes_table.get() probes_table_items = probes_table.items() for...
Return the results of the RPM probes. def get_probes_results(self): """Return the results of the RPM probes.""" probes_results = {} probes_results_table = junos_views.junos_rpm_probes_results_table(self.device) probes_results_table.get() probes_results_items = probes_results_ta...
Execute traceroute and return results. def traceroute(self, destination, source=C.TRACEROUTE_SOURCE, ttl=C.TRACEROUTE_TTL, timeout=C.TRACEROUTE_TIMEOUT, vrf=C.TRACEROUTE_VRF): """Execute traceroute and return results...