Python random.randrange() Examples

The following are code examples for showing how to use random.randrange(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: nweb   Author: pierce403   File: models_sqlite.py    (license) View Source Project 7 votes vote down vote up
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) 
Example 2
Project: easydo-ui   Author: easydo-cn   File: components.py    (Apache License 2.0) View Source Project 7 votes vote down vote up
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,
                  } 
Example 3
Project: pylspm   Author: lseman   File: tabu2.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 4
Project: kinect-2-libras   Author: inessadl   File: utils.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <[email protected]>

    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.
    """
    timeval = time.time()
    utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
    pid = os.getpid()
    randint = random.randrange(100000)
    if idstring is None:
        idstring = ''
    else:
        idstring = '.' + idstring
    idhost = socket.getfqdn()
    msgid = '<%s.%s.%s%[email protected]%s>' % (utcdate, pid, randint, idstring, idhost)
    return msgid



# These functions are in the standalone mimelib version only because they've
# subsequently been fixed in the latest Python versions.  We use this to worm
# around broken older Pythons. 
Example 5
Project: YeeBot   Author: jaspric   File: bot.py    (MIT License) View Source Project 6 votes vote down vote up
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`") 
Example 6
Project: plugin.video.exodus   Author: lastship   File: client.py    (license) View Source Project 6 votes vote down vote up
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])) 
Example 7
Project: alpha   Author: ArielHorwitz   File: attack.py    (license) View Source Project 6 votes vote down vote up
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 
Example 8
Project: robocup-soccer   Author: kengz   File: search.py    (MIT License) View Source Project 6 votes vote down vote up
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) 
Example 9
Project: robocup-soccer   Author: kengz   File: search.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 10
Project: Flask_Blog   Author: sugarguo   File: generator.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 11
Project: Flask_Blog   Author: sugarguo   File: utils.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <[email protected]>

    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.
    """
    timeval = time.time()
    utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
    pid = os.getpid()
    randint = random.randrange(100000)
    if idstring is None:
        idstring = ''
    else:
        idstring = '.' + idstring
    idhost = socket.getfqdn()
    msgid = '<%s.%s.%s%[email protected]%s>' % (utcdate, pid, randint, idstring, idhost)
    return msgid



# These functions are in the standalone mimelib version only because they've
# subsequently been fixed in the latest Python versions.  We use this to worm
# around broken older Pythons. 
Example 12
Project: code   Author: ActiveState   File: recipe-577374.py    (MIT License) View Source Project 6 votes vote down vote up
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} 
Example 13
Project: code   Author: ActiveState   File: recipe-572196.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 14
Project: v2ex-tornado-2   Author: coderyy   File: page.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
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)) 
Example 15
Project: v2ex-tornado-2   Author: coderyy   File: page.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
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)) 
Example 16
Project: v2ex-tornado-2   Author: coderyy   File: page.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
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)) 
Example 17
Project: FRG-Crowdsourcing   Author: 97amarnathk   File: sched.py    (GNU Affero General Public License v3.0) View Source Project 6 votes vote down vote up
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] 
Example 18
Project: CopyNet   Author: MultiPath   File: bst_dataset.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 19
Project: CopyNet   Author: MultiPath   File: bst_dataset.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 20
Project: Ruby-Bot   Author: ahuei123456   File: utilities.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 21
Project: zoocore   Author: dsparrow27   File: iconui.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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) 
Example 22
Project: pheweb   Author: statgen   File: make-input-file.py    (MIT License) View Source Project 6 votes vote down vote up
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) 
Example 23
Project: pheweb   Author: statgen   File: sites.py    (MIT License) View Source Project 6 votes vote down vote up
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,
            }) 
Example 24
Project: learning-texas-holdem   Author: gjgregory   File: play_holdem.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 25
Project: pytorch-dist   Author: apaszke   File: test_torch.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 26
Project: pytorch-dist   Author: apaszke   File: test_torch.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 27
Project: questionnaire   Author: kylebebak   File: test_questionnaire.py    (license) View Source Project 6 votes vote down vote up
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), {}) 
Example 28
Project: hostapd-mana   Author: adde88   File: test_reflector.py    (license) View Source Project 6 votes vote down vote up
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 
Example 29
Project: hostapd-mana   Author: adde88   File: generator.py    (license) View Source Project 6 votes vote down vote up
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 
Example 30
Project: hostapd-mana   Author: adde88   File: utils.py    (license) View Source Project 6 votes vote down vote up
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <[email protected]>

    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.
    """
    timeval = time.time()
    utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
    pid = os.getpid()
    randint = random.randrange(100000)
    if idstring is None:
        idstring = ''
    else:
        idstring = '.' + idstring
    idhost = socket.getfqdn()
    msgid = '<%s.%s.%s%[email protected]%s>' % (utcdate, pid, randint, idstring, idhost)
    return msgid



# These functions are in the standalone mimelib version only because they've
# subsequently been fixed in the latest Python versions.  We use this to worm
# around broken older Pythons. 
Example 31
Project: hostapd-mana   Author: adde88   File: uuid.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 32
Project: vspheretools   Author: devopshq   File: MIMEAttachment.py    (license) View Source Project 6 votes vote down vote up
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 
Example 33
Project: jMetalPy   Author: jMetal   File: selection.py    (license) View Source Project 6 votes vote down vote up
def execute(self, solution_list: List[S]) -> S:
        if solution_list is None:
            raise Exception("The solution list is null")
        elif len(solution_list) == 0:
            raise Exception("The solution is empty")
        elif not self.comparator_list:
            raise Exception("The list of comparators is empty")

        winner = None

        if len(solution_list) == 1:
            winner = solution_list[0]
        else:
            for comparator in self.comparator_list:
                winner = self.__winner(solution_list, comparator)
                if winner is not None:
                    break

        if not winner:
            i = random.randrange(0, len(solution_list))
            winner = solution_list[i]

        return winner 
Example 34
Project: Maps   Author: DarkPurple141   File: name_gen.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def generate_name():
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    wordlist = []

    with open ("words", 'r') as fo:
        for word in fo:
            if len(word) < 5:
                continue
            else:
                wordlist.append(word.strip())

    namelength = random.randrange(4)
    pref = random.choice(wordlist)[0:3]
    pref = pref[0].upper() + pref[1:3]

    if random.random() > 0.5:
        suff = random.choice(wordlist)[-3:]
    else:
        suff = random.choice(wordlist)[:3]

    for i in range(namelength):
        pref = pref + random.choice(alphabet)

    name = pref + suff

    return name 
Example 35
Project: Maps   Author: DarkPurple141   File: geom.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def main():
    xp = []
    yp = []
    for i in range(3):
        xp.append(random.randrange(15))
        yp.append(random.randrange(15))

    points = []

    for i in range(3):
        points.append(Point(xp.pop(),yp.pop()))

    print([i.get_cords() for i in points])

    tri = Triangle(points.pop(),points.pop(),points.pop())

    mid = tri.centre()

    for y in range(15):
        for x in range(15):
            if (tri.a.x == x and tri.a.y == y):
                print('A',end="")
            elif (tri.b.x == x and tri.b.y == y):
                print('B',end="")
            elif (tri.c.x == x and tri.c.y == y):
                print('C',end="")
            elif (mid.x == x and mid.y == y):
                print(" .",end="")
            else:
                print(" ",end="")
        print("") 
Example 36
Project: Maps   Author: DarkPurple141   File: voronoi.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def __init__(self, location, name="default"):
        self.name = name
        self.location = location
        self.owner = random.randrange(10) 
Example 37
Project: Maps   Author: DarkPurple141   File: voronoi.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def __init__(self,seed):
        random.seed(seed)
        self.ISLAND_FACTOR = 1.13 # 1.0 means no small islands; 2.0 leads to a lot
        self.bumps = random.randrange(1,7)
        self.startAngle = random.uniform(0,2*math.pi)
        self.dipAngle = random.uniform(0,2*math.pi)
        self.dipWidth = random.uniform(0.2,0.7) 
Example 38
Project: myhdlpeek   Author: xesscorp   File: test1.py    (MIT License) View Source Project 5 votes vote down vote up
def test():
    for i in range(8):
        a.next, b.next, sel.next = randrange(8), randrange(8), randrange(2)
        yield delay(2) 
Example 39
Project: pylspm   Author: lseman   File: pso.py    (MIT License) View Source Project 5 votes vote down vote up
def __init__(self, data_, n_clusters):
        self.position = []
        if not self.position:
            for i in range(len(data_)):
                self.position.append(random.randrange(n_clusters))
        print(self.position)

        self.velocity = [0 for clusterPoint in self.position]
        self.S = [0 for clusterPoint in self.position]
        self.best = deepcopy(self.position)
        self.bestfit = 0 
Example 40
Project: pylspm   Author: lseman   File: gac.py    (MIT License) View Source Project 5 votes vote down vote up
def __init__(self, data_, n_clusters, genes):
        self.genes = genes
        if not self.genes:
            for i in range(len(data_)):
                self.genes.append(random.randrange(n_clusters)) 
Example 41
Project: pylspm   Author: lseman   File: gac.py    (MIT License) View Source Project 5 votes vote down vote up
def mutation(self, pmut, n_clusters):
        for g, gene in enumerate(self.genes):
            if uniform(0, 1) <= pmut:
                oldgene = self.genes[g]
                # garante mutation diferente
                while self.genes[g] == oldgene:
                    self.genes[g] = random.randrange(n_clusters) 
Example 42
Project: python-   Author: secondtonone1   File: 2048.py    (license) View Source Project 5 votes vote down vote up
def spawn(self):
        new_element = 4 if randrange(100) > 89 else 2
        (i,j) = choice([(i,j) for i in range(self.width) for j in range(self.height) if self.field[i][j] == 0])
        self.field[i][j] = new_element 
Example 43
Project: RunescapeBots   Author: lukegarbutt   File: realmouse.py    (license) View Source Project 5 votes vote down vote up
def move(xe, ye, button):
	global mouseSpeed

	if button != (1 or 2):
		return

	ms = mouseSpeed
	randSpeed = (random.randrange(mouseSpeed) / 2.0 + mouseSpeed) / 10.0
	# get Cur mouse position
	xs,ys = pyautogui.position()

	humanWindMouse(xs, ys, xe, ye, 1, 5, 10.0/randSpeed, 15.0/randSpeed, 10.0*randSpeed)
	mouseSpeed = ms
	# click here.  Add Code 
Example 44
Project: ToeBot   Author: barkdong123   File: TicTacToe.py    (license) View Source Project 5 votes vote down vote up
def set_random_action(self):
        self.random_action = random.randrange(0,8+1) 
Example 45
Project: easydo-ui   Author: easydo-cn   File: components.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def dnd(self):
        self._dnd = True
        if not self.id:
            self.id = 'grid-%d' % random.randrange(0, 9999)
        return self 
Example 46
Project: easydo-ui   Author: easydo-cn   File: components.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def add_tab(self, link, panel, id=''):
        if not id:
            id = 'tab-%s' % random.randrange(0, 9999)
        else:
            id = 'tab-%s' % id

        link.klass.append('node')
        link.attr['href'] = '#%s-%s' % (id, random.randrange(0, 9999))
        tab = '<li id="tab-%s">%s</li>' % (id, link.html())

        self.kss._append_script("%s.find('.tabs').append(%s)" % (self.kss._selector, self.kss._escape_value(tab)), False, False)
        self.kss.append('<div id="%s" class="tabBody hidden">%s</div>' % (link.attr['href'][1:], panel.html())) 
Example 47
Project: kinect-2-libras   Author: inessadl   File: urllib2.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def randombytes(n):
    """Return n random bytes."""
    # Use /dev/urandom if it is available.  Fall back to random module
    # if not.  It might be worthwhile to extend this function to use
    # other platform-specific mechanisms for getting random bytes.
    if os.path.exists("/dev/urandom"):
        f = open("/dev/urandom")
        s = f.read(n)
        f.close()
        return s
    else:
        L = [chr(random.randrange(0, 256)) for i in range(n)]
        return "".join(L) 
Example 48
Project: kinect-2-libras   Author: inessadl   File: generator.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
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 
Example 49
Project: kinect-2-libras   Author: inessadl   File: uuid.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def _random_getnode():
    """Get a random node ID, with eighth bit set as suggested by RFC 4122."""
    import random
    return random.randrange(0, 1<<48L) | 0x010000000000L 
Example 50
Project: kinect-2-libras   Author: inessadl   File: uuid.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def uuid1(node=None, clock_seq=None):
    """Generate a UUID from a host ID, sequence number, and the current time.
    If 'node' is not given, getnode() is used to obtain the hardware
    address.  If 'clock_seq' is given, it is used as the sequence number;
    otherwise a random 14-bit sequence number is chosen."""

    # When the system provides a version-1 UUID generator, use it (but don't
    # use UuidCreate here because its UUIDs don't conform to RFC 4122).
    if _uuid_generate_time and node is clock_seq is None:
        _buffer = ctypes.create_string_buffer(16)
        _uuid_generate_time(_buffer)
        return UUID(bytes=_buffer.raw)

    global _last_timestamp
    import time
    nanoseconds = int(time.time() * 1e9)
    # 0x01b21dd213814000 is the number of 100-ns intervals between the
    # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
    timestamp = int(nanoseconds//100) + 0x01b21dd213814000L
    if _last_timestamp is not None and timestamp <= _last_timestamp:
        timestamp = _last_timestamp + 1
    _last_timestamp = timestamp
    if clock_seq is None:
        import random
        clock_seq = random.randrange(1<<14L) # instead of stable storage
    time_low = timestamp & 0xffffffffL
    time_mid = (timestamp >> 32L) & 0xffffL
    time_hi_version = (timestamp >> 48L) & 0x0fffL
    clock_seq_low = clock_seq & 0xffL
    clock_seq_hi_variant = (clock_seq >> 8L) & 0x3fL
    if node is None:
        node = getnode()
    return UUID(fields=(time_low, time_mid, time_hi_version,
                        clock_seq_hi_variant, clock_seq_low, node), version=1)