repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
cognitect/transit-python
transit/reader.py
Reader.register
def register(self, key_or_tag, f_val): """Register a custom transit tag and decoder/parser function for use during reads. """ self.reader.decoder.register(key_or_tag, f_val)
python
def register(self, key_or_tag, f_val): """Register a custom transit tag and decoder/parser function for use during reads. """ self.reader.decoder.register(key_or_tag, f_val)
[ "def", "register", "(", "self", ",", "key_or_tag", ",", "f_val", ")", ":", "self", ".", "reader", ".", "decoder", ".", "register", "(", "key_or_tag", ",", "f_val", ")" ]
Register a custom transit tag and decoder/parser function for use during reads.
[ "Register", "a", "custom", "transit", "tag", "and", "decoder", "/", "parser", "function", "for", "use", "during", "reads", "." ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/reader.py#L45-L49
cognitect/transit-python
transit/reader.py
Reader.readeach
def readeach(self, stream, **kwargs): """Temporary hook for API while streaming reads are in experimental phase. Read each object from stream as available with generator. JSON blocks indefinitely waiting on JSON entities to arrive. MsgPack requires unpacker property to be fed stream using unpacker.feed() method. """ for o in self.reader.loadeach(stream): yield o
python
def readeach(self, stream, **kwargs): """Temporary hook for API while streaming reads are in experimental phase. Read each object from stream as available with generator. JSON blocks indefinitely waiting on JSON entities to arrive. MsgPack requires unpacker property to be fed stream using unpacker.feed() method. """ for o in self.reader.loadeach(stream): yield o
[ "def", "readeach", "(", "self", ",", "stream", ",", "*", "*", "kwargs", ")", ":", "for", "o", "in", "self", ".", "reader", ".", "loadeach", "(", "stream", ")", ":", "yield", "o" ]
Temporary hook for API while streaming reads are in experimental phase. Read each object from stream as available with generator. JSON blocks indefinitely waiting on JSON entities to arrive. MsgPack requires unpacker property to be fed stream using unpacker.feed() method.
[ "Temporary", "hook", "for", "API", "while", "streaming", "reads", "are", "in", "experimental", "phase", ".", "Read", "each", "object", "from", "stream", "as", "available", "with", "generator", ".", "JSON", "blocks", "indefinitely", "waiting", "on", "JSON", "entities", "to", "arrive", ".", "MsgPack", "requires", "unpacker", "property", "to", "be", "fed", "stream", "using", "unpacker", ".", "feed", "()", "method", "." ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/reader.py#L51-L59
cognitect/transit-python
transit/rolling_cache.py
RollingCache.decode
def decode(self, name, as_map_key=False): """Always returns the name""" if is_cache_key(name) and (name in self.key_to_value): return self.key_to_value[name] return self.encache(name) if is_cacheable(name, as_map_key) else name
python
def decode(self, name, as_map_key=False): """Always returns the name""" if is_cache_key(name) and (name in self.key_to_value): return self.key_to_value[name] return self.encache(name) if is_cacheable(name, as_map_key) else name
[ "def", "decode", "(", "self", ",", "name", ",", "as_map_key", "=", "False", ")", ":", "if", "is_cache_key", "(", "name", ")", "and", "(", "name", "in", "self", ".", "key_to_value", ")", ":", "return", "self", ".", "key_to_value", "[", "name", "]", "return", "self", ".", "encache", "(", "name", ")", "if", "is_cacheable", "(", "name", ",", "as_map_key", ")", "else", "name" ]
Always returns the name
[ "Always", "returns", "the", "name" ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/rolling_cache.py#L61-L65
cognitect/transit-python
transit/rolling_cache.py
RollingCache.encode
def encode(self, name, as_map_key=False): """Returns the name the first time and the key after that""" if name in self.key_to_value: return self.key_to_value[name] return self.encache(name) if is_cacheable(name, as_map_key) else name
python
def encode(self, name, as_map_key=False): """Returns the name the first time and the key after that""" if name in self.key_to_value: return self.key_to_value[name] return self.encache(name) if is_cacheable(name, as_map_key) else name
[ "def", "encode", "(", "self", ",", "name", ",", "as_map_key", "=", "False", ")", ":", "if", "name", "in", "self", ".", "key_to_value", ":", "return", "self", ".", "key_to_value", "[", "name", "]", "return", "self", ".", "encache", "(", "name", ")", "if", "is_cacheable", "(", "name", ",", "as_map_key", ")", "else", "name" ]
Returns the name the first time and the key after that
[ "Returns", "the", "name", "the", "first", "time", "and", "the", "key", "after", "that" ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/rolling_cache.py#L67-L71
cognitect/transit-python
transit/sosjson.py
read_chunk
def read_chunk(stream): """Ignore whitespace outside of strings. If we hit a string, read it in its entirety. """ chunk = stream.read(1) while chunk in SKIP: chunk = stream.read(1) if chunk == "\"": chunk += stream.read(1) while not chunk.endswith("\""): if chunk[-1] == ESCAPE: chunk += stream.read(2) else: chunk += stream.read(1) return chunk
python
def read_chunk(stream): """Ignore whitespace outside of strings. If we hit a string, read it in its entirety. """ chunk = stream.read(1) while chunk in SKIP: chunk = stream.read(1) if chunk == "\"": chunk += stream.read(1) while not chunk.endswith("\""): if chunk[-1] == ESCAPE: chunk += stream.read(2) else: chunk += stream.read(1) return chunk
[ "def", "read_chunk", "(", "stream", ")", ":", "chunk", "=", "stream", ".", "read", "(", "1", ")", "while", "chunk", "in", "SKIP", ":", "chunk", "=", "stream", ".", "read", "(", "1", ")", "if", "chunk", "==", "\"\\\"\"", ":", "chunk", "+=", "stream", ".", "read", "(", "1", ")", "while", "not", "chunk", ".", "endswith", "(", "\"\\\"\"", ")", ":", "if", "chunk", "[", "-", "1", "]", "==", "ESCAPE", ":", "chunk", "+=", "stream", ".", "read", "(", "2", ")", "else", ":", "chunk", "+=", "stream", ".", "read", "(", "1", ")", "return", "chunk" ]
Ignore whitespace outside of strings. If we hit a string, read it in its entirety.
[ "Ignore", "whitespace", "outside", "of", "strings", ".", "If", "we", "hit", "a", "string", "read", "it", "in", "its", "entirety", "." ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/sosjson.py#L25-L39
cognitect/transit-python
transit/sosjson.py
items
def items(stream, **kwargs): """External facing items. Will return item from stream as available. Currently waits in loop waiting for next item. Can pass keywords that json.loads accepts (such as object_pairs_hook) """ for s in yield_json(stream): yield json.loads(s, **kwargs)
python
def items(stream, **kwargs): """External facing items. Will return item from stream as available. Currently waits in loop waiting for next item. Can pass keywords that json.loads accepts (such as object_pairs_hook) """ for s in yield_json(stream): yield json.loads(s, **kwargs)
[ "def", "items", "(", "stream", ",", "*", "*", "kwargs", ")", ":", "for", "s", "in", "yield_json", "(", "stream", ")", ":", "yield", "json", ".", "loads", "(", "s", ",", "*", "*", "kwargs", ")" ]
External facing items. Will return item from stream as available. Currently waits in loop waiting for next item. Can pass keywords that json.loads accepts (such as object_pairs_hook)
[ "External", "facing", "items", ".", "Will", "return", "item", "from", "stream", "as", "available", ".", "Currently", "waits", "in", "loop", "waiting", "for", "next", "item", ".", "Can", "pass", "keywords", "that", "json", ".", "loads", "accepts", "(", "such", "as", "object_pairs_hook", ")" ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/sosjson.py#L42-L48
cognitect/transit-python
transit/sosjson.py
yield_json
def yield_json(stream): """Uses array and object delimiter counts for balancing. """ buff = u"" arr_count = 0 obj_count = 0 while True: buff += read_chunk(stream) # If we finish parsing all objs or arrays, yield a finished JSON # entity. if buff.endswith('{'): obj_count += 1 if buff.endswith('['): arr_count += 1 if buff.endswith(']'): arr_count -= 1 if obj_count == arr_count == 0: json_item = copy(buff) buff = u"" yield json_item if buff.endswith('}'): obj_count -= 1 if obj_count == arr_count == 0: json_item = copy(buff) buff = u"" yield json_item
python
def yield_json(stream): """Uses array and object delimiter counts for balancing. """ buff = u"" arr_count = 0 obj_count = 0 while True: buff += read_chunk(stream) # If we finish parsing all objs or arrays, yield a finished JSON # entity. if buff.endswith('{'): obj_count += 1 if buff.endswith('['): arr_count += 1 if buff.endswith(']'): arr_count -= 1 if obj_count == arr_count == 0: json_item = copy(buff) buff = u"" yield json_item if buff.endswith('}'): obj_count -= 1 if obj_count == arr_count == 0: json_item = copy(buff) buff = u"" yield json_item
[ "def", "yield_json", "(", "stream", ")", ":", "buff", "=", "u\"\"", "arr_count", "=", "0", "obj_count", "=", "0", "while", "True", ":", "buff", "+=", "read_chunk", "(", "stream", ")", "# If we finish parsing all objs or arrays, yield a finished JSON", "# entity.", "if", "buff", ".", "endswith", "(", "'{'", ")", ":", "obj_count", "+=", "1", "if", "buff", ".", "endswith", "(", "'['", ")", ":", "arr_count", "+=", "1", "if", "buff", ".", "endswith", "(", "']'", ")", ":", "arr_count", "-=", "1", "if", "obj_count", "==", "arr_count", "==", "0", ":", "json_item", "=", "copy", "(", "buff", ")", "buff", "=", "u\"\"", "yield", "json_item", "if", "buff", ".", "endswith", "(", "'}'", ")", ":", "obj_count", "-=", "1", "if", "obj_count", "==", "arr_count", "==", "0", ":", "json_item", "=", "copy", "(", "buff", ")", "buff", "=", "u\"\"", "yield", "json_item" ]
Uses array and object delimiter counts for balancing.
[ "Uses", "array", "and", "object", "delimiter", "counts", "for", "balancing", "." ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/sosjson.py#L51-L77
cognitect/transit-python
transit/writer.py
Marshaler.are_stringable_keys
def are_stringable_keys(self, m): """Test whether the keys within a map are stringable - a simple map, that can be optimized and whose keys can be cached """ for x in m.keys(): if len(self.handlers[x].tag(x)) != 1: return False return True
python
def are_stringable_keys(self, m): """Test whether the keys within a map are stringable - a simple map, that can be optimized and whose keys can be cached """ for x in m.keys(): if len(self.handlers[x].tag(x)) != 1: return False return True
[ "def", "are_stringable_keys", "(", "self", ",", "m", ")", ":", "for", "x", "in", "m", ".", "keys", "(", ")", ":", "if", "len", "(", "self", ".", "handlers", "[", "x", "]", ".", "tag", "(", "x", ")", ")", "!=", "1", ":", "return", "False", "return", "True" ]
Test whether the keys within a map are stringable - a simple map, that can be optimized and whose keys can be cached
[ "Test", "whether", "the", "keys", "within", "a", "map", "are", "stringable", "-", "a", "simple", "map", "that", "can", "be", "optimized", "and", "whose", "keys", "can", "be", "cached" ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/writer.py#L112-L119
cognitect/transit-python
transit/writer.py
Marshaler.marshal
def marshal(self, obj, as_map_key, cache): """Marshal an individual obj, potentially as part of another container object (like a list/dictionary/etc). Specify if this object is a key to a map/dict, and pass in the current cache being used. This method should only be called by a top-level marshalling call and should not be considered an entry-point for integration. """ handler = self.handlers[obj] tag = handler.tag(obj) f = marshal_dispatch.get(tag) if f: f(self, obj, handler.string_rep(obj) if as_map_key else handler.rep(obj), as_map_key, cache) else: self.emit_encoded(tag, handler, obj, as_map_key, cache)
python
def marshal(self, obj, as_map_key, cache): """Marshal an individual obj, potentially as part of another container object (like a list/dictionary/etc). Specify if this object is a key to a map/dict, and pass in the current cache being used. This method should only be called by a top-level marshalling call and should not be considered an entry-point for integration. """ handler = self.handlers[obj] tag = handler.tag(obj) f = marshal_dispatch.get(tag) if f: f(self, obj, handler.string_rep(obj) if as_map_key else handler.rep(obj), as_map_key, cache) else: self.emit_encoded(tag, handler, obj, as_map_key, cache)
[ "def", "marshal", "(", "self", ",", "obj", ",", "as_map_key", ",", "cache", ")", ":", "handler", "=", "self", ".", "handlers", "[", "obj", "]", "tag", "=", "handler", ".", "tag", "(", "obj", ")", "f", "=", "marshal_dispatch", ".", "get", "(", "tag", ")", "if", "f", ":", "f", "(", "self", ",", "obj", ",", "handler", ".", "string_rep", "(", "obj", ")", "if", "as_map_key", "else", "handler", ".", "rep", "(", "obj", ")", ",", "as_map_key", ",", "cache", ")", "else", ":", "self", ".", "emit_encoded", "(", "tag", ",", "handler", ",", "obj", ",", "as_map_key", ",", "cache", ")" ]
Marshal an individual obj, potentially as part of another container object (like a list/dictionary/etc). Specify if this object is a key to a map/dict, and pass in the current cache being used. This method should only be called by a top-level marshalling call and should not be considered an entry-point for integration.
[ "Marshal", "an", "individual", "obj", "potentially", "as", "part", "of", "another", "container", "object", "(", "like", "a", "list", "/", "dictionary", "/", "etc", ")", ".", "Specify", "if", "this", "object", "is", "a", "key", "to", "a", "map", "/", "dict", "and", "pass", "in", "the", "current", "cache", "being", "used", ".", "This", "method", "should", "only", "be", "called", "by", "a", "top", "-", "level", "marshalling", "call", "and", "should", "not", "be", "considered", "an", "entry", "-", "point", "for", "integration", "." ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/writer.py#L193-L207
cognitect/transit-python
transit/writer.py
Marshaler.marshal_top
def marshal_top(self, obj, cache=None): """Given a complete object that needs to be marshaled into Transit data, and optionally a cache, dispatch accordingly, and flush the data directly into the IO stream. """ if not cache: cache = RollingCache() handler = self.handlers[obj] tag = handler.tag(obj) if tag: if len(tag) == 1: self.marshal(TaggedValue(QUOTE, obj), False, cache) else: self.marshal(obj, False, cache) self.flush() else: raise AssertionError("Handler must provide a non-nil tag: " + str(handler))
python
def marshal_top(self, obj, cache=None): """Given a complete object that needs to be marshaled into Transit data, and optionally a cache, dispatch accordingly, and flush the data directly into the IO stream. """ if not cache: cache = RollingCache() handler = self.handlers[obj] tag = handler.tag(obj) if tag: if len(tag) == 1: self.marshal(TaggedValue(QUOTE, obj), False, cache) else: self.marshal(obj, False, cache) self.flush() else: raise AssertionError("Handler must provide a non-nil tag: " + str(handler))
[ "def", "marshal_top", "(", "self", ",", "obj", ",", "cache", "=", "None", ")", ":", "if", "not", "cache", ":", "cache", "=", "RollingCache", "(", ")", "handler", "=", "self", ".", "handlers", "[", "obj", "]", "tag", "=", "handler", ".", "tag", "(", "obj", ")", "if", "tag", ":", "if", "len", "(", "tag", ")", "==", "1", ":", "self", ".", "marshal", "(", "TaggedValue", "(", "QUOTE", ",", "obj", ")", ",", "False", ",", "cache", ")", "else", ":", "self", ".", "marshal", "(", "obj", ",", "False", ",", "cache", ")", "self", ".", "flush", "(", ")", "else", ":", "raise", "AssertionError", "(", "\"Handler must provide a non-nil tag: \"", "+", "str", "(", "handler", ")", ")" ]
Given a complete object that needs to be marshaled into Transit data, and optionally a cache, dispatch accordingly, and flush the data directly into the IO stream.
[ "Given", "a", "complete", "object", "that", "needs", "to", "be", "marshaled", "into", "Transit", "data", "and", "optionally", "a", "cache", "dispatch", "accordingly", "and", "flush", "the", "data", "directly", "into", "the", "IO", "stream", "." ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/writer.py#L209-L227
cognitect/transit-python
transit/writer.py
Marshaler.dispatch_map
def dispatch_map(self, rep, as_map_key, cache): """Used to determine and dipatch the writing of a map - a simple map with strings as keys, or a complex map, whose keys are also compound types. """ if self.are_stringable_keys(rep): return self.emit_map(rep, as_map_key, cache) return self.emit_cmap(rep, as_map_key, cache)
python
def dispatch_map(self, rep, as_map_key, cache): """Used to determine and dipatch the writing of a map - a simple map with strings as keys, or a complex map, whose keys are also compound types. """ if self.are_stringable_keys(rep): return self.emit_map(rep, as_map_key, cache) return self.emit_cmap(rep, as_map_key, cache)
[ "def", "dispatch_map", "(", "self", ",", "rep", ",", "as_map_key", ",", "cache", ")", ":", "if", "self", ".", "are_stringable_keys", "(", "rep", ")", ":", "return", "self", ".", "emit_map", "(", "rep", ",", "as_map_key", ",", "cache", ")", "return", "self", ".", "emit_cmap", "(", "rep", ",", "as_map_key", ",", "cache", ")" ]
Used to determine and dipatch the writing of a map - a simple map with strings as keys, or a complex map, whose keys are also compound types.
[ "Used", "to", "determine", "and", "dipatch", "the", "writing", "of", "a", "map", "-", "a", "simple", "map", "with", "strings", "as", "keys", "or", "a", "complex", "map", "whose", "keys", "are", "also", "compound", "types", "." ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/writer.py#L229-L236
cognitect/transit-python
transit/writer.py
JsonMarshaler.emit_map
def emit_map(self, m, _, cache): """Emits array as per default JSON spec.""" self.emit_array_start(None) self.marshal(MAP_AS_ARR, False, cache) for k, v in m.items(): self.marshal(k, True, cache) self.marshal(v, False, cache) self.emit_array_end()
python
def emit_map(self, m, _, cache): """Emits array as per default JSON spec.""" self.emit_array_start(None) self.marshal(MAP_AS_ARR, False, cache) for k, v in m.items(): self.marshal(k, True, cache) self.marshal(v, False, cache) self.emit_array_end()
[ "def", "emit_map", "(", "self", ",", "m", ",", "_", ",", "cache", ")", ":", "self", ".", "emit_array_start", "(", "None", ")", "self", ".", "marshal", "(", "MAP_AS_ARR", ",", "False", ",", "cache", ")", "for", "k", ",", "v", "in", "m", ".", "items", "(", ")", ":", "self", ".", "marshal", "(", "k", ",", "True", ",", "cache", ")", "self", ".", "marshal", "(", "v", ",", "False", ",", "cache", ")", "self", ".", "emit_array_end", "(", ")" ]
Emits array as per default JSON spec.
[ "Emits", "array", "as", "per", "default", "JSON", "spec", "." ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/writer.py#L353-L360
cognitect/transit-python
transit/decoder.py
Decoder.decode
def decode(self, node, cache=None, as_map_key=False): """Given a node of data (any supported decodeable obj - string, dict, list), return the decoded object. Optionally set the current decode cache [None]. If None, a new RollingCache is instantiated and used. You may also hit to the decoder that this node is to be treated as a map key [False]. This is used internally. """ if not cache: cache = RollingCache() return self._decode(node, cache, as_map_key)
python
def decode(self, node, cache=None, as_map_key=False): """Given a node of data (any supported decodeable obj - string, dict, list), return the decoded object. Optionally set the current decode cache [None]. If None, a new RollingCache is instantiated and used. You may also hit to the decoder that this node is to be treated as a map key [False]. This is used internally. """ if not cache: cache = RollingCache() return self._decode(node, cache, as_map_key)
[ "def", "decode", "(", "self", ",", "node", ",", "cache", "=", "None", ",", "as_map_key", "=", "False", ")", ":", "if", "not", "cache", ":", "cache", "=", "RollingCache", "(", ")", "return", "self", ".", "_decode", "(", "node", ",", "cache", ",", "as_map_key", ")" ]
Given a node of data (any supported decodeable obj - string, dict, list), return the decoded object. Optionally set the current decode cache [None]. If None, a new RollingCache is instantiated and used. You may also hit to the decoder that this node is to be treated as a map key [False]. This is used internally.
[ "Given", "a", "node", "of", "data", "(", "any", "supported", "decodeable", "obj", "-", "string", "dict", "list", ")", "return", "the", "decoded", "object", ".", "Optionally", "set", "the", "current", "decode", "cache", "[", "None", "]", ".", "If", "None", "a", "new", "RollingCache", "is", "instantiated", "and", "used", ".", "You", "may", "also", "hit", "to", "the", "decoder", "that", "this", "node", "is", "to", "be", "treated", "as", "a", "map", "key", "[", "False", "]", ".", "This", "is", "used", "internally", "." ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/decoder.py#L73-L82
cognitect/transit-python
transit/decoder.py
Decoder.decode_list
def decode_list(self, node, cache, as_map_key): """Special case decodes map-as-array. Otherwise lists are treated as Python lists. Arguments follow the same convention as the top-level 'decode' function. """ if node: if node[0] == MAP_AS_ARR: # key must be decoded before value for caching to work. returned_dict = {} for k, v in pairs(node[1:]): key = self._decode(k, cache, True) val = self._decode(v, cache, as_map_key) returned_dict[key] = val return transit_types.frozendict(returned_dict) decoded = self._decode(node[0], cache, as_map_key) if isinstance(decoded, Tag): return self.decode_tag(decoded.tag, self._decode(node[1], cache, as_map_key)) return tuple(self._decode(x, cache, as_map_key) for x in node)
python
def decode_list(self, node, cache, as_map_key): """Special case decodes map-as-array. Otherwise lists are treated as Python lists. Arguments follow the same convention as the top-level 'decode' function. """ if node: if node[0] == MAP_AS_ARR: # key must be decoded before value for caching to work. returned_dict = {} for k, v in pairs(node[1:]): key = self._decode(k, cache, True) val = self._decode(v, cache, as_map_key) returned_dict[key] = val return transit_types.frozendict(returned_dict) decoded = self._decode(node[0], cache, as_map_key) if isinstance(decoded, Tag): return self.decode_tag(decoded.tag, self._decode(node[1], cache, as_map_key)) return tuple(self._decode(x, cache, as_map_key) for x in node)
[ "def", "decode_list", "(", "self", ",", "node", ",", "cache", ",", "as_map_key", ")", ":", "if", "node", ":", "if", "node", "[", "0", "]", "==", "MAP_AS_ARR", ":", "# key must be decoded before value for caching to work.", "returned_dict", "=", "{", "}", "for", "k", ",", "v", "in", "pairs", "(", "node", "[", "1", ":", "]", ")", ":", "key", "=", "self", ".", "_decode", "(", "k", ",", "cache", ",", "True", ")", "val", "=", "self", ".", "_decode", "(", "v", ",", "cache", ",", "as_map_key", ")", "returned_dict", "[", "key", "]", "=", "val", "return", "transit_types", ".", "frozendict", "(", "returned_dict", ")", "decoded", "=", "self", ".", "_decode", "(", "node", "[", "0", "]", ",", "cache", ",", "as_map_key", ")", "if", "isinstance", "(", "decoded", ",", "Tag", ")", ":", "return", "self", ".", "decode_tag", "(", "decoded", ".", "tag", ",", "self", ".", "_decode", "(", "node", "[", "1", "]", ",", "cache", ",", "as_map_key", ")", ")", "return", "tuple", "(", "self", ".", "_decode", "(", "x", ",", "cache", ",", "as_map_key", ")", "for", "x", "in", "node", ")" ]
Special case decodes map-as-array. Otherwise lists are treated as Python lists. Arguments follow the same convention as the top-level 'decode' function.
[ "Special", "case", "decodes", "map", "-", "as", "-", "array", ".", "Otherwise", "lists", "are", "treated", "as", "Python", "lists", "." ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/decoder.py#L100-L121
cognitect/transit-python
transit/decoder.py
Decoder.decode_string
def decode_string(self, string, cache, as_map_key): """Decode a string - arguments follow the same convention as the top-level 'decode' function. """ if is_cache_key(string): return self.parse_string(cache.decode(string, as_map_key), cache, as_map_key) if is_cacheable(string, as_map_key): cache.encode(string, as_map_key) return self.parse_string(string, cache, as_map_key)
python
def decode_string(self, string, cache, as_map_key): """Decode a string - arguments follow the same convention as the top-level 'decode' function. """ if is_cache_key(string): return self.parse_string(cache.decode(string, as_map_key), cache, as_map_key) if is_cacheable(string, as_map_key): cache.encode(string, as_map_key) return self.parse_string(string, cache, as_map_key)
[ "def", "decode_string", "(", "self", ",", "string", ",", "cache", ",", "as_map_key", ")", ":", "if", "is_cache_key", "(", "string", ")", ":", "return", "self", ".", "parse_string", "(", "cache", ".", "decode", "(", "string", ",", "as_map_key", ")", ",", "cache", ",", "as_map_key", ")", "if", "is_cacheable", "(", "string", ",", "as_map_key", ")", ":", "cache", ".", "encode", "(", "string", ",", "as_map_key", ")", "return", "self", ".", "parse_string", "(", "string", ",", "cache", ",", "as_map_key", ")" ]
Decode a string - arguments follow the same convention as the top-level 'decode' function.
[ "Decode", "a", "string", "-", "arguments", "follow", "the", "same", "convention", "as", "the", "top", "-", "level", "decode", "function", "." ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/decoder.py#L123-L132
cognitect/transit-python
transit/decoder.py
Decoder.register
def register(self, key_or_tag, obj): """Register a custom Transit tag and new parsing function with the decoder. Also, you can optionally set the 'default_decoder' with this function. Your new tag and parse/decode function will be added to the interal dictionary of decoders for this Decoder object. """ if key_or_tag == "default_decoder": self.options["default_decoder"] = obj else: self.decoders[key_or_tag] = obj
python
def register(self, key_or_tag, obj): """Register a custom Transit tag and new parsing function with the decoder. Also, you can optionally set the 'default_decoder' with this function. Your new tag and parse/decode function will be added to the interal dictionary of decoders for this Decoder object. """ if key_or_tag == "default_decoder": self.options["default_decoder"] = obj else: self.decoders[key_or_tag] = obj
[ "def", "register", "(", "self", ",", "key_or_tag", ",", "obj", ")", ":", "if", "key_or_tag", "==", "\"default_decoder\"", ":", "self", ".", "options", "[", "\"default_decoder\"", "]", "=", "obj", "else", ":", "self", ".", "decoders", "[", "key_or_tag", "]", "=", "obj" ]
Register a custom Transit tag and new parsing function with the decoder. Also, you can optionally set the 'default_decoder' with this function. Your new tag and parse/decode function will be added to the interal dictionary of decoders for this Decoder object.
[ "Register", "a", "custom", "Transit", "tag", "and", "new", "parsing", "function", "with", "the", "decoder", ".", "Also", "you", "can", "optionally", "set", "the", "default_decoder", "with", "this", "function", ".", "Your", "new", "tag", "and", "parse", "/", "decode", "function", "will", "be", "added", "to", "the", "interal", "dictionary", "of", "decoders", "for", "this", "Decoder", "object", "." ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/decoder.py#L177-L186
cognitect/transit-python
transit/read_handlers.py
UuidHandler.from_rep
def from_rep(u): """Given a string, return a UUID object.""" if isinstance(u, pyversion.string_types): return uuid.UUID(u) # hack to remove signs a = ctypes.c_ulong(u[0]) b = ctypes.c_ulong(u[1]) combined = a.value << 64 | b.value return uuid.UUID(int=combined)
python
def from_rep(u): """Given a string, return a UUID object.""" if isinstance(u, pyversion.string_types): return uuid.UUID(u) # hack to remove signs a = ctypes.c_ulong(u[0]) b = ctypes.c_ulong(u[1]) combined = a.value << 64 | b.value return uuid.UUID(int=combined)
[ "def", "from_rep", "(", "u", ")", ":", "if", "isinstance", "(", "u", ",", "pyversion", ".", "string_types", ")", ":", "return", "uuid", ".", "UUID", "(", "u", ")", "# hack to remove signs", "a", "=", "ctypes", ".", "c_ulong", "(", "u", "[", "0", "]", ")", "b", "=", "ctypes", ".", "c_ulong", "(", "u", "[", "1", "]", ")", "combined", "=", "a", ".", "value", "<<", "64", "|", "b", ".", "value", "return", "uuid", ".", "UUID", "(", "int", "=", "combined", ")" ]
Given a string, return a UUID object.
[ "Given", "a", "string", "return", "a", "UUID", "object", "." ]
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/read_handlers.py#L78-L87
kytos/python-openflow
pyof/v0x04/asynchronous/packet_in.py
PacketIn.in_port
def in_port(self): """Retrieve the 'in_port' that generated the PacketIn. This method will look for the OXM_TLV with type OFPXMT_OFB_IN_PORT on the `oxm_match_fields` field from `match` field and return its value, if the OXM exists. Returns: The integer number of the 'in_port' that generated the PacketIn if it exists. Otherwise return None. """ in_port = self.match.get_field(OxmOfbMatchField.OFPXMT_OFB_IN_PORT) return int.from_bytes(in_port, 'big')
python
def in_port(self): """Retrieve the 'in_port' that generated the PacketIn. This method will look for the OXM_TLV with type OFPXMT_OFB_IN_PORT on the `oxm_match_fields` field from `match` field and return its value, if the OXM exists. Returns: The integer number of the 'in_port' that generated the PacketIn if it exists. Otherwise return None. """ in_port = self.match.get_field(OxmOfbMatchField.OFPXMT_OFB_IN_PORT) return int.from_bytes(in_port, 'big')
[ "def", "in_port", "(", "self", ")", ":", "in_port", "=", "self", ".", "match", ".", "get_field", "(", "OxmOfbMatchField", ".", "OFPXMT_OFB_IN_PORT", ")", "return", "int", ".", "from_bytes", "(", "in_port", ",", "'big'", ")" ]
Retrieve the 'in_port' that generated the PacketIn. This method will look for the OXM_TLV with type OFPXMT_OFB_IN_PORT on the `oxm_match_fields` field from `match` field and return its value, if the OXM exists. Returns: The integer number of the 'in_port' that generated the PacketIn if it exists. Otherwise return None.
[ "Retrieve", "the", "in_port", "that", "generated", "the", "PacketIn", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/asynchronous/packet_in.py#L88-L101
kytos/python-openflow
pyof/v0x01/controller2switch/packet_out.py
PacketOut.unpack
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**. This class' unpack method is like the :meth:`.GenericMessage.unpack` one, except for the ``actions`` attribute which has a length determined by the ``actions_len`` attribute. Args: buff (bytes): Binary data package to be unpacked, without the header. offset (int): Where to begin unpacking. """ begin = offset for attribute_name, class_attribute in self.get_class_attributes(): if type(class_attribute).__name__ != "Header": attribute = deepcopy(class_attribute) if attribute_name == 'actions': length = self.actions_len.value attribute.unpack(buff[begin:begin+length]) else: attribute.unpack(buff, begin) setattr(self, attribute_name, attribute) begin += attribute.get_size()
python
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**. This class' unpack method is like the :meth:`.GenericMessage.unpack` one, except for the ``actions`` attribute which has a length determined by the ``actions_len`` attribute. Args: buff (bytes): Binary data package to be unpacked, without the header. offset (int): Where to begin unpacking. """ begin = offset for attribute_name, class_attribute in self.get_class_attributes(): if type(class_attribute).__name__ != "Header": attribute = deepcopy(class_attribute) if attribute_name == 'actions': length = self.actions_len.value attribute.unpack(buff[begin:begin+length]) else: attribute.unpack(buff, begin) setattr(self, attribute_name, attribute) begin += attribute.get_size()
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "begin", "=", "offset", "for", "attribute_name", ",", "class_attribute", "in", "self", ".", "get_class_attributes", "(", ")", ":", "if", "type", "(", "class_attribute", ")", ".", "__name__", "!=", "\"Header\"", ":", "attribute", "=", "deepcopy", "(", "class_attribute", ")", "if", "attribute_name", "==", "'actions'", ":", "length", "=", "self", ".", "actions_len", ".", "value", "attribute", ".", "unpack", "(", "buff", "[", "begin", ":", "begin", "+", "length", "]", ")", "else", ":", "attribute", ".", "unpack", "(", "buff", ",", "begin", ")", "setattr", "(", "self", ",", "attribute_name", ",", "attribute", ")", "begin", "+=", "attribute", ".", "get_size", "(", ")" ]
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**. This class' unpack method is like the :meth:`.GenericMessage.unpack` one, except for the ``actions`` attribute which has a length determined by the ``actions_len`` attribute. Args: buff (bytes): Binary data package to be unpacked, without the header. offset (int): Where to begin unpacking.
[ "Unpack", "a", "binary", "message", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/controller2switch/packet_out.py#L79-L105
kytos/python-openflow
pyof/v0x01/controller2switch/packet_out.py
PacketOut._update_actions_len
def _update_actions_len(self): """Update the actions_len field based on actions value.""" if isinstance(self.actions, ListOfActions): self.actions_len = self.actions.get_size() else: self.actions_len = ListOfActions(self.actions).get_size()
python
def _update_actions_len(self): """Update the actions_len field based on actions value.""" if isinstance(self.actions, ListOfActions): self.actions_len = self.actions.get_size() else: self.actions_len = ListOfActions(self.actions).get_size()
[ "def", "_update_actions_len", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "actions", ",", "ListOfActions", ")", ":", "self", ".", "actions_len", "=", "self", ".", "actions", ".", "get_size", "(", ")", "else", ":", "self", ".", "actions_len", "=", "ListOfActions", "(", "self", ".", "actions", ")", ".", "get_size", "(", ")" ]
Update the actions_len field based on actions value.
[ "Update", "the", "actions_len", "field", "based", "on", "actions", "value", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/controller2switch/packet_out.py#L107-L112
kytos/python-openflow
pyof/v0x01/controller2switch/packet_out.py
PacketOut._validate_in_port
def _validate_in_port(self): """Validate in_port attribute. A valid port is either: * Greater than 0 and less than or equals to Port.OFPP_MAX * One of the valid virtual ports: Port.OFPP_LOCAL, Port.OFPP_CONTROLLER or Port.OFPP_NONE Raises: ValidationError: If in_port is an invalid port. """ is_valid_range = self.in_port > 0 and self.in_port <= Port.OFPP_MAX is_valid_virtual_in_ports = self.in_port in _VIRT_IN_PORTS if (is_valid_range or is_valid_virtual_in_ports) is False: raise ValidationError(f'{self.in_port} is not a valid input port.')
python
def _validate_in_port(self): """Validate in_port attribute. A valid port is either: * Greater than 0 and less than or equals to Port.OFPP_MAX * One of the valid virtual ports: Port.OFPP_LOCAL, Port.OFPP_CONTROLLER or Port.OFPP_NONE Raises: ValidationError: If in_port is an invalid port. """ is_valid_range = self.in_port > 0 and self.in_port <= Port.OFPP_MAX is_valid_virtual_in_ports = self.in_port in _VIRT_IN_PORTS if (is_valid_range or is_valid_virtual_in_ports) is False: raise ValidationError(f'{self.in_port} is not a valid input port.')
[ "def", "_validate_in_port", "(", "self", ")", ":", "is_valid_range", "=", "self", ".", "in_port", ">", "0", "and", "self", ".", "in_port", "<=", "Port", ".", "OFPP_MAX", "is_valid_virtual_in_ports", "=", "self", ".", "in_port", "in", "_VIRT_IN_PORTS", "if", "(", "is_valid_range", "or", "is_valid_virtual_in_ports", ")", "is", "False", ":", "raise", "ValidationError", "(", "f'{self.in_port} is not a valid input port.'", ")" ]
Validate in_port attribute. A valid port is either: * Greater than 0 and less than or equals to Port.OFPP_MAX * One of the valid virtual ports: Port.OFPP_LOCAL, Port.OFPP_CONTROLLER or Port.OFPP_NONE Raises: ValidationError: If in_port is an invalid port.
[ "Validate", "in_port", "attribute", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/controller2switch/packet_out.py#L114-L131
kytos/python-openflow
pyof/v0x01/controller2switch/stats_request.py
StatsRequest.pack
def pack(self, value=None): """Pack according to :attr:`body_type`. Make `body` a binary pack before packing this object. Then, restore body. """ backup = self.body if not value: value = self.body if hasattr(value, 'pack'): self.body = value.pack() stats_request_packed = super().pack() self.body = backup return stats_request_packed
python
def pack(self, value=None): """Pack according to :attr:`body_type`. Make `body` a binary pack before packing this object. Then, restore body. """ backup = self.body if not value: value = self.body if hasattr(value, 'pack'): self.body = value.pack() stats_request_packed = super().pack() self.body = backup return stats_request_packed
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "backup", "=", "self", ".", "body", "if", "not", "value", ":", "value", "=", "self", ".", "body", "if", "hasattr", "(", "value", ",", "'pack'", ")", ":", "self", ".", "body", "=", "value", ".", "pack", "(", ")", "stats_request_packed", "=", "super", "(", ")", ".", "pack", "(", ")", "self", ".", "body", "=", "backup", "return", "stats_request_packed" ]
Pack according to :attr:`body_type`. Make `body` a binary pack before packing this object. Then, restore body.
[ "Pack", "according", "to", ":", "attr", ":", "body_type", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/controller2switch/stats_request.py#L41-L56
kytos/python-openflow
pyof/v0x01/controller2switch/stats_request.py
StatsRequest.unpack
def unpack(self, buff, offset=0): """Unpack according to :attr:`body_type`.""" super().unpack(buff) class_name = self._get_body_class() buff = self.body.value self.body = FixedTypeList(pyof_class=class_name) self.body.unpack(buff)
python
def unpack(self, buff, offset=0): """Unpack according to :attr:`body_type`.""" super().unpack(buff) class_name = self._get_body_class() buff = self.body.value self.body = FixedTypeList(pyof_class=class_name) self.body.unpack(buff)
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "super", "(", ")", ".", "unpack", "(", "buff", ")", "class_name", "=", "self", ".", "_get_body_class", "(", ")", "buff", "=", "self", ".", "body", ".", "value", "self", ".", "body", "=", "FixedTypeList", "(", "pyof_class", "=", "class_name", ")", "self", ".", "body", ".", "unpack", "(", "buff", ")" ]
Unpack according to :attr:`body_type`.
[ "Unpack", "according", "to", ":", "attr", ":", "body_type", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/controller2switch/stats_request.py#L58-L65
kytos/python-openflow
pyof/v0x04/controller2switch/common.py
TableFeaturePropType.find_class
def find_class(self): """Return a class related with this type.""" if self.value <= 1: return InstructionsProperty elif self.value <= 3: return NextTablesProperty elif self.value <= 7: return ActionsProperty return OxmProperty
python
def find_class(self): """Return a class related with this type.""" if self.value <= 1: return InstructionsProperty elif self.value <= 3: return NextTablesProperty elif self.value <= 7: return ActionsProperty return OxmProperty
[ "def", "find_class", "(", "self", ")", ":", "if", "self", ".", "value", "<=", "1", ":", "return", "InstructionsProperty", "elif", "self", ".", "value", "<=", "3", ":", "return", "NextTablesProperty", "elif", "self", ".", "value", "<=", "7", ":", "return", "ActionsProperty", "return", "OxmProperty" ]
Return a class related with this type.
[ "Return", "a", "class", "related", "with", "this", "type", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/controller2switch/common.py#L95-L104
kytos/python-openflow
pyof/v0x04/controller2switch/common.py
Property.unpack
def unpack(self, buff=None, 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`: If unpack fails. """ property_type = UBInt16(enum_ref=TableFeaturePropType) property_type.unpack(buff, offset) self.__class__ = TableFeaturePropType(property_type.value).find_class() length = UBInt16() length.unpack(buff, offset=offset+2) super().unpack(buff[:offset+length.value], offset=offset)
python
def unpack(self, buff=None, 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`: If unpack fails. """ property_type = UBInt16(enum_ref=TableFeaturePropType) property_type.unpack(buff, offset) self.__class__ = TableFeaturePropType(property_type.value).find_class() length = UBInt16() length.unpack(buff, offset=offset+2) super().unpack(buff[:offset+length.value], offset=offset)
[ "def", "unpack", "(", "self", ",", "buff", "=", "None", ",", "offset", "=", "0", ")", ":", "property_type", "=", "UBInt16", "(", "enum_ref", "=", "TableFeaturePropType", ")", "property_type", ".", "unpack", "(", "buff", ",", "offset", ")", "self", ".", "__class__", "=", "TableFeaturePropType", "(", "property_type", ".", "value", ")", ".", "find_class", "(", ")", "length", "=", "UBInt16", "(", ")", "length", ".", "unpack", "(", "buff", ",", "offset", "=", "offset", "+", "2", ")", "super", "(", ")", ".", "unpack", "(", "buff", "[", ":", "offset", "+", "length", ".", "value", "]", ",", "offset", "=", "offset", ")" ]
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`: If unpack fails.
[ "Unpack", "*", "buff", "*", "into", "this", "object", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/controller2switch/common.py#L410-L430
kytos/python-openflow
pyof/v0x04/controller2switch/common.py
TableFeatures.unpack
def unpack(self, buff=None, 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`: If unpack fails. """ length = UBInt16() length.unpack(buff, offset) super().unpack(buff[:offset+length.value], offset)
python
def unpack(self, buff=None, 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`: If unpack fails. """ length = UBInt16() length.unpack(buff, offset) super().unpack(buff[:offset+length.value], offset)
[ "def", "unpack", "(", "self", ",", "buff", "=", "None", ",", "offset", "=", "0", ")", ":", "length", "=", "UBInt16", "(", ")", "length", ".", "unpack", "(", "buff", ",", "offset", ")", "super", "(", ")", ".", "unpack", "(", "buff", "[", ":", "offset", "+", "length", ".", "value", "]", ",", "offset", ")" ]
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`: If unpack fails.
[ "Unpack", "*", "buff", "*", "into", "this", "object", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/controller2switch/common.py#L634-L650
kytos/python-openflow
pyof/v0x01/common/utils.py
new_message_from_message_type
def new_message_from_message_type(message_type): """Given an OpenFlow Message Type, return an empty message of that type. Args: messageType (:class:`~pyof.v0x01.common.header.Type`): Python-openflow message. Returns: Empty OpenFlow message of the requested message type. Raises: KytosUndefinedMessageType: Unkown Message_Type. """ message_type = str(message_type) if message_type not in MESSAGE_TYPES: raise ValueError('"{}" is not known.'.format(message_type)) message_class = MESSAGE_TYPES.get(message_type) message_instance = message_class() return message_instance
python
def new_message_from_message_type(message_type): """Given an OpenFlow Message Type, return an empty message of that type. Args: messageType (:class:`~pyof.v0x01.common.header.Type`): Python-openflow message. Returns: Empty OpenFlow message of the requested message type. Raises: KytosUndefinedMessageType: Unkown Message_Type. """ message_type = str(message_type) if message_type not in MESSAGE_TYPES: raise ValueError('"{}" is not known.'.format(message_type)) message_class = MESSAGE_TYPES.get(message_type) message_instance = message_class() return message_instance
[ "def", "new_message_from_message_type", "(", "message_type", ")", ":", "message_type", "=", "str", "(", "message_type", ")", "if", "message_type", "not", "in", "MESSAGE_TYPES", ":", "raise", "ValueError", "(", "'\"{}\" is not known.'", ".", "format", "(", "message_type", ")", ")", "message_class", "=", "MESSAGE_TYPES", ".", "get", "(", "message_type", ")", "message_instance", "=", "message_class", "(", ")", "return", "message_instance" ]
Given an OpenFlow Message Type, return an empty message of that type. Args: messageType (:class:`~pyof.v0x01.common.header.Type`): Python-openflow message. Returns: Empty OpenFlow message of the requested message type. Raises: KytosUndefinedMessageType: Unkown Message_Type.
[ "Given", "an", "OpenFlow", "Message", "Type", "return", "an", "empty", "message", "of", "that", "type", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/common/utils.py#L66-L88
kytos/python-openflow
pyof/v0x01/common/utils.py
new_message_from_header
def new_message_from_header(header): """Given an OF Header, return an empty message of header's message_type. Args: header (~pyof.v0x01.common.header.Header): Unpacked OpenFlow Header. Returns: Empty OpenFlow message of the same type of message_type attribute from the given header. The header attribute of the message will be populated. Raises: KytosUndefinedMessageType: Unkown Message_Type. """ message_type = header.message_type if not isinstance(message_type, Type): try: if isinstance(message_type, str): message_type = Type[message_type] elif isinstance(message_type, int): message_type = Type(message_type) except ValueError: raise ValueError message = new_message_from_message_type(message_type) message.header.xid = header.xid message.header.length = header.length return message
python
def new_message_from_header(header): """Given an OF Header, return an empty message of header's message_type. Args: header (~pyof.v0x01.common.header.Header): Unpacked OpenFlow Header. Returns: Empty OpenFlow message of the same type of message_type attribute from the given header. The header attribute of the message will be populated. Raises: KytosUndefinedMessageType: Unkown Message_Type. """ message_type = header.message_type if not isinstance(message_type, Type): try: if isinstance(message_type, str): message_type = Type[message_type] elif isinstance(message_type, int): message_type = Type(message_type) except ValueError: raise ValueError message = new_message_from_message_type(message_type) message.header.xid = header.xid message.header.length = header.length return message
[ "def", "new_message_from_header", "(", "header", ")", ":", "message_type", "=", "header", ".", "message_type", "if", "not", "isinstance", "(", "message_type", ",", "Type", ")", ":", "try", ":", "if", "isinstance", "(", "message_type", ",", "str", ")", ":", "message_type", "=", "Type", "[", "message_type", "]", "elif", "isinstance", "(", "message_type", ",", "int", ")", ":", "message_type", "=", "Type", "(", "message_type", ")", "except", "ValueError", ":", "raise", "ValueError", "message", "=", "new_message_from_message_type", "(", "message_type", ")", "message", ".", "header", ".", "xid", "=", "header", ".", "xid", "message", ".", "header", ".", "length", "=", "header", ".", "length", "return", "message" ]
Given an OF Header, return an empty message of header's message_type. Args: header (~pyof.v0x01.common.header.Header): Unpacked OpenFlow Header. Returns: Empty OpenFlow message of the same type of message_type attribute from the given header. The header attribute of the message will be populated. Raises: KytosUndefinedMessageType: Unkown Message_Type.
[ "Given", "an", "OF", "Header", "return", "an", "empty", "message", "of", "header", "s", "message_type", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/common/utils.py#L91-L120
kytos/python-openflow
pyof/v0x01/common/utils.py
unpack_message
def unpack_message(buffer): """Unpack the whole buffer, including header pack. Args: buffer (bytes): Bytes representation of a openflow message. Returns: object: Instance of openflow message. """ hdr_size = Header().get_size() hdr_buff, msg_buff = buffer[:hdr_size], buffer[hdr_size:] header = Header() header.unpack(hdr_buff) message = new_message_from_header(header) message.unpack(msg_buff) return message
python
def unpack_message(buffer): """Unpack the whole buffer, including header pack. Args: buffer (bytes): Bytes representation of a openflow message. Returns: object: Instance of openflow message. """ hdr_size = Header().get_size() hdr_buff, msg_buff = buffer[:hdr_size], buffer[hdr_size:] header = Header() header.unpack(hdr_buff) message = new_message_from_header(header) message.unpack(msg_buff) return message
[ "def", "unpack_message", "(", "buffer", ")", ":", "hdr_size", "=", "Header", "(", ")", ".", "get_size", "(", ")", "hdr_buff", ",", "msg_buff", "=", "buffer", "[", ":", "hdr_size", "]", ",", "buffer", "[", "hdr_size", ":", "]", "header", "=", "Header", "(", ")", "header", ".", "unpack", "(", "hdr_buff", ")", "message", "=", "new_message_from_header", "(", "header", ")", "message", ".", "unpack", "(", "msg_buff", ")", "return", "message" ]
Unpack the whole buffer, including header pack. Args: buffer (bytes): Bytes representation of a openflow message. Returns: object: Instance of openflow message.
[ "Unpack", "the", "whole", "buffer", "including", "header", "pack", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/common/utils.py#L123-L139
kytos/python-openflow
pyof/v0x04/controller2switch/meter_mod.py
MeterBandHeader.unpack
def unpack(self, buff=None, 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`: If unpack fails. """ band_type = UBInt16(enum_ref=MeterBandType) band_type.unpack(buff, offset) self.__class__ = MeterBandType(band_type.value).find_class() length = UBInt16() length.unpack(buff, offset=offset+2) super().unpack(buff[:offset+length.value], offset)
python
def unpack(self, buff=None, 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`: If unpack fails. """ band_type = UBInt16(enum_ref=MeterBandType) band_type.unpack(buff, offset) self.__class__ = MeterBandType(band_type.value).find_class() length = UBInt16() length.unpack(buff, offset=offset+2) super().unpack(buff[:offset+length.value], offset)
[ "def", "unpack", "(", "self", ",", "buff", "=", "None", ",", "offset", "=", "0", ")", ":", "band_type", "=", "UBInt16", "(", "enum_ref", "=", "MeterBandType", ")", "band_type", ".", "unpack", "(", "buff", ",", "offset", ")", "self", ".", "__class__", "=", "MeterBandType", "(", "band_type", ".", "value", ")", ".", "find_class", "(", ")", "length", "=", "UBInt16", "(", ")", "length", ".", "unpack", "(", "buff", ",", "offset", "=", "offset", "+", "2", ")", "super", "(", ")", ".", "unpack", "(", "buff", "[", ":", "offset", "+", "length", ".", "value", "]", ",", "offset", ")" ]
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`: If unpack fails.
[ "Unpack", "*", "buff", "*", "into", "this", "object", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/controller2switch/meter_mod.py#L96-L117
kytos/python-openflow
pyof/v0x04/controller2switch/multipart_reply.py
MultipartReply.pack
def pack(self, value=None): """Pack a StatsReply using the object's attributes. This method will pack the attribute body and multipart_type before pack the StatsReply object, then will return this struct as a binary data. Returns: stats_reply_packed (bytes): Binary data with StatsReply packed. """ buff = self.body if not value: value = self.body if value: if isinstance(value, (list, FixedTypeList)): obj = self._get_body_instance() obj.extend(value) elif hasattr(value, 'pack'): obj = value self.body = obj.pack() multipart_packed = super().pack() self.body = buff return multipart_packed
python
def pack(self, value=None): """Pack a StatsReply using the object's attributes. This method will pack the attribute body and multipart_type before pack the StatsReply object, then will return this struct as a binary data. Returns: stats_reply_packed (bytes): Binary data with StatsReply packed. """ buff = self.body if not value: value = self.body if value: if isinstance(value, (list, FixedTypeList)): obj = self._get_body_instance() obj.extend(value) elif hasattr(value, 'pack'): obj = value self.body = obj.pack() multipart_packed = super().pack() self.body = buff return multipart_packed
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "buff", "=", "self", ".", "body", "if", "not", "value", ":", "value", "=", "self", ".", "body", "if", "value", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "FixedTypeList", ")", ")", ":", "obj", "=", "self", ".", "_get_body_instance", "(", ")", "obj", ".", "extend", "(", "value", ")", "elif", "hasattr", "(", "value", ",", "'pack'", ")", ":", "obj", "=", "value", "self", ".", "body", "=", "obj", ".", "pack", "(", ")", "multipart_packed", "=", "super", "(", ")", ".", "pack", "(", ")", "self", ".", "body", "=", "buff", "return", "multipart_packed" ]
Pack a StatsReply using the object's attributes. This method will pack the attribute body and multipart_type before pack the StatsReply object, then will return this struct as a binary data. Returns: stats_reply_packed (bytes): Binary data with StatsReply packed.
[ "Pack", "a", "StatsReply", "using", "the", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/controller2switch/multipart_reply.py#L87-L113
kytos/python-openflow
pyof/v0x04/controller2switch/multipart_reply.py
MultipartReply.unpack
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**. This class' unpack method is like the :meth:`.GenericMessage.unpack` one, except for the ``body`` attribute which has its type determined by the ``multipart_type`` attribute. Args: buff (bytes): Binary data package to be unpacked, without the header. """ super().unpack(buff[offset:]) self._unpack_body()
python
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**. This class' unpack method is like the :meth:`.GenericMessage.unpack` one, except for the ``body`` attribute which has its type determined by the ``multipart_type`` attribute. Args: buff (bytes): Binary data package to be unpacked, without the header. """ super().unpack(buff[offset:]) self._unpack_body()
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "super", "(", ")", ".", "unpack", "(", "buff", "[", "offset", ":", "]", ")", "self", ".", "_unpack_body", "(", ")" ]
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**. This class' unpack method is like the :meth:`.GenericMessage.unpack` one, except for the ``body`` attribute which has its type determined by the ``multipart_type`` attribute. Args: buff (bytes): Binary data package to be unpacked, without the header.
[ "Unpack", "a", "binary", "message", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/controller2switch/multipart_reply.py#L115-L131
kytos/python-openflow
pyof/v0x04/controller2switch/multipart_reply.py
MultipartReply._unpack_body
def _unpack_body(self): """Unpack `body` replace it by the result.""" obj = self._get_body_instance() obj.unpack(self.body.value) self.body = obj
python
def _unpack_body(self): """Unpack `body` replace it by the result.""" obj = self._get_body_instance() obj.unpack(self.body.value) self.body = obj
[ "def", "_unpack_body", "(", "self", ")", ":", "obj", "=", "self", ".", "_get_body_instance", "(", ")", "obj", ".", "unpack", "(", "self", ".", "body", ".", "value", ")", "self", ".", "body", "=", "obj" ]
Unpack `body` replace it by the result.
[ "Unpack", "body", "replace", "it", "by", "the", "result", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/controller2switch/multipart_reply.py#L133-L137
kytos/python-openflow
pyof/v0x04/controller2switch/multipart_reply.py
MultipartReply._get_body_instance
def _get_body_instance(self): """Return the body instance.""" exp_header = ExperimenterMultipartHeader simple_body = {MultipartType.OFPMP_DESC: Desc, MultipartType.OFPMP_GROUP_FEATURES: GroupFeatures, MultipartType.OFPMP_METER_FEATURES: MeterFeatures, MultipartType.OFPMP_EXPERIMENTER: exp_header} array_of_bodies = {MultipartType.OFPMP_FLOW: FlowStats, MultipartType.OFPMP_AGGREGATE: AggregateStatsReply, MultipartType.OFPMP_TABLE: TableStats, MultipartType.OFPMP_PORT_STATS: PortStats, MultipartType.OFPMP_QUEUE: QueueStats, MultipartType.OFPMP_GROUP: GroupStats, MultipartType.OFPMP_GROUP_DESC: GroupDescStats, MultipartType.OFPMP_METER: MeterStats, MultipartType.OFPMP_METER_CONFIG: MeterConfig, MultipartType.OFPMP_TABLE_FEATURES: TableFeatures, MultipartType.OFPMP_PORT_DESC: Port} if isinstance(self.multipart_type, (int, UBInt16)): self.multipart_type = self.multipart_type.enum_ref( self.multipart_type.value) pyof_class = simple_body.get(self.multipart_type, None) if pyof_class: return pyof_class() array_of_class = array_of_bodies.get(self.multipart_type, None) if array_of_class: return FixedTypeList(pyof_class=array_of_class) return BinaryData(b'')
python
def _get_body_instance(self): """Return the body instance.""" exp_header = ExperimenterMultipartHeader simple_body = {MultipartType.OFPMP_DESC: Desc, MultipartType.OFPMP_GROUP_FEATURES: GroupFeatures, MultipartType.OFPMP_METER_FEATURES: MeterFeatures, MultipartType.OFPMP_EXPERIMENTER: exp_header} array_of_bodies = {MultipartType.OFPMP_FLOW: FlowStats, MultipartType.OFPMP_AGGREGATE: AggregateStatsReply, MultipartType.OFPMP_TABLE: TableStats, MultipartType.OFPMP_PORT_STATS: PortStats, MultipartType.OFPMP_QUEUE: QueueStats, MultipartType.OFPMP_GROUP: GroupStats, MultipartType.OFPMP_GROUP_DESC: GroupDescStats, MultipartType.OFPMP_METER: MeterStats, MultipartType.OFPMP_METER_CONFIG: MeterConfig, MultipartType.OFPMP_TABLE_FEATURES: TableFeatures, MultipartType.OFPMP_PORT_DESC: Port} if isinstance(self.multipart_type, (int, UBInt16)): self.multipart_type = self.multipart_type.enum_ref( self.multipart_type.value) pyof_class = simple_body.get(self.multipart_type, None) if pyof_class: return pyof_class() array_of_class = array_of_bodies.get(self.multipart_type, None) if array_of_class: return FixedTypeList(pyof_class=array_of_class) return BinaryData(b'')
[ "def", "_get_body_instance", "(", "self", ")", ":", "exp_header", "=", "ExperimenterMultipartHeader", "simple_body", "=", "{", "MultipartType", ".", "OFPMP_DESC", ":", "Desc", ",", "MultipartType", ".", "OFPMP_GROUP_FEATURES", ":", "GroupFeatures", ",", "MultipartType", ".", "OFPMP_METER_FEATURES", ":", "MeterFeatures", ",", "MultipartType", ".", "OFPMP_EXPERIMENTER", ":", "exp_header", "}", "array_of_bodies", "=", "{", "MultipartType", ".", "OFPMP_FLOW", ":", "FlowStats", ",", "MultipartType", ".", "OFPMP_AGGREGATE", ":", "AggregateStatsReply", ",", "MultipartType", ".", "OFPMP_TABLE", ":", "TableStats", ",", "MultipartType", ".", "OFPMP_PORT_STATS", ":", "PortStats", ",", "MultipartType", ".", "OFPMP_QUEUE", ":", "QueueStats", ",", "MultipartType", ".", "OFPMP_GROUP", ":", "GroupStats", ",", "MultipartType", ".", "OFPMP_GROUP_DESC", ":", "GroupDescStats", ",", "MultipartType", ".", "OFPMP_METER", ":", "MeterStats", ",", "MultipartType", ".", "OFPMP_METER_CONFIG", ":", "MeterConfig", ",", "MultipartType", ".", "OFPMP_TABLE_FEATURES", ":", "TableFeatures", ",", "MultipartType", ".", "OFPMP_PORT_DESC", ":", "Port", "}", "if", "isinstance", "(", "self", ".", "multipart_type", ",", "(", "int", ",", "UBInt16", ")", ")", ":", "self", ".", "multipart_type", "=", "self", ".", "multipart_type", ".", "enum_ref", "(", "self", ".", "multipart_type", ".", "value", ")", "pyof_class", "=", "simple_body", ".", "get", "(", "self", ".", "multipart_type", ",", "None", ")", "if", "pyof_class", ":", "return", "pyof_class", "(", ")", "array_of_class", "=", "array_of_bodies", ".", "get", "(", "self", ".", "multipart_type", ",", "None", ")", "if", "array_of_class", ":", "return", "FixedTypeList", "(", "pyof_class", "=", "array_of_class", ")", "return", "BinaryData", "(", "b''", ")" ]
Return the body instance.
[ "Return", "the", "body", "instance", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/controller2switch/multipart_reply.py#L139-L171
kytos/python-openflow
pyof/v0x04/controller2switch/multipart_reply.py
FlowStats.unpack
def unpack(self, buff, offset=0): """Unpack a binary message into this object's attributes. Pass the correct length for list unpacking. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. """ unpack_length = UBInt16() unpack_length.unpack(buff, offset) super().unpack(buff[:offset+unpack_length], offset)
python
def unpack(self, buff, offset=0): """Unpack a binary message into this object's attributes. Pass the correct length for list unpacking. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. """ unpack_length = UBInt16() unpack_length.unpack(buff, offset) super().unpack(buff[:offset+unpack_length], offset)
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "unpack_length", "=", "UBInt16", "(", ")", "unpack_length", ".", "unpack", "(", "buff", ",", "offset", ")", "super", "(", ")", ".", "unpack", "(", "buff", "[", ":", "offset", "+", "unpack_length", "]", ",", "offset", ")" ]
Unpack a binary message into this object's attributes. Pass the correct length for list unpacking. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking.
[ "Unpack", "a", "binary", "message", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/controller2switch/multipart_reply.py#L296-L307
kytos/python-openflow
pyof/v0x04/controller2switch/multipart_reply.py
MeterStats.unpack
def unpack(self, buff=None, 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`: If unpack fails. """ length = UBInt16() length.unpack(buff, offset) length.unpack(buff, offset=offset+MeterStats.meter_id.get_size()) super().unpack(buff[:offset+length.value], offset=offset)
python
def unpack(self, buff=None, 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`: If unpack fails. """ length = UBInt16() length.unpack(buff, offset) length.unpack(buff, offset=offset+MeterStats.meter_id.get_size()) super().unpack(buff[:offset+length.value], offset=offset)
[ "def", "unpack", "(", "self", ",", "buff", "=", "None", ",", "offset", "=", "0", ")", ":", "length", "=", "UBInt16", "(", ")", "length", ".", "unpack", "(", "buff", ",", "offset", ")", "length", ".", "unpack", "(", "buff", ",", "offset", "=", "offset", "+", "MeterStats", ".", "meter_id", ".", "get_size", "(", ")", ")", "super", "(", ")", ".", "unpack", "(", "buff", "[", ":", "offset", "+", "length", ".", "value", "]", ",", "offset", "=", "offset", ")" ]
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`: If unpack fails.
[ "Unpack", "*", "buff", "*", "into", "this", "object", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/controller2switch/multipart_reply.py#L684-L702
kytos/python-openflow
pyof/v0x04/common/flow_instructions.py
InstructionType.find_class
def find_class(self): """Return a class related with this type.""" classes = {1: InstructionGotoTable, 2: InstructionWriteMetadata, 3: InstructionWriteAction, 4: InstructionApplyAction, 5: InstructionClearAction, 6: InstructionMeter} return classes.get(self.value, None)
python
def find_class(self): """Return a class related with this type.""" classes = {1: InstructionGotoTable, 2: InstructionWriteMetadata, 3: InstructionWriteAction, 4: InstructionApplyAction, 5: InstructionClearAction, 6: InstructionMeter} return classes.get(self.value, None)
[ "def", "find_class", "(", "self", ")", ":", "classes", "=", "{", "1", ":", "InstructionGotoTable", ",", "2", ":", "InstructionWriteMetadata", ",", "3", ":", "InstructionWriteAction", ",", "4", ":", "InstructionApplyAction", ",", "5", ":", "InstructionClearAction", ",", "6", ":", "InstructionMeter", "}", "return", "classes", ".", "get", "(", "self", ".", "value", ",", "None", ")" ]
Return a class related with this type.
[ "Return", "a", "class", "related", "with", "this", "type", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_instructions.py#L46-L51
kytos/python-openflow
pyof/v0x04/common/flow_instructions.py
Instruction.unpack
def unpack(self, buff=None, 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`: If unpack fails. """ instruction_type = UBInt16(enum_ref=InstructionType) instruction_type.unpack(buff, offset) self.__class__ = InstructionType(instruction_type.value).find_class() length = UBInt16() length.unpack(buff, offset=offset+2) super().unpack(buff[:offset+length.value], offset)
python
def unpack(self, buff=None, 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`: If unpack fails. """ instruction_type = UBInt16(enum_ref=InstructionType) instruction_type.unpack(buff, offset) self.__class__ = InstructionType(instruction_type.value).find_class() length = UBInt16() length.unpack(buff, offset=offset+2) super().unpack(buff[:offset+length.value], offset)
[ "def", "unpack", "(", "self", ",", "buff", "=", "None", ",", "offset", "=", "0", ")", ":", "instruction_type", "=", "UBInt16", "(", "enum_ref", "=", "InstructionType", ")", "instruction_type", ".", "unpack", "(", "buff", ",", "offset", ")", "self", ".", "__class__", "=", "InstructionType", "(", "instruction_type", ".", "value", ")", ".", "find_class", "(", ")", "length", "=", "UBInt16", "(", ")", "length", ".", "unpack", "(", "buff", ",", "offset", "=", "offset", "+", "2", ")", "super", "(", ")", ".", "unpack", "(", "buff", "[", ":", "offset", "+", "length", ".", "value", "]", ",", "offset", ")" ]
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`: If unpack fails.
[ "Unpack", "*", "buff", "*", "into", "this", "object", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_instructions.py#L100-L121
kytos/python-openflow
pyof/v0x04/common/flow_match.py
OxmTLV.unpack
def unpack(self, buff, offset=0): """Unpack the buffer into a OxmTLV. Args: buff (bytes): The binary data to be unpacked. offset (int): If we need to shift the beginning of the data. """ super().unpack(buff, offset) # Recover field from field_and_hasmask. try: self.oxm_field = self._unpack_oxm_field() except ValueError as exception: raise UnpackException(exception) # The last bit of field_and_mask is oxm_hasmask self.oxm_hasmask = (self.oxm_field_and_mask & 1) == 1 # as boolean # Unpack oxm_value that has oxm_length bytes start = offset + 4 # 4 bytes: class, field_and_mask and length end = start + self.oxm_length self.oxm_value = buff[start:end]
python
def unpack(self, buff, offset=0): """Unpack the buffer into a OxmTLV. Args: buff (bytes): The binary data to be unpacked. offset (int): If we need to shift the beginning of the data. """ super().unpack(buff, offset) # Recover field from field_and_hasmask. try: self.oxm_field = self._unpack_oxm_field() except ValueError as exception: raise UnpackException(exception) # The last bit of field_and_mask is oxm_hasmask self.oxm_hasmask = (self.oxm_field_and_mask & 1) == 1 # as boolean # Unpack oxm_value that has oxm_length bytes start = offset + 4 # 4 bytes: class, field_and_mask and length end = start + self.oxm_length self.oxm_value = buff[start:end]
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "super", "(", ")", ".", "unpack", "(", "buff", ",", "offset", ")", "# Recover field from field_and_hasmask.", "try", ":", "self", ".", "oxm_field", "=", "self", ".", "_unpack_oxm_field", "(", ")", "except", "ValueError", "as", "exception", ":", "raise", "UnpackException", "(", "exception", ")", "# The last bit of field_and_mask is oxm_hasmask", "self", ".", "oxm_hasmask", "=", "(", "self", ".", "oxm_field_and_mask", "&", "1", ")", "==", "1", "# as boolean", "# Unpack oxm_value that has oxm_length bytes", "start", "=", "offset", "+", "4", "# 4 bytes: class, field_and_mask and length", "end", "=", "start", "+", "self", ".", "oxm_length", "self", ".", "oxm_value", "=", "buff", "[", "start", ":", "end", "]" ]
Unpack the buffer into a OxmTLV. Args: buff (bytes): The binary data to be unpacked. offset (int): If we need to shift the beginning of the data.
[ "Unpack", "the", "buffer", "into", "a", "OxmTLV", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L214-L235
kytos/python-openflow
pyof/v0x04/common/flow_match.py
OxmTLV._unpack_oxm_field
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. """ 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
python
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. """ 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", ")", ":", "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" ]
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.
[ "Unpack", "oxm_field", "from", "oxm_field_and_mask", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L237-L252
kytos/python-openflow
pyof/v0x04/common/flow_match.py
OxmTLV._update_length
def _update_length(self): """Update length field. Update the oxm_length field with the packed payload length. """ payload = type(self).oxm_value.pack(self.oxm_value) self.oxm_length = len(payload)
python
def _update_length(self): """Update length field. Update the oxm_length field with the packed payload length. """ payload = type(self).oxm_value.pack(self.oxm_value) self.oxm_length = len(payload)
[ "def", "_update_length", "(", "self", ")", ":", "payload", "=", "type", "(", "self", ")", ".", "oxm_value", ".", "pack", "(", "self", ".", "oxm_value", ")", "self", ".", "oxm_length", "=", "len", "(", "payload", ")" ]
Update length field. Update the oxm_length field with the packed payload length.
[ "Update", "length", "field", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L254-L261
kytos/python-openflow
pyof/v0x04/common/flow_match.py
OxmTLV.pack
def pack(self, value=None): """Join oxm_hasmask bit and 7-bit oxm_field.""" 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) field_bits = field_int << 1 # 2. hasmask bit hasmask_bit = self.oxm_hasmask & 1 # 3. Add hasmask bit to field value self.oxm_field_and_mask = field_bits + hasmask_bit self._update_length() return super().pack(value)
python
def pack(self, value=None): """Join oxm_hasmask bit and 7-bit oxm_field.""" 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) field_bits = field_int << 1 # 2. hasmask bit hasmask_bit = self.oxm_hasmask & 1 # 3. Add hasmask bit to field value self.oxm_field_and_mask = field_bits + hasmask_bit self._update_length() return super().pack(value)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "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", ")", "field_bits", "=", "field_int", "<<", "1", "# 2. hasmask bit", "hasmask_bit", "=", "self", ".", "oxm_hasmask", "&", "1", "# 3. Add hasmask bit to field value", "self", ".", "oxm_field_and_mask", "=", "field_bits", "+", "hasmask_bit", "self", ".", "_update_length", "(", ")", "return", "super", "(", ")", ".", "pack", "(", "value", ")" ]
Join oxm_hasmask bit and 7-bit oxm_field.
[ "Join", "oxm_hasmask", "bit", "and", "7", "-", "bit", "oxm_field", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L263-L281
kytos/python-openflow
pyof/v0x04/common/flow_match.py
OxmTLV._get_oxm_field_int
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 value. """ 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
python
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 value. """ 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", ")", ":", "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" ]
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 value.
[ "Return", "a", "valid", "integer", "value", "for", "oxm_field", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L283-L301
kytos/python-openflow
pyof/v0x04/common/flow_match.py
Match.pack
def pack(self, value=None): """Pack and complete the last byte by padding.""" 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}".')
python
def pack(self, value=None): """Pack and complete the last byte by padding.""" 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", ")", ":", "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}\".'", ")" ]
Pack and complete the last byte by padding.
[ "Pack", "and", "complete", "the", "last", "byte", "by", "padding", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L360-L368
kytos/python-openflow
pyof/v0x04/common/flow_match.py
Match._complete_last_byte
def _complete_last_byte(self, packet): """Pad until the packet length is a multiple of 8 (bytes).""" padded_size = self.get_size() padding_bytes = padded_size - len(packet) if padding_bytes > 0: packet += Pad(padding_bytes).pack() return packet
python
def _complete_last_byte(self, packet): """Pad until the packet length is a multiple of 8 (bytes).""" 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", ")", ":", "padded_size", "=", "self", ".", "get_size", "(", ")", "padding_bytes", "=", "padded_size", "-", "len", "(", "packet", ")", "if", "padding_bytes", ">", "0", ":", "packet", "+=", "Pad", "(", "padding_bytes", ")", ".", "pack", "(", ")", "return", "packet" ]
Pad until the packet length is a multiple of 8 (bytes).
[ "Pad", "until", "the", "packet", "length", "is", "a", "multiple", "of", "8", "(", "bytes", ")", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L370-L376
kytos/python-openflow
pyof/v0x04/common/flow_match.py
Match.get_size
def get_size(self, value=None): """Return the packet length including the padding (multiple of 8).""" 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()')
python
def get_size(self, value=None): """Return the packet length including the padding (multiple of 8).""" 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", ")", ":", "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()'", ")" ]
Return the packet length including the padding (multiple of 8).
[ "Return", "the", "packet", "length", "including", "the", "padding", "(", "multiple", "of", "8", ")", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L378-L385
kytos/python-openflow
pyof/v0x04/common/flow_match.py
Match.unpack
def unpack(self, buff, offset=0): """Discard padding bytes using the unpacked length attribute.""" 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+self.length], begin)
python
def unpack(self, buff, offset=0): """Discard padding bytes using the unpacked length attribute.""" 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+self.length], begin)
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "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", "+", "self", ".", "length", "]", ",", "begin", ")" ]
Discard padding bytes using the unpacked length attribute.
[ "Discard", "padding", "bytes", "using", "the", "unpacked", "length", "attribute", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L387-L394
kytos/python-openflow
pyof/v0x04/common/flow_match.py
Match.get_field
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 integer number of the 'field_type' if it exists. Otherwise return None. """ for field in self.oxm_match_fields: if field.oxm_field == field_type: return field.oxm_value return None
python
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 integer number of the 'field_type' if it exists. Otherwise return None. """ 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", ")", ":", "for", "field", "in", "self", ".", "oxm_match_fields", ":", "if", "field", ".", "oxm_field", "==", "field_type", ":", "return", "field", ".", "oxm_value", "return", "None" ]
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 integer number of the 'field_type' if it exists. Otherwise return None.
[ "Return", "the", "value", "for", "the", "field_type", "field", "in", "oxm_match_fields", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/flow_match.py#L396-L413
kytos/python-openflow
pyof/foundation/base.py
GenericType.value
def value(self): """Return this type's value. Returns: object: The value of an enum, bitmask, etc. """ 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
python
def value(self): """Return this type's value. Returns: object: The value of an enum, bitmask, etc. """ 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", ")", ":", "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" ]
Return this type's value. Returns: object: The value of an enum, bitmask, etc.
[ "Return", "this", "type", "s", "value", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L133-L147
kytos/python-openflow
pyof/foundation/base.py
GenericType.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.pack(objectB) b'\x05' Args: value: If the value is None, then we will pack the value of the current instance. Otherwise, if value is an instance of the same type as the current instance, then we call the pack of the value object. Otherwise, we will use the current instance pack method on the passed value. Returns: bytes: The binary representation. Raises: :exc:`~.exceptions.BadValueException`: If the value does not fit the binary format. """ 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(self._fmt, value) except struct.error: expected_type = type(self).__name__ actual_type = type(value).__name__ msg_args = expected_type, value, actual_type msg = 'Expected {}, found value "{}" of type {}'.format(*msg_args) raise PackException(msg)
python
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.pack(objectB) b'\x05' Args: value: If the value is None, then we will pack the value of the current instance. Otherwise, if value is an instance of the same type as the current instance, then we call the pack of the value object. Otherwise, we will use the current instance pack method on the passed value. Returns: bytes: The binary representation. Raises: :exc:`~.exceptions.BadValueException`: If the value does not fit the binary format. """ 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(self._fmt, value) except struct.error: expected_type = type(self).__name__ actual_type = type(value).__name__ msg_args = expected_type, value, actual_type msg = 'Expected {}, found value "{}" of type {}'.format(*msg_args) raise PackException(msg)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "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", "(", "self", ".", "_fmt", ",", "value", ")", "except", "struct", ".", "error", ":", "expected_type", "=", "type", "(", "self", ")", ".", "__name__", "actual_type", "=", "type", "(", "value", ")", ".", "__name__", "msg_args", "=", "expected_type", ",", "value", ",", "actual_type", "msg", "=", "'Expected {}, found value \"{}\" of type {}'", ".", "format", "(", "*", "msg_args", ")", "raise", "PackException", "(", "msg", ")" ]
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.pack(objectB) b'\x05' Args: value: If the value is None, then we will pack the value of the current instance. Otherwise, if value is an instance of the same type as the current instance, then we call the pack of the value object. Otherwise, we will use the current instance pack method on the passed value. Returns: bytes: The binary representation. Raises: :exc:`~.exceptions.BadValueException`: If the value does not fit the binary format.
[ "r", "Pack", "the", "value", "as", "a", "binary", "representation", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L149-L194
kytos/python-openflow
pyof/foundation/base.py
GenericType.unpack
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`: If unpack fails. """ 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(exception, self._fmt, buff, offset) raise UnpackException(msg)
python
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`: If unpack fails. """ 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(exception, self._fmt, buff, offset) raise UnpackException(msg)
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "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", "(", "exception", ",", "self", ".", "_fmt", ",", "buff", ",", "offset", ")", "raise", "UnpackException", "(", "msg", ")" ]
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`: If unpack fails.
[ "Unpack", "*", "buff", "*", "into", "this", "object", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L196-L218
kytos/python-openflow
pyof/foundation/base.py
MetaStruct._header_message_type_update
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. """ 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: msg_type_name = old_enum.name new_type = new_enum[msg_type_name] new_header.message_type = new_type return (attr[0], new_header)
python
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. """ 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: msg_type_name = old_enum.name new_type = new_enum[msg_type_name] new_header.message_type = new_type return (attr[0], new_header)
[ "def", "_header_message_type_update", "(", "obj", ",", "attr", ")", ":", "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", ":", "msg_type_name", "=", "old_enum", ".", "name", "new_type", "=", "new_enum", "[", "msg_type_name", "]", "new_header", ".", "message_type", "=", "new_type", "return", "(", "attr", "[", "0", "]", ",", "new_header", ")" ]
Update the message type on the header. Set the message_type of the header according to the message_type of the parent class.
[ "Update", "the", "message", "type", "on", "the", "header", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L347-L363
kytos/python-openflow
pyof/foundation/base.py
MetaStruct.get_pyof_version
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 if there isn't a version on the fullname. """ 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
python
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 if there isn't a version on the fullname. """ 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", ")", ":", "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" ]
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 if there isn't a version on the fullname.
[ "Get", "the", "module", "pyof", "version", "based", "on", "the", "module", "fullname", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L366-L384
kytos/python-openflow
pyof/foundation/base.py
MetaStruct.replace_pyof_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.header) version (str): The version to be 'inserted' on the module fullname. Returns: str: module fullname The new module fullname, with the replaced version, on the format "pyof.v0x01.common.header". If the requested version is the same as the one of the module_fullname or if the module_fullname is not a 'OF version' specific module, returns None. """ 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)
python
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.header) version (str): The version to be 'inserted' on the module fullname. Returns: str: module fullname The new module fullname, with the replaced version, on the format "pyof.v0x01.common.header". If the requested version is the same as the one of the module_fullname or if the module_fullname is not a 'OF version' specific module, returns None. """ 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", ")", ":", "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", ")" ]
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.header) version (str): The version to be 'inserted' on the module fullname. Returns: str: module fullname The new module fullname, with the replaced version, on the format "pyof.v0x01.common.header". If the requested version is the same as the one of the module_fullname or if the module_fullname is not a 'OF version' specific module, returns None.
[ "Replace", "the", "OF", "Version", "of", "a", "module", "fullname", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L387-L411
kytos/python-openflow
pyof/foundation/base.py
MetaStruct.get_pyof_obj_new_version
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. If the module is a "python-openflow version specific module" (starts with "pyof.v0"), then we will get it's version and if it is different from the 'new_version', then we will get the module on the 'new_version', look for the 'obj' class on the new module and return an instance of the new version of the 'obj'. Example: >>> from pyof.foundation.base import MetaStruct as ms >>> from pyof.v0x01.common.header import Header >>> name = 'header' >>> obj = Header() >>> new_version = 'v0x04' >>> header, obj2 = ms.get_pyof_obj_new_version(name, obj, new_version) >>> header 'header' >>> obj.version UBInt8(1) >>> obj2.version UBInt8(4) Args: name (str): the name of the class attribute being handled. obj (object): the class attribute itself new_version (string): the pyof version in which you want the object 'obj'. Return: (str, obj): Tuple with class name and object instance. A tuple in which the first item is the name of the class attribute (the same that was passed), and the second item is a instance of the passed class attribute. If the class attribute is not a pyof versioned attribute, then the same passed object is returned without any changes. Also, if the obj is a pyof versioned attribute, but it is already on the right version (same as new_version), then the passed obj is return. """ 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 do #: not have anything to do with it. new_mod = MetaStruct.replace_pyof_version(cls_mod, new_version) if new_mod is not None: # Loads the module new_mod = importlib.import_module(new_mod) #: Get the class from the loaded module new_cls = getattr(new_mod, cls_name) #: return the tuple with the attribute name and the instance return (name, new_cls()) return (name, obj)
python
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. If the module is a "python-openflow version specific module" (starts with "pyof.v0"), then we will get it's version and if it is different from the 'new_version', then we will get the module on the 'new_version', look for the 'obj' class on the new module and return an instance of the new version of the 'obj'. Example: >>> from pyof.foundation.base import MetaStruct as ms >>> from pyof.v0x01.common.header import Header >>> name = 'header' >>> obj = Header() >>> new_version = 'v0x04' >>> header, obj2 = ms.get_pyof_obj_new_version(name, obj, new_version) >>> header 'header' >>> obj.version UBInt8(1) >>> obj2.version UBInt8(4) Args: name (str): the name of the class attribute being handled. obj (object): the class attribute itself new_version (string): the pyof version in which you want the object 'obj'. Return: (str, obj): Tuple with class name and object instance. A tuple in which the first item is the name of the class attribute (the same that was passed), and the second item is a instance of the passed class attribute. If the class attribute is not a pyof versioned attribute, then the same passed object is returned without any changes. Also, if the obj is a pyof versioned attribute, but it is already on the right version (same as new_version), then the passed obj is return. """ 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 do #: not have anything to do with it. new_mod = MetaStruct.replace_pyof_version(cls_mod, new_version) if new_mod is not None: # Loads the module new_mod = importlib.import_module(new_mod) #: Get the class from the loaded module new_cls = getattr(new_mod, cls_name) #: return the tuple with the attribute name and the instance return (name, new_cls()) return (name, obj)
[ "def", "get_pyof_obj_new_version", "(", "name", ",", "obj", ",", "new_version", ")", ":", "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 do", "#: not have anything to do with it.", "new_mod", "=", "MetaStruct", ".", "replace_pyof_version", "(", "cls_mod", ",", "new_version", ")", "if", "new_mod", "is", "not", "None", ":", "# Loads the module", "new_mod", "=", "importlib", ".", "import_module", "(", "new_mod", ")", "#: Get the class from the loaded module", "new_cls", "=", "getattr", "(", "new_mod", ",", "cls_name", ")", "#: return the tuple with the attribute name and the instance", "return", "(", "name", ",", "new_cls", "(", ")", ")", "return", "(", "name", ",", "obj", ")" ]
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. If the module is a "python-openflow version specific module" (starts with "pyof.v0"), then we will get it's version and if it is different from the 'new_version', then we will get the module on the 'new_version', look for the 'obj' class on the new module and return an instance of the new version of the 'obj'. Example: >>> from pyof.foundation.base import MetaStruct as ms >>> from pyof.v0x01.common.header import Header >>> name = 'header' >>> obj = Header() >>> new_version = 'v0x04' >>> header, obj2 = ms.get_pyof_obj_new_version(name, obj, new_version) >>> header 'header' >>> obj.version UBInt8(1) >>> obj2.version UBInt8(4) Args: name (str): the name of the class attribute being handled. obj (object): the class attribute itself new_version (string): the pyof version in which you want the object 'obj'. Return: (str, obj): Tuple with class name and object instance. A tuple in which the first item is the name of the class attribute (the same that was passed), and the second item is a instance of the passed class attribute. If the class attribute is not a pyof versioned attribute, then the same passed object is returned without any changes. Also, if the obj is a pyof versioned attribute, but it is already on the right version (same as new_version), then the passed obj is return.
[ "r", "Return", "a", "class", "attribute", "on", "a", "different", "pyof", "version", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L414-L478
kytos/python-openflow
pyof/foundation/base.py
GenericStruct._validate_attributes_type
def _validate_attributes_type(self): """Validate the type of each attribute.""" 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(_attr, _class): return False return True
python
def _validate_attributes_type(self): """Validate the type of each attribute.""" 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(_attr, _class): return False return True
[ "def", "_validate_attributes_type", "(", "self", ")", ":", "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", "(", "_attr", ",", "_class", ")", ":", "return", "False", "return", "True" ]
Validate the type of each attribute.
[ "Validate", "the", "type", "of", "each", "attribute", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L534-L544
kytos/python-openflow
pyof/foundation/base.py
GenericStruct.get_class_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 requirement.) For the same reason, this lib will not work on python versions earlier than 3.6. .. code-block:: python3 for name, value in self.get_class_attributes(): print("attribute name: {}".format(name)) print("attribute type: {}".format(value)) Returns: generator: tuples with attribute name and value. """ #: 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. if GenericStruct._is_pyof_attribute(value): yield (name, value)
python
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 requirement.) For the same reason, this lib will not work on python versions earlier than 3.6. .. code-block:: python3 for name, value in self.get_class_attributes(): print("attribute name: {}".format(name)) print("attribute type: {}".format(value)) Returns: generator: tuples with attribute name and value. """ #: 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. if GenericStruct._is_pyof_attribute(value): yield (name, value)
[ "def", "get_class_attributes", "(", "cls", ")", ":", "#: 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.", "if", "GenericStruct", ".", "_is_pyof_attribute", "(", "value", ")", ":", "yield", "(", "name", ",", "value", ")" ]
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 requirement.) For the same reason, this lib will not work on python versions earlier than 3.6. .. code-block:: python3 for name, value in self.get_class_attributes(): print("attribute name: {}".format(name)) print("attribute type: {}".format(value)) Returns: generator: tuples with attribute name and value.
[ "Return", "a", "generator", "for", "class", "attributes", "names", "and", "value", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L547-L572
kytos/python-openflow
pyof/foundation/base.py
GenericStruct._get_instance_attributes
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: tuples with attribute name and value. """ for name, value in self.__dict__.items(): if name in map((lambda x: x[0]), self.get_class_attributes()): yield (name, value)
python
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: tuples with attribute name and value. """ 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", ")", ":", "for", "name", ",", "value", "in", "self", ".", "__dict__", ".", "items", "(", ")", ":", "if", "name", "in", "map", "(", "(", "lambda", "x", ":", "x", "[", "0", "]", ")", ",", "self", ".", "get_class_attributes", "(", ")", ")", ":", "yield", "(", "name", ",", "value", ")" ]
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: tuples with attribute name and value.
[ "Return", "a", "generator", "for", "instance", "attributes", "name", "and", "value", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L574-L589
kytos/python-openflow
pyof/foundation/base.py
GenericStruct._get_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)) Returns: generator: Tuples with instance attribute and class attribute """ return map((lambda i, c: (i[1], c[1])), self._get_instance_attributes(), self.get_class_attributes())
python
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)) Returns: generator: Tuples with instance attribute and class attribute """ return map((lambda i, c: (i[1], c[1])), self._get_instance_attributes(), self.get_class_attributes())
[ "def", "_get_attributes", "(", "self", ")", ":", "return", "map", "(", "(", "lambda", "i", ",", "c", ":", "(", "i", "[", "1", "]", ",", "c", "[", "1", "]", ")", ")", ",", "self", ".", "_get_instance_attributes", "(", ")", ",", "self", ".", "get_class_attributes", "(", ")", ")" ]
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)) Returns: generator: Tuples with instance attribute and class attribute
[ "Return", "a", "generator", "for", "instance", "and", "class", "attribute", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L591-L606
kytos/python-openflow
pyof/foundation/base.py
GenericStruct._get_named_attributes
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. """ 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
python
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. """ 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", ")", ":", "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" ]
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.
[ "Return", "generator", "for", "attribute", "s", "name", "instance", "and", "class", "values", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L608-L622
kytos/python-openflow
pyof/foundation/base.py
GenericStruct.get_size
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 used by the struct. Raises: Exception: If the struct is not valid. """ 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, type(self).__name__) raise PackException(msg)
python
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 used by the struct. Raises: Exception: If the struct is not valid. """ 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, type(self).__name__) raise PackException(msg)
[ "def", "get_size", "(", "self", ",", "value", "=", "None", ")", ":", "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", ",", "type", "(", "self", ")", ".", "__name__", ")", "raise", "PackException", "(", "msg", ")" ]
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 used by the struct. Raises: Exception: If the struct is not valid.
[ "Calculate", "the", "total", "struct", "size", "in", "bytes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L639-L664
kytos/python-openflow
pyof/foundation/base.py
GenericStruct.pack
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. Raises: :exc:`~.exceptions.ValidationError`: If validation fails. """ 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'' # pylint: disable=no-member for attr_info in self._get_named_attributes(): name, instance_value, class_value = attr_info try: message += class_value.pack(instance_value) except PackException as pack_exception: cls = type(self).__name__ msg = f'{cls}.{name} - {pack_exception}' raise PackException(msg) return message elif isinstance(value, type(self)): return value.pack() else: msg = "{} is not an instance of {}".format(value, type(self).__name__) raise PackException(msg)
python
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. Raises: :exc:`~.exceptions.ValidationError`: If validation fails. """ 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'' # pylint: disable=no-member for attr_info in self._get_named_attributes(): name, instance_value, class_value = attr_info try: message += class_value.pack(instance_value) except PackException as pack_exception: cls = type(self).__name__ msg = f'{cls}.{name} - {pack_exception}' raise PackException(msg) return message elif isinstance(value, type(self)): return value.pack() else: msg = "{} is not an instance of {}".format(value, type(self).__name__) raise PackException(msg)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "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''", "# pylint: disable=no-member", "for", "attr_info", "in", "self", ".", "_get_named_attributes", "(", ")", ":", "name", ",", "instance_value", ",", "class_value", "=", "attr_info", "try", ":", "message", "+=", "class_value", ".", "pack", "(", "instance_value", ")", "except", "PackException", "as", "pack_exception", ":", "cls", "=", "type", "(", "self", ")", ".", "__name__", "msg", "=", "f'{cls}.{name} - {pack_exception}'", "raise", "PackException", "(", "msg", ")", "return", "message", "elif", "isinstance", "(", "value", ",", "type", "(", "self", ")", ")", ":", "return", "value", ".", "pack", "(", ")", "else", ":", "msg", "=", "\"{} is not an instance of {}\"", ".", "format", "(", "value", ",", "type", "(", "self", ")", ".", "__name__", ")", "raise", "PackException", "(", "msg", ")" ]
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. Raises: :exc:`~.exceptions.ValidationError`: If validation fails.
[ "Pack", "the", "struct", "in", "a", "binary", "representation", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L666-L702
kytos/python-openflow
pyof/foundation/base.py
GenericMessage.pack
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:`update_header_length`. .. seealso:: This method call its parent's :meth:`GenericStruct.pack` after :meth:`update_header_length`. Returns: bytes: A binary data thats represents the Message. Raises: Exception: If there are validation errors. """ 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(self).__name__) raise PackException(msg)
python
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:`update_header_length`. .. seealso:: This method call its parent's :meth:`GenericStruct.pack` after :meth:`update_header_length`. Returns: bytes: A binary data thats represents the Message. Raises: Exception: If there are validation errors. """ 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(self).__name__) raise PackException(msg)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "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", "(", "self", ")", ".", "__name__", ")", "raise", "PackException", "(", "msg", ")" ]
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:`update_header_length`. .. seealso:: This method call its parent's :meth:`GenericStruct.pack` after :meth:`update_header_length`. Returns: bytes: A binary data thats represents the Message. Raises: Exception: If there are validation errors.
[ "Pack", "the", "message", "into", "a", "binary", "data", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L784-L812
kytos/python-openflow
pyof/foundation/base.py
GenericMessage.unpack
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 package to be unpacked, without the header. offset (int): Where to begin unpacking. """ 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
python
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 package to be unpacked, without the header. offset (int): Where to begin unpacking. """ 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", ")", ":", "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" ]
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 package to be unpacked, without the header. offset (int): Where to begin unpacking.
[ "Unpack", "a", "binary", "message", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L814-L830
kytos/python-openflow
pyof/foundation/base.py
GenericBitMask.names
def names(self): """List of selected enum names. Returns: list: Enum names. """ result = [] for key, value in self.iteritems(): if value & self.bitmask: result.append(key) return result
python
def names(self): """List of selected enum names. Returns: list: Enum names. """ result = [] for key, value in self.iteritems(): if value & self.bitmask: result.append(key) return result
[ "def", "names", "(", "self", ")", ":", "result", "=", "[", "]", "for", "key", ",", "value", "in", "self", ".", "iteritems", "(", ")", ":", "if", "value", "&", "self", ".", "bitmask", ":", "result", ".", "append", "(", "key", ")", "return", "result" ]
List of selected enum names. Returns: list: Enum names.
[ "List", "of", "selected", "enum", "names", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L895-L906
kytos/python-openflow
pyof/v0x01/common/action.py
ActionHeader.unpack
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: Exception: If there is a struct unpacking error. """ 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, offset)
python
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: Exception: If there is a struct unpacking error. """ 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, offset)
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "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", ",", "offset", ")" ]
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: Exception: If there is a struct unpacking error.
[ "Unpack", "a", "binary", "message", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/common/action.py#L79-L101
kytos/python-openflow
pyof/v0x04/controller2switch/multipart_request.py
MultipartRequest._get_body_instance
def _get_body_instance(self): """Return the body instance.""" simple_body = { MultipartType.OFPMP_FLOW: FlowStatsRequest, MultipartType.OFPMP_AGGREGATE: AggregateStatsRequest, MultipartType.OFPMP_PORT_STATS: PortStatsRequest, MultipartType.OFPMP_QUEUE: QueueStatsRequest, MultipartType.OFPMP_GROUP: GroupStatsRequest, MultipartType.OFPMP_METER: MeterMultipartRequest, MultipartType.OFPMP_EXPERIMENTER: ExperimenterMultipartHeader } array_of_bodies = {MultipartType.OFPMP_TABLE_FEATURES: TableFeatures} if isinstance(self.multipart_type, UBInt16): self.multipart_type = self.multipart_type.enum_ref( self.multipart_type.value) pyof_class = simple_body.get(self.multipart_type, None) if pyof_class: return pyof_class() array_of_class = array_of_bodies.get(self.multipart_type, None) if array_of_class: return FixedTypeList(pyof_class=array_of_class) return BinaryData(b'')
python
def _get_body_instance(self): """Return the body instance.""" simple_body = { MultipartType.OFPMP_FLOW: FlowStatsRequest, MultipartType.OFPMP_AGGREGATE: AggregateStatsRequest, MultipartType.OFPMP_PORT_STATS: PortStatsRequest, MultipartType.OFPMP_QUEUE: QueueStatsRequest, MultipartType.OFPMP_GROUP: GroupStatsRequest, MultipartType.OFPMP_METER: MeterMultipartRequest, MultipartType.OFPMP_EXPERIMENTER: ExperimenterMultipartHeader } array_of_bodies = {MultipartType.OFPMP_TABLE_FEATURES: TableFeatures} if isinstance(self.multipart_type, UBInt16): self.multipart_type = self.multipart_type.enum_ref( self.multipart_type.value) pyof_class = simple_body.get(self.multipart_type, None) if pyof_class: return pyof_class() array_of_class = array_of_bodies.get(self.multipart_type, None) if array_of_class: return FixedTypeList(pyof_class=array_of_class) return BinaryData(b'')
[ "def", "_get_body_instance", "(", "self", ")", ":", "simple_body", "=", "{", "MultipartType", ".", "OFPMP_FLOW", ":", "FlowStatsRequest", ",", "MultipartType", ".", "OFPMP_AGGREGATE", ":", "AggregateStatsRequest", ",", "MultipartType", ".", "OFPMP_PORT_STATS", ":", "PortStatsRequest", ",", "MultipartType", ".", "OFPMP_QUEUE", ":", "QueueStatsRequest", ",", "MultipartType", ".", "OFPMP_GROUP", ":", "GroupStatsRequest", ",", "MultipartType", ".", "OFPMP_METER", ":", "MeterMultipartRequest", ",", "MultipartType", ".", "OFPMP_EXPERIMENTER", ":", "ExperimenterMultipartHeader", "}", "array_of_bodies", "=", "{", "MultipartType", ".", "OFPMP_TABLE_FEATURES", ":", "TableFeatures", "}", "if", "isinstance", "(", "self", ".", "multipart_type", ",", "UBInt16", ")", ":", "self", ".", "multipart_type", "=", "self", ".", "multipart_type", ".", "enum_ref", "(", "self", ".", "multipart_type", ".", "value", ")", "pyof_class", "=", "simple_body", ".", "get", "(", "self", ".", "multipart_type", ",", "None", ")", "if", "pyof_class", ":", "return", "pyof_class", "(", ")", "array_of_class", "=", "array_of_bodies", ".", "get", "(", "self", ".", "multipart_type", ",", "None", ")", "if", "array_of_class", ":", "return", "FixedTypeList", "(", "pyof_class", "=", "array_of_class", ")", "return", "BinaryData", "(", "b''", ")" ]
Return the body instance.
[ "Return", "the", "body", "instance", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/controller2switch/multipart_request.py#L130-L156
kytos/python-openflow
pyof/v0x01/controller2switch/stats_reply.py
StatsReply.pack
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. """ 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
python
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. """ 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", ")", ":", "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" ]
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.
[ "Pack", "a", "StatsReply", "using", "the", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/controller2switch/stats_reply.py#L35-L54
kytos/python-openflow
pyof/v0x01/controller2switch/stats_reply.py
StatsReply._get_body_instance
def _get_body_instance(self): """Return the body instance.""" 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)
python
def _get_body_instance(self): """Return the body instance.""" 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", ")", ":", "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", ")" ]
Return the body instance.
[ "Return", "the", "body", "instance", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/controller2switch/stats_reply.py#L80-L89
kytos/python-openflow
pyof/v0x01/common/flow_match.py
Match.unpack
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: :exc:`~.exceptions.UnpackException`: If unpack fails. """ super().unpack(buff, offset) self.wildcards = UBInt32(value=FlowWildCards.OFPFW_ALL, enum_ref=FlowWildCards) self.wildcards.unpack(buff, offset)
python
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: :exc:`~.exceptions.UnpackException`: If unpack fails. """ 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", ")", ":", "super", "(", ")", ".", "unpack", "(", "buff", ",", "offset", ")", "self", ".", "wildcards", "=", "UBInt32", "(", "value", "=", "FlowWildCards", ".", "OFPFW_ALL", ",", "enum_ref", "=", "FlowWildCards", ")", "self", ".", "wildcards", ".", "unpack", "(", "buff", ",", "offset", ")" ]
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: :exc:`~.exceptions.UnpackException`: If unpack fails.
[ "Unpack", "*", "buff", "*", "into", "this", "object", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/common/flow_match.py#L144-L161
kytos/python-openflow
pyof/v0x01/common/flow_match.py
Match.fill_wildcards
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. """ 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 = FlowWildCards.OFPFW_NW_DST_MASK else: shift = FlowWildCards.OFPFW_NW_SRC_SHIFT base_mask = FlowWildCards.OFPFW_NW_SRC_MASK # First we clear the nw_dst/nw_src mask related bits on the current # wildcard by setting 0 on all of them while we keep all other bits # as they are. self.wildcards &= FlowWildCards.OFPFW_ALL ^ base_mask # nw_dst and nw_src wildcard fields have 6 bits each. # "base_mask" is the 'all ones' for those 6 bits. # Once we know the netmask, we can calculate the these 6 bits # wildcard value and reverse them in order to insert them at the # correct position in self.wildcards wildcard = (value.max_prefix - value.netmask) << shift self.wildcards |= wildcard else: wildcard_field = "OFPFW_{}".format(field.upper()) wildcard = getattr(FlowWildCards, wildcard_field) if value == default_value and not (self.wildcards & wildcard) or \ value != default_value and (self.wildcards & wildcard): self.wildcards ^= wildcard
python
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. """ 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 = FlowWildCards.OFPFW_NW_DST_MASK else: shift = FlowWildCards.OFPFW_NW_SRC_SHIFT base_mask = FlowWildCards.OFPFW_NW_SRC_MASK # First we clear the nw_dst/nw_src mask related bits on the current # wildcard by setting 0 on all of them while we keep all other bits # as they are. self.wildcards &= FlowWildCards.OFPFW_ALL ^ base_mask # nw_dst and nw_src wildcard fields have 6 bits each. # "base_mask" is the 'all ones' for those 6 bits. # Once we know the netmask, we can calculate the these 6 bits # wildcard value and reverse them in order to insert them at the # correct position in self.wildcards wildcard = (value.max_prefix - value.netmask) << shift self.wildcards |= wildcard else: wildcard_field = "OFPFW_{}".format(field.upper()) wildcard = getattr(FlowWildCards, wildcard_field) if value == default_value and not (self.wildcards & wildcard) or \ value != default_value and (self.wildcards & wildcard): self.wildcards ^= wildcard
[ "def", "fill_wildcards", "(", "self", ",", "field", "=", "None", ",", "value", "=", "0", ")", ":", "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", "=", "FlowWildCards", ".", "OFPFW_NW_DST_MASK", "else", ":", "shift", "=", "FlowWildCards", ".", "OFPFW_NW_SRC_SHIFT", "base_mask", "=", "FlowWildCards", ".", "OFPFW_NW_SRC_MASK", "# First we clear the nw_dst/nw_src mask related bits on the current", "# wildcard by setting 0 on all of them while we keep all other bits", "# as they are.", "self", ".", "wildcards", "&=", "FlowWildCards", ".", "OFPFW_ALL", "^", "base_mask", "# nw_dst and nw_src wildcard fields have 6 bits each.", "# \"base_mask\" is the 'all ones' for those 6 bits.", "# Once we know the netmask, we can calculate the these 6 bits", "# wildcard value and reverse them in order to insert them at the", "# correct position in self.wildcards", "wildcard", "=", "(", "value", ".", "max_prefix", "-", "value", ".", "netmask", ")", "<<", "shift", "self", ".", "wildcards", "|=", "wildcard", "else", ":", "wildcard_field", "=", "\"OFPFW_{}\"", ".", "format", "(", "field", ".", "upper", "(", ")", ")", "wildcard", "=", "getattr", "(", "FlowWildCards", ",", "wildcard_field", ")", "if", "value", "==", "default_value", "and", "not", "(", "self", ".", "wildcards", "&", "wildcard", ")", "or", "value", "!=", "default_value", "and", "(", "self", ".", "wildcards", "&", "wildcard", ")", ":", "self", ".", "wildcards", "^=", "wildcard" ]
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.
[ "Update", "wildcards", "attribute", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x01/common/flow_match.py#L163-L203
kytos/python-openflow
pyof/foundation/basic_types.py
DPID.pack
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. """ 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(':')])
python
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. """ 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", ")", ":", "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", "(", "':'", ")", "]", ")" ]
Pack the value as a binary representation. Returns: bytes: The binary representation. Raises: struct.error: If the value does not fit the binary format.
[ "Pack", "the", "value", "as", "a", "binary", "representation", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L145-L159
kytos/python-openflow
pyof/foundation/basic_types.py
DPID.unpack
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: Exception: If there is a struct unpacking error. """ 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)
python
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: Exception: If there is a struct unpacking error. """ 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", ")", ":", "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", ")" ]
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: Exception: If there is a struct unpacking error.
[ "Unpack", "a", "binary", "message", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L161-L181
kytos/python-openflow
pyof/foundation/basic_types.py
Char.pack
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. """ 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 err: msg = "Char Pack error. " msg += "Class: {}, struct error: {} ".format(type(value).__name__, err) raise exceptions.PackException(msg)
python
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. """ 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 err: msg = "Char Pack error. " msg += "Class: {}, struct error: {} ".format(type(value).__name__, err) raise exceptions.PackException(msg)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "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", "err", ":", "msg", "=", "\"Char Pack error. \"", "msg", "+=", "\"Class: {}, struct error: {} \"", ".", "format", "(", "type", "(", "value", ")", ".", "__name__", ",", "err", ")", "raise", "exceptions", ".", "PackException", "(", "msg", ")" ]
Pack the value as a binary representation. Returns: bytes: The binary representation. Raises: struct.error: If the value does not fit the binary format.
[ "Pack", "the", "value", "as", "a", "binary", "representation", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L202-L224
kytos/python-openflow
pyof/foundation/basic_types.py
Char.unpack
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: Exception: If there is a struct unpacking error. """ 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')
python
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: Exception: If there is a struct unpacking error. """ 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", ")", ":", "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'", ")" ]
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: Exception: If there is a struct unpacking error.
[ "Unpack", "a", "binary", "message", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L226-L247
kytos/python-openflow
pyof/foundation/basic_types.py
IPAddress.unpack
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: Exception: If there is a struct unpacking error. """ 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, offset, buff))
python
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: Exception: If there is a struct unpacking error. """ 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, offset, buff))
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "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", ",", "offset", ",", "buff", ")", ")" ]
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: Exception: If there is a struct unpacking error.
[ "Unpack", "a", "binary", "message", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L307-L326
kytos/python-openflow
pyof/foundation/basic_types.py
HWAddress.pack
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 not fit the binary format. """ 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]) except struct.error as err: msg = "HWAddress error. " msg += "Class: {}, struct error: {} ".format(type(value).__name__, err) raise exceptions.PackException(msg)
python
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 not fit the binary format. """ 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]) except struct.error as err: msg = "HWAddress error. " msg += "Class: {}, struct error: {} ".format(type(value).__name__, err) raise exceptions.PackException(msg)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "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", "]", ")", "except", "struct", ".", "error", "as", "err", ":", "msg", "=", "\"HWAddress error. \"", "msg", "+=", "\"Class: {}, struct error: {} \"", ".", "format", "(", "type", "(", "value", ")", ".", "__name__", ",", "err", ")", "raise", "exceptions", ".", "PackException", "(", "msg", ")" ]
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 not fit the binary format.
[ "Pack", "the", "value", "as", "a", "binary", "representation", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L360-L390
kytos/python-openflow
pyof/foundation/basic_types.py
HWAddress.unpack
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: Exception: If there is a struct unpacking error. """ 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, offset, buff)) transformed_data = ':'.join([_int2hex(x) for x in unpacked_data]) self._value = transformed_data
python
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: Exception: If there is a struct unpacking error. """ 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, offset, buff)) transformed_data = ':'.join([_int2hex(x) for x in unpacked_data]) self._value = transformed_data
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "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", ",", "offset", ",", "buff", ")", ")", "transformed_data", "=", "':'", ".", "join", "(", "[", "_int2hex", "(", "x", ")", "for", "x", "in", "unpacked_data", "]", ")", "self", ".", "_value", "=", "transformed_data" ]
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: Exception: If there is a struct unpacking error.
[ "Unpack", "a", "binary", "message", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L392-L416
kytos/python-openflow
pyof/foundation/basic_types.py
BinaryData.pack
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 """ 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"BinaryData can't be {type(value)} = '{value}'")
python
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 """ 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"BinaryData can't be {type(value)} = '{value}'")
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "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\"BinaryData can't be {type(value)} = '{value}'\"", ")" ]
Pack the value as a binary representation. Returns: bytes: The binary representation. Raises: ValueError: If value can't be represented with bytes
[ "Pack", "the", "value", "as", "a", "binary", "representation", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L460-L480
kytos/python-openflow
pyof/foundation/basic_types.py
BinaryData.get_size
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. """ if value is None: value = self._value if hasattr(value, 'get_size'): return value.get_size() return len(self.pack(value))
python
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. """ 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", ")", ":", "if", "value", "is", "None", ":", "value", "=", "self", ".", "_value", "if", "hasattr", "(", "value", ",", "'get_size'", ")", ":", "return", "value", ".", "get_size", "(", ")", "return", "len", "(", "self", ".", "pack", "(", "value", ")", ")" ]
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.
[ "Return", "the", "size", "in", "bytes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L494-L512
kytos/python-openflow
pyof/foundation/basic_types.py
TypeList.pack
def pack(self, value=None): """Pack the value as a binary representation. Returns: bytes: The binary representation. """ 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 item in value: bin_message += item.pack() return bin_message except exceptions.PackException as err: msg = "{} pack error: {}".format(type(self).__name__, err) raise exceptions.PackException(msg)
python
def pack(self, value=None): """Pack the value as a binary representation. Returns: bytes: The binary representation. """ 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 item in value: bin_message += item.pack() return bin_message except exceptions.PackException as err: msg = "{} pack error: {}".format(type(self).__name__, err) raise exceptions.PackException(msg)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "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", "item", "in", "value", ":", "bin_message", "+=", "item", ".", "pack", "(", ")", "return", "bin_message", "except", "exceptions", ".", "PackException", "as", "err", ":", "msg", "=", "\"{} pack error: {}\"", ".", "format", "(", "type", "(", "self", ")", ".", "__name__", ",", "err", ")", "raise", "exceptions", ".", "PackException", "(", "msg", ")" ]
Pack the value as a binary representation. Returns: bytes: The binary representation.
[ "Pack", "the", "value", "as", "a", "binary", "representation", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L548-L572
kytos/python-openflow
pyof/foundation/basic_types.py
TypeList.unpack
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. """ begin = offset limit_buff = len(buff) while begin < limit_buff: item = item_class() item.unpack(buff, begin) self.append(item) begin += item.get_size()
python
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. """ 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", ")", ":", "begin", "=", "offset", "limit_buff", "=", "len", "(", "buff", ")", "while", "begin", "<", "limit_buff", ":", "item", "=", "item_class", "(", ")", "item", ".", "unpack", "(", "buff", ",", "begin", ")", "self", ".", "append", "(", "item", ")", "begin", "+=", "item", ".", "get_size", "(", ")" ]
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.
[ "Unpack", "the", "elements", "of", "the", "list", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L575-L590
kytos/python-openflow
pyof/foundation/basic_types.py
TypeList.get_size
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. """ 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 multiplied by the size of the GenericType. return len(self) * self[0].get_size() # Otherwise iter over the list accumulating the sizes. return sum(item.get_size() for item in self) return type(self)(value).get_size()
python
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. """ 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 multiplied by the size of the GenericType. return len(self) * self[0].get_size() # Otherwise iter over the list accumulating the sizes. return sum(item.get_size() for item in self) return type(self)(value).get_size()
[ "def", "get_size", "(", "self", ",", "value", "=", "None", ")", ":", "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 multiplied by the size of the GenericType.", "return", "len", "(", "self", ")", "*", "self", "[", "0", "]", ".", "get_size", "(", ")", "# Otherwise iter over the list accumulating the sizes.", "return", "sum", "(", "item", ".", "get_size", "(", ")", "for", "item", "in", "self", ")", "return", "type", "(", "self", ")", "(", "value", ")", ".", "get_size", "(", ")" ]
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.
[ "Return", "the", "size", "in", "bytes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L593-L617
kytos/python-openflow
pyof/foundation/basic_types.py
FixedTypeList.append
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. """ 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.__name__)
python
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. """ 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.__name__)
[ "def", "append", "(", "self", ",", "item", ")", ":", "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", ".", "__name__", ")" ]
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.
[ "Append", "one", "item", "to", "the", "list", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L644-L662
kytos/python-openflow
pyof/foundation/basic_types.py
FixedTypeList.insert
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 type than the one specified in the constructor. """ if issubclass(item.__class__, self._pyof_class): list.insert(self, index, item) else: raise exceptions.WrongListItemType(item.__class__.__name__, self._pyof_class.__name__)
python
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 type than the one specified in the constructor. """ 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", ")", ":", "if", "issubclass", "(", "item", ".", "__class__", ",", "self", ".", "_pyof_class", ")", ":", "list", ".", "insert", "(", "self", ",", "index", ",", "item", ")", "else", ":", "raise", "exceptions", ".", "WrongListItemType", "(", "item", ".", "__class__", ".", "__name__", ",", "self", ".", "_pyof_class", ".", "__name__", ")" ]
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 type than the one specified in the constructor.
[ "Insert", "an", "item", "at", "the", "specified", "index", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L664-L681
kytos/python-openflow
pyof/foundation/basic_types.py
FixedTypeList.unpack
def unpack(self, buff, offset=0): # pylint: disable=arguments-differ """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. offset (int): If we need to shift the beginning of the data. """ super().unpack(buff, self._pyof_class, offset)
python
def unpack(self, buff, offset=0): # pylint: disable=arguments-differ """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. offset (int): If we need to shift the beginning of the data. """ super().unpack(buff, self._pyof_class, offset)
[ "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. offset (int): If we need to shift the beginning of the data.
[ "Unpack", "the", "elements", "of", "the", "list", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L683-L694
kytos/python-openflow
pyof/foundation/basic_types.py
ConstantTypeList.append
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. """ 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__, self[0].__class__.__name__)
python
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. """ 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__, self[0].__class__.__name__)
[ "def", "append", "(", "self", ",", "item", ")", ":", "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__", ",", "self", "[", "0", "]", ".", "__class__", ".", "__name__", ")" ]
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.
[ "Append", "one", "item", "to", "the", "list", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L724-L743
kytos/python-openflow
pyof/foundation/basic_types.py
ConstantTypeList.insert
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. """ 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__)
python
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. """ 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", ")", ":", "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__", ")" ]
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.
[ "Insert", "an", "item", "at", "the", "specified", "index", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L745-L763
kytos/python-openflow
pyof/v0x04/common/action.py
ActionHeader.get_size
def get_size(self, value=None): """Return the action length including the padding (multiple of 8).""" 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()')
python
def get_size(self, value=None): """Return the action length including the padding (multiple of 8).""" 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", ")", ":", "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()'", ")" ]
Return the action length including the padding (multiple of 8).
[ "Return", "the", "action", "length", "including", "the", "padding", "(", "multiple", "of", "8", ")", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/action.py#L111-L118
kytos/python-openflow
pyof/v0x04/common/action.py
ActionSetField.pack
def pack(self, value=None): """Pack this structure updating the length and padding it.""" self._update_length() packet = super().pack() return self._complete_last_byte(packet)
python
def pack(self, value=None): """Pack this structure updating the length and padding it.""" self._update_length() packet = super().pack() return self._complete_last_byte(packet)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "self", ".", "_update_length", "(", ")", "packet", "=", "super", "(", ")", ".", "pack", "(", ")", "return", "self", ".", "_complete_last_byte", "(", "packet", ")" ]
Pack this structure updating the length and padding it.
[ "Pack", "this", "structure", "updating", "the", "length", "and", "padding", "it", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/action.py#L384-L388
kytos/python-openflow
pyof/v0x04/common/action.py
ActionSetField._update_length
def _update_length(self): """Update the length field of the struct.""" action_length = 4 + len(self.field.pack()) overflow = action_length % 8 self.length = action_length if overflow: self.length = action_length + 8 - overflow
python
def _update_length(self): """Update the length field of the struct.""" 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", ")", ":", "action_length", "=", "4", "+", "len", "(", "self", ".", "field", ".", "pack", "(", ")", ")", "overflow", "=", "action_length", "%", "8", "self", ".", "length", "=", "action_length", "if", "overflow", ":", "self", ".", "length", "=", "action_length", "+", "8", "-", "overflow" ]
Update the length field of the struct.
[ "Update", "the", "length", "field", "of", "the", "struct", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/v0x04/common/action.py#L390-L396
kytos/python-openflow
pyof/foundation/network_types.py
ARP.unpack
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 to begin unpacking. Raises: :exc:`~.exceptions.UnpackException`: If unpack fails. """ super().unpack(buff, offset) if not self.is_valid(): raise UnpackException("Unsupported protocols in ARP packet")
python
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 to begin unpacking. Raises: :exc:`~.exceptions.UnpackException`: If unpack fails. """ super().unpack(buff, offset) if not self.is_valid(): raise UnpackException("Unsupported protocols in ARP packet")
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "super", "(", ")", ".", "unpack", "(", "buff", ",", "offset", ")", "if", "not", "self", ".", "is_valid", "(", ")", ":", "raise", "UnpackException", "(", "\"Unsupported protocols in ARP packet\"", ")" ]
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 to begin unpacking. Raises: :exc:`~.exceptions.UnpackException`: If unpack fails.
[ "Unpack", "a", "binary", "struct", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L114-L131
kytos/python-openflow
pyof/foundation/network_types.py
VLAN.pack
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: Binary representation of this instance. """ 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.vid if self.vid is not None else 0 self._tci = self.pcp << 13 | self.cfi << 12 | self.vid return super().pack()
python
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: Binary representation of this instance. """ 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.vid if self.vid is not None else 0 self._tci = self.pcp << 13 | self.cfi << 12 | self.vid return super().pack()
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "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", ".", "vid", "if", "self", ".", "vid", "is", "not", "None", "else", "0", "self", ".", "_tci", "=", "self", ".", "pcp", "<<", "13", "|", "self", ".", "cfi", "<<", "12", "|", "self", ".", "vid", "return", "super", "(", ")", ".", "pack", "(", ")" ]
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: Binary representation of this instance.
[ "Pack", "the", "struct", "in", "a", "binary", "representation", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L163-L185
kytos/python-openflow
pyof/foundation/network_types.py
VLAN._validate
def _validate(self): """Assure this is a valid VLAN header instance.""" if self.tpid.value not in (EtherType.VLAN, EtherType.VLAN_QINQ): raise UnpackException return
python
def _validate(self): """Assure this is a valid VLAN header instance.""" if self.tpid.value not in (EtherType.VLAN, EtherType.VLAN_QINQ): raise UnpackException return
[ "def", "_validate", "(", "self", ")", ":", "if", "self", ".", "tpid", ".", "value", "not", "in", "(", "EtherType", ".", "VLAN", ",", "EtherType", ".", "VLAN_QINQ", ")", ":", "raise", "UnpackException", "return" ]
Assure this is a valid VLAN header instance.
[ "Assure", "this", "is", "a", "valid", "VLAN", "header", "instance", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L187-L191
kytos/python-openflow
pyof/foundation/network_types.py
VLAN.unpack
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 (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: :exc:`~.exceptions.UnpackException`: If unpack fails. """ 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 = EtherType.VLAN self.pcp = None self.cfi = None self.vid = None
python
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 (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: :exc:`~.exceptions.UnpackException`: If unpack fails. """ 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 = EtherType.VLAN self.pcp = None self.cfi = None self.vid = None
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "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", "=", "EtherType", ".", "VLAN", "self", ".", "pcp", "=", "None", "self", ".", "cfi", "=", "None", "self", ".", "vid", "=", "None" ]
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 (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: :exc:`~.exceptions.UnpackException`: If unpack fails.
[ "Unpack", "a", "binary", "struct", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L193-L221
kytos/python-openflow
pyof/foundation/network_types.py
Ethernet._get_vlan_length
def _get_vlan_length(buff): """Return the total length of VLAN tags in a given Ethernet buffer.""" 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
python
def _get_vlan_length(buff): """Return the total length of VLAN tags in a given Ethernet buffer.""" 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", ")", ":", "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" ]
Return the total length of VLAN tags in a given Ethernet buffer.
[ "Return", "the", "total", "length", "of", "VLAN", "tags", "in", "a", "given", "Ethernet", "buffer", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L294-L304
kytos/python-openflow
pyof/foundation/network_types.py
Ethernet.unpack
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: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: UnpackException: If there is a struct unpacking error. """ 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]) else: attribute.unpack(buff, begin) setattr(self, attribute_name, attribute) begin += attribute.get_size()
python
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: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: UnpackException: If there is a struct unpacking error. """ 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]) else: attribute.unpack(buff, begin) setattr(self, attribute_name, attribute) begin += attribute.get_size()
[ "def", "unpack", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "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", "]", ")", "else", ":", "attribute", ".", "unpack", "(", "buff", ",", "begin", ")", "setattr", "(", "self", ",", "attribute_name", ",", "attribute", ")", "begin", "+=", "attribute", ".", "get_size", "(", ")" ]
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: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: UnpackException: If there is a struct unpacking error.
[ "Unpack", "a", "binary", "message", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L306-L334
kytos/python-openflow
pyof/foundation/network_types.py
GenericTLV.pack
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. """ 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, type(self).__name__) raise PackException(msg)
python
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. """ 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, type(self).__name__) raise PackException(msg)
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "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", ",", "type", "(", "self", ")", ".", "__name__", ")", "raise", "PackException", "(", "msg", ")" ]
Pack the TLV in a binary representation. Returns: bytes: Binary representation of the struct object. Raises: :exc:`~.exceptions.ValidationError`: If validation fails.
[ "Pack", "the", "TLV", "in", "a", "binary", "representation", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L398-L418
kytos/python-openflow
pyof/foundation/network_types.py
GenericTLV.unpack
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: Exception: If there is a struct unpacking error. """ 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])
python
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: Exception: If there is a struct unpacking error. """ 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", ")", ":", "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", "]", ")" ]
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: Exception: If there is a struct unpacking error.
[ "Unpack", "a", "binary", "message", "into", "this", "object", "s", "attributes", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L420-L439
kytos/python-openflow
pyof/foundation/network_types.py
GenericTLV.get_size
def get_size(self, value=None): """Return struct size. Returns: int: Returns the struct size based on inner attributes. """ if isinstance(value, type(self)): return value.get_size() return 2 + self.length
python
def get_size(self, value=None): """Return struct size. Returns: int: Returns the struct size based on inner attributes. """ if isinstance(value, type(self)): return value.get_size() return 2 + self.length
[ "def", "get_size", "(", "self", ",", "value", "=", "None", ")", ":", "if", "isinstance", "(", "value", ",", "type", "(", "self", ")", ")", ":", "return", "value", ".", "get_size", "(", ")", "return", "2", "+", "self", ".", "length" ]
Return struct size. Returns: int: Returns the struct size based on inner attributes.
[ "Return", "struct", "size", "." ]
train
https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/network_types.py#L441-L451