def breed_parents(male, female): print("Breeding!") m_params = male.params f_params = female.params new_params = {} param = random_choice(['lstm_layers_number', 'dense_layers_number', 'polynomial_exponent']) choice = randint(0, 3) if choice == 0: new_params[param] = m_params[param] elif choice == 1: new_params[param] = f_params[param] else: new_params[param] = int((f_params[param] + m_params[param]) / 2) list_param = random_choice(['lstm_neurons', 'dense_neurons']) working_param = m_params[list_param].copy() for idx in range(min(len(m_params[list_param]), len(f_params[list_param]))): choice = randint(0, 3) if choice == 0: working_param[idx] = m_params[list_param][idx] elif choice == 1: working_param[idx] = f_params[list_param][idx] else: working_param[idx] = int((f_params[list_param][idx] + m_params[list_param][idx]) / 2) new_params[list_param] = working_param child = NetworkUnit(params=new_params) print("Breed finished!") return child
async def cmd_mithrollversus(self, *args, message, content, member, channel, guild, **_): match = CMD_VERSUS_REGEX.match(content) if not match: raise InvalidArgs(f"The command content must match regular the regular expression\n``{CMD_VERSUS_REGEX.pattern}``") d = {k:v for k, v in match.groupdict().items() if v is not None} comp_atk = d['comp_atk'] atk_bonus = int(d.get('atk_bonus_sign', '+') + d.get('atk_bonus', '0')) comp_def = d.get('comp_def', comp_atk) def_bonus = int(d.get('def_bonus_sign', '+') + d.get('def_bonus', '0')) defenser = get_member(guild, d['def']) attacker = d.get('roller', None) attacker = member if attacker is None else get_member(guild, attacker) try: wsh1 = gc.open_by_key(CHAR_SHEET[str(attacker.id)]).sheet1 wsh2 = gc.open_by_key(CHAR_SHEET[str(defenser.id)]).sheet1 except: raise BotError("Impossible d'ouvrir la fiche de personnage du membre") datk = await roll_by_comp(parse_competences(wsh1), comp_atk.strip().lower(), atk_bonus) ddef = await roll_by_comp(parse_competences(wsh2), comp_def.strip().lower(), def_bonus) em = discord.Embed( title="Lancé de dés", description=f"{attacker.mention} **vs** {defenser.mention}", colour=attacker.colour ).set_footer(text=message.content).set_author(name=attacker.name, icon_url=attacker.avatar_url) em.add_field(name="Attaque", value=COMPROLL_DESC.format(**datk, member=attacker), inline=True) em.add_field(name="Défense", value=COMPROLL_DESC.format(**ddef, member=defenser), inline=True) em.add_field(name="Résultat", value=f"```diff\n{datk['verdict']}```**VS**```diff\n{ddef['verdict']}```", inline=False) if datk['verdict'] == "- Echec Critique": em.set_image(url=random_choice(FAIL_GIF)) elif datk['verdict'] == "+ Réussite Critique": em.set_image(url=random_choice(SUCCES_GIF)) await channel.send(embed=em)
async def cmd_mithroll(self, *args, message, channel, member, guild, content, **_): if '#' in content: content, target_query = content.split('#', 1) target = get_member(guild, target_query.strip()) else: target = member if not args: raise InvalidArgs("Usage: /mithroll {comp_name} [+/-][nombre]") try: wsh = gc.open_by_key(CHAR_SHEET[str(target.id)]).sheet1 except: raise BotError("Impossible d'ouvrir la fiche de personnage du membre") comp = parse_competences(wsh) re_result = re.search(r".*([+-])\s*(\d+)\s*$", content) if re_result: sign_char = re_result.group(1) name = content.split(sign_char, 1)[0] bonus = int(sign_char + re_result.group(2)) else: name, bonus = content, 0 d = await roll_by_comp(comp, name.strip().lower(), bonus) em = discord.Embed( title="Lancé de dés", description=COMPROLL_DESC.format(**d, member=member), colour=target.colour ).set_footer(text=message.content).set_author(name=target.name, icon_url=target.avatar_url) em.add_field(name="Résultat", value=f"```diff\n{d['verdict']}```") if d['verdict'] == "- Echec Critique": em.set_image(url=random_choice(FAIL_GIF)) elif d['verdict'] == "+ Réussite Critique": em.set_image(url=random_choice(SUCCES_GIF)) await channel.send(embed=em)
async def _stare(self, ctx, members: commands.Greedy[discord.Member], *, reason: commands.clean_content = ''): if not members: return await ctx.send( ctx.t('commands.stare.noMention', { "emoji": self.disco.emoji["false"], "author": ctx.author.name })) if ctx.author in members: return await ctx.send( ctx.t('commands.stare.selfMention', { "emoji": self.disco.emoji["false"], "author": ctx.author.name })) image = await self.weeb.random_image('stare') emoji = random_choice(self.disco.emoji['stare']) phrase = random_choice( ctx.t('commands.stare.withReason' if reason else 'commands.stare.noReason')).format( author=ctx.author.name, members=', '.join(f'**{m.name}**' for m in list(set(members))[:3]), reason=reason[:1500], ) em = discord.Embed(colour=random_color()).set_image( url=image.url).set_footer( text=f'{ctx.author} | Powered by Weeb.sh') await ctx.send(content=f'{emoji} | {phrase}', embed=em)
def generate_piano_track(l, outfile): b_bien = ["boucles/1.mid", "boucles/2.mid", "boucles/3.mid"] b_moyen = ["boucles/5.mid", "boucles/6.mid", "boucles/7.mid"] b_mauvais = ["boucles/11.mid", "boucles/12.mid", "boucles/13.mid"] d = l[0][1] ret = None for e in l[1:10]: #FIXME: changer l'intervalle d = e[1] if d["pente"] == "elevé": tmp = MidiTemplate(random_choice(b_bien)) elif d["pente"] == "moyen": tmp = MidiTemplate(random_choice(b_moyen)) elif d["pente"] == "faible": tmp = MidiTemplate(random_choice(b_mauvais)) choose_rewrite_interval(tmp, d["moyenne"], d["ecart"], d["pente"]) if ret == None: ret = tmp else: ret += tmp ret.output_midi(outfile)
def generate_drum_track(l, outfile): # génere les données depuis une piste de batterie b_bien = ["boucles/1.mid", "boucles/2.mid", "boucles/3.mid"] b_moyen = ["boucles/5.mid", "boucles/6.mid", "boucles/7.mid"] b_pasbien = ["boucles/8.mid", "boucles/9.mid", "boucles/10.mid"] b_mauvais = ["boucles/11.mid", "boucles/12.mid", "boucles/13.mid"] # FIXME : quatre types de boucles, et juste trois caractéristiques. ret = None for e in l[1:10]: #FIXME: changer l'intervalle d = e[1] if d["pente"] == "elevé": tmp = MidiTemplate(random_choice(b_bien)) elif d["pente"] == "moyen": tmp = MidiTemplate(random_choice(b_moyen)) elif d["pente"] == "faible": tmp = MidiTemplate(random_choice(b_mauvais)) if ret == None: ret = tmp else: ret += tmp ret.output_midi(outfile)
def update_fib_clock(fib_clock): now = datetime.now() fifth_minute = now.minute // 5 if fib_clock._previous_fifth_minute != fifth_minute: hour = now.hour if hour == 24: hour = 0 elif hour > 12: hour -= 12 color_codes = fib_clock._color_codes minute_codes = random_choice(color_codes[fifth_minute]) hour_codes = random_choice(color_codes[hour]) for minute, hour in zip([minute_codes, hour_codes]): if minute and hour: fib_clock.panel_colors = fib_clock._COLOR_BOTH elif minute: fib_clock.panel_colors = fib_clock._COLOR_MIN elif hour: fib_clock.panel_colors = fib_clock._COLOR_HOUR else: fib_clock.panel_colors = fib_clock._COLOR_NEITHER fib_clock._previous_fifth_minute = fifth_minute
async def _cry(self, ctx, *, reason: commands.clean_content = ''): image = await self.weeb.random_image('cry') emoji = random_choice(self.disco.emoji['cry']) phrase = random_choice( ctx.t('commands.cry.withReason' if reason else 'commands.cry.noReason')).format(author=ctx.author.name, reason=reason[:1500]) em = discord.Embed(colour=random_color()).set_image( url=image.url).set_footer( text=f'{ctx.author} | Powered by Weeb.sh') await ctx.send(content=f'{emoji} | {phrase}', embed=em)
def articles(self): print("Generating random articles") for i in range(10): text = get_random_text(3) article = Article() article.travler = self.user article.title = ' '.join(text[0].split(' ')[:random_choice([3, 4, 5, 6])]) # TODO if random_choice((0, 1)): article.subtitle = text[1][:50] # TODO article.description = text[2] # TODO filename = self.filenames.pop() article.image_cover.save(filename, File(open(path.join(self.images_dir, filename), 'rb'))) print("Generated %s articles" % Article.objects.count())
def randomlySelectWordPairs(word_list, n = 25): ''' Gets list of random word pairs :param word_list: List of words in vector set : list of str :param n: Number word pairs desired (Optional, default = 25) : int :return: List of word pairs : list of str ''' word_pairs = [] for i in range(n): w1 = random_choice(word_list) w2 = random_choice(word_list) word_pair = w1 + " " + w2 word_pairs.append(word_pair) return word_pairs
def color_chase_bounce(self, wait, iteration): i = 0 for a in range(iteration): color1 = random_choice(self.pallete[:5]) color2 = random_choice(self.pallete[:5]) while i <= self.num_pixels - 2: self.strip[i] = color1 self.strip.show() i += 1 time.sleep(wait) while i >= 0: self.strip[i] = color2 self.strip.show() i = i - 1 time.sleep(wait)
def randomlySelectSentencePairs(sentence_list, n = 25): ''' Given a list of sentences, randomly selects pairs of sentences :param sentence_list: A list of sentences: list of strings :param n: Number sentence pairs desired, default = 25 : int :return: List of randomly paired sentences: list of lists of str ''' random_sentence_list = [] for i in range(n): s1 = random_choice(sentence_list) s2 = random_choice(sentence_list) s_pair = [s1, s2] random_sentence_list.append(s_pair) return random_sentence_list
def rest(base=None, gain=1.0, gap=None) -> None: """ snap a little bit\n [1.3-3.6]s + base\n :param base: base time line. :param gain: The amplifier. :param gap: Iterable obj but not dict, snap + random in the gap """ snap = [random_randint(1, 3), random_randint(1, 3), random_randint(1, 3)] ndigit = [random_randint(1, 3), random_randint(1, 3), random_randint(1, 3)] random_shuffle(ndigit) choice = random_choice([0, 1, 2, 3, 4, 5]) if choice == 0: snap = (snap[0] / (ndigit[ndigit[0] - 1]) + snap[1] / (10**ndigit[ndigit[1] - 1]) + snap[2] / (10**ndigit[ndigit[2] - 1])) elif choice == 1: snap = (snap[0] / (ndigit[ndigit[0] - 1]) + snap[2] / (10**ndigit[ndigit[1] - 1]) + snap[1] / (10**ndigit[ndigit[2] - 1])) elif choice == 2: snap = (snap[1] / (ndigit[ndigit[0] - 1]) + snap[0] / (10**ndigit[ndigit[1] - 1]) + snap[2] / (10**ndigit[ndigit[2] - 1])) elif choice == 3: snap = (snap[1] / (ndigit[ndigit[0] - 1]) + snap[2] / (10**ndigit[ndigit[1] - 1]) + snap[0] / (10**ndigit[ndigit[2] - 1])) elif choice == 4: snap = (snap[2] / (ndigit[ndigit[0] - 1]) + snap[0] / (10**ndigit[ndigit[1] - 1]) + snap[1] / (10**ndigit[ndigit[2] - 1])) elif choice == 5: snap = (snap[0] / (ndigit[ndigit[0] - 1]) + snap[1] / (10**ndigit[ndigit[1] - 1]) + snap[0] / (10**ndigit[ndigit[2] - 1])) snap = round(snap, ndigit[choice % 3]) if snap < 1.5: snap += 1 if base: snap += int(base) if gain != 1: snap *= gain if gap is not None: snap += random_choice(gap) Logger.log([rest, f"Now resting for [{snap}]s... "]) time_sleep(int(snap)) Logger.log([rest, "Done. "])
def start_game(self): """Method starts game""" assert len(self.__players) >= 2, "Must be 2 players at least!" assert any( obj.is_comp for obj in self.__players), "Must be at least 1 Computer Player!" alive_pl_indexes = list(range(len(self.__players))) # alive players indexes if ConsoleGame.stepSleepSeconds == 0: ConsoleGame.stepSleepSeconds = 0.2 while len(alive_pl_indexes) != 1: self.__step += 1 # Increasing Game.__step attacker_ind = random_choice(alive_pl_indexes) opponent_ind = random_choice(alive_pl_indexes) # random choice of alive players indexes while opponent_ind == attacker_ind: opponent_ind = random_choice(alive_pl_indexes) # for preventing cases when attacker == opponent attacker = self.__players[attacker_ind] opponent = self.__players[opponent_ind] attacker.act_random(opponent, self.__step) # Process random deeds with opponent (or healing himself) self.log(attacker.get_last_event().get_info()) # Check if opponent's health less then 0 if opponent.health <= 0: alive_pl_indexes.remove(opponent_ind) kill_event = opponent.kill_by(attacker, self.__step) self.__losers.append(opponent.get_info()) self.log(kill_event.get_info()) self.log(self.__ALIVE_PLAYERS.format( self.get_alive_players_info())) time_sleep(ConsoleGame.stepSleepSeconds) # Sleep between steps else: # Code when it is left one player self.__winner = self.__players[alive_pl_indexes[0]].get_info() result_text = self.__GAME_OVER_RESULT.format( self.__count_players, self.winner, '\n'.join(self.losers)) self.log(result_text)
def _get_user_belonging_to_group(self, group_name): """Get the 'id' and the 'login' name of a user belonging to a specific group. :param group_name: name of the group from which retrieve a user (belonging to it) :type group_name: str :returns: A dictionary with 2 key-value couples: - 'login': the login name of the retrieved user (belonging to the group passed as argument) - 'id': the id of the retrieved user (belonging to the group passed as argument) :rtype: dict :returns: ``None`` if there isn't any user belonging to that group """ users_pool = self.registry['res.users'] users_login_list = users_pool.search_read(self.cr, self.uid, domain=[('groups_id.name', '=', group_name)], fields=['login', 'id']) try: user_data = random_choice(users_login_list) except IndexError: user_data = None return user_data
def _get_user_belonging_to_group(self, group_name): """Get the 'login' name of a user belonging to a specific group. :param group_name: name of the group from which retrieve a user (belonging to it) :type group_name: str :return: the login name of the retrieved user (belonging to the group passed as argument) :rtype: str :return: None if there isn't any user belonging to that group """ users_pool = self.registry['res.users'] users_login_list = users_pool.search_read( self.cr, self.uid, domain=[('groups_id.name', '=', group_name)], fields=['login'] ) # The search result is a list of dictionaries, # so if at least one of them exists in the list, # just its 'login' value must be returned try: login_name = random_choice(users_login_list) except IndexError: login_name = None # Here is where just the 'login' value is returned, # instead of the whole dictionary return login_name.get('login', None)
def cities(self): assert self places = Place.objects.filter(city=None) counter = 0 limit = len(places) print('There are %s places without city information' % limit) for place in places: data = Coords2City.get_mapbox_data(latitude=place.latitude, longitude=place.longitude) Coords2City.write_mapbox_data(data=data) point, region, country, center, bbox = Coords2City.read_mapbox_data(data=data) counter += 1 print(counter, place.id, point, region, country, center, bbox) try: city = City.objects.get(locality=point, region=region, country=country) except ObjectDoesNotExist: city = City() city.locality = point city.region = region city.country = country if center: city.latitude = center[1] city.longitude = center[0] if bbox: city.bbox = bbox city.save() place.city = city place.save() sleep(random_choice(range(3, 6)))
def mini_picker(hl, sl, dont_check=False): if len(hl) == 1 and len(sl) == 1: stream = sl[0] return stream else: if control.setting('action_type') == '3' or skip_directory: try: if dont_check: url = random_choice(sl) else: url = check_stream(sl) except Exception: return return url choice = control.selectDialog(heading=control.lang(30064), list=hl) if choice <= len(sl) and not choice == -1: return sl[choice] else: prevent_failure()
def username(self) -> str: """Return an adjective and a noun in camelCase, representing a username""" species = self.species.get(random_choice(ABCs)) nouns = self.nouns.get(random_choice(ABCs)) # username starts with a random species name username = random_choice(species) # 70% chance of noun, 30% chance of animal if random() > .7: username += random_choice(self.animals) else: username += random_choice(nouns).capitalize() return username + str(int(random() * 100))
def _get_user_belonging_to_group(self, group_name): """Get the 'id' and the 'login' name of a user belonging to a specific group. :param group_name: name of the group from which retrieve a user (belonging to it) :type group_name: str :returns: A dictionary with 2 key-value couples: - 'login': the login name of the retrieved user (belonging to the group passed as argument) - 'id': the id of the retrieved user (belonging to the group passed as argument) :rtype: dict :returns: ``None`` if there isn't any user belonging to that group """ users_pool = self.registry['res.users'] users_login_list = users_pool.search_read( self.cr, self.uid, domain=[('groups_id.name', '=', group_name)], fields=['login', 'id']) try: user_data = random_choice(users_login_list) except IndexError: user_data = None return user_data
def get_random(self) -> Optional[Crawler]: if not self: return None crawlers = list(self) # TODO: add weighted random crawler = random_choice(crawlers) # type: Crawler return crawler
def visible_attending_attendees(self): """ List with all attendees whom want to be displayed as attending else return a anonymous name """ dyr = [ 'piggsvin', 'kjøttmeis', 'flaggermus', 'elg', 'villsvin', 'rådyr', 'moskus', 'narhval', 'spekkhogger', 'gaupe', 'ekorn', 'kanin', 'lemen', 'neshorn', 'ørn', 'gullfisk', 'kodiakbjørn', 'hacker', 'stol', 'bever', 'datamaskin', 'piano', 'strykejern', 'samurai', 'laks', 'server' ] visible_attendees = [] for attendee in self.attending_attendees_qs: user = attendee.user visible = attendee.show_as_attending_event f_name, l_name = [ user.first_name, user.last_name ] if visible else ['Anonym ' + random_choice(dyr), ''] year = '{} klasse'.format(user.year) visible_attendees.append({ 'visible': visible, 'first_name': f_name, 'last_name': l_name, 'year': year }) return sorted(visible_attendees, key=lambda attendee: attendee['visible'], reverse=True)
def mini_picker(links): if len(links) == 1: stream = links[0][1] return stream elif control.setting('action_type') == '2' or skip_directory: try: if control.setting('check_streams') == 'false': stream = random_choice([link[1] for link in links]) else: stream = check_stream(links) except Exception: return return stream else: choice = control.selectDialog(heading=control.lang(30064), list=[link[0] for link in links]) if choice == -1: return elif control.setting('check_streams') == 'false': return [link[1] for link in links][choice] else: return check_stream(links, False, start_from=choice, show_pd=True, cycle_list=False)
def generate_random_mailbox(cls, **requests_kwargs): """Generates a mailbox with a random address. Parameters ---------- **requests_kwargs : dict, optional Additional kwargs to be passed to the OneSecMail constructor. Returns ------- onesecmail.OneSecMail Notes ----- The domain is randomly chosen from `OneSecMail.get_available_domains()`. The user is generated using the `uuid.uuid4()` function, which means it will always be 32 characters long. """ user = uuid4().hex available_domains = cls.get_available_domains() domain = random_choice(available_domains) return cls(user, domain, available_domains=available_domains, **requests_kwargs)
def random_coords(coordinate): # randomly selects n from a list -5 through 5 choice_range = [x for x in range(-5, 6)] # adds random number to x & y coordinate += random_choice(choice_range) return coordinate
def example(self): # type: () -> Ex """Provide an example of the sort of value that this strategy generates. This is biased to be slightly simpler than is typical for values from this strategy, for clarity purposes. This method shouldn't be taken too seriously. It's here for interactive exploration of the API, not for any sort of real testing. This method is part of the public API. """ if getattr(sys, "ps1", None) is None: # pragma: no branch # The other branch *is* covered in cover/test_examples.py; but as that # uses `pexpect` for an interactive session `coverage` doesn't see it. warnings.warn( "The `.example()` method is good for exploring strategies, but should " "only be used interactively. We recommend using `@given` for tests - " "it performs better, saves and replays failures to avoid flakiness, " "and reports minimal examples. (strategy: %r)" % (self, ), NonInteractiveExampleWarning, ) context = _current_build_context.value if context is not None: if context.data is not None and context.data.depth > 0: raise HypothesisException( "Using example() inside a strategy definition is a bad " "idea. Instead consider using hypothesis.strategies.builds() " "or @hypothesis.strategies.composite to define your strategy." " See https://hypothesis.readthedocs.io/en/latest/data.html" "#hypothesis.strategies.builds or " "https://hypothesis.readthedocs.io/en/latest/data.html" "#composite-strategies for more details.") else: raise HypothesisException( "Using example() inside a test function is a bad " "idea. Instead consider using hypothesis.strategies.data() " "to draw more examples during testing. See " "https://hypothesis.readthedocs.io/en/latest/data.html" "#drawing-interactively-in-tests for more details.") from hypothesis.core import given # Note: this function has a weird name because it might appear in # tracebacks, and we want users to know that they can ignore it. @given(self) @settings( database=None, max_examples=10, deadline=None, verbosity=Verbosity.quiet, phases=(Phase.generate, ), suppress_health_check=HealthCheck.all(), ) def example_generating_inner_function(ex): examples.append(ex) examples = [] # type: List[Ex] example_generating_inner_function() return random_choice(examples)
def congratulate(prefs): """Display a friendly congratulatory message upon creating recipes. Args: prefs: A dictionary containing a key/value pair for each preference. """ congrats_msg = ( "Amazing.", "Easy peasy.", "Fantastic.", "Good on ya!", "Imagine all the typing you saved.", "Isn't meta-automation great?", "(Yep, it's pretty fun for me too.)", "Pretty cool, right?", "Round of applause for you!", "Terrific job!", "Thanks!", "That's awesome!", "Want to do another?", "Well done!", "You rock star, you." ) if prefs["RecipeCreateCount"] == 1: robo_print("\nYou've created your first recipe with Recipe " "Robot. Congratulations!\n") elif prefs["RecipeCreateCount"] > 1: robo_print("\nYou've now created %s recipes with Recipe Robot. " "%s\n" % (prefs["RecipeCreateCount"], random_choice(congrats_msg)))
def select_pile(self, piles, hand): def pile_cost(pile): return sum([card.cost for card in pile]) cheapest = min(pile_cost(pile) for pile in piles) all_cheap = [pile for pile in piles if pile_cost(pile) == cheapest] return random_choice(all_cheap)
def one_ear(whichEar,scale,tempo,output,duration): # define timing quarterNote = 60*zook.sec / float(tempo) # create the sound chain; note that output["left"] and output["right"] # are connection syntax to isolate a single channel attack = 10*zook.msec decay = 150*zook.msec sustain = 0.2 release = 150*zook.msec oscar = oscType(gain=gain) envy = ADSR(adsr=(attack,decay,sustain,release)) oscar >> envy >> output[whichEar] # generate a series of random notes prevFreq = 0.0 startTime = now() while (now() < startTime + duration): noteStart = now() oscar.freq = freq = midi_to_freq(random_choice(scale)) print "T=%.3f %-5s freq=%.1f" % (now()/zook.sec,whichEar,freq) envy.key_on(urandom(0.7,1.0)) yield ("absolute", noteStart + (quarterNote*0.9) - envy._release) envy.key_off() yield ("absolute", noteStart + quarterNote)
def computer_move(board): center = [5] corners = [1, 3, 7, 9] edges = [2, 4, 6, 8] available_moves = board.get_available_locations() print("Computer is choosing from: {}".format(available_moves)) # Can I win on my next move? for move in available_moves: # Create a board copy board_copy = deepcopy(board) board_copy.update_board(move) if board_copy.winner(): return move # Can I block against a win with my next move? for move in available_moves: # Create a board copy board_copy = deepcopy(board) # Switch to the next player board_copy.turn_number += 1 board_copy.update_board(move) if board_copy.winner(): return move # Run through corners, center, then edges for next available move for l in corners, center, edges: choices = list(set(l).intersection(available_moves)) if choices: choice = random_choice(choices) break # BUG: This doesn't always print print("Computer choose {}. Your move...".format(choice)) return choice
def generate_random(self, **kwargs): """ Overriding. `kwargs` can contain the random name mapping `randgen_mapping` or `variation_name`. """ variation_name = kwargs.get("variation_name", None) randgen_mapping = kwargs.get("randgen_mapping", None) if not self._should_generate(randgen_mapping): return self._make_empty_example() if variation_name is not None: max_nb_possibilities = \ self.get_max_nb_possibilities(variation_name=variation_name) else: max_nb_possibilities = self.get_max_nb_possibilities() if isinstance(self._cached_examples, list): if ( len(self._cached_examples) > 0 and uniform(0, 1) <= \ float(len(self._cached_examples)) / float(max_nb_possibilities) ): return random_choice(deepcopy(self._cached_examples)) else: pass # TODO dict case for unit definitions with variations if variation_name is not None: basic_example = \ self._generate_random_strategy(variation_name=variation_name) else: basic_example = self._generate_random_strategy() if self._leading_space: basic_example.prepend(' ') return self._apply_modifiers(basic_example)
def detailview_display(self, context): request = context['request'] user = request.user reloading_info = self.reloading_info or {} item_count_str = str( request.GET.get('count') or reloading_info.get('count', '')) item_count = int(item_count_str) if item_count_str.isdigit() else 20 images = TEST_IMAGE_URLS image_count = len(images) image_ids = [*range(0, image_count - 1)] data = [] for item_id in range(item_count): image_name, image_url = images[random_choice(image_ids)] data.append( Dummy('Dummy ({}) - {}'.format(item_id + 1, image_name), user, media_url(image_url))) return self._render( self.get_template_context( context, data, reloading_info={'count': item_count}, ))
def playlist_handler(input_string, media_entries): ''' Handle the commands needed to generate a playlist. ''' input_string = input_string.strip() if input_string.isdigit(): input_string = int(input_string) if 0 < input_string <= len(media_entries): play(media_entries[input_string - 1:]) else: print 'Enter value from 1 to %s, try again.' % len(media_entries) elif input_string.startswith('a') or input_string == '': play(media_entries) elif input_string.startswith('r'): play([random_choice(media_entries)]) elif input_string.startswith('s'): # random.shuffle does it in-place: shuffle(media_entries) play(media_entries) else: 'Not a valid playlist command, try again.'
def detailview_display(self, context): request = context['request'] user = request.user reloading_info = self.reloading_info or {} item_count_str = str(request.GET.get('count') or reloading_info.get('count', '')) item_count = int(item_count_str) if item_count_str.isdigit() else 20 images = TEST_IMAGE_URLS image_count = len(images) image_ids = list(range(0, image_count - 1)) data = [] for item_id in range(item_count): image_name, image_url = images[random_choice(image_ids)] data.append(Dummy('Dummy ({}) - {}'.format(item_id + 1, image_name), user, media_url(image_url))) # return self._render(self.get_block_template_context( return self._render(self.get_template_context( context, data, reloading_info={'count': item_count} # update_url='/creme_core/blocks/reload/basic/%s/' % self.id_ # update_url=reverse('creme_core__set_block_state', args=(self.id_,)), ))
def find_imp_neig(imp_neigs, g1, perc, model, scaler, inputs, explore_prob, rand_flag): # rename to epsilon-greedy score_fin = None comp_bool_fin = None if len(imp_neigs) == 1: imp_neig = list(imp_neigs.keys())[0] else: cur_trial = rand_uniform(low=0.0, high=1.0) if cur_trial <= explore_prob: logging_debug("Exploring with low probability" ) # Move to top for efficiency and remove del max imp_neig = random_choice(list(imp_neigs.keys())) rand_flag = 1 else: if inputs["use_all_neigs"] == 0: imp_neigs = pick_top_weight_neigs(imp_neigs, perc, inputs) # Return none when imp_neigs is None for neig in imp_neigs: # Add to graph g1 = add_newnode(g1, neig, imp_neigs[neig]['graph_neigs']) # Check score (score_curr, comp_bool) = get_score(g1, model, scaler, inputs['model_type']) imp_neigs[neig]['compScore'] = score_curr imp_neigs[neig]['compBool'] = comp_bool g1.remove_node(neig) imp_neig_tup = max(imp_neigs.items(), key=lambda elem: elem[1]['compScore']) imp_neig = imp_neig_tup[0] score_fin = imp_neig_tup[1]['compScore'] comp_bool_fin = imp_neig_tup[1]['compBool'] return imp_neig, score_fin, comp_bool_fin, rand_flag
def regex(): occ = randint(5, 20) r = "abc" for o in xrange(occ): w = randint(0, 10) if w >= 0 and w <= 3: r += random_choice(REGEX_CHARS) elif w == 4: r += "{%d, %d}" % (randint(0, 1024), randint(0, 1024)) elif w == 5: r += "{%d,}" % randint(0, 1024) elif w == 6: l = randint(0, len(r)-1) r1, r2 = r[:l], r[l:] r = "(%s|%s)" % (r1, r2) elif w == 7: l = randint(0, len(r)-1) r1, r2 = r[:l], r[l:] r = "(%s)%s" % (r1, r2) elif w == 8: l = randint(0, len(r)-1) r1, r2 = r[:l], r[l:] r = "[%s]%s" % (r1, r2) elif w == 9: l = randint(0, len(r)-1) r1, r2 = r[:l], r[l:] r = "[^%s]%s" % (r1, r2) return r
def slide_tones(duration): filename = programName + ".wav" print >>stderr, "writing audio output to %s" % filename output = WavOut(filename=filename,channels=1) # define timing quarterNote = 60*zook.sec / float(tempo) slideDur = quarterNote / 4.5 # create a scale, two octaves of an Eb pentatonic Eb = 51 # (51 is the midi note number for E-flat) twoOctaves = 2*5+1 # (two 5-note octaves plus root on both ends) scale = build_pentatonic_scale("IV",Eb,twoOctaves) print "scale=[%s]" % ",".join([str(note) for note in scale]) # create the sound chain; this is a simple oscillator but with the # frequency controlled by a ramp object; the ramp parameters will be # set inside the loop slide = CubicRamp() oscar = oscType(gain=gain) oscar.freq = slide oscar >> output # generate a series of random notes; for each note we choose a random # frequency and use the ramp object to "slide" the oscillator from the old # frequency to the new prevFreq = 0.0 startTime = now() while (now() < startTime + duration): noteStart = now() endOfNote = noteStart + quarterNote freq = midi_to_freq(random_choice(scale)) if (freq < prevFreq): # slide down to the new frequency in one application of the ramp print "sliding from %.1f to %.1f" % (prevFreq,freq) slide.trigger(freq,slideDur) yield slideDur else: # slide up past, then down to, the new frequency in two # applications of the ramp overshootRatio = randint(3,7) overshootFreq = freq * overshootRatio print "sliding from %.1f thru %.1f to %.1f" % (prevFreq,overshootFreq,freq) slide.trigger(overshootFreq,slideDur/2) yield slideDur/2 slide.trigger(freq,slideDur/2) yield slideDur/2 # hold the note frequency steady for the remainger of the quarter note yield ("absolute",endOfNote) prevFreq = freq; output.close()
def __init__(self, player_a, player_b): self.player_a = player_a self.player_b = player_b self.field = ['---', '---', '---'] self.first_player = self.active_player = random_choice([player_a, player_b]) self.winner = None self.finished = False self.room = str(uuid4())
def spin_reel(reel_id): prizes = db(db.prize.reel == reel_id).select() reel = [] for prize in prizes: reel += prize.repeat * [prize.id] from random import choice as random_choice from random import shuffle shuffle(reel) c1 = random_choice(reel) c2 = random_choice(reel) c3 = random_choice(reel) return c1, c2, c3
def sample_(S): """ # sample from a set with replacement """ if len(S) == 0: return '' else: return random_choice(list(S))
def __rnd_fill(self, colours, shapes, stones): """ Generate the random code, return the list. """ if colours <= stones >= shapes: colour_list = [] shapes_list = [] rnd_list = [] for i in range(1, colours + 1): colour_list += str(i) for i in range(1, shapes + 1): shapes_list += str(i) for i in range(1, stones + 1): rnd_colour = random_choice(colour_list) rnd_shape = random_choice(shapes_list) rnd_list.append([int(rnd_colour), int(rnd_shape)]) colour_list.remove(rnd_colour) shapes_list.remove(rnd_shape) return rnd_list
def integer(): """return a random integer""" what = randint(0, 2) if what == 0: return randint(0, 0xFFFFFFFF) elif what == 1: return -randint(0, 0xFFFFFFFF) elif what == 2: return random_choice(SPECIAL_VALUES)
def get_random_quote_or_default(): all_quotes = AllQuotesQuery.get_cached() if all_quotes: quote = random_choice(all_quotes) else: quote = Quote() quote.quote = 'Ingen quotes er lastet opp enda.' quote.author = 'Trist teknisk ansvarlig' return quote
def operation(): """return random operation""" opps = [ '+', '-', '*', '/', '%' ] nbop = randint(0, MAX_OPERATION) op = "" for i in range(nbop): op += str(integer()) + random_choice(opps) op += str(integer()) return op
def gene_distance(A,B): '''compute sequence distance between two genes A and B ''' X,Y = '','' # new sequence removing common gaps for a,b in izip(A.values,B.values): if (a in A.gap_chars) and (b in B.gap_chars): continue if a in A.degenerate_chars: X += random_choice(list(A.degenerate_map[a])) else: X += a if b in B.degenerate_chars: Y += random_choice(list(B.degenerate_map[b])) else: Y += b newA = DNA(X,metadata={}) newB = DNA(Y,metadata={}) return newA.distance(newB)
def html(): tags = ('html', 'head', 'body', 'b', 'h1', 'font', 'audio', 'embed') occ = randint(5, 20) s = "" for o in xrange(occ): w = randint(0, 4) if w == 0: s += "<%s>" % random_choice(tags) elif w == 1: s += "</%s>" % random_choice(tags) elif w == 2: s += regex() elif w == 3: s += "&#%u;" % randint() * randint() elif w == 4: s += "&" # TODO: more elif. return s
def article_image(request, article_id): try: article = Article.get_or_404(article_id) except: return HttpResponseTemporaryServerError() if article.image_url: return HttpResponse(article.image_url) # BIG FAT WARNING: do not commit until the method gets more love. image_url = article.find_image(commit=False) if image_url: return HttpResponse(image_url) numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) categories = ('abstract', 'animals', 'business', 'cats', 'city', 'food', 'nightlife', 'fashion', 'people', 'nature', 'sports', 'technics', 'transport') tags = set([t.name.lower() for t in article.tags] + [t.name.lower() for t in article.feed.tags]) # # HEADS UP: if you change LoremPixel dimensions, # replicate them in _read-list.scss # try: for tag in tags: if tag in categories: return HttpResponse( u'http://lorempixel.com/g/180/112/{0}/{1}'.format( tag, random_choice(numbers))) except: LOGGER.exception('Could not do fun things with article/feed tags') # This will probably be confusing for the user (category # images changes everytime), but is easily fixable. return HttpResponse(u'http://lorempixel.com/g/180/112/{0}/{1}'.format( random_choice(categories), random_choice(numbers)))
def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) questions = self.get_queryset() if questions: magic_question_id = random_choice([q.id for q in questions]) inst = Question.objects.get(id=magic_question_id) context['form'] = QuestionForm(instance=inst) context['question'] = inst context['question_list'] = questions.exclude(id=inst.id) #get_thumbnailer(inst.question_img)['avatar'] return context
def run(self): self.init() try: while True: test_file = random_choice(self.filedb) print "[+] %s error -- test file: %s" % (self.nb_error, test_file) fuzz = FileFuzzer(self, test_file) ok = self.fuzzFile(fuzz) if not ok: break except KeyboardInterrupt: print "Stop"
def test_polls(self): for i in range(1, 10): print("Round {}".format(i)) for poll in Poll.objects.all(): print("Voting in poll {}".format(poll.id)) choice = random_choice(poll.choice_set.all()) poll.vote_for(choice_id=choice.id) for poll in Poll.objects.all(): winner_choice = poll.get_winner_choice() print("Winner choice for poll {} is {} with {} votes".format( poll.id, winner_choice.id, winner_choice.votes))
def get_random_spawnpoint(self, flags, team): spawnpoints = [] for item in flags: if flags[item]['status'] == team: if int(flags[item]['spawnX']) != 0: spawnpoints.append(Vector(flags[item]['spawnX']+30, flags[item]['spawnY']+30, flags[item]['spawnZ']+10)) else: spawnpoints.append(Vector(flags[item]['X']+30, flags[item]['Y']+30, flags[item]['Z']+10)) if not spawnpoints: return None vector = random_choice(spawnpoints) return vector
def choose(entries, random=False): """Choose an entry from a entries, or get a random one.""" if not entries: raise Exception("Can't choose. List is empty.") if random: return random_choice(entries) if len(entries) == 1: return entries display(entries) response = input("Choose: ") # Split optionally on ",", to allow entry of multiple choices choice = [int(i.strip()) for i in response.split(",")] return [entries[c] for c in choice]
def proxy_check(): proxies = {'http': HTTP_PROXY, 'https': HTTPS_PROXY} try: url = random_choice(_proxy_test_site) r = requests.get(url=url, proxies=proxies, timeout=3) if r.status_code == 200: return True else: return False except (exceptions.MissingSchema, exceptions.ConnectTimeout, exceptions.ReadTimeout, exceptions.ConnectionError) as e: sys.stdout.flush() print_color('RED', 'Failed to enable proxy - Using directly connection(Reason: {0})'.format(e)) return False
def main(): from string import ascii_letters from random import choice as random_choice ascii_length = len(ascii_letters) for i in range(ascii_length): test_string_1 = test_string_2 = ascii_letters[i] random_letter = random_choice(ascii_letters) if i % 2 == 0: test_string_2 += random_letter else: test_string_1 += random_letter difference = string_difference(test_string_1, test_string_2) assert difference == "{}".format(random_letter), "Expected string difference of {}, was actually {} when s1 = {} and s2 = {} on i = {}".format(random_letter, difference, test_string_1, test_string_2, i)
def string(): """return a random string""" string = '"' size = randint(15, MAX_STRING_SIZE) if randint(0, 5) > 3: string += random_choice(PROTOS) + "://" if randint(0, 5) > 3: string += "/" #for i in range(size): # string += chr(randint(48, 122)) string += "A" * (size - 15) string += '%0.262159f%s%jn%qu%s%S%s%s%n../../%s%n%555555n%x%x%x%x%x%n%n%n%n%x%x' if randint(0, 5) == 3: string += "%" + str(integer()) + "." + str(integer()) + random_choice(FORMATS) if randint(0, 5) == 3: string += "%" + str(integer()) + random_choice(FORMATS) if randint(0, 5) == 3: string += "%" + str(integer()) + "." + "*" * randint(0, 7) + random_choice(FORMATS) if randint(0, 5) == 3: string += "%." + str(integer()) + random_choice(FORMATS) string += '"' return string
def add_ship_randomly(self, length=None): ''' length: the length of the ship which will be added; if not given, a random value in the intervall [2; 5] is used ''' logger.debug('calling Player.add_ship_randomly') start_x = randrange(DEFAULT_FIELD_WIDTH) start_y = randrange(DEFAULT_FIELD_HEIGHT) start_coordinates = Coordinates(start_x, start_y) if length is None: length = randrange( DEFAULT_MIN_SHIP_LENGTH, DEFAULT_MAX_SHIP_LENGTH + 1) is_horintal = random_choice((True, False)) if is_horintal: new_x_coordinate = start_coordinates.x + length end_coordinates = Coordinates( new_x_coordinate, start_coordinates.y) else: new_y_coordinates = start_coordinates.y + length end_coordinates = Coordinates( start_coordinates.x, new_y_coordinates) try: validate_ship_coordinates( self.own_field, self.own_ships, start_coordinates, end_coordinates) except OutOfFieldError: logger.debug('out of field') # `length` was *added* which caused the ship to overlap a border of # the field # -> # `length` must be *subtracted* from the corresponding # coordinate of the start point if is_horintal: end_coordinates_x = start_coordinates.x - length end_coordinates = Coordinates( end_coordinates_x, end_coordinates.y) else: end_coordinates_y = start_coordinates.y - length end_coordinates = Coordinates( end_coordinates.x, end_coordinates_y) logger.debug(repr((start_coordinates, end_coordinates))) self.add_ship(start_coordinates, end_coordinates)
def mangle(data, percent, min_count=MIN_COUNT, max_count=MAX_COUNT): """ Mangle data: add few random bytes in input byte array. This function is based on an idea of Ilja van Sprundel (file mangle.c). """ hsize = len(data)-1 max_percent = max(min(percent, 1.0), 0.0001) count = int( float(len(data)) * max_percent ) count = max(count, min_count) count = min(count, max_count) count = randint(1, count) for index in xrange(count): operation = random_choice(MANGLE_OPERATIONS) offset = randint(0, hsize) operation(data, offset) return count