Python random.getstate() Examples
The following are 30
code examples of random.getstate().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
random
, or try the search function
.

Example #1
Source Project: skeltorch Author: davidalvarezdlt File: runner.py License: MIT License | 7 votes |
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'])
Example #2
Source Project: simple-effective-text-matching-pytorch Author: alibaba-edu File: model.py License: Apache License 2.0 | 6 votes |
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)
Example #3
Source Project: GTDWeb Author: lanbing510 File: crypto.py License: GNU General Public License v2.0 | 6 votes |
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))
Example #4
Source Project: bioforum Author: reBiocoder File: crypto.py License: MIT License | 6 votes |
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))
Example #5
Source Project: jet-bridge Author: jet-admin File: common.py License: MIT License | 6 votes |
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))
Example #6
Source Project: picklable-itertools Author: mila-iqia File: __init__.py License: MIT License | 6 votes |
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)
Example #7
Source Project: BioQueue Author: liyao001 File: install.py License: Apache License 2.0 | 6 votes |
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))
Example #8
Source Project: diogenes Author: dssg File: subset.py License: MIT License | 6 votes |
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})
Example #9
Source Project: diogenes Author: dssg File: subset.py License: MIT License | 6 votes |
def __iter__(self): y = self._y subset_size = self.__subset_size n_subsets = self.__n_subsets count = Counter(y) n_categories = len(count) proportions = {key: 1.0 / n_categories 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})
Example #10
Source Project: diogenes Author: dssg File: subset.py License: MIT License | 6 votes |
def __iter__(self): y = self._y subset_size = self.__subset_size positive_cases = np.where(y)[0] negative_cases = np.where(np.logical_not(y))[0] seed(self.__random_state_seed) random_state = getstate() for prop_pos in self.__proportions_positive: setstate(random_state) positive_sample = sample(positive_cases, int(subset_size * prop_pos)) negative_sample = sample(negative_cases, int(subset_size * (1 - prop_pos))) random_state = getstate() # If one of these sets is empty, concatentating them casts to float, so we have # to cast it back (hence the astype) all_indices = np.sort(np.concatenate([positive_sample, negative_sample])).astype(int) yield (all_indices, self._col_names, 'prop_positive={}'.format(prop_pos))
Example #11
Source Project: 26-Cogs Author: Twentysix26 File: penis.py License: GNU General Public License v3.0 | 6 votes |
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)
Example #12
Source Project: cupy Author: cupy File: random.py License: MIT License | 6 votes |
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)
Example #13
Source Project: Hands-On-Application-Development-with-PyCharm Author: PacktPublishing File: crypto.py License: MIT License | 6 votes |
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))
Example #14
Source Project: python Author: Yeah-Kun File: crypto.py License: Apache License 2.0 | 6 votes |
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))
Example #15
Source Project: luscan-devel Author: blackye File: crypto.py License: GNU General Public License v2.0 | 6 votes |
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)])
Example #16
Source Project: tiny_python_projects Author: kyclark File: solution.py License: MIT License | 6 votes |
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) # --------------------------------------------------
Example #17
Source Project: openhgsenti Author: drexly File: crypto.py License: Apache License 2.0 | 6 votes |
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))
Example #18
Source Project: flexx Author: flexxui File: _session.py License: BSD 2-Clause "Simplified" License | 6 votes |
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))
Example #19
Source Project: lang2program Author: kelvinguu File: utils.py License: Apache License 2.0 | 6 votes |
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)
Example #20
Source Project: lang2program Author: kelvinguu File: utils.py License: Apache License 2.0 | 6 votes |
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)
Example #21
Source Project: CSBDeep Author: CSBDeep File: utils.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #22
Source Project: rl_swiss Author: KamyarGh File: _simple_replay_buffer_with_rand_state.py License: MIT License | 6 votes |
def __init__( self, max_rb_size_per_task, observation_dim, action_dim, discrete_action_dim=False, policy_uses_pixels=False, policy_uses_task_params=False, concat_task_params_to_policy_obs=False, random_seed=2001 ): prev_py_rand_state = python_random.getstate() python_random.seed(random_seed) self._py_rand_state = python_random.getstate() python_random.setstate(prev_py_rand_state) self._obs_dim = observation_dim self._act_dim = action_dim self._max_rb_size_per_task = max_rb_size_per_task self._disc_act_dim = discrete_action_dim self._policy_uses_pixels = policy_uses_pixels self._policy_uses_task_params = policy_uses_task_params self._concat_task_params_to_policy_obs = concat_task_params_to_policy_obs p = self._get_partial() self.task_replay_buffers = defaultdict(p)
Example #23
Source Project: python2017 Author: bpgc-cte File: crypto.py License: MIT License | 6 votes |
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))
Example #24
Source Project: cotk Author: thu-coai File: test_single_turn_dialog.py License: Apache License 2.0 | 6 votes |
def base_test_restart(self, dl): with pytest.raises(ValueError): dl.restart("unknown set") for set_name in dl.data.keys(): with pytest.raises(ValueError): dl.restart(set_name) record_index = copy.copy(dl.index[set_name]) dl.restart(set_name, batch_size=3, shuffle=False) assert record_index == dl.index[set_name] assert dl.batch_id[set_name] == 0 assert dl.batch_size[set_name] == 3 #rng_state_st = random.getstate() dl.restart(set_name, shuffle=True) #rng_state_ed = random.getstate() #assert operator.eq(rng_state_st, rng_state_ed) assert dl.batch_id[set_name] == 0 record_index = copy.copy(dl.index[set_name]) dl.restart(set_name, shuffle=False) assert record_index == dl.index[set_name] assert dl.batch_id[set_name] == 0
Example #25
Source Project: cotk Author: thu-coai File: test_dataloader.py License: Apache License 2.0 | 6 votes |
def base_test_restart(self, lp: LanguageProcessing): with pytest.raises(ValueError): lp.restart("unknown set") for set_name in lp.data.keys(): with pytest.raises(ValueError): lp.restart(set_name) record_index = copy.copy(lp.index[set_name]) lp.restart(set_name, batch_size=3, shuffle=False) assert record_index == lp.index[set_name] assert lp.batch_id[set_name] == 0 assert lp.batch_size[set_name] == 3 #rng_state_st = random.getstate() lp.restart(set_name, shuffle=True) #rng_state_ed = random.getstate() #assert operator.eq(rng_state_st, rng_state_ed) assert lp.batch_id[set_name] == 0 record_index = copy.copy(lp.index[set_name]) lp.restart(set_name, shuffle=False) assert record_index == lp.index[set_name] assert lp.batch_id[set_name] == 0
Example #26
Source Project: cotk Author: thu-coai File: test_dataloader.py License: Apache License 2.0 | 6 votes |
def base_test_get_batches(self, lp: LanguageProcessing): lp_cp = copy.deepcopy(lp) for set_name in lp.data.keys(): #rng_state = random.getstate() lp_batches = iter(lp.get_batches(set_name, 3, False)) #random.setstate(rng_state) lp_cp.restart(set_name, 3, False) while True: res_cp = lp_cp.get_next_batch(set_name) if res_cp is None: break res = next(lp_batches) assert sorted(res_cp.keys()) == sorted(res.keys()) for key in res_cp.keys(): if isinstance(res_cp[key], np.ndarray): assert (res_cp[key] == res[key]).all() else: assert res_cp[key] == res[key]
Example #27
Source Project: cotk Author: thu-coai File: test_language_generation.py License: Apache License 2.0 | 6 votes |
def base_test_restart(self, dl): with pytest.raises(ValueError): dl.restart("unknown set") for set_name in dl.data.keys(): with pytest.raises(ValueError): dl.restart(set_name) record_index = copy.copy(dl.index[set_name]) dl.restart(set_name, batch_size=3, shuffle=False) assert record_index == dl.index[set_name] assert dl.batch_id[set_name] == 0 assert dl.batch_size[set_name] == 3 #rng_state_st = random.getstate() dl.restart(set_name, shuffle=True) #rng_state_ed = random.getstate() #assert operator.eq(rng_state_st, rng_state_ed) assert dl.batch_id[set_name] == 0 record_index = copy.copy(dl.index[set_name]) dl.restart(set_name, shuffle=False) assert record_index == dl.index[set_name] assert dl.batch_id[set_name] == 0
Example #28
Source Project: neat-python Author: CodeReclaimers File: checkpoint.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def save_checkpoint(self, config, population, species_set, generation): """ Save the current simulation state. """ filename = '{0}{1}'.format(self.filename_prefix, generation) print("Saving checkpoint to {0}".format(filename)) with gzip.open(filename, 'w', compresslevel=5) as f: data = (generation, config, population, species_set, random.getstate()) pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL)
Example #29
Source Project: decaNLP Author: salesforce File: iterator.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, random_state=None): self._random_state = random_state self.extra = 0 if self._random_state is None: self._random_state = random.getstate()
Example #30
Source Project: decaNLP Author: salesforce File: iterator.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def use_internal_state(self): """Use a specific RNG state.""" old_state = random.getstate() random.setstate(self._random_state) yield self._random_state = random.getstate() random.setstate(old_state)