本文整理汇总了Python中zlib.adler32函数的典型用法代码示例。如果您正苦于以下问题:Python adler32函数的具体用法?Python adler32怎么用?Python adler32使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了adler32函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: add_module
def add_module(self, ref, text, format=None,
expect_modulename=None, expect_revision=None,
expect_failure_error=True):
"""Parse a module text and add the module data to the context
`ref` is a string which is used to identify the source of
the text for the user. used in error messages
`text` is the raw text data
`format` is one of 'yang' or 'yin'.
Returns the parsed and validated module on success, and None on error.
"""
if format == None:
format = util.guess_format(text)
if format == 'yin':
p = yin_parser.YinParser()
else:
p = yang_parser.YangParser()
module = p.parse(self, ref, text)
if module is None:
return None
if expect_modulename is not None and expect_modulename != module.arg:
if expect_failure_error:
error.err_add(self.errors, module.pos, 'BAD_MODULE_NAME',
(module.arg, ref, expect_modulename))
return None
else:
error.err_add(self.errors, module.pos, 'WBAD_MODULE_NAME',
(module.arg, ref, expect_modulename))
latest_rev = util.get_latest_revision(module)
if expect_revision is not None:
if expect_revision != latest_rev:
if expect_failure_error:
error.err_add(self.errors, module.pos, 'BAD_REVISION',
(latest_rev, ref, expect_revision))
return None
else:
error.err_add(self.errors, module.pos, 'WBAD_REVISION',
(latest_rev, ref, expect_revision))
if module.arg not in self.revs:
self.revs[module.arg] = []
revs = self.revs[module.arg]
revs.append((latest_rev, None))
if sys.version < '3':
module.i_adler32 = zlib.adler32(text)
else:
module.i_adler32 = zlib.adler32(text.encode('UTF-8'))
return self.add_parsed_module(module)
开发者ID:rchuppala,项目名称:usc_agent,代码行数:53,代码来源:__init__.py
示例17: calc_hash
def calc_hash(self):
if self.list_choice == "File":
if os.path.isfile(self.filename):
# read() from file as bytes
txt = open(self.filename, 'rb').read()
else:
# No such file, warning
self.filename = ''
messagebox.showinfo('Error', 'File not found !\n' + self.entry.get())
return
elif self.list_choice == "Text":
txt = self.entry.get().encode()
self.enable_entry()
self.clear_fields()
print(self.list_choice)
# algorithms_guaranteed
self.entryMd5.insert(0, hlb.md5(txt).hexdigest())
self.entrySha1.insert(0, hlb.sha1(txt).hexdigest())
self.entrySha224.insert(0, hlb.sha224(txt).hexdigest())
self.entrySha256.insert(0, hlb.sha256(txt).hexdigest())
self.entrySha384.insert(0, hlb.sha384(txt).hexdigest())
self.entrySha512.insert(0, hlb.sha512(txt).hexdigest())
# algorithms_not_guaranteed
# Collisions might occur
# Using the same object initialized in __init__ method results in unsecured hashes.
# So initialize objects each time
self.init_insecure_hashes()
# ripemd160
self.ripe.update(txt)
self.entryRipeMd.insert(0, self.ripe.hexdigest())
# md4
self.md4.update(txt)
self.entryMd4.insert(0, self.md4.hexdigest())
# whirlpool
self.whirl.update(txt)
self.entryWhirl.insert(0, self.whirl.hexdigest())
# dsa
self.dsa.update(txt)
self.entryDsa.insert(0, self.dsa.hexdigest())
# Starting from index 2 to get rid of the '0x'
# crc32
self.entryCrc.insert(0, (8 - len(hex(crc32(txt))[2:])) * '0' + hex(crc32(txt))[2:])
# adler32
self.entryAdler.insert(0, (8 - len(hex(adler32(txt))[2:])) * '0' + hex(adler32(txt))[2:])
self.disable_entry()
开发者ID:risalmuhammed,项目名称:HashGenerator,代码行数:52,代码来源:HashGen.py
示例18: format_article
def format_article(art, **response_args):
art["X-FromName"], art["X-FromEmail"] = parseaddr(art["From"] if "From" in art else "")
if art["X-FromName"] == '': art["X-FromName"] = art["X-FromEmail"]
date = mktime_tz(parsedate_tz(art["Date"]))
if date < time.time() - 120:
title = "\x0314In \x0F\x03{0:02d}{Newsgroups}\x0F\x0314: on \x0F{Date}\x0314 by \x0F\x03{0:02d}{X-FromName}\x0F \x02{Subject}\x0F"
else:
title = "\x0314In \x0F\x03{0:02d}{Newsgroups}\x0F\x0314: by \x0F\x03{0:02d}{X-FromName}\x0F \x02{Subject}\x0F"
return Response(art.get_payload().replace('\n', ' '),
title=title.format(adler32(art["Newsgroups"].encode()) & 0xf, adler32(art["X-FromEmail"].encode()) & 0xf, **{h: decode_header(i) for h,i in art.items()}),
**response_args)
开发者ID:nemunaire,项目名称:nemubot,代码行数:13,代码来源:nntp.py
示例19: _execute_cb
def _execute_cb(self, goal):
rospy.loginfo('Received a new request to start behavior: %s' % goal.behavior_name)
try:
be_id, behavior = next((id, be) for (id, be) in self._behavior_lib.items() if be["name"] == goal.behavior_name)
except Exception as e:
rospy.logwarn("Did not find behavior with requested name: %s" % goal.behavior_name)
self._as.set_preempted()
return
be_selection = BehaviorSelection()
be_selection.behavior_id = be_id
be_selection.autonomy_level = 255
be_selection.arg_keys = goal.arg_keys
be_selection.arg_values = goal.arg_values
be_structure = ContainerStructure()
be_structure.containers = self._create_behavior_structure(goal.behavior_name)
be_filepath_new = os.path.join(self._rp.get_path(behavior["package"]), 'src/' + behavior["package"] + '/' + behavior["file"] + '.py')
with open(be_filepath_new, "r") as f:
be_content_new = f.read()
be_filepath_old = os.path.join(self._rp.get_path(behavior["package"]), 'src/' + behavior["package"] + '/' + behavior["file"] + '_tmp.py')
if not os.path.isfile(be_filepath_old):
be_selection.behavior_checksum = zlib.adler32(be_content_new)
else:
with open(be_filepath_old, "r") as f:
be_content_old = f.read()
sqm = difflib.SequenceMatcher(a=be_content_old, b=be_content_new)
diffs = [x[1] for x in sqm.get_grouped_opcodes(0)]
for opcode, a0, a1, b0, b1 in diffs:
content = be_content_new[b0:b1]
be_selection.modifications.append(BehaviorModification(a0, a1, content))
be_selection.behavior_checksum = zlib.adler32(be_content_new)
self._pub.publish(be_selection)
self._behavior_running = True
rate = rospy.Rate(10)
while self._behavior_running and not rospy.is_shutdown():
if self._current_state is not None:
self._as.publish_feedback(BehaviorExecutionFeedback(self._current_state))
self._current_state = None
rate.sleep()
rospy.loginfo('Finished behavior execution!')
self._as.set_succeeded('')
开发者ID:nianxing,项目名称:flexbe_behavior_engine,代码行数:50,代码来源:behavior_action_server.py
示例20: parse_raw
def parse_raw(cls, data):
# bail early if there is not enough data
if len(data) < cls.header_size:
raise ACPMessageError("need to pass at least {0} bytes".format(cls.header_size))
header_data = data[:cls.header_size]
# make sure there's data beyond the header before we try to access it
body_data = data[cls.header_size:] if len(data) > cls.header_size else None
(magic, version, header_checksum, body_checksum, body_size, flags, unused, command, error_code, key) = cls._header_format.unpack(header_data)
logging.debug("ACP message header fields, parsed not validated")
logging.debug("magic {0!r}".format(magic))
logging.debug("header_checksum {0:#x}".format(header_checksum))
logging.debug("body_checksum {0:#x}".format(body_checksum))
logging.debug("body_size {0:#x}".format(body_size))
logging.debug("flags {0:#x}".format(flags))
logging.debug("unused {0:#x}".format(unused))
logging.debug("command {0:#x}".format(command))
logging.debug("error_code {0:#x}".format(error_code))
logging.debug("key {0!r}".format(key))
if magic != cls._header_magic:
raise ACPMessageError("bad header magic")
if version not in [0x00000001, 0x00030001]:
raise ACPMessageError("invalid version")
#TODO: can we zero the header_checksum field without recreating the struct (how?)
tmphdr = cls._header_format.pack(magic, version, 0, body_checksum, body_size, flags, unused, command, error_code, key)
if header_checksum != zlib.adler32(tmphdr):
raise ACPMessageError("header checksum does not match")
if body_data and body_size == -1:
raise ACPMessageError("cannot handle stream header with data attached")
if body_data and body_size != len(body_data):
raise ACPMessageError("message body size does not match available data")
if body_data and body_checksum != zlib.adler32(body_data):
raise ACPMessageError("body checksum does not match")
#TODO: check flags
#TODO: check status
if command not in [1, 3, 4, 5, 6, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b]:
raise ACPMessageError("unknown command")
#TODO: check error code
return cls(version, flags, unused, command, error_code, key, body_data, body_size)
开发者ID:iMokhles,项目名称:airpyrt-tools,代码行数:50,代码来源:message.py
注:本文中的zlib.adler32函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论