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
def corrupt(self): """ Return a (notw2, weight), a corrupt target word and its weight. Note: This will return a different random value every call. """ from hyperparameters import HYPERPARAMETERS import random possible_targets = targetmap()[self.w1][self.l2] assert len(possible_targets) > 1 assert self.w2 in possible_targets notw2 = self.w2 cnt = 0 while self.w2 == notw2: if HYPERPARAMETERS["NGRAM_FOR_TRAINING_NOISE"] == 0: notw2 = random.choice(possible_targets) pr = 1./len(possible_targets) elif HYPERPARAMETERS["NGRAM_FOR_TRAINING_NOISE"] == 1: assert 0 # import noise # from common.myrandom import weighted_sample # e[-1], pr = weighted_sample(noise.indexed_weights()) ## from vocabulary import wordmap ## print wordmap.str(e[-1]), pr else: assert 0 cnt += 1 # Backoff to 0gram smoothing if we fail 10 times to get noise. if cnt > 10: notw2 = random.choice(possible_targets) if HYPERPARAMETERS["UNIFORM EXAMPLE WEIGHTS"]: weight = 1. else: weight = 1./pr return notw2, weight
def comp_attack(computer): misses = [] if computer.hits == []: while True: x = random.randint(0, 9) y = random.randint(0, 9) if (x, y) in computer.misses: continue elif (x, y) in computer.hits: continue else: return (x, y) else: while True: xy = random.choice(computer.hits) change = random.choice(((0, 1), (1, 0))) xy = update_coordinate(xy, change) if xy in computer.misses: misses.append(0) elif xy in computer.hits: misses.append(0) else: return xy if len(misses) >= 5: while True: x = random.randint(0, 9) y = random.randint(0, 9) if (x, y) in computer.misses: continue elif (x, y) in computer.hits: continue else: return (x, y)
def gen_insult(user): adj = [ "acidic", "antique", "contemptible", "culturally-unsound", "despicable", "evil", "fermented", "festering", "foul", "fulminating", "humid", "impure", "inept", "inferior", "industrial", "left-over", "low-quality", "malodorous", "off-color", "penguin-molesting", "petrified", "pointy-nosed", "salty", "sausage-snorfling", "tastless", "tempestuous", "tepid", "tofu-nibbling", "unintelligent", "unoriginal", "uninspiring", "weasel-smelling", "wretched", "spam-sucking", "egg-sucking", "decayed", "halfbaked", "infected", "squishy", "porous", "pickled", "coughed-up", "thick", "vapid", "hacked-up", "unmuzzleld", "bawdy", "vain", "lumpish", "churlish", "fobbing", "rank", "craven", "puking", "jarring", "fly-bitten", "pox-marked", "fen-sucked", "spongy", "droning", "gleeking", "warped", "currish", "milk-livered", "surly", "mammering", "ill-borne", "beef-witted", "tickle-brained", "half-faced", "headless", "wayward", "rump-fed", "onion-eyed", "beslubbering", "villainous", "lewd-minded", "cockered", "full-gorged", "rude-snouted", "crook-pated", "pribbling", "dread-bolted", "fool-born", "puny", "fawning", "sheep-biting", "dankish", "goatish", "weather-bitten", "knotty-pated", "malt-wormy", "saucyspleened", "motley-mind", "it-fowling", "vassal-willed", "loggerheaded", "clapper-clawed", "frothy", "ruttish", "clouted", "common-kissing", "pignutted", "folly-fallen", "plume-plucked", "flap-mouthed", "swag-bellied", "dizzy-eyed", "gorbellied", "weedy", "reeky", "measled", "spur-galled", "mangled", "impertinent", "bootless", "toad-spotted", "hasty-witted", "horn-beat", "yeasty", "boil-brained", "tottering", "hedge-born", "hugger-muggered", "elf-skinned" ] amt = [ "accumulation", "bucket", "coagulation", "enema-bucketful", "gob", "half-mouthful", "heap", "mass", "mound", "petrification", "pile", "puddle", "stack", "thimbleful", "tongueful", "ooze", "quart", "bag", "plate", "ass-full", "assload" ] noun = [ "bat toenails", "bug spit", "cat hair", "chicken piss", "dog vomit", "dung", "fat-woman's stomach-bile", "fish heads", "guano", "gunk", "pond scum", "rat retch", "red dye number-9", "Sun IPC manuals", "waffle-house grits", "yoo-hoo", "dog balls", "seagull puke", "cat bladders", "pus", "urine samples", "squirrel guts", "snake assholes", "snake bait", "buzzard gizzards", "cat-hair-balls", "rat-farts", "pods", "armadillo snouts", "entrails", "snake snot", "eel ooze", "slurpee-backwash", "toxic waste", "Stimpy-drool", "poopy", "poop", "craptacular carpet droppings", "jizzum", "cold sores", "anal warts" ] msg = '%s is a %s %s of %s.' % (user, choice(adj), choice(amt), choice(noun)) return msg
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 choose(buttons, data, algorithm, threshold = .10): """ takes as input an iterable of button types and input data. Currently the data will be passed in the form of a dictionary with button names as keys and boolean lists from a bernoulli distribution as values. Optionally, set the threshold for the espilon first algorithm. For ucb1 returns a list of length three with name, best_true_mean, and confidence_bound. For epsilon first returns a list of length two with name and current expected mean """ # Exploration rand = random() if (rand < threshold) and (algorithm != 'ucb1'): # if we decided to explore, choose a button at random r_choice = choice(buttons) # determing the reward for the choice and update reward r_choice.reward_count += choice(data[r_choice.name]) r_choice.trial_count += 1 return [r_choice, r_choice.reward_count/r_choice.trial_count] # if we're not in ucb1 and we're not exploring, find the max expected mean expected_list = [] for i in range(len(buttons)): if algorithm == 'ucb1': confidence_bound = math.sqrt(2*math.log(buttons[i].big_n)/buttons[i].trial_count) best_true_mean = (buttons[i].reward_count/buttons[i].trial_count) + confidence_bound # update the expected list expected_list.append([buttons[i], best_true_mean, confidence_bound]) buttons[i].big_n += 1 #print buttons[i], buttons[i].big_n, buttons[i].name else: # calculate expected mean and update to expected list expected_list.append([buttons[i],buttons[i].reward_count/buttons[i].trial_count]) # get maximum expected value (adjusted with conf. bound for ucb1) winner = max(expected_list, key = lambda x: x[1]) # update the reward and trial counts winner[0].get_reward(choice(data[winner[0].name])) return winner
def randomMoves(self): # Spazz out for 12 seconds, making random move every 3 seconds for x in range(1,5): #running 4 times dirX = random.choice([0,1,2]) dirY = random.choice([0,2]) #not using 1 as it would just turn wheels speed = random.randint(5,10) self.moveXY(dirX,dirY,speed,3)
def make_text(self, dictionary): """Takes dictionary of markov chains; returns random text.""" capital_keys_list = [key for key in dictionary.keys() if key[0][0].isupper()] # create list of only keys that start with an uppercase letter starting_key = random.choice(capital_keys_list) # choose key (tuple) to start at new_text_string = " ".join(starting_key) # add items in that tuple to string of created text limit = 140 punctuation = "?.!" # create punctuation string while dictionary.get(starting_key) != None and len(new_text_string) < limit: # Continue until the key is not found in the dictionary or until the limit is hit value_list = dictionary[starting_key] # assign value of key (list) next_word = random.choice(value_list) # choose random word w/in list new_text_string = new_text_string + " " + next_word # add next_word to list of created text starting_key = tuple(list(starting_key[1:]) + [next_word]) # create new tuple from second word of previous tuple + item at that index #print "at start of while loop:", new_text_string while len(new_text_string) > limit: # if length of the current string is greater than the limit, iterate through each character from the end to find punctuation # print "if block initiated", len(new_text_string), new_text_string for i in range(len(new_text_string)-2,-1,-1): # print "checking next character", len(new_text_string) if new_text_string[i] in punctuation: new_text_string = new_text_string[0:(i+1)] # cut off string at punctuation print "after cutting at punct:", len(new_text_string) if len(new_text_string) <= limit: return new_text_string else: # if no punctuation was found: new_text_string = new_text_string[:limit] # chop off after 140 characters return new_text_string # return new text
async def _top_(self, *, content : str): """Make a retrosign with top and middle text""" texts = [t.strip() for t in content.split(';')] if len(texts) != 2: await self.bot.say("\N{CROSS MARK} please provide two words seperated by ';'") return else: data = dict( bcg=choice([1, 2, 3, 4, 5]), txt=choice([1, 2, 3, 4]), text1=texts[0], text2=texts[1], text3="" ) await self.bot.type() with aiohttp.ClientSession() as session: async with session.post("http://photofunia.com/effects/retro-wave", data=data) as response: if response.status == 200: soup = b_s(await response.text(), "lxml") download_url = soup.find("div", class_="downloads-container").ul.li.a["href"] async with session.get(download_url) as image_response: if image_response.status == 200: image_data = await image_response.read() with BytesIO(image_data) as temp_image: await self.bot.upload(temp_image, filename="retro.jpg")
def download_shares(): while True: desired = yield self.node.desired_var.get_when_satisfies(lambda val: len(val) != 0) peer_addr, share_hash = random.choice(desired) if len(self.peers) == 0: yield deferral.sleep(1) continue peer = random.choice(self.peers.values()) print 'Requesting parent share %s from %s' % (p2pool_data.format_hash(share_hash), '%s:%i' % peer.addr) try: shares = yield peer.get_shares( hashes=[share_hash], parents=random.randrange(500), # randomize parents so that we eventually get past a too large block of shares stops=list(set(self.node.tracker.heads) | set( self.node.tracker.get_nth_parent_hash(head, min(max(0, self.node.tracker.get_height_and_last(head)[0] - 1), 10)) for head in self.node.tracker.heads ))[:100], ) except defer.TimeoutError: print 'Share request timed out!' continue except: log.err(None, 'in download_shares:') continue if not shares: yield deferral.sleep(1) # sleep so we don't keep rerequesting the same share nobody has continue self.handle_shares([(share, []) for share in shares], peer)
def __init__(self, game, where= 0, adjective="", description="", boss=False, carrier=False): self.number = Monster.number Monster.number += 1 game.monsters[self.number] = self # add monster into game dict self.adjective = adjective self.location = where # room number self.description = description self.hitpoints = random.randint(5,15) self.player = False self.carrier = carrier # can carry items ? self.attack = 10 + random.randint(-2,2) self.defense = 10 + random.randint(-2,2) self.speed = 10 + random.randint(-2,2) self.damage = 3 + random.randint(-2,2) self.armor = 3 + random.randint(-2,2) self.agressive = False self.slots = {"head":1, "body":1, "hand":2, "finger":2, "neck":1, "feet":2} # only one magic ring per ring-finger if description == "": if boss: self.adjective = random.choice(("deadly","fantastic", "creepy","ugly","epic")) self.description = random.choice(("dragon","cave drake", "sea serpent","gorgon","giant beetle","arch druid")) self.hitpoints *= 5 self.attack += random.randint(2,7) self.defense += random.randint(2,7) self.speed += random.randint(2,7) else: self.adjective = random.choice(("weak","boring", "tired","cheap","old")) self.description = random.choice(("goblin","ork","troll", "mice","rat","dwarf","spider"))
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 get_npc_belongings(npc_dict, level, npc_class): level = int(level) npc_belongings_value = int(level) * 100 * rd.gauss(1,0.5) weapons = [] armors = [] belongings = "" try: assert npc_belongings_value >= 0 for i in range(int(level / 5) + 1): choose_weapon = rd.choice(npc_dict["weapon"]) choose_armor = rd.choice(npc_dict["armor"]) weapons.append(choose_weapon[0]) armors.append(choose_armor[0]) npc_belongings_value -= (int(choose_weapon[1]) + int(choose_armor[1])) except AssertionError: for armor in armors: belongings += armor + ", " belongings = belongings[:-2] + "\n" for weapon in weapons: belongings += weapon + ", " return belongings for armor in armors: belongings += armor + ", " belongings = belongings[:-2] + "\n" for weapon in weapons: belongings += weapon + ", " belongings = belongings[:-2] + "\n" while npc_belongings_value > 0: chosen_item = rd.choice(npc_dict["other"]) belongings += chosen_item[0] + ", " npc_belongings_value -= int(chosen_item[1]) belongings = belongings[:-2] + "\n" return get_npc_ac(armors, npc_class), belongings
def get_npc_name(npc_dict, race, gender): race = race.lower() gender = gender.lower() names = npc_dict["{}_names".format(race)] preffixes = [] intermediate = [] suffixes = [] if gender is "male" or gender is "m": gender = "m" else: gender = "f" for value_lists in names: if value_lists[0] == "{}pre".format(gender): preffixes.append(value_lists[1]) else: preffixes.append(value_lists[1]) if "{}suf".format(gender) == value_lists[0]: suffixes.append(value_lists[1]) else: suffixes.append(value_lists[1]) if "{}in".format(gender) == value_lists[0]: intermediate.append(value_lists[1]) else: intermediate.append("") return rd.choice(preffixes) + rd.choice(intermediate) + rd.choice(suffixes)
def test_call(self): db = yield tnt.Connection(tnt_host, tnt_port, reconnect=False) data = ( ( ''.join(choice(insert_string_choice) for x in xrange(randint(0, insert_string_length_max))), randint(0, 2 ** 32 - 1), long(randint(0, 2 ** 64 - 1)), ), ( randint(0, 2 ** 32 - 1), ''.join(choice(insert_string_choice) for x in xrange(randint(0, insert_string_length_max))), long(randint(0, 2 ** 64 - 1)), ), ( long(randint(0, 2 ** 64 - 1)), randint(0, 2 ** 32 - 1), ''.join(choice(insert_string_choice) for x in xrange(randint(0, insert_string_length_max))), ), ) for t in data: r = yield db.call("box.insert", tuple(type(x) for x in t), str(space_no0), *t) self.assertEqual(len(r), 1) self.assertEqual(t, r[0]) for t in data: r = yield db.call("box.select", tuple(type(x) for x in t), str(space_no0), "0", t[0]) self.assertEqual(len(r), 1) self.assertEqual(t, r[0]) yield db.disconnect()
def test_insert_list(self): db = yield tnt.Connection(tnt_host, tnt_port, reconnect=False) data = ( ( ''.join(choice(insert_string_choice) for x in xrange(randint(0, insert_string_length_max))), randint(0, 2 ** 32 - 1), long(randint(0, 2 ** 64 - 1)), ), ( randint(0, 2 ** 32 - 1), ''.join(choice(insert_string_choice) for x in xrange(randint(0, insert_string_length_max))), long(randint(0, 2 ** 64 - 1)), ), ( long(randint(0, 2 ** 64 - 1)), randint(0, 2 ** 32 - 1), ''.join(choice(insert_string_choice) for x in xrange(randint(0, insert_string_length_max))), ), ) defer_list = [] for t in data: r = db.insert(space_no0, *t) defer_list.append(r) result = yield defer.DeferredList(defer_list) for status, r in result: self.assertTrue(status) self.assertEqual(len(r), 0) self.assertIn(" inserted", repr(r)) yield db.disconnect()
def test_insert_ret_list(self): db = yield tnt.Connection(tnt_host, tnt_port, reconnect=False) data = ( ( ''.join(choice(insert_string_choice) for x in xrange(randint(0, insert_string_length_max))), randint(0, 2 ** 32 - 1), long(randint(0, 2 ** 64 - 1)), ), ( randint(0, 2 ** 32 - 1), ''.join(choice(insert_string_choice) for x in xrange(randint(0, insert_string_length_max))), long(randint(0, 2 ** 64 - 1)), ), ( long(randint(0, 2 ** 64 - 1)), randint(0, 2 ** 32 - 1), ''.join(choice(insert_string_choice) for x in xrange(randint(0, insert_string_length_max))), ), ) defer_list = [] for t in data: r = db.insert_ret(space_no0, tuple(type(x) for x in t), *t) defer_list.append(r) result = yield defer.DeferredList(defer_list) for i, r in enumerate(result): self.assertTrue(r[0]) self.assertEqual(len(r[1]), 1) self.assertEqual(data[i], r[1][0]) yield db.disconnect()
def test_insert(self): db = yield tnt.Connection(tnt_host, tnt_port, reconnect=False) data = ( ( ''.join(choice(insert_string_choice) for x in xrange(randint(0, insert_string_length_max))), randint(0, 2 ** 32 - 1), long(randint(0, 2 ** 64 - 1)), ), ( randint(0, 2 ** 32 - 1), ''.join(choice(insert_string_choice) for x in xrange(randint(0, insert_string_length_max))), long(randint(0, 2 ** 64 - 1)), ), ( long(randint(0, 2 ** 64 - 1)), randint(0, 2 ** 32 - 1), ''.join(choice(insert_string_choice) for x in xrange(randint(0, insert_string_length_max))), ), ) for t in data: r = yield db.insert(space_no0, *t) self.assertEqual(len(r), 0) self.assertIn(" inserted", repr(r)) yield db.disconnect()
def genQuarters(main_cells): quarter_cells = [] prev_note = -3 pre_prev_note = -2 for main_cell in main_cells: main_pits = [i[0] for i in main_cell.beat_pits] if len(main_pits) == 1: main_pits.append(None) #we have a "Free" note if main_cell.chord == None or main_cell.chord == []: quarter_cells.append(gc.genBlankCell(2.0)) else: pits = [] for main_pit in main_pits: if main_pit == None: if pre_prev_note == prev_note: pits.append(sc.closestNoteDegreeInChord(prev_note + random.choice([-2,2]), main_cell.chord)) else: pits.append(sc.closestNoteDegreeInChord(prev_note, main_cell.chord)) else: closest_chord_notes = sc.closestNotesInChord(prev_note + random.choice([-2,2]), main_cell.chord) closest_chord_notes = filter(lambda i: i > -7, closest_chord_notes) for chord_note in closest_chord_notes: if hm.matches(chord_note, main_pit): pits.append(chord_note) break pre_prev_note = prev_note prev_note = pits[-1] durs = [1.0,1.0] quarter_cells.append(Chunk(pits=pits, durs=durs, chord=main_cell.chord, key = main_cell.key)) prev_note = quarter_cells[-1].pits[-1] return quarter_cells
def spawn_number(self, *args): empty = list(self.iterate_empty()) if not empty: return value = choice([2]*9+[4]) ix, iy = choice(empty) self.spawn_number_at(ix, iy, value)
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)
def reset_password(self, user): if not user: return { 'status': 'error', 'message': "You must pass a user to reset a password", 'data': None } if user.has_key('status'): if user['status'] == 'ok': user = user['data'] else: return user # generate random password password = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8)) # crypt password cpassword = crypt.crypt(password, ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(2))) # update the user entry in the DB self.users_db.execute("UPDATE users SET password=? WHERE login=?", (cpassword, user['login'], )) # send the user a mail with the new password email = user['email'] messageSubject = "anvio password reset" messageText = "You have requested your password for your anvi'o account to be reset.\n\nYour new password is:\n\n"+password+"\n\nPlease log into anvi'o with these credentials and change your password."; self.mailer.send(email, messageSubject, messageText) return { 'status': 'ok', 'message': "User password reset, message sent to %s" % email, 'data': None }
def encode(f): var_name = ''.join( random.choice(string.ascii_lowercase + string.ascii_uppercase) for i in range(50)) if _version is 2: rev_data = binascii.b2a_base64(f)[-2::-1] data = var_name + ' = "' + str(rev_data) + '"' if _version is 3: rev_data = binascii.b2a_base64(f.encode('utf8')).decode('utf8')[-2::-1] data = var_name + ' = "' + str(rev_data) + '"' func_name = ''.join( random.choice(string.ascii_lowercase + string.ascii_uppercase) for i in range(50)) func_argv = ''.join( random.choice(string.ascii_lowercase + string.ascii_uppercase) for i in range(50)) f = ''' import binascii import sys %s def %s(%s): if sys.version_info.major is 2: return str(binascii.a2b_base64(%s[::-1])) elif sys.version_info.major is 3: return str(binascii.a2b_base64(%s[::-1]).encode('utf8'))[::-1].decode('utf8') else: sys.exit('Your python version is not supported!') exec(%s(%s)) ''' % (data, func_name, func_argv, func_argv, func_argv, func_name, var_name) return f
def handle(self, *args, **options): users = list(User.objects.all()) for i in range(10): t = Topic() t.name = u'Topic Name {}'.format(i) t.description = u'Topic Description {}'.format(i) t.save() topics = list(Topic.objects.all()) for j in range(100): q = Question() q.author = random.choice(users) q.title = u'title {}'.format(j) q.text = u'text {}'.format(j) q.pub_date = datetime.datetime.now() q.is_published = True q.save() q.topics = random.sample(topics, random.randint(1, 6)) questions = list(Question.objects.all()) for k in range(100): c = Comment() c.author = random.choice(users) c.question = random.choice(questions) c.text = u'text {}'.format(k) c.pub_date = datetime.datetime.now() c.save()
def window_seg(floors, is_door=True): """Randomly generated window segment of tower. """ windowed = BEAM + (random.choice([' ', WINDOW]) if is_door else HI_BEAM) for _ in range(1, floors): windowed += BLANK + random.choice([' ', WINDOW]) return windowed + BEAM
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()
def generate(data): m = random.choice([3, 1.4, 1.6, 1.8]) h = random.choice([4, 12, 14, 16]) d = 1.5*h g = 9.8 v0xmin = d*math.sqrt(g/(2*h)) v0x = round(random.choice([4, v0xmin*1.4, v0xmin*1.6, v0xmin*1.8]), 3) data["params"]["m"] = m data["params"]["h"] = h data["params"]["d"] = d data["params"]["v0x"] = v0x t = d/v0x data["params"]["t_c"] = round(t, 3) data["params"]["t_x1"] = round(math.sqrt(2*h/g), 3) data["params"]["t_x2"] = round(v0x*2/g, 3) v0y = 0.5*g*t - h/t data["params"]["vy_c"] = round(v0y, 2) data["params"]["vy_x1"] = round(-math.sqrt((g*t)**2 + v0x**2/2), 2) data["params"]["vy_x2"] = round( -0.5*g*t - h/2, 2) data["params"]["vy_x3"] = round(-math.sqrt(v0x**2 + v0y**2), 2) data["params"]["vy_x4"] = 0
def __init__(self, alphabet=['A', 'B', 'C'], motifs=['ABC'], m=0.2, size=100): """Generate a new random sequence. Parameters: - alphabet: a list of letters - motifs : a list of strings - m : probability of starting a motif at a random position of the sequence - size : length of the sequence """ self.alphabet = set(alphabet) for motif in motifs: self.alphabet = self.alphabet.union(motif) self.alphabet = list(self.alphabet) self.motifs = motifs # Motif average length L = sum(len(motif) for motif in motifs)/float(len(motifs)) p = m*L # threshold to insert a new motif s = '' # random string n = 0 # string length while n < size: motif = random.choice(motifs) w = len(motif) if random.random() <= p: s += motif else: for i in xrange(w): s += random.choice(self.alphabet) n += w super(TestSequence, self).__init__(s[:size])
def ss(): families = [] mapping = {} with open('easy-248.txt') as f: for line in f.readlines(): families.append(line.split()) families.sort(key = lambda x: -len(x)) recip = [] for family in families: recip.append(family[:]) for (i, family) in enumerate(families): for person in family: # select a family other_families = list(range(len(recip))) other_families.remove(i) random_family = random.choice(other_families) fail_count = 0 while len(recip[random_family]) == 0: if fail_count > len(families): return {} random_family = random.choice(other_families) # select a member within that family random_member = random.choice(recip[random_family]) mapping[person] = random_member # remove from recip list recip[random_family].remove(random_member) return mapping
def addChemotaxis(CompuCell3DElmnt, config): PluginElmnt_4=CompuCell3DElmnt.ElementCC3D("Plugin",{"Name":"Chemotaxis"}) # Select chemical field? ChemicalFieldElmnt=PluginElmnt_4.ElementCC3D("ChemicalField",{"Name":"FDS","Source":"DiffusionSolverFE"}) # Define chemotaxis for cell type # TODO: iterate over cell types addedChemo = False for cell in range(1, config["numCellTypes"] + 1): if random.choice([True, False]): addedChemo = True ChemicalFieldElmnt.ElementCC3D("ChemotaxisByType",{"Lambda":getChemotaxisLambda(),"Type":str(cell)}) elif cell == config["numCellTypes"] and addedChemo == False: # Always add chemotaxis for at least one cell type ChemicalFieldElmnt.ElementCC3D("ChemotaxisByType",{"Lambda":getChemotaxisLambda(),"Type":"1"}) # Define chemical field SteppableElmnt=CompuCell3DElmnt.ElementCC3D("Steppable",{"Type":"DiffusionSolverFE"}) DiffusionFieldElmnt=SteppableElmnt.ElementCC3D("DiffusionField",{"Name":"FDS"}) DiffusionDataElmnt=DiffusionFieldElmnt.ElementCC3D("DiffusionData") DiffusionDataElmnt.ElementCC3D("FieldName",{},"FDS") DiffusionDataElmnt.ElementCC3D("GlobalDiffusionConstant",{},randomFloatStr(0, 1.0)) DiffusionDataElmnt.ElementCC3D("GlobalDecayConstant",{},randomFloatStr(0, 1.0)) secretionDataElement = DiffusionFieldElmnt.ElementCC3D("SecretionData") addedSecretion = False for cell in range(1, config["numCellTypes"] + 1): if random.choice([True, False]): addedSecretion = True secretionDataElement.ElementCC3D("Secretion", {"Type":str(cell)}, randomFloatStr(0.0, 100)) elif cell == config["numCellTypes"] and addedSecretion == False: # Always add secretion for at least one cell type secretionDataElement.ElementCC3D("Secretion", {"Type":"1"}, randomFloatStr(0.0, 100))
def run_simulation(args, client): """This function performed one test run using the args parameters and connecting to the carla client passed. """ display_manager = None vehicle = None vehicle_list = [] timer = CustomTimer() try: # Getting the world and world = client.get_world() original_settings = world.get_settings() if args.sync: traffic_manager = client.get_trafficmanager(8000) settings = world.get_settings() traffic_manager.set_synchronous_mode(True) settings.synchronous_mode = True settings.fixed_delta_seconds = 0.05 world.apply_settings(settings) # Instanciating the vehicle to which we attached the sensors bp = world.get_blueprint_library().filter('charger2020')[0] vehicle = world.spawn_actor( bp, random.choice(world.get_map().get_spawn_points())) vehicle_list.append(vehicle) #vehicle.set_autopilot(True) # Display Manager organize all the sensors an its display in a window # If can easily configure the grid and the total window size display_manager = DisplayManager(grid_size=[1, 1], window_size=[args.width, args.height]) # Then, SensorManager can be used to spawn RGBCamera, LiDARs and SemanticLiDARs as needed # and assign each of them to a grid position, # SensorManager(world, display_manager, 'RGBCameraleft', carla.Transform(carla.Location(x=0, z=2.4), carla.Rotation(yaw=-60)), # vehicle, {}, display_pos=[0, 1]) SensorManager(world, display_manager, 'RGBCameramid', carla.Transform(carla.Location(x=0, z=2.4), carla.Rotation(yaw=+00)), vehicle, {}, display_pos=[0, 0]) # SensorManager(world, display_manager, 'RGBCameraright', carla.Transform(carla.Location(x=0, z=2.4), carla.Rotation(yaw=+60)), # vehicle, {}, display_pos=[0, 2]) #SensorManager(world, display_manager, 'RGBCamera', carla.Transform(carla.Location(x=0, z=2.4), carla.Rotation(yaw=180)), # vehicle, {}, display_pos=[1, 1]) # SensorManager(world, display_manager, 'LiDAR', carla.Transform(carla.Location(x=0, z=2.4)), # vehicle, {'channels' : '64', 'range' : '50', 'points_per_second': '100000', 'rotation_frequency': '20'}, display_pos=[1, 0]) #SensorManager(world, display_manager, 'SemanticLiDAR', carla.Transform(carla.Location(x=0, z=2.4)), # vehicle, {'channels' : '64', 'range' : '100', 'points_per_second': '100000', 'rotation_frequency': '20'}, display_pos=[1, 2]) # state 0: find which road , # 1 : already find calculate junction distance # 2 : on junction, keeps find if find road not junction to state 0 state = 0 #Simulation loop global record_on global no global saved_rgb call_exit = False time_init_sim = timer.time() find_on = 0 if find_on == 1: road_points = world.get_map().generate_waypoints(distance=4.0) while True: # Carla Tick if args.sync: world.tick() else: world.wait_for_tick() if find_on == 1: position = vehicle.get_location() acc = vehicle.get_acceleration() #start=((acc.x==0) and (acc.y==0)and (acc.z==0)) if find_on == 1: if state == 0: this_w = find_road(road_points, position, acc) try: if this_w.is_junction: state = 0 else: state = 1 distance_last = 1000 except: pass elif state == 1: try: ww_pos = cal_junct(road_points, this_w, position) distance = sqrt((ww_pos.x - position.x)**2 + (ww_pos.y - position.y)**2 + (ww_pos.z - position.z)**2) if distance > distance_last: state = 0 distance_last = distance #print("------------------------\n", end='\r') #print("Which lane: \n",this_w.lane_id, end='\r') print(distance, end='\r') #print("------------------------", end='\r') if distance <= 5: state = 0 except: state = 0 # Render received data display_manager.render() #print("current time : ",timer.time()) if find_on == 1: if this_w == "c": print("can not find road", end='\r') for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == K_g: record_on += 1 if record_on % 2 == 0: record_on = 0 print("---------------") print("End recording!") print("Starting output!") print("---------------") for image in saved_rgb: image.save_to_disk( '_out/mid_camera/%03d/%08d' % (no, image.frame)) saved_rgb.clear() no += 1 else: print("---------------") print("Start recording!") print("---------------") if control(vehicle): return if call_exit: break finally: if display_manager: display_manager.destroy() client.apply_batch( [carla.command.DestroyActor(x) for x in vehicle_list]) world.apply_settings(original_settings)
def runs(bot: Bot, update: Update): update.effective_message.reply_text(random.choice(fun_strings.RUN_STRINGS))
def parse(self,url, store_name): response = requests.get(url,headers=random.choice(headers)) number = 0 while True: try: info_dict = json.loads(response.text) info_list = info_dict['data'] if info_list: break else: print('some wrong') number += 1 if number >= 10: return None time.sleep(10) response = requests.get(url, headers=random.choice(headers)) except: number += 1 if number >= 10: return None time.sleep(10) response = requests.get(url, headers=random.choice(headers)) ##用户总体评价 taglist = [] try: for comment in info_list['tags']: count = comment['count'] tag = comment['tag'] tag_item = { '标签':tag, '累计数量':count } taglist.append(tag_item) except TypeError: # if no tags information taglist = [] ##用户具体评价 itemlist = [] for comment in info_list['comments']: username = comment['userName'] avgPrice = comment['avgPrice'] user_comment = comment['comment'] commenttime = comment['commentTime'] menu = comment['menu'] dealEndtime = comment['dealEndtime'] star = comment['star'] item = { '店名': store_name, '用户名': username, '平均消费': avgPrice, '星级': star, '菜单': menu, '评价时间': commenttime, '用餐结束时间': dealEndtime, '评价': user_comment } itemlist.append(item) return taglist, itemlist
def get_computer_move(self, f1): choice = random.choice(list(self.valid_answers.values())) self.retract(f1) self.declare(ComputerChoice(choice)) self.declare(Action('determine-results'))
def abuse(bot: Bot, update: Update): reply_text = update.effective_message.reply_to_message.reply_text if update.effective_message.reply_to_message else update.effective_message.reply_text reply_text(random.choice(fun_strings.ABUSE_STRINGS))
def toss(bot: Bot, update: Update): update.message.reply_text(random.choice(fun_strings.TOSS))
def roll(bot: Bot, update: Update): update.message.reply_text(random.choice(range(1, 7)))
def decide(bot: Bot, update: Update): reply_text = update.effective_message.reply_to_message.reply_text if update.effective_message.reply_to_message else update.effective_message.reply_text reply_text(random.choice(fun_strings.DECIDE))
def choose_random_move(board): positions = renju.list_positions(board, renju.Player.NONE) return renju.to_move(random.choice(positions))
def table(bot: Bot, update: Update): reply_text = update.effective_message.reply_to_message.reply_text if update.effective_message.reply_to_message else update.effective_message.reply_text reply_text(random.choice(fun_strings.TABLE))
def string_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size))
def ya(): one = 6 #total lives con = 0 ba = "_" numbers = [ ] #this is to read the document data2.txt and chose a ramdom word with open("data2.txt", "r", encoding="utf-8") as files: for line in files: if line == "\n": break numbers.append(line) txt = random.choice(numbers) for i in txt: con = con + 1 print(txt) ba = ba * (con - 1) #define each letter in the word chosed to space t = 0 s = 0 abu = [] mangos = 0 time = [] while t == 0: os.system("cls") hangman(one) print(ba) cont = 0 cont2 = 0 p = 0 #if s == 0: # ba=ba*7 # s=1 if mangos == 0: for i in txt: cont = cont + 1 abu.append(i) mangos = 1 while p == 0: if one == 1: os.system("cls") print("sorry ,end game ¡¡¡¡") break try: a = input("!guess the word¡") z = abu.index(a) p = 1 except ValueError: os.system("cls") one = one - 1 hangman(one) print(ba) p = 0 for i in abu: cont2 = cont2 + 1 if i == a: string_list = list(ba) cont2 = cont2 - 1 string_list[cont2] = a ba = "".join(string_list) cont2 = cont2 + 1 if one == 1: os.system("cls") print("sorry ,end game ¡¡¡¡") break if ba + "\n" == txt: os.system("cls") print("congratulations : the word is ", ba) break
def colorAleatorio(): opciones= [NEGRO, MORADO, ROJO, AZUL,VERDE_BANDERA] color = random.choice(opciones) return color
def random_rsp(): '''무작위 가위바위보''' import random return random.choice(['가위', '바위', '보'])
def runs(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] update.effective_message.reply_text(random.choice(tld(chat.id, "RUNS-K")))
def get_shape(): return Piece(5, 0, random.choice(shapes))
def use(network="dark", custom_seed=None, broadcast=10, latency=1): """ Select ARK network. Keyword argument: network (str) -- network name you want to connetc with custom_seed (str) -- a custom peer you want to choose broadcast (int) -- max valid peer number to use for broadcasting latency (int) -- max latency you want in second Returns None """ global SEEDS, PEERS, ROOT # find network configuration files (*.net) and load it if a filename match asked # network else throw error networks = [os.path.splitext(name)[0] for name in os.listdir(ROOT) if name.endswith(".net")] if len(networks) and network in networks: in_ = open(os.path.join(ROOT, network + ".net"), "r") data = json.load(in_) in_.close() network_properties = ([k, v] for k, v in data.items() if k in ["wif", "pubKeyHash", "messagePrefix"]) for key, value in network_properties: data[key] = binascii.unhexlify(value) cfg.__NETWORK__.update(arkydify(data)) else: raise NetworkError("Unknown %s network properties" % network) # update logger data so network appear on log logger = logging.getLogger() logger.handlers[0].setFormatter(logging.Formatter('[%s]' % network + '[%(asctime)s] %(message)s')) # in js month value start from 0, in python month value start from 1 cfg.__BEGIN_TIME__ = datetime.datetime(2017, 3, 21, 13, 0, 0, 0, tzinfo=UTC) cfg.__NET__ = network # find seeds if custom_seed: seed_list = [custom_seed] else: port = cfg.__NETWORK__.port seed_list = ["http://%s:%s" % (ip, port) for ip in cfg.__NETWORK__.seeds] if not len(seed_list): sys.ps1 = "cold@%s>>> " % network sys.ps2 = "cold@%s... " % network cfg.__HOT_MODE__ = False PEERS = SEEDS = [] return # select a valid seed SEEDS = [] while not len(SEEDS) >= min(5, len(seed_list)): temp = random.choice(seed_list) if checkPeerLatency(temp, timeout=latency): SEEDS.append(temp) seed_list.pop(seed_list.index(temp)) if not len(SEEDS): sys.ps1 = "cold@%s>>> " % network sys.ps2 = "cold@%s... " % network cfg.__HOT_MODE__ = False PEERS = SEEDS = [] return # get all valid peers api_peers = [] while not len(api_peers): try: result = requests.get(random.choice(SEEDS) + "/api/peers", timeout=latency).json() api_peers = result.get("peers", []) except requests.exceptions.ConnectionError: sys.ps1 = "cold@%s>>> " % network sys.ps2 = "cold@%s... " % network cfg.__HOT_MODE__ = False PEERS = SEEDS = [] return peer_list = [] result = requests.get(random.choice(SEEDS) + '/api/peers/version', timeout=latency).json() version = result.get("version", '0.0.0') good_peers = ["http://%(ip)s:%(port)s" % p for p in api_peers if p["status"] == "OK" and p["version"] == version] random.shuffle(good_peers) # select a set of peers for transaction broadcasting for peer in good_peers: if checkPeerLatency(peer, timeout=latency): peer_list.append(peer) if len(peer_list) == broadcast: break if not len(peer_list): sys.ps1 = "cold@%s>>> " % network sys.ps2 = "cold@%s... " % network cfg.__HOT_MODE__ = False PEERS = SEEDS = [] return PEERS = peer_list # finish network conf cfg.__FEES__.update(get('/api/blocks/getFees', returnKey="fees")) autoconf = get('/api/loader/autoconfigure', returnKey="network") cfg.__EXPLORER__ = autoconf.get("explorer", False) cfg.__SYMBOL__ = autoconf.get("symbol", False) cfg.__TOKEN__ = autoconf.get("token", False) cfg.__HEADERS__.update({ 'Content-Type': 'application/json; charset=utf-8', 'os': 'arky', 'port': '1', 'version': __version__, 'nethash': autoconf.get("nethash", "") }) sys.ps1 = "@%s>>> " % network sys.ps2 = "@%s... " % network cfg.__HOT_MODE__ = True
def _make_transaction_id(): a = ''.join([random.choice('0123456789ABCDEF') for x in range(24)]) return binascii.a2b_hex(a)
#!/usr/bin/env python3.5 # encoding: utf-8 # Created by leiwei on 2020/8/17 15:25 import random nums = [2, 3, 15, [23, 34, 67], 43, 7, 5, 9] teachers = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'G', 'K', 'M'] rooms = [[], [], []] for teacher in teachers: room = random.choice(rooms) # choice 从列表中随机选择一个数据 room.append(teacher) print(rooms)
def insults(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] text = random.choice(tld(chat.id, "INSULTS-K")) update.effective_message.reply_text(text)
def getAction( self, state ): return random.choice( state.getLegalActions( self.index ) )
# Body of the Snake body = [] # Get Your snake something to eat ;) colours = [ 'blue', 'magenta', 'yellow', 'red', 'lightgreen', 'lightblue', 'brown', 'black' ] food = turtle.Turtle() food.shape("turtle") food.color(random.choice(colours)) food.pu() # Functions for the Movement of the Snake def goup(): if head.direction != "down": head.direction = "up" def godown():
def chooseWord(wordlist): return random.choice(wordlist)
for order in ['forward', 'reverse']: if(order == 'forward'): direct = exampleSites[0] modelled = exampleSites[1] elif(order == 'reverse'): direct = exampleSites[1] modelled = exampleSites[0] agesToConsider = [age for age in sorted(allAgesSampled) if ( ((age >= min(zoomXRange))and(age <= max(zoomXRange))) and (datasetModels[direct].ageValueInRawData(age) and datasetModels[modelled].ageValueIsInRangeCoveredByModel(age)) )] for age in agesToConsider: print age demoComparisonPoint = random.choice(agesToConsider) print "-> ", demoComparisonPoint directElevation = datasetObjects[direct].getElevationByGivenAge(demoComparisonPoint) modelledElevation = datasetModels[modelled].getModelledElevation(demoComparisonPoint) print "Direct [%s]:" % direct, directElevation print "Modelled [%s]:" % modelled, modelledElevation ##plt.plot([demoComparisonPoint, demoComparisonPoint], [directElevation, modelledElevation], "%s" % mapSiteToColour(direct), linewidth=3.0) plt.plot([demoComparisonPoint, demoComparisonPoint], [directElevation, modelledElevation], "%s-." % mapSiteToColour(direct), linewidth=2.0) ##'--' ##plt.title("Plot of Elevation by Age\nRaw Data with Model") plt.ylabel('Elevation (m IGLD1985)')
config = InferenceConfig() # Create model object in inference mode. model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config) # Load weights trained on MS-COCO # model_path = model.find_last() model_path = os.path.join(ROOT_DIR, "logs/coco_vrepall_1002.h5") # model.load_weights(COCO_MODEL_PATH, by_name=True) model.load_weights(model_path, by_name=True) class_names = ['BG', 'SlidingDoor', 'Wall', 'Shelf', 'Robot', 'Human', 'ConveyorBelt', 'Dockstation', 'Product'] # Load a random image from the images folder file_names = next(os.walk(IMAGE_DIR))[2] image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names))) # calculate time cost for detection, a is start time, b is end time a = time.time() # Run detection # if verbose == 1, more information print on terminal results = model.detect([image], verbose=1) b = time.time() load_detect_cost = b - a # Visualize results print("----------------------------------------------------------------------") print("Loading weights from ", model_path) print("Load and Detection time for this image is %.3f seconds" % load_detect_cost ) r = results[0] visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'],
def get_size(self): return '%dx%d' % (random.choice(self._sizes), random.choice(self._sizes))
import os import time from random import choice from models import Journal from pony.orm import commit, db_session LEVEL_CHOICE = [10, 20, 30, 40, 50] count = int(os.environ.get('ITERATIONS', '1000')) start = now = time.time() for i in range(count): with db_session(): Journal(level=choice(LEVEL_CHOICE), text=f'Insert from A, item {i}') commit() now = time.time() print(f'Pony ORM, A: Rows/sec: {count / (now - start): 10.2f}')
def dare(update: Update, context: CallbackContext): args = context.args update.effective_message.reply_text( random.choice(truth_and_dare_string.DARE))
async def on_message(message): # we do not want the bot to reply to itself if message.author == client.user: return if message.content.startswith('!start'): # ") await message.channel.send("Введи !Камень,!Ножницы или !Бумага") if message.content.startswith('!Камень'): list1 = [] list1.append("Камень") print(message.author.mention + "\n" + "поставил\n"+list1[0].lower()+".\n\n") list2 = ['Бумага', 'Камень', 'Ножницы'] rand = random.choice(list2) if(list1[0] == rand): await message.channel.send("Бот выбрал " + rand.lower()+".") await message.channel.send("Ничья!") bot_player = {"Бот": win_bot[0], "Игрок": win_player[0] } await message.channel.send("Бот - " + str(bot_player["Бот"]) + "\n") await message.channel.send("Игрок - " + str(bot_player["Игрок"]) + "\n") print("\n\nБот - " + str(bot_player["Бот"]) + "\n") print("Игрок - " + str(bot_player["Игрок"]) + "\n") if(list1[0] == 'Бумага'and rand == 'Камень'): await message.channel.send("Бот выбрал " + rand.lower()+".") await message.channel.send("Ты победил") win_player.append(win_player[-1]+1) bot_player = {"Бот": win_bot[-1], "Игрок": win_player[-1] } await message.channel.send("Бот - " + str(bot_player["Бот"]) + "\n") await message.channel.send("Игрок - " + str(bot_player["Игрок"]) + "\n") print("\n\nБот - " + str(bot_player["Бот"]) + "\n") print("Игрок - " + str(bot_player["Игрок"]) + "\n") if(list1[0] == 'Камень'and rand == 'Бумага'): await message.channel.send("Бот выбрал " + rand.lower()+".") await message.channel.send("Ты проиграл(") win_bot.append(win_bot[-1]+1) bot_player = {"Бот": win_bot[-1], "Игрок": win_player[-1] } await message.channel.send("Бот - " + str(bot_player["Бот"]) + "\n") await message.channel.send("Игрок - " + str(bot_player["Игрок"]) + "\n") print("\n\nБот - " + str(bot_player["Бот"]) + "\n") print("Игрок - " + str(bot_player["Игрок"]) + "\n") if(list1[0] == 'Ножницы'and rand == 'Камень'): await message.channel.send("Бот поставил " + rand.lower()+".") await message.channel.send("Вы проиграли!") win_bot.append(win_bot[-1]+1) bot_player = {"Бот": win_bot[-1], "Игрок": win_player[-1] } await message.channel.send("Бот - " + str(bot_player["Бот"]) + "\n") await message.channel.send("Игрок - " + str(bot_player["Игрок"]) + "\n") print("\n\nБот - " + str(bot_player["Бот"]) + "\n") print("Игрок - " + str(bot_player["Игрок"]) + "\n") if(list1[0] == 'Камень'and rand == 'Ножницы'): await message.channel.send("Бот поставил " + rand.lower()+".") await message.channel.send("Вы победили!") win_player.append(win_player[-1]+1) bot_player = {"Бот": win_bot[-1], "Игрок": win_player[-1] } await message.channel.send("Бот - " + str(bot_player["Бот"]) + "\n") await message.channel.send("Игрок - " + str(bot_player["Игрок"]) + "\n") print("\n\nБот - " + str(bot_player["Бот"]) + "\n") print("Игрок - " + str(bot_player["Игрок"]) + "\n") if(list1[0] == 'Бумага'and rand == 'Ножницы'): await message.channel.send("Бот поставил " + rand.lower()+".") await message.channel.send("Вы проиграли!") win_bot.append(win_bot[-1]+1) bot_player = {"Бот": win_bot[-1], "Игрок": win_player[-1] } await message.channel.send("Бот - " + str(bot_player["Бот"]) + "\n") await message.channel.send("Игрок - " + str(bot_player["Игрок"]) + "\n") print("\n\nБот - " + str(bot_player["Бот"]) + "\n") print("Игрок - " + str(bot_player["Игрок"]) + "\n") if(list1[0] == 'Ножницы'and rand == 'Бумага'): await message.channel.send("Бот поставил " + rand.lower()+".") await message.channel.send("Вы победили!") win_player.append(win_player[-1]+1) bot_player = {"Бот": win_bot[-1], "Игрок": win_player[-1] } await message.channel.send("Бот - " + str(bot_player["Бот"]) + "\n") await message.channel.send("Игрок - " + str(bot_player["Игрок"]) + "\n") print("\n\nБот - " + str(bot_player["Бот"]) + "\n") print("Игрок - " + str(bot_player["Игрок"]) + "\n") # ------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------------- if message.content.startswith('!Бумага'): list1 = [] list1.append("Бумага") print(message.author.mention + "\n" + "поставил\n"+list1[0].lower()+".\n\n") list2 = ['Бумага', 'Камень', 'Ножницы'] rand = random.choice(list2) check_win(answer, rand) # ------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------------- if message.content.startswith('!Ножницы'): list1 = [] list1.append("Ножницы") print(message.author.mention + "\n" + "поставил\n"+list1[0].lower()+".\n\n") list2 = ['Бумага', 'Камень', 'Ножницы'] rand = random.choice(list2) check_win(answer, rand) if message.content.startswith('!leave'): await message.channel.send(second_comand[0]+'\n'+second_comand[1]+'\n'+second_comand[2])
def __init__(self, nodeid, plen, distance, bs): global experiment global Ptx global gamma global d0 global var global Lpld0 global GL # new: base station ID self.bs = bs self.nodeid = nodeid # randomize configuration values self.sf = random.randint(6,12) self.cr = random.randint(1,4) self.bw = random.choice([125, 250, 500]) # for certain experiments override these if experiment==1 or experiment == 0: self.sf = 12 self.cr = 4 self.bw = 125 # for certain experiments override these if experiment==2: self.sf = 6 self.cr = 1 self.bw = 500 # for experiment 3 find the best setting # OBS, some hardcoded values Prx = Ptx ## zero path loss by default # log-shadow Lpl = Lpld0 + 10*gamma*math.log(distance/d0) print (Lpl) Prx = Ptx - GL - Lpl if (experiment == 3): minairtime = 9999 minsf = 0 minbw = 0 for i in range(0,6): for j in range(1,4): if (sensi[i,j] < Prx): self.sf = sensi[i,0] if j==1: self.bw = 125 elif j==2: self.bw = 250 else: self.bw=500 at = airtime(self.sf,4,20,self.bw) if at < minairtime: minairtime = at minsf = self.sf minbw = self.bw self.rectime = minairtime self.sf = minsf self.bw = minbw if (minairtime == 9999): print ("does not reach base station") exit(-1) # transmission range, needs update XXX self.transRange = 150 self.pl = plen self.symTime = (2.0**self.sf)/self.bw self.arriveTime = 0 self.rssi = Prx # frequencies: lower bound + number of 61 Hz steps self.freq = 860000000 + random.randint(0,2622950) # for certain experiments override these and # choose some random frequences if experiment == 1: self.freq = random.choice([860000000, 864000000, 868000000]) else: self.freq = 860000000 self.rectime = airtime(self.sf,self.cr,self.pl,self.bw) # denote if packet is collided self.collided = 0 self.processed = 0 # mark the packet as lost when it's rssi is below the sensitivity # don't do this for experiment 3, as it requires a bit more work if experiment != 3: global minsensi self.lost = self.rssi < minsensi print ("node {} bs {} lost {}".format(self.nodeid, self.bs, self.lost))