コード例 #1
0
def login():
    global err
    err = ''
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        # Get user input:
        nick = mdb.escape_string(request.form['nickname'])
        password = request.form['pwd']
        if authenticate(nick, password):  # Verify the address for nickname.
            query = QueryGenerator.get_score()
            connector = DbConnector()
            data = connector.get_one_result_for_query(
                query, (nick, nick))  # Get user's score.
            connector.close()
            if data[0] is None:  # User has not played any game yet.
                score = 0
            else:
                score = data[0]
            err = None
            response = make_response(redirect('/'))
            return update_cookies_logged_in(nick, score, response)
        else:
            err = 'Invalid nickname or password. Please try again!\n If you are new to Mr. Music, please sign up'
            return render_template('login.html', error=err)
コード例 #2
0
    def update_cookie_with_new_score(nickname, response):
        connector = DbConnector()
        new_score_row = connector.get_one_result_for_query(
            QueryGenerator.get_score(), (nickname, nickname))
        new_score = str(new_score_row[0])
        connector.close()
        response.set_cookie('score', new_score)

        return response
コード例 #3
0
ファイル: PairsGame.py プロジェクト: Assafbs/DataBlasters
def generate_countries_game():
    reload(sys)
    sys.setdefaultencoding('UTF8')
    connector = DbConnector()

    nickname = Common.common.get_value_from_cookie(request, 'nickname')
    if nickname is None:
        return redirect('/log_in')

    winner_artists = translate_artist_id_list_to_artist_name_list(
        connector,
        get_winning_artists_from_countries(connector))  # get the right answer
    lst_of_bad_artists = translate_artist_id_list_to_artist_name_list(
        connector,
        get_bad_artists_from_countries(connector))  # get the wrong answers
    right_answer = winner_artists[0] + "!@" + winner_artists[1]
    wrong_answers = calc_answers_artist_pairs(lst_of_bad_artists)
    answers = random.sample(wrong_answers + [right_answer],
                            4)  # mix the answers
    connector.close()
    try:
        user_score = Common.common.get_value_from_cookie(request, 'score')

        if float(user_score) > 500 and nickname is not None:
            get_bonus = 'true'
        else:
            get_bonus = ''
        response = make_response(
            render_template(
                'PairsGame.html',
                question=
                " Which of these pairs of artists come from the same country?",
                option_1_1=answers[0].split('!@')[0],
                option_1_2=answers[0].split('!@')[1],
                option_2_1=answers[1].split('!@')[0],
                option_2_2=answers[1].split('!@')[1],
                option_3_1=answers[2].split('!@')[0],
                option_3_2=answers[2].split('!@')[1],
                option_4_1=answers[3].split('!@')[0],
                option_4_2=answers[3].split('!@')[1],
                game=game_manager.answer_num + 1,
                score=user_score,
                nickname=nickname,
                game_score=game_manager.score,
                bonus=get_bonus))
        response.set_cookie('correctAnswerNum',
                            str(answers.index(right_answer) +
                                1))  # update num of right answer
        return game_manager.update_cookies_for_new_question(
            response)  # prepare next question
    except Exception as e:
        print "Error occurred with response"
        print e.message
        generate_countries_game()
コード例 #4
0
def create_main_highscores_page(category, num):
    nickname = Common.common.get_value_from_cookie(request, 'nickname')
    # Make sure user is logged in, otherwise redirect to log in page.
    if nickname is None:
        return redirect('/log_in')
    user_score = Common.common.get_value_from_cookie(request, 'score')
    connector = DbConnector()
    top_users = get_relevant_result(connector, num)
    users_scores = get_relevant_user_scores(connector, num, nickname)
    connector.close()
    dummy_user = ("", "")
    while len(top_users) < 10:  # In case we have less than 10 users, fill with dummy ones.
        top_users = top_users + (dummy_user,)

    if float(user_score) > 500 and nickname is not None:
        get_bonus = 'true'
    else:
        get_bonus = ''
    response = make_response(render_template('highscores.html',
                                             category=category,
                                             score=user_score,
                                             nickname=nickname,
                                             user_score=users_scores[0][0],
                                             user_total_points=users_scores[0][1],
                                             tab1=get_tab_class(1, num),
                                             tab2=get_tab_class(2, num),
                                             tab3=get_tab_class(3, num),
                                             tab4=get_tab_class(4, num),
                                             tab5=get_tab_class(5, num),
                                             tab6=get_tab_class(6, num),
                                             tab7=get_tab_class(7, num),
                                             user_1=mark_if_user(top_users[0][0], nickname),
                                             score_user_1=clean(top_users[0][1]),
                                             user_2=mark_if_user(top_users[1][0], nickname),
                                             score_user_2=clean(top_users[1][1]),
                                             user_3=mark_if_user(top_users[2][0], nickname),
                                             score_user_3=clean(top_users[2][1]),
                                             user_4=mark_if_user(top_users[3][0], nickname),
                                             score_user_4=clean(top_users[3][1]),
                                             user_5=mark_if_user(top_users[4][0], nickname),
                                             score_user_5=clean(top_users[4][1]),
                                             user_6=mark_if_user(top_users[5][0], nickname),
                                             score_user_6=clean(top_users[5][1]),
                                             user_7=mark_if_user(top_users[6][0], nickname),
                                             score_user_7=clean(top_users[6][1]),
                                             user_8=mark_if_user(top_users[7][0], nickname),
                                             score_user_8=clean(top_users[7][1]),
                                             user_9=mark_if_user(top_users[8][0], nickname),
                                             score_user_9=clean(top_users[8][1]),
                                             user_10=mark_if_user(top_users[9][0], nickname),
                                             score_user_10=clean(top_users[9][1]),
                                             bonus=get_bonus,
                                             ))
    return response
コード例 #5
0
def new_password():
    # Validation - user is logged in.
    nickname = Common.common.get_value_from_cookie(request, 'nickname')
    if nickname is None:  # if not logged in - send to home page.
        return redirect('/log_in')
    user_score = Common.common.get_value_from_cookie(
        request, 'score')  # To show the user's score.

    global err
    err = ''
    nick_cookie = Common.common.get_value_from_cookie(request, 'nickname')
    user_score = Common.common.get_value_from_cookie(request, 'score')
    if float(user_score) > 500 and nickname is not None:
        get_bonus = 'true'
    else:
        get_bonus = ''
    if request.method == 'GET':
        return render_template('new_pass.html',
                               score=user_score,
                               nickname=nickname,
                               bonus=get_bonus)
    elif request.method == 'POST':
        nick = mdb.escape_string(request.form['nickname'])
        if nick_cookie != nick:  # Avoid user from changing another user's password.
            err = "You can only change your own password"
            return render_template('new_pass.html',
                                   error=err,
                                   score=user_score,
                                   nickname=nickname,
                                   bonus=get_bonus)  # Display error.
        oldPwd = mdb.escape_string(request.form['oldPwd'])
        newPwd = mdb.escape_string(request.form['newPwd'])
        if oldPwd == newPwd:  # Check that user is actually changing password.
            err = "Your new password is identical to your old one."
            return render_template('new_pass.html',
                                   error=err,
                                   score=user_score,
                                   nickname=nickname,
                                   bonus=get_bonus)  # Display error.
        con = DbConnector()
        if authenticate(nick, oldPwd):  # Check user gave his current password.
            hased_new = pbkdf2_sha256.hash(newPwd)  # Hash new password.
            con.execute_query(QueryGenerator.update_password(),
                              (hased_new, nick))  # Update password.
            con.close()
            err = "Congrats! You have a new password!"
            return render_template('new_pass.html',
                                   error=err,
                                   score=user_score,
                                   nickname=nickname,
                                   bonus=get_bonus)
        else:
            con.close()
            err = "Nickname or password are invalid. Please try again"
            return render_template('new_pass.html',
                                   error=err,
                                   score=user_score,
                                   nickname=nickname,
                                   bonus=get_bonus)
コード例 #6
0
def authenticate(nick, password):
    if not (is_valid_login_input(nick, password)):
        return False
    connector = DbConnector()
    data = connector.get_one_result_for_query(QueryGenerator.get_user_data(),
                                              (nick, ))
    connector.close()
    if data is None:
        return False
    else:
        if pbkdf2_sha256.verify(
                password,
                data[2]):  # Compares to the hash stored in the users table.
            return True
        return False
コード例 #7
0
ファイル: WordInSongs.py プロジェクト: Assafbs/DataBlasters
def create_words_in_song_game_page():
    nickname = Common.common.get_value_from_cookie(request, 'nickname')
    if nickname is None:
        return redirect('/log_in')

    connector = DbConnector()
    song_row = connector.get_one_result_for_query(QueryGenerator.get_word_in_song_question_query())

    lyrics = song_row[2]
    popular_words = get_5_popular_words(lyrics)
    right_answer = popular_words[0]
    wrong_answers = popular_words[1:4]

    connector.close()
    answers = random.sample(wrong_answers + [right_answer], 4)
    question_kind = "Which of the following words appears the most in the song? "

    try:
        user_score = Common.common.get_value_from_cookie(request, 'score')

        if float(user_score) > 500 and nickname is not None:
            get_bonus = 'true'
        else:
            get_bonus = ''
        response = make_response(render_template('WordInSongGame.html',
                                                 question=song_row[1],
                                                 question_kind=question_kind,
                                                 option_1=answers[0],
                                                 option_2=answers[1],
                                                 option_3=answers[2],
                                                 option_4=answers[3],
                                                 game=game_manager.answer_num + 1,
                                                 score=user_score,
                                                 nickname=nickname,
                                                 game_score=game_manager.score,
                                                 bonus=get_bonus))

        response.set_cookie('correctAnswerNum', str(answers.index(right_answer) + 1))
        return game_manager.update_cookies_for_new_question(response)
    except Exception as e:
        print "Error occurred with response"
        print e.message
        create_words_in_song_game_page()
コード例 #8
0
ファイル: WordInSongs.py プロジェクト: Assafbs/DataBlasters
def build_frq_word_dict():
    global frq_word_dict
    query = "SELECT lyrics FROM lyrics WHERE lyrics_language=%s"
    con = DbConnector()
    data = con.get_all_results_for_query(query, ('en',))
    con.close()
    for lyc in data:
        words_count = get_dict_word_count(lyc[0])
        for word in words_count:
            if word not in ign_words:
                if word not in frq_word_dict:
                    frq_word_dict.update({word: 1})
                else:
                    frq_word_dict.update({word: frq_word_dict[word] + 1})
    del_lst = []
    for key in frq_word_dict:
        if frq_word_dict[key] < 20 or len(key) < 2:
            del_lst.append(key)
    for key in del_lst:
        frq_word_dict.pop(key, None)
    return
コード例 #9
0
def generate_most_popular_song_question():
    nickname = Common.common.get_value_from_cookie(request, 'nickname')
    # Make sure user is logged in, otherwise redirect to log in page.
    if nickname is None:
        return redirect('/log_in')

    connector = DbConnector()
    country_index = game_manager.answer_num % len(COUNTRIES)
    result = connector.get_all_results_for_query(
        QueryGenerator.get_four_ranked_songs_in_country(),
        (COUNTRIES[country_index], COUNTRIES[country_index],
         COUNTRIES[country_index], COUNTRIES[country_index]))
    while len(
            result
    ) == 0:  # Just for safety, shouldn't happen unless DB is corrupted.
        country_index = (country_index + 1) % len(COUNTRIES)
        result = connector.get_all_results_for_query(
            QueryGenerator.get_four_ranked_songs_in_country(),
            (COUNTRIES[country_index], COUNTRIES[country_index],
             COUNTRIES[country_index], COUNTRIES[country_index]))
    connector.close()
    options = result[0]
    right_answer = options[0]
    answers = list(options)
    random.shuffle(answers)

    try:
        user_score = Common.common.get_value_from_cookie(request, 'score')

        if float(user_score) > 500 and nickname is not None:
            get_bonus = 'true'
        else:
            get_bonus = ''
        response = make_response(
            render_template(
                'RankByCountryGame.html',
                question=
                "Which of the following songs is ranked the highest in " +
                COUNTRIES[country_index] + "?",
                option_1=answers[0],
                option_2=answers[1],
                option_3=answers[2],
                option_4=answers[3],
                game=game_manager.answer_num + 1,
                score=user_score,
                nickname=nickname,
                game_score=game_manager.score,
                bonus=get_bonus))

        response.set_cookie('correctAnswerNum',
                            str(answers.index(right_answer) + 1))
        return game_manager.update_cookies_for_new_question(response)

    # In case there was a problem rendering the template, we will try replacing the question.
    # This is just for safety, and should not happen.
    except Exception as e:
        print "Error occurred with response - rank by country game - most popular song."
        print e.message
        generate_most_popular_song_question()
コード例 #10
0
def create_game_page():
    nickname = Common.common.get_value_from_cookie(request, 'nickname')
    if nickname is None:
        return redirect('/log_in')

    connector = DbConnector()
    # find two artist that sang together
    answer_row = connector.get_one_result_for_query(QueryGenerator.get_duets_question_query())

    right_answer = answer_row[2]  # seconed artist name
    wrong_answers = calc_answers(connector, answer_row[0])  # first artist id
    connector.close()
    answers = random.sample(wrong_answers + [right_answer], 4)

    try:
        user_score = Common.common.get_value_from_cookie(request, 'score')
        if float(user_score) > 500 and nickname is not None:
            get_bonus = 'true'
        else:
            get_bonus = ''
        response = make_response(render_template('DuetsGame.html',
                                                 question=answer_row[1],  # first artist name
                                                 option_1=answers[0],
                                                 option_2=answers[1],
                                                 option_3=answers[2],
                                                 option_4=answers[3],
                                                 game=game_manager.answer_num + 1,
                                                 score=user_score,
                                                 nickname=nickname,
                                                 game_score=game_manager.score,
                                                 bonus=get_bonus))

        response.set_cookie('correctAnswerNum', str(answers.index(right_answer) + 1))
        return game_manager.update_cookies_for_new_question(response)
    except Exception as e:
        print "Error occurred with response"
        print e.message
        create_game_page()
コード例 #11
0
ファイル: WordInSongs.py プロジェクト: Assafbs/DataBlasters
def create_3_songs_game_page():
    # validate user logged in. if not- send to login page
    nickname = Common.common.get_value_from_cookie(request, 'nickname')
    if nickname is None:
        return redirect('/log_in')

    connector = DbConnector()
    query = "SELECT word FROM frequent_words ORDER BY RAND() LIMIT 1"
    correct_answer = connector.get_one_result_for_query(query)[0]  # get a frequent word randomly
    # get 3 song(titles) containging the word
    data = connector.get_all_results_for_query(QueryGenerator.get_songs_lyrics_contain(), (correct_answer, correct_answer))
    while len(data) < 3:  # if returned less than 3 titles
        correct_answer = connector.get_one_result_for_query(query)[0]  # change word
        data = connector.get_all_results_for_query(QueryGenerator.get_songs_lyrics_contain(),
                                                   (correct_answer, correct_answer))  # get 3 songs for new word
    songs = [tup[0] for tup in data]
    wrong_answers = get_wrong_answers(connector, correct_answer, songs, query)  # get 3 words that do not appear in all 3 songs
    connector.close()
    answers = random.sample(wrong_answers + [correct_answer], 4)  # randomize the order of the 4 options
    question_kind = "Which one of the words appear in all the following songs:"
    question = ", ".join(songs[0:3])
    try:
        user_score = Common.common.get_value_from_cookie(request, 'score')

        if float(user_score) > 500 and nickname is not None:
            get_bonus = 'true'
        else:
            get_bonus = ''
        response = make_response(render_template('WordInSongGame.html',
                                                 question=question,
                                                 question_kind=question_kind,
                                                 option_1=answers[0],
                                                 option_2=answers[1],
                                                 option_3=answers[2],
                                                 option_4=answers[3],
                                                 game=game_manager.answer_num + 1,
                                                 score=user_score,
                                                 nickname=nickname,
                                                 game_score=game_manager.score,
                                                 bonus=get_bonus))
        # store correct answer in cookie for further use
        response.set_cookie('correctAnswerNum', str(answers.index(correct_answer) + 1))
        return game_manager.update_cookies_for_new_question(response)
    except Exception as e:
        print "Error occurred with response"
        print e.message
        create_game_page()
コード例 #12
0
def generate_in_which_country_is_least_popular_question():
    nickname = Common.common.get_value_from_cookie(request, 'nickname')
    # Make sure user is logged in, otherwise redirect to log in page.
    if nickname is None:
        return redirect('/log_in')

    random_countries = random.sample(COUNTRIES, 4)
    connector = DbConnector()
    result = connector.get_all_results_for_query(
        QueryGenerator.get_song_ranking_in_four_countries(),
        (random_countries[0], random_countries[1], random_countries[2],
         random_countries[3]))
    while len(result) == 0:
        random_countries = random.sample(COUNTRIES, 4)
        result = connector.get_all_results_for_query(
            QueryGenerator.get_song_ranking_in_four_countries(),
            (random_countries[0], random_countries[1], random_countries[2],
             random_countries[3]))
    connector.close()
    song_name = result[0][0]
    ranking = result[0][1:]
    right_answer = random_countries[ranking.index(
        max(ranking))]  # The country with highest ranking.

    try:
        user_score = Common.common.get_value_from_cookie(request, 'score')

        if float(user_score) > 500 and nickname is not None:
            get_bonus = 'true'
        else:
            get_bonus = ''
        response = make_response(
            render_template('RankByCountryGame.html',
                            question="In which country the song '" +
                            song_name + "' is ranked the lowest?",
                            option_1=random_countries[0],
                            option_2=random_countries[1],
                            option_3=random_countries[2],
                            option_4=random_countries[3],
                            game=game_manager.answer_num + 1,
                            score=user_score,
                            nickname=nickname,
                            game_score=game_manager.score,
                            bonus=get_bonus))

        response.set_cookie('correctAnswerNum',
                            str(random_countries.index(right_answer) + 1))
        return game_manager.update_cookies_for_new_question(response)

    # In case there was a problem rendering the template, we will try replacing the question.
    # This is just for safety, and should not happen.
    except Exception as e:
        print "Error occurred with response - rank by country game - least popular."
        print e.message
        generate_in_which_country_is_least_popular_question()
コード例 #13
0
def is_valid_sign_up_input(nick, email, password):
    global err
    if not nick.isalnum():
        err = "Nickname can contain only numbers and letters"
        return False
    if not password.isalnum():
        err = "Password can contain only numbers and letters"
        return False
    connector = DbConnector()
    data = connector.get_one_result_for_query(QueryGenerator.get_user_data(),
                                              (nick, ))
    if data is not None:
        err = "This nickname is already taken. Please choose a different one"
        return False
    data = connector.get_one_result_for_query(QueryGenerator.get_email(),
                                              (email, ))
    if data is not None:
        err = "This email is already in use"
        return False
    connector.close()
    return True
コード例 #14
0
def signup():
    global err
    err = ''
    if request.method == 'GET':
        return render_template('signup.html', error=err)
    elif request.method == 'POST':
        # Get user input:
        nick = mdb.escape_string(request.form['nickname'])
        password = request.form[
            'pwd']  # No need to sanitize - going through hash.
        email = mdb.escape_string(str(request.form['email']))

        if is_valid_sign_up_input(nick, email, password):  # Validate input,
            hash_password = pbkdf2_sha256.hash(password)  # Hash the password,
            connector = DbConnector()
            connector.execute_query(
                QueryGenerator.sign_in_user(),
                (nick, email,
                 hash_password))  # Insert new user to users table.
            connector.close()
            err = "You have signed up successfully! Let's Play!"
            response = make_response(redirect('/'))
            return update_cookies_logged_in(nick, 0, response)
        return render_template('signup.html', error=err)
コード例 #15
0
def create_game_page():
    # Avoiding UnicodeDecodeError
    reload(sys)
    sys.setdefaultencoding('UTF8')

    nickname = Common.common.get_value_from_cookie(request, 'nickname')
    # Make sure the user is logon before accessing this page
    if nickname is None:
        return redirect('/log_in')

    connector = DbConnector()
    rand_song_row = connector.get_one_result_for_query(QueryGenerator.get_release_order_question_query())
    rand_song_name = rand_song_row[3]

    album_id = rand_song_row[0]
    release_month = rand_song_row[1]
    release_year = rand_song_row[2]

    answers_rows = connector.get_all_results_for_query(
        QueryGenerator.get_release_order_answers_query(),
        (release_year, release_month, release_year, release_month, release_year,
         release_month, release_year, rand_song_name, album_id))
    connector.close()

    # order the 4 songs by the release date (merge rand_song_name with answers_rows)
    global ordered_answers
    ordered_answers = []
    inserted_rand_song_row = False
    for i in range(3):
        if int(answers_rows[i][0]) > 0 and not inserted_rand_song_row:
            ordered_answers.append(rand_song_name)
            inserted_rand_song_row = True
        ordered_answers.append(answers_rows[i][1])
    if not inserted_rand_song_row:
        ordered_answers.append(rand_song_name)

    rand_order_answers = random.sample(ordered_answers, 4)

    try:
        user_score = Common.common.get_value_from_cookie(request, 'score')

        if float(user_score) > 500 and nickname is not None:
            get_bonus = 'true'
        else:
            get_bonus = ''
        response = make_response(render_template('ReleaseOrderGame.html',
                                                 game=game_manager.answer_num + 1,
                                                 score=user_score,
                                                 nickname=nickname,
                                                 game_score=game_manager.score,
                                                 question='"' + '",  "'.join(rand_order_answers) + '"',
                                                 option_1=rand_order_answers[0],
                                                 option_2=rand_order_answers[1],
                                                 option_3=rand_order_answers[2],
                                                 option_4=rand_order_answers[3],
                                                 bonus=get_bonus))

        return game_manager.update_cookies_for_new_question(response)
    except Exception as e:
        # in case there was a problem with rendering question page, we will try again
        print "Error occurred with response - release order game"
        print e.message
        create_game_page()
コード例 #16
0
 def update_game_result(self, nickname):
     connector = DbConnector()
     connector.execute_query(QueryGenerator.create_score_update_query(),
                             (nickname, time.strftime('%Y-%m-%d %H:%M:%S'),
                              self.game_id, self.score))
     connector.close()
コード例 #17
0
					event_data = pickle.loads(client.recv(size))
				except:
					continue
				response = False
				if event_data._event_type == 'ORDER':
					response = self._exchange.handle_order(event_data)
				elif event_data._event_type == 'REGISTER':
					response = self._exchange.handle_player_registration(event_data)
					self._connected_players[event_data._player_name] = client
					self.update_exchange_client_list()

				client.send(pickle.dumps(response))

			except Exception as e:
				print(e)
				#self._connected_players.remove(client)
				#self.update_exchange_client_list()
				print(f'closing for client {client} due to inactivity')
				client.close()
				return False

	def update_exchange_client_list(self):
		self._exchange._clients = self._connected_players
		self._exchange.update_player_id_to_name_mapper()

if __name__ == '__main__':
	conn = DbConnector('postgres', 5432, 'exchangedb', '127.0.0.1')
	cs = CastingServer('', 12346)
	ns = NotificationServer('', 12121)
	ex = Exchange(conn, ns, cs)
	server = ExchangeServer('', 12345, ex)
コード例 #18
0
import socket

from Common.db_connector import DbConnector

from Event.event_manager import EventManager

from Player.player import Player
from Player.data_listener import BookListener

initial_money = 10000
player_name = 'Notroop'

em = EventManager(12345)
conn = DbConnector('postgres', 5432, 'postgres', '127.0.0.1')
file_path = 'D:\\genericbacktesters\\book_data\\file.dat'
bl = BookListener('', 12347, file_path)

player = Player(initial_money, player_name, socket.gethostname(), 12121, em, conn)

symbol = 'YESBANK_EQ'
price = 14
direction = 'LONG'
quantity = 37
order_id = '292b93bb-ac8a-4e0c-b00c-7399c993c427'
#player.place_new_order(symbol, float(price), direction, int(quantity))


player.place_new_order(symbol, float(price), direction, int(quantity))
inp = input()
direction = 'SHORT'
player.place_new_order(symbol, float(price), direction, int(quantity))