Exemple #1
0
def yield_BlastHit(len_seq=100, n_hit=5, min_len_hit=5, max_len_hit=20, s_id="seq_0"):
    for _ in range (n_hit):
        length = ri(min_len_hit, max_len_hit)
        start = ri(1, len_seq-length)
        end = start+length
        seq = length*"N"
        yield(BlastHit(s_id=s_id, s_start=start, s_end=end, q_seq=seq))
Exemple #2
0
def genElements(recurseCount=0):
    global usedIds, usedClasses, usedElements
    BADLEN = 20
    usedElements += [rc(elements) for j in range(BADLEN)]

    divString = b"\n"
    closer = b"\n"
    if recurseCount: BADLEN = int(BADLEN / 2)
    for j in range(BADLEN):
        selfCloser = (ri(0, 10) >= 7)
        tagName = rc(selfclosers) if selfCloser else rc(elements)
        if tagName not in usedElements: usedElements.append(tagName)
        tagName = tagName.encode("UTF-8")

        clsId = ri(1, 2)
        divString += b"<%s %s=\"%s\">%s</%s>" % (
            tagName, b"class" if clsId == 1 else b"id", rc(usedClasses).encode(
                "UTF-8") if clsId == 1 else rc(usedIds).encode("UTF-8"),
            genElements(recurseCount=recurseCount + 1)
            if ri(1, 10) == 3 and recurseCount <= 2 else genContent(), tagName)

        if not selfCloser:
            closer = b"</%s>\n" % tagName + closer if ri(1, 2) == 1 else b""
    divString += closer + b"\n"

    return divString
Exemple #3
0
def generate(hor, ver, w, h):
    edge = []
    for i in range(w - 1):
        for j in range(h - 1):
            cur = i * h + j
            edge.append((ri(0, 100000000000), cur, cur + 1))
            edge.append((ri(0, 100000000000), cur, cur + h))
    for i in range(w - 1):
        cur = i * h + h - 1
        edge.append((ri(0, 100000000000), cur, cur + h))
    for j in range(h - 1):
        cur = (w - 1) * h + j
        edge.append((ri(0, 100000000000), cur, cur + 1))

    par = [i for i in range(w * h)]
    deep = [0] * (w * h)
    edge.sort()
    for i in edge:
        v1 = i[1]
        v2 = i[2]
        if get(v1, par) != get(v2, par):
            r = v1 // h
            c = v1 % h
            if v2 - v1 == 1:
                ver[r][c] = True
            else:
                hor[c][r] = True
            un(v1, v2, par, deep)
Exemple #4
0
def gen_post_eqn(depth=0):
    ops = ["+", "-", "*", "/"]
    if depth >= MAX_EQN_DEPTH:
        return " " + str(ri(1, 9)) + " " + str(ri(1, 9)) + " " + ch(ops)
    return gen_post_eqn(depth + 1) + " " + str(ri(1, 9)) + " " + ch(ops) if ri(
        0,
        1) else " " + str(ri(1, 9)) + gen_post_eqn(depth + 1) + " " + ch(ops)
Exemple #5
0
    def __init__(self, len_subject, len_query, random_query=False):
        # Generate a random subject fasta file
        self.s_seq = rDNA(len_subject)
        self.s_path = tempfile.mkstemp()[1]
        with open(self.s_path, "w") as fp:
            fp.write(">ref\n{}\n".format(self.s_seq))

        # Generate either a random query sequence in forward or reverse orientation from the subject sequence
        if random_query:
            self.q_seq = rDNA(len_query)
        elif ri(0, 1):
            self.s_orient = "+"
            self.s_start = ri(0, len_subject - len_query)
            self.s_end = self.s_start + len_query
            self.q_seq = self.s_seq[self.s_start:self.s_end]
        else:
            self.s_orient = "-"
            self.s_end = ri(0, len_subject - len_query)
            self.s_start = self.s_end + len_query
            self.q_seq = "".join([
                self.DNA_COMPLEMENT[base]
                for base in self.s_seq[self.s_start - 1:self.s_end - 1:-1]
            ])

        self.q_path = tempfile.mkstemp()[1]
        with open(self.q_path, "w") as fp:
            fp.write(">query\n{}\n".format(self.q_seq))
Exemple #6
0
	def title_maker(self):
		charTitle = ri(0, 2)

		if not bool(charTitle):

			ttl = self.charObj.firstName + " " + self.charObj.lastName

		else:
			
			titleSource = ri(0, 3)

			if titleSource == 0:
				textSource = rc(self.charObj.scenes)
			elif titleSource == 1:
				textSource = rc(self.charObj.drugTrips)
			elif titleSource == 2:
				textSource = rc(self.charObj.scpReports)
			elif titleSource == 3:
				textSource = rc(self.charObj.gbergExcerpts)

			tokens = nltk.word_tokenize(textSource)

			if len(tokens) > 20:
				index = ri(0, len(tokens)-10)
				titleLen = ri(2, 6)
				ttl = ' '.join(tokens[index:index+titleLen])
			else:
				ttl = self.charObj.firstName + " " + self.charObj.lastName

		self.title = ttl
 def restart(self):
     x, y = [], []
     for _ in range(len(self.x)):
         if len(self.x) == 0:
             continue
         i = ri(0, len(self.x)-1)
         x.append(self.x[i])
         self.x.pop(i)
         y.append(self.y[i])
         self.y.pop(i)
     self.x = x
     self.y = y
     x_t, y_t = [], []
     for _ in range(len(self.x)):
         if len(self.x_t) == 0:
             continue
         i = ri(0, len(self.x_t)-1)
         x_t.append(self.x_t[i])
         self.x_t.pop(i)
         y_t.append(self.y_t[i])
         self.y_t.pop(i)
     self.x_t = x_t
     self.y_t = y_t
     self.i = 0
     self.i_t = 0
Exemple #8
0
    def connectionMade(self):
        """
        Initializes the session
        """
        super(SSHProtocol, self).connectionMade()

        self.user = self.terminal.transport.session.avatar
        self.userName = self.user.username.decode()
        self.name = config.sshName
        self.port = config.sshPort
        self._parser = FilesystemParser(config.path_to_filesys)
        self.userIP = self.user.conn.transport.transport.client[0]
        self.l = log
        self.current_dir = expanduser("~")

        load = self.loadLoginTime(self.userName)
        if load == False:
            # Zufällige, plausible last login time
            tdelta = timedelta(days=ri(1, 365),
                               seconds=ri(0, 60),
                               minutes=ri(0, 60),
                               hours=ri(0, 24))
            now = datetime.now()
            login = now - tdelta
            loginStr = str(login.ctime())
        else:
            loginStr = load

        self.saveLoginTime(self.userName)
        self.terminal.write("Last login: " + loginStr)
        self.terminal.nextLine()

        self.showPrompt()
Exemple #9
0
def Estrellas():
    r = bm
    glClearColor(0,0,0)    
    for x in range(1, r.width-1):
        for y in range(1, r.height-1):
            st = ri(0, 1000)
            tamano = ri(0,2) #determinara el tamano de las estrellas
            try:
                if (st  == 3):
                    if tamano ==0: # estrella de tamaño de 1 pixeles
                        r.framebuffer[y][x] = color(255,255,255)
                    if tamano ==1: # estrella de tamaño de 4 pixeles
                        r.framebuffer[y][x] = color(255,255,255)
                        r.framebuffer[y][x+1] = color(255,255,255)
                        r.framebuffer[y+1][x] = color(255,255,255)
                        r.framebuffer[y+1][x+1] = color(255,255,255)
                    if tamano ==2: # estrella de tamaño de 9 pixeles
                        r.framebuffer[y][x] = color(255,255,255)
                        r.framebuffer[y][x+1] = color(255,255,255)
                        r.framebuffer[y][x+2] = color(255,255,255)
                        r.framebuffer[y+1][x] = color(255,255,255)
                        r.framebuffer[y+1][x+1] = color(255,255,255)
                        r.framebuffer[y+1][x+2] = color(255,255,255)
                        r.framebuffer[y+2][x] = color(255,255,255)
                        r.framebuffer[y+2][x+1] = color(255,255,255)
                        r.framebuffer[y+2][x+2] = color(255,255,255)
            except IndexError:
                pass
Exemple #10
0
 def random_point(self):
     x_random = ri(SIDE_x + GAME_border,
                   SIDE_x + WINDOW_width - GAME_border - 1)
     y_random = ri(SIDE_y + GAME_border,
                   SIDE_y + WINDOW_height - GAME_border - 1)
     theta_random = (2 * np.pi - 0.0001) * ri(0, 1)
     return ((x_random, y_random, theta_random))
Exemple #11
0
 async def list_reaction_roles(self, ctx):
     groups = await self.database.get_reaction_roles_by_server(ctx.guild.id)
     if len(groups) == 0:
         return await ctx.send(embed=command_error(
             f"No Reaction Roles set up!",
             f"Use **{ctx.prefix}rr group add [name] [description]** to make a group"
         ))
     e = discord.Embed(
         title=f"{ctx.guild.name}'s Reaction Roles",
         description=
         f"Use **{ctx.prefix}rr send [group name]** to activate that group",
         color=discord.Color.from_rgb(ri(1, 255), ri(1, 255), ri(1, 255)))
     for group in groups:
         roles = ""
         if len(group['roles']) > 0:
             for role in group['roles']:
                 roles += f"@{role.role_name} | {role.role_emoji}\n"
         else:
             roles += f"None\nYou can add roles with **{ctx.prefix}rr role add @[role] [reaction] [group_name]**"
         e.add_field(
             name=f"**Name**: {group['name']}, \n"
             f"**Description**: {group['description'] if group['description'] != '' else 'None'}\n"
             f"**Message**: {group['message'].message_id if group['message'] else 'None'}",
             value=f"Roles:\n"
             f"{roles}",
             inline=False)
     await ctx.send(embed=e)
    def flipCoin(numberOfFlip):
        arrayNumb = []
        arrayNumb2 = []

        for i in range(numberOfFlip):
            randNumb = ri(0, 1)
            randNumb2 = ri(0, 1)
            # print(randNumb)
            arrayNumb.append(randNumb)
            arrayNumb2.append(randNumb2)
        print(arrayNumb)
        print(arrayNumb2)

        AA = 0  #AA = 00
        AG = 0  #AG = 01 / 01
        GG = 0  #GG = 11

        for i in range(len(arrayNumb)):
            if arrayNumb[i] == 0 and arrayNumb2[i] == 0:
                AA += 1
            elif arrayNumb[i] == 0 and arrayNumb2[i] == 1 or arrayNumb[
                    i] == 1 and arrayNumb2[i] == 0:
                AG += 1
            elif arrayNumb[i] == 1 and arrayNumb2[i] == 1:
                GG += 1

        print("Banyaknya Muncul AA", AA)
        print("Banyaknya Muncul AG/GA", AG)
        print("Banyaknya Muncul GG", GG)

        print("Probabilitas AA :", AA / len(arrayNumb))
        print("Probabilitas AG/GA :", AG / len(arrayNumb))
        print("Probabilitas GG :", GG / len(arrayNumb))
Exemple #13
0
 async def send(self, ctx, group_name=None):
     await self.database.check_for_reaction_role_messages(
         group_name=group_name, server_id=ctx.guild.id)
     group = await self.database.get_reaction_role_by_group(
         group_name=group_name, server_id=ctx.guild.id)
     if len(group['roles']) == 0:
         return await ctx.send(embed=command_error(
             "No Roles in this Group!",
             f"Add Roles to this group by using **{ctx.prefix}reactionroles add @role :emoji: [group_name]**"
         ))
     desc = ""
     if len(group['group'].group_description) > 0:
         desc += group['group'].group_description + '\n\n'
     for role in group['roles']:
         discord_role = ctx.guild.get_role(role.role_id)
         if discord_role is not None:
             desc += f"**{discord_role.name}** : {role.role_emoji}\n"
     e = discord.Embed(title="React to get your roles!",
                       description=desc,
                       color=discord.Color.from_rgb(ri(1, 255), ri(1, 255),
                                                    ri(1, 255)))
     msg = await ctx.send(embed=e)
     for role in group['roles']:
         await msg.add_reaction(role.role_emoji)
     await self.database.post_reaciton_role_message(
         group_id=group['group'].id, message_id=msg.id)
Exemple #14
0
def yield_sequence_and_BlastHit(len_seq=500,
                                n_query=10,
                                min_len_hit=20,
                                max_len_hit=40):

    # Generate a random subject sequence
    with rand_fasta(len_seq=len_seq, n_seq=1) as subject:
        pyfasta_gen = pyfasta.Fasta(subject.fasta_path, flatten_inplace=True)
        seq_record = pyfasta_gen["seq_0"]
        sequence = Sequence(name="seq_0", seq_record=seq_record)

        seq_dict = {}
        # Generate random hits from the subject
        for i in range(n_query):
            start = ri(1, len_seq - max_len_hit)
            end = start + ri(min_len_hit, max_len_hit)
            seq_dict["query_{}:{}-{}".format(i, start,
                                             end)] = str(seq_record[start:end])
        with defined_fasta(seq_dict) as query:

            # Create Blast DB and perform a blast to generate a list of hits
            with Blastn(subject.fasta_path) as blastn:
                hit_list = blastn(
                    query.fasta_path,
                    task="blastn",
                    best_query_hit=True,
                )

            yield (sequence, hit_list)
def generate(letter_range=(97, 122),
             lenght=settings["game"]["LETTER_NUMBER"],
             language=settings["game"]["DICT_LANGUAGE"]):
    global word_dict
    if lenght > 20:
        raise ValueError(f"Trop de lettres ({lenght})")
    if settings["settings"]["USE_INPROVED_GENERATOR"]:
        valid = False
        while not valid:
            shuffle_word = word_dict[ri(1,
                                        len(word_dict) - 1)].replace('\n', '')
            if settings["debug"]["DEBUG_WORDS"]:
                print(shuffle_word)
            if len(list(set(list(shuffle_word)))) > lenght:
                valid = False
                pass
            elif len(list(set(list(shuffle_word)))) == lenght:
                return list(set(list(remove_accents(shuffle_word))))
            else:
                r = list(set(list(shuffle_word)))
                while len(r) < lenght:
                    r.append(chr(ri(letter_range[0], letter_range[1])))

    else:
        r = list()
        for i in range(lenght):
            r.append(chr(ri(letter_range[0], letter_range[1])))
        return r
Exemple #16
0
 def genLogin(self):
     login = ''.join(map(str, [ri(0, 9) for _ in range(6)]))
     while getUser(login):
         login = ''.join(map(str, [ri(0, 9) for _ in range(6)]))
     self.login = login
     updateUser(self)
     return login
Exemple #17
0
def integer(allowNeg=True):
    ret = ""
    if allowNeg:
        if ri(0, 2) == 2: ret += "-"
        elif ri(0, 2) == 2: ret += "+"
    ret += "%d" % ri(1, 10)
    return ret
Exemple #18
0
def try_solve():
    x = Sudoku()
    x.print()
    from random import randint as ri
    count = 1
    tried = 1
    ones = 0
    twos = 0
    threes = 0
    fours = 0
    while x.check_full() != True:
        #x.insert(ri(1,9),ri(1,9),ri(1,9))
        for i in range(5):
            for row in range(1, 10):
                row += ri(1, 9)
                if row > 9:
                    row -= 9
                #print("row:           "+str(row))
                #x.print()
                for col in range(1, 10):
                    col += ri(1, 9)
                    if col > 9:
                        col -= 9
                    #print(x.check_none())
                    for data in range(1, 10):
                        x.insert(row, col, data)

                    #x.insert(row,col,ri(1,9))

        nones = x.check_none()
        if nones != None and nones < 5:
            x.print()
            if nones == 1:
                ones += 1
            elif nones == 2:
                twos += 1
            elif nones == 3:
                threes += 1
            elif nones == 4:
                fours += 1

            print('\nblanks:' + str(nones) + '\ntries:' + str(tried) + ' ')
            print('ones:' + str(ones) + '  twos:' + str(twos) + '  threes:' +
                  str(threes) + '  fours:' + str(fours) + '\n')

        else:
            #print(x.check_none())
            pass
        tried += 1
        x.initialise()
        #x.print()
    ##
    ##                  count += 1
    ##                  if count % 10000 == 0:
    ##                        print('\n'*4)
    ##                        x.print()
    ##                        x.check_none()

    x.print()
Exemple #19
0
def gen(n):
    global maxW, maxL
    pos = [(ri(0, maxW), ri(0, maxL)) for _ in range(n)]
    M = [[] for _ in range(n)] * n
    for i in range(n):
        for j in range(n):
            M[i].append(dist(pos[i], pos[j]))
    return M
Exemple #20
0
def inputGen(f):
    n = ri(1, 100)
    f.write("%d\n" % n)
    for _ in range(n):
        for __ in range(n):
            f.write("%d " % ri(0, 100000))
        f.write("\n")
    f.close()
Exemple #21
0
def inputGen(f):
    n, m = ri(1, 100), ri(1, 100)
    f.write("%d %d %d %d\n" % (n, m, ri(1, n), ri(1, m)))
    for _ in range(n):
        for __ in range(m):
            f.write("%d " % ri(0, 100000))
        f.write("\n")
    f.close()
Exemple #22
0
def main():
    create_matrix()
    window = arcade.Window(WIDTH, HEIGHT, "GAME OF PYFE", True)
    arcade.set_background_color((ri(0, 255), ri(0, 255), ri(0, 255)))
    window.set_update_rate(interval)
    arcade.schedule(on_draw, interval)

    arcade.run()
Exemple #23
0
def gen_in_eqn(depth=0):
    ops = ["+", "-", "*", "/"]
    if depth >= MAX_EQN_DEPTH:
        return "( " + str(ri(1, 9)) + " " + ch(ops) + " " + str(ri(1,
                                                                   9)) + " )"
    return "(" + gen_in_eqn(depth + 1) + " " + ch(ops) + " " + str(ri(
        1, 9)) + " )" if ri(0, 1) else "( " + str(ri(
            1, 9)) + " " + ch(ops) + gen_in_eqn(depth + 1) + " )"
Exemple #24
0
 def __init__(self, _list=[]):
     if not isinstance(_list, list):  # TODO should I use type() insted
         raise TypeError("Argument should be type list")
     self._list = _list or [ri(1, 1552566551) * (12 ** ri(1, 10)) for _ in range(1001)]
     self.item_max = 0
     self.ph_index = 0
     self.ph_value = 0
     self.placeholder_init()
Exemple #25
0
def test_len_works():
    for _ in xrange(10):
        length = ri(1, 100)
        curr = head = ll.from_list(range(length), True)
        steps = ri(0, length - 1)
        while steps > 0:
            curr, steps = curr.nxt, steps - 1
        assert len(curr) == length
Exemple #26
0
def gen(n):
    global maxW, maxL
    pos = [ (ri(0, maxW), ri(0, maxL)) for _ in range(n) ]
    M = [ [] for _ in range(n) ] * n
    for i in range(n):
        for j in range(n):
            M[i].append(dist(pos[i], pos[j]))
    return M
Exemple #27
0
def random_dict(num=0):
    if not num:
        num = ri(5, 20)
    d = {}
    for _ in xrange(num):
        d[random_str(ri(3, 10))] = random_str(ri(
            3, 10)) + random_keyword() + random_str(ri(3, 10))
    return d
def projectile():
    projectiles.append(
        makeCircle(ri(0, 255),
                   ri(0, 255),
                   ri(2, 8),
                   fill=h(0, 0, ri(0, 15)),
                   outline="#00f",
                   activefill=h(ri(0, 15), ri(0, 15), ri(0, 15)),
                   activeoutline=h(ri(0, 15), ri(0, 15), ri(0, 15))))
def traversal(d):
    """
    Debug the given code to traverse the given tree, writing the preorder traversal
    and then the postorder traversal.
    """
    if ri(0, d) == 0:
        return '(' + str(ri(-9,30)) + ')'
    else:
        return '(' + traversal(d-1) + ', ' + str(ri(-9, 30)) + ', ' + traversal(d-1) + ')'
Exemple #30
0
def crear_piloto(nombre, equipo):
    personalidad = sample(p.EQUIPOS[equipo]["PERSONALIDAD"], 1)[0]
    contextura = ri(p.EQUIPOS[equipo]["CONTEXTURA"]["MIN"],
                    p.EQUIPOS[equipo]["CONTEXTURA"]["MAX"])
    equilibrio = ri(p.EQUIPOS[equipo]["EQUILIBRIO"]["MIN"],
                    p.EQUIPOS[equipo]["EQUILIBRIO"]["MAX"])
    piloto = obj.Piloto(nombre, 5000, personalidad, contextura, equilibrio, 0,
                        equipo)
    return piloto
Exemple #31
0
    def do(cls, actor, weapon, allies: list, enemies: list, target_pos, session):
        if not enemies[target_pos]:
            return False

        damage = cls.trueAttDamage(actor, weapon)
        res = f'{actor.passive.name} использует навык {cls.name}\n'

        if ri(0, 100) < damage[1]:
            return res + enemies[target_pos].get_damage('crit', damage[0][1] * 2, session)
        return res + enemies[target_pos].get_damage(None, ri(damage[0][0], damage[0][1]), session)
def add_feature_data():
    cur, conn = connection()
    for i in xrange(10):
        alcohol_ai = str(rf(1, 200))
        positive = str(rf(1, 150))
        negative = str(rf(1, 20))
        extra = str(rf(1, 300))
        user_name = "username" + str(i)
        rating_count = str(ri(1, 100))
        rating = str(rf(0, 5))
        drink = str(ri(1, 20))
        alcohol_bk = str(ri(1, 20))
        bottle = str(ri(1, 20))
        money = str(ri(1, 20))
        quit = str(ri(1, 20))
        addict = str(ri(1, 20))
        problem = str(ri(1, 20))
        health = str(ri(1, 20))
        cur.execute(
            "INSERT into acc_intents values(%s, %s, %s, %s, %s, %s, %s)",
            (user_name, alcohol_ai, positive, negative, extra, rating_count,
             rating))
        cur.execute(
            "INSERT into bio_keywords values(%s, %s, %s, %s, %s, %s, %s, %s, %s)",
            (user_name, drink, alcohol_bk, bottle, money, quit, addict,
             problem, health))
    conn.commit()
    cur.close()
    conn.close()
def salesman(n):
    """
    Write code to provide a solution to the classic Traveling Salesman Problem. 
    Input is a list of points; output should be those points in the order that 
    they should be visited to form the shortest loop which visits every one 
    then returns to the start.
    """
    arr = []
    for i in range(n):
        arr.append((ri(-100, 100), ri(-100, 100)))
    return arr
Exemple #34
0
def yield_BlastHit(len_seq=100,
                   n_hit=5,
                   min_len_hit=5,
                   max_len_hit=20,
                   s_id="seq_0"):
    for _ in range(n_hit):
        length = ri(min_len_hit, max_len_hit)
        start = ri(1, len_seq - length)
        end = start + length
        seq = length * "N"
        yield (BlastHit(s_id=s_id, s_start=start, s_end=end, q_seq=seq))
def formatData():
	from random import randint as ri

	deviceInstance={}# MAC adress as key
	for x in range(1,2):# how many mac adresses
		sensors=[]
		for i in range(1,4):
			sensors.append({'sensor#':ri(0,12), 'avRSSI':ri(-90,-10), 'numRSSIReadings':ri(2,14)})
			#append the fake data into a list
		deviceInstance["3c:2d:4g:3%d"%ri(0,9)] = sorted(sensors, key=lambda y:y['avRSSI'])
			#Sort the fake data using the lambda function that used the key 'avRSSI'
			# then assign the fake data to a mac address
	return deviceInstance
Exemple #36
0
    def __init__(self, screen_size):
        screen_width, screen_height = screen_size
        pos = ri(5, screen_width), ri(5, screen_height)

        width = ri(1, 3)
        size = (width, width)
        self.rect = pygame.Rect(pos, size)
        self.color = (ri(100, 220), ri(100, 220), ri(100, 220))

        self.degrees = ri(0, 360)
        self.frequency = ri(0, 50)
        self.depth = ri(1, 20)

        self.frame_count = 0
        self.flicker_delay = ri(1, 180)  # Frames
        self.flickering = False
def chTitle(hi):
    htmlFile = open(APPPATH+'static/output/'+hi+'.html', 'r')
    html = htmlFile.read()
    htmlFile.close()
    soup = BeautifulSoup(html)
    text = "\n".join([unicode(i) for i in soup.p.contents]).replace("<br/>", "\n")
    s = parsetree(text)
    nounPhrases = []
    for sentence in s:
        for chunk in sentence.chunks:
            if chunk.type == "NP":
                nounPhrases.append(chunk.string)
    selectNPs = rs([np for np in nounPhrases if not "&" in np], ri(1,2))

    articles = ["a", "an", "the"]

    nps = []

    for np in selectNPs:
        if startsWithCheck(np, articles):
            nps.append(np)
        else:
            nps.append(a_or_an(np))

    if len(selectNPs) == 1:
        title = titlecase(nps[0])
    elif len(selectNPs) == 2:
        title = titlecase(" and ".join(nps))
    # elif len(selectNPs) == 3:
    #     title = titlecase("%s, %s, and %s" % tuple(nps))

    return title.encode('ascii', 'xmlcharrefreplace')
 def crossover_2way(self, other_parent, crossover_probability):
     l1 = len(self.rep)
     l2 = len(other_parent.rep)
     expected_length = 0
     #print "before crossover"
     #print self.rep
     #print other_parent.rep
     if l1 == l2:
         expected_length = l1
         tmp_p1 = ""
         tmp_p2 = ""
         for i in xrange(0, l1 , self.sig_size):
             p1 = self.rep[i: (i+self.sig_size) ]
             p2 = other_parent.rep[i: (i+self.sig_size) ]
             point = ri(0, self.sig_size  - 1) 
             #print point
             tmp1 = p1[point:]
             tmp2 = p2[point:]
             p1 = p1[:point] + tmp2
             p2 = p2[:point] + tmp1
             tmp_p1 = tmp_p1 + p1
             tmp_p2 = tmp_p2 + p2
         #print "After crossover"
         #print tmp_p1
         #print tmp_p2
         # used parent replaces children survivor selection
         if expected_length != 0:
             self.change_individual(tmp_p1.zfill(expected_length))
             other_parent.change_individual(tmp_p2.zfill(expected_length))
         #print "After crossover"
         #print self.rep 
         #print other_parent.rep 
     else:
         print "length of both parents must be equal"
Exemple #39
0
def _chat(CHAT_CHANNEL, s):
    """ Randomly print anarchy or democracy. Use to stay connected to 
    chat"""
    if ri(0,1) == 0:
        s.send(bytes("PRIVMSG #%s :anarchy\r\n" % CHAT_CHANNEL, "UTF-8"))
    else:
        s.send(bytes("PRIVMSG #%s :democracy\r\n" % CHAT_CHANNEL, "UTF-8"))
Exemple #40
0
def people(param_num):
	people = []
	# Create people
	for ii in range(PEOPLE):
		new_person = Person(PSHARE[param_num], PCREATE[param_num], DOI, param_num)
		new_person.reset() # Init
		people.append(new_person)

	# Create quotas
	quotas = []
	for ii, topic in enumerate(TOPICS):
		quotas.append(int(math.ceil(PEOPLE * I_CONF[ii])))

	# Distribute interests
	for ii, quota in enumerate(quotas):
		for nn in range(quota):
			# Interested or very interested
			d = DOI[0] if rr() < DOI_PREF else DOI[1]

			# Pick a suitable person. Pick any person after 3 tries.
			person = 0 # Init
			for jj in range(3): # HARDCODE 3
				person = ri(0, PEOPLE - 1)
				# Count previus topics of interest
				num = 0
				for interest in people[person].interests.values():
					if interest != 0:
						num += 1
				# Give new interest if few previous interests
				if num < 2: # HARDCODE 2
					people[person].interests[TOPICS[ii]] = d
					break
				# Smaller chance to get many interests
				elif rr() < 0.3: # HARDCODE 0.3
					people[person].interests[TOPICS[ii]] = d
					break
			# Anyone goes
			else:
				person = ri(0, PEOPLE -1)
				people[person].interests[TOPICS[ii]] = d

			# Split topic
			if (ii == 0):
				# Preferences go half and half
				people[person].preference = 1 if nn % 2 == 0 else 2

	return people
 def __init__(self, number_of_signals, bit_length = 16):
     self.rep = ""
     self.sig_size = bit_length
     #self.signal_range = signal_ranges(datasets)
     for i in xrange(number_of_signals):
         random_val =  bin(ri(0, 2 ** bit_length))[2:]
         random_val = random_val.zfill(bit_length)
         self.rep = self.rep + random_val 
def arrsort(n):
    """
    Debug the code which sorts an array.
    """
    arr = []
    for i in range(n):
        arr.append(ri(-20,20))
    return arr
Exemple #43
0
def cominp():
    """
    @func: get computer's choice
    @return: 0 => rock, 1 => paper, 2 => scissors
    @rtype: int
    """

    return ri(0, 2)
def create_plist(n=12):
    """
    Returns a list of n Process objects, numbered 1-n. Burst times for
    each process are 500-4000 ms, randomly generated. If no argument is
    given, default n to 12. Arrival times are based on an exponential
    distribution averaging 800ms.
    """
    times = get_process_times(n, PERCENT_ARRIVING_TIME_ZERO)
    return [Process(i, ri(500, 4000), j) for i, j in zip(range(1, n + 1), times)]
def subsets(n):
    """
    Debug the code which finds all those subsets of the given set which sum to 0.
    Desired output is the number of subsets which sum to 0.
    """
    out = []
    for i in range(n):
        out.append(ri(-50,50))
    return out
def linklist(n):
    """
    Complete the code which traverses the linked list and prints its smallest
    value.
    """
    l = []
    for i in range(n):
        l.append(ri(0,9))
    return l
Exemple #47
0
 def flicker(self):
     self.degrees += self.frequency
     if min(self.degrees, 360) % 360 == 0:
         self.flickering = False  # Flicker complete
         self.degrees = 0  # Reset counter
         self.frequency = ri(0, 50)  # Random flicker rate
         self.depth = lognorm(1, 0) * 20  # Random flicker depth
     variation = math.cos(math.radians(self.degrees))
     new_color = tuple([max(0, min(c + variation * self.depth, 220)) for c in self.color])
     self.color = new_color
def reservoir_sample(buf_size, num_inputs):
    bf = [0] * buf_size
    for i in range(num_inputs):
        if i < buf_size:
            bf[i] = i
        else:
            v = ri(0, i)
            if v < buf_size:
                bf[v] = i

    return np.median(bf)
Exemple #49
0
    def update(self):
        if not self.frequency:  # No flickering will occur anyway
            return

        if not self.flickering:
            if self.frame_count % self.flicker_delay == 0:
                self.flickering = True  # Start flickering
                self.frame_count = 0  # Restart counter
                self.flicker_delay = ri(1, 180)  # Different next time
        else:
            self.flicker()  # Update appearance
        self.frame_count += 1
Exemple #50
0
def yield_sequence_and_BlastHit(len_seq=500, n_query=10, min_len_hit=20, max_len_hit=40):

    # Generate a random subject sequence
    with rand_fasta(len_seq=len_seq, n_seq=1) as subject:
        pyfasta_gen = pyfasta.Fasta(subject.fasta_path, flatten_inplace=True)
        seq_record = pyfasta_gen["seq_0"]
        sequence = Sequence(name = "seq_0", seq_record = seq_record)

        seq_dict = {}
        # Generate random hits from the subject
        for i in range(n_query):
            start = ri(1, len_seq-max_len_hit)
            end = start+ri(min_len_hit, max_len_hit)
            seq_dict["query_{}:{}-{}".format(i, start, end)] = str(seq_record[start:end])
        with defined_fasta(seq_dict) as query:

            # Create Blast DB and perform a blast to generate a list of hits
            with Blastn(subject.fasta_path) as blastn:
                hit_list = blastn(query.fasta_path, task="blastn", best_query_hit=True,)

            yield (sequence, hit_list)
Exemple #51
0
 def create(self):
     for topic in self.interests:
         # Check if interested
         if self.interests[topic] != 0:
             # To create or not to create
             if rr() < self.pCreate:
                 # Create
                 for ii in range(ri(0, 3)):  # HARDCODE (0, 3)
                     # Add preference if necessary
                     pref = 0
                     if topic == TOPICS[0]:
                         pref = self.preference
                     self.outbox.append(Post(topic, 1, pref))
Exemple #52
0
def invent_word():
    candidates = list()
    for _ in range(64):
        candidates.append("".join(chseq(ri(6, 12))))

    ga = Jabberwocky(candidates)
    i = 0
    # ga.avg < 1.0 and
    while i < 1000:
        ga.update(top=0.125, mutation=0.2)
        i += 1

    return max(ga.population, key=lambda x: ga.population.count(x))
Exemple #53
0
    def __init__(self, len_subject, len_query, random_query=False):
        # Generate a random subject fasta file
        self.s_seq = rDNA(len_subject)
        self.s_path = tempfile.mkstemp()[1]
        with open (self.s_path, "w") as fp:
            fp.write (">ref\n{}\n".format(self.s_seq))

        # Generate either a random query sequence in forward or reverse orientation from the subject sequence
        if random_query:
            self.q_seq = rDNA(len_query)
        elif ri(0,1):
            self.s_orient = "+"
            self.s_start = ri(0, len_subject-len_query)
            self.s_end = self.s_start + len_query
            self.q_seq = self.s_seq [self.s_start:self.s_end]
        else:
            self.s_orient = "-"
            self.s_end = ri(0, len_subject-len_query)
            self.s_start = self.s_end + len_query
            self.q_seq = "".join ([self.DNA_COMPLEMENT[base] for base in self.s_seq[self.s_start-1:self.s_end-1:-1]])

        self.q_path = tempfile.mkstemp()[1]
        with open (self.q_path, "w") as fp:
            fp.write (">query\n{}\n".format(self.q_seq))
Exemple #54
0
def xmastree():
    "              "
    from random import randint as ri

    print "\n".join(
        [
            s.center(80)
            for s in (
                lambda h: (
                    lambda b: ["*"]
                    + sum([b(n) for n in range(1, (h - 1) // 2)], [])  #
                    + b((h - 1) // 2, True)
                    + ["| |"]
                )(
                    lambda n, last=False: (
                        lambda o: [
                            "/" + "".join([o() for m in range(0, n * 2 - 1)]) + "\\",
                            "/" + ("_" * (n * 2 + 1) if last else "".join([o() for m in range(0, n * 2 - 1)])) + "\\",
                        ]
                    )(lambda: "!@#$%^&"[ri(0, 6)] if ri(0, 99) > 80 else " ")
                )
            )(20)
        ]
    )  #
 def __init__(self, pid, burst_time, arrival_time):
     """
     self.pid:  Process ID
     self.time: time **REMAINING**
     self.arrived: time entering ready queue
     self.priority: process priority. lower number = higher priority
     self.popped: time FIRST popped out of q
     self.time_q: total time spent waiting in q
     """
     self.pid = pid
     self.time = burst_time
     self.arrived = arrival_time
     self.popped = None
     self.time_q = 0
     self.priority = ri(1, 4)
     self.turnaround = 0
     self.i_wait = 0
Exemple #56
0
def friends(people, param_num):
	for ii, person in enumerate(people):
		# Send friend requests
		for nn in range(int(gauss(F_MEAN[param_num], F_DEVIATION[param_num]))):
			# Pick a person
			id = ri(0, PEOPLE - 1)
			# Skip self
			if id == ii:
				continue
			other_person = people[id]

			# Logic of accepting a friend request
			# Amount of previous friends
			# HARDCODE All numbers
			if len(other_person.friends) < 8 or (len(other_person.friends) < 12 and rr() < 0.7) or rr() < 0.3:
				prob = 0.6 - F_PROB_BONUS[param_num]
				# Mutual interests
				for jj, topic in enumerate(TOPICS):
					# Split topic
					if jj == 0:
						# No preference
						if other_person.preference == 0 or person.preference == 0:
							pass
						# Same preference
						elif person.preference == other_person.preference:
							# Shared interest
							prob += F_PROB_BONUS[param_num]
							# Bonus
							prob += 0.1
						# Different preference
						else:
							# Penalty
							prob -= 0.1
					# Rest
					else:
						# Shared interest
						if other_person.interests[topic] > 0 and person.interests[topic] > 0:
							prob += F_PROB_BONUS[param_num]
				# Accept of decline friend request
				if rr() < prob:
					person.friends.append(id)
					other_person.friends.append(ii)
Exemple #57
0
def test_Reference_add_hit_list(n_ref, len_seq, n_seq):
    """Test the ability of add_hit_list to add a proper number of fake hits to each sequence in ref"""
    for ref in yield_reference(n_ref=n_ref, len_seq=len_seq, n_seq=n_seq):

        seq_dict = OrderedDict()
        hit_list = []
        for i in range (n_seq):
            n_hit = ri (0,10)
            s_id = "seq_{}".format(i)
            seq_dict[s_id] = n_hit
            hit_list.extend([hit for hit in yield_BlastHit(len_seq=len_seq, n_hit=n_hit, s_id=s_id)])

        ref.add_hit_list(hit_list)

        for name, n_hit in seq_dict.items():
            assert ref.seq_dict[name].n_hit == n_hit

        #ref.output_masked_reference(compress=False)
    # Reset ref name to start a new round
    Reference.RESET_REFERENCE_NAMES()
def keyHandler(event) :
    
    # create or delete smiley faces
    if event.keysym == "Right" :
        
        circles.append([ri(uw(20),uw(255)-uw(20)), ri(uh(20),uh(255)-uh(20))])  # [center x-value, center y-value]
        circles[-1] = [[
        makeCircle(circles[-1][0], circles[-1][1], uh(20), fill=h(int(rh(circles[-1][1])/16), int(rw(circles[-1][0])/16), 0), outline=""),
        makeCircle(circles[-1][0]-uh(8), circles[-1][1]-uh(10), uh(5), fill="#000", outline=""),
        makeCircle(circles[-1][0]+uh(8), circles[-1][1]-uh(10), uh(5), fill="#000", outline=""),
        makeCircularArc(circles[-1][0], circles[-1][1], uh(12), start=210, extent=120, width=uh(5), style=ARC)],
        ri(-1, 1), ri(-1, 1)]
        
        while circles[-1][1] == 0 and circles[-1][2] == 0 :  # makes sure the faces aren't stationary
            circles[-1][1] = ri(-1, 1)
            circles[-1][2] = ri(-1, 1)
    
    if event.keysym == "Left" and len(circles) > 0 :
        for item in circles[-1][0] :
            canvas.delete(item)
        circles.pop()  # defaults to -1
    
    
    # turn collisions off or on
    global collide
    if event.keysym == "o" :
        if collide :
            collide = False
        else :
            collide = True
    
    
    # resize the canvas
    global cw
    global ch
    if event.keysym == "Up" :
        cw *= 1.05
        ch *= 1.05
        canvas.config(width=cw, height=ch)
        for face in circles :
            for feature in face[0] :
                "This is where I'd reconfigure each feature of the smiley faces."
    if event.keysym == "Down" :
        cw *= .95
        ch *= .95
        canvas.config(width=cw, height=ch)
        for face in circles :
            for feature in face[0] :
                "This is where I'd reconfigure each feature of the smiley faces."
Exemple #59
0
def main():
    print('I''m thinking of an integer between 1 and 10. You have three guesses')
    answer = ri(1,10)

    guesses = ['first', 'second', 'third']
    playGame(guesses, answer)