def __getitem__(self, field): struct = self.structures[field] return { "size": len(struct()), "serializer": (lambda x: x.serialize()), "deserializer": (lambda x: struct().marshall(FileLike(x))) }
def get_struct(str_, off, struct): s = struct() slen = ctypes.sizeof(s) _bytes = str_[off:off + slen] fit = min(len(_bytes), slen) ctypes.memmove(ctypes.addressof(s), _bytes, fit) return s
def get_struct(str_, off, struct): s = struct() slen = ctypes.sizeof(s) bytes = str_[off:off+slen] fit = min(len(bytes), slen) ctypes.memmove(ctypes.addressof(s), bytes, fit) return s
def structure(self, strt): """ discover utilise cette fonction pour intéroger SAP avec la fonction RFC_GET_STRUCTURE_DEFINITION_P et connaitre le format d'une stucture """ if self.is_connected() == 0: raise NameError, "RFC is NOT connected for structure discovery!" info = self.sapinfo() isapstruct = iface("RFC_GET_STRUCTURE_DEFINITION_P") etabname = parm("TABNAME", "", RFCEXPORT, RFCTYPE_CHAR, len(strt), 0, strt.upper()) isapstruct.addParm(etabname) tparams = tab("FIELDS", "", 83) isapstruct.addParm(tparams) if saprfcutil.call_receive(self, isapstruct) == 0: raise NameError, "failed on RFC_GET_STRUCTURE_DEFINITION_P" s = struct(strt) # record structure changes from 3.x to 4.x if re.compile("^[4-9]\d\w").match(info["RFCSAPRL"]): regex = "30s 30s 4s 6s 6s 6s 1s" else: regex = "10s 10s 4s 6s 6s 6s 1s" for row in tparams.value: tabname, fld, pos, off, intlen, decs, exid = unpack(regex, row) s.addField(field(fld, exid, decs, intlen, off)) del etabname del isapstruct return s
def error_struct(self, error_code, error_message): struct = namedtuple("error_struct", "op_code error_code error_message offset") error_message = error_message.encode('utf-8') struct_handle = Struct("!h h " + str(len(error_message)) + "s c") return struct_handle.pack( *struct(self.OpCode, error_code, error_message, b'\0'))
def read_struct(li, struct): s = struct() slen = ctypes.sizeof(s) _bytes = li.read(slen) fit = min(len(_bytes), slen) ctypes.memmove(ctypes.addressof(s), _bytes, fit) return s
def read_struct(li, struct): s = struct() slen = ctypes.sizeof(s) bytes = li.read(slen) fit = min(len(bytes), slen) ctypes.memmove(ctypes.addressof(s), bytes, fit) return s
def save(self): with open(Directory.FILE_PATH, 'wb') as f: pac = struct.pac('L', self.global_depth) f.write(pac) for i in range(0, 2 ^ self.global_depth): pac = struct('LL', self.buckets[i].local_depth, self.buckets[i].qtd_videos) f.write(pac)
def get_struct(str_, off, struct): s = struct() slen = ctypes.sizeof(s) bytes = str_[off:off+slen] fit = min(len(bytes), slen) if fit < slen: raise Exception("can't read struct: %d bytes available but %d required" % (fit, slen)) ctypes.memmove(ctypes.addressof(s), bytes, fit) return s
def request_struct(self, filename, mode): struct = namedtuple("request_struct", "op_code filename offset_file mode offset_mode") filename = filename.encode('utf-8') mode = mode.encode("utf-8") struct_handle = Struct("!h " + str(len(filename)) + "s c " + str(len(mode)) + "s c") return struct_handle.pack( *struct(self.OpCode, filename, b'\0', mode, b'\0'))
def parsePacket(self, packet): e = struct.unpack(">BBHII",packet[:12]) if (e[0]>>6) != 2: # check version is 2 return None # ignore padding bit atm hasPadding = e[0] & 0x20 hasExtension = e[0] & 0x10 numCSRCs = e[0] & 0x0f hasMarker = e[1] & 0x80 payloadType = e[1] & 0x7f seqnum = e[2] timestamp = e[3] ssrc = e[4] i=12 if numCSRCs: csrcs = struct.unpack(">"+str(numCSRCs)+"I", packet[i:i+4*csrcs]) i=i+4*numCSRCs else: csrcs = [] if hasExtension: ehdr, length = struct(">2sH",packet[i:i+4]) epayload = packet[i+4:i+4+length] extension = (ehdr,epayload) i=i+4+length else: extension = None # now work out how much padding needs stripping, if at all end = len(packet) if hasPadding: amount = ord(packet[-1]) end = end - amount payload = packet[i:end] return ( seqnum, { 'payloadtype' : payloadType, 'payload' : payload, 'timestamp' : timestamp, 'ssrc' : ssrc, 'extension' : extension, 'csrcs' : csrcs, 'marker' : hasMarker, } )
def parsePacket(self, packet): e = struct.unpack(">BBHII", packet[:12]) if (e[0] >> 6) != 2: # check version is 2 return None # ignore padding bit atm hasPadding = e[0] & 0x20 hasExtension = e[0] & 0x10 numCSRCs = e[0] & 0x0f hasMarker = e[1] & 0x80 payloadType = e[1] & 0x7f seqnum = e[2] timestamp = e[3] ssrc = e[4] i = 12 if numCSRCs: csrcs = struct.unpack(">" + str(numCSRCs) + "I", packet[i:i + 4 * csrcs]) i = i + 4 * numCSRCs else: csrcs = [] if hasExtension: ehdr, length = struct(">2sH", packet[i:i + 4]) epayload = packet[i + 4:i + 4 + length] extension = (ehdr, epayload) i = i + 4 + length else: extension = None # now work out how much padding needs stripping, if at all end = len(packet) if hasPadding: amount = ord(packet[-1]) end = end - amount payload = packet[i:end] return (seqnum, { 'payloadtype': payloadType, 'payload': payload, 'timestamp': timestamp, 'ssrc': ssrc, 'extension': extension, 'csrcs': csrcs, 'marker': hasMarker, })
def f(fileno): buffer = struct() if c.ioctl(fileno, request, ctypes.byref(buffer)) < 0: err = ctypes.c_int.in_dll(c, 'errno').value raise OSError(err, errno.errorcode[err]) return buffer
indent, rp.rhsalias[i], i - rp.nrhs) fprintf(out, "%s )\n", indent) else: fprintf(out, "%s return None\n", indent) return # Each state contains a set of token transaction and a set of # nonterminal transactions. Each of these sets makes an instance of # the following structure. An array of these structures is used to # order the creation of entries in the yy_action[] table. axset = struct( 'axset', ( 'stp', # A state 'isTkn', # True to use tokens. False for non-terminals 'nAction', # Number of actions 'iOrder', # Original order of action sets )) def axset_compare(a, b): '''Compare to axset structures for sorting purposes.''' c = b.nAction - a.nAction if c == 0: c = b.iOrder - a.iOrder assert c != 0 or a == b return c def writeRuleText(out, rp):
def ack_struct(self, block): struct = namedtuple("ack_struct", "op_code block") struct_handle = Struct("!h h") return struct_handle.pack(*struct(self.OpCode, block))
def discover(self, name): """ Fonction de detection automatique des paramètres IMPORT EXPORT d'une fonction """ if self.is_connected() == 0: raise NameError, "RFC is NOT connected for interface discovery!" info = self.sapinfo() isapiface = iface("RFC_GET_FUNCTION_INTERFACE_P") efuncname = parm(name="FUNCNAME", structure="", type=RFCEXPORT, intype=RFCTYPE_CHAR, len=len(name), decimals=0, py_value=name.upper(), default="") isapiface.addParm(efuncname) tparams = tab("PARAMS_P") for i in range(25): table_row = struct(name="LIGNE%d" % (i)) table_row.__add__( parm(name="type", structure="", type=RFCEXPORT, intype=RFCTYPE_CHAR, len=1, decimals=0, py_value="", default="err_default")) table_row.__add__( parm(name="name", structure="", type=RFCEXPORT, intype=RFCTYPE_CHAR, len=30, decimals=0, py_value="", default="err_default")) table_row.__add__( parm(name="tabname", structure="", type=RFCEXPORT, intype=RFCTYPE_CHAR, len=30, decimals=0, py_value="", default="err_default")) table_row.__add__( parm(name="field", structure="", type=RFCEXPORT, intype=RFCTYPE_CHAR, len=30, decimals=0, py_value="", default="err_default")) table_row.__add__( parm(name="datatype", structure="", type=RFCEXPORT, intype=RFCTYPE_CHAR, len=1, decimals=0, py_value="", default="err_default")) table_row.__add__( parm(name="pos", structure="", type=RFCEXPORT, intype=RFCTYPE_CHAR, len=4, decimals=0, py_value="", default="err_default")) table_row.__add__( parm(name="off", structure="", type=RFCEXPORT, intype=RFCTYPE_CHAR, len=6, decimals=0, py_value="", default="err_default")) table_row.__add__( parm(name="intlen", structure="", type=RFCEXPORT, intype=RFCTYPE_CHAR, len=6, decimals=0, py_value="", default="err_default")) table_row.__add__( parm(name="decs", structure="", type=RFCEXPORT, intype=RFCTYPE_CHAR, len=6, decimals=0, py_value="", default="err_default")) table_row.__add__( parm(name="default", structure="", type=RFCEXPORT, intype=RFCTYPE_CHAR, len=21, decimals=0, py_value="", default="err_default")) table_row.__add__( parm(name="text", structure="", type=RFCEXPORT, intype=RFCTYPE_CHAR, len=79, decimals=0, py_value="", default="err_default")) table_row.__add__( parm(name="rem", structure="", type=RFCEXPORT, intype=RFCTYPE_CHAR, len=1, decimals=0, py_value="", default="err_default")) tparams.__add__(table_row) isapiface.addParm(tparams) isapiface.encode() if saprfcutil.call_receive(self, isapiface) == 0: raise NameError, "failed on RFC_GET_FUNCTION_INTERFACE_P" isapiface.decode() return isapiface if re.compile("^[4-9]\d\w").match(info["RFCSAPRL"]): regex = "1s 30s 30s 30s 1s 4s 6s 6s 6s 21s 79s 1s" else: regex = "1s 30s 10s 10s 1s 4s 6s 6s 6s 21s 79s" if self.trace > 0: print regex for row in tparams.value: if len(row) == 215: type, name, tabname, field, datatype, pos, off, intlen, decs, default, text, rem = unpack( regex, row) else: type, name, tabname, field, datatype, pos, off, intlen, decs, default, text = unpack( regex, row) name = name.strip() tabname = tabname.strip() field = field.strip() intlen = int(intlen) decs = int(decs) reResult = re.compile("^\"(.*?)\"\s*$").search(default) if reResult: default = reResult.group(0) else: reResult = re.compile("^SY\-(\w+)\W*$").search(default) if reResult: default = "RFC" + reResult.group(0) if info[default]: default = info[default] else: default = "" structure = "" if datatype == "C": # Character datatype = RFCTYPE_CHAR if re.compile("^SPACE\s*$").search(default): default = " " elif datatype == "X": # Hex datatype = RFCTYPE_BYTE if default: default = "%*X" % intlen, default elif datatype == "I": # Integer datatype = RFCTYPE_INT if re.compile("^\s+$").match(default): default = 0 else: default = int(default) intlen = 4 elif datatype == "s": # Short Integer datatype = RFCTYPE_INT2 if re.compile("^\s+$").match(default): default = 0 else: default = int(default) intlen = 2 elif datatype == "b": # Very Short Integer datatype = RFCTYPE_INT1 if re.compile("^\s+$").match(default): default = 0 else: default = int(default) intlen = 1 elif datatype == "D": # Date datatype = RFCTYPE_DATE default = "00000000" intlen = 8 elif datatype == "T": # Time datatype = RFCTYPE_TIME default = "000000" intlen = 6 elif datatype == "P": # Binary Coded Decimal eg. CURR QUAN etc datatype = RFCTYPE_BCD elif datatype == "N": # Numchar datatype = RFCTYPE_NUM if default == 0 or re.compile("^[0-9]+$").search(default): default = sprintf("%0" + intlen + "d", default) elif datatype == "F": # Float datatype = RFCTYPE_FLOAT intlen = 8 # new style elif (datatype == "u" or datatype == "h" or datatype == " " or datatype == "") and field == "" and type != "X": structure = self.structure(tabname) datatype = RFCTYPE_BYTE else: # Character datatype = RFCTYPE_CHAR if re.compile("^SPACE\s*$").match(default): default = " " if datatype == "": datatype = RFCTYPE_CHAR if type == "I": # Export Parameter - Reverse perspective eparam = parm(name, structure, RFCEXPORT, datatype, intlen, decs, default, default) interface.addParm(eparam) elif type == "E": # Import Parameter - Reverse perspective iparam = parm(name, structure, RFCIMPORT, datatype, intlen, decs, "", "") interface.addParm(iparam) elif type == "T": # Table tparam = tab(name, structure, intlen) interface.addParm(tparam) else: # This is an exception definition interface.addException(name) del efuncname del tparams del isapiface return interface
def data_struct(self, block, data): struct = namedtuple("data_struct", "op_code block data") struct_handle = Struct("!h h " + str(len(data)) + "s") return struct_handle.pack(*struct(self.OpCode, block, data))
# _*_ coding:utf-8 _*_ __author__ = "yangtuo" __date__ = "2019/3/25 20:44" import struct st = struct('i16sf') data = ["123", "abc", 123] data = st.pack(data) print(data) st.unpack(data)
class HL2RaceGhostHandler(DatagramProtocol): # Called on server startup (specifically when we've started to listen) def startProtocol(self): self.players = {} self.inRace = False # Handle receieved packets def datagramReceived(self, data, (host, port)): print data # Get packet ID pID = self.getPacketID(data) # First check if its a communication or data packet if pID > 127: # Position code will go here if self.inRace and (host, port) in self.players and pID == 128: position_data = struct.unpack("Bfff", data) print "X: %f Y: %f Z: %f" % position_data[0], position_data[1], position_data[2] # Relay position data to everyone else in your map for player in self.players.values(): if player["map"] == self.players[(host, port)]["map"]: tosend = struct.pack("B" + str(len(self.player[(host, port)]["name"])) + "sBfff", 128, self.player[(host, port)]["name"], 0, position_data[1], position_data[2], position_data[3]) self.transport.write(tosend, (host, port)) else: # Communcation code goes here if pID == 0: # Do not let any connections in if the race has started. # Connect / Disconnect handling pass_attempt = struct.unpack(str(len(data) - 1) + "s", data[1:])[0] if pass_attempt == PASSWORD: if not self.inRace: self.players[(host, port)] = {} self.transport.write(struct.pack("BB", 0, 1), (host, port)) print host + " has connected." else: if (host, port) in self.players: self.transport.write(struct("BB", 0, 1), (host, port)) else: self.transport.write(struct.pack("BB", 0, 0), (host, port)) else: try: del self.players[(host, port)] except: pass finally: self.transport.write(struct.pack("BB", 0, 0), (host, port)) print host + " has disconnected." # The following packet checks should only work if the client has "connected" if (host, port) in self.players: if pID == 1: # Map change map_change = struct.unpack(str(len(data)-1) + "s", data[1:])[0] self.players[(host, port)]["map"] = map_change print host + " has changed to map " + map_change + "." if pID == 2: # Model / Name change if not self.inRace: # We're going to split the data by a null terminator to get # both strings separately split_data = data[1:].split("\x0A") model = struct.unpack(str(len(split_data[0])) + "s", split_data[0])[0] name = struct.unpack(str(len(split_data[1])) + "s", split_data[1])[0] print host + " has changed name to " + name + " and model to " + model + "." self.players[(host, port)]["model"] = model self.players[(host, port)]["name"] = name self.startRace()
fprintf(out, "%s )\n", indent) else: fprintf(out, "%s return None\n", indent) return # Each state contains a set of token transaction and a set of # nonterminal transactions. Each of these sets makes an instance of # the following structure. An array of these structures is used to # order the creation of entries in the yy_action[] table. axset = struct( "axset", ( "stp", # A state "isTkn", # True to use tokens. False for non-terminals "nAction", # Number of actions "iOrder", # Original order of action sets ), ) def axset_compare(a, b): """Compare to axset structures for sorting purposes.""" c = b.nAction - a.nAction if c == 0: c = b.iOrder - a.iOrder assert c != 0 or a == b return c
import serial import struct pi_ser_cmd = serial.Serial() pi_ser_cmd.port = '/dev/ttyAMA0' pi_ser_cmd.baudrate = 115200 pi_ser_cmd.bytesize = serial.EIGHTBITS pi_ser_cmd.parity = serial.PARITY_NONE pi_ser_cmd.stopbits = serial.STOPBITS_ONE pi_ser_cmd.timeout = 3 pi_ser_cmd.xonxoff = False pi_ser_cmd.rtscts = False pi_ser_cmd.dsrdtr = False pi_ser_cmd.writeTimeout = 2 pi_ser_cmd.open() pi_ser_cmd.write(struct('!l', 1)) pi_ser_cmd.readall() values = (2, 2, 3) picmd = '' for i in values: picmd += struct.pack('!lll', i) pi_ser_cmd.write(picmd) pi_ser_cmd.readall()
def read_by_struct(struct, bytedata): size = struct.struct_size return [ struct(bytedata[i * size:(i + 1) * size]) for i in range(len(bytedata) // size) ]
''' Code for processing tables in the LEMON parser generator. ''' from struct import * from ccruft import * # There is one instance of the following structure for each # associative array s_x = struct( 's_x', ( 'size', # The number of available slots. # Must be a power of 2 greater than or equal to 1 'count', # Number of currently slots filled 'tbl', # The data stored here 'ht', # Hash table for lookups ) ) # There is one instance of this structure for every data element in an # associative array s_xnode = struct( 's_xnode', ( 'data', # The data 'key', # The key 'next', # Next entry with the same hash '_from', # Previous link )
def __init__(self, file_images, file_labels): with open(file_images, 'rb') as f: _, num, rows, cols = struct('>IIII', f.read(16)) train_data = np.fromfile(f, dtype=np.uint8)
WAITING_FOR_FALLBACK_ID, WAITING_FOR_WILDCARD_ID, ) = range(18) pstate = struct( 'pstate', ( 'filename', # Name of the input file 'tokenlineno', # Linenumber at which current token starts 'errorcnt', # Number of errors so far 'tokenstart', # Text of current token 'gp', # Global state vector 'state', # The state of the parser 'fallback', # The fallback token 'lhs', # Left-hand side of current rule 'lhsalias', # Alias for the LHS 'nrhs', # Number of right-hand side symbols seen 'rhs', # RHS symbols 'alias', # Aliases for each RHS symbol (or NULL) 'prevrule', # Previous rule parsed 'declkeyword', # Keyword of a declaration 'declargslot', # Where the declaration argument should be put 'insertLineMacro', # Add #line before declaration insert 'declassoc', # Assign this association to decl arguments 'preccounter', # Assign this precedence to decl arguments 'firstrule', # Pointer to first rule in the grammar 'lastrule', # Pointer to the most recently parsed rule )) def parseonetoken(psp, x): '''Parse a single token.'''
def __init__(self, struct): self.struct = struct self.size = struct().getSize()
#!/usr/bin/env python3 import struct # Packing values to bytes # The first parameter is the format string. Here it specifies # the data is structured with a single four-byte integer followed # by two characters. # The rest of the parameters are the values for each item in order binary_data = struct('icc', 8499000, b'A', b'Z') print(binary_data) # When unpacking, you recieve a tuple of all data in the same order tuple_of_data = struct('icc', binary_data) print(tuple_of_data) # For more information on format strings and endiannes, refer to # http://docs.python.org/3.5/library/struct.html
) = range(18) pstate = struct( 'pstate', ( 'filename', # Name of the input file 'tokenlineno', # Linenumber at which current token starts 'errorcnt', # Number of errors so far 'tokenstart', # Text of current token 'gp', # Global state vector 'state', # The state of the parser 'fallback', # The fallback token 'lhs', # Left-hand side of current rule 'lhsalias', # Alias for the LHS 'nrhs', # Number of right-hand side symbols seen 'rhs', # RHS symbols 'alias', # Aliases for each RHS symbol (or NULL) 'prevrule', # Previous rule parsed 'declkeyword', # Keyword of a declaration 'declargslot', # Where the declaration argument should be put 'insertLineMacro', # Add #line before declaration insert 'declassoc', # Assign this association to decl arguments 'preccounter', # Assign this precedence to decl arguments 'firstrule', # Pointer to first rule in the grammar 'lastrule', # Pointer to the most recently parsed rule ) ) def parseonetoken(psp, x):
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name,too-many-boolean-expressions,redundant-keyword-arg """ =========================================================== QPY serialization (:mod:`qiskit.circuit.qpy_serialization`) =========================================================== .. currentmodule:: qiskit.circuit.qpy_serialization .. warning:: QPY serialization is still an experimental feature, the API and/or forward compatibility are not yet guaranteed. Future versions of Qiskit may not be fully compatible. .. autosummary:: load dump
# default action for the state_number is returned. # # All actions associated with a single state_number are first entered # into aLookahead[] using multiple calls to acttab_action(). Then the # actions for that single state_number are placed into the aAction[] # array with a single call to acttab_insert(). The acttab_insert() call # also resets the aLookahead[] array in preparation for the next # state number. acttab = struct( 'acttab', ( 'nAction', # Number of used slots in aAction[] 'nActionAlloc', # Slots allocated for aAction[] 'aAction', # The yy_action[] table under construction 'aLookahead', # A single new transaction set 'mnLookahead', # Minimum aLookahead[].lookahead 'mnAction', # Action associated with mnLookahead 'mxLookahead', # Maximum aLookahead[].lookahead 'nLookahead', # Used slots in aLookahead[] 'nLookaheadAlloc', # Slots allocated in aLookahead[] ) ) action = struct( 'action', ( 'lookahead', # Value of the lookahead token 'action', # Action to take on the given lookahead ) )