"""
Cubic hermite splines in 1d, 2d, and 3d

Related to FYS-4096 Computational Physics
exercise 3 assignments.

By Ilkka Kylanpaa on January 2019
"""

import numpy as np
import matplotlib.pyplot as plt

def p1(t):
    return (1.+2.*t)*(t-1.)**2
def p2(t):
    return t**2*(3.-2.*t)
def q1(t):
    return t*(t-1.)**2
def q2(t):
    return t**2*(t-1.)

def init_1d_spline(x,f,h):
    # now using complete boundary conditions
    # - natural boundary conditions commented
    a=np.zeros((len(x),))
    b=np.zeros((len(x),))
    c=np.zeros((len(x),))
    d=np.zeros((len(x),))
    fx=np.zeros((len(x),))

    # a[0]=1.0 # not needed
    b[0]=1.0

    # natural boundary conditions
    #c[0]=0.5
    #d[0]=1.5*(f[1]-f[0])/(x[1]-x[0])

    # complete boundary conditions
    c[0]=0.0
    d[0]=(f[1]-f[0])/(x[1]-x[0])

    for i in range(1,len(x)-1):
        d[i]=6.0*(h[i]/h[i-1]-h[i-1]/h[i])*f[i]-6.0*h[i]/h[i-1]*f[i-1]+6.0*h[i-1]/h[i]*f[i+1]
        a[i]=2.0*h[i]
        b[i]=4.0*(h[i]+h[i-1])
        c[i]=2.0*h[i-1]
    #end for

    b[-1]=1.0
    #c[-1]=1.0 # not needed

    # natural boundary conditions
    #a[-1]=0.5
    #d[-1]=1.5*(f[-1]-f[-2])/(x[-1]-x[-2])

    # complete boundary conditions
    a[-1]=0.0
    d[-1]=(f[-1]-f[-2])/(x[-1]-x[-2])

    # solve tridiagonal eq. A*f=d
    c[0]=c[0]/b[0]
    d[0]=d[0]/b[0]
    for i in range(1,len(x)-1):
        temp=b[i]-c[i-1]*a[i]
        c[i]=c[i]/temp
        d[i]=(d[i]-d[i-1]*a[i])/temp
    #end for

    fx[-1]=d[-1]
    for i in range(len(x)-2,-1,-1):
        fx[i]=d[i]-c[i]*fx[i+1]
    #end for

    return fx

"""
Add smoothing functions

def smooth1d(x,f,factor=3):
    ...
    ...
    return ...

def smooth2d(x,y,f,factor=3):
    ...
    ...
    return ...

def smooth3d(x,y,z,f,factor=3):
    ...
    ...
    ...
    return ...
"""

class spline:

    def __init__(self,*args,**kwargs):
        self.dims=kwargs['dims']
        if (self.dims==1):
            self.x=kwargs['x']
            self.f=kwargs['f']
            self.hx=np.diff(self.x)
            self.fx=init_1d_spline(self.x,self.f,self.hx)
        elif (self.dims==2):
            self.x=kwargs['x']
            self.y=kwargs['y']
            self.f=kwargs['f']
            self.hx=np.diff(self.x)
            self.hy=np.diff(self.y)
            self.fx=np.zeros(np.shape(self.f))
            self.fy=np.zeros(np.shape(self.f))
            self.fxy=np.zeros(np.shape(self.f))
            for i in range(max([len(self.x),len(self.y)])):
                if (i<len(self.y)):
                    self.fx[:,i]=init_1d_spline(self.x,self.f[:,i],self.hx)
                if (i<len(self.x)):
                    self.fy[i,:]=init_1d_spline(self.y,self.f[i,:],self.hy)
            #end for
            for i in range(len(self.y)):
                self.fxy[:,i]=init_1d_spline(self.x,self.fy[:,i],self.hx)
            #end for
        elif (self.dims==3):
            self.x=kwargs['x']
            self.y=kwargs['y']
            self.z=kwargs['z']
            self.f=kwargs['f']
            self.hx=np.diff(self.x)
            self.hy=np.diff(self.y)
            self.hz=np.diff(self.z)
            self.fx=np.zeros(np.shape(self.f))
            self.fy=np.zeros(np.shape(self.f))
            self.fz=np.zeros(np.shape(self.f))
            self.fxy=np.zeros(np.shape(self.f))
            self.fxz=np.zeros(np.shape(self.f))
            self.fyz=np.zeros(np.shape(self.f))
            self.fxyz=np.zeros(np.shape(self.f))
            for i in range(max([len(self.x),len(self.y),len(self.z)])):
                for j in range(max([len(self.x),len(self.y),len(self.z)])):
                    if (i<len(self.y) and j<len(self.z)):
                        self.fx[:,i,j]=init_1d_spline(self.x,self.f[:,i,j],self.hx)
                    if (i<len(self.x) and j<len(self.z)):
                        self.fy[i,:,j]=init_1d_spline(self.y,self.f[i,:,j],self.hy)
                    if (i<len(self.x) and j<len(self.y)):
                        self.fz[i,j,:]=init_1d_spline(self.z,self.f[i,j,:],self.hz)
            #end for
            for i in range(max([len(self.x),len(self.y),len(self.z)])):
                for j in range(max([len(self.x),len(self.y),len(self.z)])):
                    if (i<len(self.y) and j<len(self.z)):
                        self.fxy[:,i,j]=init_1d_spline(self.x,self.fy[:,i,j],self.hx)
                    if (i<len(self.y) and j<len(self.z)):
                        self.fxz[:,i,j]=init_1d_spline(self.x,self.fz[:,i,j],self.hx)
                    if (i<len(self.x) and j<len(self.z)):
                        self.fyz[i,:,j]=init_1d_spline(self.y,self.fz[i,:,j],self.hy)
            #end for
            for i in range(len(self.y)):
                for j in range(len(self.z)):
                    self.fxyz[:,i,j]=init_1d_spline(self.x,self.fyz[:,i,j],self.hx)
            #end for
        else:
            print('Either dims is missing or specific dims is not available')
        #end if

    def eval1d(self,x):
        if np.isscalar(x):
            x=np.array([x])
        N=len(self.x)-1
        f=np.zeros((len(x),))
        ii=0
        for val in x:
            i=np.floor(np.where(self.x<=val)[0][-1]).astype(int)
            if i==N:
                f[ii]=self.f[i]
            else:
                t=(val-self.x[i])/self.hx[i]
                f[ii]=self.f[i]*p1(t)+self.f[i+1]*p2(t)+self.hx[i]*(self.fx[i]*q1(t)+self.fx[i+1]*q2(t))
            ii+=1

        return f
    #end eval1d

    def eval2d(self,x,y):
        if np.isscalar(x):
            x=np.array([x])
        if np.isscalar(y):
            y=np.array([y])
        Nx=len(self.x)-1
        Ny=len(self.y)-1
        f=np.zeros((len(x),len(y)))
        A=np.zeros((4,4))
        ii=0
        for valx in x:
            i=np.floor(np.where(self.x<=valx)[0][-1]).astype(int)
            if (i==Nx):
                i-=1
            jj=0
            for valy in y:
                j=np.floor(np.where(self.y<=valy)[0][-1]).astype(int)
                if (j==Ny):
                    j-=1
                u = (valx-self.x[i])/self.hx[i]
                v = (valy-self.y[j])/self.hy[j]
                pu = np.array([p1(u),p2(u),self.hx[i]*q1(u),self.hx[i]*q2(u)])
                pv = np.array([p1(v),p2(v),self.hy[j]*q1(v),self.hy[j]*q2(v)])
                A[0,:]=np.array([self.f[i,j],self.f[i,j+1],self.fy[i,j],self.fy[i,j+1]])
                A[1,:]=np.array([self.f[i+1,j],self.f[i+1,j+1],self.fy[i+1,j],self.fy[i+1,j+1]])
                A[2,:]=np.array([self.fx[i,j],self.fx[i,j+1],self.fxy[i,j],self.fxy[i,j+1]])
                A[3,:]=np.array([self.fx[i+1,j],self.fx[i+1,j+1],self.fxy[i+1,j],self.fxy[i+1,j+1]])

                f[ii,jj]=np.dot(pu,np.dot(A,pv))
                jj+=1
            ii+=1
        return f
    #end eval2d

    def eval3d(self,x,y,z):
        if np.isscalar(x):
            x=np.array([x])
        if np.isscalar(y):
            y=np.array([y])
        if np.isscalar(z):
            z=np.array([z])
        Nx=len(self.x)-1
        Ny=len(self.y)-1
        Nz=len(self.z)-1
        f=np.zeros((len(x),len(y),len(z)))
        A=np.zeros((4,4))
        B=np.zeros((4,4))
        ii=0
        for valx in x:
            i=np.floor(np.where(self.x<=valx)[0][-1]).astype(int)
            if (i==Nx):
                i-=1
            jj=0
            for valy in y:
                j=np.floor(np.where(self.y<=valy)[0][-1]).astype(int)
                if (j==Ny):
                    j-=1
                kk=0
                for valz in z:
                    k=np.floor(np.where(self.z<=valz)[0][-1]).astype(int)
                    if (k==Nz):
                        k-=1
                    u = (valx-self.x[i])/self.hx[i]
                    v = (valy-self.y[j])/self.hy[j]
                    t = (valz-self.z[k])/self.hz[k]
                    pu = np.array([p1(u),p2(u),self.hx[i]*q1(u),self.hx[i]*q2(u)])
                    pv = np.array([p1(v),p2(v),self.hy[j]*q1(v),self.hy[j]*q2(v)])
                    pt = np.array([p1(t),p2(t),self.hz[k]*q1(t),self.hz[k]*q2(t)])
                    B[0,:]=np.array([self.f[i,j,k],self.f[i,j,k+1],self.fz[i,j,k],self.fz[i,j,k+1]])
                    B[1,:]=np.array([self.f[i+1,j,k],self.f[i+1,j,k+1],self.fz[i+1,j,k],self.fz[i+1,j,k+1]])
                    B[2,:]=np.array([self.fx[i,j,k],self.fx[i,j,k+1],self.fxz[i,j,k],self.fxz[i,j,k+1]])
                    B[3,:]=np.array([self.fx[i+1,j,k],self.fx[i+1,j,k+1],self.fxz[i+1,j,k],self.fxz[i+1,j,k+1]])
                    A[:,0]=np.dot(B,pt)
                    B[0,:]=np.array([self.f[i,j+1,k],self.f[i,j+1,k+1],self.fz[i,j+1,k],self.fz[i,j+1,k+1]])
                    B[1,:]=np.array([self.f[i+1,j+1,k],self.f[i+1,j+1,k+1],self.fz[i+1,j+1,k],self.fz[i+1,j+1,k+1]])
                    B[2,:]=np.array([self.fx[i,j+1,k],self.fx[i,j+1,k+1],self.fxz[i,j+1,k],self.fxz[i,j+1,k+1]])
                    B[3,:]=np.array([self.fx[i+1,j+1,k],self.fx[i+1,j+1,k+1],self.fxz[i+1,j+1,k],self.fxz[i+1,j+1,k+1]])
                    A[:,1]=np.dot(B,pt)

                    B[0,:]=np.array([self.fy[i,j,k],self.fy[i,j,k+1],self.fyz[i,j,k],self.fyz[i,j,k+1]])
                    B[1,:]=np.array([self.fy[i+1,j,k],self.fy[i+1,j,k+1],self.fyz[i+1,j,k],self.fyz[i+1,j,k+1]])
                    B[2,:]=np.array([self.fxy[i,j,k],self.fxy[i,j,k+1],self.fxyz[i,j,k],self.fxyz[i,j,k+1]])
                    B[3,:]=np.array([self.fxy[i+1,j,k],self.fxy[i+1,j,k+1],self.fxyz[i+1,j,k],self.fxyz[i+1,j,k+1]])
                    A[:,2]=np.dot(B,pt)
                    B[0,:]=np.array([self.fy[i,j+1,k],self.fy[i,j+1,k+1],self.fyz[i,j+1,k],self.fyz[i,j+1,k+1]])
                    B[1,:]=np.array([self.fy[i+1,j+1,k],self.fy[i+1,j+1,k+1],self.fyz[i+1,j+1,k],self.fyz[i+1,j+1,k+1]])
                    B[2,:]=np.array([self.fxy[i,j+1,k],self.fxy[i,j+1,k+1],self.fxyz[i,j+1,k],self.fxyz[i,j+1,k+1]])
                    B[3,:]=np.array([self.fxy[i+1,j+1,k],self.fxy[i+1,j+1,k+1],self.fxyz[i+1,j+1,k],self.fxyz[i+1,j+1,k+1]])
                    A[:,3]=np.dot(B,pt)

                    f[ii,jj,kk]=np.dot(pu,np.dot(A,pv))
                    kk+=1
                jj+=1
            ii+=1
        return f
    #end eval3d
#end class spline

def main():

    # 1d example
    x=np.linspace(0.,2.*np.pi,20)
    y=np.sin(x)
    spl1d=spline(x=x,f=y,dims=1)
    xx=np.linspace(0.,2.*np.pi,100)
    plt.figure()
    # function
    plt.plot(xx,spl1d.eval1d(xx))
    plt.plot(x,y,'o',xx,np.sin(xx),'r--')
    plt.title('function')

    # 2d example
    fig=plt.figure()
    ax=fig.add_subplot(121)
    x=np.linspace(0.0,3.0,11)
    y=np.linspace(0.0,3.0,11)
    X,Y = np.meshgrid(x,y)
    Z = (X+Y)*np.exp(-1.0*(X*X+Y*Y))
    ax.pcolor(X,Y,Z)
    ax.set_title('original')

    spl2d=spline(x=x,y=y,f=Z,dims=2)
    #figure()
    ax2=fig.add_subplot(122)
    x=np.linspace(0.0,3.0,51)
    y=np.linspace(0.0,3.0,51)
    X,Y = np.meshgrid(x,y)
    Z = spl2d.eval2d(x,y)
    ax2.pcolor(X,Y,Z)
    ax2.set_title('interpolated')

    # 3d example
    x=np.linspace(0.0,3.0,10)
    y=np.linspace(0.0,3.0,10)
    z=np.linspace(0.0,3.0,10)
    X,Y,Z = np.meshgrid(x,y,z)
    F = (X+Y+Z)*np.exp(-1.0*(X*X+Y*Y+Z*Z))
    X,Y= np.meshgrid(x,y)
    fig3d=plt.figure()
    ax=fig3d.add_subplot(121)
    ax.pcolor(X,Y,F[...,int(len(z)/2)])
    ax.set_title('original')

    spl3d=spline(x=x,y=y,z=z,f=F,dims=3)
    x=np.linspace(0.0,3.0,50)
    y=np.linspace(0.0,3.0,50)
    z=np.linspace(0.0,3.0,50)
    X,Y= np.meshgrid(x,y)
    ax2=fig3d.add_subplot(122)
    F=spl3d.eval3d(x,y,z)
    ax2.pcolor(X,Y,F[...,int(len(z)/2)])
    ax2.set_title('interpolated')

    plt.show()
#end main

if __name__=="__main__":
    main()


from datetime import datetime
from typing import Any
from CxAdmin.jsonable import JSONSerializable

class Skill(JSONSerializable):
    id: str
    name: str
    proficiency: int
    added: datetime

    def __init__(
        self,
        id: str,
        name: str,
        proficiency: int,
        added: datetime,
    ):
        self.id = id
        self.name = name
        self.proficiency = proficiency
        self.added = added

    @staticmethod
    def from_json(data: dict[str, Any]) -> "Skill":
        return Skill(
            id=data["id"],
            name=data["name"],
            proficiency=data["proficiency"],
            added=datetime.fromisoformat(data["added"][:-1]),
        )

    def to_json(self) -> dict[str, Any]:
        return {
            "id": self.id,
            "name": self.name,
            "proficiency": self.proficiency,
            "added": self.added.isoformat(),
        }


from ..html.nodes.ElementNode import Node
from .StyledNode import StyledNode

def matchesSelector(elem: Node, selector: dict):

    # Check tag
    if selector["type"] == "tag":
        return selector["name"] == elem.name

    # Check id
    if selector["type"] == "id":
        return selector["name"] == elem.getID()

    # Check classes
    if selector["type"] == "class":
        return selector["name"] in elem.getClasses()

    # Nothing matched
    return False

def getRulesForNode(elem: Node, stylesheet: dict):
    rules = []

    # Iterate through all defined rules
    for rule in stylesheet:

        # Iterate each selector for the rule
        for selector in rule["selectors"]:
            if type(elem) != dict and matchesSelector(elem, selector):

                # Add this rule's declatations to the ruleset
                rules += rule["declarations"]

    return rules

def buildStyleTree(root: Node, stylesheet: dict):
    output = StyledNode()

    # Set node and style data
    output.node = root
    output.style_values = getRulesForNode(root, stylesheet)

    # For each of root's children, add it to the style tree
    for child in root.children:
        if type(child) != dict:
            output.children.append(buildStyleTree(child, stylesheet))

    return output


#coding:utf-8
import re

ttt = re.match('www', 'www.runwwwowwwobwww.comwww')
print(ttt.group())

pattern = 'content\/\d-\d\/\d\/content_\d.htm\?node=40882'
file = open('lawCaseUrl', 'r+', encoding='utf-8')
string = file.read()
result = re.match(r'content/[0-9]-[0-9]/[0-9]/content_[0-9]\.htm\?node=40882', string,flags=0)
print(result)
if result:
    resultList = result.group()
    print(resultList)


from Bio import SeqIO
from differences import diff
from sys import argv

prot_name: str = argv[1]
out = open(prot_name + ".tsv", "w")
out.write("index\tstart\tend\tref\talt\tlocation\tdate\tproteome_id\n")

records = SeqIO.parse(f"{prot_name}.fasta", "fasta")
ref = next(records)
ref_seq: str = ref.seq

gen_index = 1
mut_index = 1
for record in records:
    annotations = record.name.split("|")
    meta = ()
    try:
        meta = (annotations[1].split("/")[1], annotations[2], f"{prot_name}{gen_index}")
        gen_index += 1
    except Exception:
        continue

    tups = diff(ref_seq, record.seq)
    for tup in tups:
        out.write("\t".join([str(mut_index), str(tup[0]), str(tup[1]), tup[2], tup[3], *meta]) + "\n")
        mut_index += 1

out.close()


import sys

import tkinter as tk
from tkinter import ttk
from tkinter import messagebox

from datetime import *
from src.model.ingredient import Ingredient, Lista_Preco
from src.model.recipe import Recipe
from src.model.bolo import Bolo
from src.controller.ingredient_collection import Ingredient_Collection
from src.controller.recipe_collection import Recipe_Collection
from src.controller.bolo_collection import Bolo_Collection

class View():
    ing_coll = Ingredient_Collection()
    recp_coll = Recipe_Collection()
    bolo_coll = Bolo_Collection()

    def __init__(self):
        self.root = tk.Tk()
        self.root.configure(background="#008")
        self.root.geometry("800x600")
        self.container = tk.Frame(self.root)
        self.container.pack(expand=True)

        self.frameMenu()
        self.frameIngrediente()
        self.frameAtt_Ingredient()
        self.frameCdst_Ingredient()
        self.frameReceita()
        self.frameBolo()
        self.frameRlt_Bolo()

        self.frameMenu.grid(row=0, column=0, sticky='nsew')
        self.frameIngr.grid(row=0, column=0, sticky='nsew')
        self.frameAtt_Ingr.grid(row=0, column=0, sticky='nsew')
        self.frameCdst_Ingr.grid(row=0, column=0, sticky='nsew')
        self.frameReceita.grid(row=0, column=0, sticky='nsew')
        self.frameBolo.grid(row=0, column=0, sticky='nsew')
        self.frameRlt_Bolo.grid(row=0, column=0, sticky='nsew')

        self.showFrameMenu()

        self.root.mainloop()

    def showFrameMenu(self):
            self.frameMenu.tkraise()

    def frameMenu(self):
        self.frameMenu = tk.Frame(self.container, bg="#4080ff")

        label = tk.Label(self.frameMenu, pady=10 ,text='IBolo - Doceria', bg="#006494", fg="#FFFFFF", font=("Helvetica", 16))
        label.pack(side='top', pady=10, ipadx=50)

        buttonAddIngrediente = tk.Button(self.frameMenu, text='Cadastrar Ingrediente', command=self.showframeIngr)
        buttonAddIngrediente.pack(side='top',ipadx= 10, ipady=10)

        buttonBuscaIngrediente = tk.Button(self.frameMenu, text='Atualizar custo atribuído', command=self.showframeAtt_Ingr)
        buttonBuscaIngrediente.pack(side='top')

        buttonAddReceita = tk.Button(self.frameMenu, text='Cadastrar novo custo de ingrediente', command=self.showframeCdst_Ingr)
        buttonAddReceita.pack(side='top')

        buttonBuscaReceita = tk.Button(self.frameMenu,text='Cadastrar nova receita', command=self.showframeReceita)
        buttonBuscaReceita.pack(side='top', ipadx= 10, ipady=10, pady=10)

        buttonBuscaReceita = tk.Button(self.frameMenu, text='Cadastrar novo Bolo', command=self.showframeBolo)
        buttonBuscaReceita.pack(side='top',ipadx= 10, ipady=10)

        buttonBuscaReceita = tk.Button(self.frameMenu, text='Emitir relatório de bolo produzido', command=self.showframeRlt_Bolo)
        buttonBuscaReceita.pack(side='top',ipadx= 10)

        label = tk.Label(self.frameMenu, text='By: Yusuf', bg="#006494", fg="#FFFFFF", font=("Helvetica", 12))
        label.pack(side='bottom', ipadx=130)

    def showframeIngr(self):
        self.frameIngr.tkraise()

    def showframeAtt_Ingr(self):
        self.frameAtt_Ingr.tkraise()

    def showframeCdst_Ingr(self):
        self.frameCdst_Ingr.tkraise()

    def showframeReceita(self):
        self.frameReceita.tkraise()

    def showframeBolo(self):
        self.frameBolo.tkraise()

    def showframeRlt_Bolo(self):
        self.frameRlt_Bolo.tkraise()

    def showFrame5(self):
        if not self.lista:
            tk.messagebox.showwarning(master=None, title='Erro', message='Ingredientes não selecionados.')
        elif self.entryNameRecipe.get() == '':
            tk.messagebox.showwarning(master=None, title='Erro', message='Nome da receita não informado')

        else:
            self.proximaLista()
            self.prox_Lista.tkraise()

    def frameIngrediente(self):
        self.frameIngr = tk.Frame(self.container)

        label = tk.Label(self.frameIngr, text='INGREDIENTE', bg="#006494", fg="#FFFFFF", font=("Helvetica", 10))
        label.pack(side='top', ipadx=130)

        label = tk.Label(self.frameIngr, text='Nome')
        label.pack(side='top', pady=10)

        self.entryIngrediente = tk.Entry(self.frameIngr, width=20)
        self.entryIngrediente.pack()

        labelUnit = tk.Label(self.frameIngr, text='Tipo de Medida')
        labelUnit.pack(side='top', pady=10)

        self.entryUnit = tk.Entry(self.frameIngr, width=20)
        self.entryUnit.pack()

        label = tk.Label(self.frameIngr, text='Lista de preços com datas')
        label.pack(side='top')
        labelPrecoCompra = tk.Label(self.frameIngr, text='Preço de Compra')
        labelPrecoCompra.pack(side='top')

        self.entryPrecoCompra = tk.Entry(self.frameIngr, width=20)
        self.entryPrecoCompra.pack()

        labelUnitCompra = tk.Label(self.frameIngr, text='Unidade')
        labelUnitCompra.pack(side='top')

        self.entryUnitCompra = tk.Entry(self.frameIngr, width=20)
        self.entryUnitCompra.pack()

        buttonMsg = tk.Button(self.frameIngr, text='Salvar', bg="#4080ff", fg="gray1" , command=self.salvarIngrediente)
        buttonMsg.pack(side='top', pady=20)

        buttonBack = tk.Button(self.frameIngr, text='Tela anterior',
                               command=self.showFrameMenu, bg="#4080ff", fg="gray1")
        buttonBack.pack(side='bottom', anchor="sw")

    def frameAtt_Ingredient(self):
        self.frameAtt_Ingr = tk.Frame(self.container)
        labelAt = tk.Label(self.frameAtt_Ingr, text='Atualizar', bg="#006494", fg="#FFFFFF", font=("Helvetica", 10) )
        labelAt.pack(side='top', ipadx=130)
        labelIngredienteAt = tk.Label(self.frameAtt_Ingr, text='Ingrediente')
        labelIngredienteAt.pack(side='top', pady=10)
        self.entryOption = tk.Entry(self.frameAtt_Ingr, width=20)
        self.entryOption.pack()

        buttonMsg = tk.Button(self.frameAtt_Ingr, text='Buscar', bg="#4080ff", fg="gray1",
                              command=self.buscarIngrediente)
        buttonMsg.pack(side='top', pady=10)

        self.dadosAtualizarCusto()

        buttonBack = tk.Button(self.frameAtt_Ingr, text='Tela anterior',
                               command=self.showFrameMenu, bg="#4080ff", fg="gray1")
        buttonBack.pack(side='bottom', anchor="sw")

    def frameCdst_Ingredient(self):
        self.frameCdst_Ingr = tk.Frame(self.container)

        labelAt = tk.Label(self.frameCdst_Ingr,text='Cadastrar Novo Custo', bg="#006494", fg="#FFFFFF", font=("Helvetica", 10))
        labelAt.pack(side='top', ipadx=130)

        labelIngredienteNew = tk.Label(self.frameCdst_Ingr, text='Ingrediente')
        labelIngredienteNew.pack(side='top',pady=10)
        self.entryOptionNew = tk.Entry(self.frameCdst_Ingr, width=20)
        self.entryOptionNew.pack()

        buttonMsg = tk.Button(self.frameCdst_Ingr, text='Buscar',  bg="#4080ff", fg="gray1",
                              command=self.buscarIngredienteCadastro)
        buttonMsg.pack(side='top', pady=10)

        self.dadosCadastrarCusto()

        buttonBack = tk.Button(self.frameCdst_Ingr, text='Tela anterior',
                               command=self.showFrameMenu, bg="#4080ff", fg="gray1")
        buttonBack.pack(side='bottom', anchor="sw")

    def frameReceita(self):
        self.frameReceita = tk.Frame(self.container)

        labelAt = tk.Label(self.frameReceita, text='Cadastrar Receita', bg="#006494", fg="#FFFFFF", font=("Helvetica", 10))
        labelAt.pack(side='top', ipadx=130)

        labelRec = tk.Label(self.frameReceita, text='Nome para receita')
        labelRec.pack(side='top', pady=10)
        self.entryNameRecipe = tk.Entry(self.frameReceita, bg='whitesmoke', width=20)
        self.entryNameRecipe.pack()
        self.lista = []

        labelIng = tk.Label(self.frameReceita, text='Ingredientes')
        labelIng.pack(side='top', pady=10)
        self.entryOptionRecipe = tk.Entry(self.frameReceita, bg='whitesmoke', width=20)
        self.entryOptionRecipe.pack()

        buttonMsg = tk.Button(self.frameReceita, text='Buscar', bg="#4080ff", fg="gray1",command=self.newEntry)
        buttonMsg.pack(side='top')
        self.listOption = tk.Listbox(self.frameReceita)
        self.labelOptions = tk.Label(self.frameReceita, text="Ingredientes selecionados: ")
        self.labelOptions.pack()
        self.listOption.pack()

        buttonMsg = tk.Button(self.frameReceita, text='Proximo', bg="#4080ff", fg="gray1",command=self.showFrame5)
        buttonMsg.pack(side='top')

        buttonBack = tk.Button(self.frameReceita, text='Tela anterior', command=self.showFrameMenu, bg="#4080ff", fg="gray1")
        buttonBack.pack(side='bottom', anchor="sw")

    def frameBolo(self):
        self.frameBolo = tk.Frame(self.container)

        label = tk.Label(self.frameBolo, text='Nome do Bolo')
        label.pack(side='top')

        self.entryBolo = tk.Entry(self.frameBolo, width=20)
        self.entryBolo.pack()

        labelBoloRecipe = tk.Label(self.frameBolo, text='Receita')
        labelBoloRecipe.pack(side='top')

        self.entryBoloRecipe = tk.Entry(self.frameBolo, width=20)
        self.entryBoloRecipe.pack()

        buttonMsg = tk.Button(self.frameBolo, text='Buscar', command=self.calculoCustoIngrediente,  bg="#4080ff", fg="gray1")
        buttonMsg.pack(side='top', pady=10)

        labelBoloVenda = tk.Label(self.frameBolo, text='Preço de Venda')
        labelBoloVenda.pack(side='top')

        self.entryBoloSell = tk.Entry(self.frameBolo, width=20)
        self.entryBoloSell.pack()

        labelBoloCliente = tk.Label(self.frameBolo, text='Cliente')
        labelBoloCliente.pack(side='top')

        self.entryBoloCliente = tk.Entry(self.frameBolo, width=20)
        self.entryBoloCliente.pack()

        self.labelBoloIngrediente = tk.Label(self.frameBolo, text='Ingredientes: ').pack()
        self.ingText = tk.StringVar()
        self.entryIng = tk.Entry(self.frameBolo, state="readonly", text=self.ingText)
        self.entryIng.pack()

        self.labelBoloCustoIngrediente = tk.Label(self.frameBolo, text='Custo: ').pack()
        self.ingCustoText = tk.StringVar()
        self.entryIngCusto = tk.Entry(self.frameBolo, state="readonly", text=self.ingCustoText)
        self.entryIngCusto.pack()

        buttonMsg = tk.Button(self.frameBolo, text='Salvar', command=self.salvarBolo,  bg="#4080ff", fg="gray1")
        buttonMsg.pack(side='top', pady=10)

        buttonBack = tk.Button(self.frameBolo, text='Tela anterior', command=self.showFrameMenu, bg="#4080ff", fg="gray1")
        buttonBack.pack(side='bottom', anchor="w")

    def frameRlt_Bolo(self):
        self.frameRlt_Bolo = tk.Frame(self.container)

        label = tk.Label(self.frameRlt_Bolo, text='Cálculo de Lucro', bg="#006494", fg="#FFFFFF", font=("Helvetica", 10))
        label.pack(side='top', ipadx=130)

        label = tk.Label(self.frameRlt_Bolo, text='Nome do Bolo')
        label.pack(side='top', pady=10)
        self.entryBoloSearch = tk.Entry(self.frameRlt_Bolo, width=20)
        self.entryBoloSearch.pack()

        buttonMsg = tk.Button(self.frameRlt_Bolo, text='Buscar', command=self.calculoLucro, bg="#4080ff", fg="gray1")
        buttonMsg.pack(side='top', pady=10)

        self.labelCusto = tk.Label(self.frameRlt_Bolo, text='Custo: ').pack(pady=10)
        self.ingCustoLucroText = tk.StringVar()
        self.entryIngCusto = tk.Entry(self.frameRlt_Bolo, state="readonly", text=self.ingCustoLucroText)
        self.entryIngCusto.pack()

        self.labelVenda = tk.Label(self.frameRlt_Bolo, text='Preço de Venda: ').pack(pady=10)
        self.ingVendaText = tk.StringVar()
        self.entryIngVenda = tk.Entry(self.frameRlt_Bolo, state="readonly", text=self.ingVendaText)
        self.entryIngVenda.pack()

        self.labelLucro = tk.Label(self.frameRlt_Bolo, text='Lucro: ').pack(pady=10)
        self.ingLucroText = tk.StringVar()
        self.entryIngLucro = tk.Entry(self.frameRlt_Bolo, state="readonly", text=self.ingLucroText)
        self.entryIngLucro.pack()

        buttonBack = tk.Button(self.frameRlt_Bolo, text='Tela anterior',
                               command=self.showFrameMenu, bg="#4080ff", fg="gray1")
        buttonBack.pack(side='left', pady=10)

    def buscarIngrediente(self):
        try:
            ingrediente = self.ing_coll.find_ingredient(self.entryOption.get())
        except ValueError:
            tk.messagebox.showerror(master=None, title="Erro", message='Ingrediente não encontrado!')
            if self.entryOption.get() is not None:
                self.entryPrecoCompra.delete(0, 100)
            else:
                tk.messagebox.showerror(master=None, title="Erro", message='Informe o ingrediente para busca-lo!')
        else:
            tk.messagebox.showinfo(master=None, title="Sucesso", message='Ingrediente encontrado com sucesso!')

    def buscarIngredienteCadastro(self):
        global ingrediente
        try:
            ingrediente = self.ing_coll.find_ingredient(self.entryOptionNew.get())
        except ValueError:
            tk.messagebox.showerror(master=None, title="Erro", message='Ingrediente não encontrado!')
            if self.entryOptionNew.get() is not None:
                self.entryPrecoNew.delete(0, 100)
            else:
                tk.messagebox.showerror(master=None, title="Erro", message='Informe o ingrediente para busca-lo!')
        else:
            tk.messagebox.showinfo(master=None, title="Sucesso", message='Ingrediente encontrado com sucesso!')

    def atualizarIngredienteCusto(self):
        try:
            ingrediente = self.ing_coll.find_ingredient(self.entryOption.get())
        except ValueError:
            tk.messagebox.showerror(master=None, title="Erro", message='Ingrediente não atualizado.')
            self.entryPrecoCompraAt.delete(0, 100)
            self.entryUnitCompraAt.delete(0, 100)

        else:
            tk.messagebox.showinfo(master=None, title="Sucesso", message='Ingrediente atualizado com sucesso.')
            lista = Lista_Preco.from_data(
                float(self.entryPrecoCompraAt.get()),
                datetime.today(),
                self.entryUnitCompraAt.get()
            )
            self.ing_coll.update_ingredient(ingrediente, lista.dict_data)
            self.entryPrecoCompraAt.delete(0, 100)
            self.entryUnitCompraAt.delete(0, 100)
            self.entryOption.delete(0, 100)

    def cadastrarIngredienteCusto(self):
        custo = float(self.entryPrecoNew.get()) / float(self.entryUnitCompraNew.get())
        try:
            ingrediente = self.ing_coll.find_ingredient(self.entryOptionNew.get())
        except ValueError:
            tk.messagebox.showerror(master=None, title="Erro", message='Ingrediente não atualizado.')
            self.entryPrecoNew.delete(0, 100)
            self.entryUnitCompraNew.delete(0, 100)

        else:
            tk.messagebox.showinfo(master=None, title="Sucess",
                                   message='Novo custo cadastrado com sucesso. Valor do custo: '
                                           + str(custo))
            lista = Lista_Preco.from_data(
                float(self.entryPrecoNew.get()),
                datetime.today(),
                self.entryUnitCompraNew.get()
            )
            self.ing_coll.new_cost_ingredient(ingrediente, lista.dict_data)
            self.clearIngredientCadastrado()

    def salvarIngrediente(self):
        lista = Lista_Preco.from_data(
            float(self.entryPrecoCompra.get()),
            datetime.today(),
            self.entryUnitCompra.get()
        )
        ing_1 = Ingredient.from_data(
            self.entryIngrediente.get(),
            float(self.entryPrecoCompra.get()) / float(self.entryUnitCompra.get()),
            self.entryUnit.get(),
            lista.dict_data
        )
        try:
            _id = self.ing_coll.insert_ingredient(ing_1)

        except ValueError:
            tk.messagebox.showerror(master=None, title="Error", message='Ingrediente já inserido na coleção.')
            self.clearIngredient()
        else:
            tk.messagebox.showinfo(master=None, title="Sucesso", message="Ingrediente adicionado com sucesso!")
            self.clearIngredient()

    def calculoCustoIngrediente(self):
        costIngrediente = []
        ingredient = []
        ingText = []
        try:
            self.recipe = self.recp_coll.find_recipe(self.entryBoloRecipe.get())
            for i in range(len(self.recipe['ingredientes'])):
                ingredient = self.ing_coll.find_ingredient(self.recipe['ingredientes'][i]['name'])
                ingText += [ingredient['name']]
                costIngrediente += [(ingredient['cost'] * int(self.recipe['ingredientes'][i]['quantidade']))]
            self.ingText.set(ingText)
        except ValueError as err:
            tk.messagebox.showerror(master=None, title="Erro", message="Receita não encontrada, não foi possivel calcular o custo")
        else:
            custo = sum(costIngrediente)
            self.ingCustoText.set(custo)
            self.listaIngrediente = []
            for i in range(len(self.recipe['ingredientes'])):
                self.listaIngrediente += [{
                    'name': self.recipe['ingredientes'][i]['name'],
                    'quantidade': self.recipe['ingredientes'][i]['quantidade']
                }]
            self.recipe = [{
                'name': self.recipe['name'],
                'ingredientes':
                    self.listaIngrediente

            }]

    def proximaLista(self):
        self.prox_Lista = tk.Frame(self.container)
        self.prox_Lista.grid(row=0, column=0, sticky='nsew')
        self.labelQtd = tk.Label(self.prox_Lista, text="Quantidade dos ingredientes", bg="#006494", fg="#FFFFFF", font=("Helvetica", 10))
        self.labelQtd.pack(ipadx=130)
        self.entryQtd = []
        self.labelQtd = []
        for i in range(len(self.lista)):
            self.labelQtd.append(tk.Label(self.prox_Lista, pady=10, text="Quantidade do Ingrediente: " + self.lista[i]))
            self.entryQtd.append(tk.Entry(self.prox_Lista, width="20"))
        for i in range(len(self.lista)):
            self.labelQtd[i].pack()
            self.entryQtd[i].pack()

        buttonMsg = tk.Button(self.prox_Lista, text='Enviar',bg="#4080ff", fg="gray1", command=self.newRecipe)
        buttonMsg.pack(side='top', pady=20)

    def newRecipe(self):
        listaIngrediente = []
        for i in range(len(self.entryQtd)):
            qtdList = self.entryQtd[i].get()
            listaIngrediente += [{
                'name': self.lista[i],
                'quantidade': qtdList
            }]
        recipe = Recipe.from_data(
            self.entryNameRecipe.get(),
            listaIngrediente
        )
        try:
            _id = self.recp_coll.insert_recipe(recipe)

        except ValueError:
            tk.messagebox.showerror(master=None, title="Erro", message=ValueError)
        else:
            tk.messagebox.showinfo(master=None, title="Sucesso", message="Receita adicionada com sucesso!")
            self.clearRecipe()
            self.showframeReceita()

    def newEntry(self):
        try:
            _id = self.ing_coll.find_ingredient(self.entryOptionRecipe.get())
        except ValueError:
            tk.messagebox.showerror(master=None, title="Erro", message="Ingrendiente não encontrado")
            self.entryOptionRecipe.delete(0, 100)
        else:
            if self.entryOptionRecipe.get() not in self.lista:
                self.lista += [self.entryOptionRecipe.get()]
                self.listOption.insert('end', self.entryOptionRecipe.get())

        self.entryOptionRecipe.delete(0, 100)

    def dadosAtualizarCusto(self):
        labelAt = tk.Label(self.frameAtt_Ingr, text='Lista de preços\datas')
        labelAt.pack(side='top')
        labelPrecoCompraAt = tk.Label(self.frameAtt_Ingr, text='Preço de Compra')
        labelPrecoCompraAt.pack(side='top')

        self.entryPrecoCompraAt = tk.Entry(self.frameAtt_Ingr, width=20,)
        self.entryPrecoCompraAt.pack()

        labelUnitCompraAt = tk.Label(self.frameAtt_Ingr, text='Unidade')
        labelUnitCompraAt.pack(side='top', pady=10)

        self.entryUnitCompraAt = tk.Entry(self.frameAtt_Ingr, width=20)
        self.entryUnitCompraAt.pack()

        buttonMsg = tk.Button(self.frameAtt_Ingr, text='Atualizar', bg="#4080ff", fg="gray1",
                              command=self.atualizarIngredienteCusto)
        buttonMsg.pack(side='top', pady=10)

    def dadosCadastrarCusto(self):

        labelAt = tk.Label(self.frameCdst_Ingr, text='Lista de preços\datas')
        labelAt.pack(side='top')
        labelPrecoCompraAt = tk.Label(self.frameCdst_Ingr, text='Preço de Compra')
        labelPrecoCompraAt.pack(side='top')

        self.entryPrecoNew = tk.Entry(self.frameCdst_Ingr, width=20)
        self.entryPrecoNew.pack()

        labelUnitCompraAt = tk.Label(self.frameCdst_Ingr, text='Unidade')
        labelUnitCompraAt.pack(side='top', pady=10)

        self.entryUnitCompraNew = tk.Entry(self.frameCdst_Ingr, width=20)
        self.entryUnitCompraNew.pack()

        buttonMsg = tk.Button(self.frameCdst_Ingr, text='Salvar', bg="#4080ff", fg="gray1",
                              command=self.cadastrarIngredienteCusto)
        buttonMsg.pack(side='top', pady=20)

    def close(self, evento=None):
        sys.exit()

    def salvarBolo(self):
        if len(self.entryBolo.get()) == 0:
            tk.messagebox.showerror(master=None, title="Error", message="Insira o nome do bolo")
        elif len(self.entryBoloRecipe.get()) == 0:
            tk.messagebox.showerror(master=None, title="Error", message="Insira o nome da receita")
        elif len(self.entryBoloSell.get()) == 0:
            tk.messagebox.showerror(master=None, title="Error", message="Insira o valor da venda")
        elif len(self.entryBoloCliente.get()) == 0:
            tk.messagebox.showerror(master=None, title="Error", message="Insira o nome do cliente")
        else:
            try:
                bolo = Bolo.from_data(
                    self.entryBolo.get(),
                    self.entryBoloCliente.get(),
                    float(self.ingCustoText.get()),
                    datetime.today(),
                    float(self.entryBoloSell.get()),
                    self.recipe
                )
                _id = self.bolo_coll.insert_bolo(bolo)
            except ValueError:
                tk.messagebox.showerror(master=None, title="Erro", message="Bolo já inserido na coleção ou Receita não encontrada.")
            else:
                tk.messagebox.showinfo(master=None, title="Sucesso", message="Bolo inserido com sucesso")
                self.clearBolo()

    def calculoLucro(self):
        try:
            bolo = self.bolo_coll.find_bolo(self.entryBoloSearch.get())

        except ValueError:
            tk.messagebox.showerror(master=None, title="Erro", message="Bolo não encontrado")
            self.ingCustoLucroText.set("")
            self.ingVendaText.set("")
            self.ingLucroText.set("")
        else:
            tk.messagebox.showinfo(master=None, title="Sucesso", message="Calculo do lucro efetuado com sucesso!")
            self.ingCustoLucroText.set(bolo['cost_ingredients'])
            self.ingVendaText.set(bolo['price_sell'])
            self.ingLucroText.set((bolo['price_sell'] - bolo['cost_ingredients']))

    def clearIngredient(self):
        self.entryIngrediente.delete(0, 100)
        self.entryUnit.delete(0, 100)
        self.entryUnitCompra.delete(0, 100)
        self.entryPrecoCompra.delete(0, 100)

    def clearBolo(self):
        self.entryBoloSell.delete(0, 100)
        self.entryBoloCliente.delete(0, 100)
        self.entryBoloRecipe.delete(0, 100)
        self.entryBoloSearch.delete(0, 100)
        self.ingCustoText.set("")
        self.ingText.set("")

    def clearRecipe(self):
        self.entryNameRecipe.delete(0, 100)
        self.entryOptionRecipe.delete(0, 100)
        self.listOption[:] = []
        self.entryQtd.clear()

    def clearIngredientCadastrado(self):
        self.entryUnitCompraNew.delete(0, 100)
        self.entryPrecoNew.delete(0, 100)
        self.entryOptionNew.delete(0, 100)


'''
Class Files for ImageProc Class
Captures Images through Raspberry Pi camera
Captures Command Signals
Classifies Images in Classes 1-7
Stores Images in Train/1-7 directories
Manish Mahajan
9 Dec 2019
'''
# import the necessary packages
from yaml import load, Loader, dump
from picamera.array import PiRGBArray
from picamera import PiCamera
import os
import io
import sys
import time
from datetime import datetime
import numpy as np
import argparse
import threading
from PIL import Image

#Testing Functions
def get_commands():
	return np.random.randn(2)
def is_driving():
	return True
def is_paused():
	return False
def get_category():
	return 'straight'
#####

class ImageProc(object):
	def __init__(self,args,params):
		try:
			camera = PiCamera(
				resolution = params['resolution'],
				framerate = args.framerate)
		except:
			sys.exit('could not set up camera')
		camera.rotation = params['rotation']
		camera.iso = params['iso'] #800 for indoors, 200 outdoors
		# allow the camera to warmup
		time.sleep(2)
		camera.exposure_mode = params['exposure_mode']
		camera.awb_mode = params['awb_mode']
		self.camera = camera
		self.args = args
		self.params = params
		self._lock=threading.RLock()
		self.image_array = PiRGBArray(camera, size=params['resolution'])
		self.frame_num = 0
		#create requisite Directories
		if args.selfdrive == 'True':
			self.dirName = os.path.join(params['self_drive_dirname'],\
				'Example{0}'.format(args.example))
		else:
			self.dirName = os.path.join(params['training_dirname'],\
				'Example{0}'.format(args.example))

		if args.labels == 'True':
			self.labels=[]
		else:
			for category_name in params['category_names']:
				try:
					os.makedirs(os.path.join(self.dirName,category_name))
				except FileExistsError:
					pass
		pass

	def collect_data(self,get_category=get_category,\
			get_commands=get_commands,is_driving=is_driving,is_paused=is_paused):
		'''
		collects example data and stores to file in separate directories
		Classifies the steer data into categories and stores them in relevant Directories
		'''
		start_time = time.time()
		frame_num = 0
		with io.BytesIO() as stream:
			for _ in self.camera.capture_continuous(stream,format="jpeg",use_video_port=True):

				while is_paused() and is_driving():
					time.sleep(0.5)
				if not is_driving():
					break
				category = get_category()
				if category == 'straight':
					self.camera.framerate = self.args.framerate/10
					#capture stright category at a sampling rate of 10%
				else:
					self.camera.framerate = min(50,self.args.framerate)
				timestring = datetime.now().strftime("%Y%m%d%H%M%S-%f")[:-3]

				if self.args.labels == 'True':
					filepath = self.dirName
					self.labels.append([category,get_commands()])
				else:
					filepath = os.path.join(self.dirName,category)

				filename = os.path.join(filepath,'img{0:d}-{1}-{2}.jpg'\
					.format(self.args.example,category,timestring))
				with open(filename,"wb") as imagefile:
					imagefile.write(stream.getbuffer())
				# clear the stream in preparation for the next frame
				stream.seek(0)
				stream.truncate(0)
				frame_num +=1
		print('Finished Collecting {0:d} frames in {1} mins'.\
			format(frame_num,(time.time()-start_time)/60.0))
		self.cleanup()
		pass

	def capture_image(self,get_category=get_category,\
			get_commands=get_commands,is_driving=is_driving,is_paused=is_paused):
			'''
			capture images for the self driver; sends data for prediction ;
			also stores them in files for later analysis
			'''
			frame_num = 0
			with PiRGBArray(self.camera) as stream:
				for _ in self.camera.capture_continuous(stream,format="rgb",use_video_port=True):
					#print(is_paused(), is_driving())
					while is_paused() and is_driving():
						time.sleep(0.05)
					if not is_driving():
						break
					category = get_category()
					timestring = datetime.now().strftime("%Y%m%d%H%M%S-%f")[:-3]
					with self._lock:
						self.image_array=stream
						self.frame_num+=1

					if self.args.labels == 'True':
						filepath = self.dirName
						self.labels.append([category,get_commands()])
					else:
						filepath = os.path.join(self.dirName,category)

					filename = os.path.join(filepath,'img{0:d}-{1}-{2}.jpg'\
						.format(self.args.example,category,timestring))
					#Write to File, using PIL Image class definition
					Image.fromarray(stream.array).save(filename)
					# clear the stream in preparation for the next frame
					stream.truncate(0)
					frame_num+=1
					#if frame_num == self.Max_Frames:
					#	break
			print('Finished Recording {0:d} Images'.format(frame_num))
			self.cleanup()
			pass

	def cleanup(self):
		self.camera.close()
		if self.args.labels=='True' :
			np.save(os.join(self.dirName,'labels_{0:d}.npy'\
				.format(self.args.example)),self.labels,allow_pickle=True)
		self.params['example']+=1
		with open('/home/pi/ChaturCar/ChaturCar.yaml','w') as outfile:
			dump(self.params,outfile)
		print('ImageProc Cleaned Up')
		pass

	def get_frame_num(self):
		with self._lock:
			return self.frame_num

	def set_frame_num(self,frame_num):
		with self._lock:
			self.frame_num=frame_num
		pass

	def set_PiRGBimage_array(self,image_array):#PIRGBArray):
		with self._lock:
			self.image_array=image_array

	def get_image_array(self):
		#returns array attribute
		with self._lock:
			return self.image_array.array

def main():
	params = load(open('ChaturCar.yaml').read(), Loader=Loader)
	parser = argparse.ArgumentParser(description='Capture Video and Content Frames')
	parser.add_argument('--example', default=params['example'])
	parser.add_argument('--framerate',default=params['framerate'])
	parser.add_argument('--selfdrive',default=params['selfdrive'])
	parser.add_argument('--collectdata',default=params['collectdata'])
	parser.add_argument('--labels', default=params['labels'])
	args = parser.parse_args()
	c = ImageProc(args,params)
	c.collect_data()
if __name__=="__main__":
        main()


import tkinter as tk
import pandas as pd

column_names = ['user_id', 'item_id', 'rating', 'timestamp']
#Data
df = pd.read_csv('file.tsv', sep = '\t', names = column_names)
titles = pd.read_csv('Movie_Id_Titles.csv')
data = pd.merge(df, titles, on = 'item_id')

# creating dataframe with 'rating' count values
ratings = pd.DataFrame(data.groupby('title')['rating'].mean())
ratings['num of ratings'] = pd.DataFrame(data.groupby('title')['rating'].count())

# Sorting values according to
# the 'num of rating column'
moviemat = data.pivot_table(index ='user_id', columns ='title', values ='rating')
#--------------------------------------------------
print("Welcome to John's movie recommender app!\n")
inp = ' '
while inp != 'E':
    inp = input("Enter movie, enter E to exit\n")
    if inp == 'E':
        print('Goodbye!')
    else:
        inp_user_ratings = moviemat[inp]
        similar_to_inp = moviemat.corrwith(inp_user_ratings)
        corr_inp = pd.DataFrame(similar_to_inp, columns =['Correlation'])
        corr_inp.dropna(inplace = True)

        corr_inp.sort_values('Correlation', ascending = False).head(10)
        corr_inp = corr_inp.join(ratings['num of ratings'])
        print('Based on your movie ' + inp + ' I think you would like these movies!\n')
        print(corr_inp[corr_inp['num of ratings']>100].sort_values('Correlation', ascending = False).head())


import codecs

me = {
    "Hit Points": 100,
    "Damage": 0,
    "Armor": 0
}

shop = {  # (cost, damage, armor)
    "Weapons": [(8, 4, 0),
                (10, 5, 0),
                (25, 6, 0),
                (40, 7, 0),
                (74, 8, 0)
                ],
    "Armor": [(13, 0, 1),
              (31, 0, 2),
              (53, 0, 3),
              (75, 0, 4),
              (102, 0, 5),
              (0, 0, 0)
              ],
    "Rings": [(25, 1, 0),
              (50, 20, 0),
              (100, 3, 0),
              (20, 0, 1),
              (40, 0, 2),
              (80, 0, 3),
              (0, 0, 0),
              (0, 0, 0)
              ]
}

def simulate_game(my_dict, boss_dict, player=True):
    if player:
        loss = max(my_dict["Damage"] - boss_dict["Armor"], 1)
        boss_dict["Hit Points"] -= loss
        if boss_dict["Hit Points"] <= 0:
            return True
        else:
            return simulate_game(my_dict, boss_dict, player=False)
    else:
        loss = max(boss_dict["Damage"] - my_dict["Armor"], 1)
        my_dict["Hit Points"] -= loss
        if my_dict["Hit Points"] <= 0:
            return False
        else:
            return simulate_game(my_dict, boss_dict)

if __name__ == "__main__":
    with codecs.open("input.txt") as input_file:
        lines = list(map(lambda i: i.strip().split(": "), input_file.readlines()))
        boss = {i[0]: int(i[1]) for i in lines}
        min_cost, min_win, max_cost = 1000000, 100, 0
        for weapon in shop["Weapons"]:
            for armor in shop["Armor"]:
                for index1, ring1 in enumerate(shop["Rings"]):
                    for index2, ring2 in enumerate(shop["Rings"]):
                        if index1 != index2:
                            me_copy, boss_copy = me.copy(), boss.copy()
                            weapon_cost, weapon_damage, weapon_armor = weapon
                            armor_cost, armor_damage, armor_armor = armor
                            c1, d1, a1 = ring1
                            c2, d2, a2 = ring2
                            total_cost = sum((weapon_cost, armor_cost, c1, c2))
                            total_damage = sum((weapon_damage, armor_damage, d1, d2))
                            total_armor = sum((weapon_armor, armor_armor, a1, a2))
                            me_copy["Damage"] = total_damage
                            me_copy["Armor"] = total_armor
                            result = simulate_game(me_copy, boss_copy)
                            if result:
                                min_cost = min(min_cost, total_cost)
                            else:
                                max_cost = max(total_cost, max_cost)
        print("part 1:", min_cost)
        print("part 2:", max_cost)


# dfs
# rightmost = {} // rightmost[3] = 7 depth at 3 when value is 7

def dfs(d):
	if d == None:
	 	return None
	rightmost[depth] = most
	dfs(d.left)
	dfs(d.right)

# Question:print out the whole tree


class Function:
    def __init__(self, param1, param2, operator):
        self.param1 = param1
        self.param2 = param2
        self.operator = operator

    def summa(self):
        return self.param1 + self.param2

    def definition(self):
        return self.param1 - self.param2

    def mul(self):
        return self.param1 * self.param2

    def div(self):
        if self.param2 == 0:
            return "На 0 делить нельзя"
        else:
            return round(self.param1 / self.param2, 2)

    def result(self):
        if self.operator == "+":
            return self.summa()
        elif self.operator == "-":
            return self.definition()
        elif self.operator == "*":
            return self.mul()
        elif self.operator == "/":
            return self.div()
        else:
            return str(self.param1) + self.operator + str(self.param2)

    def method(self):
        pass

    def __add__(self, other):
        return "разница первых параметров: " + str(self.param1 - other.param1) + "\n разница вторых параметров: " + str(
            self.param2 - other.param2)

class SumOfThree(Function):
    def method(self, param3):
        return self.summa() + param3

class DefWithDiv(Function):
    def method(self):
        if self.param2 != 0:
            return self.definition() / float(self.param2)
        else:
            return str(self.definition()) + "/0"

class Pow(Function):
    def mul(self):
        res = 1
        for i in range(int(self.param2)):
            res *= self.param1
        return res

    def method(self):
        return self.mul()

a = float(input("Введите первый параметр: "))
b = float(input("Введите второй параметр: "))
op = input("Введите операцию: ")
func = Function(a, b, op)
func2 = Function(5, 10, '-')
print(func.result())
print(func + func2)

sum_of_three = SumOfThree(a, b, op)
print(sum_of_three.method(3))
def_with_div = DefWithDiv(a, b, op)
print(def_with_div.method())
power = Pow(a, b, op)
print(power.method())


from neo4j import GraphDatabase
import pymatgen.core as pmat

from poly_graphs_lib.database import PASSWORD,DBMS_NAME,LOCATION,DB_NAME,CIF_DIR
from poly_graphs_lib.database.populate.nodes import Node

def populate_element_nodes(elements):
    elements = dir(pmat.periodic_table.Element)[:-4]
    create_statements = []
    for element in elements[:]:
        # pymatgen object. Given element string, will have useful properties
        pmat_element = pmat.periodic_table.Element(element)

        node=Node(node_name=element,class_name='Element')
        node.add_property(name='atomic_number',value=pmat_element.Z)
        node.add_property(name='atomic_mass',value=float(pmat_element.atomic_mass))

        if str(pmat_element.X) != 'nan':
            node.add_property(name='X',value=pmat_element.X)
        else:
            node.add_property(name='X',value=None)

        if str(pmat_element.atomic_radius) != 'nan' and str(pmat_element.atomic_radius) != 'None':
            node.add_property(name='atomic_radius',value=float(pmat_element.atomic_radius))
        else:
            node.add_property(name='atomic_radius',value=None)

        if str(pmat_element.group) != 'nan':
            node.add_property(name='group',value=pmat_element.group)
        else:
            node.add_property(name='group',value=None)

        if str(pmat_element.row) != 'nan':
            node.add_property(name='row',value=pmat_element.row)
        else:
            node.add_property(name='row',value=None)

        execute_statement=node.final_execute_statement()
        create_statements.append(execute_statement)

    return create_statements

def main():
    # This statement Connects to the database server
    connection = GraphDatabase.driver(LOCATION, auth=(DBMS_NAME, PASSWORD))
    # To read and write to the data base you must open a session
    session = connection.session(database=DB_NAME)

    elements = dir(pmat.periodic_table.Element)[:-4]
    create_statements=populate_element_nodes(elements=elements)
    for execute_statment in create_statements:
        session.run(execute_statment)

    session.close()
    connection.close()

if __name__ == '__main__':
    main()


from collections import deque

N, K = map(int, input().split())
MAX = 100001
visited = [0] * MAX

def BFS(N):
    q = deque()
    q.append(N)
    visited[N] = 0
    while q:
        N = q.popleft()
        if N == K:
            return visited[N]
        for num in (N - 1, N + 1, N * 2):
            if 0 <= num < MAX and visited[num] == 0:
                visited[num] = visited[N] + 1
                q.append(num)
print(BFS(N))


import argparse
import logging
import os
import queue
import random
import socket
import sys

import psutil
import setproctitle
from mpi4py import MPI

comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()

if __name__ == "__main__":
    setproctitle.setproctitle("BGNN:" + str(rank))

    logging.basicConfig(filename="./Graphsage.log_embedding",
                        level=logging.INFO,
                        format=str(rank) + ' - %(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S')

    hostname = socket.gethostname()
    logging.debug("#############process ID = " + str(rank) +
                  ", host name = " + hostname + "########" +
                  ", process ID = " + str(os.getpid()) +
                  ", process Name = " + str(psutil.Process(os.getpid())))

    # 972 parallel processes
    hpo_batch_size = [400, 500, 600, 700]  # 3
    hpo_epochs = [2, 3, 4]  # 4
    hpo_lr = [0.0002, 0.0003, 0.0004]  # 3
    hpo_weight_decay = [0.001, 0.0005, 0.0008]  # 3
    first_layer_dim = [32, 64, 128]
    hpo_dropout = [0.35, 0.4, 0.45]  # 3

    hpo_cnt = 0
    paras = dict()
    for batch_size in hpo_batch_size:
        for epochs in hpo_epochs:
            for lr in hpo_lr:
                for weight_decay in hpo_weight_decay:
                    for first_dim in first_layer_dim:
                        for dropout in hpo_dropout:
                            paras[hpo_cnt] = (batch_size, epochs, lr, weight_decay, first_dim, dropout)
                            hpo_cnt += 1

    (batch_size, epochs, lr, weight_decay, first_dim, dropout) = paras[rank]

    print("start hgcn_cmd")
    hgcn_cmd = "/mnt/shared/etc/anaconda3/bin/python3 /mnt/shared/home/bipartite-graph-learning/GraphSage/graphsage/unsupervised_train.py" \
               "--model graphsage --batch_size %d --epochs %d --learning_rate %f --weight_decay %f --dim_1 %d " \
               "--dropout %f --rank %d" % (
                   batch_size,
                   epochs,
                   lr,
                   weight_decay,
                   first_dim,
                   dropout,
                   rank)
    os.system(hgcn_cmd)
    print("end hgcn_cmd")

    print("start lr_cmd")
    lr_cmd = "/mnt/shared/etc/anaconda3/bin/python3 /mnt/shared/home/bipartite-graph-learning/Graphsage/binary_classification.py --rank %s" % rank
    os.system(lr_cmd)
    print("end lr_cmd")


import numpy as np
import pytest

from pandas import DataFrame, date_range
import pandas._testing as tm

class TestTranspose:
    def test_transpose_tzaware_1col_single_tz(self):
        # GH#26825
        dti = date_range("2016-04-05 04:30", periods=3, tz="UTC")

        df = DataFrame(dti)
        assert (df.dtypes == dti.dtype).all()
        res = df.T
        assert (res.dtypes == dti.dtype).all()

    def test_transpose_tzaware_2col_single_tz(self):
        # GH#26825
        dti = date_range("2016-04-05 04:30", periods=3, tz="UTC")

        df3 = DataFrame({"A": dti, "B": dti})
        assert (df3.dtypes == dti.dtype).all()
        res3 = df3.T
        assert (res3.dtypes == dti.dtype).all()

    def test_transpose_tzaware_2col_mixed_tz(self):
        # GH#26825
        dti = date_range("2016-04-05 04:30", periods=3, tz="UTC")
        dti2 = dti.tz_convert("US/Pacific")

        df4 = DataFrame({"A": dti, "B": dti2})
        assert (df4.dtypes == [dti.dtype, dti2.dtype]).all()
        assert (df4.T.dtypes == object).all()
        tm.assert_frame_equal(df4.T.T, df4)

    @pytest.mark.parametrize("tz", [None, "America/New_York"])
    def test_transpose_preserves_dtindex_equality_with_dst(self, tz):
        # GH#19970
        idx = date_range("20161101", "20161130", freq="4H", tz=tz)
        df = DataFrame({"a": range(len(idx)), "b": range(len(idx))}, index=idx)
        result = df.T == df.T
        expected = DataFrame(True, index=list("ab"), columns=idx)
        tm.assert_frame_equal(result, expected)

    def test_transpose_object_to_tzaware_mixed_tz(self):
        # GH#26825
        dti = date_range("2016-04-05 04:30", periods=3, tz="UTC")
        dti2 = dti.tz_convert("US/Pacific")

        # mixed all-tzaware dtypes
        df2 = DataFrame([dti, dti2])
        assert (df2.dtypes == object).all()
        res2 = df2.T
        assert (res2.dtypes == [dti.dtype, dti2.dtype]).all()

    def test_transpose_uint64(self, uint64_frame):

        result = uint64_frame.T
        expected = DataFrame(uint64_frame.values.T)
        expected.index = ["A", "B"]
        tm.assert_frame_equal(result, expected)

    def test_transpose_float(self, float_frame):
        frame = float_frame
        dft = frame.T
        for idx, series in dft.items():
            for col, value in series.items():
                if np.isnan(value):
                    assert np.isnan(frame[col][idx])
                else:
                    assert value == frame[col][idx]

        # mixed type
        index, data = tm.getMixedTypeDict()
        mixed = DataFrame(data, index=index)

        mixed_T = mixed.T
        for col, s in mixed_T.items():
            assert s.dtype == np.object_

    def test_transpose_get_view(self, float_frame):
        dft = float_frame.T
        dft.values[:, 5:10] = 5

        assert (float_frame.values[5:10] == 5).all()


# TODO - Fix expression command, and interaction with negative numbers.
# TODO - Add more commands!

import discord
from discord.ext import commands
import math
import re

class MathCog:
    """
        Used for math functions such as adding, subtracting, multiplying, and dividing.
        Uses regexes for more friendly interaction.
        I currently have an expression command utilizing Python's built in parser, but doesn't work too well currently.
        It has quite a few problems, like interacting with negative numbers will mess up sometimes. I'll have to look into that.
    """

    def __init__(self, client):

        self.client = client
        self.simpleRegex = re.compile(r'''
                                                    ([-]?   # Checks for negative number
                                                    [0-9]*  # Integer part of number
                                                    \.?[0-9]+)+ #Decimal part of number
                                                    ''', re.VERBOSE)

    @commands.command()
    async def expression(self, expression: str):
        """Uses a parser to solve more complicated equations. With the built in Python one, it's not that good."""

        # Will use parser for more complicated equations.
        compiledequation = compile(expression, "math.py", "eval")

        await self.client.say(eval(compiledequation))

    @commands.command()
    async def add(self, *args):
        """Adds numbers."""

        if len(list(args)) == 0:
            await self.client.say("0")
            return

        # String to be passed to regex, will include all the user parameters.
        regexstring = ""

        for x in list(args):
            regexstring += str(x) + " "

        mo = self.simpleRegex.findall(regexstring)

        for x in mo:
            x.strip()

        total = float(mo[0])

        for x in mo[1:]:
            total += float(x)

        await self.client.say(total)

    @commands.command()
    async def subtract(self, *args):
        """Subtracts numbers."""

        if len(list(args)) == 0:
            await self.client.say("0")
            return

        regexstring = ""
        for x in list(args):
            regexstring += str(x) + " "

        mo = self.simpleRegex.findall(regexstring)

        for x in mo:
            x.strip()

        total = float(mo[0])

        for x in mo[1:]:
            total -= float(x)

        await self.client.say(total)

    @commands.command()
    async def multiply(self, *args):
        """Multiplies numbers."""

        if len(list(args)) == 0:
            await self.client.say("0")
            return

        regexstring = ""
        for x in list(args):
            regexstring += str(x) + " "

        mo = self.simpleRegex.findall(regexstring)

        for x in mo:
            x.strip()

        total = float(mo[0])

        for x in mo[1:]:
            total *= float(x)

        await self.client.say(total)

    @commands.command()
    async def divide(self, *args):
        """Divides numbers."""

        if len(list(args)) == 0:
            await self.client.say("0")
            return

        regexstring = ""
        for x in list(args):
            regexstring += str(x) + " "

        mo = self.simpleRegex.findall(regexstring)

        for x in mo:
            x.strip()

        total = float(mo[0])

        for x in mo[1:]:
            total /= float(x)

        await self.client.say(total)

def setup(client):
    client.add_cog(MathCog(client))


"""
Purpose :  Define a function that finds the maximum amount of internal
biofuel and the amount of oscillation in the level of internal biofuel.

Created on 30/4/2020

@author: Murray Keogh

Program description:
    Write a function that finds the maximum value and its indices in the
    input array. The function then finds the minimum value at an index after
    the maximum value.  The oscillation is calculated by subtracting the
    minimum from the maximum. The output is the maximum value and
    the calculated oscillation size.

Data dictionary:

   Inputs:
   input_array         :(array) given input array

   Outputs:
   max_value           :maximum amount of internal biofuel
   oscillationSize     :oscillation size

   Other:
   len_input_array         :length of the input array
   max_value_index         :index of the maximum value
   min_biofuel_int         :minimum value after the maximum value

"""
import numpy as np

def find_max_and_oscillation(input_array):

    #create length value
    len_input_array = len(input_array)

    #find max value of input array
    max_value = np.max(input_array)
    #find index of max value in input array
    max_value_index = np.where(input_array==max_value)[0][0]

    #if max value is at last index, set oscillation size to zero
    if max_value_index == len_input_array-1:
        oscillationSize = 0

    else:
        #find the next minimum value after the max value
        min_biofuel_int = np.min(input_array[max_value_index:])
        #calculate oscillation size
        oscillationSize = max_value - min_biofuel_int

    #return output
    return max_value, oscillationSize


import cv2
from cv2 import aruco
import numpy as np

### --- aruco設定 --- ###
dict_aruco = aruco.Dictionary_get(aruco.DICT_4X4_50)
parameters = aruco.DetectorParameters_create()

cap = cv2.VideoCapture(0)

try:
    while True:
        ret, frame = cap.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)

        corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, dict_aruco, parameters=parameters)
        list_ids = np.ravel(ids)
        frame_markers = aruco.drawDetectedMarkers(frame.copy(), corners, ids)
        windowsize = (800, 600)
        frame_markers = cv2.resize(frame_markers, windowsize)
        print(list_ids)
        cv2.imshow('frame', frame_markers)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cv2.destroyWindow('frame')
    cap.release()
except KeyboardInterrupt:
    cv2.destroyWindow('frame')
    cap.release()


#!/bin/python
import os
import js2py
from pathlib import Path

from configStrategies import cS
from configIndicators import cI

class makeSettings():
    def __init__(self, entries):
        '''
        print(entries)
        def iterate(self, DATA):
            for W in DATA.keys():
                if type(DATA[W]) == dict:
                    iterate(self,DATA[W])
                else:
                    self.__dict__.update(DATA)
        iterate(self,entries)
        '''
        self.__dict__.update(entries)

    def getstrat(self, name):
        return self.strategies[name]

def getSettings(specific=None):
    HOME = str(Path.home())
    s = {
        'Global': {
            'gekkoPath': '/steve/gekko',
            'configFilename': 'config.js',
            'log_name': 'evolution_gen.csv',

            # Hosts list of remote machines running gekko, to distribute evaluation load;
            # option values: path to HOSTS file list OR False;
            'RemoteAWS': '../AmazonSetup/hosts',

            # Your gekko local URL - CHECK THIS!
            'GekkoURLs': ['http://localhost:3000','http://18.219.12.229:3000','http://18.221.183.250:3000'],
            'showFailedStrategies': False
        },
        # genetic algorithm settings
        'generations': {
            # show gekko verbose (strat info) - gekko must start with -d flag;
            'gekkoDebug': True,

            # Verbose single evaluation results;
            'showIndividualEvaluationInfo': True,

            # if parameter is set to value rather than tuple limits at settings, make the value
            # a tuple based on chosen spread value (percents); value: 10 --spread=50-->  value: (5,15)
            'parameter_spread' : 60,

            # Initial population size, per locale
            'POP_SIZE': 30,

            # number of epochs to run
            'NBEPOCH': 800,

            # number of locales on parallel GA;
            'NBLOCALE': 6,

            # show current best settings on every X epochs. (or False)
            'evaluateSettingsPeriodically': False,

            # time window size on days of candlesticks for each evaluation
            'deltaDays': 90,

            # Number of candlestick data loaded simultaneously in each locale;
            # slower EPOCHS, theoretical better evolution;
            # seems broken. values other than 1 makes evolution worse.
            'ParallelCandlestickDataset': 1,

            # -- Genetic Algorithm Parameters
            'cxpb': 0.8, # Probabilty of crossover
            'mutpb': 0.2,# Probability of mutation;
            '_lambda': 7,# size of offspring generated per epoch;

            # weight of PRoFIGA calculations on variability of population size
            'PRoFIGA_beta': 0.005,
            'ageBoundaries': (9, 19), # minimum age to die, age when everyone dies (on EPOCHS)

            'candleSize': 10, # candle size for gekko backtest, in minutes

            # number of evaluations on evaluation break. for each selected individue on locales;
            'proofSize': 12,
            # filter individuals for minimum trade count; [has heavy impact]
            'minTradeNumber': 6,
            'DRP': 70,# Date range persistence; Number of subsequent rounds
             # until another time range in dataset is selected;

            # number of parallel backtests running on gekko;
            'ParallelBacktests': 16,

            'finaltest': {
                # number of individues selected by score on each evaluation break for each locale;
                'NBBESTINDS': 2,
                # number of individues randomly selected on each evaluation break for each locale;
                'NBADDITIONALINDS': 4,
            },
            # chromosome settings are for -gc mode, which uses another GA internal representation mode
            # for parameter values of each individue;
            # check promoterz/representation/chromosome.py to see how it works.
            # both parameters interact with crossover probability AKA cxpb;
            # practical effects on evolution are really uknown;
            'chromosome': {
                # length of the representation for each parameter. largers sizes should mantain
                # evolutionary dynamics for parameters with proportional larger ranges;
                'GeneSize': 2,
                # number of parameters represented by each cromosome;
                # this should mantain evolutionary dynamics for strategies with proportional larger
                # parameter counts;
                'Density': 3,
            },
            # weights to score each individual, self explanatory;
            'weights': {
                'profit': 1.0,
                'sharpe': 0.1},

            # mode of profit interpretation: v1, v2 or v3.
            # please check the first functions at evaluation.gekko.backtest
            # to understand what is this. has big impact on evolutionary agenda.
            'interpreteBacktestProfit': 'v3',

            # after this age in epoches, locale surely explodes i.e. ends.
            'localeExpirationAge': 100,
            # chance, on each epoch, of a locale to finish [in percentage];
            'localeExplodeChance': 2
        },

        # bayesian optimization settings
        'bayesian': {
            # show gekko verbose (strat info) - gekko must start with -d flag;
            'gekkoDebug': False,

            # time window size on days of candlesticks for each evaluation
            'deltaDays': 120,

            # number of evaluation rounds
            'num_rounds': 10,

            # seed for randomziation of values
            'random_state': 2018,

            # number of iterations on each round
            'num_iter': 50,

            # number of random values to start bayes evaluation
            'init_points': 9,

            'parallel': False,
            'show_chart': False,
            'save': True,

            'parameter_spread': 100,

            # candleSize & historySize on Gekko, for all evals
            'candleSize': 10,
            'historySize': 1000,

            'watch':{
                "exchange": "bitfinex",
                "currency": 'USD',
                "asset": 'ETH'
            },

            'interpreteBacktestProfit': 'v3'

        },
        'dataset' : {
            # -- Gekko Dataset Settings
            # in order to enable dataset selection, turn off ignore&autoselect entry;
            'dataset_source': {
                'ignore&autoselect': False,
                "exchange": "bitfinex",
                "currency": 'USD',
                "asset": 'ETH',
            },
            'dataset_source2': {
                'ignore&autoselect': False,
                "exchange": "bitfinex",
                "currency": 'USD',
                "asset": 'BTC',
            },
            'dataset_source3': {
                'ignore&autoselect': False,
                "exchange": "bitfinex",
                "currency": 'USD',
                "asset": 'LTC',
            },
            'dataset_source4': {
                'ignore&autoselect': False,
                "exchange": "bitfinex",
                "currency": 'USD',
                "asset": 'XRP',
            },
            'dataset_source5': {
                'ignore&autoselect': False,
                "exchange": "bitfinex",
                "currency": 'USD',
                "asset": 'IOT',
            },
            'eval_dataset_source': {
                'ignore&autoselect': False,
                "exchange": "bitfinex",
                "currency": 'USD',
                "asset": 'ETH',
            },
            # span in days from the end of dataset to the beggining. Or zero.
            # (to restrain length);
            'dataset_span': 0,
            'eval_dataset_span': 0

            },
        'strategies': cS,
        'indicators': cI,
        'skeletons': {
            'ontrend': {
                "SMA_long": 1000,
                "SMA_short": 50
            }
        }
    }

    if specific != None:
        if not specific:
            return makeSettings(s)
        else:
            return makeSettings(s[specific])

    return s

def get_configjs(filename="example-config.js"):
    with open(filename, "r") as f:
        text = f.read()
    text = text.replace("module.exports = config;","config;")
    return js2py.eval_js(text).to_dict()


# ðŸš¨ Don't change the code below ðŸ‘‡
age = input("What is your current age? ")
# ðŸš¨ Don't change the code above ðŸ‘†

#Write your code below this line ðŸ‘‡
#Define how many days, weeks & months are in a year
days = 365
weeks = 52
months = 12

#convert age to integer
n_age = int(age)

#How many years left until 90
life = 90 - n_age

#Output
print(f"You have {days * life} days, {weeks * life} weeks, and {months * life} months left.")


import cv2
import numpy as np
import matplotlib.pyplot as plt

def apply_sobel_filter_manual(image):
    image_data = image.read()
    nparr = np.frombuffer(image_data, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Convert image to float32 before applying Sobel filter
    img = np.float32(img)

    # Define the Sobel kernels
    kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
    kernel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])

    # Apply the kernels to the grayscale image
    img_sobel_x = cv2.filter2D(img, -1, kernel_x)
    img_sobel_y = cv2.filter2D(img, -1, kernel_y)

    # Combine the effects of the x and y kernels
    img_sobel = cv2.sqrt(cv2.addWeighted(cv2.pow(img_sobel_x, 2.0), 1.0, cv2.pow(img_sobel_y, 2.0), 1.0, 0))

    plt.figure(figsize=(10, 5))

    # Original Image
    plt.subplot(1, 2, 1)
    plt.imshow(img, cmap='gray')
    plt.title("Original Image")

    # Image after applying the Sobel filter
    plt.subplot(1, 2, 2)
    plt.imshow(img_sobel, cmap='gray')
    plt.title("Image after Sobel filter")

    plt.show()


from flask import Flask
from flask import request
# from pymongo import MongoClient
app = Flask(__name__)

# client = MongoClient('localhost:27017')
# db=client.air_data

print("done establishing connection!")

@app.route('/sensor',methods = ['POST', 'GET'])
def sensor():
   if request.method == 'POST':
        # print (request.is_json)
        content = request.json
        print(content)
#         db.air_datas.insert_one(content)
#         fivestar = db.sensor_datas.find()
#         print(fivestar)
        return "done"
   else:
        return "error"
@app.route('/',methods = ['GET'])
def index():
   return "done"

@app.route('/val/<co>/<dust>',methods = ['GET'])
def val(co=None,dust=None):
	print(co+" "+dust)
	db.air_datas.insert_one({'co': co,'dust':dust})
	return co+" "+dust

@app.route('/<area>',methods = ['GET'])
def val(area=None):
	print(area)
	#db.air_datas.insert_one({'co': co,'dust':dust})

	return "{'co':'211','du':'211'}"

if __name__ == "__main__":
    app.run()


import xml.etree.ElementTree as ET
import os

#Initializig file location
dir_path=os.path.dirname(os.path.realpath(__file__))
dir_path=dir_path.replace("\\",'/')
#XML file
file_name="person.xsd"
input_filename=dir_path+'/input_files/'+file_name

try:
    #Reading the file
    fhandler=open(input_filename,'r')
except:
    print("Provided file name",file_name,"is not available in the path",dir_path)
    quit()

tree = ET.fromstring(fhandler.read())
#creates an iterative list
data_list = tree.findall('people/user')

for i in data_list:
    print("******* MEMBER DETAILS *******")
    print('Membership ID: ', i.find('name').get('member_id'))
    print('Name: ' , i.find('name').text)
    print('phone: ' , i.find('phone').text)
    print('sex: ' , i.find('sex').text)


import board
import digitalio
from time import sleep
import usb_hid
from adafruit_hid.keycode import Keycode
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.mouse import Mouse

LED = digitalio.DigitalInOut(board.GP25)
LED.direction = digitalio.Direction.OUTPUT

button1 = digitalio.DigitalInOut(board.GP16)
button1.switch_to_input(pull=digitalio.Pull.DOWN)

kbd = Keyboard(usb_hid.devices)
mouse = Mouse(usb_hid.devices)

while True:
    if button1.value:
        while button1.value:
            sleep(0.1)
        LED.value = True

        while not button1.value:
            mouse.click(Mouse.LEFT_BUTTON)
            sleep(0.05)
        while button1.value:
            sleep(0.1)
        LED.value = False


class Node:
    def __init__(self, data):
        self.data = data  # храним информацию
        self.pref = None # ссылка на предыдущий узел

class Stack:

    def __init__(self):
        self.end = None  # ссылка на конец стека

    def pop(self):
        try:
            val = self.end.data
            self.end = self.end.pref
            return val
        except AttributeError:
            print("Стек пуст")

    def push(self, val):
        if self.end == None:
            node = Node(val)
            self.end = node
        else:
            node = Node(val)
            node.pref = self.end
            self.end = node

    def print(self):
        item = self.end
        while item:
            print(item.data)
            item = item.pref


# -*- coding: utf-8 -*-
from typing import (
    Union,
    Set
)

from PyQt5.QtCore import (
    QPointF,
    QPoint,
    QRect,
    Qt
)
from PyQt5.QtGui import (
    QPainterPath,
    QKeyEvent
)
from PyQt5.QtWidgets import (
    QGraphicsItemGroup,
    QGraphicsPathItem,
    # QGraphicsRectItem,
    QGraphicsItem,
    QMenu,
    QAction,
    QGraphicsSceneMouseEvent
)
from cadnano.fileio import (
    v3encode,
    v3decode
)
from cadnano.views.sliceview.virtualhelixitem import SliceVirtualHelixItem
from cadnano.gui.palette import getPenObj
from cadnano.views.sliceview import slicestyles as styles
from .abstractslicetool import AbstractSliceTool
from cadnano.views.sliceview import (
    SliceToolManagerT,
    SliceNucleicAcidPartItemT
)
from cadnano.cntypes import (
    RectT,
    Vec3T
)

def normalizeRect(rect: RectT) -> RectT:
    """
    Args:
        rect: Description

    Returns:
        tuple of a rectangle corners
    """
    x1, y1, x2, y2 = rect
    if x1 > x2:
        # swap
        x1, x2 = x2, x1
    if y1 > y2:
        # swap
        y1, y2 = y2, y1
    return (x1, y1, x2, y2)

_SELECT_PEN_WIDTH = styles.SELECTED_PEN_WIDTH
_SELECT_COLOR = styles.SELECTED_COLOR  # "#ff0000"
_TEST_COLOR = "#00ff00"

class SelectSliceTool(AbstractSliceTool):
    """Handles SelectTool operations in the Slice view

    Attributes:
        clipboard (TYPE): Description
        group (TYPE): Description
        individual_pick (bool): Description
        is_selection_active (bool): Description
        last_rubberband_vals (tuple): Description
        part_item (TYPE): Description
        selection_set (TYPE): Description
        snap_origin_item (TYPE): Description
    """

    def __init__(self, manager: SliceToolManagerT):
        """Summary

        Args:
            manager (TYPE): Description
        """
        super(SelectSliceTool, self).__init__(manager)
        self.last_rubberband_vals = (None, None, None)
        self.selection_set = set()
        self.group = SliceSelectionGroup(self, parent=self)
        self.group.hide()
        self.is_selection_active = False
        self.individual_pick = False
        self.snap_origin_item = None
        self.clipboard = None
    # end def

    def __repr__(self) -> str:
        """
        Returns:
            tool name string
        """
        return "select_tool"  # first letter should be lowercase

    def methodPrefix(self) -> str:
        """
        Returns:
            prefix string
        """
        return "selectTool"  # first letter should be lowercase

    def isSelectionActive(self) -> bool:
        """
        Returns:
            is the selection active?
        """
        return self.is_selection_active
    # end def

    def resetSelections(self):
        """
        """
        # print("resetSelections")
        doc = self.manager.document
        doc.clearAllSelected()

    def modelClear(self):
        """Clear model selections
        """
        # print("modelClear")
        doc = self.manager.document
        doc.clearAllSelected()

    def setPartItem(self, part_item: SliceNucleicAcidPartItemT):
        """
        Args:
            part_item: Description
        """
        if part_item is not self.part_item:
            if self.sgv is not None:
                # attempt to enforce good housekeeping, not required
                try:
                    self.sgv.rubberBandChanged.disconnect(self.selectRubberband)
                except Exception:
                    # required for first call
                    pass
            if self.part_item is not None:
                # print("modelClear yikes")
                self.modelClear()
            self.part_item = part_item

            # In the event that the old part_item was deleted (and garbage
            # collected), self.group (whose parent was the old part_item) is
            # also garbage collected.  Therefore, create a new
            # SliceSelectionGroup when this is the case
            try:
                self.group.setParentItem(part_item)
            except RuntimeError:
                self.group = SliceSelectionGroup(self, parent=part_item)

            # required for whatever reason to renable QGraphicsView.RubberBandDrag
            # TODO[NF]:  Determine why self.slice_graphics_view is None when the dual-slice view is enabled
            # TODO[NF]:  Now that SVG is being set properly, can the conditional be removed?
            # TODO[NF]:  This might be better kept as an error condition logged to logger.error
            if self.sgv is not None:
                self.sgv.activateSelection(True)
                self.sgv.rubberBandChanged.connect(self.selectRubberband)
            else:
                # TODO[NF]:  Use logger.error here
                print("SGV is still none")
    # end def

    def selectRubberband(self, rect: QRect, from_pt: QPointF, to_point: QPointF):
        """
        Args:
            rect: Description
            from_pt: Description
            to_point: Description
        """
        fset = self.manager.document.filter_set
        if self.FILTER_NAME not in fset:
            return
        rbr_last, fp_last, tp_last = self.last_rubberband_vals
        if rect.isNull() and rbr_last.isValid():
            part_item = self.part_item
            part = part_item.part()

            # convert and normalize the drag rectangle
            from_pt_part_item = part_item.mapFromScene(fp_last)
            to_pt_part_item = part_item.mapFromScene(tp_last)

            # note QRectF.normalized doesn't seem to actually normalize a
            # rectangle near as I can tell no we have normaliz
            from_model_point: Vec3T =   part_item.getModelPos(from_pt_part_item)
            to_model_point: Vec3T =     part_item.getModelPos(to_pt_part_item)
            query_rect = (from_model_point[0], from_model_point[1],
                          to_model_point[0], to_model_point[1])
            query_rect = normalizeRect(query_rect)
            # print("Query rect", query_rect,
            #     query_rect[0] < query_rect[2], query_rect[1] < query_rect[3])
            res = part.getVirtualHelicesInArea(query_rect)

            doc = self.manager.document
            doc.clearAllSelected()
            doc.addVirtualHelicesToSelection(part, res)
        else:
            self.last_rubberband_vals = (rect, from_pt, to_point)
    # end def

    def getSelectionBoundingRect(self):
        """Show the bounding rect
        """
        part_item = self.part_item
        group = self.group
        # self.deselectItems()
        for id_num in self.selection_set:
            vhi = part_item.getVirtualHelixItem(id_num)
            group.addToGroup(vhi)

        self.is_selection_active = True
        if len(group.childItems()) > 0:
            group.setSelectionRect()
            # print("showing")
            group.show()
        else:
            print("Nothing in selection_set")
    # end def

    def deselectItems(self) -> bool:
        """
        Returns:
            ``True`` if selection cleared ``False`` if no selection active
        """
        # print("deselecting")
        group = self.group
        if self.snap_origin_item is not None:
            self.snap_origin_item.setSnapOrigin(False)
            self.snap_origin_item = None
        if self.is_selection_active:
            part_item = self.part_item
            for id_num in self.selection_set:
                vhi = part_item.getVirtualHelixItem(id_num)
                if vhi is not None:
                    group.removeFromGroup(vhi)
            self.selection_set.clear()
            group.clearSelectionRect()
            group.hide()
            self.is_selection_active = False
            return True
        if group is not None:
            group.clearSelectionRect()
        return False
    # end def

    def deselectSet(self, vh_set: Set[int]) -> bool:
        """
        Args:
            vh_set: Description

        Returns:
            ``False`` if selection is not active, ``True`` if active
        """
        group = self.group
        if self.snap_origin_item is not None:
            self.snap_origin_item.setSnapOrigin(False)
            self.snap_origin_item = None
        selection_set = self.selection_set
        if self.is_selection_active:
            part_item = self.part_item
            for id_num in vh_set:
                vhi = part_item.getVirtualHelixItem(id_num)
                if vhi is not None:
                    group.removeFromGroup(vhi)
                    selection_set.remove(id_num)
            group.clearSelectionRect()
            group.hide()
            if len(selection_set) > 0 and len(group.childItems()) > 0:
                group.setSelectionRect()
                group.show()
            return True
        group.clearSelectionRect()
        return False
    # end def

    def selectOrSnap(self,  part_item: SliceNucleicAcidPartItemT,
                            target_item: SliceVirtualHelixItem,
                            event: QGraphicsSceneMouseEvent):
        """
        Args:
            part_item:
            target_item: Description
            event: Description

        Deleted Parameters:
            snap_to_item (SliceVirtualHelixItem or GridEvent): Item to snap
                selection to
        """
        self.setPartItem(part_item)
        if (self.snap_origin_item is not None and event.modifiers() == Qt.AltModifier):
            self.doSnap(part_item, target_item)
            self.individual_pick = False
        else:  # just do a selection
            if event.modifiers() != Qt.ShiftModifier:
                self.modelClear()   # deselect if shift isn't held

            if isinstance(target_item, SliceVirtualHelixItem):
                # NOTE: individual_pick seems not needed.
                # it's supposed to allow for single item picking
                # self.individual_pick = True

                if self.snap_origin_item is not None:
                    self.snap_origin_item.setSnapOrigin(False)
                    self.snap_origin_item = None

                doc = self.manager.document
                part = part_item.part()
                doc.addVirtualHelicesToSelection(part, [target_item.idNum()])
    # end def

    def doSnap(self, part_item: SliceNucleicAcidPartItemT,
                    snap_to_item: SliceVirtualHelixItem):
        """
        Args:
            part_item:
            snap_to_item: Item to snap
                selection to
        """
        # print("snapping")
        origin = self.snap_origin_item.getCenterScenePos()

        # xy = part_item.mapFromScene(snap_to_item.scenePos())
        # xy2 = part_item.mapFromScene(self.snap_origin_item.scenePos())
        # print("snapping from:", xy2.x(), xy2.y())
        # print("snapped to:", xy.x(), xy.y())

        if isinstance(snap_to_item, SliceVirtualHelixItem):
            self.setVirtualHelixItem(snap_to_item)
            destination = self.findNearestPoint(part_item, origin)
        else:  # GridEvent
            destination = snap_to_item.pos()
            print("GridEvent", destination)

        origin = part_item.mapFromScene(origin)
        if destination is None:
            destination = origin
        if origin == destination:
            # snap clockwise
            destination = self.findNextPoint(part_item, origin)
        if origin is None or destination is None:
            print("o", origin, "d", destination)
        delta = destination - origin
        dx, dy = delta.x(), delta.y()
        group = self.group
        pos = group.pos() + delta
        self.group.setPos(pos)
        self.moveSelection(dx, dy, False, use_undostack=True)
        self.hideLineItem()
    # end def

    def copySelection(self):
        """Summary

        Returns:
            TYPE: Description
        """
        part_instance = self.part_item.partInstance()
        copy_dict = v3encode.encodePartList(part_instance, list(self.selection_set))
        self.clipboard = copy_dict
#        print('SliceSelectTool %s' % self.selection_set)
    # end def

    def pasteClipboard(self):
        """Summary

        Returns:
            TYPE: Description
        """
        doc = self.manager.document
#        part = self.part_item.part()
        part_instance = self.part_item.partInstance()
        offset = self.part_item.copypaste_origin_offset

        # Abort if there is no offset (e.g. if the location is invalid)
        if offset is None:
            return

        doc.undoStack().beginMacro("Paste VirtualHelices")
        new_vh_set = v3decode.importToPart(part_instance, self.clipboard, offset)
        doc.undoStack().endMacro()
        self.modelClear()
        self.clipboard = None
        # doc.addVirtualHelicesToSelection(part, new_vh_set)
        return new_vh_set
    # end def

    def moveSelection(self, dx: float, dy: float,
                            finalize: bool,
                            use_undostack: bool = True):
        """Y-axis is inverted in Qt +y === DOWN

        Args:
            dx: Description
            dy: Description
            finalize: Description
            use_undostack (bool, optional): Description
        """
        # print("moveSelection: {}, {}".format(dx, dy))
        part_item = self.part_item
        sf = part_item.scaleFactor()
        part = part_item.part()
        part.translateVirtualHelices(self.selection_set,
                                     dx / sf, -dy / sf, 0,
                                     finalize,
                                     use_undostack=use_undostack)
    # end def

    def deactivate(self):
        """Summary

        Returns:
            TYPE: Description
        """
        if self.sgv is not None:
            try:
                self.sgv.rubberBandChanged.disconnect(self.selectRubberband)
            except Exception:
                pass    # required for first call
        self.modelClear()
        if self.snap_origin_item is not None:
            self.snap_origin_item.setSnapOrigin(False)
            self.snap_origin_item = None
        AbstractSliceTool.deactivate(self)
    # end def

    def getCustomContextMenu(self, point: QPoint):
        """point

        Args:
            point: Description
        """
        if len(self.selection_set) > 0:
            sgv = self.sgv
            menu = QMenu(sgv)
            copy_act = QAction("Copy selection", sgv)
            copy_act.setStatusTip("Copy selection")
            copy_act.triggered.connect(self.copySelection)
            menu.addAction(copy_act)
            if self.clipboard and self.part_item.copypaste_origin_offset:
                copy_act = QAction("Paste", sgv)
                copy_act.setStatusTip("Paste from clipboard")
                copy_act.triggered.connect(self.pasteClipboard)
                menu.addAction(copy_act)
            menu.aboutToShow.connect(self.lockHints)
            menu.aboutToHide.connect(self.unlockHints)
            menu.exec_(sgv.mapToGlobal(point))
    # end def

    def lockHints(self):
        self.part_item.lock_hints = True
    # end def

    def unlockHints(self):
        self.part_item.lock_hints = False
    # end def
# end class

class SliceSelectionBox(QGraphicsPathItem):
    _RADIUS = styles.SLICE_HELIX_RADIUS

    def __init__(self, parent: QGraphicsItem = None):
        super(QGraphicsPathItem, self).__init__(parent)
        self._rect = None
    # end def

    def painterPath(self):
        rect = self._rect
        radius = self._RADIUS

        path = QPainterPath()
        path.addRoundedRect(rect, radius, radius)
        return path
    # end def

    def refreshPath(self):
        """Summary

        Returns:
            TYPE: Description
        """
        self.prepareGeometryChange()
        self.setPath(self.painterPath())
        self._pos0 = self.pos()
    # end def

    def setRect(self, rect):
        self._rect = rect
    # end def

class SliceSelectionGroup(QGraphicsItemGroup):
    """Summary

    Attributes:
        bounding_rect_item (TYPE): Description
        drag_last_position (TYPE): Description
        drag_start_position (TYPE): Description
        tool (TYPE): Description
    """

    def __init__(self, tool, parent: QGraphicsItem = None):
        """Summary

        Args:
            tool (TYPE): Description
            parent (None, optional): Description
        """
        super(SliceSelectionGroup, self).__init__(parent)
        self.tool = tool
        self.setFiltersChildEvents(True)
        self.setFlag(QGraphicsItem.ItemIsFocusable)  # for keyPressEvents
        self.setFlag(QGraphicsItem.ItemIsMovable)

        # self.bounding_rect_item = bri = QGraphicsRectItem(tool)
        self.bounding_rect_item = bri = SliceSelectionBox()
        bri.hide()
        bri.setPen(getPenObj(_SELECT_COLOR, _SELECT_PEN_WIDTH))

        self.setZValue(styles.ZSELECTION)

        self.drag_start_position = QPointF()
        self.drag_last_position = QPointF()
    # end def

    def setSelectionRect(self):
        """Summary

        Returns:
            TYPE: Description
        """
        bri = self.bounding_rect_item
        rect = self.childrenBoundingRect()
        point = rect.topLeft() + self.scenePos()
        bri.setPos(bri.mapFromScene(point))
        bri.setRect(bri.mapRectFromItem(self, rect))
        self.addToGroup(bri)
        bri.refreshPath()
        bri.show()
        self.setFocus(True)
    # end def

    """ reimplement boundingRect if you want to call resetGroupPos
    """

    def clearSelectionRect(self):
        """reset positions to zero to keep things in check
        """
        bri = self.bounding_rect_item
        if bri.group() == self:
            bri.hide()
            self.removeFromGroup(bri)
            self.setFocus(False)
            bri.setParentItem(self.tool)
    # end def

    def keyPressEvent(self, event: QKeyEvent):
        """event.key() seems to be capital only?

        Args:
            event (TYPE): Description
        """
        # print("press", ord('g'))
        if event.text() == 'g':
            print("hey het")
        return QGraphicsItem.keyPressEvent(self, event)
    # end def

    def mousePressEvent(self, event: QGraphicsSceneMouseEvent):
        """Handler for user mouse press.

        Args:
            event: Contains item, scene, and screen
            coordinates of the the event, and previous event.
        """
        return QGraphicsItemGroup.mousePressEvent(self, event)
    # end def

    def mouseMoveEvent(self, event):
        """because SliceSelectionGroup has the flag
        QGraphicsItem.ItemIsMovable
        we need only get the position of the item to figure
        out what to submit to the model

        Args:
            event (TYPE): Description
        """
        # 1. call this super class method first to get the item position updated
        return
        res = QGraphicsItemGroup.mouseMoveEvent(self, event)
        # watch out for bugs here?  everything seems OK for now, but
        # could be weird window switching edge cases
        if not self.tool.individual_pick and event.buttons() == Qt.LeftButton:
            new_pos = self.pos()
            delta = new_pos - self.drag_last_position
            self.drag_last_position = new_pos
            dx, dy = delta.x(), delta.y()
            self.tool.moveSelection(dx, dy, False, use_undostack=False)
        return res
    # end def

    def mouseReleaseEvent(self, event):
        """because SliceSelectionGroup has the flag
        QGraphicsItem.ItemIsMovable
        we need only get the position of the item to figure
        out what to submit to the model

        Args:
            event (TYPE): Description
        """
        MOVE_THRESHOLD = 0.01   # ignore small moves
        # print("mouse mouseReleaseEvent", self.tool.individual_pick)
        if not self.tool.individual_pick and event.button() == Qt.LeftButton:
            delta = self.pos() - self.drag_start_position
            dx, dy = delta.x(), delta.y()
            # print(abs(dx), abs(dy))
            if abs(dx) > MOVE_THRESHOLD or abs(dy) > MOVE_THRESHOLD:
                # print("finalizling", dx, dy)
                self.tool.moveSelection(dx, dy, True)
        self.tool.individual_pick = False
        return QGraphicsItemGroup.mouseReleaseEvent(self, event)
    # end def