# -*- coding: utf-8 -*-
"""
Input nom de jeu
"""

import tkinter as tk
import numpy as n
import pygame as p
import pygame.mixer as pm
import pygame.mixer_music as pmm

global Lmap
Lmap=[]
Map_dispo=10

# # Fonctions pour les menus # #
def Menu_principal():
    global Menu
    Menu = tk.Tk()
    Menu.geometry("800x500")
    centrefenetre(Menu)
    Menu.title("Nom du jeu - Menu principal")
    Menu.resizable(width=False, height=False)

    Case_Titre = tk.Frame(Menu,borderwidth=10,relief=tk.GROOVE)
    Case_Titre.pack(side=tk.TOP, pady=50)
    Titre = tk.Label(Case_Titre,text="Trouver un titre il faut",font="Arial 32")
    Titre.pack()

    Frame_jeu=tk.Frame(Menu,borderwidth=5, relief=tk.GROOVE)
    Frame_jeu.pack(side=tk.TOP, pady=10)
    bouton_jeu= tk.Button(Frame_jeu, text="Nouvelle partie", command= lambda fen=Menu,fonc=Newgame :chgmt_fen(fen,fonc))
    bouton_jeu.pack()

    Frame_info=tk.Frame(Menu,borderwidth=5, relief=tk.GROOVE)
    Frame_info.pack(side=tk.TOP, pady=10)
    bouton_info= tk.Button(Frame_info, text="A propos", command=Info)
    bouton_info.pack()

    Frame_quit = tk.Frame(Menu, borderwidth=5, relief=tk.GROOVE)
    Frame_quit.pack(side=tk.TOP, pady=10)
    bouton_quit=tk.Button(Frame_quit, text="Quitter", command=Menu.destroy)
    bouton_quit.pack()
    Menu.mainloop()

def Info():
    print("Jeu créé par moi")
    print("Musique : Land Below Fire Emblem Fates OST")

def Newgame():
    global Lmap
    Lmap=[]
    for i in range (Map_dispo):
        Lmap.append(eval("map"+str(i+1)))
    global Menu_Lvl
    Menu_Lvl= tk.Tk()
    Menu_Lvl.geometry("800x500")
    centrefenetre(Menu_Lvl)
    Menu_Lvl.title("Nom du jeu - Menu des niveaux")
    Menu_Lvl.resizable(width=False, height=False)

    Case_Titre = tk.Frame(Menu_Lvl,borderwidth=10,relief=tk.GROOVE)
    Case_Titre.grid(row=10,column=1,columnspan=8, pady=50) # Travailler sur le centrage
    Titre = tk.Label(Case_Titre,text="Choisissez un niveau",font="Arial 24")
    Titre.grid()
    for i in range (len(Lmap)):
        Case_niveau(i)

    Frame_quit = tk.Frame(Menu_Lvl, borderwidth=5, relief=tk.GROOVE)
    Frame_quit.grid(row=600,column=3,columnspan=3, pady=10)
    bouton_quit=tk.Button(Frame_quit, text="Retour au menu", command=lambda fen=Menu_Lvl,fonc=Menu_principal :chgmt_fen(fen,fonc))
    bouton_quit.grid()
    Menu_Lvl.mainloop()

def Case_niveau(i):
    global Lmap
    global Menu_Lvl
    Case_Lvl = tk.Frame(Menu_Lvl,borderwidth=5,relief=tk.GROOVE)
    Case_Lvl.grid(column=i%8,row=100+(i//8)*10,padx=24,pady=10)
    Bouton_Lvl = tk.Button(Case_Lvl,text="Lvl "+str(i+1),command=lambda fen=Menu_Lvl,fonc=Lmap[i] :chgmt_fen(fen,fonc))
    Bouton_Lvl.grid()

def Pause():
    global Play
    Play = False
    global Menu_pause
    Menu_pause=tk.Tk()
    Menu_pause.geometry("800x500")
    centrefenetre(Menu_pause)
    Menu_pause.title("Nom du jeu - Pause")
    Menu_pause.resizable(width=False, height=False)

    Case_Titre = tk.Frame(Menu_pause,borderwidth=10,relief=tk.GROOVE)
    Case_Titre.pack(side=tk.TOP, pady=50)
    Titre = tk.Label(Case_Titre,text="Pause",font="Arial 24")
    Titre.pack()

    Frame_reprendre=tk.Frame(Menu_pause,borderwidth=5, relief=tk.GROOVE)
    Frame_reprendre.pack(side=tk.TOP, pady=10)
    bouton_reprendre= tk.Button(Frame_reprendre, text="Reprendre", command=lambda fen=Menu_pause,fonc=reprendre :chgmt_fen(fen,fonc))
    bouton_reprendre.pack()

    Frame_recommencer=tk.Frame(Menu_pause,borderwidth=5, relief=tk.GROOVE)
    Frame_recommencer.pack(side=tk.TOP, pady=10)
    bouton_recommencer= tk.Button(Frame_recommencer, text="Recommencer", command=lambda fen=Menu_pause,fonc=recommencer :chgmt_fen(fen,fonc))
    bouton_recommencer.pack()

    Frame_quit = tk.Frame(Menu_pause, borderwidth=5, relief=tk.GROOVE)
    Frame_quit.pack(side=tk.TOP, pady=10)
    bouton_quit=tk.Button(Frame_quit, text="Retour au menu", command=lambda fen=Menu_pause,fonc=quitter :chgmt_fen(fen,fonc))
    bouton_quit.pack()
    Menu_pause.mainloop()

def reprendre():
    global Play
    Play=True
    Mouvement_adverse()

def recommencer():
    global fenetre
    fenetre.destroy()
    eval("map"+str(Niveau))()

def quitter():
    global fenetre
    pmm.stop()
    fenetre.destroy()
    Menu_principal()

def fenGO():
    global GO
    GO = tk.Tk()
    GO.geometry("800x500")
    centrefenetre(GO)
    GO.title("Game Over")
    GO.resizable(width=False, height=False)

    Case_Titre = tk.Frame(GO,borderwidth=10,relief=tk.GROOVE)
    Case_Titre.pack(side=tk.TOP, pady=50)
    Titre = tk.Label(Case_Titre,text="Vous avez perdu",font="Arial 24")
    Titre.pack()

    Frame_recommencer=tk.Frame(GO,borderwidth=5, relief=tk.GROOVE)
    Frame_recommencer.pack(side=tk.TOP, pady=10)
    bouton_recommencer= tk.Button(Frame_recommencer, text="Réessayer", command=lambda fen=GO,fonc=recommencer :chgmt_fen(fen,fonc))
    bouton_recommencer.pack()

    Frame_quit = tk.Frame(GO, borderwidth=5, relief=tk.GROOVE)
    Frame_quit.pack(side=tk.TOP, pady=10)
    bouton_quit=tk.Button(Frame_quit, text="Retour au menu", command=lambda fen=GO,fonc=quitter :chgmt_fen(fen,fonc))
    bouton_quit.pack()
    GO.mainloop()

def fenW():
    global W
    W = tk.Tk()
    W.geometry("800x500")
    centrefenetre(W)
    W.title("Fin de niveau")
    W.resizable(width=False, height=False)

    Case_Titre = tk.Frame(W,borderwidth=10,relief=tk.GROOVE)
    Case_Titre.pack(side=tk.TOP, pady=50)
    Titre = tk.Label(Case_Titre,text="Vous avez gagné",font="Arial 24")
    Titre.pack()

    Frame_recommencer=tk.Frame(W,borderwidth=5, relief=tk.GROOVE)
    Frame_recommencer.pack(side=tk.TOP, pady=10)
    bouton_recommencer= tk.Button(Frame_recommencer, text="Réessayer", command=lambda fen=W,fonc=recommencer :chgmt_fen(fen,fonc))
    bouton_recommencer.pack()

    Frame_Next_Lvl=tk.Frame(W,borderwidth=5, relief=tk.GROOVE)
    Frame_Next_Lvl.pack(side=tk.TOP, pady=10)
    bouton_Next_Lvl= tk.Button(Frame_Next_Lvl, text="Niveau suivant", command=lambda fen=W,fonc=Next_Lvl :chgmt_fen(fen,fonc))
    bouton_Next_Lvl.pack()

    Frame_quit = tk.Frame(W, borderwidth=5, relief=tk.GROOVE)
    Frame_quit.pack(side=tk.TOP, pady=10)
    bouton_quit=tk.Button(Frame_quit, text="Retour au menu", command=lambda fen=W,fonc=quitter :chgmt_fen(fen,fonc))
    bouton_quit.pack()
    W.mainloop()

def Next_Lvl():
    global fenetre
    fenetre.destroy()
    global Niveau
    eval("map"+str(Niveau+1))()

def geoliste(g):
    r=[i for i in range(0,len(g)) if not g[i].isdigit()]
    return [int(g[0:r[0]]),int(g[r[0]+1:r[1]]),int(g[r[1]+1:r[2]]),int(g[r[2]+1:])]

def centrefenetre(fen):
    fen.update_idletasks()
    l,h,x,y=geoliste(fen.geometry())
    fen.geometry("%dx%d%+d%+d" % (l,h,(fen.winfo_screenwidth()-l)//2,(fen.winfo_screenheight()-h)//2))

def chgmt_fen(fen,fonc):
    fen.destroy()
    fonc()

# # Création des map # #

def create_map():
    print("createMap")
    global Zone_interdite
    Zone_interdite=[]
    global Info_garde
    Info_garde=[]
    global Vision
    Vision=[]
    global Objet
    Objet=[]
    global Teleporteur
    Teleporteur=[]
#    global Porte
#    Porte=[]
    global Laser
    Laser=[]
    global Inventaire
    Inventaire=[0]
    global Play
    Play = True
    global Tps_mvt
    Tps_mvt=100
    global Alarme_active
    Alarme_active=False
    global Temps_ralentit
    Temps_ralentit=False
    global testp
    testp=0

    global fenetre
    fenetre = tk.Tk()
    fenetre.attributes('-fullscreen',True )
    global Event
    Event=tk.Frame(fenetre,borderwidth=2, relief=tk.GROOVE,width=269,height=244)
    Event.pack_propagate(False)
    Event.pack(side=tk.LEFT)
    label=tk.Label(Event,text="Rapport des évènements \n",font="Arial 14")
    label.pack()
    tk.Label(Event,text="Cliquez sur la fenêtre avant de jouer").pack()
    global Info
    Info=[]
    global Tps_ecoule
    Tps_ecoule=0
    Tps_Score=tk.Frame(fenetre)
    Tps_Score.pack(side=tk.RIGHT)
    label2=tk.Label(Tps_Score,text="                       \n",font="Arial 14")
    label2.pack()
    global Aff_Temps
    Aff_Temps=tk.StringVar()
    Aff_Temps.set("Temps : "+str(Tps_ecoule/1000))
    label1=tk.Label(Tps_Score,textvariable=Aff_Temps)
    label1.pack()
    global Aff_cle
    Aff_cle=tk.StringVar()
    Aff_cle.set("Vous avez "+str(Inventaire[0])+" clé(s)")
    label3=tk.Label(Tps_Score,textvariable=Aff_cle)
    label3.pack()
    # création du canvas
    global canvas
    canvas = tk.Canvas(fenetre, width=Longueur_map, height=Largeur_map, bg="ivory",highlightthickness=False)
    p.init()
    pmm.load("MusiqueBG.wav")
    pmm.play(-1)
    global Son_alarme
    Son_alarme=pm.Sound("Alarme.wav")

def map1():
    print("map1")
    global Niveau
    Niveau=1
    create_map()

    # # Murs # #
    obstacle(150,160,80,70)
    obstacle(260,110,60,160)
    obstacle(50,110,70,160)
    obstacle(120,50,150,80)
    obstacle(120,270,150,30)
    obstacle(340,330,40,30)
    obstacle(500,440,30,40)
    obstacle(440,490,40,40)
    obstacle(550,490,30,40)
    obstacle(480,550,60,30)
    obstacle(350,510,30,30)
    obstacle(900,440,300,60)
    obstacle(1020,300,60,300)
    # # Objets # #
    Creation_alarme(120,800)
    Cle(260,800)
    Portail(400,770,60,"v")
    Portail(900,800,60,"h")
    TimeSlower(600,800)
    Plaque_tp(2,20,20,300,300)
    Plaque_tp(1,800,800,1200,800)
    # # Lasers alarme # #
    Creation_alarme2f(120,500,200,500)
    Creation_alarme2f(60,500,60,700)
    Creation_alarme2m("h",120,550,80,550,650,5)
    Creation_alarme2m("v",150,950,80,120,230,5)
    # # Objectif # #
    global objectif
    objectif = canvas.create_rectangle(1400,1000,1400+Taille_perso,1000+Taille_perso,fill="yellow")
    # # Personage # #
    global Perso
    Perso = canvas.create_rectangle(0,0,Taille_perso,Taille_perso,fill="violet")

    # # Gardes # #

    Creation_garde(350,200,420,300,350,200,1,-10)
    Creation_garde(130,140,230,230,230,230,3,-5)
    Creation_garde(730,140,800,200,730,140,1,5)
    Creation_garde2(500,500,1,-500)   # OK
    Creation_garde2(1000,500,1,500)  #  35 gauche
    Creation_garde2(1080,500,1,-500)  # 35 droite et bas
    Creation_garde2(1000,420,1,-500)  # OK
    Creation_garde2(1080,420,1,500)   # 35 haut
    # obstacle au dessus ou à gauche --> 35
    Creation_garde2(700,700,4,0)
    Creation_garde(400,500,400,700,400,500,1,-10)
    Creation_garde2(100,660,1,0)
    Mouvement_adverse()

    canvas.focus_set()
    canvas.bind("<Key>", clavier)
    canvas.pack(expand=1)
    fenetre.mainloop()

def map2():
    global Niveau
    Niveau=2
    create_map()

    # # Murs # #
    obstacle(0,0,1440,300)
    obstacle(0,300,210,360)
    obstacle(0,660,1440,390)
    obstacle(1250,300,210,360)
    obstacle(210,420,160,80)
    obstacle(520,300,160,200)
    obstacle(290,540,120,80)
    obstacle(490,540,120,80)
    obstacle(850,420,120,240)
    obstacle(970,300,120,40)
    # # Objectif # #
    global objectif
    objectif = canvas.create_rectangle(1090,630,1090+Taille_perso,630+Taille_perso,fill="yellow")
    # # Personage # #
    global Perso
    Perso = canvas.create_rectangle(250,350,250+Taille_perso,350+Taille_perso,fill="violet")
    # # Guardes # #
    Creation_garde(380,460,490,460,380,460,1,5)
    Creation_garde(270,520,410,620,270,520,1,-5)
    Creation_garde(470,520,610,620,470,520,1,5)
    Creation_garde(750,510,750,630,750,510,1,5)
    Creation_garde2(680,480,1,500)
    Creation_garde2(830,480,3,500)
    Creation_garde2(750,350,2,0)
    Creation_garde2(980,640,4,0)
    Creation_garde2(1220,640,4,0)
    Creation_garde(1000,380,1080,500,1000,380,1,5)
    Creation_garde(1080,380,1200,460,1200,460,3,-5)
    Creation_garde(1000,500,1120,580,1080,500,1,-5)
    Creation_garde(1120,460,1200,580,1120,580,3,5)
    Mouvement_adverse()

    canvas.focus_set()
    canvas.bind("<Key>", clavier)
    canvas.pack(expand=1)
    fenetre.mainloop()

def map3():
    global Niveau
    Niveau=3
    create_map()

    # # Murs # #
    obstacle(100,0,120,350)
    obstacle(220,0,1220,100)
    obstacle(0,430,220,90)
    obstacle(910,180,170,340)
    obstacle(1200,260,100,60)
    obstacle(1070,380,120,60)
    obstacle(1310,380,130,60)
    obstacle(0,520,1080,160)
    obstacle(1070,600,140,160)
    obstacle(1290,600,150,350)
    obstacle(1080,840,210,100)
    obstacle(430,670,80,80)
    obstacle(310,730,80,100)
    obstacle(310,830,200,100)
    obstacle(0,670,80,260)
    obstacle(0,930,1440,120)
    # # Objectif # #
    global objectif
    objectif = canvas.create_rectangle(180,800,180+Taille_perso,800+Taille_perso,fill="yellow")
    # # Perso # #
    global Perso
    Perso = canvas.create_rectangle(0,0,Taille_perso,Taille_perso,fill="violet")
    # # Guardes # #
    for i in range (6):
        for j in range (4):
            Creation_garde2(260+120*i,120+120*j,2-(-1)**(i+j),500)
    Creation_garde(1080,190,1200,190,1080,190,1,5)
    Creation_garde(1300,190,1420,190,1420,190,1,5)
    Creation_garde(1080,230,1200,230,1200,230,1,5)
    Creation_garde(1300,230,1420,230,1300,230,1,5)
    Creation_garde(1080,280,1170,280,1080,280,1,5)
    Creation_garde(1310,280,1400,280,1400,280,1,5)
    Creation_garde2(1240,390,1,800)
    Creation_garde2(1160,450,1,0)
    Creation_garde2(1320,450,3,0)
    Creation_garde(1115,450,1115,570,1115,450,1,-5)
    Creation_garde(1365,450,1365,570,1365,570,1,5)
    Creation_garde2(1240,540,1,500)
    Creation_garde(1080,580,1200,580,1080,580,1,5)
    Creation_garde(1300,580,1420,580,1420,580,1,5)
    for i in range(11):
        Creation_garde(550+50*i,680,550+50*i,740,550+50*i,680+10*abs(5-i),2-signe(5-i),1)
        Creation_garde(550+50*i,850,550+50*i,910,550+50*i,850+10*abs(5-i),2+signe(5-i),1)
    Creation_garde(120,740,240,860,120,740,1,10)
    Creation_garde(120,740,240,860,240,740,2,10)
    Creation_garde(120,740,240,860,240,860,3,10)
    Creation_garde(120,740,240,860,120,860,4,10)

    Mouvement_adverse()

    canvas.focus_set()
    canvas.bind("<Key>", clavier)
    canvas.pack(expand=1)
    fenetre.mainloop()

def map4():
    global Niveau
    Niveau=4
    create_map()

    # # Murs # #
    obstacle(-20,60,90,330)
    obstacle(130,0,130,300)
    obstacle(130,320,130,60)
    obstacle(40,440,60,40)
    obstacle(160,440,60,40)
    obstacle(260,320,70,180)
    obstacle(-20,540,60,300)
    obstacle(-20,830,310,220)
    obstacle(90,540,240,120)
    obstacle(90,660,10,50)
    obstacle(90,780,10,50)
    obstacle(170,680,80,50)
    obstacle(170,760,80,50)
    obstacle(330,620,80,240)
    obstacle(290,920,180,130)
    obstacle(470,720,100,330)
    obstacle(570,840,210,210)
    obstacle(770,550,120,500)
    obstacle(410,620,160,40)
    obstacle(570,550,160,110)
    obstacle(720,660,10,50)
    obstacle(620,710,80,80)
    obstacle(330,320,50,150)
    obstacle(400,490,30,100)
    obstacle(570,470,10,80)
    obstacle(440,180,140,290)
    obstacle(370,180,70,80)
    obstacle(260,0,230,100)
    obstacle(490,0,140,130)
    obstacle(630,0,160,200)
    obstacle(790,0,100,500)
    obstacle(570,250,130,40)
    obstacle(690,250,30,110)
    obstacle(650,460,160,40)
    obstacle(620,340,30,160)
    obstacle(890,0,320,250)
    obstacle(890,800,320,250)
    obstacle(930,300,100,40)
    obstacle(1070,300,100,40)
    obstacle(950,400,60,90)
    obstacle(1090,400,60,90)
    obstacle(1020,560,60,90)
    obstacle(930,620,40,40)
    obstacle(1130,620,40,40)
    obstacle(970,700,160,60)
    obstacle(1210,0,230,490)
    obstacle(1210,550,140,400)
    obstacle(1210,950,80,100)
    # # Objectif # #
    global objectif
    objectif = canvas.create_rectangle(1400,1000,1400+Taille_perso,1000+Taille_perso,fill="yellow")
    # # Personage # #
    global Perso
    Perso = canvas.create_rectangle(0,0,Taille_perso,Taille_perso,fill="violet")
    # # Guardes # #
    Creation_garde(130,300,240,300,130,300,1,5)
    Creation_garde(20,420,100,480,20,420,1,5)
    Creation_garde(140,420,220,480,200,480,3,-5)
    Creation_garde2(0,520,1,1000)
    Creation_garde2(0,520,3,1000)
    Creation_garde2(100,660,2,0)
    Creation_garde(150,660,250,730,150,680,2,-5)
    Creation_garde(150,740,250,810,150,740,1,-5)
    Creation_garde(330,860,390,860,330,860,1,5)
    Creation_garde2(470,700,1,700)
    Creation_garde(600,690,700,790,700,690,1,-5)
    Creation_garde(600,690,700,790,600,690,2,-5)
    Creation_garde(600,690,700,790,600,790,3,-5)
    Creation_garde(600,690,700,790,700,790,4,-5)
    Creation_garde2(330,470,1,0)
    Creation_garde(440,490,470,570,440,490,1,-5)
    Creation_garde(500,490,540,570,540,570,3,-5)
    Creation_garde(340,260,420,300,340,260,1,5)
    Creation_garde(260,160,330,240,330,160,2,5)
    Creation_garde2(470,100,1,1200)
    Creation_garde2(470,100,3,1200)
    Creation_garde(720,200,770,250,720,200,1,-5)
    Creation_garde(660,370,760,370,660,370,1,5)
    Creation_garde(660,430,760,430,760,430,3,5)
    Creation_garde2(620,500,1,700)
    Creation_garde(910,280,1030,340,910,280,1,-5)
    Creation_garde(910,280,1030,340,1030,340,3,-5)
    Creation_garde(1050,280,1170,340,1050,280,1,-5)
    Creation_garde(1050,280,1170,340,1170,340,3,-5)
    Creation_garde(930,380,1010,490,930,380,1,5)
    Creation_garde(930,380,1010,490,1010,490,3,5)
    Creation_garde(1070,380,1150,490,1070,380,1,-5)
    Creation_garde(1070,380,1150,490,1150,490,3,-5)
    Creation_garde(910,600,970,660,910,600,1,5)
    Creation_garde(1000,540,1080,650,1000,540,1,-5)
    Creation_garde(1000,540,1080,650,1080,650,3,-5)
    Creation_garde(1110,600,1170,660,1100,600,1,-5)
    Creation_garde(950,680,1130,760,1040,680,1,-5)
    Creation_garde(950,680,1130,760,1040,760,3,-5)

    Mouvement_adverse()

    canvas.focus_set()
    canvas.bind("<Key>", clavier)
    canvas.pack(expand=1)
    fenetre.mainloop()

def map5():
    global Niveau
    Niveau=5
    create_map()
    # # Murs # #
    obstacle(0,0,350,180)
    obstacle(0,180,50,160)
    obstacle(0,340,150,120)
    obstacle(0,460,70,80)
    obstacle(0,620,70,80)
    obstacle(0,700,150,350)
    obstacle(120,220,150,40)
    obstacle(290,180,20,160)
    obstacle(230,260,40,200)
    obstacle(150,540,80,80)
    obstacle(180,720,20,50)
    obstacle(180,810,20,50)
    obstacle(150,900,130,40)
    obstacle(150,940,520,110)
    obstacle(270,420,80,40)
    obstacle(310,460,40,80)
    obstacle(350,480,100,60)
    obstacle(310,620,280,80)
    obstacle(230,700,280,80)
    obstacle(230,780,50,40)
    obstacle(300,780,50,40)
    obstacle(370,780,30,40)
    obstacle(420,780,30,40)
    obstacle(490,780,20,40)
    obstacle(300,900,50,40)
    obstacle(370,900,30,40)
    obstacle(420,900,30,40)
    obstacle(490,900,180,40)
    obstacle(550,780,40,180)
    obstacle(350,0,260,40)
    obstacle(610,0,120,20)
    obstacle(330,340,20,80)
    obstacle(330,240,80,100)
    obstacle(410,320,60,20)
    obstacle(410,190,60,110)
    obstacle(410,140,120,60)
    obstacle(410,120,140,20)
    obstacle(550,120,60,80)
    obstacle(610,140,160,60)
    obstacle(490,240,40,60)
    obstacle(590,640,80,60)
    obstacle(670,640,100,180)
    obstacle(670,900,40,30)
    obstacle(670,1030,160,20)
    obstacle(790,820,40,110)
    obstacle(770,450,60,370)
    obstacle(670,430,160,20)
    obstacle(610,430,60,120)
    obstacle(610,400,40,30)
    obstacle(550,240,40,80)
    obstacle(590,240,80,60)
    obstacle(610,300,60,80)
    obstacle(670,340,80,70)
    obstacle(770,220,60,190)
    obstacle(830,220,80,880)
    obstacle(770,140,180,80)
    obstacle(730,0,220,140)
    obstacle(610,140,160,60)
    obstacle(550,120,60,80)
    obstacle(510,420,80,200)
    obstacle(430,380,160,40)
    obstacle(490,320,100,60)
    obstacle(950,0,80,100)
    obstacle(1030,0,80,40)
    obstacle(1110,0,330,100)
    obstacle(1190,100,250,120)
    obstacle(1230,220,210,240)
    obstacle(1330,460,110,80)
    obstacle(1230,540,210,240)
    obstacle(1190,780,250,270)
    obstacle(1110,900,80,150)
    obstacle(1030,960,80,90)
    obstacle(950,900,80,150)
    obstacle(910,780,40,270)
    obstacle(1030,260,60,160)
    obstacle(960,550,60,180)
    obstacle(1120,550,60,180)
    # # Objets # #
    Cle(660,70)
    Cle(740,1000)
    Cle(1060,920)
    Portail(60,540,80,"v")
    Portail(50,540,80,"v")
    Portail(1230,460,80,"v")
    Plaque_tp(1,10,570,1060,60)
    # # Lasers alarme # #
    Creation_alarme2f(600,40,600,120)
    Creation_alarme2f(710,910,790,910)
    Creation_alarme2f(910,300,1030,300)
#    Creation_alarme2f(950,840,990,840)
#    Creation_alarme2f(1150,840,1190,840)
    Creation_alarme2m("h",1020,880,100,820,880,5)
    Creation_alarme2m("v",260,820,80,260,510,5)
#    Creation_alarme2m("v",957,760,50,955,1045,2)
#    Creation_alarme2m("v",1185,760,50,1095,1185,2)
    # # Objectif # #
    global objectif
    objectif = canvas.create_rectangle(1280,490,1280+Taille_perso,490+Taille_perso,fill="yellow")
    # # Personage # #
    global Perso
    Perso = canvas.create_rectangle(710,510,710+Taille_perso,510+Taille_perso,fill="violet")
    # # Gardes # #
    Creation_garde(590,300,590,505,590,300,1,4)
    Creation_garde(670,410,810,410,670,410,1,4)
    Creation_garde2(670,320,1,1000)
    Creation_garde2(670,320,3,1000)
    Creation_garde2(750,200,1,1000)
    Creation_garde2(750,200,3,1000)
    Creation_garde(530,140,530,280,530,140,1,5)
    Creation_garde(410,300,510,300,410,300,1,5)
    Creation_garde(355,360,405,440,355,360,1,5)
    Creation_garde2(490,420,1,800)
    Creation_garde2(490,420,3,800)
    Creation_garde2(490,600,1,800)
    Creation_garde2(490,600,3,800)
    Creation_garde2(430,540,1,800)
    Creation_garde(130,520,230,620,130,520,1,-5)
    Creation_garde(130,520,230,620,230,620,3,-5)
    Creation_garde2(70,520,1,1000)
    Creation_garde2(70,620,1,-1000)
    Creation_garde(160,700,160,850,160,700,1,6)
    Creation_garde(200,700,200,850,200,850,3,-6)
    Creation_garde(280,780,280,920,280,780,1,5)
    Creation_garde(350,780,350,920,350,850,1,5)
    Creation_garde(400,780,400,920,400,920,1,5)
    Creation_garde(450,780,450,920,450,780,1,5)
    Creation_garde(470,780,470,920,470,920,1,5)
    Creation_garde(590,700,650,760,590,700,1,-5)
    Creation_garde(660,830,760,870,760,870,3,-5)
    Creation_garde(690,950,790,950,690,950,1,5)
    Creation_garde(150,270,150,380,150,270,1,3)
    Creation_garde(180,295,180,405,180,405,1,3)
    Creation_garde(210,320,210,430,210,320,1,3)
    Creation_garde2(270,400,1,900)
    Creation_garde2(270,400,3,900)
    Creation_garde(310,180,310,320,310,180,1,3)
    Creation_garde(360,60,380,120,360,60,1,-5)
    Creation_garde(620,30,700,110,620,30,1,5)
    Creation_garde(960,150,1030,200,960,150,1,5)
    Creation_garde(1090,150,1160,200,1160,200,3,5)
    Creation_garde(910,340,1010,340,910,340,1,5)
    Creation_garde(910,380,1010,380,1010,380,3,5)
    Creation_garde(1090,300,1210,300,1090,300,1,5)
    Creation_garde(1090,380,1210,380,1210,380,3,5)
    Creation_garde2(1140,340,1,500)
    Creation_garde2(930,490,1,600)
    Creation_garde2(1190,490,3,600)
    Creation_garde2(1100,590,1,500)
    Creation_garde2(1020,650,3,500)
    Creation_garde2(1100,710,1,500)
    Creation_garde2(920,720,4,0)
    Creation_garde2(1200,720,4,0)
    Creation_garde(1060,490,1060,720,1060,490,1,6)
    Creation_garde2(990,820,3,-700)
    Creation_garde2(1130,820,1,-700)

    Mouvement_adverse()
    canvas.focus_set()
    canvas.bind("<Key>", clavier)
    canvas.pack(expand=1)
    fenetre.mainloop()

def map6():
    print(6)

def map7():
    print(7)

def map8():
    print(8)

def map9():
    print(9)

def map10():
    print(10)

def map11():
    print(11)

def map12():
    print(12)

# # Fonctions annexes # #
def signe(x):
    if x>=0:
        return 1
    else:
        return -1

def signe1(x):
    if x>0:
        return 3
    else:
        return 1

def signe3(x):
    if x>0:
        return 1
    else:
        return 3

def Add_Visionx(n,sens):
    if n==2 or (n==3 and sens>0) or(n==1 and sens<0):
        return Taille_perso
    else:
        return 0

def Add_Visiony(n,sens):
    if (n==3 and sens>0) or (n==1 and sens<0) or n==4:
        return Taille_perso
    else:
        return 0

def Reduce_Visionx(n,sens):
    if (n==2 and sens>0) or (n==4 and sens<0):
        return 10
    elif n==1 and sens<0:
        return 5
    else:
        return -1

def Reduce_Visionxr(n,sens):
    if n==3:
        return 5
    else:
        return -1

def Reduce_Visiony(n,sens):
    if n==3:
        return 10
    else:
        return -1

def Reduce_Visionyr(n,sens):
    if (n==4 and sens>0) or (n==2 and sens<0):
        return 5
    elif n==4 and sens<0:
        return -5
    else:
        return -1

def betweenL(x,a,b):
    m=a
    M=b
    if m>M:
        m,M = M,m
    if x>=m and x<=M:
        return True
    else:
        return False

def betweenS(x,a,b):
    m=a
    M=b
    if m>M:
        m,M = M,m
    if x>m and x<M:
        return True
    else:
        return False

def Suppr_List(L,i):
    return L[0:i]+L[i+1:]

def Add_info(texte):
    global Info
    global Event
    A=tk.Label(Event,text=texte)
    if len(Info)>6:
        for i in range (len(Info)-1):
            Info[i]=Info[i+1]
        Info[len(Info)-1]=texte
        for i in range(1,len(Event.winfo_children())):
            Event.winfo_children()[1].destroy()
        for i in range (len(Info)):
            tk.Label(Event,text=Info[i]).pack()
    else:
        Info.append(texte)
        A.pack()

# # Fonction canvas # #
def rotation(objet,point,angle):
    global canvas
    Nombre_points= len(canvas.coords(objet))
    Nouvelle_coords=[]
    for i in range(0,Nombre_points,2):
        X0s=point[0] + (canvas.coords(objet)[i]-point[0])*n.cos(angle) + (canvas.coords(objet)[i+1]-point[1])*n.sin(angle)
        Nouvelle_coords.append(X0s)
        Y0s=point[1] - (canvas.coords(objet)[i]-point[0])*n.sin(angle) + (canvas.coords(objet)[i+1]-point[1])*n.cos(angle)
        Nouvelle_coords.append(Y0s)
    canvas.coords(objet,Nouvelle_coords)

def Vision_garde(x0,y0,Taille_vision,sens):
    global canvas
    if sens>0:
        V=canvas.create_polygon([x0+Taille_perso,y0+Taille_perso/4,x0+Taille_perso,y0+3/4*Taille_perso,x0+Taille_perso+Taille_vision,y0+3/4*Taille_perso+Pente_cone*Taille_vision,x0+Taille_perso+Taille_vision,y0+Taille_perso/4-Pente_cone*Taille_vision],outline="black",fill="yellow")
    else:
        V=canvas.create_polygon([x0,y0+Taille_perso/4,x0,y0+3/4*Taille_perso,x0-Taille_vision,y0+3/4*Taille_perso+Pente_cone*Taille_vision,x0-Taille_vision,y0+Taille_perso/4-Pente_cone*Taille_vision],outline="black",fill="yellow")
    return V

def Reduire_visionr(i):
    global Zone_interdite
    global Info_garde
    Info_garde[i][8]=0
    canvas.delete(Info_garde[i][7])
    Info_garde[i][7]=Vision_garde(canvas.coords(Info_garde[i][0])[0],canvas.coords(Info_garde[i][0])[1],Info_garde[i][8],1)
    Centre=((canvas.coords(Info_garde[i][0])[0]+canvas.coords(Info_garde[i][0])[2])/2,(canvas.coords(Info_garde[i][0])[1]+canvas.coords(Info_garde[i][0])[3])/2)
    rotation(Info_garde[i][7],Centre,-signe(Info_garde[i][5])*(Info_garde[i][6]-1)*n.pi/2)
    while (Restriction_mouvement(canvas.coords(Info_garde[i][7])[4],canvas.coords(Info_garde[i][7])[5],"L")) and (Restriction_mouvement(canvas.coords(Info_garde[i][7])[6],canvas.coords(Info_garde[i][7])[7],"L")) and Info_garde[i][8]<50:
        Info_garde[i][8]=Info_garde[i][8]+5 # 1 : + précis mais ralentit le jeu
        canvas.delete(Info_garde[i][7])
        Info_garde[i][7]=Vision_garde(canvas.coords(Info_garde[i][0])[0],canvas.coords(Info_garde[i][0])[1],Info_garde[i][8],1)
        rotation(Info_garde[i][7],Centre,-signe(Info_garde[i][5])*(Info_garde[i][6]-1)*n.pi/2)

def Reduire_vision(i):
    global Zone_interdite
    global Info_garde
   # print(Info_garde[i][6])
    Info_garde[i][8]=0
    canvas.delete(Info_garde[i][7])
    Info_garde[i][7]=Vision_garde(canvas.coords(Info_garde[i][0])[0],canvas.coords(Info_garde[i][0])[1],Info_garde[i][8],signe(Info_garde[i][5]))
    Centre=((canvas.coords(Info_garde[i][0])[0]+canvas.coords(Info_garde[i][0])[2])/2,(canvas.coords(Info_garde[i][0])[1]+canvas.coords(Info_garde[i][0])[3])/2)
    rotation(Info_garde[i][7],Centre,-signe(Info_garde[i][5])*(Info_garde[i][6]-1)*n.pi/2)
    while (Restriction_mouvement(canvas.coords(Info_garde[i][7])[4],canvas.coords(Info_garde[i][7])[5],"L")) and (Restriction_mouvement(canvas.coords(Info_garde[i][7])[6],canvas.coords(Info_garde[i][7])[7],"L")) and Info_garde[i][8]<50:
        Info_garde[i][8]=Info_garde[i][8]+5  # 1 : + précis mais ralentit le jeu
        canvas.delete(Info_garde[i][7])
        Info_garde[i][7]=Vision_garde(canvas.coords(Info_garde[i][0])[0],canvas.coords(Info_garde[i][0])[1],Info_garde[i][8],signe(Info_garde[i][5]))
        rotation(Info_garde[i][7],Centre,-signe(Info_garde[i][5])*(Info_garde[i][6]-1)*n.pi/2)

def Restriction_mouvement(x,y,Type):
    global Zone_interdite
    Possible = True
    i = 0
    while i < len(Zone_interdite) and Possible:
        if eval("between"+Type)(x,Zone_interdite[i][0],Zone_interdite[i][1]) and eval("between"+Type)(y,Zone_interdite[i][2],Zone_interdite[i][3]):
                Possible = False
        i=i+1
    return Possible

def clavier(event):
    if Play:
        touche = event.keysym
        if touche == "z" or touche == "s" or touche == "d" or touche == "q":
            Mouvement(touche)
        if touche == "Escape":
            Pause()
        if touche=="f":
            print(canvas.coords(Perso))
        if touche=="Return":
            Action()

def Mouvement(touche):
    global canvas
    global Perso
    global objectif
    global Last_moov
    if touche == "z" and canvas.coords(Perso)[1]>0 and Restriction_mouvement(canvas.coords(Perso)[0]+10, canvas.coords(Perso)[1]-8,"L"):
        canvas.move(Perso,0,-10)
    elif touche == "s" and canvas.coords(Perso)[1]<Largeur_map-Taille_perso and Restriction_mouvement(canvas.coords(Perso)[0]+10, canvas.coords(Perso)[1]+10+10,"L"):
       canvas.move(Perso,0,10)
    elif touche == "d" and canvas.coords(Perso)[0]<Longueur_map-Taille_perso and Restriction_mouvement(canvas.coords(Perso)[0]+10+10, canvas.coords(Perso)[1]+10,"L"):
       canvas.move(Perso,10,0)
    elif touche == "q" and canvas.coords(Perso)[0]>0 and Restriction_mouvement(canvas.coords(Perso)[0]-10+10, canvas.coords(Perso)[1]+10,"L"):
         canvas.move(Perso,-10,0)
    Last_moov=touche
    if Detection():
        Game_over()
    Detection_Laser()
    Test_TP()
    if canvas.coords(Perso)==canvas.coords(objectif):
        Victoire()

def Test_TP():
    global canvas
    global Perso
    global Teleporteur
    L=[canvas.coords(Perso)[0],canvas.coords(Perso)[1]]
    Recherche=False
    i=0
    while i<len(Teleporteur) and not Recherche:
        if L==Teleporteur[i][1:3]:
            Recherche=True
            Plaque=1
        elif L==Teleporteur[i][3:5]:
            Recherche=True
            Plaque=2
        else:
            pass
        i=i+1
    if Recherche:
        teleport(i-1,Plaque)

def Detection_Laser():
    global Laser
    global canvas
    global Perso
    X,Y=canvas.coords(Perso)[0],canvas.coords(Perso)[1]
    Vu = False
    i=0
    while i<len(Laser) and not Vu:
        Rayon=canvas.coords(Laser[i][1])
        if Rayon[1]==Rayon[3]:
            if (betweenL(X,Rayon[0],Rayon[2]) and betweenL(Rayon[1],Y,Y+Taille_perso)) or (betweenL(X+Taille_perso,Rayon[0],Rayon[2]) and betweenL(Rayon[1],Y,Y+Taille_perso)):
                Vu=True
        else:
            if (betweenL(Y,Rayon[1],Rayon[3]) and betweenL(Rayon[0],X,X+Taille_perso)) or (betweenL(Y+Taille_perso,Rayon[1],Rayon[3]) and betweenL(Rayon[0],X,X+Taille_perso)):
                Vu=True
        i=i+1
    if Vu:
        AlarmeON()

def Action():
    global Objet
    global canvas
    global Perso
    global Last_moov
    if Last_moov=="z":
        L=[canvas.coords(Perso)[0],canvas.coords(Perso)[1]-Taille_perso]
    elif Last_moov=="q":
        L=[canvas.coords(Perso)[0]-Taille_perso,canvas.coords(Perso)[1]]
    elif Last_moov=="s":
        L=[canvas.coords(Perso)[0],canvas.coords(Perso)[1]+Taille_perso]
    else:
        L=[canvas.coords(Perso)[0]+Taille_perso,canvas.coords(Perso)[1]]
    Recherche = False
    i=0
    while i<len(Objet) and not Recherche:
        if Objet[i][0]=="p":
            if Last_moov=="d" or Last_moov=="q":
                if (betweenL(canvas.coords(Objet[i][1])[0],L[0],L[0]+Taille_perso)) and (betweenL(L[1],canvas.coords(Objet[i][1])[1],canvas.coords(Objet[i][1])[3])):
                   Recherche = True
                   Type=Objet[i][0]
#            elif Last_moov=="q":
#                if (L[0]==canvas.coords(Objet[i][1])[0]) and (betweenL(L[1],canvas.coords(Objet[i][1])[1],canvas.coords(Objet[i][1])[3])):
#                   Recherche = True
#                   Type=Objet[i][0]
            else:
                if (betweenL(canvas.coords(Objet[i][1])[1],L[1],L[1]+Taille_perso)) and (betweenL(L[0],canvas.coords(Objet[i][1])[0],canvas.coords(Objet[i][1])[2])):
                   Recherche = True
                   Type=Objet[i][0]
        else:
            if canvas.coords(Objet[i][1])[0:2]==L:
                Recherche = True
                Type=Objet[i][0]
        i=i+1
    if Recherche:
        if Type=="a":
            AlarmeON()
#            info=canvas.create_text(Largeur_map//2,10,text="Vous activez l'alarme !")
#            canvas.after(3000,canvas.delete(info))
        elif Type=="c":
            Recup_cle(i-1)
#            info=canvas.create_text(Largeur_map//2,10,text="Vous récupérez une clé !")
#            canvas.after(3000,canvas.delete(info))
        elif Type=="p":
            Ouvrir_porte(i-1)
        elif Type=="t":
            TimeSlow(i-1)
#            info=canvas.create_text(Largeur_map//2,10,text="Le temps est ralenti !")
#            canvas.after(3000,canvas.delete(info))

def Recup_cle(i):
    global canvas
    global Objet
    global Zone_interdite
    global Inventaire
    global Aff_cle
    Inventaire[0]=Inventaire[0]+1
    indice=Objet[i][2]
    canvas.delete(Objet[i][1])
    Objet=Suppr_List(Objet,i)
    Zone_interdite=Suppr_List(Zone_interdite,indice)
    for j in range (len(Objet)):
        if Objet[j][0]!="a":
            if Objet[j][2]>indice:
                Objet[j][2]=Objet[j][2]-1
    Add_info("Vous récupérez une clé !")
    Aff_cle.set("Vous avez "+str(Inventaire[0])+" clé(s)")

def Ouvrir_porte(i):
    global canvas
    global Objet
    global Zone_interdite
    global Inventaire
    global Aff_cle
    if Inventaire[0]>0:
        Inventaire[0]=Inventaire[0]-1
        indice=Objet[i][2]
        canvas.delete(Objet[i][1])
        Objet=Suppr_List(Objet,i)
        Zone_interdite=Suppr_List(Zone_interdite,indice)
        for j in range (len(Objet)):
            if Objet[j][0]!="a":
                if Objet[j][2]>indice:
                    Objet[j][2]=Objet[j][2]-1
        Add_info("La porte s'ouvre !")
        Aff_cle.set("Vous avez "+str(Inventaire[0])+" clé(s)")

    else:
        Add_info("La porte est fermé à clé ...")

def TimeSlow(i):
    global canvas
    global Objet
    global Zone_interdite
    global Tps_mvt
    global Tps_slow
    global Temps_ralentit
    Tps_mvt=Tps_mvt*3
    Tps_slow=0
    Temps_ralentit=True
    indice=Objet[i][2]
    canvas.delete(Objet[i][1])
    Objet=Suppr_List(Objet,i)
    Zone_interdite=Suppr_List(Zone_interdite,indice)
    for j in range (len(Objet)):
        if Objet[j][0]!="a":
            if Objet[j][2]>indice:
                Objet[j][2]=Objet[j][2]-1
    Add_info("Le temps est ralentit !")

def teleport(i,j):
    global canvas
    global Perso
    global Teleporteur
    if j==1:
        anim_teleport(Perso,Teleporteur[i][3],Teleporteur[i][4])
        #canvas.coords(Perso,[Teleporteur[i][3],Teleporteur[i][4],Teleporteur[i][3]+Taille_perso,Teleporteur[i][4]+Taille_perso])
    elif j==2 and Teleporteur[i][0]==2:
        anim_teleport(Perso,Teleporteur[i][1],Teleporteur[i][2])
        #canvas.coords(Perso,[Teleporteur[i][1],Teleporteur[i][2],Teleporteur[i][1]+Taille_perso,Teleporteur[i][2]+Taille_perso])
    else:
        pass

def anim_teleport(objet,x,y):
    X,Y=canvas.coords(objet)[0],canvas.coords(objet)[1]
    Temps=[250,500,600,700,800,900,950,1000,1050,1100,1200,1300,1400,1500]
    L1=[X,Y,X+Taille_perso,Y+Taille_perso]
    L2=[X+5,Y+5,X+Taille_perso-5,Y+Taille_perso-5]
    for i in range (len(Temps)):
        if i%2==0:
            canvas.after(Temps[i], lambda cible=objet, coord=L2 : canvas.coords(cible,coord))
        else:
            canvas.after(Temps[i], lambda cible=objet, coord=L1 : canvas.coords(cible,coord))
        if i>=7:
            L1=[x,y,x+Taille_perso,y+Taille_perso]
            L2=[x+5,y+5,x+Taille_perso-5,y+Taille_perso-5]

def obstacle(x,y,Lx,Ly):
    global canvas
    global Zone_interdite
    canvas.create_rectangle(x,y,x+Lx,y+Ly,fill="black")
    Zone_interdite.append([x,x+Lx,y,y+Ly])

def Portail(x,y,taille,sens):
    global canvas
    global Objet
    global Zone_interdite
    if sens=="h":
        portail=canvas.create_rectangle(x,y,x+taille,y+10,fill="brown")
        Zone_interdite.append([x,x+taille,y,y+10])
    else:
        portail=canvas.create_rectangle(x,y,x+10,y+taille,fill="brown")
        Zone_interdite.append([x,x+10,y,y+taille])
    Objet.append(["p",portail,len(Zone_interdite)-1])

def Creation_alarme(x,y):
    global canvas
    global Objet
    global Zone_interdite
    alarme=canvas.create_rectangle(x,y,x+Taille_perso,y+Taille_perso,fill="brown")
    Zone_interdite.append([x,x+Taille_perso,y,y+Taille_perso])
    Objet.append(["a",alarme])

def Cle(x,y):
    global canvas
    global Objet
    global Zone_interdite
    cle=canvas.create_rectangle(x,y,x+Taille_perso,y+Taille_perso,fill="brown")
    Zone_interdite.append([x,x+Taille_perso,y,y+Taille_perso])
    Objet.append(["c",cle,len(Zone_interdite)-1])

def TimeSlower(x,y):
    global canvas
    global Objet
    global Zone_interdite
    TimeSlower=canvas.create_rectangle(x,y,x+Taille_perso,y+Taille_perso,fill="brown")
    Zone_interdite.append([x,x+Taille_perso,y,y+Taille_perso])
    Objet.append(["t",TimeSlower,len(Zone_interdite)-1])

def Plaque_tp(nb_sens,x1,y1,x2,y2):
    global canvas
    global Teleporteur
    canvas.create_rectangle(x1,y1,x1+Taille_perso,y1+Taille_perso,fill="green")
    canvas.create_rectangle(x2,y2,x2+Taille_perso,y2+Taille_perso,fill="green")
    Teleporteur.append([nb_sens,x1,y1,x2,y2])

def Creation_alarme2f(x1,y1,x2,y2):
    global canvas
    global Laser
    rayon=canvas.create_line(x1,y1,x2,y2,fill="red")
    Laser.append(["f",rayon])

def Creation_alarme2m(Type,x0,y0,l,P1,P2,dmouv):
    global canvas
    global Laser
    if Type=="h":
        rayon=canvas.create_line(x0,y0,x0+l,y0,fill="red")
    else:
        rayon=canvas.create_line(x0,y0,x0,y0+l,fill="red")
    Laser.append([Type,rayon,P1,P2,dmouv,1])

def Creation_garde(x0,y0,x1,y1,XD,YD,Phase,dmouv):
    global canvas
    global Info_garde
    global Vision
    Garde=canvas.create_rectangle(XD,YD,XD+Taille_perso,YD+Taille_perso,fill="red")
    V = Vision_garde(XD,YD,50,signe(dmouv))
    rotation(V,(XD+Taille_perso/2,YD+Taille_perso/2),-signe(dmouv)*(Phase-1)*n.pi/2)
    if dmouv<0:
        rotation(V,(XD+Taille_perso/2,YD+Taille_perso/2),n.pi)
    Info_garde.append([Garde,x0,y0,x1,y1,dmouv,Phase,V,50])
    Vision.append([canvas.coords(V)[0],canvas.coords(V)[1],canvas.coords(V)[4],canvas.coords(V)[5]])

def Creation_garde2(x0,y0,Phase,dt):
    Garde=canvas.create_rectangle(x0,y0,x0+Taille_perso,y0+Taille_perso,fill="red")
    V = Vision_garde(x0,y0,50,1)
    if dt==0:
        rotation(V,(x0+Taille_perso/2,y0+Taille_perso/2),-(Phase-1)*n.pi/2)
    Info_garde.append([Garde,x0,y0,1,-4,dt,Phase,V,50])
    Vision.append([canvas.coords(V)[0],canvas.coords(V)[1],canvas.coords(V)[4],canvas.coords(V)[5]])

def Mouvement_adverse():
    global fenetre
    global canvas
    global Info_garde
    global Vision
    global Alarme_active
    global Temps_ralentit
    global Tps_alarme
    global Tps_slow
    global Laser
    global testp
    global Tps_ecoule
    global Aff_Temps
    if Play:
        for i in range(len(Info_garde)):
            if Info_garde[i][4]<0:    #dmouv=0 --> Tourne sur lui-même
                if Info_garde[i][3]==abs(Info_garde[i][5])//100:
                    Info_garde[i][6]=Info_garde[i][6]+1
                    if Info_garde[i][6]==5:
                        Info_garde[i][6]=1
                    Reduire_visionr(i)
                    Info_garde[i][3]=1
                else:
                    Info_garde[i][3]=Info_garde[i][3]+1
            else:

                if Info_garde[i][6]==1:
                    if canvas.coords(Info_garde[i][0])[0]*signe(Info_garde[i][5])<Info_garde[i][signe1(Info_garde[i][5])]*signe(Info_garde[i][5]):
                        canvas.move(Info_garde[i][0],Info_garde[i][5],0)

                        if Restriction_mouvement(canvas.coords(Info_garde[i][7])[4],canvas.coords(Info_garde[i][7])[5]-10,"L"):
                            canvas.move(Info_garde[i][7],Info_garde[i][5],0)
                        else:
                            Info_garde[i][8]=Info_garde[i][8]-abs(Info_garde[i][5])
                            canvas.delete(Info_garde[i][7])
                            Info_garde[i][7]=Vision_garde(canvas.coords(Info_garde[i][0])[0]-Info_garde[i][5],canvas.coords(Info_garde[i][0])[1],Info_garde[i][8],signe(Info_garde[i][5]))
                            canvas.move(Info_garde[i][7],Info_garde[i][5],0)

                    else:
                        Info_garde[i][6]=2
                        Reduire_vision(i)

                if Info_garde[i][6]==2:
                    if canvas.coords(Info_garde[i][0])[1]<Info_garde[i][4]:
                        canvas.move(Info_garde[i][0],0,abs(Info_garde[i][5]))

                        if Restriction_mouvement(canvas.coords(Info_garde[i][7])[4]+signe(Info_garde[i][5])*10,canvas.coords(Info_garde[i][7])[5],"L"):
                            canvas.move(Info_garde[i][7],0,abs(Info_garde[i][5]))
                        else:
                            Info_garde[i][8]=Info_garde[i][8]-abs(Info_garde[i][5])
                            canvas.delete(Info_garde[i][7])
                            Info_garde[i][7]=Vision_garde(canvas.coords(Info_garde[i][0])[0],canvas.coords(Info_garde[i][0])[1]+abs(Info_garde[i][5]),Info_garde[i][8],signe(Info_garde[i][5]))
                            Centre=((canvas.coords(Info_garde[i][0])[0]+canvas.coords(Info_garde[i][0])[2])/2,(canvas.coords(Info_garde[i][0])[1]+canvas.coords(Info_garde[i][0])[3])/2)
                            rotation(Info_garde[i][7],Centre,-signe(Info_garde[i][5])*n.pi/2) # Angle = Info_garde[i][6]-1
                            canvas.move(Info_garde[i][7],Info_garde[i][5],0)

                    else:
                        Info_garde[i][6]=3
                        Reduire_vision(i)

                if Info_garde[i][6]==3:
                    if canvas.coords(Info_garde[i][0])[0]*signe(Info_garde[i][5])>Info_garde[i][signe3(Info_garde[i][5])]*signe(Info_garde[i][5]):
                        canvas.move(Info_garde[i][0],-Info_garde[i][5],0)

                        if Restriction_mouvement(canvas.coords(Info_garde[i][7])[4],canvas.coords(Info_garde[i][7])[5]+10,"L"):
                            canvas.move(Info_garde[i][7],-Info_garde[i][5],0)
                        else:
                            Info_garde[i][8]=Info_garde[i][8]-abs(Info_garde[i][5])
                            canvas.delete(Info_garde[i][7])
                            Info_garde[i][7]=Vision_garde(canvas.coords(Info_garde[i][0])[0]-Info_garde[i][5],canvas.coords(Info_garde[i][0])[1],Info_garde[i][8],signe(Info_garde[i][5]))
                            Centre=((canvas.coords(Info_garde[i][0])[0]+canvas.coords(Info_garde[i][0])[2])/2,(canvas.coords(Info_garde[i][0])[1]+canvas.coords(Info_garde[i][0])[3])/2)
                            rotation(Info_garde[i][7],Centre,n.pi)
                            canvas.move(Info_garde[i][7],-Info_garde[i][5],0)

                    else:
                        Info_garde[i][6]=4
                        Reduire_vision(i)

                if Info_garde[i][6]==4:
                    if canvas.coords(Info_garde[i][0])[1]>Info_garde[i][2]:
                        canvas.move(Info_garde[i][0],0,-abs(Info_garde[i][5]))

                        if Restriction_mouvement(canvas.coords(Info_garde[i][7])[4]-signe(Info_garde[i][5])*10,canvas.coords(Info_garde[i][7])[5],"L"):
                            canvas.move(Info_garde[i][7],0,-abs(Info_garde[i][5]))
                        else:
                            Info_garde[i][8]=Info_garde[i][8]-abs(Info_garde[i][5])
                            canvas.delete(Info_garde[i][7])
                            Info_garde[i][7]=Vision_garde(canvas.coords(Info_garde[i][0])[0],canvas.coords(Info_garde[i][0])[1]+abs(Info_garde[i][5]),Info_garde[i][8],signe(Info_garde[i][5]))
                            Centre=((canvas.coords(Info_garde[i][0])[0]+canvas.coords(Info_garde[i][0])[2])/2,(canvas.coords(Info_garde[i][0])[1]+canvas.coords(Info_garde[i][0])[3])/2)
                            rotation(Info_garde[i][7],Centre,signe(Info_garde[i][5])*n.pi/2)
                            canvas.move(Info_garde[i][7],-Info_garde[i][5],0)

                    else:
                        Info_garde[i][6]=1
                        Reduire_vision(i)

            Vision[i]=[canvas.coords(Info_garde[i][0])[0]+Add_Visionx(Info_garde[i][6],Info_garde[i][5]),canvas.coords(Info_garde[i][0])[1]+Add_Visiony(Info_garde[i][6],Info_garde[i][5]),canvas.coords(Info_garde[i][7])[4],canvas.coords(Info_garde[i][7])[5]]
        if Detection():
            Game_over()
        if not Alarme_active or (Alarme_active and (-1)**testp>0):
            for i in range (len(Laser)):
                if Laser[i][0]=="h":
                    canvas.move(Laser[i][1],0,Laser[i][4]*(-1)**Laser[i][5])
                    if canvas.coords(Laser[i][1])[1]<=Laser[i][2]:
                        Laser[i][5]=2
                    elif canvas.coords(Laser[i][1])[1]>=Laser[i][3]:
                        Laser[i][5]=1
                elif Laser[i][0]=="v":
                    canvas.move(Laser[i][1],Laser[i][4]*(-1)**Laser[i][5],0)
                    if canvas.coords(Laser[i][1])[0]<=Laser[i][2]:
                        Laser[i][5]=2
                    elif canvas.coords(Laser[i][1])[0]>=Laser[i][3]:
                        Laser[i][5]=1
        Detection_Laser()
        #print(Info_garde[i][9])
        if Alarme_active:
            testp=testp+1
            Tps_alarme=Tps_alarme+Tps_mvt
            if Tps_alarme>10000:
                testp=0
                AlarmeOFF()
        if Temps_ralentit:
            Tps_slow=Tps_slow+Tps_mvt
            if Tps_slow>10000:
                SlowtimeOFF()
        if not Alarme_active:
            Tps_ecoule=Tps_ecoule+Tps_mvt
            Aff_Temps.set("Temps : "+str(Tps_ecoule/1000))
        elif Alarme_active and (-1)**testp>0:
            Tps_ecoule=Tps_ecoule+2*Tps_mvt
            Aff_Temps.set("Temps : "+str(Tps_ecoule/1000))
        fenetre.after(Tps_mvt,Mouvement_adverse)

def Detection():
    global canvas
    global Vision
    global Perso
    X=[canvas.coords(Perso)[0],canvas.coords(Perso)[0],canvas.coords(Perso)[2],canvas.coords(Perso)[2]]
    Y=[canvas.coords(Perso)[1],canvas.coords(Perso)[3],canvas.coords(Perso)[1],canvas.coords(Perso)[3]]
    i=0
    Vu= False
    while i<len(Vision) and not Vu:
        for j in range (4):
            if betweenL(X[j],Vision[i][0],Vision[i][2]) and betweenL(Y[j],Vision[i][1],Vision[i][3]):
                Vu = True
        i=i+1
    return Vu

def Game_over():
    global fenetre
    global canvas
    global Play
    Play=False
    canvas.create_text(740,525,text="Game over",font="Arial 40",fill="Red")
    fenetre.after(2000,fenGO)

def Victoire():
    global fenetre
    global canvas
    global Play
    global Map_dispo
    global Niveau
    Play=False
    if Niveau==Map_dispo:
        Map_dispo=Map_dispo+1
    canvas.create_text(740,525,text="Niveau terminé !",font="Arial 40",fill="Red")
    fenetre.after(2000,fenW)

def AlarmeON():
    global Alarme_active
    global Tps_mvt
    global Tps_alarme
    global Son_alarme
    Tps_alarme=0
    if not Alarme_active:
        Alarme_active=True
        Tps_mvt=Tps_mvt//2
        Add_info("L'alarme est activée !")
        Son_alarme.play()

def AlarmeOFF():
    global Alarme_active
    global Tps_mvt
    Alarme_active=False
    Tps_mvt=Tps_mvt*2

def SlowtimeOFF():
    global Temps_ralentit
    global Tps_mvt
    Temps_ralentit=False
    Tps_mvt=Tps_mvt//3

# # Caractéristiques générales du canvas # #

Longueur_map =1440
Largeur_map=1050
Taille_perso=20
Taille_vision=50
Pente_cone=Taille_perso/(4*Taille_vision)

# # Programme # #
Menu_principal()


from typing import List

class UnionFind:
    def __init__(self, n: int) -> None:
        self.uf = list(range(n))
        self.components = n

    def find(self, i: int) -> int:
        if self.uf[i] != i:
            self.uf[i] = self.find(self.uf[i])
        return self.uf[i]

    def union(self, a: int, b: int) -> None:
        parent_a = self.find(a)
        parent_b = self.find(b)
        if parent_a != parent_b:
            self.uf[parent_a] = parent_b
            self.components -= 1

class Solution:
    def findCircleNum(self, M: List[List[int]]) -> int:
        uf = UnionFind(len(M))
        for i in range(len(M)):
            row = M[i]
            for j in range(i + 1, len(row)):
                value = row[j]
                if value == 1:
                    uf.union(i, j)
        return uf.components


#
# Tests for Ai (2020) Enertech parameter set loads
#
import pybamm
import unittest
import os

class TestAi2020(unittest.TestCase):
    def test_load_params(self):
        Li_plating = pybamm.ParameterValues({}).read_parameters_csv(
            pybamm.get_parameters_filepath(
                "input/parameters/lithium_ion/lithium_platings/okane2020_Li_plating/"
                "parameters.csv"
            )
        )
        self.assertEqual(
            Li_plating["Lithium metal partial molar volume [m3.mol-1]"],
            "1.30E-05"
        )

    def test_functions(self):
        root = pybamm.root_dir()
        param = pybamm.ParameterValues(chemistry=pybamm.parameter_sets.Chen2020_plating)
        T = pybamm.Scalar(298.15)

        p = "pybamm/input/parameters/lithium_ion/lithium_platings/okane2020_Li_plating/"
        k_path = os.path.join(root, p)

        fun_test = {
            "plating_exchange_current_density_OKane2020.py": ([1e3, 1e4, T], 9.6485e-3),
            "stripping_exchange_current_density_OKane2020.py": (
                [1e3, 1e4, T],
                9.6485e-2
            ),
        }

        for name, value in fun_test.items():
            fun = pybamm.load_function(os.path.join(k_path, name))
            self.assertAlmostEqual(param.evaluate(fun(*value[0])), value[1], places=4)

if __name__ == "__main__":
    print("Add -v for more debug output")
    import sys

    if "-v" in sys.argv:
        debug = True
    pybamm.settings.debug_mode = True
    unittest.main()


import torch
import torch.nn as nn
import torch.nn.functional as F
import math

from .block import TopDownBlock, BottomUpBlock

from vistem.modeling.backbone import Backbone
from vistem.modeling.layers import Conv2d, get_norm
from vistem.utils import weight_init
from vistem.structures import ShapeSpec

__all__ = ['BiFPNBase']

class BiFPNBase(Backbone):
    def __init__(self, bottom_up, top_block, out_channels, num_layers, norm='BN', fuse_type='fast_norm'):
        super().__init__()

        self.bottom_up = bottom_up
        assert isinstance(bottom_up, Backbone)

        self.top_block = top_block
        assert top_block, 'Top-Block in BiFPN should be callable functions.'

        in_channels = top_block.out_channels
        out_features = top_block.out_features

        td_blocks = []
        bu_blocks = []
        for _ in range(num_layers):
            td_blocks.append(TopDownBlock(in_channels, out_channels, norm=norm, fuse_type=fuse_type))
            bu_blocks.append(BottomUpBlock(in_channels, out_channels, norm=norm, fuse_type=fuse_type))
            in_channels = {k:out_channels for k in in_channels.keys()}

        self.num_layers = num_layers
        self.td_blocks = nn.ModuleList(td_blocks)
        self.bu_blocks = nn.ModuleList(bu_blocks)

        # weight_init.c2_xavier_fill(lateral_conv)
        # weight_init.c2_xavier_fill(output_conv)

        in_features = top_block.in_features
        out_feature_strides = [bottom_up.out_feature_strides[f] for f in in_features]
        for _ in range(top_block.num_block):
            s = out_feature_strides[-1]
            out_feature_strides.append(2*s)
        _assert_strides_are_log2_contiguous(out_feature_strides)

        self._out_features = top_block.out_features
        self._out_feature_channels = {k: out_channels for k in self._out_features}
        self._out_feature_strides = dict(zip(self._out_features, out_feature_strides))
        self._size_divisibility = out_feature_strides[-1]

    @property
    def size_divisibility(self):
        return self._size_divisibility

    def forward(self, x):
        bottom_up_features = self.bottom_up(x)
        x = self.top_block(bottom_up_features)

        for td_block, bu_block in zip(self.td_blocks, self.bu_blocks):
            td_nodes = td_block(x)
            x = bu_block([x, td_nodes])

        return x

    def output_shape(self):
        return {
            name: ShapeSpec(
                channels=self._out_feature_channels[name], stride=self._out_feature_strides[name]
            )
            for name in self._out_features
        }

def _assert_strides_are_log2_contiguous(strides):
    for i, stride in enumerate(strides[1:], 1):
        assert stride == 2 * strides[i - 1], f"Strides {stride} {strides[i - 1]} are not log2 contiguous"


import urllib.request
import re
def imageCrawler(url,topath):
    headers = {
        "User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36"
    }
    req = urllib.request.Request(url,headers=headers)
    response = urllib.request.urlopen(req)
    HtmlStr = response.read().decode("utf-8")
    #with open( r"E:\CX.PY\爬虫\file\yhd.html","wb")as f:
     #   f.write(HtmlStr)

   #pat = r"<"img" style="position: relative" defaultFlag="0" id="pdlink1_10502820097" parentId=0 pmId="0" isSnapProduct="0" isOverSea="0" isGrouponProv="0" grouponId="0" grouponType="0"(multiAreaStock="99" stockStatusMonitor="1" isOTCorRX="0" specialBusinessCate="0" isReserve="0"href="//item.yhd.com/1664645450.html" target="_blank" isSeiralCombine="0")|(multiAreaStock="0" stockStatusMonitor="0" isOTCorRX="0" specialBusinessCate="0" isReserve="0"href="//item.yhd.com/17970273482.html" target="_blank" isSeiralCombine="0")(.*?)target="_blank">"
   # re_image = re.compile(pat)
    #imageList = re_image.findall(HtmlStr)
    #print(imageList)
url = r"http://search.yhd.com/c0-0-1003302/"
topath = r"E:\CX.PY\爬虫\file"
imageCrawler(url,topath)

#正则有问题

爬虫/爬虫/爬虫练习.py


import functools

import click
from click import Context, HelpFormatter
from dbt.cli.options import MultiOption

# define common parameters
project_path = click.option(
    "--project-path",
    type=click.Path(exists=True),
    default=".",
    help="The path to the dbt project to operate on. Defaults to the current directory.",
)

project_paths = click.option(
    "--project-paths",
    cls=MultiOption,
    multiple=True,
    type=tuple,
    default=None,
    help="The paths to the set of dbt projects to connect. Must supply 2+ paths.",
)

projects_dir = click.option(
    "--projects-dir",
    type=click.Path(exists=True),
    default=None,
    help="The path to a directory containing multiple dbt projects. Directory must contain 2+ projects.",
)

exclude_projects = click.option(
    "--exclude-projects",
    "-e",
    cls=MultiOption,
    multiple=True,
    type=tuple,
    default=None,
    help="The set of dbt projects to exclude from the operation when using the --projects-dir option.",
)

create_path = click.option(
    "--create-path",
    type=click.Path(exists=False),
    default=None,
    help="The path to create the new dbt project. Defaults to the name argument supplied.",
)

exclude = click.option(
    "--exclude",
    "-e",
    cls=MultiOption,
    multiple=True,
    type=tuple,
    default=None,
    help="The dbt selection syntax specifying the resources to exclude in the operation",
)

group_yml_path = click.option(
    "--group-yml-path",
    type=click.Path(exists=False),
    help="An optional path to store the new group YAML definition.",
)

select = click.option(
    "--select",
    "-s",
    cls=MultiOption,
    multiple=True,
    type=tuple,
    default=None,
    help="The dbt selection syntax specifying the resources to include in the operation",
)

selector = click.option(
    "--selector",
    cls=MultiOption,
    multiple=True,
    type=tuple,
    default=None,
    help="The name(s) of the YML selector specifying the resources to include in the operation",
)

owner_name = click.option(
    "--owner-name",
    help="The group Owner's name.",
)

owner_email = click.option(
    "--owner-email",
    help="The group Owner's email address.",
)

owner_properties = click.option(
    "--owner-properties",
    help="Additional properties to assign to a group Owner.",
)

read_catalog = click.option(
    "--read-catalog",
    "-r",
    is_flag=True,
    envvar="DBT_MESHIFY_READ_CATALOG",
    help="Skips the dbt docs generate step and reads the local catalog.json file.",
)

latest = click.option(
    "--latest",
    "-l",
    is_flag=True,
    help="Makes the newest version the latest version when incrementing model versions",
)

def owner(func):
    """Add click options and argument validation for creating Owner objects."""

    @functools.wraps(func)
    def wrapper_decorator(*args, **kwargs):
        if kwargs.get('owner_name') is None and kwargs.get('owner_email') is None:
            raise click.UsageError(
                "Groups require an Owner to be defined using --owner-name and/or --owner-email."
            )
        return func(*args, **kwargs)

    return wrapper_decorator

class TupleCompatibleCommand(click.Command):
    """
    A Click Command with a custom formatter that adds metavar options after all arguments.
    This is valuable for commands that use tuple-type options, since type types will eat
    arguments.
    """

    def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:
        pieces = self.collect_usage_pieces(ctx)
        pieces = pieces[1:] + [pieces[0]]
        formatter.write_usage(ctx.command_path, " ".join(pieces))


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

import ast
from io import open
import re
import sys
import subprocess
from setuptools import Command, setup, find_packages

_version_re = re.compile(r"__version__\s+=\s+(.*)")

with open("urestapi/__init__.py", "rb") as f:
    version = str(
        ast.literal_eval(_version_re.search(f.read().decode("utf-8")).group(1))
    )

def open_file(filename):
    """Open and read the file *filename*."""
    with open(filename, "r") as f:
        return f.read()

readme = open_file("README.md")

install_requirements = [
    "click >= 4.1",
    "Pygments >= 1.6",
    "prompt_toolkit>=3.0.8", # 2.0.0,<2.1.0",
    "cli_helpers[styles] >= 1.0.1",
    "PyJWT >= 2.4.0",
    "requests",
    "urllib3 >=1.21.1",
]

setup(
    name="urestapi",
    author="vkumar",
    author_email="vibhor.aim@gmail.com",
    license="BSD",
    version=version,
    packages=find_packages(),
    package_data={"urestapi": ["urestapirc", "AUTHORS"]},
    description="Uptycs Rest API call " "highlighting.",
    long_description=readme,
    long_description_content_type="text/markdown",
    install_requires=install_requirements,
    entry_points={
        "console_scripts": ["urestapi = urestapi.main:cli"],
        "distutils.commands": ["lint = tasks:lint", "test = tasks:test"],
    },
    classifiers=[
        "Intended Audience :: Developers",
        "License :: OSI Approved :: BSD License",
        "Operating System :: Unix",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: SQL",
        "Topic :: Database",
        "Topic :: Database :: Front-Ends",
        "Topic :: Software Development",
        "Topic :: Software Development :: Libraries :: Python Modules",
    ],
)


# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# Orbital Mechanics & Dynamics Software Collection
# Author:   Steven Anderson
# Created:  JUL 2022
# Brief:    This script is to plot a satellite's orbit
#
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

#fig = plt.figure()
#ax = fig.gca(projection='3d')

# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)

# plot in wireframe
#ax.plot_wireframe(x, y, z, color="r")

# plot as surface (alpha controls opacity)
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(x, y, z, color="b", alpha=0.6)
point = np.array([1,1,1])
ax.scatter(point[0],point[1],point[2],'black')

plt.show()


import os
from flask import Flask, request, abort, jsonify
import face_recognition
import json
from werkzeug.utils import secure_filename
import numpy as np

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
app.debug = True

face_encodes = []
data_dir = "./data"

# You can change this to any folder on your system
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/v1/post_face_auth', methods=['POST'])
def post_face_auth():

    if "file" not in request.files:
        return json.dumps({"code": "1", "message": "no file"})

    file = request.files["file"]
    if file.filename == '':
        return json.dumps({"code": "2", "message": "no filename"})

    if not file or not allowed_file(file.filename):
        return json.dumps({"code": "3", "message": "no support image"})

    filename = secure_filename(file.filename)
    filename = os.path.join(data_dir, filename)
    file.save(filename)
    encs = get_face_encoding(filename)
    os.remove(filename)
    if len(encs) == 0:
        return json.dumps({"code": "4", "message": "no face"})

    if len(face_encodes) == 0:
        return json.dumps({"code": "5", "message": "no add face"})
    # See how far apart the test image is from the known faces
    face_distances = face_recognition.face_distance(np.array(face_encodes), encs[0])
    for i, face_distance in enumerate(face_distances):
        if face_distance < 0.5:
            return json.dumps({"code": "0", "message": str(face_distance)})

    return json.dumps({"code": "6", "message": "auth failed"})

@app.route('/v1/add-face-encodings', methods=['POST'])
def post_face_encodings():

    if "file" not in request.files:
        return json.dumps({"code": "1", "message": "no file"})

    file = request.files["file"]
    if file.filename == '':
        return json.dumps({"code": "2", "message": "no filename"})

    if not file or not allowed_file(file.filename):
        return json.dumps({"code": "3", "message": "no support image"})

    filename = secure_filename(file.filename)
    filename = os.path.join(data_dir, filename)
    file.save(filename)
    encs = get_face_encoding(filename)
    os.remove(filename)
    if len(encs) == 0:
        return json.dumps({"code": "4", "message": "no face"})
    for enc in encs:
        face_encodes.append(enc)
    return json.dumps({"code": "0", "message": ""})

def get_face_encoding(file):
    image = face_recognition.load_image_file(file)
    encoding = face_recognition.face_encodings(image)
    return encoding

if __name__ == '__main__':
    if not os.path.exists(data_dir):
        os.makedirs(data_dir)
    app.run(debug=True, host='0.0.0.0')


from django.core.validators import MaxValueValidator
from django.core.validators import MinValueValidator
from django.db import models
from django.utils import timezone

from phonenumber_field.modelfields import PhoneNumberField

from location.models import Location

class OrderQuerySet(models.QuerySet):
    """Order model custom queryset."""

    def calculate_order_amount(self):
        """Calculates the total amount of the order."""
        return self.annotate(
            order_amount=models.Sum(
                models.F('order_products__cost'),
                output_field=models.DecimalField(),
            ),
        )

    def only_unprocessed(self):
        """Returns only unprocessed orders."""
        return self.calculate_order_amount().exclude(status='processed')

    def with_coords_from_cache(self):
        """Get the coordinates from the location table."""
        location = Location.objects.filter(address=models.OuterRef('address'))
        return self.annotate(
            lat=models.Subquery(
                queryset=location.values('lat'),
                output_field=models.FloatField(),
            ),
            lon=models.Subquery(
                queryset=location.values('lon'),
                output_field=models.FloatField(),
            ),
        )

class Order(models.Model):
    """Order model."""

    PROCESSED = 'processed'
    UNPROCESSED = 'unprocessed'
    ORDER_STATUS_CHOICES = [
        (PROCESSED, 'Обработанный'),
        (UNPROCESSED, 'Необработанный'),
    ]

    CASH = 'cash'
    CARD = 'card'
    NOT_SELECTED = 'not_selected'
    PAYMENT_METHOD_CHOICES = [
        (CASH, 'Наличные'),
        (CARD, 'Карта'),
        (NOT_SELECTED, 'Не выбрано'),
    ]

    firstname = models.CharField('Имя', max_length=20)
    lastname = models.CharField('Фамилия', max_length=20)
    phonenumber = PhoneNumberField('Номер телефона', max_length=15, db_index=True)
    address = models.CharField('Адрес доставки', max_length=200, db_index=True)
    status = models.CharField(
        'Статус',
        choices=ORDER_STATUS_CHOICES,
        default=UNPROCESSED,
        max_length=11,
        db_index=True,
    )
    comment = models.TextField('Комментарий', max_length=200, blank=True)
    registrated_at = models.DateTimeField('Дата регистрации', default=timezone.now, db_index=True)
    called_at = models.DateTimeField('Дата звонка', null=True, blank=True, db_index=True)
    delivered_at = models.DateTimeField('Дата доставки', null=True, blank=True, db_index=True)
    payment_method = models.CharField(
        'Способ оплаты',
        choices=PAYMENT_METHOD_CHOICES,
        default=NOT_SELECTED,
        max_length=15,
        db_index=True,
    )

    restaurant = models.ForeignKey(
        'Restaurant',
        on_delete=models.SET_NULL,
        verbose_name='Забрать в ресторане',
        related_name='orders',
        null=True,
        blank=True,
    )

    objects = OrderQuerySet.as_manager()

    class Meta:
        verbose_name = 'заказ'
        verbose_name_plural = 'заказы'

    def __str__(self):
        return f'{self.firstname} {self.lastname}'

class OrderProduct(models.Model):
    """Order product model."""

    order = models.ForeignKey(
        Order,
        on_delete=models.CASCADE,
        verbose_name='Заказ',
        related_name='order_products',
    )

    product = models.ForeignKey(
        'Product',
        on_delete=models.CASCADE,
        verbose_name='Продукт',
        related_name='order_products',
    )

    quantity = models.PositiveIntegerField('Количество', validators=[MaxValueValidator(50)])
    cost = models.DecimalField(
        'Стоимость',
        max_digits=8,
        decimal_places=2,
        validators=[MinValueValidator(0)],
    )

    class Meta:
        verbose_name = 'товар в заказе'
        verbose_name_plural = 'товары в заказе'

    def __str__(self):
        return f'{self.product.name} {self.quantity}'


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

from PIL import Image

pickle_in = open("classifier.pkl","rb")
classifier=pickle.load(pickle_in)

def welcome():
    return "Welcome All"

def predict_impact(opened_by, location, ID_caller, Category_id, ID):
    """Let's find the prediction
    This is using docstrings for specifications.
    ---
    parameters:
      - name: opened_by
        in: query
        type: number
        required: true
      - name: location
        in: query
        type: number
        required: true
      - name: ID_caller
        in: query
        type: number
        required: true
      - name: Category_id
        in: query
        type: number
        required: true
      -name: ID
        in: query
        type: number
        required: true
    responses:
        200:
            description: The output values

    """
    prediction = classifier.predict([[opened_by, location, ID_caller, Category_id, ID]])
    print(prediction)
    return prediction

def main():

    html_temp ="""

Incident Impact Prediction ML App

    """
    st.markdown(html_temp, unsafe_allow_html=True)

    opened_by= st.text_input("Opened_By","Type Here")
    location = st.text_input("Location","Type Here")
    ID_caller = st.text_input("ID_Caller","Type Here")
    Category_id = st.text_input("Category_ID","Type Here")
    ID = st.text_input("ID","Type Here")
    result=""
    if st.button("Predict"):
        result=predict_impact(opened_by,location,ID_caller,Category_id,ID)
    st.success('The output is {}'.format(result))

if __name__ == '__main__':
    main()


from typing import (
    Optional,
    List
)

from qgis.PyQt.QtCore import (
    QObject,
    pyqtSignal
)

from qgis.core import QgsMapLayer

from kart.utils import setting, setSetting

from ..kartapi import (
    Repository,
    KartException
)

class RepoManager(QObject):
    """
    Manages the local repositories
    """

    _instance: Optional['RepoManager'] = None

    repo_added = pyqtSignal(Repository)
    repo_removed = pyqtSignal(Repository)

    @classmethod
    def instance(cls) -> 'RepoManager':
        """
        Returns the repo manager instance
        """
        if not RepoManager._instance:
            RepoManager._instance = RepoManager()

        return RepoManager._instance

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

        self._repos: List[Repository] = []

        self.read_repos_from_settings()

    def read_repos_from_settings(self):
        """
        Reads repos from user settings
        """
        s = setting("repos")
        if s is None:
            self._repos = []
        else:
            self._repos = []
            paths = s.split("|")
            for path in paths:
                repo = Repository(path)
                if repo.isInitialized():
                    self._repos.append(repo)
                    self.repo_added.emit(repo)

    def save_repos_to_settings(self):
        """
        Saves repos to user settings
        """
        s = "|".join([repo.path for repo in self._repos])
        setSetting("repos", s)

    def add_repo(self, repo: Repository):
        """
        Adds a repository to the manager
        """
        self._repos.append(repo)
        self.save_repos_to_settings()
        self.repo_added.emit(repo)

    def remove_repo(self, repo: Repository):
        """
        Removes a repository from the manager
        """
        for r in self._repos:
            if r.path == repo.path:
                self._repos.remove(r)
                break
        self.save_repos_to_settings()
        self.repo_removed.emit(repo)

    def repos(self) -> List[Repository]:
        """
        Returns the list of known repositories
        """
        return self._repos

    def repo_for_layer(self, layer: QgsMapLayer) -> Optional[Repository]:
        """
        Returns the repo matching a layer, or None if not found
        """
        try:
            for repo in self._repos:
                if repo.layerBelongsToRepo(layer):
                    return repo
        except KartException:
            pass

        return None


import torch

import pickle
import gensim
from create_vocab import Vocabulary, create_vocab

model_config = {
    #'gpu': 1,
    'npu': 0,
    '<PAD>': 0,
    '<SOS>': 1,
    '<EOS>': 2,
    '<UNK>': 3,
    'n_layers': 2,
    'dropout': 0.2,
    'output_dim': 6,  # number of classes
    'hidden_dim': 500,
    'n_epochs': 10000, #45000
    'batch_size': 128,  # carefully chosen
    'embedding_dim': 200,  # 50/100/200/300
    'bidirectional': True,
    'learning_rate': 0.0001,
    'model_code': 'bi_lstm_2_layer',
    'max_sequence_length': 20,
    'embeddings_dir': './inputs/data_url_0/t2e/embeddings/'
}

from utils import generate_word_embeddings

def set_dynamic_hparams():
    try:

        with open('./inputs/data_url_0/t2e/vocab.pkl', 'rb') as f:
            vocab = pickle.load(f)
    except FileNotFoundError as e:
        vocab = create_vocab()
        generate_word_embeddings(vocab)

    model_config['vocab_size'] = vocab.size
    model_config['vocab_path'] = 'vocab.pkl'
    return model_config

model_config = set_dynamic_hparams()


def bubble_sort(a):
    for j  in range (len(a)):
        for i in range(len(a)):
            if i < len(a)-1 :
                if a[i]>a[i+1]:
                    a[i],a[i+1]=a[i+1],a[i]
                else:
                    i+=1
arr = []
n = int(input())
for i in range(n):
    m = int(input())
    arr.append(m)
bubble_sort(arr)
for k in range(len(arr)):
    print(arr[k])
"""
i = 0
a = [0,5,6,4,1,155]
for j  in range (len(a)):
    for i in range(len(a)):
        if i < len(a)-1 :
            if a[i]>a[i+1]:
                a[i],a[i+1]=a[i+1],a[i]
            else:
                i+=1
print(a)
"""


import torch
import math
import numpy as np

#########################
### Design Parameters ###
#########################
n = 100 # amount of antenna elements
m = 6  # dimension of our state space

m1x_0 = torch.ones(m, 1)
m1x_0 = torch.transpose(torch.tensor([[2.5, -9.1, 1.5, 0.01, 0.97, 0]], dtype=torch.float), 0, 1)
P_0 = m1x_0 + torch.transpose(torch.tensor([np.random.normal(0, [0.5**2, 0.5**2, 0.01**2, 0.01**2/10, 0.97**2/10, 0])], dtype=torch.float), 0, 1)
m2x_0 = torch.zeros(m, m)
#P_0 = P_0[None, :]

T = 20  # Amount of timesteps
T_test = 20
lmb = 0.010714285714286  # Wavelength
Dmin = lmb/(2*math.pi)

########################
### Model Parameters ###
########################
tau = 1  # temporal step

A = torch.eye(6)
A[0:3, 3:6] = torch.mul(torch.eye(3), tau)  # State Transition Matrix

B = torch.zeros(3, m)
B[0:3, 0:3] = torch.eye(3)

# Noise Parameters
Qx = torch.tensor([[0.03**2,  0, 0], [0, 0.03**2, 0], [0,  0, 0]])
sigma_r_mod = 0.349065850398866  # noise standard deviation in radians (corresponds to 20°)

# Noise Matrices
Q_aux = torch.block_diag(torch.mul(Qx, pow(tau, 2)/2), torch.mul(Qx, pow(tau, 2)/2))  # auxiliary matrix to define transition covariance matrix
Q_mod = torch.block_diag(torch.mul(Qx, pow(tau, 3)/3), torch.mul(Qx, tau))
Q_mod[3:6, 0:3] = Q_aux[0:3, 0:3]
Q_mod[0:3, 3:6] = Q_aux[0:3, 0:3]  # Finalized transition covariance matrix

R_mod = sigma_r_mod * torch.eye(n)  # Observation covariance matrix

#########################
### Antenna positions ###
#########################

qn = torch.zeros(n, 3)  # Antenna positions
dqn = 0.005357142857143  # distance between individual array elements
sqrtn = math.sqrt(n)
for i in range(n):
    qn[i][2] = dqn * (i % sqrtn)
    qn[i][1] = dqn * math.trunc(i / sqrtn)

Dmax = 2*(19*dqn*math.sqrt(2)/2)**2/lmb  # Maximum Near-Field distance ("sqrtn-1" changed to 19 to generate area of points similar to other paper
q0 = torch.tensor([0, (math.sqrt(n)-1)/2*dqn, (math.sqrt(n)-1)/2*dqn])  # Reference position


# -*- coding: utf-8 -*-
"""
Created on Wed Jun 27 00:48:07 2018

@author: Tareq
"""
'''
- two ways of creating dataframe 1. using the dataframe syntax and read_csv. read_excel
- line is the default graph type for the plot method
- tareq.j@metroc.ca
'''

import os
os.chdir(r'C:\Users\mfatemeh\Desktop\python')

import pandas as pd
import numpy as np
from sklearn import preprocessing

#reading excel
file1=pd.read_excel('scimagojr-3.xlsx',sheet_name='Sheet1', index_col=0, na_values=['NA']) # we use col=0 as the index
file1.head()

file1.loc[[1,2,3,4,5],['Country']]
file1.loc[[5],['Country']] # reading an specific row with specif column

#writing to excel
df_out = pd.DataFrame([('string1', 1),('string2', 2),('string3', 3)],
                       columns=['Name', 'Value'])
df_out

df_out.to_excel('tmp.xlsx')

pd.read_excel('tmp.xlsx')

pd.read_excel('tmp.xlsx', dtype={'Name':str, 'Value':float}) # not supported in my lap top

pd.read_excel('tmp.xlsx', converters={'Name':str, 'Value':float}) #since above does not work

pd.read_excel('tmp.xlsx', na_values=['string1', 'string2']) # we specifi any string we want as na_value

#skipping rows with comment
df = pd.DataFrame({'a': ['1', '2', '4'], 'b': ['#2', '#3', '#5']})
df.to_excel('tmp2.xlsx', index=False) #we don't want to have indexes
pd.read_excel('tmp2.xlsx')
pd.read_excel('tmp2.xlsx', comment='#') # we specify that the string after hash is comment even the third column(if there was any)

df = pd.DataFrame({'a': ['1', '2', '4'], 'b': ['#2', '#3', '#5'], 'c': ['1', '2', '4'], 'd': ['#2', '#3', '#5']})
df.to_excel('tmp2.xlsx', index=False) #we don't want to have indexes
pd.read_excel('tmp2.xlsx')
pd.read_excel('tmp2.xlsx', comment='#')

df = pd.DataFrame({'a': ['#1', '#2', '#4'], 'b': ['2', '3', '5']})
df.to_excel('tmp2.xlsx', index=False)
pd.read_excel('tmp2.xlsx', comment='#') #everything after hash key in one row is ignored

#--------------------------------
#Plotting

#Matplotlib is the whole package; matplotlib.pyplot is a module in matplotlib;
#and pylab is a module that gets installed alongside matplotlib.

import matplotlib.pyplot as plt

plt.interactive(False)#interactive mode is off, you have to call plt.show() explicitly to pop up figure window.

x = np.linspace(-2, 2, 100) #creating 100 values between -2 and 2

plt.plot(x, x, label='linear') #first cordinate is the x and the second is y.. we are not saving the plot to any object
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')

plt.xlabel('x label')
plt.ylabel('y label')

plt.title("Simple Plot")

plt.show() # if we do plt.plot all at the samr time and then run
#---------------------------
#Line chart

values = [1, 5, 8, 9, 7, 11, 8, 12, 14, 9]
plt.plot(values)
plt.show() #showing that if we don't specify two arguments, the given value is considered to be  y and the index is used for the x axis

#Multiple line chart
sales1 = [1, 5, 8, 9, 7, 11, 8, 12, 14, 9, 5]
sales2 = [3, 7, 9, 6, 4, 5, 14, 7, 6, 16, 12]
line_chart1 = plt.plot(range(1,12), sales1) #first argument is the x axis and the second argument is the y axis
line_chart2 = plt.plot(range(1,12), sales2)
plt.title('Monthly sales of 2016 and 2017')
plt.ylabel('Sales')
plt.xlabel('Month')
plt.legend(['year 2016', 'year 2017'], loc=1) #loc is the location of the legend and the order is important and the first is for the first object and
#the second argument is for the second object that been run
plt.legeInd(['year 2016', 'year 2017'], loc=4) #loc=4
plt.show()

#Line style
line_chart1 = plt.plot(range(1,12), sales1,'--') # the style is pased
line_chart2 = plt.plot(range(1,12), sales2,':')

#colour
line_chart1 = plt.plot(range(1,12), sales1,'g') # the colour type.. if we are adding more than one parameter, we need to specifiy with the parameter name like colour=
line_chart2 = plt.plot(range(1,12), sales2,'r')
line_chart2 = plt.plot(range(1,12), sales2, color='r', linestyle='--')
#the website to get the style and colour
#https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html
#-----------------------------

#Pie chart
# we have to have values, colour and labe; values are the first parameter an dffthe
values = [60, 80, 90, 55, 10, 30]
colors = ['b', 'g', 'r', 'c', 'm', 'y']
labels = ['US', 'UK', 'India', 'Germany', 'Australia', 'South Korea']
explode = (0.2, 0, 0, 0, 0, 0) #the US  that is the first value that and come out
plt.pie(values, colors=colors, labels= values,explode=explode,
        counterclock=False, shadow=True)
plt.title('Population Density Index')
plt.legend(labels,loc=3)
plt.show()

#Percentage
plt.pie(values, colors=colors, labels=labels,
explode=explode, autopct='%1.2f%%', counterclock=True, shadow=True) # we put the autopct to show the percentage in the slice

#-----------------------------

#Scatter plot chart

weight1=[63.3,57,64.3,63,71,61.8,62.9,65.6,64.8,63.1,68.3,69.7,65.4,66.3,60.7]
height1=[156.3,100.7,114.8,156.3,237.1,123.9,151.8,164.7,105.4,136.1,175.2,137.4,164.2,151,124.3]

plt.scatter(weight1,height1,c='b',marker='o')#marker=’o’ denotes the type of plot  "O' is showing each in circle and
#(. , o v ^ 8 s p D +)
plt.xlabel('weight', fontsize=16)
plt.ylabel('height', fontsize=16)
plt.title('scatter plot - height vs weight',fontsize=20)
plt.show()

#scatter plot for three different groups
weight1=[57,58.2,58.6,59.6,59.8,60.2,60.5,60.6,60.7,61.3,61.3,61.4,61.8,61.9,62.3]
height1=[100.7,195.6,94.3,127.1,111.7,159.7,135,149.9,124.3,112.9,176.7,110.2,123.9,161.9,107.8]

weight2=[62.9,63.1,63.2,63.3,63.4,63.4,63.4,63.5,63.6,63.7,64.1,64.3,64.3,64.7,64.8]
height2=[151.8,156.3,136.1,124.2,156.3,181.2,255.9,163.1,123.1,119.5,179.9,114.8,174.1,108.8,105.4]

weight3=[69.2,69.2,69.4,69.7,70,70.3,70.8,71,71.1,71.7,71.9,72.4,73,73.1,76.2]
height3=[166.8,172.9,193.8,137.4,162.4,137.1,169.1,237.1,189.1,179.3,174.8,213.3,198,191.1,220.6]

weight=np.concatenate((weight1,weight2,weight3)) #45 values
height=np.concatenate((height1,height2,height3))
len(weight)
len(height)

color_array = ['b'] * 15 + ['g'] * 15 + ['r']*15  # we need to cover all 45 values

plt.scatter(weight, height, marker='*', c=color_array)

plt.xlabel('weight', fontsize=16)
plt.ylabel('height', fontsize=16)
plt.title('grouped scatter plot - height vs weight',fontsize=20)
plt.show()
#----------------------------

#Bar chart

city=['Delhi','Beijing','Washington','Tokyo','Moscow']
pos = np.arange(len(city))
Happiness_Index=[60,40,70,65,85]

plt.bar(pos,Happiness_Index,color='blue',edgecolor='black')
plt.xticks(pos, city) #xtick uses the city for the pos.. without the xtick we will see 0,1,2,..
plt.xlabel('City', fontsize=16)
plt.ylabel('Happiness_Index', fontsize=16)
plt.title('Barchart - Happiness index across cities',fontsize=20)
plt.show()

#Horizontal Bar Chart
plt.barh(pos,Happiness_Index,color='blue',edgecolor='black')

#Stacked Bar Chart with legends:
city=['Delhi','Beijing','Washington','Tokyo','Moscow']
Gender=['Male','Female']
pos = np.arange(len(city))
Happiness_Index_Male=[60,40,70,65,85]
Happiness_Index_Female=[30,60,70,55,75]

plt.bar(pos,Happiness_Index_Male,color='blue',edgecolor='black')
plt.bar(pos,Happiness_Index_Female,color='pink',edgecolor='black',bottom=Happiness_Index_Male) #the bottom parameters helping us to avoid the overlap
plt.xticks(pos, city)
plt.xlabel('City', fontsize=16)
plt.ylabel('Happiness_Index', fontsize=16)
plt.title('Stacked Barchart - Happiness index across cities',fontsize=18)
plt.legend(Gender,loc=2)
plt.show()

#Overlapping!!
plt.bar(pos,Happiness_Index_Male,color='blue',edgecolor='black')
plt.bar(pos,Happiness_Index_Female,color='pink',edgecolor='black')

#Grouped Bar Chart with legends:
city=['Delhi','Beijing','Washington','Tokyo','Moscow']
Gender=['Male','Female']
pos = np.arange(len(city))
bar_width = 0.35
Happiness_Index_Male=[60,40,70,65,85]
Happiness_Index_Female=[30,60,70,55,75]

plt.bar(pos,Happiness_Index_Male,bar_width,color='blue',edgecolor='black') #we pass the weigth to get the
plt.bar(pos+bar_width,Happiness_Index_Female,bar_width,color='pink',edgecolor='black')
plt.xticks(pos, city)
plt.xlabel('City', fontsize=16)
plt.ylabel('Happiness_Index', fontsize=16)
plt.title('Group Barchart - Happiness index across cities By Gender',fontsize=18)
plt.legend(Gender,loc=2)
plt.show()

#----------------------------------------------
#Box plot #ploting one numeric coloumns

value1 = [82,76,24,40,67,62,75,78,71,32,98,89,78,67,72,82,87,66,56,52]
value2=[62,5,91,25,36,32,96,95,3,90,95,32,27,55,100,15,71,11,37,21]
value3=[23,89,12,78,72,89,25,69,68,86,19,49,15,16,16,75,65,31,25,52]
value4=[59,73,70,16,81,61,88,98,10,87,29,72,16,23,72,88,78,99,75,30]

box_plot_data=[value1,value2,value3,value4]
plt.boxplot(box_plot_data)
plt.show()

#box plot with fills and labels:
bp=plt.boxplot(box_plot_data,patch_artist=True, labels=['course1','course2','course3','course4']) #to fill the box with the default colour
#argument patch_artist fills the boxplot
#bp is the object

for x in bp['boxes']: #the Box inside the bp is the reserved key word for the
    # change outline color
    x.set(color='red', linewidth=2) #this refers to the color of the outliner
    # change fill color
    x.set(facecolor = 'green') #this refers to the color of the box itself

#Horizontal box with different colors:
box=plt.boxplot(box_plot_data,vert=0,patch_artist=True,labels=['course1','course2','course3','course4'],)

colors = ['cyan', 'lightblue', 'lightgreen', 'tan']
for patch, color in zip(box['boxes'], colors): #batch is the loop iterator fot box['Box'] and the color is the temp variable to go in colors
    patch.set_facecolor(color)

plt.show()

#notch format of the box plot
plt.boxplot(box_plot_data,notch='True',patch_artist=True,labels=['course1','course2','course3','course4'])
#----------------------
#Histogram chart
#step type (no fills)
values = [82,76,24,40,67,62,75,78,71,32,98,89,78,67,72,82,87,66,56,52]
plt.hist(values,bins=5, histtype='step', align='mid', color='g', label='Test Score Data') #5 is the number of bins the number of the steps is bins-1
plt.legend(loc=2)
plt.title('Histogram of score')
plt.show()

#bar type (with fills).
plt.hist(values,5, histtype='bar',
align='mid', color='c', label='Test score Data',edgecolor='black')
plt.legend()
#----------------------
#Create a DataFrame
#Filter/index

d = {
    'Name':['Alisa','Bobby','Cathrine','Alisa','Bobby','Cathrine',
            'Alisa','Bobby','Cathrine','Alisa','Bobby','Cathrine'],
    'Exam':['Semester 1','Semester 1','Semester 1','Semester 1','Semester 1','Semester 1',
            'Semester 2','Semester 2','Semester 2','Semester 2','Semester 2','Semester 2'],

    'Subject':['Mathematics','Mathematics','Mathematics','Science','Science','Science',
               'Mathematics','Mathematics','Mathematics','Science','Science','Science'],
   'Score':[62,47,55,74,31,77,85,63,42,67,89,81]}

df = pd.DataFrame(d,columns=['Name','Exam','Subject','Score'])
df

df['Name'] # accessing the column

x=df['Score'].mean()
type(x)
x
z=df['Score']
type(z)

y=np.array(x)
type(y)
y
np.mean(y)
#therefore we have optioms of

df[['Name', 'Score']]

df[:2]

df['Score'] > 70

df[df['Score'] > 70] #we get the subset of the data

df[(df['Score'] > 70) & (df['Score'] < 85)]

df.ix[:,'Score'] # is the series

type(df.ix[:,'Score'])
#Indexing with .ix:

df.ix[3,2] #one element 4th row and the 3rd column.. ix is similar to the iloc
df

#Normalisation
d = {
       'Score':[62,-47,-55,74,31,77,85,63,42,67,89,81,56]}

df = pd.DataFrame(d,columns=['Score'], dtype='float')
df

#Create a min max processing object
min_max_scaler = preprocessing.MinMaxScaler()
scaled_array = min_max_scaler.fit_transform(df)

df_normalized = pd.DataFrame(scaled_array)
df_normalized

#---------------------
d = {
    'Name':['Alisa','Bobby','Cathrine','Alisa','Bobby','Cathrine',
            'Alisa','Bobby','Cathrine','Alisa','Bobby','Cathrine'],
    'Exam':['Semester 1','Semester 1','Semester 1','Semester 1','Semester 1','Semester 1',
            'Semester 2','Semester 2','Semester 2','Semester 2','Semester 2','Semester 2'],

    'Subject':['Mathematics','Mathematics','Mathematics','Science','Science','Science',
               'Mathematics','Mathematics','Mathematics','Science','Science','Science'],
   'Result':['Pass','Pass','Fail','Pass','Fail','Pass','Pass','Fail','Fail','Pass','Pass','Fail']}

df = pd.DataFrame(d,columns=['Name','Exam','Subject','Result'])
df

pd.crosstab(df.Subject, df.Result,margins=False) # the first argument needed to be categortical and the second can be numeric
# it does show the frequency

pd.crosstab([df.Subject, df.Exam],df.Result, margins=True) #margin means to get the total(All) in each margin


#!/bin/python3
import os
import getopt
import yaml
import math
import sys

JD_ID = 00.00
META = False

def parseArgs():
    global META

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hf:p:m",
                ["help", "file=", "path="])
    except:
        sys.exit(2)

    source_file = "../res/jd.yaml"
    dest_path = "./"

    for opt, arg in opts:
        if opt in ("-h","--help"):
            sys.exit(2)
        elif opt in ("-f", "--file"):
            source_file = arg
        elif opt in ("-p", "--path"):
            dest_path = arg
        elif opt in ("-m", "--meta"):
            META = True
        else:
            assert False, "unknown option"

    return source_file, dest_path

def generateLayerPrefix(jd_id, level):
    if level == 1:
        result = "{:02} - {:02}".format(math.floor(jd_id),math.floor(jd_id + 9))
    elif level == 2:
        result = "{:02}".format(round(jd_id))
    else:
        result = "{:05.2f}".format(jd_id)
    return result

def generateFileSystem(jd_data, dest_path):
    global JD_ID
    global META

    os.chdir(dest_path)

    for upper in jd_data:

        if not META:
            JD_ID += 10

        current_upper_macro = JD_ID
        upper_name = "{} {}".format(generateLayerPrefix(JD_ID,1), upper)

        os.mkdir(upper_name)
        os.chdir(upper_name)

        for middle in jd_data[upper]:

            JD_ID += 1
            current_middle_macro = JD_ID
            middle_name = "{} {}".format(generateLayerPrefix(JD_ID,2), middle)

            os.mkdir(middle_name)
            os.chdir(middle_name)

            for end in jd_data[upper][middle]:
                JD_ID += .01
                end_name = "{} {}".format(generateLayerPrefix(JD_ID,3), end)

                os.mkdir(end_name)

            os.chdir("..")
            JD_ID = current_middle_macro

        os.chdir("..")
        JD_ID = current_upper_macro

        if META:
            JD_ID += 10

if __name__ == '__main__':

    source_file, dest_path = parseArgs()
    print(META)
    source_stream = open(source_file,'r')
    jd_data = yaml.load(source_stream,Loader=yaml.Loader)

    generateFileSystem(jd_data, dest_path)