Пример #1
0
def m4k3_r4nd_1p4ddr(num):
    h0sts = []
    for x in range(int(num)):
        h0sts.append('%d.%d.%d.%d' % (random.randrange(0,255),
                random.randrange(0,255), random.randrange(0,255),
                random.randrange(0,255)))
    return h0sts
def show_example():
	# Configurable parameters
	field = fieldmath.BinaryField(0x11D)
	generator = 0x02
	msglen = 8
	ecclen = 5
	rs = reedsolomon.ReedSolomon(field, generator, msglen, ecclen)
	
	# Generate random message
	message = [random.randrange(field.size) for _ in range(msglen)]
	print("Original message: {}".format(message))
	
	# Encode message to produce codeword
	codeword = rs.encode(message)
	print("Encoded codeword: {}".format(codeword))
	
	# Perturb some values in the codeword
	probability = float(ecclen // 2) / (msglen + ecclen)
	perturbed = 0
	for i in range(len(codeword)):
		if random.random() < probability:
			codeword[i] ^= random.randrange(1, field.size)
			perturbed += 1
	print("Number of values perturbed: {}".format(perturbed))
	print("Perturbed codeword: {}".format(codeword))
	
	# Try to decode the codeword
	decoded = rs.decode(codeword)
	print("Decoded message: {}".format(decoded if (decoded is not None) else "Failure"))
	print("")
Пример #3
0
def lootRoom():
    global life
    global clownattack
    runAway = False
    loot = raw_input("Loot this Room? (Y/N)\n")
    if(str.upper(loot) == "Y"):
        foundItem = supplies[random.randrange(0, len(supplies)-1)]
        foundWeapon = weapon.keys()[random.randrange(1, len(weapon)-1)]
        clowns = random.randrange(0, 2)
        print(str(clowns) + " clowns found in room.")
        if clowns != 0:
            attack = raw_input("Attack or Run? (A/R)\n")
            if str.upper(attack) == "A":
                hit = clowns * (hitMultiplier[random.randrange(0, len(hitMultiplier)-4)])
                life = life - hit
                print (str(clowns) + " clowns attacked you, and you killed them with your " + str(myWeapons[0]) + "\nLife health is now " + str(life))
            else:
                runAway = True
                print("You run away quietly, with no cool stuff.")
        else:
            print ("The room is empty of clowns, but full of cool stuff...")
        if (runAway != True):
            takeItem = raw_input("You found a " + foundItem + "\nEquip? (Y/N)")
            takeWeapon = raw_input("Cool! You found a " + foundWeapon + "\nEquip? (Y/N)")
            if str.upper(takeWeapon) == "Y": myWeapons.insert(0, foundWeapon)
            if str.upper(takeItem) == "Y": inventory[foundItem] += 1
            print ("Current weapon: " + str(myWeapons[0]))
            print ("Destruction power: " + str(weapon[myWeapons[0]]))
            print("Inventory:\n==========")
            for item in inventory:
                if(inventory[item] > 0):
                    print (item + ": " + str(inventory[item]))
            print("\n")
Пример #4
0
def draw(cmds, size=2): #output tree
    stack = []
    for cmd in cmds:
        if cmd=='F':
            turtle.forward(size)
        elif cmd=='-':
            t = random.randrange(0,7,1)
            p = ["Red","Green","Blue","Grey","Yellow","Pink","Brown"]
            turtle.color(p[t])
            turtle.left(15) #slope left
        elif cmd=='+':
            turtle.right(15) #slope right
            t = random.randrange(0,7,1) #рандомная пер. для цвета
            p = ["Red","Green","Blue","Grey","Yellow","Pink","Brown"] #ряд цветов
            turtle.color(p[t]) #выбор цвета из ряда
        elif cmd=='X':
            pass
        elif cmd=='[':
            stack.append((turtle.position(), turtle.heading()))
        elif cmd==']':
            position, heading = stack.pop()
            turtle.penup()
            turtle.setposition(position)
            turtle.setheading(heading)  
            turtle.pendown()
    turtle.update()
Пример #5
0
    def generate_picture(self, file_name="image.png"):
        size = list(self.destination.size)
        if size[0] > 700:
            aspect = size[1] / float(size[0])
            size[0] = 600
            size[1] = int(600 * aspect)
            self.destination = self.destination.resize(
                    size, Image.BILINEAR).convert('RGB')

        # fit the pallet to the destination image
        self.palette = self.palette.resize(size, Image.NEAREST).convert('RGB')
        self.destination.paste(self.palette, (0, 0))

        # randomly switch two pixels if they bring us closer to the image
        for i in xrange(500000):
            first = (random.randrange(0, self.destination.size[0]),
                     random.randrange(0, self.destination.size[1]))
            second = (random.randrange(0, self.destination.size[0]),
                      random.randrange(0, self.destination.size[1]))

            original_first = self.original.getpixel(first)
            original_second = self.original.getpixel(second)

            dest_first = self.destination.getpixel(first)
            dest_second = self.destination.getpixel(second)

            if color_diff(original_first, dest_first) + \
                    color_diff(original_second, dest_second) > \
                    color_diff(original_first, dest_second) + \
                    color_diff(original_second, dest_first):
                self.destination.putpixel(first, dest_second)
                self.destination.putpixel(second, dest_first)

        self.destination.save(file_name)
        return file_name
Пример #6
0
def main():
    tList = []
    head = 0
    numTurtles = 10
    wn = turtle.Screen()
    wn.setup(500,500)
    
    for i in range(numTurtles):
        nt = turtle.Turtle()   # Make a new turtle, initialize values
        nt.setheading(head)
        nt.pensize(2)
        nt.color(random.randrange(256), \
                random.randrange(256), \
                random.randrange(256))
        nt.speed(10)
        wn.tracer(30,0)
        tList.append(nt)       # Add the new turtle to the list
        head = head + 360/numTurtles

    for i in range(100):
        moveTurtles(tList,15,i)

    w = tList[0]
    w.up()
    w.goto(0,40)
    w.write("How to Think Like a ",True,"center","40pt Bold")
    w.goto(0,-35)
    w.write("Computer Scientist",True,"center","40pt Bold")
Пример #7
0
def fightClowns(clowns):
    global life
    global hit

    if clowns != 0:
        print(str(clowns) + " clowns stagger towards you. Ready your " + str.lower(myWeapons[0]) + "!\n")
        attack = raw_input("Attack, or Run? (A for attack, R for run)\n")
        if (str.upper(attack) == "A"):
            print(str(clowns) + " clowns attacked you!")
            life = life - clownattack*clowns
            hit = (hitMultiplier[random.randrange(0, len(hitMultiplier))]*weapon[myWeapons[0]])
            if hit != 0:
                print("You successfully killed them!")
                print("Your life is now: " + str(life))
            if (hit == 0):
                print("That was a lucky miss. Next time you should attack! (You successfully runned)")
                return 0
        elif str.upper(attack) == "R":
              stumblee = random.randrange(0, 2)
              stumble = random.randrange(1, 7)
              if stumblee > 0:
                  print("Run away from the zombies, you have stumbled and lost " + str(stumble) + " hp")
                  life = life - stumble
              else:
                  print("Nothing was happened.")
    elif clowns == 0:
         print ("But Nobody Came!")
    else:
        hit = (hitMultiplier[random.randrange(0, len(hitMultiplier))]*weapon[myWeapons[0]])
        if hit > 0:
            life = life - clownattack
        print (str(clowns) + " attack you, but you killed them\n" "Life health is now " + str(life))
Пример #8
0
def getParents(children, k, lamda):
    parents = []
    if randomParent == "True":
        for i in range(0, lamda):
            parents.append(children[random.randrange(0, len(children))])
            
    elif parentTournament == "True":
        for j in range(0, lamda):  
            tournament = []
            for i in range(0, k):
                tournament.append(children[random.randrange(0, len(children))])

            fittestIndex = getFittest(tournament)
            parents.append(tournament[fittestIndex])

    else:
        totalFitness = int(sumOfFitness(children))
        for i in range(lamda):
            randomFitness = random.randrange(0, totalFitness)
            counter = 0
            for child in children:
                counter+=child.fitness
                if counter >= randomFitness:
                    parents.append(child)
                    break
    return parents
Пример #9
0
def test_random_addition_and_slicing():
    seed = random.randrange(10000)
    print seed
    random.seed(seed)
    st = "abc"
    curr = LiteralStringNode(st)
    last = None
    all = []
    for i in range(1000):
        a = (chr(random.randrange(ord('a'), ord('z') + 1)) *
                random.randrange(500))
        last = curr
        all.append(curr)
        c = random.choice([0, 1, 2])
        if c == 0:
            curr = curr + LiteralStringNode(a)
            st = st + a
        elif c == 1:
            curr = LiteralStringNode(a) + curr
            st = a + st
        else:
            if len(st) < 10:
                continue
            # get a significant portion of the string
            #import pdb; pdb.set_trace()
            start = random.randrange(len(st) // 3)
            stop = random.randrange(len(st) // 3 * 2, len(st))
            curr = getslice_one(curr, start, stop)
            st = st[start: stop]
        assert curr.flatten_string() == st
    curr = curr.rebalance()
    assert curr.flatten_string() == st
    def _spawn_character(self, character, side):

        max_x = 0
        max_y = 0
        min_x = 0
        min_y = 0

        if side == TEAM_GOODGUYS:
            max_x = (self.size_x/2) - 1
            max_y = (self.size_y/2) - 1

            min_x = 0
            min_y = 0
        else:
            max_x = self.size_x
            max_y = self.size_y

            min_x = (self.size_x/2) + 1
            min_y = (self.size_y/2) + 1

        rand_x = randrange(max_x, min_x)
        rand_y = randrange(max_y, min_y)

        if not self._has_character_on_board(character.unique_id) and self._is_slot_free(rand_x, rand_y):
            character.x = rand_x
            character.y = rand_y
            self.boardBody[rand_x][rand_y] = character
        else:
            print('Character already on board or slot is not free')
Пример #11
0
def run_command(command, info):
    if settings.WORKERS_USE_TOR:
        # Initialize and use tor proxy
        socks_port = random.randrange(50000, 60000)
        control_port = random.randrange(50000, 60000)
        directory = '/tmp/%s' % uuid.uuid1()
        os.makedirs(directory)

        # Port collision? Don't worry about that.
        tor_command = "tor --SOCKSPort %s --ControlPort %s --DataDirectory %s" % (socks_port, control_port, directory)
        print "Executing tor command: %s" % tor_command
        tor_command = shlex.split(tor_command)
        proc = subprocess.Popen(tor_command, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

        while proc.poll() is None:
            output = proc.stdout.readline()
            if 'Bootstrapped 100%: Done.' in output:
                print 'We have a working connection!'
                break

        command += ' --proxy="127.0.0.1:%s" --proxy-type="socks5"' % socks_port

    j = Job(run_command.request.id, info)
    result = j.run(command)
    j.finish(result)

    if settings.WORKERS_USE_TOR:
        proc.kill()
        shutil.rmtree(directory)
Пример #12
0
def sampleQuizzes(num_trials):
    """Problem 5.1
    You are taking a class that plans to assign final grades based on two 
    midterm quizzes and a final exam. The final grade will be based on 25% for
    each midterm, and 50% for the final. You are told that the grades on the 
    exams were each uniformly distributed integers:
    Midterm 1: 50 <= grade <= 80
    Midterm 2: 60 <= grade <= 90
    Final Exam: 55 <= grade <= 95
    
    Write a function called sampleQuizzes that implements a Monte Carlo 
    simulation that estimates the probability of a student having a final
    score >= 70 and <= 75. Assume that 10,000 trials are sufficient to provide 
    an accurate answer.
    """
    in_range = 0  
    # as per spec
    mid1_low, mid1_high = 50, 80
    mid2_low, mid2_high = 60, 90
    fin_low, fin_high = 55, 95
    for trials in range(num_trials):
        grade = .25 * random.randrange(mid1_low, mid1_high + 1) +          \
                .25 * random.randrange(mid2_low, mid2_high + 1) +          \
                .50 * random.randrange(fin_low, fin_high + 1) 
        if 70 <= grade <= 75:
            in_range += 1
    # P(totG) with 70 <= totG <= 75 is simply in_range / num_trials ratio
    return in_range / float(num_trials)
Пример #13
0
def createBridge(numOfNodes, edgeProb, bridgeNodes):
	'''
	numOfNodes: Number of nodes in the clustered part of the Bridge Graph
	edgeProb: Probability of existance of an edge between any two vertices.
	bridgeNodes: Number of nodes in the bridge
	This function creates a Bridge Graph with 2 main clusters connected by a bridge.
	'''	
	print "Generating and Saving Bridge Network..."	
	G1 = nx.erdos_renyi_graph(2*numOfNodes + bridgeNodes, edgeProb) #Create an ER graph with number of vertices equal to twice the number of vertices in the clusters plus the number of bridge nodes.
	G = nx.Graph() #Create an empty graph so that it can be filled with the required components from G1
	G.add_edges_from(G1.subgraph(range(numOfNodes)).edges()) #Generate an induced subgraph of the nodes, ranging from 0 to numOfNodes, from G1 and add it to G
	G.add_edges_from(G1.subgraph(range(numOfNodes + bridgeNodes,2*numOfNodes + bridgeNodes)).edges()) #Generate an induced subgraph of the nodes, ranging from (numOfNodes + bridgeNodes) to (2*numOfNodes + bridgeNodes)

	A = random.randrange(numOfNodes) #Choose a random vertex from the first component
	B = random.randrange(numOfNodes + bridgeNodes,2*numOfNodes + bridgeNodes) #Choose a random vertex from the second component

	prev = A #creating a connection from A to B via the bridge nodes
	for i in range(numOfNodes, numOfNodes + bridgeNodes):
		G.add_edge(prev, i)
		prev = i
	G.add_edge(i, B)
	
	StrMap = {}
	for node in G.nodes():
		StrMap[node] = str(node)
	G = nx.convert.relabel_nodes(G,StrMap)
	filename = "BG_" + str(numOfNodes) + "_" + str(edgeProb) + "_" + str(bridgeNodes) + ".gpickle"
	nx.write_gpickle(G,filename)#generate a gpickle file of the learnt graph.
	print "Successfully written into " + filename
Пример #14
0
    def __init__(self, world, player, name):
        self.player = player
        self.name = name
        self.world = world
        self.pos = None
        self.color = colors[randint(0, len(colors) - 1)]
        self.distance_travelled = 0
        self.hits = 0
        self.kills = 0

        while 1:
            # Pick a random spot in the maze
            rand_x = randrange(len(self.world.world) - 1)
            rand_y = randrange(len(self.world.world[0]) - 1)
            pos = self.world.world[rand_x][rand_y]

            # Is there someone else there?
            found = False
            for p in self.world.players:
                if p.pos == pos:
                    found = True
                    break
            if not found:
                self.pos = pos
                self.pos.player = self
                break

        self.direction = ['n', 's', 'e', 'w'][randint(0,3)]

        # Hookup the IO
        self.player.set_forward(self.forward)
        self.player.set_left(self.left)
        self.player.set_right(self.right)
        self.player.set_fire(self.fire)
Пример #15
0
def specialQuestion(oldq):
	newq = [oldq[0], oldq[1]]
	qtype = oldq[0].upper()

	if qtype == "!MONTH":
		newq[0] = "What month is it currently (in UTC)?"
		newq[1] = time.strftime("%B", time.gmtime()).lower()
	elif qtype == "!MATH+":
		try:
			maxnum = int(oldq[1])
		except ValueError:
			maxnum = 10
		randnum1 = random.randrange(0, maxnum+1)
		randnum2 = random.randrange(0, maxnum+1)
		newq[0] = "What is %d + %d?" % (randnum1, randnum2)
		newq[1] = spellout(randnum1+randnum2)
	elif qtype == "!ALGEBRA+":
		try:
			num1, num2 = [int(i) for i in oldq[1].split('!')]
		except ValueError:
			num1, num2 = 10, 10
		randnum1 = random.randrange(0, num1+1)
		randnum2 = random.randrange(randnum1, num2+1)
		newq[0] = "What is x? %d = %d + x" % (randnum2, randnum1)
		newq[1] = spellout(randnum2-randnum1)
	else: pass #default to not modifying
	return newq
Пример #16
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
Пример #17
0
def int_generator(count=1, begin=1, end=101, is_fill=False):
    _len = len(str(end))
    for _ in range(count):
        if is_fill:
            yield str(random.randrange(begin,end)).zfill(_len)
        else:
            yield str(random.randrange(begin,end))
Пример #18
0
def generate_mac():
    chars = ["a", "b", "c", "d", "e", "f", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    mac = ":".join(
        chars[random.randrange(0, len(chars), 1)] + chars[random.randrange(0, len(chars), 1)] for x in range(6)
    )

    return mac
Пример #19
0
def generate_facts(system_name):

    uuid = generate_uuid()
    ipaddr = generate_ipaddr()

    copies = {}

    for key in facts:
        if type(facts[key]) == dict:
            attr_type = facts[key].keys()[0]
            if attr_type == "array":
                elem = random.randrange(0, len(facts[key]["array"]), 1)
                facts[key] = facts[key]["array"][elem]
            elif attr_type == "uuid":
                facts[key] = generate_uuid()
            elif attr_type == "copy":
                copies[key] = facts[key]["copy"]
            elif attr_type == "ipaddr":
                facts[key] = generate_ipaddr()
            elif attr_type == "hostname":
                facts[key] = system_name
            elif attr_type == "date":
                facts[key] = time.strftime("%m/%d/%Y", time.gmtime(time.time() - random.randrange(0, 100000, 1)))
            elif attr_type == "macaddr":
                facts[key] = generate_mac()

    for attr in copies:
        source = facts[attr]["copy"]
        facts[attr] = facts[source]

    return facts
Пример #20
0
def generate_prime(b, k=None):
    #Will generate an integer of b bits that is probably prime.
    #Reasonably fast on current hardware for values of up to around 512 bits.
    
    bits = int(b)
    assert bits > 1
    if k is None:
        k = 2*bits
    k = int(k)
    if k < 64:
        k = 64
    if DEBUG: print "(b=%i, k=%i)"%(bits,k),
    good = 0
    while not good:
        possible = random.randrange(2**(bits-1)+1, 2**bits)|1
        good = 1
        if DEBUG: sys.stdout.write(';');sys.stdout.flush()
        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
                if DEBUG: sys.stdout.write('.');sys.stdout.flush()
    if DEBUG: print
    return possible
Пример #21
0
        def heli_transport_flight(countries, airports: List[dcs.terrain.Airport]):
            country_str = countries[random.randrange(0, len(countries))]
            country = self.m.country(country_str)

            transports = [x for x in country.helicopters
                          if x.task_default == dcs.task.Transport]
            htype = random.choice(transports)

            start_airport = random.choice(airports)
            rand = random.random()
            name = "Helicopter Transport " + str(c_count)
            if 0.7 < rand:
                bound = dcs.mapping.Rectangle.from_point(start_airport.position, 100*1000)
                pos = bound.random_point()
                hg = self.m.flight_group_inflight(country, name, htype, pos, random.randrange(800, 1500, 100), 200)
                hg.add_runway_waypoint(start_airport)
                hg.land_at(start_airport)
            elif 0.4 < rand < 0.7:
                hg = self.m.flight_group_from_airport(country, name, htype, start_airport)
                hg.uncontrolled = True
            else:
                dest_airport = None
                while True:
                    dest_airport = airports[random.randrange(0, len(airports))]
                    if dest_airport != start_airport:
                        break

                hg = self.m.flight_group_from_airport(
                    country, name, htype, start_airport, start_type=random.choice(list(dcs.mission.StartType))
                )
                hg.add_runway_waypoint(start_airport)
                hg.add_runway_waypoint(dest_airport)
                hg.land_at(dest_airport)
            return hg
 def new_tile(self):
     """
     Create a new tile in a randomly selected empty
     square.  The tile should be 2 90% of the time and
     4 10% of the time.
     """
     # replace with your code
     # complete search ....
     non_zero_count = 0;
     for row in range(self._grid_height):
         for col in range(self._grid_width):
             if self._grid_tile[row][col] == 0:
                 non_zero_count += 1
     random_choice = random.randrange(0, non_zero_count)
     count = 0
     # another search ....
     generated_new_tile = False
     for row in range(self._grid_height):
         for col in range(self._grid_width):
             if generated_new_tile == False and self._grid_tile[row][col] == 0:
                 if count != random_choice:
                     count += 1   
                 else:
                     if random.randrange(0,100) < 10:
                         self.set_tile(row, col ,4)
                     else:
                         self.set_tile(row, col ,2)
                     generated_new_tile = True
Пример #23
0
def reset():
    micek[0] = SIRKA//2 - 10
    micek[1] = VYSKA//2 - 10
    micek[2] = SIRKA//2 + 10
    micek[3] = VYSKA//2 + 10    
    smer[0] = randrange(1,5)
    smer[1] = randrange(-5,5)
Пример #24
0
    def say (self, what):
        sentences=what.split(".")

        for sentence in sentences:
            sentence=sentence.strip()
            if sentence=="":
                continue

            print ("SAYING: ", sentence)
            path=os.path.dirname(os.path.abspath(__file__))+"/speechcache/"
            filename=sentence.lower().replace(" ", "")+".mp3"

            if not filename in self.soundCache:
                tts=googletts.googleTTS(text=''+sentence,lang='es', debug=False)
                tts.save(path+str(self.soundCache["soundIndex"])+".mp3")
                self.soundCache[filename]=str(self.soundCache["soundIndex"])+".mp3"
                self.soundCache["soundIndex"]=self.soundCache["soundIndex"]+1

            song = pyglet.media.load(path+self.soundCache[filename])
            song.play()
            time_speaking=song.duration-0.5
            start_time=time.time()

            while time.time()-start_time<time_speaking:
                pos=random.randrange(10,20)
                self.head.jaw.moveTo(pos)
                time.sleep(0.2)
                pos=random.randrange(30,50)
                self.head.jaw.moveTo(pos)
                time.sleep(0.2)
            self.head.jaw.moveTo(10)
            time.sleep(0.5)
Пример #25
0
def testRun():
	# For testing
	# count = [500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 6500, 7000, 7500, 8000, 8500, 9000, 9500, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000, 60000, 65000, 70000, 75000, 80000, 85000, 90000, 95000, 100000]

	count = 5000

	while count < 5000000000:
	# for num in testList:
		randList = [None] * count
		for n in range(0, count):
			randNum = random.randrange(0, 101)
			if (random.randrange(0, 2) == 0):
				randNum = randNum * -1
			randList[n] = randNum

		startTime = time.clock()
		result = linearSearch(randList)
		stopTime = time.clock()

		resultTime = stopTime - startTime

		print("n: " + str(len(randList)))
		print("Largest Result: " + str(result[2]))
		print("Running Time: " + str(resultTime))

		count = count * 10
Пример #26
0
def main():
    l = [random.randrange(-10, 10) for i in range(random.randrange(5, 10))]
    print l

    # function
    print "max value in list:%d" % (max_list(l))
    print "min value in list:%d" % (min_list(l))
Пример #27
0
Файл: gm.py Проект: vovkd/Simula
def generate_bodies(place, area, body_amount):
	delta = 0
	bodies = []
	for i in range(body_amount):
		random.seed(i)
		radiusXY = 	(randrange(2*area) - area)*0.05
		radiusZ = 	(randrange(2*area) - area)*0.05
		if (i <= body_amount/4):
			shift = (delta, 0)
		elif (i <= 2*body_amount/4):
			shift = (-delta, 0)
		elif (i <= 3*body_amount/4):
			shift = (0, -delta)
		else:
			shift = (0, delta)
		bodies.append	(
							{															
							'x': place[0] + radiusXY*cos(pi/AMOUNT * i) + shift[0],
							'y': place[1] + radiusXY*sin(pi/AMOUNT * i) + shift[1], 		
							'z': place[0] + radiusZ*sin(pi/AMOUNT * i), 		
							'mass': randrange(10**(SUPERMASS//2), 10**(SUPERMASS-5)), #10**(SUPERMASS-4),
							'radius': 10
							}
						)
	return bodies
Пример #28
0
 def test_merge(self):
     inputs = []
     for i in range(random.randrange(5)):
         row = sorted(random.randrange(1000) for j in range(random.randrange(10)))
         inputs.append(row)
     self.assertEqual(sorted(chain(*inputs)), list(self.module.merge(*inputs)))
     self.assertEqual(list(self.module.merge()), [])
Пример #29
0
    def __init__(self,numPlayers):

        x = 0
        while x < numPlayers:
            #set random roles
            r = randrange(0,numPlayers,1)
            while self.roles[r][1] == True:
                r = randrange(0,numPlayers,1)
            self.roles[r][1] = True
            self.role.append(self.roles[r][0])
            
            #set health
            if self.role[x] == "Sheriff":
                self.health.append(5)
            else: self.health.append(4)
            #set horse through jail to false and no card
            self.mustang.append([False,None])
            self.scope.append([False,None])
            self.barrel.append([False,None])
            self.dynamite.append([False,None])
            self.jail.append([False,None])
            #set gun to none and volcanic to false
            self.gun.append([1,None])
            self.volcanic.append(False)
            x += 1
Пример #30
0
def process_buck(L1,L2,D0,D1,D2,ratio,weight,gui_mode):

    #CALL NEXT MODULE

    #buck0i_1

    if os.path.isfile(sys.path[0]+os.sep+"price_skew.txt"):
        os.remove(sys.path[0]+os.sep+"price_skew.txt")

    target = 60

    i = 200
    while i > 0:
        Length = randrange(L1,L2)                 #setting tree length 

           #Tree descriptor vectors
        log_vector = [0,Length] 
        diameter_vector = [D0,randrange(D1,D2)] 

        # calculations
        (Lf,v1,td1,p1,Lf2,v2,td2,p2) = buck2(Length,log_vector,diameter_vector)
        set_price_skew(target,ratio,weight)
        track_data(Lf,p1,v1)
        i = i - 1

#    buck_result_display(gui_mode,Lf,v1,td1,p1,Lf2,v2,td2,p2)

    graph_data(target)

    os.remove(sys.path[0]+os.sep+"data.txt")
Пример #31
0
def addNoise(signal, numpoints, step = 0.01, vary = 1):
     theRange = int((1/step))
     for i in range(numpoints):
         signal[i] = signal[i] + random.randrange(-theRange, +theRange)*step*vary
     return signal
Пример #32
0
	def scatter(self):

		self.position.x = random.randrange(settings.WIDTH)
		self.position.y = random.randrange(settings.HEIGHT)
		self.velocity.x = random.randrange(-max_speed, max_speed + 1)
		self.velocity.y = random.randrange(-max_speed, max_speed + 1)
Пример #33
0

#class that saves the values on an array
def create_space(num):
    l = []
    for i in range(0, num):
        d = Dot(120 + random.uniform(0, num), 100 + random.uniform(0, num),
                (255, 125, 0), random.uniform(0, 5), screen)
        #append() method appends a passed obj into the existing list
        l.append(d)

    return l


#create how many circles have, in this case, between 50 and 70
dot_list = create_space(random.randrange(50, 70))

#while program doesn't stop
while running:
    #gets a single event from the queue and it's going to appear in the terminal
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        running = 0

    #RGB
    screen.fill((0, 0, 0))

    for i in dot_list:
        i.update()
        i.draw()
Пример #34
0
    print("#" * 80)
    sys.exit()

#initializing m
m = []
col = []
for j in range(0, cols, 1):
    col.append(0)

for i in range(0, k, 1):
    m.append(col)

random1 = 0

for p in range(0, k, 1):
    random1 = random.randrange(0, (rows - 1))
    m[p] = data[random1]

#classifying points
trainlabels = {}
diff = 1

prev = [[0] * cols for x in range(k)]

dist = []

mdist = []
for p in range(0, k, 1):
    mdist.append(0)
n = []
for p in range(0, k, 1):
Пример #35
0
def mutate(population):
  for individual in population:
    individual.chromosomes[random.randrange(individual.length)] = random.choice(individual.possibilities)
  return population
Пример #36
0
def crossover(population):
  half = len(population) / 2
  for individual1, individual2 in zip(population[:half], population[half:]):
    cross_section = slice(random.randrange(0, individual1.length / 2), random.randrange(individual1.length / 2, individual1.length))
    individual1.chromosomes[cross_section], individual2.chromosomes[cross_section] = individual2.chromosomes[cross_section], individual1.chromosomes[cross_section]
  return population
Пример #37
0
def swap(population):
  for individual in population:
    i, j = random.randrange(individual.length), random.randrange(individual.length)
    individual.chromosomes[i], individual.chromosomes[j] = individual.chromosomes[j], individual.chromosomes[i]
  return population
Пример #38
0
def get_word(lst):
    stuff = randrange(0, len(lst), 1)
    return lst[stuff]
Пример #39
0
                         dest='message',
                         help="message to send to rabbit server")
    opt_parse.add_option('-b',
                         '--host',
                         dest='hostname',
                         help="message to send to rabbit server")
    opt_parse.add_option('-p', '--port', dest='port', help="port server")
    opt_parse.add_option('-u', '--user', dest='username', help="username")
    opt_parse.add_option('-P', '--pass', dest='pasword', help="pasword")
    opt_parse.add_option('-t', "--type", dest="type", help="type")
    params = opt_parse.parse_args()[0]
    if params.hostname == None and len(sys.argv) > 1:
        params = urlparse(sys.argv[1])
    try:
        USERNAME = params.username if params.username != None else USERNAME
        PASSWORD = params.pasword if params.password != None else PASSWORD
    except:
        pass
    AMQP_HOST = params.hostname
    AMQP_PORT = int(params.port)
    msg = json.dumps({
        "ordernum": random.randrange(0, 100, 1),
        "type": params.type
    })
    amqp = AMQP(USERNAME, PASSWORD, AMQP_HOST, AMQP_PORT, PATH)
    amqp.connect()
    amqp.send(message=msg,
              exchange=EXCHANGE_NAME,
              content_type="application/json",
              routing_key=ROUTING)
import urllib2
from random import randrange

for number in range(50, 63):
    data1 = '{ "$class": "org.arc.recon.BreakExplaination", "reconUnit": "resource:org.arc.recon.ReconUnit#client-street-recon-'
    data2 = '", "reconUser": "******", "explainValue":' + str(
        explainValue) + ', "comment": "None", "reasonCode": "CLIENT_ERROR" }'
    data = data1 + str(number) + data2 + str(data3) + date4
    url = 'http://localhost:3000/api/BreakExplaination'
    req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
    f = urllib2.urlopen(req)
    f.close()
Пример #41
0
 def getRandomStr(self, length=None):  #生成随机字符串,nonce_str
     c = length or random.randrange(5, 31)
     s = str(uuid.uuid1())
     smd5 = self.getMd5(s)
     return smd5[0:c]
Пример #42
0
def getNumber():
    return random.randrange(1, 46)
Пример #43
0
        # 去掉数据库中的 token 信息
        ans = serializer.data
        ans.pop('experiment_case_file_token', None)
        ans.pop('answer_file_token', None)
        return Response(utils.generate_response(ans, True), headers=response_headers)

    elif request.method == 'PUT':
        serializer = ExperimentCaseDatabaseSerializer(
            case, data=request.data, partial=True)
        if serializer.is_valid():

            response_headers = {}

            # case file
            file_display_name = serializer.data["experiment_case_file_name"]
            random_hex_string = ('%030x' % random.randrange(16 ** 30))
            file_token = f"{EXPERIMENT_CASE_PREFIX}/{random_hex_string}/{file_display_name}"
            post_url = local_minio_client.presigned_url("PUT",
                                                        DEFAULT_BUCKET,
                                                        file_token,
                                                        expires=DEFAULT_FILE_URL_TIMEOUT)
            response_headers['CASE_FILE_UPLOAD_URL'] = post_url

            # answer file
            file_display_name = serializer.data["answer_file_name"]
            random_hex_string = ('%030x' % random.randrange(16 ** 30))
            file_token = f"{EXPERIMENT_CASE_PREFIX}/{random_hex_string}/{file_display_name}"
            post_url = local_minio_client.presigned_url("PUT",
                                                        DEFAULT_BUCKET,
                                                        file_token,
                                                        expires=DEFAULT_FILE_URL_TIMEOUT)
Пример #44
0
def rolldice():                                             #this function give a and b random values betweeen [1,7) and return the sum of dice numbers
     global a,b
     a = random.randrange(1,7)
     b = random.randrange(1,7)

     return a+b
Пример #45
0
import random

mylist = []  # Generate random number on the list
x = int(input("Masukkan jumlah data yang akan diiterasi: "))
for i in range(x):
    mylist.append(random.randrange(1, 200))


def maxima(list_a):
    indexing_length = len(
        list_a) - 1  #[1,2,3,4,5==> tdk bisa dibandingkan karena paling kanan]
    sorted = False

    while not sorted:
        sorted = True
        for i in range(0, indexing_length):
            if list_a[i] > list_a[i + 1]:
                sorted = False
                list_a[i], list_a[i + 1] = list_a[i + 1], list_a[
                    i]  #swapping location based on value

    return list_a[-1]


print((mylist), "==> Belum Sort")
print(maxima(mylist), "==> Menggunakan Maxima")


def minima(list_b):
    indexing_length = len(
        list_b) - 1  #[1,2,3,4,5==> tdk bisa dibandingkan karena paling kanan]
Пример #46
0
def experiment_case_list(request):
    """
    List all cases, or create a new case.
    """

    if request.method == 'GET':
        cases = ExperimentCaseDatabase.objects.all()
        serializer = ExperimentCaseDatabaseSerializer(cases, many=True)
        for index, case in enumerate(serializer.data):
            serializer.data[index].pop('experiment_case_file_token', None)
            serializer.data[index].pop('answer_file_token', None)
        ans = sorted(serializer.data, key=lambda x: datetime.datetime.strptime(x['case_created_timestamp'][:10], '%Y-%m-%d').timestamp())
        return Response(utils.generate_response(ans, True))
    elif request.method == 'POST':

        if not local_minio_client.bucket_exists(DEFAULT_BUCKET):
            local_minio_client.make_bucket(DEFAULT_BUCKET)

        new_case = {}
        response_headers = {}

        try:

            # case file
            file_display_name = request.data["experiment_case_file_name"]
            random_hex_string = ('%030x' % random.randrange(16 ** 30))
            file_token = f"{EXPERIMENT_CASE_PREFIX }/{random_hex_string}/{file_display_name}"
            post_url = local_minio_client.presigned_url("PUT",
                                                        DEFAULT_BUCKET,
                                                        file_token,
                                                        expires=DEFAULT_FILE_URL_TIMEOUT)
            new_case['experiment_case_file_token'] = file_token
            response_headers['CASE_FILE_UPLOAD_URL'] = post_url

            # answer file
            file_display_name = request.data["answer_file_name"]
            random_hex_string = ('%030x' % random.randrange(16 ** 30))
            file_token = f"{EXPERIMENT_CASE_PREFIX }/{random_hex_string}/{file_display_name}"
            post_url = local_minio_client.presigned_url("PUT",
                                                        DEFAULT_BUCKET,
                                                        file_token,
                                                        expires=DEFAULT_FILE_URL_TIMEOUT)
            new_case['answer_file_token'] = file_token
            response_headers['ANSWER_FILE_UPLOAD_URL'] = post_url

            # other info
            new_case['experiment_name'] = request.data['experiment_name']
            new_case['experiment_case_name'] = request.data['experiment_case_name']

        except Exception as e:
            print(str(e))
            return Response(utils.generate_response(str(e), False), status=status.HTTP_400_BAD_REQUEST)

        serializer = ExperimentCaseDatabaseSerializer(data=new_case)
        if serializer.is_valid():
            serializer.save()
            ans = serializer.data
            ans.pop('experiment_case_file_token', None)
            ans.pop('answer_file_token', None)
            return Response(utils.generate_response(ans, True), headers=response_headers, status=status.HTTP_201_CREATED)
        else:
            return Response(utils.generate_response(serializer.errors, False), status=status.HTTP_400_BAD_REQUEST)
        outpath = sys.argv[2]
    except:
        print "Second argument expected: output-tile"        
        sys.exit(-1)     
    try:
        k = int(sys.argv[3])
    except:
        print "Third argument expected: sample-size (number)"        
        sys.exit(-1)     
    
    #count records
    numrecords  = sum( 1 for record in io.read_zbl_records(open(zblpath)) ) 

    #select indexes:
    ixs         = set()
    while len(ixs) < k:
        ixs.add( random.randrange(0, numrecords, 1) )

    #select records:
    selected    = []
    ix          = 0
    for record in io.read_zbl_records(open(zblpath)):
        if ixs.issuperset(set([ix])):
            selected.append(record)
        ix = ix + 1

    #write output
    io.write_zbl_records(open(outpath, "w"), selected)    


Пример #48
0
		print("round and round")

		if (io.input(in3_pin) == False):
			change_direction()

		if (io.input(in4_pin) == False and io.input(in5_pin) == True):
			faster()

		if (io.input(in5_pin) == False and io.input(in4_pin) == True):
			slower()

	elif (program == 2 or program == 3):
		print ("Time till next speed change: " + str(time_till_next_speed_change - time_passed % time_till_next_speed_change))
		
		if ((time_passed % time_till_next_speed_change) == 0):
			time_till_next_speed_change = randrange(1,4)
			speed = (randrange(20,100,10))
			print("changing speed to " + str(speed))
			if (speed < 30):
				if stoped:
					time_till_next_speed_change = 0.5
				else:
					stop_start()
			else:
				if stoped:
					stop_start()
				else:
					apply_changes()
	if (program == 3):
		if ((time_passed % 2) == 0):
			randombool = randrange(8)
Пример #49
0
def producer(q,name,food):
	for i in range(1,6):
		time.sleep(random.randrange(2))
		print('{}生产了{}'.format(name,food+str(i)))
		q.put(food+str(i))
Пример #50
0
def join_meeting(meeting):
    global hangup_thread, current_meeting, already_joined_ids, active_correlation_id

    hangup()

    if meeting.calendar_meeting:
        switch_to_calendar_tab()
        join_btn = wait_until_found(f"div[id='{meeting.m_id}'] > div > button",
                                    5)

    else:
        browser.execute_script(
            f'window.location = "{conversation_link}a?threadId={meeting.channel_id}&ctx=channel";'
        )
        switch_to_teams_tab()

        join_btn = wait_until_found(
            f"div[id='{meeting.m_id}'] > calling-join-button > button", 5)

    if join_btn is None:
        return

    browser.execute_script("arguments[0].click()", join_btn)

    join_now_btn = wait_until_found("button[data-tid='prejoin-join-button']",
                                    30)
    if join_now_btn is None:
        return

    uuid = re.search(uuid_regex, join_now_btn.get_attribute("track-data"))
    if uuid is not None:
        active_correlation_id = uuid.group(0)
    else:
        active_correlation_id = ""
    # turn camera off
    video_btn = browser.find_element_by_css_selector(
        "toggle-button[data-tid='toggle-video']>div>button")
    video_is_on = video_btn.get_attribute("aria-pressed")
    if video_is_on == "true":
        video_btn.click()
        print("Video off")

    # turn mic off
    audio_btn = browser.find_element_by_css_selector(
        "toggle-button[data-tid='toggle-mute']>div>button")
    audio_is_on = audio_btn.get_attribute("aria-pressed")
    if audio_is_on == "true":
        audio_btn.click()
        print("Audio off")

    if 'random_delay' in config and config['random_delay']:
        delay = random.randrange(10, 31, 1)
        print(f"Wating for {delay}s")
        time.sleep(delay)

    # find again to avoid stale element exception
    join_now_btn = wait_until_found("button[data-tid='prejoin-join-button']",
                                    5)
    if join_now_btn is None:
        return
    join_now_btn.click()

    current_meeting = meeting
    already_joined_ids.append(meeting.m_id)

    print(f"Joined meeting: {meeting.title}")

    if mode != 3:
        switch_to_teams_tab()
    else:
        switch_to_calendar_tab()

    if 'auto_leave_after_min' in config and config['auto_leave_after_min'] > 0:
        hangup_thread = Timer(config['auto_leave_after_min'] * 60, hangup)
        hangup_thread.start()
def asgn_mark_gen():
    mark = ''.join((str(randrange(100*100)/100),'%'))
    return mark
Пример #52
0
def consumer(q,name):
	while True:
		food = q.get()
		time.sleep(random.randrange(2))
		print('{}吃了{}'.format(name,food))
Пример #53
0
    def test_server_vlv_with_cookie_while_adding_and_deleting(self):
        """What happens if we add or remove items in the middle of the VLV?

        Nothing. The search and the sort is not repeated, and we only
        deal with the objects originally found.
        """
        attrs = ['cn'] + [
            x for x in self.users[0].keys() if x not in ('dn', 'objectclass')
        ]
        user_number = 0
        iteration = 0
        for attr in attrs:
            full_results, controls, sort_control = \
                            self.get_full_list(attr, True)
            original_n = len(self.users)

            expected_order = full_results
            random.seed(1)

            for before in range(0, 3) + [6, 11, 19]:
                for after in range(0, 3) + [6, 11, 19]:
                    start = max(before - 1, 1)
                    end = max(start + 4, original_n - after + 2)
                    for offset in range(start, end):
                        #if iteration > 2076:
                        #    return
                        cookie = get_cookie(controls, original_n)
                        vlv_search = encode_vlv_control(before=before,
                                                        after=after,
                                                        offset=offset,
                                                        n=original_n,
                                                        cookie=cookie)

                        iteration += 1
                        res = self.ldb.search(
                            self.ou,
                            scope=ldb.SCOPE_ONELEVEL,
                            attrs=[attr],
                            controls=[sort_control, vlv_search])

                        controls = res.controls
                        results = [x[attr][0] for x in res]
                        real_offset = max(1, min(offset, len(expected_order)))

                        expected_results = []
                        skipped = 0
                        begin_offset = max(real_offset - before - 1, 0)
                        real_before = min(before, real_offset - 1)
                        real_after = min(after,
                                         len(expected_order) - real_offset)

                        for x in expected_order[begin_offset:]:
                            if x is not None:
                                expected_results.append(x[0])
                                if (len(expected_results) == real_before +
                                        real_after + 1):
                                    break
                            else:
                                skipped += 1

                        if expected_results != results:
                            print("attr %s before %d after %d offset %d" %
                                  (attr, before, after, offset))
                        self.assertEquals(expected_results, results)

                        n = len(self.users)
                        if random.random() < 0.1 + (n < 5) * 0.05:
                            if n == 0:
                                i = 0
                            else:
                                i = random.randrange(n)
                            user = self.create_user(i,
                                                    n,
                                                    suffix='-%s' % user_number)
                            user_number += 1
                        if random.random() < 0.1 + (n > 50) * 0.02 and n:
                            index = random.randrange(n)
                            user = self.users.pop(index)

                            self.ldb.delete(user['dn'])

                            replaced = (user[attr], user['cn'])
                            if replaced in expected_order:
                                i = expected_order.index(replaced)
                                expected_order[i] = None
Пример #54
0
        if (cell==0 and neighborSum==3): return 1
        else: return 0
    
    return [[cellstep(grid[i][j], neighbor(grid, i, j))
             for j in range(0,edge)] for i in range(0,edge)]

if __name__ == '__main__':

    import pyglet
    from pyglet.gl import *
    from pyglet.window import mouse

    size = 30
    window = pyglet.window.Window(size*edge, size*edge)

    grid = [[randrange(2) for j in range(0, edge)] for i in range(0, edge)]

    def drawBlock(i, j, size):
        glBegin(GL_POLYGON)
        glVertex2f(i*size, j*size)
        glVertex2f((i+1)*size, j*size)
        glVertex2f((i+1)*size, (j+1)*size)
        glVertex2f(i*size, (j+1)*size)
        glEnd()

    @window.event
    def on_mouse_press(x, y, button, modifiers):
        global grid
        grid = step(grid)

    @window.event
Пример #55
0
def couleur_aleatoire():
    return [127 * randrange(3) for i in range(3)]  # peut etre noir
def exam_mark_gen(total):
    mark = randrange(0,2*(total+1))/2
    return mark
Пример #57
0
def genWire(dimension):
    return (random.randrange(dimension), random.randrange(dimension))
Пример #58
0
    def create_game_objects(self, level=1):
        self.vis_buttons = [0, 1, 1, 1, 1, 0, 1, 0, 0]
        self.mainloop.info.hide_buttonsa(self.vis_buttons)

        self.ai_enabled = False
        self.board.draw_grid = False
        s = random.randrange(100, 150, 5)
        v = random.randrange(230, 255, 5)
        h = random.randrange(0, 255, 5)
        bg_col = (255, 255, 255)
        if self.mainloop.scheme is not None:
            if self.mainloop.scheme.dark:
                bg_col = (0, 0, 0)
        color0 = ex.hsv_to_rgb(h, 1, 255)  # highlight 1
        self.color2 = ex.hsv_to_rgb(h, 255, 170)  # contours & borders
        self.font_color = self.color2

        white = (255, 255, 255)

        self.disp_counter = 0
        self.disp_len = 1
        lvl = 0

        gv = self.mainloop.m.game_variant
        if gv == 0:
            category = "animals"
            self.imgs = [
                'cow', 'turkey', 'shrimp', 'wolf', 'panther', 'panda',
                'magpie', 'clam', 'pony', 'mouse', 'pug', 'koala', 'frog',
                'ladybug', 'gorilla', 'llama', 'vulture', 'hamster', '',
                'starfish', 'crow', 'parakeet', 'caterpillar', 'tiger',
                'hummingbird', 'piranha', 'pig', 'scorpion', 'fox', 'leopard',
                'iguana', 'dolphin', 'bat', 'chick', 'crab', 'hen', 'wasp',
                'chameleon', 'whale', 'hedgehog', 'fawn', 'moose', 'bee',
                'viper', 'shrike', 'donkey', 'guinea_pig', 'sloth', 'horse',
                'penguin', 'otter', 'bear', 'zebra', 'ostrich', 'camel',
                'antelope', 'lemur', 'pigeon', '', 'mole', 'ray', 'ram',
                'skunk', 'jellyfish', 'sheep', 'shark', 'kitten', 'deer',
                'snail', 'flamingo', 'rabbit', 'oyster', 'beaver', 'sparrow',
                'dove', 'eagle', 'beetle', 'hippopotamus', 'owl', 'cobra',
                'salamander', 'goose', 'kangaroo', 'dragonfly', '', 'pelican',
                'squid', 'lion_cub', 'jaguar', 'duck', 'lizard', 'rhinoceros',
                'hyena', 'ox', 'peacock', 'parrot', '', 'alligator', 'ant',
                'goat', 'baby_rabbit', 'lion', 'squirrel', 'opossum', 'chimp',
                'doe', 'gopher', 'elephant', 'giraffe', 'spider', 'puppy',
                'jay', 'seal', 'rooster', 'turtle', 'bull', 'cat', 'rat',
                'slug', 'buffalo', 'blackbird', 'swan', 'lobster', 'dog',
                'mosquito', 'snake', 'chicken', 'anteater'
            ]
        elif gv == 1:
            category = "sport"
            self.imgs = [
                'judo', 'pool', 'ride', 'stretch', 'helmet', 'ice_skating',
                'walk', 'run', 'swim', '', '', 'boxing', 'hockey', 'race',
                'throw', 'skate', 'win', 'squat', 'ski', 'golf', 'whistle',
                'torch', 'sailing', 'stand', 'tennis', 'jump', 'rowing', '',
                'rope'
            ]
        elif gv == 2:
            category = "body"
            self.imgs = [
                'teeth', 'cheek', 'ankle', 'knee', 'toe', 'muscle', 'mouth',
                'feet', 'hand', 'elbow', 'hair', 'eyelash', 'beard',
                'belly_button', 'thumb', 'breast', 'nostril', 'nose', 'hip',
                'arm', 'eyebrow', 'fist', 'neck', 'wrist', 'throat', 'eye',
                'leg', 'spine', 'ear', 'finger', 'foot', 'braid', 'face',
                'back', 'chin', 'bottom', 'thigh', 'belly'
            ]
        elif gv == 3:
            category = "people"
            self.imgs = [
                'girl', '', 'son', '', 'friends', 'baby', 'child', 'dad',
                'mom', 'twin_boys', 'brothers', 'man', '', 'grandfather',
                'family', '', 'wife', 'husband', '', '', 'grandmother',
                'couple', '', 'twin_girls', 'tribe', 'boy', 'sisters', 'woman',
                ''
            ]
        elif gv == 4:
            category = "actions"
            self.imgs = [
                'lick', 'slam', 'beg', 'fell', 'scratch', 'touch', 'sniff',
                'see', 'climb', 'dig', 'howl', 'sleep', 'explore', 'draw',
                'hug', 'teach', 'nap', 'clay', 'catch', 'clap', 'cry', 'sing',
                'meet', 'sell', 'peck', 'beat', 'kneel', 'find', 'dance',
                'cough', 'cut', 'think', 'bark', 'speak', 'cheer', 'bake',
                'write', 'punch', 'strum', 'study', 'plow', 'dream', 'post',
                'dive', 'whisper', 'sob', 'shake', 'feed', 'crawl', 'camp',
                'spill', 'clean', 'scream', 'tear', 'float', 'pull', 'ate',
                'kiss', 'sit', 'hatch', 'blink', 'hear', 'smooch', 'play',
                'wash', 'chat', 'drive', 'drink', 'fly', 'juggle', 'bit',
                'sweep', 'look', 'knit', 'lift', 'fetch', 'read', 'croak',
                'stare', 'eat'
            ]
        elif gv == 5:
            category = "construction"
            self.imgs = [
                'lighthouse', 'door', 'circus', 'church', 'kennel', 'temple',
                'smoke', 'chimney', 'brick', 'well', 'street', 'castle',
                'store', 'staircase', 'school', 'farm', 'bridge', 'dam',
                'pyramid', 'barn', 'mill', 'window', '', 'step', 'shop',
                'shed', 'roof', 'steeple', 'garage', 'mosque', 'hospital',
                'tent', 'house', 'wall', 'bank', 'shutter', 'hut'
            ]
        elif gv == 6:
            category = "nature"
            self.imgs = [
                'land', 'cliff', 'hill', 'canyon', 'rock', 'sea', 'lake',
                'coast', 'shore', 'mountain', 'pond', 'peak', 'lava', 'cave',
                'dune', 'island', 'forest', 'desert', 'iceberg'
            ]
        elif gv == 7:
            category = "jobs"
            self.imgs = [
                'clown', 'engineer', 'priest', 'vet', 'judge', '', 'athlete',
                'librarian', 'juggler', 'police', 'plumber', '', 'queen',
                'farmer', 'magic', 'knight', 'doctor', 'bricklayer', 'cleaner',
                'teacher', 'hunter', 'soldier', 'musician', 'lawyer',
                'fisherman', 'princess', 'fireman', 'nun', 'pirate', 'cowboy',
                'electrician', 'nurse', 'king', 'president', 'office',
                'carpenter', 'jockey', 'worker', 'mechanic', 'pilot', 'actor',
                'cook', 'student', 'butcher', 'accountant', 'prince', 'pope',
                'sailor', 'boxer', 'ballet', 'coach', 'astronaut', 'painter',
                'anaesthesiologist', 'scientist'
            ]
        elif gv == 8:
            category = "clothes_n_accessories"
            self.imgs = [
                'jewellery', 'sock', 'jacket', 'heel', 'smock', 'shorts',
                'pocket', 'necklace', 'sweatshirt', 'uniform', 'raincoat',
                'trousers', 'sunglasses', 'coat', 'pullover', 'shirt',
                'sandals', 'suit', 'pyjamas', 'skirt', 'zip', 'shoes', 'jewel',
                'tie', 'slippers', 'gloves', 'hat', 'sleeve', 'cap',
                'swimming_suit', 'sneaker', 'vest', 'glasses', 'shoelace',
                'patch', 'scarf', 'shoe', 'button', 'dress', 'sash',
                'shoe_sole', 'robe', 'pants', 'kimono', 'overalls'
            ]
        elif gv == 9:
            category = "fruit_n_veg"
            self.imgs = [
                'carrot', 'blackberries', 'celery', 'turnip', 'cacao', 'peach',
                'melon', 'grapefruit', 'broccoli', 'grapes', 'spinach', 'fig',
                'kernel', 'radish', 'tomato', 'kiwi', 'asparagus', 'olives',
                'cucumbers', 'beans', 'strawberry', 'peppers', 'raspberry',
                'apricot', 'potatoes', 'peas', 'cabbage', 'cherries', 'squash',
                'blueberries', 'pear', 'orange', 'pumpkin', 'avocado',
                'garlic', 'onion', 'apple', 'lime', 'cauliflower', 'mango',
                'lettuce', 'lemon', 'aubergine', 'artichokes', 'plums', 'leek',
                'bananas', 'papaya'
            ]
        elif gv == 10:
            category = "transport"
            self.imgs = [
                'sail', 'taxi', 'car', '', 'raft', 'pedal', 'bus', 'handlebar',
                'boat', 'truck', 'sleigh', 'carpet', 'motorcycle', 'train',
                'ship', 'van', 'canoe', 'rocket', 'mast', 'sledge', 'bicycle'
            ]
        elif gv == 11:
            category = "food"
            self.imgs = [
                'candy', 'sausage', 'hamburger', 'steak', 'fudge', 'doughnut',
                'coconut', 'rice', 'ice_cream', 'jelly', 'yoghurt', 'dessert',
                'pretzel', 'peanut', 'jam', 'feast', 'cookie', 'bacon',
                'spice', 'coffee', 'pie', 'lemonade', 'chocolate',
                'water_bottle', 'lunch', 'ice', 'sugar', 'sauce', 'soup',
                'juice', 'fries', 'cake', 'mashed_potatoes', 'tea', 'bun',
                'cheese', 'beef', 'sandwich', 'slice', 'sprinkle', 'pizza',
                'flour', 'gum', 'spaghetti', 'roast', 'stew', 'spread', 'meat',
                'milk', 'meal', 'corn', 'bread', 'walnut', 'egg', 'hot_dog',
                'ham'
            ]

        # Maximum words per screen 19 (nature)

        self.captions = self.d["a4a_%s" % category]

        if self.level.lvl > self.level.lvl_count:
            self.level.lvl = self.level.lvl_count
        if self.level.lvl == 1:
            data = [10, 3, 3, 2, 3]
        elif self.level.lvl == 2:
            data = [10, 4, 3, 2, 4]
        elif self.level.lvl == 3:
            data = [10, 5, 3, 2, 5]

        # rescale the number of squares horizontally to better match the screen width
        m = data[0] % 2
        if m == 0:
            x = self.get_x_count(data[1], even=True)
        else:
            x = self.get_x_count(data[1], even=False)

        if x > data[0]:
            data[0] = x

        self.data = data

        self.found = 0
        self.clicks = 0

        self.squares = self.data[3] * self.data[4]

        self.square_count = self.squares * 2  # self.data[3]*self.data[4]
        self.history = [None, None]

        self.layout.update_layout(data[0], data[1])
        self.board.level_start(data[0], data[1], self.layout.scale)
        texts1 = []
        texts2 = []

        l = len(self.imgs)
        drawn_numbers = []
        while len(drawn_numbers) < data[1] * 2:
            r = random.randint(0, l - 1)
            if r not in drawn_numbers:
                if self.imgs[r] != '' and self.captions[r][0] != "<":
                    drawn_numbers.append(r)

        self.completed_mode = False

        choice = [x for x in range(0, self.square_count // 2)]
        shuffled = choice[:]
        random.shuffle(shuffled)
        self.chosen = shuffled[0:self.square_count // 2]
        self.chosen = self.chosen * 2

        h1 = (data[1] - data[4]) // 2  # height of the top margin
        h2 = data[1] - h1 - data[
            4]  # -1 #height of the bottom margin minus 1 (game label)
        w2 = (data[0] - data[3] * 4) // 2 - 1  # side margin width

        x = w2
        y = h1
        small_slots = []
        for j in range(h1, data[1] - h2):
            for i in range(w2, w2 + data[3]):
                small_slots.append([i, j])
        random.shuffle(small_slots)

        wide_slots = []
        for j in range(h1, data[1] - h2):
            for i in range(w2 + data[3], data[0] - w2, 4):
                wide_slots.append([i, j])
        random.shuffle(wide_slots)
        switch = self.square_count // 2
        for i in range(self.square_count):
            if i < switch:
                img = "%s.jpg" % self.imgs[drawn_numbers[i]]
                img_src = os.path.join('art4apps', category, img)
                position_list = small_slots
                pos = i
                xw = 1
                self.board.add_unit(position_list[pos][0],
                                    position_list[pos][1], xw, 1,
                                    classes.board.ImgShip, "", color0, img_src)
            else:
                caption = self.captions[drawn_numbers[i - switch]]
                position_list = wide_slots
                pos = i - switch
                xw = 4
                self.board.add_unit(position_list[pos][0],
                                    position_list[pos][1], xw, 1,
                                    classes.board.Letter, caption, color0, "",
                                    8)
                self.board.ships[-1].font_color = self.font_color
            self.board.ships[i].immobilize()
            self.board.ships[i].readable = False
            self.board.ships[i].perm_outline = True
            self.board.ships[i].uncovered = False
            self.board.ships[i].checkable = True
            self.board.ships[i].init_check_images()
        self.outline_all(self.color2, 1)
Пример #59
0
def how_many(doctype):
	return random.randrange(*prob.get(doctype, prob["default"])["qty"])
Пример #60
0
def mutDelWire(individual):
    index = random.randrange(len(individual))
    del individual[index]