Example #1
1
    def create(self):
        self.algo = []
        self.name = ""
        self.filename = ""
        for i in digits:
            self.algo.append(i)

        for i in ascii_letters:
            self.algo.append(i)
        if platform.system() == "Linux":
            self.path = "/home/" + getuser() + "/dcrypt"

        if platform.system() == "Windows":
            self.path = os.environ["appdata"] + "\\dcrypt"
        for i in range(4):
            self.name += random.choice(ascii_letters)

        for i in range(4):
            self.name += random.choice(digits)

        self.name += ".dcrt"
        if platform.system() == "Linux":
            self.filename = path + "/" + self.name
        if platform.system() == "Windows":
            self.filename = path + "\\" + self.name
        print(self.filename)
        self.file = open(self.filename, "w")
        for i in range(len(printable)):
            self.file.write(random.choice(self.algo) + random.choice(self.algo))
            if i != len(printable) - 1:
                self.file.write("_")
        self.file.close()
def perchoice(xs, vs):
    global lastchosen
    lastchosen = random.choice(vs)
    while lastchosen in xs:
        lastchosen = random.choice(vs)
    xs.append(lastchosen)
    return lastchosen
 def next_task(self, channel):
     if self.state == TaskManager.START:
         self.map_iter = iter(self.datasource)
         self.working_maps = {}
         self.map_results = {}
         # self.waiting_for_maps = []
         self.state = TaskManager.MAPPING
     if self.state == TaskManager.MAPPING:
         try:
             map_key = self.map_iter.next()
             map_item = map_key, self.datasource[map_key]
             self.working_maps[map_item[0]] = map_item[1]
             return ("map", map_item)
         except StopIteration:
             if len(self.working_maps) > 0:
                 key = random.choice(self.working_maps.keys())
                 return ("map", (key, self.working_maps[key]))
             self.state = TaskManager.REDUCING
             self.reduce_iter = self.map_results.iteritems()
             self.working_reduces = {}
             self.results = {}
     if self.state == TaskManager.REDUCING:
         try:
             reduce_item = self.reduce_iter.next()
             self.working_reduces[reduce_item[0]] = reduce_item[1]
             return ("reduce", reduce_item)
         except StopIteration:
             if len(self.working_reduces) > 0:
                 key = random.choice(self.working_reduces.keys())
                 return ("reduce", (key, self.working_reduces[key]))
             self.state = TaskManager.FINISHED
     if self.state == TaskManager.FINISHED:
         self.server.handle_close()
         return ("disconnect", None)
Example #4
1
def random_generator(num_vals, n_points_only=False):
    """outputs a random generator of len(lst) = num_vals"""
    start_list = random_list(num_vals)
    if n_points_only:
        gen_str = "n_points"
    else:
        gen_str = random.choice(["one_point", "random_point", "n_points"])
    if gen_str == "one_point":
        loc = random.choice(["start", "mid", "end"])
        generator = gen_one_point(start_list, loc)
        out_str = "%s\n%s at %s" % (start_list, gen_str, loc)
    elif gen_str == "random_point":
        generator = gen_random_point(start_list)
        out_str = "%s\n%s" % (start_list, gen_str)
    else:
        min_pts = len(start_list) // 10
        max_pts = len(start_list) // 5
        if min_pts < 1:
            min_pts = 1
        if max_pts < 2:
            max_pts = 2
        num_points = random.randrange(min_pts, max_pts + 1)
        generator = gen_n_points(start_list, num_points)
        out_str = "%s\n%s n=%s" % (start_list, gen_str, num_points)
    return generator, out_str
Example #5
1
def setting(**kwargs):
    defaults = {
        "name": "".join(random.choice(letters) for _ in range(10)),
        "value": "".join(random.choice(letters) for _ in range(10)),
    }
    defaults.update(kwargs)
    return Setting(**defaults)
Example #6
1
def DocGenerator(number, test_templates, offset):
    ret = {}
    dStore = test_templates["doc"]["datastore"]
    doc_query = DocEntry.query(ancestor=generic_key(dStore["dstore"], dStore["dname"]))
    test_cases = doc_query.fetch()
    if number > len(test_cases):
        number = len(test_cases)
    cnt = 0
    # for test_case in test_cases:
    while cnt < number:
        test_case = choice(test_cases)
        test_cases.remove(test_case)
        tmpStr = base64.decodestring(test_case.test_text)
        test_questions = base64.decodestring(test_case.test_questions).split(",")
        qLen = len(test_questions)
        if qLen > 3:
            qLen = 3
        for cnt2 in range(0, qLen):
            cnt2 = cnt2
            tmpQuestion = choice(test_questions)
            tmpStr = tmpStr + "\n\n\t" + base64.decodestring(tmpQuestion)
            test_questions.remove(tmpQuestion)
        ret[cnt + offset] = tmpStr
        cnt += 1
        if cnt >= number:
            break
    return ret
def reWeightedRW(G, income, sampleSize):
    node = random.choice(G.nodes())

    sampling = list()
    node_degrees = list()
    node_incomes = list()
    prob = list()

    for i in range(sampleSize):
        sampling.append(node)
        node_degrees.append(len(G[node]))
        node_incomes.append(income[node])

        # Select a random neighbor of node
        node = random.choice(G.neighbors(node))

    # The normal random walk. biased, without correction.
    biased_average_degrees = numpy.average(node_degrees)
    biased_average_incomes = numpy.average(node_incomes)

    # Correcting the random walk sampling with inverted-node-degree probability
    summation_of_denominator = 0.0
    for x in node_degrees:
        summation_of_denominator += 1.0 / x

        numerator = 0.0

        for i in range(len(node_degrees)):
            numerator += (node_incomes[i] * 1.0) / node_degrees[i]
        reweighted_average_degrees = len(node_degrees) / summation_of_denominator
    reweighted_average_incomes = numerator / summation_of_denominator

    return [biased_average_degrees, reweighted_average_degrees, biased_average_incomes, reweighted_average_incomes]
def getNewTitle(old_title):
    new_title = ""
    total_str = (
        random.choice(titles_ls)
        + " "
        + random.choice(titles_ls)
        + " "
        + import_utilities.strip_punctuation(random.choice(titles_ls))
    )
    total = total_str.split(" ")
    random.shuffle(total)
    for w in total:
        if total.index(w) % 4:
            new_title += w + " "

    new_title = " ".join(w for w in new_title.split(" ") if " , " not in w and len(w) < 7)

    new_title = new_title.replace("Review", "")

    new_title = " ".join(unique_list(new_title.split()))
    # check last word
    if new_title.lower().split(" ")[-1] in import_utilities.stopwords_ls:
        new_title = new_title.rsplit(" ", 1)[0]

    #
    new_title = new_title.rsplit(" ", 1)[0] + " " + new_title.split(" ")[-1].rstrip(",:;").title()
    return new_title
    def _generate_password(self, length, symbolgroups):
        """Generate a random password from the supplied symbol groups.

        At least one symbol from each group will be included. Unpredictable
        results if length is less than the number of symbol groups.

        Believed to be reasonably secure (with a reasonable password length!)
        """
        # NOTE(jerdfelt): Some password policies require at least one character
        # from each group of symbols, so start off with one random character
        # from each symbol group
        password = [random.choice(s) for s in symbolgroups]
        # If length < len(symbolgroups), the leading characters will only
        # be from the first length groups. Try our best to not be predictable
        # by shuffling and then truncating.
        random.shuffle(password)
        password = password[:length]
        length -= len(password)

        # then fill with random characters from all symbol groups
        symbols = "".join(symbolgroups)
        password.extend([random.choice(symbols) for _i in range(length)])

        # finally shuffle to ensure first x characters aren't from a
        # predictable group
        random.shuffle(password)

        return "".join(password)
Example #10
0
def generate_log(timestamp):
    user = random.randint(1, 10000)
    action = random.choice(actions)
    domain = random.choice(domains)
    campaign = random.randint(1, 20)
    session = "session_%s" % random.randint(1, 100)
    # cost is in cents, could be zero
    cost = random.randint(1, 200) - 20
    if cost < 0:
        cost = 0

    # csv
    if log_format == "csv":
        logline = "%s,%s,%s,%s,%s,%s,%s" % (timestamp, user, action, domain, campaign, cost, session)

    # generate JSON format
    if log_format == "json":
        dict = {
            "timestamp": timestamp,
            "user": user,
            "action": action,
            "domain": domain,
            "campaign": campaign,
            "cost": cost,
            "session": session,
        }
        logline = json.dumps(dict)

    # print logline
    return logline
 def testOpaqueWriteBatch(self):
     db = self.db_class(self.db_path, create_if_missing=True)
     scoped_db = db.scope("prefix2_")
     scopes = [db.scope("prefix1_"), scoped_db, scoped_db.scope("a_"), scoped_db.scope("b_"), db.scope("prefix3_")]
     batch = db.newBatch()
     for i, scope in enumerate(scopes):
         scope.putTo(batch, str(i), str(i))
     db.write(batch)
     for i, scope in enumerate(scopes):
         self.assertEquals(scope.get(str(i)), str(i))
     batch.clear()
     for i, scope in enumerate(scopes):
         scope.deleteFrom(batch, str(i))
     db.write(batch)
     for i, scope in enumerate(scopes):
         self.assertEquals(scope.get(str(i)), None)
     # same effect when done through any scope
     batch = random.choice(scopes).newBatch()
     for i, scope in enumerate(scopes):
         scope.putTo(batch, str(i), str(2 * (i + 1)))
     random.choice(scopes).write(batch)
     for i, scope in enumerate(scopes):
         self.assertEquals(scope.get(str(i)), str(2 * (i + 1)))
     batch.clear()
     for i, scope in enumerate(scopes):
         scope.deleteFrom(batch, str(i))
     random.choice(scopes).write(batch)
     for i, scope in enumerate(scopes):
         self.assertEquals(scope.get(str(i)), None)
Example #12
0
    def __init__(self, p):
        """Generate a result"""
        self.person = p
        self.datestring, self.month, self.day, self.hr, self.min, self.sec = self.randomDate()

        self.serialNum = Measurement.serialNum
        Measurement.serialNum = Measurement.serialNum + 1

        # +/- 1 random measurement error
        self.volume = self.person.trueVolume + choice([-1, 0, 0, 0, +1])
        self.range = self.person.trueRange + choice([-1, 0, 0, 0, +1])
        self.discrimination = self.person.trueDiscrimination + choice([-1, 0, 0, 0, +1])

        self.volume = self.limit(self.volume)
        self.range = self.limit(self.range)
        self.discrimination = self.limit(self.discrimination)

        # before this date, things were being recorded 0..9 rather than 1..10
        fixmonth = 8
        fixday = 18
        fixhr = 10

        fixdate = fixmonth * 10000 + fixday * 100 + fixhr
        checkdate = self.month * 10000 + self.day * 100 + self.hr
        if checkdate < fixdate:
            self.volume = self.volume - 1
            self.range = self.range - 1
            self.discrimination = self.discrimination - 1

        if random() < Measurement.incompleteFraction:
            self.discrimination = None
Example #13
0
def compPlay():

    if len(compCoor) >= 2:
        for combos in list(itertools.combinations(compCoor, 2)):
            chance = 15 - (magicSquare[combos[0].x][combos[0].y] + magicSquare[combos[1].x][combos[1].y])
            for i in range(len(magicSquare)):
                if chance in magicSquare[i]:
                    coordinate = coor(i, magicSquare[i].index(chance))
                    if coordinate in center:
                        center.remove(coordinate)
                        compCoor.append(coordinate)
                        return
                    elif coordinate in corners:
                        corners.remove(coordinate)
                        compCoor.append(coordinate)
                        return
                    elif coordinate in edges:
                        edges.remove(coordinate)
                        compCoor.append(coordinate)
                        return
                    else:
                        pass

    if len(playerCoor) >= 2:
        for combos in list(itertools.combinations(playerCoor, 2)):
            chance = 15 - (magicSquare[combos[0].x][combos[0].y] + magicSquare[combos[1].x][combos[1].y])
            for i in range(len(magicSquare)):
                if chance in magicSquare[i]:
                    coordinate = coor(i, magicSquare[i].index(chance))
                    if coordinate in center:
                        center.remove(coordinate)
                        compCoor.append(coordinate)
                        return
                    elif coordinate in corners:
                        corners.remove(coordinate)
                        compCoor.append(coordinate)
                        return
                    elif coordinate in edges:
                        edges.remove(coordinate)
                        compCoor.append(coordinate)
                        return
                    else:
                        pass

    if len(center) > 0:
        compCoor.append(center[0])
        center.pop(0)
        return
    elif len(corners) > 0:
        coordinate = random.choice(corners)
        compCoor.append(coordinate)
        corners.remove(coordinate)
        return
    elif len(edges) > 0:
        coordinate = random.choice(edges)
        compCoor.append(coordinate)
        edges.remove(coordinate)
        return
    else:
        return
Example #14
0
def populateReadings(professors, cur):
    r = []
    id = 0
    topics = [
        "Gen Math",
        "Trig",
        "Calc",
        "Integration",
        "derivatives",
        "Intro",
        "CS",
        "Trees",
        "Linked Lists",
        "Arrays",
        "C",
        "C++",
    ]
    books = ["Trig Book", "Math Book", "Calc Book 1", "Calc Book 2", "CS Book", "CS Langs"]
    for p in professors:
        numReadings = random.randrange(5)
        for _ in range(numReadings):
            cur.execute(
                "INSERT INTO readings VALUES( %s, %s, %s, %s, %s, %s)",
                [id, random.choice(topics), random.choice(books), genPage(), genURL(random.randint(5, 20)), p[0]],
            )
            r += [id]
            id += 1
    return r
Example #15
0
def populateSection(
    cur
):  # courses are simply the abbreviation for a department plus a 3 digit number... CRNS are dept abreviation + course # + section #
    sections = []
    classNums = list(range(101, 500))
    majors = list(["CS", "ECE", "GEO", "ECON", "MATH"])
    times = ["10:00 - 10:50", "1:10 - 2:00"]
    days = ["MWF", "TR", "MW", "WF", "MTWRF"]
    rooms = list(range(100, 120))
    rooms += list(range(200, 220))
    rooms += list(range(300, 320))
    for _ in range(300):
        classNum_list = list(classNums)
        num = random.choice(classNum_list)
        classNums.remove(num)
        majors2 = list(majors)
        for _ in range(random.randint(1, 4)):
            if len(majors2) == 0:
                break
            m = random.choice(majors2)
            majors2.remove(m)
            for i in range(random.randint(1, 3)):  # number of sections
                t = random.choice(list(times))
                d = random.choice(list(days))
                r = random.choice(list(rooms))
                SQL = "INSERT INTO sections VALUES(%s, %s, %s, %s, %s)"
                data = [m + str(num) + str(i), m + str(num), t, d, r]
                cur.execute(SQL, data)
                sections.append((m + str(num) + str(i), m + str(num), t, d, r))
    return sections
Example #16
0
 def spawn(self):
     emptyCells = []
     for gridRow in self.ground.getGrid():
         for gridColl in gridRow:
             if gridColl.status == "FREE":
                 emptyCells.append(gridColl)
     choice(emptyCells).placeFood(self)
Example #17
0
 def __init__(self, game, size, center):
     self.groups = game.all_sprites, game.rocks, game.mobs
     self._layer = ROCK_LAYER
     pg.sprite.Sprite.__init__(self, self.groups)
     self.size = size
     self.game = game
     self.img_name = choice(ROCK_IMAGES[size])
     self.image = game.spritesheet.get_image_by_name(self.img_name)
     self.image_clean = self.image.copy()
     self.rect = self.image.get_rect()
     self.pos = vec(0, 0)
     self.vel = vec(uniform(ROCK_SPEED_MIN, ROCK_SPEED_MAX), 0).rotate(uniform(0, 360))
     self.rot = 0
     self.rot_speed = choice([-1.5, -1, -0.5, 0.5, 1, 1.5])
     if center is None:
         edge = choice(["h", "v"])
         if edge == "h":
             self.pos.x = -self.rect.width
             self.pos.y = randint(0, HEIGHT)
         elif edge == "v":
             self.pos.y = -self.rect.height
             self.pos.x = randint(0, WIDTH)
     else:
         self.pos = center
     self.rect.center = self.pos
Example #18
0
def generate_fake_coachreport_logs(password="hellothere"):
    try:
        t = FacilityUser.objects.get(facility=Facility.objects.all()[0], username=random.choice(firstnames))
    except FacilityUser.DoesNotExist as e:
        t = FacilityUser(facility=Facility.objects.all()[0], username=random.choice(firstnames))
        t.set_password(password)
        t.save()

    # TODO: create flags later
    num_logs = 20
    logs = []
    for _ in xrange(num_logs):
        date_logged_in = datetime.datetime.now() - datetime.timedelta(days=random.randint(1, 10))
        date_viewed_coachreport = date_logged_in + datetime.timedelta(minutes=random.randint(0, 30))
        date_logged_out = date_viewed_coachreport + datetime.timedelta(minutes=random.randint(0, 30))
        login_log = UserLog.objects.create(
            user=t,
            activity_type=UserLog.get_activity_int("login"),
            start_datetime=date_logged_in,
            last_active_datetime=date_viewed_coachreport,
            end_datetime=date_logged_out,
        )
        logging.info("created login log for teacher %s" % t.username)
        coachreport_log = UserLog.objects.create(
            user=t,
            activity_type=UserLog.get_activity_int("coachreport"),
            start_datetime=date_viewed_coachreport,
            last_active_datetime=date_viewed_coachreport,
            end_datetime=date_viewed_coachreport,
        )
        logs.append((login_log, coachreport_log))
        logging.info("created coachreport log for teacher %s" % t.username)
    return logs
Example #19
0
def get_or_group():
    ret = "(%s|%s)"
    words = [
        "cat",
        "dog",
        "lion",
        "fish",
        "tiger",
        "sloth",
        "wolf",
        "giraffe",
        "gazelle",
        "spider",
        "potato",
        "chair",
        "phone",
        "table",
        "alien",
        "bernie",
        "trump",
        "clinton",
        "tomato",
        "apple",
        "banana",
        "clementine",
        "penguin",
        "dolphin",
        "elephant",
    ]
    return ret % (random.choice(words), random.choice(words))
def choose_solo_rhythm():
    rest_beginning = random.choice([True, False, False, False, False])
    rest_middle = random.choice([True, True, False])
    rest_end = random.choice([True, True, True, False, False])

    rests = [rest_beginning, rest_middle, rest_end]
    num_rests = rests.count(True)

    min_num_divs = 3 + num_rests

    num_divs = random.randint(min_num_divs, 9)

    divs = divide(16, num_divs)

    notes = [{"pitch": None, "duration": div / 4.0} for div in divs]

    if rest_beginning:
        notes[0]["pitch"] = "rest"

    if rest_end:
        notes[-1]["pitch"] = "rest"

    if rest_middle:
        if rest_beginning:
            start = 2
        else:
            start = 1
        if rest_end:
            end = -2
        else:
            end = -1
        middle_rest_index = random.choice(range(len(notes))[start:end])
        notes[middle_rest_index]["pitch"] = "rest"

    return notes
Example #21
0
    def create_trials(self, combinations):
        df = pd.DataFrame(combinations, columns=("setSize", "probeType"))

        for i, r in df.iterrows():
            # Store the current used set
            used_set = random.sample(self.STIM_SET, r["setSize"])
            unused_set = list(set(self.STIM_SET) - set(used_set))

            df.set_value(i, "set", "".join(str(x) for x in used_set))

            # Store the target probe number
            # Probe will be from/in the set 50% of the time (probe present)
            if r["probeType"] == "present":
                df.set_value(i, "probe", str(random.choice(used_set)))
            else:
                df.set_value(i, "probe", str(random.choice(unused_set)))

            # Store blank columns to be used later
            df["trialNum"] = ""
            df["block"] = ""
            df["response"] = ""
            df["RT"] = ""
            df["correct"] = ""

            # Rearrange the dataframe
            columns = ["trialNum", "block", "setSize", "probeType", "set", "probe", "response", "RT", "correct"]
            df = df[columns]

        return df
Example #22
0
def getAction(state, time_left=None):
    """This is the main AI function.  It should return a valid AI action for this state."""
    global myDTree

    if myDTree is None:
        print "Loading DTree"
        myDTree = loadDTree("pa2_trees\Dataset_216918_attacker_ai_P1_attacker_ai_P2_20141107-085947_10.dtree")
        print "Done."

    # Get the possible actions in this state
    actions = getAllowedActions(state)

    # Select a Random Action
    myaction = random.choice(actions)

    if state.turn_type == "PreAssign":
        myaction = pickAssign(state, actions)
        # print 'I chose the action: ', myaction
    if state.turn_type == "Attack":
        myaction = actions[0]

    if state.turn_type == "Place" or state.turn_type == "Fortify" or state.turn_type == "PrePlace":
        possible_actions = []

        for a in actions:
            if a.to_territory is not None:
                for n in state.board.territories[state.board.territory_to_id[a.to_territory]].neighbors:
                    if state.owners[n] != state.current_player:
                        possible_actions.append(a)

        if len(possible_actions) > 0:
            myaction = random.choice(possible_actions)

    return myaction
Example #23
0
def simMontyHall(numTrials, chooseFcn):
    stickWins, switchWins, noWin = (0, 0, 0)
    doors = [1, 2, 3, 4]
    guessChoices = [1, 2, 3, 4]
    playerStick = True
    for t in range(numTrials):
        prizeDoors = random.sample([1, 2, 3, 4], 2)
        guess = random.choice(doors)
        toOpen = chooseFcn(guess, prizeDoors)
        if guess in prizeDoors:
            stickWins += 1

        newchoices = []
        for i in doors:
            if i != guess and i != toOpen:
                newchoices.append(i)
        guess = random.choice(newchoices)
        if guess in prizeDoors:
            switchWins += 1

        # print "Player guess " + str(guess)
        # print "Monty open " + str(toOpen)
        # print "Prize door choices" + str(prizeDoors)

        # if toOpen in prizeDoors:
        #    noWin += 1
        # elif guess in prizeDoors:
        #    stickWins += 1
        # else:
        #    switchWins += 1
    return (stickWins, switchWins)
Example #24
0
    def test_random(self):
        import random

        d = {}  # mirror the database
        for dummy in range(5):
            f = dumbdbm.open(_fname)
            for dummy in range(100):
                k = random.choice("abcdefghijklm")
                if random.random() < 0.2:
                    if k in d:
                        del d[k]
                        del f[k]
                else:
                    v = random.choice("abc") * random.randrange(10000)
                    d[k] = v
                    f[k] = v
                    self.assertEqual(f[k], v)
            f.close()

            f = dumbdbm.open(_fname)
            expected = d.items()
            expected.sort()
            got = f.items()
            got.sort()
            self.assertEqual(expected, got)
            f.close()
Example #25
0
def random_note():
    note = random.choice("abcdefg")
    acc = random.choice(["", "-", "--", "#", "##"])
    articulation = random.choice("n/otTS$RuHh;QpU[]_(){}\'s\\`~^vz,mwMW")
    duration = random.choice(["2", "4", "8", "16", "32", "64"])
    dot = random.choice(["", ".", ".."])
    return duration + dot + note + acc + articulation
    def generateFilterCountAndTraffic(self, runLevel):
        """
        returns traffic and filterCount for any case
        """
        traffic = []
        filterCount = 1
        filterModes = ["fwd", "drop"]
        self.mode = []
        if runLevel == "single":
            filterCount = 1
            traffic.append(self.parser.getTrafficType())
            self.mode.append(random.choice(filterModes))
        elif runLevel == "multi":
            filterCount = random.randint(2, 12)
            mode = random.choice(filterModes)
            for i in range(filterCount):
                traffic.append(self.parser.getTrafficType())
                self.mode.append(mode)
        elif runLevel == "random":
            filterCount = random.randint(2, 12)
            traffic = self.generateRandomeFiltersTypes(filterCount)
        else:
            print runLevel
            self.failPrint()

        return filterCount, traffic
Example #27
0
 def createName(self):
     if self.sex == "m":
         fn = random.choice(world.World.firstnamesm)
     else:
         fn = random.choice(world.World.firstnamesf)
     ln = random.choice(world.World.lastnames)
     return fn[:-1] + " " + ln[:-1]
Example #28
0
    def zipcode(city):
        manchZip = ["03101", "03102", "03103", "03104", "03105", "03107", "03108", "03109", "03111"]
        nashZip = ["03060", "03061", "03062", "03063", "03064"]
        conZip = ["03301", "03302", "03303", "03305"]
        derryZip = ["03038"]
        doverZip = ["03820", "03821", "03822"]
        rochZip = ["03839", "03866", "03867", "03868"]
        salemZip = ["03089"]
        merZip = ["03054"]
        hudZip = ["03051"]
        londonZip = ["03053"]

        if city == "MANCHESTER":
            return random.choice(manchZip)
        elif city == "NASHUA":
            return random.choice(nashZip)
        elif city == "CONCORD":
            return random.choice(conZip)
        elif city == "DERRY":
            return random.choice(derryZip)
        elif city == "DOVER":
            return random.choice(doverZip)
        elif city == "ROCHESTER":
            return random.choice(rochZip)
        elif city == "SALEM":
            return random.choice(salemZip)
        elif city == "MERRIMACK":
            return random.choice(merZip)
        elif city == "HUDSON":
            return random.choice(hudZip)
        elif city == "LONDONDERRY":
            return random.choice(londonZip)
        else:
            return "Not Option"
 def test_invalid_assertion(self):
     # Randomly pick and run a _test_invalid_assertion_<foo>() method.
     tests = []
     for nm in dir(self):
         if nm.startswith("_test_invalid_assertion"):
             tests.append(getattr(self, nm))
     random.choice(tests)()
    def generate_similar_trials(
        self, important_category, all_target_images, all_distractors, all_similar_images, distractors_by_level1
    ):
        trials = []
        for similar_trial_num in range(self.number_of_similar_trials):
            trial_images = [choice(all_target_images), choice(all_similar_images)]

            for level1_images in distractors_by_level1.values():
                level1_image = choice(level1_images)
                while level1_image.categories[0] == important_category.similar:  # Check if similar category is chosen
                    level1_image = choice(level1_images)  # Pick a new random one from the same level1
                trial_images.append(level1_image)

            while len(trial_images) < 10:
                distractor = choice(all_distractors)
                is_duplicate = False
                for image in trial_images:
                    if image.categories[0] == distractor.categories[0]:
                        is_duplicate = True

                if not is_duplicate:
                    trial_images.append(distractor)

            shuffle(trial_images)
            trials.append(Trial(images=trial_images, important_category=important_category, trial_type="similar"))
        return trials