INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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 when a mutable model class is prepared """ referenced_models = set() # Collect all model class the obsolet...
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() except definition_cls.DoesNotExist: pass
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 = True while len(look...
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=str) parser.add_argument('-s', '--series', ...
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): keys[field] = (topic, field[len(topic) + 1:]) return keys
Read in a rosbag file and create a pandas data frame that is indexed by the time the message was recorded in the bag.
def bag_to_dataframe(bag_name, include=None, exclude=None, parse_header=False, seconds=False): ''' 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...
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 + t['messages'] break return tota...
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]: key = (base_name + f).replace('.', '_') ...
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
def prune_topics(bag_topics, include, exclude): '''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 l...
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 = {} classes = {} for topic in topics: base_key = get_key_name(topic) msg_pa...
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(subprocess.Popen( ['rosbag', 'info', '--yaml', bag_file], stdout=subprocess.PIPE).communicate()[0]) ...
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 dictionary topics = yaml_info['topics'] for topic in topics: names.append(topic['to...
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(msg, i) if not parse_header and i == 'header': conti...
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 found in x''' data = msg paths = key.split('.') for i in paths: data = getattr(data, i) return data
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', type=str) parser.add_argument('-i', '--include', ...
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 post_attributes.get('hea...
: type signatureKey: ECPublicKey
def verifySignature(self, signatureKey): """ :type signatureKey: ECPublicKey """ try: parts = ByteUtil.split(self.serialized, len(self.serialized) - self.__class__.SIGNATURE_LENGTH, self.__class__.SIGNATURE...
: type signatureKey: ECPrivateKey: type serialized: bytearray
def getSignature(self, signatureKey, serialized): """ :type signatureKey: ECPrivateKey :type serialized: bytearray """ try: return Curve.calculateSignature(signatureKey, serialized) except InvalidKeyException as e: raise AssertionError(e)
: param sessionRecord:: param message:: type message: PreKeyWhisperMessage
def process(self, sessionRecord, message): """ :param sessionRecord: :param message: :type message: PreKeyWhisperMessage """ messageVersion = message.getMessageVersion() theirIdentityKey = message.getIdentityKey() unsignedPreKeyId = None if not ...
: type sessionRecord: SessionRecord: type message: PreKeyWhisperMessage
def processV2(self, sessionRecord, message): """ :type sessionRecord: SessionRecord :type message: PreKeyWhisperMessage """ if message.getPreKeyId() is None: raise InvalidKeyIdException("V2 message requires one time prekey id!") if not self.preKeyStore.conta...
: param sessionRecord:: param message:: type message: PreKeyWhisperMessage: return:
def processV3(self, sessionRecord, message): """ :param sessionRecord: :param message: :type message: PreKeyWhisperMessage :return: """ if sessionRecord.hasSessionState(message.getMessageVersion(), message.getBaseKey().serialize()): logger.warn("We've...
: 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()) if preKey.getSignedPreKey(...
: type senderKeyName: SenderKeyName: type senderKeyDistributionMessage: SenderKeyDistributionMessage
def process(self, senderKeyName, senderKeyDistributionMessage): """ :type senderKeyName: SenderKeyName :type senderKeyDistributionMessage: SenderKeyDistributionMessage """ senderKeyRecord = self.senderKeyStore.loadSenderKey(senderKeyName) senderKeyRecord.addSenderKeyState...
: type senderKeyName: SenderKeyName
def create(self, senderKeyName): """ :type senderKeyName: SenderKeyName """ try: senderKeyRecord = self.senderKeyStore.loadSenderKey(senderKeyName); if senderKeyRecord.isEmpty() : senderKeyRecord.setSenderKeyState(KeyHelper.generateSenderKeyId(), ...
: type sessionState: SessionState: type sessionVersion: int: type parameters: SymmetricAxolotlParameters
def initializeSession(sessionState, sessionVersion, parameters): """ :type sessionState: SessionState :type sessionVersion: int :type parameters: SymmetricAxolotlParameters """ if RatchetingSession.isAlice(parameters.getOurBaseKey().getPublicKey(), parameters.getTheirBase...
: type sessionState: SessionState: type sessionVersion: int: type parameters: AliceAxolotlParameters
def initializeSessionAsAlice(sessionState, sessionVersion, parameters): """ :type sessionState: SessionState :type sessionVersion: int :type parameters: AliceAxolotlParameters """ sessionState.setSessionVersion(sessionVersion) sessionState.setRemoteIdentityKey(par...
: type sessionState: SessionState: type sessionVersion: int: type parameters: BobAxolotlParameters
def initializeSessionAsBob(sessionState, sessionVersion, parameters): """ :type sessionState: SessionState :type sessionVersion: int :type parameters: BobAxolotlParameters """ sessionState.setSessionVersion(sessionVersion) sessionState.setRemoteIdentityKey(paramet...
: 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: ECPublicKey """ self.senderKeyStates.append(SenderKeyState(id, iteration, chainKey, signatureKey))
: 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 """ del self.senderKeyStates[:] self.senderKeyStates.append(SenderKeyState(id, iteration, cha...
: 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, bytearray)) or type(paddedMessage)...
: 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 bytes instead of string """ if not self.sessionStore.containsSession(self.recipientId, self.deviceId): ...
: 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, ciphertext) plaintext = self.decry...
: type sessionRecord: SessionRecord: type cipherText: WhisperMessage
def decryptWithSessionRecord(self, sessionRecord, cipherText): """ :type sessionRecord: SessionRecord :type cipherText: WhisperMessage """ previousStates = sessionRecord.getPreviousSessionStates() exceptions = [] try: sessionState = SessionState(sessi...
: 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 >= 3: cipher = self.getCipher(messageKeys.getCipherKey(), messageKeys.getIv()) ...
: type publicKey: ECPublicKey: type privateKey: ECPrivateKey
def calculateAgreement(publicKey, privateKey): """ :type publicKey: ECPublicKey :type privateKey: ECPrivateKey """ if publicKey.getType() != privateKey.getType(): raise InvalidKeyException("Public and private keys must be of the same type!") if publicKey.getT...
: type ecPublicSigningKey: ECPublicKey: type message: bytearray: type signature: bytearray
def verifySignature(ecPublicSigningKey, message, signature): """ :type ecPublicSigningKey: ECPublicKey :type message: bytearray :type signature: bytearray """ if ecPublicSigningKey.getType() == Curve.DJB_TYPE: result = _curve.verifySignature(ecPublicSigningKe...
: 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) res = _curve.calculateSignature(rand, privateSigningKey.getP...
: 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, bytearray)) or type(paddedMess...
: type senderKeyMessageBytes: bytearray
def decrypt(self, senderKeyMessageBytes): """ :type senderKeyMessageBytes: bytearray """ try: record = self.senderKeyStore.loadSenderKey(self.senderKeyName) if record.isEmpty(): raise NoSessionException("No sender key for: %s" % self.senderKeyName)...
: 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) plaintext = cipher.decrypt(ciphertext) if sys.version_info >= (3, 0): ...
: 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(plaintext))
: 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 ourRatchetKey: ECKeyPair :type ourIdentityKey: IdentityKeyPair """ structure = self.sessionStructure.PendingKeyExchange...
: 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.pendingPreKey.signedPreKeyId = signedPreKeyId self.sessionStructure.pendingPreKey.ba...
Generate an identity key pair. Clients should only do this once at install time.
def generateIdentityKeyPair(): """ Generate an identity key pair. Clients should only do this once, at install time. @return the generated IdentityKeyPair. """ keyPair = Curve.generateKeyPair() publicKey = IdentityKey(keyPair.getPublicKey()) serialized = ...
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.
def generatePreKeys(start, count): """ 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...
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 cls.values.items()], key=lambda x: x[0]) if blank: choices.insert(0, ('', Enum.Value...
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 value or attribute name :type name_or_numeric: int or str :rtype: Enum.Value """ if isinstance(name_or_numeric, six.string_types): name_or_num...
: 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 in cls.values.items()] return sorted(items, key=lambda x: x[1])
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_valid_transition(cls, from_value, to_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: in...
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 current value is set as '_enum_[att_name]' on the model instance. """ att_name = self.get_attname() private_att_name = '_enum_%s' % att_n...
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) if hasattr(enum, '_transitions') and not enum.is_valid_transition(from_value, 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 ValueError: message_str = "'{value}' cannot be ...
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( 'sot_file', self.replace_file.split('/')[-1]), raw_te...
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.transport.set_keepalive(self.keepalive...
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 { 'vendor': u'Juni...
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(): result[iface] = { ...
Function to derive address family from a junos table name.
def _get_address_family(table): """ Function to derive address family from a junos table name. :params table: The name of the routing table :returns: address family """ address_family_mapping = { 'inet': 'ipv4', 'inet6': 'ipv6', 'inetf...
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, 'description': '', ...
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 handle logs # otherwi...
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 rpcerr: # this assumes the l...
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 well arp_table ...
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 {napalm_base.helpers.ip(peer[0])...
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 {} return {napalm_base.helpers.i...
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\.+-:]+)' '\s+([a-zA-Z0-9\.]+)\s+...
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 devices mac_table...
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 probe_test in probes_table_items: ...
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_table.items() for probe_result i...
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.""" traceroute_result = {} ...
Parse a single entry from show interfaces output.
def parse_intf_section(interface): """Parse a single entry from show interfaces output. Different cases: mgmt0 is up admin state is up Ethernet2/1 is up admin state is up, Dedicated Interface Vlan1 is down (Administratively down), line protocol is down, autostate enabled Ethernet154/...
Get a diff between running config and a proposed file.
def _get_diff(self): """Get a diff between running config and a proposed file.""" diff = [] self._create_sot_file() command = ('show diff rollback-patch file {0} file {1}'.format( 'sot_file', self.replace_file.split('/')[-1])) diff_out = self.device.send_comman...
Save the current running config to the given file.
def _save_to_checkpoint(self, filename): """Save the current running config to the given file.""" command = 'checkpoint file {}'.format(filename) self.device.send_command(command)
Return a set of facts from the devices.
def get_facts(self): """Return a set of facts from the devices.""" # default values. vendor = u'Cisco' uptime = -1 serial_number, fqdn, os_version, hostname, domain_name = ('',) * 5 # obtain output from device show_ver = self.device.send_command('show version') ...
Get arp table information.
def get_arp_table(self): """ Get arp table information. Return a list of dictionaries having the following set of keys: * interface (string) * mac (string) * ip (string) * age (float) For example:: [ { ...
Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table having the following keys * mac ( string ) * interface ( string ) * vlan ( int ) * active ( boolean ) * static ( boolean ) * moves ( int ) * last_move ( float ) Format1:
def get_mac_address_table(self): """ Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table, having the following keys * mac (string) * interface (string) * vlan (int) * active (boolean) * static (...
Remove all auth tokens owned by request. user.
def get(self, request, format=None): """ Remove all auth tokens owned by request.user. """ tokens = Token.objects.filter(user=request.user) for token in tokens: token.delete() content = {'success': _('User logged out.')} return Response(content, status...
Set attributes to dictionary values so can access via dot notation.
def _set_attrs_to_values(self, response={}): """ Set attributes to dictionary values so can access via dot notation. """ for key in response.keys(): setattr(self, key, response[key])
Add a custom filter nl2br to jinja2 Replaces all newline to <BR >
def add_custom_nl2br_filters(self, app): """Add a custom filter nl2br to jinja2 Replaces all newline to <BR> """ _paragraph_re = re.compile(r'(?:\r\n|\r|\n){3,}') @app.template_filter() @evalcontextfilter def nl2br(eval_ctx, value): result = '\n\n'.j...
Add flask route to autodoc for automatic documentation
def doc(self, groups=None, set_location=True, **properties): """Add flask route to autodoc for automatic documentation Any route decorated with this method will be added to the list of routes to be documented by the generate() or html() methods. By default, the route is added to the 'a...
Return a list of dict describing the routes specified by the doc () method
def generate(self, groups='all', sort=None): """Return a list of dict describing the routes specified by the doc() method Each dict contains: - methods: the set of allowed methods (ie ['GET', 'POST']) - rule: relative url (ie '/user/<int:id>') - endpoint: function nam...
Return an html string of the routes specified by the doc () method
def html(self, groups='all', template=None, **context): """Return an html string of the routes specified by the doc() method A template can be specified. A list of routes is available under the 'autodoc' value (refer to the documentation for the generate() for a description of available...
Return true if OK to continue with close or quit or whatever
def unsaved_files_dialog( self, all_files=False, with_cancel=True, with_discard=True): """Return true if OK to continue with close or quit or whatever""" for image in self.images: if image.metadata.changed() and (all_files or image.selected): break else: ...
Sufficiently general ISO 8601 parser.
def from_ISO_8601(cls, date_string, time_string, tz_string): """Sufficiently general ISO 8601 parser. Inputs must be in "basic" format, i.e. no '-' or ':' separators. See https://en.wikipedia.org/wiki/ISO_8601 """ # parse tz_string if tz_string: tz_offset = ...
Create a new post. Form Data: title content authorid.
def post_post(): """Create a new post. Form Data: title, content, authorid. """ authorid = request.form.get('authorid', None) Post(request.form['title'], request.form['content'], users[authorid]) return redirect("/posts")
Finds another node by XPath originating at the current node.
def xpath(self, xpath): """ Finds another node by XPath originating at the current node. """ return [self.get_node_factory().create(node_id) for node_id in self._get_xpath_ids(xpath).split(",") if node_id]
Finds another node by a CSS selector relative to the current node.
def css(self, css): """ Finds another node by a CSS selector relative to the current node. """ return [self.get_node_factory().create(node_id) for node_id in self._get_css_ids(css).split(",") if node_id]
Returns the value of a boolean HTML attribute like checked or disabled
def get_bool_attr(self, name): """ Returns the value of a boolean HTML attribute like `checked` or `disabled` """ val = self.get_attr(name) return val is not None and val.lower() in ("true", name)
Sets the value of an attribute.
def set_attr(self, name, value): """ Sets the value of an attribute. """ self.exec_script("node.setAttribute(%s, %s)" % (repr(name), repr(value)))
Returns the node s value.
def value(self): """ Returns the node's value. """ if self.is_multi_select(): return [opt.value() for opt in self.xpath(".//option") if opt["selected"]] else: return self._invoke("value")
Sets a HTTP header for future requests.
def set_header(self, key, value): """ Sets a HTTP header for future requests. """ self.conn.issue_command("Header", _normalize_header(key), value)
Returns a list of the last HTTP response headers. Header keys are normalized to capitalized form as in User - Agent.
def headers(self): """ Returns a list of the last HTTP response headers. Header keys are normalized to capitalized form, as in `User-Agent`. """ headers = self.conn.issue_command("Headers") res = [] for header in headers.split("\r"): key, value = header.split(": ", 1) for line in val...
Evaluates a piece of Javascript in the context of the current page and returns its value.
def eval_script(self, expr): """ Evaluates a piece of Javascript in the context of the current page and returns its value. """ ret = self.conn.issue_command("Evaluate", expr) return json.loads("[%s]" % ret)[0]
Renders the current page to a PNG file ( viewport size in pixels ).
def render(self, path, width = 1024, height = 1024): """ Renders the current page to a PNG file (viewport size in pixels). """ self.conn.issue_command("Render", path, width, height)