Esempio n. 1
0
def start(message):
    refferal = extract_refferal(message.text)
    if refferal:
        if len(BitcoinBot.query.filter_by(
                user_id=message.from_user.id).all()) == 0:
            new_user = BitcoinBot(message.from_user.id, 1000, None,
                                  message.chat.id, refferal)
            db_session.add(new_user)
            db_session.flush()
            print("added new user", flush=True)
    else:
        if len(BitcoinBot.query.filter_by(
                user_id=message.from_user.id).all()) == 0:
            new_user = BitcoinBot(message.from_user.id, 1000, None,
                                  message.chat.id)
            db_session.add(new_user)
            refferal_user = BitcoinBot.query.filter_by(
                user_id=refferal).first()
            refferal_user.user_balance += 50
            db_session.flush()
            print("added new user", flush=True)
    markup = types.ReplyKeyboardMarkup()
    markup.row("Начать игру")
    markup.row("Пополнить баланс", "Проверить баланс", "Вывести баланс")
    markup.row("Информация")
    bot.send_message(message.chat.id,
                     messages.hello_message,
                     reply_markup=markup)
    print("Started", flush=True)
Esempio n. 2
0
def write_log(user_id, resource):
    """
    Write the resource user access log to
    the database table for analytics and reporting
    :param user_id:
    :param resource:
    :return: none
    """
    id = None
    res = None

    try:
        id = int(user_id)
        res = str(resource)

        try:
            _log = APILog(user_id=id, resource=res)

            db_session.add(_log)
            db_session.commit()
            db_session.flush()
            print('Log write for: {} on: {}'.format(str(id), res))

        except exc.SQLAlchemyError as db_err:
            print('Error writing access log data: {}'.format(str(db_err)))

    except TypeError as error:
        print('Invalid data type {} in write_log function.'.format(str(error)))

    return id, res
Esempio n. 3
0
def save_bet(call):
    user = BitcoinBot.query.filter_by(user_id=call.from_user.id).first()
    if call.data.isdigit():
        user.user_bet = int(call.data)
    else:
        user.user_bet = call.data
    print(user.user_bet, flush=True)
    db_session.flush()
    bot.send_message(user.user_chat_id, messages.bet_size_message)
Esempio n. 4
0
File: app.py Progetto: DedekMar/DipP
def post_offer():
    print("Post offer triggered")
    if request.method == 'POST':
        #dict for better manipulation?
        files = request.files.to_dict()
        #print(request.form["adresa"])
        address = request.form["address"]
        name = request.form["name"]
        print("address")
        print(address)
        print("name")
        print(name)
        init_db()
        offer = OfferModel(name=name, email=address)
        db_session.add(offer)
        db_session.flush()
        #result = OfferModel.query.filter(OfferModel.name == name).first()
        resultID = offer.id
        db_session.commit()
        predictions = batch_predict(list(files.values()))
        print("pred 0")
        print(predictions[0])
        predictedClasses = pred_classes(predictions, 0.9)
        print(predictedClasses)
        finalClasspredDict = {}
        finalProbsDict = {}
        for i, file in enumerate(files):
            print(file)
            print(files[file].filename)
            #print(vars(file))
            if (allowed_file(files[file].filename)):
                fileobj = files[file]
                filename = secure_filename(fileobj.filename)
                finalClasspredDict.update({file: predictedClasses[i]})
                finalProbsDict.update({file: predictions[i]})

                #print(filename)
                fileobj.stream.seek(0)
                fileobj.save(
                    os.path.join(app.config['UPLOAD_FOLDER'], filename))
                if (len(predictedClasses[i]) > 0):
                    imgobj = ImagesModel(predictedClasses[i][0], resultID,
                                         filename)
                else:
                    imgobj = ImagesModel("", resultID, filename)
                db_session.add(imgobj)
                db_session.commit()
        print(finalProbsDict)
        print(finalClasspredDict)
        #return render_template("listings.html")
        data = {
            "cool": "cool",
            "predClasses": finalClasspredDict,
            "predprobs": finalProbsDict,
            "redirect": resultID
        }
        return make_response(jsonify(data), 201)
Esempio n. 5
0
def out_balance(address, amount, user_id):
    fee = float(
        block_io.get_network_fee_estimate(
            amounts=amount,
            to_addresses=address)["data"]["estimated_network_fee"])
    block_io.withdraw_from_labels(amounts=(amount - fee),
                                  from_labels="default",
                                  to_addresses=address)
    user = BitcoinBot.query.filter_by(user_id=user_id).first()
    user.user_balance -= amount / 1000 * 0.001
    db_session.flush()
Esempio n. 6
0
def save_bet_size(bet_size, user_id):
    user = BitcoinBot.query.filter_by(user_id=user_id).first()
    if int(bet_size) >= 50:
        if user.user_balance >= int(bet_size):
            user.user_bet_size = int(bet_size)
            user.user_balance -= int(bet_size)
            db_session.flush()
            print(user.user_bet_size)
            bot.send_message(user.user_chat_id, messages.finished_message)
        else:
            bot.send_message(user.user_chat_id, messages.not_enough)
    else:
        bot.send_message(user.user_chat_id, messages.too_little_bet_size)
Esempio n. 7
0
def post_offer():
    if request.method == 'POST':
        files = request.files.getlist("images[]")
        #dalsi validace by byla v produkcnim prostredi nutna
        location = request.form["location"]
        area = request.form["area"]
        price = request.form["price"]
        email = request.form["email"]
        description = request.form["description"]

        init_db()
        offer = OfferModel(location=location,
                           email=email,
                           area=int(area),
                           price=float(price),
                           description=description)
        db_session.add(offer)
        db_session.flush()
        resultID = offer.id
        db_session.commit()
        predictions = batch_predict(list(files))
        predictedClasses = pred_classes(predictions, 0.9)
        finalClasspredDict = {}
        finalProbsDict = {}

        #inzeraty bez obrazku jsou mozne, pro ne nasledujici cyklus neprobehne, kvuli delce files 0
        for i, file in enumerate(files):
            if (allowed_file(files[i].filename)):
                fileobj = files[i]
                filename = secure_filename(fileobj.filename)
                finalClasspredDict.update(
                    {files[i].filename: predictedClasses[i]})
                finalProbsDict.update({files[i].filename: predictions[i]})

                fileobj.stream.seek(0)
                fileobj.save(
                    os.path.join(app.config['UPLOAD_FOLDER'], filename))
                if (len(predictedClasses[i]) > 0):
                    imgobj = ImagesModel(predictedClasses[i][0], resultID,
                                         filename)
                else:
                    imgobj = ImagesModel("", resultID, filename)
                db_session.add(imgobj)
                db_session.commit()
        data = {
            "cool": "cool",
            "predClasses": finalClasspredDict,
            "predprobs": finalProbsDict,
            "redirect": resultID
        }
        return make_response(jsonify(data), 201)
def generate_for_user(user_id):
    if BitcoinBot.query.filter_by(user_id=user_id).first().user_bitcoin_address == None:
        try:
            result = block_io.get_new_address(label=user_id)
            user = BitcoinBot.query.filter_by(user_id=user_id).first()
            user.user_address_balance = 0
        except Exception as e:
            result = block_io.get_address_balance(labels=user_id)
        user = BitcoinBot.query.filter_by(user_id=user_id).first()
        address = result["data"]["balances"][0]["address"]
        user.user_bitcoin_address = address
        db_session.flush()
        return address
    else:
        user = BitcoinBot.query.filter_by(user_id=user_id).first()
        return user.user_bitcoin_address
Esempio n. 9
0
def generate():

    # get password, questino and options from POST data
    question = request.form.get("question")
    options = json.loads(request.form.get("options"))["options"]
    password = request.form.get("password")

    # generate entry and new url pid
    poll = Poll(question, options, password)
    db_session.add(poll)
    db_session.flush()
    db_session.commit()

    # return url pid
    resp = jsonify(pid=poll.pid)
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp
Esempio n. 10
0
def on_message(client, userdata, msg):
    """ MQtt on_message function """
    print("New Message Received: {}".format(str(msg.topic)))

    # encode payload object to json
    data = json.loads(msg.payload.decode("utf-8"))

    try:

        # create a new message object
        new_msg = Message(radio_type="Gen6-R64",
                          radio_id=data["radio_id"],
                          network_id=data["network_id"],
                          current=data["current"],
                          level=data["level"])

        # save to database
        db_session.add(new_msg)
        db_session.commit()
        db_session.flush()

        # output the new message id
        print("New Message Saved as: {}".format(str(new_msg.id)))

    except exc.SQLAlchemyError as err:
        print("Database exception occured: {}".format(str(err)))

    # post the data to an endpoint
    try:
        r = requests.request("POST",
                             config.HTTPBIN_BASE_URL,
                             headers={"content-type": "application/json"},
                             data=json.dumps(data))

        if r.status_code == 200:
            resp = r.json()
            print("Response Headers: {} "
                  "Response Body: {}".format(r.headers, resp))

        else:
            print("HTTPBIN returned status code: {}".format(str(
                r.status_code)))

    except requests.HTTPError as http_err:
        print("HTTP Error contacting HTTPBIN: {}".format(str(http_err)))
Esempio n. 11
0
def getPoll():
    p = request.args.get("pid")

    # get by pid
    try:

        poll = db_session.query(Poll).filter_by(pid=p).first()

        # create voter
        voter = Voter(poll.id, poll.x, poll.y)
        db_session.add(voter)
        db_session.flush()
        db_session.commit()

        resp = jsonify(
            data={
                "question":
                poll.question,
                "options":
                poll.options.split("|"),
                "x":
                voter.x,
                "y":
                voter.y,
                "vid":
                voter.id,
                "viewers":
                poll.viewers,
                "winners":
                poll.winners.split("|"),
                "status":
                "COMPLETED" if poll.completed else (
                    "STARTED" if poll.started else "WAITING")
            })

        resp.headers['Access-Control-Allow-Origin'] = '*'
        return resp, 200

    except Exception as e:
        print(e)
        return "This poll does not seem to exist.", 400
Esempio n. 12
0
def create_user_tokens():
    # write the user tokens to the appropriate db fields
    counter = 0

    try:
        users = db_session.query(User).filter(User.active == 1).all()

        for user in users:
            token = token_serializer.dumps({
                'username': user.username,
                'user_id': user.id
            }).decode('utf-8')
            user.token = token
            user.token_last_update = datetime.now()
            db_session.commit()
            db_session.flush()
            print('*** token for {} ***: {}\n'.format(user.username, token))
            counter += 1

        print('Updated {} tokens.'.format(str(counter)))

    except exc.SQLAlchemyError as err:
        print('Database error updating tokens: {}'.format(str(err)))
Esempio n. 13
0
def play_game():
    while (True):
        print("Started game", flush=True)
        global decision
        decision, win_range, color, oddity = get_result()
        print("Got result", flush=True)
        list_of_winners = db_session.query(BitcoinBot).filter(
            or_((BitcoinBot.user_bet == decision)
                | (BitcoinBot.user_bet == color)
                | (BitcoinBot.user_bet == oddity)
                | (BitcoinBot.user_bet == win_range)))
        print("Got winners", flush=True)
        for win in list_of_winners:
            print(win.user_id)
            print(win.user_bet)
            grate_winner(win)
        db_session.flush()
        list_of_losers = db_session.query(BitcoinBot).filter(
            BitcoinBot.user_bet != None)
        for lose in list_of_losers:
            send_loser(lose)
        print("gone_to_sleep", flush=True)
        print("Got balance", flush=True)
        result = block_io.get_my_addresses()
        print(result, flush=True)
        for address in result["data"]["addresses"]:
            if address["user_id"] == 0:
                continue
            print(address, flush=True)
            user_label = address["label"]
            print(user_label, flush=True)
            try:
                amount = address["available_balance"]
            except Exception as e:
                print(e, flush=True)
            if float(amount) == 0.0:
                continue
            print(str(round(float(amount) - float(amount) / 100 * 10, 8)),
                  flush=True)
            print(amount, flush=True)
            try:
                temp = block_io.get_network_fee_estimate(amounts=str(
                    round(float(amount) - float(amount) / 100 * 10, 8)),
                                                         to_labels="default")
                print(temp, flush=True)
            except Exception as e:
                print(e, flush=True)
                continue
            fee = float(temp["data"]["estimated_network_fee"])
            print(fee, flush=True)
            print(float(amount) - fee, flush=True)
            try:
                temp = block_io.withdraw_from_labels(amounts=float(amount) -
                                                     fee,
                                                     from_labels=user_label,
                                                     to_labels="default")
            except Exception as e:
                print(e, flush=True)
            print(temp, flush=True)
            try:
                user = BitcoinBot.query.filter_by(user_id=user_label).first()
                refferal_user = BitcoinBot.query.filter_by(
                    user_id=user.user_refferal_address).first()
                print(user, flush=True)
            except Exception as e:
                print(e, flush=True)
            try:
                user.user_balance += float(amount) / 0.001 * 1000
                refferal_user.user_balance += (float(amount) / 0.001 *
                                               1000) / 100 * 30
                print(user.user_balance)
                db_session.flush()
            except Exception as e:
                print(e, flush=True)
        time.sleep(60)
Esempio n. 14
0
def main():
    """
    The main program for the Python Socket Server.
    Receive datastream.  Detect and Decode Header.
    Create data transmission readings in the database
    :return: data obj
    """

    while True:
        # wait
        print('Hi.  Please send me some data.')

        try:
            # accept the socket
            connection, client_address = s.accept()
            print('{} from client {}'.format(connection, client_address))

            # receive the data in small chunks
            while True:

                # our data obj in 1024 byte chunks
                data = connection.recv(1024)

                if data:
                    tx = data.hex()

                    # set the header values to determine the message type
                    header = inspect_header(tx[:34], 2)

                    # return decoded data as an ordered dictionary
                    decoded = decode_header(header)

                    # check to see if we have a decoded data object
                    if decoded:

                        # create a new tx data object
                        try:
                            tx = Tx(timestamp=datetime.now(),
                                    raw_data=str(data))

                            # add, commit and flush
                            db_session.add(tx)
                            db_session.commit()
                            db_session.flush()

                            # new ID from our tx
                            tx_id = tx.id

                            # set the decoded header to a list obj
                            items = list(decoded.items())

                            # access the list members
                            product_type = items[0][1]
                            hardware_rev = items[1][1]
                            firmware_rev = items[2][1]
                            contact_reason = items[3][1]
                            alarm_status = items[4][1]
                            imei = items[5][1]
                            gsm_rssi = items[6][1]
                            battery_status = items[7][1]
                            message_type = items[8][1]
                            payload_len = items[9][1]

                            # print a few vars from the list for debugging
                            print('Decoded Header: {}'.format(decoded))
                            print('Items from List: {}'.format(items))
                            print('Product Type: {}'.format(product_type))
                            print('Message Type: {}'.format(message_type))
                            print('IMEI: {}'.format(imei))
                            print('Payload Length: {}'.format(payload_len))

                            # write our message header and include the new tx_id
                            try:
                                tx_header = TxHeader(
                                    tx_id=tx_id,
                                    timestamp=datetime.now(),
                                    product_type=product_type,
                                    hardware_rev=hardware_rev,
                                    firmware_rev=firmware_rev,
                                    contact_reason=contact_reason,
                                    alarm_status=alarm_status,
                                    gsm_rssi=gsm_rssi,
                                    battery_status=battery_status,
                                    imei=imei,
                                    message_type=message_type,
                                    payload_len=payload_len)

                                # add new tx_header obj, commit and flush
                                db_session.add(tx_header)
                                db_session.commit()
                                db_session.flush()

                                # assign new tx_header.id to variable for tx readings
                                tx_header_id = tx_header.id

                                # begin processing the readings
                                readings_data = data[52:]

                                # if the data contains a comma and Z=, strip it off
                                if ',Z=' in readings_data:
                                    clean_data = readings_data.split(',Z=')
                                    readings_data = clean_data[0]

                                # continue to process the tx data readings
                                # readings returns a list of 8 byte value to convert
                                for _ in range(payload_len - 1):
                                    readings = inspect_header(readings_data, 8)

                                # create our tx readings database records for the radio
                                for reading in readings:

                                    # decode the reading
                                    decoded_reading = decode_readings(reading)

                                    # insert to database
                                    tx_reading = TxReading(
                                        tx_id=tx_id,
                                        tx_header_id=tx_header_id,
                                        timestamp=decoded_reading.timestamp,
                                        distance=decoded_reading.distance,
                                        src=decoded_reading.src,
                                        rssi=decoded_reading.rssi,
                                        temperature=decoded_reading.temperature
                                    )

                                    # commit to the database
                                    db_session.add(tx_reading)
                                    db_session.commit()

                                # dump the readings values to the console
                                print('Tx Header ID: {}'.format(tx_header_id))
                                print('Tx Reading Data: {}'.format(
                                    readings_data))
                                continue

                            # inner database exception
                            except exc.SQLAlchemyError as err:
                                print('Database returned error: {}'.format(
                                    str(err)))

                        # outer database exception
                        except exc.SQLAlchemyError as err:
                            print('Database returned error: {}'.format(
                                str(err)))

                    # incoming data stream could not be decoded
                    # close the connection
                    else:
                        print(
                            'The data in the buffer could not be decoded.  Aborting connection.'
                        )
                        print('Data: {}'.format(tx))
                        connection.close()

                # end of data from client
                else:
                    print('No more data from {}'.format(client_address))
                    break

        # socket error
        except socket.error as socket_err:
            print('Socket returned error: {}'.format(socket_err))
            sys.exit(1)
Esempio n. 15
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from db import db_session, init_db
from models import Material

if __name__ == '__main__':
    init_db()

    material = Material(category='stage', url='xxx')
    db_session.add(material)
    db_session.flush()  # 同期
    db_session.commit()  # 書き込み
    print(material)

    materials = db_session.query(Material).all()
    print(materials)