Esempio n. 1
0
def get_message(room_id):
    if not 'loggedin' in session:
        message = {
            'status': False,
            'message': "Voce precisa estar autenticado para fazer isso"
        }
    elif not check_if_user_is_participant_of_group(session['id'], room_id):
        message = {
            'status': False,
            'message': "Voce nao participa desse grupo"
        }
    else:
        message = {'status': True, 'room_id': room_id, 'messages': []}
        users = Database().get_users()
        messages_raw = Database().get_user_messages(room_id)

        for _message in messages_raw:
            message['messages'].append({
                'id':
                _message['id'],
                'message':
                _message['message'],
                'username':
                find_user_name_by_id(_message['user_id'], users),
                'user_id':
                _message['user_id']
            })
    return jsonify(message)
Esempio n. 2
0
def get_participants_users(room_id):
    participants = Database().get_participants(room_id)
    users = Database().get_users()
    for participant in participants:
        participant['username'] = find_user_name_by_id(participant['user_id'],
                                                       users)
        participant['id'] = participant['user_id']
        del participant['room_id']
        del participant['user_id']
    return jsonify({'status': True, 'participants': participants})
Esempio n. 3
0
    def post(self):
        row = request.form['row']
        col = request.form['col']
        room_id = request.form['room_id']

        if is_logged():
            user_id = session['id']
            if row and col and room_id:
                row = int(row)
                col = int(col)
                room = Database().get_room(room_id)
                if user_id != room['user1_id'] and user_id != room['user2_id']:
                    return {'status': False, 'message': "you"}

                board: list = arr_to_matrix(str_to_arr(room['board']))

                if user_id == room['user2_id']:
                    board = board[::-1]
                    if room['turn'] == 1:
                        return {
                            'status': False,
                            'message': 'Is not your time to move'
                        }

                if not 'piece_selected' in session:
                    return {
                        'status': False,
                        'message': "You need to select a piece"
                    }

                select_row = int(session['piece_selected']['row'])
                select_col = int(session['piece_selected']['col'])

                moved = False

                for moves in session['movements']:
                    if moves['row'] == row and moves['col'] == col:
                        piece = board[select_row][select_col]
                        board[select_row][select_col] = 0
                        board[row][col] = piece
                        moved = True
                        break

                if moved:
                    room['turn'] = room['turn'] * -1

                Database().update_room_board(room['id'], arr_to_str(board))
                socket.emit("played", {"room_id": room_id})

                return {'status': moved}

            else:
                return send_invalid_form()
        else:
            return send_not_logged()
Esempio n. 4
0
def create_room():
    if not 'loggedin' in session:
        return jsonify({
            'status':
            False,
            'message':
            "Voce precisa estar autenticado para fazer isso"
        })
    elif 'name' in request.form:
        name = request.form['name']
        room_id = Database().add_room(name)
        Database().add_participant(room_id, session['id'])
        return jsonify({'status': True})
    else:
        return jsonify({'status': False})
Esempio n. 5
0
def delete_room():
    if 'room_id' in request.form:
        room_id = request.form['room_id']
        Database().delete_room(room_id)
        return jsonify({'status': True})
    else:
        return jsonify({'status': False})
Esempio n. 6
0
def index(req, **kwargs):
    req.content_type = "text/html"
    req.send_http_header()

    search = int(kwargs["search"])
    titles = [int(k) for k in kwargs["titles"].split(',')]
    selected = int(kwargs["selected"])

    mynet = SearchNet(Database(SqliteDriver('/var/www/data/nn.db')))
    #mynet.maketables()
    mynet.trainquery([search], titles, selected)

    anisearch = AnimeInfo(Database(SqliteDriver('/var/www/data/anime.db')))
    url = anisearch.info(selected)[0]

    return "<script>document.location='%s'</script>" % url
    def test_get_persons_born_between(self):
        database = Database(':memory:')
        session = database.get_session()

        dob_1 = DayOfBirth(date=datetime(year=1963, month=7, day=15))
        dob_2 = DayOfBirth(date=datetime(year=1975, month=1, day=3))
        dob_3 = DayOfBirth(date=datetime(year=2020, month=3, day=20))

        person_1 = Person(email='to early')
        person_1.day_of_birth = [dob_1]
        person_2 = Person(email='should be returned')
        person_2.day_of_birth = [dob_2]
        person_3 = Person(email='to late')
        person_3.day_of_birth = [dob_3]

        min_date = datetime(year=1970, month=1, day=1)
        max_date = datetime(year=1999, month=12, day=30)

        session.add_all([person_1, person_2, person_3])
        session.commit()

        data_fetcher = DataFetcher(database)

        values, columns = data_fetcher.get_persons_born_between(
            min_date=min_date, max_date=max_date)

        assert len(values) == 1
        assert values[0][0].email == 'should be returned'
Esempio n. 8
0
    def __init__(self, fake_database=False):
        # Misc. initializations go here:
        self.__scheduler = None  #   None

        # Initialize variables related to the discord connection:
        self.client = discord.Client()
        self.on_message = self.client.event(
            self.on_message)  # register with explicit decorator call

        # Initialize the database, fake_database param is used in tests, can also use while implementing features
        if fake_database:
            self.__database = MockDatabase()
        else:
            self.__database = Database()

        # Initialize things relating to commands, it will be a map that links a string identifier to a command instance
        self.command_prefix = "!"  # What should a message start with to identify it as a command?
        self.__commands = {}

        self.attach_scheduler(EventScheduler())

        # TODO Register actual commands here, these are simply here to show the system in action, remove them later
        self.register_command(
            PingPongCommand(self, 'ping', aliases=['pingpong', 'pongping']))
        self.register_command(ArgsTestCommand(self, 'test'))
        self.register_command(EventAdminCommand(self, 'event'))
        self.register_command(
            CalendarTestCommand(self,
                                'calendar',
                                aliases=['calendartest', 'testcalendar']))
        self.register_command(ReportCommand(self, 'report'))
Esempio n. 9
0
 def __init__(self):
     self.__path_dir_this = os.path.abspath(
         os.path.dirname(os.path.dirname(__file__)))
     #        self.__path_dir_this = os.path.abspath(os.path.dirname(__file__))
     #        self.__db = Database(self.__path_dir_this)
     self.__db = Database()
     #        self.__db = Database()
     self.__db.Initialize()
Esempio n. 10
0
def main():
    options = Options()
    args = options.get_arguments()

    database = Database()

    manager = Manager(args, database)
    manager.run()
Esempio n. 11
0
 def get_retweet(self):
     result = Database().buscar_todos_tweet()
     for r in result:
         try:
             print(r["text"])
             print('\n')
         except Exception as e:
             pass
Esempio n. 12
0
def remove_participant():
    room_id = request.form['room_id']
    user_id = request.form['user_id']

    if room_id and user_id:
        Database().remove_participant(room_id, user_id)
        return jsonify({'status': True})
    else:
        return jsonify({'status': False})
Esempio n. 13
0
    def get(self):
        if is_logged():
            rooms = Database().get_rooms()
            for room in rooms:
                room['board'] = arr_to_matrix(str_to_arr(room['board']))

            return {'status': True, 'rooms': rooms}
        else:
            return send_not_logged()
Esempio n. 14
0
    def setUp(self):
        self.db = Database()
        self.sql_count_article = 'SELECT count(article_id) FROM HooliASE.articles'
        self.sql_count_question = 'SELECT count(question_id) FROM HooliASE.questions'
        self.sql_count_history = 'SELECT count(history_id) FROM HooliASE.history'
        self.sql_count_feedback = 'SELECT count(id) FROM HooliASE.answer_feedback'

        self.sql_delete_article = 'DELETE from HooliASE.articles WHERE article_id=%s'
        self.sql_delete_question = 'DELETE from HooliASE.questions WHERE question_id=%s'
        self.sql_delete_history = 'DELETE from HooliASE.history WHERE history_id=%s'
        self.sql_delete_feedback = 'DELETE from HooliASE.answer_feedback WHERE id=%s'
Esempio n. 15
0
    def post(self):
        room_id = request.form['room_id']

        if is_logged():
            if room_id:
                Database().delete_room(room_id)
                return {'status': True}
            else:
                return send_invalid_form()
        else:
            return send_not_logged()
Esempio n. 16
0
def send_message():
    room_id = request.form['room_id']
    message = request.form['message']

    if room_id and message:

        Database().send_message(room_id, session['id'], message)
        socketio.emit('nm', {'room_id': room_id})
        return jsonify({'status': True})

    else:
        return jsonify({'status': False})
Esempio n. 17
0
def cadastro():
    msg = ''

    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if username and password:

            account = Database().get_user(username)

            if account:
                msg = "Nome de usuario já existente"
            else:
                Database().add_user(username, password)
                msg = 'Você se cadastrou com sucesso'
                return render_template('Login.html', error_msg=msg)
        else:
            msg = 'Digite todos os campos'

    return render_template('Cadastro.html', error_msg=msg)
    def test_load_person_data_set_id_table_row(self):
        database = Database(':memory:')
        session = database.get_session()
        database_loader = DatabaseLoader(database)

        person = self.get_person_data()
        database_loader.load_person_data(person)
        result = session.query(ID).first()
        expected = self.data['id']

        assert result.name == expected['name']
        assert result.value == expected['value']
    def test_load_person_data_add_tables(self):
        database = Database(':memory:')
        session = database.get_session()
        database_loader = DatabaseLoader(database)

        person = self.get_person_data()
        database_loader.load_person_data(person)

        assert len(session.query(Location).all()) == 1
        assert len(session.query(TimeZone).all()) == 1
        assert len(session.query(Coordinates).all()) == 1
        assert len(session.query(Street).all()) == 1
    def test_load_person_data_set_day_of_birth_table_row(self):
        database = Database(':memory:')
        session = database.get_session()
        database_loader = DatabaseLoader(database)

        person = self.get_person_data()
        database_loader.load_person_data(person)
        result = session.query(DayOfBirth).first()
        expected = self.data['dob']

        assert result.date == datetime.datetime(year=1966, month=6, day=26, hour=11, minute=50, second=25,
                                                microsecond=558000)
        assert result.age == expected['age']
    def test_load_person_data_set_registered_table_row(self):
        database = Database(':memory:')
        session = database.get_session()
        database_loader = DatabaseLoader(database)

        person = self.get_person_data()
        database_loader.load_person_data(person)
        result = session.query(Registered).first()
        expected = self.data['registered']

        assert result.date == datetime.datetime(year=2016, month=8, day=11, hour=6, minute=51, second=52,
                                                microsecond=86000)
        assert result.age == expected['age']
    def test_load_person_data_set_name_table_row(self):
        database = Database(':memory:')
        session = database.get_session()
        database_loader = DatabaseLoader(database)

        person = self.get_person_data()
        database_loader.load_person_data(person)
        result = session.query(Name).first()
        expected = self.data['name']

        assert result.title == expected['title']
        assert result.first == expected['first']
        assert result.last == expected['last']
    def test_load_person_data_set_person_table_row(self):
        database = Database(':memory:')
        session = database.get_session()
        database_loader = DatabaseLoader(database)

        person = self.get_person_data()
        database_loader.load_person_data(person)
        result = session.query(Person).first()

        assert result.gender == self.data['gender']
        assert result.email == self.data['email']
        assert result.phone == "0262351898"
        assert result.cell == self.data['cell']
        assert result.nat == self.data['nat']
    def test_load_person_data_set_timezone_table_row(self):
        database = Database(':memory:')
        session = database.get_session()
        database_loader = DatabaseLoader(database)

        person = self.get_person_data()

        expected = self.data['location']['timezone']

        database_loader.load_person_data(person)
        result = session.query(TimeZone).first()

        assert result.offset == expected['offset']
        assert result.description == expected['description']
    def test_load_person_data_set_coordinates_table_row(self):
        database = Database(':memory:')
        session = database.get_session()
        database_loader = DatabaseLoader(database)

        person = self.get_person_data()

        expected = self.data['location']['coordinates']

        database_loader.load_person_data(person)
        result = session.query(Coordinates).first()

        assert result.latitude == expected['latitude']
        assert result.longitude == expected['longitude']
Esempio n. 26
0
    def post(self):
        room_id = request.form['room_id']
        message = request.form['message']

        if is_logged():
            user_id = session['id']
            if room_id and message:
                Database().add_message(user_id, room_id, message)
                socket.emit("newMessage", {'room_id': room_id})
                return {'status': True}
            else:
                return send_invalid_form()
        else:
            return send_not_logged()
Esempio n. 27
0
    def post(self):
        username = request.form['username']
        password = request.form['password']

        if username and password:
            password = hash_string(password)
            user = Database().get_user(username, password)
            if user:
                session['logged_in'] = True
                session['id'] = user['id']
                return {'status': True}
            else:
                return {'status': False, 'message': "user not find"}
        else:
            return send_invalid_form()
    def test_load_person_data_add_all_tables(self):
        database = Database(':memory:')
        session = database.get_session()
        database_loader = DatabaseLoader(database)

        person = self.get_person_data()
        database_loader.load_person_data(person)

        assert len(session.query(Location).all()) == 1
        assert len(session.query(Name).all()) == 1
        assert len(session.query(Login).all()) == 1
        assert len(session.query(DayOfBirth).all()) == 1
        assert len(session.query(Registered).all()) == 1
        assert len(session.query(ID).all()) == 1
        assert len(session.query(Person).all()) == 1
Esempio n. 29
0
 def __init__(self):
     db = Database()
     self.db = db.get('motor')
     if not len(self.db):
         print(f'Falha ao carregar a tabela: motor')
         exit(1)
     self.row = self.db[0]
     self.perguntas = Perguntas()
     self.resultado = [
         ['falha_rede', 'falha na rede elétrica'],
         ['falha_instalacao', 'falha na instalação elétrica'],
         ['falha_dimensionamento', 'falha de dimensionamento do motor'],
         ['defeito_motor', 'defeito no motor'],
         ['falha_mecanica', 'falha mecânica']
     ]
Esempio n. 30
0
    def test_get_gender_percentage_female(self):
        database = Database(':memory:')
        session = database.get_session()

        person_1 = Person(gender='female')
        person_2 = Person(gender='female')
        person_3 = Person(gender='female')
        session.bulk_save_objects([person_1, person_2, person_3])
        session.commit()

        data_fetcher = DataFetcher(database)

        values, columns = data_fetcher.get_gender_percentage()
        expected = [('female', 100)]

        assert set(values) == set(expected)