from tkinter import *
from tkinter import ttk
import tkinter.messagebox
from docx import Document
from docx.oxml.ns import qn  # 设置字体
from docx.shared import Pt  # 设置字体大小
from docx.enum.text import WD_ALIGN_PARAGRAPH  # 设置对象居中、对齐等
import math
from ttkbootstrap import Style

LOG_LINE_NUM = 0
style = Style(theme='minty')

class MY_GUI():
    def __init__(self,init_window_name):
        self.init_window_name = init_window_name

    #设置窗口
    def set_init_window(self):
        self.init_window_name.title("悬挑板计算小工具_v1.0")           #窗口名
        #self.init_window_name.geometry('320x160+10+10')                         #290 160为窗口大小，+10 +10 定义窗口弹出时的默认展示位置
        self.init_window_name.geometry('1068x681+10+10')
        #self.init_window_name["bg"] = "pink"                                    #窗口背景色，其他背景色见：blog.csdn.net/chl0000/article/details/7657887
        #self.init_window_name.attributes("-alpha",0.9)                          #虚化，值越小虚化程度越高
        #标签
        self.inputlabel = Label(self.init_window_name, text="信息输入：", font=("宋体", 12, "bold"))
        self.inputlabel.grid(row=0, column=0, sticky='e')
        self.namelabel = Label(self.init_window_name, text="构件名称：")
        self.namelabel.grid(row=1, column=1, sticky='e')
        self.hlabel = Label(self.init_window_name, text="板厚h（mm）：")
        self.hlabel.grid(row=2, column=1, sticky='e')
        self.llabel = Label(self.init_window_name, text="挑出长度l（mm）：")
        self.llabel.grid(row=3, column=1, sticky='e')
        self.blabel = Label(self.init_window_name, text="计算宽度b（mm）：")
        self.blabel.grid(row=4, column=1, sticky='e')
        self.dllabel = Label(self.init_window_name, text="恒载dl（kN/m\u00b2）：")
        self.dllabel.grid(row=5, column=1, sticky='e')
        self.lllabel = Label(self.init_window_name, text="活载ll（kN/m\u00b2）：")
        self.lllabel.grid(row=6, column=1, sticky='e')
        self.bllabel = Label(self.init_window_name, text="边缘翻边线荷载bl(kN/m)：")
        self.bllabel.grid(row=7, column=1, sticky='e')
        self.cglabel = Label(self.init_window_name, text="混凝土强度等级c_g：")
        self.cglabel.grid(row=8, column=1, sticky='e')
        self.fclabel = Label(self.init_window_name, text="fc（N/mm\u00b2）：")
        self.fclabel.grid(row=9, column=1, sticky='e')
        self.ftlabel = Label(self.init_window_name, text="ft（N/mm\u00b2）：")
        self.ftlabel.grid(row=10, column=1, sticky='e')
        self.sglabel = Label(self.init_window_name, text="钢筋强度等级s_g：")
        self.sglabel.grid(row=11, column=1, sticky='e')
        self.fylabel = Label(self.init_window_name, text="fy（N/mm\u00b2）：")
        self.fylabel.grid(row=12, column=1, sticky='e')
        self.pminlabel = Label(self.init_window_name, text="最小配筋率：")
        self.pminlabel.grid(row=13, column=1, sticky='e')
        self.aslabel = Label(self.init_window_name, text="纵筋合力点至近边距离（mm）：")
        self.aslabel.grid(row=14, column=1, sticky='e')
        self.y0label = Label(self.init_window_name, text="重要性系数：")
        self.y0label.grid(row=15, column=1, sticky='e')
        self.bblabel = Label(self.init_window_name, text="是否计算内部梁：")
        self.bblabel.grid(row=16, column=1, sticky='e')
        self.Lblabel = Label(self.init_window_name, text="梁宽（mm）：")
        self.Lblabel.grid(row=17, column=1, sticky='e')
        self.Lhlabel = Label(self.init_window_name, text="梁高（mm）：")
        self.Lhlabel.grid(row=18, column=1, sticky='e')
        self.LLlabel = Label(self.init_window_name, text="梁长（mm）：")
        self.LLlabel.grid(row=19, column=1, sticky='e')
        self.nameText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.nameText.grid(row=1, column=2)
        self.nameText.insert(0,'雨棚1')
        self.hText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.hText.grid(row=2, column=2)
        self.hText.insert(0,'120')
        self.lText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.lText.grid(row=3, column=2)
        self.lText.insert(0,'1200')
        self.bText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.bText.grid(row=4, column=2)
        self.bText.insert(0,'1000')
        self.dlText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.dlText.grid(row=5, column=2)
        self.dlText.insert(0,'1.5')
        self.llText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.llText.grid(row=6, column=2)
        self.llText.insert(0,'2')
        self.blText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.blText.grid(row=7, column=2)
        self.blText.insert(0,'1')
        self.cgText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.cgText.grid(row=8, column=2)
        self.cgText.insert(0,'C30')
        self.fcText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.fcText.grid(row=9, column=2)
        self.fcText.insert(0,'14.3')
        self.ftText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.ftText.grid(row=10, column=2)
        self.ftText.insert(0,'1.43')
        self.sgText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.sgText.grid(row=11, column=2)
        self.sgText.insert(0,'HRB400')
        self.fyText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.fyText.grid(row=12, column=2)
        self.fyText.insert(0,'360')
        self.pminText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.pminText.grid(row=13, column=2)
        self.pminText.insert(0,'0.002')
        self.asText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.asText.grid(row=14, column=2)
        self.asText.insert(0,'20')
        self.y0Text = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.y0Text.grid(row=15, column=2)
        self.y0Text.insert(0,'1.0')

        self.bbselection = ttk.Combobox (self.init_window_name,  width=17, textvariable='')
        self.bbselection["value"] = ("是", "否")
        self.bbselection.grid(row=16, column=2)
        self.bbselection.current(0)

        self.LbText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.LbText.grid(row=17, column=2)
        self.LbText.insert(0,'200')
        self.LhText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.LhText.grid(row=18, column=2)
        self.LhText.insert(0,'500')
        self.LLText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.LLText.grid(row=19, column=2)
        self.LLText.insert(0,'2400')

        self.outputlabel = Label(self.init_window_name, text="结果输出：", font=("宋体", 12, "bold"))
        self.outputlabel.grid(row=0, column=6, sticky='e')
        self.Aslabel = Label(self.init_window_name, text="板受力筋计算面积As(mm\u00b2)：")
        self.Aslabel.grid(row=1, column=7, sticky='e')
        self.AsText = Entry(self.init_window_name, width=20,textvariable="")
        self.AsText.grid(row=1, column=8)
        self.AsText.insert(0,'250')
        self.Aspjlabel = Label(self.init_window_name, text="板受力筋配筋（eg:E8@200)：")
        self.Aspjlabel.grid(row=2, column=7, sticky='e')
        self.AspjText = Entry(self.init_window_name, width=20,textvariable="")
        self.AspjText.grid(row=2, column=8)
        self.Asmjlabel = Label(self.init_window_name, text="实际面积As(mm\u00b2)：")
        self.Asmjlabel.grid(row=3, column=7, sticky='e')
        self.AsmjText = Entry(self.init_window_name, width=20,textvariable="")
        self.AsmjText.grid(row=3, column=8)

        self.LAsvslabel = Label(self.init_window_name, text="梁箍筋计算面积（mm\u00b2/100mm）：")
        self.LAsvslabel.grid(row=5, column=7, sticky='e')
        self.LAsvsText = Entry(self.init_window_name, width=20,textvariable="")
        self.LAsvsText.grid(row=5, column=8)
        self.LAsvsText.insert(0,'250')
        self.LAsvspjlabel = Label(self.init_window_name, text="梁箍筋实际配筋（eg:E8@200）：")
        self.LAsvspjlabel.grid(row=6, column=7, sticky='e')
        self.LAsvspjText = Entry(self.init_window_name, width=20,textvariable="")
        self.LAsvspjText.grid(row=6, column=8)
        self.Lasvsmjlabel = Label(self.init_window_name, text="梁箍筋实际面积Asv/s(mm\u00b2/100mm)：")
        self.Lasvsmjlabel.grid(row=7, column=7, sticky='e')
        self.LasvsmjText = Entry(self.init_window_name, width=20,textvariable="")
        self.LasvsmjText.grid(row=7, column=8)

        self.AsLlabel = Label(self.init_window_name, text="梁上下纵筋计算面积As=As\'(mm\u00b2)：")
        self.AsLlabel.grid(row=9, column=7, sticky='e')
        self.AsLText = Entry(self.init_window_name, width=20,textvariable="")
        self.AsLText.grid(row=9, column=8)
        self.AsLText.insert(0,'400')
        self.LAspjlabel = Label(self.init_window_name, text="梁上下纵筋配筋（eg:2E16)：")
        self.LAspjlabel.grid(row=10, column=7, sticky='e')
        self.LAspjText = Entry(self.init_window_name, width=20,textvariable="")
        self.LAspjText.grid(row=10, column=8)
        self.LAsmjlabel = Label(self.init_window_name, text="梁上下纵筋实际面积As(mm\u00b2)：")
        self.LAsmjlabel.grid(row=11, column=7, sticky='e')
        self.LAsmjText = Entry(self.init_window_name, width=20,textvariable="")
        self.LAsmjText.grid(row=11, column=8)

        self.Astllabel = Label(self.init_window_name, text="梁抗扭纵筋计算面积Astl(mm\u00b2)：")
        self.Astllabel.grid(row=13, column=7, sticky='e')
        self.AstlText = Entry(self.init_window_name, width=20,textvariable="")
        self.AstlText.grid(row=13, column=8)
        self.AstlText.insert(0,'400')
        self.LAstlpjlabel = Label(self.init_window_name, text="梁抗扭纵筋配筋（eg:2E16)：")
        self.LAstlpjlabel.grid(row=14, column=7, sticky='e')
        self.LAstlpjText = Entry(self.init_window_name, width=20,textvariable="")
        self.LAstlpjText.grid(row=14, column=8)
        self.LAstlmjlabel = Label(self.init_window_name, text="梁抗扭纵筋实际面积As(mm\u00b2)：")
        self.LAstlmjlabel.grid(row=15, column=7, sticky='e')
        self.LAstlmjText = Entry(self.init_window_name, width=20,textvariable="")
        self.LAstlmjText.grid(row=15, column=8)

        #按钮
        self.cal = Button(self.init_window_name, text="计算", bg="lightblue", width=10,command=lambda:self.calculation(self.hText.get(),self.lText.get(),self.bText.get(),self.dlText.get(),self.llText.get(),self.blText.get(),self.fcText.get(),self.ftText.get(),self.fyText.get(),self.pminText.get(),self.asText.get(),self.y0Text.get(),self.bbselection.get(),self.LbText.get(),self.LhText.get(),self.LLText.get()))  # 调用内部方法  加()为直接调用
        self.cal.grid(row=21, column=2)
        self.docx = Button(self.init_window_name, text="生成计算书", bg="lightblue", width=10,command=lambda:self.txt(self.nameText.get(),self.hText.get(),self.lText.get(),self.bText.get(),self.dlText.get(),self.llText.get(),self.blText.get(),self.cgText.get(),self.fcText.get(),self.ftText.get(),self.sgText.get(),self.fyText.get(),self.pminText.get(),self.asText.get(),self.y0Text.get(),self.bbselection.get(),self.LbText.get(),self.LhText.get(),self.LLText.get()))  # 调用内部方法  加()为直接调用
        self.docx.grid(row=21, column=8)

    def calculation(self,h,l,b,dl,ll,bl,fc,ft,fy,pmin,a_s,y0,bool_beam,Lb,Lh,LL):
        h = float(h)  # 板厚 mm
        l = float(l)  # 挑出长度  mm
        b = float(b)  # 宽度  mm
        dl = float(dl)  # 恒载 kN/m\u00b2
        ll = float(ll)  # 活载  kN/m\u00b2
        bl = float(bl)  # 边缘翻边线荷载  kN/m\u00b2
        fc = float(fc)  # N/mm\u00b2
        ft = float(ft)  # N/mm\u00b2
        fy = float(fy)  # N/mm\u00b2
        pmin = float(pmin)  # 最小配筋率
        a_s = float(a_s)  # 纵筋合力点至近边距离
        y0 = float(y0)  # 重要性系数
        Lb = float(Lb)  # 梁宽mm  梁即使不算，也保留勿删
        Lh = float(Lh)  # 梁高mm
        LL = float(LL)  # 梁长mm

        # 板荷载计算
        Md = 0.5 * (25 * h / 1000 + dl) * l * l / 1000000
        Vd = (h / 1000 * 25 + dl) * l / 1000
        Ml = 0.5 * (25 * h / 1000 + ll) * l * l / 1000000
        Vl = (h / 1000 * 25 + ll) * l / 1000
        Mb = bl * l / 1000
        Vb = bl
        M = 1.3 * (Md + Mb) + 1.5 * Ml
        V = 1.3 * (Vd + Vb) + 1.5 * Vl
        # 内梁荷载计算
        Lx = V
        LTm = M + Lx * Lb / 2 / 1000
        Tmax = LTm * LL / 2 / 1000
        Mmax = 1 / 8 * Lx * LL * LL / 1000000
        Vmax = 0.5 * Lx * LL / 1000
        # 正截面受弯计算
        h0 = h - a_s
        xb = 0.518
        as1 = y0 * M * 1000000 / (fc * 1000 * h0 * h0)
        x1 = 1 - math.sqrt(1 - 2 * as1)  # 计算相对受压区高度
        if x1 > xb:
            tkinter.messagebox.showinfo('警告','受压区高度' + str(x1) + '>' + str(xb) + ';不满足要求')
        else:
            pass
        As = fc * b * h0 * x1 / fy
        p = As / (b * h)
        Asmin = pmin * b * h
        if As <Asmin:
            As = Asmin
        else:
            pass
        self.AsText.delete(0,END)
        self.AsText.insert(0,int(As))

        # 梁计算参数
        ast = 35
        asb = 35
        Lh0 = Lh - asb
        Wt = Lb * Lb * (3 * Lh0 - Lb) / 6
        bcor = Lb - 50
        hcor = Lh - ast - asb
        Acor = bcor * hcor
        ucor = 2 * (bcor + hcor)

        if bool_beam == '是':  # 梁截面设计
            allow1 = 0.25 * 1 * fc
            allow2 = 0.2 * 1 * fc
            result1 = Vmax * 1000 / (Lb * Lh0) + Tmax * 1000000 / (0.8 * Lb * Lb * (3 * Lh - Lb) / 6)
            if Lh0 / Lb <= 4:  # 梁截面验算
                if result1 <= allow1:
                    result_jm = '梁截面满足要求'
                else:
                    tkinter.messagebox.showinfo('警告','梁截面不满足要求')
            elif 4 < Lh0 / Lb < 6:
                allow3 = allow1 * (6 - Lh0 / Lb) / 2 + allow2 * (Lh0 / Lb - 4)
                if result1 <= allow3:
                    result_jm = '梁截面满足要求'
                else:
                    tkinter.messagebox.showinfo('警告','梁截面不满足要求')
            else:
                tkinter.messagebox.showinfo('梁高宽比大于6，受扭构件的截面尺寸要求及扭曲截面承载力计算应符合专门规定。')
            result2 = Vmax * 1000 / (Lb * Lh0) + Tmax * 1000000 / (Lb * Lb * (3 * Lh - Lb) / 6)
            allow4 = 0.7 * ft

            if result2 < allow4: # 剪扭计算判定
                tkinter.messagebox.showinfo('满足要求，可不进行构件受减扭承载力计算，但需满足规范构造要求。')
            else:
                pass
# 正截面受弯计算
            x = 2 * ast
            AsL = (Mmax - 1 * fc * Lb * x * (Lh0 - x / 2)) / (fy * (Lh0 - ast))
            AsLmin = 0.002 * Lb * Lh
            if AsL < AsLmin:
                AsL = AsLmin
            else:
                pass
            self.AsLText.delete(0,END)
            self.AsLText.insert(0,int(AsL))
# 剪扭计算
            bt = 1.5 / (1 + 0.5 * Vmax * Wt / (Tmax * 1000 * Lb * Lh0))
            if bt< 0.5:
                bt = 0.5
            elif bt > 1:
                bt = 1
            else:
                pass
            Ast1_st = (Tmax * 1000000 - 0.35 * bt * ft * Wt) / (1.2 * math.sqrt(1.2) * fy * Acor)
            nAsv1_sv = (Vmax - 0.7 * (1.5 - bt) * ft * Lb * Lh0) / (1.25 * fy * Lh0)
            if nAsv1_sv < 0:
                nAsv1_sv = 0
            else:
                pass
            Asv_s = nAsv1_sv / 2 + Ast1_st
            psvmin = 0.28 * ft / fy
            Asvmin_s = psvmin * Lb / 2
            if Asv_s < Asvmin_s:
                Asv_s = Asvmin_s
            else:
                pass

            Astl = 1.2 * fy * ucor / fy * (Ast1_st)
            T_Vb = Tmax * 1000 / Vmax / Lb
            if T_Vb > 2:
                T_Vb = 2
            else:
                pass
            ptlmin = 0.6 * math.sqrt(Tmax * 1000 / (Vmax * Lb)) * ft / fy
            Atlmin = ptlmin * Lb * Lh
            if Astl < Atlmin:
                Astl = Atlmin
            else:
                pass

            self.LAsvsText.delete(0,END)
            self.LAsvsText.insert(0,int(Asv_s * 100))
            self.AstlText.delete(0,END)
            self.AstlText.insert(0,int(Astl))

        else:
            pass

    def txt(self,name,h,l,b,dl,ll,bl,concrete_g,fc,ft,steel_g,fy,pmin,a_s,y0,bool_beam,Lb,Lh,LL):
        # 板参数定义
        h = int(h)  # 板厚 mm
        l = int(l)  # 挑出长度  mm
        b = int(b)  # 宽度  mm
        dl = float(dl)  # 恒载 kN/m\u00b2
        ll = float(ll)  # 活载  kN/m\u00b2
        bl = float(bl)  # 边缘翻边线荷载  kN/m\u00b2
        fc = float(fc)  # N/mm\u00b2
        ft = float(ft)  # N/mm\u00b2
        fy = float(fy)  # N/mm\u00b2
        pmin = float(pmin)  # 最小配筋率
        a_s = int(a_s)  # 纵筋合力点至近边距离
        y0 = float(y0)  # 重要性系数
        Lb = int(Lb)  # 梁宽mm  梁即使不算，也保留勿删
        Lh = int(Lh)  # 梁高mm
        LL = int(LL)  # 梁长mm

        # 板荷载计算
        Md = 0.5 * (25 * h / 1000 + dl) * l * l / 1000000
        Vd = (h / 1000 * 25 + dl) * l / 1000
        Ml = 0.5 * (25 * h / 1000 + ll) * l * l / 1000000
        Vl = (h / 1000 * 25 + ll) * l / 1000
        Mb = bl * l / 1000
        Vb = bl
        M = 1.3 * (Md + Mb) + 1.5 * Ml
        V = 1.3 * (Vd + Vb) + 1.5 * Vl
        # 内梁荷载计算
        Lx = V
        LTm = M + Lx * Lb / 2 / 1000
        Tmax = LTm * LL / 2 / 1000
        Mmax = 1 / 8 * Lx * LL * LL / 1000000
        Vmax = 0.5 * Lx * LL / 1000
        # 正截面受弯计算
        h0 = h - a_s
        xb = 0.518
        as1 = y0 * M * 1000000 / (fc * 1000 * h0 * h0)
        x1 = 1 - math.sqrt(1 - 2 * as1)  # 计算相对受压区高度
        As = fc * b * h0 * x1 / fy
        p = As / (b * h)
        Asmin = pmin * b * h
        # 梁计算参数
        ast = 35
        asb = 35
        Lh0 = Lh - asb
        Wt = Lb * Lb * (3 * Lh0 - Lb) / 6
        bcor = Lb - 50
        hcor = Lh - ast - asb
        Acor = bcor * hcor
        ucor = 2 * (bcor + hcor)

        if bool_beam == '是':  # 梁截面设计
            allow1 = 0.25 * 1 * fc
            allow2 = 0.2 * 1 * fc
            allow3 = allow1 * (6 - Lh0 / Lb) / 2 + allow2 * (Lh0 / Lb - 4)
            result1 = Vmax * 1000 / (Lb * Lh0) + Tmax * 1000000 / (0.8 * Lb * Lb * (3 * Lh - Lb) / 6)
            result2 = Vmax * 1000 / (Lb * Lh0) + Tmax * 1000000 / (Lb * Lb * (3 * Lh - Lb) / 6)
            allow4 = 0.7 * ft
            bt = 1.5 / (1 + 0.5 * Vmax * Wt / (Tmax * 1000 * Lb * Lh0))

            x = 2 * ast
            AsL = (Mmax - 1 * fc * Lb * x * (Lh0 - x / 2)) / (fy * (Lh0 - ast))
            AsLmin = 0.002 * Lb * Lh
        else:
            pass

        # 文本生成
        document = Document()
        document.styles['Normal'].font.name = 'Times New Roman'  # 默认西体
        document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')  # 默认中体
        document.styles['Normal'].font.size = Pt(10.5)  # 正文全局大小为10.5 小五
        document.styles['Heading 1'].font.size = Pt(14)  # 一级标题字体大小14 四号
        document.styles['Heading 1'].font.bold = True  # 加粗
        document.styles['Heading 2'].font.size = Pt(12)
        document.styles['Heading 2'].font.bold = True

        run = document.add_heading('悬挑板计算书', level=1)  # 标题
        run.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER

        document.add_heading('一、构件编号：' + name, level=2)  # 一、计算信息
        document.add_heading('二、计算信息', level=2)  # 计算信息
        document.add_paragraph('1. 几何参数\n        截面类型：矩形\n        截面宽度：b=' + str(b) + 'mm\n        截面高度：h=' + str(h) + 'mm')
        document.add_paragraph('2. 材料信息\n        混凝土等级：' + concrete_g + '  fc=' + str(fc) + 'N/mm\u00b2    ft=' + str(ft) + 'N/mm\u00b2\n        钢筋种类：' + steel_g + '   fy=' + str(fy) + 'N/mm\u00b2\n        最小配筋率：ρmin=' + str(pmin * 100) + '%\n        纵筋合力点至近边距离：as=' + str(a_s) + 'mm')
        document.add_paragraph('3. 设计参数\n        结构重要性系数：γo=' + str(y0))

        document.add_heading('三、荷载计算', level=2)  # 荷载计算
        document.add_paragraph('1. 恒载\n        板面及板底恒载DL=' + str(dl) + 'kN/m\u00b2\n        板端弯矩标准值Md=1/2*(25*h/1000+dl)*l\u00b2/10^6=' + str('%.1f' % Md) + 'kN.m\n        板端剪力标准值Vd=(h/1000*25+dl)*l/1000=' + str('%.1f' % Vd) + 'kN')
        document.add_paragraph('2. 活载\n        板面活载LL=' + str(ll) + 'kN/m\u00b2\n        板端弯矩标准值Ml=1/2*(25*h/1000+ll)*l\u00b2/10^6=' + str('%.1f' % Ml) + 'kN.m\n        板端剪力标准值Vl=(h/1000*25+ll)*l/1000=' + str('%.1f' % Vl) + 'kN')
        document.add_paragraph('3. 翻边\n        均布线荷载BL=' + str(bl) + 'kN/m\u00b2\n        板端弯矩标准值Mb=bl*l/1000=' + str('%.1f' % Mb) + 'kN.m\n        板端剪力标准值Vb=bl=' + str('%.1f' % Vb) + 'kN')
        document.add_paragraph('4. 荷载组合\n        弯矩设计值M=1.3*(Md+Mb)+1.5*Ml=' + str('%.1f' % M) + 'kN.m\n        剪力设计值V=1.3*(Vd+Vb)+1.5*Vl=' + str('%.1f' % V) + 'kN')
        if bool_beam == 'y':
            document.add_paragraph('5. 内梁\n        折算每米均布线荷载Lx=V=' + str(Lx) + 'kN/m\n        折算每米扭矩荷载LT/m=M+Lx*Lb/2/1000=' + str('%.1f' % LTm) + 'kN.m/m\n        梁中最大扭矩Tmax=LT/m*LL/2/1000=' + str('%.1f' % Tmax) + 'kN.m\n        梁中最大弯矩Mmax=1/8*Lx*LL\u00b2/10^6=' + str('%.1f' % Mmax) + 'kN.m\n        梁端最大剪力Vmax=1/2*Lx*LL/1000=' + str('%.1f' % Vmax) + 'kN')
        else:
            pass

        document.add_heading('四、板正截面受弯计算', level=2)  # 板正截面受弯计算
        document.add_paragraph('1. 计算截面有效高度:\n        ho=h-as=' + str(h) + '-' + str(a_s) + '=' + str(h0) + 'mm')
        document.add_paragraph('2. 计算相对受压区高度:\n        ξb=β1/(1+fy/(Es×εcu))=0.8/(1+' + str(fy) + '/(2×10^5×0.0033))=' + str(xb))
        document.add_paragraph('3. 确定计算系数:\n        αs=γo*M/(α1*fc*b*ho*ho)=' + str('%.1f' % y0) + '*' + str('%.1f' % M) + '*10^6/(1.0*' + str(fc) + '*1000*' + str(b) + '*' + str(h0) + '*' + str(h0) + ')=' + str('%.1f' % as1))
        document.add_paragraph('4. 计算相对受压区高度:\n        ξ=1-sqrt(1-2αs)=1-sqrt(1-2*' + str('%.1f' % as1) + ')=' + str('%.3f' % x1) + '≤ξb=0.518    满足要求。')
        document.add_paragraph('5. 计算纵向受拉钢筋面积:\n        As＝α1*fc*b*ho*ξ/fy=1.0*' + str(fc) + '*' + str(b) + '*' + str(h0) + '*' + str('%.3f' % x1) + '/' + str(fy) + '=' + str('%.1f' % As) + 'mm\u00b2')
        document.add_paragraph('6. 验算最小配筋率:\n        ρ=As/(b*h)=' + str('%.1f' % As) + '/(' + str(b) + '*' + str(h) + ')=' + str('%.2f' % (p * 100)) + '%')
        if p < pmin:
            document.add_paragraph('       ρ=' + str('%.2f' % (p * 100)) + '%<ρmin=' + str('%.2f' % (pmin * 100)) + '%，不满足最小配筋率要求，\n        取As=ρmin*b*h=' + str('%.2f' % (pmin * 100)) + '%*' + str(b) + '*' + str(h) + '=' + str('%.2f' % Asmin) + 'mm\u00b2')
            As = Asmin
        else:
            document.add_paragraph('       ρ=' + str('%.2f' % (p * 100)) + '%>ρmin=' + str('%.2f' % (pmin * 100)) + '%，满足最小配筋率要求。')

        Aspj = self.AspjText.get()
        Asmj = self.AsmjText.get()
        document.add_heading('五、板配筋', level=2)  # 板配筋
        document.add_paragraph('       实配为' + Aspj + '，实际配筋面积为' + Asmj + 'mm\u00b2。')

        if bool_beam == '是':
            document.add_heading('六：内梁计算', level=2)  # 内梁弯剪扭计算
# 1. 已知条件
            document.add_paragraph('1. 已知条件及计算要求：\n（1）已知条件：\n        计算截面：矩形梁    Lb=' + str(Lb) + 'mm,Lh=' + str(Lh) + 'mm。\n        砼等级：' + concrete_g + '，fc=' + str(fc) + 'N/mm\u00b2，ft=' + str(ft) + 'N/mm\u00b2\n        纵筋等级：' + steel_g + '，fy=' + str(fy) + 'N/mm\u00b2，fy\'=' + str(fy) + 'N/mm\u00b2\n        箍筋等级：' + steel_g + '，fy=' + str(fy) + 'N/mm\u00b2。')
            document.add_paragraph('      弯矩设计值M=' + str('%.1f' % Mmax) + 'kN.m，剪力设计值V=' + str('%.1f' % Vmax) + 'kN，扭矩设计值T=' + str('%.1f' % Tmax) + 'kN.m。')
            document.add_paragraph('（2）计算要求：\n        1）正截面受弯承载力计算\n        2）斜截面受剪承载力计算\n        3）受扭承载力计算')
# 2. 截面特征量计算
            document.add_paragraph('2. 截面特征量计算：\n        Wt=Lb*Lb*(3*Lh0-Lb)/6=' + str(Lb) + '*' + str(Lb) + '*(3*' + str(Lh0) + '-' + str(Lb) + ')/6=' + str('%.1f' % Wt) + 'mm^3\n        bcor=Lb-50=' + str(Lb) + '-50=' + str(bcor) + 'mm\n        hcor=Lh-as上-as下=' + str(Lh) + '-' + str(ast) + '-' + str(asb) + '=' + str(hcor) + 'mm\n        Acor=bcor*hcor=' + str(bcor) + '*' + str(hcor) + '=' + str(Acor) + 'mm\u00b2\n        ucor=2(bcor+hcor)=2*(' + str(bcor) + '+' + str(hcor) + ')=' + str(ucor) + 'mm')
# 3. 截面尺寸复核
            document.add_paragraph('3. 截面尺寸复核：')
            if Lh0 / Lb <= 4:
                document.add_paragraph('        Lh0/Lb=' + str('%.1f' % (Lh0 / Lb)) + '<4\n        Vmax/(Lb*h0)+Tmax/Wt=' + str('%.2f' % result1) + 'N/mm\u00b2<\n                0.25*βc*fc=' + str(0.25 * 1 * fc) + 'N/mm\u00b2\n        截面尺寸复核要求。')
            else:
                document.add_paragraph('        4<Lh0/Lb=' + str('%.1f' % (Lh0 / Lb)) + '<6\n        Vmax/(Lb*h0)+Tmax/(0.8*Lb*Lb*(3*Lh-Lb)/6)=' + str('%.2f' % result1) + 'N/mm\u00b2\n                <(6-Lh0/Lb)/2*0.25*1*fc)+(Lh0/Lb-4)*(0.2*1*fc)=' + str('%.2f' % allow3) + 'N/mm\u00b2\n        截面尺寸符合要求。')
# 4. 是否按剪扭计算
            document.add_paragraph('4. 是否需按剪扭计算:')
            if result2 < allow4:
                document.add_paragraph('        Vmax/(Lb*Lh0)+Tmax/Wt=' + str('%.1f' % Vmax) + '*1000/(' + str(Lb) + '*' + str(Lh0) + ')+' + str('%.1f' % Tmax) + '*1000000/' + str('%.1f' % Wt) + '=' + str('%.1f' % result2) + '\n                <0.7ft=0.7*' + str(ft) + '=' + str('%.1f' % allow4) + 'N/mm\u00b2\n        满足要求，可不进行构件受减扭承载力计算，但需满足规范构造要求。')
                tkinter.messagebox.showinfo('本计算小程序仅针对需要按剪扭计算进行计算，若不需要，可将第6.7节剪扭计算部分删除')
            else:
                document.add_paragraph('        Vmax/(Lb*Lh0)+Tmax/Wt=' + str('%.1f' % Vmax) + '*1000/(' + str(Lb) + '*' + str(Lh0) + ')+' + str('%.1f' % Tmax) + '*1000000/' + str('%.1f' % Wt) + '=' + str('%.1f' % result2) + '\n                >0.7ft=0.7*' + str(ft) + '=' + str('%.1f' % allow4) + 'N/mm\u00b2\n        需进行构件受减扭承载力计算。')
    # 5. 双筋梁正截面受弯计算
            document.add_paragraph('5. 正截面受弯承载力计算：\n（1）按双筋计算：as下=' + str(asb) + 'mm，as上=' + str(ast) + 'mm\n        假设采用上下对称配筋，则x=(fy*As-fy\'*As\')/(α1*fc*Lb)=0\n        则x≤ξb*Lh0，且需x≥2*a\'，所以取x=2*' + str(ast) + '=' + str(2 * ast) + 'mm\n        As=As\'=(M-α1*fc*Lb*x*(Lh0-x/2))/(fy\'*(Lh0-as\'))=(' + str('%.1f' % M) + '-1.0*' + str(fc) + '*' + str(Lb) + '*' + str(2 * ast) + '*(' + str(Lh0) + '-' + str(2 * ast) + '/2))/(' + str(fy) + '*(' + str(Lh0) + '-' + str(ast) + '))=' + str('%.1f' % AsL) +
                                'mm\u00b2\n（2）构造要求：非抗震ρmin=0.20%，Asmin=0.2%*' + str(Lb) + '*' + str(Lh) + '=' + str(AsLmin) + 'mm\u00b2')
            if AsL <= AsLmin:
                document.add_paragraph('（3）配筋面积：As = ' + str('%.1f' % AsL) + '≤Asmin=' + str(AsLmin) + 'mm\u00b2\n        需As=As\'=' + str(AsLmin) + 'mm\u00b2')
                AsL = AsLmin
            else:
                document.add_paragraph('（3）配筋面积：As = ' + str('%.1f' % AsL) + '>Asmin=' + str(AsLmin) + 'mm\u00b2\n        需As=As\'=' + str('%.1f' % AsL) + 'mm\u00b2')
    # 6. 确定箍筋
            if bt < 0.5:
                document.add_paragraph('6. 确定受剪及受扭箍筋\n（1）受扭所需箍筋量\n        计算剪扭构件受扭承载力降低系数βt\n        βt=1.5/(1+0.5*(V*Wt/(T*Lb*Lh0))=' + str('%.1f' % bt) + '<0.5\n        故取βt=0.5')
                bt = 0.5
            elif bt > 1:
                document.add_paragraph('6. 确定受剪及受扭箍筋\n（1）受扭所需箍筋量\n        计算剪扭构件受扭承载力降低系数βt\n        βt=1.5/(1+0.5*(V*Wt/(T*Lb*Lh0))=' + str('%.1f' % bt) + '>1.0\n        故取βt=1')
                bt = 1
            else:
                document.add_paragraph('6. 确定受剪及受扭箍筋\n（1）受扭所需箍筋量\n        计算剪扭构件受扭承载力降低系数βt\n        βt=1.5/(1+0.5*(V*Wt/(T*Lb*Lh0))=' + str('%.1f' % bt) + '>0.5且<1')
            Ast1_st = (Tmax * 1000000 - 0.35 * bt * ft * Wt) / (1.2 * math.sqrt(1.2) * fy * Acor)
            document.add_paragraph('        令配筋强度比ζ=1.2\n        Ast1/st=(T-0.35*βt*ft*Wt)/(1.2*sqrt(ζ)*fyv*Acor)=' + str('%.1f' % (Ast1_st * 100)) + 'mm\u00b2/100mm')
            nAsv1_sv = (Vmax - 0.7 * (1.5 - bt) * ft * Lb * Lh0) / (1.25 * fy * Lh0)
            Asv_s = nAsv1_sv / 2 + Ast1_st
            psvmin = 0.28 * ft / fy
            Asvmin_s = psvmin * Lb / 2
            if nAsv1_sv > 0:
                document.add_paragraph('（2）受剪所需箍筋数量\n        nAsv1/sv=(V-0.7(1.5-βt)*ft*Lb*Lh0)/(1.25*fyv*Lh0)=' + str('%.1f' % (nAsv1_sv * 100)) + 'mm\u00b2/100mm\n        按照双肢箍考虑，n=2,则单肢箍总的箍筋用量为\n        Asv1\"/s=Asv1/sv+Ast1/st=' + str('%.1f' % (Asv_s * 100)) + 'mm\u00b2/100mm\n        最小配箍率验算：\n        ρsv,min=0.28*ft/fy=' + str('%.2f' % (psvmin * 100)) + '%\n        单肢箍最小配箍面积：\n        Asv,min/s=ρsv,min*b/n=' + str('%.1f' % (Asvmin_s * 100)) + 'mm\u00b2/100mm')
            else:
                Asv_s = Ast1_st
                document.add_paragraph('（2）受剪所需箍筋数量\n        nAsv1/sv=(V-0.7(1.5-βt)*ft*Lb*Lh0)/(1.25*fyv*Lh0)=' + str('%.1f' % (nAsv1_sv * 100)) + 'mm\u00b2/100mm<0取0\n        按照双肢箍考虑，n=2,则单肢箍总的箍筋用量为\n        Asv1\"/s=Asv1/sv+Ast1/st=' + str('%.1f' % (Asv_s * 100)) + 'mm\u00b2/100mm\n        最小配箍率验算：\n        ρsv,min=0.28*ft/fy=' + str('%.2f' % (psvmin * 100)) + '%\n        单肢箍最小配箍面积：\n        Asv,min/s=ρsv,min*b/n=' + str('%.1f' % (Asvmin_s * 100)) + 'mm\u00b2/100mm')
            if Asv_s < Asvmin_s:
                document.add_paragraph('        因为Asv1\"/s<Asv,min/s,\n        故取Asv1\"/s=Asv,min/s=' + str('%.2f' % (psvmin * 100)) + 'mm\u00b2/100mm')
                Asv_s = Asvmin_s
            else:
                document.add_paragraph('        因此Asv1\"/s>Asv,min/s,满足最小配筋率要求。')
            Astl = 1.2 * fy * ucor / fy * (Ast1_st)
            # 7. 计算抗扭纵筋用量
            document.add_paragraph('7. 计算抗扭纵筋用量\n        Astl=ζ*fyv*ucor/fy*(Ast1/st)=' + str(int(Astl)) + 'mm\u00b2\n        抗扭纵筋最小配筋率：')
            T_Vb = Tmax * 1000 / Vmax / Lb
            if T_Vb < 2:
                document.add_paragraph('        T/(V*b)=' + str('%.1f' % T_Vb) + '<2')
            else:
                document.add_paragraph('        T/(V*b)=' + str('%.1f' % T_Vb) + '≥2，取T/(V*b)=2')
            ptlmin = 0.6 * math.sqrt(Tmax * 1000 / (Vmax * Lb)) * ft / fy
            Atlmin = ptlmin * Lb * Lh
            document.add_paragraph('        ρtl,min=0.6*sqrt(T/(V*b))*ft/fy=' + str('%.1f' % (ptlmin * 100)) + '%\n        抗扭纵筋最小配筋面积：Atl,min=ρtl,min*Lb*Lh=' + str(int(Atlmin)) + 'mm\u00b2')
            if Astl > Atlmin:
                document.add_paragraph('        因此Astl>Atl,min，满足最小配筋率要求。')
            else:
                document.add_paragraph('        因为Astl<Atl,min,故取Astl=Atl,min=' + str(int(Atlmin)))
                Astl = Atlmin
    # 8. 梁配筋
            document.add_paragraph('8.梁配筋')
            document.add_paragraph('        箍筋计算面积：Asv/s=' + str(int (Asv_s * 100)) + 'mm\u00b2/100mm')
            LAsvspj = self.LAsvspjText.get()
            Lasvsmj = self.LasvsmjText.get()
            document.add_paragraph('        选用：' + LAsvspj + '\n        实际Asv/s=' + Lasvsmj + 'mm\u00b2')
            document.add_paragraph('        顶部及底部纵筋计算面积：As=As\'=' + str(int( AsL)) + 'mm\u00b2')
            LAspj = self.LAspjText.get()
            Lasmj = self.LAsmjText.get()
            document.add_paragraph('        选用：' + LAspj + '\n        实际As=As\'=' + Lasmj + 'mm\u00b2')
            document.add_paragraph('        抗扭纵筋计算面积：Astl=' + str(int(AsL)) + 'mm\u00b2')
            LAstlpj = self.LAstlpjText.get()
            Lastlmj = self.LAstlmjText.get()
            document.add_paragraph('        选用：' + LAstlpj + '\n        实际Astl=' + Lastlmj + 'mm\u00b2')

        for paragraph in document.paragraphs:
            paragraph_format = paragraph.paragraph_format
            paragraph_format.space_before = Pt(0)
            paragraph_format.space_after = Pt(0)
            paragraph_format.line_spacing = Pt(18)

        document.save(name + '.docx')
        tkinter.messagebox.showinfo('Congratrulations!','计算书已成功导出！')

def gui_start():
    init_window = style.master              #实例化出一个父窗口
    ZMJ_PORTAL = MY_GUI(init_window)
    # 设置根窗口默认属性
    ZMJ_PORTAL.set_init_window()

    init_window.mainloop()          #父窗口进入事件循环，可以理解为保持窗口运行，否则界面不展示

gui_start()


from sqlalchemy import create_engine, desc
from sqlalchemy.orm import sessionmaker
from draft_kings_db import models, db_data

class DraftKingsHistory(object):
    def __init__(
        self,
        db_url='sqlite:///:memory:',
        verbose=False
    ):
        self.most_recent_data = None
        if verbose:
            self.verbose = True
        else:
            self.verbose = False

        engine = create_engine(db_url)
        models.Base.metadata.create_all(engine)
        Session = sessionmaker(bind=engine)
        self.session = Session()

    def __del__(self):
        self.session.close()

    def initialize_nba(self, to_date=None, from_date=None):
        self.most_recent_data = db_data.retrieve_data(
            self.session,
            self.verbose,
            to_date=to_date,
            from_date=from_date,
        )
        print('Retrieved data from {} to {}'.format(
            from_date or db_data.DB_START,
            to_date or self.most_recent_data,
        ))

    def lookup_nba_performances(self, name=None, date=None, limit=5):
        query = self.session.query(models.NBAPerformance)

        if name:
            query = query.filter(models.NBAPerformance.name == name)
        if date:
            query = query.filter(models.NBAPerformance.date == date)

        query = query.order_by(desc(models.NBAPerformance.date))
        return query.limit(limit) if limit else query.all()


#!/usr/bin/env python
# coding: utf-8

# In[12]:

import findspark
findspark.init()

# In[13]:

import pyspark
import random
from pyspark.sql import SQLContext
from pyspark.sql.types import  (StructType,
                                StructField,
                                DateType,
                                BooleanType,
                                DoubleType,
                                IntegerType,
                                StringType,
                               TimestampType)

# In[14]:

emp_schema = StructType([StructField("ID", StringType(), True),
                            StructField("Name", StringType(), True),
                            StructField("age", StringType(), True ),
                            StructField("City", StringType(), True)
                            ])
schema_lst = ["Id","Name","age","city"]

# In[31]:

spark = pyspark.SparkContext.getOrCreate()
words = spark.textFile("/home/cgt_jpr_lin_nikhil/nikhil/spark/data/emp.txt")
print(type(words))
#print(words.getNumPartitions())
rdd_new = words.collect
print(type(rdd_new))

# In[16]:

# function to convert RDD to dataframe
def RDD_to_df(sqlContext,df,schema):

  # converting RDD to df using createDataframe()
  # in which we are passing RDD and schema of df
  df1 = sqlContext.createDataFrame(df,schema)
  return df1

# In[26]:

sqlContext = SQLContext(spark)
converted_df = RDD_to_df(sqlContext,words,emp_schema)
print(converted_df.first)

# In[24]:

print(type(words))
converted_df.show()

# In[ ]:

# In[ ]:

# In[ ]:


import json
import typer

from ksql import KSQLAPI
from modules.models import Field
from modules.openlineage_help import DatasetHelper
from modules.schema_helper import SchemaHelper
from modules.openlineage_help import OpenLineage, TopicDataset
from modules.rest_helper import *
from modules.helpers import Helpers
import apicurioregistryclient
from apicurioregistryclient.api import artifacts_api
from apicurioregistryclient.model.if_exists import IfExists
from apicurioregistryclient.model.artifact_type import ArtifactType
from apicurioregistryclient.model.configuration_property import ConfigurationProperty
from apicurioregistryclient.model.error import Error
from apicurioregistryclient.model.log_configuration import LogConfiguration
from apicurioregistryclient.model.named_log_configuration import NamedLogConfiguration
from apicurioregistryclient.model.role_mapping import RoleMapping
from apicurioregistryclient.model.rule import Rule
from apicurioregistryclient.model.rule_type import RuleType
from apicurioregistryclient.model.update_configuration_property import UpdateConfigurationProperty
from apicurioregistryclient.model.update_role import UpdateRole

app = typer.Typer()

@app.command()
def list():
    """
    Lists all the domains in the data mesh
    """
    typer.echo(f"listing all domains")

@app.command()
def describe(domain_id: str):
    """
    Describes a domain including location, owners, and published data products and ids
    """
    typer.echo(f"describing item: {domain_id}")

@app.command()
def request(domain_id: str, data_product: str):
    """
    Requests access to a data product by the current (your) domain.
    """
    profile, config = Helpers.get_config()
    p = config['profiles'][profile]['prop']
    client = KSQLAPI(f"http://{p['ksql']['rest']}")
    desc = client.ksql(f'describe {data_product} extended')[0]

@app.command()
def link(domain_id:str, data_product:str):
    cl_resp, cluster_id = create_link(domain_id=domain_id)
    mirror_resp = mirror_topic(
        data_product=data_product,
        domain_id=domain_id,
        cluster_id=cluster_id)

    results = {
        "link": cl_resp,
        "mirror": mirror_resp
    }
    typer.echo(results)

def mirror_topic(data_product:str, domain_id:str, cluster_id:str):
    profile, config = Helpers.get_config()
    # Enter a context with an instance of the API client
    # configuration = apicurioregistryclient.Configuration(
    #     host = config['apicurio']
    # )
    # with apicurioregistryclient.ApiClient(configuration) as api_client:
    #     api_instance = artifacts_api.ArtifactsApi(api_client)

    #     try:
    #         search_response = api_instance.search_artifacts(name=data_product)
    #         # api_response = api_instance.create_artifact(
    #         #     group_id=profile,
    #         #     body=yaml,
    #         #     x_registry_artifact_id=desc['sourceDescription']['topic'],
    #         #     if_exists=IfExists("RETURN_OR_UPDATE"),
    #         #     _content_type="application/x-yaml",
    #         #     x_registry_artifact_type=ArtifactType("ASYNCAPI"))
    #         typer.echo(search_response)
    #     except apicurioregistryclient.ApiException as e:
    #         print("Exception: %s\n" % e)

    data = {
        "source_topic_name": f"{data_product}",
        "configs": [
            {
                "name": "unclean.leader.election.enable",
                "value": "true"
            }
        ],
        "replication_factor": 1
    }
    headers = {"Content-Type": "application/json; charset=utf-8"}
    link_name = f"{domain_id}_{profile}"
    rest_proxy = config['profiles'][profile]['prop']['kafka']['rest.proxy']
    mirror_resp = post(url=f"http://{rest_proxy}/v3/clusters/{cluster_id}/links/{link_name}/mirrors",
        data=data,
        headers=headers)

    topic = data_product
    ol = OpenLineage(profile=profile, sdm_config=config)
    run = ol.get_run(facet={
        "name":f"link.{link_name}",
        "type":"source",
        "mirror":mirror_resp
    })
    job = ol.get_job(namespace=profile, name=link_name, facets={
        "name":f"link.{link_name}",
        "type":"source",
        "mirror":mirror_resp
    })

    fields = get_fields_from_apicurio(config['apicurio'], topic)

    src_facet = DatasetHelper.get_facet(fields=fields)

    src_topic_dataset:TopicDataset = TopicDataset(topic=topic, namespace=domain_id, name=f"topic.{topic}", facets=src_facet)
    dst_topic_dataset:TopicDataset = TopicDataset(topic=topic, namespace=profile, name=f"topic.{topic}", facets=src_facet)
    ol_response = ol.emit_run(inputs=[src_topic_dataset], outputs=[dst_topic_dataset], job=job, run=run)

    print(ol_response)

def get_fields_from_apicurio(apicurio_host:str, topic:str):
    # Enter a context with an instance of the API client
    configuration = apicurioregistryclient.Configuration(
        host = apicurio_host
    )
    with apicurioregistryclient.ApiClient(configuration) as api_client:
        api_instance = artifacts_api.ArtifactsApi(api_client)
        try:
            api_response = api_instance.get_content_by_global_id(
                global_id=1)
            data = json.loads(api_response.raw.read())
            props = data['components']['schemas'][topic]['properties']
            fields = [ { "name":k, "type":props[k]['type']} for k in props.keys()]
            typer.echo(fields)
            return fields
        except apicurioregistryclient.ApiException as e:
            print("Exception: %s\n" % e)
            raise e

def create_link(domain_id:str):
    profile, config = Helpers.get_config()
    rest_proxy = config['profiles'][profile]['prop']['kafka']['rest.proxy']
    cluster_id = json.loads(get(f'http://{rest_proxy}/v3/clusters').text)['data'][0]['cluster_id']
    control_plane_url = config['url']
    source_config = json.loads(get(f'{control_plane_url}/{domain_id}').text)
    source_clusters = json.loads(get(f"http://{source_config['prop']['kafka']['rest.proxy']}/v3/clusters").text)
    source_cluster_id = source_clusters['data'][0]['cluster_id']
    data = {
        "source_cluster_id": f"{source_cluster_id}",
        "configs": [
            {
                "name": "bootstrap.servers",
                "value": f"{source_config['prop']['kafka']['bootstrap.servers']}"
            },
            {
                "name": "acl.sync.enable",
                "value": "false"
            },
            {
                "name": "consumer.offset.sync.ms",
                "value": "30000"
            }
        ]
    }
    link_name = f"{domain_id}_{profile}"
    headers = {"Content-Type": "application/json; charset=utf-8"}
    rest_proxy = config['profiles'][profile]['prop']['kafka']['rest.proxy']
    create_resp = post(url=f'http://{rest_proxy}/v3/clusters/{cluster_id}/links?link_name={link_name}',
                        data=data,
                        headers=headers)
    return (create_resp, cluster_id)

if __name__ == "__main__":
    app()


import mimetypes
import werkzeug
from functools import wraps

from flask import Flask, send_file, request, Response, render_template
from flask.ext.restful import Api, Resource, reqparse, fields, marshal_with
from flask_cors import CORS
from werkzeug.exceptions import Unauthorized

from image_service.storage import *

CONFIG_STORAGE_DIR = 'STORAGE_DIRECTORY'

app = Flask(__name__)
app.config.from_pyfile('../config.py', silent=True)
api = Api(app)
cors = CORS(app, resources={r'/*': {'origins': '*'}})

_storage = None

@app.after_request
def add_header(response):
    response.headers['Access-Control-Allow-Headers'] = ', '.join((
            'Origin',
            'X-Requested-With',
            'Content-Type',
            'Accept',
            'Cache-Control',
            'Authorization'
    ))
    return response

def storage():
    """returns access to the storage (save_image(), get() and exists())"""
    global _storage
    if not _storage:
        _storage = FileSystemStorage(app.config[CONFIG_STORAGE_DIR])
    return _storage

def _serve_image(image_file, extension):
    mime_type = mimetypes.types_map['.%s' % extension.lower()]
    return send_file(image_file, mimetype=mime_type, add_etags=False)

def _check_auth_token(origin, token):
    if 'AUTH_TOKEN' in app.config and app.config['AUTH_TOKEN'] != '':
        expected_origin, expected_token = app.config['AUTH_TOKEN']
        return (expected_origin == '*' or expected_origin == origin) and expected_token == token

def _check_auth_basic(username, password):
    if 'AUTH_BASIC' in app.config and app.config['AUTH_BASIC'] != '':
        correct_user, correct_pass = app.config['AUTH_BASIC']
        return username == correct_user and password == correct_pass

@app.route('/')
def index():
    if app.config['ENABLE_DEMO']:
        return render_template('demo.html')
    return Response('Nothing to see here ;)', 404)

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        # check if it has auth token
        auth_header = request.headers.get('Authorization')
        origin = request.headers.get('Origin')
        if auth_header is not None:
            if auth_header.startswith('Token'):
                # get the origin header
                key, token = auth_header.split(' ')
                if _check_auth_token(origin, token):
                    return f(*args, **kwargs)
            if auth_header.startswith('Basic'):
                auth = request.authorization
                if _check_auth_basic(auth.username, auth.password):
                    return f(*args, **kwargs)
        raise Unauthorized()
    return decorated

def _upload_json_response(success, **kwargs):
    res_dict = dict(status='ok' if success else 'fail')
    res_dict.update(kwargs)
    code = 201 if success else 500
    return res_dict, code

def serve_image(project_name, name, extension, mode=None, size=None):
    if project_name not in app.config['PROJECTS']:
        raise NotFound()
    return _serve_image(project_name, name, extension, mode, size)

class UploadResponse:
    resource_fields = {
        'url': fields.String
    }

class UploadAPI(Resource):
    """
    API that supports POST for images.
    """
    decorators = [requires_auth]

    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('file', type=werkzeug.datastructures.FileStorage, required=True,
                                   help='No file provided', location='files')
        super(UploadAPI, self).__init__()

    @marshal_with(UploadResponse.resource_fields)
    def post(self):
        args = self.reqparse.parse_args()
        uploaded_file = args['file']
        filename, extension = secure_filename(uploaded_file.filename).rsplit(
            '.', 1)
        filename = storage().safe_name(filename, extension)
        storage().save(filename, extension, uploaded_file.read())
        url = api.url_for(ImageAPI, name=filename, extension=extension)
        return {'url': url}, 201

class ImageAPI(Resource):
    """
    API that supports GET, PUT and DELETE for images.
    """

    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('file', type=werkzeug.datastructures.FileStorage, required=True,
                                   help='No file provided', location='files')
        super(ImageAPI, self).__init__()

    @requires_auth
    def put(self, name, extension):
        args = self.reqparse.parse_args()
        uploaded_file = args['file']
        created = not storage().exists(name, extension)
        storage().save(name, extension, uploaded_file.read())
        return Response('', 201 if created else 200)

    @requires_auth
    def delete(self, project, name, extension):
        if storage().exists(project, name, extension):
            storage().delete(project, name, extension)
            return Response('', 200)
        raise NotFound()

    def get(self, name, extension):
        image = storage().get(name, extension)
        return _serve_image(image, extension)

class ManipulatedImageAPI(Resource):
    """
    API that supports GET for manipulated images.
    """

    def get(self, name, mode, width, height, extension):
        try:
            image = storage().get(name, extension, mode, (int(width), int(height)))
        except ValueError:
            raise NotFound()
        return _serve_image(image, extension)

api.add_resource(UploadAPI, '/images/')
api.add_resource(ImageAPI, '/images/<name>.<extension>')
api.add_resource(ManipulatedImageAPI, '/images/<name>@<mode>-<width>x<height>.<extension>')


import docker

base_url='unix://var/run/docker.sock'

def find_container(needle):
    cli = docker.APIClient(base_url='unix://var/run/docker.sock',version='auto')
    for container in cli.containers():
        for name in container['Names']:
            if needle in name:
                return container
    return False


import re
import requests
import sys

def get(url):
    html=str(requests.get(url).text)
    end_point, dependent, independent = [], [".png",".jpg",".wav",".jpeg",".json",".js",".php",".xml"], ["http://","https://","file://","php://","ftp://","./","../","/"]
    for i in [idk.split("\\")[0] for idk in re.split(f"'|\"|,|\*|\n|[|]", html) if idk.split("\\")[0] != ""]:
        if not i:
            pass
        else:
            for de in independent:
                if i.startswith(de): end_point.append(i)
            for ind in dependent:
                if i.endswith(ind):
                    if i[0] == "/": end_point.append(f"{url}{i}")
                    else: end_point.append(f"{url}/{i}")
    ik = []
    for idk in [item for item in end_point if item != []]:
        if idk[0] == "/": ik.append(f"{url}{idk}")
        else: ik.append(idk)
    return ik


# -*- coding: UTF-8 -*-
"""
title: 有序数组中的缺失元素
Given an integer array nums which is sorted in ascending order and all of its elements are unique and given also an integer k, return the kth missing number starting from the leftmost number of the array.

Example 1:
Input: nums = [4,7,9,10], k = 1
Output: 5
Explanation: The first missing number is 5.

Example 2:
Input: nums = [4,7,9,10], k = 3
Output: 8
Explanation: The missing numbers are [5,6,8,...], hence the third missing number is 8.

Example 3:
Input: nums = [1,2,4], k = 3
Output: 6
Explanation: The missing numbers are [3,5,6,7,...], hence the third missing number is 6.

Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^7
nums is sorted in ascending order, and all the elements are unique.
1 <= k <= 10^8

Follow up: Can you find a logarithmic time complexity (i.e., O(log(n))) solution?
"""
from typing import List

class Solution:
    def missingElement(self, nums: List[int], k: int) -> int:
        """线性扫描。时间复杂度为O(n)"""
        # 使用lambda定义一个方法，该方法会返回nums[0] ~ nums[idx]之间缺失的数字个数
        missing_cnt = lambda idx: nums[idx] - nums[0] - idx
        n = len(nums)
        if k > missing_cnt(n - 1):
            return nums[n - 1] + k - missing_cnt(n - 1)
        idx = 0
        # 顺序查找最后一个小于k的missing_cnt(idx)
        while missing_cnt(idx + 1) < k:
            idx += 1
        return nums[idx] + k - missing_cnt(idx)

    def missingElement_2(self, nums: List[int], k: int) -> int:
        """二分查找。时间复杂度为O(logn)"""
        # 使用lambda定义一个方法，该方法会返回nums[0] ~ nums[idx]之间缺失的数字个数
        missing_cnt = lambda idx: nums[idx] - nums[0] - idx
        n = len(nums)
        # 二分查找最后一个小于k的missing_cnt(idx)
        left, right = 0, n - 1
        while left < right:
            mid = (left + right + 1) // 2
            if missing_cnt(mid) >= k:
                right = mid - 1
            else:
                left = mid
        return nums[left] + k - missing_cnt(left)

if __name__ == '__main__':
    print(Solution().missingElement_2(nums=[4, 7, 9, 10], k=3))


import numpy as np
import matplotlib.pyplot as plt

def main():

    # our system definition - vanilla second order system
    A = np.matrix([[1, 0.1], [0, 1]])
    B = np.matrix([[0], [0.1]])

    # penalty for position, velocity
    Q = np.matrix([[5, 0], [0, 1]])

    # penalty for controls
    R = np.matrix([[0.1]])

    # run for 100 timesteps
    T = 100

    ##################################################
    # pre-compute my K, V matrices

    Kmats = [ np.matrix([[0, 0]]) ]

    V = Q
    Vmats = [ V ]

    for i in range(T-1):

        K = np.linalg.inv( B.T * V * B + R ) * B.T * V * A

        ABthing = A - B*K
        V = Q + K.T * R * K + ABthing.T * V * ABthing

        Kmats.insert(0, K)
        Vmats.insert(0, V)

    plt.plot([Ki[0,0] for Ki in Kmats], label='pos gain (kp)')
    plt.plot([Ki[0,1] for Ki in Kmats], label='vel gain (kd)')

    plt.legend()
    plt.xlabel('Timestep')
    plt.ylabel('Gain value')
    plt.title('Optimized gains from LQR')
    plt.show()

    '''
    ##################################################
    # simulate the system

    # for each timestep
    for i in range(T):

        # append the current state
        qdata.append(q)

        # compute a control
        u = -K_fixed*q

        # append the next state
        q = A*q + B*u

    # plot the trajectory
    qdata = np.array(qdata)
    plt.plot(qdata[:,0])
    plt.xlabel('Timestep')
    plt.ylabel('Position (m)')
    plt.title('Non-optimal control')
    plt.show()
    '''

if __name__ == '__main__':
    main()


# blast_integration.py
from Bio.Blast import NCBIWWW
from Bio.Blast import NCBIXML

class BlastIntegration:
    def __init__(self):
        pass

    def run_blast(self, sequence):
        try:
            # Perform a BLAST search using NCBI's online service
            result_handle = NCBIWWW.qblast("blastn", "nt", sequence)

            # Parse the BLAST results
            blast_record = NCBIXML.read(result_handle)

            # Process and analyze the BLAST results as needed
            # For simplicity, we'll just print the alignment descriptions here
            alignments = blast_record.alignments
            if alignments:
                for alignment in alignments:
                    print("Alignment Title:", alignment.title)

            result_handle.close()
        except Exception as e:
            print("Error running BLAST:", str(e))

if __name__ == "__main__":
    # Example usage of the BlastIntegration class
    sequence_to_search = "AGCTACGTA"  # Replace with your actual sequence
    blast = BlastIntegration()
    blast.run_blast(sequence_to_search)


### To Run : "python3 a b c" , where 'a' is the method, 'b' is the function number and 'c' represent de dimension to the function

import matplotlib.pyplot as plt
import sys

names = ["elDE", "elDE_SHADE","elDE_EDM", "elDE_EDM_v2"]

method = names[int(sys.argv[1])-1]
func_num = sys.argv[2]
dimension = int(sys.argv[3])

name = "Resumen_"+method+"_"+func_num+"_"+str(dimension)+".txt"

X = [ i for i in range(4000) ]
Y = [ [] for i in range(dimension) ]

for line in open(name, 'r'):
    values = line.split()
    k = 2
    for j in range(dimension):
        Y[j].append(float(values[k]))
        k = k + 2

plt.title("SD")
plt.ylabel(r'$SD( \overrightarrow{x_i})$')
plt.xlabel('iterations')

k = 1
for y in Y:
    name = "x" + str(k)
    y = y[0:int(sys.argv[4])]
    X = X[0:int(sys.argv[4])]
    plt.plot(X, y , label = name )
    k = k + 1

nameOutout = "Graphs/"+method+"_"+func_num+"_"+str(dimension)+".png"
plt.legend( loc = 'upper right')
plt.savefig(nameOutout)


# imports and setup
import numpy as np
import os.path
import scipy.io
from loadmat import loadmat

import matplotlib as mpl
default_dpi = mpl.rcParamsDefault['figure.dpi']
mpl.rcParams['figure.dpi'] = default_dpi*2
import matplotlib.pyplot as plt

# load gulfport campus image
img_fname = 'muufl_gulfport_campus_w_lidar_1.mat'
spectra_fname = 'tgt_img_spectra.mat'

dataset = loadmat(img_fname)['hsi']

hsi = dataset['Data'][:,:,4:-4] # trim noisy bands
valid_mask = dataset['valid_mask'].astype(bool)
n_r,n_c,n_b = hsi.shape
wvl = dataset['info']['wavelength'][4:-4]
rgb = dataset['RGB']

# extract some endmembers using Pixel Purity Index algorithm
#  using PySptools from https://pysptools.sourceforge.io
import pysptools
import pysptools.eea

hsi_array = np.reshape(hsi,(n_r*n_c,n_b))
valid_array = np.reshape(valid_mask,(n_r*n_c,))
M = hsi_array[valid_array,:]
q = 3
numSkewers = 500
E,inds = pysptools.eea.eea.PPI(M, q, numSkewers)

# plot the endmembers we found
plt.plot(wvl,E.T)
plt.xlabel('wavelength (nm)')
plt.ylabel('reflectance')
plt.legend([str(i+1) for i in range(q)])
plt.title("PPI Endmembers")

# find abundances given the endmembers
import pysptools.abundance_maps

maps = pysptools.abundance_maps.amaps.FCLS(M, E)
#maps = np.zeros((M.shape[0],E.shape[1]))

# re-ravel abundance maps
map_imgs = []
for i in range(q):
    map_lin = np.zeros((n_r*n_c,))
    map_lin[valid_array] = maps[:,i]
    map_imgs.append(np.reshape(map_lin,(n_r,n_c)))

# display abundance maps
for i in range(q):
    plt.figure()
    plt.imshow(map_imgs[i],vmin=0,vmax=1)
    plt.colorbar()
    plt.title('FCLS Abundance Map %d'%(i+1,))

	# run SPICE to find number of endmembers, endmembers, and abundances simultaneously
from SPICE import *

params = SPICEParameters()
inputData = M.T.astype(float)
# to save time, downsample inputData
dsData = inputData[:,::20]
dsData.shape

# run SPICE
[eM,dsP] = SPICE(dsData,params)

# unmix endmembers again with full data matrix (because we downsampled for sake of time)
P = unmix2(inputData,eM)
n_em = eM.shape[1]

#plot endmembers
plt.plot(wvl,eM)
plt.xlabel('wavelength (nm)')
plt.ylabel('reflectance')
plt.legend([str(i+1) for i in range(5)])
plt.title('SPICE Endmembers')

# re-reval abundance maps
P_imgs = []
for i in range(n_em):
    map_lin = np.zeros((n_r*n_c,))
    map_lin[valid_array] = P[:,i]
    P_imgs.append(np.reshape(map_lin,(n_r,n_c)))

	# display abundance maps
for i in range(n_em):
    plt.figure()
    plt.imshow(P_imgs[i],vmin=0,vmax=1)
    plt.colorbar()
    plt.title('SPICE Abundance Map %d'%(i+1,))


import argparse
import logging
import os
import sys
import pyqtgraph as pg
from PyQt5 import QtGui
from PyQt5.QtOpenGL import *
from PyQt5 import QtCore, Qt
from PyQt5.Qt import *
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from pyqtgraph.Qt import QtGui, QtCore
from PyQt5.QtGui import QFont
from brainflow.board_shim import BoardShim, BrainFlowInputParams, BoardIds
from brainflow.data_filter import DataFilter, FilterTypes, DetrendOperations
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
from random import randint

class graph_win(QMainWindow):
    def __init__(self, board_shim):
        super(graph_win, self).__init__()
        self.board_id = board_shim.get_board_id()
        self.board_shim = board_shim
        self.eeg_channels = BoardShim.get_eeg_channels(self.board_id)
        self.sampling_rate = BoardShim.get_sampling_rate(self.board_id)
        self.update_speed_ms = 50
        self.window_size = 4
        self.num_points = self.window_size * self.sampling_rate

        #region Initial layout
        styles = {'color': 'black', 'font-size': '16px'}
        self.setWindowTitle('Main Window')
        self.setGeometry(0, 0, 1500, 900)

        self.vLayout = QVBoxLayout()
        self.hLayout = QHBoxLayout()
        self.gridLayout = QGridLayout()
        self.vLayout.addLayout(self.hLayout)
        self.vLayout.addLayout(self.gridLayout)

        self.vLayout.setContentsMargins(10, 10, 10, 10)
        self.hLayout.setContentsMargins(10, 10, 10, 10)
        self.vLayout.setSpacing(10)
        self.hLayout.setSpacing(10)

        self.widget = QWidget()
        self.widget.setLayout(self.vLayout)
        self.setCentralWidget(self.widget)
        #endregion

        #region Buttons
        self.button1 = QPushButton('Channel 1')
        self.button2 = QPushButton('Channel 2')
        self.button3 = QPushButton('Channel 3')
        self.button4 = QPushButton('Channel 4')

        self.button1.setFixedSize(80, 30)
        self.button2.setFixedSize(80, 30)
        self.button3.setFixedSize(80, 30)
        self.button4.setFixedSize(80, 30)

        self.button1.setCheckable(True)
        self.button2.setCheckable(True)
        self.button3.setCheckable(True)
        self.button4.setCheckable(True)

        self.button1.clicked.connect(self.update_plot_data)
        self.button2.clicked.connect(self.update_plot_data)
        self.button3.clicked.connect(self.update_plot_data)
        self.button4.clicked.connect(self.update_plot_data)

        self.button1.setStyleSheet("background-color : lightgrey")
        self.button2.setStyleSheet("background-color : lightgrey")
        self.button3.setStyleSheet("background-color : lightgrey")
        self.button4.setStyleSheet("background-color : lightgrey")

        self.hLayout.addWidget(self.button1)
        self.hLayout.addWidget(self.button2)
        self.hLayout.addWidget(self.button3)
        self.hLayout.addWidget(self.button4)
        #endregion

        #region Graphs
        self.graphWidget1 = pg.PlotWidget()
        self.graphWidget1.setTitle('Channel 1', **styles)
        self.graphWidget1.setLabel('left', 'Amplitude', **styles)
        self.graphWidget1.setLabel('bottom', 'Time', **styles)
        self.graphWidget1.setBackground('w')
        self.gridLayout.addWidget(self.graphWidget1, 0, 0)

        self.graphWidget2 = pg.PlotWidget()
        self.graphWidget2.setTitle('Channel 2', **styles)
        self.graphWidget2.setLabel('left', 'Amplitude', **styles)
        self.graphWidget2.setLabel('bottom', 'Time', **styles)
        self.graphWidget2.setBackground('w')
        self.gridLayout.addWidget(self.graphWidget2, 1, 0)

        self.graphWidget3 = pg.PlotWidget()
        self.graphWidget3.setTitle('Channel 3', **styles)
        self.graphWidget3.setLabel('left', 'Amplitude', **styles)
        self.graphWidget3.setLabel('bottom', 'Time', **styles)
        self.graphWidget3.setBackground('w')
        self.gridLayout.addWidget(self.graphWidget3, 2, 0)

        self.graphWidget4 = pg.PlotWidget()
        self.graphWidget4.setTitle('Channel 4', **styles)
        self.graphWidget4.setLabel('left', 'Amplitude', **styles)
        self.graphWidget4.setLabel('bottom', 'Time', **styles)
        self.graphWidget4.setBackground('w')
        self.gridLayout.addWidget(self.graphWidget4, 3, 0)
        #endregion

        pen = pg.mkPen(color=(255, 0, 0))
        self.x = list(range(100))
        self.y = [0] * 100
        self.data_line1 = self.graphWidget1.plot(self.x, self.y, pen=pen)
        self.data_line2 = self.graphWidget2.plot(self.x, self.y, pen=pen)
        self.data_line3 = self.graphWidget3.plot(self.x, self.y, pen=pen)
        self.data_line4 = self.graphWidget4.plot(self.x, self.y, pen=pen)

        self.timer = QtCore.QTimer()
        self.timer.setInterval(100)
        self.timer.timeout.connect(self.update_plot_data)
        self.timer.start()

    def update_plot_data(self):
        data = self.board_shim.get_current_board_data(self.num_points)

        if self.button1.isChecked():
            pass
        else:
            # what does this do?
            # DataFilter.detrend(data[0], DetrendOperations.CONSTANT.value)
            # append for y? and which index is for channel 1?
            self.x = self.x[1:]
            self.x.append(self.x[-1] + 1)
            # self.y = self.y[1:]
            # self.y.append(randint(0, 100))
            self.y = data[self.eeg_channels[0]].tolist()
            self.data_line1.setData(self.y)

        if self.button2.isChecked():
            pass
        else:
            self.x = self.x[1:]
            self.x.append(self.x[-1] + 1)
            self.y = data[self.eeg_channels[1]].tolist()
            self.data_line2.setData(self.y)

        if self.button3.isChecked():
            pass
        else:
            self.x = self.x[1:]
            self.x.append(self.x[-1] + 1)
            self.y = data[self.eeg_channels[2]].tolist()
            self.data_line3.setData(self.y)

        if self.button4.isChecked():
            pass
        else:
            self.x = self.x[1:]
            self.x.append(self.x[-1] + 1)
            self.y = data[self.eeg_channels[3]].tolist()
            self.data_line4.setData(self.y)

        # self.app.processEvents()

def main():
    BoardShim.enable_dev_board_logger()
    logging.basicConfig(level=logging.DEBUG)

    parser = argparse.ArgumentParser()
    parser.add_argument('--timeout', type=int, help='timeout for device discovery or connection', required=False,
                        default=0)
    parser.add_argument('--ip-port', type=int, help='ip port', required=False, default=0)
    parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False,
                        default=0)
    parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='')
    parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='COM4')
    parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='')
    parser.add_argument('--other-info', type=str, help='other info', required=False, default='')
    parser.add_argument('--streamer-params', type=str, help='streamer params', required=False, default='')
    parser.add_argument('--serial-number', type=str, help='serial number', required=False, default='')
    parser.add_argument('--board-id', type=int, help='board id, check docs to get a list of supported boards',
                        required=False, default=BoardIds.CYTON_BOARD)
    parser.add_argument('--file', type=str, help='file', required=False, default='')
    args = parser.parse_args()

    params = BrainFlowInputParams()
    params.ip_port = args.ip_port
    params.serial_port = args.serial_port
    params.mac_address = args.mac_address
    params.other_info = args.other_info
    params.serial_number = args.serial_number
    params.ip_address = args.ip_address
    params.ip_protocol = args.ip_protocol
    params.timeout = args.timeout
    params.file = args.file

    try:
        board_shim = BoardShim(args.board_id, params)
        board_shim.prepare_session()
        board_shim.start_stream(450000, args.streamer_params)
        app = QtWidgets.QApplication(sys.argv)
        main = graph_win(board_shim)
        main.show()
        data = board_shim.get_board_data()
        print(data)
        sys.exit(app.exec())
    except BaseException:
        logging.warning('Exception', exc_info=True)
    finally:
        logging.info('End')
        if board_shim.is_prepared():
            logging.info('Releasing session')
            board_shim.release_session()

if __name__ == '__main__':
    main()


import psycopg2 as ps
import config

def exec_query(query: str) -> list:
    with ps.connect(dbname=config.db_name, user=config.user) as conn:
        with conn.cursor() as cur:
            cur.execute(query)
            res = cur.fetchall()
    return res


import sqlparse

from database_access import DatabaseAccess
from function_generator import FunctionGenerator
from parse_cte import parse_cte, PipelineType
from stream import construct_insert_function_name

def create_continuous_view(plpy, cv_name: str, query: str) -> None:
    # wrap plpy object
    db = DatabaseAccess(plpy)

    # register continuous view, will fail if another view with the same name exists
    db.continuous_views_insert(cv_name)

    # extract common table expressions and the actual query (ordering of the ctes does not change)
    parsed_query = sqlparse.parse(query)
    query_string, ctes = parse_cte(parsed_query)

    upper_pipelines = []

    # new schema for the view (add to search path allows to use same table names)
    db.create_schema(f'cv_{cv_name}')
    db.add_to_search_path(f'cv_{cv_name}')

    for cte_name, cte in ctes.items():
        pipeline_name = f'cv_{cv_name}.{cte_name}'

        if cte.pipeline_type == PipelineType.STREAM:
            stream_name = cte.get_stream()

            # construct the insert function for the stream
            function_name = construct_insert_function_name(stream_name)

            # create an auxiliary table for aggregates
            db.create_stream_pipeline(pipeline_name, cte.query.normalized)

            # store stream query for later use
            db.stream_pipelines_insert(cv_name, stream_name, pipeline_name, function_name, cte.query.normalized)

            # if we group by attributes create an index on the primary keys
            if len(cte.primary_keys()) > 0:
                db.create_index(f'cv_{cv_name}_{cte_name}_index', pipeline_name, cte.primary_keys())

            # construct the insert function for the stream
            declarations, body = FunctionGenerator().generate_stream_insert_function(f'cv_{cv_name}', stream_name,
                                                                                pipeline_name, cte)

            # create insert function
            db.create_insert_function(function_name, stream_name, declarations, body)

        elif cte.pipeline_type == PipelineType.STATIC:
            # evaluate static pipelines and save them
            db.create_static_pipeline(pipeline_name, cte.query.normalized)
            # create index on static pipeline
            if len(cte.keys_for_index()) > 0:
                db.create_index(f'cv_{cv_name}_{cte_name}_index', pipeline_name, cte.keys_for_index())

        elif cte.pipeline_type == PipelineType.UPPER:
            # merge all upper pipelines
            upper_pipelines.append(cte)

    # create query from all upper pipelines
    db.create_upper_pipeline(f'cv.{cv_name}', upper_pipelines, query_string)

def create_continuous_view_from_file(plpy, cv_name: str, filename: str) -> None:
    # read file (replace all newlines)
    file = open(filename, 'r')
    query = ' '.join(file.read().replace('\n', ' ').split())
    create_continuous_view(plpy, cv_name, query)


# %% --------------------------------------- Imports -------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.optimizers import Adam
from sklearn.metrics import accuracy_score
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.initializers import glorot_uniform

# %% ----------------------------------- Hyper Parameters --------------------------------------------------------------
LR = 0.2
N_NEURONS = 2
N_EPOCHS = 3000

# %% ----------------------------------- Helper Functions --------------------------------------------------------------
def acc(x, y):
    """ Simple function to get the accuracy. The label with the highest prob is chosen """
    # model.evaluate can also be used, this is just to illustrate the argmax operation
    probs = model.predict(x)  # (n_examples, n_labels) --> Need to operate on columns, so axis=1 on argmax
    pred_labels = np.argmax(probs, axis=1)
    return 100*accuracy_score(np.argmax(y, axis=1), pred_labels)  # Uses argmax again to come back from one-hot-encoded

# %% -------------------------------------- Data Prep ------------------------------------------------------------------
p = np.array([[0, 0], [1, 1], [0, 1], [1, 0]])
t = np.array([0, 0, 1, 1])
# One-hot-encodes the targets to use the softmax and categorical cross-entropy performance index
t = to_categorical(t, num_classes=2)

# %% -------------------------------------- Training Prep --------------------------------------------------------------
model = Sequential([
    Dense(N_NEURONS, input_dim=2, kernel_initializer=glorot_uniform(42)),
    Activation("sigmoid"),
    Dense(2, kernel_initializer=glorot_uniform(42)),  # Output layer with softmax to map to the two classes
    Activation("softmax")
])
# Compiles using categorical cross-entropy performance index and tracks the accuracy during training
model.compile(optimizer=Adam(lr=LR), loss="categorical_crossentropy", metrics=["accuracy"])

# %% -------------------------------------- Training Loop --------------------------------------------------------------
model.fit(p, t, batch_size=len(p), epochs=N_EPOCHS)

# %% -------------------------------------- Check Approx ---------------------------------------------------------------
print("The MLP accuracy is", acc(p, t), "%")
# Gets the weights and biases from the first layer
w, b = model.layers[0].get_weights()
# Gets some points on the interval [0, 1] and the two decision boundaries
a = np.arange(0, 1.1, 0.1)
db1 = -w[0, 0]*a/w[1, 0] - b[0]/w[1, 0]  # Note than on Keras the shape of the weight matrix
db2 = -w[0, 1]*a/w[1, 1] - b[1]/w[1, 1]  # is RxS (n_inputs x n_neurons)
# Plots the points and the decision boundaries
plt.scatter(p[:2, 0], p[:2, 1], marker="*", c="b")
plt.scatter(p[2:, 0], p[2:, 1], marker=".", c="b")
plt.plot(a, db1, c="b")
plt.plot(a, db2, c="b")

plt.show()


import numpy as np
from utils.datasets import DataLoader
from evaluation.wrapper import WrapperEvaluation
from fitness.function import WrapperFitnessFunction

class SubsetSizePenalty(WrapperFitnessFunction):
    """
    Objective function that penalizes large subsets of features.

    Rashid, A.N.M Bazlur, et al. "A novel penalty-based wrapper objective function for feature
    selection in Big Data using cooperative co-evolution." IEEE Access 8 (2020): 150113-150129.

    Attributes
    ----------
    w1: float
        Predictive performance weight.
    w2: float
        Penalty weight.
    """

    def __init__(self, evaluator: WrapperEvaluation, weights: list):
        super().__init__(evaluator)
        # Check the number of weights
        if len(weights) != 2:
            raise AssertionError(
                f"'{SubsetSizePenalty.__name__}' fitness function has only two components "
                "(predictive performance and penalty). Therefore, it requires only two weights."
            )
        # Check the sum of the weights
        if sum(weights) != 1:
            raise AssertionError(
                f"The sum of weights is {sum(weights)} but must be 1."
            )
        self.w1 = weights[0]
        self.w2 = weights[1]

    def evaluate(self, context_vector: np.ndarray, data: DataLoader):
        """
        Evaluate the given context vector using the fitness function.

        Parameters
        ----------
        context_vector: np.ndarray
            Solution of the complete problem.
        data: DataLoader
            Container with process data and training and test sets.

        Returns
        -------
        fitness: float
            Quality of the context vector.
        """
        penalty = context_vector.sum()/data.n_features
        evaluations = self._evaluate_predictive_performance(context_vector, data)
        evaluation = evaluations[self.evaluator.eval_function]
        fitness = self.w1*evaluation - self.w2*penalty
        return fitness


from ssdaq.data import MonitorData
import datetime
import os
import zmq
import asyncio

class ReceiverMonSender:
    def __init__(self, name, loop, zmqcontext):
        """Summary

        Args:
            name (TYPE): Description
            loop (TYPE): Description
            zmqcontext (TYPE): Description
        """
        # monitoring socket
        self._context = zmqcontext
        self._monitor_sock = self._context.socket(zmq.PUSH)
        self._monitor_sock.connect("tcp://127.0.0.101:10002")
        self.total_data_counter = 0
        self.current_data_counter = 0
        self.got_data = False
        self.data_timeout = None
        self.mon_wait = 1.0
        self.name = name
        self.past = None
        loop.create_task(self.sendmon())
        self.loop = loop

    def register_data_packet(self):
        """Summary
        """
        self.total_data_counter += 1
        self.current_data_counter += 1
        self.got_data = True

    def _compute_rates(self):
        """Summary

        Returns:
            TYPE: Description
        """
        now = datetime.datetime.now().timestamp()

        if self.past is None:
            self.past = now
            self.current_data_counter = 0
            return
        dt = now - self.past
        self.past = now
        rate = self.current_data_counter / dt
        self.current_data_counter = 0

        return rate

    async def sendmon(self):
        """Summary
        """
        while True:
            await asyncio.sleep(self.mon_wait)

            mdata = MonitorData()
            # constructing timestamp
            tstamp = datetime.datetime.utcnow().timestamp()
            mdata.time.sec = int(tstamp)
            mdata.time.nsec = int((tstamp - mdata.time.sec) * 1e9)
            # Constructing monitoring message
            mdata.reciver.pid = os.getpid()
            mdata.reciver.name = self.name
            rate = self._compute_rates()
            if rate is None:
                continue
            mdata.reciver.data_rate = rate
            mdata.reciver.recv_data = self.got_data
            self.got_data = False
            # Putting it into a monitor data message

            self._monitor_sock.send(mdata.SerializeToString())


from dataclasses import dataclass
from typing import Optional

from app.store.bot.state import EventTypes

@dataclass
class Message:
    user_id: int
    peer_id: int
    text: str
    payload: Optional[dict]
    event_id: Optional[str]

    @classmethod
    def from_message_new(cls, message: dict) -> "Message":
        return cls(
            user_id=message["from_id"],
            peer_id=message["peer_id"],
            text=message["text"],
            payload=message["payload"] if "payload" in message.keys() else None,
            event_id=None,
        )

    @classmethod
    def from_message_event(cls, message: dict) -> "Message":
        if "payload" in message.keys():
            return cls(
                user_id=message["user_id"],
                peer_id=message["peer_id"],
                text=None,
                payload=message["payload"],
                event_id=message["event_id"],
            )

@dataclass
class UpdateObject:
    id: int
    body: Message

    @classmethod
    def from_message_new(cls, update_obj: dict) -> "UpdateObject":
        return cls(
            id=update_obj["message"]["id"],
            body=Message.from_message_new(update_obj["message"]),
        )

    @classmethod
    def from_message_event(cls, update_obj: dict) -> "UpdateObject":
        return cls(id=None, body=Message.from_message_event(update_obj))

@dataclass
class Update:
    type: str
    object: UpdateObject

    @classmethod
    def from_dict(cls, update: dict) -> "Update":
        if update["type"] == EventTypes.MESSAGE_NEW:
            return cls(
                type=update["type"],
                object=UpdateObject.from_message_new(update["object"]),
            )
        elif update["type"] == EventTypes.MESSAGE_EVENT:
            return cls(
                type=update["type"],
                object=UpdateObject.from_message_event(update["object"]),
            )

    @property
    def user_id(self):
        return self.object.body.user_id

    @property
    def peer_id(self):
        return self.object.body.peer_id

    @property
    def text(self):
        return self.object.body.text

    @property
    def payload(self):
        return self.object.body.payload


from typing import Dict, List, Optional
import torch
from fairseq.distributed import fsdp_wrap
from fairseq.models import (
    register_model,
    register_model_architecture,
)
from fairseq.models.transformer.transformer_config import (
    TransformerConfig,
    DEFAULT_MAX_SOURCE_POSITIONS,
    DEFAULT_MAX_TARGET_POSITIONS,
    DEFAULT_MIN_PARAMS_TO_WRAP,
)
import math
import torch.nn as nn
from fairseq.models.transformer import (
    TransformerModel,
    TransformerEncoder,
    TransformerDecoder
)
from fairseq.modules import (
    FairseqDropout,
    LayerDropModuleList,
    LayerNorm,
    PositionalEmbedding,
    SinusoidalPositionalEmbedding,
)
from fairseq.modules import transformer_layer, TransformerEncoderLayer
from fairseq.modules.checkpoint_activations import checkpoint_wrapper
from fairseq.modules.quant_noise import quant_noise as apply_quant_noise_
from torch import Tensor

# rewrite name for backward compatibility in `make_generation_fast_`
def module_name_fordropout(module_name: str) -> str:
    if module_name == 'TransformerEncoderBase':
        return 'TransformerEncoder'
    else:
        return module_name

class T5TransformerEncoderLayer(TransformerEncoderLayer):
    """Encoder layer block.

    In the original paper each operation (multi-head attention or FFN) is
    postprocessed with: `dropout -> add residual -> layernorm`. In the
    tensor2tensor code they suggest that learning is more robust when
    preprocessing each layer with layernorm and postprocessing with:
    `dropout -> add residual`. We default to the approach in the paper, but the
    tensor2tensor approach can be enabled by setting
    *cfg.encoder.normalize_before* to ``True``.

    Args:
        args (argparse.Namespace): parsed command-line arguments
    """

    def __init__(self, args, dictionary, embed_tokens):
        super().__init__(args, dictionary, embed_tokens)

    def forward(
            self,
            x,
            encoder_padding_mask: Optional[Tensor],
            attn_mask: Optional[Tensor] = None,
    ):
        """
        Args:
            x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
            encoder_padding_mask (ByteTensor): binary ByteTensor of shape
                `(batch, seq_len)` where padding elements are indicated by ``1``.
            attn_mask (ByteTensor): binary tensor of shape `(tgt_len, src_len)`,
                where `tgt_len` is the length of output and `src_len` is the
                length of input, though here both are equal to `seq_len`.
                `attn_mask[tgt_i, src_j] = 1` means that when calculating the
                embedding for `tgt_i`, we exclude (mask out) `src_j`. This is
                useful for strided self-attention.

        Returns:
            encoded output of shape `(seq_len, batch, embed_dim)`
        """
        # anything in original attn_mask = 1, becomes -1e8
        # anything in original attn_mask = 0, becomes 0
        # Note that we cannot use -inf here, because at some edge cases,
        # the attention weight (before softmax) for some padded element in query
        # will become -inf, which results in NaN in model parameters
        if attn_mask is not None:
            attn_mask = attn_mask.masked_fill(
                attn_mask.to(torch.bool),
                -1e8 if x.dtype == torch.float32 else -1e4
            )

        residual = x
        if self.normalize_before:
            x = self.self_attn_layer_norm(x)
        x, _ = self.self_attn(
            query=x,
            key=x,
            value=x,
            key_padding_mask=encoder_padding_mask,
            need_weights=False,
            attn_mask=attn_mask,
        )
        x = self.dropout_module(x)
        x = self.residual_connection(x, residual)
        if not self.normalize_before:
            x = self.self_attn_layer_norm(x)

        residual = x
        if self.normalize_before:
            x = self.final_layer_norm(x)
        x = self.activation_fn(self.fc1(x))
        x = self.activation_dropout_module(x)
        x = self.fc2(x)
        x = self.dropout_module(x)
        x = self.residual_connection(x, residual)
        if not self.normalize_before:
            x = self.final_layer_norm(x)
        return x

class T5TransformerEncoder(TransformerEncoder):
    """
    Transformer encoder consisting of *cfg.encoder.layers* layers. Each layer
    is a :class:`TransformerEncoderLayer`.

    Args:
        args (argparse.Namespace): parsed command-line arguments
        dictionary (~fairseq.data.Dictionary): encoding dictionary
        embed_tokens (torch.nn.Embedding): input embedding
    """

    def __init__(self, cfg, dictionary, embed_tokens):
        self.cfg = cfg
        super().__init__(dictionary)
        self.register_buffer("version", torch.Tensor([3]))

        self.dropout_module = FairseqDropout(
            cfg.dropout, module_name=module_name_fordropout(self.__class__.__name__)
        )
        self.encoder_layerdrop = cfg.encoder.layerdrop

        embed_dim = embed_tokens.embedding_dim
        self.padding_idx = embed_tokens.padding_idx
        self.max_source_positions = cfg.max_source_positions

        self.embed_tokens = embed_tokens

        self.embed_scale = 1.0 if cfg.no_scale_embedding else math.sqrt(embed_dim)

        self.embed_positions = (
            PositionalEmbedding(
                cfg.max_source_positions,
                embed_dim,
                self.padding_idx,
                learned=cfg.encoder.learned_pos,
            )
            if not cfg.no_token_positional_embeddings
            else None
        )
        if cfg.layernorm_embedding:
            self.layernorm_embedding = LayerNorm(embed_dim, export=cfg.export)
        else:
            self.layernorm_embedding = None

        if not cfg.adaptive_input and cfg.quant_noise.pq > 0:
            self.quant_noise = apply_quant_noise_(
                nn.Linear(embed_dim, embed_dim, bias=False),
                cfg.quant_noise.pq,
                cfg.quant_noise.pq_block_size,
            )
        else:
            self.quant_noise = None

        if self.encoder_layerdrop > 0.0:
            self.layers = LayerDropModuleList(p=self.encoder_layerdrop)
        else:
            self.layers = nn.ModuleList([])
        self.layers.extend(
            [self.build_encoder_layer(cfg) for i in range(cfg.encoder.layers)]
        )
        self.num_layers = len(self.layers)

        if cfg.encoder.normalize_before:
            self.layer_norm = LayerNorm(embed_dim, export=cfg.export)
        else:
            self.layer_norm = None

    def build_encoder_layer(self, args):
        return super().build_encoder_layer(
            TransformerConfig.from_namespace(args),
        )

    def forward_embedding(
            self, src_tokens, token_embedding: Optional[torch.Tensor] = None
    ):
        # embed tokens and positions
        if token_embedding is None:
            token_embedding = self.embed_tokens(src_tokens)
        x = embed = self.embed_scale * token_embedding
        if self.embed_positions is not None:
            x = embed + self.embed_positions(src_tokens)
        if self.layernorm_embedding is not None:
            x = self.layernorm_embedding(x)
        x = self.dropout_module(x)
        if self.quant_noise is not None:
            x = self.quant_noise(x)
        return x, embed

    # TorchScript doesn't support super() method so that the scriptable Subclass
    # can't access the base class model in Torchscript.
    # Current workaround is to add a helper function with different name and
    # call the helper function from scriptable Subclass.
    def forward_scriptable(
            self,
            src_tokens,
            src_lengths: Optional[torch.Tensor] = None,
            return_all_hiddens: bool = False,
            token_embeddings: Optional[torch.Tensor] = None,
    ):
        """
        Args:
            src_tokens (LongTensor): tokens in the source language of shape
                `(batch, src_len)`
            src_lengths (torch.LongTensor): lengths of each source sentence of
                shape `(batch)`
            return_all_hiddens (bool, optional): also return all of the
                intermediate hidden states (default: False).
            token_embeddings (torch.Tensor, optional): precomputed embeddings
                default `None` will recompute embeddings

        Returns:
            dict:
                - **encoder_out** (Tensor): the last encoder layer's output of
                  shape `(src_len, batch, embed_dim)`
                - **encoder_padding_mask** (ByteTensor): the positions of
                  padding elements of shape `(batch, src_len)`
                - **encoder_embedding** (Tensor): the (scaled) embedding lookup
                  of shape `(batch, src_len, embed_dim)`
                - **encoder_states** (List[Tensor]): all intermediate
                  hidden states of shape `(src_len, batch, embed_dim)`.
                  Only populated if *return_all_hiddens* is True.
        """
        # compute padding mask
        encoder_padding_mask = src_tokens.eq(self.padding_idx)
        has_pads = src_tokens.device.type == "xla" or encoder_padding_mask.any()

        x, encoder_embedding = self.forward_embedding(src_tokens, token_embeddings)

        self_attn_mask = self.build_self_attn_mask(src_tokens, bidirectional=True)
        # relative positions bias
        if self.relative_position is not None:
            rel_pos_bias = self.relative_position(
                batch_size=src_tokens.size(0),
                qlen=src_tokens.size(1),
                klen=src_tokens.size(1)
            )
            self_attn_mask = self_attn_mask.unsqueeze(0) + rel_pos_bias

        # account for padding while computing the representation
        if has_pads:
            x = x * (1 - encoder_padding_mask.unsqueeze(-1).type_as(x))

        # B x T x C -> T x B x C
        x = x.transpose(0, 1)

        encoder_states = []

        if return_all_hiddens:
            encoder_states.append(x)

        # encoder layers
        for layer in self.layers:
            x = layer(
                x,
                self_attn_mask=self_attn_mask,
                encoder_padding_mask=encoder_padding_mask if has_pads else None
            )
            if return_all_hiddens:
                assert encoder_states is not None
                encoder_states.append(x)

        if self.layer_norm is not None:
            x = self.layer_norm(x)

        # The Pytorch Mobile lite interpreter does not supports returning NamedTuple in
        # `forward` so we use a dictionary instead.
        # TorchScript does not support mixed values so the values are all lists.
        # The empty list is equivalent to None.
        src_lengths = src_tokens.ne(self.padding_idx).sum(dim=1, dtype=torch.int32).reshape(-1, 1).contiguous()
        return {
            "encoder_out": [x],  # T x B x C
            "encoder_padding_mask": [encoder_padding_mask],  # B x T
            "encoder_embedding": [encoder_embedding],  # B x T x C
            "encoder_states": encoder_states,  # List[T x B x C]
            "src_tokens": [],
            "src_lengths": [src_lengths],
        }

@register_model("t5_transformer")
class T5TransformerModel(TransformerModel):
    """
    This is the legacy implementation of the transformer model that
    uses argparse for configuration.
    """

    @classmethod
    def build_encoder(cls, args, src_dict, embed_tokens):
        return T5TransformerEncoder(TransformerConfig.from_namespace(args), src_dict, embed_tokens)

    @classmethod
    def build_decoder(cls, args, tgt_dict, embed_tokens):
        return super().build_decoder(
            TransformerConfig.from_namespace(args), tgt_dict, embed_tokens
        )

# architectures
@register_model_architecture("t5_transformer", "t5_transformer")
def t5_transformer_base_architecture(args):
    args.encoder_embed_path = getattr(args, "encoder_embed_path", None)
    args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
    args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048)
    args.encoder_layers = getattr(args, "encoder_layers", 6)
    args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8)
    args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
    args.encoder_learned_pos = getattr(args, "encoder_learned_pos", True)
    args.decoder_embed_path = getattr(args, "decoder_embed_path", None)
    args.decoder_embed_dim = getattr(args, "decoder_embed_dim", args.encoder_embed_dim)
    args.decoder_ffn_embed_dim = getattr(
        args, "decoder_ffn_embed_dim", args.encoder_ffn_embed_dim
    )
    args.decoder_layers = getattr(args, "decoder_layers", 6)
    args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8)
    args.decoder_normalize_before = getattr(args, "decoder_normalize_before", False)
    args.decoder_learned_pos = getattr(args, "decoder_learned_pos", True)
    args.attention_dropout = getattr(args, "attention_dropout", 0.0)
    args.activation_dropout = getattr(args, "activation_dropout", 0.0)
    args.activation_fn = getattr(args, "activation_fn", "relu")
    args.dropout = getattr(args, "dropout", 0.1)
    args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
    args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
    args.share_decoder_input_output_embed = getattr(
        args, "share_decoder_input_output_embed", False
    )
    args.share_all_embeddings = getattr(args, "share_all_embeddings", True)
    args.no_token_positional_embeddings = getattr(
        args, "no_token_positional_embeddings", False
    )
    args.adaptive_input = getattr(args, "adaptive_input", False)
    args.no_cross_attention = getattr(args, "no_cross_attention", False)
    args.cross_self_attention = getattr(args, "cross_self_attention", False)

    args.decoder_output_dim = getattr(
        args, "decoder_output_dim", args.decoder_embed_dim
    )
    args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)

    args.no_scale_embedding = getattr(args, "no_scale_embedding", False)
    args.layernorm_embedding = getattr(args, "layernorm_embedding", False)
    args.tie_adaptive_weights = getattr(args, "tie_adaptive_weights", False)
    args.checkpoint_activations = getattr(args, "checkpoint_activations", False)
    args.offload_activations = getattr(args, "offload_activations", False)
    if args.offload_activations:
        args.checkpoint_activations = True
    args.encoder_layers_to_keep = getattr(args, "encoder_layers_to_keep", None)
    args.decoder_layers_to_keep = getattr(args, "decoder_layers_to_keep", None)
    args.encoder_layerdrop = getattr(args, "encoder_layerdrop", 0)
    args.decoder_layerdrop = getattr(args, "decoder_layerdrop", 0)
    args.quant_noise_pq = getattr(args, "quant_noise_pq", 0)
    args.quant_noise_pq_block_size = getattr(args, "quant_noise_pq_block_size", 8)
    args.quant_noise_scalar = getattr(args, "quant_noise_scalar", 0)

@register_model_architecture("t5_transformer", "t5_transformer_base")
def t5_transformer_base(args):
    t5_transformer_base_architecture(args)

@register_model_architecture("t5_transformer", "t5_transformer_big")
def t5_transformer_big(args):
    args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1024)
    args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4096)
    args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 16)
    args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
    args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 1024)
    args.decoder_ffn_embed_dim = getattr(args, "decoder_ffn_embed_dim", 4096)
    args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 16)
    args.dropout = getattr(args, "dropout", 0.3)
    t5_transformer_base_architecture(args)


import os
import utils
import torch
import tqdm
import random
import matplotlib
import numpy as np
from torchvision import transforms
from evaluator.evaluator import KinshipEvaluator
from datasets.kinfacew_loader_gen import KinFaceWLoaderGenerator
from models.small_siamese_face_model import SmallSiameseFaceModel
from sklearn.metrics import accuracy_score
matplotlib.use('TkAgg')

seed = 990411
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(seed)
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)

dataset_name = "KinFaceW-I"
dataset_path = "/home/manuel/Documents/masters/Computer Vision/YGYME/data/"

model_path = f"logs/triplet_bn_auc/"
# model_path = f"logs/no_triplet_bn_auc/"
loader_gen = KinFaceWLoaderGenerator(dataset_name=dataset_name, dataset_path=dataset_path, color_space_name="rgb")

pair_type = "fd"
fold = 1
gpu_id = 0

# ms fold 3

device = torch.device(f"cuda:{gpu_id}" if torch.cuda.is_available() else "cpu")
# device = "cpu"
distances = list()

model = SmallSiameseFaceModel()
model.eval()
state_dict = torch.load(os.path.join(model_path, f"best_model_{pair_type}_fold_{fold}.pth"))
model.load_state_dict(state_dict)
model.to(device)
transformer = transforms.Compose([transforms.ToPILImage(),
                                  transforms.Resize((64, 64)),
                                  transforms.ToTensor()])

for fold in [1, 2, 3, 4, 5]:
    model = SmallSiameseFaceModel()
    model.eval()
    state_dict = torch.load(os.path.join(model_path, f"best_model_{pair_type}_fold_{fold}.pth"))
    model.load_state_dict(state_dict)
    model.to(device)

    loader_test, loader_train = loader_gen.get_data_loader(fold, 16, pair_type, transformer, transformer)

    evaluator = KinshipEvaluator(set_name="Training", pair=pair_type, log_path="logs/testing", fold=fold)
    evaluator.reset()
    parent_features = list()
    child_features = list()
    model_out = list()
    targets = list()

    for sample in tqdm.tqdm(loader_test, total=len(loader_test), desc=f"Val epoch {1}"):
        parent_image, children_image = sample["parent_image"].to(device), \
                                       sample["children_image"].to(device)
        labels = sample["kin"].to(device).float()
        output, p_f, c_f = model(parent_image.float(), children_image.float())
        output, p_f, c_f = output.squeeze(1), p_f.squeeze(1).detach().cpu().numpy(), c_f.squeeze(1).detach().cpu().numpy()
        parent_features.append(p_f)
        child_features.append(c_f)
        output = torch.sigmoid(output)
        model_out += list(output.detach().cpu().numpy())
        targets += list(labels.detach().cpu().numpy())
    best_threshold = utils.load_json(f"{model_path}/{pair_type}_testing_fold_{fold}.json")["best_threshold"]

    targets = np.array(targets)
    y_hat = np.zeros_like(model_out)
    y_hat[np.array(model_out) > 0.5338352918624878] = 1
    acc = accuracy_score(targets, y_hat)
    print("Accuracy ", acc)