def pack_file_final(self): path = self.path outname = self.outname.get() format = self.format.get().upper() endian = ENDIANS[self.endian.get().lower()] stringopts = self.opts.get() opts = self.parse_opts(stringopts) if format not in formats: showerror('Format error', 'This is not a supported format for packing') return pack(path, outname, format, endian, opts)
def pack_files(filenames, output, compression, format, isbigendian, verbose, opts): endian = '>' if isbigendian else '<' for name in filenames: if not os.path.exists(name): error.FileNotFoundError('Input file %s is not found' % name) if format.upper() in pack.formats: print('Packing %s...' % output) pack.pack(filenames, output, format, endian, verbose, opts) print('Packed!') else: error.UnsupportedFormatError('3DSkit is currently unable to pack this format') if compression is not None: compress_file(output, compression, verbose, False)
def submit(): token, consumer = authenticate() game_def = get_definition() project_path, y = get_game_dir_info() path = "%s/%s" % (project_path,y) pack() content = open(project_path + "/game.zip", 'rb').read() digest = hashlib.sha1() digest.update(content) game = get_game(game_def['game_id']) if game_def['autoVersion']: print "Submiting %s" % (game['name']) else: print "Submiting %s v%s" % (game['name'],game_def['version']) print "Digest (SHA1): " + digest.hexdigest() files = [("submission", 'game', content)] params = { 'oauth_version': "1.0", 'oauth_nonce': oauth.generate_nonce(), 'oauth_timestamp': int(time.time()), 'oauth_token': token.key, 'oauth_consumer_key': consumer.key, 'game_id': game_def['game_id'], } #create a fake request with your upload url and parameters faux_req = oauth.Request(method='POST', url="http://localhost:8000/api/submissions.json", parameters=params) #sign the fake request. signature_method = oauth.SignatureMethod_HMAC_SHA1() faux_req.sign_request(signature_method, consumer, token) #create a dict out of the fake request signed params params = dict(parse_qsl(faux_req.to_postdata())) content_type, body = encode_multipart_formdata(params, files) headers = {'Content-Type': content_type, 'Content-Length': str(len(body))} r = urllib2.Request('%s' % "http://localhost:8000/api/submissions.json", body, headers) try: urllib2.urlopen(r).read() print "Successful" except urllib2.HTTPError, ex: print >> sys.stderr, 'Received error code: ', ex.code print >> sys.stderr print >> sys.stderr, ex f = open("coredump",'w') f.write(ex.read()) sys.exit(1)
def createBranch(self, changeList): targetBranch = distribTools.releaseInfo.releasePath2filename( changeList.branchTo, '/') # # write desc file # descFile = '%s_%05d.desc' % (self.filebase, changeList.id) stream = open(self.outputFile(descFile), 'wt') stream.write('<?xml version="1.0"?>\n') stream.write('<PerforceChange id="%d">\n' % changeList.id) stream.write(' <Comment>Branch from %s to %s</Comment>\n' % (self.filebase, targetBranch)) stream.write(' <Files>\n') stream.write(' <!--- all files are branched --->\n') stream.write(' </Files>\n') stream.write('</PerforceChange>\n') stream.close() # # pack and transfer branch # archive = '%s_%05dbranchto_%s' % (self.filebase, changeList.id, targetBranch) localFile = pack.pack(self.outputFile(archive), [descFile], self.options.outdir) distribTools.common.transferByFTP(self.options, localFile) return []
def pack (self, stdfiles): relid = distribTools.releaseInfo.release2filename (self.releaseInfo) filename = '%s_%05d' % (relid, self.changeList) fname = os.path.join (self.options.outdir, filename) filelist = ['filelist.xml'] + stdfiles for filename, kind in self.fileList: filelist.append (filename) self.snapshotFile = pack.pack (fname, filelist, self.sourceTree.getLocalPath ())
class vehicle(object): motorCount = -1 batteryPack = pack() motorList = [] structuralMass = 0 payloadMass = 0 totalWeight = 0 totalThurst = 0
def packChunk(self, chunk, chunkStart, chunkEnd): chunk = filter(None, chunk) if not chunk: return chunkStart archivebase = '%s_%05dto%05d' % (self.filebase, chunkStart, chunkEnd) archive = self.outputFile(archivebase) localFile = pack.pack(archive, chunk, self.options.outdir) distribTools.common.transferByFTP(self.options, localFile) return chunkEnd
def send(self, client, id, message): resp_length, resp_data = data_pack(message) resp_header = pack(resp_length, id) try: client.sendall(resp_header) client.sendall(resp_data) return id except OSError: self.clients[client]["loop"] = False return
def verify_dir(): # test2: test that a packed dir gets unpacked correctly tweet_id = pack(TEST_SRC, memory_uploader) root_payload = deserialize(memory_downloader(tweet_id)) unpack(root_payload, memory_downloader, name_override=TEST_DIR_DEST, recur=True) if not are_identical_dirs(TEST_SRC, TEST_DIR_DEST): raise RuntimeError('%s is diff than %s, packing test failed' % \ (TEST_SRC, TEST_DIR_DEST)) else: print 'TEST 2: PASSED'
def sendData(stock_id, data): skt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) skt.bind(SequencerConfig.SENDER_ADD) packages = pack(stock_id, data) b = bytes() for each in packages: skt.sendto(each, SequencerConfig.MULTICAST_DST) b += each[12:] recover = json.loads(b.decode()) print("SendMessage Keys", len(b), recover.keys()) skt.close()
def verify_file(): # test1: test that a packed file gets unpacked correctly fn = TEST_SRC + '/foo' tweet_id = pack(fn, memory_uploader) payload = deserialize(memory_downloader(tweet_id)) unpack(payload, memory_downloader, name_override=TEST_FILE_DEST , recur=True) if not are_identical_dirs(fn, TEST_FILE_DEST): raise RuntimeError('%s is diff than %s, packing test failed' % \ (fn, TEST_FILE_DEST)) else: print 'TEST 1: PASSED'
def init(): if args.args.get('pack'): pack.pack(args.args['pack']) sys.exit() if args.args.get('pack_data'): pack.pack_data(args.args['pack_data']) sys.exit() if args.args.get('unpack'): pack.unpack(args.args['unpack']) sys.exit() if not os.path.isdir('accounts'): try: os.mkdir('accounts') except PermissionError: print('Unable to create accounts directory') sys.exit() acc = args.args['account'] if acc is None: acc = forceInput('Enter account name ({}): '.format( listAccounts() or 'no existing accounts')) if not validateName(acc): print('Invalid account name') sys.exit() if accountExists(acc): selectAccount(acc) else: try: if not listAccounts() or input( 'Account {} does not exist. Create it? [y/n]'.format( acc)).lower() == 'y': print('Creating new account') createAccount(acc) else: sys.exit() except EOFError: print() sys.exit()
def verify_file(): # test1: test that a packed file gets unpacked correctly fn = TEST_SRC + '/foo' tweet_id = pack(fn, memory_uploader) payload = deserialize(memory_downloader(tweet_id)) unpack(payload, memory_downloader, name_override=TEST_FILE_DEST, recur=True) if not are_identical_dirs(fn, TEST_FILE_DEST): raise RuntimeError('%s is diff than %s, packing test failed' % \ (fn, TEST_FILE_DEST)) else: print 'TEST 1: PASSED'
def sendDic(self, dic): if print_log: print 'DlgChat::sendDic=', dic output =pack.pack(self.pwd, dic) if len(output)>0 and self.sock and self.connected: try: self.sock.send(output) except : self.sock.close() self.clearConnectedInfo() self.insertEditInfo(u'[%s] 服务器已断连,请重新连接服务!'%(self.formatTime(self.timeNow()))); return False else: return True else: return False
def sendDic(self, dic): if print_log: print 'DlgChat::sendDic=', dic output = pack.pack(self.pwd, dic) if len(output) > 0 and self.sock and self.connected: try: self.sock.send(output) except: self.sock.close() self.clearConnectedInfo() self.insertEditInfo(u'[%s] 服务器已断连,请重新连接服务!' % (self.formatTime(self.timeNow()))) return False else: return True else: return False
def pack_gcodes(gcodes, width, height, padding, seed=None): gcodes = filter(None, [g.rotate_to_fit(width, height) for g in gcodes]) result = [] sizes = [g.size for g in gcodes] sizes = [(w + padding * 2, h + padding * 2) for w, h in sizes] # print best_seed(width, height, sizes, 1000) bins = pack(width, height, sizes, seed) for b in bins: bg = GCode() for item in b: index, rotated, (x, y, _, _) = item g = gcodes[index] if rotated: g = g.rotate(-90).origin() g = g.translate(x + padding, y + padding) bg += g result.append(bg) return result
def on_btnSend_clicked(self): """ Slot documentation goes here. """ if self.sock: txt =self.editInput.toPlainText() timenow =time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) d ={'chid':str(self.chid.toUtf8()), 'txt':str(txt.toUtf8()), 'timenow':timenow} output =pack.pack(self.pwd, d) if len(output)<1: self.editInfo.append(u"发送失败!"); else: print 'sent:', output[8:] self.sock.send(output) self.editInput.clear() self.editOutput.append('['+timenow +'] '+self.chid +u' (自己)说: '+ txt +u'\n') else: self.editInfo.append(u"请先连接服务器!");
def send(socket, data, fStopped=None, bClose=True, fPercentUpdate=None): if fStopped: socket.settimeout(SOCKET_TIMEOUT) total = 0 data = pack.pack(data) size = len(data) data = str(size) + ';' + data size = float(len(data)) while 1: try: sent = socket.sendall(data[total:]) total += sent if fPercentUpdate: fPercentUpdate(total/size) if total >= size: if bClose: socket.close() return True except AttributeError, e: if fStopped and fStopped(): if bClose: socket.close() return False
def init(): global key, readlock logger.info('Initializing...') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) logger.log(f'Using pack version {pack.version}') logger.info( f'Connecting to the server: {server[0]} on port {str(server[1])}') s.connect(server) logger.info('Starting listening thread...') t = threading.Thread(target=connection_keep_recv, args=(s, server)) t.setDaemon(True) t.start() readlock = True logger.info('Registering existance...') rand = secrets.token_urlsafe(32) s.send(pack.pack('register', json.dumps({'rand': rand}).encode())) logger.info('Existance registered, waiting for the reply...') logger.info('Obtaining key for encryption...') # Obtain secrect key for encryption, via HTTPS r = requests.get('https://' + keyserver + '/obtain', {'rand': rand}) if 'key' not in r.json(): logger.fatal('Failed to obtain key!') key = base64.b64decode(r.json()['key']) logger.log(key=key) readlock = False logger.info('Successfully obtained key!') # while True: # logger.info('Loading...') t.join()
#coding:utf-8 #基于python2.6 import struct import pack import dataUnpack import PlayerInfo_pb2 test=PlayerInfo_pb2.PlayerInfo() test.uin=13558871 test.role_id=2 test.name='F**K' test_str = test.SerializeToString() print len(test_str) k=pack.pack('1001',[len(test_str),2,3,2,13558871,2,'192.168.1.2',2]) print repr(k+test_str) print len(k+test_str) print dataUnpack.dataUnpack('1001',k) print struct.calcsize('<IIIIIIh11sI')
n, f = info['compression'] log("Compression: %s" % n) data = f(data) if data is None: die("Decompression failed") log("Unpacking...") numFiles, numBytes = unpack(data, args.outdir or '.') log("Unpacked %d file(s) (%s)" % (numFiles, bytesToStr(numBytes))) elif args.create: dst = args.create info = [VERSION] + [0] * 11 data = pack(args.src) pieces = [] if args.compress != False: args.compress = args.compress or 'zlib' log('Compression: %s' % args.compress) n, f = { 'zlib': (1, comp.zlib.compress), 'hmc': (2, comp.hmc.compress), 'bpk': (3, comp.bpk.compress), 'qed': (4, comp.qed.compress), }[args.compress] info[1] = n data = f(data) if args.encrypt != False:
def main(): STATES = {'D':('Development',bcolors.WARNING), '':("Unknown",bcolors.FAIL)} if len(sys.argv) <= 1: help(); return app = sys.argv[1] if app == "pack": print "Packing project into game.zip..." pack() elif app == "validate": verify_game_auth() print "Everything seems to be ok." elif app == "listgames": print "Listing your games:" print games = get_all_games() for game in games: print bcolors.HEADER + game['name'] + bcolors.ENDC + ":" print " Game Id : " + game['game_id'] state = STATES[game['status']] print " Status : " + state[1] + state[0] + bcolors.ENDC print elif app == "auth": update_tokens() return elif app == "submit": submit() elif app == "wait": STATES = {'U':('Pending',bcolors.OKBLUE), 'T':("Processed",bcolors.OKGREEN), 'E':("Error",bcolors.FAIL)} collect = {} for sub in get_submited(): if sub['game']['key'] in collect: collect[sub['game']['key']].append(sub) else: collect[sub['game']['key']] = [ sub ] for key in collect.keys(): game = collect[key] print bcolors.HEADER + "%s" % (game[0]['game']['name']) + bcolors.ENDC + ":" print " Game ID : %s" % game[0]['game']['key'] for ver in game[:5]: print print (" Submited on %s by" + bcolors.OKGREEN + " %s " + bcolors.ENDC) % (ver['submission_date'].replace("T"," "), ver['user']['username']) state = STATES[ver['status']] print " Status : " + state[1] + state[0] + bcolors.ENDC print " Digest : " + ver['digest'] elif app == "start": if len(sys.argv) < 3: print "You must specify a project name.\n\nusage: intigos start <project name>" start(sys.argv[2]) return; elif app == "run": try: opts, args = getopt.getopt(sys.argv[2:], 'a:,', ['addr=']) except getopt.GetoptError, err: print str(err) # will print something like "option -a not recognized" sys.exit(2) addr = 'localhost:8000' for o, a in opts: if o in ("-a", "--addr"): addr = a run(addr=addr)
test=PlayerInfo_pb2.PlayerInfo() test.uin=13558871 test.role_id=2 test.name='FUChhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhKkkklkljljlkjljlk' test_str = test.SerializeToString() print len(test_str) toIP = lambda x: '.'.join([str(x/(256**i)%256) for i in range(3,-1,-1)]) toINT = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])]) k=pack.pack('1001',[len(test_str),1,3,2,13558871,2,toINT('192.168.0.2'),2]) print repr(k+test_str) print len(k+test_str) j=struct.unpack('<IIIIIIII',k) print '包头大小',struct.calcsize('<IIIIIIII') print j sock.send(k+test_str) test22= sock.recv(1024) sock.close() print struct.unpack('>I',test22)
def upload(fn, uploader, concealer): ''' fn: a filename or dirnname ''' print 'mode: upload' tweet_id = pack(fn, uploader, concealer) print 'done'
from pack import pack from update_version import update_version if __name__ == "__main__": pack() update_version()
#file --main.py-- from cell import cell from motor import motor from pack import pack from vehicle import vehicle #Vehicle inputs: motorCount = 1 #example #Motor input: motorName = 'Emrax 228 MV' motorVoltage = 300 motorMaxCurrent = 266.6 #Energy input: #Format [power(Watts), duration(hours)],[power2(Watts), duration2(hours)] powerInterval = [[80000, .017], [64000, .067], [ 36400, .33 ]] #FIXME: This doesn't assign correctly, set it in line 13 in pack.py myPack = pack() myPack.setVoltageRequired(motorVoltage) myPack.energyRequiredFromList(powerInterval) myPack.setPowerRequired(motorMaxCurrent * motorCount) print('_______________________________________________________________') myPack.optimizePack()