def swaprevmut(p, threshold, mutprob): if rand() <= mutprob: a = choose(range(len(p))) b = choose([i for i in range(max(0, a-threshold), min(a+threshold, len(p))) if i!=a]) if a>b: a,b = b,a return p[:a] + p[a:b+1][::-1] + p[b+1:] else: return p
def revswapmut(p, threshold, mutprob): p = p[:] for a in xrange(len(p)): if rand() <= mutprob: a = choose(range(len(p))) b = choose([i for i in range(max(0, a-threshold), min(a+threshold, len(p))) if i!=a]) p[a], p[b] = p[b], p[a] return p
def generate_name(self): '''generate full name based on country and sex''' names_list = import_this('names.' + self.country.replace(' ', '_')) if self.sex == 'male': first_name = choose(names_list.male).lower() else: first_name = choose(names_list.female).lower() last_name = choose(names_list.last).lower() return first_name, last_name
def fill(grid): for i in range(H): for j in range(W): if grid[i][j].count(None)==1: grid[i][j] = [x if x != None else choice([0,1],p=[0.9,0.1]) for x in grid[i][j]] connect(grid) if grid[i][j].count(None)==2: grid[i][j][choose([x for x in range(4) if grid[i][j][x]==None])] = choice([0,1],p=[0.9,0.1]) connect(grid) if grid[i][j].count(None)>=3: grid[i][j][choose([x for x in range(4) if grid[i][j][x]==None])] = choice([0,1],p=[0.9,0.1])
def generate_birthplace(self): '''generate a place of birth''' country_data = import_this('cities.' + self.country.replace(' ', '_')) if self.country == 'united states': state = choose(country_data.states).lower() zip = str(self.generate_zip(country_data.zip_codes[state])).zfill(5) cities_list = import_this('cities.us.' + state.replace(' ', '_')) city = choose(cities_list.cities).lower() return city, state, zip else: return choose(country_data.cities).lower(), None, None
def generate_email(self): '''generate a (phony) email''' # TODO: expand this first = sub(r" |'|\-", '', self.first_name) last = sub(r" |'|\-", '', self.last_name) number = randint(1, 999) separator = choose(('-', '_', '.', '')) format = (f'{first}{separator}{last}{number}', f'{first[0]}{separator}{last}{number}', f'{first}{separator}{last[0]}{number}') return choose(format) + '@mentiormail.{}'.format(iso_codes_reversed[self.country])
def generate_phone(self): '''generate (phony) phone number''' if self.country == 'united states': return '1-{}-{}-{}'.format(choose(us_area_codes[self.state]), ''.join(str(randint(1, 9)) for _ in range(3)), ''.join(str(randint(1, 9)) for _ in range(4))) else: return '{}-{}-{}-{}'.format(country_codes[self.country], choose(world_area_codes[self.country]), ''.join(str(randint(1, 9)) for _ in range(3)), ''.join(str(randint(1, 9)) for _ in range(4))).replace('--', '-')
def generateFull(F, T, root, height): if height < 0: root.operator = choose(T) return root else: root.operator = choose(F) for _ in spec(root.operator).args: n = Node() root.operands.append(generateFull(F, T, n, height-1)) return root
def generateGrow(F, T, root, height, minheight): if height < 0: root.operator = choose(T) return root else: if minheight>0: root.operator = choose(F) else: root.operator = choose(F+T) if hasattr(root.operator, "__call__"): for _ in spec(root.operator).args: n = Node() root.operands.append(generateGrow(F, T, n, height-1, minheight-1)) return root else: return root
def getConfigForInstanceSingleFile(self, key, name): logging.debug("getConfigForInstanceSingleFile(%s, %s)" % (key, name)) c = self.getConfig(name) if c is None: return None match = 0 if key not in c: return None v = c[key] logging.debug("getConfigForInstanceSingleFile(%s, %s) value=%s" % (key, name, v)) if isinstance(v, dict): rv = None for (key, value) in v.iteritems(): tm = self.matchesInstance(key) if tm > match: match = tm rv = value v = rv if v is None: return None if isinstance(v, list): v = random.choose(v) return (match, v)
def mutateSingleAllele(p, chrom, chars): """ get the `chrom`th chromosome of the Individual p. Replace a random gene in this chromosome with a different allele from chars Precondition: p[chrom] should be castable into a list Return a new individual. Do not destroy the input pre: isinstance(p, Individual) isinstance(chrom, int) forall(p.chromosomes[chrom], lambda e: e in chars) (0 <= chrom <= len(p.chromosomes)-1) ^ (len(p.chromosomes)*-1 <= chrom <= -1) post[p, chrom]: __old__.p == p __old__.chrom == chrom __return__ is not p __return__ != p __return__.chromosomes != __old__.p.chromosomes forall(__return__.chromosomes[chrom], lambda e: e in chars) forall([i for i in range(len(p.chromosomes)) if i!=chrom], lambda c: __old__.p.chromosomes[i]==__return__.chromosomes[i]) """ chromosome = p[chrom][:] gene = randint(0, len(chromosome)-1) allele = choose([i for i in chars if i!= chromosome[gene]]) chromosome = chromosome[:gene] + [allele] + chromosome[gene+1:] answer = Individual(p.chromosomes[:]) answer[chrom] = chromosome return answer
def test_package_import__semantics(self): # Generate a couple of broken modules to try importing. # ...try loading the module when there's a SyntaxError self.rewrite_file('for') try: __import__(self.module_name) except SyntaxError: pass else: raise RuntimeError, 'Failed to induce SyntaxError' self.assertNotIn(self.module_name, sys.modules) self.assertFalse(hasattr(sys.modules[self.package_name], 'foo')) # ...make up a variable name that isn't bound in __builtins__ var = 'a' while var in dir(__builtins__): var += random.choose(string.letters) # ...make a module that just contains that self.rewrite_file(var) try: __import__(self.module_name) except NameError: pass else: raise RuntimeError, 'Failed to induce NameError.' # ...now change the module so that the NameError doesn't # happen self.rewrite_file('%s = 1' % var) module = __import__(self.module_name).foo self.assertEqual(getattr(module, var), 1)
def mutateSingleAllele(p, chrom, chars): """ get the `chrom`th chromosome of the Individual p. Replace a random gene in this chromosome with a different allele from chars Precondition: p[chrom] should be castable into a list Return a new individual. Do not destroy the input pre: isinstance(p, Individual) isinstance(chrom, int) forall(p.chromosomes[chrom], lambda e: e in chars) (0 <= chrom <= len(p.chromosomes)-1) ^ (len(p.chromosomes)*-1 <= chrom <= -1) post[p, chrom]: __old__.p == p __old__.chrom == chrom __return__ is not p __return__ != p __return__.chromosomes != __old__.p.chromosomes forall(__return__.chromosomes[chrom], lambda e: e in chars) forall([i for i in range(len(p.chromosomes)) if i!=chrom], lambda c: __old__.p.chromosomes[i]==__return__.chromosomes[i]) """ chromosome = p[chrom][:] gene = randint(0, len(chromosome) - 1) allele = choose([i for i in chars if i != chromosome[gene]]) chromosome = chromosome[:gene] + [allele] + chromosome[gene + 1:] answer = Individual(p.chromosomes[:]) answer[chrom] = chromosome return answer
def insult(bot, event, *args): if args: insulttouse = choose(insultslist.insults) checkforbot = "".join(args) for c in string.punctuation: checkforbot = checkforbot.replace(c, "") for i in range(len(checkforbot)): if not checkforbot[i].isalnum == True: checkforbot[i].replace(checkforbot[i], "") tobeinsulted = " ".join(args) if ( "@" in tobeinsulted or "0" in tobeinsulted.lower() or "()" in tobeinsulted.lower() or "soda" in tobeinsulted.lower() or "soda" in checkforbot.lower() ): msg = _("I'm not insulting myself") elif ( "s" in tobeinsulted.lower() and "o" in tobeinsulted.lower() and "d" in tobeinsulted.lower() and "a" in tobeinsulted.lower() ): msg = _("I'm not insulting myself") else: msg = _("Hey {}, {}").format(tobeinsulted, insulttouse) else: msg = _("I'm not going to insult nobody. They dont' have a life anyways ;)") yield from bot.coro_send_message(event.conv, msg)
def generate_text(d: Dict[str, List[str]], maximum_text_length: int = 280, chance_to_exit_when_sentence_terminates: float = 0.375, sentence_separator: str = " ", overflow_indicator: str = "...") -> str: """ Generates text using the given superdictionary. See create_superdict(). :param d: The superdictionary. See create_superdict(). :param maximum_text_length: The maximum length the text may have. Default 280. :param chance_to_exit_when_sentence_terminates: The chance that the procedure exits after each sentence terminates. Default 0.375 (37.5% chance). :param sentence_separator: The text that is inserted when a sentence terminates. Default ' ' (one whitespace). :param overflow_indicator: The text that is appended if the text exceeds maximum_text_length. Default '...'. :return: The generated text. """ text = "" lastWord = None sentences = 0 while len(text) < maximum_text_length: w = choose(d[lastWord]) lastWord = w if w is None: if chance(chance_to_exit_when_sentence_terminates): break text += sentence_separator sentences += 1 else: if len(text + w) > (maximum_text_length - len(overflow_indicator)): text = text[:-1] + overflow_indicator break else: text += w + " " return text
def next(self): if len(self.children.keys()) == 0: raise GameEnded() else: names = self.children.keys() choice = -2 while choice < 0 or choice > len(names)-1: for i in enumerate(names): print "%d: %s" % i try: choice = int(raw_input("Choose from [0-%d] > " % (len(names) - 1))) except: pass chosen_name = names[choice] possible_choices = filter(lambda x: x.predicate(), self.children[chosen_name]) next_state = choose(possible_choices) history.append(next_state) print next_state.description if len(next_state.children.keys()) == 0: next_state.next() return next_state
def select_action(self, friends, enemies): hp = self.properties.get('hit_points') if hp < self.properties('retreat_hit_points'): return self.retreat if hp < self.properties('defend_hit_points'): return self.defend return functools.partial(self.attack, random.choose(enemies))
def generate_random_nick(base_name, max_length=16): max_length = max_length - len(base_name) chars = string.ascii_lowercase digits = string.digits selection = chars + digits random_string = "".join(choose(selection) for x in range(randint(max_length))) return "%s-%s" % (base_name, random_string)
def scrambleWord(self, word, difficulty): """Returns a scrambled word.\n difficulty - The difficulty of the scrambled word.\n Note: A \"normal\" difficulty will scramble each word (if there are multiple words).\n An \"expert\" difficulty will scramble the entire phrase.\n """ # Normal scramble if difficulty == "normal": # Split words into list wordList = word.split(" ") newWordList = [] for word in wordList: newWordList.append( self.scrambleWord(word, "expert") ) return " ".join(newWordList) # Expert scramble else: # Split up word normally wordList = list(word) newWord = "" while len(wordList) > 0: char = choose(wordList) wordList.remove(char) newWord += char return newWord
def compliment(bot, event, *args): if args: if 'me' in ''.join(args).lower(): complimenttouse = choose(compliments) tobecomplimented = event.user.first_name msg = _("Hey {}, {}").format(tobecomplimented, complimenttouse) elif 'trump' not in ''.join(args).lower(): complimenttouse = choose(compliments) tobecomplimented = ' '.join(args) msg = _("Hey {}, {}").format(tobecomplimented, complimenttouse) else: msg =_("Trump is unable to be complimented") else: compliment = choose(compliments) msg = _("{}").format(compliment) yield from bot.coro_send_message(event.conv, msg)
def find_reaction_emoji(self): mentions = [ Mention(self.author_id, length=len(self.author.first_name) + 1) ] if len(self.user_params) == 0: return None elif len(self.user_params) == 1: emoji = self.user_params[0].strip() try: emoji = MessageReaction(emoji) return emoji except ValueError: try: emoji = self.emoji_dict[emoji] if emoji == "run_random": emoji = choose( ["❤", "😍", "😆", "😮", "😢", "😠", "👍", "👎"]) return MessageReaction(emoji) except KeyError: response_text = "@{}\nSorry, you can't react with that.".format( self.author.first_name) self.client.send(Message(text=response_text, mentions=mentions), thread_id=self.thread_id, thread_type=self.thread_type) return "invalid" else: response_text = "@{}\nPlease input only 1 emoji.".format( self.author.first_name) self.client.send(Message(text=response_text, mentions=mentions), thread_id=self.thread_id, thread_type=self.thread_type) return "invalid"
async def generateWord(self): """Returns a random word from the list of words in the database """ self._word = await omegaPsi.getScrambleWords() self._word = choose(self._word["words"]) self._hints = self._word["hints"] self._scramble = self.scrambleWord(self._word["value"], self._difficulty)
def getConfigForInstanceSingleFile(self, key, name): logging.debug('getConfigForInstanceSingleFile(%s, %s)' % (key, name)) c = self.getConfig(name) if c is None: return None match = 0 if key not in c: return None v = c[key] logging.debug('getConfigForInstanceSingleFile(%s, %s) value=%s' % (key, name, v)) if isinstance(v, dict): rv = None for (key, value) in v.iteritems(): tm = self.matchesInstance(key) if tm > match: match = tm rv = value v = rv if v is None: return None if isinstance(v, list): v = random.choose(v) return (match, v)
def choice(currentPlayerHand): cards_held_by_player = [] for items in currentPlayerHand: cards_held_by_player.append(items[0]) choice = None ''' uncomment the following #line and the first #line of the while loop, and comment out the try block to have the game auto choose cards ''' #comment out the following line theList = [ 'a', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'j', 'q', 'k' ] while choice == None: #comment out the following line choice = choose(theList) ''' #section to comment out for auto choosing try: choice = str(input('ask for a card, valid choices are(A,2,3,4,5,6,7,8,9,10,J,Q,K) but you must have one of that type card: ')) except Exception as e: print(e) #end of section to comment out for auto choosing ''' if choice.upper() in cards_held_by_player: return choice.upper() else: choice = None print('you do not have a card of that type')
def neugierige_aktion(situation, moegliche_aktionen): if rd.randint(0, 100) > EPSILON * 100: besteAktion = beste_aktion(situation, moegliche_aktion) return besteAktion else: return rd.choose(moegliche_aktionen) return 0
def xkcd(bot, event, *args): '''Gets xkcd comic. Random number is chosen if number is not given. Format is /bot xkcd <number>''' try: numlist = list(range(1, 1631)) if len(args) == 1 and args[0].isdigit(): num = int(args[0]) link_image = str(pykcd.XKCDStrip(num).image_link) title = str(pykcd.XKCDStrip(num).title) alt_text = str(pykcd.XKCDStrip(num).alt_text) link = 'http://xkcd.com/' + str(num) else: chosencomic = choose(numlist) num = int(chosencomic) link_image = str(pykcd.XKCDStrip(num).image_link) title = str(pykcd.XKCDStrip(num).title) alt_text = str(pykcd.XKCDStrip(num).alt_text) link = 'http://xkcd.com/' + str(num) logger.info("getting {}".format(link_image)) filename = os.path.basename(link_image) r = yield from aiohttp.request('get', link_image) raw = yield from r.read() image_data = io.BytesIO(raw) msg = _('Title: {}<br>Caption: {}<br>Number: {}<br>Link: {}').format(title, alt_text, num, link) image_id = yield from bot._client.upload_image(image_data, filename=filename) yield from bot.coro_send_message(event.conv.id_, None, image_id=image_id) yield from bot.coro_send_message(event.conv, msg) except BaseException as e: msg = _('{} -- {}').format(str(e), event.text) yield from bot.coro_send_message(CONTROL,msg)
def GENERATE_PATTERN(keyword=None): pat = choose(patternNames.values()) # Make sure we get right number of args num_defs = len(pat.__defaults__) if pat.__defaults__ is not None else 0 num_args = pat.__code__.co_argcount # Only change default args occasionally if random() > 0.9 and num_defs > 0: num_defs -= randint(1, num_defs) n = num_args - num_defs if pat.__name__ not in patternInputs: args = [str(GENERATE_INTEGER(keyword)) for i in range(n)] else: args = [] for i in range(n): args.append(str(patternInputs[pat.__name__][i](keyword))) return pat.__name__ + "({})".format(", ".join(args))
def goal_manager(self): while True: if self.msg_buff: message_recieved = self.msg_buff_t3.pop(0) if message_recieved.T == self.T: if self.lexigraphically_greater(message_recieved.p, self.p): if random.uniform(0, 1.0) > 0.1: self.T = self.q_u self.update_last_check() else: self.T = random.choose(Q) self.update_last_check() if self.distance_between( self.p, message_recieved.T) < self.distance_between( self.p, self.T): if self.exchange(): #define self.T = message_recieved.T self.update_last_check() if self.distance_between( self.p, message_recieved.T) == self.distance_between( self.p, self.T): if random.uniform(0, 1.0) < beta: if self.exchange(): #define self.T = message_recieved.T self.update_last_check() print('meeeep')
def deal_card(player, display=True): card = random.choose(deck.cards.pop()) player.cards.append(card) if display and player.is_bot: print("The dealer has been dealt the {} of {}".format( card.name, card.suit)) elif display: print("You have been dealt the {} of {}".format(card.name, card.suit))
def ai(self, x): self.disable_btn() ai = choose(self.board_index) self.btn_var_list[ai].set(x) self.game_board[ai] = x self.board_index.remove(ai) self.win_check() self.enable_btn()
def swapmut(p, mutprob): """ Pick any two random cities and swap their positions in the tour """ # i,j = sample(range(len(p)), 2) # if rand() <= mutprob: p[i], p[j] = p[j], p[i] for i in range(len(p)): if rand() <= mutprob: j = choose([ii for ii in range(len(p)) if ii != i]) p[i], p[j] = p[j], p[i] return p
def pointMutation(indiv, F, T): M = getCrossPoint(indiv) iparent,isubtree = None, indiv i = [0] if not M else M while i: iparent = isubtree isubtree = isubtree.operands[i.pop(0)] if hasattr(isubtree.operator, "__call__"): arity = len(spec(isubtree.operator)) otherGuys = [f for f in F if len(spec(f)) == arity and f!=isubtree.operator] isubtree.operator = choose(otherGuys) else: otherGuys = [t for t in T if t!=isubtree.operator] isubtree.operator = choose(otherGuys) return [indiv]
def generate_country(self): '''generate a country''' if self.country: country = self.correct(self.country.lower()) if country not in countries: raise ValueError('country not implemented') else: country = choose(countries) return country
def ADD_NEW_KWARG(*args, **kwargs): new_kw = [kw for kw in Keywords if kw not in kwargs['kwargs']] if len(new_kw) > 0: if "dur" not in new_kw and random() > 0.25: new_kw = "dur" else: new_kw = choose(new_kw) kwargs['kwargs'][new_kw] = GEN_CHOOSE_VALUE(new_kw) return kwargs
async def avatar(self, message, parameters): """Returns a random cute avatar that can be used as a placeholder. Parameters: parameters (list): The parameters that detect for too many parameters. """ # Check for too many parameters if len(parameters) > self._avatar.getMaxParameters(): embed = getErrorMessage(self._avatar, Image.TOO_MANY_PARAMETERS) await sendMessage( self.client, message, embed=embed.set_footer(text="Requested by {}#{}".format( message.author.name, message.author.discriminator), icon_url=message.author.avatar_url)) # There were the proper amount of parameters else: # Get list of face features faceValues = await loop.run_in_executor(None, requests.get, Image.AVATAR_LIST) faceValues = faceValues.json()["face"] # Choose random eyes, nose, mouth, and color eyes = choose(faceValues["eyes"]) nose = choose(faceValues["nose"]) mouth = choose(faceValues["mouth"]) color = hex(randint(0, 16777215))[2:].rjust(6, "0") # Load image image = await loop.run_in_executor( None, loadImageFromUrl, Image.AVATAR_API.format(eyes, nose, mouth, color)) # Save image temporarily avatarFile = "{}_{}_{}_{}.png".format(eyes, nose, mouth, color) pygame.image.save(image, avatarFile) # Send file then delete image await sendMessage(self.client, message, filename=avatarFile) os.remove(avatarFile)
def get(url): req = urllib.request.Request( url, data=None, headers={'User-Agent': ag}) try: f = urllib.request.urlopen(req) except: ag=random.choose(agents) return f.read()
def play(self): seq = self.game.autoGet() self.cp = seq[0] if not seq in self.knowledge: self.createKnowledge(seq) k = self.knowledge[seq] ind = choose(list(k.keys()), list(k.values())) ind = ind[0] self.roundKnow[seq] = ind self.game.autoTurn(ind)
def genfixeddecimalstr(size=38, precision=12, signed=True): # voltdb decimal is 16-byte with fixed scale of 12 and precision of 38 p = -1 * precision r = ''.join(random.sample(NUMERIC_CHARSET, len(NUMERIC_CHARSET))) r = r * int(size / len(r)) + r[:size % len(r)] if (p > 0): r = r[:p] + '.' + r[p:] if signed: r = random.choose(["-", "+", ""]) + r return r
def genfixeddecimalstr(size=38, precision=12, signed=True): # voltdb decimal is 16-byte with fixed scale of 12 and precision of 38 p = -1*precision r = ''.join(random.sample(NUMERIC_CHARSET, len(NUMERIC_CHARSET))) r = r * int(size/len(r)) + r[:size%len(r)] if (p>0): r = r[:p] + '.' + r[p:] if signed: r = random.choose(["-","+",""]) + r return r
def computer_turn(currentPlayerHand): cards_to_ask_for = [] if currentPlayerHand != []: for items in currentPlayerHand: cards_to_ask_for.append(items) card = choose(cards_to_ask_for) card = card[0] return card else: print('something weird happened')
def CHANGE_KWARG(*args, **kwargs): if kwargs['kwargs']: kw, value = choose(kwargs['kwargs'].items()) if random() > 0.5: kwargs['kwargs'][kw] = GEN_CHANGE_VALUE(value, kw) else: kwargs['kwargs'][kw] = GEN_CHOOSE_VALUE(value) else: kwargs = ADD_NEW_KWARG(*args, **kwargs) return kwargs
def genPop(N, G): """Return a population of N individuals. Each individual has G chromosomes""" answer = set() while N: indiv = ''.join(choose('01') for _ in range(G)) if indiv not in answer: N -= 1 answer.add(indiv) return list(answer)
def add_symmetric(): for rel in rel_set: for pair in combinations(A, 2): pair = list(pair) if pair[0] != pair[1]: if choose( [True, False]): # Escolher aleatóriamente se o par será posto na rel.append(pair) # Adiciona pares até aqui -- reutilizar em add_non_symmetric rel.append(pair[::-1])
def choose_wyckoff(wyckoffs, number): """ choose the wyckoff sites based on the current number of atoms rules 1, the newly added sites is equal/less than the required number. 2, prefer the sites with large multiplicity """ for wyckoff in wyckoffs: if len(wyckoff[0]) <= number: return choose(wyckoff) return False
def GENERATE_PATTERN(keyword=None): pat = choose(list(patternNames.values())) n = len(signature(pat).parameters) if pat.__name__ not in patternInputs: args = [str(GENERATE_INTEGER(keyword)) for i in range(n)] else: args = [] for i in range(n): args.append(str(patternInputs[pat.__name__][i](keyword))) return pat.__name__ + "({})".format(", ".join(args))
async def ejected(self, name: str, crewmate: Union[str, int, CrewMateColors] = CrewMateColors.RED, impostor: bool = False, imposter: bool = False) -> Image: impostor = impostor or imposter get_color = await _get_from_enum(CrewMateColors, crewmate) if get_color is CrewMateColors.RANDOM or not get_color: crewmate = choose(list(CrewMateColors)).name else: crewmate = get_color.name response = await self._api_request( "ejected", {"name": str(name), "crewmate": str(crewmate.lower()), "impostor": bool(impostor)}) return Image(str(response.url), response)
def _set_init_position(self): ''' puts the agent in an initial position, usually within the bounds of the cage Options: [the cage] door, or anywhere in the plane at x=.1 meters set initial velocity from fitted distribution ''' # generate random intial velocity condition using normal distribution fitted to experimental data if self.initial_position_selection == 'realistic': """these were calculated by taking selecting the initial positions of all observed trajectories in all conditions. Then, for each dimension, I calculated the distance of each initial position to the nearest wall in that dimension (i.e. for each z I calculated the distance to the floor and ceiling and selected the smallest distance. Then, Decisions aand""" downwind, upwind, left, right, floor, ceiling = self.boundary x_avg_dist_to_wall = 0.268 y_avg_dist_to_wall = 0.044 z_avg_dist_to_wall = 0.049 x = choose([(downwind + x_avg_dist_to_wall), (upwind - x_avg_dist_to_wall)]) y = choose([left + y_avg_dist_to_wall, (right - y_avg_dist_to_wall)]) z = ceiling - z_avg_dist_to_wall initial_position = np.array([x,y,z]) elif self.initial_position_selection == 'downwind_high': initial_position = np.array( [0.05, np.random.uniform(-0.127, 0.127), 0.2373]) # 0.2373 is mode of z pos distribution elif type(self.initial_position_selection) is list: initial_position = np.array(self.initial_position_selection) elif self.initial_position_selection == "door": # start trajectories as they exit the front door initial_position = np.array([0.1909, np.random.uniform(-0.0381, 0.0381), np.random.uniform(0., 0.1016)]) # FIXME cage is actually suspending above floor elif self.initial_position_selection == 'downwind_plane': initial_position = np.array([0.1, np.random.uniform(-0.127, 0.127), np.random.uniform(0., 0.254)]) else: raise Exception('invalid agent position specified: {}'.format(self.initial_position_selection)) return initial_position
def injectionco(p1, p2): """ Order CrossOver from the handout """ answer = [] a,b = sample(range(len(p1)), 2) if a < b: a,b = b,a q = choose(range(len(p1))) ab = p1[a:b] for i in xrange(q): if p2[1] not in ab: answer.append(p2[i]) answer.extend(ab) for city in p2: if city not in answer: answer.append(city) return answer
def genCharsChrom(l, chars): """ Return chromosome (list) of length l, each of which is made up of the characters from chars. pre: isinstance(l, int) hasattr(chars, '__getitem__') hasattr(chars, '__len__') len(chars) > 0 post[l, chars]: __old__.l == l __old__.chars == chars len(__return__) == l forall(__return__, lambda a: a in chars) """ return [choose(chars) for _ in xrange(l)]
def xkcd(bot, event, *args): # Don't handle events caused by the bot himself numlist = list(range(1, 1631)) if args: msg = _("Please don't enter any arguments") yield from bot.coro_send_message(event.conv, msg) else: chosencomic = choose(numlist) chosennum = int(chosencomic) link_image = str(pykcd.XKCDStrip(chosennum).image_link) logger.info("getting {}".format(link_image)) filename = os.path.basename(link_image) r = yield from aiohttp.request('get', link_image) raw = yield from r.read() image_data = io.BytesIO(raw) link = shorten(link_image) image_id = yield from bot._client.upload_image(image_data, filename=filename) yield from bot.coro_send_message(event.conv.id_, None, image_id=image_id) yield from bot.coro_send_message(event.conv, _('{}').format(link))
def insult(bot, event, *args): '''Insult something/somebody using a predefined list of insults. Will not insult itself. Format is /bot insult <whattoinsult>''' if args: insulttouse = choose(insultslist.insults) checkforbot = ''.join(args) for c in string.punctuation: checkforbot = checkforbot.replace(c, '') for i in range(len(checkforbot)): if not checkforbot[i].isalnum == True: checkforbot[i].replace(checkforbot[i], '') tobeinsulted = ' '.join(args) if '@' in tobeinsulted or '0' in tobeinsulted.lower() or '()' in tobeinsulted.lower() or 'soda' in tobeinsulted.lower() or 'soda' in checkforbot.lower(): msg = _("I'm not insulting myself") elif 's' in tobeinsulted.lower() and 'o' in tobeinsulted.lower() and 'd' in tobeinsulted.lower() and 'a' in tobeinsulted.lower(): msg = _("I'm not insulting myself") else: msg = _("Hey {}, {}").format(tobeinsulted, insulttouse) else: msg = _("I'm not going to insult nobody. They dont' have a life anyways ;)") yield from bot.coro_send_message(event.conv, msg)
def __init__(self, *args, **kw): self.package_name = 'PACKAGE_' while self.package_name in sys.modules: self.package_name += random.choose(string.letters) self.module_name = self.package_name + '.foo' unittest.TestCase.__init__(self, *args, **kw)
V,E = clone(VV), clone(EE) u, n = None, None while u is None: try: us = [v for v in V if v.residents and (rerouts and v.id not in [r[0] for r in rerouts]) and \ any( (e for e in E if v in e and e.capacity==inf and \ routable(e.src if v==e.dest else e.dest, paths) and \ e.weight <= dist) ) ] U = max(paths, key=lambda a: sum((e.weight for e in paths[a])) ) for v in V: if U in v.residents: u = v break else: u = choose(us) except: u = None while not n: try: n = filter( lambda v: min( (e.weight for e in E if (v in e and u in e) )) <= dist, (v for v in V if (u!=v and any(( (v in e and u in e and e.capacity==inf) for e in E)) )) ) except: n = False n = choose(n) ress = list(u.residents) r = choose(ress) u.residents = set(u.residents); u.residents.remove(r) n.residents = set(n.residents); n.residents.add(r)#; n.residents = set(n.residents)
return x * y def divide(x, y): return x/y if __name__ == "__main__": func = {'-':subtract, "+":add, '/':divide, "*":multiply} # controls the digit-limit for +/- questions. If you want 7-digit numbers, ask for 10**8 -1. 10**7 -1 for 6-digit numbers addlimit = 10**8 -1 # controls the digit-limit for +/- questions. If you want 3-digit numbers, ask for 10**4 -1. 10**3 -1 for 2-digit numbers divlimit = 10**4 -1 while 1: op = choose("-+") if op in '+-': # change '+-' to '-/*+' to include multiplication and division problems nums = nums = ["%07d" %s for s in getNumbers(2, 0, addlimit)] else: nums = ["%04d" %s for s in getNumbers(2, 0, divlimit)] gotResp = False while not gotResp: try: response = int(ask("what is \n%s %s \n%s" %(nums[0], op, nums[1]))) gotResp = True except ValueError: 'Oops, typo. Try again' if response != func[op](*[int(n) for n in nums]): print 'you fail'
def vaporize(image_dir, make_mp4_instead_of_gif, img_types, audio_file = None): # first get image type dir_contents = listdir(image_dir) image_type = None if audio_file is None: audio_file = choose(['x-files.ogg', 'short-macplus.mp3']) for filename in dir_contents: for some_type in img_types: if filename.endswith(some_type): image_type = some_type break if image_type is None: print 'UNKNOWN IMAGE TYPE!' return None # add the `you decide` feature # link a random yd[1-5] to image099.type to the proper directory YOU_DECIDES = ['yd1', 'yd2', 'yd3', 'yd4', 'yd5'] # screw memory yd_cmd = Template('cp ./you-decide/$ydn.$itp $idr/image00$l.$itp') img_files = filter(lambda file: file.endswith(image_type) and file.startswith('image0'), dir_contents) yd_cmd = yd_cmd.substitute(ydn = choose(YOU_DECIDES), itp = image_type, idr = image_dir, l = str(len(img_files) + 1)) print yd_cmd call(yd_cmd.split(' ')) # optimize jp(e)gs if img_types == 'jpeg' or image_type == 'jpg': for img_file in img_files: call(['jpegoptim', image_dir + '/' + img_file]) slideshow_cmd = Template('ffmpeg -framerate 1/2 -i $idr/image%03d.$itp -movflags faststart -c:v libx264 -pix_fmt yuv420p $idr/show.mp4') # TODO: pipe `yes` for overwriting? slideshow_cmd = '' + slideshow_cmd.substitute(idr = image_dir, itp = image_type) result_cmd = None result_path = None if make_mp4_instead_of_gif: result_cmd = Template('ffmpeg -i $idr/show.mp4 -i ./$adf -movflags faststart -strict -2 -vcodec copy $idr/final.mp4') # result_path = image_dir + '/' + image_dir + '-' + 'final.mp4' result_path = 'final.mp4' else: result_cmd = Template('ffmpeg -i $idr/show.mp4 $idr/final.gif') # result_path = image_dir + '/' + image_dir + '-' + 'final.gif' result_path = 'final.gif' # TODO: pipe `yes` for overwriting? result_cmd = '' + result_cmd.substitute(idr = image_dir, adf = audio_file) call(slideshow_cmd.split(' ')) call(result_cmd.split(' ')) print '\n\n\n' print slideshow_cmd print result_cmd print '\n\n\n' return result_path
import os, sys, string, random, tempfile, unittest
def __init__(self, *args, **kw): self.package_name = "PACKAGE_" while sys.modules.has_key(self.package_name): self.package_name += random.choose(string.letters) self.module_name = self.package_name + ".foo" unittest.TestCase.__init__(self, *args, **kw)
# reading part of a text file and returning it as a string my_file.read(1) # returns the first byte of my_file as a string, e.g., "T" my_file.read() # returns the entire text of the file WITHOUT running Python code in it print my_file.read() # prints the contents of the text file including any Python code inside # closing an object, updating the source file file_in.close() # closes out the file used to read in data_in file_out.close() # closes out the file that csv.writer has been modifying, updating out_data.csv ### OTHER USEFUL TOOLS ### # using pydoc from the shell python -m pydoc raw_input # returns the built-in Python documentation for the raw_input function ### MODULES ### ## Random ## import random # choose a random number (int) from a given range my_num = random.randrange(0,10) # assigns a pseudorandom int between 0 and 9 to my_num my_num1 = random.uniform(0,1) # assigns a random float between 0 and 1 to my_num1 # "shuffle" entries in a list randomly lst = [1,2,3,4,5,6] random.shuffle(lst) # returns, e.g., [4,3,1,2,5,6]; shuffles the list order # randomly choose an entry from a list random.choose(lst) # returns 4