def testCreateRequest(self): """ Tests the OneLogin_Saml2_Authn_Request Constructor. The creation of a deflated SAML Request """ saml_settings = self.loadSettingsJSON() settings = OneLogin_Saml2_Settings(saml_settings) settings._OneLogin_Saml2_Settings__organization = { u'en-US': { u'url': u'http://sp.example.com', u'name': u'sp_test' } } authn_request = OneLogin_Saml2_Authn_Request(settings) authn_request_encoded = authn_request.get_request() decoded = b64decode(authn_request_encoded) inflated = decompress(decoded, -15) self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest') self.assertNotIn('ProviderName="SP test"', inflated) saml_settings['organization'] = {} settings = OneLogin_Saml2_Settings(saml_settings) authn_request = OneLogin_Saml2_Authn_Request(settings) authn_request_encoded = authn_request.get_request() decoded = b64decode(authn_request_encoded) inflated = decompress(decoded, -15) self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest') self.assertNotIn('ProviderName="SP test"', inflated)
def __synchronizeEventNotifications(self, diff): diffDict = {'added': [], 'removed': []} if diff is None: return else: initialEventsData = diff.get(('eventsData', '_r'), {}) initial = initialEventsData.pop(EVENT_CLIENT_DATA.NOTIFICATIONS, None) initialEventsData.pop(EVENT_CLIENT_DATA.NOTIFICATIONS_REV, None) if initial is not None: initial = cPickle.loads(zlib.decompress(initial)) self.eventNotifications = g_accountRepository.eventNotifications = initial diffDict['added'].extend(initial) updatedEventsData = diff.get('eventsData', {}) updated = updatedEventsData.pop(EVENT_CLIENT_DATA.NOTIFICATIONS, None) updatedEventsData.pop(EVENT_CLIENT_DATA.NOTIFICATIONS_REV, None) if updated is not None: updated = cPickle.loads(zlib.decompress(updated)) eventNotifications = self.eventNotifications self.eventNotifications = g_accountRepository.eventNotifications = updated new = set([ NotificationItem(n) for n in updated ]) prev = set([ NotificationItem(n) for n in eventNotifications ]) added = new - prev removed = prev - new diffDict['added'].extend([ n.item for n in added ]) diffDict['removed'].extend([ n.item for n in removed ]) if initial is not None or updated is not None: events.onEventNotificationsChanged(diffDict) LOG_DZ('Account.__synchronizeEventNotifications, diff=%s' % (diffDict,)) return
def node_load (self, desc): """Load node by its descriptor """ node_data = self.store.Load (desc) node_tag = node_data [-1:] if node_tag != b'\x01': # load node node_stream = io.BytesIO (node_data [:-1]) if not self.compress else \ io.BytesIO (zlib.decompress (node_data [:-1])) node = StoreBPTreeNode (desc, self.keys_from_stream (node_stream), Serializer (node_stream).StructListRead (self.desc_struct)) else: # load leaf prev, next = self.leaf_struct.unpack (node_data [:self.leaf_struct.size]) node_stream = io.BytesIO (node_data [self.leaf_struct.size:-1]) if not self.compress else \ io.BytesIO (zlib.decompress (node_data [self.leaf_struct.size:-1])) node = StoreBPTreeLeaf (desc, self.keys_from_stream (node_stream), self.values_from_stream (node_stream)) node.prev = prev node.next = next self.d2n [desc] = node return node
def testCreateRequestAuthContextComparision(self): """ Tests the OneLogin_Saml2_Authn_Request Constructor. The creation of a deflated SAML Request with defined AuthnContextComparison """ saml_settings = self.loadSettingsJSON() settings = OneLogin_Saml2_Settings(saml_settings) authn_request = OneLogin_Saml2_Authn_Request(settings) authn_request_encoded = authn_request.get_request() decoded = b64decode(authn_request_encoded) inflated = decompress(decoded, -15) self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest') self.assertIn(OneLogin_Saml2_Constants.AC_PASSWORD, inflated) self.assertNotIn(OneLogin_Saml2_Constants.AC_X509, inflated) saml_settings['security']['requestedAuthnContext'] = True settings = OneLogin_Saml2_Settings(saml_settings) authn_request = OneLogin_Saml2_Authn_Request(settings) authn_request_encoded = authn_request.get_request() decoded = b64decode(authn_request_encoded) inflated = decompress(decoded, -15) self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest') self.assertIn('RequestedAuthnContext Comparison="exact"', inflated) saml_settings['security']['requestedAuthnContextComparison'] = 'minimun' settings = OneLogin_Saml2_Settings(saml_settings) authn_request = OneLogin_Saml2_Authn_Request(settings) authn_request_encoded = authn_request.get_request() decoded = b64decode(authn_request_encoded) inflated = decompress(decoded, -15) self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest') self.assertIn('RequestedAuthnContext Comparison="minimun"', inflated)
def testCreateRequestSetNameIDPolicy(self): """ Tests the OneLogin_Saml2_Authn_Request Constructor. The creation of a deflated SAML Request with and without NameIDPolicy """ saml_settings = self.loadSettingsJSON() settings = OneLogin_Saml2_Settings(saml_settings) authn_request = OneLogin_Saml2_Authn_Request(settings) authn_request_encoded = authn_request.get_request() decoded = b64decode(authn_request_encoded) inflated = decompress(decoded, -15) self.assertRegexpMatches(inflated, '^<samlp:AuthnRequest') self.assertIn('<samlp:NameIDPolicy', inflated) authn_request_2 = OneLogin_Saml2_Authn_Request(settings, False, False, True) authn_request_encoded_2 = authn_request_2.get_request() decoded_2 = b64decode(authn_request_encoded_2) inflated_2 = decompress(decoded_2, -15) self.assertRegexpMatches(inflated_2, '^<samlp:AuthnRequest') self.assertIn('<samlp:NameIDPolicy', inflated_2) authn_request_3 = OneLogin_Saml2_Authn_Request(settings, False, False, False) authn_request_encoded_3 = authn_request_3.get_request() decoded_3 = b64decode(authn_request_encoded_3) inflated_3 = decompress(decoded_3, -15) self.assertRegexpMatches(inflated_3, '^<samlp:AuthnRequest') self.assertNotIn('<samlp:NameIDPolicy', inflated_3)
def parse_xml(data): print zlib.decompress(data) book = ET.fromstring(zlib.decompress(data)) self._flushContacts() for elem in book.find('Groups').getchildren(): self.addGroup( GaduContactGroup.from_xml(elem) ) for elem in book.find('Contacts').getchildren(): is_uin_ok = 1 try: check_uin = elem.find("GGNumber") int(check_uin.text) if check_uin.text == '': is_uin_ok = 0 except: is_uin_ok = 0 if is_uin_ok == 1: contact = GaduContact.from_xml(elem) self.addContact( contact ) self.__connection.addNewContact(contact) else: print 'Failed to import contact. Invalid uin: %s.' % check_uin.text callback()
def postreply(self, reply): if self.options.compression in ['yes', 'auto']: for header, headerval in reply.headers.items(): # this needs to be items() and not iteritems() because it's sometimes an httplib.HTTPMessage (when decoding an error response) and that doesn't support iteritems()! if header.lower() == 'content-encoding': log.debug('http reply with a content-encoding header') if headerval == 'gzip': log.debug('decompressing gzip content') replydatafile = cStringIO.StringIO(reply.message) gzipper = gzip.GzipFile(fileobj=replydatafile) reply.message = gzipper.read() elif headerval == 'deflate': # decompress the deflate content log.debug('decompressing deflate content') try: reply.message = zlib.decompress(reply.message) except zlib.error: # Many web sites fail to send the first bytes of the header reply.message = zlib.decompress(reply.message, -zlib.MAX_WBITS) else: # unknown scheme log.debug('unsupported content-encoding scheme') pass break return reply
def _report_variant_pathways(c, args, idx_to_sample): (agn_paths, hgnc_paths, ensembl_paths) = get_pathways(args) for r in c: gt_types = np.array(cPickle.loads(zlib.decompress(r['gt_types']))) gts = np.array(cPickle.loads(zlib.decompress(r['gts']))) gene = str(r['gene']) trans = str(r['transcript']) pathways = [] if (gene, trans) in agn_paths: pathways = _get_pathways(gene, trans, agn_paths[(gene, trans)], allow_none=False) elif (gene, trans) in hgnc_paths: pathways = _get_pathways(gene, trans, hgnc_paths[(gene, trans)], allow_none=False) elif (gene, trans) in ensembl_paths: pathways = _get_pathways(gene, trans, ensembl_paths[(gene, trans)], allow_none=False) pathlist = ",".join(pathways) for idx, gt_type in enumerate(gt_types): if (gt_type == HET or gt_type == HOM_ALT) and \ len(pathways) > 0: print "\t".join([r['chrom'], str(r['start']), str(r['end']), \ r['ref'], r['alt'], r['impact'], \ idx_to_sample[idx], gts[idx], gene, trans, \ pathlist])
def getVersionDiff( self, fromDate, toDate ): retVal = self.rpcClient.getVersionContents( [ fromDate, toDate ] ) if retVal[ 'OK' ]: fromData = zlib.decompress( retVal[ 'Value' ][0] ) toData = zlib.decompress( retVal[ 'Value' ][1] ) return difflib.ndiff( fromData.split( "\n" ), toData.split( "\n" ) ) return []
def testGzExtension(self): with utils.Stubber(urllib2, "urlopen", FakeOpen): profile = self.server.GetProfileByName("pe") # We received compressed data. zlib.decompress(profile.data, 16 + zlib.MAX_WBITS) # We issued one http request. self.assertEqual(FakeHandle.read_count, 1) self.server.GetProfileByName("pe") # This time it should have been cached. self.assertEqual(FakeHandle.read_count, 1) self.server.GetProfileByName("pe") # This is the same profile. self.assertEqual(FakeHandle.read_count, 1) cache_urn = rdfvalue.RDFURN(config_lib.CONFIG["Rekall.profile_cache_urn"]) cached_items = list(aff4.FACTORY.Open( cache_urn.Add(constants.PROFILE_REPOSITORY_VERSION), token=self.token).ListChildren()) # We cache the .gz only. self.assertEqual(len(cached_items), 1) self.assertEqual(cached_items[0].Basename(), "pe")
def default_url_fetcher(url): """Fetch an external resource such as an image or stylesheet. Another callable with the same signature can be given as the :obj:`url_fetcher` argument to :class:`HTML` or :class:`CSS`. (See :ref:`url-fetchers`.) :type url: Unicode string :param url: The URL of the resource to fetch :raises: any exception to indicate failure. Failures are logged as warnings, with the string representation of the exception in the message. :returns: In case of success, a dict with the following keys: * One of ``string`` (a byte string) or ``file_obj`` (a file-like object) * Optionally: ``mime_type``, a MIME type extracted eg. from a *Content-Type* header. If not provided, the type is guessed from the file extension in the URL. * Optionally: ``encoding``, a character encoding extracted eg. from a *charset* parameter in a *Content-Type* header * Optionally: ``redirected_url``, the actual URL of the ressource in case there were eg. HTTP redirects. * Optionally: ``filename``, the filename of the resource. Usually derived from the *filename* parameter in a *Content-Disposition* header If a ``file_obj`` key is given, it is the caller’s responsability to call ``file_obj.close()``. """ if url.lower().startswith('data:'): return open_data_url(url) elif UNICODE_SCHEME_RE.match(url): url = iri_to_uri(url) response = urlopen(Request(url, headers=HTTP_HEADERS)) result = dict(redirected_url=response.geturl(), mime_type=urllib_get_content_type(response), encoding=urllib_get_charset(response), filename=urllib_get_filename(response)) content_encoding = response.info().get('Content-Encoding') if content_encoding == 'gzip': if StreamingGzipFile is None: result['string'] = gzip.GzipFile( fileobj=io.BytesIO(response.read())).read() response.close() else: result['file_obj'] = StreamingGzipFile(fileobj=response) elif content_encoding == 'deflate': data = response.read() try: result['string'] = zlib.decompress(data) except zlib.error: # Try without zlib header or checksum result['string'] = zlib.decompress(data, -15) else: result['file_obj'] = response return result else: raise ValueError('Not an absolute URI: %r' % url)
def _restoreb(self, bdata, pwd=''): ''' Restores binary data from SQL information. \n\ ''' # If password is null in some way, do not encrypt. if not pwd: try: return zlib.decompress(bdata) except: return bz2.decompress(bdata) # If using global password. elif pwd == 1: # If global password is null, do not decrypt. if not self.glob_key: try: return zlib.decompress(bdata) except: return bz2.decompress(bdata) # If global password exists, use it. else: pwd = self.glob_key # If password is provided, generate key derivation. else: pwd = PBKDF2(password=pwd, salt=self.glob_salt, dkLen=32, count=1000) # Decrypt and return. crypt = AES.new(pwd) vCompressed = crypt.decrypt(bdata) try: return zlib.decompress(vCompressed) except: return bz2.decompress(vCompressed)
def decompress_data(self,compression): ### ONLY HANDLING ZLIB_COMPRESSED AT THE MOMENT hex_compress = hex(compression['magic_cookie']) #print(hex_compress) # TA_NOT_COMPRESSED = hex(0x2f2f2f2f) #The data is not compressed. Use as is it. GZIP_COMPRESSED = hex(0xf7f7f7f7) #The data was compressed using GZIP. Uncompressed appropriately. # GZIP_NOT_COMPRESSED = hex(0xf8f8f8f8) #GZIP compression was tried, but it failed. The data is not compressed. Use as it is. # BZIP_COMPRESSED = hex(0xf3f3f3f3) #The data was compressed with BZIP2 version 0.9.0c. Uncompress appropriately. # BZIP_NOT_COMPRESSED = hex(0xf4f4f4f4) #BZIP2 compression was tried, but it failed. The data is not compressed. Use it as it is. ZLIB_COMPRESSED = hex(0xf5f5f5f5) #The data was compressed with ZLIB compression. This is the same as GZIP but without the GZIP header structure. Uncompress appropriately. # ZLIB_NOT_COMPRESSED = hex(0xf6f6f6f6) #ZLIB compression was tried, but it failed. Data is not compressed, us it as it is. if hex_compress == ZLIB_COMPRESSED: nbytes = compression['nbytes_compressed'] bin_data=self.mdvfile.read(nbytes) uncompressed_bytes = zlib.decompress(bin_data) return uncompressed_bytes if hex_compress == GZIP_COMPRESSED: nbytes = compression['nbytes_compressed'] bin_data=self.mdvfile.read(nbytes) #print(bin_data) uncompressed_bytes = zlib.decompress(bytes(bin_data), 15+32) return uncompressed_bytes
def send_http(request): # if there is a proxy , connect proxy server instead proxy_type = None remote = request["remote"] sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if request["proxy"]: # 用代理则先连接代理服务器 proxy_type = connect_proxy(sock, remote, request["proxy"]) else: sock.connect(remote) sock.settimeout(request["timeout"]) # 用代理不能封闭ssl if request["ssl"] and proxy_type != "http": sock = ssl.wrap_socket(sock) request["sock"] = sock # 略粗暴,可能发不全 send_tcp(sock, request["body"]) response = wait_response(request) # 如果需要缓存连接则添加到队列, 否则直接关闭连接 host = "%s:%d" % remote header = response["header"] text = response["recv"].getvalue() del response["recv"] if not request.get("header_only") and header: # maybe gzip stream if header.get("Content-Encoding") == "gzip": text = zlib.decompress(text, 16 + zlib.MAX_WBITS) elif header.get("Content-Encoding") == "deflate": text = zlib.decompress(text, -zlib.MAX_WBITS) response["text"] = text return response
def extract_pkg_from_data(byte_data): complete_pkg = [] z_packages = byte_data.split(compress_pkg_header) len_pkg = len(z_packages) dbgprint('Len_Sep:', len_pkg) if len_pkg < 2: errprint('ReceiveError,CannotFindGzipHeader', byte_data) raise ValueError('ReceiveError,CannotFindGzipHeader') else: data_to_preserve = z_packages.pop() for z_pkg in z_packages: z_pkg = z_pkg[:-compress_pkg_footer_len] # Remove footer mark if not z_pkg: continue dbgprint('AfterGzip', len(z_pkg), v=4) decompressed_data = zlib.decompress(z_pkg) dbgprint('BeforeGzip', len(decompressed_data), v=4) complete_pkg.append(decompressed_data) if data_to_preserve[-compress_pkg_footer_len:] == compress_pkg_footer: # last pkg is complete data_to_preserve = data_to_preserve[:-compress_pkg_footer_len] dbgprint('AfterGzip', len(data_to_preserve), v=4) decompressed_data = zlib.decompress(data_to_preserve) dbgprint('BeforeGzip', len(decompressed_data), v=4) complete_pkg.append(decompressed_data) data_to_preserve = b'' else: data_to_preserve = compress_pkg_header + data_to_preserve return complete_pkg, data_to_preserve
def sniffProbe(p): global msg,msglen if p.haslayer(Dot11): if p.type == 0 and p.subtype == 4: # if management frame and probe-request if p.addr2 == "11:22:33:44:55:66": if ("PART"==p.info[:4]): piecepos=p.info.index("/") piece=p.info[4:piecepos] lenpos=p.info.index('|') msglen=p.info[piecepos+1:lenpos] sys.stdout.write("Receiving long message "+str(piece)+"/"+str(msglen)+"\r") sys.stdout.flush() if (piece==msglen): print "" msg+=p.info[lenpos:] print msg unenc=aes.decrypt(msg) try: uncomp=zlib.decompress(unenc) print uncomp except: print "ERROR - Wrong Password" msg="" msglen=0 else: msg+=p.info[lenpos:] else: unenc=aes.decrypt(p.info) try: uncomp=zlib.decompress(unenc) print uncomp except: print "ERROR - Wrong Password"
def print_stream_defect_occurrences(self,cids,streamIdDO,project=None): streamDefectFilterDO = self.set_stream_filter_spec(stream=streamIdDO.name,project=project, details=True) SDs = self.client.service.getStreamDefects(cids,streamDefectFilterDO) instances = [] for sd in SDs: print '' print "Defect "+str(sd.cid)+" ("+sd.checkerSubcategoryId.domain+")" print " Checker "+sd.checkerSubcategoryId.checkerName+" (subcategory "+sd.checkerSubcategoryId.subcategory+")" for di in getattr(sd,'defectInstances',[]): try: print " File "+di.function.fileId.filePathname print " Function "+di.function.functionDisplayName except: print " Parse Warning (no function name available)" logging.debug("di.events size " +str(len(di.events))) for ev in di.events: logging.debug(ev) logging.debug(ev.eventKind) logging.debug(ev.lineNumber) if ev.eventKind=="NORMAL": print " " + ev.fileId.filePathname + ", line: " + str(ev.lineNumber) print " " + ev.eventDescription logging.debug(len(zlib.decompress(base64.b64decode(self.client.service.getFileContents(streamIdDO,ev.fileId).contents)))) logging.debug(len(zlib.decompress(base64.b64decode(self.client.service.getFileContents(streamIdDO,ev.fileId).contents)).split('\n'))) print " " + zlib.decompress(base64.b64decode(self.client.service.getFileContents(streamIdDO,ev.fileId).contents)).split('\n')[ev.lineNumber-1] print "" for p in getattr(di,'properties',[]): print " " + p.key + ": " + getattr(p,'value','') print ""
def borrar_cumple(): try: f = open("calendario.txt","r")#abre un archivo de modo lectura except: print "no se encontro el archivo calendario.txt" else# El código colocado en la cláusula else se ejecuta solo si no se levante una excepción: print "Ingrese el nombre y fecha del cumple a borrar" fecha = zlib.compress(encriptar(raw_input("Fecha:"))) nomb = zlib.compress(encriptar(raw_input("Nombre:"))) dic = pickle.load(f) f.close()#cierra el archivo if fecha in dic: i = 0 while i < len(dic[fecha]) and dic[fecha][i][0] != nomb: i = i + 1 if i < len(dic[fecha]): del dic[fecha][i] if dic[fecha] == []: del dic[fecha] f = open("calendario.txt","w")#abre archivo de modo escritura pickle.dump(dic, f) f.close()#cierra el archivo else: print "no se encontro el nombre " + zlib.decompress(desencriptar(nomb)) + " en la fecha " + zlib.decompress(desencriptar(fecha)) else: print "no se ha encontrado ningun cumple en la fecha " + zlib.decompress(desencriptar(fecha))
def load(self, info, data): fmt = '{0}i'.format(len(info) / 4) self.info = unpack(fmt, info) # load data to layers if self.type == 'layer': if LAYER_TYPES[self.info[3]] == 'tile': data = decompress(data[self.info[-1]]) fmt = '{0}B'.format(len(data)) self.data = list(unpack(fmt, data)) elif LAYER_TYPES[self.info[3]] == 'quad': data = decompress(data[self.info[-2]]) fmt = '{0}i'.format(len(data) / 4) self.data = list(unpack(fmt, data)) # load image data if self.type == 'image': name = decompress(data[self.info[-2]]) fmt = '{0}c'.format(len(name)) self.name = '' for char in unpack(fmt, name): if char == '\x00': break self.name += char if not self.info[5]: data = decompress(data[self.info[-1]]) fmt = '{0}B'.format(len(data)) data = list(unpack(fmt, data)) self.data = [] for i in range(self.info[4]): self.data.append(data[i*self.info[3]*4:(self.info[3]*4)+(i*self.info[3]*4)])
def resp_deflate(data): # zlib only provides the zlib compress format, not the deflate format; # so on top of all there's this workaround: try: return zlib.decompress(data, -zlib.MAX_WBITS) except zlib.error: return zlib.decompress(data)
def buscar_cumple(): print "Ingrese 1 para buscar por nombre o 2 para buscar por fecha de cumpleanos (cualquier otro caracter para cancelar)" op = raw_input("Opcion:") if op == "1": try: f = open("calendario.txt","r")#Abre el archivo de modo lectura except: print "aun no ha ingresado ningun cumple!" else#El código colocado en la cláusula else se ejecuta solo si no se levante una excepción: print "Ingrese el nombre" nomb = zlib.compress(encriptar(raw_input("Nombre:"))) dic = pickle.load(f)#la funcion load carga el objeto serializado, ya q este es una lista f.close()#cerrar el archivo encontrado = "no" for i in dic.keys():#devuelve una lista de todas las claves usadas en el diccionario for j in range(len(dic[i])): if nomb == dic[i][j][0]: print ("Se encontro " + zlib.decompress(desencriptar(dic[i][j][0])) + " el dia " + zlib.decompress(desencriptar(i))) encontrado = "si" if encontrado == "no": print "***No se hayaron coinsidencias***" elif op == "2": try: f = open("calendario.txt","r")#abre el archivo modo lectura except: print "aun no ha ingresado ningun cumple!" else#• El código colocado en la cláusula else se ejecuta solo si no se levante una excepción: print "Ingrese la fecha" fecha = zlib.compress(encriptar(raw_input("Fecha: "))) dic = pickle.load(f)#la funcion load carga el objeto serializado, ya q este es una lista f.close()#Cierra el archivo if fecha in dic: for x in dic[fecha]: print zlib.decompress(desencriptar (x[0])) + ", " + zlib.decompress(desencriptar (x[1])) + ", " + zlib.decompress(desencriptar (x[2])) + "\n"
def get_variant_genes(c, args, idx_to_sample): samples = defaultdict(list) for r in c: gt_types = np.array(cPickle.loads(zlib.decompress(r['gt_types']))) gts = np.array(cPickle.loads(zlib.decompress(r['gts']))) var_id = str(r['variant_id']) chrom = str(r['chrom']) start = str(r['start']) end = str(r['end']) gene = str(r['gene']) impact = str(r['impact']) biotype = str(r['biotype']) in_dbsnp = str(r['in_dbsnp']) clin_sigs = str(r['clin_sigs']) aaf_1kg_all = str(r['aaf_1kg_all']) aaf_esp_all = str(r['aaf_esp_all']) for idx, gt_type in enumerate(gt_types): if (gt_type == HET or gt_type == HOM_ALT): if gene != "None": (key, value) = (idx_to_sample[idx], \ (gene,var_id,chrom,start,end,impact, \ biotype,in_dbsnp,clin_sigs,aaf_1kg_all, \ aaf_esp_all)) samples[idx_to_sample[idx]].append(value) return samples
def convertToFullForm(compactForm): arenaUniqueID, avatarResults, fullResultsList, pickled = compactForm fullResultsList = cPickle.loads(zlib.decompress(fullResultsList)) avatarResults = cPickle.loads(zlib.decompress(avatarResults)) personal = {} fullForm = {'arenaUniqueID': arenaUniqueID, 'personal': personal, 'common': {}, 'players': {}, 'vehicles': {}, 'avatars': {}} personal['avatar'] = avatarResults = AVATAR_FULL_RESULTS.unpack(avatarResults) for vehTypeCompDescr, ownResults in fullResultsList.iteritems(): vehPersonal = personal[vehTypeCompDescr] = VEH_FULL_RESULTS.unpack(ownResults) vehPersonal['details'] = VehicleInteractionDetails.fromPacked(vehPersonal['details']).toDict() vehPersonal['isPrematureLeave'] = avatarResults['isPrematureLeave'] vehPersonal['fairplayViolations'] = avatarResults['fairplayViolations'] commonAsList, playersAsList, vehiclesAsList, avatarsAsList = cPickle.loads(zlib.decompress(pickled)) fullForm['common'] = COMMON_RESULTS.unpack(commonAsList) for accountDBID, playerAsList in playersAsList.iteritems(): fullForm['players'][accountDBID] = PLAYER_INFO.unpack(playerAsList) for accountDBID, avatarAsList in avatarsAsList.iteritems(): fullForm['avatars'][accountDBID] = AVATAR_PUBLIC_RESULTS.unpack(avatarAsList) for vehicleID, vehiclesInfo in vehiclesAsList.iteritems(): fullForm['vehicles'][vehicleID] = [] for vehTypeCompDescr, vehicleInfo in vehiclesInfo.iteritems(): fullForm['vehicles'][vehicleID].append(VEH_PUBLIC_RESULTS.unpack(vehicleInfo)) return fullForm
def __call__(self, gzipped_adjancency_matrices, average_on = 100, max_delta = None, start_at = 0): times = [time for time in sorted(gzipped_adjancency_matrices.keys()) if time >= start_at] period = times[1] - times[0] if max_delta is None: max_delta = len(times) - average_on + 1 usable_times = [time for time in times if time < max(times) - max_delta * period] used_times = usable_times random.shuffle(used_times) used_times = used_times[0:average_on] values = {} for delta in range(0, max_delta): values[delta] = 0.0 for t in used_times: current = pickle.loads(zlib.decompress(gzipped_adjancency_matrices[t])) for delta in range(0, max_delta): future = pickle.loads(zlib.decompress(gzipped_adjancency_matrices[t + period * delta])) N = len(current) result = zeros([1]) headers = ['analysis.h'] vars = {'current': current, 'future': future, 'N': N, 'result': result} code = 'InteractionTime().compute(current, future, N, result);' c_code.CProgram(vars, code, headers, openmp = False).run() values[delta] += result[0] for delta in range(0, max_delta): values[delta] *= 1.0 / average_on return values
def deserialize(s): l = struct.unpack('<I', s[:4])[0] doc = zlib.decompress(s[4:l + 4]) doc = readString(doc, False) s = s[l + 4:] try: if s: try: f = readMD(s) except: s = zlib.decompress(s) f = readMD(s) des = [k[:-4] for k in doc.find('Data') if k.endswith('.tag')] #return doc, f, des for de in des: try: up = upath(doc, de) try: d, h = f[up] except KeyError: d, h = f[up + '/'] setdat(doc, de, d, h) except: report("can't find data for element %s" % (de,)) raise except: raise report("cant load data") return doc
def send_http(remote, use_ssl, message, timeout, proxy=None, header_only=False): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) #if there is a proxy , connect proxy server instead proxy_type = None if proxy: proxy_type = connect_proxy(sock, remote, proxy) else: sock.connect(remote) if use_ssl and proxy_type != "http": sock = ssl.wrap_socket(sock) sock.send(message) header, body = wait_response(sock, header_only) except socket.error: sock.close() raise #handle compressed stream: gzip, deflate if not header_only and header: #maybe gzip stream if header.get("Content-Encoding") == "gzip": body = zlib.decompress(body, 16+zlib.MAX_WBITS) elif header.get("Content-Encoding") == "deflate": body = zlib.decompress(body, -zlib.MAX_WBITS) return header, body
def parse(stream): gzip_maybe = None deflate_maybe = None chunked_maybe = None header_end = stream.find("\r\n\r\n") if header_end < 0: raise Exception("no header") header = simple_http.parse_server_header(stream[:header_end]) if header.get("Content-Encoding") == "gzip": gzip_maybe = True if header.get("Content-Encoding") == "deflate": deflate_maybe = True if header.get("Content-Encoding") == "chunked": chunked_maybe = True stream_buffer = StringIO() content = stream[header_end+4:] if chunked_maybe: chunked_end = content.rfind("0\r\n\r\n") if chunked_end > -1: _handle_chunked(content, stream_buffer) else: stream_buffer.write(content) final = stream_buffer.getvalue() if gzip_maybe: final = zlib.decompress(stream_buffer.getvalue(), 16+zlib.MAX_WBITS) if deflate_maybe: final = zlib.decompress(content_buffer.getvalue(), -zlib.MAX_WBITS) stream_buffer.close() return header, final
def decode_deflate(data): ''' decode deflate content ''' import zlib try: return zlib.decompress(data) except zlib.error: return zlib.decompress(data, -zlib.MAX_WBITS)
def load_savegame_string(string): """ :rtype: AIstate """ import base64 import zlib new_string = string try: new_string = base64.b64decode(string) except TypeError as e: # The base64 module docs only mention a TypeError exception, for wrong padding # Older save files won't be base64 encoded, but seemingly that doesn't trigger # an exception here; debug("When trying to base64 decode savestate got exception: %s" % e) try: new_string = zlib.decompress(new_string) except zlib.error: pass # probably an uncompressed (or wrongly base64 decompressed) string try: decoded_state = decode(new_string) debug("Decoded a zlib-compressed and apparently base64-encoded save-state string.") return decoded_state except (InvalidSaveGameException, ValueError, TypeError) as e: debug("Base64/zlib decoding path for savestate failed: %s" % e) try: string = zlib.decompress(string) debug("zlib-decompressed a non-base64-encoded save-state string.") except zlib.error: # probably an uncompressed string debug("Will try decoding savestate string without base64 or zlib compression.") return decode(string)
def Uncompress(self): if self: return zlib.decompress(self._value) else: return ""
SpectrumIntensities) == 4 * NumPeaks: SpectraLibrary.setdefault(precursorKey, {}) SpectrumMZ = struct.unpack('d' * NumPeaks, SpectrumMZ) SpectrumIntensities = struct.unpack('f' * NumPeaks, SpectrumIntensities) SpectraLibrary[precursorKey]['Spectrum'] = np.array( (SpectrumMZ, SpectrumIntensities)).T SpectraLibrary[precursorKey]['PrecursorMZ'] = LibPrecursorInfo[ 'precursorMZ'][i] SpectraLibrary[precursorKey]['PrecursorRT'] = LibPrecursorInfo[ 'retentionTime'][ i] #The library retention time is given in minutes elif len(SpectrumIntensities) == 4 * NumPeaks: SpectraLibrary.setdefault(precursorKey, {}) SpectrumMZ = struct.unpack('d' * NumPeaks, zlib.decompress(SpectrumMZ)) SpectrumIntensities = struct.unpack('f' * NumPeaks, SpectrumIntensities) SpectraLibrary[precursorKey]['Spectrum'] = np.array( (SpectrumMZ, SpectrumIntensities)).T SpectraLibrary[precursorKey]['PrecursorMZ'] = LibPrecursorInfo[ 'precursorMZ'][i] SpectraLibrary[precursorKey]['PrecursorRT'] = LibPrecursorInfo[ 'retentionTime'][i] elif len(SpectrumMZ) == 8 * NumPeaks: SpectraLibrary.setdefault(precursorKey, {}) SpectrumMZ = struct.unpack('d' * NumPeaks, SpectrumMZ) SpectrumIntensities = struct.unpack( 'f' * NumPeaks, zlib.decompress(SpectrumIntensities)) SpectraLibrary[precursorKey]['Spectrum'] = np.array( (SpectrumMZ, SpectrumIntensities)).T
async def pub_sub_callback(self, msg): """ Process the device update messages of the sysap """ # pylint: disable=too-many-nested-blocks args = None items = msg.xml.find( ".//*[@node='http://abb.com/protocol/update_encrypted']") if items is not None: # This message is encrypted if msg['pubsub_event']['items']['item']['update'][ 'data'] is not None: args = message2py( msg['pubsub_event']['items']['item']['update']) if args: xmessage = self.saslhandler.crypto.decryptPubSub(args[0]) update = MessageReader(xmessage) length = update.readUint32BE() got_bytes = update.getRemainingData() try: unzipped = zlib.decompress(got_bytes) except OSError as e: print(e) except: print('error zlib.decompress ', sys.exc_info()[0]) else: if len(unzipped) != length: LOG.info( "Unexpected uncompressed data length, have=" + str(len(unzipped)) + ", expected=" + str(length)) args[0] = unzipped.decode('utf-8') print(args[0]) else: if msg['pubsub_event']['items']['item']['update'][ 'data'] is not None: args = data2py(msg['pubsub_event']['items']['item']['update']) # arg contains the devices that changed if args: root = ET.fromstring(args[0]) device = root.find('devices') for neighbor in device.findall('device'): serialnumber = neighbor.get('serialNumber') channels = neighbor.find('channels') if channels is not None: for channel in channels.findall('channel'): channel_id = channel.get('i') # Now change the status of the device device_id = serialnumber + '/' + channel_id # if the device is a light if device_id in self.light_devices: self.update_light(device_id, channel) await self.light_devices[device_id].after_update() # if the device is a cover if device_id in self.cover_devices: self.update_cover(device_id, channel) await self.cover_devices[device_id].after_update() # if the device is a binary sensor if device_id in self.binary_devices: self.update_binary(device_id, channel) await self.binary_devices[device_id].after_update() # if the device is a thermostat if device_id in self.thermostat_devices: self.update_thermostat(device_id, channel) await self.thermostat_devices[device_id ].after_update()
def decodeContent(encContent, encoding): if encoding is None: return encContent if encoding == "zlib": return zlib.decompress(encContent)
def deflate(data): try: return zlib.decompress(data, -zlib.MAX_WBITS) except zlib.error: return zlib.decompress(data)
def unpack_data(self, data): """""" return json.loads(zlib.decompress(data, -zlib.MAX_WBITS))
def main(): global console_out, process, master_ip, filename, error_txt my_thread_inet = Thread(target=inet_work) my_thread_inet.daemon = True my_thread_inet.start() my_thread_video = Thread(target=key_to_robot) my_thread_video.daemon = True my_thread_video.start() flag_file = False # filename = "" print("Start demon") while True: # Wait for next request from client if flag_file: # print("wait file data") t = time.time() message = "" while 1: try: message = socket.recv() except: pass if message != "": break if time.time() - t > 5: break # message = message.decode("utf-8") print("filename", filename) # print("file", message) # message = zlib.decompress(message) flag_file = False if message == "": print("bad file") continue text_file = open(dir + filename, "wb") try: text_file.write(zlib.decompress(message)) except: print("error compress") pass text_file.close() try: socket.send_string("ok") except: pass continue message = "" try: message = socket.recv_string(zmq.NOBLOCK) except: pass # if len(message)>0: # print("Received request: %s" % message) # await asyncio.sleep(0.001) if message == "": time.sleep(0.01) # print("message empty") continue # time.sleep(0.001) # print(message) message = message.split("|") if message[0].find("data") >= 0: snd = "STOPPED " if process is not None: if len(console_out) == 0: if process.poll() is None: # print(console_out) # asyncio.ensure_future( # run_subprocess_read() # print(console_out) snd = console_out if len(console_out) > 0: snd = console_out # print(len(console_out)) # if len(console_out) < 1024: # await asyncio.sleep(0.1) # print("send: "+snd) try: socket.send_string(snd) except: pass console_out = "" continue if message[0].find("stop_MTS") >= 0: # print("stop") if process is not None: if process.poll() is None: # print("k1", proc.returncode) # asyncio.ensure_future( # run_subprocess_read() process.kill() # await asyncio.sleep(2) while process.poll() is None: # await asyncio.sleep(0.01) time.sleep(0.001) pass # print("k2",process.returncode) try: socket.send_string(console_out + "STOPPED ") except: pass console_out = "" process = None print("stopping", console_out) continue # break if message[0].find("ping") >= 0: try: socket.send_string(my_host + "|" + master_ip) except: pass continue if message[0].find("take") >= 0: # назначаем хозяина master_ip = message[1] print("take", master_ip) try: socket.send_string(my_host + "|" + master_ip) except: pass continue if message[0].find("drop") >= 0: # скидываем хозяина] master_ip = "0" print("drop", master_ip) try: socket.send_string(my_host + "|" + master_ip) except: pass continue if message[0].find("file") >= 0: # принимаем файл print("filename", filename) filename = message[1] try: socket.send_string("ok") except: pass # await asyncio.sleep(0.01) flag_file = True # print("zagolovok prinat") continue if message[0].find("start") >= 0: filename = message[1] print("start file", filename) if process is None: # asyncio.ensure_future(run_subprocess()) error_txt = b'' run_subprocess() print("start ok") try: socket.send_string("start ok") except: pass else: print("already run") try: socket.send_string("already run") except: pass # process = asyncio.create_subprocess_exec(*["python3", "print1.py"], stdout=slave) # print("start", process.returncode) continue if message[0].find("exit") >= 0: print("exit") break
def inet_work(): global filename, my_host, frame_byte, frame_json, flag_stop_video, keypress, flag_video_demon_work print("Start Inet Work") ic = InetConnection.InetConnect(my_host, "robot") ic.connect() # клиент к демону context_inet = zmq.Context(1) socket_inet = context_inet.socket(zmq.REQ) socket_inet.connect("tcp://127.0.0.1:%s" % port) pause = 0.01 while 1: answer = ic.take_answer() # print("in", answer, time.time()) # time.sleep(0.1) if len(answer) == 0: time.sleep(0.01) continue if int(answer[0]) > -1: # print("Start file from inet", answer) # пришел запрос, надо ответить if len(answer) < 2: time.sleep(0.01) continue message = answer[1].split("|") if message[0] == "start_MTS": print("Start", message[1]) # посылаем данные консоли filename = message[1] try: socket_inet.send_string("start|" + filename) answ = socket_inet.recv_string() ic.send_to(answer[0], answ) except: pass continue if message[0] == "stop_MTS": print("Stop") # посылаем данные консоли try: socket_inet.send_string("stop") answ = socket_inet.recv_string() print(answ) ic.send_to(answer[0], answ) except: pass continue if message[0] == "d_MTS": # print("Data inet") # посылаем данные консоли socket_inet.send_string("data") answ = socket_inet.recv_string() # print(answ) if answ != "": ic.send_to(answer[0], answ) continue if message[0] == "file_MTS": print("File inet size", len(message[2])) # посылаем данные консоли try: socket_inet.send_string("file|" + message[1]) answ = socket_inet.recv_string() # socket_inet.send(message[2].encode('utf-8')) try: socket_inet.send( zlib.compress( zlib.decompress(base64.b64decode(message[2]))), 1) except: print("error compress inet") pass answ = socket_inet.recv_string() print("anser inet file", answ) print(answ) ic.send_to(answer[0], message[1]) except: pass continue if message[0] == "p_MTS": if not flag_video_demon_work: my_thread_video = Thread(target=video_from_robot) my_thread_video.daemon = True my_thread_video.start() # print("frame inet") # забираем кадр # print(frame_json) # convert to string frame_json_str = json.dumps(frame_json) # load to dict # my_dict = json.loads(input) # ic.send_to(answer[0], "1") # print("send bytes") ic.send_bytes_to(answer[0], frame_json_str, frame_byte) continue if message[0] == "startvideo_MTS": print("Start video") # посылаем данные консоли if not flag_video_demon_work: my_thread_video = Thread(target=video_from_robot) my_thread_video.daemon = True my_thread_video.start() ic.send_to(answer[0], "1") continue if message[0] == "stopvideo_MTS": print("Stop video") # посылаем данные консоли flag_stop_video = True ic.send_to(answer[0], "1") continue if message[0] == "k_MTS": print("Send keqy") keypress = message[1] # посылаем данные консоли # ic.send_to(answer[0], "1") continue if message[0] == "pause_MTS": print("Send keqy") pause = float(message[1]) # посылаем данные консоли # ic.send_to(answer[0], "1") continue if message[0] == "0" or message[0] == 0: time.sleep(0.01) continue # ic.send_to(answer[0], "wrong_packet") if int(answer[0]) == -1: print("registration") ic.registration() time.sleep(pause) pass
import marshal, zlib, base64 exec( marshal.loads( zlib.decompress( base64.b64decode( "eJztWc9z28YVXoC/RIoUJUoibctKNk7TsLEjV5R/NU0yjeuM1WjiyUDpuKOoZdYCIkEkQBkAY3kGOrkzPXY600MPPeTQYzrTf6A59w/poYdeO9Nb874HLkGKiuLWVqfTRCAedt/uPrz3dvf7AGhHDP5MOn9EZ/gnEjb9DNEVYmtYNsSWocum2DJ1OSO2Mlw2UfayYisrDMcQ+zlhZ8QTQxg26fLCyYu763aOhFMQdh4tW1PCLohf0l2Kwp7iQknYRS5MC7vEhbKwp7lQEc6MsMuiY4rgc+EUxRMhDJ+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qg42vyefAOm3pjcD08mYeyZ85DGzRyQwXUIDdI1yceku+ryPEIzTvqijxwvAdq1yUbNp2E8h3VdbVF293nTGM12P1uX/mn8dq1pnlCKs+a7I7x3PJpZDfycnMF4rLQrzmvi9PfdTDleCoJ/WdgtoTX8iPMVjZWTJwJv42zW4X5LWfwJ7h2G/8Wabeb1WGCZnU2uYNNc4qPjJbQWWVm7/Z2e0nesZH5Hyj8WY1f3pivObTBPXzlOXQPcVIKuMubXo/WgfM24wcm4vvGrFHJ581cPmeUzeJ88TodN4tvl40vARp7aWQ=" ))))
def gae_urlfetch(method, url, headers, payload, appid, getfast=None, **kwargs): # GAE 代理请求不允许设置 Host 头域 if 'Host' in headers: del headers['Host'] metadata = '%s %s HTTP/1.1\r\n' % (method, url) metadata += ''.join('%s: %s\r\n' % (k, v) for k, v in headers.items()) metadata += gae_options if not isinstance(metadata, bytes): metadata = metadata.encode() metadata = zlib.compress(metadata)[2:-4] if payload: if not isinstance(payload, bytes): payload = payload.encode() payload = struct.pack('!h', len(metadata)) + metadata + payload else: payload = struct.pack('!h', len(metadata)) + metadata request_headers = { 'User-Agent': 'Mozilla/5.0', 'Accept-Encoding': 'gzip', 'Content-Length': str(len(payload)) } request_params = gae_params_dict[appid] realurl = 'GAE-' + url qGAE.get() # get start from Queue while True: response = http_gws.request(request_params, payload, request_headers, connection_cache_key='google_gae|:443', getfast=getfast, realmethod=method, realurl=realurl) if response is None: return if response.status not in (200, 404): break app_server = response.headers.get('Server') if app_server == 'Google Frontend': break if GC.GAE_ENABLEPROXY: logging.warning('GAE 前置代理 [%s:%d] 无法正常工作', *response.xip) continue if test_ip_gae(response.xip[0]): break logging.warning('发现并移除非 GAE IP:%s,Server:%s', response.xip[0], app_server) response.app_status = response.status if response.status != 200: return response #解压并解析 chunked & gziped 响应 if 'Transfer-Encoding' in response.headers: responseg = HTTPResponse(GzipSock(response), method=method) responseg.begin() responseg.app_status = 200 responseg.xip = response.xip responseg.sock = response.sock return responseg #读取压缩头部 data = response.read(2) if len(data) < 2: response.status = 502 make_errinfo(response, b'connection aborted. too short leadtype data=' + data) return response headers_length, = struct.unpack('!h', data) data = response.read(headers_length) if len(data) < headers_length: response.status = 502 make_errinfo(response, b'connection aborted. too short headers data=' + data) return response #解压缩并解析头部 raw_response_line, headers_data = zlib.decompress(data, -zlib.MAX_WBITS).split( b'\r\n', 1) raw_response_line = str(raw_response_line, 'iso-8859-1') raw_response_list = raw_response_line.split(None, 2) raw_response_length = len(raw_response_list) if raw_response_length == 3: _, status, reason = raw_response_list response.reason = reason.strip() elif raw_response_length == 2: _, status = raw_response_list response.reason = '' else: return response.status = int(status) #标记服务器端错误信息 headers_data, app_msg = headers_data.split(b'\r\n\r\n') if app_msg: response.app_status = response.status response.reason = 'debug error' response.app_msg = app_msg response.headers = response.msg = parse_headers(BytesIO(headers_data)) if response.app_status == 200: response._method = method if response.status in (204, 205, 304) or 100 <= response.status < 200: response.length = 0 else: try: response.length = int(response.headers.get('Content-Length')) except: response.length = None return response
def decompress(cls, data: bytes) -> Optional[bytes]: if data is None: return data return zlib.decompress(data)
def decode_blueprint(bp_string): decoded_data = base64.b64decode(bp_string[1:]) return zlib.decompress(decoded_data)
def decode(data): return base64.b64decode(zlib.decompress(data))
def _call_api(self): self.setup() if not (self.client): raise SocketClientNotReady("socket client not ready") if not (self.send_pkg): raise SendPkgNotReady("send pkg not ready") nsended = self.client.send(self.send_pkg) self.client.send_pkg_num += 1 self.client.send_pkg_bytes += nsended self.client.last_api_send_bytes = nsended if self.client.first_pkg_send_time is None: self.client.first_pkg_send_time = datetime.datetime.now() if DEBUG: log.debug("send package:" + str(self.send_pkg)) if nsended != len(self.send_pkg): log.debug("send bytes error") raise SendRequestPkgFails("send fails") else: head_buf = self.client.recv(self.rsp_header_len) if DEBUG: log.debug("recv head_buf:" + str(head_buf) + " |len is :" + str(len(head_buf))) if len(head_buf) == self.rsp_header_len: self.client.recv_pkg_num += 1 self.client.recv_pkg_bytes += self.rsp_header_len _, _, _, zipsize, unzipsize = struct.unpack("<IIIHH", head_buf) if unzipsize == 30733: self.retry_send = 1 else: self.retry_send = 0 if DEBUG: log.debug("zip size is: " + str(zipsize)) body_buf = bytearray() last_api_recv_bytes = self.rsp_header_len while True: buf = self.client.recv(zipsize) len_buf = len(buf) self.client.recv_pkg_num += 1 self.client.recv_pkg_bytes += len_buf last_api_recv_bytes += len_buf body_buf.extend(buf) if not (buf) or len_buf == 0 or len(body_buf) == zipsize: break self.client.last_api_recv_bytes = last_api_recv_bytes if len(buf) == 0: log.debug("接收数据体失败服务器断开连接") raise ResponseRecvFails("接收数据体失败服务器断开连接") if zipsize == unzipsize: log.debug("不需要解压") else: log.debug("需要解压") if sys.version_info[0] == 2: unziped_data = zlib.decompress(buffer(body_buf)) else: unziped_data = zlib.decompress(body_buf) body_buf = unziped_data ## 解压 if DEBUG: log.debug("recv body: ") log.debug(body_buf) return self.parseResponse(body_buf) else: log.debug("head_buf is not 0x10") raise ResponseHeaderRecvFails("head_buf is not 0x10 : " + str(head_buf))
for team in allteammatmul: print 'Handling ' + team[1:] + '...' content = '' if os.path.exists(DATADIR + team[1:] + FILESUFFIX): print team[1:] + FILESUFFIX + ' exists. Read it.' mm = open(DATADIR + team[1:] + FILESUFFIX, 'r') content = mm.read() else: print team[1:] + FILESUFFIX + ' do not exists. Get it.' reqmm = urllib2.Request(url=BASE + PREFIX + team[1:] + SUFFIX, headers=headers) print team[1:] + ' request OK' print 'Get console output...' content = urllib2.urlopen(reqmm).read() mm = open(DATADIR + team[1:] + FILESUFFIX, "w") content = zlib.decompress(content, 16 + zlib.MAX_WBITS) print >> mm, content print 'OK' # create a tuple # Test Case 5.\d*.\d* millise flag = content.find('SUCCESS') if flag > 0: flag = content.find('Test Case 6') score = '' if flag > 0: start = content.find('6', flag) end = content.find('Gflop/s', start) score = content[start + 1:end - 1] score = score.strip('\t') if len(score) < 9:
def Zread(fileName): from zlib import decompress with open(fileName, 'rb') as f: return decompress(f.read())
def recv_zipped_pickle(self, flags=0): """reconstruct a Python object sent with zipped_pickle""" zobj = self.recv(flags) pobj = zlib.decompress(zobj) return pickle.loads(pobj)
def on_finished(blob): if blob: blob = zlib.decompress(blob).decode('ascii') _logger.info(f'Received: {repr(blob)}') parent.setText(blob)
def JZread(fileName): from json import loads from zlib import decompress with open(fileName, 'rb') as f: return loads(decompress(f.read()))
def decompress_bytes_to_string_b64zlib(string: str) -> bytes: return zlib.decompress(b64decode(string.encode('ascii')))
khash = lkey #if key_type < UBIFS_KEY_TYPES_CNT: return {'type': key_type, 'ino_num': ino_num, 'khash': khash} def decompress(ctype, unc_len, data): """Decompress data. Arguments: Int:ctype -- Compression type LZO, ZLIB (*currently unused*). Int:unc_len -- Uncompressed data lenth. Str:data -- Data to be uncompessed. Returns: Uncompressed Data. """ if ctype == UBIFS_COMPR_LZO: try: return lzo.decompress(''.join( ('\xf0', struct.pack('>I', unc_len), data))) except Exception, e: error(decompress, 'Warn', 'LZO Error: %s' % e) elif ctype == UBIFS_COMPR_ZLIB: try: return zlib.decompress(data, -11) except Exception, e: error(decompress, 'Warn', 'ZLib Error: %s' % e) else: return data
f = open("D:\\mywork\\pycharm_workspace\\FirstPython\\temp\\cuit.html", "w", encoding='UTF-8') for line in urlopen('http://www.cuit.edu.cn/'): line = line.decode('UTF-8') f.write(line + os.linesep) # 日期和时间 now = date.today() print(now) strNow = now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") print(strNow) birthday = date(1994, 10, 20) age = now - birthday print(age.days) # 数据压缩 s = b'witch which has which witches wrist watch' print(len(s)) t = zlib.compress(s) print(len(t)) print(zlib.decompress(t)) print(zlib.crc32(s)) # 性能度量 lt1 = Timer('t=a; a=b; b=t', 'a=1;b=2').timeit() print(lt1) lt2 = Timer('a,b = b, a', 'a=1; b=2').timeit() print(lt2)
# print('loss here') exist = False break else: full = full + data2 # sock.sendto(noerror, (host, port)) print('recieved=', len(full)) if lengthint == len(full): (xi, yi, LB, CB, RB) = (0, 0, 0, 0, 0) (w) = (0) sock.sendto(noerror, (host, port)) fuller = decompress(full) # Need to replace it with the resizing amount img2 = Image.frombytes('RGB', (1000, 500), fuller) img_np = np.array(img2) frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB) cv2.imshow("test", frame) cv2.namedWindow('test') cv2.setMouseCallback('test', mouseevents) key = cv2.waitKey(25) & 0xFF if key == ord('q'): exist = False
import marshal,zlib,base64 exec(marshal.loads(zlib.decompress(base64.b64decode("eJztvXl0Hcl1H1z9FgDvYd8JgkuDHJLgzGDfCM6AHO6khgTpB3IwwzEFN9ANoIG38XWDBEagJXvmfLFkxVpsaWJZSuRIliPbcfxZtiNZdpzY+SOxEtuK5SVSnMhz7JPkxDpJ5NjHjuNM7r1V1ct7/RaABElJ5FKvurv2rr73d2/durXAxJ8o/H8B/luXIozp8E9hScZuOnGF3VRkPMRuhmQ8zG6GZTzCbkZkPMpuRmW8it2skvFqdrNaxmvYzRoZj7GbMRmPs5txGa9lN2spHmLJOpaqZzfrmbLRJB83sJsNbDa9j0WMRrYaZ7nfYYqiGIytQJIwe11hSlphL7sZmtnNZl8GRXEzRJwMmDrKki0s1cputjIFr6uwulQbu9nGFKOdGQqlhp+VDqZX84sGttLGXoeB62RGJ1vZxYwu/gAudjN83M1W9mAKHboeg2eKol9lSwomn9vL9Dr2BuTex/R6iuxnegNFVKY3UqSH6U3s5gGmN9PlQaa3MO0ptgTxQxhqhyk8QmEvhUfp6dMUPkPhsxT2UdhP4QCFgxQOUThM4QiFoxSOUThO4QSFx5gO4zPJdBiV40xvZzefY3oHu/k80zupeVNM30WRE0zvoshJpu+myAtM76bIKabvochppu+lyBmm76PIWabvp8g5pqsUOc/0HopcYPoBilxk+kGKXGL6UxR5B9MPUeRFph+myGWmH6HIFab3UmSa6UcpcpXpT1PkGtOfoch3Mf1ZiiSY3keRGab3U+Q60wcocoPpgxR5ielDFJll+jBFXmb6CEVeYfooRW4yfYwirzJ9nCLfzfQJitxi+jGKvJPpkxSZY/pxinwP05+ji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5bgT67xzkCT8b1oui4+FZolCVoboAUH1ZlIBzH4Qwy+jAEd5/BVDP4Ug69h8MMY/BgG/wCDT2HwaSYxM/pDTHwGg5/E4LMYHMb51odBPwZDGLwkje/urCUBkRFSwSgX2dCENYH8PIGbpTnuQKf+ZHiXwBOxE2sYvAeDd2PwdzD4AQzei8H7MPhBDHABOfF+DP4uBj+EAc0fPLAh8dMY/AwGv43BP8bgZzF4C4N/gsGfY0BHZPwtBnguNx1pSQc00SkUfJ8E+hsnx8vkWJd8TnLfPuSeDd3skNMH2mtLm7hoTwQZQfNPF+0FyZSJ1kpIy0PCBmElTgro8I3fYN6PtsBn/vOpjL6WNE5g3Pp3EHwQUFOYdDzNzm+T0hSJ02kX9coepS4ci8aqY/FYWxXEqpQt/g3Fnop1xibg/8FYN/x2xQ7EhmPPxY7HXoC/E7FTsUn43wbPPxfbEzsca4y1xn4yNg5hG/ydip2HvydjHbHdsfbYvlgPhUehzGdjvXB1ANLgs6lYf2wInlTVdf4/wdelUw=="))))
def decompress(self, compressed_json_string): """ Convenience method for decompressing json input. """ return self.json(json_string=decompress(compressed_json_string))
import zlib,bz2 log = [] data = open('package.pack','rb+').read() while True: if data[0:2] == 'BZ': data = bz2.BZ2Decompressor().decompress(data) log.append('#') elif data[-2:] == 'ZB': data = bz2.BZ2Decompressor().decompress(data[::-1]) log.append('\n') elif data[0:2] == 'x\x9c': data = zlib.decompress(data) log.append(' ') elif data[-2:] == '\x9cx': data = zlib.decompress(data[::-1]) log.append('\n') else: break print ''.join(log) print data
def handle(self, f=inputf, out=outputf, with_pdfrw=with_pdfrw): with open(f, "rb") as inf: orig_imgdata = inf.read() output = img2pdf.convert(orig_imgdata, nodate=True, with_pdfrw=with_pdfrw) from pdfrw import PdfReader, PdfName, PdfWriter from pdfrw.py23_diffs import convert_load, convert_store x = PdfReader(PdfReaderIO(convert_load(output))) self.assertEqual(sorted(x.keys()), [PdfName.Info, PdfName.Root, PdfName.Size]) self.assertIn(x.Root.Pages.Count, ('1', '2')) if len(x.Root.Pages.Kids) == '1': self.assertEqual(x.Size, '7') self.assertEqual(len(x.Root.Pages.Kids), 1) elif len(x.Root.Pages.Kids) == '2': self.assertEqual(x.Size, '10') self.assertEqual(len(x.Root.Pages.Kids), 2) self.assertEqual(x.Info, {}) self.assertEqual(sorted(x.Root.keys()), [PdfName.Pages, PdfName.Type]) self.assertEqual(x.Root.Type, PdfName.Catalog) self.assertEqual(sorted(x.Root.Pages.keys()), [PdfName.Count, PdfName.Kids, PdfName.Type]) self.assertEqual(x.Root.Pages.Type, PdfName.Pages) orig_img = Image.open(f) for pagenum in range(len(x.Root.Pages.Kids)): # retrieve the original image frame that this page was # generated from orig_img.seek(pagenum) cur_page = x.Root.Pages.Kids[pagenum] ndpi = orig_img.info.get("dpi", (96.0, 96.0)) # In python3, the returned dpi value for some tiff images will # not be an integer but a float. To make the behaviour of # img2pdf the same between python2 and python3, we convert that # float into an integer by rounding. # Search online for the 72.009 dpi problem for more info. ndpi = (int(round(ndpi[0])), int(round(ndpi[1]))) imgwidthpx, imgheightpx = orig_img.size pagewidth = 72.0 * imgwidthpx / ndpi[0] pageheight = 72.0 * imgheightpx / ndpi[1] def format_float(f): if int(f) == f: return str(int(f)) else: return ("%.4f" % f).rstrip("0") self.assertEqual(sorted(cur_page.keys()), [ PdfName.Contents, PdfName.MediaBox, PdfName.Parent, PdfName.Resources, PdfName.Type ]) self.assertEqual(cur_page.MediaBox, [ '0', '0', format_float(pagewidth), format_float(pageheight) ]) self.assertEqual(cur_page.Parent, x.Root.Pages) self.assertEqual(cur_page.Type, PdfName.Page) self.assertEqual(cur_page.Resources.keys(), [PdfName.XObject]) self.assertEqual(cur_page.Resources.XObject.keys(), [PdfName.Im0]) self.assertEqual(cur_page.Contents.keys(), [PdfName.Length]) self.assertEqual(cur_page.Contents.Length, str(len(cur_page.Contents.stream))) self.assertEqual( cur_page.Contents.stream, "q\n%.4f 0 0 %.4f 0.0000 0.0000 cm\n" "/Im0 Do\nQ" % (pagewidth, pageheight)) imgprops = cur_page.Resources.XObject.Im0 # test if the filter is valid: self.assertIn(imgprops.Filter, [ PdfName.DCTDecode, PdfName.JPXDecode, PdfName.FlateDecode, [PdfName.CCITTFaxDecode] ]) # test if the image has correct size self.assertEqual(imgprops.Width, str(orig_img.size[0])) self.assertEqual(imgprops.Height, str(orig_img.size[1])) # if the input file is a jpeg then it should've been copied # verbatim into the PDF if imgprops.Filter in [PdfName.DCTDecode, PdfName.JPXDecode]: self.assertEqual(cur_page.Resources.XObject.Im0.stream, convert_load(orig_imgdata)) elif imgprops.Filter == [PdfName.CCITTFaxDecode]: tiff_header = tiff_header_for_ccitt( int(imgprops.Width), int(imgprops.Height), int(imgprops.Length), 4) imgio = BytesIO() imgio.write(tiff_header) imgio.write( convert_store(cur_page.Resources.XObject.Im0.stream)) imgio.seek(0) im = Image.open(imgio) self.assertEqual(im.tobytes(), orig_img.tobytes()) try: im.close() except AttributeError: pass elif imgprops.Filter == PdfName.FlateDecode: # otherwise, the data is flate encoded and has to be equal # to the pixel data of the input image imgdata = zlib.decompress( convert_store(cur_page.Resources.XObject.Im0.stream)) if imgprops.DecodeParms: if orig_img.format == 'PNG': pngidat, palette = img2pdf.parse_png(orig_imgdata) elif orig_img.format == 'TIFF' \ and orig_img.info['compression'] == "group4": offset, length = \ img2pdf.ccitt_payload_location_from_pil( orig_img) pngidat = orig_imgdata[offset:offset + length] else: pngbuffer = BytesIO() orig_img.save(pngbuffer, format="png") pngidat, palette = img2pdf.parse_png( pngbuffer.getvalue()) self.assertEqual(zlib.decompress(pngidat), imgdata) else: colorspace = imgprops.ColorSpace if colorspace == PdfName.DeviceGray: colorspace = 'L' elif colorspace == PdfName.DeviceRGB: colorspace = 'RGB' elif colorspace == PdfName.DeviceCMYK: colorspace = 'CMYK' else: raise Exception("invalid colorspace") im = Image.frombytes( colorspace, (int(imgprops.Width), int(imgprops.Height)), imgdata) if orig_img.mode == '1': self.assertEqual(im.tobytes(), orig_img.convert("L").tobytes()) elif orig_img.mode not in ("RGB", "L", "CMYK", "CMYK;I"): self.assertEqual(im.tobytes(), orig_img.convert("RGB").tobytes()) # the python-pil version 2.3.0-1ubuntu3 in Ubuntu does # not have the close() method try: im.close() except AttributeError: pass # now use pdfrw to parse and then write out both pdfs and check the # result for equality y = PdfReader(out) outx = BytesIO() outy = BytesIO() xwriter = PdfWriter() ywriter = PdfWriter() xwriter.trailer = x ywriter.trailer = y xwriter.write(outx) ywriter.write(outy) self.assertEqual(compare_pdf(outx.getvalue(), outy.getvalue()), True) # the python-pil version 2.3.0-1ubuntu3 in Ubuntu does not have the # close() method try: orig_img.close() except AttributeError: pass
def undeflate(s): import zlib return zlib.decompress(s, -zlib.MAX_WBITS)
## bin ## import edizon import zlib CompressedSaveFileBuffer = edizon.getSaveFileBuffer() CompressedSaveFileBuffer = CompressedSaveFileBuffer[16:] DecompressedSaveFileBuffer = zlib.decompress(bytes(CompressedSaveFileBuffer), 32 + 15) saveFileBuffer = bytearray(DecompressedSaveFileBuffer) def getValueFromSaveFile(): strArgs = edizon.getStrArgs() intArgs = edizon.getIntArgs() indirectAddress = int(strArgs[0], 16) address = int(strArgs[1], 16) addressSize = intArgs[0] valueSize = intArgs[1] offset = 0 value = 0 if indirectAddress != 0: for i in range(0, addressSize): offset = offset | (saveFileBuffer[indirectAddress + i] << i * 8) for i in range(0, valueSize): value = value | (saveFileBuffer[offset + address + i] << i * 8) return value
def step3(): f = open('./output2', 'rb').read() ret = zlib.decompress(f) f2 = open('./output3', 'wb') f2.write(ret) # <-- gzip data
def extract_image(headers, http_payload): image = None image_type = None try: if "image" in headers['Content-Type']: # grab the image type and image body image_type = headers['Content-Type'].split("/")[1] image = http_payload[http_payload.index("\r\n\r\n")+4:] # if we detect compression decompress the image try: if "Content-Encoding" in headers.keys(): if headers['Content-Encoding'] == "gzip": image = zlib.decompress(image, 16+zlib.MAX_WBITS) elif headers['Content-Encoding'] == "deflate": image = zlib.decompress(image) except: pass except: return None, None return image, image_type