code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
field_int = self.oxm_field_and_mask >> 1 # We know that the class below requires a subset of the ofb enum if self.oxm_class == OxmClass.OFPXMC_OPENFLOW_BASIC: return OxmOfbMatchField(field_int) return field_int
def _unpack_oxm_field(self)
Unpack oxm_field from oxm_field_and_mask. Returns: :class:`OxmOfbMatchField`, int: oxm_field from oxm_field_and_mask. Raises: ValueError: If oxm_class is OFPXMC_OPENFLOW_BASIC but :class:`OxmOfbMatchField` has no such integer value.
8.383427
5.645774
1.484903
payload = type(self).oxm_value.pack(self.oxm_value) self.oxm_length = len(payload)
def _update_length(self)
Update length field. Update the oxm_length field with the packed payload length.
9.743044
4.453185
2.187882
if value is not None: return value.pack() # Set oxm_field_and_mask instance attribute # 1. Move field integer one bit to the left try: field_int = self._get_oxm_field_int() except ValueError as exception: raise PackException(exception...
def pack(self, value=None)
Join oxm_hasmask bit and 7-bit oxm_field.
5.465629
4.629199
1.180686
if self.oxm_class == OxmClass.OFPXMC_OPENFLOW_BASIC: return OxmOfbMatchField(self.oxm_field).value elif not isinstance(self.oxm_field, int) or self.oxm_field > 127: raise ValueError('oxm_field above 127: "{self.oxm_field}".') return self.oxm_field
def _get_oxm_field_int(self)
Return a valid integer value for oxm_field. Used while packing. Returns: int: valid oxm_field value. Raises: ValueError: If :attribute:`oxm_field` is bigger than 7 bits or should be :class:`OxmOfbMatchField` and the enum has no such valu...
3.317669
3.097348
1.071132
if isinstance(value, Match): return value.pack() elif value is None: self._update_match_length() packet = super().pack() return self._complete_last_byte(packet) raise PackException(f'Match can\'t unpack "{value}".')
def pack(self, value=None)
Pack and complete the last byte by padding.
7.877416
5.894649
1.336367
padded_size = self.get_size() padding_bytes = padded_size - len(packet) if padding_bytes > 0: packet += Pad(padding_bytes).pack() return packet
def _complete_last_byte(self, packet)
Pad until the packet length is a multiple of 8 (bytes).
3.916147
3.282469
1.193049
if isinstance(value, Match): return value.get_size() elif value is None: current_size = super().get_size() return ceil(current_size / 8) * 8 raise ValueError(f'Invalid value "{value}" for Match.get_size()')
def get_size(self, value=None)
Return the packet length including the padding (multiple of 8).
4.364499
3.91069
1.116043
begin = offset for name, value in list(self.get_class_attributes())[:-1]: size = self._unpack_attribute(name, value, buff, begin) begin += size self._unpack_attribute('oxm_match_fields', type(self).oxm_match_fields, buff[:offset+sel...
def unpack(self, buff, offset=0)
Discard padding bytes using the unpacked length attribute.
6.094276
5.594334
1.089366
for field in self.oxm_match_fields: if field.oxm_field == field_type: return field.oxm_value return None
def get_field(self, field_type)
Return the value for the 'field_type' field in oxm_match_fields. Args: field_type (~pyof.v0x04.common.flow_match.OxmOfbMatchField, ~pyof.v0x04.common.flow_match.OxmMatchFields): The type of the OXM field you want the value. Returns: The i...
5.008411
2.910704
1.720687
if self.isenum(): if isinstance(self._value, self.enum_ref): return self._value.value return self._value elif self.is_bitmask(): return self._value.bitmask else: return self._value
def value(self)
Return this type's value. Returns: object: The value of an enum, bitmask, etc.
4.340264
3.776051
1.149419
r if isinstance(value, type(self)): return value.pack() if value is None: value = self.value elif 'value' in dir(value): # if it is enum or bitmask gets only the 'int' value value = value.value try: return struct.pack(...
def pack(self, value=None)
r"""Pack the value as a binary representation. Considering an example with UBInt8 class, that inherits from GenericType: >>> from pyof.foundation.basic_types import UBInt8 >>> objectA = UBInt8(1) >>> objectB = 5 >>> objectA.pack() b'\x01' >>> objectA.pac...
4.724863
4.767684
0.991019
try: self._value = struct.unpack_from(self._fmt, buff, offset)[0] if self.enum_ref: self._value = self.enum_ref(self._value) except (struct.error, TypeError, ValueError) as exception: msg = '{}; fmt = {}, buff = {}, offset = {}.'.format(except...
def unpack(self, buff, offset=0)
Unpack *buff* into this object. This method will convert a binary data into a readable value according to the attribute format. Args: buff (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: :exc:`~.exceptions.UnpackException`: I...
3.359459
3.251508
1.0332
old_enum = obj.message_type new_header = attr[1] new_enum = new_header.__class__.message_type.enum_ref #: This 'if' will be removed on the future with an #: improved version of __init_subclass__ method of the #: GenericMessage class if old_enum: ...
def _header_message_type_update(obj, attr)
Update the message type on the header. Set the message_type of the header according to the message_type of the parent class.
6.021913
5.885553
1.023169
ver_module_re = re.compile(r'(pyof\.)(v0x\d+)(\..*)') matched = ver_module_re.match(module_fullname) if matched: version = matched.group(2) return version return None
def get_pyof_version(module_fullname)
Get the module pyof version based on the module fullname. Args: module_fullname (str): The fullname of the module (e.g.: pyof.v0x01.common.header) Returns: str: openflow version. The openflow version, on the format 'v0x0?' if any. Or None ...
4.397032
3.579152
1.228512
module_version = MetaStruct.get_pyof_version(module_fullname) if not module_version or module_version == version: return None return module_fullname.replace(module_version, version)
def replace_pyof_version(module_fullname, version)
Replace the OF Version of a module fullname. Get's a module name (eg. 'pyof.v0x01.common.header') and returns it on a new 'version' (eg. 'pyof.v0x02.common.header'). Args: module_fullname (str): The fullname of the module (e.g.: pyof.v0x01.common....
3.975087
4.472719
0.888741
r if new_version is None: return (name, obj) cls = obj.__class__ cls_name = cls.__name__ cls_mod = cls.__module__ #: If the module name does not starts with pyof.v0 then it is not a #: 'pyof versioned' module (OpenFlow specification defined), so we d...
def get_pyof_obj_new_version(name, obj, new_version)
r"""Return a class attribute on a different pyof version. This method receives the name of a class attribute, the class attribute itself (object) and an openflow version. The attribute will be evaluated and from it we will recover its class and the module where the class was defined. ...
4.739469
3.744191
1.265819
for _attr, _class in self._get_attributes(): if isinstance(_attr, _class): return True elif issubclass(_class, GenericType): if GenericStruct._attr_fits_into_class(_attr, _class): return True elif not isinstance(_at...
def _validate_attributes_type(self)
Validate the type of each attribute.
5.774721
5.023049
1.149645
#: see this method docstring for a important notice about the use of #: cls.__dict__ for name, value in cls.__dict__.items(): # gets only our (kytos) attributes. this ignores methods, dunder # methods and attributes, and common python type attributes. ...
def get_class_attributes(cls)
Return a generator for class attributes' names and value. This method strict relies on the PEP 520 (Preserving Class Attribute Definition Order), implemented on Python 3.6. So, if this behaviour changes this whole lib can loose its functionality (since the attributes order are a strong ...
22.325735
21.479021
1.039421
for name, value in self.__dict__.items(): if name in map((lambda x: x[0]), self.get_class_attributes()): yield (name, value)
def _get_instance_attributes(self)
Return a generator for instance attributes' name and value. .. code-block:: python3 for _name, _value in self._get_instance_attributes(): print("attribute name: {}".format(_name)) print("attribute value: {}".format(_value)) Returns: generator: t...
4.368962
5.025745
0.869316
return map((lambda i, c: (i[1], c[1])), self._get_instance_attributes(), self.get_class_attributes())
def _get_attributes(self)
Return a generator for instance and class attribute. .. code-block:: python3 for instance_attribute, class_attribute in self._get_attributes(): print("Instance Attribute: {}".format(instance_attribute)) print("Class Attribute: {}".format(class_attribute)) R...
9.288342
7.305624
1.271396
for cls, instance in zip(self.get_class_attributes(), self._get_instance_attributes()): attr_name, cls_value = cls instance_value = instance[1] yield attr_name, instance_value, cls_value
def _get_named_attributes(self)
Return generator for attribute's name, instance and class values. Add attribute name to meth:`_get_attributes` for a better debugging message, so user can find the error easier. Returns: generator: Tuple with attribute's name, instance and class values.
4.929834
4.042174
1.2196
if value is None: return sum(cls_val.get_size(obj_val) for obj_val, cls_val in self._get_attributes()) elif isinstance(value, type(self)): return value.get_size() else: msg = "{} is not an instance of {}".format(value, ...
def get_size(self, value=None)
Calculate the total struct size in bytes. For each struct attribute, sum the result of each one's ``get_size()`` method. Args: value: In structs, the user can assign other value instead of a class' instance. Returns: int: Total number of bytes u...
4.279128
3.9344
1.087619
if value is None: if not self.is_valid(): error_msg = "Error on validation prior to pack() on class " error_msg += "{}.".format(type(self).__name__) raise ValidationError(error_msg) else: message = b'' ...
def pack(self, value=None)
Pack the struct in a binary representation. Iterate over the class attributes, according to the order of definition, and then convert each attribute to its byte representation using its own ``pack`` method. Returns: bytes: Binary representation of the struct object. ...
3.359564
3.294927
1.019617
if value is None: self.update_header_length() return super().pack() elif isinstance(value, type(self)): return value.pack() else: msg = "{} is not an instance of {}".format(value, type...
def pack(self, value=None)
Pack the message into a binary data. One of the basic operations on a Message is the pack operation. During the packing process, we convert all message attributes to binary format. Since that this is usually used before sending the message to a switch, here we also call :meth:`...
3.728247
3.310796
1.126088
begin = offset for name, value in self.get_class_attributes(): if type(value).__name__ != "Header": size = self._unpack_attribute(name, value, buff, begin) begin += size
def unpack(self, buff, offset=0)
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. It is an inplace method and it receives the binary data of the message **without the header**. Args: buff (bytes): Binary data packa...
6.165063
7.366247
0.836934
result = [] for key, value in self.iteritems(): if value & self.bitmask: result.append(key) return result
def names(self)
List of selected enum names. Returns: list: Enum names.
5.636436
5.889371
0.957052
self.action_type = UBInt16(enum_ref=ActionType) self.action_type.unpack(buff, offset) for cls in ActionHeader.__subclasses__(): if self.action_type.value in cls.get_allowed_types(): self.__class__ = cls break super().unpack(buff, off...
def unpack(self, buff, offset=0)
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: Exc...
4.389292
5.045666
0.869913
simple_body = { MultipartType.OFPMP_FLOW: FlowStatsRequest, MultipartType.OFPMP_AGGREGATE: AggregateStatsRequest, MultipartType.OFPMP_PORT_STATS: PortStatsRequest, MultipartType.OFPMP_QUEUE: QueueStatsRequest, MultipartType.OFPMP_GROUP: GroupS...
def _get_body_instance(self)
Return the body instance.
2.740803
2.684518
1.020966
buff = self.body if not value: value = self.body if value and hasattr(value, 'pack'): self.body = BinaryData(value.pack()) stats_reply_packed = super().pack() self.body = buff return stats_reply_packed
def pack(self, value=None)
Pack a StatsReply using the object's attributes. This method will pack the attribute body and body_type before pack the StatsReply object, then will return this struct as a binary data. Returns: bytes: Binary data with StatsReply packed.
6.468979
5.250091
1.232165
pyof_class = self._get_body_class() if pyof_class is None: return BinaryData(b'') elif pyof_class is DescStats: return pyof_class() return FixedTypeList(pyof_class=pyof_class)
def _get_body_instance(self)
Return the body instance.
6.454335
5.683758
1.135575
super().unpack(buff, offset) self.wildcards = UBInt32(value=FlowWildCards.OFPFW_ALL, enum_ref=FlowWildCards) self.wildcards.unpack(buff, offset)
def unpack(self, buff, offset=0)
Unpack *buff* into this object. Do nothing, since the _length is already defined and it is just a Pad. Keep buff and offset just for compability with other unpack methods. Args: buff (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: ...
7.060421
8.421941
0.838337
if field in [None, 'wildcards'] or isinstance(value, Pad): return default_value = getattr(Match, field) if isinstance(default_value, IPAddress): if field == 'nw_dst': shift = FlowWildCards.OFPFW_NW_DST_SHIFT base_mask = FlowWildCa...
def fill_wildcards(self, field=None, value=0)
Update wildcards attribute. This method update a wildcards considering the attributes of the current instance. Args: field (str): Name of the updated field. value (GenericType): New value used in the field.
4.828935
4.861182
0.993366
if isinstance(value, type(self)): return value.pack() if value is None: value = self._value return struct.pack('!8B', *[int(v, 16) for v in value.split(':')])
def pack(self, value=None)
Pack the value as a binary representation. Returns: bytes: The binary representation. Raises: struct.error: If the value does not fit the binary format.
3.510399
3.903933
0.899196
begin = offset hexas = [] while begin < offset + 8: number = struct.unpack("!B", buff[begin:begin+1])[0] hexas.append("%.2x" % number) begin += 1 self._value = ':'.join(hexas)
def unpack(self, buff, offset=0)
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: Exc...
3.922638
5.08991
0.770669
if isinstance(value, type(self)): return value.pack() try: if value is None: value = self.value packed = struct.pack(self._fmt, bytes(value, 'ascii')) return packed[:-1] + b'\0' # null-terminated except struct.error as er...
def pack(self, value=None)
Pack the value as a binary representation. Returns: bytes: The binary representation. Raises: struct.error: If the value does not fit the binary format.
4.878989
5.181899
0.941545
try: begin = offset end = begin + self.length unpacked_data = struct.unpack(self._fmt, buff[begin:end])[0] except struct.error: raise Exception("%s: %s" % (offset, buff)) self._value = unpacked_data.decode('ascii').rstrip('\0')
def unpack(self, buff, offset=0)
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: Exc...
4.085661
4.165996
0.980717
try: unpacked_data = struct.unpack('!4B', buff[offset:offset+4]) self._value = '.'.join([str(x) for x in unpacked_data]) except struct.error as exception: raise exceptions.UnpackException('%s; %s: %s' % (exception, ...
def unpack(self, buff, offset=0)
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: Exc...
4.059963
4.495535
0.90311
if isinstance(value, type(self)): return value.pack() if value is None: value = self._value if value == 0: value = '00:00:00:00:00:00' value = value.split(':') try: return struct.pack('!6B', *[int(x, 16) for x in value]...
def pack(self, value=None)
Pack the value as a binary representation. If the passed value (or the self._value) is zero (int), then the pack will assume that the value to be packed is '00:00:00:00:00:00'. Returns bytes: The binary representation. Raises: struct.error: If the value does no...
3.606327
3.180954
1.133725
def _int2hex(number): return "{0:0{1}x}".format(number, 2) try: unpacked_data = struct.unpack('!6B', buff[offset:offset+6]) except struct.error as exception: raise exceptions.UnpackException('%s; %s: %s' % (exception, ...
def unpack(self, buff, offset=0)
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: Exc...
4.052299
4.319527
0.938135
if value is None: value = self._value if hasattr(value, 'pack') and callable(value.pack): return value.pack() elif isinstance(value, bytes): return value elif value is None: return b'' else: raise ValueError(f"...
def pack(self, value=None)
Pack the value as a binary representation. Returns: bytes: The binary representation. Raises: ValueError: If value can't be represented with bytes
3.145052
3.34727
0.939587
if value is None: value = self._value if hasattr(value, 'get_size'): return value.get_size() return len(self.pack(value))
def get_size(self, value=None)
Return the size in bytes. Args: value (bytes): In structs, the user can assign other value instead of this class' instance. Here, in such cases, ``self`` is a class attribute of the struct. Returns: int: The address size in bytes.
3.552142
4.016293
0.884433
if isinstance(value, type(self)): return value.pack() if value is None: value = self else: container = type(self)(items=None) container.extend(value) value = container bin_message = b'' try: for it...
def pack(self, value=None)
Pack the value as a binary representation. Returns: bytes: The binary representation.
3.3657
3.401239
0.989551
begin = offset limit_buff = len(buff) while begin < limit_buff: item = item_class() item.unpack(buff, begin) self.append(item) begin += item.get_size()
def unpack(self, buff, item_class, offset=0)
Unpack the elements of the list. Args: buff (bytes): The binary data to be unpacked. item_class (:obj:`type`): Class of the expected items on this list. offset (int): If we need to shift the beginning of the data.
3.48334
3.792255
0.918541
if value is None: if not self: # If this is a empty list, then returns zero return 0 elif issubclass(type(self[0]), GenericType): # If the type of the elements is GenericType, then returns the # length of the list m...
def get_size(self, value=None)
Return the size in bytes. Args: value: In structs, the user can assign other value instead of this class' instance. Here, in such cases, ``self`` is a class attribute of the struct. Returns: int: The size in bytes.
4.462822
4.740142
0.941495
if isinstance(item, list): self.extend(item) elif issubclass(item.__class__, self._pyof_class): list.append(self, item) else: raise exceptions.WrongListItemType(item.__class__.__name__, self._pyof_class._...
def append(self, item)
Append one item to the list. Args: item: Item to be appended. Its type must match the one defined in the constructor. Raises: :exc:`~.exceptions.WrongListItemType`: If the item has a different type than the one specified in the constructor.
4.306952
3.539176
1.216936
if issubclass(item.__class__, self._pyof_class): list.insert(self, index, item) else: raise exceptions.WrongListItemType(item.__class__.__name__, self._pyof_class.__name__)
def insert(self, index, item)
Insert an item at the specified index. Args: index (int): Position to insert the item. item: Item to be inserted. It must have the type specified in the constructor. Raises: :exc:`~.exceptions.WrongListItemType`: If the item has a different ...
5.108157
4.04448
1.262995
def unpack(self, buff, offset=0): # pylint: disable=arguments-differ super().unpack(buff, self._pyof_class, offset)
Unpack the elements of the list. This unpack method considers that all elements have the same size. To use this class with a pyof_class that accepts elements with different sizes, you must reimplement the unpack method. Args: buff (bytes): The binary data to be unpacked. ...
null
null
null
if isinstance(item, list): self.extend(item) elif not self: list.append(self, item) elif item.__class__ == self[0].__class__: list.append(self, item) else: raise exceptions.WrongListItemType(item.__class__.__name__, ...
def append(self, item)
Append one item to the list. Args: item: Item to be appended. Raises: :exc:`~.exceptions.WrongListItemType`: If an item has a different type than the first item to be stored.
3.375015
2.696835
1.251473
if not self: list.append(self, item) elif item.__class__ == self[0].__class__: list.insert(self, index, item) else: raise exceptions.WrongListItemType(item.__class__.__name__, self[0].__class__.__name__)
def insert(self, index, item)
Insert an item at the specified index. Args: index (int): Position to insert the item. item: Item to be inserted. Raises: :exc:`~.exceptions.WrongListItemType`: If an item has a different type than the first item to be stored.
3.885068
3.008832
1.291221
if isinstance(value, ActionHeader): return value.get_size() elif value is None: current_size = super().get_size() return ceil(current_size / 8) * 8 raise ValueError(f'Invalid value "{value}" for Action*.get_size()')
def get_size(self, value=None)
Return the action length including the padding (multiple of 8).
5.339352
4.261005
1.253073
self._update_length() packet = super().pack() return self._complete_last_byte(packet)
def pack(self, value=None)
Pack this structure updating the length and padding it.
14.13411
9.036143
1.564175
action_length = 4 + len(self.field.pack()) overflow = action_length % 8 self.length = action_length if overflow: self.length = action_length + 8 - overflow
def _update_length(self)
Update the length field of the struct.
6.853869
5.310986
1.290508
super().unpack(buff, offset) if not self.is_valid(): raise UnpackException("Unsupported protocols in ARP packet")
def unpack(self, buff, offset=0)
Unpack a binary struct into this object's attributes. Return the values instead of the lib's basic types. Check if the protocols involved are Ethernet and IPv4. Other protocols are currently not supported. Args: buff (bytes): Binary buffer. offset (int): Where t...
11.533863
8.15219
1.414818
if isinstance(value, type(self)): return value.pack() if self.pcp is None and self.cfi is None and self.vid is None: return b'' self.pcp = self.pcp if self.pcp is not None else 0 self.cfi = self.cfi if self.cfi is not None else 0 self.vid = self....
def pack(self, value=None)
Pack the struct in a binary representation. Merge some fields to ensure correct packing. If no arguments are set for a particular instance, it is interpreted as abscence of VLAN information, and the pack() method will return an empty binary string. Returns: bytes: ...
2.717813
2.344412
1.159273
if self.tpid.value not in (EtherType.VLAN, EtherType.VLAN_QINQ): raise UnpackException return
def _validate(self)
Assure this is a valid VLAN header instance.
13.374357
7.536973
1.7745
super().unpack(buff, offset) if self.tpid.value: self._validate() self.tpid = self.tpid.value self.pcp = self._tci.value >> 13 self.cfi = (self._tci.value >> 12) & 1 self.vid = self._tci.value & 4095 else: self.tpid...
def unpack(self, buff, offset=0)
Unpack a binary struct into this object's attributes. Return the values instead of the lib's basic types. After unpacking, the abscence of a `tpid` value causes the assignment of None to the field values to indicate that there is no VLAN information. Args: buff (by...
3.572555
3.193418
1.118725
length = 0 begin = 12 while(buff[begin:begin+2] in (EtherType.VLAN.to_bytes(2, 'big'), EtherType.VLAN_QINQ.to_bytes(2, 'big'))): length += 4 begin += 4 return length
def _get_vlan_length(buff)
Return the total length of VLAN tags in a given Ethernet buffer.
4.102768
3.410357
1.203032
begin = offset vlan_length = self._get_vlan_length(buff) for attribute_name, class_attribute in self.get_class_attributes(): attribute = deepcopy(class_attribute) if attribute_name == 'vlans': attribute.unpack(buff[begin:begin+vlan_length]) ...
def unpack(self, buff, offset=0)
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Ethernet headers may have VLAN tags. If no VLAN tag is found, a 'wildcard VLAN tag' is inserted to assure correct unpacking. Args: ...
3.935405
3.76696
1.044717
if value is None: output = self.header.pack() output += self.value.pack() return output elif isinstance(value, type(self)): return value.pack() else: msg = "{} is not an instance of {}".format(value, ...
def pack(self, value=None)
Pack the TLV in a binary representation. Returns: bytes: Binary representation of the struct object. Raises: :exc:`~.exceptions.ValidationError`: If validation fails.
3.370992
3.791016
0.889206
header = UBInt16() header.unpack(buff[offset:offset+2]) self.tlv_type = header.value >> 9 length = header.value & 511 begin, end = offset + 2, offset + 2 + length self._value = BinaryData(buff[begin:end])
def unpack(self, buff, offset=0)
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: Exc...
4.188161
5.033881
0.831994
if isinstance(value, type(self)): return value.get_size() return 2 + self.length
def get_size(self, value=None)
Return struct size. Returns: int: Returns the struct size based on inner attributes.
7.596492
8.29588
0.915695
source_list = [int(octet) for octet in self.source.split(".")] destination_list = [int(octet) for octet in self.destination.split(".")] source_upper = (source_list[0] << 8) + source_list[1] source_lower = (source_list[2] << 8) + source_list[3] ...
def _update_checksum(self)
Update the packet checksum to enable integrity check.
2.388454
2.178308
1.096472
# Set the correct IHL based on options size if self.options: self.ihl += int(len(self.options) / 4) # Set the correct packet length based on header length and data self.length = int(self.ihl * 4 + len(self.data)) self._version_ihl = self.version << 4 | self...
def pack(self, value=None)
Pack the struct in a binary representation. Merge some fields to ensure correct packing. Returns: bytes: Binary representation of this instance.
4.216593
4.158116
1.014063
super().unpack(buff, offset) self.version = self._version_ihl.value >> 4 self.ihl = self._version_ihl.value & 15 self.dscp = self._dscp_ecn.value >> 2 self.ecn = self._dscp_ecn.value & 3 self.length = self.length.value self.identification = self.identifi...
def unpack(self, buff, offset=0)
Unpack a binary struct into this object's attributes. Return the values instead of the lib's basic types. Args: buff (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: :exc:`~.exceptions.UnpackException`: If unpack fails.
2.006174
2.088351
0.96065
binary = UBInt8(self.sub_type).pack() + self.sub_value.pack() return BinaryData(binary)
def value(self)
Return sub type and sub value as binary data. Returns: :class:`~pyof.foundation.basic_types.BinaryData`: BinaryData calculated.
11.456223
6.398577
1.790433
header = UBInt16() header.unpack(buff[offset:offset+2]) self.tlv_type = header.value >> 9 length = header.value & 511 begin, end = offset + 2, offset + 2 + length sub_type = UBInt8() sub_type.unpack(buff[begin:begin+1]) self.sub_type = sub_type.va...
def unpack(self, buff, offset=0)
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: Exc...
2.965861
3.343001
0.887185
if not isinstance(packet, bytes): raise UnpackException('invalid packet') packet_length = len(packet) if packet_length < 8 or packet_length > 2**16: raise UnpackException('invalid packet') if packet_length != int.from_bytes(packet[2:4], byteorder='big'): raise UnpackExcep...
def validate_packet(packet)
Check if packet is valid OF packet. Raises: UnpackException: If the packet is invalid.
2.57829
2.355994
1.094353
validate_packet(packet) version = packet[0] try: pyof_lib = PYOF_VERSION_LIBS[version] except KeyError: raise UnpackException('Version not supported') try: message = pyof_lib.common.utils.unpack_message(packet) return message except (UnpackException, ValueE...
def unpack(packet)
Unpack the OpenFlow Packet and returns a message. Args: packet: buffer with the openflow packet. Returns: GenericMessage: Message unpacked based on openflow packet. Raises: UnpackException: if the packet can't be unpacked.
4.955664
4.608276
1.075383
classes = {'OFPET_HELLO_FAILED': HelloFailedCode, 'OFPET_BAD_REQUEST': BadRequestCode, 'OFPET_BAD_ACTION': BadActionCode, 'OFPET_BAD_INSTRUCTION': BadInstructionCode, 'OFPET_BAD_MATCH': BadMatchCode, 'OFPET_F...
def get_class(self)
Return a Code class based on current ErrorType value. Returns: enum.IntEnum: class referenced by current error type.
1.677833
1.536384
1.092066
super().unpack(buff, offset) code_class = ErrorType(self.error_type).get_class() self.code = code_class(self.code)
def unpack(self, buff, offset=0)
Unpack binary data into python object.
5.730001
5.599963
1.023221
classes = {'OFPET_HELLO_FAILED': HelloFailedCode, 'OFPET_BAD_REQUEST': BadRequestCode, 'OFPET_BAD_ACTION': BadActionCode, 'OFPET_FLOW_MOD_FAILED': FlowModFailedCode, 'OFPET_PORT_MOD_FAILED': PortModFailedCode, ...
def get_class(self)
Return a Code class based on current ErrorType value. Returns: enum.IntEnum: class referenced by current error type.
2.802546
2.291971
1.222766
if value is None: data_backup = None if self.data is not None and not isinstance(self.data, bytes): data_backup = self.data self.data = self.data.pack() packed = super().pack() if data_backup is not None: se...
def pack(self, value=None)
Pack the value as a binary representation. :attr:`data` is packed before the calling :meth:`.GenericMessage.pack`. After that, :attr:`data`'s value is restored. Returns: bytes: The binary representation. Raises: :exc:`~.exceptions.PackException`: If pack fails.
2.655389
2.561334
1.036721
icon = qutepart.getIcon(iconFileName) action = QAction(icon, text, widget) action.setShortcut(QKeySequence(shortcut)) action.setShortcutContext(Qt.WidgetShortcut) action.triggered.connect(slot) widget.addAction(action) return action
def _createAction(self, widget, iconFileName, text, shortcut, slot)
Create QAction with given parameters and add to the widget
2.601144
2.413193
1.077885
for block in qutepart.iterateBlocksFrom(startBlock): self._setBlockMarked(block, False) if block == endBlock: break
def clear(self, startBlock, endBlock)
Clear bookmarks on block range including start and end
11.135091
12.210793
0.911906
for block in qutepart.iterateBlocksBackFrom(self._qpart.textCursor().block().previous()): if self.isBlockMarked(block): self._qpart.setTextCursor(QTextCursor(block)) return
def _onPrevBookmark(self)
Previous Bookmark action triggered. Move cursor
9.455732
9.025444
1.047675
for block in qutepart.iterateBlocksFrom(self._qpart.textCursor().block().next()): if self.isBlockMarked(block): self._qpart.setTextCursor(QTextCursor(block)) return
def _onNextBookmark(self)
Previous Bookmark action triggered. Move cursor
8.533087
8.228267
1.037045
# Chars in the start line endTime = time.time() + self._MAX_SEARCH_TIME_SEC for columnIndex, char in list(enumerate(block.text()))[startColumnIndex:]: yield block, columnIndex, char block = block.next() # Next lines while block.isValid(): ...
def _iterateDocumentCharsForward(self, block, startColumnIndex)
Traverse document forward. Yield (block, columnIndex, char) Raise _TimeoutException if time is over
4.750523
3.515059
1.351477
# Chars in the start line endTime = time.time() + self._MAX_SEARCH_TIME_SEC for columnIndex, char in reversed(list(enumerate(block.text()[:startColumnIndex]))): yield block, columnIndex, char block = block.previous() # Next lines while block.isValid(...
def _iterateDocumentCharsBackward(self, block, startColumnIndex)
Traverse document forward. Yield (block, columnIndex, char) Raise _TimeoutException if time is over
4.21651
3.110909
1.355395
if bracket in self._START_BRACKETS: charsGenerator = self._iterateDocumentCharsForward(block, columnIndex + 1) else: charsGenerator = self._iterateDocumentCharsBackward(block, columnIndex) depth = 1 oposite = self._OPOSITE_BRACKET[bracket] for bl...
def _findMatchingBracket(self, bracket, qpart, block, columnIndex)
Find matching bracket for the bracket. Return (block, columnIndex) or (None, None) Raise _TimeoutException, if time is over
3.813597
3.915547
0.973963
selection = QTextEdit.ExtraSelection() if matched: bgColor = Qt.green else: bgColor = Qt.red selection.format.setBackground(bgColor) selection.cursor = QTextCursor(block) selection.cursor.setPosition(block.position() + columnIndex) ...
def _makeMatchSelection(self, block, columnIndex, matched)
Make matched or unmatched QTextEdit.ExtraSelection
2.142805
1.881727
1.138744
try: matchedBlock, matchedColumnIndex = self._findMatchingBracket(bracket, qpart, block, columnIndex) except _TimeoutException: # not found, time is over return[] # highlight nothing if matchedBlock is not None: self.currentMatchedBrackets = ((block...
def _highlightBracket(self, bracket, qpart, block, columnIndex)
Highlight bracket and matching bracket Return tuple of QTextEdit.ExtraSelection's
3.973464
3.811101
1.042603
blockText = block.text() if columnIndex < len(blockText) and \ blockText[columnIndex] in self._ALL_BRACKETS and \ qpart.isCode(block, columnIndex): return self._highlightBracket(blockText[columnIndex], qpart, block, columnIndex) elif columnIndex > ...
def extraSelections(self, qpart, block, columnIndex)
List of QTextEdit.ExtraSelection's, which highlighte brackets
2.940439
2.722139
1.080194
if a.format == b.format and \ a.start == b.start and \ a.length == b.length: return 0 else: return cmp(id(a), id(b))
def _cmpFormatRanges(a, b)
PyQt does not define proper comparison for QTextLayout.FormatRange Define it to check correctly, if formats has changed. It is important for the performance
2.521149
2.769732
0.91025
dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isCode(data, column)
def isCode(self, block, column)
Check if character at column is a a code
7.808517
8.199626
0.952302
dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isComment(data, column)
def isComment(self, block, column)
Check if character at column is a comment
7.876111
7.937848
0.992223
dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isBlockComment(data, column)
def isBlockComment(self, block, column)
Check if character at column is a block comment
7.283656
7.624322
0.955318
dataObject = block.userData() data = dataObject.data if dataObject is not None else None return self._syntax.isHereDoc(data, column)
def isHereDoc(self, block, column)
Check if character at column is a here document
7.783542
8.368964
0.930048
endTime = time.time() + timeout block = fromBlock lineData = self._lineData(block.previous()) while block.isValid() and block != atLeastUntilBlock: if time.time() >= endTime: # time is over, schedule parsing later and release event loop self._pendingBlockNu...
def _highlighBlocks(self, fromBlock, atLeastUntilBlock, timeout)
Emit sizeChanged when highlighting finished, because document size might change. See andreikop/enki issue #191
3.336718
3.104952
1.074644
if re.search(r'^\s*;;;', block.text()): return '' elif re.search(r'^\s*;;', block.text()): #try to align with the next line nextBlock = self._nextNonEmptyBlock(block) if nextBlock.isValid(): return self._blockIndent(nextBlock) ...
def computeSmartIndent(self, block, ch)
special rules: ;;; -> indent 0 ;; -> align with next line, if possible ; -> usually on the same line as code -> ignore
5.471166
4.918432
1.11238
def wrapper(*args, **kwargs): self = args[0] with self._qpart: func(*args, **kwargs) return wrapper
def _atomicModification(func)
Decorator Make document modification atomic
4.735753
5.046943
0.938341
if index < 0: index = len(self) + index if index < 0 or index >= self._doc.blockCount(): raise IndexError('Invalid block index', index) return index
def _checkAndConvertIndex(self, index)
Check integer index, convert from less than zero notation
4.460642
3.919117
1.138175
cursor = QTextCursor(self._doc) cursor.movePosition(QTextCursor.End) cursor.insertBlock() cursor.insertText(text)
def append(self, text)
Append line to the end
3.367366
3.442956
0.978045
if index < 0 or index > self._doc.blockCount(): raise IndexError('Invalid block index', index) if index == 0: # first cursor = QTextCursor(self._doc.firstBlock()) cursor.insertText(text) cursor.insertBlock() elif index != self._doc.block...
def insert(self, index, text)
Insert line to the document
2.957508
2.88342
1.025695
lineText = block.text() prevLineText = self._prevNonEmptyBlock(block).text() alignOnly = char == '' if alignOnly: # XML might be all in one line, in which case we want to break that up. tokens = re.split(r'>\s*<', lineText) if len(tokens) >...
def computeSmartIndent(self, block, char)
Compute indent for the block
4.011034
3.953453
1.014565
block = self._prevNonEmptyBlock(block) while block.isValid() and self._isCommentBlock(block): block = self._prevNonEmptyBlock(block) return block
def _prevNonCommentBlock(self, block)
Return the closest non-empty line, ignoring comments (result <= line). Return -1 if the document
3.09581
3.484935
0.888341
return column >= self._lastColumn(block) or \ self._isComment(block, self._nextNonSpaceColumn(block, column + 1))
def _isLastCodeColumn(self, block, column)
Return true if the given column is at least equal to the column that contains the last non-whitespace character at the given line, or if the rest of the line is a comment.
6.580703
5.064176
1.299462
currentPos = -1 currentBlock = None currentColumn = None currentChar = None for char in '({[': try: foundBlock, foundColumn = self.findBracketBackward(block, column, char) except ValueError: continue els...
def lastAnchor(self, block, column)
Find the last open bracket before the current line. Return (block, column, char) or (None, None, None)
3.580777
3.226116
1.109934
prevBlock = self._prevNonCommentBlock(block) while prevBlock.isValid() and \ (((prevBlock == block.previous()) and self._isBlockContinuing(prevBlock)) or \ self.isStmtContinuing(prevBlock)): block = prevBlock prevBlock = self._prevNonCommentB...
def findStmtStart(self, block)
Return the first line that is not preceded by a "continuing" line. Return currBlock if currBlock <= 0
4.485328
4.029511
1.11312
if ch == "" or ch == "\n": return True # Explicit align or new line match = rxUnindent.match(block.text()) return match is not None and \ match.group(3) == ""
def _isValidTrigger(block, ch)
check if the trigger characters are in the right context, otherwise running the indenter might be annoying to the user
12.724175
11.679955
1.089403
stmtEnd = self._prevNonCommentBlock(block) stmtStart = self.findStmtStart(stmtEnd) return Statement(self._qpart, stmtStart, stmtEnd)
def findPrevStmt(self, block)
Returns a tuple that contains the first and last line of the previous statement before line.
8.804711
9.072548
0.970478