#modulos
import main_edited as main
from tkinter import *
from tkinter import ttk, Tk, Frame, Menu
import tkinter as tk
from PIL import Image, ImageTk

#chama main
def chama(*args):
    m1=matg1var.get()
    m2=matg2var.get()
    m3=matg3var.get()
    m4=matg4var.get()
    f1=flug1var.get()
    f2=flug2var.get()
    f3=flug3var.get()
    f4=flug4var.get()
    ti1=Tempming1.get()
    ti2=Tempming2.get()
    ti3=Tempming3.get()
    ti4=Tempming4.get()
    ts1=Tempmaxg1.get()
    ts2=Tempmaxg2.get()
    ts3=Tempmaxg3.get()
    ts4=Tempmaxg4.get()
    tf1=Tempambg1.get()
    tf2=Tempambg2.get()
    tf3=Tempambg3.get()
    tf4=Tempambg4.get()
    vs1=estg1.get()
    if vs1 == 1:
        s1=txtg1.get()
    else:
        s1=formg1.get()
    vs2=estg2.get()
    if vs2 == 1:
        s2=txtg2.get()
    else:
        s2=formg2.get()
    vs3=estg3.get()
    if vs3 == 1:
        s3=txtg3.get()
    else:
        s3=formg3.get()
    vs4=estg4.get()
    if vs4 == 1:
        s4=txtg4.get()
    else:
        s4=formg4.get()

    if Tempxvar.get()==True :
        ts2=ts1
        ts3=ts1
        ts4=ts1
    if Tempmvar.get() == True :
        ti2=ti1
        ti3=ti1
        ti4=ti1
    if estvar.get() == True :
        vs2=vs1
        vs3=vs1
        vs4=vs1
        s2=s1
        s3=s1
        s4=s1
    if matvar.get() == True :
        m2=m1
        m3=m1
        m4=m1
    if fluvar.get() == True :
        f2=f1
        f3=f1
        f4=f1
    if Tempavar.get() == True :
        tf2=tf1
        tf3=tf1
        tf4=tf1

    main.simula(m1,m2,m3,m4,f1,f2,f3,f4,float(ti1),float(ti2),float(ti3),float(ti4),float(ts1),float(ts2),float(ts3),float(ts4),float(tf1),float(tf2),float(tf3),float(tf4),vs1,s1,vs2,s2,vs3,s3,vs4,s4)

#defs show/hide
def updatecheck():
    if Tempxvar.get()==True and Tempmvar.get() == True and estvar.get() == True and matvar.get() == True and fluvar.get() == True and Tempavar.get() == True:
        titulog1.configure(text="Chapas:", font=('Oswald',14))
        titulog2.grid_forget()
        titulog3.grid_forget()
        titulog4.grid_forget()
    else:
        titulog1.configure(text="Chapa 1:", font=('Oswald',14))
        titulog2.grid(column=0, row=5, sticky=(W))
        titulog3.grid(column=0, row=7, sticky=(W))
        titulog4.grid(column=0, row=9, sticky=(W))

    if Tempavar.get() == True:
        tempatitg2.grid_forget()
        Tempag2.grid_forget()

        tempatitg3.grid_forget()
        Tempag3.grid_forget()

        tempatitg4.grid_forget()
        Tempag4.grid_forget()
    else:
        tempatitg2.grid(column=2, row=0, pady=5)
        Tempag2.grid(column=3, row=0 )

        tempatitg3.grid(column=2, row=0, pady=5)
        Tempag3.grid(column=3, row=0 )

        tempatitg4.grid(column=2, row=0, pady=5)
        Tempag4.grid(column=3, row=0 )

    if Tempxvar.get() == True:
        tempxtitg2.grid_forget()
        Tempxg2.grid_forget()

        tempxtitg3.grid_forget()
        Tempxg3.grid_forget()

        tempxtitg4.grid_forget()
        Tempxg4.grid_forget()
    else:
        tempxtitg2.grid(column=2, row=1, pady=5)
        Tempxg2.grid(column=3, row=1 )

        tempxtitg3.grid(column=2, row=1, pady=5)
        Tempxg3.grid(column=3, row=1 )

        tempxtitg4.grid(column=2, row=1, pady=5)
        Tempxg4.grid(column=3, row=1 )

    if Tempmvar.get() == True:
        tempmtitg2.grid_forget()
        Tempmg2.grid_forget()

        tempmtitg3.grid_forget()
        Tempmg3.grid_forget()

        tempmtitg4.grid_forget()
        Tempmg4.grid_forget()
    else:
        tempmtitg2.grid(column=2, row=2, pady=5)
        Tempmg2.grid(column=3, row=2 )

        tempmtitg3.grid(column=2, row=2, pady=5)
        Tempmg3.grid(column=3, row=2 )

        tempmtitg4.grid(column=2, row=2, pady=5)
        Tempmg4.grid(column=3, row=2 )

    if estvar.get() == True:
        esttitg2.grid_forget()
        esttxtg2.grid_forget()
        estformg2.grid_forget()
        formtitg2.grid_forget()
        formentg2.grid_forget()
        txtentg2.grid_forget()
        txttitg2.grid_forget()

        esttitg3.grid_forget()
        esttxtg3.grid_forget()
        estformg3.grid_forget()
        formtitg3.grid_forget()
        formentg3.grid_forget()
        txtentg3.grid_forget()
        txttitg3.grid_forget()

        esttitg4.grid_forget()
        esttxtg4.grid_forget()
        estformg4.grid_forget()
        formtitg4.grid_forget()
        formentg4.grid_forget()
        txtentg4.grid_forget()
        txttitg4.grid_forget()
    else:
        esttitg2.grid(column=4, row=0, padx=5)
        esttxtg2.grid(column=4, row=1,padx=5)
        estformg2.grid(column=4, row=2,padx=5)

        esttitg3.grid(column=4, row=0, padx=5)
        esttxtg3.grid(column=4, row=1,padx=5)
        estformg3.grid(column=4, row=2,padx=5)

        esttitg4.grid(column=4, row=0, padx=5)
        esttxtg4.grid(column=4, row=1,padx=5)
        estformg4.grid(column=4, row=2,padx=5)

    if matvar.get() == True:
        matnameg2.grid_forget()
        matg2.grid_forget()

        matnameg3.grid_forget()
        matg3.grid_forget()

        matnameg4.grid_forget()
        matg4.grid_forget()
    else:
        matnameg2.grid(column=0, row=0)
        matg2.grid(column=0, row=1)

        matnameg3.grid(column=0, row=0)
        matg3.grid(column=0, row=1)

        matnameg4.grid(column=0, row=0)
        matg4.grid(column=0, row=1)

    if fluvar.get() == True:
        flunameg2.grid_forget()
        flug2.grid_forget()

        flunameg3.grid_forget()
        flug3.grid_forget()

        flunameg4.grid_forget()
        flug4.grid_forget()
    else:
        flunameg2.grid(column=1, row=0)
        flug2.grid(column=1, row=1, padx=10)

        flunameg3.grid(column=1, row=0)
        flug3.grid(column=1, row=1, padx=10)

        flunameg4.grid(column=1, row=0)
        flug4.grid(column=1, row=1, padx=10)

def updateg1():
    x1=estg1.get()
    if x1 == 1:
        formtitg1.grid_forget()
        formentg1.grid_forget()
        txtentg1.grid(column=5,row=1,padx=5)
        txttitg1.grid(column=5, row=0)
    if x1 == 2:
        txtentg1.grid_forget()
        txttitg1.grid_forget()
        formtitg1.grid(column=5,row=0)
        formentg1.grid(column=5,row=1,padx=5)

def updateg2():
    x2=estg2.get()
    if x2 == 1:
        formtitg2.grid_forget()
        formentg2.grid_forget()
        txtentg2.grid(column=5,row=1,padx=5)
        txttitg2.grid(column=5, row=0)
    if x2 == 2:
        txtentg2.grid_forget()
        txttitg2.grid_forget()
        formtitg2.grid(column=5,row=0)
        formentg2.grid(column=5,row=1,padx=5)

def updateg3():
    x3=estg3.get()
    if x3 == 1:
        formtitg3.grid_forget()
        formentg3.grid_forget()
        txtentg3.grid(column=5,row=1,padx=5)
        txttitg3.grid(column=5, row=0)
    if x3 == 2:
        txtentg3.grid_forget()
        txttitg3.grid_forget()
        formtitg3.grid(column=5,row=0)
        formentg3.grid(column=5,row=1,padx=5)

def updateg4():
    x4=estg4.get()
    if x4 == 1:
        formtitg4.grid_forget()
        formentg4.grid_forget()
        txtentg4.grid(column=5,row=1,padx=5)
        txttitg4.grid(column=5, row=0)
    if x4 == 2:
        txtentg4.grid_forget()
        txttitg4.grid_forget()
        formtitg4.grid(column=5,row=0)
        formentg4.grid(column=5,row=1,padx=5)

#defs Menu
def openProjeto():
    Projetowin = Toplevel(root)
    Projetowin.title("Sobre o projeto")
    projframe = ttk.Frame(Projetowin, padding=(5, 5, 10, 10))
    projframe.grid(column=0, row=0, sticky=(N,W,E,S))
    Projetowin.grid_columnconfigure(0, weight=1)
    Projetowin.grid_rowconfigure(0,weight=1)

    projtxt=ttk.Label(projframe, text ="Sobre o projeto em Python de um simulador de resfriamento de chapas finas")
    projtxt.grid(column=0,row=0)
    Projetowin.mainloop()

def openIntegrantes():
    Integranteswin = Toplevel(root)
    Integranteswin.title("Sobre os integrantes")
    inteframe = ttk.Frame(Integranteswin, padding=(5, 5, 10, 10))
    inteframe.grid(column=0, row=0, sticky=(N,W,E,S))
    Integranteswin.grid_columnconfigure(0, weight=1)
    Integranteswin.grid_rowconfigure(0,weight=1)

    projtxt=ttk.Label(inteframe, text ="Sobre os integrantes:\n Enzo \n Gabriela \n Lucas \n Matheus \n Pedro \n Rafael")
    projtxt.grid(column=0,row=0)
    Integranteswin.mainloop()

#interface
root=Tk()
root.title('Simulador de resfriamento de chapas finas')

mainframe = ttk.Frame(root, padding=(5, 5, 10, 10))
mainframe.grid(column=0, row=0, sticky=(N,W,E,S))
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0,weight=1)

root.tk.call('source', 'breeze.tcl')
style=ttk.Style(root)
style.theme_use('Breeze')

#Menu
menubar = Menu(root)
root.config(menu=menubar)

about_menu= Menu(menubar, tearoff=False)
about_menu.add_command(label='Projeto', command=openProjeto)
about_menu.add_command(label='Integrantes', command=openIntegrantes)
menubar.add_cascade(
    label="Sobre",
    menu=about_menu,
    underline=0
)

help_menu = Menu(menubar, tearoff=False)
help_menu.add_command(label='Manual')
menubar.add_cascade(
    label="Ajuda",
    menu=help_menu,
    underline=0
)

#Inicio
frametit=ttk.Frame(mainframe, padding=(5, 5, 10, 10))
frametit.grid(column=0,row=0, sticky=(N, W))
img = Image.open("USP.gif")
img = img.resize((75,90), Image.ANTIALIAS)
photoImg =  ImageTk.PhotoImage(img)
eelicon=ttk.Label(frametit, image=photoImg)
eelicon.grid(column=0,row=0,sticky=(N,W))

titulo = ttk.Label(frametit, text="Simulador de resfriamento de chapas finas:", font=('Oswald',16))
titulo.grid(column=1, row=0, sticky=(W),padx=20)

butao=ttk.Button(mainframe, text="Simular", width=15, command=chama)
butao.grid(column=1 , row=0 , sticky=(E))

framein=ttk.Frame(mainframe, padding=(5, 5, 10, 10))
framein.grid(column=0,row=1, sticky=(W))

frase1 = ttk.Label(framein, text="• Utilizar quais dados iguais para todas as chapas:  ")
frase1.grid(column=0, row=0, sticky=(W))
Tempxvar = BooleanVar(value=False)
checkTempx= ttk.Checkbutton(framein, text='Temperatura de estampagem', variable=Tempxvar, onvalue=True, offvalue=False, command=updatecheck)
checkTempx.grid(column=3, row=0, sticky=(W))
Tempmvar = BooleanVar(value=False)
checkTempm= ttk.Checkbutton(framein, text='Temperatura inicial', variable=Tempmvar, onvalue=True, offvalue=False, command=updatecheck)
checkTempm.grid(column=2, row=0, sticky=(W))
matvar = BooleanVar(value=False)
checkmat= ttk.Checkbutton(framein, text='Material', variable=matvar, onvalue=True, offvalue=False, command=updatecheck)
checkmat.grid(column=1, row=1, sticky=(W))
fluvar = BooleanVar(value=False)
checkflu= ttk.Checkbutton(framein, text='Fluido', variable=fluvar, onvalue=True, offvalue=False, command=updatecheck)
checkflu.grid(column=3, row=1, sticky=(W))
estvar = BooleanVar(value=False)
checkest= ttk.Checkbutton(framein, text='Estampagem', variable=estvar, onvalue=True, offvalue=False, command=updatecheck)
checkest.grid(column=1, row=0, sticky=(W))
Tempavar = BooleanVar(value=False)
checkTempa= ttk.Checkbutton(framein, text='Temperatura do fluido', variable=Tempavar, onvalue=True, offvalue=False, command=updatecheck)
checkTempa.grid(column=2, row=1, sticky=(W))

#Grafico 1

titulog1 = ttk.Label(mainframe, text="Chapa 1:", font=('Oswald',14))
titulog1.grid(column=0, row=3, sticky=(W))
frameg1=ttk.Frame(mainframe, padding=(5, 5, 10, 10))
frameg1.grid(column=0, row=4)

matnameg1= ttk.Label(frameg1, text="• Material")
matnameg1.grid(column=0, row=0)
matg1var= StringVar()
matg1= ttk.Combobox(frameg1, textvariable=matg1var)
matg1['values']=('Cobre','Ferro','Alumínio','Bronze','Ouro','Prata','Aço','Chumbo')
matg1.grid(column=0, row=1)

flunameg1= ttk.Label(frameg1, text="• Fluido")
flunameg1.grid(column=1, row=0)
flug1var= StringVar()
flug1= ttk.Combobox(frameg1, textvariable=flug1var)
flug1['values']=('Ar','Ar em movimento','Água','Água em movimento','Óleo','Óleo em movimento')
flug1.grid(column=1, row=1, padx=10)

tempatitg1=ttk.Label(frameg1, text="• Temperatura do fluido:")
tempatitg1.grid(column=2, row=0, pady=5)
Tempambg1= StringVar()
Tempag1=ttk.Entry(frameg1, width=7, textvariable=Tempambg1)
Tempag1.grid(column=3, row=0 )

tempxtitg1=ttk.Label(frameg1, text="• Temperatura de estampagem:")
tempxtitg1.grid(column=2, row=1, pady=5)
Tempmaxg1= StringVar()
Tempxg1=ttk.Entry(frameg1, width=7, textvariable=Tempmaxg1)
Tempxg1.grid(column=3, row=1 )

tempmtitg1=ttk.Label(frameg1, text="• Temperatura inicial:")
tempmtitg1.grid(column=2, row=2, pady=5)
Tempming1= StringVar()
Tempmg1=ttk.Entry(frameg1, width=7, textvariable=Tempming1)
Tempmg1.grid(column=3, row=2 )

estg1=IntVar()
esttitg1=ttk.Label(frameg1, text="• Estampagem:")
esttitg1.grid(column=4, row=0, padx=20, sticky=(W))

esttxtg1=ttk.Radiobutton(frameg1, text="Em texto", variable=estg1, value=1, command=updateg1)
esttxtg1.grid(column=4, row=1,padx=20,sticky=(W))
txtg1=StringVar()
txttitg1=ttk.Label(frameg1, text='• Texto:')
txtentg1=ttk.Entry(frameg1, width=7, textvariable=txtg1)

estformg1=ttk.Radiobutton(frameg1, text="Formas geométricas", variable=estg1, value=2, command=updateg1)
estformg1.grid(column=4, row=2,padx=20, sticky=(W))
formg1=StringVar()
formtitg1=ttk.Label(frameg1, text='• Forma:')
formentg1=ttk.Combobox(frameg1, textvariable=formg1)
formentg1['values']=('Anel circular','Anel elíptico','Círculo','Furo circular')

#Grafico 2

titulog2 = ttk.Label(mainframe, text="Chapa 2:", font=('Oswald',14))
titulog2.grid(column=0, row=5, sticky=(W))
frameg2=ttk.Frame(mainframe, padding=(5, 5, 10, 10))
frameg2.grid(column=0, row=6)

matnameg2= ttk.Label(frameg2, text="• Material")
matnameg2.grid(column=0, row=0)
matg2var= StringVar()
matg2= ttk.Combobox(frameg2, textvariable=matg2var)
matg2['values']=('Cobre','Ferro','Alumínio','Bronze','Ouro','Prata','Aço','Chumbo')
matg2.grid(column=0, row=1)

flunameg2= ttk.Label(frameg2, text="• Fluido")
flunameg2.grid(column=1, row=0)
flug2var= StringVar()
flug2= ttk.Combobox(frameg2, textvariable=flug2var)
flug2['values']=('Ar','Ar em movimento','Água','Água em movimento','Óleo','Óleo em movimento')
flug2.grid(column=1, row=1, padx=10)

tempatitg2=ttk.Label(frameg2, text="• Temperatura do fluido:")
tempatitg2.grid(column=2, row=0, pady=5)
Tempambg2= StringVar()
Tempag2=ttk.Entry(frameg2, width=7, textvariable=Tempambg2)
Tempag2.grid(column=3, row=0 )

tempxtitg2=ttk.Label(frameg2, text="• Temperatura de estampagem:")
tempxtitg2.grid(column=2, row=1, pady=5)
Tempmaxg2= StringVar()
Tempxg2=ttk.Entry(frameg2, width=7, textvariable=Tempmaxg2)
Tempxg2.grid(column=3, row=1 )

tempmtitg2=ttk.Label(frameg2, text="• Temperatura inicial:")
tempmtitg2.grid(column=2, row=2, pady=5)
Tempming2= StringVar()
Tempmg2=ttk.Entry(frameg2, width=7, textvariable=Tempming2)
Tempmg2.grid(column=3, row=2 )

estg2=IntVar()
esttitg2=ttk.Label(frameg2, text="• Estampagem:")
esttitg2.grid(column=4, row=0, padx=20, sticky=(W))

esttxtg2=ttk.Radiobutton(frameg2, text="Em texto", variable=estg2, value=1, command=updateg2)
esttxtg2.grid(column=4, row=1,padx=20,sticky=(W))
txtg2=StringVar()
txttitg2=ttk.Label(frameg2, text='• Texto:')
txtentg2=ttk.Entry(frameg2, width=7, textvariable=txtg2)

estformg2=ttk.Radiobutton(frameg2, text="Formas geométricas", variable=estg2, value=2, command=updateg2)
estformg2.grid(column=4, row=2,padx=20, sticky=(W))
formg2=StringVar()
formtitg2=ttk.Label(frameg2, text='• Forma:')
formentg2=ttk.Combobox(frameg2, textvariable=formg2)
formentg2['values']=('Anel circular','Anel elíptico','Círculo','Furo circular')

#Grafico 3

titulog3 = ttk.Label(mainframe, text="Chapa 3:", font=('Oswald',14))
titulog3.grid(column=0, row=7, sticky=(W))
frameg3=ttk.Frame(mainframe, padding=(5, 5, 10, 10))
frameg3.grid(column=0, row=8)

matnameg3= ttk.Label(frameg3, text="• Material")
matnameg3.grid(column=0, row=0)
matg3var= StringVar()
matg3= ttk.Combobox(frameg3, textvariable=matg3var)
matg3['values']=('Cobre','Ferro','Alumínio','Bronze','Ouro','Prata','Aço','Chumbo')
matg3.grid(column=0, row=1)

flunameg3= ttk.Label(frameg3, text="• Fluido")
flunameg3.grid(column=1, row=0)
flug3var= StringVar()
flug3= ttk.Combobox(frameg3, textvariable=flug3var)
flug3['values']=('Ar','Ar em movimento','Água','Água em movimento','Óleo','Óleo em movimento')
flug3.grid(column=1, row=1, padx=10)

tempatitg3=ttk.Label(frameg3, text="• Temperatura do fluido:")
tempatitg3.grid(column=2, row=0, pady=5)
Tempambg3= StringVar()
Tempag3=ttk.Entry(frameg3, width=7, textvariable=Tempambg3)
Tempag3.grid(column=3, row=0 )

tempxtitg3=ttk.Label(frameg3, text="• Temperatura de estampagem:")
tempxtitg3.grid(column=2, row=1, pady=5)
Tempmaxg3= StringVar()
Tempxg3=ttk.Entry(frameg3, width=7, textvariable=Tempmaxg3)
Tempxg3.grid(column=3, row=1 )

tempmtitg3=ttk.Label(frameg3, text="• Temperatura inicial:")
tempmtitg3.grid(column=2, row=2, pady=5)
Tempming3= StringVar()
Tempmg3=ttk.Entry(frameg3, width=7, textvariable=Tempming3)
Tempmg3.grid(column=3, row=2 )

estg3=IntVar()
esttitg3=ttk.Label(frameg3, text="• Estampagem:")
esttitg3.grid(column=4, row=0, padx=20, sticky=(W))

esttxtg3=ttk.Radiobutton(frameg3, text="Em texto", variable=estg3, value=1, command=updateg3)
esttxtg3.grid(column=4, row=1,padx=20,sticky=(W))
txtg3=StringVar()
txttitg3=ttk.Label(frameg3, text='• Texto:')
txtentg3=ttk.Entry(frameg3, width=7, textvariable=txtg3)

estformg3=ttk.Radiobutton(frameg3, text="Formas geométricas", variable=estg3, value=2, command=updateg3)
estformg3.grid(column=4, row=2,padx=20, sticky=(W))
formg3=StringVar()
formtitg3=ttk.Label(frameg3, text='• Forma:')
formentg3=ttk.Combobox(frameg3, textvariable=formg3)
formentg3['values']=('Anel circular','Anel elíptico','Círculo','Furo circular')

#Grafico 4

titulog4 = ttk.Label(mainframe, text="Chapa 4:", font=('Oswald',14))
titulog4.grid(column=0, row=9, sticky=(W))
frameg4=ttk.Frame(mainframe, padding=(5, 5, 10, 10))
frameg4.grid(column=0, row=10)

matnameg4= ttk.Label(frameg4, text="• Material")
matnameg4.grid(column=0, row=0)
matg4var= StringVar()
matg4= ttk.Combobox(frameg4, textvariable=matg4var)
matg4['values']=('Cobre','Ferro','Alumínio','Bronze','Ouro','Prata','Aço','Chumbo')
matg4.grid(column=0, row=1)

flunameg4= ttk.Label(frameg4, text="• Fluido")
flunameg4.grid(column=1, row=0)
flug4var= StringVar()
flug4= ttk.Combobox(frameg4, textvariable=flug4var)
flug4['values']=('Ar','Ar em movimento','Água','Água em movimento','Óleo','Óleo em movimento')
flug4.grid(column=1, row=1, padx=10)

tempatitg4=ttk.Label(frameg4, text="• Temperatura do fluido:")
tempatitg4.grid(column=2, row=0, pady=5)
Tempambg4= StringVar()
Tempag4=ttk.Entry(frameg4, width=7, textvariable=Tempambg4)
Tempag4.grid(column=3, row=0 )

tempxtitg4=ttk.Label(frameg4, text="• Temperatura de estampagem:")
tempxtitg4.grid(column=2, row=1, pady=5)
Tempmaxg4= StringVar()
Tempxg4=ttk.Entry(frameg4, width=7, textvariable=Tempmaxg4)
Tempxg4.grid(column=3, row=1 )

tempmtitg4=ttk.Label(frameg4, text="• Temperatura inicial:")
tempmtitg4.grid(column=2, row=2, pady=5)
Tempming4= StringVar()
Tempmg4=ttk.Entry(frameg4, width=7, textvariable=Tempming4)
Tempmg4.grid(column=3, row=2 )

estg4=IntVar()
esttitg4=ttk.Label(frameg4, text="• Estampagem:")
esttitg4.grid(column=4, row=0, padx=20, sticky=(W))

esttxtg4=ttk.Radiobutton(frameg4, text="Em texto", variable=estg4, value=1, command=updateg4)
esttxtg4.grid(column=4, row=1,padx=20,sticky=(W))
txtg4=StringVar()
txttitg4=ttk.Label(frameg4, text='• Texto:')
txtentg4=ttk.Entry(frameg4, width=7, textvariable=txtg4)

estformg4=ttk.Radiobutton(frameg4, text="Formas geométricas", variable=estg4, value=2, command=updateg4)
estformg4.grid(column=4, row=2,padx=20, sticky=(W))
formg4=StringVar()
formtitg4=ttk.Label(frameg4, text='• Forma:')
formentg4=ttk.Combobox(frameg4, textvariable=formg4)
formentg4['values']=('Anel circular','Anel elíptico','Círculo','Furo circular')

root.mainloop()


from src.Transition import Transition
from src.Algorithms.minimisation import minimisation
from src.Graph import Graph

def equivalence(graph1, graph2):
    """ Fonction de vérification de l'équivalence de deux automates

    Algorithme prenant deux automates, et déterminant si ceux-ci sont équivalents.

    """
    # graph1_min = minimisation(graph1)
    # graph2_min = minimisation(graph2)
    graph1_min = graph1
    graph2_min = graph2

    print("eq")
    print('\n------------------------------------------------\n')
    if len(graph1_min.states) != len(graph2_min.states):
        print('Pas d\'équivalance\nNombre d\'états différent')
        print('\n------------------------------------------------\n')

        return False

    graph1_min.alphabet.sort()
    graph2_min.alphabet.sort()
    if graph1_min.alphabet != graph2_min.alphabet:
        print('\nPas d\'équivalence. Alphabets différents')
        print('\n------------------------------------------------\n')

        return False

    queue1 = [graph1_min.initialState]
    queue2 = [graph2_min.initialState]
    done1 = []
    done2 = []
    type1 = {}
    type2 = {}
    while (len(queue1) > 0 and len(queue2) > 0):
        current1 = queue1.pop()
        current2 = queue2.pop()
        for letter in graph1_min.alphabet:
            trans1 = graph1_min.getStateTransitionsLetter(current1, letter)
            trans2 = graph2_min.getStateTransitionsLetter(current2, letter)
            if len(trans1) != len(trans2):
                print('\nPas d\'équivalence. Transitions différentes\n')
                print('\n------------------------------------------------\n')

                return False
            elif len(trans1) != 0 and len(trans2) != 0:
                dest1 = trans1[0].mGoto
                dest2 = trans2[0].mGoto

                # Vérifier le type de l'état destination du premier automate
                if dest1 == graph1_min.initialState and dest1 in graph1_min.finalStates:
                    type1[dest1] = 'initial and final'
                elif dest1 == graph1_min.initialState:
                    type1[dest1] = 'initial'
                elif dest1 in graph1_min.finalStates:
                    type1[dest1] = 'final'
                else:
                    type1[dest1] = 'other'

                # Vérifier le type de l'état destination du deuxième automate
                if dest2 == graph2_min.initialState and dest2 in graph2_min.finalStates:
                    type2[dest2] = 'initial and final'
                elif dest2 == graph2_min.initialState:
                    type2[dest2] = 'initial'
                elif dest2 in graph2_min.finalStates:
                    type2[dest2] = 'final'
                else:
                    type2[dest2] = 'other'

                # Si les états sont de nature différente alors les automates ne sont pas équivalents
                if type1[dest1] != type2[dest2]:
                    print('\nAutomates pas équivalants\n')
                    print('\n------------------------------------------------\n')
                    return False

                done1.append(current1)
                if dest1 not in done1:
                    queue1.append(dest1)

                done2.append(current2)
                if dest2 not in done2:
                    queue2.append(dest2)
    print('Les graphes sont équivalents!')
    print('\n------------------------------------------------\n')

    return True


import os.path
import sys

INTO_FILE = False
output = []

def fast_input(file_name):
    global INTO_FILE
    if os.path.isfile(file_name):
        INTO_FILE = True
        with open(file_name, 'r') as file:
            input_lines = file.readlines()
    else:
        INTO_FILE = False
        input_lines = sys.stdin.readlines()

    for line in input_lines:
        yield line

fast_input_reader = fast_input('input.txt')

def input():
    return fast_input_reader.__next__()

def print(line):
    output.append(str(line))

def solve():
    from collections import deque
    # read data
    H, W = map(int, input().strip().split())
    field = []
    for _ in range(H):
        field.append(input().strip())
    start_x, start_y = map(int, input().strip().split())
    end_x, end_y = map(int, input().strip().split())

    # build infrastructure
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1)]
    MAX_DISTANCE = H * W + 1
    MAX_W, MAX_N_DIR = 1000 * 10, 10
    distances = [[[MAX_DISTANCE for _ in directions] for _ in range(W)] for _ in range(H)]
    queue = deque([])
    for dir_index, _ in enumerate(directions):
        distances[H - start_y][start_x - 1][dir_index] = 1
        code = ((H - start_y) * MAX_W + (start_x - 1)) * MAX_N_DIR + dir_index
        queue.append(code)

    # loop
    res = -1
    while queue:
        code = queue.popleft()
        i, j, dir_index = code // (MAX_W * MAX_N_DIR), (code // MAX_N_DIR) % MAX_W, code % MAX_N_DIR
        d = distances[i][j][dir_index]

        if (i, j) == (H - end_y, end_x - 1):
            res = d
            break

        # 0-edge
        di, dj = directions[dir_index]
        if 0 <= i + di < H and 0 <= j + dj < W and field[i + di][j + dj] == '.':
            dir_index = directions.index((di, dj))
            if d < distances[i + di][j + dj][dir_index]:
                distances[i + di][j + dj][dir_index] = d
                queue.appendleft(((i + di) * MAX_W + (j + dj)) * MAX_N_DIR + dir_index)

        # 1-edge
        for di_, dj_ in directions:
            if 0 <= i + di_ < H and 0 <= j + dj_ < W and field[i + di_][j + dj_] == '.':
                dir_index = directions.index((di_, dj_))
                if distances[i + di_][j + dj_][dir_index] == MAX_DISTANCE:
                    distances[i + di_][j + dj_][dir_index] = d + 1
                    queue.append(((i + di_) * MAX_W + (j + dj_)) * MAX_N_DIR + dir_index)

    print(res)

def main():
    solve()
    answer = '\n'.join(output) + '\n'

    if INTO_FILE:
        with open('output.txt', 'w') as output_file:
            output_file.write(answer)
    else:
        sys.stdout.write(answer)

if __name__ == '__main__':
    main()


#!/usr/bin/env python3

import sys
import rospy
import numpy as np
from std_msgs.msg import Float64

class joints_mover:
    """Class for moving joints"""

    def __init__(self):
        # initialize the node
        rospy.init_node('joints_mover', anonymous=True)
        self.rate = rospy.Rate(30) # 30hz
        # initialize publishers to modify joint angles
        self.joint1_pub = rospy.Publisher("/robot/joint1_position_controller/command",
                                          Float64,
                                          queue_size=10)
        self.joint2_pub = rospy.Publisher("/robot/joint2_position_controller/command",
                                          Float64,
                                          queue_size=10)
        self.joint3_pub = rospy.Publisher("/robot/joint3_position_controller/command",
                                          Float64,
                                          queue_size=10)
        self.joint4_pub = rospy.Publisher("/robot/joint4_position_controller/command",
                                          Float64,
                                          queue_size=10)

    def move_joints_2_1(self, delta_t=5.3):
        """Function called when the node is run to move the joints
        according to the specifications of 2.1"""
        # save initialization time
        t0 = rospy.get_time()
        t = 0
        # run for delta_t seconds
        while t < delta_t:
            t = (np.array([rospy.get_time()]) - t0)
            print(t)
            # Calculate angles
            j2 = (np.pi/2.0) * np.sin(t * np.pi/15)
            j3 = (np.pi/2.0) * np.sin(t * np.pi/18)
            j4 = (np.pi/2.0) * np.sin(t * np.pi/20)
            self.set_joint_angle(2, j2)
            self.set_joint_angle(3, j3)
            self.set_joint_angle(4, j4)
            self.rate.sleep()
        self.reset_joints()

    # Sets the angle of the specified joint (1-4) to the given value
    def set_joint_angle(self, joint, angle):
        publishers = [self.joint1_pub, self.joint2_pub, self.joint3_pub, self.joint4_pub]
        to_publish = Float64()
        to_publish.data = angle
        publishers[joint-1].publish(to_publish)

    # Sets all joint angles to zero
    def reset_joints(self):
        for i in range(10):
            for i in range(1, 5):
                self.set_joint_angle(i, 0)
            self.rate.sleep()

# run the code if the node is called
if __name__ == '__main__':
    try:
        choice = sys.argv[1]
        jm = joints_mover()
        if choice == '2.1':
            jm.move_joints_2_1()
            jm.reset_joints()
        elif choice == 'reset':
            jm.reset_joints()
        else:
            raise Exception('Invalid argument \"{}\"'.format(choice))
    except rospy.ROSInterruptException:
        pass


class Candidate(object):
    def __init__(self, name, dept):
        self.name = name
        self.dept = dept

        self.officer_scores = []
        self.lead_scores = []
        self.lb_scores = []

        self.officer_score = -1
        self.lead_score = -1
        self.lb_score = -1

        self.score = -1

    def add_officer_score(self, evaluation):
        relationship = evaluation['How is the relationship building skills? ']
        leadership = evaluation['Leadership/Organization Ability']
        involvement = evaluation['Meeting Involvement (officer) / Meeting Effectiveness (Lead)']
        innovation = evaluation['Quality of ideas / Innovation']
        contribution = evaluation['Team Contribution']

        self.officer_scores.append(np.mean([relationship, leadership, involvement, innovation, contribution]) / 5.0)

    def add_lead_score(self, evaluation):
        relationship = evaluation['How is the relationship building skills? ']
        leadership = evaluation['Leadership/Organization Ability']
        involvement = evaluation['Meeting Involvement (officer) / Meeting Effectiveness (Lead)']
        innovation = evaluation['Quality of ideas / Innovation']
        contribution = evaluation['Team Contribution']

        self.lead_scores.append(np.mean([relationship, leadership, involvement, innovation, contribution]) / 5.0)

    def add_lb_score(self, evaluation):
        r_list = [
            evaluation['Please vote based on your assessment on the video contents.'],
            evaluation['Please vote based on your assessment on the feedback provided by the officers.'],
            evaluation['Please vote based on your knowledge about this candidate.']
        ]

        s_list = []
        for r in r_list:
            if type(r) == int:
                s_list.append(r)

        self.lb_scores.append(np.mean(s_list) / 5.0)

    def calculate_scores(self):
        scores = 0.0
        portions = 0.0

        if len(self.officer_scores) != 0:
            self.officer_score = np.mean(self.officer_scores)
            scores += self.officer_score * 0.3
            portions += 0.3

        if len(self.lb_scores) != 0:
            self.lb_score = np.mean(self.lb_scores)
            scores += self.lb_score * 0.3
            portions += 0.3

        if len(self.lead_scores) != 0:
            self.lead_score = np.mean(self.lead_scores)
            scores += self.lead_score * 0.4
            portions += 0.4

        self.score = scores / portions * 100

    def __str__(self):
        return """name: {}
department: {}
officer_scores: {}
officer_score: {}
lead_scores: {}
lead_score: {}
lb_scores: {}
lb_score: {}
score: {}""".format(self.name, self.dept, self.officer_scores,
                    self.officer_score, self.lead_scores, self.lead_score,
                    self.lb_scores, self.lb_score, self.score)


# 2621번 카드게임
# https://www.acmicpc.net/problem/2621

"""
0. R, B, Y, G 4가지 색의 1~9의 숫자가 쓰여진 카드가 각각 9장씩 있다.
   36장의 카드에서 5장을 뽑고, 아래와 같은 규칙으로 정수를 계산
1. 5장이 모두 '같은 색' 이면서 숫자가 연속적일 때, 가장 높은 수에 900을 더한다.
2. 5장 중에 4장의 '숫자가 같을 때' 점수는 같은 숫자에 800을 더한다.
3. 5장 중에 3장의 '숫자가 같고' 나머지 2장의 '숫자가 같을 때'
   3장이 같은 숫자에 10을 곱하고, 2장이 같은 숫자를 더한 다음 700을 더한다.
4. 5장의 카드가 모두 "같은 색일 때" 가장 높은 숫자에 600을 더한다.
5. 5장의 "숫자가 연속적"일 때, 가장 높은 숫자에 500을 더한다.
6. 5장 중 3장의 "숫자가 같을 때" 같은 숫자에 400을 더한다.
7. 5장 중 2장의 "숫자가 같고" 다른 2장의 "숫자가 같을 때"
   같은 숫자 중 큰 숫자에 10을 곱하고, 작은 숫자를 더한 뒤 300을 더한다.
8. 5장 중 2장의 "숫자가 같을 때" 점수가 같은 숫자에 200을 더한다.
9. 어떤 경우에도 해당하지 않을 때 가장 큰 숫자에 100을 더한다.
"""
from collections import defaultdict

# 입력 정보 받기
dict_color = defaultdict(int)
dict_number = defaultdict(int)
numbers = set()
cards = []
for _ in range(5):
    c, n = list(input().split())
    cards.append([c, int(n)])
    dict_color[c] += 1
    dict_number[int(n)] += 1
    numbers.add(int(n))

cards.sort()

breaky = False
score = 100 + max(numbers)

# 카드 5장이 모두 같은 색인 1번과 4번 경우를 처리
for color, cnt in dict_color.items():
    if cnt == 5:
        for idx in range(4):
            if cards[idx][1] + 1 != cards[idx+1][1]:
                breaky = True
                break
        else:
            score = max(score, 900 + cards[-1][1])

        if breaky:
            score = max(score, 600 + cards[-1][1])

for number, cnt in dict_number.items():
    # 2. 카드 5장 중 4장의 숫자가 같을 때
    if cnt == 4:
        score = max(score, 800 + number)
        break
    # 카드 5장 중 3장의 숫자가 같을 때
    elif cnt == 3:
        # 3. 다른 두 장의 숫자가 같은 경우
        if 2 in dict_number.values():
            number2 = 0
            for num in numbers:
                if num != number:
                    number2 = num
                    break
            score = max(score, 700 + number * 10 + number2)
            break
        # 6. 다른 두 장의 숫자가 같지 않고, 3장의 숫자만 캍을 때
        else:
            score = max(score, 400 + number)
            break
    elif cnt == 2:
        # 7. 5장 중 2장의 숫자가 같고 또 다른 2장의 숫자가 같을 때
        if list(dict_number.values()).count(2) == 2:
            n2 = []
            for k, v in dict_number.items():
                if v == 2:
                    n2.append(k)
            n2.sort()

            score = max(score, 300 + n2[1] * 10 + n2[0])
            break
        # 8. 5장 중 2장의 숫자만 같을 때
        else:
            score = max(score, 200 + number)

# 5. 카드 5장의 숫자가 연속적일 때
numbers = sorted(list(numbers))
# 모든 숫자가 달라야 하니까 set에서는 같은 숫자가 생기면 5보다 작아진다.
if len(numbers) == 5:
    for idx in range(4):
        if numbers[idx] + 1 != numbers[idx + 1]:
            break
    else:
        score = max(score, 500 + numbers[-1])

print(score)

"""
1.
B 1
B 2
B 3
B 4
B 5
905

2.
B 4
Y 4
G 4
R 4
B 1
804

3.
B 4
Y 4
G 4
R 2
B 2
742

4.
B 1
B 2
B 3
B 4
B 6
606

5.
B 1
B 2
B 3
B 4
G 5
505

6.
G 3
B 4
Y 5
G 6
B 7
507

7.
G 3
G 7
B 3
B 7
Y 1
373

8.
G 3
G 7
B 3
B 6
Y 1
203

9.
G 9
G 7
B 3
B 6
Y 1
109

Y 4
Y 3
Y 2
Y 5
Y 6
906

"""


# -*- coding: utf-8 -*-
# __author__ = 'mxins@qq.com'
from __future__ import print_function
from pyspark.sql import SparkSession
from pyspark.sql import SQLContext
from pyspark.sql.types import *
import os
import time
'''
create table spark.consume_agg
(
  game_id,
  server_id,
  uid,
  register_date,
  date_desc,
  level,
  amount,
  consume_times
)
AS
SELECT t1.game_id,
       t1.server_id,
       t1.uid,
       max(t1.register_date),
       t1.date_desc,
       max(t1.level),
       SUM(t1.amount),
       COUNT(1)
FROM spark.consume_log t1
  JOIN spark.game_dim t2
    ON t1.game_id = t2.game_id
GROUP BY t1.game_id,
         t1.server_id,
         t1.date_desc,
         t1.uid;
'''

spark = SparkSession\
    .builder\
    .appName("Python Spark SQL Test")\
    .getOrCreate()
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
output_dir = base_dir + '/output/'

def save_df(df, table_name):
    df.write.mode('overwrite').csv(output_dir + table_name + '/', timestampFormat="yyyy-MM-dd HH:mm:ss")

def timer(table_name):
    def timeit(func):
        def wrapper(*args):
            t1 = time.time()
            df = func(*args)
            t2 = time.time()
            print('table: %s, count: %d, save df cost time: %r seconds, count cost time: %r seconds, '
                  'total: %r seconds.\n' % (table_name, df.count(), t2 - t1, time.time() - t2, time.time() - t1))
            return df
        return wrapper
    return timeit

class ETL(object):

    @staticmethod
    @timer('game_dim')
    def get_game_dim():
        t1 = time.time()
        game_path = base_dir + '/data/game_dim/'
        game_fields = [StructField('game_id', IntegerType(), True), StructField('game_name', StringType(), True)]
        game_schema = StructType(game_fields)
        game = spark.read.csv(game_path, game_schema)
        t2 = time.time()
        game.createOrReplaceTempView('game_dim')
        t3 = time.time()
        print('get_game_dim:', t2-t1, t3 - t2)
        return game

    @staticmethod
    @timer('consume_log')
    def get_consume_log():
        t1 = time.time()
        consume_path = base_dir + '/data/consume_log/'
        consume_fields = [StructField('game_id', IntegerType(), True), StructField('server_id', IntegerType(), True),
                          StructField('uid', StringType(), True), StructField('register_date', DateType(), True),
                          StructField('date_desc', DateType(), True), StructField('data_time', TimestampType(), True),
                          StructField('session', StringType(), True), StructField('object', StringType(), True),
                          StructField('amount', FloatType(), True), StructField('level', IntegerType(), True),
                          StructField('coin', IntegerType(), True)]
        consume_schema = StructType(consume_fields)
        consume = spark.read.csv(consume_path, consume_schema)
        t2 = time.time()
        consume.createOrReplaceTempView('consume_log')
        t3 = time.time()
        print('get_consume_log:', t2 - t1, t3 - t2)
        return consume

    @staticmethod
    @timer('consume_agg')
    def get_consume_agg():
        t1 = time.time()
        sql = '''
            SELECT t1.game_id,
                   t1.server_id,
                   t1.uid,
                   max(t1.register_date) AS register_date,
                   t1.date_desc,
                   max(t1.level) AS level,
                   SUM(t1.amount) AS amount,
                   COUNT(1) AS consume_times
            FROM consume_log t1
              JOIN game_dim t2
                ON t1.game_id = t2.game_id
            GROUP BY t1.game_id,
                     t1.server_id,
                     t1.date_desc,
                     t1.uid
        '''
        df = spark.sql(sql)
        t2 = time.time()
        save_df(df, 'consume_agg')
        t3 = time.time()
        print('get_consume_agg:', t2-t1, t3 - t2)
        return df

    @staticmethod
    @timer('consume_agg_raw')
    def get_consume_agg_raw():
        t1 = time.time()
        sql = "SELECT t.game_id,\n" + \
              "       t.server_id,\n" + \
              "       t.uid, \n" + \
              "       year(register_date) AS date_year, \n" + \
              "       month(date_desc) AS date_month,\n" + \
              "       t.level, \n" + \
              "       t.amount, \n" + \
              "       t.consume_times \n" + \
              "FROM (SELECT t1.game_id,\n" + \
              "             t1.server_id,\n" + \
              "             t1.uid,\n" + \
              "             max(t1.register_date) AS register_date,\n" + \
              "             t1.date_desc,\n" + \
              "             max(t1.level) AS level,\n" + \
              "             SUM(t1.amount) AS amount,\n" + \
              "             COUNT(1) AS consume_times\n" + \
              "      FROM consume_log t1\n" + \
              "          JOIN game_dim t2\n" + \
              "              ON t1.game_id = t2.game_id\n" + \
              "      GROUP BY t1.game_id,\n" + \
              "               t1.server_id,\n" + \
              "               t1.date_desc,\n" + \
              "               t1.uid) t"
        df = spark.sql(sql)
        df.cache()
        t2 = time.time()
        save_df(df, 'consume_agg_raw')
        t3 = time.time()
        print('get_consume_agg_raw:', t2-t1, t3 - t2)
        return df

    @staticmethod
    @timer('consume_agg_udf')
    def get_consume_agg_udf():
        t1 = time.time()
        sc = spark.sparkContext
        ctx = SQLContext.getOrCreate(sc)
        ctx.registerFunction('udf_year', lambda register_date: register_date.year, IntegerType())
        ctx.registerFunction('udf_month', lambda date_desc: date_desc.month, IntegerType())
        sql = '''
            SELECT t.game_id, t.server_id, t.uid, udf_year(register_date) AS date_year,
                    udf_year(date_desc) AS date_month, t.level, t.amount, t.consume_times
            FROM (SELECT t1.game_id,
                       t1.server_id,
                       t1.uid,
                       max(t1.register_date) AS register_date,
                       t1.date_desc,
                       max(t1.level) AS level,
                       SUM(t1.amount) AS amount,
                       COUNT(1) AS consume_times
                FROM consume_log t1
                  JOIN game_dim t2
                    ON t1.game_id = t2.game_id
                GROUP BY t1.game_id,
                         t1.server_id,
                         t1.date_desc,
                         t1.uid) t
        '''
        df = spark.sql(sql)
        df.cache()
        t2 = time.time()
        save_df(df, 'consume_agg_udf')
        t3 = time.time()
        print('get_consume_agg_udf:', t2-t1, t3 - t2)
        return df

if __name__ == '__main__':
    start = time.time()
    etl = ETL()
    etl.get_game_dim()
    etl.get_consume_log()
    etl.get_consume_agg()
    etl.get_consume_agg_raw()
    etl.get_consume_agg_udf()
    end = time.time()
    print('job finished. cost time: %r seconds.' % (end - start))


# Get all the "References"

from bs4 import BeautifulSoup
import requests

url = 'https://en.wikipedia.org/wiki/Transhumanism'
# get contents from url
content = requests.get(url).content
# get soup
soup = BeautifulSoup(content, 'lxml')  # choose lxml parser
# find all the references
ref_tags = soup.findAll('span', {'class': 'reference-text'})
# iterate through the ResultSet
for i, ref_tag in enumerate(ref_tags):
    # print text only
    print('[{0}] {1}'.format(i, ref_tag.text))


import argparse
import json
from pathlib import Path
from typing import Tuple

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from tqdm import tqdm

def evaluate(data: list, dir_name: str, plot: bool = False) -> Tuple[dict, pd.DataFrame]:
    helper = {}

    for dataset in data:
        for k1, v1 in dataset.items():
            if k1 not in helper:
                helper[k1] = {}

            for k2, v2 in v1.items():
                if k2 not in helper[k1]:
                    helper[k1][k2] = {}

                for k3, v3 in v2.items():
                    if isinstance(v3, dict):
                        if k3 not in helper[k1][k2]:
                            helper[k1][k2][k3] = {}
                        for k4, v4 in v3.items():
                            if k4 not in helper[k1][k2][k3]:
                                helper[k1][k2][k3][k4] = [v4]
                            else:
                                helper[k1][k2][k3][k4].append(v4)
                    else:
                        if k3 not in helper[k1][k2]:
                            helper[k1][k2][k3] = [v3]
                        else:
                            helper[k1][k2][k3].append(v3)

    evaluation = {}
    latex = pd.DataFrame([])

    for k1, v1 in helper.items():
        if k1 not in evaluation:
            evaluation[k1] = {}

        for k2, v2 in v1.items():
            if k2 not in evaluation[k1]:
                evaluation[k1][k2] = {}

            for k3, v3 in v2.items():
                if isinstance(v3, dict):
                    if k3 not in evaluation[k1][k2]:
                        evaluation[k1][k2][k3] = {}
                    for k4, v4 in v3.items():
                        if plot: plot_boxplot(v4, dir_name, "{} {}".format(k2, k4))
                        evaluation[k1][k2][k3][k4] = box_plot_dict(v4)
                        latex.loc[k2, k4] = round(np.mean(v4), 4)
                else:
                    if plot: plot_boxplot(v3, dir_name, "{} {}".format(k2, k3))
                    evaluation[k1][k2][k3] = box_plot_dict(v3)
                    if k3 != "expected_clusters":
                        latex.loc[k2, k3] = round(np.mean(v3), 4)

    return evaluation, latex

def box_plot_dict(values: list):
    return {"mean": round(np.mean(values), 4),
            "25th": round(np.quantile(values, 0.25), 4),
            "75th": round(np.quantile(values, 0.75), 4),
            "min": round(min(values), 4),
            "min_ind": int(np.argmin(values)),
            "max": round(max(values), 4),
            "max_ind": int(np.argmax(values))}

def plot_boxplot(data, dir_name: str, title: str):
    Path("{}/result_plots".format(dir_name)).mkdir(parents=True, exist_ok=True)

    fig, ax = plt.subplots()
    ax.set_title(title)
    ax.boxplot(data)
    ax.set_xticks([])

    title = title.replace(" ", "_")

    plt.savefig("{}/result_plots/{}.pdf".format(dir_name, title), format="pdf")
    # plt.show()
    plt.close()

def _main(result_path: str, save_path: str, plot: bool = False):
    results_list = []
    j = 0

    for i in tqdm(range(1200)):
        path = Path(result_path).joinpath(str(i)).joinpath("results.json")

        with open(path, "r") as file:
            results_list.append(json.load(file))

        if i % 100 == 99:
            evaluation, latex = evaluate(results_list, save_path + "/box_plots_{}".format(j), plot)

            with open("{}/evaluation_{}.json".format(save_path, j), "w") as file:
                json.dump(evaluation, file)
            with open("{}/latex_{}.txt".format(save_path, j), "w") as file:
                latex.columns = ["AMI", "ARI", "Comp", "FM", "Hom", "V-Mea", "F1", "Ham", "Jac", "Acc", "Rec", "Pre",
                                 "# clus", "time (s)"]
                new_index = ["Affinity Propagation", "Agglomerative Clust", "BIRCH", "DBScan", "K-Means",
                             "Mini-Batch K-Means", "Mean-Shift", "OPTICS", "Spectral Clustering", "Gaussian Mixture",
                             "KNN", "Decision Tree", "Random Forest", "SVM", "Logistic Regression", "Naive Bayes"]
                latex.rename(index={l1: l2 for l1, l2 in zip(latex.index, new_index)}, inplace=True)
                latex.to_latex(file, header=True, index=True, caption=str(j), label="tabel:{}".format(j),
                               column_format="lrrrrrrrrrrrrrr", position="tb", na_rep="-")

            j += 1
            results_list = []

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-r', "--result_path", action='store', type=str,
                        default="evaluation",
                        help='Where the json which should be evaluated is saved.')
    parser.add_argument('-d', "--directory", action='store', type=str, default="evaluation",
                        help='Dictionary where to evaluation results.')
    parser.add_argument("-p", "--plot", action='store_true', default=True, help='Whether to plot the results.')

    args = parser.parse_args()

    _main(args.result_path, args.directory, args.plot)


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

import pydot
import pandas as pd
import numpy as np
import seaborn as sns
sns.set()

import matplotlib
import matplotlib.pyplot as plt

# Ignore warnings
import warnings
warnings.filterwarnings('ignore')

import sklearn
from sklearn import metrics
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import export_graphviz, DecisionTreeClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.exceptions import NotFittedError

import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras import optimizers
from keras.wrappers.scikit_learn import KerasClassifier

from IPython.display import display

#Plotting Display Functions
def display_confusion_matrix(target, prediction, score=None):
    cm = metrics.confusion_matrix(target, prediction)
    plt.figure(figsize=(6,6))
    sns.heatmap(cm, annot=True, fmt=".3f", linewidths=.5, square=True, cmap='Blues_r')
    plt.ylabel('Actual label')
    plt.xlabel('Predicted label')
    if score:
        score_title = 'Accuracy Score: {0}'.format(round(score, 5))
        plt.title(score_title, size = 14)
    classification_report = pd.DataFrame.from_dict(metrics.classification_report(target, prediction, output_dict=True), orient='index')
    display(classification_report.round(2))

# Importing the dataset
dataset = pd.read_csv('path to training csv dataset')
X = dataset.drop(['OBJECTID', 'Cluster'], axis=1)
y = dataset['Cluster']

# Splitting the dataset into the Training set and Test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

#################Logistic Regression CLASSIFIER

# Create and train model on train data sample
lg = LogisticRegression(solver='lbfgs', random_state=42)
lg.fit(X_train, y_train)

#Predict for test data sample
logistic_prediction = lg.predict(X_test)

#Compute error between predicted data and true response and display it in confusion matrix
score = metrics.accuracy_score(y_test, logistic_prediction)
display_confusion_matrix(y_test, logistic_prediction, score=score)

from sklearn.metrics import classification_report,confusion_matrix
print(confusion_matrix(y_test,logistic_prediction))
print(classification_report(y_test,logistic_prediction))

################Decision Tree

dt = DecisionTreeClassifier(min_samples_split=15, min_samples_leaf=20, random_state=42)
dt.fit(X_train, y_train)
dt_prediction = dt.predict(X_test)

score = metrics.accuracy_score(y_test, dt_prediction)
display_confusion_matrix(y_test, dt_prediction, score=score)

from sklearn.metrics import classification_report,confusion_matrix
print(confusion_matrix(y_test,dt_prediction))
print(classification_report(y_test,dt_prediction))

############### SVM CLASSIFIER

svm = SVC(gamma='auto', random_state=42)
svm.fit(X_train, y_train)
svm_prediction = svm.predict(X_test)

score = metrics.accuracy_score(y_test, svm_prediction)
display_confusion_matrix(y_test, svm_prediction, score=score)

from sklearn.metrics import classification_report,confusion_matrix
print(confusion_matrix(y_test,svm_prediction))
print(classification_report(y_test,svm_prediction))

############# RANDOM fOREST CLASSIFIER
rf = RandomForestClassifier(n_estimators=200, random_state=42)
rf.fit(X_train, y_train)
rf_prediction = rf.predict(X_test)

score = metrics.accuracy_score(y_test, rf_prediction)
display_confusion_matrix(y_test, rf_prediction, score=score)

from sklearn.metrics import classification_report,confusion_matrix
print(confusion_matrix(y_test,rf_prediction))
print(classification_report(y_test,rf_prediction))

############# Multilayer Perceprton (ANN)
def build_ann(optimizer='adam'):

    # Initializing our ANN
    model = Sequential()

    # Adding the input layer and the first hidden layer of our ANN with dropout
    model.add(Dense(output_dim = 3, init = 'uniform', activation = 'relu',input_dim = 3))

    # Adding the second hidden layer
    model.add(Dense(output_dim = 3, init = 'uniform', activation = 'relu'))

    # Adding the output layer
    model.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid'))

    # Compiling the ANN
    model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

    return model

    # Initializing our ANN
    ann = Sequential()

    # Adding the input layer and the first hidden layer of our ANN with dropout
    ann.add(Dense(output_dim = 3, init = 'uniform', activation = 'relu', input_dim = 3))

    # Adding the second hidden layer
    ann.add(Dense(output_dim = 3, init = 'uniform', activation = 'relu'))

    # Adding the output layer
    ann.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid'))

    # Compiling the ANN
    ann.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

    return ann

opt = optimizers.Adam(lr=0.001)
ann = build_ann(opt)

 #Fitting the ANN to the Training set
ann.fit(X_train, y_train, batch_size = 10, nb_epoch = 100)

 #Predicting the Test set results
ann_prediction = ann.predict(X_test)
ann_prediction = (ann_prediction > 0.5)

score = metrics.accuracy_score(y_test, ann_prediction)
display_confusion_matrix(y_test, ann_prediction, score=score)

from sklearn.metrics import classification_report,confusion_matrix
print(confusion_matrix(y_test,ann_prediction))
print(classification_report(y_test,ann_prediction))

######################K-FOLD CROSS VALIDATION#######################

n_folds = 10
cv_score_lg = cross_val_score(estimator=lg, X=X_train, y=y_train, cv=n_folds, n_jobs=-1)
cv_score_dt = cross_val_score(estimator=dt, X=X_train, y=y_train, cv=n_folds, n_jobs=-1)
cv_score_svm = cross_val_score(estimator=svm, X=X_train, y=y_train, cv=n_folds, n_jobs=-1)
cv_score_rf = cross_val_score(estimator=rf, X=X_train, y=y_train, cv=n_folds, n_jobs=-1)
cv_score_ann = cross_val_score(estimator=KerasClassifier(build_fn=build_ann, batch_size=16, epochs=20, verbose=0), X=X_train, y=y_train, cv=n_folds, n_jobs=-1)

cv_result = {'lg': cv_score_lg, 'dt': cv_score_dt, 'svm': cv_score_svm, 'rf': cv_score_rf, 'ann': cv_score_ann}
cv_data = {model: [score.mean(), score.std()] for model, score in cv_result.items()}
cv_df = pd.DataFrame(cv_data, index=['Mean_accuracy', 'Variance'])
cv_df

plt.figure(figsize=(20,8))
plt.plot(cv_result['lg'])
plt.plot(cv_result['dt'])
plt.plot(cv_result['svm'])
plt.plot(cv_result['rf'])
plt.plot(cv_result['ann'])
plt.title('Models Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Trained fold')
plt.xticks([k for k in range(n_folds)])
plt.legend(['logreg', 'tree', 'randomforest', 'ann', 'svm'], loc='upper left')
plt.show()

#####################TEST ON NEW DATASET

test_df_raw = pd.read_csv('Test.csv')
test = test_df_raw.copy()
test.head()

# Create and train model on train data sample
model_test = ann()
model_test.fit(X, y)

# Predict for test data sample
prediction = model_test.predict(test)

from sklearn.metrics import classification_report,confusion_matrix
print(confusion_matrix(y_test,ann_prediction))
print(classification_report(y_test,ann_prediction))

result_df = test_df_raw.copy()
result_df['Cluster'] = prediction
result_df.to_csv('Test.csv', columns=['Cluster'], index=False)

Classification of Informal Buildings/Classification.py


import pandas as pd
import pickle
import xgboost as xgb
import lightgbm as lgb
from catboost import CatBoostClassifier
import datetime
import glob
import numpy as np

def ensemble_models(df):
    """
        This Function is supposed to read all files in local dir with patter '*MODEL.pkl',
        load these models, append them in a vector, then avegare them.
    """

    # os.chdir("/mydir")
    y_pred = np.zeros(test.shape[0])  # Vector to be filled
    for file in glob.glob("*MODEL.pkl"):
        print(file)
        model = pickle.load(open(file, 'rb'))
        if 'LGB' in file: # Load LGB Models
            y_pred += np.array(model.predict(df))
        elif 'XGB' in file: # Load XGBoost Models
            y_pred += np.array(model.predict(xgb.DMatrix(df.values)))
        elif 'CatBoost' in file:
            y_pred += np.array(model.predict_proba(df)[:, 1])
    lenn = len(glob.glob("*MODEL.pkl"))
    print(f'len: {lenn}')
    y_pred /= len(glob.glob("*MODEL.pkl"))
    return y_pred

test = pd.read_pickle("test.pkl")
test_id = test['ID_code'].values
test.drop(['ID_code'], axis=1, inplace=True)
y_pred = ensemble_models(df=test)

submission = pd.DataFrame({"ID_code": test_id})
submission['target'] = y_pred
filename = "ENSEMBLE_" + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ".csv"
filename = filename.replace(':', '_')
submission.to_csv(filename, index=False)


# Implement a class to hold room information. This should have name and
# description attributes.
from item import Item

class Room:
    # constructor
    def __init__(self, name, description, items=[]):
        # instance attributes
        self.name = name
        self.description = description
        self.items = items
        # defaults to null until we check for a valid association
        self.n_to = None
        self.s_to = None
        self.e_to = None
        self.w_to = None

    def __str__(self):
        return f'Room(name: {self.name}, description: {self.description}, items: {[str(item) for item in self.items]})'

    def __repr__(self):
        """
      REPR method for the Room class
      """
        return f"Room({repr(self.name)}, {repr(self.description)}, {repr(self.items)} )"

k = Item("Keys", "An ancient gold key that shines with an ethereal shinner.")
#print(k)
s = Item(
    "Sword",
    "Those sparks during battles are REAL! Our knights use real weapons - even swords made from titanium!"
)

# second argument in Player class - current_room (Room instance below)
r = Room("Outside Cave Entrance", "North of you, the cave mount beckons",
         [k, s])

#print(r)
# current_room.name = "Outside Cave Entrance"
# current_room.description = "North of you, the cave mount beckons"


"""Base document class."""
import contextlib
import warnings
from collections import OrderedDict

from bson import ObjectId, SON

from aiomongodel.errors import ValidationError
from aiomongodel.queryset import MotorQuerySet
from aiomongodel.fields import Field, ObjectIdField, SynonymField, _Empty
from aiomongodel.utils import snake_case

class Meta:
    """Storage for Document meta info.

    Attributes:
        collection_name: Name of the document's db collection (note that
            it should be specified as ``collection`` Meta class attribute).
        indexes: List of ``pymongo.IndexModel`` for collection.
        queryset: Query set class to query documents.
        default_query: Each query in query set will be extended using this
            query through ``$and`` operator.
        default_sort: Default sort expression to order documents in ``find``.
        fields: OrderedDict of document fields as ``{field_name => field}``.
        fields_synonyms: Dict of synonyms for field
            as ``{field_name => synonym_name}``.
        codec_options: Collection's codec options.
        read_preference: Collection's read preference.
        write_concern: Collection's write concern.
        read_concern: Collection's read concern.

    """

    OPTIONS = {'queryset', 'collection',
               'default_query', 'default_sort',
               'fields', 'fields_synonyms', 'indexes',
               'codec_options', 'read_preference', 'read_concern',
               'write_concern'}

    def __init__(self, **kwargs):
        self._validate_options(kwargs)

        self.queryset = kwargs.get('queryset', None)
        self.collection_name = kwargs.get('collection', None)
        self.default_query = kwargs.get('default_query', {})
        self.default_sort = kwargs.get('default_sort', None)
        self.fields = kwargs.get('fields', None)
        self.fields_synonyms = kwargs.get('fields_synonyms', None)
        self.indexes = kwargs.get('indexes', None)

        self.codec_options = kwargs.get('codec_options', None)
        self.read_preference = kwargs.get('read_preference', None)
        self.read_concern = kwargs.get('read_concern', None)
        self.write_concern = kwargs.get('write_concern', None)

    def _validate_options(self, kwargs):
        keys = set(kwargs.keys())
        diff = keys - self.__class__.OPTIONS
        if diff:
            # TODO: change Exception type
            raise ValueError(
                'Unrecognized Meta options: {0}.'.format(', '.join(diff)))

    def collection(self, db):
        """Get collection for documents.

        Args:
            db: Database object.

        Returns:
            Collection object.
        """
        return db.get_collection(
            self.collection_name,
            read_preference=self.read_preference,
            read_concern=self.read_concern,
            write_concern=self.write_concern,
            codec_options=self.codec_options)

class BaseDocumentMeta(type):
    """Base metaclass for documents."""

    meta_options_class = Meta

    def __new__(mcls, name, bases, namespace):
        """Create new Document class.

        Gather meta options, gather fields, set document's meta.
        """
        new_class = super().__new__(mcls, name, bases, namespace)

        if name in {'Document', 'EmbeddedDocument'}:
            return new_class

        # prepare meta options from Meta class of the new_class if any.
        options = mcls._get_meta_options(new_class)

        # gather fields
        (options['fields'],
         options['fields_synonyms']) = mcls._get_fields(new_class)

        setattr(new_class, 'meta', mcls.meta_options_class(**options))

        return new_class

    @classmethod
    def _get_fields(mcls, new_class):
        """Gather fields and fields' synonyms."""
        # we should search for fields in all bases classes in reverse order
        # than python search for attributes so that fields could be
        # overwritten in subclasses.
        # As bases we use __mro__.
        fields = OrderedDict()
        synonyms = dict()
        # there are no fields in base classes.
        ignore_bases = {'object', 'BaseDocument',
                        'Document', 'EmbeddedDocument'}
        mro_ns_gen = (cls.__dict__
                      for cls in reversed(new_class.__mro__)
                      if cls.__name__ not in ignore_bases)

        for ns in mro_ns_gen:
            for name, item in ns.items():
                if isinstance(item, Field):
                    if not item.name:
                        item.name = name
                    fields[name] = item
                elif isinstance(item, SynonymField):
                    synonyms[item] = name

        return fields, {item.original_field_name: name
                        for item, name in synonyms.items()}

    @classmethod
    def _get_meta_options(mcls, new_class):
        """Get meta options from Meta class attribute."""
        doc_meta_options = {}
        doc_meta = new_class.__dict__.get('Meta', None)
        if doc_meta:
            doc_meta_options = {key: doc_meta.__dict__[key]
                                for key in doc_meta.__dict__
                                if not key.startswith('__')}

        return doc_meta_options

class DocumentMeta(BaseDocumentMeta):
    """Document metaclass.

    This meta class add ``_id`` field if it is not specified in
    document class.

    Set collection name for document to snake case of the document class name
    if it is not specified in Meta class attribute of a the document class.

    Attributes:
        queryset: Default query set class.
        default_id_field: Field to use as ``_id`` field if it is not
            specified in document class.

    """

    queryset = MotorQuerySet
    default_id_field = ObjectIdField(name='_id', required=True,
                                     default=lambda: ObjectId())

    @classmethod
    def _get_fields(mcls, new_class):
        fields, synonyms = super()._get_fields(new_class)

        # add _id field if needed
        if '_id' not in fields:
            fields['_id'] = mcls.default_id_field
            setattr(new_class, '_id', mcls.default_id_field)
            return fields, synonyms

        if not fields['_id'].required:
            raise ValueError(
                "'{0}._id' field should be required.".format(
                    new_class.__name__))

        return fields, synonyms

    @classmethod
    def _get_meta_options(mcls, new_class):
        meta_options = super()._get_meta_options(new_class)

        if 'collection' not in meta_options:
            meta_options['collection'] = snake_case(new_class.__name__)

        if 'queryset' not in meta_options:
            meta_options['queryset'] = mcls.queryset

        return meta_options

class EmbeddedDocumentMeta(BaseDocumentMeta):
    """Embedded Document metaclass."""

class BaseDocument(object):
    """Base class for Document and EmbeddedDocument."""

    def __init__(self, *, _empty=False, **kwargs):
        """Initialize document.

        Args:
            _empty (bool): If True return an empty document without setting
                any field.
            **kwargs: Fields values to set. Each key should be a field name
                not a mongo name of the field.
        """
        self._data = OrderedDict()
        if _empty:
            return

        for field_name, field in self.meta.fields.items():
            try:
                value = self._get_field_value_from_data(kwargs, field_name)
            except KeyError:
                value = field.default

            if value is not _Empty:
                setattr(self, field_name, value)

    def to_data(self):
        """Return internal data of the document.

        .. note::
            Internal data can contain embedded document objects,
            lists etc.

        Returns:
            OrderedDict: Data of the document.
        """
        # TODO: Add recursive parameter
        return self._data

    def _get_field_value_from_data(self, data, field_name):
        """Retrieve value from data for given field_name.

        Try use synonym name if field's name is not in data.

        Args:
            data (dict): Data in form {field_name => value}.
            field_name (str): Field's name.

        Raises:
            KeyError: If there is no value in data for given field_name.
        """
        with contextlib.suppress(KeyError):
            return data[field_name]
        # try synonym name
        return data[self.meta.fields_synonyms[field_name]]

    def _set_mongo_data(self, data):
        """Set document's data using mongo data."""
        self._data = OrderedDict()
        for field_name, field in self.meta.fields.items():
            with contextlib.suppress(KeyError):  # ignore missed fields
                self._data[field_name] = field.from_mongo(
                    data[field.mongo_name])

        return self

    def populate_with_data(self, data):
        """Populate document object with data.

        Args:
            data (dict): Document data in form {field_name => value}.

        Returns:
            Self instance.

        Raises:
            AttributeError: On wrong field name.
        """
        # TODO: should we ignore wrong field_names?
        for field_name, value in data.items():
            setattr(self, field_name, value)
        return self

    def to_mongo(self):
        """Convert document to mongo format."""
        son = SON()
        for field_name, field in self.meta.fields.items():
            if field_name in self._data:
                son[field.mongo_name] = field.to_mongo(self._data[field_name])

        return son

    @classmethod
    def from_mongo(cls, data):
        """Create document from mongo data.

        Args:
            data (dict): SON data loaded from mongodb.

        Returns:
            Document instance.
        """
        inst = cls(_empty=True)
        inst._set_mongo_data(data)
        return inst

    @classmethod
    def from_data(cls, data):
        """Create document from user provided data.

        Args:
            data (dict): Data dict in form {field_name => value}.

        Returns:
            Document isinstance.
        """
        return cls(**data)

    def validate(self):
        """Validate data.

        Returns:
            Self instance.

        Raises:
            ValidationError: If document's data is not valid.
        """
        self.__class__.validate_document(self)
        return self

    @classmethod
    def validate_document(cls, document):
        """Validate given document.

        Args:
            document: Document instance to validate.

        Raises:
            ValidationError: If document's data is not valid.
        """
        errors = {}
        for field_name, field in cls.meta.fields.items():
            try:
                field.validate(document._data[field_name])
            except ValidationError as e:
                errors[field_name] = e
            except KeyError:
                if field.required:
                    errors[field_name] = ValidationError('field is required')

        if errors:
            raise ValidationError(errors)

class Document(BaseDocument, metaclass=DocumentMeta):
    """Base class for documents.

    Each document class should be defined by inheriting from this
    class and specifying fields and optionally meta options using internal
    Meta class.

    Fields are inherited from base classes and can be overwritten.

    Meta options are NOT inherited.

    Possible meta options for ``class Meta``:

    - ``collection``: Name of the document's db collection.
    - ``indexes``: List of ``pymongo.IndexModel`` for collection.
    - ``queryset``: Query set class to query documents.
    - ``default_query``: Each query in query set will be extended using
      this query through ``$and`` operator.
    - ``default_sort``: Default sort expression to order documents in
      ``find``.
    - ``codec_options``: Collection's codec options.
    - ``read_preference``: Collection's read preference.
    - ``write_concern``: Collection's write concern.
    - ``read_concern``: Collection's read concern.

    .. note::
        Indexes are not created automatically. Use
        ``MotorQuerySet.create_indexes`` method to create document's indexes.

    Example:

    .. code-block:: python

        from pymongo import IndexModel, ASCENDING, DESCENDING

        class User(Document):
            name = StrField(regex=r'^[a-zA-Z]{6,20}$')
            is_active = BoolField(default=True)
            created = DateTimeField(default=lambda: datetime.utcnow())

            class Meta:
                # define a collection name
                collection = 'users'
                # define collection indexes. Use
                # await User.q(db).create_indexes()
                # to create them on application startup.
                indexes = [
                    IndexModel([('name', ASCENDING)], unique=True),
                    IndexModel([('created', DESCENDING)])]
                # order by `created` field by default
                default_sort = [('created', DESCENDING)]

        class ActiveUser(User):
            is_active = BoolField(default=True, choices=[True])

            class Meta:
                collection = 'users'
                # specify a default query to work ONLY with
                # active users. So for example
                # await ActiveUser.q(db).count({})
                # will count ONLY active users.
                default_query = {'is_active': True}

    """

    @classmethod
    def q(cls, db, session=None):
        """Return queryset object.

        Args:
            db: Motor database object.
            session: Motor client session object.

        Returns:
            MotorQuerySet: Queryset object.
        """
        return cls.meta.queryset(cls, db, session=session)

    @classmethod
    def coll(cls, db):
        """Return raw collection object.

        Args:
            db: Motor database object.

        Returns:
            MotorCollection: Raw Motor collection object.
        """
        return cls.meta.collection(db)

    @classmethod
    async def create(cls, db, session=None, **kwargs):
        """Create document in mongodb.

        Args:
            db: Database instance.
            session: Motor session object.
            **kwargs: Document's fields values.

        Returns:
            Created document instance.

        Raises:
            ValidationError: If some fields are not valid.
        """
        warnings.warn("Use `create` method of `queryset` instead",
                      DeprecationWarning,
                      stacklevel=2)

        inst = cls.from_data(kwargs)
        return await inst.save(db, do_insert=True, session=session)

    async def save(self, db, do_insert=False, session=None):
        """Save document in mongodb.

        Args:
            db: Database instance.
            do_insert (bool): If ``True`` always perform ``insert_one``, else
                perform ``replace_one`` with ``upsert=True``.
            session: Motor session object.
        """
        data = self.to_mongo()
        if do_insert:
            await self.__class__.q(db, session=session).insert_one(data)
        else:
            await self.__class__.q(db, session=session).replace_one(
                    {'_id': data['_id']},
                    data, upsert=True)

        return self

    async def reload(self, db, session=None):
        """Reload current object from mongodb."""
        cls = self.__class__
        data = await cls.coll(db).find_one(self.query_id, session=session)
        self._set_mongo_data(data)
        return self

    async def update(self, db, update_document, session=None):
        """Update current object using query.

        Usage:

        .. code-block:: python

            class User(Document):
                name = StrField()
                value = IntField(default=0)

            async def go(db):
                u = await User(name='xxx').save(db)
                await u.update(db,
                               {'$set': {User.name.s: 'yyy'},
                                '$inc': {User.value.s: 1}})

        """
        qs = self.__class__.q(db, session=session)
        count = await qs.update_one(self.query_id, update_document)
        # TODO: maybe we should return number of updates or raise if it's 0.
        if count > 0:
            await self.reload(db, session=session)

        return self

    async def delete(self, db, session=None):
        """Delete current object from db."""
        qs = self.__class__.q(db, session=session)
        return await qs.delete_one(self.query_id)

    @property
    def query_id(self):
        return {'_id': self.__class__._id.to_mongo(self._id)}

    @classmethod
    async def create_collection(self, db, session=None):
        """Create collection for documents.

        Args:
            db: Database object.

        Returns:
            Collection object.
        """
        return await db.create_collection(
            self.meta.collection_name,
            read_preference=self.meta.read_preference,
            read_concern=self.meta.read_concern,
            write_concern=self.meta.write_concern,
            codec_options=self.meta.codec_options,
            session=session)

class EmbeddedDocument(BaseDocument, metaclass=EmbeddedDocumentMeta):
    """Base class for embedded documents."""


from os.path import isfile, isdir
from os import makedirs, system
import shutil

opening_files_txt = """You should immediately notice that we import another handy command named exists. \n This returns True if a file exists, based on its name in a string as an argument. \n
It returns False if not. We'll be using this function in the second half of this book to do lots of things, \n but right now you should see how you can import it. \n Using import is a way to get tons of free code other better (well, usually) \n
programmers have written so you do not have to write it. """

new_file = r'.\open_test.txt'

if isfile(new_file)  == True:
    print ('This file already exists' )
else:

    object_new_file = open(new_file, 'w')

    object_new_file.write(opening_files_txt)

    object_new_file.close()

    object_new_file = open(new_file, 'r')

    for line in new_file:
        if line != '':
            print(object_new_file.readline())
        if line == '':
            print('Finished reading file')

    object_new_file.close()

sub_dir = './text/'
makedirs(sub_dir, exist_ok=True)

def copy_file(src, dest):
    try:
        shutil.copy(src, dest)
    # eg. src and dest are the same file
    except shutil.Error as e:
        print('Error: %s' % e)
    # eg. source or destination doesn't exist
    except IOError as e:
        print('Error: %s' % e.strerror)

copy_file (new_file, sub_dir )
old_filename = 'open_test'
new_filename ='copied_open_test.txt'
system('old_filename new_filename')


import threading
from contextlib import contextmanager

_tls = threading.local()

@contextmanager
def _nested():
    _tls.level = getattr(_tls, "level", 0) + 1
    try:
        yield "   " * _tls.level
    finally:
        _tls.level -= 1

@contextmanager
def _recursion_lock(obj):
    if not hasattr(_tls, "history"):
        _tls.history = []  # can't use set(), not all objects are hashable
    if obj in _tls.history:
        yield True
        return
    _tls.history.append(obj)
    try:
        yield False
    finally:
        _tls.history.pop(-1)

def humanize(cls):
    def __repr__(self):
        if getattr(_tls, "level", 0) > 0:
            return str(self)
        else:
            attrs = ", ".join("%s = %r" % (k, v) for k, v in self.__dict__.items())
            return "%s(%s)" % (self.__class__.__name__, attrs)

    def __str__(self):
        with _recursion_lock(self) as locked:
            if locked:
                return "<...>"
            with _nested() as indent:
                attrs = []
                for k, v in self.__dict__.items():
                    if k.startswith("_"):
                        continue
                    if isinstance(v, (list, tuple)) and v:
                        attrs.append("%s%s = [" % (indent, k))
                        with _nested() as indent2:
                            for item in v:
                                attrs.append("%s%r," % (indent2, item))
                        attrs.append("%s]" % (indent,))
                    elif isinstance(v, dict) and v:
                        attrs.append("%s%s = {" % (indent, k))
                        with _nested() as indent2:
                            for k2, v2 in v.items():
                                attrs.append("%s%r: %r," % (indent2, k2, v2))
                        attrs.append("%s}" % (indent,))
                    else:
                        attrs.append("%s%s = %r" % (indent, k, v))
                if not attrs:
                    return "%s()" % (self.__class__.__name__,)
                else:
                    return "%s:\n%s" % (self.__class__.__name__, "\n".join(attrs))

    cls.__repr__ = __repr__
    cls.__str__ = __str__
    return cls


import socket
import qrcode

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
s.close()

img = qrcode.make('http://'+ip+':6500')
img.save('web_address.png')


def extractKoalasplaygroundCom(item):
	'''
	Parser for 'koalasplayground.com'
	'''

	bad_tags = ['Films', 'awards', 'TW & C dramas', 'Miscellaneous', 'K-dramas', 'Music', 'My Loves', 'J-doramas', 'fashion', 'Musings']

	if any((bad in item['tags'] for bad in bad_tags)):
		return None

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('PRC',       'PRC',                      'translated'),
		('Loiterous', 'Loiterous',                'oel'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


# Dado un grupo de 20 estudiantes que cursaron la materia Algoritmos, se desea saber cuál es el promedio del grupo, cual fue la nota más alta y cual la más baja.

suma=0

for i in range(1,21):
    nota =float(input(f"ingrese la nota {i}: "))
    suma = suma+nota

promedio = suma/7

print("El promedio es", promedio)


from fastapi import FastAPI, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware

from .server.routers import gpus, price
from .server.tasks import crawler

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins="*",
    allow_credentials=True,
    allow_methods=["GET"],
    allow_headers=["*"],
)

app.include_router(gpus.router)
app.include_router(price.router)

def start_crawling():
    crawler.start()

@app.get("/", tags=["root"])
def get_root(background_tasks: BackgroundTasks):
    background_tasks.add_task(start_crawling)
    return {"message": "This is a root"}


import setuptools

def requirements():
    with open('requirements.txt', "r") as fh:
        return [x for x in fh.read().split('\n') if x]

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(name='gaitpy',
                 version='1.6.1',
                 description='Read and process raw vertical accelerometry data from a lumbar sensor during gait; calculate clinical gait characteristics.',
                 long_description=long_description,
                 long_description_content_type="text/markdown",
                 url='http://github.com/matt002/gaitpy',
                 packages=setuptools.find_packages(),
                 author='Matthew Czech',
                 author_email='czech1117@gmail.com',
                 keywords=['gait', 'gaitpy', 'lumbar', 'waist', 'sensor', 'wearable', 'continuous wavelet', 'inverted pendulum', 'czech'],
                 classifiers=["Programming Language :: Python :: 3.6",
                              "License :: OSI Approved :: MIT License"],
                 license='MIT',
                 zip_safe=False,
                 install_requires=requirements(),
                 include_package_data=True)


from tkinter import *
from tkinter import filedialog as Fichero

ruta = ""

def nuevo():
    texto.delete(1.0, "end")
    root.title("Mi editor")
    mensaje.set("Nuevo Archivo")

def abrir():
    global ruta
    ruta = Fichero.askopenfilename(
        initialdir='.',
        filetypes=(("Ficheros de texto", "*.txt"),
        ),
        title="Abrir un fichero."
    )
    if ruta:
        with open(ruta, "r") as archivo:
            contenido = archivo.read()
            texto.delete("1.0", END)
            texto.insert(END, contenido)
            archivo.close()
            mensaje.set("Archivo abierto con exito!")

def guardar():
    global ruta
    if ruta != "":
        contenido = texto.get(1.0, 'end')
        fichero = open(ruta, 'w+')
        fichero.write(contenido)
        fichero.close()
        mensaje.set('Archivo guardado con exito!')
    else:
        guardar_como()

def guardar_como():
    global ruta
    ruta = Fichero.asksaveasfilename(title = 'Guardar un archivo',
                                        defaultextension = '.txt')
    if ruta is not None:
        contenido = texto.get("1.0", END)
        with open(ruta, 'w') as archivo:
            archivo.write(contenido)
            archivo.close()
        mensaje.set("Archivo guardado con exito!")

root = Tk()
root.title("El bloc de Paola")

menubar = Menu(root)
root.config(menu = menubar, background="pink")
filemenu = Menu(menubar, tearoff = 0)
filemenu.add_command(label='Nuevo', command=nuevo)
filemenu.add_command(label='Abrir', command = abrir)
filemenu.add_command(label='Guardar', command=guardar)
filemenu.add_command(label='Guardar como', command=guardar_como)
filemenu.add_separator()
filemenu.add_command(label='Salir', command = root.destroy)
menubar.add_cascade(label = 'Archivo', menu = filemenu)

texto = Text(root)
texto.pack(fill = 'both', expand = 1)
texto.config(font=('Arial', 18),
            padx=15,
            pady=15,
            selectbackground='#ff0080')

mensaje = StringVar()
mensaje.set("Bienvenido a tu bloc de notas")
monitor = Label(root, textvar = mensaje, justify= "center", background="pink")
monitor.pack(side = "left")

root.mainloop()


"""move osm id generation to loader code

Revision ID: 106942da4dcc
Revises: ae776f283429
Create Date: 2022-03-29 17:52:28.916521

"""
import os

from alembic import op

here = os.path.dirname(os.path.realpath(__file__))

# revision identifiers, used by Alembic.
revision = "106942da4dcc"
down_revision = "8832d7a1b5fb"
branch_labels = None
depends_on = None

revision_dir = f"{here}/{revision}"

# idea from https://github.com/tbobm/alembic-sequeled
def process_migration(script_name: str):
    filename = f"{revision_dir}/{script_name}.sql"

    query = "\n".join(open(filename))
    if len(query) > 0:
        op.execute(query)

def upgrade():
    process_migration("upgrade")

def downgrade():
    process_migration("downgrade")


"""
File containing simple server-side validators in form of functors
"""
from rest_framework import serializers
import re

class ValidatePattern:
    """
    Functor class for validating string pattern
    Using Regular Expressions
    """
    def __init__(self, pattern: str, msg: str = None):
        self.pattern = pattern
        self.msg = msg

    def __call__(self, value):
        if not re.fullmatch(self.pattern, value):
            raise serializers.ValidationError(self.msg)

class ValidateName:
    """
    Functor class for validating real name
    Based on word count limit and checking symbols different from letters and hyphens
    """
    def __init__(self, min_words=2, max_words=3, msg: str = None):
        self.min_words = min_words
        self.max_words = max_words

        self.msg = msg

    def __call__(self, value):
        words = value.split()
        if not (self.min_words <= len(words) <= self.max_words):
            raise serializers.ValidationError(self.msg)

        for word in words:
            if not word.isalpha():
                sub_words = word.split("-")

                for sub_word in sub_words:
                    if not sub_word.isalpha():
                        raise serializers.ValidationError(self.msg)


import sys

data = []
name = "e140n40"

with open("rawmaps/" + name + ".dem", "rb") as fr:
    while True:
        a = fr.read(1)
        b = fr.read(1)
        if not a or not b:
            break

        data.append((int.from_bytes(a, "big", signed=True) << 8) + int.from_bytes(b, "big", signed=True))
        # data.append(int.from_bytes(a, "big", signed=True))

dsdata = []
for row in range(0, 6000, 5):
    for col in range(0, 4800, 5):
        val = data[row * 4800 + col]
        for i in range(5):
            for j in range(5):
                index = (row + i) * 4800 + col + j
                val = max(val, data[index])

        dsdata.append(val)

with open("maps/" + name + ".dem", "wb") as fw:
    for i in dsdata:
        ba = bytearray(i.to_bytes(2, sys.byteorder, signed=True))
        fw.write(ba)