Python random.randrange() Examples

The following are 30 code examples for showing how to use random.randrange(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module random , or try the search function .

Example 1
Project: hydrus   Author: HTTP-APIs   File: user.py    License: MIT License 6 votes vote down vote up
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 2
Project: pkmeter   Author: pkkid   File: picasa.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 3
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: Pulse.py    License: MIT License 6 votes vote down vote up
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 4
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: hyperspace.py    License: MIT License 6 votes vote down vote up
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 5
Project: tpu_pretrain   Author: allenai   File: pregenerate_training_data.py    License: Apache License 2.0 6 votes vote down vote up
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 6
Project: Pytorch-Project-Template   Author: moemen95   File: dqn.py    License: MIT License 6 votes vote down vote up
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
Project: fine-lm   Author: akzaidi   File: algorithmic_math.py    License: MIT License 6 votes vote down vote up
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 8
Project: fine-lm   Author: akzaidi   File: algorithmic_math.py    License: MIT License 6 votes vote down vote up
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 9
Project: django-anonymizer   Author: BetterWorks   File: base.py    License: MIT License 6 votes vote down vote up
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 10
Project: myhdl   Author: myhdl   File: test_bitonic.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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 11
Project: myhdl   Author: myhdl   File: test_bcd2led.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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 12
Project: myhdl   Author: myhdl   File: dffa.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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 13
Project: myhdl   Author: myhdl   File: test_loops.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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 14
Project: myhdl   Author: myhdl   File: test_initial_values.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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 15
Project: myhdl   Author: myhdl   File: test_loops.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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 16
Project: myhdl   Author: myhdl   File: test_loops.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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 17
Project: myhdl   Author: myhdl   File: test_misc.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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 18
Project: myhdl   Author: myhdl   File: test_misc.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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 19
Project: indras_net   Author: gcallah   File: test_api_endpoints.py    License: GNU General Public License v3.0 5 votes vote down vote up
def random_name():
    return "".join(random.choices(string.ascii_letters,
                                  k=random.randrange(1, 10))) 
Example 20
Project: indras_net   Author: gcallah   File: trade_utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def rand_dist(to_goods, from_goods, comp=None):
    """
    select random good by random amount and transfer to trader
    """
    selected_good = get_rand_good(from_goods, nonzero=True)
    amt = random.randrange(0, from_goods[selected_good][AMT_AVAIL], 1)
    transfer(to_goods, from_goods, selected_good, amt, comp=comp) 
Example 21
Project: wafw00f   Author: EnableSecurity   File: main.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def nonExistent(self):
        return self.Request(path=self.path + str(random.randrange(100, 999)) + '.html') 
Example 22
Project: pkmeter   Author: pkkid   File: picasa.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def choose_random_album(self):
        counter = 0
        numphotos = sum([album['photos'] for album in self.data['albums']])
        diceroll = random.randrange(numphotos)
        for album in self.data['albums']:
            counter += album['photos']
            if counter >= diceroll: break
        return album 
Example 23
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: Tetris.py    License: MIT License 5 votes vote down vote up
def _getNextPiece(self):
        stop = len(tetris_shapes) if self._doEvil else 7
        return tetris_shapes[rand(0, stop)] 
Example 24
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: Twinkle.py    License: MIT License 5 votes vote down vote up
def pick_led(self, speed):
        idx = random.randrange(0, self.layout.numLEDs)
        p_dir, p_color, p_level = self.pixels[idx]

        if random.randrange(0, 100) < self.density:
            if p_dir == 0:  # 0 is off
                p_level += speed
                p_dir = 1  # 1 is growing
                p_color = random.choice(self.colors)
                self.layout._set_base(idx, color_scale(p_color, p_level))

                self.pixels[idx] = p_dir, p_color, p_level 
Example 25
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: Pulse.py    License: MIT License 5 votes vote down vote up
def add_pulse(self):
        self.pulse_color = random.choice(self.palette)
        self.pulse_speed = random.randrange(self.min_speed, self.max_speed)
        self.pulse_position = 0 
Example 26
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: WhiteTwinkle.py    License: MIT License 5 votes vote down vote up
def pick_led(self, inc):
        # Pick a random led, if it's off bump it up an even number so it gets brighter
        idx = random.randrange(0, self.layout.numLEDs)
        this_led = self.layout.get(idx)
        r = this_led[0]

        if random.randrange(0, self._maxLed) < self.density:
            if r == 0:
                r += inc
                self.layout.set(idx, (2, 2, 2)) 
Example 27
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: ImageAnim.py    License: MIT License 5 votes vote down vote up
def loadNextGIF(self):
        if self.random:
            if len(self.gif_indices) < 2:
                self.folder_index = self.gif_indices[0]
                self.gif_indices = list(range(len(self.gif_files)))
            else:
                index = random.randrange(len(self.gif_indices))
                self.folder_index = self.gif_indices.pop(index)
        else:
            self.folder_index += 1
            if self.folder_index >= len(self.gif_files):
                self.folder_index = 0
        self.loadGIFFile(self.gif_files[self.folder_index]) 
Example 28
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: LangtonsAnt.py    License: MIT License 5 votes vote down vote up
def pre_run(self):
        self.x = random.randrange(self.width)
        self.y = random.randrange(self.height)
        self.d = random.randrange(4) 
Example 29
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: hyperspace.py    License: MIT License 5 votes vote down vote up
def step(self, amt=1):
        self.layout.all_off()

        for i in range(self._growthRate):
            newTail = random.randrange(0, 360, self._angleDiff)
            self._tails[newTail].append(0)

        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 <= self.lastRing:
                        c = self.palette.get(tail * (255 // self.lastRing))
                        self._drawTail(a, tail, c)

                    if tail - (self._tail - 1) <= self.lastRing:
                        tail = tail + amt
                        self._tails[a][r] = tail
                    else:
                        removals.append(tail)
                for r in removals:
                    self._tails[a].remove(r)

        self._step = 0 
Example 30
Project: gated-graph-transformer-network   Author: hexahedria   File: turing.py    License: MIT License 5 votes vote down vote up
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