import os
from unittest import result
import banco1
from tkinter import *
from tkinter import ttk
import re
if os.name == "nt":
    os.system("cls");
c=os.path.dirname(__file__)
nomeArquivo=c+"\\nome.txt"

class validacpf:#validação de cpf
    def __init__(self,cpf):
        self.cpf=cpf
        print(f"cpf usado ={self.cpf}")
        self.valida()
    def valida(self):#funcão principal
        if not self.cpf:
            return False
        novo_cpf=self._calcula_digito(self.cpf[:9])
        novo_cpf=self._calcula_digito(novo_cpf)

        if novo_cpf==self.cpf:
            print("valida 1 ")
            return   True
        else:
            print ("nao valida 1")
            return False

    @staticmethod
    def _calcula_digito(fatia_cpf):#calculo

        if not fatia_cpf:
            return False
        sequencia=fatia_cpf[0]*len(fatia_cpf)
        print(sequencia)
        if sequencia == fatia_cpf:
            return False
        print("cauculo")
        soma=0
        for chave,multiplicador in enumerate(range(len(fatia_cpf)+1,1,-1)):
            soma += int(fatia_cpf[chave])* multiplicador
            print(soma)
        resto=11-(soma%11)
        resto=resto if resto <=9 else 0
        return fatia_cpf + str(resto)
    @property
    def cpf(self):#decorador
        print("1")
        return self._cpf

    @cpf.setter
    def cpf (self,cpf):#setter no cpf
        print("2")
        self._cpf=self._so_numeros(cpf)

    @staticmethod
    def _so_numeros(cpf):#3
        print("3")
        print(cpf)
        return re.sub('[^0-9]', '', cpf)#Revisão e substituição de caracteres desnecessário.

class Nova_Tela:
    def __init__(self, janela):
        self.Janela = janela
        self.Tela() #chamada da Função
        self.Frames_Tela()
        self.Botoes_Tela()
        self.label()
        self.menu()

        self.buttonradio()
    def validacao(self):
        cpf3=self.Nome.get()
        str(cpf3)
        print(f"cpf3: {cpf3}")
        validacpf(cpf3)

        if validacpf == True:
                print("cpf valido")
                return True
        else:
                print("cpf invalio")
                return False
    def Tela(self):#tela principal
        self.Janela.title("Aula 03/06/2022")
        self.Janela.configure(background="#4e5263")
        self.Janela.geometry("1000x800")
        self.Janela.resizable(True, True)
        self.Janela.maxsize(width=1000, height=800)
        self.Janela.minsize(width=600, height=400)
    def gravar_dados(self):
            self.vnome= self.Nome.get();
            self.vidade = self.idade.get();
            # self.vemail = self.email.get("1.0",END);
            nome="cola "
            matricula=654321
            idade=29
            sexo="masculino"
            mensalidade=9
            vquery =f'INSERT INTO aluno (nome,matricula,sexo,idade,mensalidade) VALUES ("{nome}",{matricula},"{sexo}",{idade},{mensalidade})'
            print("passou")
            print(vquery)
            banco1.inserirnobanco(vquery)
            # self.Nome.delete(0,END)
            # self.idade.delete(0,END)
            # self.email.delete("1.0",END)
            print("gravar dados executada")
    def semcomando(self):#funcao teste
        print("teste")
        self.cpf= self.Nome.get();

    def Frames_Tela(self):#janelas ou setores dentro da tela princiapal
        self.Frame_1 = Frame(self.Janela, bg="#2e5c5a",
                            highlightbackground="#fff",
                            highlightthickness=4)#borda do frame
        self.Frame_1.place(relx=0.00, rely=0.06, relwidth=0.99,
                            relheight=0.46)
        self.Frame_2 = Frame(self.Janela, bg="",
                            highlightbackground="#02043d",
                            highlightthickness=2)
        self.Frame_2.place(relx=0.01, rely=0.5, relwidth=0.96,
                            relheight=0.46)#relx=x mais em porcentagem  tudo por poecentagem
    def armazenarTXT(self):
        self.arquivo=open(nomeArquivo,"a")
        self.arquivo.write("  nome....:%s"% self.Nome.get())
        self.arquivo.write("\n idade...:%s"% self.idade.get())
        self.arquivo.write("\n email...:%s"% self.email.get())
        self.arquivo.write("\n\n")
        self.arquivo.close
    def Pegar_Dados(self):
        print(f"Nome: {self.Nome.get()}")
        print(f"Idade: {self.idade.get()}")
        print(f"Observações:\n{self.email.get()}")
        self.Texto_4["text"] = self.Nome.get()
        self.Nome.delete(0,END)
        self.idade.delete(0,END)
        self.email.delete("1.0",END)
    def mostrarTXT(self):
     self.arquivo = open(nomeArquivo, 'r')
     self.conteudo = self.arquivo.readlines()
    #  self.Texto_5["text"]=self.conteudo
    def mostrarBD(self):
        vquery="SELECT * FROM aluno"
        self.Texto_5["text"]= banco1.lerdados_banco(vquery)

    def grid(self):
        lista=[]
        tv=ttk.Treeview(self.Frame_1,columns=('id','nome','numero','idade','sei_nao','sexo'),show='headings')
        print("oi")
        tv.column('id',minwidth=0,width=30)
        tv.column('nome',minwidth=0,width=30)
        tv.column('numero',minwidth=0,width=30)
        tv.column('idade',minwidth=0,width=30)
        tv.column('sei_nao',minwidth=0,width=30)
        tv.column('sexo',minwidth=0,width=30)
        tv.heading('id',text='ID')
        tv.heading('nome',text='nome')
        tv.heading('numero',text='numero')
        tv.heading('idade',text='Idede')
        tv.heading('sei_nao',text='sei nao')
        tv.heading('sexo',text='sexo')
        tv.place(relx=0.01, rely=0.1,relwidth=0.9 ,relheight=0.9)
        vquery="SELECT * FROM aluno"
        v=banco1.lerdados_banco(vquery)
        print(v)
        # for f in range (6):
        #     f(str)
        print(v)
        for (id,nome,numero,sexo,idade,sei_nao) in v :
            id(str)
            idade(str)
            sei_nao(str)
            tv.insert("","end",values=(id(str),nome,numero,sexo,idade(str),sei_nao(str)))

    def update_banco_tela(self):
        nome="cola "
        Data="2012-04-03"
        quant=1220
        matricula=654321
        idade=29
        sexo="masculino"
        mensalidade=9
        p=1
        vquery=f"UPDATE aluno SET nome ='{nome}',matricula={matricula},sexo='{sexo}',idade={idade},mensalidade={mensalidade} where id_aluno = {p}"
        banco1.update_banco(vquery)
    def delete_banco_tela(self):
        produto=3
        vquery=f"DELETE FROM aluno WHERE  id_aluno={3}"
        print(f"xoi")
        banco1.delete_banco(vquery)
    def menu(self):
        barrademenu=Menu(self.Frame_2)#adivinhaa

        menucomtatos=Menu(barrademenu,tearoff=0)#opicao do menu

        menucomtatos.add_command(label="novo",command=self.grid)
        menucomtatos.add_command(label="pesquisa",command=self.pesquisa)
        menucomtatos.add_command(label="deletar",command=self.semcomando)
        menucomtatos.add_separator()#separacao
        menucomtatos.add_command(label="fechar",command=Janela.quit)#fechara a janela
        barrademenu.add_cascade(label="contados",menu=menucomtatos)#acrecentando na funcao barramenu(importante)

        menumanutencao=Menu(barrademenu,tearoff=0)
        menumanutencao.add_command(label="Banco de dados",command=self.semcomando)
        barrademenu.add_cascade(label="manutencao",menu=menumanutencao)
        menusobre=Menu(barrademenu,tearoff=0)
        menusobre.add_command(label="cfb",command=self.semcomando)
        barrademenu.add_cascade(label="sobre",menu=menusobre)#nao se esqueca desse menu(menu=)

        Janela.config(menu=barrademenu)
    def label(self):
        self.Texto_3 = Label(self.Frame_1, bg="#570318", fg="#000")
        self.Texto_3["text"] = "nome"
        self.Texto_3["font"] = ("Arial", "14", "bold")#especificacoe do texto
        self.Texto_3.place(relx=0.01, rely=0.1,relwidth=0.1 ,relheight=0.1)

        self.Nome = Entry (self.Frame_1)
        self.Nome["font"] = ("Arial", "14", "bold")
        self.Nome.place(relx=0.03, rely=0.2,relwidth=0.2, relheight=0.2)

        self.Texto_2 = Label(self.Frame_1, bg="#570318", fg="#000")
        self.Texto_2["text"] = "idade"
        self.Texto_2["font"] = ("Arial", "14", "bold")#especificacoe do texto
        self.Texto_2.place(relx=0.01, rely=0.5,relwidth=0.1 ,relheight=0.1)
        self.idade =Entry(self.Frame_1)
        self.idade["font"] = ("Arial", "14", "bold")
        self.idade.place(relx=0.03, rely=0.6,relwidth=0.2, relheight=0.2)

        self.Texto_1 = Label(self.Frame_1, bg="#570318", fg="#000")
        self.Texto_1["text"] = "email"
        self.Texto_1["font"] = ("Arial", "14", "bold")#especificacoe do texto
        self.Texto_1.place(relx=0.25, rely=0.5,relwidth=0.1 ,relheight=0.1)
        self.email = Text(self.Frame_1)
        self.email["font"] = ("Arial", "14", "bold")
        self.email.place(relx=0.27, rely=0.6,relwidth=0.2, relheight=0.2)

        self.Texto_4 = Label(self.Frame_2, bg="#570318", fg="#000")
        self.Texto_4["text"] =""#especificacoe do texto
        self.Texto_4["font"] = ("Arial", "14", "bold")#especificacoe do texto
        self.Texto_4.place(relx=0.01, rely=0.2,relwidth=0.2 ,relheight=0.3)
        self.Texto_5 = Label(self.Frame_2, bg="#570318", fg="#000")
        self.Texto_5["text"] =""#especificacoe do texto
        self.Texto_5["font"] = ("Arial", "11", "bold")#especificacoe do texto
        self.Texto_5.place(relx=0.55, rely=0.01,relwidth=0.44 ,relheight=0.9)
        self.Texto_1 = Label(self.Frame_1, bg="#570318", fg="#000")
        self.Texto_1["text"] = "sexo"
        self.Texto_1["font"] = ("Arial", "14", "bold")#especificacoe do texto
        self.Texto_1.place(relx=0.25, rely=0.1,relwidth=0.1 ,relheight=0.1)
        self.sexo = Text(self.Frame_1)
        self.sexo["font"] = ("Arial", "14", "bold")
        self.sexo.place(relx=0.25, rely=0.2,relwidth=0.2, relheight=0.2)

    def Botoes_Tela(self):#butoes
        self.Botao_1 = Button(self.Frame_1)#localizacao para seus parametros
        self.Botao_1["text"] = "Fechar"
        self.Botao_1["font"] = ("Arial", "12", "bold")#especificacoe do texto
        self.Botao_1["command"] = self.validacao
        self.Botao_1.place(relx=0.9, rely=0.0,relwidth=0.1, relheight=0.15)

        self.Botao_2 = Button(self.Frame_2)
        self.Botao_2["text"] = "nova aba"
        self.Botao_2["font"] = ("Arial", "12", "italic")
        self.Botao_2["command"] = self.Nova_Janela
        self.Botao_2.place(relx=0.1, rely=0.0,relwidth=0.1, relheight=0.15)

        self.Botao_3 = Button(self.Frame_2)
        self.Botao_3["text"] = "pegar"
        self.Botao_3["font"] = ("Arial", "12", "italic")
        self.Botao_3["command"] =  self.Pegar_Dados

        self.Botao_3.place(relx=0.00, rely=0.01,relwidth=0.1, relheight=0.15)
        self.Botao_3 = Button(self.Frame_2)
        self.Botao_3["text"] = "armazenar"
        self.Botao_3["font"] = ("Arial", "12", "italic")
        self.Botao_3["command"] = self.armazenarTXT

        self.Botao_3.place(relx=0.4, rely=0.01,relwidth=0.15, relheight=0.15)
        self.Botao_4= Button(self.Frame_2)
        self.Botao_4["text"] = "mostrar"
        self.Botao_4["font"] = ("Arial", "12", "italic")
        self.Botao_4["command"] = self.mostrarBD

        self.Botao_4.place(relx=0.5, rely=0.5,relwidth=0.15, relheight=0.15)
        self.Botao_5= Button(self.Frame_2)
        self.Botao_5["text"] = "banco de dados"
        self.Botao_5["font"] = ("Arial", "12", "italic")
        self.Botao_5["command"] = self.delete_banco_tela
        self.Botao_5.place(relx=0.4, rely=0.2,relwidth=0.15, relheight=0.15)
    def buttonradio(self):
        self.verdominio=StringVar()
        self.Texto_9 = Label(self.Frame_1, bg="#570318", fg="#000")
        self.Texto_9["text"] = "dominio"
        self.Texto_9["font"] = ("Arial", "14", "bold")
        self.Texto_9.place(relx=0.5, rely=0.02,relwidth=0.2 ,relheight=0.1)
        self.dominio_adm=Radiobutton(self.Frame_1,text="adm",value="e",variable=self.verdominio)
        self.dominio_adm.place(relx=0.5, rely=0.1,relwidth=0.1 ,relheight=0.1)
        self.dominio_aluno=Radiobutton(self.Frame_1,text="aluno",value="u",variable=self.verdominio)
        self.dominio_aluno.place(relx=0.5, rely=0.2,relwidth=0.1 ,relheight=0.1)
        self.dominio_funcionario=Radiobutton(self.Frame_1,text="funcionario",value="w",variable=self.verdominio)
        self.dominio_funcionario.place(relx=0.5, rely=0.3,relwidth=0.1 ,relheight=0.1)
        self.btn_domominio=Button(self.Frame_1,text="dominio selecionado",command=self.inprimirdominio)
        self.btn_domominio.place(relx=0.5, rely=0.4,relwidth=0.2 ,relheight=0.1)

    def inprimirdominio(self):
        self.ve=self.verdominio.get()
        print(self.ve)
        if self.ve=="e":
            print("ele serar um adm")
        elif self.ve=="w":
            print("ele serar um funcionario")
        elif self.ve=="u":
            print("ele serar um aluno")
        else:
            print("escolha um dominio")
    def Nova_Janela(self):#criar nova janela
        self.Janela_2 = Toplevel()
        self.Janela_2.title("Nova Janela")
        self.Janela_2.geometry("300x300")
        self.Janela_2.configure(background="#000")
        self.Janela_2.resizable(False, False)
        self.Janela_2.transient(self.Janela)
        self.Janela_2.focus_force()
        self.Janela_2.grab_set()
        self.Texto_3 = Label(self.Janela_2, bg="#570318", fg="#000")
        self.Texto_3["text"] = "cadastro efetuado"
        self.Texto_3["font"] = ("Arial", "14", "bold")
        self.Texto_3.place(relx=0.05, rely=0.1,relwidth=0.4 ,relheight=0.4)
    def pesquisa(self):#criar nova janela
        self.Janela_3 = Toplevel()
        self.Janela_3.title("Nova Janela")
        self.Janela_3.geometry("600x600")
        self.Janela_3.configure(background="#000")
        # self.Janela_3.resizable(False, False)
        self.Janela_3.transient(self.Janela)
        self.Janela_3.focus_force()
        self.Janela_3.grab_set()
        self.Texto_9= Label(self.Janela_3, bg="#570318", fg="#000")
        self.Texto_9["text"] = "manipulaaao do banco"
        self.Texto_9["font"] = ("Arial", "14", "bold")
        self.Texto_9.place(relx=0.00, rely=0.0,relwidth=0.99 ,relheight=0.1)
Janela = Tk()
Nova_Tela(Janela)
Janela.mainloop()


import logging
from datetime import timedelta
from datetime import datetime

import voluptuous as vol

import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (CONF_NAME, STATE_UNKNOWN, ATTR_DATE, ATTR_ATTRIBUTION)
from homeassistant.helpers.entity import Entity

import chinese_calendar as calendar

REQUIREMENTS = ['chinesecalendar==1.2.0']

_LOGGER = logging.getLogger(__name__)

DOMAIN = "chinese_calendar"

CONF_ATTRIBUTION = "中国节假日"

DEFAULT_NAME = 'Chinese Calendar'

MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string
})

def setup_platform(hass, config, add_devices, discovery_info=None):
    name = config.get(CONF_NAME)

    add_devices([ChineseCalendarSensor(name)], True)

class ChineseCalendarSensor(Entity):
    """Implementation of the Yahoo! weather sensor."""

    def __init__(self, name):
        """Initialize the sensor."""
        self._name = name
        self._state = STATE_UNKNOWN
        self._attr_name = ''

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def state(self):
        """Return the state of the device."""
        return self._state

    @property
    def state_attributes(self):
        """Return the state attributes.

        Implemented by component base class.
        """
        return {
            ATTR_DATE: datetime.today().date().strftime('%Y-%m-%d'),
            'name': self._attr_name
        }

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        return {
            ATTR_ATTRIBUTION: CONF_ATTRIBUTION,
        }

    def update(self):
        """Get the latest data from Yahoo! and updates the states."""
        is_holiday, holiday_name = calendar.get_holiday_detail(datetime.today().date())
        if is_holiday:
            self._state = 'holiday'
            self._attr_name = holiday_name
        else:
            self._state = 'workday'


import grpc
from concurrent import futures
import time
import queue
from collections import defaultdict
import random

import chat_pb2
import chat_pb2_grpc

class User:
    def __init__(self, name, queue):
        self.name = name
        self.queue = queue
        self.role = None

class Room:
    def __init__(self):
        self.users = []
        self.game_started = False
        self.enter_messages = []

class ChatServicer(chat_pb2_grpc.ChatServicer):
    def __init__(self):
        self.rooms = defaultdict(Room)
        self.roles = ["policeman", "villager", "villager", "mafia", "mafia"]

    def CheckRoom(self, request, context):
        room = self.rooms[request.room_number]
        if len(room.users) >= 5 or room.game_started:
            return chat_pb2.RoomStatus(is_filled=True)
        else:
            return chat_pb2.RoomStatus(is_filled=False)

    def CheckUsername(self, request, context):
        room = self.rooms[request.room_number]
        if any(user.name == request.username for user in room.users):
            return chat_pb2.UsernameStatus(is_taken=True)
        else:
            return chat_pb2.UsernameStatus(is_taken=False)

    def SendMessage(self, request, context):
        room = self.rooms[request.room_number]
        for user in room.users:
            if user.name != request.user:
                user.queue.put(request)
            room.enter_messages.append(request)
        return chat_pb2.Empty()

    def ListActiveUsers(self, request, context):
        return chat_pb2.UserList(user=[user.name for user in self.rooms[request.room_number].users])
    def ReceiveMessages(self, request, context):
        room = self.rooms[request.room_number]
        if room.game_started:
            return
        if len(room.users) >= 5:
            return
        if any(user.name == request.user for user in room.users):
            return
        q = queue.Queue()
        user = User(request.user, q)
        room.users.append(user)
        for message in room.enter_messages:
            q.put(message)
        enter_message = chat_pb2.Message(user="Server", text=f"{request.user} joined the game")
        room.enter_messages.append(enter_message)
        for u in room.users:
            u.queue.put(enter_message)
        if len(room.users) == 5:
            self.start_game(room)
        try:
            while True:
                yield q.get()
        except grpc.RpcError:
            exit_message = chat_pb2.Message(user="Server", text=f"{request.user} left the game")
            room.enter_messages.append(exit_message)
            for u in room.users:
                if u.name != request.user:
                    u.queue.put(exit_message)
        finally:
            room.users[:] = [user for user in room.users if user.name != request.user]

    def Quit(self, request, context):
        room_number = request.room_number
        user = request.user
        room = self.rooms[room_number]

        room.users[:] = [user for user in room.users if user.name != request.user]

        exit_message = chat_pb2.Message(user="Server", text=f"{request.user} left the game")
        room.enter_messages.append(exit_message)
        for u in room.users:
            if u.name != request.user:
                u.queue.put(exit_message)

        return chat_pb2.Empty()

    def start_game(self, room):
        room.game_started = True
        for user in room.users:
            user.queue.put(chat_pb2.Message(user="Server", text=f"Game has started!"))
        roles = self.roles[:]
        random.shuffle(roles)
        for user in room.users:
            user.role = roles.pop()
            user.queue.put(chat_pb2.Message(user="Server", text=f"You are a {user.role}."))

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    chat_pb2_grpc.add_ChatServicer_to_server(ChatServicer(), server)
    print('Starting server. Listening on port 50051.')
    server.add_insecure_port('[::]:50051')
    server.start()

    try:
        while True:
            time.sleep(86400)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    serve()


import sys
import json
import tkinter as tk
from tkinter import filedialog
from pathlib import Path

######################### File Input Dialog #########################

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename()

######################### Skill ID to Skill Name relation #########################

skills = {1: "Attack Boost",
          2: "Agitator",
          3: "Peak Performance",
          4: "Resentment",
          5: "Resuscitate",
          6: "Critical Eye",
          7: "Critical Boost",
          8: "Weakness Exploit",
          9: "Latent Power",
          10: "Maximum Might",
          11: "Critical Element",
          12: "Master's Touch",
          13: "Fire Attack",
          14: "Water Attack",
          15: "Ice Attack",
          16: "Thunder Attack",
          17: "Dragon Attack",
          18: "Poison Attack",
          19: "Paralysis Attack",
          20: "Sleep Attack",
          21: "Blast Attack",
          22: "Handicraft",
          23: "Razor Sharp",
          24: "Spare Shot",
          25: "Protective Polish",
          26: "Mind's Eye",
          27: "Ballistics",
          28: "Bludgeoner",
          30: "Focus",
          31: "Power Prolonger",
          32: "Marathon Runner",
          33: "Constitution",
          34: "Stamina Surge",
          35: "Guard",
          36: "Guard Up",
          37: "Offensive Guard",
          38: "Critical Draw",
          39: "Punishing Draw",
          40: "Quick Sheath",
          41: "Slugger",
          42: "Stamina Thief",
          43: "Affinity Sliding",
          44: "Horn Maestro",
          45: "Artillery",
          46: "Load Shells",
          47: "Special Ammo Boost",
          48: "Normal/Rapid Up",
          49: "Pierce Up",
          50: "Spread Up",
          51: "Ammo Up",
          52: "Reload Speed",
          53: "Recoil Down",
          54: "Steadiness",
          55: "Rapid Fire Up",
          56: "Defense Boost",
          57: "Divine Blessing",
          58: "Recovery Up",
          59: "Recovery Speed",
          60: "Speed Eating",
          61: "Earplugs",
          62: "Windproof",
          63: "Tremor Resistance",
          64: "Bubbly Dance",
          65: "Evade Window",
          66: "Evade Extender",
          67: "Fire Resistance",
          68: "Water Resistance",
          69: "Ice Resistance",
          70: "Thunder Resistance",
          71: "Dragon Resistance",
          72: "Blight Resistance",
          73: "Poison Resistance",
          74: "Paralysis Resistance",
          75: "Sleep Resistance",
          76: "Stun Resistance",
          77: "Muck Resistance",
          78: "Blast Resistance",
          79: "Botanist",
          80: "Geologist",
          81: "Partbreaker",
          84: "Good Luck",
          85: "Speed Sharpening",
          86: "Bombardier",
          87: "Mushroomancer",
          88: "Item Prolonger",
          89: "Wide-Range",
          90: "Free Meal",
          91: "Heroics",
          92: "Fortify",
          93: "Flinch Free",
          94: "Jump Master",
          95: "Carving Pro",
          96: "Hunger Resistance",
          97: "Leap of Faith",
          98: "Diversion",
          99: "Master Mounter",
          104: "Wirebug Whisperer",
          105: "Wall Runner",
          106: "Counterstrike",
          107: "Rapid Morph",
          108: "Hellfire Cloak",
          116: "Coalescence",
          122: "Redirection",
          123: "Spiribird's Call",
          124: "Charge Master",
          125: "Foray",
          126: "Tune-Up",
          127: "Grinder (S)",
          128: "Bladescale Hone",
          129: "Wall Runner (Boost)",
          131: "Chain Crit"}

######################### Function #########################

"""
Construct correctly formated strings from a JSON file of charms exported
from 'Charm Editor and Item Cheat' mods to statisfy the formating of
Monster Hunter Rise:Sunbreak Armorset Search on https://mhrise.wiki-db.com/sim/?hl=en

:param data: JSON file exported from 'Charm Editor and Item Cheat' mod for MH Rise
:return: returns a list of formated charm strings
"""
def stringbuilder(data):
    formated_strings = []

    for charm in data:
        try:
            skill_1 = skills[charm["Skills"][0]]

            tmp = f'{skill_1},{charm["SkillLevels"][0]}'

            if charm["Skills"][1] != 0:                         # if there are 2 skills
                skill_2 = skills[charm["Skills"][1]]
                tmp += f',{skill_2},{charm["SkillLevels"][0]}'
            else:
                tmp += ',,0'                                    # append ,,0 if there is only one skill on the charm

            if len(charm["Slots"]) >= 1:                        # dont think this check is neccessary but just to be sure
                tmp += f',{",".join(str(x) for x in charm["Slots"])}'

            formated_strings.append(tmp)

        except:
            print(charm)

    return formated_strings

######################### Reading and parsing JSON #########################

with open(file_path, "r") as f:
    file = f.read()

try:
    data = json.loads(file)
except:
    print("Please select a valid json file")
    _ = input("Press the enter button to exit")
    sys.exit(-1)

######################### Execute function #########################

charms = stringbuilder(data)

######################### Check if we missed some charms #########################

if len(data) != len(charms):
    print(f"somehow not all your charms could be exported. We are missing {len(data)-len(charms)} charms.")

######################### Write charms to text-file #########################

with open('charms.txt', "w") as file:
    for charm in charms:
        file.write(charm + "\n")

print(f"Successfully exported your charms to 'charms.txt' in {Path(__file__).parent.absolute()}.")
_ = input("Press the enter button to exit")
sys.exit(0)


from collections import deque

fireworks_effect = deque(int(x) for x in input().split(", "))
explosive_power = [int(x) for x in input().split(", ")]
fireworks_enough = False
palm = 0
willow = 0
crossette = 0

while fireworks_effect and explosive_power:
    current_effect = fireworks_effect.popleft()
    current_power = explosive_power.pop()
    if current_power <= 0:
        fireworks_effect.appendleft(current_effect)
        continue
    if current_effect <= 0:
        explosive_power.append(current_power)
        continue

    mix = current_effect + current_power

    if mix % 3 == 0 and mix % 5 != 0:
        palm += 1
    elif mix % 3 != 0 and mix % 5 == 0:
        willow += 1
    elif mix % 3 == 0 and mix % 5 == 0:
        crossette += 1
    else:
        fireworks_effect.append(current_effect - 1)
        explosive_power.append(current_power)
    if palm > 2 and willow > 2 and crossette > 2:
        fireworks_enough = True
        break

if fireworks_enough:
    print("Congrats! You made the perfect firework show!")
else:
    print("Sorry. You can't make the perfect firework show.")

if fireworks_effect:
    print(f"Firework Effects left: {', '.join(str(x) for x in fireworks_effect)}")

if explosive_power:
    print(f"Explosive Power left: {', '.join(str(x) for x in explosive_power)}")

print(f"Palm Fireworks: {palm}")
print(f"Willow Fireworks: {willow}")
print(f"Crossette Fireworks: {crossette}")


#!/usr/bin/env python3
import os
import rospy
from detection_srv.srv import Detector as D_srv
from detection_srv.srv import DetectorResponse
from sensor_msgs.msg import Image
import ros_numpy
from detector import Detector
from classmap import category_map as classmap

class DetectionService():

    def __init__(self):
        rospy.init_node('detection_node')
        rospy.loginfo("Loading model")
        self.DET_PATH=os.path.join(os.path.dirname(__file__),'efficientdet_d1_coco17_tpu-32')
        self.mydetector = Detector(self.DET_PATH)
        self.objects = []
        self.counter = 10
        self.connectPepper()

    def reset_service(self,topic):
        topic.unregister()
        self.objects.clear()
        self.counter = 10

    def serviceCallback(self, data):
        rospy.loginfo("Subscribe to image topic")
        topic = rospy.Subscriber("/testcam/image_raw", Image, self.rcv_image)
        while self.counter != 0:
            pass
        self.reset_service(topic)
        return DetectorResponse(self.objects)

    def connectPepper(self):
        rospy.loginfo("Advertise service")
        s = rospy.Service('detection_srv', D_srv, self.serviceCallback)

    def rcv_image(self, msg):
        rospy.loginfo("Image received")
        image = ros_numpy.numpify(msg)
        detections = self.mydetector(image)
        # Create the message and fill the data in the message (format conversion)
        # message = Detection2DArray()

        for clabel,score,box in zip(detections['detection_classes'], detections['detection_scores'], detections['detection_boxes']):
            #d = Detection2D()
            if classmap[clabel] not in self.objects:
                self.objects.append(classmap[clabel])

        self.counter = self.counter-1

if __name__=="__main__":
    detection_service = DetectionService()

    rospy.spin()


"""
Retrieve and process data from PRB — https://www.prb.org/
"""

# Standard library imports
from pathlib import Path
import csv
import os
import sys

# Third-party library imports
import requests
from dataflows import (
    Flow,
    PackageWrapper,
    ResourceWrapper,
    add_field,
    delete_fields,
    dump_to_path,
    load,
    set_type,
    validate,
)

# Local imports
from scripts import settings

# Hack to send data to change_path function without using additional parameters
FILE_NAME = None

def change_path(package: PackageWrapper):
    """Change the path to nest data in the subdirectory data/."""
    package.pkg.descriptor["resources"][0]["path"] = f"data/{FILE_NAME}.csv"
    yield package.pkg
    res_iter = iter(package)
    try:
        first: ResourceWrapper = next(res_iter)
    except StopIteration:
        pass
    yield first.it
    yield from package

def clean_data(filename: str, location: str) -> None:
    """Clean and validate data with `dataflows`, creating data packages in the
    process, one for each file."""
    global FILE_NAME
    FILE_NAME = f"{location}-{filename}"
    clean_directory, _, processing_directory = set_location_dirs(location)
    exported_file = f"{clean_directory}/{filename}"
    _ = Flow(
        load(
            f"{processing_directory}/{filename}.csv",
            name=FILE_NAME,
        ),
        change_path,
        add_field("NameFIPS", "string"),
        concat_name_columns,
        delete_fields(["Name", "FIPS"]),
        set_type("Data", type="any"),
        validate(),
        dump_to_path(exported_file),
    ).process()[1]

def concat_name_columns(row: dict) -> None:
    """Merge content of columns 'FIPS' and 'Name' into new column 'NameFIPS'."""
    row["NameFIPS"] = f"{row['Name']} {row['FIPS']}"

def delete_empty_rows(filename: str, location: str) -> None:
    """Delete empty lines in file located at `filepath`."""
    _, _, processing_directory = set_location_dirs(location)
    filepath = f"{processing_directory}/{filename}.csv"
    temp_file = f"{settings.DIRS['temp_dir']}/{filename}.csv"
    try:
        with open(filepath) as in_file, open(temp_file, "w") as out_file:
            writer = csv.writer(out_file)
            for row in csv.reader(in_file):
                if row:
                    writer.writerow(row)
        os.replace(temp_file, filepath)
    except FileNotFoundError:
        print(f"[Deleting empty lines] '{filepath}' not found. Next.")

def download_data(filename: str, url_bit: str) -> None:
    """Download given file from `url_bit` based on the required `filename`."""
    url = f"https://datacenter.prb.org/download/{url_bit}/indicator/{filename}/csv/"
    save_file = f"{filename}.csv"
    if url_bit == settings.DATA_US["url_bit"]:
        save_dir = f"{settings.DIRS['original_data_us']}/"
    else:
        save_dir = f"{settings.DIRS['original_data_inter']}/"
    save_path = f"{save_dir}{save_file}"

    if not os.path.isfile(save_path):
        request = requests.get(url, allow_redirects=True)
        with open(save_path, "wb") as data_file:
            data_file.write(request.content)

        # delete the file if the retrieved dataset doesn't exist
        # (file size < 1000 bytes)
        if Path(save_path).stat().st_size < 1000:
            # printed on the same line containing the dataset name
            print("DATA NOT FOUND.\n")
            os.remove(save_path)

def execute_on_all(location: str, func) -> None:
    """Take a `location` and do `func` on all items in that location."""
    func_arg = location
    if func is download_data:
        if location_is_us(location):
            func_arg = settings.DATA_US["url_bit"]
        else:
            func_arg = settings.DATA_INTER["url_bit"]

    if func is trim_file_header:
        if location_is_us(location):
            if folder_is_empty("original_data_us"):
                print("[Removing US header] No dataset found. Exiting.")
                sys.exit(0)
        else:
            if folder_is_empty("original_data_inter"):
                print(
                    "[Removing international header] No dataset found. Exiting."
                )
                sys.exit(0)

    if func is delete_empty_rows:
        if location_is_us(location):
            if folder_is_empty("processed_data_us"):
                print(
                    "[Deleting empty lines for US] No dataset found. Exiting."
                )
                sys.exit(0)
        else:
            if folder_is_empty("processed_data_inter"):
                print(
                    "[Deleting empty lines for international] No dataset found. Exiting."
                )
                sys.exit(0)

    for item in settings.LOCATIONS[location]:
        func(item, func_arg)

def folder_is_empty(folder_name: str) -> bool:
    """Return bool as to whether `folder_name` is empty."""
    return os.listdir(settings.DIRS[folder_name]) == []

def location_is_us(source_name: str) -> bool:
    """Return bool as to whether `source_name` equals "us" or not."""
    return source_name == "us"

def set_location_dirs(location: str) -> tuple:
    """Return a tuple containing directory settings for a given `location`."""
    if location_is_us(location):
        clean_directory = settings.DIRS["clean_data_us"]
        original_directory = settings.DIRS["original_data_us"]
        processing_directory = settings.DIRS["processed_data_us"]
    else:
        clean_directory = settings.DIRS["clean_data_inter"]
        original_directory = settings.DIRS["original_data_inter"]
        processing_directory = settings.DIRS["processed_data_inter"]
    return (clean_directory, original_directory, processing_directory)

def trim_file_header(filename: str, location: str, lines: int = 4) -> None:
    """Remove the first `lines` in `filename` for `location`."""
    (_, original_directory, processing_directory,) = set_location_dirs(
        location
    )
    try:
        trimmed = False
        with open(f"{original_directory}/{filename}.csv") as input_file, open(
                f"{settings.DIRS['temp_dir']}/{filename}.csv", "w"
        ) as output_file:
            first_line = input_file.readline()
            if not first_line.startswith("FIPS"):  # file needs to be trimmed
                input_file.seek(0)  # reset position to first line
                for _ in range(lines):
                    next(input_file)  # discard header lines
                for line in input_file:  # save remaining lines
                    output_file.write(line)
                trimmed = True
        if trimmed:  # only replace if the file has been trimmed
            os.replace(
                f"{settings.DIRS['temp_dir']}/{filename}.csv",
                f"{processing_directory}/{filename}.csv",
            )
        else:
            print(f"No header found in {filename}.csv.")
    except FileNotFoundError:
        print(f"[Removing header] '{filename}.csv' not found. Next.")

def run() -> None:
    """Retrieve and clean everything in one go."""
    for location in settings.LOCATIONS:
        execute_on_all(location, download_data)
        execute_on_all(location, trim_file_header)
        execute_on_all(location, delete_empty_rows)
        execute_on_all(location, clean_data)

if __name__ == "__main__":
    run()


from logging import Logger

import numpy as np
import pandas as pd
from sqlalchemy import Table, select
from sqlalchemy.sql import Select

from src.pipeline.processing import get_unused_col_name, join_on_multiple_keys

def make_add_vessels_columns_query(
    vessel_ids: list,
    vessels_table: Table,
    vessels_columns_to_add: list = None,
    districts_table: Table = None,
    districts_columns_to_add: list = None,
) -> Select:
    """
    Creates a `sqlalchemy.select` statement representing a query to fetch the
    designated columns from the `vessels` and / or `districts` tables for the
    indicated `vessel_ids`.

    Args:
        vessel_ids (list): List of vessels `id` to fetch data for.
        vessels_table (Table): vessels table.
        vessels_columns_to_add (list, optional): List of columns to get from the
          `vessels` table. Defaults to None.
        districts_table (Table, optional): districts table. Must be supplied if
          `districts_columns_to_get` is given. Defaults to None.
        districts_columns_to_add (list, optional): List of columns to get from the
          `districts` table. Defaults to None.

    Returns:
        Select: select statement to execute to get the indicated data.
    """

    from_table = vessels_table

    if districts_columns_to_add:
        assert isinstance(districts_table, Table)
        from_table = from_table.join(
            districts_table,
            from_table.c.district_code == districts_table.c.district_code,
            isouter=True,
        )

    columns = [vessels_table.c.id.label("vessel_id")]

    if vessels_columns_to_add:
        columns += [vessels_table.c.get(col) for col in vessels_columns_to_add]

    if districts_columns_to_add:
        columns += [districts_table.c.get(col) for col in districts_columns_to_add]

    q = (
        select(*columns)
        .select_from(from_table)
        .where(vessels_table.c.id.in_(vessel_ids))
    )

    return q

def make_find_vessels_query(
    vessels: pd.DataFrame,
    vessels_table: Table,
) -> Select:
    """
    Creates a `sqlalchemy.select` object representing a query to find `vessels` in
    the `vessels` table that match any of the lines in the input `DataFrame` on any of
    `cfr`, `ircs` or `external_immatriculation`.

    Args:
        vessels (pd.DataFrame): `DataFrame`. Must have columns `cfr`, `ircs` and
          `external_immatriculation`. If any other columns are present they are
          ignored.
        vessels_table (Table): `sqlalchemy.Table` object representing the `vessels`
          table. Must have columns `cfr`, `ircs` and `external_immatriculation`. If any
          other columns are present they are ignored.

    Returns:
        Select: query object with columns `vessel_id`, `cfr`, `ircs` and
          `external_immatriculation`.
    """
    assert "cfr" in vessels
    assert "ircs" in vessels
    assert "external_immatriculation" in vessels

    q = select(
        vessels_table.c.id.label("vessel_id"),
        vessels_table.c.cfr,
        vessels_table.c.ircs,
        vessels_table.c.external_immatriculation,
    ).where(
        vessels_table.c.cfr.in_(vessels.cfr.dropna().drop_duplicates().to_list())
        | vessels_table.c.external_immatriculation.in_(
            vessels.external_immatriculation.dropna().drop_duplicates().to_list()
        )
        | vessels_table.c.ircs.in_(vessels.ircs.dropna().drop_duplicates().to_list())
    )

    return q

def merge_vessel_id(
    vessels: pd.DataFrame, found_vessels: pd.DataFrame, logger: Logger
) -> pd.DataFrame:
    """
    The two input DataFrames are assumed to be:

      - a list of vessels with `cfr`, `ircs` and `external_immatriculation` identifiers
        (plus potential other columns) without a `vessel_id` column
      - a list of vessels with `cfr`, `ircs` and `external_immatriculation` and
        `vessel_id` columns (and no other columns). Typically these are the vessels
        that are found in the `vessels` table that match one of the identifiers of the
        `vessels` DataFrame by the `make_find_vessels_query` query.

    The idea is to add the `vessel_id` from the second DataFrame as a new column in the
    first DataFrame, by matching the right lines in both DataFrame.

    This is done by perfoming a left join of the input DataFrames using
    join_on_multiple_keys on ["cfr", "ircs", "external_immatriculation"].

    Additionnally, the returned `vessel_id` for each line in the first DataFrame is
    `None` if the following conditions are not met :

      - there is no ambiguity: only one vessel in the second DataFrame can be matched
        to a given line in the first DataFrame
      - there is no conflict: at most one vessel in the first DataFrame can be matched
        to a given line in the second DataFrame

    Lines in the second DataFrame that do not match a line in the first DataFrame are
    absent from the result.

    Lines in the first DataFrame that do not match a line in the second DataFrame are
    present in the result with a `vessel_id` of `None`.

    The result always has exactly the same lines as the first input DataFrame.

    Args:
        vessels (pd.DataFrame): Vessels to match to a found_vessel
        found_vessels (pd.DataFrame): found_vessels to match to a vessel
        logger (Logger): Logger instance

    Returns:
        pd.DataFrame: Same as vessels with an added `vessel_id` column.
    """
    initial_length = len(vessels)
    vessels = vessels.copy(deep=True)

    # Number rows of input DataFrame
    input_id = get_unused_col_name("input_row_number", vessels)
    vessels[input_id] = range(len(vessels))

    # Join
    vessels = join_on_multiple_keys(
        vessels,
        found_vessels,
        or_join_keys=["cfr", "ircs", "external_immatriculation"],
        how="left",
        coalesce_common_columns=False,
    )

    vessels["is_ambiguous"] = vessels.duplicated(subset=input_id, keep=False)
    vessels["is_in_conflict"] = vessels.duplicated(subset="vessel_id", keep=False)

    if vessels.is_ambiguous.any():
        ambiguous_vessels = vessels.loc[
            vessels.is_ambiguous,
            [input_id, "cfr", "ircs", "external_immatriculation", "vessel_id"],
        ].sort_values(input_id)

        warning_message = (
            "The following identifiers are ambiguous as they could correspond to "
            "more than one vessel:\n" + str(ambiguous_vessels.to_markdown(index=False))
        )

        logger.warning(warning_message)

    if vessels.is_in_conflict.any():
        vessels_in_conflict = vessels.loc[
            vessels.is_in_conflict,
            [input_id, "cfr", "ircs", "external_immatriculation", "vessel_id"],
        ].sort_values("vessel_id")

        warning_message = (
            "The following identifiers conflict with one another - "
            "more than one match the same vessel:\n"
            + str(vessels_in_conflict.to_markdown(index=False))
        )

        logger.warning(warning_message)

    vessels = vessels.drop_duplicates(subset=input_id)

    assert len(vessels) == initial_length

    vessels["vessel_id"] = vessels.vessel_id.where(
        ~(vessels[["is_ambiguous", "is_in_conflict"]].any(axis=1)), np.nan
    )

    return (
        vessels.sort_values(input_id)
        .drop(columns=[input_id, "is_ambiguous", "is_in_conflict"])
        .reset_index(drop=True)
    )


# -*- coding: utf-8 -*-
__author__ = 'buzz'
__date__ = '2018/4/7 上午11:30'

import threading

a = 0

def test():
    threading.Timer(2.0, test).start()
    global a
    if a == 0:
        print("aaa")
        a = 1
    elif a == 1:
        print("bbb")
        a = 2
    else:
        print("ccc")
        a = 0

test()


import os
import json
import httpx
from babel.dates import format_timedelta
import dateparser
from flask import Flask, jsonify, request, send_file, render_template, Response

import google.auth
from googleapiclient.discovery import build

app = Flask(__name__, static_url_path='/static', static_folder='static')
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True

_, project = google.auth.default()
region = os.environ.get("REGION", "us-central1")

def run_report():
    run = build("run", "v1")
    services = (
        run.projects()
        .locations()
        .services()
        .list(parent=f"projects/{project}/locations/{region}")
        .execute()
    )

    cb = build("cloudbuild", "v1")

    results = {}
    for srv in services["items"]:
        name = srv["metadata"]["name"]
        url = srv["status"]["url"]

        trigger = None; commit_id = None; finishTime = None; success = None

        if name == "admin":
            continue

        trigger_id = get_trigger_id(cb, name)
        if trigger_id:
            last_build = latest_build(cb, trigger_id)
            if last_build:
                commit_id = last_build["substitutions"]["SHORT_SHA"]
                finishTime = last_build["finishTime"]
                success = last_build["status"] == "SUCCESS"

        results[name] = {"commit_id": commit_id,
                        "finishTime": finishTime,
                         "url": url,
                         "success": success}
    return results

def get_trigger_id(cb, name):
    triggers = cb.projects().triggers().list(projectId=project).execute()
    for t in triggers["triggers"]:
        if "substitutions" not in t.keys():
            continue
        if "_SERVICE" not in t["substitutions"].keys():
            continue
        if t["substitutions"]["_SERVICE"] == name:
            return t["id"]
    return None

def latest_build(cb, trigger_id):
    kwargs = {
                "projectId": project,
                "filter": f'trigger_id="{trigger_id}"',
                "pageSize": 1
            }
    # presumes order
    builds = cb.projects().builds().list(**kwargs).execute()
    if builds:
        return builds["builds"][0]
    else:
        return None

@app.route("/api")
def report():
    return jsonify(run_report())

def relative_time(dstr):
    if not dstr:
        return "(no data)"
    delta = dateparser.parse("now Z") - dateparser.parse(dstr, settings={"TIMEZONE": "Z"})
    return f"{format_timedelta(delta)} ago"

@app.route("/status")
def status():
    data = run_report()

    # converting dict to list, for table formatting ease
    resp = []
    for key in data.keys():
        state = data[key]
        state["name"] = key
        state["relativeFinishTime"] = relative_time(state["finishTime"])
        resp.append(state)
    return render_template("index.html", data=resp)

@app.route("/status/<service>.svg")
def status_image(service):
    cb = build("cloudbuild", "v1")
    commit_id = "unknown"; success_color = "inactive"
    trigger_id = get_trigger_id(cb, service)
    if trigger_id:
        result = latest_build(cb, trigger_id)
        if result:
            if result["status"] == "SUCCESS":
                success_color = "success"
            else:
                success_color = "critical"
            if "substitutions" in result.keys() and "SHORT_SHA" in result["substitutions"].keys():
                commit_id = result["substitutions"]["SHORT_SHA"]
            else:
                commit_id = "unknown"

    shield_label = "Last sample deployed at commit".replace(" ", "%20")
    shield_url = (f"https://img.shields.io/badge/{shield_label}-{commit_id}-{success_color}"
                   "?style=flat-square&logo=google-cloud&logoColor=white")
    resp = httpx.get(shield_url)
    return Response(resp.content, mimetype="image/svg+xml")

@app.route("/")
def home():
    return """

    """

if __name__ == "__main__":
    app.run(host="localhost", port=8080, debug=True)


from dataclasses import dataclass, field

from dotmap import DotMap
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QDialog, QWidget, QFormLayout, QLabel, QDialogButtonBox

from gui.config_editor_widgets import MultiDropdownWidget, SingleDropdownWidget
from gui.config_editor_widgets import MultilineInputWidget, SingleLineInputWidget

@dataclass
class ConfigSetting:
    display_name: str
    object_name: str
    tooltip: str = ""
    has_multi_value: bool = False
    options: list[str] = field(default_factory=list)
    widget: object = None

class ProjectConfigDialog(QDialog):
    config_settings = [
        ConfigSetting(display_name="Moodle username:", object_name="username"),
        ConfigSetting(display_name="Moodle password:", object_name="password"),
        ConfigSetting(display_name="Moodle server URL:", object_name="server_url"),
        ConfigSetting(display_name="Moodle service:", object_name="moodle_service"),
        ConfigSetting(
            display_name="Moodle course shortname:", object_name="course_shortname"
        ),
        ConfigSetting(
            display_name="Assignment regexes:",
            object_name="assignment_regexes",
            tooltip="Info :: pattern",
            has_multi_value=True,
            options="assignment_regexes_presets",
        ),
        ConfigSetting(
            display_name="Username conversions:",
            object_name="username_conversions",
            tooltip="Info :: from-pattern :: to-pattern",
            has_multi_value=True,
            options="username_conversions_presets",
        ),
        ConfigSetting(
            display_name="Assignment conversions:",
            object_name="assignment_conversions",
            tooltip="Info :: from-pattern :: to-pattern",
            has_multi_value=True,
            options="assignment_conversions_presets",
        ),
        ConfigSetting(
            display_name="Archive directories:",
            object_name="archive_dirs",
            has_multi_value=True,
        ),
        ConfigSetting(display_name="Basecode directory:", object_name="template_dir"),
        ConfigSetting(
            display_name="Language parser:",
            object_name="language",
            has_multi_value=False,
            options="language_presets",
        ),
        ConfigSetting(display_name="Min sim to report:", object_name="min_sim"),
        ConfigSetting(display_name="Java path:", object_name="java_path"),
    ]

    def _makeWidget(self, setting):
        multivalue = setting.has_multi_value
        options = setting.options
        obj = setting.object_name
        hint = setting.tooltip
        opts = [] if not setting.options else self._config[setting.options]

        if multivalue and options:  # a group of combo boxes
            return MultiDropdownWidget(object_name=obj, tooltip=hint, options=opts)
        elif not multivalue and options:  # a single combo box
            return SingleDropdownWidget(object_name=obj, tooltip=hint, options=opts)
        elif multivalue:  # a group of single-line inputs
            return MultilineInputWidget(object_name=obj, tooltip=hint)
        else:  # a single-line input box
            return SingleLineInputWidget(object_name=obj, tooltip=hint)

    def __init__(self, parent: QWidget, config: DotMap) -> None:
        super().__init__(parent)

        self._config = config
        self.setWindowTitle("Project Settings")
        self.form_layout = QFormLayout(verticalSpacing=15)

        for setting in self.config_settings:
            label = QLabel(setting.display_name)
            setting.widget = self._makeWidget(setting)
            self.form_layout.addRow(label, setting.widget)

        buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self
        )
        self.form_layout.addRow(buttons)

        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)

        self.setLayout(self.form_layout)
        self._loadConfigValues()

    def _loadConfigValues(self) -> None:
        for widget, value in [(s.widget, s.object_name) for s in self.config_settings]:
            widget.display_value(self._config[value])

    def _saveConfigValues(self) -> None:
        for widget in [s.widget for s in self.config_settings]:
            self._config[widget.objectName()] = widget.get_value()

    @staticmethod
    def show(parent, config) -> tuple[bool, DotMap]:
        dialog = ProjectConfigDialog(parent, config)
        result = dialog.exec()
        if result == QDialog.Accepted:
            dialog._saveConfigValues()
        return result == QDialog.Accepted, dialog._config


customers = [
            {
                "name": "Alice",
                "pets": [],
                "cash": 1000
            },
            {
                "name": "Bob",
                "pets": [],
                "cash": 50
            },
            {
                "name": "Jack",
                "pets": [],
                "cash": 100
            }
        ]

pet_shop = {
            "pets": [
                {
                    "name": "Sir Percy",
                    "pet_type": "cat",
                    "breed": "British Shorthair",
                    "price": 500
                },
                {
                    "name": "King Bagdemagus",
                    "pet_type": "cat",
                    "breed": "British Shorthair",
                    "price": 500
                },
                {
                    "name": "Sir Lancelot",
                    "pet_type": "dog",
                    "breed": "Pomsky",
                    "price": 1000,
                },
                {
                    "name": "Arthur",
                    "pet_type": "dog",
                    "breed": "Husky",
                    "price": 900,
                },
                {
                    "name": "Tristan",
                    "pet_type": "cat",
                    "breed": "Basset Hound",
                    "price": 800,
                },
                {
                    "name": "Merlin",
                    "pet_type": "cat",
                    "breed": "Egyptian Mau",
                    "price": 1500,
                }
            ],
            "admin": {
                "total_cash": 1000,
                "pets_sold": 0,
            },
            "name": "Camelot of Pets"
        }
# WRITE YOUR FUNCTIONS HERE
# Test 1
def get_pet_shop_name (pet_shop):
    name = pet_shop ["name"]
    return name

# Test 2
def get_total_cash(pet_shop):
    total = pet_shop ["admin"]["total_cash"]
    return total

# Test 3 & 4
def add_or_remove_cash(pet_shop,add):
    pet_shop["admin"]["total_cash"]+= add
    return  get_total_cash

# Test 5
def get_pets_sold(pet_shop):
    pets_sold = pet_shop["admin"]["pets_sold"]
    return pets_sold

# Test 6
def increase_pets_sold (pet_shop, num_sold):
    pet_shop["admin"]["pets_sold"]+= num_sold
    return get_pets_sold

#  Test 7
def get_stock_count(pet_shop):
    stock = len(pet_shop["pets"])
    return stock

# Test 8 & 9
def get_pets_by_breed(pet_shop,breed):
    pets_by_breed = []
    for pet in pet_shop["pets"]:
        if breed == (pet["breed"]):
            pets_by_breed.append(pet["name"])
    return pets_by_breed

# Test 10 & 11
def find_pet_by_name(pet_shop,pet_name):
    for pet in pet_shop["pets"]:
        if pet_name == (pet["name"]):
            return pet

# Test 12
def remove_pet_by_name(pet_shop, pet_name):
    for pet in pet_shop["pets"]:
        if pet_name == (pet["name"]):
            pet_shop["pets"].remove(pet)

# Test 13
def add_pet_to_stock(pet_shop, new_pet):
    pet_shop["pets"].append([new_pet])

# Test 14
def get_customer_cash(customer):
    return customer["cash"]

# Test 15
def remove_customer_cash(customer,spend):
    customer["cash"]-= spend
    return customer

# # Test 16
def get_customer_pet_count(customer):
    return len(customer["pets"])

# # Test 17
def  add_pet_to_customer(customer, new_pet):
    customer["pets"].append([new_pet])
    return len(customer["pets"])

# Test 18 & 19
def customer_can_afford_pet(customer,pet):
    if customer["cash"] >= pet["price"]:
        return True
    else:
        return False

# Test 20 & 21 & 22
def sell_pet_to_customer(pet_shop,pet,customer):
    num_sold = 1
    cost = pet["price"]
    if pet in pet_shop["pets"] and customer_can_afford_pet(customer,pet) == True:
        add_pet_to_customer(customer,pet)
        increase_pets_sold (pet_shop, num_sold)
        remove_customer_cash(customer,cost)
        add_or_remove_cash(pet_shop,cost)
        return get_customer_cash(customer), get_total_cash(pet_shop), get_pets_sold(pet_shop)
customer = customers[0]
pet = find_pet_by_name(pet_shop,"Arthur")
print (sell_pet_to_customer(pet_shop,pet,customer))


import pandas as pd
import streamlit as st
import pickle
import sklearn
import numpy as np
import datetime

df=pd.read_csv('car_data.xls')
forest = open('Car_Price_prediction_model.pkl','rb')
model = pickle.load(forest)
st.title(':violet[VEHICLE PRICE PREDICTION APP]')
dict={'ritz': 90.0, 'sx4': 93.0, 'ciaz': 68.0, 'wagon_r': 96.0, 'swift': 92.0,'vitara_brezza': 95.0, 's_cross': 91.0, 'alto_800': 62.0, 'ertiga': 76.0, 'dzire': 73.0, 'alto_k10': 63.0,
      'ignis': 85.0, '800': 0.0, 'baleno': 65.0, 'omni': 89.0, 'fortuner': 81.0, 'innova': 86.0, 'corolla_altis': 71.0, 'etios_cross': 77.0, 'etios_g': 78.0, 'etios_liva': 80.0,
      'corolla': 70.0, 'etios_gd': 79.0, 'camry': 67.0, 'land_cruiser': 88.0, 'Royal_Enfield_Thunder_500': 49.0, 'UM_Renegade_Mojave': 56.0, 'KTM_RC200': 42.0, 'Bajaj_Dominar_400': 11.0,
      'Royal_Enfield_Classic_350': 46.0, 'KTM_RC390': 43.0, 'Hyosung_GT250R': 40.0, 'Royal_Enfield_Thunder_350': 48.0, 'KTM_390_Duke_': 41.0, 'Mahindra_Mojo_XT300': 44.0,
      'Bajaj_Pulsar_RS200': 17.0, 'Royal_Enfield_Bullet_350': 45.0, 'Royal_Enfield_Classic_500': 47.0, 'Bajaj_Avenger_220': 6.0, 'Bajaj_Avenger_150': 4.0, 'Honda_CB_Hornet_160R': 32.0,
      'Yamaha_FZ_S_V_2.0': 60.0, 'Yamaha_FZ_16': 58.0, 'TVS_Apache_RTR_160': 51.0, 'Bajaj_Pulsar_150': 14.0, 'Honda_CBR_150': 37.0, 'Hero_Extreme': 20.0, 'Bajaj_Avenger_220_dtsi': 7.0,
      'Bajaj_Avenger_150_street': 5.0, 'Yamaha_FZ__v_2.0': 57.0, 'Bajaj_Pulsar__NS_200': 12.0, 'Bajaj_Pulsar_220_F': 15.0, 'TVS_Apache_RTR_180': 52.0, 'Hero_Passion_X_pro': 26.0,
      'Bajaj_Pulsar_NS_200': 16.0, 'Yamaha_Fazer_': 61.0, 'Honda_Activa_4G': 31.0, 'TVS_Sport_': 54.0, 'Honda_Dream_Yuga_': 38.0, 'Bajaj_Avenger_Street_220': 8.0, 'Hero_Splender_iSmart': 28.0,
      'Activa_3g': 1.0, 'Hero_Passion_Pro': 25.0, 'Honda_CB_Trigger': 34.0, 'Yamaha_FZ_S_': 59.0, 'Bajaj_Pulsar_135_LS': 13.0, 'Activa_4g': 2.0, 'Honda_CB_Unicorn': 35.0, 'Hero_Honda_CBZ_extreme': 22.0,
      'Honda_Karizma': 39.0, 'Honda_Activa_125': 30.0, 'TVS_Jupyter': 53.0, 'Hero_Honda_Passion_Pro': 23.0, 'Hero_Splender_Plus': 27.0, 'Honda_CB_Shine': 33.0, 'Bajaj_Discover_100': 9.0,
      'Suzuki_Access_125': 50.0, 'TVS_Wego': 55.0, 'Honda_CB_twister': 36.0, 'Hero_Glamour': 21.0, 'Hero_Super_Splendor': 29.0, 'Bajaj_Discover_125': 10.0, 'Hero_Hunk': 24.0,
      'Hero__Ignitor_Disc': 19.0, 'Hero__CBZ_Xtreme': 18.0, 'Bajaj__ct_100': 3.0, 'i20': 84.0, 'grand_i10': 82.0, 'i10': 83.0, 'eon': 75.0, 'xcent': 97.0, 'elantra': 74.0, 'creta': 72.0,
      'verna': 94.0, 'city': 69.0, 'brio': 66.0, 'amaze': 64.0, 'jazz': 87.0}

#code to remove whitespace
def remove(string):
    return string.replace(" ", "_")

col1,col2=st.columns(2)
with col1:
    # For vehicle Type
    vehicle=st.selectbox(':blue[Select Vehicle]',df['Car_Name'].unique())
    if vehicle:
        veh=remove(vehicle)
        vehicle=dict[veh]
    #st.write(vehicle)

    # For price column
    price=st.text_input(':blue[Enter The Present Price of Vehicle in Lacks]')
    if price:
        present_price=int(price)

    # Seller Type
    seller = st.selectbox(':blue[Select Seller Type]', ['Dealer', 'Individual'])
    if seller == 'Dealer':
        Seller_Type = 0
    else:
        Seller_Type = 1
    # st.write(Seller_Type)

    # For Kilometers driven
    kilometers_driven = st.text_input(':blue[Enter the Number of Kilometers Driven]')
    if kilometers_driven:
        kilometers_driven = int(kilometers_driven)
    #st.write(kilometers_driven)

with col2:
    # For Transmission Type
    trans=st.selectbox(':blue[Select Transmission Type]',['Manual', 'Automatic'])
    if trans == 'Manual':
        Transmission=0
    else:
        Transmission = 1
    #st.write(Transmission)

    # For owner
    owner=st.text_input(':blue[Enter The Number Of Owners]')
    if owner:
        owner=int(owner)
    #st.write(owner)

     # For fuel column
    fuel = st.selectbox(':blue[Select Fuel Type]', ['Petrol', 'Diesel', 'CNG'])
    if fuel == 'Petrol':
        fuel_type = 0
    elif fuel == 'Diesel':
        fuel_type = 1
    else:
        fuel_type = 2
    # st.write(fuel_type)

    # For age column
    age=st.text_input(':blue[Enter The Registered Year of Vehicle]')
    if age:
        date_time = datetime.datetime.now()
        age= date_time.year-int(age)

    #st.write(age)

predict=st.button('predict')
if predict:
    prediction=model.predict([[vehicle,present_price, kilometers_driven, fuel_type, Seller_Type, Transmission, owner, age]])
    st.write("### :green[The predicted price of vehicle is]",int(prediction[0]))

st.write( f'<h5 style="color:rgb(0, 153, 153,0.35);">App Created by RAVI CHANDRA PALEM </h5>', unsafe_allow_html=True )


from turtle import Turtle,Screen
t=Turtle()
s=Screen()
t.width(5)
t.penup()
t.goto(-200,0)
t.pendown()
t.begin_fill()
t.forward(20*20)
t.left(90)
t.circle(radius=(20*20)/2,extent=180)
t.fillcolor("light yellow")
t.end_fill()
#carne
t.penup()
t.goto(-220,0)
t.pendown()
t.begin_fill()
t.left(90)
t.forward(22*20)
t.left(90)
t.circle(radius=(22*20)/2,extent=180)
t.left(90)
t.forward(20)

t.left(90)
t.circle(radius=(-20*20)/2,extent=180)
t.fillcolor("brown")
t.end_fill()
#occhi
t.penup()
t.goto(-100,140)
t.pendown()
t.left(180)
t.circle(radius=-40,extent=180)
t.penup()
t.goto(20,140)
t.pendown()
t.left(180)
t.circle(radius=-40,extent=180)
#bocca
t.penup()
t.goto(-40,60)
t.pendown()
t.circle(radius=40,extent=180)
#insalata
#base insalata
t.penup()
t.goto(-240,0)
t.pendown()
t.right(90)
t.forward(24*20)
#arco1
t.penup()
t.goto(240.00000000000006,-1.3851501580850336e-13)
t.pendown()
t.begin_fill()
t.left(180)
t.left(190)
t.circle(radius=42,extent=180)

for i in range(0,8):
    t.left(200)
    t.circle(radius=42, extent=180)
t.left(10)
print(t.heading(),t.xcor(),t.ycor())
t.forward(23.7367205840652)
t.left(90)
t.circle(radius=(-22*20)/2,extent=180)
t.fillcolor("green")
t.end_fill()
#pane
t.right(90)
t.penup()
t.goto(240.00000000000006,-1.3851501580850336e-13)
t.pendown()
t.begin_fill()
t.left(190)
t.circle(radius=42,extent=180)
for i in range(0,8):
    t.left(200)
    t.circle(radius=42, extent=180)
t.left(10)
print(t.heading())
t.right(180)
t.forward(50)
print(t.xcor(),t.ycor())
t.right(90)
t.circle(radius=-293.7367205840626,extent=180)
t.right(90)
t.forward(50)
t.fillcolor("light yellow")
t.end_fill()

s.mainloop()


from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Min

from home.models import Favorite, PinnedProduct

from generic.constants import (ACTIVITY_POINT,MAX_TRENDING_SPACE,
	MIN_RATE_FOR_SPACE_TRENDING)
from generic.crypto import hashing_into_int

from space.models import Product, ProductReact, Space, Status

def handle_pin(user, uid, req):
	req = req.strip()
	req = req.upper()
	if req =='ADD' or req == 'REMOVE':
		try:
			product = Product.objects.get(uid = uid)
			space = Space.objects.get(id=product.space_id)
			if space.owner_id == user.id:
				return False
			status = Status.objects.get(space_id = product.space_id)

			if req == 'ADD':
				try:
					pin = PinnedProduct.objects.get(user_id=user.id, product_id=product.uid)
					return False
				except ObjectDoesNotExist as e:
					pin = PinnedProduct(user_id=user.id, product_id=product.uid)
					pin.save()

					status.total_pinned += 1
					status.rating = _addition(status.rating, ACTIVITY_POINT['PIN'])
					status.save()

					return True
			else:
				try:
					pin = PinnedProduct.objects.get(user_id=user.id, product_id=product.uid)
					pin.delete()

					status.total_pinned -= 1
					status.rating = _addition(status.rating, -ACTIVITY_POINT['PIN'])
					status.save()

					return True

				except ObjectDoesNotExist as e:
					pass

		except ObjectDoesNotExist as e:
			pass
	return False

def handle_react(user, uid, what):
	_REACTS = ['GOOD', 'BAD', 'FAKE', 'NONE']

	what = what.strip()
	what = what.upper()

	if  what in _REACTS:
		try:
			product = Product.objects.get(uid=uid)
			space = Space.objects.get(id=product.space_id)
			if space.owner_id == user.id:
				return None

			status = Status.objects.get(space_id=product.space_id)

			react_obj = None

			try:
				react_obj = ProductReact.objects.get(product_id=product.uid, user_id=user.id)
			except ObjectDoesNotExist as e:
				react_obj = None

			if react_obj is None:
				if what != 'NONE':
					if what == 'GOOD':
						_increase_good_react(product, status)
						new_react_obj = ProductReact(user_id=user.id, product_id=product.uid, react='G')

					elif what == 'BAD':
						_increase_bad_react(product, status)
						new_react_obj = ProductReact(user_id=user.id, product_id=product.uid, react='B')

					elif what == 'FAKE':
						_increase_fake_react(product, status)
						new_react_obj = ProductReact(user_id=user.id, product_id=product.uid, react='F')

					new_react_obj.save()

			else:
				_decrease_current_react(react_obj, product, status)
				if what != 'NONE':
					if what == 'GOOD':
						_increase_good_react(product, status)
						react_obj.react = 'G'
					elif what == 'BAD':
						_increase_bad_react(product, status)
						react_obj.react = 'B'

					elif what == 'FAKE':
						_increase_fake_react(product, status)
						react_obj.react = 'F'

					react_obj.save()

				else:
					react_obj.delete()

			product.save()
			status.save()

			return product

		except ObjectDoesNotExist as e:
			pass
	return None

def handle_favorite(user, name, req):

	if not user.is_authenticated:
		return False
	try:
		space = Space.objects.get(code=hashing_into_int(name))
		if space.owner_id == user.id:
			return False

		req = req.strip()
		req = req.upper()

		if req == 'ADD' or req == 'REMOVE':
			try:
				row = Favorite.objects.get(user_id=user.id, space_id=space.id)
			except ObjectDoesNotExist as e:
				row = None

			status = Status.objects.get(space_id=space.id)

			if req == 'ADD':
				if row is None:
					row = Favorite(user_id=user.id, space_id=space.id)
					row.save()

					status.total_favorite += 1
					status.rating = _addition(status.rating, ACTIVITY_POINT['FAVORITE'])
					status.save()

					return True

			else:
				if row is not None:
					row.delete()

					status.total_favorite -= 1
					status.rating = _addition(status.rating, -ACTIVITY_POINT['FAVORITE'])
					status.save()

					return True

	except ObjectDoesNotExist as e:
		pass
	return False

def _decrease_current_react(react_obj, product, status):
	if react_obj.react == 'G':
		_decrease_good_react(product, status)

	elif react_obj.react == 'B':
		_decrease_bad_react(product, status)

	else:
		_decrease_fake_react(product, status)

def _addition(value1, value2):
	if value1 + value2 >= 0:
		return value1 + value2
	return value1

def _increase_good_react(product, status):
	product.react_good += 1
	status.total_good_react += 1
	status.rating = _addition(status.rating, ACTIVITY_POINT['GOOD'])

def _increase_bad_react(product, status):
	product.react_bad += 1
	status.total_bad_react += 1
	status.rating = _addition(status.rating, ACTIVITY_POINT['BAD'])

def _increase_fake_react(product, status):
	product.react_fake += 1
	status.total_fake_react += 1
	status.rating = _addition(status.rating, ACTIVITY_POINT['FAKE'])

def _decrease_good_react(product, status):
	product.react_good -= 1
	status.total_good_react -= 1
	status.rating = _addition(status.rating, -ACTIVITY_POINT['GOOD'])

def _decrease_bad_react(product, status):
	product.react_bad -= 1
	status.total_bad_react -= 1
	status.rating = _addition(status.rating, ACTIVITY_POINT['BAD'])

def _decrease_fake_react(product, status):
	product.react_fake -= 1
	status.total_fake_react -= 1
	status.rating = _addition(status.rating, ACTIVITY_POINT['FAKE'])


import numpy as np

from cidan.LSSC.functions.data_manipulation import load_filter_tif_stack

def test_load_filter_tif_stack():
    test, stack = load_filter_tif_stack(path="test_files/small_dataset1.tif",
                                        filter=True,
                                        median_filter=True, median_filter_size=[3, 3, 3],
                                        z_score=False, slice_stack=False, slice_start=0,
                                        slice_every=3, crop_stack=False, crop_x=[0, 400],
                                        crop_y=[0, 155])
    assert stack.shape == (99, 400, 150)
    assert stack.dtype == np.float32
    test, stack = load_filter_tif_stack(path="test_files/small_dataset1.tif",
                                        filter=True,
                                        median_filter=False, median_filter_size=[3, 3, 3],
                                        z_score=True, slice_stack=True, slice_start=0,
                                        slice_every=3, crop_stack=True, crop_x=[4, 200],
                                        crop_y=[4, 125])
    assert stack.shape == (33, 196, 121)
    assert stack.dtype == np.float32
    mean = np.mean(stack, axis=0)
    assert np.max(mean) < .01
    assert np.min(mean) > -.01


import os
import csv

csvpath = os.path.join("../../","PyBank/Resources/","budget_data.csv")

with open(csvpath) as csvfile:
    csvreader = csv.reader(csvfile, delimiter = ",")
    header = next(csvreader)
    Date = []
    Amount=[]
    for row in csvreader:
        Date.append(row[0])
        Amount.append(int(row[1]))

    Total_months = len(Date)
    Total_amounts = sum(Amount)
    Avg_Change = Total_amounts/Total_months
    Greatest_Increase_amount = max(Amount)
    Greatest_Decrease_amount = min(Amount)

    print("Financial Analysis")
    print("-------------------------------")
    print(f"Total Months: {str(Total_months)}")
    print(f"Total: ${Total_amounts}")
    print(f"Average  Change: ${str(round(Avg_Change,2))}")
with open(csvpath) as csvfile:
    csvreader = csv.reader(csvfile, delimiter = ",")
    header = next(csvreader)
    for row in csvreader:
        if int(row[1]) == Greatest_Increase_amount:

            print("Greatest Increase in Profits: " +row[0]+" ($"+row[1]+")")
        if int(row[1]) == Greatest_Decrease_amount:
            print("Greatest Decrease in Profits: " +row[0]+" ($"+row[1]+")")


'''
Ficheros en Python
'''
from Compras import mostrarMenuCompra
from RRHH import *
from Ventas import *
from Compras import *
from Pagos import *
from Gastos import *
from colorama import init, Fore
init(autoreset=True)

from Color import *

def leer_todas_las_lineas2_ComprobarExisteUsuario(archivo, usuario):
    leerArchivo = open(archivo, "r")

    for linea in leerArchivo.readlines():
        comprobarUsuario = linea.split(" , ")
        if comprobarUsuario[0].lower() == usuario.lower():
            print(color.RED+"Error !!... el usuario "+ usuario.upper()+ " ya existe !!"+color.END)
            return True

    leerArchivo.close()

def leer_todas_las_lineas2_IniciarSesion(archivo, usuario, contrasenya):
    leerArchivo = open(archivo, "r")

    for linea in leerArchivo.readlines():
        comprobarUsuario = linea.split(" , ")
        if comprobarUsuario[0].lower() == usuario.lower() and comprobarUsuario[1] == contrasenya:
            return True
    leerArchivo.close()

def elegirOpcionDepartamento(archivo, usuario, contrasenya):
    leerArchivo = open(archivo, "r")
    contador =0

    for linea in leerArchivo.readlines():
        comprobarUsuario = linea.split(" , ")

        if comprobarUsuario[0].lower() == usuario.lower() and comprobarUsuario[1] == contrasenya:

            print()

            print(color.BLUE+"Buenos días "+ usuario.upper()+ ", elige un departamento: \n"+color.END)
            for i in range (2, len(comprobarUsuario)):
                contador +=1
                print("\t"+color.BLUE+ str(contador)+color.END+" "+str(comprobarUsuario[i]))

            respuesta = input(color.BLUE+"Escribe el nombre del Departamento: "+color.END)

            print()

            while respuesta.lower() != "ventas" and  respuesta != "compras" and  respuesta != "pagos" and  respuesta != "gastos" and  respuesta != "rrhh":
                print(color.RED+"Error !!... introduce el nombre del departamento !!"+ color.END)
                respuesta = input(color.BLUE+"Escribe el nombre del Departamento: "+color.END)

            if respuesta.lower() == "ventas":
                print(color.BLUE+"Bienvenido al departamento de Ventas"+color.END)
                mostrarMenuVenta()

            if respuesta.lower() == "compras":
                print(color.BLUE+"Bienvenido al departamento de Compras"+color.END)
                mostrarMenuCompra()

            if respuesta.lower()== "pagos":
                print(color.BLUE+"Bienvenido al departamento de Pagos: "+color.END)
                pagarFacturas(usuario)

            if respuesta.lower()== "gastos":
                print(color.BLUE+"Bienvenido al departamento de Gastos: "+color.END)
                eligeGastos(usuario)

            if respuesta.lower()== "rrhh":
                print(color.BLUE+"Bienvenido al departamento de RRHH: "+color.END)
                MenuRRHH()

    leerArchivo.close()

def escribir_varias_lineas(archivo,nombre,contrasenya, departamento):

    archivo = open(archivo, "a+")

    lista = [nombre," , " ,contrasenya," , " ,departamento,"\n"]

    archivo.writelines(lista)

def tipoActividad():
    resultado = ""

    print("Elige Departamento:\n"
          "\t1 Compras\n"
          "\t2 Ventas\n"
          "\t3 Salir"
          )

    opcion = int(input("Opcion: "))
    while opcion != 3:
        if (opcion == 1):
            resultado = "Compras"
            print("Has añadido el departamento COMPRAS")
        if (opcion == 2):
            resultado = "Ventas"
            print("Has añadido el departamento VENTAS")

        opcion = int(input("Quieres añadir mas departamentos? Opcion: "))

    return resultado

# Estas funciones al final no las he utilizado, para crear un usuario le mando directamente a la funcion de 'crear un trabajador' en el departamento de RRHH
def crearUsuarioConDepartamentos(archivo,nombre,apellido,contrasenya):

    archivo = open(archivo, "a+")
    lista = [nombre," , ",contrasenya,]

    print()

    print("Estos son los departamentos que existen:\n\n"+
          color.BLUE+"\tCompras\n"
          "\tVentas\n"+color.END)

    opcion1 = False
    opcion2 = False

    while not opcion1 and not opcion2:

        compras = input(color.BLUE + "Quieres añadir al departamento COMPRAS ? (S/N): " + color.END)
        while (compras!= "s" and compras != "n"):
            print(color.RED + "Error !!, introduce 's' o 'n'" + color.END)
            compras = input(color.BLUE + "Quieres añadir al departamento COMPRAS ? (S/N): " + color.END)

        ventas = input(color.BLUE + "Quieres añadir al departamento VENTAS ? (S/N): " + color.END)
        while (ventas!= "s" and ventas != "n"):
            print(color.RED + "Error !!, introduce 's' o 'n'" + color.END)
            compras = input(color.BLUE + "Quieres añadir al departamento VENTAS ? (S/N): " + color.END)

        print()

        if (compras.lower() =="s" and ventas.lower() == "s"):
            resultado = " , Compras , Ventas\n"
            lista.append(resultado)
            print(Fore.GREEN+"Se ha creado correctamente el comercial: "+nombre.upper()+ " "+apellido.upper()+ " con acceso a los departamentos: COMPRAS y VENTAS ")
            opcion1 = True
            opcion2 = True

        if (compras.lower() =="s" and ventas.lower() == "n"):
            resultado = " , Compras\n"
            lista.append(resultado)
            print(Fore.GREEN+"Se ha creado correctamente el comercial: "+nombre.upper()+ " "+apellido.upper()+ " con acceso al departamento: COMPRAS")
            opcion1 = True
            opcion2 = False

        if (compras.lower() =="n" and ventas.lower() == "s"):
            resultado = " , Ventas\n"
            lista.append(resultado)
            print(Fore.GREEN+"Se ha creado correctamente el comercial: "+nombre.upper()+ " "+apellido.upper()+ " con acceso al departamento: VENTAS")
            opcion1 = False
            opcion2 = True

        if not opcion1 and not opcion2:
            print(color.RED + "Error !... debes elegir como mínimo una opción !!" + color.END)
            print()

    archivo.writelines(lista)


from itertools import product
import sys
input = sys.stdin.readline

# def cal_num(button, num):
#     if num not in button:
#         return [str(num)]
#     dif = 10
#     ret = []
#     for i in range(11):
#         if i not in button and abs(num - i) < dif:
#             dif = num - i
#             ret = [str(i)]
#         elif i not in button and abs(num - i) == dif:
#             ret.append(str(i))
#     return ret

# def dfs(ls, temp, cnt, n):
#     if cnt == n:
#         ans.append(temp)
#         return
#     for i in ls[cnt]:
#         temp += i
#         dfs(ls, temp, cnt+1, n)
#         temp = temp[:-1]

# ans = []
# N = input().rstrip()
# M = int(input().rstrip())
# if M == 0:
#     print(len(N))
# else:
#     button = list(map(int, input().rstrip().split()))

#     ls = []
#     for i in range(len(N)):
#         ls.append(cal_num(button, int(N[i])))
#     dfs(ls, "", 0, len(N))
#     print(ans)
#     diff = 1000000
#     diff_100 = 1000000
#     for answer in ans:
#         if abs(int(answer) - int(N)) < diff:
#             diff = abs(int(answer) - int(N))
#         if abs(int(N) - 100) < diff_100:
#             diff_100 = abs(int(N) - 100)
#     print(min(diff + len(N), diff_100))
bt_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
N = input().rstrip()
M = int(input().rstrip())
if M == 0:
    print(min(len(N), abs(int(N) - 100)))
elif M == 10:
    print(abs(int(N) - 100))
else:
    button = list(input().rstrip().split())
    bt_list = [x for x in bt_list if x not in button]
    bf = list(product(bt_list, repeat = len(N)))
    bf += list(product(bt_list, repeat = len(N)-1))
    bf += list(product(bt_list, repeat = len(N)+1))
    diff_100 = abs(int(N) - 100)
    diff = 1000000
    ans = 0
    for ks in bf:
        if len(ks) > 1 and diff > abs(int(''.join(ks)) - int(N)) + len(ks):
            diff = abs(int(''.join(ks)) - int(N)) + len(ks)
            if ks[0] == '0':
                diff -= 1
        elif len(ks) == 1 and diff > abs(int(ks[0]) - int(N)) + len(ks):
            diff = abs(int(ks[0]) - int(N)) + len(ks)
    print(min(diff, diff_100))

# 문제 접근 방법
# # 각 자리마다 가장 가까운 숫자를 선택해서 조합한 다음 계산하려 함
# # 자리수가 다를 때의 방법을 생각할 수 없었음
# # 최대 10^6이기 때문에 중복 순열로 모든 경우를 살펴봐도 시간 내에 가능하여 완탐으로 변경
# # product를 사용하여 자리수-1, 자리수, 자리수+1 모든 경우를 살펴봄
# # 한자리 수인 경우, 고장이 안난 경우, 전부 고장난 경우에 대해서는 예외 처리를 해줌


# Ashur Motlagh
# 018319910
import numpy as np
import random

def nSidedDie(p):  # same code from lab 1
    listsum = 0
    length = len(p)
    checker = float(1.0)
    flag = True
    # print(np.size(p))

    for i in range(length):  # this gives us length of the list
        listsum += p[i]
    # print(listsum)  # this is for debugging

    if listsum > checker:
        print("WRONG, the sum of the list cannot be greater than 1!!!!!")
        flag = False

    if flag:  # if the flag is true we will continue
        testcase = 1  # Only need one roll for this lab
        eList = []  # empty list to append to

        cs = np.cumsum(p)  # Cumulative Sum
        sp = np.append(0, cs)

        for i in range(0, testcase):  # 0 - 10,000
            r = random.random()
            for j in range(0, length):  # 0 - size of p
                if r > sp[j] and r <= sp[j + 1]:
                    d = j + 1
            eList.append(d)
    return d - 1

def ProbAbsorption(N, n):
    temp1 = 0
    temp2 = 0
    S = []
    initial = [0, 0, 1, 0, 0]
    mat0 = [1, 0, 0, 0, 0]
    mat1 = [0.3, 0, 0.7, 0, 0]
    mat2 = [0, 0.5, 0, 0.5, 0]
    mat3 = [0, 0, 0.6, 0, 0.4]
    mat4 = [0, 0, 0, 0, 1]

    for i in range(N):
        for j in range(n):
            r = nSidedDie(initial)
            S.append(r)
        for k in range(1, n): # using nSidedDie
            if S[k - 1] == 0:
                S[k] = nSidedDie(mat0)
            elif S[k - 1] == 1:
                S[k] = nSidedDie(mat1)
            elif S[k - 1] == 2:
                S[k] = nSidedDie(mat2)
            elif S[k - 1] == 3:
                S[k] = nSidedDie(mat3)
            else:
                S[k] = nSidedDie(mat4)

        if 4 in S:
            temp1 += 1
        elif 0 in S:
            temp2 += 1
        S = []
    print("b_20 = ", temp1 / N)
    print("b_24 = ", temp2 / N)

ProbAbsorption(10000,15)


import sys
a = int(sys.stdin.readline())
def factorization(x):
    d = 2
    arr = []
    while d <= x:
        if x % d == 0:
            arr.append(d)
            x = x / d
        else:
            d = d + 1
    return arr
for i in factorization(a):
    print(i)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
print(tf.__version__)

(X_train, y_train), (X_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()

# type(tf_data)

# print(tf_data)

# type(X_train)

# X_train.shape

# y_train.shape

# X_test.shape

# y_test.shape

f, ax = plt.subplots()
ax.imshow(X_train[1])

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10)
    ])
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
model.summary()

model.fit(X_train, y_train, epochs=5)

loss, acc = model.evaluate(X_test, y_test, verbose=2)
model.predict(X_test)

norm = layers.Normalization(input_shape=[1,], axis=None)
norm.adapt(X_train)
model = keras.Sequential([
      norm,
      layers.Dense(units=1)
])
# model.summary()
model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.1), loss='mse')
hist = model.fit(X_train, y_train, epochs=100, verbose=0)

f, ax = plt.subplots()
ax.scatter(X, y)
ax.plot(np.linspace(-0.1, 0.15, 20), model.predict(np.linspace(-0.1, 0.15, 20)))

norm = layers.Normalization(input_shape=[1,], axis=None)
norm.adapt(X_train)
model = keras.Sequential([
      norm,
      layers.Dense(units=64, activation='relu'),
      layers.Dense(units=64, activation='relu'),
      layers.Dense(units=1)
])
# model.summary()
model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.1), loss='mse')
hist = model.fit(X_train, y_train, epochs=1000, verbose=0)

f, ax = plt.subplots()
ax.scatter(X, y)
ax.plot(np.linspace(-0.1, 0.15, 20), model.predict(np.linspace(-0.1, 0.15, 20)), c='red')

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import google

pd_data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data',header=None,sep='\t', skipinitialspace=True)
data = []
for i in pd_data[0]:
    data.append(i.strip().split())
# print(data)
pd_data2 = pd.DataFrame(data).dropna()
print(pd_data2.isna().sum())
print(pd_data2)

X_train, X_test, y_train, y_test = train_test_split(pd_data2[0].astype('float64'), pd_data2[7].astype('float64'))
norm = layers.Normalization(input_shape=[1,], axis=None)
norm.adapt(X_train)
model = keras.Sequential([
    norm,
    layers.Dense(units=64, activation='relu'),
    layers.Dense(units=32, activation='relu'),
    layers.Dense(3)
])
model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.1), loss='mse')
hist = model.fit(X_train, y_train, epochs=1000, verbose=0)

f, ax = plt.subplots()
ax.plot(hist.history['loss'])

f, ax = plt.subplots()
ax.scatter(X_test, y_test)
ax.plot(X_test, model.predict(X_test))


"""
    Pick the min or max element and move it to the right or left

    Time complexity - O(n2)
    Space complexity - O(1)

"""

from decorators.decorators import log

@log
def selection_sort(nums: list[int]) -> list[int]:
    for i in range(len(nums)):
        min = i
        for j in range(i + 1, len(nums)):
            if nums[j] < nums[min]:
                min = j
        nums[i],nums[min]  = nums[min], nums[i]
    return nums

selection_sort([4, 9, 1, 5, 97, 34]) # [1, 4, 5, 9, 34, 97]


from gui.filtering_window import FilteringWindow
from PyQt5.QtWidgets import QWidget, QLabel, QVBoxLayout, QHBoxLayout, QPushButton, QApplication, QFrame
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QFont
import sys
import os

class StartWindow(QWidget):
    """
    Starting window that welcomes user and opens the filtering window
    """

    def __init__(self):
        super().__init__()

        # Create filtering window
        self.filter_window = FilteringWindow()
        self.setWindowTitle("ClassMate")
        self.setStyleSheet("background-color: azure;")  # previous color: darkcyan
        layout = QHBoxLayout()

        layout_v = QVBoxLayout()
        lbl = QLabel('Welcome to Classmate')
        lbl.setFont(QFont('Bodoni MT', 55))
        lbl.setAlignment(Qt.AlignHCenter | Qt.AlignBottom)

        button1 = QPushButton("Get Started")
        button1.setStyleSheet("background-color: dodgerblue; color: white; font-weight: bold; ")
        button1.setFont(QFont('Bodoni MT', 15))  # set font family and size
        button1.clicked.connect(self.toggle_filter_window)
        layout_v.addWidget(lbl)
        layout_v.addWidget(button1, alignment=Qt.AlignTop)

        pic = QLabel()
        image = QPixmap(os.path.join(os.pardir, 'Ucla_Pic.jpg'))
        pixmap_resized = image.scaled(512, 512, Qt.KeepAspectRatio)
        pic.setPixmap(pixmap_resized)

        layout.addLayout(layout_v)
        layout.addWidget(pic, alignment=Qt.AlignHCenter)

        self.setLayout(layout)
        self.show()
        self.showFullScreen()

    def toggle_filter_window(self) -> None:
        """
        Toggles filtering window if it is not visible
        :return: None
        """
        if self.filter_window.isVisible():
            self.filter_window.hide()
        else:
            self.filter_window.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = StartWindow()
    w.show()
    app.exec()


#encoding:utf-8_*_
#author：@robin
#create time：2018/11/20 8:32
#file：compare_models.py
#IDE:PyCharm
import numpy as np
import regression_Tree.CART_tree as cart
#regression Tree & model Tree predict
#regression Tree
def regTreeEvalue(model,indata):
    return float(model)
#model tree
def modelTreeEvalue(model,indata):
    n = np.shape(indata)[1]
    x = np.mat(np.ones((1,n+1)))#传参一般是通过元组的形式
    x[:,1:n+1] = indata
    return float(x*model)
def TreeForCast(tree,indata,modelEvalue = regTreeEvalue):
    if not cart.istree(tree): return modelEvalue(tree,indata)

    if(indata[tree['splitfeature']]>tree['val']):
        if cart.istree(tree):
            return TreeForCast(tree['ltree'],indata,modelEvalue)
        else:
            return modelEvalue(tree['ltree'],indata)
    else:
        if cart.istree(tree):
            return TreeForCast(tree['rtree'],indata,modelEvalue)
        else:
            return modelEvalue(tree['rtree'],indata)
def createForCast(tree,testdata,modelEvalue=regTreeEvalue):
    m = np.shape(testdata)[0]
    y = np.mat(np.zeros((m,1)))
    for i in range(m):
        y[i,0] = TreeForCast(tree,np.mat(testdata[i]),modelEvalue)
    return y
if __name__=='__main__':

    # #回归树
    train = np.mat(cart.loadData('bikeSpeedVsIq_test.txt'))
    test = np.mat(cart.loadData('bikeSpeedVsIq_train.txt'))
    regTree = cart.createTree(train,ops=(1,20))
    yHat = createForCast(regTree,test[:,0])
    #使用hstack()堆叠
    x = np.vstack((np.hstack(yHat),np.hstack(test[:,1])))
    # 出错代码x = np.vstack(np.hstack(yHat),np.hstack(test[:,1]))#TypeError: vstack() takes 1 positional argument but 2 were given 以元组的形式传入参数（（a,b））而不是（a,b）
    # print('堆叠后的矩阵:',x)
    corr = np.corrcoef(yHat,test[:,1],rowvar=0)#计算同一个相关系数，不同的写法（一）
    corr1 = np.corrcoef(x)#计算同一个相关系数，不同的写法（er）
    print('regTree corrcoef:\n',corr1)

    #模型树
    modelTree = cart.createTree(train,cart.modelLeaf,cart.modelError,ops=(1,20))
    yHat_model = createForCast(modelTree,test[:,0],modelTreeEvalue)
    x = np.vstack((np.hstack(yHat_model),np.hstack(test[:,1])))
    corr_model = np.corrcoef(x)#计算同一个相关系数，不同的写法（er）
    print('modelTree corrcoef:\n',corr_model)

    #标准回归
    ws,x,y = cart.linear(train)
    m_test = np.shape(test)[0]
    yHat_stard = np.mat(np.zeros((m_test,1)))
    for i in range(m_test):
        yHat_stard[i] = test[i,0]*ws[1,0]+ws[0,0]
    # print(yHat_stard)
    x = np.vstack((np.hstack(yHat_stard), np.hstack(test[:, 1])))
    corr_stand = np.corrcoef(x)  # 计算同一个相关系数，不同的写法（er）
    print('corr_stand corrcoef:\n', corr_stand)