当前位置: 首页>>代码示例>>Python>>正文


Python random.randrange方法代码示例

本文整理汇总了Python中random.randrange方法的典型用法代码示例。如果您正苦于以下问题:Python random.randrange方法的具体用法?Python random.randrange怎么用?Python random.randrange使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在random的用法示例。


在下文中一共展示了random.randrange方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_token

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:23,代码来源:user.py

示例2: choose_random_photo

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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 
开发者ID:pkkid,项目名称:pkmeter,代码行数:26,代码来源:picasa.py

示例3: step

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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 
开发者ID:ManiacalLabs,项目名称:BiblioPixelAnimations,代码行数:19,代码来源:Pulse.py

示例4: step

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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 
开发者ID:ManiacalLabs,项目名称:BiblioPixelAnimations,代码行数:27,代码来源:hyperspace.py

示例5: sample_doc

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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] 
开发者ID:allenai,项目名称:tpu_pretrain,代码行数:20,代码来源:pregenerate_training_data.py

示例6: select_action

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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) 
开发者ID:moemen95,项目名称:Pytorch-Project-Template,代码行数:19,代码来源:dqn.py

示例7: random_expr

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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) 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:26,代码来源:algorithmic_math.py

示例8: generate_algebra_simplify_sample

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:27,代码来源:algorithmic_math.py

示例9: datetime

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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) 
开发者ID:BetterWorks,项目名称:django-anonymizer,代码行数:19,代码来源:base.py

示例10: bench

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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 
开发者ID:myhdl,项目名称:myhdl,代码行数:25,代码来源:test_bitonic.py

示例11: bench

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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 
开发者ID:myhdl,项目名称:myhdl,代码行数:25,代码来源:test_bcd2led.py

示例12: test_dffa

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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 
开发者ID:myhdl,项目名称:myhdl,代码行数:27,代码来源:dffa.py

示例13: LoopBench

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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 
开发者ID:myhdl,项目名称:myhdl,代码行数:18,代码来源:test_loops.py

示例14: test_signed_list

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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) 
开发者ID:myhdl,项目名称:myhdl,代码行数:19,代码来源:test_initial_values.py

示例15: benchBool

# 需要导入模块: import random [as 别名]
# 或者: from random import randrange [as 别名]
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 
开发者ID:myhdl,项目名称:myhdl,代码行数:18,代码来源:test_misc.py


注:本文中的random.randrange方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。