Exemplo n.º 1
0
def index():
    """
    Return home page and activate functionality of buttons.
    Input: URL request
    Output: renders data using index.html
    """
    # Enables random GIFs to show.
    if request.args.get('random'):
        gif_info = []
        gif_type = None
        # Makes sure 10! Gifs are generated by searching a random word
        while len(gif_info) < 10:
            # Generates a random word to search
            gif_type = randomwordgenerator.generate_random_words(n=1)
            parameters = {"q": gif_type, "key": TENOR_API_KEY, "limit": limit}
            gif_info = get_gif_info("https://api.tenor.com/v1/random?",
                                    parameters)
        return render_template("index.html",
                               gif_info=gif_info,
                               gif_type=gif_type)

    # Enables top trends GIFs to show
    if request.args.get('trending'):
        parameters = {"key": TENOR_API_KEY, "limit": limit}
        gif_info = get_gif_info("https://api.tenor.com/v1/trending?",
                                parameters)
        return render_template("index.html", gif_info=gif_info, gif_type="")

    # Enables the page to initially load with 10 Gifs
    parameters = {"q": "", "key": TENOR_API_KEY, "limit": limit}
    gif_info = get_gif_info("https://api.tenor.com/v1/search?", parameters)
    return render_template("index.html", gif_info=gif_info, gif_type="")
Exemplo n.º 2
0
def create_fake_user_data(output_file_name, total_users, total_playlists,
                          total_songs):
    with open(
            'sql_creation/{}.sql'.format(CREATION_INSERTION_FILE
                                         or output_file_name),
            WRITE_PERM) as f:
        for id in range(0, total_users):
            f.write(insert('user', get_user_columns(id)))

        random_words = randomwordgenerator.generate_random_words(n=5000)
        for id in range(0, total_playlists):
            f.write(insert('playlist', get_playlist_columns(id, random_words)))

        for _ in range(0, total_playlists):
            f.write(
                insert(
                    'playlist_to_user',
                    get_playlist_to_user_columns(total_users,
                                                 total_playlists)))

        with open(SONG_DETAILS_FILENAME, 'r') as tracks_data:
            tracks = json.load(tracks_data)
            tracks = tracks['track_details']
            for _ in range(0, total_songs):
                f.write(
                    insert(
                        'track_in_playlist',
                        get_track_in_playlist_columns(total_playlists,
                                                      tracks)))
Exemplo n.º 3
0
def get_word():
    while (True):
        try:
            word = RandomWords().get_random_word(hasDictionaryDef="true",
                                                 includePartOfSpeech="noun")
        except Exception as exc:
            print('There was a problem: %s' % (exc))
            word = r_backup.generate_random_words(1)
        print("Random word: " + word)

        return word
Exemplo n.º 4
0
def randomWord():
    '''
    fetch random word from internet, or backup text list
    '''
    try:
        randNum = random.randrange(0, 20)        #gen random number between 1 and 20
        num_words = 20                           #int var of 20
        wordList = randomwordgenerator.generate_random_words(n = num_words)
        return wordList[randNum]  #<-returnword from list, ^gen random word list
    except UnicodeEncodeError:    #if the above fails
        backupList = ['test', 'bounce', 'child', 'golf', 'whim']
        randNum = random.randrange(0, (len(backupList))) #choose random word from backup list
        return backupList[randNum]    #return random word
Exemplo n.º 5
0
 def gen_city(self, pop_mod):
     city = City()
     city.population = pop_mod * random.randint(5, 12)
     city.food = food_cost(city.population) * 5
     city.wealth = city.population
     city.location = (random.randint(0, self.world_gen.map_width),
                      random.randint(0, self.world_gen.map_height))
     city.name = rword.generate_random_words(1).capitalize()
     city.race = random.choice(primitives['races']["humanoid"])
     god = random.choice(list(self.gods))
     god.worshiped_by.add(city.race)
     city.patron_god = god
     city.patron_god_attributes = god.divine_attributes
     return city
Exemplo n.º 6
0
def __main__():
    # 0: single track, only one track
    # 1: synchronous, start at the same time
    # 2: asynchronous, independent tracks (breaks .length)
    file = MidiFile(type=1)

    # generate tracks
    track_length = random.randint(min_time, max_time)
    steps = 0
    for i in tqdm(range(random.randint(min_tracks, max_tracks))):
        track = MidiTrack()
        file.tracks.append(track)

        load_file(i)

        track.append(Message('program_change', program=114, time=0))

        previous_note = None
        if i == 1:
            while file.length < track_length:
                steps += 1
                note = generate_weighted(previous_note)
                track.append(note)
                track.append(Message('note_off', note=64, velocity=127,
                                     time=0))
                previous_note = note
        else:
            for j in range(steps):
                note = generate_weighted(previous_note)
                track.append(note)
                track.append(Message('note_off', note=64, velocity=127,
                                     time=0))
                previous_note = note

    name = randomwordgenerator.generate_random_words(random.randint(1, 3))
    if type(name) is list:
        name = ' '.join(name)
    file.save('created_music/' + name + '.mid')

    winsound.PlaySound('sounds/oh no.wav', winsound.SND_ALIAS)
Exemplo n.º 7
0
def generate_dfs(num_df=5, cols=2, rows=5, variable_size=True):
    """
    NOTE: randomwordgenerator is quite slow!
    
    Function generates list with dfs.
    cols = number of cols in df
    rows = number of rows in df
    variable_size = allows df to have different size
    If variable_size == True; cols = lower bound on on cols and rows, rows = upper bound cols and rows.

    """
    if ((variable_size == True) & (cols > rows)):
        print("TESTW")
        raise ValueError("variable_size == True and cols > rows!")

    # Parameters
    num_df = num_df
    variable_size = variable_size
    if variable_size == False:
        # set fixed col and row sized if variable sizes are false
        df_cols = cols
        df_rows = rows
        num_words = df_rows

    df_list = []
    for i in range(num_df):
        if variable_size == True:
            df_cols = np.random.randint(cols, rows)
            df_rows = np.random.randint(cols, rows)
            num_words = df_rows
        words = randomwordgenerator.generate_random_words(n=num_words)
        if (type(words) is list) == False:
            words = [words]
        dat = np.random.rand(df_cols, df_rows)
        df = pd.DataFrame(dat, columns=words)
        df_list.append(df)

    return df_list
Exemplo n.º 8
0
from person import array
from randomwordgenerator import randomwordgenerator
get_word = lambda: randomwordgenerator.generate_random_words(n=1)


def play_game(word):
    lives = 6
    index = 0
    dashes = ["-" for _ in range(len(word))]
    print("Welcome to Hangman - Terminal Edition!!!")
    print("---------------------------------------------")
    print(f"LIVES LEFT: {lives}")
    print(array[6 - lives])
    print('\n')
    while lives > 1:
        print(index)
        print(f"LIVES:{lives}")
        letter = input(f"GUESS A LETTER: {''.join(dashes)} ")
        print(f"{len(letter)} is the length of your input")
        if len(letter) > 1 or len(letter) == 0:
            print("Not a valid letter.")
            print(f"LIVES LEFT: {lives}")
            print(array[6 - lives])
            print('\n')

        print(len(letter))
        if letter.upper() not in word and len(letter) == 1:
            index += 1
            lives -= 1
            print("---------------------------------------------")
            print("Incorrect letter.")
def hangman(name):

    from randomwordgenerator import randomwordgenerator as rw
    word_of_the_game = rw.generate_random_words(
    )  # generates a random English word

    word = word_of_the_game

    meaning = wordnet.synsets(
        word_of_the_game)  # gets the meaning of the input word to assist user
    print("\n")
    if meaning:
        print("Definition of your word: {}".format(meaning[0].definition()))
        print("\n")
    else:
        x = hangman(name)
        if x == 'Done':
            return 'finished'

    guess_counter = 0  # keeps a count of the number of guesses so far

    #  creating an empty string with blanks to keep track of the letters correctly guessed
    blank_word = []
    length = int(len(word_of_the_game))
    for i in range(0, length):
        blank_word.append("_")
    print(blank_word)
    print("\n")

    # looping till the user gets the word right or he has used up all his guesses

    while guess_counter <= 7:
        print("\n")
        print("Guesses Left - {}".format(7 - guess_counter))
        x = input("Take a guess: ")  # gets a guess letter from the user
        flag = word_of_the_game.find(
            x
        )  # finds the index position of the first occurence of the letter if it exists
        if flag >= 0:
            while flag >= 0:
                #blank_word_list = list(blank_word)
                blank_word[
                    flag] = x  # replacing the position of the correctly found letter in the blank word
                if word_of_the_game.count(x) == 1:
                    print(blank_word)
                word_of_the_game = word_of_the_game.replace(
                    x, '_', 1)  # replace it in original input string
                flag = word_of_the_game.find(
                    x
                )  # recursive call in case more than one occurence of a letter is there
        else:
            guess_counter = guess_counter + 1  # if not found, increase the guess count

        if guess_counter == 7:  # if guess count reaches 7, exit the loop
            break
        if word_of_the_game.count("_") == len(
                word_of_the_game):  # if all letters are found, exit the loop
            break

    if guess_counter == 7:
        print("\n")
        print('The word was {}'.format(word))
        print("{} lost! Please try again".format(name))
        print("\n")
        choice = input("Do you want to play again? Yes/No ")
        if (choice == 'Yes'):
            y = hangman(name)
        return "Done"

    elif len(blank_word) == len(word_of_the_game) and guess_counter != 7:
        print("\n")
        print("{} wins!!".format(name))
        print(blank_word)
        print("\n")
        choice = input("Do you want to play again? Yes/No ")
        if (choice == 'Yes'):
            y = hangman(name)
        return "Done"
Exemplo n.º 10
0
def get_word():
    return randomwordgenerator.generate_random_words()
Exemplo n.º 11
0
import json
import random

import requests
from randomwordgenerator import randomwordgenerator as rwg

BASE_URL = "http://localhost:8000/messages"
RANDOM_WORDS = rwg.generate_random_words(1000000)


def test_messenger_apis():
    """
    tests the messenger app create and get single message functionality
    """
    for i in range(12):
        # create a test message through the API
        test_message = _generate_test_message()
        print(f"creating test message = {test_message}")
        create = requests.post(BASE_URL, data=json.dumps(test_message))
        assert create.status_code == 201

        # get the created message and verify field matches
        message_location = create.headers['location']
        retrieve = requests.get(f"{BASE_URL}{message_location}")
        assert retrieve.status_code == 200
        returned_message = retrieve.json()
        assert returned_message['message'] == test_message['message']
        assert returned_message['sender'] == test_message['sender']
        assert returned_message['recipient'] == test_message['recipient']