本文整理汇总了Python中random.getstate方法的典型用法代码示例。如果您正苦于以下问题:Python random.getstate方法的具体用法?Python random.getstate怎么用?Python random.getstate使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类random
的用法示例。
在下文中一共展示了random.getstate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def save(self, states, name=None):
if name:
filename = os.path.join(self.args.summary_dir, name)
else:
filename = os.path.join(self.args.summary_dir, f'{self.prefix}_{self.updates}.pt')
params = {
'state_dict': {
'model': self.network.state_dict(),
'opt': self.opt.state_dict(),
'updates': self.updates,
},
'args': self.args,
'random_state': random.getstate(),
'torch_state': torch.random.get_rng_state()
}
params.update(states)
if self.args.cuda:
params['torch_cuda_state'] = torch.cuda.get_rng_state()
torch.save(params, filename)
示例2: get_random_string
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
settings.SECRET_KEY)).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
示例3: get_random_string
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Return a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
('%s%s%s' % (random.getstate(), time.time(), settings.SECRET_KEY)).encode()
).digest()
)
return ''.join(random.choice(allowed_chars) for i in range(length))
示例4: get_random_string
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def get_random_string(length, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', salt=''):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
salt)).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
示例5: verify_tee
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def verify_tee(n, original, seed):
try:
state = random.getstate()
iterators = list(tee(original, n=n))
results = [[] for _ in range(n)]
exhausted = [False] * n
while not all(exhausted):
# Upper argument of random.randint is inclusive. Argh.
i = random.randint(0, n - 1)
if not exhausted[i]:
if len(results[i]) == len(original):
assert_raises(StopIteration, next, iterators[i])
assert results[i] == original
exhausted[i] = True
else:
if random.randint(0, 1):
iterators[i] = cPickle.loads(
cPickle.dumps(iterators[i]))
elem = next(iterators[i])
results[i].append(elem)
finally:
random.setstate(state)
示例6: get_random_secret_key
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def get_random_secret_key():
import random
import hashlib
import time
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
import warnings
warnings.warn('A secure pseudo-random number generator is not available '
'on your system. Falling back to Mersenne Twister.')
using_sysrandom = False
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$^&*(-_=+)'
if not using_sysrandom:
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
'BioQueue')).encode('utf-8')
).digest())
return ''.join(random.choice(chars) for i in range(50))
示例7: __iter__
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def __iter__(self):
y = self._y
subset_size = self.__subset_size
n_subsets = self.__n_subsets
count = Counter(y)
size_space = float(sum(count.values()))
proportions = {key: count[key] / size_space for key in count}
n_choices = {key: int(proportions[key] * subset_size) for
key in proportions}
indices = {key: np.where(y == key)[0] for key in count}
seed(self.__random_state_seed)
random_state = getstate()
for i in xrange(n_subsets):
setstate(random_state)
samples = {key: sample(indices[key], n_choices[key]) for key in count}
random_state = getstate()
all_indices = np.sort(np.concatenate(samples.values()))
yield (all_indices, self._col_names, {'sample_num': i})
示例8: penis
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def penis(self, ctx, *users: discord.Member):
"""Detects user's penis length
This is 100% accurate.
Enter multiple users for an accurate comparison!"""
if not users:
await self.bot.send_cmd_help(ctx)
return
dongs = {}
msg = ""
state = random.getstate()
for user in users:
random.seed(user.id)
dongs[user] = "8{}D".format("=" * random.randint(0, 30))
random.setstate(state)
dongs = sorted(dongs.items(), key=lambda x: x[1])
for user, dong in dongs:
msg += "**{}'s size:**\n{}\n".format(user.display_name, dong)
for page in pagify(msg):
await self.bot.say(page)
示例9: do_setup
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def do_setup(deterministic=True):
global _old_python_random_state
global _old_numpy_random_state
global _old_cupy_random_states
_old_python_random_state = random.getstate()
_old_numpy_random_state = numpy.random.get_state()
_old_cupy_random_states = cupy.random.generator._random_states
cupy.random.reset_states()
# Check that _random_state has been recreated in
# cupy.random.reset_states(). Otherwise the contents of
# _old_cupy_random_states would be overwritten.
assert (cupy.random.generator._random_states is not
_old_cupy_random_states)
if not deterministic:
random.seed()
numpy.random.seed()
cupy.random.seed()
else:
random.seed(99)
numpy.random.seed(100)
cupy.random.seed(101)
示例10: get_random_string
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
settings.SECRET_KEY)).encode('utf-8')
).digest())
return ''.join([random.choice(allowed_chars) for i in range(length)])
示例11: save_states
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def save_states(self):
"""Saves the states inside a checkpoint associated with ``epoch``."""
checkpoint_data = dict()
if isinstance(self.model, torch.nn.DataParallel):
checkpoint_data['model'] = self.model.module.state_dict()
else:
checkpoint_data['model'] = self.model.state_dict()
checkpoint_data['optimizer'] = self.optimizer.state_dict()
checkpoint_data['random_states'] = (
random.getstate(), np.random.get_state(), torch.get_rng_state(), torch.cuda.get_rng_state() if
torch.cuda.is_available() else None
)
checkpoint_data['counters'] = self.counters
checkpoint_data['losses_epoch'] = self.losses_epoch
checkpoint_data['losses_it'] = self.losses_it
checkpoint_data.update(self.save_states_others())
self.experiment.checkpoint_save(checkpoint_data, self.counters['epoch'])
示例12: test_scramble
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def test_scramble():
"""Test scramble"""
state = random.getstate()
random.seed(1)
assert scramble("a") == "a"
assert scramble("ab") == "ab"
assert scramble("abc") == "abc"
assert scramble("abcd") == "acbd"
assert scramble("abcde") == "acbde"
assert scramble("abcdef") == "aecbdf"
assert scramble("abcde'f") == "abcd'ef"
random.setstate(state)
# --------------------------------------------------
示例13: get_random_string
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def get_random_string(length=24, allowed_chars=None):
""" Produce a securely generated random string.
With a length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
allowed_chars = allowed_chars or ('abcdefghijklmnopqrstuvwxyz' +
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
try:
srandom = random.SystemRandom()
except NotImplementedError: # pragma: no cover
srandom = random
logger.warning('Falling back to less secure Mersenne Twister random string.')
bogus = "%s%s%s" % (random.getstate(), time.time(), 'sdkhfbsdkfbsdbhf')
random.seed(hashlib.sha256(bogus.encode()).digest())
return ''.join(srandom.choice(allowed_chars) for i in range(length))
示例14: random_seed
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def random_seed(seed=None):
"""Execute code inside this with-block using the specified seed.
If no seed is specified, nothing happens.
Does not affect the state of the random number generator outside this block.
Not thread-safe.
Args:
seed (int): random seed
"""
if seed is None:
yield
else:
py_state = random.getstate() # save state
np_state = np.random.get_state()
random.seed(seed) # alter state
np.random.seed(seed)
yield
random.setstate(py_state) # restore state
np.random.set_state(np_state)
示例15: choice
# 需要导入模块: import random [as 别名]
# 或者: from random import getstate [as 别名]
def choice(population, k=1, replace=True):
ver = platform.sys.version_info
if replace and (ver.major,ver.minor) in [(2,7),(3,5)]: # python 2.7 or 3.5
# slow if population is large and not a np.ndarray
return list(np.random.choice(population, k, replace=replace))
else:
try:
# save state of 'random' and set seed using 'np.random'
state = random.getstate()
random.seed(np.random.randint(np.iinfo(int).min, np.iinfo(int).max))
if replace:
# sample with replacement
return random.choices(population, k=k)
else:
# sample without replacement
return random.sample(population, k=k)
finally:
# restore state of 'random'
random.setstate(state)