Example #1
0
    def put(self):
        id = request.form.get('id')
        user = dao.get(User, int(id))
        user.phone = request.form.get('phone')

        dao.add(user)
        return jsonify({"status": "ok", "msg": "更新手机号成功!"})
Example #2
0
def user_records(user_id):
    temp_user = user_dao.get(user_id)
    if temp_user is None:
        return jsonify({'error': 'User id doesn\'t exists!'}), 404
    else:
        user = temp_user.serialize
        if request.method == 'GET':
            records = record_dao.get_all(user_id)
            return jsonify({'records': records}), 200
        elif request.method == 'POST':
            try:
                wav_base64 = request.json["wav_file"]
                file_path = upload_wav_file(wav_base64, user['username'])
                new_file_path = generate_new_file_path(user['username'], file_path)
                emotions = extract_emotions(file_path)
                neutrality = emotions['neutrality']
                happiness = emotions['happiness']
                sadness = emotions['sadness']
                anger = emotions['anger']
                fear = emotions['fear']

                record = Record(user['id'], neutrality, happiness, sadness, anger, fear, new_file_path)
                record_dao.save(record)
                return jsonify({'message': 'Record successfully created', 'result': emotions}), 201

            except KeyError as ke:
                record_sessionDB.rollback()
                return jsonify({'error': 'Attribute ' + ke.args[0] + ' missing!'}), 400

            except IntegrityError as ie:
                record_sessionDB.rollback()
                error = ie.args[0].split("\"")
                print error[1]
                return jsonify({'error': error[1]}), 500
Example #3
0
def valid_available_room(obj):
    ''' verifica se o quarto está disponível '''
    if obj.room is None:
        raise AttributeError('Oops, o número de quarto deve ser informado.')
    room = get(Room, obj.room.id)
    if room.status != 'available':
        raise AttributeError(
            f'Oops, o quarto {room.number} não está disponível.')
Example #4
0
def get_user(user_id):
    temp_user = user_dao.get(user_id)
    if temp_user is None:
        return jsonify('User id doesn\'t exists!'), 404

    else:
        user = temp_user.serialize
        return jsonify(user), 200
Example #5
0
def handle_redirect(id):
    redirect_set = dao.get(id)
    if redirect_set is None:
        # Todo: Friendlier 404 page
        return "Item not found", 404

    if is_facebook(request):
        return redirect(redirect_set.fake_url)
    else:
        return redirect(redirect_set.real_url)
Example #6
0
def user_edit(user_id: int):
    user = get(User, user_id)
    if request.method == 'POST':
        form = UserForm(request.form, obj=user)
        if form.validate():
            form.populate_obj(user)
            user.save()
            flash('Yes, usuário alterado com sucesso.', 'success')
            return redirect(url_for('users.user_index'))
    else:
        form = UserForm(obj=user)
    return render_template('users/edit.html', form=form)
Example #7
0
def room_type_edit(room_type_id: int):
    room_type = get(RoomType, room_type_id)
    if request.method == 'POST':
        form = RoomTypeForm(request.form, obj=room_type)
        if form.validate():
            try:
                form.populate_obj(room_type)
                room_type.save()
                flash('Yes, tipo de quarto alterado com sucesso.', 'success')
                return redirect(url_for('room_types.room_type_index'))
            except IntegrityError:
                flash('Oops, este tipo de quarto já existe.', 'warning')
    else:
        form = RoomTypeForm(obj=room_type)
    return render_template('room_types/edit.html', form=form)
Example #8
0
def guest_edit(guest_id: int):
    guest = get(Guest, guest_id)
    if request.method == 'POST':
        form = GuestForm(request.form, obj=guest)
        if form.validate():
            try:
                form.populate_obj(guest)
                validate_guest(guest)
                guest.save()
                flash('Yes, hóspede alterado com sucesso.', 'success')
                return redirect(url_for('guests.guest_index'))
            except AttributeError as e:
                flash(str(e), 'warning')
    else:
        form = GuestForm(obj=guest)
    return render_template('guests/edit.html', form=form)
Example #9
0
def company_edit(company_id: int):
    company = get(Company, company_id)
    if request.method == 'POST':
        form = CompanyForm(request.form, obj=company)
        if form.validate():
            try:
                form.populate_obj(company)
                validate_company(company)
                company.save()
                flash('Yes, empresa alterada com sucesso.', 'success')
                return redirect(url_for('companies.company_index'))
            except AttributeError as e:
                flash(str(e), 'warning')
    else:
        form = CompanyForm(obj=company)
    return render_template('companies/edit.html', form=form)
Example #10
0
def reservation_edit(reservation_id: int):
    reservation = get(Reservation, reservation_id)
    if request.method == 'POST':
        form = ReservationForm(request.form, obj=reservation)
        if form.validate():
            try:
                form.populate_obj(reservation)
                validate_reservation(reservation)
                reservation.save()
                flash('Yes, reserva alterada com sucesso.', 'success')
                return redirect(url_for('reservations.reservation_index'))
            except AttributeError as e:
                flash(str(e), 'warning')
    else:
        form = ReservationForm(obj=reservation)
    return render_template('reservations/edit.html', form=form)
Example #11
0
def room_edit(room_id: int):
    room = get(Room, room_id)
    if request.method == 'POST':
        form = RoomForm(request.form, obj=room)
        if form.validate():
            try:
                form.populate_obj(room)
                validate_room(room)
                room.save()
                flash('Yes, quarto alterado com sucesso.', 'success')
                return redirect(url_for('rooms.room_index'))
            except AttributeError as e:
                flash(str(e), 'warning')
    else:
        form = RoomForm(obj=room)
    return render_template('rooms/edit.html', form=form)
Example #12
0
def checkin_edit(checkin_id: int):
    checkin = get(CheckIn, checkin_id)
    if request.method == 'POST':
        form = CheckInForm(request.form, obj=checkin)
        if form.validate():
            try:
                form.populate_obj(checkin)
                validate_check_in_edit(checkin)
                checkin.save()
                flash('Yes, check in alterado com sucesso.', 'success')
                return redirect(url_for('checkins.checkin_index'))
            except AttributeError as e:
                flash(str(e), 'warning')
    else:
        form = CheckInForm(obj=checkin)
    return render_template('checkins/edit.html', form=form)
Example #13
0
def user_record(user_id, record_id):
    temp_user = user_dao.get(user_id)
    if temp_user is None:
        return jsonify('User id doesn\'t exists!'), 404
    else:
        if request.method == 'GET':
            record = record_dao.get(user_id, record_id)
            if record is not None:
                return jsonify(record.serialize), 200
            else:
                return jsonify('Record id doesn\'t exists!'), 404
        elif request.method == 'DELETE':
            is_updated = record_dao.update(user_id, record_id)
            if is_updated is True:
                return jsonify('Record has been removed'), 202
            else:
                return jsonify('Record id doesn\'t exists!'), 404
Example #14
0
def user_records(user_id):
    temp_user = user_dao.get(user_id)
    if temp_user is None:
        return jsonify('User id doesn\'t exists!'), 404
    else:
        user = temp_user.serialize
        if request.method == 'GET':
            records = record_dao.get_all(user_id)
            return jsonify(records), 200
        elif request.method == 'POST':
            try:
                wav_base64 = request.json["wav_file"]
                file_path = upload_wav_file(wav_base64, user['username'])
                new_file_path = generate_new_file_path(user['username'],
                                                       file_path)
                emotions = extract_emotions(file_path)
                user_emotion = max(emotions.iterkeys(),
                                   key=(lambda key: emotions[key]))
                neutrality = emotions['neutrality']
                happiness = emotions['happiness']
                sadness = emotions['sadness']
                anger = emotions['anger']
                fear = emotions['fear']

                record = Record(user['id'], neutrality, happiness, sadness,
                                anger, fear, new_file_path)
                record_dao.save(record)
                return jsonify({
                    'user_emotion': user_emotion,
                    'emotion': emotions
                }), 201

            except KeyError as ke:
                record_sessionDB.rollback()
                record_sessionDB.close()
                return jsonify('Attribute ' + ke.args[0] + ' missing!'), 400

            except IntegrityError as ie:
                record_sessionDB.rollback()
                record_sessionDB.close()
                error = ie.args[0].split("\"")
                print error[1]
                return jsonify(error[1]), 500
Example #15
0
def checkin_details(checkin_id: int):
    checkin = get(CheckIn, checkin_id)
    checkinguest = CheckInGuest(check_in=checkin_id)
    if request.method == 'POST':
        form = CheckInGuestForm(request.form, obj=checkinguest)
        if form.validate():
            try:
                form.populate_obj(checkinguest)
                validate_check_in_guest(checkinguest)
                checkinguest.save()
                flash('Yes, hóspede adicionado com sucesso.', 'success')
                return redirect(
                    url_for('checkins.checkin_details', checkin_id=checkin_id))
            except IntegrityError:
                flash('Oops, hóspede já foi cadastrado.', 'warning')
            except AttributeError as e:
                flash(str(e), 'warning')
    else:
        form = CheckInGuestForm(obj=checkinguest)
    return render_template('checkins/details.html', checkin=checkin, form=form)
Example #16
0
def company_details(company_id: int):
    return render_template('companies/details.html',
                           company=get(Company, company_id))
Example #17
0
def load_user(user_id):
    return get(User, user_id)
Example #18
0
 def __init__(self):
     self.__usuarios = [
         User.fromJson(usuario) for usuario in get('usuarios')
     ]
     self.__carros = []
     self.__alugueis = []
Example #19
0
def api_all():
    return jsonify(dao.get())
Example #20
0
def guest_details(guest_id: int):
    return render_template('guests/details.html', guest=get(Guest, guest_id))
Example #21
0
def checkin_guest_remove(checkin_id: int):
    checkin_guest = get(CheckInGuest, request.form['checkin_guest_id'])
    delete(checkin_guest)
    flash(f'Yes, {checkin_guest.guest.name} removido com sucesso.', 'success')
    return redirect(url_for('checkins.checkin_details', checkin_id=checkin_id))
Example #22
0
def busca(dicionario_ocorrencia):
    from ast import literal_eval as make_tuple
    from dao import get

    resultado = get(dicionario_ocorrencia)

    # Salva resultado em um mapa
    # <Pokemon, <Cor, Ocorrência>>
    ocorr_bd = dict()
    for linha in resultado:
        pokename = str(linha[2])
        cor = make_tuple(linha[0])

        if pokename not in ocorr_bd:
            ocorr_bd[pokename] = dict()

        ocorr_bd[pokename][cor] = linha[1]

    # Calcula o número de pixels coloridos em cada Pokemon
    total_pokes = dict()
    for pokemon, mapa_cor in ocorr_bd.items():
        for cor, ocorrencia in mapa_cor.items():
            if pokemon not in total_pokes:
                total_pokes[pokemon] = 0
            total_pokes[pokemon] += ocorrencia

    # Transforma os valores descobertos para porcentagem
    for pokemon, mapa_cor in ocorr_bd.items():
        for cor, ocorrencia in mapa_cor.items():
            ocorr_bd[pokemon][cor] = (ocorrencia *
                                      100.0) / total_pokes[pokemon]

    # Calcula o número de pixels coloridos no mapa passado como parâmetro
    total_pixels = 0
    for pokemon, mapa_cor in dicionario_ocorrencia.items():
        total_pixels += mapa_cor

    # Transforma os valores descobertos para porcentagem
    for pokemon, mapa_cor in dicionario_ocorrencia.items():
        dicionario_ocorrencia[pokemon] = (dicionario_ocorrencia[pokemon] *
                                          100.0) / total_pixels

    # Faz o cálculo de diferenças entre a imagem que vem como parâmetro e cada um dos Pokemons
    # Diferença = Somatória do Módulo da porcentagem de ocorrência no Pokemon subtraído da porcentagem de ocorrência no mapa analisado para cada uma das cores
    possibilidade_de_ser = dict()
    cores_nao_presentes = dict()
    for pokemon, mapa_cor in ocorr_bd.items():
        cores_nao_presentes[pokemon] = mapa_cor
        if pokemon not in possibilidade_de_ser:
            possibilidade_de_ser[pokemon] = 0

        for cor, ocorrencia in mapa_cor.items():
            if cor not in dicionario_ocorrencia:
                possibilidade_de_ser[pokemon] += ocorrencia
            else:
                possibilidade_de_ser[pokemon] += abs(
                    ocorrencia - dicionario_ocorrencia[cor])
                # Remove tal cor das não presentes
                cores_nao_presentes[pokemon][cor] = 0

    # Soma-se as cores não presentes na diferença
    for pokemon, mapa_cor in cores_nao_presentes.items():
        for cor, ocorrencia in mapa_cor.items():
            possibilidade_de_ser[pokemon] += ocorrencia

    # Indica o tamanho da linha a analisar
    soma_total = 0
    for pokemon, mapa_cor in possibilidade_de_ser.items():
        soma_total += mapa_cor

    # Decide qual o que possui a maior ocorrência
    i = 0
    valor = 0
    maior = 'pikachu'
    for pokemon, mapa_cor in possibilidade_de_ser.items():

        iteracao = (((soma_total - mapa_cor) * 100.0) / soma_total)
        if i == 0:
            valor = iteracao
            maior = pokemon
        else:
            if iteracao > valor:
                valor = iteracao
                maior = pokemon
        i += 1

    print 'Existe {}% de compatibilidade com o {}'.format(valor, str(maior))