def main():
    connect_to_db("/".join(dir_name.split('/')[:-1]) + '/nips-papers.db')
    document = get_documents()
    document_words = document.replace('\n', " ").split(" ")
    low_document_words = [d.lower() for d in document_words]
    query_words_positions = get_query_words_positions(low_document_words)
    snippets = create_snippets(document_words, query_words_positions)
    print(snippets)
Ejemplo n.º 2
0
    def setUp(self):
        """Prepare for each test before execution."""

        connect_to_db(app, 'postgresql:///testdb')

        db.create_all()
        load_users()
        load_activities()
        load_sessions()
        load_records()
Ejemplo n.º 3
0
    def setUp(self):
        """Stuff to do before every test."""

        self.client = app.test_client()
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, 'sqlite:///test.db')

        # Create tables in testdb
        db.create_all()
Ejemplo n.º 4
0
    def setUp(self):
        """Stuff to do before every test."""

        self.client = app.test_client()
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, "postgresql:///todo_test")

        # Create tables in testdb
        db.create_all()
        load_example_data()
Ejemplo n.º 5
0
    def setUp(self):
        """Prepare for each test before execution."""

        self.app = app.test_client()
        app.config['TESTING'] = True
        app.config['SECRET_KEY'] = 'key'

        connect_to_db(app, 'postgresql:///testdb')

        db.create_all()
        load_users()
        load_activities()
        load_sessions()
        load_records()
Ejemplo n.º 6
0
def graphs():
    file_name = request.form["csv_file"]
    jess_adjustment = request.form["jess_adjustment"]
    pete_adjustment = request.form["pete_adjustment"]
    return render_template('underconstruction.html', do_not_display=123, csv_file= file_name, 
    jess_adjustment= jess_adjustment, pete_adjustment= pete_adjustment) #page under construction
    file_name = request.form["csv_file"]
    jess_adjustment = request.form["jess_adjustment"]
    pete_adjustment = request.form["pete_adjustment"]
    con = connect_to_db()
    cur = con.cursor()
    cur.execute("SELECT DISTINCT Category FROM {0};".format("May2019"))
    categories = cur.fetchall()
    categories2 = []
    for category in categories:
        categories2.append(category[0])
    totals = []
    category3 = []
    for category in categories2:
        cur.execute("SELECT SUM(Debit) FROM {0} WHERE Category = '{1}';".format("May2019", category))
        totals.append(cur.fetchall()[0][0])
        category3.append(category)

    figure = plt.figure(figsize=(12, 10))
    plt.plot(category3,totals)
    figure.savefig('static/images/myfig.png')
    return render_template('graphs.html', do_not_display=123, csv_file= file_name, 
    jess_adjustment= jess_adjustment, pete_adjustment= pete_adjustment)
Ejemplo n.º 7
0
def main():
    connect_to_db()
    if SLACK_CLIENT.rtm_connect(with_team_state=False):
        logger.info("Stand-up bot connected and running!")
        while True:
            command, message, team, event = parse_bot_commands(SLACK_CLIENT.rtm_read())

            if event:
                response = handle_command(command, message, team, event)
                # Sends the response back to the channel
                SLACK_CLIENT.api_call(
                    "chat.postMessage",
                    channel=event['channel'],
                    text=response or DEFAULT_RESPONSE)
            time.sleep(RTM_READ_DELAY)
    else:
        print("Connection failed. Exception traceback printed above.")
    close_db_connection()
def chek_receipt_transaction():
    global all_trans_compleate
    try:
        session = connect_to_db(SQLALCHEMY_DATABASE_URI)
        pendingtrans = session.query(Withdrawals).filter(Withdrawals.pending == 1).all()
        logger.info(f'Found {len(pendingtrans)} transactions')

        for pend_tr in pendingtrans:
            try:
                r = w3.eth.getTransactionReceipt(pend_tr.txhash)
                if not r:
                    # pending ...
                    continue
                else:
                    status = r['status']
                    if status == 1:
                        # транзакция прошла
                        pend_tr.pending = 0
                        pend_tr.status = 1
                        pend_tr.txhash = ''
                        session.commit()
                        send_message(f'withdrawal_bot said: Произведён вывод {pend_tr.amount} wtp по адресу {pend_tr.wallet}')
                    else:
                        # транзакция неуспешна
                        pend_tr.pending = 0
                        pend_tr.status = 0
                        pend_tr.txhash = 'fail'
                        session.commit()

            except Exception as e:
                # транзакция ненайдена
                print(e)

        # проверяме если в базе есть тразакции которые ожидают завершения
        pendingtrans = session.query(Withdrawals).filter(Withdrawals.pending == 1).all()
        if len(pendingtrans) > 0:
            logger.info(f'Found {len(pendingtrans)} pendingt transaction')
            return False
        else:
            # проверяем есть ли транзакции которые не прошли - txhash = fail
            failtrans = session.query(Withdrawals).filter(Withdrawals.txhash == 'fail').all()
            if len(failtrans) > 0:
                logger.info(f'{len(failtrans)} transaction fail, repeat them')
            else:
                logger.info(f'All transaction complete')
                all_trans_compleate = True
            return True

    except Exception as e:
        logger.exception('chek_receipt_transaction')
    finally:
        session.close()
def run_etherscan():
    try:

        session = connect_to_db(SQLALCHEMY_DATABASE_URI)
        if session:
            all = session.query(User_wallets).all()
            message = f'~ start repeat, found {len(all)} user wallets'
            logger.info(message)

            for i, r in enumerate(all):
                api_url = f'https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=' \
                          f'0x1680CfdAD75dA2bb56Ded4f36BB9423C86ffa7B7&address={r.wallet}&page=1&offset=100&sort=asc&apikey={ETHERSCAN_TOKEN}'

                try:
                    req = requests.get(api_url)
                except Exception as e:
                    logger.exception(e)

                if req.status_code == 200:
                    # Check for empty response
                    if req.text:
                        data = req.json()
                        status = data.get('status')
                        if status == '1':
                            logger.info(
                                f'~{i + 1}: Found tranzaction for {r.wallet}')
                            update_data(data.get('result'), r.wallet,
                                        r.user_id, session)
                        else:
                            logger.info(
                                f'~{i + 1}: Not found tranzaction for {r.wallet}'
                            )
                else:
                    logger.info(f'status_code: {req.status_code}')

                time.sleep(TIME_OUT)

            message = f'compleat'
            logger.info(message)
        else:
            logger.error('session not open')
    except:
        logger.exception('run_etherscan')
Ejemplo n.º 10
0
def past_data():
    file_name = request.form["csv_file"]
    jess_adjustment = request.form["jess_adjustment"]
    pete_adjustment = request.form["pete_adjustment"]
    con = connect_to_db()
    raw_data = list_of_tables()
    table_list =[]
    for name in raw_data:
        if name[0] != "user":
            table_list.append(name[0])
    if request.method == "POST" and request.form['table_list'] != '':
        jess_adjustment = request.form["jess_adjustment"]
        pete_adjustment = request.form["pete_adjustment"]
        table_name = request.form['table_list']
        data = pd.read_sql_query(f"select * from {table_name};", con)
        return render_template("past_data.html", list=table_list, data=(data.to_html(classes='table')), 
        table_name=table_name, do_not_display=123,csv_file=file_name, jess_adjustment= jess_adjustment, pete_adjustment= pete_adjustment)
    return render_template("past_data.html", list=table_list, do_not_display=123,csv_file= file_name, 
    jess_adjustment= jess_adjustment, pete_adjustment= pete_adjustment)
Ejemplo n.º 11
0
import sys
import numpy as np
import networkx as nx

sys.path.insert(0, '../')
from models import connect_to_db, Paper_authors, Authors

amount_authors = 10000

author_matrix = np.zeros([amount_authors, amount_authors])
paper_index = {}

# Create co-author matrix

connect_to_db('../nips-papers.db')

for entry in Paper_authors.select():
    paper, author = entry.paper_id, entry.author_id
    try:
        author = int(author)
    except ValueError:
        continue
    if paper in paper_index:
        paper_index[paper].append(author)
    else:
        paper_index[paper] = [author]

for paper, authors in paper_index.items():
    for author1 in authors:
        for author2 in authors:
def send_wtp_tokens():
    global out_nonce
    try:
        session = connect_to_db(SQLALCHEMY_DATABASE_URI)

        out_nonce = w3.eth.getTransactionCount(out_wallet)
        logger.info(f'out_wallet nouce {out_nonce}')

        contract_address=Web3.toChecksumAddress(CONTRACT_ADD)

        try:
            contract_abi = json.loads(open(ABI_FILE_PATH,"r").read())
        except:
            logger.info(f'ABI file {ABI_FILE_PATH} not found')
            return False

        contract = w3.eth.contract(address=contract_address, abi=contract_abi)
        decimal = contract.functions.decimals().call()
        out_wallet_balance = contract.functions.balanceOf(Web3.toChecksumAddress(out_wallet)).call()
        eth_balance = w3.eth.getBalance(Web3.toChecksumAddress(out_wallet))

        logger.info(f'Out wallet balance {out_wallet_balance}')
        logger.info(f"Eth balance: {eth_balance}")

        withdrawals = session.query(Withdrawals).filter(Withdrawals.status == 0).all()
        logger.info(f'In table Withdrawals found {len(withdrawals)} wallets')
        nonce = w3.eth.getTransactionCount(Web3.toChecksumAddress(out_wallet))

        for i, w in enumerate(withdrawals):
            time.sleep(TIME_OUT)

            logger.info(f'Send {w.amount} WTP tokens to {w.wallet} ...')
            txn = contract.functions.transfer(
                Web3.toChecksumAddress(w.wallet),
                int(w.amount*10**decimal),
            ).buildTransaction({
                'chainId': 1,
                'gas': 100000,
                'gasPrice': w3.toWei(ETH_FEE_WD, 'gwei'),
                'nonce': nonce,
            })
            signed_txn = w3.eth.account.signTransaction(txn, private_key=OUT_PRIVKEY)

            try:
                txhash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
                # ставим  pending и сохраням txhash
                w.pending = 1
                w.txhash = txhash.hex()
                session.commit()

                #send_message(f'withdrawal_bot said: Произведён вывод {w.amount} wtp по адресу {w.wallet}')

                nonce = nonce +1
            except Exception as e:
                message = f'Error {e}'
                logger.error(message)

    except Exception as e:
        logger.exception('send wtp')
        send_message(f'withdrawal_bot said: {e}')
    finally:
        session.close()
Ejemplo n.º 13
0
from flask import Flask, render_template, redirect, request, flash, session
from models import connect_to_db, Movie

app = Flask(__name__)
# Required to use Flask sessions and the debug toolbar
app.secret_key = "ChaosReigns"
app.config['DEBUG'] = True
# set up SQLAlchemy with app as context
connect_to_db(app)


@app.route('/')
def index():
    """ Show the main page, with featured collection(s) and any horror movies currently in theater. """
    # get the "featured" collection to display at top of page

    # get movies now playing to display in second row
    movies = Movie.query.all()

    return render_template("index.html", movies=movies)

if __name__ == '__main__':
    app.run()
Ejemplo n.º 14
0
    return jsonify(suggestion)


@app.route('/optimize')
def optimization_dashboard():
    """Display optimization page as well as available outgoing sources"""

    if "user" not in session:
        flash("Please log in first")
        return redirect('/')

    user = User.query.get(session["user"])
    goal = request.args.get("goal_program")

    if not goal:
        programs = Program.query.all()
        return render_template('optimize.html', programs=programs)

    outgoing = OrderedDict(sorted(user.user_outgoing_collection(goal).items()))

    return jsonify(outgoing)


if __name__ == "__main__":
    connect_to_db(app, os.environ.get("DATABASE_URL"))
    db.create_all(app=app)

    DEBUG = "NO_DEBUG" not in os.environ
    PORT = int(os.environ.get("PORT", 5000))
    app.run(host="0.0.0.0", port=PORT)
Ejemplo n.º 15
0
from dynaconf import settings
from telegram.ext import Updater

from handlers import Handlers
from models import connect_to_db

updater = Updater(settings.BOT_TOKEN, use_context=True)
job_queue = updater.job_queue

connect_to_db()
Handlers.register(updater.dispatcher)
job_queue.run_repeating(Handlers.send_reminds, interval=60, first=0)
updater.start_polling()
updater.idle()
Ejemplo n.º 16
0
from models import connect_to_db
from views import app

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0")

    from flask import Flask
    app = Flask(__name__)

    connect_to_db(app)

    app.run()

# took out from seed import & from models import extras
Ejemplo n.º 17
0
def main():
    connect_to_db(app)
    app.run(debug=DEBUG, port=PORT, host="0.0.0.0")    
Ejemplo n.º 18
0
"""Script to seed database"""

import os  #module from Python's library, code related to working with your computer's operating system
import json
from random import choice, randint
from datetime import datetime

import models
import server

os.system('dropdb rooms')
os.system('createdb rooms')

models.connect_to_db(server.app)
models.db.create_all()

#Create 10 users
for n in range(10):
    username = f'user{n}'
    email = f'user{n}@test.com'  #unique email
    password = f'test{n}'

    user = models.User(username=username, email=email, password=password)
    models.db.session.add(user)
    models.db.session.commit()

# Create rooms, store them in list so we can use them
# to create fake posts, likes and comments later
posts_in_db = []
posts = ["living room", "bedroom", "kitchen", "patio", "home office"]
Ejemplo n.º 19
0
from flask import Flask
import models
from resources.courses import courses_api
from resources.reviews import reviews_api

app = Flask(__name__)
app.register_blueprint(courses_api)
app.register_blueprint(reviews_api)

DEBUG = True
HOST = '0.0.0.0'
PORT = 5000


@app.route('/')
def hello_word():
    return 'hello world'


if __name__ == '__main__':
    models.connect_to_db(app)
    app.run(debug=DEBUG, host=HOST, port=PORT)
Ejemplo n.º 20
0
        edges: list of edges
        nodes: list of nodes
        depth: distance to the original author

    Returns: list of edges and list of nodes in the graph

    """
    # nodes, edges = add_authors_to_graph(nodes, edges, author_id)
    co_authors = get_co_authors(author_id)
    nodes, edges = add_authors_to_graph(nodes, edges, co_authors, author_id)
    for co_author in co_authors:
        if depth < int(options.max_depth) and len(nodes) < 150:
            nodes, edges = process_author(co_author,
                                          nodes,
                                          edges,
                                          depth=depth + 1)
    return nodes, edges


def main():
    nodes = []
    edges = []
    nodes, edges = add_authors_to_graph(nodes, edges, options.author)
    nodes, edges = process_author(options.author, nodes, edges)
    print(json.dumps({'nodes': nodes, 'edges': edges}))


if __name__ == '__main__':
    connect_to_db("/".join(dir_name.split("/")[:-1]) + '/nips-papers.db')
    main()