我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用random.Random()。
def gen_values(self, n, reversed = False, shuffled = False, gen_dupes = False): if reversed: keys = xrange(n-1,-1,-1) else: keys = xrange(n) if shuffled: keys = list(keys) r = random.Random(1234827) r.shuffle(keys) if gen_dupes: return itertools.chain( itertools.izip(keys, xrange(0, 2*n, 2)), itertools.islice(itertools.izip(keys, xrange(0, 2*n, 2)), 10, None), ) else: return itertools.izip(keys, xrange(0, 2*n, 2))
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0): self.forever = forever self.renewkeys = renewkeys self.inf = inf self.rnd = random.Random(seed) self.sbox_size = 256 self.top = sup-inf+1 n=0 while (1<<n) < self.top: n += 1 self.n =n self.fs = min(3,(n+1)/2) self.fsmask = 2**self.fs-1 self.rounds = max(self.n,3) self.turns = 0 self.i = 0
def show_page(page, rating=True): attribution = page.build_attribution_string( templates=dict( author='written {hdate} by {user}', rewrite='rewritten {hdate} by {user}', translator='translated {hdate} by {user}', maintainer='maintained {hdate} by {user}'), group_templates=dict( author='co-written {hdate} by {users} and {last_user}', rewrite='rewritten {hdate} by {users} and {last_user}', translator='translated {hdate} by {users} and {last_user}', maintainer='maintained {hdate} by {users} and {last_user}')) out = lex.page_lookup.summary if rating else lex.page_lookup.nr_summary if page.name == 'scp-1848': r = rand.Random(int(arrow.now().format('YYYYMMDDHH'))) rating = r.randrange(-160, -140) else: rating = page.rating return out(page=page, rating=rating, attribution=attribution)
def run_with_fixed_seeds(count=128, master_seed=0x243F6A8885A308D3): """ decorator run test method w/ multiple fixed seeds. """ def builder(func): @wraps(func) def wrapper(*args, **kwds): rng = random.Random(master_seed) for _ in irange(count): kwds['seed'] = rng.getrandbits(32) func(*args, **kwds) return wrapper return builder #============================================================================= # custom test harness #=============================================================================
def getrandbytes(rng, count): """return byte-string containing *count* number of randomly generated bytes, using specified rng""" # NOTE: would be nice if this was present in stdlib Random class ###just in case rng provides this... ##meth = getattr(rng, "getrandbytes", None) ##if meth: ## return meth(count) if not count: return _BEMPTY def helper(): # XXX: break into chunks for large number of bits? value = rng.getrandbits(count<<3) i = 0 while i < count: yield value & 0xff value >>= 3 i += 1 return join_byte_values(helper())
def shuffle_and_batch(items: List[T], batch_size: int, rng: Optional[random.Random] = None) \ -> Iterator[List[T]]: """Optionally shuffles and batches items in a list. Args: - items: List of items to shuffle & batch. - batch_size: size of batches. - rng: random number generator if items should be shuffles, else None. Returns: Batch iterator """ todo = list(range(len(items))) if rng is not None: rng.shuffle(todo) while todo: indices = todo[:batch_size] todo = todo[batch_size:] items_batch = [items[i] for i in indices] yield items_batch
def random_str(randomlength=8, just_number=False): """???????????? :param randomlength: ????????? :param just_number: ????? :return: """ string = "" if just_number: chars = '0123456789' else: chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789' length = len(chars) - 1 random = Random() for i in range(randomlength): string += chars[random.randint(0, length)] return string
def generate_hold_out_split (dataset, training = 0.8, base_dir="splits"): r = random.Random() r.seed(1489215) article_ids = list(dataset.articles.keys()) # get a list of article ids r.shuffle(article_ids) # and shuffle that list training_ids = article_ids[:int(training * len(article_ids))] hold_out_ids = article_ids[int(training * len(article_ids)):] # write the split body ids out to files for future use with open(base_dir+ "/"+ "training_ids.txt", "w+") as f: f.write("\n".join([str(id) for id in training_ids])) with open(base_dir+ "/"+ "hold_out_ids.txt", "w+") as f: f.write("\n".join([str(id) for id in hold_out_ids]))
def my_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None): """ custom colors for wordcloud, derived from wordcloud source Parameters ---------- word font_size position orientation font_path random_state Returns ------- """ if random_state is None: random_state = Random() return "hsl(%d, 70%%, 40%%)" % random_state.randint(0, 255)
def test_random_sample(self): alist = list(range(100)) assert list( random_sample(1, alist, random_state=2016)) == alist mk_rsample = lambda rs=1: \ list(random_sample(0.1, alist, random_state=rs)) rsample1 = mk_rsample() assert rsample1 == mk_rsample() rsample2 = mk_rsample(1984) randobj = Random(1984) assert rsample2 == mk_rsample(randobj) assert rsample1 != rsample2 assert mk_rsample(object) == mk_rsample(object) assert mk_rsample(object) != mk_rsample(object()) assert mk_rsample(b"a") == mk_rsample(u"a") assert raises(TypeError, lambda: mk_rsample([]))
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0): self.forever = forever self.renewkeys = renewkeys self.inf = inf self.rnd = random.Random(seed) self.sbox_size = 256 self.top = sup-inf+1 n=0 while (1<<n) < self.top: n += 1 self.n =n self.fs = min(3,(n+1)//2) self.fsmask = 2**self.fs-1 self.rounds = max(self.n,3) self.turns = 0 self.i = 0
def __init__(self, f, block_size=0x40000, max_blocks=512, encoding='utf-8', seed=123): assert 'b' in f.mode self.random = Random(seed) self.block_size = block_size self.max_blocks = max_blocks self.lines = None self.f = f self.encoding = encoding f.seek(0, 2) file_size = f.tell() f.seek(0, 0) if file_size <= block_size*max_blocks: # For sufficiently small files, read the whole one into RAM self.lines = [str(line.rstrip(b'\n'), encoding) for line in f] shuffle(self.lines, self.random.random) else: # For large files, only store a list of block offsets self.offsets = list(range(0, file_size, block_size))
def file_splitter(filename, seed = 0, train_prop = 0.7, dev_prop = 0.15, test_prop = 0.15): """Splits the lines of a file into 3 output files.""" import random rnd = random.Random(seed) basename = filename[:-4] train_file = open(basename + ".train.txt", "w") test_file = open(basename + ".test.txt", "w") dev_file = open(basename + ".dev.txt", "w") with open(filename, 'r') as f: for l in f.readlines(): p = rnd.random() if p < train_prop: train_file.write(l) elif p < train_prop + dev_prop: dev_file.write(l) else: test_file.write(l) train_file.close() test_file.close() dev_file.close()
def file_splitter(all_file, train_file, dev_file): """Splits the labeled data into train and dev, sentence-wise.""" import random all_sents, all_labels = read_file(all_file) train_f = open(train_file, "w") dev_f = open(dev_file, "w") seed = 0 dev_prop = 0.25 rnd = random.Random(seed) for i in xrange(len(all_sents)): if rnd.random() < dev_prop: write_sent(dev_f, all_sents[i], all_labels[i]) else: write_sent(train_f, all_sents[i], all_labels[i]) train_f.close() dev_f.close()
def test_zeroinputs(self): # Verify that distributions can handle a series of zero inputs' g = random.Random() x = [g.random() for i in range(50)] + [0.0]*5 g.random = x[:].pop; g.uniform(1,10) g.random = x[:].pop; g.paretovariate(1.0) g.random = x[:].pop; g.expovariate(1.0) g.random = x[:].pop; g.weibullvariate(1.0, 1.0) g.random = x[:].pop; g.normalvariate(0.0, 1.0) g.random = x[:].pop; g.gauss(0.0, 1.0) g.random = x[:].pop; g.lognormvariate(0.0, 1.0) g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0) g.random = x[:].pop; g.gammavariate(0.01, 1.0) g.random = x[:].pop; g.gammavariate(1.0, 1.0) g.random = x[:].pop; g.gammavariate(200.0, 1.0) g.random = x[:].pop; g.betavariate(3.0, 3.0) g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
def Random(self, randlength): '''Return a random integer with randlength digits. The actual number of digits may be less than randlength because leading zeroes are stripped from the result.''' result = DecInt() result.radix = self.radix result.sign = 1 result.terms = [] power, base = self.radix full, partial = divmod(randlength, power) for i in range(full): result.terms.append(mp(_rr.randrange(long(Radix2Value(self.radix))))) result.terms.append(mp(_rr.randrange(long(Radix2Value((partial, base)))))) while len(result.terms) > 1 and result.terms[-1] == ZERO: result.terms.pop() return result
def generate_digits_file(source_path: str, target_path: str, line_count: int = 100, line_length: int = 9, sort_target: bool = False, line_count_empty: int = 0, seed=13): assert line_count_empty <= line_count random_gen = random.Random(seed) with open(source_path, "w") as source_out, open(target_path, "w") as target_out: all_digits = [] for _ in range(line_count - line_count_empty): digits = [random_gen.choice(_DIGITS) for _ in range(random_gen.randint(1, line_length))] all_digits.append(digits) for _ in range(line_count_empty): all_digits.append([]) random_gen.shuffle(all_digits) for digits in all_digits: print(" ".join(digits), file=source_out) if sort_target: digits.sort() print(" ".join(digits), file=target_out)
def demo_bw(): # demo Baum Welch by generating some sequences and then performing # unsupervised training on them print() print("Baum-Welch demo for market example") print() model, states, symbols = _market_hmm_example() # generate some random sequences training = [] import random rng = random.Random() rng.seed(0) for i in range(10): item = model.random_sample(rng, 5) training.append([(i[0], None) for i in item]) # train on those examples, starting with the model that generated them trainer = HiddenMarkovModelTrainer(states, symbols) hmm = trainer.train_unsupervised(training, model=model, max_iterations=1000)
def __init__(self, name, selection_strategy='1', seed=None): ''' :param name: name of the Stage :param selection_strategy: strategy for selecting amount of template in each mutation :param seed: RNG seed (default: None) ''' super(Stage, self).__init__('Stage[%s]' % name) self._templates = [] self._strategy = selection_strategy self._min_sequence = None self._max_sequence = None self._r = random.Random() self._seed = seed if seed: self._r.seed(seed) self._current_sequence_templates = None self._default_sequence_templates = None self._ready = False self._validate_strategy(selection_strategy)
def test_zeroinputs(self): # Verify that distributions can handle a series of zero inputs' g = random.Random() x = [g.random() for i in xrange(50)] + [0.0]*5 g.random = x[:].pop; g.uniform(1,10) g.random = x[:].pop; g.paretovariate(1.0) g.random = x[:].pop; g.expovariate(1.0) g.random = x[:].pop; g.weibullvariate(1.0, 1.0) g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0) g.random = x[:].pop; g.normalvariate(0.0, 1.0) g.random = x[:].pop; g.gauss(0.0, 1.0) g.random = x[:].pop; g.lognormvariate(0.0, 1.0) g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0) g.random = x[:].pop; g.gammavariate(0.01, 1.0) g.random = x[:].pop; g.gammavariate(1.0, 1.0) g.random = x[:].pop; g.gammavariate(200.0, 1.0) g.random = x[:].pop; g.betavariate(3.0, 3.0) g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
def test_constant(self): g = random.Random() N = 100 for variate, args, expected in [ (g.uniform, (10.0, 10.0), 10.0), (g.triangular, (10.0, 10.0), 10.0), (g.triangular, (10.0, 10.0, 10.0), 10.0), (g.expovariate, (float('inf'),), 0.0), (g.vonmisesvariate, (3.0, float('inf')), 3.0), (g.gauss, (10.0, 0.0), 10.0), (g.lognormvariate, (0.0, 0.0), 1.0), (g.lognormvariate, (-float('inf'), 0.0), 0.0), (g.normalvariate, (10.0, 0.0), 10.0), (g.paretovariate, (float('inf'),), 1.0), (g.weibullvariate, (10.0, float('inf')), 10.0), (g.weibullvariate, (0.0, 10.0), 0.0), ]: for i in range(N): self.assertEqual(variate(*args), expected)
def __init__(self, name=None, fuzzable=True): namer = NameGen() fields = [] r = Random() for tag in opcodes: for i in range(4): opcode = tag | i current = chr(opcode) for j in range(i): current += chr(r.randint(0, 255)) fields.append(Static(name=namer.gen(opcode), value=current)) super(RandomHidReport, self).__init__( fields=fields, min_elements=10, max_elements=40, fuzzable=fuzzable, name=name )
def test_zeroinputs(self): # Verify that distributions can handle a series of zero inputs' g = random.Random() x = [g.random() for i in range(50)] + [0.0]*5 g.random = x[:].pop; g.uniform(1,10) g.random = x[:].pop; g.paretovariate(1.0) g.random = x[:].pop; g.expovariate(1.0) g.random = x[:].pop; g.weibullvariate(1.0, 1.0) g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0) g.random = x[:].pop; g.normalvariate(0.0, 1.0) g.random = x[:].pop; g.gauss(0.0, 1.0) g.random = x[:].pop; g.lognormvariate(0.0, 1.0) g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0) g.random = x[:].pop; g.gammavariate(0.01, 1.0) g.random = x[:].pop; g.gammavariate(1.0, 1.0) g.random = x[:].pop; g.gammavariate(200.0, 1.0) g.random = x[:].pop; g.betavariate(3.0, 3.0) g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
def test_constant(self): g = random.Random() N = 100 for variate, args, expected in [ (g.uniform, (10.0, 10.0), 10.0), (g.triangular, (10.0, 10.0), 10.0), #(g.triangular, (10.0, 10.0, 10.0), 10.0), (g.expovariate, (float('inf'),), 0.0), (g.vonmisesvariate, (3.0, float('inf')), 3.0), (g.gauss, (10.0, 0.0), 10.0), (g.lognormvariate, (0.0, 0.0), 1.0), (g.lognormvariate, (-float('inf'), 0.0), 0.0), (g.normalvariate, (10.0, 0.0), 10.0), (g.paretovariate, (float('inf'),), 1.0), (g.weibullvariate, (10.0, float('inf')), 10.0), (g.weibullvariate, (0.0, 10.0), 0.0), ]: for i in range(N): self.assertEqual(variate(*args), expected)
def sink_generator(sink, rand_threshold=100): prng = random.Random(42) for i in range(len(sink_cb_cr)): valid = 0 while True: valid = (prng.randrange(100) < rand_threshold) if valid: yield sink.valid.eq(1) yield sink.y.eq(sink_y[i]) yield sink.cb_cr.eq(sink_cb_cr[i]) yield while not (yield sink.ready): yield yield sink.valid.eq(0) break else: yield sink.valid.eq(0) yield # yield for processing latency for i in range(128): yield
def __init__(self, seed=None): Data.__init__(self) self.output = '' self.yesno_callback = False self.yesno_casual = False # whether to insist they answer self.clock1 = 30 # counts down from finding last treasure self.clock2 = 50 # counts down until cave closes self.is_closing = False # is the cave closing? self.panic = False # they tried to leave during closing? self.is_closed = False # is the cave closed? self.is_done = False # caller can check for "game over" self.could_fall_in_pit = False # could the player fall into a pit? self.random_generator = random.Random() if seed is not None: self.random_generator.seed(seed)
def rng(self): cur_pid = _os.getpid() if cur_pid != getattr(self, '_rng_pid', None): self._rng = _Random() self._rng_pid = cur_pid return self._rng
def give_port(): """ Returns a random port and registers it. """ global port_random context = get_deploy_context() # default behavior if context["config"] is None: return randint(1000, 65000) if "banned_ports_parsed" not in context["config"]: banned_ports_result = [] for port_range in context["config"].banned_ports: banned_ports_result.extend(list(range(port_range["start"], port_range["end"] + 1))) context["config"]["banned_ports_parsed"] = banned_ports_result # during real deployment, let's register a port if port_random is None: port_random = Random(context["config"].deploy_secret) # if this instance already has a port, reuse it if (context["problem"], context["instance"]) in inv_port_map: return inv_port_map[(context["problem"], context["instance"])] if len(context["port_map"].items()) + len(context["config"].banned_ports_parsed) == 65536: raise Exception("All usable ports are taken. Cannot deploy any more instances.") while True: port = port_random.randint(0, 65535) if port not in context["config"].banned_ports_parsed: owner, instance = context["port_map"].get(port, (None, None)) if owner is None or (owner == context["problem"] and instance == context["instance"]): context["port_map"][port] = (context["problem"], context["instance"]) return port
def update_problem_class(Class, problem_object, seed, user, instance_directory): """ Changes the metaclass of the given class to introduce necessary fields before object instantiation. Args: Class: The problem class to be updated problem_name: The problem name seed: The seed for the Random object user: The linux username for this challenge instance instance_directory: The deployment directory for this instance Returns: The updated class described above """ random = Random(seed) attributes = deepcopy(problem_object) # pass configuration options in as class fields attributes.update(dict(deploy_config)) attributes.update({"random": random, "user": user, "directory": instance_directory, "server": deploy_config.hostname}) return challenge_meta(attributes)(Class.__name__, Class.__bases__, Class.__dict__)
def initial_state(self): r = Random() return [r.randint(1, 8) for y in range(8)]
def crossover(self, p1, p2): r = Random() crossover_index = r.randint(0, 8) left = p1.state[0:crossover_index] right = p2.state[crossover_index:8] left.extend(right) return left
def mutate(self): r = Random() for i in range(len(self.state)): if random() < self._mutation_rate: self.state[i] = r.randint(1,8)
def mutate(self): r = Random() if random() < self._mutation_rate: ix1 = r.randint(0,len(self.state)-1) ix2 = r.randint(0,len(self.state)-1) temp = self.state[ix1] self.state[ix1] = self.state[ix2] self.state[ix2] = temp
def __init__(self): self.mutex = _allocate_lock() self.rng = _Random() self.normcase = _os.path.normcase
def __init__(gen, rng=1, chain=None, **kwargs): if not hasattr(rng, 'randrange'): import random rng = random.Random(rng) if chain is None: chain = Abe.Chain.create("Testnet") gen._rng = rng gen.chain = chain for attr, val in kwargs.items(): setattr(gen, attr, val)