from gym_prescan.envs.PrescanModel2 import *
from time import sleep,time

class Enviroment:
    def __init__(self,outport=None, inport=None,host='localhost'):
        self.outport = outport
        self.out = Reciver_UDP_json(outport)
        self.out.build()

        self.inport = inport
        self.inp = Transmitter_UDP(inport,fmt='ddd',host=host)
        self.done=False

    def __del__(self):
        self.close()

    def close(self):
        self.out.close()
        self.inp.close()

        for model in Model.objects:
            model.close()
        try:
            eng.quit()
        except:
            pass
        # print('Enviroment-------close')

    def reset(self):
        self.send_vec([0,0,1])

        # while True:
        #     self.get()
        #     if not bool(self.data['done']):
        #         break
        ### self.done = False
        flag = True
        while flag:
            t = time()
            while True:
                self.get()
                if not bool(self.data['done']):
                    flag = False
                    break
                if time() - t > 3:
                    print('Retrying to reset environment!')
                    break
            self.send_vec([0,0,0])
            self.send_vec([0,0,1])
        self.send_vec([0,0,0])
        self.send_vec([0,0,0])
        return

    def send_vec(self,data):
        o = data[0];v = data[1];r = data[2]
        self.inp.send(o,v,r)

    def send(self,data):
        o = data[0];v = data[1]
        self.inp.send(o,v,0)
        # self.off_set_UDP.send(o)
        # self.desired_velocity_UDP.send(v)
        # self.reset_UDP.send(r,'?')

    def get(self):
        self.data = self.out.get()
        self.agent = self.data['Vehicles'][self.data['Object']]
        self.collision = self.data['Collision']
        self.collision['Occurred'] = bool(self.collision['Occurred'])
        # if self.data['done'] :
        #     self.done = True
        self.done = bool(self.data['done'])
        return self.data

    def create_model(self, car_name=None, road_name=None):
        self.road = Road(road_name)
        self.car = Vehicle(car_name, self.road)
        self.road.create()
        self.car.create()

    def close_window(self):
        os.system('TASKKILL /F /IM VisViewerApp.exe 2> NUL')


from tkinter import Frame, Label, Grid, N, S, E, W
import tkinter as tk
import customtkinter as ctk
from datetime import datetime
from PIL import Image, ImageTk

class VistaRutas(ctk.CTkFrame):
    def __init__(self, app, controladorRutas, destinos, actividades, rutas):
        super().__init__(app)
        self.app = app
        self.controlador = controladorRutas
        self.destinos = destinos
        self.actividades = actividades
        self.rutas = rutas
        self.destino_seleccionado = {} #es un objeto

        """AQUI CAMBIO EL TAMAÑO Y EL TITULO DE LA VENTANA"""
        self.app.title("FoodTravels App - Destinos")
        self.app.geometry("885x620")
        self.configure(fg_color='#F39116')
        #self.app.resizable(1, 1)

        self.create_widgets()

    def create_widgets(self):

        self.titulo = ctk.CTkLabel(self, text="Planifica tu visita", font=("Arial", 30, 'bold'))
        self.titulo.place(x=300,y=20)

        self.titulo = ctk.CTkLabel(self, text="Busca tu destino ingresando \n el tipo de comida que te gusta o actividad que te interesa \n y agregalo a tu ruta", font=("Arial", 16, 'bold'))
        self.titulo.place(x=210, y=60)

        self.titulo = ctk.CTkLabel(self, text="Ingresa Tipo de comida o Actividad", font=("Arial", 14, 'bold'))
        self.titulo.place(x=10, y=130)

        # Agregar un cuadro de texto para el buscador
        self.buscador_entrada = ctk.CTkEntry(self, width=250)
        self.buscador_entrada.place(x=10, y=160)
        self.buscador_entrada.configure(fg_color='#E8DFDA', text_color='#23272d')

        # Asociar el evento de escritura al buscador
        self.buscador_entrada.bind("<KeyRelease>", self.filtrar_destinos)

        #listabox de destinos
        self.listbox_destinos = tk.Listbox(self, width=35, height=15, bg="#E8DFDA", font=("Arial", 10))
        self.listbox_destinos.place(x=10, y=190)

        for destino in self.destinos:
            self.listbox_destinos.insert(tk.END, destino.nombre)

        self.listbox_destinos.bind("<<ListboxSelect>>", self.controlador.mostrar_informacion_destino)

        # Etiquetas para mostrar los ingredientes y el tipo de cocina del destino seleccionado
        self.destino_label = ctk.CTkLabel(self, text="Destino", font=("Arial", 20, 'bold'), text_color="#267166")
        self.destino_label.place(x=300, y=130)

        self.tipo_cocina_titulo = ctk.CTkLabel(self, text="Tipo de cocina: ", font=("Arial", 16, 'bold'))
        self.tipo_cocina_titulo.place(x=300, y=170)

        self.tipo_cocina_label = ctk.CTkLabel(self, text="", font=("Arial", 14))
        self.tipo_cocina_label.place(x=300, y=200)

        self.actividades_titulo = ctk.CTkLabel(self, text="Actividades Programadas", font=("Arial", 16, 'bold'))
        self.actividades_titulo.place(x=300, y=230)

        self.actividades_label = ctk.CTkLabel(self, text="", font=("Arial", 14), justify="left")
        self.actividades_label.place(x=300, y=260)

        imagen = ctk.CTkImage(Image.open('assets/img/food-travel-app.jpg'), size=(250, 250))
        self.imagen_label = ctk.CTkLabel(self, image=imagen, text="")
        self.imagen_label.place(x=600, y=170)

        # Crea el botón "Agregar a mi ruta"
        # y el metodo agregar a ruta muestra una nueva ventana y le
        # paso el objeto seleccionado que viene de mostrar informacion en el controlador
        self.boton_agregar_ruta = ctk.CTkButton(
            self,
            text="Agregar destino y ver rutas",
            command=lambda: self.controlador.agregar_a_ruta(self.destino_seleccionado)
        )

        self.boton_agregar_ruta.place(x=300, y=450)
        self.boton_agregar_ruta.configure(fg_color="#FF5722")

        # Crea el botón "Ir a Inicio" y lo agrega al contenedor
        self.boton_inicio = ctk.CTkButton(
             self, text="Volver", command=self.controlador.regresar_inicio
        )
        self.boton_inicio.place(x=700,y=450)
        self.boton_inicio.configure(fg_color="#FF5722")

    def filtrar_destinos(self, event):
        """
        Filtra los destinos en el Listbox según el término de búsqueda ingresado en el cuadro de texto.
        """
        termino_busqueda = self.buscador_entrada.get().lower()
        destinos = self.controlador.destinos  # Usamos la lista de destinos del controlador

        # Filtrar destinos según el término de búsqueda
        destinos_filtrados = [destino for destino in destinos if
                              termino_busqueda in destino.tipo_cocina.lower() or
                              any(termino_busqueda in actividad.nombre.lower() for actividad in self.controlador.actividades if actividad.destino_id == destino.id)]

        # Actualizar el Listbox con los destinos filtrados
        self.listbox_destinos.delete(0, tk.END)
        for destino in destinos_filtrados:
            self.listbox_destinos.insert(tk.END, destino.nombre)

    def cargar_imagen(self, imagen_url):
        # Cargar la imagen desde la URL usando Pillow
        imgPath = f'assets/img/{imagen_url}'
        imagen = Image.open(imgPath)
        imagen = ctk.CTkImage(imagen, size=(250,250))
        self.imagen_label = ctk.CTkLabel(self, image=imagen, text="")
        self.imagen_label.place(x=600, y=170)


from module.DM  import *
from module.GM  import *
from module.Layers import *
from module.tools import *

# tensorflow: convert PSFs to OTFs
# psf: tensor with shape [height, width, channels_in, channels_out]
# img_shape: pair of integers

def deblur_model_GDC(iter_num,modelSigma1=49,modelSigma2=13, sigma = 0.01, dis_prior_weight=0.0001, D_weights=''):

    discriminator = Discriminative_module()
    discriminator.load_weights(D_weights)

    if iter_num==1:
        modelSigmaS=modelSigma2
    else:
        modelSigmaS=np.logspace(np.log10(modelSigma1),np.log10(modelSigma2),iter_num)

    DeconvolutionLayer_GDC.modelSigmaS=modelSigmaS

    # build the whole deblur model
    z=[]
    u=[]

    x_in=Input(shape=(None,None,1),name='input_x')
    k_in=Input(shape=(None,None),name='input_k')
    sigma_in=Input(shape=(1,),name='input_sigma')
    z_old = x_in
    denominator=ConstantLayer_Denominator()([x_in,k_in])
    upperleft=ConstantLayer_Upperleft()([x_in,k_in])

    net_index = get_net_index(sigma, iter_num)
    print(net_index)

    for j in range(iter_num):

        # warm start
        x=DeconvolutionLayer_GDC(j, name=('DeconvLayer_%d' % j))([(x_in if j==0 else z),(x_in if j==0 else u),denominator,upperleft,sigma_in])
        # Generative Module
        gm = Generative_model()
        print('loading weights of iter: %d' % net_index[j])
        gm.load_weights('ckpt/gms_ckpt/net%d.hdf5'%(net_index[j]))
        z_out = gm(x)
        u=z_out

        # Discriminative Module
        v=discriminator(u)
        u=GradientDescentLayer(j, dis_prior_weight, name = 'D_Graient_Descent_Layer_%d_%d' % (j, 1))([u, x, v])
        # Corrective Module
        z_out = Proximal_Layer(0.001, 0.0015)([u, denominator, upperleft])
        zs= Energy_Choose_Layer2(name='Energy_Choose_Layer_%d' % j)([z_out, z_old, x_in, k_in])
        z =zs [0]
        # Proximal Layer
        z = Proximal_Layer(0.001, 0.0015)([z, denominator, upperleft])
        # z_old = z

    return Model([x_in, k_in, sigma_in], z_out)

if __name__=="__main__":

    D_weights_path = os.path.join('ckpt','dm_ckpt',
                                    'dis_model.hdf5')
    deblur_model_total = deblur_model_GDC(30,49,13,D_weights = D_weights_path)
    # Load the CNN modules
    # deblur_model_total.load_weights('./Experiments/GCD_V1_Large_gp_loss_weight/generator_epoch_019.hdf5')
    # # # # GDC
    target = 'GDC'
    Levin_Result = []
    # BSD68_Result = []
    Noise_Level = [0.01]
    print('Testing Levin Set ...')
    for i in Noise_Level:
        A_Levin_PSNR =test_levin(deblur_model_total, i, target)
        Levin_Result.append(A_Levin_PSNR)

    for i in range(len(Noise_Level)):
           print('Levin %.2f : %.2f' % (Noise_Level[i], Levin_Result[i]))

    print('done')


import argparse
from signal import signal, SIGINT
import socket
import subprocess
from sys import exit
import time

# Setup parser
parser = argparse.ArgumentParser(description='Check and monitor the connectivity to a specified host.', prog='InetCheck')
parser.add_argument('--version', action='version', version='%(prog)s v1.2.1')
parser.add_argument('-H', '--host',
    metavar='',
    help='specify host')
parser.add_argument('-p', '--port',
    metavar='',
    type=int,
    help='specify port')
parser.add_argument('-t', '--timeout',
    metavar='',
    type=int,
    help='specify connection timeout')
parser.add_argument('-i', '--interval',
    metavar='',
    type=int,
    help='delay between connection checks')
parser.add_argument('-lf', '--log_file',
    metavar='',
    help='specify log file')
parser.add_argument('-cc', '--cmd_connected',
    metavar='',
    help='shell command which will be executed when the system can establish a connection to the host again')
parser.add_argument('-cd', '--cmd_disconnected',
    metavar='',
    help='shell command which will be executed when the system can not establish a connection to the host anymore')
parser.add_argument('-bc', '--beeps_connected',
    metavar='',
    type=int,
    help='number of beeps the system should make when it can establish a connection to the host again')
parser.add_argument('-bd', '--beeps_disconnected',
    metavar='',
    type=int,
    help='number of beeps the system should make when it can not establish a connection to the host anymore')
parser.add_argument('-q', '--quiet',
    action='store_true',
    help='use this to not display any output in the terminal')
args = parser.parse_args()

# Define variables and initialize with default values
conn_host = "example.com"
conn_port = 80
conn_timeout = 3

check_interval = 5
log_file = ""

cmd_connected = None
cmd_disconnected = None

beeps_connected = 0
beeps_disconnected = 0

# program variables
time_connected = 0
time_disconnected = 0

# my_print
#
# Prints text to the console if not --quiet and to a log-file if supplied.
#
# @param    string  s       String to print and save.
# @param    string  end     End.
# @param    bool    flush   Flush.
#
# @return   None
#
# @note     Use like builtin function print().
def my_print(s='', end='\n', flush=True):
    if not args.quiet:
        print(s, end=end, flush=flush)
    if log_file != "":
        file = open(log_file, 'a+')
        file.write(s + end)
        file.close()

# apply_program_arguments
#
# Get values passed to argparse and update program parameters.
#
# @return   None
def apply_program_arguments():
    global conn_host
    global conn_port
    global conn_timeout
    global check_interval
    global log_file
    global cmd_connected
    global cmd_disconnected
    global beeps_connected
    global beeps_disconnected

    if args.host != None:
        conn_host = args.host
        my_print("Using host " + conn_host)
    if args.port != None:
        conn_port = args.port
        my_print("Using port " + str(conn_port))
    if args.timeout != None:
        conn_timeout = args.timeout
        my_print("Using timeout " + str(conn_timeout) + "s")

    if args.interval != None:
        check_interval = args.interval
        my_print("Using interval " + str(check_interval) + "s")

    if args.log_file != None:
        log_file = args.log_file
        my_print("Using log-file " + log_file)

    if args.cmd_connected != None:
        cmd_connected = args.cmd_connected
        my_print("Command when connected: " + cmd_connected)
    if args.cmd_disconnected != None:
        cmd_disconnected = args.cmd_disconnected
        my_print("Command when disconnected: " + cmd_disconnected)

    if args.beeps_connected != None and args.beeps_connected >= 0:
        beeps_connected = args.beeps_connected
        my_print("Beeping " + str(beeps_connected) + " times when connected")
    if args.beeps_disconnected != None and args.beeps_disconnected >= 0:
        beeps_disconnected = args.beeps_disconnected
        my_print("Beeping " + str(beeps_disconnected) + " times when disconnected")

# check_connection
#
# Check if we can connect to a host.
#
# @param    string      host        Host.
# @param    int         port        Port.
# @param    int         timeout     Timeout.
#
# @return   Bool        Returns True if host can be reached. False otherwise.
def check_connection(host='example.com', port=80, timeout=3):
    try:
        socket.setdefaulttimeout(timeout)
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
        return True
    except socket.error as ex:
        return False

# passed_time
#
# Convert seconds into readable string with format '0d 12h 15m 30s'.
#
# @param    int         t_seconds   The seconds to convert.
#
# @return   string      String representation of the seconds.
def passed_time(t_seconds):
    days    = int(t_seconds / (60*60*24))
    hours   = int((t_seconds - (days * (60*60*24))) / (60*60))
    minutes = int((t_seconds - (days * (60*60*24)) - hours * (60*60)) / 60)
    seconds = int(t_seconds - (days * (60*60*24)) - hours * (60*60) - minutes * (60))
    return_string = ""
    return_string += str(days) + "d "
    return_string += str(hours) + "h "
    return_string += str(minutes) + "m "
    return_string += str(seconds) + "s"
    return return_string

# time_pretty
#
# Converts a timestamp into a string with format '2022-06-15 16:17:00'.
#
# @param    number  timestamp   The timestamp to convert.
#
# @return   string  String representation of the timestamp.
def time_pretty(timestamp):
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))

# Declare and initialize program variables
connection_status = check_connection()
connection_status_old = connection_status
time_status_change = time.time()

def main():
    global connection_status
    global connection_status_old
    global time_status_change
    global time_connected
    global time_disconnected

    global check_interval
    global log_file
    global cmd_connected
    global cmd_disconnected
    global beeps_connected
    global beeps_disconnected

    apply_program_arguments()

    # Show first connection status
    if check_connection():
        my_print("Connected     from ", end='')
    else:
        my_print("Not connected from ", end='')
    my_print(time_pretty(time_status_change), end='', flush=True)

    while True:
        # Update connection status
        connection_status_old = connection_status
        connection_status = check_connection()

        # Did connection status change?
        if connection_status and not connection_status_old:
            my_print(" to ", end='')
            my_print(time_pretty(time.time()), end='')
            my_print(" - " + passed_time(time.time() - time_status_change))
            time_disconnected += time.time() - time_status_change

            my_print("Connected     from ", end='')
            my_print(time_pretty(time_status_change), end='', flush=True)
            time_status_change = time.time()

            # Execute command and beep if requested.
            if cmd_connected != None:
                subprocess.run(cmd_connected, shell=True)
            for i in range(beeps_connected):
                print('\a', end='', flush=True)
                time.sleep(0.25)
        elif not connection_status and connection_status_old:
            my_print(" to ", end='')
            my_print(time_pretty(time.time()), end='')
            my_print(" - " + passed_time(time.time() - time_status_change))
            time_connected += time.time() - time_status_change

            my_print("Not connected from ", end='')
            my_print(time_pretty(time_status_change), end='', flush=True)
            time_status_change = time.time()

            # Execute command and beep if requested.
            if cmd_disconnected != None:
                subprocess.run(cmd_disconnected, shell=True)
            for i in range(beeps_disconnected):
                print('\a', end='', flush=True)
                time.sleep(0.25)

        time.sleep(check_interval)

# end
#
# Prints summary.
#
# @param    int         signal_received     Signal.
# @param    FrameType   frame               Frame.
#
# @return   None
def end(signal_received, frame):
    global connection_status
    global time_connected
    global time_disconnected
    global time_status_change

    if connection_status:
        time_connected += time.time() - time_status_change
    else:
        time_disconnected += time.time() - time_status_change

    my_print(" to ", end='')
    my_print(time_pretty(time.time()), end='')
    my_print(" - " + passed_time(time.time() - time_status_change))
    my_print()

    total_time = time_connected + time_disconnected

    if total_time > 0.0:
        my_print("Time connected   : " + passed_time(time_connected) + " - ", end='')
        my_print(str(round((time_connected / total_time) * 100, 2)) + "%")

        my_print("Time disconnected: " + passed_time(time_disconnected) + " - ", end='')
        my_print(str(round((time_disconnected / total_time) * 100, 2)) + "%")
    else:
        my_print("No statistics to print.")

    my_print("Goodbye!")
    exit(0)

if __name__ == "__main__":
    signal(SIGINT, end)
    main()


import cv2

if __name__ == '__main__':
    cascade_filename = "data/haarcascade_frontalface_alt.xml"
    cascade = cv2.CascadeClassifier(cascade_filename)

    src = cv2.imread("image/wonwoo2.jpg")
    gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    # cv2.imshow("Gray", gray)

    result = cascade.detectMultiScale(gray,
                                      scaleFactor=1.2,
                                      minNeighbors=1,
                                      minSize=(25, 25))
    print(result)

    for box in result:
        x, y, w, h = box
        cv2.rectangle(src, (x, y), (x+w, y+h), (0, 255, 0), thickness=2)
    cv2.imshow("img", src)

    cv2.waitKey(0)
    cv2.destroyAllWindows()


from colorama import Fore, Style
import requests
import platform
import time
import json
import math
import os

def PrintTitle(status, amount, left, artist):
    if "win" in platform.system().lower():
        os.system("cls")
    if "lin" in platform.system().lower():
        os.system("clear")
    spaces = 50
    if status == 200: stat = f"{Fore.GREEN}{status}{Fore.RESET}"
    else: stat = f"{Fore.YELLOW}{status}{Fore.RESET}"
    if 0 < amount < 10:
        amnt = f"{Fore.GREEN}{amount}{Fore.LIGHTBLACK_EX}/16{Fore.RESET}] "
    elif amount > 0:
        amnt = f"{Fore.GREEN}{amount}{Fore.LIGHTBLACK_EX}/16{Fore.RESET}]"
    else:
        amnt = f"{Fore.YELLOW}{amount}{Fore.LIGHTBLACK_EX}/16{Fore.RESET}] "
    if left > 9: lefty = f"{Fore.YELLOW}{left} secs{Fore.RESET}] "
    elif left == 1: lefty = f"{Fore.GREEN}{left} sec{Fore.RESET}]   "
    else: lefty = f"{Fore.GREEN}{left} secs{Fore.RESET}]  "
    print(
        f"{Fore.YELLOW}          ,EE,        \n" +
        f"        .m@@@@K.      \n" +
        f"       n@@@zz@@@n`    \n" +
        f"      'H@q-  'p@p'    " +
        f"{Fore.LIGHTYELLOW_EX}    _______ _______ _______ \n"+
        f"   {Fore.YELLOW}~QB^ ` ^BB^ ` ^BQ~ " +
        f"{Fore.LIGHTYELLOW_EX}   |    |  |    ___|_     _|\n"+
        f"   {Fore.YELLOW}~QB^ ` ^BB^ ` ^BQ> " +
        f"{Fore.LIGHTYELLOW_EX}   |       |    ___| |   |  \n"+
        f"   {Fore.YELLOW}   'p@q-  'p@p'    " +
        f"{Fore.LIGHTYELLOW_EX}   |__|____|___|     |___| \n"+
        f"   {Fore.YELLOW}    n@@@zz@@@n`    " +
        f"{Fore.RED}            Alerter\n"
        f"   {Fore.YELLOW}     .m@@@@K.      \n" +
        f"          ,EE,        {Fore.RESET}\n\n" +
        f" ┌{'─'*(math.ceil((spaces-len(artist))/2))}{Fore.BLUE}{Fore.LIGHTBLUE_EX}{artist}{Fore.RESET}{'─'*(math.floor((spaces-len(artist))/2))}┐ \n"+
        f" │{' '*spaces}│ \n"+
        f" │               STATUS:  [{stat}]{' '*21}│ \n"+
        f" │               AMOUNT:  [{amnt}{' '*19}│ \n"+
        f" │{' '*spaces}│ \n"+
        f" │{' '*spaces}│ \n"+
        f" │               REFRESH: [{lefty}{' '*16}│ \n"+
        f" │{' '*spaces}│ \n"+
        f" └{'─'*spaces}┘ "
    )

config = json.load(open("config.json", "r+"))
urls = {
    "products": "https://www.binance.com/bapi/nft/v1/friendly/nft/artist-product-list",
    "artist": f"https://www.binance.com/bapi/nft/v1/public/nft/home-artist-detail?artistId={config['artist']}"
}
data = {"amountFrom": "", "amountTo": "", "creatorId": config['artist'], "currency": "", "keyword": "", "orderBy": "list_time", "orderType": -1, "page": 1, "reSale": 0, "rows": 16, "tradeType": ""}
k = 0

while True:
    r = requests.get(urls['artist'], timeout=2.5)
    artist = r.json()['data']
    r = requests.post(urls['products'], json=data, timeout=2.5)
    stat = r.status_code
    if r.status_code == 200:
        k = r.json()['data']['total']
    else:
        k = 0
    if stat == 200:
        r = r.json()
        if r['data']['total'] > 0:
            data = {
                'username': 'Binance NFT Alerter',
                'embeds': [
                    {
                        'type': 'rich',
                        'title': f"NEW DROP BY: @{artist['nickName']}",
                        'description': f"There's {r['data']['total']} NFTs dropped!",
                        'author': {
                            'name': f"@{artist['nickName']}",
                            'url': f"https://www.binance.com/en/nft/shopWindow?reSale=0&tradeType=&currency=&amountFrom=&amountTo=&keyword=&orderBy=list_time&orderType=-1&isBack=1&uid={config['artist']}&order=list_time%40-1",
                            'icon_url': artist['avatarUrl']
                        }
                    }
                ]
            }
            requests.post(config['webhook'], json=data)
            for i in range(0, 300):
                PrintTitle(stat, k, 60-i, f" @{artist['nickName']} ")
                time.sleep(1)
            continue
    for i in range(0, 60):
        PrintTitle(stat, k, 60-i, f" @{artist['nickName']} ")
        time.sleep(1)
    continue


bike_colors = {
    'Red': ['Yamaha', 'Honda'],
    'Blue': ['Yamaha', 'Honda', 'Suzuki'],
    'Green': ['Kawasaki'],
    'Black': ['Yamaha', 'Honda', 'Suzuki', 'Kawasaki']
}

def group_by_brand():
    brands = {}
    for v in bike_colors.values():
        for brand in v:
            brands[brand] = []

    for color in bike_colors:
        for brand in brands:
            if brand in bike_colors[color]:
                brands[brand].append(color)
    print(brands)

group_by_brand()


# -*- coding: utf-8 -*-
from django.contrib import admin
from cart.models import Order, OrderItem

class OrderItemInline(admin.TabularInline):
    model = OrderItem
    readonly_fields = [field.name for field in OrderItem._meta.fields
                                  if field.name.lower()!='id'] + ['get_sum_price']
    can_delete = False
    extra = 0
class OrderAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'status', 'address', 'get_item_count', 'get_sum_order', 'get_dt_mod')
    readonly_fields = list(set([field.name for field in Order._meta.fields if field.name.lower()!='id']) - set(['status']))
    list_filter = ('status', )
    inlines = [OrderItemInline]
admin.site.register(Order, OrderAdmin)


import preparedata.load_data as ld
import csv

def PredictByRule():
    csvpath = "data/datedata/2014-12-16.csv"
    dict_suspect = ld.GetCartButNotBuy(csvpath)
    abnormal =ld.LoadAbnormal()
    f = open("result/rule_result.csv", "wb")
    write = csv.writer(f)
    write.writerow(["user_id", "item_id"])
    for key in dict_suspect:
        hour = int(dict_suspect[key])
        if hour < 17:
            continue
        user_id, item_id = key
        if abnormal.has_key(user_id):
            continue
        write.writerow([user_id,item_id])
    f.close()


#! /usr/bin/python python3

from lxml import html
import requests
import teams
import players

URL = 'http://www.hockey-reference.com/teams/'

page = requests.get(URL)
tree = html.fromstring(page.content)
teamCodes = {}

def getCodes():

	for element in tree.xpath('//table[@id="active_franchises"]//a'):
		href = element.attrib['href']
		code = href[7:10]
		name = element.text_content()
		teamCodes[name] = code

def getTeams():

	teamsWeb = tree.xpath('//table[@id="active_franchises"]//a/text()')
	statsWeb = tree.xpath('//table[@id="active_franchises"]//tr[@class!="partial_table"]/td/text()')

	row = 1
	for team in teamsWeb:
		name = team
		code = teamCodes[name]
		players = getPlayers(code)
		origin = statsWeb[row]
		games = statsWeb[row + 3]
		win = statsWeb[row + 4]
		loss = statsWeb[row + 5]
		tie = statsWeb[row + 6]
		overtime = statsWeb[row + 7]
		points = statsWeb[row + 8]
		pp = statsWeb[row + 9]
		plyoff = statsWeb[row + 10]
		div = statsWeb[row + 11]
		conf = statsWeb[row + 12]
		league = statsWeb[row + 13]
		stan = statsWeb[row + 14]

		addition = teams.Team(name, code, players, origin, games, win, loss, tie, overtime, points, pp, plyoff, div, conf, league, stan)

		print("***************************************        " + name + "        ***************************************************************")
		print(addition)

		row += 16

def getPlayers(code):
	teamPage = requests.get(URL + code + '/2016.html')
	teamTree = html.fromstring(teamPage.content)

	playersWeb = teamTree.xpath('//table[@id="roster"]//a/text()')
	playerStats = teamTree.xpath('//table[@id="roster"]/tbody/tr/td/text()')

	if '\xa0' in playerStats:
		playerStats.remove('\xa0')

	teamPlayers = []

	row = 0
	for player in playersWeb:
		team = code
		name = player
		position = playerStats[row + 1]
		age = playerStats[row + 2]
		height = playerStats[row + 3]
		weight = playerStats[row + 4]
		experience = playerStats[row + 6]
		summary = playerStats[row + 8]
		salary = playerStats[row + 9]

		addition = players.Player(team, name, position, age, height, weight, experience, summary, salary)
		teamPlayers.append(addition)

		row += 10

	return teamPlayers

def getProbability(team, againstTeam, weight, stat, result):
	result = 0
	probability = 0.0
	statsToTest = [wins, losses, ties, points]

	for stat in statsToTest:
		prob = team.stat - againstTeam.stat

	return probability

def simulateMatch(team, againstTeam):

	matchPage = requests.get('http://www.hockey-reference.com/leagues/NHL_2016_games.html')
	teamTree = html.fromstring(matchPage.content)

	matchTeamsWeb = teamTree.xpath('//table[@id="games"]//a/text()')
	matchGoalsWeb = teamTree.xpath('//table[@id="games"]/tbody/tr/td/text()')

	matchTeams = []
	matchGoals = []

	for string in matchTeamsWeb:
		if '-' not in string:
			matchTeams.append(string)

	for string in matchGoalsWeb:
		if 'O' not in string and '-' not in string and int(string) < 17:
			matchGoals.append(string)

	wins = 0
	losses = 0
	ties = 0
	for x in range(0, len(matchGoals)):

		if x % 2 == 0 and matchTeams[x] == team and matchTeams[x + 1] == againstTeam:
			goalsFor = matchGoals[x]
			goalsAgainst = matchGoals[x + 1]

			if goalsFor > goalsAgainst:
				wins = wins + 1
			elif goalsFor < goalsAgainst:
				losses = losses + 1
			else:
				ties = ties + 1

		if x % 2 != 0 and matchTeams[x] == team and matchTeams[x - 1] == againstTeam:
			goalsFor = matchGoals[x]
			goalsAgainst = matchGoals[x - 1]

			if goalsFor > goalsAgainst:
				wins = wins + 1
			elif goalsFor < goalsAgainst:
				losses = losses + 1
			else:
				ties = ties + 1

	print(team + ' against ' + againstTeam + ':\nWins: {}, Losses: {}, Ties: {}\n'.format(wins, losses, ties))
	return ties/2 + wins - losses


import numpy

def policy_evaluation(policy, env, gamma=1.0, epsilon=1e-5):
    """Policy evaluation algorithm.

    Compute state-value function of given policy.

    policy is the policy to by evaluated in form of transition matrix.
    env is a OpenAI gym environment transition dynamics as attribute P.
    gamma is a discount rate.
    epsilon is a threshold determining accuracy of estimation.
    """
    # initialize state-value function arbitrarily
    V = numpy.zeros(env.observation_space.n)
    # while unsufficient accuracy defined by threshold
    while True:
        delta = 0
        for s in range(env.observation_space.n):
            # apply update given by Bellman equation
            v = V[s]
            acc = 0
            for a in range(env.action_space.n):
                acc += policy[s, a] * (env.P[a, s] @ (env.R[a, s] + gamma * V))
            V[s] = acc
            # store biggest inaccuracy
            delta = max(delta, numpy.abs(v - V[s]))
        if delta < epsilon:
            return V

def policy_improvement(env, V, gamma=1.0):
    """Policy improvement algorithm.

    Return transition matrix of policy given by state-value function V.

    env is a OpenAI gym environment transition dynamics as attribute P.
    V is numpy array of state-values.
    gamma is a discount rate.
    """
    # construct empty transition matrix
    policy = numpy.zeros((env.observation_space.n, env.action_space.n))
    for s in range(env.observation_space.n):
        # for each state construct state-action value
        action_values = numpy.zeros(env.action_space.n)
        for a in range(env.action_space.n):
            action_values[a] = env.P[a, s] @ (env.R[a, s] + gamma * V)
        # choose the best action
        a = numpy.argmax(action_values)
        # set probability 1 for that action
        policy[s, a] = 1.0
    return policy

def policy_iteration(env, gamma=1.0):
    """Policy iteration algorithm.

    Return optimal policy and optimal state-value function for given MDP.

    env is a OpenAI gym environment transition dynamics as attribute P.
    gamma is a discount rate.
    """
    # start with uniform random policy
    policy = numpy.ones((env.observation_space.n, env.action_space.n))
    policy /= env.action_space.n
    while True:
        # evaluate policy
        V = policy_evaluation(policy, env, gamma)
        # greedily improve policy
        policy_prime = policy_improvement(env, V, gamma)
        # check if optimal
        if (policy == policy_prime).all():
            return policy, V
        policy = policy_prime

def value_iteration(env, gamma=1.0, epsilon=1e-5):
    """Value iteration algorithm.

    Return optimal policy and optimal state-value function for given MDP.

    env is a OpenAI gym environment transition dynamics as attribute P.
    gamma is a discount rate.
    """
    # arbitrary initialization
    V = numpy.zeros(env.observation_space.n)
    while True:
        v = numpy.copy(V)
        # improve value function
        V = numpy.max(env.R + (gamma * env.P @ V), axis=0)
        delta = numpy.max(numpy.abs(v - V))
        # check termination condition
        if delta < epsilon:
            break
    # compute policy and return
    return policy_improvement(env, V, gamma), V


import torch

import dlc_practical_prologue as prologue

from models import get_2nets, get_2nets_ws, get_2nets_ws_do

from train import grid_search
import io_bin_process
import io_num_process

GETTERS_DICT =  {
                    '2nets_ws_do': ('Binary', get_2nets_ws_do)
                }

PAIRS_NB = 1000
AUGMENTATION_FOLDS = 0
DATA_DOUBLING = False

#models = [(Net(nb_hidden),"Net " + str(nb_hidden), 2e-3) for nb_hidden in nb_hidden_layers] + [(Net2(), "Net2", 1e-2), (LeNet5(), "LeNet5", 4e-2)]

def main(args):
    if args.seed >= 0:
        torch.manual_seed(args.seed)
    try:
        model_tuple = GETTERS_DICT[args.model.lower()]
    except KeyError:
        print('ERROR : model unknown')
        return

    tr_input, tr_target, tr_figure_target, te_input, te_target,_ = prologue.generate_pair_sets(PAIRS_NB)
    tr_input, tr_target, tr_figure_target = io_bin_process.data_augmentation(tr_input, tr_target, tr_figure_target, PAIRS_NB, AUGMENTATION_FOLDS)
    if DATA_DOUBLING:
        tr_input, tr_target, tr_figure_target = io_bin_process.data_doubling(tr_input, tr_target, tr_figure_target)
    #tr_target, te_target = io_bin_process.targets_reshape(tr_target, te_target)
    m_model = model_tuple[1]()

    lrt_array = torch.logspace(-4, -3, steps = 3)
    beta_array = [0.9]#torch.linspace(0.5, 0.9, steps = 5)
    wdt_array = torch.logspace(-6,-4, steps = 3)
    num_epoch_pretrain = 0
    #lrp_array = [] #lrt_array.clone()
    #wdp_array = [] #wdt_array.clone()
    wal_array = [1.]

    print("---------- START SEARCH ---------------")
    try :
        train_results, independant_bests, hyperparameters = grid_search(m_model, 'grid_search.pth', tr_input, tr_target, tr_figure_target, torch.nn.CrossEntropyLoss, 'adam', max(1,args.k_fold),  args.batch_size, args.n_epochs,\
                                   lrt_array = lrt_array, beta_array = beta_array,  wdt_array = wdt_array)

        with open('hyperparameters_'+args.model.lower()+'.txt', 'w+') as f:
            f.write(args.model.lower() + '\n')
            f.write('\nlearning_rate = %f\nbeta = %f\nweight_decay = %f \n' % tuple(hyperparameters[:3]))

    except KeyboardInterrupt:
        del(m_model)
        return
    print("----------- END GRID SEARCH ----------------")
if __name__ == '__main__':
    # miscelaneous parameters
    #parser.add_argument('--seed', type=int, default=1, help = 'Random seed (default 1, < 0 is no seeding)')
    #parser.add_argument('--make_gif', type=bool, default=True)
    #parser.add_argument('--device', type=str, default='cpu')
    main(prologue.get_args())


#!/usr/bin/python3.5
# -*- coding: utf-8 -*-
# Project: Python100example
#    File: Example76
#  Author: liyaoyan
#   Email: helloalvin@163.com
#    Time: 2018/10/21 下午12:51

"""编写一个函数，输入n为偶数时，调用函数求1/2+1/4+...+1/n,当输入n为奇数时，调用函数1/1+1/3+...+1/n"""
from com.python100.example.files.ExampleBase import *

class Example76(ExampleBase):
    def execute(self):
        n = input('请输入n:')
        self.sum(int(n))

    def sum(self, n):
        sum = 0.0
        for i in range(1, int((n + 1) / 2)+1):
            if n % 2 == 0:
                sum += 1.0 /( 2 * i)
                #print('+'+str(1)+'/'+str(2*i),end='')
            else:
                sum = 1.0 / (2 * i - 1)
                #print('+' + str(1) + '/' + str(2 * i - 1),end='')
        print(sum)


import torch
import torch.nn.functional as F
import numpy as np

import constants

def prune_channels(output_gradient,weights):
	'''
		The procedure for error map pruning is implemented as defined as in the paper:
		Enabling On-Device CNN Training by Self-Supervised Instance Filtering and Error Map Pruning
		https://arxiv.org/pdf/2007.03213.pdf
	'''

	output_gradient_importance_score = output_gradient.norm(p=1,dim=(2,3))
	weights_importance_score = weights.norm(p=1,dim=(1,2,3))

	importance_score = constants.error_map_pruning_gamma_2*output_gradient_importance_score + constants.error_map_pruning_gamma_1*weights_importance_score

	mini_bacth_importance_score = torch.sum(importance_score,dim=0)

	# Since the number of channels are C_out*(1-pruning_ratio), the top C_out*pruning_ratio channels are selected and passed for gradient calculation
	number_of_channels_to_be_retained = int((constants.error_map_pruning_ratio)*mini_bacth_importance_score.shape[0])

	_,indices_of_channels_to_be_retained = torch.topk(mini_bacth_importance_score,k=number_of_channels_to_be_retained)

	pruned_output_gradients = output_gradient[:,indices_of_channels_to_be_retained.type(torch.long),:,:]
	pruned_weights = weights[indices_of_channels_to_be_retained.type(torch.long),:,:,:]

	return pruned_output_gradients,pruned_weights,indices_of_channels_to_be_retained

'''
	The implementation of the below function of 2d convolution is mentioned in:
	https://discuss.pytorch.org/t/implementing-a-custom-convolution-using-conv2d-input-and-conv2d-weight/18556/21
'''
class conv2d_with_error_map_pruning(torch.autograd.Function):
	@staticmethod
	def forward(ctx, input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1, use_emp=False):
		# Save arguments to context to use on backward
		# WARNING : if stride, padding, dilation etc is array, this will not work properly!!!!
		if padding == 'same':
			confs = torch.from_numpy(np.array([stride, 1, dilation, groups, use_emp]))
		elif padding == 'valid':
			confs = torch.from_numpy(np.array([stride, 0, dilation, groups, use_emp]))
		else:
			confs = torch.from_numpy(np.array([stride, padding, dilation, groups, use_emp]))
		ctx.save_for_backward(input, weight, bias, confs)

		# Compute Convolution
		return F.conv2d(input, weight, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups)

	@staticmethod
	def backward(ctx, grad_output):
		# Load saved tensors
		input, weight, bias, confs = ctx.saved_variables
		confs = confs.numpy()
		stride, padding, dilation, groups, use_emp= confs[0], confs[1], confs[2], confs[3], confs[4]

		if use_emp:

			pruned_grad_output,pruned_weights,indices_of_channels_to_be_retained = prune_channels(grad_output,weight)

			# Calculate Gradient
			grad_input = grad_weight = grad_bias = None
			grad_weight = torch.zeros(weight.shape).to(weight.device.type)
			grad_bias = torch.zeros(bias.shape).to(bias.device.type)

			pruned_grad_weight = pruned_grad_bias = None

			if ctx.needs_input_grad[0]:
				grad_input = torch.nn.grad.conv2d_input(input.shape, pruned_weights, pruned_grad_output, stride, padding, dilation, groups)

			if ctx.needs_input_grad[1]:
				pruned_grad_weight = torch.nn.grad.conv2d_weight(input, pruned_weights.shape, pruned_grad_output, stride, padding, dilation, groups)
				grad_weight[indices_of_channels_to_be_retained.type(torch.long),:,:,:] = pruned_grad_weight

			if bias is not None and ctx.needs_input_grad[2]:
				pruned_grad_bias = pruned_grad_output.sum(dim=(0,2,3))
				grad_bias[indices_of_channels_to_be_retained] = pruned_grad_bias

			if bias is not None:
				return grad_input, grad_weight, grad_bias, None, None, None, None, None
			else:
				return grad_input, grad_weight, None, None, None, None, None, None

		else:

			# Calculate Gradient
			grad_input = grad_weight = grad_bias = None
			grad_weight = torch.zeros(weight.shape).to(weight.device.type)
			grad_bias = torch.zeros(bias.shape).to(bias.device.type)

			if ctx.needs_input_grad[0]:
				grad_input = torch.nn.grad.conv2d_input(input.shape, weight, grad_output, stride, padding, dilation, groups)

			if ctx.needs_input_grad[1]:
				grad_weight = torch.nn.grad.conv2d_weight(input, weight.shape, grad_output, stride, padding, dilation, groups)

			if bias is not None and ctx.needs_input_grad[2]:
				grad_bias = grad_output.sum(dim=(0,2,3))

			if bias is not None:
				return grad_input, grad_weight, grad_bias, None, None, None, None, None
			else:
				return grad_input, grad_weight, None, None, None, None, None, None

class Conv2d_with_EMP(torch.nn.Module):

	def __init__(self,in_channels,out_channels,kernel_size,bias=True,stride=1, padding=0, dilation=1, groups=1, use_emp=False):
		super(Conv2d_with_EMP,self).__init__()

		if type(kernel_size) == tuple:
			self.weight = torch.nn.Parameter(torch.empty(out_channels,in_channels//groups,kernel_size[0],kernel_size[1]))
		elif type(kernel_size) == int:
			self.weight = torch.nn.Parameter(torch.empty(out_channels,in_channels//groups,kernel_size,kernel_size))

		if bias == True:
			self.bias = torch.nn.Parameter(torch.empty(out_channels))
		else:
			self.bias = None

		torch.nn.init.xavier_normal_(self.weight)

		if self.bias is not None:
			self.bias.data.fill_(0.01)

		self.stride = stride
		self.padding = padding
		self.dilation = dilation
		self.groups = groups
		self.use_emp = use_emp

		self.Conv2d_Function = conv2d_with_error_map_pruning.apply

	def forward(self,input_tensor):
		return self.Conv2d_Function(input_tensor,self.weight,self.bias,self.stride,self.padding,self.dilation,self.groups,self.use_emp)


from unittest.mock import patch
from unittest.mock import MagicMock
from etl import config
from etl.handlers import sql_query

@patch('etl.handlers.sql_query.context')
def _invoke_with(sql, conf, mock_context):
    """Run the handler with the specified config, in a mocked context. Return a tuple consisting of the handler's result
    and the mocked DB cursor object."""
    # Create a fake DB connection and a cursor
    mock_db = MagicMock()
    mock_db.cursor.return_value = mock_cursor = MagicMock()

    # Mock iterator result and column headers of the cursor
    mock_cursor.__iter__.return_value = [['abc', 'def', 10, True], ['ghi', 'jkl', 42, False]]
    mock_cursor.description = [['str1'], ['str2'], ['int'], ['bool']]

    # Set up our fake context
    mock_context.get_db_connection.return_value = mock_db

    # Run the handler
    result = sql_query.Handler().run(config.Config({'database': 'mockdb', 'sql': sql}, **conf))

    # Verify our DB was requested
    mock_context.get_db_connection.assert_called_once_with('mockdb')

    # Check the cursor was requested and closed after use
    mock_db.cursor.assert_called_once_with()
    mock_cursor.close.assert_called_once_with()
    return result, mock_cursor

def test_default():
    """handlers.sql_query: test query with defaults"""
    result, cur = _invoke_with('TEST_QUERY_1', {})
    # Check query was executed
    cur.execute.assert_called_once_with('TEST_QUERY_1', {})
    # Check query result
    assert result['data'] == 'abcdef10True\nghijkl42False\n'

def test_output_param():
    """handlers.sql_query: test output param mapping"""
    result, cur = _invoke_with('TEST_QUERY_2', {'output_param': 'xYz'})
    # Check query was executed
    cur.execute.assert_called_once_with('TEST_QUERY_2', {})
    # Check query result
    assert result['xYz'] == 'abcdef10True\nghijkl42False\n'

def test_delimiters():
    """handlers.sql_query: test field and record delimiters"""
    result, cur = _invoke_with('TEST_QUERY_3', {'field_delimiter': '|', 'record_delimiter': 'FOO'})
    # Check query was executed
    cur.execute.assert_called_once_with('TEST_QUERY_3', {})
    # Check query result
    assert result['data'] == 'abc|def|10|TrueFOOghi|jkl|42|FalseFOO'

def test_col_headers():
    """handlers.sql_query: test column headers"""
    result, cur = _invoke_with('TEST_QUERY_4', {'col_headers': True, 'field_delimiter': '*'})
    # Check query was executed
    cur.execute.assert_called_once_with('TEST_QUERY_4', {})
    # Check query result
    assert result['data'] == 'str1*str2*int*bool\nabc*def*10*True\nghi*jkl*42*False\n'

def test_quotechar_bracket():
    """handlers.sql_query: test quote char of '('"""
    result, cur = _invoke_with('TEST_QUERY_5', {'quotechar': '('})
    # Check query was executed
    cur.execute.assert_called_once_with('TEST_QUERY_5', {})
    # Check query result
    assert result['data'] == '(abc)(def)(10)(True)\n(ghi)(jkl)(42)(False)\n'

def test_quotechar_sq_bracket():
    """handlers.sql_query: test quote char of '['"""
    result, cur = _invoke_with('TEST_QUERY_6', {'quotechar': '['})
    # Check query was executed
    cur.execute.assert_called_once_with('TEST_QUERY_6', {})
    # Check query result
    assert result['data'] == '[abc][def][10][True]\n[ghi][jkl][42][False]\n'

def test_quotechar_brace():
    """handlers.sql_query: test quote char of '{'"""
    result, cur = _invoke_with('TEST_QUERY_7', {'quotechar': '{'})
    # Check query was executed
    cur.execute.assert_called_once_with('TEST_QUERY_7', {})
    # Check query result
    assert result['data'] == '{abc}{def}{10}{True}\n{ghi}{jkl}{42}{False}\n'

def test_params():
    """handlers.sql_query: test parameter binding and substitution"""
    result, cur = _invoke_with(
        'TEST_QUERY_8',
        {
            'params': [
                {'name': 'X', 'value': '123'},
                {'name': 'Y', 'value': '{SUBST}'}
            ],
            'SUBST': '_text_'
        }
    )
    # Check query was executed
    cur.execute.assert_called_once_with('TEST_QUERY_8', {'X': '123', 'Y': '_text_'})


one_hot = True
embedding_size = 256  # is ignored if one_hot=True
num_layers = 3
rnn_size = 512
dropout = 0.5

learning_rate = 0.003
learning_rate_decay_after = 20
learning_rate_decay = 0.97

batch_size = 64
max_epoch = 100
grad_clipping = 5
validation_fraction = 0.05
validate_every = 1000  # iterations

save_every = 10  # epochs

device_name = 'gpu' #gpu or cpu based on which device you want use


from AccessControl import ClassSecurityInfo
from Products.Archetypes.public import SelectionWidget
from Products.Archetypes.Registry import registerWidget

class MasterSelectWidget(SelectionWidget):
    security = ClassSecurityInfo()

    _properties = SelectionWidget._properties.copy()
    _properties.update({
        'macro': 'masterselection',
        'format': 'select',
        'helper_js': ('++resource++masterselect.js',),
        'slave_fields': (), # Fields controlled by this field, if control_type
                            # is vocabulary only the first entry is used
        })

registerWidget(MasterSelectWidget,
               title='Master Select',
               description="Select field which uses javascript to control subordinate widgets.",
               used_for=('Products.Archetypes.public.StringField',
                         'Products.Archetypes.Field.LinesField')
               )


from django.shortcuts import render, redirect
from datetime import datetime
from django.contrib import messages
# Create your views here.

from .models import Controle, Veiculo

from .forms import MotoristaForm, VeiculoForm, ControleForm

oleo = False
edit = False
cad = False
veiculo = False

def reset():
    global oleo
    oleo = False

    global cad
    cad = False

    global edit
    edit = False

    global veiculo
    veiculo = False

def setOleoTrue():
    global oleo
    oleo = True

def setEditTrue():
    global edit
    edit = True

def setCadTrue():
    global cad
    cad = True

def setVeiculo(veic):
    global veiculo
    veiculo = veic

def index(request):
    controles = Controle.objects.all().order_by('-data_saida')
    if request.method == 'POST':
        dates = request.POST.get('date')
        if dates != '':
            dates = datetime.strptime(dates, '%Y-%m-%d').date()
            controles = Controle.objects.all().filter(
                data_saida=dates).order_by('-data_saida')

    return render(request, 'index.html', {'controles': controles, 'oleo': oleo, 'edit': edit, 'cad': cad, 'veiculo': veiculo})

def veiculos(request):
    reset()
    formulario = VeiculoForm(request.POST or None)
    if formulario.is_valid():
        formulario.save()
        messages.success(request, 'Veiculo cadastrado com sucesso')
    return render(request, 'veiculos/form.html', {'formulario': formulario})

def motorista(request):
    reset()
    formulario = MotoristaForm(request.POST or None)
    if formulario.is_valid():
        formulario.save()
        messages.success(request, 'Motorista cadastrado com sucesso')
    return render(request, 'motorista/form.html', {'formulario': formulario})

def cadastrarControle(request):
    reset()
    formulario = ControleForm(request.POST or None)
    if formulario.is_valid() and request.POST:
        formulario.save()
        km = float(request.POST.get('km_retorno'))
        cod_veic = request.POST.get('cod_veiculos')
        veiculo = Veiculo.objects.get(id=cod_veic)

        if(km >= veiculo.km_troca_oleo):
            setOleoTrue()
        setVeiculo(veiculo)
        setCadTrue()
        return redirect('index')
    return render(request, 'criarControle.html', {'formulario': formulario})

def visualizarControle(request, id):
    reset()
    controle = Controle.objects.get(id=id)
    formulario = ControleForm(request.POST or None, instance=controle)
    return render(request, 'visualizarControle.html', {'formulario': formulario, 'view': True})

def editarControle(request, id):
    reset()
    controle = Controle.objects.get(id=id)
    veiculo = Veiculo.objects.get(id=controle.cod_veiculos.id)
    formulario = ControleForm(request.POST or None, instance=controle)
    if formulario.is_valid() and request.POST:
        formulario.save()
        if(controle.km_retorno >= veiculo.km_troca_oleo):
            setOleoTrue()
        setEditTrue()
        setVeiculo(veiculo)
        return redirect('index')
    return render(request, 'editarControle.html', {'formulario': formulario})

def excluirControle(request, id):
    reset()
    controle = Controle.objects.get(id=id)
    if request.method == 'POST':
        controle.delete()
        return redirect('index')
    return render(request, 'excluirControle.html')


import requests
import argparse
import sys

parser = argparse.ArgumentParser()

parser.add_argument('-p', '--project', default="CMC")
parser.add_argument('-v', '--version', required=True)
parser.add_argument('-k', '--apikey', required=True)

args = parser.parse_args()

ALL_PROJECTS = ""
ALL_VERSIONS = ""
PROJECT_NAME = args.project
API_TOKEN = "token " + args.apikey

AUTHENTICATE_ENDPOINT = "https://rocketsoftware.blackducksoftware.com/api/tokens/authenticate"
GET_PROJECTS_ENDPOINT = "https://rocketsoftware.blackducksoftware.com/api/projects"
GET_ALL_VERSIONS_ENDPOINT = ""

headers = {}

def generate_bearer_token():
    """
        This function is for generating the bearer token.
    """

    headers["Authorization"] = API_TOKEN
    post_req = requests.post(AUTHENTICATE_ENDPOINT, headers=headers)

    return "Bearer " + str(post_req.json()['bearerToken'])

def get_my_project_from_all_projects():

    headers["Accept"] = "application/vnd.blackducksoftware.project-detail-4+json"
    headers["Authorization"] = TOKEN

    ALL_PROJECTS = requests.get(GET_PROJECTS_ENDPOINT, headers=headers)

    for i in ALL_PROJECTS.json()["items"]:
        if i["name"] == PROJECT_NAME:
            for j in i["_meta"]['links']:
                if j['rel'] == "versions":
                    return j['href']

def get_all_version_names():

    headers["Authorization"] = TOKEN
    Request3 = requests.get(GET_ALL_VERSIONS_ENDPOINT, headers=headers)
    ALL_VERSIONS = Request3.json()['items']

    for i in ALL_VERSIONS:
        if args.version == i['versionName']:
            print(f"Given verion name: {args.version} already exist, please use different version name")
            sys.exit(-1)

TOKEN = generate_bearer_token()
GET_ALL_VERSIONS_ENDPOINT =  get_my_project_from_all_projects()
get_all_version_names()


from analysis_package import Execute

# Example usage:
if __name__ == "__main__":
    # Set the root_path and create the "analysis_results" folder
    root_path = "D:\Academics\PyCharmProjects\Data\Actives-May-2023"
    # root_path = "D:\Academics\PyCharmProjects\Data\groupindex_ex"
    analyzer = Execute(root_path)
    # results_df = analyzer.analyze_cutback()
    results_df = analyzer.gen_analysis()
    print(results_df)
    # analyzer.analyze_bragg()
    # analyzer.analyze_gIndex()


from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync,sync_to_async
import json
from .models import *

class SendThumbnails(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['socket_url']
        self.room_group_name = 'socket_url%s' % self.room_name
        print(self.room_group_name)

        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )
        self.accept()

        self.send(text_data=json.dumps({
            'payload': 'connected'
        }))

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    def receive(self, text_data):
        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'order_status',
                'payload': text_data
            }
        )

    # Receive message from room group
    def send_thumbnails(self, event):
        print(event)
        data = json.loads(event['value'])
        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'payload': data
        }))


"""
Parse population data from the ASCII input files that are provided by the
Socioeconomic Data and Applications Center (sedac) and that have been
downloaded using download-sedac-gpw-data.sh.

Loads the ascii input files, crops the data to match a specified country and
stores the data in a custom space-saving file format for later use. Provides
functions to compress and decompress, i.e., load and save data to and from the
custom file format.

The data itself describes the population count per pixel.

An example data set in the custom file format reads like so:

ncols 880
nrows 1780
llcrnrlon 102.14166666666557
llcrnrlat 8.56666666666699
cellsize 0.0083333333333333
NOTINCOUNTRY_value -2
NODATA_value -1
381x-2.0 1x125.026 498x-2.0
377x-2.0 1x114.891 1x122.275 1x130.712 1x130.297 1x135.221 1x133.586 497x-2.0
...
322x-2.0 1x20.37 1x39.449 1x40.073 1x5.32 554x-2.0

The first 7 lines are the header. They describe:
- The longitudinal extent of the data, i.e., the number of grid-cells or pixel
  in longitudinal direction.
- The latitudinal extent of the data, i.e., the number of grid-cells or pixel
  in latitudinal direction.
- The longitudinal position of the lower left corner of the image and, hence,
  also the lower left corner of of the lower left pixel.
- The latitudinal position of the lower left corner of the image and, hence,
  also the lower left corner of of the lower left pixel.
- The pixel- or cellsize in both, latitudinal and longitudinal, directions
  (measured in radiants). For the 30 arc-second resolution this value should
  correspond to 1/120.
- The value indicating if a pixel or grid-cell is outside the considered
  country (usually -2).
- The value indicating if a pixel or grid-cell has no data but is located
  inside the considered country (usually -1).

The following *nrows* lines hold the data in a compressed format. The line

381x-2.0 1x125.026 498x-2.0

Implies that the corresponding row of a decompressed array holds 381 times a
-2, 1 time a 125.026 and then again 498 times a -2. The number of multipliers
must equal the number of columns (ncols in the header). In this example we have
381+1+498=880=ncols.
"""
import os
import numpy as np
from sedac_gpw_parser.grid import Grid

POPULATION_FILE_NAME = "gpw_v4_population_count_rev11_2020_30_sec_{0}.asc"
POP_OUTPUT_FILE_NAME = "{0}_population.txt"
DATA_FOLDER = os.path.expanduser("~") + "/.sedac_gpw_parser/"

def _decompress(indices):
    """
    Convert a str representing a sequence of entries into a list.

    :param indices: One line in the custom input data that represents a
                    sequence of entries in a list. See module docstring for
                    information on the file format.
    :type indices: str

    :returns: The decompressed list
    :rtype: list of float

    Examples:
    >>> _decompress("2x3.0 1x4.2 3x2.0")
    [3.0, 3.0, 4.2, 2.0, 2.0, 2.0]

    >>> _decompress("3x0 2x5 3x4")
    [0.0, 0.0, 0.0, 5.0, 5.0, 4.0, 4.0, 4.0]
    """
    decompressed = []
    for entry in indices.split(" "):
        if "x" in entry:
            counter, value = entry.split("x")
        else:
            counter = 1
            value = entry
        decompressed.extend(int(counter) * [float(value)])
    return decompressed

def _compress(array):
    """
    Convert a list or array into a str representing the sequence of elements.

    If the list contains integer and float values the compressed array may be
    expressed in terms of integers or floats depending on the type of the first
    occurence of a number (see the last two examples below for details). Since
    this function is only meant to be used in conjuction with the _decompress()
    function this behaviour does not make any difference as _decompress()
    always returns a list of floats.

    :param array: The uncompressed list
    :type array: 1d numpy array or list of int or float

    :returns: The compressed representation of the array as explained in the
              module docstring.
    :rtype: str

    Examples:
    >>> _compress([3.0, 3.0, 4.2, 2.0, 2.0, 2.0])
    '2x3.0 1x4.2 3x2.0'

    >>> _compress([0, 0, 0, 5, 5, 4, 4, 4])
    '3x0 2x5 3x4'

    >>> _compress([0, 0.0, 0, 5, 5, 4, 4, 4])
    '3x0 2x5 3x4'

    >>> _compress([0.0, 0, 0, 5, 5, 4, 4, 4])
    '3x0.0 2x5 3x4'
    """
    indices = ""

    start = array[0]
    counter = 1
    for _ in range(1, len(array)):
        if array[_] == start:
            counter += 1
        else:
            indices += str(counter) + "x"+str(start) + " "
            start = array[_]
            counter = 1
    indices += str(counter) + "x"+str(start)

    return indices

class Population(Grid):

    def __init__(self, country_id, output_folder=DATA_FOLDER+"output/",
                 population_input_folder=DATA_FOLDER+"gpw-v4-population-count-rev11_2020_30_sec_asc/",
                 grid_input_folder=DATA_FOLDER+"gpw-v4-national-identifier-grid-rev11_30_sec_asc/",
                 overwrite=False):

        assert not overwrite, "Not implemented yet!"

        pop_output_file_name = POP_OUTPUT_FILE_NAME.format(country_id)

        self._country_id = country_id
        self._input_path = population_input_folder + POPULATION_FILE_NAME
        self._population_output_path = output_folder + pop_output_file_name

        print(country_id)
        print("Initialize parent class Grid...")
        Grid.__init__(self, country_id=country_id, output_folder=output_folder,
                      input_folder=grid_input_folder, overwrite=overwrite)

        if not os.path.exists(self._population_output_path):
            print("Parsing population...")
            self.parse_population()
            print("Saving population...")
            self.save_compressed_population()
        print("Loading population...")
        self.load_compressed_population()

        print("Total population:", self.total_population())

    def population_array(self):

        return self._population

    def total_population(self):

        return self._total_population

    def load_compressed_population(self):

        input_file = self._population_output_path

        total_population = 0

        population = []

        with open(input_file, "r") as infile:

            n_col = int(infile.readline()[:-1].split(" ")[-1])
            n_row = int(infile.readline()[:-1].split(" ")[-1])
            self._llcrnrlon = float(infile.readline()[:-1].split(" ")[-1])
            self._llcrnrlat = float(infile.readline()[:-1].split(" ")[-1])
            self._cellsize = float(infile.readline()[:-1].split(" ")[-1])

            for _ in range(2):
                infile.readline()

            population = np.zeros((n_row, n_col))

            for _ in range(n_row):
                indices = infile.readline()
                decompressed = np.array(_decompress(indices))
                population[_] = decompressed
                total_population += decompressed[decompressed > 0].sum()
                print(_, end="\r")

        self._nlat = n_row
        self._nlon = n_col
        self._population = population
        self._total_population = total_population
        print("Done..")

    def latitude_range(self):

        lats = self._llcrnrlat + np.arange(self._nlat) * self._cellsize

        return lats

    def longitude_range(self):

        lons = self._llcrnrlon + np.arange(self._nlon) * self._cellsize

        return lons

    def save_compressed_population(self):

        output_filepath = self._population_output_path
        population = self._population

        max_value = len(population)

        n_row, n_col = population.shape
        outstring = ""
        outstring += "ncols {0}\n".format(n_col)
        outstring += "nrows {0}\n".format(n_row)
        outstring += "llcrnrlon {0}\n".format(self._llcrnrlon)
        outstring += "llcrnrlat {0}\n".format(self._llcrnrlat)
        outstring += "cellsize {0}\n".format(self._cellsize)
        outstring += "NOTINCOUNTRY_value -2\nNODATA_value -1\n"

        print(outstring)
        for _, entry in enumerate(population):
            print(_, max_value, end="\r")
            outstring += _compress(entry)+"\n"

        with open(output_filepath, "w") as outfile:
            outfile.write(outstring)

    def mask_invalid_data(self, below=0):

        for i, _pop in enumerate(self._population):
            nan_pop = self._population[i] < below
            self._population[i][nan_pop] = np.nan

    def parse_population(self, accuracy=3):

        print("Parsing population...")
        coords = self._country_coords
        input_path = self._input_path

        population = np.zeros((10800*2, 10800*4))

        valid_x = set()
        valid_y = set()

        for file_id, file_coords in coords.items():

            x_offset = 10800 * ((file_id-1) % 4)
            y_offset = 10800 * (file_id > 4)

            with open(input_path.format(file_id)) as infile:

                for _ in range(4):
                    infile.readline()

                cellsize = infile.readline()
                cellsize = float(cellsize[:-1].split(" ")[-1])

                infile.readline()

                all_y = list(file_coords.keys())
                min_index = np.min(all_y)
                max_index = np.max(all_y)

                for _ in range(min_index):
                    infile.readline()

                for i in range(max_index - min_index + 1):
                    print(file_id, i, len(population), end="\r")
                    row_id = min_index + i
                    if row_id not in all_y:
                        continue

                    col_id = file_coords[row_id]

                    line = infile.readline()
                    line = line.split(" ")
                    assert line[0] != ""
                    assert line[-1] == "\n"
                    assert len(line) == 10801

                    coords_x = [_x + x_offset for _x in col_id]
                    coords_y = [row_id + y_offset] * len(col_id)

                    valid_x.update(coords_x)
                    valid_y.update((row_id + y_offset,))

                    pop = [float(line[_x]) + 2 for _x in col_id]
                    population[(coords_y, coords_x)] = pop

                print()

        min_x = np.min(list(valid_x))
        max_x = np.max(list(valid_x))
        min_y = np.min(list(valid_y))
        max_y = np.max(list(valid_y))

        population = population[min_y:(max_y+1), min_x:(max_x+1)]
        population -= 2
        population[population < -1000] = -1

        max_value = len(population)

        # Do this on for-loop to be light on memory
        for i in range(max_value):
            print("Rounding:", i, max_value, end="\r")
            population[i] = np.round(population[i], accuracy)

        print(min_x, max_x, min_y, max_y)
        self._population = population
        self._llcrnrlon = (min_x * cellsize) % 360 - 180
        self._llcrnrlat = (180 - max_y * cellsize) % 180 - 90
        self._cellsize = cellsize

    def as_list(self, return_invalid=False):

        n_lat, n_lon = self._population.shape
        lats = np.repeat(np.flip(self.latitude_range()), n_lon)
        lons = np.tile(self.longitude_range(), n_lat)
        table = np.stack((lons, lats, self._population.flatten())).T

        if not return_invalid:
            table = table[table[:, 2] > -2]

        return table

def main():
    pop = Population(country_id=68)
    pop.mask_invalid_data(below=0)
    print(pop.population_array()[0][pop._invalid_values[0]])

if __name__ == "__main__":
    main()


from random import choice
import json

def get_person():
    name = ''
    tel = ''

    letter = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
    nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']

    while len(name) != 7:
        name += choice(letter)

    while len(tel) != 10:
        tel += choice(nums)

    person = {
        'name': name,
        'tel': tel
    }
    return person, tel

def write_json(person_dict, num):

    try:
        data = json.load(open('persons.json'))
    except FileNotFoundError:
        data = {}

    data[num] = person_dict
    print(data)

    with open('person.json', 'w') as file:
        json.dump(data, file, indent=2)
    # with open('persons.json', 'w') as f:
    #     json.dump(data, f, indent=2)

for i in range(5):
    write_json(get_person()[0], get_person()[1])


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug  3 15:14:30 2017

@author: elliott
"""

# set this to your working directory
WORKING_DIR = '/home/elliott/Dropbox/_Ash_Teaching/2018-09 - Bocconi - Text Data and ML/code'
import os
os.chdir(WORKING_DIR)

import pandas as pd
df1 = pd.read_csv('death-penalty-cases.csv')
Xraw = pd.read_pickle('X.pkl')
vocab = pd.read_pickle('vocab.pkl')

###
# OLS Regression
###

# list of words from our vectorizer
vocab = [w.replace(' ', '_') for w in vocab]

# convert frequency counts to dataframe
df4 = pd.DataFrame(Xraw.todense(),
                   columns=vocab)

# import statsmodels package for R-like regression formulas
import statsmodels.formula.api as smf

# add metadata
df4['Y'] = df1['citeCount'] # cites to this opinion
df4['courtfe'] = df1['court_id']   # court fixed effect
df4['yearfe'] = df1['year']        # year fixed effect

# empty lists for t-statistics and coefficients
tstats, betas = [], []
for xvar in vocab: # loop through the words in vocab
    if any([c.isdigit() for c in xvar]) or 'hellip' in xvar:
        tstats.append(0)
        betas.append(0)
        continue
    model = smf.ols('Y ~ %s' % xvar,data=df4)
    result = model.fit()
    tstats.append(result.tvalues[1])
    betas.append(result.params[1])

# save estimates
pd.to_pickle(tstats,'tstats.pkl')
pd.to_pickle(betas,'betas.pkl')

# zip up words and t-statistics
stats = list(zip(vocab,tstats))
stats.sort(key = lambda x: x[1], reverse=True) # sort by second item (tstats)
stats[:10] + stats[-10:]

# Overfitting
from sklearn.model_selection import cross_val_score
import numpy as np
from sklearn.linear_model import LinearRegression

m = 100
X = 6 * np.random.rand(m,1) - 3
y = 0.5 * X ** 2 + X + 2 + np.random.randn(m,1)
y = y.ravel()

from sklearn.preprocessing import PolynomialFeatures
poly_2 = PolynomialFeatures(degree=2) # also adds interactions
X_poly_2 = poly_2.fit_transform(X)

poly_300 = PolynomialFeatures(degree=300)
X_poly_300 = poly_300.fit_transform(X)

lin_reg = LinearRegression()
cross_val_score(lin_reg, X, y, cv=3, n_jobs=3).mean()
cross_val_score(lin_reg, X_poly_2, y, cv=3, n_jobs=3).mean()
cross_val_score(lin_reg, X_poly_300, y, cv=3, n_jobs=3).mean()

###
# Regularized Regression
###

# Lasso
from sklearn.linear_model import Lasso
lasso_reg = Lasso(alpha=0.1)
lasso_reg.fit(X,y)

# Ridge
from sklearn.linear_model import Ridge, SGDRegressor
ridge_reg = Ridge(alpha=1)
ridge_reg.fit(X,y)

sgd_ridge_reg = SGDRegressor(penalty="l2",max_iter=1000)
sgd_ridge_reg.fit(X,y.ravel())

###
# Elastic Net
###
from sklearn.linear_model import ElasticNetCV
enet_reg = ElasticNetCV(alphas=[.01,.1,1], l1_ratio=[.01,.1,.5,.9, .99, 1])
enet_reg.fit(X,y)
enet_reg.alpha_, enet_reg.l1_ratio_

cross_val_score(enet_reg,X,y).mean()

# Scaling with Sparsity
from sklearn.preprocessing import StandardScaler
sparse_scaler = StandardScaler(with_mean=False)
X_sparse = sparse_scaler.fit_transform(Xraw)

# Multinomial Logistic
from sklearn.linear_model import LogisticRegression
logistic = LogisticRegression(C=1, # default L2 penalty
                              class_weight='balanced')

scores = cross_val_score(logistic,
                         X_sparse,
                         df4['state'],
                         cv=3,
                         n_jobs=3)

scores.mean(), scores.std()


# add equivalent pack window

from Tkinter import *
colors = ['red', 'green', 'yellow', 'orange', 'blue', 'navy']

def gridbox(parent):
    r = 0
    for c in colors:
        l = Label(parent, text=c, relief=RIDGE,  width=25)
        e = Entry(parent, bg=c,   relief=SUNKEN, width=50)
        l.grid(row=r, column=0)
        e.grid(row=r, column=1)
        r = r+1

def packbox(parent):
    for c in colors:
        f = Frame(parent)
        l = Label(f, text=c, relief=RIDGE,  width=25)
        e = Entry(f, bg=c,   relief=SUNKEN, width=50)
        f.pack(side=TOP)
        l.pack(side=LEFT)
        e.pack(side=RIGHT)

if __name__ == '__main__':
    root = Tk( )
    gridbox(Toplevel( ))
    packbox(Toplevel( ))
    Button(root, text='Quit', command=root.quit).pack( )
    mainloop( )

Libros de Python/Tutorial Tkinter/51-GRID/grid2.py


def merge(left,right,compareWith):
    if compareWith == 'x' or compareWith == 'X' \
          or compareWith == 'Y' or compareWith == 'y':
        compared_ref = True
    else:
        compared_ref = False
    result = []
    i=0
    j = 0
    while i<len(left) and j<len(right):
        if compared_ref == False:
            if left[i]<right[j]:
                result.append(left[i])
                i += 1
            else:
                result.append(right[j])
                j+=1
        else:
            if compareWith == 'X' or compareWith == 'x':
                if left[i][0]<right[j][0]:
                    result.append(left[i])
                    i += 1
                else:
                    result.append(right[j])
                    j+=1
            else:
                if left[i][1]<right[j][1]:
                    result.append(left[i])
                    i += 1
                else:
                    result.append(right[j])
                    j+=1

    while i<len(left):
        result.append(left[i])
        i+=1
    while j<len(right):
        result.append(right[j])
        j+=1
    return result
def mergeSort(List,compareWith = None):
    if len(List)<2:
        return List[:]
    else:
        mid = len(List)//2
        left = mergeSort(List[:mid],compareWith)
        right = mergeSort(List[mid:],compareWith)
        return merge(left,right,compareWith)
if __name__=='__main__':
    List = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
    print("Final sort = " +str(mergeSort(List,'x')))


# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
from dash.dependencies import Input, Output
import dash_html_components as html

import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots

import pandas as pd

df = pd.read_csv('Imiona_nadane_wPolsce_w_latach_2000-2019.csv')

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server

app.layout = html.Div(children=[
                      html.H1('Popularność imion w XXI wieku', style={'textAlign': 'center',}),
                      html.Div(["Imię: ", dcc.Input(id='name-input', value='KAZIMIERZ', type='text')],
                               style={'textAlign': 'center',}),
                      html.Hr(),
                      dcc.Graph(id='graph',),
                      html.Hr(),
                      html.Span(["**Dane pochodzą z ",
                                html.A('dane.gov.pl/dataset/219,imiona-nadawane-dzieciom-w-polsce',
                                        href="https://dane.gov.pl/dataset/219,imiona-nadawane-dzieciom-w-polsce",
                                        target="blank")]),
                      ])

@app.callback(
    [Output(component_id='graph', component_property='figure'),],
    [Input(component_id='name-input', component_property='value')]
)

def update(name):
    '''Get name from name-input, load data from df, update graph.'''
    name = name.upper()
    df_temp = df[df['Imię'] == name].drop(columns=['Płeć'])
    fig = go.Figure(data=go.Bar(y=df_temp['Liczba'].values, x=df_temp['Rok'].values),)
    fig.update_layout(title=f'Tyle razy imię {name} zostało nadane jako pierwsze w Polsce w latach 2000-2019',
                      hovermode='x',
                      xaxis_title = 'Lata - up',
                      font=dict(
                        family="Courier New, monospace",
                        size=18,
                        color="RebeccaPurple"),)
    return (fig,)

if __name__ == '__main__':
    app.run_server(debug=False)


from turtle import Screen
from score_board import Score
from food import Food
import time
from snake import Snake

move_on = True
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor('black')
screen.title("Welcome to The Snake Game")
screen.tracer(0)

snake = Snake()
food = Food()
scoreboard = Score()

screen.listen()
screen.onkey(snake.up, 'Up')
screen.onkey(snake.down, 'Down')
screen.onkey(snake.left, 'Left')
screen.onkey(snake.right, 'Right')

while move_on:
    screen.update()
    time.sleep(0.1)
    snake.move()

    # Detect collision with food

    if snake.head.distance(food) < 15:
        food.refresh()
        snake.extend()
        scoreboard.clear()
        scoreboard.increase()

    # Detect collision with wall

    if snake.head.ycor() <= -300 or snake.head.ycor() >= 320:
        scoreboard.lose()
        break

    if snake.head.xcor() <= -300 or snake.head.xcor() >= 300:
        scoreboard.lose()
        break

    # Detect collision with own tail

    for segment in snake.segments[1:]:
        if snake.head.distance(segment) < 10:
            move_on = False
            scoreboard.lose()

with open('data.txt', 'r') as file:
    greatest_score = file.readline()
    if int(scoreboard.score) > int(greatest_score):
        with open('data.txt', 'w') as new_score:
            new_score.write(f'{scoreboard.score}')

screen.exitonclick()


import os
import env_config
from src.model.docker_cmd import DockerCmd

if __name__ == "__main__":
    # ------------------------ env_params ------------------------
    CONTAINER_NAME = env_config.CONTAINER_PYTHON_3_8_18_NAME
    ROOT_PATH_DOCKER = env_config.CONTAINER_PYTHON_3_8_18_PROJECT_PATH    # DOCKER 執行路徑
    ROOT_PATH_LOCAL = env_config.MLOPS_ROOT_PATH_LOCAL_PROJECT_PATH      # LOCAL 執行路徑

    # 重啟docker container
    DockerCmd.dockerRestart(CONTAINER_NAME)

    # 移除container中的舊程式
    DockerCmd.dockerExec(
        name=CONTAINER_NAME,
        cmd=f"rm -rf {ROOT_PATH_DOCKER}",
        detach=False,
        interactive=True,
        TTY=False,
    )

    # 把gitHub上的程式碼clone到docker container中
    GITHUB_URL = env_config.GITHUB_URL
    DockerCmd.dockerExec(
        name=CONTAINER_NAME,
        cmd=f"git clone {GITHUB_URL} {ROOT_PATH_DOCKER}",
        detach=False,
        interactive=True,
        TTY=False,
    )

    # CONTAINERNAME - CI
    for root, dirs, files in os.walk(ROOT_PATH_LOCAL):
        rootCheck = False
        for r_ in ["__pycache__", ".git", ".idea", "venv", "OLD"]:
            if root.find(r_) != -1:
                rootCheck = True
        if rootCheck:
            continue

        DockerCmd.dockerExec(
            name=CONTAINER_NAME,
            cmd=f"mkdir -p {root.replace(ROOT_PATH_LOCAL, ROOT_PATH_DOCKER)}",
            detach=False,
            interactive=True,
            TTY=False,
        )

        for file in files:
            # 把現在執行的程式更新到container中
            file_name = os.path.join(root, file).replace('(', '\\(').replace(')', '\\)')
            DockerCmd.dockerCopy(
                name=CONTAINER_NAME,
                filePath=file_name,
                targetPath=file_name.replace(ROOT_PATH_LOCAL, ROOT_PATH_DOCKER),
            )


from Date import Date

class Calendar(object):

    __date = Date();

    def set_date(self, date):
        self.__date = date;
        self.__day = date.get_day();
        self.__month = date.get_month();
        self.__year = date.get_year();

    __day = 0;
    __month = 0;
    __year = 0;

    __names = {0:"Воскресенье", 1:"Понедельник", 2:"Вторник", 3:"Среда", 4:"Четверг", 5:"Пятница", 6:"Суббота"};

    def convert_to_names(self, iso):
        print(self.__names.get(iso));

    def day_of_week(self):
        countOfMonthsInYear = 12;
        a = int((14 - self.__month) / countOfMonthsInYear);
        y = int(self.__year - a);
        m = int(self.__month + 12 * a - 2);
        iso = int((7000 + (self.__day + y + y / 4
                          - y / 100 + y / 400 + (31 * m) / 12)) % 7);
        self.convert_to_names(iso);


def CopyFile(source_filename, target_filename, override=True, md5_check=False, copy_symlink=True):
    '''
    Copy a file from source to target.

    :param  source_filename:
        @see _DoCopyFile

    :param  target_filename:
        @see _DoCopyFile

    :param bool md5_check:
        If True, checks md5 files (of both source and target files), if they match, skip this copy
        and return MD5_SKIP

        Md5 files are assumed to be {source, target} + '.md5'

        If any file is missing (source, target or md5), the copy will always be made.

    :param  copy_symlink:
        @see _DoCopyFile

    :raises FileAlreadyExistsError:
        If target_filename already exists, and override is False

    :raises NotImplementedProtocol:
        If file protocol is not accepted

        Protocols allowed are:
            source_filename: local, ftp, http
            target_filename: local, ftp

    :rtype: None | MD5_SKIP
    :returns:
        MD5_SKIP if the file was not copied because there was a matching .md5 file

    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information
    '''
    from ._exceptions import FileNotFoundError

    # Check override
    if not override and Exists(target_filename):
        from ._exceptions import FileAlreadyExistsError
        raise FileAlreadyExistsError(target_filename)

    # Don't do md5 check for md5 files themselves.
    md5_check = md5_check and not target_filename.endswith('.md5')

    # If we enabled md5 checks, ignore copy of files that haven't changed their md5 contents.
    if md5_check:
        source_md5_filename = source_filename + '.md5'
        target_md5_filename = target_filename + '.md5'
        try:
            source_md5_contents = GetFileContents(source_md5_filename)
        except FileNotFoundError:
            source_md5_contents = None

        try:
            target_md5_contents = GetFileContents(target_md5_filename)
        except FileNotFoundError:
            target_md5_contents = None

        if source_md5_contents is not None and \
           source_md5_contents == target_md5_contents and \
           Exists(target_filename):
            return MD5_SKIP

    # Copy source file
    _DoCopyFile(source_filename, target_filename, copy_symlink=copy_symlink)

    # If we have a source_md5, but no target_md5, create the target_md5 file
    if md5_check and source_md5_contents is not None and source_md5_contents != target_md5_contents:
        CreateFile(target_md5_filename, source_md5_contents)


import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
screen.listen()

player = Player()
cars = CarManager()
score = Scoreboard()

screen.onkey(player.move, "Up")
screen.onkey(player.move, "w")

game_is_on = True
cnt = 0

while game_is_on:
    time.sleep(0.1)
    if cnt == 5:
        cars.add_car()
        cnt = 0
    cnt += 1
    cars.cars_move()

    if cars.detect_collision(player):
        score.game_over()
        game_is_on = False

    if player.ycor() == 280:
        player.next_level()
        cars.next_level()
        score.next_level()

    screen.update()

screen.exitonclick()


import eel #third party (open source)
import wx #third party (open source)
import ctypes
import re
from decimal import Decimal
from fileController import getPath #custom for project
from proteinTranscriber import matchBases #custom for project
from loopingTools import generateInitiator, findAll, getExonCombinations #custom for project

terminator = "CGCGCGCGAAACGCGCGCGTTTTTTT"
promoters = generateInitiator() #generates all of the possible initiators
substrings = []
totalExons = []
proteins = []

try: #prevents the file dialog from looking blurry
    ctypes.windll.shcore.SetProcessDpiAwareness(True)
except Exception: #testing for any exception is usually too broad but this feature is uneccessary so there is no risk benifit
    print("High resolution failed")
#sends data to the front-end
def send(data, target):
    eel.update(str(data), target)

@eel.expose
def findPromoters(data):
    DNA = data
    #creates a list of all promoter positions using list comprehension
    promoterPos = [list(findAll(DNA, promoter)) for promoter in promoters if list(findAll(DNA, promoter)) != []]
    terminatorPos = list(findAll(DNA, terminator))
    #strings are immutable so conversion to a list is neccessary to use indices
    temp = list(DNA)
    for i in promoterPos:
        count = 0
        for start in i:
            length, startCount = 7, 2
            if DNA[start:start+6] == "TATAAA": #the special case
                length, startCount = 6, 25
                #for every other promoter
            if len(terminatorPos) == 0:
                send("Please input at least one terminator", "output")
                break
            if start + length < terminatorPos[count]: #if the string is withing the current terminator
                substrings.append(DNA[start+startCount: terminatorPos[count]+26])
            elif start + length > terminatorPos[count]:
                count += 1
                try: #attempts to go to the next terminator
                    substrings.append(DNA[start+startCount: terminatorPos[count]+26])
                except IndexError:
                    continue

            temp[start] = f'>{temp[start]}' #replaces at that specific index
            temp[terminatorPos[count]] = f'<{temp[terminatorPos[count]]}'
    #sends to the output
    send(f"Promoters followed by a '>' \nTerminators followed by a '<'\n {''.join(temp)}", 'output')
    send("Promoters and terminators successfully found \nDNA converted to RNA", "status")

@eel.expose
def findExons():
    #converts every substring into RNA and splits by exons
    splicedStrings = [re.split('GUAAGU|GUGAGU',string.replace("T", "U")) for string in substrings]

    for spliced in splicedStrings:
        innerExons = []
        for individualString in spliced:
            endPos = individualString.find("CAG")
            if(endPos > -1): #if the endPos doesn't exist
                endRemoved = individualString[endPos+3: len(individualString)]
                innerExons.append(endRemoved)
            else: #appends everything between the exons
                innerExons.append(individualString)
        totalExons.append(innerExons)
    #gets all combinations of exons and sends it to the ouput
    send(f"All Total Exons - \n {totalExons}\n All total combinations - \n {getExonCombinations(totalExons)}\n", "output")
    send("Exon Combinations Found", "status")

@eel.expose
def transcribeProteins():
    codonLists = []
    #loops throught the combinations of exons
    for combo in getExonCombinations(totalExons):
        codons = ([combo[i:i+3] for i in range(0, len(combo), 3)])#splits on every codon
        #finds the positions of start and stop codons
        startPos = [count for count, codon in enumerate(codons) if codon == "AUG"]
        endPos = [count for count, codon in enumerate(codons) if codon == "UGA" or codon == "UAA" or codon =="UAG"]
        count = 0 #used for codon sequences withing codon sequences
        for start in startPos:
            if start < endPos[count]:
                codonLists.append(codons[start:endPos[count]])
            else:
                count+=1
                try:      #attempts to find the next ending
                    codonLists.append(codons[start:endPos[count]])
                except IndexError:
                    continue

    finalCodons = []
    [finalCodons.append(i) for i in codonLists if i not in finalCodons] #removes duplicates
    send(f'\nList of all codon combinations (duplicates removed) {finalCodons}\n', "output")
    send("Codon combinations found", "status")

    #Begins protein transcription
    for independentCodon in finalCodons:
        currentProtein = ""
        mass = Decimal(str("0")) #decimal module avoids floating point error
        charge = 0
        for codon in independentCodon:
            #adds all the values of the corresponding protein
            returnedProtein = matchBases(codon)
            currentProtein += returnedProtein[0]
            mass += Decimal(str(returnedProtein[1]))
            charge += returnedProtein[2]
        proteins.append([currentProtein, f'{mass}u', f'{charge}e'])
    #and outputs the result to console
    send("FINAL LIST OF PROTEINS\n", "output")
    for protein in proteins:
        send(f'{protein}\n', "output")
    send("Proteins found", "status")
    send("WARNING IF THE CHARGE OF THE LONGEST PROTEIN IS OFF BY 1, THE TEST CASE MAY HAVE BEEN INCORRECTLY DONE BY HAND (see 'TEST CASE ERROR' in documentation for the explanation)", "output")
    #If the charge for the longest protein is the wrong, you may have a flawed test case

@eel.expose
def reset(): #resets variables to default values
    global substrings, totalExons, proteins
    substrings = []
    totalExons = []
    proteins = []
    send("Program Reset", "status")

@eel.expose
def getFile(): #opens file dialog from file controller
    path = getPath('*')
    if path != None:
        return open(path, "r").read()
    else:
        return 'No File Selected'

def startEel(): #starts the front-end server
    eel.init('web')
    eel.start('index.html')

if __name__ == "__main__":
    startEel()


def mode(nums):
    """Return most-common number in list.

    For this function, there will always be a single-most-common value;
    you do not need to worry about handling cases where more than one item
    occurs the same number of times.

        >>> mode([1, 2, 1])
        1

        >>> mode([2, 2, 3, 3, 2])
        2
    """
    loop_dict = {}
    greatest = (0, 0)
    for num in nums:
        loop_dict[num] = 0
    for num in nums:
        loop_dict[num] += 1

    #print(loop_dict.items())
    for k, v in loop_dict.items():
        #print(v, greatest[1])
        if v > greatest[1]:
            greatest = (k, v)
    return greatest[0]


from INF1771_GameClient import HandleClient
from GameAI import AIController
import threading
import time

class GameBot(threading.Thread):
    def __init__(self, name=None, color=None):
        ''' Create bot. name = string, color = tuple (R[0-255], G[0-255], B[0-255]) '''
        super().__init__()
        self.alive = threading.Event()
        self.alive.set()
        self.interval = 0.1
        self.ai = AIController()
        self.game = HandleClient(self.__disconnectCB)
        self.game.setAIController(self.ai)

        self.actions = {"virar_direita"  : self.game.sendTurnRight,
                        "virar_esquerda" : self.game.sendTurnLeft,
                        "andar"          : self.game.sendForward,
                        "atacar"         : self.game.sendShoot,
                        "pegar_ouro"     : self.game.sendGetItem,
                        "pegar_anel"     : self.game.sendGetItem,
                        "pegar_powerup"  : self.game.sendGetItem,
                        "andar_re"       : self.game.sendBackward
                       }

        #self.game.connect("127.0.0.1")
        #self.game.connect("atari.icad.puc-rio.br")
        self.game.connect("139.82.2.67")
        if name:
            self.game.sendName(name)

        if color:
            self.game.sendColor(color)

        self.start()

    def __disconnectCB(self):
        self.alive.clear()

    def run(self):
        while self.alive.is_set():
            self.game.sendRequestGameStatus()
            self.game.recv(0.5) # Wait response

            # Read all pending messages
            while self.game.recv(0):
                pass

            if self.game.gameState == "Game" and self.game.state == "game":
                self.doDecision()
            else:
                time.sleep(3*self.interval)

            time.sleep(self.interval)

    def doDecision(self):
        ''' Ask AI for the next action '''
        self.game.sendRequestUserStatus()

        a = self.ai.getDecision()
        print("Decision: "+a) # Debug / requisito

        f = self.actions.get(a)
        if f:
            f()
        else:
            print("Acao invalida")

        self.game.sendRequestObservation()

    def close(self):
        self.alive.clear()
        if self.is_alive():
            self.join()
        self.game.sendGoodbye()


import pandas as pd
import plotly.graph_objs as go
from plotly.offline import iplot

def draw_picture(pd_data: pd.DataFrame):
    count_data = pd_data['类型'].value_counts()
    # 准备数据
    pie1 = count_data.values
    labels = count_data.index
    # figure
    fig = {
        "data": [
            {
                "values": pie1,  # 值
                "labels": labels,  # 标签
                "domain": {"x": [0, 1]},
                "name": "Top20中不同类大学所占比例",
                "hoverinfo": "label+percent",
                "hole": .3,
                "type": "pie"
            }, ],
        "layout": {
            "title": "Top20中不同类大学所占比例",
            "annotations": [
                {"font": {"size": 20},
                 "showarrow": False,
                 "text": "",
                 "x": 0.3,
                 "y": 1
                 },
            ]
        }
    }
    iplot(fig)

def main():
    # 文件路径，注意根据自己所存路径修改
    path = "China_school_top20.xlsx"
    # 利用pandas读取数据
    data = pd.read_excel(path)
    print(data)
    # 绘图
    draw_picture(data)

if __name__ == "__main__":
    main()


from django.contrib import admin
from django.urls import path, include
from . import views

urlpatterns = [
    # path('', views.index, name="hotelBookindex"),
    # path('detail/<hotelbook_id>', views.showdetail, name="hotelbookdetail"),
    path('create/', views.create, name="hotelbookcreate"),
    # path('store/', viewshotelinv.store, name="hotelinvstore"),
    # path('delete/<hotelbook_id>', views.delete, name="hotelbookdelete"),
    # path('edit/<hotelbook_id>', views.edit, name="hotelBookedit"),
    # path('update/<hotelbook_id>', views.update, name="hotelBookUpdate"),

    # class based view
    path('', views.BookingListView.as_view(), name="hotelbookindex"),
    path('delete/<hotelbook_id>',views.BookingDelete.as_view(),name="hotelbookdelete"),

    # path('create/', views.InventoryCreate.as_view(), name="hotelinvcreate"),
    path('show/<int:pk>',views.BookingDetail.as_view(),name="hotelbookdetail"),
    path('update/<int:pk>', views.BookingUpdate.as_view(), name="hotelBookUpdate"),

]


#!/usr/bin/env python3

import sys
position = int(sys.argv[1])
s = input()

i = -1
j = -1
k = 0
while k < position + 1:
    i = j + 1
    j = i
    while j < len(s) and s[j] != ",":
        j += 1
    k += 1

print(s[i:j])


import os
import json
import time
from typing import Iterator

import pandas as pd

_SRC_DIR = './tmp'

def morp_to_tag(morp: str) -> Iterator:
    part_of_sppech = set(["名詞", "動詞", "副詞", "形容詞"])
    print('morp: ', morp)
    for m in morp:
        print('m')
        print(m)
        if m == '':
            continue
        elif m.split('/')[1].find('連語') >= 0 and m.split('/')[1].split('+')[-1] in part_of_sppech:
            print('part_of_speech')
            print(m.split('/')[0])
            yield m.split('/')[0]
            continue
        elif m.split('/')[1] in part_of_sppech:
            print('part_of_speech')
            print(m.split('/')[0])
            yield m.split('/')[0]

def process_POS_for_collocation(data):
    ner_list = data.ner_list
    morp_list = data.morp_list
    print('ner_list : ', ner_list)
    print('morp_list : ', morp_list)
    process = []
    for ner in ner_list:
        if ner == '\r\n':
            return process
            break

        print('ner: ', ner)
        target = ner.split('/')[0]
        print('target : ', target)
        if target.find('=') >= 0:
            words = target.split('=')
            print('words : ', words)
            strings = ''
            pos_init = '連語 '
            pos = []
            yomi = ''
            for word in words:
                print('word : ', word)
                print('morp_list : ', morp_list)
                tmp_morp = morp_list.pop(0)
                print('tmp_morp : ', tmp_morp)
                strings += word
                pos.append(tmp_morp.split('/')[1])
                yomi += tmp_morp.split('/')[2]
                print('strings: ', strings)
                print('pos: ', pos)
                print('yomi: ', yomi)
            pos = '+'.join(pos)
            pos = pos_init + pos
            target = strings + '/' + pos + '/' + yomi
            print('target : ', target)
            process.append(target)
            print('process : ', process)
        else:
            target = morp_list.pop(0)
            print('target : ', target)
            process.append(target)
            print('process : ', process)

    return process

def is_join(data):
    ner_list = data.ner_list
    wakati_list = data.wakati_list
    ner_strings = data.ner_strings

    if len(ner_list) != len(wakati_list) and ner_strings.find('=') >= 0:
        return True
    else:
        return False

class Data:
    def __init__(self, data):
        self.ner_list = data['ner'].rstrip().split(' ')
        self.wakati_list = data['wakati'].rstrip().split(' ')
        self.morp_list = data['morp'].rstrip().split(' ')
        self.ner_strings = data['ner'].rstrip()

def main():
    file_list = os.listdir(_SRC_DIR)
    count = 0
    time0 = time.time()
    preprocessing = []
    for f in range(len(file_list)):
        filepath = os.path.join(_SRC_DIR, 'kytea_recipetag_' + str(f) + '.json')
        with open(filepath, 'r', encoding='utf-8') as r:
            data = json.load(r)
            data = Data(data)

        if is_join(data):
            print('ner_list : ', len(data.ner_list))
            print('wakati_list : ', len(data.wakati_list))
            print(data.ner_list)
            print(data.wakati_list)
            print(data.morp_list)
            print(filepath)
            count += 1
            process = process_POS_for_collocation(data)
        else:
            process = data.morp_list

        preprocessing.append(process)

    time1 = time.time()
    print(time1 - time0)
    print(count)

    time2 = time.time()
    result = [list(morp_to_tag(p)) for p in preprocessing]
    time3 = time.time()
    print(time3 - time2)
    print(result)

    csv = pd.DataFrame(result)
    csv.to_csv('kytearecipetag.csv')

if __name__ == '__main__':
    main()


import re
REMOVE_OUTER_BRACKETS = re.compile(r'\[(.*)\]')
GET_PAIRS = re.compile(r'(\[?.*\]?),(\[?.*\]?)')

class Tree :

	def __init__(self , s:str) :
		print(s)
		if len(s) != 1 :
			self._value = parser(s)
			self._left = Tree(self._value[0])
			self._right = Tree(self._value[1])
		return self

	def __str__(self) :
		return "[" + \
				str(self._left) + "," + str(self._right) + \
			   "]"

def parser(s:str) -> (str , str) :

	if len(s) == 1 :
		return s

	x = REMOVE_OUTER_BRACKETS.findall(s)
	try :
			_left_child = GET_PAIRS.match(*x).group(1)
			_right_child = GET_PAIRS.match(*x).group(2)
			return _left_child , _right_child
	except TypeError :
		print('error' , x)

s = '[[3,[2,[1,[7,3]]]],[6,[5,[4,[3,2]]]]]'
print(Tree(s))


# [1] Getting the descriptions
# [2]Splitting it on \n
# [3] Extracting the first N lines [change with N]
# [4] remove stop words, stemming (common NLP methods)
# [5] add that to the csv
from nltk.stem import PorterStemmer
import csv

def extract(data, writerobj):
    lines = data.split('\n')
    numLines = len(lines)
    print ("there are " + str(numLines) + " lines how many do you want to analyze?")
    n = int(input())
    lines = lines[:n]
    ps = PorterStemmer()
    for line in lines:
        words = line.split()
        for i in range(len(words)):
            words[i] = ps.stem(words[i])
        stemmed_line = " ".join(words)
        writerobj.writerow(words)

def main():
    data = input("ENTER INPUT")
    with open("stemmed_data.csv", 'w') as csvfile:
        writerobj = csv.writer(csvfile)
        extract(data, writerobj)

if __name__ == "__main__":
    main()