Python random.randrange() Examples
The following are 30
code examples of random.randrange().
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 File: test_initial_values.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def test_signed_list(): '''The correct initial value should be used for signed type signal lists ''' min_val = -12 max_val = 4 initial_vals = [intbv( randrange(min_val, max_val), min=min_val, max=max_val) for each in range(10)] runner(initial_vals, tb=initial_value_list_bench) # All the same case initial_vals = [intbv( randrange(min_val, max_val), min=min_val, max=max_val)] * 10 runner(initial_vals, tb=initial_value_list_bench)
Example #2
Source File: pregenerate_training_data.py From tpu_pretrain with Apache License 2.0 | 6 votes |
def sample_doc(self, current_idx, sentence_weighted=True): # Uses the current iteration counter to ensure we don't sample the same doc twice if sentence_weighted: # With sentence weighting, we sample docs proportionally to their sentence length if self.doc_cumsum is None or len(self.doc_cumsum) != len(self.doc_lengths): self._precalculate_doc_weights() rand_start = self.doc_cumsum[current_idx] rand_end = rand_start + self.cumsum_max - self.doc_lengths[current_idx] sentence_index = randrange(rand_start, rand_end) % self.cumsum_max sampled_doc_index = np.searchsorted(self.doc_cumsum, sentence_index, side='right') else: # If we don't use sentence weighting, then every doc has an equal chance to be chosen sampled_doc_index = (current_idx + randrange(1, len(self.doc_lengths))) % len(self.doc_lengths) assert sampled_doc_index != current_idx if self.reduce_memory: return self.document_shelf[str(sampled_doc_index)] else: return self.documents[sampled_doc_index]
Example #3
Source File: algorithmic_math.py From fine-lm with MIT License | 6 votes |
def random_expr(depth, vlist, ops): """Generate a random expression tree. Args: depth: At least one leaf will be this many levels down from the top. vlist: A list of chars. These chars are randomly selected as leaf values. ops: A list of ExprOp instances. Returns: An ExprNode instance which is the root of the generated expression tree. """ if not depth: return str(vlist[random.randrange(len(vlist))]) max_depth_side = random.randrange(2) other_side_depth = random.randrange(depth) left = random_expr(depth - 1 if max_depth_side else other_side_depth, vlist, ops) right = random_expr(depth - 1 if not max_depth_side else other_side_depth, vlist, ops) op = ops[random.randrange(len(ops))] return ExprNode(left, right, op)
Example #4
Source File: test_loops.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def LoopBench(LoopTest): a = Signal(intbv(-1)[16:]) z = Signal(intbv(0)[16:]) looptest_inst = LoopTest(a, z) data = tuple([randrange(2**min(i, 16)) for i in range(100)]) @instance def stimulus(): for i in range(100): a.next = data[i] yield delay(10) print(z) return stimulus, looptest_inst
Example #5
Source File: test_loops.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def LoopBench(LoopTest): a = Signal(intbv(-1)[16:]) z = Signal(intbv(0)[16:]) looptest_inst = LoopTest(a, z) data = tuple([randrange(2**min(i, 16)) for i in range(100)]) @instance def stimulus(): for i in range(100): a.next = data[i] yield delay(10) print(z) return stimulus, looptest_inst
Example #6
Source File: dqn.py From Pytorch-Project-Template with MIT License | 6 votes |
def select_action(self, state): """ The action selection function, it either uses the model to choose an action or samples one uniformly. :param state: current state of the model :return: """ if self.cuda: state = state.cuda() sample = random.random() eps_threshold = self.config.eps_start + (self.config.eps_start - self.config.eps_end) * math.exp( -1. * self.current_iteration / self.config.eps_decay) self.current_iteration += 1 if sample > eps_threshold: with torch.no_grad(): return self.policy_model(state).max(1)[1].view(1, 1) else: return torch.tensor([[random.randrange(2)]], device=self.device, dtype=torch.long)
Example #7
Source File: test_misc.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def benchBool(self, ConstWire): p = Signal(bool(0)) q = Signal(bool(0)) q_v = Signal(bool(0)) constwire_inst = toVerilog(ConstWire, p, q) constwire_v_inst = ConstWire_v(ConstWire.__name__, p, q_v) def stimulus(): for i in range(100): p.next = randrange(2) yield delay(10) self.assertEqual(q, q_v) return stimulus(), constwire_inst, constwire_v_inst
Example #8
Source File: test_misc.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def bench(self, adder): a = Signal(intbv(0)[8:]) b = Signal(intbv(0)[8:]) c = Signal(intbv(0)[9:]) c_v = Signal(intbv(0)[9:]) ignorecode_inst = toVerilog(adder, a, b, c) # ignorecode_inst = adder(a, b, c) ignorecode_v_inst = Ignorecode_v(adder.__name__, a, b, c_v) def stimulus(): for i in range(100): a.next = randrange(2**8) b.next = randrange(2**8) yield delay(10) self.assertEqual(c, c_v) return stimulus(), ignorecode_inst, ignorecode_v_inst
Example #9
Source File: turing.py From gated-graph-transformer-network with MIT License | 6 votes |
def make_turing_machine_rules(n_states, n_symbols): the_rules = [ [ (random.randrange(n_symbols), random.randrange(n_states), random.choice('LNR')) for symbol in range(n_symbols)] for state in range(n_states)] return the_rules
Example #10
Source File: algorithmic_math.py From fine-lm with MIT License | 6 votes |
def generate_algebra_simplify_sample(vlist, ops, min_depth, max_depth): """Randomly generate an algebra simplify dataset sample. Given an input expression, produce the simplified expression. See go/symbolic-math-dataset. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The allowed operators for the expression. min_depth: Expression trees will not have a smaller depth than this. 0 means there is just a variable. 1 means there is one operation. max_depth: Expression trees will not have a larger depth than this. To make all trees have the same depth, set this equal to `min_depth`. Returns: sample: String representation of the input. target: String representation of the solution. """ depth = random.randrange(min_depth, max_depth + 1) expr = random_expr(depth, vlist, ops) sample = str(expr) target = format_sympy_expr(sympy.simplify(sample)) return sample, target
Example #11
Source File: hyperspace.py From BiblioPixelAnimations with MIT License | 6 votes |
def step(self, amt=1): self.layout.all_off() for i in range(self._growthRate): newTail = random.randrange(0, 360, self._angleDiff) color = random.choice(self.palette) self._tails[newTail].append((0, color)) for a in range(360): angle = self._tails[a] if len(angle) > 0: removals = [] for r in range(len(angle)): tail = angle[r] if tail[0] <= self.lastRing: self._drawTail(a, tail[0], tail[1]) if tail[0] - (self._tail - 1) <= self.lastRing: tail = (tail[0] + amt, tail[1]) self._tails[a][r] = tail else: removals.append(tail) for r in removals: self._tails[a].remove(r) self._step = 0
Example #12
Source File: test_loops.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def LoopBench(LoopTest): a = Signal(intbv(-1)[16:]) z = Signal(intbv(0)[16:]) looptest_inst = LoopTest(a, z) data = tuple([randrange(2**min(i, 16)) for i in range(100)]) @instance def stimulus(): for i in range(100): a.next = data[i] yield delay(10) print(z) return stimulus, looptest_inst
Example #13
Source File: base.py From django-anonymizer with MIT License | 6 votes |
def datetime(self, field=None, val=None): """ Returns a random datetime. If 'val' is passed, a datetime within two years of that date will be returned. """ if val is None: def source(): tzinfo = get_default_timezone() if settings.USE_TZ else None return datetime.fromtimestamp(randrange(1, 2100000000), tzinfo) else: def source(): tzinfo = get_default_timezone() if settings.USE_TZ else None return datetime.fromtimestamp(int(val.strftime("%s")) + randrange(-365*24*3600*2, 365*24*3600*2), tzinfo) return self.get_allowed_value(source, field)
Example #14
Source File: Pulse.py From BiblioPixelAnimations with MIT License | 6 votes |
def step(self, amt=1): self.layout.all_off() if self.pulse_speed == 0 and random.randrange(0, 100) <= self.chance: self.add_pulse() if self.pulse_speed > 0: self.layout.set(self.pulse_position, self.pulse_color) for i in range(self._tail): c = color_scale(self.pulse_color, 255 - (self._fadeAmt * i)) self.layout.set(self.pulse_position - i, c) self.layout.set(self.pulse_position + i, c) if self.pulse_position > self._size + self._tail: self.pulse_speed = 0 else: self.pulse_position += self.pulse_speed
Example #15
Source File: dffa.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def test_dffa(): q, d, clk, rst = [Signal(bool(0)) for i in range(4)] dffa_inst = dffa(q, d, clk, rst) @always(delay(10)) def clkgen(): clk.next = not clk @always(clk.negedge) def stimulus(): d.next = randrange(2) @instance def rstgen(): yield delay(5) rst.next = 1 while True: yield delay(randrange(500, 1000)) rst.next = 0 yield delay(randrange(80, 140)) rst.next = 1 return dffa_inst, clkgen, stimulus, rstgen
Example #16
Source File: picasa.py From pkmeter with BSD 3-Clause "New" or "Revised" License | 6 votes |
def choose_random_photo(self, album): photo = {} photos_url = PHOTOS_URL % {'username':self.username, 'albumid':album['id']} response = utils.http_request(photos_url).get('response') if response: content = json.loads(response.read().decode('utf-8')) numphotos = utils.rget(content, 'feed.gphoto$numphotos.$t') if numphotos: diceroll = random.randrange(numphotos) entry = utils.rget(content, 'feed.entry')[diceroll] photo['id'] = entry['gphoto$id']['$t'] photo['url'] = entry['content']['src'] photo['title'] = utils.rget(entry, 'title.$t') photo['summary'] = utils.rget(entry, 'summary.$t') photo['timestamp'] = utils.rget(entry, 'gphoto$timestamp.$t') photo['published'] = utils.rget(entry, 'published.$t') photo['width'] = utils.rget(entry, 'gphoto$width.$t') photo['height'] = utils.rget(entry, 'gphoto$height.$t') photo['size'] = int(utils.rget(entry, 'gphoto$size.$t', 0)) photo['credit'] = ', '.join([item['$t'] for item in utils.rget(entry, 'media$group.media$credit')]) for tag, value in utils.rget(entry, 'exif$tags').items(): tagstr = tag.replace('exif$', '') photo[tagstr] = value['$t'] return photo
Example #17
Source File: test_bcd2led.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def bench(): led = Signal(intbv(0)[7:]) bcd = Signal(intbv(0)[4:]) clock = Signal(bool(0)) dut = bcd2led(led, bcd, clock) @always(delay(PERIOD//2)) def clkgen(): clock.next = not clock @instance def check(): for i in range(100): bcd.next = randrange(10) yield clock.posedge yield clock.negedge expected = int(seven_segment.encoding[int(bcd)], 2) assert led == expected raise StopSimulation return dut, clkgen, check
Example #18
Source File: user.py From hydrus with MIT License | 6 votes |
def add_token(request: LocalProxy, session: Session) -> str: """ Create a new token for the user or return a valid existing token to the user. """ token = None id_ = int(request.authorization['username']) try: token = session.query(Token).filter(Token.user_id == id_).one() if not token.is_valid(): update_token = '%030x' % randrange(16**30) token.id = update_token token.timestamp = datetime.now() session.commit() except NoResultFound: token = '%030x' % randrange(16**30) new_token = Token(user_id=id_, id=token) session.add(new_token) session.commit() return token return token.id
Example #19
Source File: test_bitonic.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def bench(): n = 8 w = 4 a0, a1, a2, a3, a4, a5, a6, a7 = inputs = [Signal(intbv(0)[w:]) for i in range(n)] z0, z1, z2, z3, z4, z5, z6, z7 = outputs = [Signal(intbv(0)[w:]) for i in range(n)] inst = Array8Sorter_v(a0, a1, a2, a3, a4, a5, a6, a7, z0, z1, z2, z3, z4, z5, z6, z7) @instance def check(): for i in range(100): data = [randrange(2**w) for i in range(n)] for i in range(n): inputs[i].next = data[i] yield delay(10) data.sort() assert data == outputs return inst, check
Example #20
Source File: test_RandomScrambler.py From myhdl with GNU Lesser General Public License v2.1 | 5 votes |
def stimulus(self): input = intbv(0) output = intbv(0) output_v = intbv(0) for i in range(100): # while 1: input[:] = randrange(M) i7.next = input[7] i6.next = input[6] i5.next = input[5] i4.next = input[4] i3.next = input[3] i2.next = input[2] i1.next = input[1] i0.next = input[0] yield delay(10) output[7] = o7 output[6] = o6 output[5] = o5 output[4] = o4 output[3] = o3 output[2] = o2 output[1] = o1 output[0] = o0 output_v[7] = o7 output_v[6] = o6 output_v[5] = o5 output_v[4] = o4 output_v[3] = o3 output_v[2] = o2 output_v[1] = o1 output_v[0] = o0 ## print output ## print output_v ## print input self.assertEqual(output, output_v)
Example #21
Source File: test_inc_initial.py From myhdl with GNU Lesser General Public License v2.1 | 5 votes |
def stimulus(self, enable, clock, reset): reset.next = ACTIVE_LOW yield negedge(clock) reset.next = INACTIVE_HIGH for i in range(1000): enable.next = min(1, randrange(5)) yield negedge(clock) raise StopSimulation
Example #22
Source File: test_dec.py From myhdl with GNU Lesser General Public License v2.1 | 5 votes |
def stimulus(self, enable, clock, reset): reset.next = INACTIVE_HIGH yield clock.negedge reset.next = ACTIVE_LOW yield clock.negedge reset.next = INACTIVE_HIGH for i in range(1000): enable.next = 1 yield clock.negedge for i in range(1000): enable.next = min(1, randrange(5)) yield clock.negedge raise StopSimulation
Example #23
Source File: test_initial_values.py From myhdl with GNU Lesser General Public License v2.1 | 5 votes |
def test_long_signals(): '''The correct initial value should work with wide bitwidths (i.e. >32) ''' min_val = -(2**71) max_val = 2**71 - 1 initial_val = intbv( randrange(min_val, max_val), min=min_val, max=max_val) runner(initial_val)
Example #24
Source File: test_initial_values.py From myhdl with GNU Lesser General Public License v2.1 | 5 votes |
def test_memory_convert(): inst = initial_value_mem_convert_bench() # TODO: this needs to be converted to use the `block` convert # only and not modify the `toV*` but this will require # changes to `conversion.verify` and `conversion.analyze` # or a `config_conversion` function add to the `Block`. pre_xiv = toVerilog.initial_values pre_viv = toVHDL.initial_values # not using the runner, this test is setup for analyze only toVerilog.initial_values = True toVHDL.initial_values = True try: assert conversion.analyze(inst) == 0 finally: toVerilog.initial_values = pre_xiv toVHDL.initial_values = pre_viv #def test_init_used_list(): # '''It should be the _init attribute of each element in the list # that is used for initialisation # # It should not be the current value, which should be ignored. # ''' # min_val = -34 # max_val = 15 # initial_val = [intbv( # randrange(min_val, max_val), min=min_val, max=max_val) # for each in range(10)] # # list_runner(initial_val, change_input_signal=True)
Example #25
Source File: test_initial_values.py From myhdl with GNU Lesser General Public License v2.1 | 5 votes |
def test_bool(): '''The correct initial value should be used for bool type signal. ''' initial_val = bool(randrange(0, 2)) runner(initial_val)
Example #26
Source File: test_initial_values.py From myhdl with GNU Lesser General Public License v2.1 | 5 votes |
def test_signed(): '''The correct initial value should be used for signed type signal. ''' min_val = -12 max_val = 4 initial_val = intbv( randrange(min_val, max_val), min=min_val, max=max_val) runner(initial_val)
Example #27
Source File: test_initial_values.py From myhdl with GNU Lesser General Public License v2.1 | 5 votes |
def test_unsigned(): '''The correct initial value should be used for unsigned type signal. ''' min_val = 0 max_val = 34 initial_val = intbv( randrange(min_val, max_val), min=min_val, max=max_val) runner(initial_val)
Example #28
Source File: test_issue_127.py From myhdl with GNU Lesser General Public License v2.1 | 5 votes |
def test_sort(self): """ Check the functionality of the bitonic sort """ length = 8 width = 4 def test_impl(): ''' test implementation ''' inputs = [ Signal(intbv(0)[width:]) for _ in range(length) ] outputs = [ Signal(intbv(0)[width:]) for _ in range(length) ] z_0, z_1, z_2, z_3, z_4, z_5, z_6, z_7 = outputs a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7 = inputs inst = array8sorter(a_0, a_1, a_2, a_3, a_4, a_5, a_6, a_7, z_0, z_1, z_2, z_3, z_4, z_5, z_6, z_7) @instance def check(): ''' testbench input and validation ''' for i in range(100): data = [randrange(2**width) for i in range(length)] for i in range(length): inputs[i].next = data[i] yield delay(10) data.sort() self.assertEqual(data, outputs, 'wrong data') raise StopSimulation return inst, check # convert
Example #29
Source File: test_rs232.py From myhdl with GNU Lesser General Public License v2.1 | 5 votes |
def ParityError(self): tx = Signal(intbv(0)) rx = tx actual = intbv(0) cfg_rx = Config(parity=ODD) cfg_tx = Config(parity=EVEN) data = intbv(randrange(256)) yield join(rs232_tx(tx, data, cfg_tx), rs232_rx(rx, actual, cfg_rx))
Example #30
Source File: dff.py From myhdl with GNU Lesser General Public License v2.1 | 5 votes |
def test_dff(): q, d, clk = [Signal(bool(0)) for i in range(3)] dff_inst = dff(q, d, clk) @always(delay(10)) def clkgen(): clk.next = not clk @always(clk.negedge) def stimulus(): d.next = randrange(2) return dff_inst, clkgen, stimulus