示例#1
0
def sealStatementInfoSave(req):
    """
    添加刻章信息保存!
    :param req:
    :return:
    """
    sealStatementInput = req.POST["sealStatementInput"]
    statementContent = Statement.objects.filter(
        statementContent=sealStatementInput)
    # isShow = bool(req.POST["radioVal"])
    if req.POST["radioVal"] == "1":
        isShow = True
    else:
        isShow = False
    if statementContent.exists():
        return HttpResponse(2)
    statementId = uuid.uuid1()  # 生成36位随机数
    try:
        with transaction.atomic():  # 事务的使用,包含的内容一旦出错,则保存的信息全部撤回
            statement = Statement(statementId=statementId,
                                  statementContent=sealStatementInput,
                                  isShow=isShow)
            statement.save()
            i = 0
            while i < len(req.POST) - 2:  #附件长度
                dataNameNum = "dataName" + str(i)
                statementInfo = req.POST[dataNameNum]
                dataType = DataType(dataTypeId=uuid.uuid1(),
                                    statementId_id=statementId,
                                    dataName=statementInfo)
                dataType.save()
                i = i + 1
            return HttpResponse(1)
    except Exception as err:
        return HttpResponse(0)
示例#2
0
def statement_entry(user, descript, credit=0, debit=0):
    state = Statement.create(ac_no=user.acc_num,
                             credit=credit,
                             debit=debit,
                             timestamp=datetime.now(),
                             os_balance=user.balance,
                             description=descript)
示例#3
0
def start_analysis_loop():
    static_assessment.load()

    min_to_end_stmnt = static_assessment.maximum_question_length // letters_per_min
    sec_to_end_stmnt = static_assessment.maximum_question_length // letters_per_second
    print("[start_analysis_loop] min to end: ", min_to_end_stmnt,
          ", sec to end: ", sec_to_end_stmnt)

    # Analyse all that was not up to now
    do_analyse()

    current_exec_event = None
    while True:
        channel_id, user_id, message_id, message, creation_time = message_queue.get(
        )
        created_ago = creation_time - datetime.timedelta(
            minutes=min_to_end_stmnt)
        updated_ago = creation_time - datetime.timedelta(
            seconds=(len(message) // letters_per_second))
        new_statment_was_created = False

        session = db_session()
        stmnt = Statement.query.\
                filter(and_(Statement.channel_id==channel_id,
                    Statement.user_id==user_id,
                    Statement.created>created_ago,
                    Statement.updated>updated_ago)).\
                first()

        if stmnt is None:
            stmnt = Statement(channel_id, user_id, message_id, creation_time)
            session.add(stmnt)
            new_statment_was_created = True
            print("New stmnt (msgid): ", message_id)
        else:
            print("Update stmnt: ", stmnt.id)
            update_query = Statement.__table__.update().values(updated=creation_time, last_msg_id=message_id).\
                where(Statement.id==stmnt.id)
            session.execute(update_query)

        session.commit()
        session.close()

        do_analyse()

        if current_exec_event is not None:
            scheduler.cancel(current_exec_event)
            current_exec_event = None
        else:
            if not scheduler.empty():
                print("[start_analysis_loop] SYNC ERROR...")
        current_exec_event = scheduler.enter(sec_to_end_stmnt + 5, 1,
                                             do_analyse)
        scheduler.run(blocking=False)
示例#4
0
def __coalesce_statements(paragraphs):
    statements = []
    current_statement = None
    prev_paragraph = None
    for paragraph in paragraphs:
        speaker_match = re.match(SPEAKER_REGEX, paragraph)
        if speaker_match:
            # Wrap up the the statement and append it to the list:
            if current_statement is not None:
                # Infer attributes signaled by the end of the statement:
                if prev_paragraph is not None:
                    if prev_paragraph.strip().endswith(" --"):
                        current_statement.ended_by_interruption = True
                    elif prev_paragraph.strip().endswith("?"):
                        current_statement.ends_with_question = True
                statements.append(current_statement)

            # Create a new current statement:
            speaker = speaker_match.group(1)
            paragraph = re.sub(SPEAKER_REGEX, "", paragraph).strip()
            current_statement = Statement(speaker=speaker,
                                          ended_by_interruption=False,
                                          includes_laughter=False,
                                          ends_with_question=False,
                                          speaker_is_petitioner=False,
                                          speaker_is_respondent=False)
            current_statement.temp_paragraphs = []
            current_statement.temp_paragraphs.append(paragraph)

        elif current_statement is not None:
            if paragraph == "(Laughter.)":
                current_statement.includes_laughter = True
            else:
                current_statement.temp_paragraphs.append(paragraph)

        prev_paragraph = paragraph

    if current_statement is not None:
        statements.append(current_statement)

    return statements
示例#5
0
def register():
    name = input("Enter full name: ")
    pin = int(input("Enter a four digit PIN: "))
    while True:
        temp_acc = randrange(10000, 99999)
        acc = Customer.select().where(Customer.acc_num == temp_acc)
        if acc.exists():
            continue
        else:
            gen_acc = temp_acc
            break
    init_bal = float(input("Enter initial balance: "))
    print(f"Your account number is: {gen_acc}")
    Customer.create(full_name=name, pin=pin, acc_num=gen_acc, balance=init_bal)
    Statement.create(ac_no=gen_acc,
                     credit=init_bal,
                     debit=0,
                     timestamp=datetime.now(),
                     os_balance=init_bal,
                     description="Opening balance")
    print("Press any key")
    dummy = input()
示例#6
0
def gen_statement(user):
    print(f"Name: {user.full_name}")
    print(f"Account Number: {user.acc_num} \n")
    entries = Statement.select().where(Statement.ac_no == user.acc_num)
    table = PrettyTable(
        ["Date and Time", "Credit", "Debit", "Balance", "Description"])
    for entry in entries:
        table.add_row([
            str(entry.timestamp)[:19], entry.credit, entry.debit,
            entry.os_balance, entry.description
        ])
    print(table)
    print("\n\nSave to file ? (y for yes, any other key to go back main menu)")
    dummy = input()
    if dummy == "y" or dummy == "Y":
        with open('Mini Statement.txt', 'w') as statement_file:
            statement_file.write(f"Name: {user.full_name} \n")
            statement_file.write(f"Account Number: {user.acc_num} \n")
            statement_file.write(str(table))
            print("Saved!")
            dummy = input("Press any key")
示例#7
0
def generate_file(questions, filename):
    i = 0
    for question in questions:
        i = i + 1
        if (len(question) == 1) & (question.get("instruction") is not None):
            Statement(question.get("instruction")).append(filename, 0)
        elif (len(question) == 2) & (question.get("text") is not None) & (
                question.get("var") is not None):
            VarCapture(question.get("text"),
                       question.get("var")).append(filename, 0)
        elif (len(question) == 3) & (question.get("text") is not None) & (
                question.get("var") is not None) & (question.get("options")
                                                    is not None):
            VarOptions(question.get("text"), question.get("var"),
                       question.get("options")).append(filename, 0)
        elif (len(question) == 3) & (question.get("text") is not None) & (
                question.get("var") is not None) & (question.get("conditions")
                                                    is not None):
            Condtional(question.get("text"), question.get("var"),
                       question.get("conditions")).append(filename, 0)
        elif (len(question) == 3) & (question.get("formula") is not None) & (
                question.get("var") is not None) & (
                    question.get("calculated_variable") is not None):
            Evaluate(question.get("calculated_variable"), question.get("var"),
                     question.get("formula")).append(filename, 0)
        elif (len(question)
              == 2) & (question.get("instruction") is not None) & (
                  question.get("instruction_var") is not None):
            Substiute(question.get("instruction"),
                      question.get("instruction_var")).append(filename, 0)
        elif (len(question) == 4) & (question.get("list_var") is not None) & (
                question.get("list_length")
                is not None) & (question.get("instruction") is not None) & (
                    question.get("instruction_var") is not None):
            Print(question.get("list_var"), question.get("list_length"),
                  question.get("instruction"),
                  question.get("instruction_var")).append(filename, 0)
        else:
            print("Problem in JSON file")
示例#8
0
def metrics(name, form_type, year):
    company = Company.query.filter_by(title=name).first()
    statement = Statement.query.filter_by(company_id=company.id).first()
    current = dt.datetime.now()
    date_array = [current]

    for i in range(5):
        fortnite = dt.timedelta(days=14)
        current += fortnite
        date_array.append(current)

    try:
        mobb = hf.Mobbin(name, form_type, year)
    except:
        flash('Certain form requests may be unavailable')
        return redirect(url_for('index'))

    try:
        robb = hf.Robbin(company.ticker, date_points=date_array)
    except:
        flash('Some financial metrics unavailable')

    df_array, file_array, table_titles, engine, session = \
    mobb.statements_to_sql()

    table_list = ['Balance', 'Income', 'Operations', 'Equity', 'Cash']
    sort_list = ['new', 'asc', 'desc']
    bala, inco, oper, equi, cash = [None] * 5
    table_val = [bala, inco, oper, equi, cash]

    if file_array:
        for i in range(len(table_titles)):
            for j in range(len(table_list)):
                table_val[i] = file_array[i] \
                if table_titles[i] == table_list[j] \
                else table_val[i]

    if statement is None:
        statement = Statement(form_type=form_type,
                              year=year,
                              company=name,
                              bs=bala,
                              income=inco,
                              ops=oper,
                              equity=equi,
                              cash=cash,
                              company_id=company.id)

        db.session.add(statement)

        try:
            db.session.commit()
        except Exception:
            db.session.rollback()
            return redirect(url_for('index'))

    df_dict = {}

    for i in range(len(table_titles)):
        df_dict[table_titles[i]] = {}
        columns = session.execute(f"SELECT * FROM {table_titles[i]}").keys()
        df_dict[table_titles[i]]['columns'] = list(columns)

        for j in range(len(sort_list)):

            for k in range(len(columns)):
                dict_str = f"col_{k}_{sort_list[j]}"
                if j == 0 and k > 0:
                    continue
                elif j == 0:
                    df_dict[table_titles[i]]['new'] = \
                    session.execute(f"SELECT * FROM {table_titles[i]}")\
                    .fetchall()
                else:
                    df_dict[table_titles[i]][dict_str] = \
                    session.execute(f"SELECT * FROM {table_titles[i]} \
                    ORDER BY `{columns[k]}` {sort_list[j]}"                                                           ).fetchall()

        df_dict[table_titles[i]]['keys_list'] = \
        list(df_dict[table_titles[i]].keys())

    ratios = SearchResults(mobb, robb, session)
    form = SearchForm()
    companies = Company.query.with_entities(Company.title).all()

    if form.validate_on_submit():
        name = form.name.data.lower().title()
        form_type = form.form_type.data
        year = form.year.data

        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('metrics',
                                name=name,
                                form_type=form_type,
                                year=year)
        return redirect(next_page)

    return render_template('metrics.html',
                           form=form,
                           name=name,
                           form_type=form_type,
                           year=year,
                           company=company,
                           ratios=ratios,
                           table_titles=table_titles,
                           columns=columns,
                           companies=companies,
                           session=session,
                           df_dict=df_dict,
                           scrollToAnchor='head')
示例#9
0
                        if transfer.name == transaction.name:
                            if transfer.amount == transaction.amount:
                                exists = True
                if exists != True:
                    transactions.append(transaction)
        line_count = line_count + 1

states = []

with open('transactions.json', 'w') as json_file:
    data = {}
    data["Transactions"] = []
    for transfer in transactions:
        date_day = datetime.datetime.strptime(
            transfer.date, "%Y-%m-%d").date().strftime("%Y%m")
        statement = Statement(date_day, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
        data["Transactions"].append(transfer.serialize())
        exists = False
        for stat_ in states:
            if stat_.date == date_day:
                statement = stat_

        statement.create_statement(transfer)
        statement.set_ending_balance_month()
        for state in states:
            if state.date == statement.date:
                exists = True

        if not exists:
            states.append(statement)
                            if operation.amount == transaction.amount:
                                exists = True
                if exists != True:
                    # data["Transactions"].append(transaction.__dict__)
                    transactions.append(transaction)
        line_count += 1

# Write to JSONfile 
statements = []

with open('transaction.json', 'w') as json_file:
    data = {}
    data["Transactions"] = []
    for operation in transactions:
        date_ = datetime.datetime.strptime(operation.date, "%d/%m/%Y").date().strftime("%Y%m")
        statement = Statement(date_, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
        data["Transactions"].append(operation.serialize())
        exists = False
        for state in statements:
            if state.date == statement.date: # statement with the same date already added in the list (one statement per month)
                exists = True
                if state.date == date_:
                    statement = state
        statement.create_statement(operation)
        statement.set_ending_balance_month()
        statement.set_tax_and_profit()
        if exists != True:
            statements.append(statement)
    json.dump(data, json_file, sort_keys=True, indent=4) 

with open('statement.json', 'w') as json_file: