python类randrange()的实例源码

models_sqlite.py 文件源码 项目:nweb 作者: pierce403 项目源码 文件源码 阅读 53 收藏 0 点赞 0 评论 0
def add_corpus():
    """add files in corpus to database"""
    db = get_db()
    files = os.listdir("corpus")
    basenames = set()
    for filename in files:
        basenames.add(filename.split('.')[0])
    for basename in basenames:
        basepath = os.path.join('corpus', basename)
        with open(basepath + '.nmap', "r") as f:
            nmap = f.read()
        try:
            with open(basepath + '.xml', "r") as f:
                xml = f.read()
        except IOError:
            xml = ""
        try:
            with open(basepath + '.gnmap', "r") as f:
                gnmap = f.read()
        except IOError:
            gnamp = ""
        for i in range(0, 100):
            rando_ip = "%d.%d.%d.%d" % (random.randrange(1,254),
                                        random.randrange(1,254),
                                        random.randrange(1,254),
                                        random.randrange(1,254))
            (ip, real_ctime) = nmap_to_ip_ctime(nmap)
            for i in range(0, random.randrange(1, 10)):
                rando_ctime = real_ctime - random.randrange(3600, 3600*24*365)
                create_sighting(nmap, xml, gnmap, rando_ctime, rando_ip)
components.py 文件源码 项目:easydo-ui 作者: easydo-cn 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def render_navtree(navtree_data, node_template=None, load=False):
    load = load and 'true' or 'false'
    if node_template is None:
        node_template = '''<a href="{{href}}">{{title}}</a>'''

    m = md5()
    m.update(node_template + str(random.randrange(0, 100)))
    template_md5 = m.hexdigest()
    return '''<div id="nav_%(md5)s" class="navtree" kssattr:templ="templ_%(md5)s">
                  <script type="text/javascript">
                      var templ_%(md5)s = Handlebars.compile('%(template)s');
                      $('#nav_%(md5)s').html(render_navtree(%(json)s, templ_%(md5)s, %(load)s));
                  </script>
              </div>
           ''' % {'md5': template_md5,
                  'template': node_template.replace('\'', '\\\'').replace('\n', r'\n').replace('\r', r'\r'),
                  'json': json.dumps(navtree_data),
                  'load': load,
                  }
tabu2.py 文件源码 项目:pylspm 作者: lseman 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def stochasticTwoOpt(perm):
    result = perm[:]  # make a copy
    size = len(result)
    p1, p2 = random.randrange(0, size), random.randrange(0, size)
    exclude = set([p1])
    if p1 == 0:
        exclude.add(size - 1)
    else:
        exclude.add(p1 - 1)

    if p1 == size - 1:
        exclude.add(0)
    else:
        exclude.add(p1 + 1)

    while p2 in exclude:
        p2 = random.randrange(0, size)

    if p2 < p1:
        p1, p2 = p2, p1

    result[p1:p2] = reversed(result[p1:p2])

    return result
generator.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def _make_boundary(text=None):
    # Craft a random boundary.  If text is given, ensure that the chosen
    # boundary doesn't appear in the text.
    token = random.randrange(sys.maxint)
    boundary = ('=' * 15) + (_fmt % token) + '=='
    if text is None:
        return boundary
    b = boundary
    counter = 0
    while True:
        cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
        if not cre.search(text):
            break
        b = boundary + '.' + str(counter)
        counter += 1
    return b
bot.py 文件源码 项目:YeeBot 作者: jaspric 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def roll(ctx, *args):
    name = ctx.message.author.name
    args = args[0].lower().split('d')
    die = args[1]
    mod = args[0]
    results = []
    if mod:
        if die in ['4', '6', '8', '10', '12', '20', '100']:
            if int(mod) > 1 and int(mod) < 7:
                for x in range(0, int(mod)):
                    this_roll = random.randrange(1, int(die) + 1)
                    results.append(this_roll)
                results_string = ', '.join(str(x) for x in results)
                return await yeebot.say("{} rolled a d{} {} times and got `{}`!".format(name, die, mod, results_string))
            elif int(mod) == 1:
                result = str(random.randrange(1, int(die) + 1))
                return await yeebot.say("{} rolled a d{} and got `{}`!".format(name, die, result))
            else:
                return await yeebot.say("Please use the format: `!roll <1-6>d<4, 6, 8, 10, 12, 20, 100>` eg: `!roll 2d20`")
        else:
            return await yeebot.say("Please use the format: `!roll <1-6>d<4, 6, 8, 10, 12, 20, 100>` eg: `!roll 2d20`")
    else:
        return await yeebot.say("Please use the format: `!roll <1-6>d<4, 6, 8, 10, 12, 20, 100>` eg: `!roll 2d20`")
client.py 文件源码 项目:plugin.video.exodus 作者: lastship 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def randomagent():
    BR_VERS = [
        ['%s.0' % i for i in xrange(18, 50)],
        ['37.0.2062.103', '37.0.2062.120', '37.0.2062.124', '38.0.2125.101', '38.0.2125.104', '38.0.2125.111', '39.0.2171.71', '39.0.2171.95', '39.0.2171.99',
         '40.0.2214.93', '40.0.2214.111',
         '40.0.2214.115', '42.0.2311.90', '42.0.2311.135', '42.0.2311.152', '43.0.2357.81', '43.0.2357.124', '44.0.2403.155', '44.0.2403.157', '45.0.2454.101',
         '45.0.2454.85', '46.0.2490.71',
         '46.0.2490.80', '46.0.2490.86', '47.0.2526.73', '47.0.2526.80', '48.0.2564.116', '49.0.2623.112', '50.0.2661.86', '51.0.2704.103', '52.0.2743.116',
         '53.0.2785.143', '54.0.2840.71'],
        ['11.0'],
        ['8.0', '9.0', '10.0', '10.6']]
    WIN_VERS = ['Windows NT 10.0', 'Windows NT 7.0', 'Windows NT 6.3', 'Windows NT 6.2', 'Windows NT 6.1', 'Windows NT 6.0', 'Windows NT 5.1', 'Windows NT 5.0']
    FEATURES = ['; WOW64', '; Win64; IA64', '; Win64; x64', '']
    RAND_UAS = ['Mozilla/5.0 ({win_ver}{feature}; rv:{br_ver}) Gecko/20100101 Firefox/{br_ver}',
                'Mozilla/5.0 ({win_ver}{feature}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{br_ver} Safari/537.36',
                'Mozilla/5.0 ({win_ver}{feature}; Trident/7.0; rv:{br_ver}) like Gecko',
                'Mozilla/5.0 (compatible; MSIE {br_ver}; {win_ver}{feature}; Trident/6.0)']
    index = random.randrange(len(RAND_UAS))
    return RAND_UAS[index].format(win_ver=random.choice(WIN_VERS), feature=random.choice(FEATURES), br_ver=random.choice(BR_VERS[index]))
attack.py 文件源码 项目:alpha 作者: ArielHorwitz 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def point_damage(universe,target,dmg,bodypart,damage_type=None):
    bodypart = target.body.get_bodypart(bodypart)
    if bodypart is None:
        Common.debug(8,'No such bodypart! get_bodypart returned None')
        return False
    if bodypart.hp <= 0:
        if bodypart.size != 0:
            truth_about_death = bodypart_death(universe,target,bodypart,damage_type)
            Common.debug(9,'Bodypart found dead. Applying death mechanic')
            return truth_about_death
        else:
            Common.debug(8,'bodypart is a category. randomizing child')
            bodypart = bodypart.get_children()[random.randrange(bodypart.get_children().__len__())]
            if bodypart is None:
                Common.debug(8, 'No bodypart found, point attack missed!')
                return False

    damage_remainder = damage(target,dmg,bodypart,damage_type)
    if damage_remainder <= 0:
        truth_about_death = bodypart_death(universe,target,bodypart,damage_type)
    return True
search.py 文件源码 项目:robocup-soccer 作者: kengz 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def genetic_algorithm(population, fitness_fn, ngen=1000, pmut=0.0):
    """[Fig. 4.7]"""
    def reproduce(p1, p2):
        c = random.randrange(len(p1))
        return p1[:c] + p2[c:]

    for i in range(ngen):
        new_population = []
        for i in len(population):
            p1, p2 = random_weighted_selections(population, 2, fitness_fn)
            child = reproduce(p1, p2)
            if random.uniform(0,1) > pmut:
                child.mutate()
            new_population.append(child)
        population = new_population
    return argmax(population, fitness_fn)
search.py 文件源码 项目:robocup-soccer 作者: kengz 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def RandomGraph(nodes=range(10), min_links=2, width=400, height=300,
                                curvature=lambda: random.uniform(1.1, 1.5)):
    """Construct a random graph, with the specified nodes, and random links.
    The nodes are laid out randomly on a (width x height) rectangle.
    Then each node is connected to the min_links nearest neighbors.
    Because inverse links are added, some nodes will have more connections.
    The distance between nodes is the hypotenuse times curvature(),
    where curvature() defaults to a random number between 1.1 and 1.5."""
    g = UndirectedGraph()
    g.locations = {}
    ## Build the cities
    for node in nodes:
        g.locations[node] = (random.randrange(width), random.randrange(height))
    ## Build roads from each city to at least min_links nearest neighbors.
    for i in range(min_links):
        for node in nodes:
            if len(g.get(node)) < min_links:
                here = g.locations[node]
                def distance_to_node(n):
                    if n is node or g.get(node,n): return infinity
                    return distance(g.locations[n], here)
                neighbor = argmin(nodes, distance_to_node)
                d = distance(g.locations[neighbor], here) * curvature()
                g.connect(node, neighbor, int(d)) 
    return g
generator.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 46 收藏 0 点赞 0 评论 0
def _make_boundary(text=None):
    # Craft a random boundary.  If text is given, ensure that the chosen
    # boundary doesn't appear in the text.
    token = random.randrange(sys.maxint)
    boundary = ('=' * 15) + (_fmt % token) + '=='
    if text is None:
        return boundary
    b = boundary
    counter = 0
    while True:
        cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
        if not cre.search(text):
            break
        b = boundary + '.' + str(counter)
        counter += 1
    return b
recipe-577374.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def __init__(self):
    import random
    doors = {
             0: Door(1),
             1: Door(2),
             2: Door(3)}
    # random.randrange(startInt,endInt) generates a random integer in the range
    # of startInt (which is included in the possibilities) to endInt (which is
    # not included in the possibilities.
    prize_door = random.randrange(0,3)
    doors[prize_door].contents = "prize"
    doors[((prize_door + 1) % 3)].contents = "goat"
    doors[((prize_door + 2) % 3)].contents = "goat"

    self.keep_track = {"doors": doors,
                       "prize": doors[prize_door],
                       "selected": None,
                       "opened": None}
recipe-572196.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def getPrime(b,seed):
    #Generates an integer of b bits that is probably prime
    #written by Josiah Carlson
    #modified (heavily) and optimized by Collin Stocks
    bits=int(b)
    assert 64<=bits
    k=bits<<1
    possible=seed|1 # make it odd
    good=0
    while not good:
        possible+=2 # keep it odd
        good=1
        for i in smallprimes:
            if possible%i==0:
                good=0
                break
        else:
            for i in xrange(k):
                test=random.randrange(2,possible)|1
                if RabinMillerWitness(test,possible):
                    good=0
                    break
    return possible
page.py 文件源码 项目:v2ex-tornado-2 作者: coderyy 项目源码 文件源码 阅读 79 收藏 0 点赞 0 评论 0
def get(self):
        site = GetSite()
        template_values = {}
        template_values['site'] = site
        template_values['rnd'] = random.randrange(1, 100)
        note = GetKindByNum('Note', 127)
        if note is False:
            note = GetKindByNum('Note', 2)
        template_values['note'] = note
        member = CheckAuth(self)
        if member:
            template_values['member'] = member
        template_values['page_title'] = site.title + u' › About'
        l10n = GetMessages(self, member, site)
        template_values['l10n'] = l10n
        path = os.path.join(os.path.dirname(__file__), 'tpl', 'desktop')
        t=self.get_template(path, 'about.html')
        self.finish(t.render(template_values))
page.py 文件源码 项目:v2ex-tornado-2 作者: coderyy 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def get(self):
        site = GetSite()
        template_values = {}
        template_values['site'] = site
        template_values['rnd'] = random.randrange(1, 100)
        note = GetKindByNum('Note', 195)
        if note is False:
            note = GetKindByNum('Note', 4)
        template_values['note'] = note
        member = CheckAuth(self)
        if member:
            template_values['member'] = member
        template_values['page_title'] = site.title + u' › FAQ'
        l10n = GetMessages(self, member, site)
        template_values['l10n'] = l10n
        path = os.path.join(os.path.dirname(__file__), 'tpl', 'desktop')
        t=self.get_template(path,'faq.html')
        self.finish(t.render(template_values))
page.py 文件源码 项目:v2ex-tornado-2 作者: coderyy 项目源码 文件源码 阅读 45 收藏 0 点赞 0 评论 0
def get(self):
        site = GetSite()
        template_values = {}
        template_values['site'] = site
        template_values['rnd'] = random.randrange(1, 100)
        note = GetKindByNum('Note', 240)
        if note is False:
            note = GetKindByNum('Note', 5)
        template_values['note'] = note
        member = CheckAuth(self)
        if member:
            template_values['member'] = member
        template_values['page_title'] = site.title + u' › Mission'
        l10n = GetMessages(self, member, site)
        template_values['l10n'] = l10n
        path = os.path.join(os.path.dirname(__file__), 'tpl', 'desktop')
        t=self.get_template(path,'mission.html')
        self.finish(t.render(template_values))
sched.py 文件源码 项目:FRG-Crowdsourcing 作者: 97amarnathk 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def get_incremental_task(project_id, user_id=None, user_ip=None,
                         external_uid=None, offset=0, limit=1, orderby='id', desc=False):
    """Get a new task for a given project with its last given answer.

    It is an important strategy when dealing with large tasks, as
    transcriptions.
    """
    candidate_tasks = get_candidate_task_ids(project_id, user_id, user_ip,
                                                external_uid, limit, offset,
                                                orderby='priority_0', desc=True)
    total_remaining = len(candidate_tasks)
    if total_remaining == 0:
        return None
    rand = random.randrange(0, total_remaining)
    task = candidate_tasks[rand]
    # Find last answer for the task
    q = session.query(TaskRun)\
        .filter(TaskRun.task_id == task.id)\
        .order_by(TaskRun.finish_time.desc())
    last_task_run = q.first()
    if last_task_run:
        task.info['last_answer'] = last_task_run.info
        # TODO: As discussed in GitHub #53
        # it is necessary to create a lock in the task!
    return [task]
bst_dataset.py 文件源码 项目:CopyNet 作者: MultiPath 项目源码 文件源码 阅读 102 收藏 0 点赞 0 评论 0
def test(args=None, BSTtype=BST):
    import random, sys
    random.seed(19920206)
    if not args:
        args = sys.argv[1:]
    if not args:
        print 'usage: %s <number-of-random-items | item item item ...>' % \
              sys.argv[0]
        sys.exit()
    elif len(args) == 1:
        items = (random.randrange(100) for i in xrange(int(args[0])))
    else:
        items = [int(i) for i in args]

    tree   = BSTtype()
    source = []
    for item in items:
        tree.insert(item)
        source += [str(item)]
    print ' '.join(source)
    print tree
bst_dataset.py 文件源码 项目:CopyNet 作者: MultiPath 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def generate():
    import random, sys
    random.seed(19920206)

    Lmin   = 2 ** 2 - 1
    Lmax   = 2 ** 4 - 1
    Xnum   = 1000000
    voc    = 26

    wfile  = open('/home/thoma/Work/Dial-DRL/dataset/BST_1M.txt', 'w')
    for id in xrange(Xnum):
        tree   = BST()
        items  = (random.randrange(voc) for i in
                 xrange(random.randint(Lmin, Lmax)))
        source = []
        for item in items:
            item = chr(item + 65)
            tree.insert(item)
            source += [str(item)]
        source = ' '.join(source)
        target = str(tree)
        line   = '{0} -> {1}'.format(source, target)
        wfile.write(line + '\n')
        if id % 10000 == 0:
            print id
utilities.py 文件源码 项目:Ruby-Bot 作者: ahuei123456 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def randomize(rlist, repeat = 0, count = 1):
    fpick = rlist[:]
    play = list()

    if count == -1:
        count = len(fpick)

    for x in range(0, count):
        if repeat:
            play.append(fpick[random.randrange(len(fpick))])
        else:
            if len(fpick) > 0:
                play.append(fpick.pop(random.randrange(len(fpick))))
            else:
                break

    return play
iconui.py 文件源码 项目:zoocore 作者: dsparrow27 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def initUI(self):
        self.mainLayout = QtWidgets.QVBoxLayout(self)
        self.scrollArea = QtWidgets.QScrollArea(parent=self)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setFrameStyle(QtWidgets.QFrame.NoFrame)
        self.scrollArea.setFrameShadow(QtWidgets.QFrame.Plain)
        self.scrollWidget = QtWidgets.QWidget()
        self.scrollLayout = flowlayout.FlowLayout()

        self.scrollWidget.setLayout(self.scrollLayout)
        self.scrollArea.setWidget(self.scrollWidget)
        self.mainLayout.addWidget(self.scrollArea)
        self.setLayout(self.mainLayout)
        for i in iconlib.Icon.iconCollection:
            colorRandom = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255))
            btn = QtWidgets.QToolButton(parent=self)
            icon = iconlib.Icon.iconColorized(i, size=256, color=colorRandom)
            btn.setIcon(icon)
            btn.setText(i)
            btn.clicked.connect(self.copyNameToClipboard)
            self.scrollLayout.addWidget(btn)
make-input-file.py 文件源码 项目:pheweb 作者: statgen 项目源码 文件源码 阅读 44 收藏 0 点赞 0 评论 0
def make_pheno(pheno_name, use_maf, use_af, use_ac, use_ns):

    ns = random.randrange(100, 10_000)
    num_chromosomes = ns*2

    with TSVWriter(f'input_files/assoc-files/{pheno_name}.txt') as writer:

        for v in variants:
            if v['chrom'] == '1' and v['pos'] == 869334 or random.random() < 100 / len(variants):

                d = dict(
                    chrom=v['chrom'],
                    pos=v['pos'],
                    ref=v['ref'],
                    alt=v['alt'],
                    pval=format_float(random.random()),
                )
                ac = random.randrange(0,num_chromosomes+1) # allow MAF=0 b/c I'm sure somebody will.
                af = ac / num_chromosomes
                if use_maf: d['maf'] = format_float(min(af, 1-af))
                if use_af: d['af'] = format_float(af)
                if use_ac: d['ac'] = ac
                if use_ns: d['ns'] = ns

                writer.writerow(d)
sites.py 文件源码 项目:pheweb 作者: statgen 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def put_task(self, taskq):
        if self.n_procs == 1 and len(self.files) == 1 and self.files[0]['type'] == 'merged':
            # ALL DONE!
            self.n_procs -= 1
            taskq.put({'exit':True})
            return 'ALLDONE'
        elif len(self.files) == 0:
            # NO WORK, TERMINATE WORKER
            self.n_procs -= 1
            taskq.put({'exit':True})
        elif self.n_procs > 1 and len(self.files) < MIN_NUM_FILES_TO_MERGE_AT_ONCE:
            # INSUFFICIENT WORK, TERMINATE WORKER
            self.n_procs -= 1
            taskq.put({'exit':True})
        else:
            # MAKE A TASK FOR THE WORKER
            files_to_merge = self.files[:MAX_NUM_FILES_TO_MERGE_AT_ONCE]
            self.files =     self.files[MAX_NUM_FILES_TO_MERGE_AT_ONCE:]
            out_filepath = get_tmp_path('merging-{}'.format(random.randrange(1e10)))
            taskq.put({
                'files_to_merge': files_to_merge,
                'out_filepath': out_filepath,
            })
play_holdem.py 文件源码 项目:learning-texas-holdem 作者: gjgregory 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _cpu_move(self):
        """Performs a move by the AI."""
        #self.game.call(self.cpu)
        decision = random.randrange(4)
        if decision == 1 and self.game.lastraise == 0: #shouldn't call. check instead.
            decision = 0
        elif decision == 0 and self.cpu.bid < self.game.lastraise: #can't check. call instead.
            decision = 1
        if decision == 0:
            self.game.check(self.cpu)
            self._set_text(self.prompt, self.cpu.name + " checked.")
        elif decision == 1:
            self.game.call(self.cpu)
            self._set_text(self.prompt, self.cpu.name + " called.")
        elif decision >= 2:
            bid_amount = random.randrange(self.game.lastraise, self.game.lastraise*2+1)
            bid_amount += 50 - (bid_amount % 50)
            self.game.make_bid(self.cpu, bid_amount)
            self._set_text(self.prompt, self.cpu.name + " raised the bet to " \
                    + locale.format("%d", self.game.bid, grouping=True) + ".")

        self._update_display(False)
        if self.game.is_next(self.cpu) and not self.game.finished:
            self._cpu_move()
test_torch.py 文件源码 项目:pytorch-dist 作者: apaszke 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def test_scatter(self):
        m, n, o = random.randint(10, 20), random.randint(10, 20), random.randint(10, 20)
        elems_per_row = random.randint(1, 10)
        dim = random.randrange(3)

        idx_size = [m, n, o]
        idx_size[dim] = elems_per_row
        idx = torch.LongTensor().resize_(*idx_size)
        self._fill_indices(idx, dim, ([m, n, o])[dim], elems_per_row, m, n, o)
        src = torch.Tensor().resize_(*idx_size).normal_()

        actual = torch.zeros(m, n, o).scatter_(dim, idx, src)
        expected = torch.zeros(m, n, o)
        for i in range(idx_size[0]):
            for j in range(idx_size[1]):
                for k in range(idx_size[2]):
                    ii = [i, j, k]
                    ii[dim] = idx[i,j,k]
                    expected[tuple(ii)] = src[i,j,k]
        self.assertEqual(actual, expected, 0)

        idx[0][0][0] = 34
        self.assertRaises(RuntimeError, lambda: torch.zeros(m, n, o).scatter_(dim, idx, src))
test_torch.py 文件源码 项目:pytorch-dist 作者: apaszke 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def test_scatterFill(self):
        m, n, o = random.randint(10, 20), random.randint(10, 20), random.randint(10, 20)
        elems_per_row = random.randint(1, 10)
        dim = random.randrange(3)

        val = random.random()
        idx_size = [m, n, o]
        idx_size[dim] = elems_per_row
        idx = torch.LongTensor().resize_(*idx_size)
        self._fill_indices(idx, dim, ([m, n, o])[dim], elems_per_row, m, n, o)

        actual = torch.zeros(m, n, o).scatter_(dim, idx, val)
        expected = torch.zeros(m, n, o)
        for i in range(idx_size[0]):
            for j in range(idx_size[1]):
                for k in range(idx_size[2]):
                    ii = [i, j, k]
                    ii[dim] = idx[i,j,k]
                    expected[tuple(ii)] = val
        self.assertEqual(actual, expected, 0)

        idx[0][0][0] = 28
        self.assertRaises(RuntimeError, lambda: torch.zeros(m, n, o).scatter_(dim, idx, val))
test_questionnaire.py 文件源码 项目:questionnaire 作者: kylebebak 项目源码 文件源码 阅读 132 收藏 0 点赞 0 评论 0
def test_questionnaire(self):
        q = Questionnaire()
        q.add('k', prompter=lambda prompt: 'v')
        q.run()
        self.assertEqual(q.answers['k'], 'v')

        q.add('k2', prompter=lambda prompt: 'v2_first').condition(('k', 'v_'))
        q.add('k2', prompter=lambda prompt: 'v2_second').condition(('k', 'v'))
        q.ask()
        self.assertEqual(q.answers['k2'], 'v2_second')
        self.assertEqual(len(q.answers), 2)

        q.add('k3', prompter=lambda prompt: randrange(10)).validate(
            lambda a: None if a == 0 else 'error'
        ).transform(lambda a: a-1)
        q.ask()
        self.assertEqual(q.answers['k3'], -1)

        q.reset()
        self.assertEqual(dict(q.answers), {})
test_reflector.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def randomizeRow(row, nulls_ok=True, trailing_spaces_ok=True):
    values = {}
    for name, type in row.rowColumns:
        if util.getKeyColumn(row, name):
            values[name] = getattr(row, name)
            continue
        elif nulls_ok and random.randint(0, 9) == 0:
            value = None # null
        elif type == 'int':
            value = random.randint(-10000, 10000)
        else:
            if random.randint(0, 9) == 0:
                value = ''
            else:
                value = ''.join(map(lambda i:chr(random.randrange(32,127)),
                                    xrange(random.randint(1, 64))))
            if not trailing_spaces_ok:
                value = value.rstrip()
        setattr(row, name, value)
        values[name] = value
    return values
generator.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def _make_boundary(text=None):
    # Craft a random boundary.  If text is given, ensure that the chosen
    # boundary doesn't appear in the text.
    token = random.randrange(sys.maxint)
    boundary = ('=' * 15) + (_fmt % token) + '=='
    if text is None:
        return boundary
    b = boundary
    counter = 0
    while True:
        cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
        if not cre.search(text):
            break
        b = boundary + '.' + str(counter)
        counter += 1
    return b
uuid.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 41 收藏 0 点赞 0 评论 0
def uuid4():
    """Generate a random UUID."""

    # When the system provides a version-4 UUID generator, use it.
    if _uuid_generate_random:
        _buffer = ctypes.create_string_buffer(16)
        _uuid_generate_random(_buffer)
        return UUID(bytes=_buffer.raw)

    # Otherwise, get randomness from urandom or the 'random' module.
    try:
        import os
        return UUID(bytes=os.urandom(16), version=4)
    except:
        import random
        bytes = [chr(random.randrange(256)) for i in range(16)]
        return UUID(bytes=bytes, version=4)
MIMEAttachment.py 文件源码 项目:vspheretools 作者: devopshq 项目源码 文件源码 阅读 43 收藏 0 点赞 0 评论 0
def _make_boundary(text=None):
    #some code taken from python stdlib
    # Craft a random boundary.  If text is given, ensure that the chosen
    # boundary doesn't appear in the text.
    token = random.randrange(sys.maxint)
    boundary = ('=' * 10) + (_fmt % token) + '=='
    if text is None:
        return boundary
    b = boundary
    counter = 0
    while True:
        cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
        if not cre.search(text):
            break
        b = boundary + '.' + str(counter)
        counter += 1
    return b


问题


面经


文章

微信
公众号

扫码关注公众号