当前位置: 首页>>代码示例>>Python>>正文


Python zlib.adler32函数代码示例

本文整理汇总了Python中zlib.adler32函数的典型用法代码示例。如果您正苦于以下问题:Python adler32函数的具体用法?Python adler32怎么用?Python adler32使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了adler32函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: sync_status

def sync_status(req):
    if not req.user:
        return HttpResponse(status=403)

    stats = db.stats.find_one()
    syncHash = 1  # Just used to refresh the dashboard page, until I get on the Angular bandwagon.
    conns = User.GetConnectionRecordsByUser(req.user)
    errorCodes = []
    for conn in conns:
        syncHash = zlib.adler32(bytes(conn.HasExtendedAuthorizationDetails()), syncHash)
        if not hasattr(conn, "SyncErrors"):
            continue
        for err in conn.SyncErrors:
            syncHash = zlib.adler32(bytes(str(err), "UTF-8"), syncHash)
            if "Code" in err and err["Code"] is not None and len(err["Code"]) > 0:
                errorCodes.append(err["Code"])
            else:
                errorCodes.append("SYS-" + err["Step"])

    sync_status_dict = {"NextSync": (req.user["NextSynchronization"].ctime() + " UTC") if "NextSynchronization" in req.user and req.user["NextSynchronization"] is not None else None,
                        "LastSync": (req.user["LastSynchronization"].ctime() + " UTC") if "LastSynchronization" in req.user and req.user["LastSynchronization"] is not None else None,
                        "Synchronizing": "SynchronizationWorker" in req.user,
                        "SynchronizationProgress": req.user["SynchronizationProgress"] if "SynchronizationProgress" in req.user else None,
                        "SynchronizationStep": req.user["SynchronizationStep"] if "SynchronizationStep" in req.user else None,
                        "SynchronizationWaitTime": None, # I wish.
                        "Errors": errorCodes,
                        "Hash": syncHash}

    if stats and "QueueHeadTime" in stats:
        sync_status_dict["SynchronizationWaitTime"] = (stats["QueueHeadTime"] - (datetime.utcnow() - req.user["NextSynchronization"]).total_seconds()) if "NextSynchronization" in req.user and req.user["NextSynchronization"] is not None else None

    return HttpResponse(json.dumps(sync_status_dict), mimetype="application/json")
开发者ID:dyung,项目名称:tapiriik,代码行数:32,代码来源:sync.py

示例2: get_ea

    def get_ea(self, url):
        """ Download exit nodes, check if there are changes """

        print "Pulling current TOR exit nodes..."

        try:
            response = urllib2.urlopen(url)
        except urllib2.HTTPError:
            print "TORcheck unavailable"
            exit(1)
        except Exception as e:
            print "Exception: %s" % e
            exit(1)

        self.ea_list = response.read()
        response.close()

        ea_file_adler32 = 0
        if os.path.exists(self.conf["ea_file"]):
            try:
                with open(self.conf["ea_file"], "r") as f:
                    ea_file_adler32 = adler32(f.read())
            except Exception as e:
                print "Exception: %s" % e
                exit(1)

        if ea_file_adler32 == adler32(self.ea_list):
            print "Exit address list not changed, exiting"
            exit(0)

        print "TOR exit node list downloaded"
开发者ID:RealEnder,项目名称:cisco-tor-block,代码行数:31,代码来源:cisco-tor-block.py

示例3: __serialize_errors

 def __serialize_errors(self, resp):
     """reformat the error structure and add the error codes"""
     if not resp.get('errors'):
         return resp
     elif resp['errors'].get('global_error'):
         ge_message = resp['errors'].pop('global_error')
         resp['errors']['global_error'] = {
             'code': adler32(ge_message.encode('UTF-16')),
             'message': ge_message
         }
         return resp
     else:
         # compose field errors
         field_errors = {}
         for field in resp['errors']:
             field_errors[field] = {
                 'code': adler32(resp['errors'][field].encode('UTF-16')),
                 'message': resp['errors'][field]
             }
         resp['errors'] = {
             'fields': field_errors
         }
         # compose global_error
         if resp['errors'].get('global_error'):
             ge_message = resp['errors']['global_error']
             resp['errors']['global_error'] = {
                 'code': adler32(ge_message.encode('UTF-16')),
                 'message': ge_message
             }
         else:
             resp['errors']['global_error'] = {
                 'code': adler32(VALIDATION_ERROR_MESSAGE.encode('UTF-16')),
                 'message': VALIDATION_ERROR_MESSAGE
             }
         return resp
开发者ID:trydirect,项目名称:flask-formula,代码行数:35,代码来源:controllers.py

示例4: UnpackState

def UnpackState(packed_state):
  """Convert a packed State binary string into a StateStruct object. If the
  input doesn't have the STATE_MARK_ZIP prefix, it is assumed to be an old-style
  compressed state object, and is directly decompressed.

  Args:
    packed_state - Binary string of the type produces by PackState.

  Returns:
    Populated StateStruct object.
  """
  if not packed_state:
    return None

  if ord(packed_state[0]) == STATE_MARK_ZIP:
    # Extract the meta-data Struct from the packed data.
    meta = StateMeta()
    meta.Deserialize(packed_state)

    # Extract the compressed State from the packed data.
    compressed_state = packed_state[meta.Size():]

    # Compute the checksum and make sure it matches the metadata.
    cksum = zlib.adler32(compressed_state)
    if cksum != meta.checksum:
      raise ValueError('Compressed State Checksum Error')

    # Return the decompressed State.
    return pickle.loads(zlib.decompress(compressed_state))

  elif ord(packed_state[0]) == STATE_MARK_SNAPPY:
    # Extract the meta-data Struct from the packed data.
    meta = StateMeta()
    meta.Deserialize(packed_state)

    # Extract the compressed State from the packed data.
    compressed_state = packed_state[meta.Size():]

    # Compute the checksum and make sure it matches the metadata.
    cksum = zlib.adler32(compressed_state)
    if cksum != meta.checksum:
      raise ValueError('Compressed State Checksum Error')

    # Return the decompressed State.
    return pickle.loads(snappy.decompress(compressed_state))

  elif ord(packed_state[0]) == STATE_MARK_LIGHT:
    # Extract the meta-data Struct from the packed data.
    meta = StateMeta()
    meta.Deserialize(packed_state)

    # Extract the State buffer from the packed data.
    state_buffer = packed_state[meta.Size():]

    # Return the decompressed State.
    return pickle.load(state_buffer)

  else:
    # Unsupported format.
    raise ValueError('Unrecognized State serialization format')
开发者ID:dgouldin,项目名称:taba,代码行数:60,代码来源:taba_state.py

示例5: __init__

	def __init__(self,x,y,terrain,ptype,feature,owner,area,visible,values,hints,scale):
		Plot.__init__(self,x,y,visible,terrain,owner);

		self.ptype = ptype
		self.feature = feature
		self.area = area
		self.values = values
		self.hints = hints

		if (self.owner!=-1):
			color_owner = pg.Color("#FF00FF")
			color_owner.hsva = ( zlib.adler32("%08d"%self.owner) % 360, 100, 100, 100 )
		else:
			color_owner = None

		color_area = pg.Color("#FF00FF")
		color_area.hsva = ( zlib.adler32("%08d"%self.area) % 360, 100, 100, 100 )

		self.color_values = [color_owner,color_area]

		assert( len(self.values)==len(scale) )
		gray = [int(255.*v/s) for v,s in zip(self.values,scale)]
		for g in gray:
			if g<0:
				if self.values[0]<0:
					self.color_values.append( pg.Color(128,0,128) ) #blocked
				else:
					self.color_values.append( pg.Color(-g,0,0) )
			else:
				self.color_values.append( pg.Color(0,+g,0) )
开发者ID:localdisk51,项目名称:Community-Patch-DLL,代码行数:30,代码来源:citysites.py

示例6: test_crc32_adler32_unsigned

 def test_crc32_adler32_unsigned(self):
     foo = 'abcdefghijklmnop'
     # explicitly test signed behavior
     self.assertEqual(zlib.crc32(foo), 2486878355)
     self.assertEqual(zlib.crc32('spam'), 1138425661)
     self.assertEqual(zlib.adler32(foo+foo), 3573550353)
     self.assertEqual(zlib.adler32('spam'), 72286642)
开发者ID:LinkedModernismProject,项目名称:web_code,代码行数:7,代码来源:test_zlib.py

示例7: test_abcdefghijklmnop

 def test_abcdefghijklmnop(self):
     """test issue1202 compliance: signed crc32, adler32 in 2.x"""
     foo = 'abcdefghijklmnop'
     # explicitly test signed behavior
     self.assertEqual(zlib.crc32(foo), -1808088941)
     self.assertEqual(zlib.crc32('spam'), 1138425661)
     self.assertEqual(zlib.adler32(foo+foo), -721416943)
     self.assertEqual(zlib.adler32('spam'), 72286642)
开发者ID:DecipherOne,项目名称:Troglodyte,代码行数:8,代码来源:test_zlib.py

示例8: test_penguins

    def test_penguins(self):
        ##self.assertEqual32(zlib.crc32("penguin", 0), 0x0e5c1a120L)
        self.assertEqual32(zlib.crc32("penguin", 1), 0x43b6aa94)
        ##self.assertEqual32(zlib.adler32("penguin", 0), 0x0bcf02f6)
        self.assertEqual32(zlib.adler32("penguin", 1), 0x0bd602f7)

        ##self.assertEqual(zlib.crc32("penguin"), zlib.crc32("penguin", 0))
        self.assertEqual(zlib.adler32("penguin"),zlib.adler32("penguin",1))
开发者ID:BackupTheBerlios,项目名称:etpe-svn,代码行数:8,代码来源:test_zlib.py

示例9: get_in_rcaches

 def get_in_rcaches(self, s1, s2):
     try:
         return self.__rcaches[ self.ctype ][ zlib.adler32( s1 + s2 ) ]
     except KeyError:
         try:
             return self.__rcaches[ self.ctype ][ zlib.adler32( s2 + s1 ) ]
         except KeyError:
             return -1, -1
开发者ID:appknox,项目名称:androguard,代码行数:8,代码来源:similarity.py

示例10: copy

def copy(original, destination, purge=settings.PURGE_OLD_FILES, replace_files=True):
    """
    Do the file copying with all the appropriate error checking. Don't replace 
    an existing file if ``replace_files`` is ``False``
    
    :param original:
        The path to the original file/directory
    :type original: 
        ``string``
    :param destination: 
        The path to the destination file/directory
    :type destination: 
        ``string``
    :param purge:
        Should directories be emptied before copying. **Default:** ``settings.PURGE_OLD_FILES``
    :type purge:
        ``bool``
    :param replace_files:
        Should existing files be over-written (``True``) or kept (``False``). 
        Whole directories will *not* be over-written. Each file within a directory
        will be evaluated. **Default:** ``True``
    :type replace_files:
        ``bool``
    """
    if not os.path.exists(original):
        print "Can't access %s or it doesn't exist." % original
        return
    
    if os.path.basename(original) and os.path.basename(original)[0] == '.':
        print "Skipping the hidden item " % original
        return
    
    # If original is a file, copy it over
    if os.path.isfile(original):
        if os.path.isdir(destination):
            dst_file = os.path.join(destination, os.path.basename(original))
        else:
            dst_file = destination
        if os.path.exists(dst_file) and replace_files:
            src_chksum = zlib.adler32(open(original, 'rb').read())
            dst_chksum = zlib.adler32(open(dst_file, 'rb').read())
            if src_chksum != dst_chksum:
                print "Replacing %s" % dst_file
                shutil.copy2(original, dst_file)
    
    # if original is a directory, check for an existing directory
    # Empty it out if configured
    if os.path.isdir(original):
        if os.path.exists(destination) and purge:
            print "Purging %s" % destination
            shutil.rmtree(destination)
            os.makedirs(destination)
        elif os.path.exists(destination) and not os.path.isdir(destination):
            print "The destination (%s) for directory %s is a file instead of a directory." % (destination, original)
            return
        elif not os.path.exists(destination):
            os.makedirs(destination)
        copydir(original, destination, replace_files)
开发者ID:alekam,项目名称:django-staticmediamgr,代码行数:58,代码来源:utils.py

示例11: test_penguins

    def test_penguins(self):
        self.assertEqual32(zlib.crc32("penguin", 0), 0x0e5c1a120L)
        self.assertEqual32(zlib.crc32("penguin", 1), 0x43b6aa94)
        if not test_support.is_jython:
            self.assertEqual32(zlib.adler32("penguin", 0), 0x0bcf02f6)
        self.assertEqual32(zlib.adler32("penguin", 1), 0x0bd602f7)

        self.assertEqual(zlib.crc32("penguin"), zlib.crc32("penguin", 0))
        self.assertEqual(zlib.adler32("penguin"),zlib.adler32("penguin",1))
开发者ID:babble,项目名称:babble,代码行数:9,代码来源:test_zlib.py

示例12: checksumfile

def checksumfile(fs, path):
    """Compute adler32 checksum of file."""
    value = zlib.adler32("")

    with fs.open(path, "rb") as f:
        for data in f:
            value = zlib.adler32(data, value)

    return value
开发者ID:lnielsen,项目名称:filededupe,代码行数:9,代码来源:filededupe.py

示例13: hashkey_fast

def hashkey_fast(obj, salt=0):
    """Optimized version of :py:func:`~.hashkey`"""
    if obj.__class__ in hashkey_fast.types:
        if obj.__class__ is str:
            return zlib.adler32(obj.encode(), salt) & 0xffffffff
        elif obj.__class__ is bytes:
            return zlib.adler32(obj, salt) & 0xffffffff
        # must be datetime_type
        else:
            return zlib.adler32(str(obj).encode(), salt) & 0xffffffff
    return hash(obj) & 0xffffffff
开发者ID:maxfischer2781,项目名称:pysistency,代码行数:11,代码来源:keys.py

示例14: checksum

 def checksum(self, include_metas=True):
     # TODO: zlib.adler32 does not work for numpy arrays with dtype object
     # (after pickling and unpickling such arrays, checksum changes)
     # Why, and should we fix it or remove it?
     """Return a checksum over X, Y, metas and W."""
     cs = zlib.adler32(self.X)
     cs = zlib.adler32(self.Y, cs)
     if include_metas:
         cs = zlib.adler32(self.metas, cs)
     cs = zlib.adler32(self.W, cs)
     return cs
开发者ID:Isilendil,项目名称:orange3,代码行数:11,代码来源:table.py

示例15: read

	def read(self):
		self._ini.read(config_file)

		if self.conn_mode == Config.CONN_MODE_LOGIN:
			ah = '%08X' % (zlib.adler32((((((((((('')))))))))).encode()) & 0xFFFFFFFF)
		else:
			ah = '%08X' % (zlib.adler32(self.cert_file_content.encode()) & 0xFFFFFFFF)

		if self.get('AMI', 'hash') != ah:

			self.set('AMI', 'jsid', '')
			self.set('AMI', 'hash', ah)
开发者ID:ami-lpsc,项目名称:pyAMICore,代码行数:12,代码来源:config.py


注:本文中的zlib.adler32函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。