import os
import socket
import threading
import time
import tkinter as tk
import tkinter.messagebox
from io import BytesIO

import customtkinter
import pafy
import pyperclip
import vlc
from PIL import ImageTk, Image
from pyngrok import ngrok
from pytube import Playlist
from pytube import YouTube
from requests import get

global Video_info
Video_info = ["None", "False", "Video_time_sek"]
global sock
global Hoster
global vra
Hoster = 0

customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("sallify.json")
print(os.path.dirname(os.path.abspath(__file__)))

global False_Call
def play_song(url, volume):
    global Video_info
    Video_info[0] = url
    global player
    global video
    video = pafy.new(url)
    best = video.getbestaudio()
    play_url = best.url
    instance = vlc.Instance()
    player = instance.media_player_new()
    media = instance.media_new(play_url)
    media.get_mrl()
    player.set_media(media)
    player.play()
    player.audio_set_volume(int(volume))

def start_server():
    global sock
    ngrok.set_auth_token("2AYWrd8D7u9WAhpit1cRzCclzt4_47YboKYHbaAFqx2VvbQbU")
    host = socket.gethostname()
    port = 1509

    # Create a TCP socket

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Bind a local socket to the port
    server_address = ("", port)
    sock.bind(server_address)
    sock.listen(1)

    # Open a ngrok tunnel to the socket
    public_url = ngrok.connect(port, "tcp", options={"remote_addr": "{}:{}".format(host, port)})
    print("ngrok tunnel \"{}\" -> \"tcp://127.0.0.1:{}/\"".format(public_url, port))
    global code
    code = str(public_url)[20] + str(public_url)[34:40]

    global Video_info

    while True:
        connection = None
        try:
            # Wait for a connection
            print("\nWaiting for a connection ...")
            connection, client_address = sock.accept()

            print("... connection established from {}".format(client_address))

            # Receive the message, send a response
            while True:
                data = connection.recv(1024)
                if data:
                    Request = data.decode("utf-8")
                    print("Sending: {}".format(str(Video_info)))
                    connection.sendall(str(Video_info).encode("utf-8"))
                else:
                    break
        except KeyboardInterrupt:
            print(" Shutting down server.")

            if connection:
                connection.close()
            break

    sock.close()

"""with open('Playlists.txt', 'rb') as f:
    Songs = load(f)"""
Songs_Full = []
Songs = []
url = "https://youtu.be/1VD17MgCMhM"
video = YouTube(url)
Songs_Half = video.description
for i in Songs_Half.split(","):
    Songs.append(i.split("¦"))

root = customtkinter.CTk()
root.title('Sallify')
root.geometry("1000x500+50+50")
root.iconbitmap("Assets/Sqaure.ico")
Icon = ImageTk.PhotoImage(Image.open("Assets/Green.png"))
panel = tk.Label(root, image=Icon, bg="black")
Ican = ImageTk.PhotoImage(Image.open("Assets/Reload_white.png"))
img = []

def load_songs():
    try:
        for i in Songs:
            p = Playlist(i[1])
            y = YouTube(p.video_urls[0])
            url = y.thumbnail_url
            response = get(url)
            img_data = response.content
            img.append(ImageTk.PhotoImage(Image.open(BytesIO(img_data))))
    except:
        tkinter.messagebox.showerror(root, title="Conection error",message="Please make wifi good and restart")

load_s = threading.Thread(target=load_songs)
load_s.start()

def showimg(e):
    a = lst.curselection()
    fname = lst.get(a)
    for i in range(len(Songs)):
        if Songs[i][0] == fname:
            try:
                panel.configure(image=img[i])
                panel.pack(side="bottom", fill="both", expand="yes")
                panel.update()
            except:
                panel.configure(image=Ican)
                panel.pack(side="bottom", fill="both", expand="yes")
                panel.update()

def Start_playlist():
    subroot =  customtkinter.CTk()
    subroot.geometry("490x340")
    subroot.grid_columnconfigure(0, weight=1)
    subroot.grid_rowconfigure(0, weight=1)
    playlist = tk.Listbox(subroot, selectmode=tk.SINGLE, bg="black", fg="white", width=40)
    playlist.config(font=('Roboto', 15))
    playlist.grid(columnspan=10, sticky="news")
    Z = lst.curselection()
    Aname = lst.get(Z)
    def threaded_Loading():
        for e in range(len(Songs)):
            if Songs[e][0] == Aname:
                p = Playlist(Songs[e][1])
                print(p.title)
                for Url in p.video_urls:
                    Name = YouTube(Url).title
                    playlist.insert(tk.END, Name+" "*1000+","+Url)

    a = threading.Thread(target=threaded_Loading)
    a.start()

    def test(e):
        print("select")
    playlist.bind("<<ListboxSelect>>", test)

    def Load_Song(Link):
        global Video_info
        Video_info[0] = Link
        try:
            player.stop()
        except:
            pass
        play_song(Link, Volumeslider.get())
        Timeslider.config(from_=0, to=video.length)
        Timeslider.set(0)
        z = threading.Thread(target=Has_ended)
        z.start()

    def Has_ended():
        global Video_info
        global False_Call
        while True:
            False_Call = True
            global Video_info
            Timeslider.set(video.length*(player.get_position()))
            Video_info[2] = round(video.length*(player.get_position()))
            time.sleep(5)
            try:
                if str(player.get_state()) == "State.Ended":
                    Next_int = -1
                    print(player.get_state())
                    while True:
                        Next_int += 1
                        if video.title in str(playlist.get(Next_int)):
                            try:
                                print((playlist.get(Next_int+1)).split(",")[0])
                                Load_Song((playlist.get(Next_int+1)).split(",")[1])
                                break
                            except:
                                Load_Song((playlist.get(0)).split(",")[1])
                                break
                                print("First song")
                    break
                else:

                    print(str(player.get_state()))
            except NameError as e:
                print(e)

    def playSong():
        try:
            player.stop()
        except:
            pass
        Puase_Resumebtn.config(text="  ⏸ ")
        pay = playlist.curselection()
        gayname = playlist.get(pay)
        play_song(gayname.split(",")[1], Volumeslider.get())
        Timeslider.config(from_=0, to=video.length)
        Timeslider.set(0)
        z = threading.Thread(target=Has_ended)
        z.start()
        Volumeslider.set(player.audio_get_volume())

    def Puase_ResumeSong():
        print(player.is_playing())
        if player.is_playing() == 1:
            player.pause()
            Video_info[1] = "True"
            Puase_Resumebtn.config(text="  ▶ ")
        elif player.is_playing() == 0:
            Video_info[1] = "False"
            Puase_Resumebtn.config(text="  ⏸ ")
            player.pause()

    def Change_volume(e):
        try:
            text = ("Volume : "+str(round(e)))
            player.audio_set_volume(int(e)*5)
            VolumeEntry.delete(0,tk.END)
            VolumeEntry.insert(0,text)
        except:
            pass

    def Change_Loacation(e):
        global False_Call
        try:
            if False_Call:
                Video_info[2] = e
                False_Call = False
            elif not False_Call:
                Video_info[2] = e
                player.set_time(int(e)*1000)
                False_Call = False
        except:
            pass

    def Enterred(e):
        try:
            Text = int(VolumeEntry.get())
            if Text > 0 and Text < 200:
                Volumeslider.set(Text)
        except:
            text = ("Volume : " + str(round(player.audio_get_volume()/5)))
            VolumeEntry.delete(0, tk.END)
            VolumeEntry.insert(0, text)

    def CLicked(e):
        VolumeEntry.configure(state=tk.NORMAL)
        VolumeEntry.delete(0, tk.END)

    subroot.title('Sallify')
    subroot.iconbitmap("Assets/Sqaure.ico")
    songstatus = tk.StringVar()
    songstatus.set("choosing")
    # playlist---------------

    playbtn = customtkinter.CTkButton(subroot, text="play", command=playSong, text_font=('Roboto', 20))
    # playbtn.config(font=('arial', 20), bg="black", fg="white", padx=70, pady=6)
    playbtn.grid(row=1, rowspan=2, column=0, sticky="news")
    Puase_Resumebtn = customtkinter.CTkButton(subroot, text="  ⏸ ", command=Puase_ResumeSong)
    # Puase_Resumebtn.config(font=('arial', 20), bg="black", fg="white", padx=7, pady=6)
    Puase_Resumebtn.grid(row=1, rowspan=2, column=1, sticky="NSEW")
    # Canvy = customtkinter.CTkFrame(subroot)
    # Canvy.grid(row=1, column=2, sticky="ew", )
    VolumeEntry = customtkinter.CTkEntry(subroot,placeholder_text="Volume")
    VolumeEntry.config()
    # Volumeslider.config(font=('arial', 20), bg="black", fg="white",length=150)
    VolumeEntry.grid(row=1, column=2)
    Volumeslider = customtkinter.CTkSlider(subroot, from_=1,to=100, orient='horizontal',command=Change_volume)
    Volumeslider.set(20)
    # Volumeslider.config(font=('arial', 20), bg="black", fg="white",length=150)
    Volumeslider.grid(row=2, column=2)
    Timeslider = customtkinter.CTkSlider(subroot, from_=0,to=100, orient='horizontal',command=Change_Loacation)
    # Timeslider.config(font=('arial', 20), bg="gray", fg="white",length=450)
    Timeslider.grid(row=3, column=0,columnspan=4, sticky="NSEW")
    VolumeEntry.bind('<Button-1>', CLicked)
    VolumeEntry.bind('<Return>', Enterred)
    subroot.mainloop()

def start_threaded_playlist():
    # x =threading.Thread(target=Start_playlist)
    # x.start()
    Start_playlist()
def client_listen_along(Code):
    while True:
        time.sleep(1)
        Full_info = Code.split(":")
        host = f"{Full_info[0]}.tcp.ngrok.io"
        port = str(Full_info[1])

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        server_address = (host, port)
        sock.connect(server_address)
        print("Connected to {}:{}".format(host, port))

        message = "Video"
        print("Sending: {}".format(message))
        sock.sendall(message.encode("utf-8"))

        data_received = 0
        data_expected = len(message)

        while data_received < data_expected:
            data = sock.recv(1024)
            data_received += len(data)
            print(data.decode("utf-8"))
            sock.close()
        sock.close()
def Client_setup():
    Host_b.pack_forget()
    Join_b.pack_forget()
    Ask_code.pack(side="right", fill=tk.X)
    start.pack(side="right", fill=tk.X)
    Filan_audio_bar.pack(side="right", fill=tk.X)
def start_threaded_listen_along():
    if stream_Buton.get():
        tkinter.messagebox.showinfo(message="Please full screen window to see full gui")
        Host_b.pack(side="right", fill=tk.X)
        Join_b.pack(side="right", fill=tk.X)
    else:
        vra = False
        Filan_audio_bar.pack_forget()
        Host_b.pack_forget()
        Join_b.pack_forget()
        stop.pack_forget()
        Ask_code.pack_forget()
        copyCode.pack_forget()
        start.pack_forget()
        ngrok.kill()
def start_server_setup():
    server = threading.Thread(target=start_server)
    server.start()
    Host_b.pack_forget()
    Join_b.pack_forget()
    stop.pack(side="right", fill=tk.X)
    copyCode.pack(side="right", fill=tk.X)
def stop_server():
    ngrok.kill()
    global vra
    vra = False
    stream_Buton.toggle()

global old_hoho
old_hoho = Video_info
old_hoho[1] == "False"
global vra
vra = False
def vra_serber_vir_informasie():
    global old_hoho
    while vra:
        print(vra)
        time.sleep(1)
        gagagagaag = Ask_code.get().split(":")
        host = f"{gagagagaag[0]}.tcp.ngrok.io"
        port = int(gagagagaag[1])
        pock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_address = (host, port)
        pock.connect(server_address)
        message = "Video"
        pock.sendall(message.encode("utf-8"))
        data_received = 0
        data_expected = len(message)
        while data_received < data_expected:
            data = pock.recv(1024)
            data_received += len(data)
            time.sleep(2)
            hohoho = data.decode("utf-8")
            hohoho = hohoho.replace(" ", "").replace("'", "").replace("[", "").replace("]", "")
            hohoho = hohoho.split(",")
            if hohoho != old_hoho:
                if hohoho[0] != old_hoho[0]:
                    try:
                        player.stop()
                    except:
                        pass
                    play_song(hohoho[0], Filan_audio_bar.get())
                    old_hoho = hohoho
                if hohoho[1] != old_hoho[1]:
                    print(str(hohoho) + " Recieved")
                    print(str(old_hoho) + " had")
                    old_hoho = hohoho
                    if hohoho[1] == "True":
                        print("pausing")
                        if player.is_playing() == 1:
                            player.pause()
                    elif hohoho[1] == "False":
                        if player.is_playing() == 0:
                            print("playing")
                            player.pause()
                if hohoho[2] != old_hoho[2]:
                    if int(hohoho[2]) - 5 > round(video.length*(player.get_position())):
                        try:
                            player.set_time(int(hohoho[2])*1000)
                        except:
                            pass
                    elif int(hohoho[2]) + 5 < round(video.length*(player.get_position())):
                        try:
                            player.set_time(int(hohoho[2]) * 1000)
                        except:
                            pass
                    old_hoho = hohoho
            pock.close()
        pock.close()

def join_server():
    global vra
    print("Joining")
    vra = True
    client = threading.Thread(target=vra_serber_vir_informasie)
    client.start()
def Copy_code():
    global code
    pyperclip.copy(code)
def Final_audio_slider(e):
    try:
        player.audio_set_volume(int(e))
    except:
        pass

def on_closing():
    print("closing")
    ngrok.kill()
    try:
        player.stop()
    except:
        pass
    root.destroy()
    quit()
    quit()

root.protocol("WM_DELETE_WINDOW", on_closing)

Filan_audio_bar = customtkinter.CTkSlider(from_=1,to=100, orient='horizontal', command=Final_audio_slider)
subbie = customtkinter.CTk()
copyCode = customtkinter.CTkButton(text="Copy code", command=Copy_code)
stop = customtkinter.CTkButton(text="Stop", command=stop_server)
start = customtkinter.CTkButton(text="Join", command=join_server)
Ask_code = customtkinter.CTkEntry(placeholder_text="Paste Code here")
Host_b = customtkinter.CTkButton(text="Host listen along", command=start_server_setup)
Join_b = customtkinter.CTkButton(text="Join listen along", command=Client_setup)
stream_Buton = customtkinter.CTkSwitch(text="Listen along",command=start_threaded_listen_along )
stream_Buton.pack(side="top",fill=tk.X)
b1 = customtkinter.CTkButton(text="Play",command=start_threaded_playlist)
b1.pack(side="bottom",fill=tk.X)
lst = tk.Listbox(root, bg="black", fg="white")
lst.pack(side="left",fill="both", ipadx=20)

for fname in Songs:
    lst.insert(tk.END, fname[0])
lst.config(font=('Roboto', 12))
lst.bind("<<ListboxSelect>>", showimg)
panel.pack(side="bottom", fill="both", expand="yes", ipadx=10)
# panel.pack(side="bottom", fill="both", expand="yes")
print("done")

root.mainloop()


import base64
import io
import os

from PIL import Image, ImageDraw, ImageFont
import requests

class WelcomeCard:
    BASE_FONT = ImageFont.truetype(
        os.path.abspath("ether/assets/fonts/Inter-Medium.ttf"), 16
    )
    WELCOME_FONT = ImageFont.truetype(
        os.path.abspath("ether/assets/fonts/Inter-Bold.ttf"), 24
    )
    MASK = Image.open("ether/assets/mask.png", "r").convert("L").resize((100, 100))

    @classmethod
    def create_card(cls, user, guild):
        img = Image.new("RGBA", (400, 200), (231, 228, 220))

        # Profile Picture
        r = requests.get(user.display_avatar.with_size(256).url)
        pp = Image.open(io.BytesIO(r.content))
        pp = pp.resize((100, 100))

        img.paste(pp, (150, 25), cls.MASK)

        draw = ImageDraw.Draw(img)

        # Welcome Text
        draw.text(
            xy=(200, 140),
            text="Welcome!",
            fill=(64, 64, 64),
            font=cls.WELCOME_FONT,
            anchor="ma",
        )

        # Name
        draw.text(
            xy=(200, 170),
            text=f"{user.display_name[:20]}",
            fill=(64, 64, 64),
            font=cls.BASE_FONT,
            anchor="ma",
        )

        # Convert to Base64
        with io.BytesIO() as buffer:
            img.save(buffer, format="PNG", quality=75)
            buffer.seek(0)
            result = base64.b64encode(buffer.getvalue()).decode()
            return io.BytesIO(base64.b64decode(result))


import requests
import urllib.parse as urlparse
import json,sys
from pprint import pprint

isErrorbased = ['"', "'", '--']
isJson = []

CYELL = '\033[1;93m'
CENDYELL = '\033[0m'
CGRE = '\033[1;92m'
CYAN = '\033[1;36m'
RED =  '\033[1;31m'

class SimpleSqlCheck():

    def __init__(self, isUrl, isLocation):
        self.isUrl = isUrl
        self.isLocation = isLocation

    def ParsingJson(self):
        if (self.isLocation == False):
            print (RED,"[WARNING] Please add specifict file json location example -j /home/user/api.json",CENDYELL)
            sys.exit(0)
        else :
            print ("[INFO] Parsing Json where method GET ..")
            try:
                with open(self.isLocation) as f:
                    data = json.load(f)
                    isItems = data['item']
                    for items in isItems:
                        try:
                            item = items['item']
                        except (TypeError, KeyError):
                            pass

                        for i in item:
                            try:
                                isMethod = i['request']['method']
                                if (isMethod == 'GET'):
                                    isJson.append(i)
                            except (TypeError, KeyError):
                                pass
            except (FileNotFoundError) :
                print (RED,"[WARNING] Please add specifict file json location example -j /home/user/api.json ", CENDYELL)
                sys.exit(0)

    def isCheckNormalQuery(self):
        try:
            isHeaders = { 'userToken' : 'null'}
            isStatus = (requests.get(self.isUrl, params=isHeaders , timeout=10))
            if (isStatus.status_code == 200):
                print ("[INFO] status OK")
                return isStatus.headers['Content-Length']

        except Exception as e:
                print (RED,"[WARNING] Oops Request timeout ",e, CENDYELL)
                sys.exit(0)

    def isParsingUrl(self):
        print (CYAN,"[INFO] is Parsing url ..", CENDYELL)
        # pprint (isJson)
        print (CYAN,"[INFO] Is url detected ..", CENDYELL)
        for isurl in isJson:
            print (isurl['request']['url']['raw'])

    def IsQueryErrors(self, isContentLength):
        print ("[INFO] Checking Error Based ..")
        # isQueryParsed = urlparse.urlparse(self.isUrl).query
        # isQuery = isQueryParsed.split('&')
        # print(isQuery)

        parsed = urlparse.urlparse(self.isUrl).query
        print (urlparse.parse_qs(parsed))
        # querys = parsed.query.split("&")
        # result = []
        # for query in querys:
        #     for pairs in isErrorbased :
        #         print (query)
        #         new_query = "&".join([ "{}{}".format(query, pairs)])
        #         print (new_query)
        #         parsed = parsed._replace(query=new_query)
        #         result.append(urlparse.urlunparse(parsed))
        # print (result)

    def CheckSqlInjection(self):
        if (self.isLocation != False):
            self.ParsingJson()
            self.isParsingUrl()

        else:
            lenght = self.isCheckNormalQuery()
            self.IsQueryErrors(lenght)


import os, os.path
import string
import cherrypy
import datetime
import requests
import lxml
import cssselect
import lxml.html
import json
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#from email.MIMEBase import MIMEBase
from pprint import pprint

class Data(object):
    def __init__(self,title,description,link):
        self.title = title
        self.description = description
        self.link = link
class SendMail(object):
    def __init__(self):
        print('envoi de mail')
    def methodetest(self):
        print('je suis dans la méthode test')

class MonSiteWeb(object):

    global htmlsite
    global variable
    global tabtitle
    global tabdesc
    global tablink
    global tabind
    #global tabdata
    global listededonnee

    def methodetest(self):
        print('je suis dans la méthode test')

    @cherrypy.expose
    def index(self):

        now = datetime.datetime.now()
        entetesite = ''' <!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Appel d'offre</title>

    <link href="/static/bootstrap-3.3.7-dist/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="/static/bootstrap-3.3.7-dist/css/scrolling-nav.css" rel="stylesheet">

	<link rel="stylesheet" type="text/css" href="/static/bootstrap-3.3.7-dist/DataTables/datatables.min.css"/>

Socitech

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              About

              Ajouter un filtre

              Action

 Appel d'offre venant du site global tender

resultat du "data scraping" du site global tender

Resultat de la recherche

			<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong">
				Envoi de la selection
			</button>

Date	Title	Description	Link

'''
        table = "
{}	{}	{}	{}
"

        footer = '''

Contacts

				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					×
				</button>

Ajoujer un Contact

				<form>

						Name :
						<input type="text" class="form-control" id="name" placeholder="Name"  required>

						Email :
						<input type="email" class="form-control" id="email" placeholder="EMAIL"  required>

						Telephone :
						<input type="tel" class="form-control" id="telephone" placeholder="Telephone"  required>

						<button type="button" class="btn btn-primary" id="addContact">Add Contacts</button>

				</form>

NOMS	EMAIL	NUMERO

Rudy	rudy@yahoo.fr	671402318

				<button id="moveContact" type="button" class="btn btn-primary">move selected row</button>
				<button id="sendEmail" type="button" class="btn btn-primary">send to selected row</button>
				<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

Copyright © Your Website 2017

'''
        tabtitle = []
        tabdesc = []
        tablink = []
        tabind = []
        global tabdata

        txt = 'ma variable'
        indice = 0
        url = 'https://www.globaltenders.com/tenders-cameroon.php'
        while(url !='#'):
            reponse = requests.get(url)#'http://www.globaltenders.com/'
            tree = lxml.html.fromstring(reponse.text)
            tdElems = tree.xpath('//table/tr/td[@style="width:70%; vertical-align:top; text-align:left;"]')#|//table/tr/td/a/@href
            tdElink = tree.xpath('//table/tr/td/a/@href')
            taille = len(tdElems)
            indice = 0
            intitule =''
            adresse = ''
            mylist = list()
            mydescription = list()
            mytitle = list()
            listData = list()
            while (indice < taille):
                if(tdElems[indice].text_content() == ' Technology Hardware and Equipment'):
                    ltail = indice//2
                    intitule = ' Technology Hardware and Equipment'
                    adresse = tdElink[ltail]
                    mylist.append(adresse)
                    val = indice+1
                    mydescription.append(tdElems[val].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[val].text_content(),adresse)
                    listData.append(data)
                    print(tdElems[indice].text_content())
                    #print(adresse)
                elif(tdElems[indice].text_content() == ' Smart Cards and other Access Control system , Printing and publishing'):

                    ltailt = indice//2
                    intitulet = tdElems[indice].text_content()
                    adresset = tdElink[ltailt]
                    mylist.append(adresset)
                    val = indice+1
                    mydescription.append(tdElems[val].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[val].text_content(),adresset)
                    listData.append(data)
                    print(tdElems[indice].text_content())
                    #print(adresset)

                elif(tdElems[indice].text_content() == ' Software Services'):

                    ltailf = indice//2
                    intitulef = tdElems[indice].text_content()
                    adressef = tdElink[ltailf]
                    mylist.append(adressef)
                    val = indice+1
                    mydescription.append(tdElems[val].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[val].text_content(),adressef)
                    listData.append(data)
                    print(tdElems[indice].text_content())
                    #print(adressef)

                elif(tdElems[indice].text_content() == ' Bridges and Tunnels'):

                    ltails = indice//2
                    intitules = tdElems[indice].text_content()
                    adresses = tdElink[ltails]
                    mylist.append(adresses)
                    val = indice+1
                    mydescription.append(tdElems[val].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[val].text_content(),adresses)
                    listData.append(data)
                    print(tdElems[indice].text_content())
                    #print(adresses)

                elif(tdElems[indice].text_content() == ' Services'):

                    ltailn = indice//2
                    intitulen = tdElems[indice].text_content()
                    adressen = tdElink[ltailn]
                    mylist.append(adressen)
                    val = indice+1
                    mydescription.append(tdElems[val].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[val].text_content(),adressen)
                    listData.append(data)
                    print(tdElems[indice].text_content())
                    #print(adressen)

                elif(tdElems[indice].text_content() == ' Printing and publishing'):

                    ltailk = indice//2
                    intitulek = tdElems[indice].text_content()
                    adressek = tdElink[ltailk]
                    mylist.append(adressek)
                    mydescription.append(tdElems[indice+1].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[indice+1].text_content(),adressek)
                    listData.append(data)
                    print(tdElems[indice].text_content())
                    #print(adressek)

                elif(tdElems[indice].text_content() == ' Industry , Technology Hardware and Equipment , Furniture'):

                    ltaily = indice//2
                    intituley = tdElems[indice].text_content()
                    adressey = tdElink[ltaily]
                    mylist.append(adressey)
                    mydescription.append(tdElems[indice+1].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[indice+1].text_content(),adressey)
                    listData.append(data)
                    print(tdElems[indice].text_content())
                    #print(adressey)
                elif(tdElems[indice].text_content() == ' Telecommunications , Information Technology (IT) , Consultancy , Services , Infrastructure and construction'):
                    ltaill = indice//2
                    intitulel = tdElems[indice].text_content()
                    adressel = tdElink[ltaill]
                    mylist.append(adressel)
                    mydescription.append(tdElems[indice+1].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[indice+1].text_content(),adressel)
                    listData.append(data)
                    print(tdElems[indice].text_content())
                    #print('*****************')

                elif(tdElems[indice].text_content() == ' Industry , Technology Hardware and Equipment'):

                    ltailycp = indice//2
                    intituleycp = tdElems[indice].text_content()
                    adresseycp = tdElink[ltailycp]
                    mylist.append(adresseycp)
                    mydescription.append(tdElems[indice+1].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[indice+1].text_content(),adresseycp)
                    listData.append(data)
                    print(tdElems[indice].text_content())

                elif(tdElems[indice].text_content() == ' Telecommunications'):

                    ltailytele = indice//2
                    intituleytele = tdElems[indice].text_content()
                    adresseytele = tdElink[ltailytele]
                    mylist.append(adresseytele)
                    mydescription.append(tdElems[indice+1].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[indice+1].text_content(),adresseytele)
                    listData.append(data)
                    print(tdElems[indice].text_content())

                elif(tdElems[indice].text_content() == ' Technology Hardware and Equipment , Energy, Power and Electrical'):

                    ltailyHard = indice//2
                    intituleyHard = tdElems[indice].text_content()
                    adresseyHard = tdElink[ltailyHard]
                    mylist.append(adresseyHard)
                    mydescription.append(tdElems[indice+1].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[indice+1].text_content(),adresseyHard)
                    listData.append(data)
                    print(tdElems[indice].text_content())

                elif(tdElems[indice].text_content() == ' Telecommunications , Banking, Finance, Insurance and Securities (BFIS) , Information Technology (IT) , Consultancy'):

                    ltailyBank = indice//2
                    intituleyBank = tdElems[indice].text_content()
                    adresseyBank = tdElink[ltailyBank]
                    mylist.append(adresseyBank)
                    mydescription.append(tdElems[indice+1].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[indice+1].text_content(),adresseyBank)
                    listData.append(data)
                    print(tdElems[indice].text_content())

                elif(tdElems[indice].text_content() == ' Telecommunications , Information Technology (IT) , Consultancy , Infrastructure and construction , Building'):

                    ltailyInfor = indice//2
                    intituleyInfor = tdElems[indice].text_content()
                    adresseyInfor = tdElink[ltailyInfor]
                    mylist.append(adresseyInfor)
                    mydescription.append(tdElems[indice+1].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[indice+1].text_content(),adresseyInfor)
                    listData.append(data)
                    print(tdElems[indice].text_content())

                elif(tdElems[indice].text_content() == ' Telecommunications , Information Technology (IT) , Software Services , Consultancy'):

                    ltailymunic = indice//2
                    intituleymunic = tdElems[indice].text_content()
                    adresseymunic = tdElink[ltailymunic]
                    mylist.append(adresseymunic)
                    mydescription.append(tdElems[indice+1].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[indice+1].text_content(),adresseymunic)
                    listData.append(data)
                    print(tdElems[indice].text_content())

                elif(tdElems[indice].text_content() == ' Telecommunications , Infrastructure and construction'):

                    ltailyInfras = indice//2
                    intituleyInfras = tdElems[indice].text_content()
                    adresseyInfras = tdElink[ltailyInfras]
                    mylist.append(adresseyInfras)
                    mydescription.append(tdElems[indice+1].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[indice+1].text_content(),adresseyInfras)
                    listData.append(data)
                    print(tdElems[indice].text_content())

                elif(tdElems[indice].text_content() == ' Telecommunications , Information Technology (IT) , Consultancy'):

                    ltailyConsul = indice//2
                    intituleyConsul = tdElems[indice].text_content()
                    adresseyConsul = tdElink[ltailyConsul]
                    mylist.append(adresseyConsul)
                    mydescription.append(tdElems[indice+1].text_content())
                    mytitle.append(tdElems[indice].text_content())
                    data = Data(tdElems[indice].text_content(),tdElems[indice+1].text_content(),adresseyConsul)
                    listData.append(data)
                    print(tdElems[indice].text_content())

                indice = indice + 1
                tabtitle = tabtitle + mytitle
                #tabtitle = mytitle
                tabdesc  = tabdesc + mydescription
                #tabdesc = mydescription
                tablink  = tablink + mylist
                #tablink = mylist
                tabdata = listData

            #tabdata = listData
            #tabind =
            #print(listData,'*********************')
            tdElemslm = tree.xpath('//select[@style="float:left"]')
            mlistlm = tdElemslm[0].getnext().getchildren()
            if len(mlistlm) == 2 :
                #print(mlistlm[1].xpath('@href')[0])
                adressederedirection = mlistlm[1].xpath('@href')[0]
            else :
                #print(mlistlm[0].xpath('@href')[0])
                if(mlistlm[0].text_content() == 'Next Page'):
                    adressederedirection = mlistlm[0].xpath('@href')[0]
                else:
                    adressederedirection = '#'
            url= adressederedirection

        #global listData
        #listData = list()
        listededonnee = list()
        nlisted = list()
        inlist=0
        while inlist < len(tabtitle):
            donnee = Data(tabtitle[inlist],tabdesc[inlist],tablink[inlist])
            listededonnee.append(donnee)
            inlist = inlist+1
        print(listededonnee)
        print(len(listededonnee),'/*-/*-/*-/*-/*-/*-/*-/*-/*-/*-/*-/*-/*-/*-/*-')

        for donnee in listededonnee :
            c = 0
            nindic = 1
            lesindices = []
            listedesdons = listededonnee
            while nindic < len(listededonnee):
                if donnee.title == listededonnee[nindic].title and donnee.description == listededonnee[nindic].description and donnee.link == listededonnee[nindic].link:
                    c = c+1
                    if(c>0):
                       listededonnee.remove(listededonnee[nindic])
                nindic = nindic + 1
            print(c)

        print(listededonnee)
        print(len(listededonnee),'/*-+/*-+/*-+/*-+/*-+/*-+/*-+/*-+/*-+/*-+/*-+/*-+/*-+')

        #listData = listededonnee

        for el in listededonnee :
            inc = 0
            indel = 0
            while indel < len(listededonnee):
                if el.title == listededonnee[indel].title and el.description == listededonnee[indel].description and el.link == listededonnee[indel].link:
                    inc = inc + 1
                    if inc >1 :
                        listededonnee.remove(listededonnee[indel])
                indel = indel + 1
        for iii in listededonnee :
            print(iii.title)

        pagehtml = ''
        for td in listededonnee :
            pagehtml = pagehtml + table.format(str(now),td.title,td.description,td.link,td.link)

        return entetesite + pagehtml + footer

    @cherrypy.expose
    def sendMail(self,donnee,qtdonnee,addresse,qtAddonnee):
        cherrypy.response.headers['Content-Type'] = 'application/json'
        variable = r"""{}"""
        data = json.loads(variable.format(donnee))
        print(data,'+/++/+/++/++/++/++/++/*+/+*/+*/+*/+*/+*/+*/+*/')
        print('---------------------------------------------------')
        indice = 0
        message = """
                    <!DOCTYPE html>

                                <meta charset="utf-8">
                                <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
                                <meta name="description" content="">
                                <meta name="author" content="">
                                <title>Appel d'offre</title>

                                <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

Title	Description	Link

"""
        tdata = """
{}	{}	lien du site
"""

        fin = """

                    """
        valdonnee = ''
        while indice < int(qtdonnee) :
            chn = str(indice)
            valdonnee = valdonnee + tdata.format(data[chn]['titre'],data[chn]['description'],'http://www.globaltenders.com/auth-tenders.php?action=details&id='+data[chn]['lien'])
            indice = indice + 1

        indicead = 0
        variablead = r"""{}"""
        address = json.loads(variable.format(addresse))
        lAd = list()
        while indicead < int(qtAddonnee) :
           chn = str(indicead)
           valAd = address[chn]['init']+'@'+ address[chn]['end']
           lAd.append(valAd)
           print(valAd)
           indicead = indicead + 1

        MessageSending = message + valdonnee +fin
        indiceMail = 0
        me = 'tekamfossi@gmail.com'
        text = "Appel d'offre !"
        part1 = MIMEText(text, 'plain')
        part2 = MIMEText(MessageSending, 'html')
        msg = MIMEMultipart('alternative')
        msg['Subject'] = "Appel d'offre"
        msg['From'] = me
        msg.attach(part1)
        msg.attach(part2)
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(me, "degrace1")
        while indiceMail < len(lAd):
            msg['To'] = lAd[indiceMail]
            server.sendmail(me, lAd[indiceMail], msg.as_string())
            indiceMail = indiceMail + 1
        server.quit()
        lstre = {}
        lstre['resultat'] = 'ok'
        return ''

    #index.exposed = True

    #methodetest.exposed = True

    #sendMail.exposed = True
if __name__ == '__main__':
    print(os.path.dirname(os.getcwd()))
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir':'./public'
        }
    }
    cherrypy.quickstart(MonSiteWeb(), '/', conf)

#cherrypy.quickstart(MonSiteWeb(), config ="server.conf")


from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse
# Create your views here.
from .serializer import CustomerSerializer, ProductSerializer, SubscriptionSerializer
from .models import Customer, Product, Subscription
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET', 'POST'])
def subscription_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        subscription = Subscription.objects.all()
        serializer = SubscriptionSerializer(subscription, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = SubscriptionSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PATCH'])
def subscription_detail(request, pk):
    """
    Retrieve, update or delete a code snippet.
    """
    try:
        snippet = Subscription.objects.get(pk=pk)
    except Subscription.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = Subscription(snippet)
        return Response(serializer.data)

    elif request.method == 'PATCH':
        serializer = SubscriptionSerializer(snippet, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'POST'])
def customer_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        customer = Customer.objects.all()
        serializer = CustomerSerializer(customer, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = CustomerSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'POST'])
def product_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        products = Product.objects.all()
        serializer = ProductSerializer(products, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ProductSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
def subscription_check(request,customer_id, product_name):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        subscription_check = get_object_or_404(Subscription,customer_id=customer_id, product_name= product_name)
        serializer = SubscriptionSerializer(subscription_check)
        return Response(serializer.data)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from rest_framework.decorators import api_view
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from .serializers import *
# Create your views here.
def index(request):
	return HttpResponse('
The index page of App
')

class Wells(APIView):
	def get(self,request):
		welllist = Well.objects.all()
		serializer=WellSerializer(welllist, many=True)
		return Response(serializer.data)
	def post(self,request):
		pass

def maps(request):
    #template = loader.get_template('maps/maps.html')
    markers1={0:{'lat':-33.7772, 'long':151.1241}}
    return render(request, 'app/maps.html',{'points':markers1})

class MapList(APIView):
	def get(self, request):
		maplist = Farmpoints.objects.all()
		serializer=FarmpointSerializer(maplist, many=True)
		return Response(serializer.data)
	def post(self):
		pass

#class News(APIView):
#	def get(self,request):
	#	query= Farmpoints.objects.raw('SELECT * FROM Farm JOIN Farmer JOIN Farmpoints WHERE Farmpoints.Farm_id= 1')
#		return render(request, 'app/maps.html',{'farmdet':query})
#		query=Farmer.objects.raw('SELECT * FROM app_farmer JOIN app_farm ON app_farmer.id=1')
#		return render(request, 'app/abc.html',{'resu':query})

@api_view(['GET', 'PUT', 'DELETE'])
def MapDetail(request,pk, format=None):
	try:
		map_detail=Farmpoints.objects.get(pk=pk)
	except Farmpoints.DoesNotExist:
		return Response(status=status.HTTP_404_NOT_FOUND)

	if request.method=='GET':
		serializer=FarmpointSerializer(map_detail)
		return Response(serializer.data)

	elif request.method=='PUT':
		serializer=FarmpointSerializer(map_detail, data=request.data)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data)
		return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

	elif request.method=='DELETE':
		map_detail.delete()
		return Response(status=status.HTTP_204_NO_CONTENT)

class FarmerList(APIView):
	def get(self,request):
		farmerlist = Farmer.objects.all()
		serializer=FarmerSerializer(farmerlist, many=True)
		return Response(serializer.data)
	def post(self,request):
		pass

@api_view(['GET', 'PUT', 'DELETE'])
def FarmerDetail(request,pk, format=None):
	try:
		f_detail=Farmer.objects.get(pk=pk)
	except Farmer.DoesNotExist:
		return Response(status=status.HTTP_404_NOT_FOUND)

	if request.method=='GET':
		serializer=FarmerSerializer(f_detail)
		return Response(serializer.data)

	elif request.method=='PUT':
		serializer=FarmerSerializer(f_detail, data=request.data)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data)
		return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

	elif request.method=='DELETE':
		f_detail.delete()
		return Response(status=status.HTTP_204_NO_CONTENT)

class HouseHoldList(APIView):
	def get(self, request):
		hhlist = HouseHold.objects.all()
		serializer=HouseHoldSerializer(hhlist, many=True)
		return JsonResponse(serializer.data, safe=False)
	def post(self):
		pass
@api_view(['GET', 'PUT', 'DELETE'])
def HouseHoldDetail(request,pk, format=None):
	try:
		hh_detail=HouseHold.objects.get(pk=pk)
	except HouseHold.DoesNotExist:
		return Response(status=status.HTTP_404_NOT_FOUND)

	if request.method=='GET':
		serializer=HouseHoldSerializer(hh_detail)
		return Response(serializer.data)

	elif request.method=='PUT':
		serializer=HouseHoldSerializer(hh_detail, data=request.data)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data)
		return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

	elif request.method=='DELETE':
		hh_detail.delete()
		return Response(status=status.HTTP_204_NO_CONTENT)

class MemberList(APIView):
	def get(self, request):
		memberlist = Member.objects.all()
		serializer=MemberSerializer(memberlist, many=True)
		return Response(serializer.data)
	def post(self):
		pass
@api_view(['GET', 'PUT', 'DELETE'])
def MemberDetail(request,pk, format=None):
	try:
		m_detail=Member.objects.get(pk=pk)
	except Member.DoesNotExist:
		return Response(status=status.HTTP_404_NOT_FOUND)

	if request.method=='GET':
		serializer=MemberSerializer(m_detail)
		return Response(serializer.data)

	elif request.method=='PUT':
		serializer=MemberSerializer(m_detail, data=request.data)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data)
		return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

	elif request.method=='DELETE':
		m_detail.delete()
		return Response(status=status.HTTP_204_NO_CONTENT)

class FarmList(APIView):
        def get(self, request):
                flist = Farm.objects.all()
                serializer=FarmSerializer(flist, many=True)
                return Response(serializer.data)
        def post(self):
                pass


"""env.py: Environment configuration for the maze simulation"""

__author__ = "Pablo Alvarado"
__copyright__ = "Copyright 2020, Pablo Alvarado"
__license__ = "BSD 3-Clause License (Revised)"

import math
import random
import maze
import agent

class Environment:
    """"Environment class

        The environment holds a maze and one or more agents
    """

    def __init__(self, nx, ny, cellSizeX, cellSizeY=None):
        if cellSizeY is None:
            cellSizeY = cellSizeX
        self.maze = maze.Maze(nx, ny, cellSizeX, cellSizeY)
        self.agent = agent.Agent()
        self.reset()
        self.contR=()
        self.contL = ()
        self.contA = ()
        self.probR = ()
        self.probL = ()
        self.probA = ()
        self.values = ()
        self.politics = ()

    def reset(self):
        self.agent.state.reset()
        self.agent.setPos((self.maze.startX+0.5)*self.maze.cellSizeX,
                          (self.maze.startY+0.5)*self.maze.cellSizeY)
        if self.agent.sensors and self.agent.maxDistance > self.agent.radius:
            self.agent.observations = self.observe(self.agent)

    def tryAction(self, anAgent, action, arg=None):
        """Executes the action on the agent, but verifies that the achieved
           result is compatible with the environment.  The environment
           fixes all invalid information.

           "action" must be a method of the agent class (i.e. right, left or
           advance) which might receive an optional argument "arg".
        """

        if arg is None:
            pre = action()
        else:
            pre = action(arg)

        anAgent.setState(self.validate(anAgent, pre))
        if anAgent.sensors and anAgent.maxDistance > anAgent.radius:
            anAgent.observations = self.observe(anAgent)
            # print("[DBG] Observations: ", anAgent.observations)

    def validate(self, anAgent, newState):
        """Restrict the newState to a valid environmental compatible
           state.

           This method just returned the possible state, but does not
           affect the agent.
        """

        res = agent.AgentState(newState)

        # Is it rotating?
        if (not anAgent.state.sameAngle(newState)):
            # For now, let's asume no major obstacles for rotation,
            # but some noise
            res.angle += random.normalvariate(0, anAgent.rotationNoise)

        # Is it moving?
        if (not anAgent.state.samePos(newState)):
            length = anAgent.state.distance(newState)
            nx = random.normalvariate(0, length*anAgent.translationNoiseFactor)
            ny = random.normalvariate(0, length*anAgent.translationNoiseFactor)

            dx, dy = self.maze.tryMovement(anAgent.state.posX,
                                           anAgent.state.posY,
                                           newState.posX+nx,
                                           newState.posY+ny,
                                           anAgent.radius)

            res.posX, res.posY = dx, dy

        return res

    def observe(self, anAgent):
        """Observe the environment.  The agent sensor array must be properly
           configured.

           The return observation array correspons to one distance
           measurment for each angle (in degrees) specified in the agent's
           sensorArray.  If the measurements exceed the sensor's reach
           then -1 is returned
        """

        if anAgent.sensorArray is None or not anAgent.sensorArray:
            return []

        ret = [0]*len(anAgent.sensorArray)
        i = 0
        for sangle in anAgent.sensorArray:
            d = self.maze.observe(anAgent.state.posX,
                                  anAgent.state.posY,
                                  anAgent.state.angle + sangle,
                                  anAgent.maxDistance)
            ret[i] = d
            i += 1

        return ret

    def inCell(self, cx, cy, anAgent):
        """Check if the provided agent is touching the center of the given
           cell
        """

        x, y = anAgent.state.posX, anAgent.state.posY
        r2 = anAgent.radius*anAgent.radius

        ccx, ccy = (cx+0.5)*self.maze.cellSizeX, (cy+0.5)*self.maze.cellSizeY
        dx, dy = ccx-x, ccy-y

        d2 = dx*dx+dy*dy

        # if d2 <= r2:
        #     d = math.sqrt(d2)
        #     print("[DBG] d=", d, " < ", anAgent.radius)

        return (d2 <= r2)

    def finished(self):
        """ Check if the agent is touching the center of the finish cell """
        return self.inCell(self.maze.endX, self.maze.endY, self.agent)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Common fixtures and utils for io tests."""

import copy
import os

import pytest

from orion.core.evc import conflicts

@pytest.fixture()
def config_file():
    """Open config file with new config"""
    file_path = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), "orion_config.yaml"
    )

    return open(file_path)

@pytest.fixture()
def old_config_file():
    """Open config file with original config from an experiment in db"""
    file_path = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), "orion_old_config.yaml"
    )

    return open(file_path)

@pytest.fixture()
def incomplete_config_file():
    """Open config file with partial database configuration"""
    file_path = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), "orion_incomplete_config.yaml"
    )

    return open(file_path)

@pytest.fixture
def parent_config():
    """Generate a new experiment configuration"""
    return dict(_id="test", name="test", metadata={"user": "corneauf"}, version=1)

@pytest.fixture
def child_config(parent_config):
    """Generate a new experiment configuration"""
    config = copy.deepcopy(parent_config)
    config["_id"] = "test2"
    config["refers"] = {"parent_id": "test"}
    config["version"] = 2

    return config

@pytest.fixture
def experiment_name_conflict(storage, parent_config, child_config):
    """Generate an experiment name conflict"""
    exps = storage.fetch_experiments({"name": "test"}) + storage.fetch_experiments(
        {"name": "test2"}
    )
    for exp in exps:
        storage.delete_experiment(uid=exp["_id"])
    storage.create_experiment(parent_config)
    storage.create_experiment(child_config)
    return conflicts.ExperimentNameConflict(parent_config, parent_config)


# DSC 510
# Week 11
# Programming Assignment Week 11
# Author: Reenie Christudass
# 05/23/2022

# Change#:1
# Change(s) Made: Cash register program
# Date of Change: 05/23/2022
# Author: Reenie Christudass
# Change Approved by: Michael Eller
# Date Moved to Production: 05/23/2022

import locale
from termcolor import colored

locale.setlocale(locale.LC_ALL, 'en_US')

class CashRegister:

    # constructor
    def __init__(self):
        self.total = 0.0
        self.itemCount = 0

    # setter
    def add_item(self, price):
        self.total = self.total + float(price)
        self.itemCount = self.itemCount + 1

    # getter
    def get_total(self):
        return self.total

    def get_count(self):
        return self.itemCount

def process_line(create_list):
    print("")
    print("---------------THANK YOU FOR USING CASH REGISTER---------------------------")
    print("")
    # Print all items purchased
    if create_list:
        for n in range(len(create_list)):
            text = colored(create_list[n], 'blue')
            print("Item Purchased " + str(n + 1) + ":" + '$ ' + text)
    else:
        print("")
        print("No items selected")

def main():
    print("WELCOME TO CASH REGISTER!!!!")
    register = CashRegister()
    create_list = []
    # variable declared to have the program in loop unless exited by the user
    item_loop = 0
    while item_loop >= 0:
        # Allow user to enter the price of the item
        if item_loop == 0:
            input_message = input("Enter the price of the item or enter exit to quit the program:")
        elif item_loop > 0:
            input_message = input("Enter the price of another item or enter exit to quit the program:")
        # read the file

        if input_message != 'exit':
            try:
                # program will convert the user input value to float
                input_message = float(input_message)
                create_list.append(input_message)
            except ValueError as e:
                # if the program couldn't convert the value to float , it will prompt the user to enter value in numeric
                print("Please enter the numeric value for item")
                continue

            register.add_item(input_message)
        # if the user input is equal to exit
        elif input_message == 'exit':
            break
        print()
        item_loop = item_loop + 1
    process_line(create_list)

    print("")
    message_output = ("Total Cost of the items purchased : {}".format(locale.currency(register.get_total())))
    print(colored(message_output, 'yellow'))
    message_output = ("Total Items Purchased: {}".format(colored(register.get_count()), 'blue'))
    print(colored(message_output, 'magenta'))
    print("")
    print("Thank you and have a great day")

# using special variable
if __name__ == "__main__":
    main()


from matplotlib import pyplot as plt

def plot_forest_management(gamma_values, iterations, time_array, rewards, title):
    plt.plot(gamma_values, rewards)
    plt.ylabel('Rewards')
    plt.xlabel('Discount')
    plt.title('{} - Reward vs Discount'.format(title))
    plt.grid()
    plt.show()

    plt.plot(gamma_values, iterations)
    plt.ylabel('Iterations to Converge')
    plt.xlabel('Discount')
    plt.title('{} - Convergence vs Discount'.format(title))
    plt.grid()
    plt.show()

    plt.plot(gamma_values, time_array)
    plt.title('{} - Execution Time vs Discount'.format(title))
    plt.xlabel('Discount')
    plt.ylabel('Time Taken (in seconds)')
    plt.grid()
    plt.show()


import exp1

if __name__ == '__main__':
    # test_classifier()
    # name = ['LSTM', 'CNN']
    name = ['bilstm']
    cuda = False
    # dga = ['khaos_original', 'kraken', 'gozi', 'suppobox', 'maskDGA', 'our']
    dga_test = ['maskDGA']
    for model in name:
        exp1.classification(model, 1, ' ', dga_test, cuda)
    # classification('Graph', 1, ['no'])


import numpy as np

def _extend(M, sym):
    """Extend window by 1 sample if needed for DFT-even symmetry"""
    if not sym:
        return M + 1, True
    else:
        return M, False

def _len_guards(M):
    """Handle small or incorrect window lengths"""
    if int(M) != M or M < 0:
        raise ValueError('Window length M must be a non-negative integer')
    return M <= 1

def _truncate(w, needed):
    """Truncate window by 1 sample if needed for DFT-even symmetry"""
    if needed:
        return w[:-1]
    else:
        return w

def general_cosine(M, a, sym=True):
    if _len_guards(M):
        return np.ones(M)
    M, needs_trunc = _extend(M, sym)

    fac = np.linspace(-np.pi, np.pi, M)
    w = np.zeros(M)
    for k in range(len(a)):
        w += a[k] * np.cos(k * fac)

    return _truncate(w, needs_trunc)

def general_hamming(M, alpha, sym=True):
    return general_cosine(M, [alpha, 1. - alpha], sym)

def hann(M, sym=True):
    # Docstring adapted from NumPy's hanning function
    return general_hamming(M, 0.5, sym)

_win_equiv_raw = {
    ('hanning', 'hann', 'han'): (hann, False),
}

# Fill dict with all valid window name strings
_win_equiv = {}
for k, v in _win_equiv_raw.items():
    for key in k:
        _win_equiv[key] = v[0]

# Keep track of which windows need additional parameters
_needs_param = set()
for k, v in _win_equiv_raw.items():
    if v[1]:
        _needs_param.update(k)

def get_window(window, Nx, fftbins=True):
    sym = not fftbins
    try:
        beta = float(window)
    except (TypeError, ValueError) as e:
        args = ()
        if isinstance(window, tuple):
            winstr = window[0]
            if len(window) > 1:
                args = window[1:]
        elif isinstance(window, str):
            if window in _needs_param:
                raise ValueError("The '" + window + "' window needs one or "
                                 "more parameters -- pass a tuple.") from e
            else:
                winstr = window
        else:
            raise ValueError("%s as window type is not supported." %
                             str(type(window))) from e

        try:
            winfunc = _win_equiv[winstr]
        except KeyError as e:
            raise ValueError("Unknown window type.") from e

        params = (Nx,) + args + (sym,)
    else:
        winfunc = hann
        params = (Nx, sym)

    return winfunc(*params)

def _triage_segments(window, nperseg, input_length):
    # parse window; if array like, then set nperseg = win.shape
    if isinstance(window, str) or isinstance(window, tuple):
        # if nperseg not specified
        if nperseg is None:
            nperseg = 256  # then change to default
        if nperseg > input_length:
            warnings.warn('nperseg = {0:d} is greater than input length '
                          ' = {1:d}, using nperseg = {1:d}'
                          .format(nperseg, input_length))
            nperseg = input_length
        win = get_window(window, nperseg)
    else:
        win = np.asarray(window)
        if len(win.shape) != 1:
            raise ValueError('window must be 1-D')
        if input_length < win.shape[-1]:
            raise ValueError('window is longer than input signal')
        if nperseg is None:
            nperseg = win.shape[0]
        elif nperseg is not None:
            if nperseg != win.shape[0]:
                raise ValueError("value specified for nperseg is different"
                                 " from length of window")
    return win, nperseg

def _median_bias(n):
    ii_2 = 2 * np.arange(1., (n-1) // 2 + 1)
    return 1 + np.sum(1. / (ii_2 + 1) - 1. / ii_2)

def welch(x, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None,
          detrend='constant', return_onesided=True, scaling='density',
          axis=-1, average='mean'):
    """Estimate power spectral density using Welch's method"""

    freqs, Pxx = csd(x, x, fs=fs, window=window, nperseg=nperseg,
                     noverlap=noverlap, nfft=nfft, detrend=detrend,
                     return_onesided=return_onesided, scaling=scaling,
                     axis=axis, average=average)

    return freqs, Pxx.real

def csd(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None,
        detrend='constant', return_onesided=True, scaling='density',
        axis=-1, average='mean'):
    freqs, _, Pxy = _spectral_helper(x, y, fs, window, nperseg, noverlap, nfft,
                                     detrend, return_onesided, scaling, axis,
                                     mode='psd')

    # Average over windows.
    if len(Pxy.shape) >= 2 and Pxy.size > 0:
        if Pxy.shape[-1] > 1:
            if average == 'median':
                Pxy = np.median(Pxy, axis=-1) / _median_bias(Pxy.shape[-1])
            elif average == 'mean':
                Pxy = Pxy.mean(axis=-1)
            else:
                raise ValueError('average must be "median" or "mean", got %s'
                                 % (average,))
        else:
            Pxy = np.reshape(Pxy, Pxy.shape[:-1])

    return freqs, Pxy

def even_ext(x, n, axis=-1):
    if n < 1:
        return x
    if n > x.shape[axis] - 1:
        raise ValueError(("The extension length n (%d) is too big. " +
                         "It must not exceed x.shape[axis]-1, which is %d.")
                         % (n, x.shape[axis] - 1))
    left_ext = axis_slice(x, start=n, stop=0, step=-1, axis=axis)
    right_ext = axis_slice(x, start=-2, stop=-(n + 2), step=-1, axis=axis)
    ext = np.concatenate((left_ext,
                          x,
                          right_ext),
                         axis=axis)
    return ext

def odd_ext(x, n, axis=-1):
    if n < 1:
        return x
    if n > x.shape[axis] - 1:
        raise ValueError(("The extension length n (%d) is too big. " +
                         "It must not exceed x.shape[axis]-1, which is %d.")
                         % (n, x.shape[axis] - 1))
    left_end = axis_slice(x, start=0, stop=1, axis=axis)
    left_ext = axis_slice(x, start=n, stop=0, step=-1, axis=axis)
    right_end = axis_slice(x, start=-1, axis=axis)
    right_ext = axis_slice(x, start=-2, stop=-(n + 2), step=-1, axis=axis)
    ext = np.concatenate((2 * left_end - left_ext,
                          x,
                          2 * right_end - right_ext),
                         axis=axis)
    return ext

def axis_slice(a, start=None, stop=None, step=None, axis=-1):
    a_slice = [slice(None)] * a.ndim
    a_slice[axis] = slice(start, stop, step)
    b = a[tuple(a_slice)]
    return b

def axis_reverse(a, axis=-1):
    """Reverse the 1-D slices of `a` along axis `axis`.
    Returns axis_slice(a, step=-1, axis=axis).
    """
    return axis_slice(a, step=-1, axis=axis)

def const_ext(x, n, axis=-1):
    if n < 1:
        return x
    left_end = axis_slice(x, start=0, stop=1, axis=axis)
    ones_shape = [1] * x.ndim
    ones_shape[axis] = n
    ones = np.ones(ones_shape, dtype=x.dtype)
    left_ext = ones * left_end
    right_end = axis_slice(x, start=-1, axis=axis)
    right_ext = ones * right_end
    ext = np.concatenate((left_ext,
                          x,
                          right_ext),
                         axis=axis)
    return ext

def zero_ext(x, n, axis=-1):
    if n < 1:
        return x
    zeros_shape = list(x.shape)
    zeros_shape[axis] = n
    zeros = np.zeros(zeros_shape, dtype=x.dtype)
    ext = np.concatenate((zeros, x, zeros), axis=axis)
    return ext

### Helper functions ###
def _spectral_helper(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None,
                     nfft=None, detrend='constant', return_onesided=True,
                     scaling='density', axis=-1, mode='psd', boundary=None,
                     padded=False):
    if mode not in ['psd', 'stft']:
        raise ValueError("Unknown value for mode %s, must be one of: "
                            "{'psd', 'stft'}" % mode)
    boundary_funcs = {'even': even_ext,
                      'odd': odd_ext,
                      'constant': const_ext,
                      'zeros': zero_ext,
                      None: None}

    if boundary not in boundary_funcs:
        raise ValueError("Unknown boundary option '{0}', must be one of: {1}"
                         .format(boundary, list(boundary_funcs.keys())))

    # If x and y are the same object we can save ourselves some computation.
    same_data = y is x

    if not same_data and mode != 'psd':
        raise ValueError("x and y must be equal if mode is 'stft'")

    axis = int(axis)

    # Ensure we have np.arrays, get outdtype
    x = np.asarray(x)
    if not same_data:
        y = np.asarray(y)
        outdtype = np.result_type(x, y, np.complex64)
    else:
        outdtype = np.result_type(x, np.complex64)

    if not same_data:
        # Check if we can broadcast the outer axes together
        xouter = list(x.shape)
        youter = list(y.shape)
        xouter.pop(axis)
        youter.pop(axis)
        try:
            outershape = np.broadcast(np.empty(xouter), np.empty(youter)).shape
        except ValueError as e:
            raise ValueError('x and y cannot be broadcast together.') from e

    if same_data:
        if x.size == 0:
            return np.empty(x.shape), np.empty(x.shape), np.empty(x.shape)
    else:
        if x.size == 0 or y.size == 0:
            outshape = outershape + (min([x.shape[axis], y.shape[axis]]),)
            emptyout = np.rollaxis(np.empty(outshape), -1, axis)
            return emptyout, emptyout, emptyout

    if x.ndim > 1:
        if axis != -1:
            x = np.rollaxis(x, axis, len(x.shape))
            if not same_data and y.ndim > 1:
                y = np.rollaxis(y, axis, len(y.shape))

    # Check if x and y are the same length, zero-pad if necessary
    if not same_data:
        if x.shape[-1] != y.shape[-1]:
            if x.shape[-1] < y.shape[-1]:
                pad_shape = list(x.shape)
                pad_shape[-1] = y.shape[-1] - x.shape[-1]
                x = np.concatenate((x, np.zeros(pad_shape)), -1)
            else:
                pad_shape = list(y.shape)
                pad_shape[-1] = x.shape[-1] - y.shape[-1]
                y = np.concatenate((y, np.zeros(pad_shape)), -1)

    if nperseg is not None:  # if specified by user
        nperseg = int(nperseg)
        if nperseg < 1:
            raise ValueError('nperseg must be a positive integer')

    # parse window; if array like, then set nperseg = win.shape
    win, nperseg = _triage_segments(window, nperseg, input_length=x.shape[-1])

    if nfft is None:
        nfft = nperseg
    elif nfft < nperseg:
        raise ValueError('nfft must be greater than or equal to nperseg.')
    else:
        nfft = int(nfft)

    if noverlap is None:
        noverlap = nperseg//2
    else:
        noverlap = int(noverlap)
    if noverlap >= nperseg:
        raise ValueError('noverlap must be less than nperseg.')
    nstep = nperseg - noverlap

    # Padding occurs after boundary extension, so that the extended signal ends
    # in zeros, instead of introducing an impulse at the end.
    # I.e. if x = [..., 3, 2]
    # extend then pad -> [..., 3, 2, 2, 3, 0, 0, 0]
    # pad then extend -> [..., 3, 2, 0, 0, 0, 2, 3]

    if boundary is not None:
        ext_func = boundary_funcs[boundary]
        x = ext_func(x, nperseg//2, axis=-1)
        if not same_data:
            y = ext_func(y, nperseg//2, axis=-1)

    if padded:
        # Pad to integer number of windowed segments
        # I.e make x.shape[-1] = nperseg + (nseg-1)*nstep, with integer nseg
        nadd = (-(x.shape[-1]-nperseg) % nstep) % nperseg
        zeros_shape = list(x.shape[:-1]) + [nadd]
        x = np.concatenate((x, np.zeros(zeros_shape)), axis=-1)
        if not same_data:
            zeros_shape = list(y.shape[:-1]) + [nadd]
            y = np.concatenate((y, np.zeros(zeros_shape)), axis=-1)

    # Handle detrending and window functions
    if not detrend:
        def detrend_func(d):
            return d
    elif not hasattr(detrend, '__call__'):
        def detrend_func(d):
            return signaltools_detrend(d, type=detrend, axis=-1)
    elif axis != -1:
        # Wrap this function so that it receives a shape that it could
        # reasonably expect to receive.
        def detrend_func(d):
            d = np.rollaxis(d, -1, axis)
            d = detrend(d)
            return np.rollaxis(d, axis, len(d.shape))
    else:
        detrend_func = detrend

    if np.result_type(win, np.complex64) != outdtype:
        win = win.astype(outdtype)

    if scaling == 'density':
        scale = 1.0 / (fs * (win*win).sum())
    elif scaling == 'spectrum':
        scale = 1.0 / win.sum()**2
    else:
        raise ValueError('Unknown scaling: %r' % scaling)

    if mode == 'stft':
        scale = np.sqrt(scale)

    if return_onesided:
        if np.iscomplexobj(x):
            sides = 'twosided'
            warnings.warn('Input data is complex, switching to '
                          'return_onesided=False')
        else:
            sides = 'onesided'
            if not same_data:
                if np.iscomplexobj(y):
                    sides = 'twosided'
                    warnings.warn('Input data is complex, switching to '
                                  'return_onesided=False')
    else:
        sides = 'twosided'

    if sides == 'twosided':
        freqs = sp_fft_fftfreq(nfft, 1/fs)
    elif sides == 'onesided':
        freqs = sp_fft_rfftfreq(nfft, 1/fs)

    # Perform the windowed FFTs
    result = _fft_helper(x, win, detrend_func, nperseg, noverlap, nfft, sides)

    if not same_data:
        # All the same operations on the y data
        result_y = _fft_helper(y, win, detrend_func, nperseg, noverlap, nfft,
                               sides)
        result = np.conjugate(result) * result_y
    elif mode == 'psd':
        result = np.conjugate(result) * result

    result *= scale
    if sides == 'onesided' and mode == 'psd':
        if nfft % 2:
            result[..., 1:] *= 2
        else:
            # Last point is unpaired Nyquist freq point, don't double
            result[..., 1:-1] *= 2

    time = np.arange(nperseg/2, x.shape[-1] - nperseg/2 + 1,
                     nperseg - noverlap)/float(fs)
    if boundary is not None:
        time -= (nperseg/2) / fs

    result = result.astype(outdtype)

    # All imaginary parts are zero anyways
    if same_data and mode != 'stft':
        result = result.real

    # Output is going to have new last axis for time/window index, so a
    # negative axis index shifts down one
    if axis < 0:
        axis -= 1

    # Roll frequency axis back to axis where the data came from
    result = np.rollaxis(result, -1, axis)

    return freqs, time, result

def _fft_helper(x, win, detrend_func, nperseg, noverlap, nfft, sides):
    # Created strided array of data segments
    if nperseg == 1 and noverlap == 0:
        result = x[..., np.newaxis]
    else:
        # https://stackoverflow.com/a/5568169
        step = nperseg - noverlap
        shape = x.shape[:-1]+((x.shape[-1]-noverlap)//step, nperseg)
        strides = x.strides[:-1]+(step*x.strides[-1], x.strides[-1])
        result = np.lib.stride_tricks.as_strided(x, shape=shape,
                                                 strides=strides)

    # Detrend each data segment individually
    result = detrend_func(result)

    # Apply window by multiplication
    result = win * result

    # Perform the fft. Acts on last axis by default. Zero-pads automatically
    if sides == 'twosided':
        func = sp_fft_fft
    else:
        result = result.real
        func = sp_fft_rfft
    result = func(result, n=nfft)

    return result

def signaltools_detrend(data, axis=-1, type='linear', bp=0, overwrite_data=False):
    if type not in ['linear', 'l', 'constant', 'c']:
        raise ValueError("Trend type must be 'linear' or 'constant'.")
    data = np.asarray(data)
    dtype = data.dtype.char
    if dtype not in 'dfDF':
        dtype = 'd'
    if type in ['constant', 'c']:
        ret = data - np.expand_dims(np.mean(data, axis), axis)
        return ret
    else:
        dshape = data.shape
        N = dshape[axis]
        bp = np.sort(np.unique(np.r_[0, bp, N]))
        if np.any(bp > N):
            raise ValueError("Breakpoints must be less than length "
                             "of data along given axis.")
        Nreg = len(bp) - 1
        # Restructure data so that axis is along first dimension and
        #  all other dimensions are collapsed into second dimension
        rnk = len(dshape)
        if axis < 0:
            axis = axis + rnk
        newdims = np.r_[axis, 0:axis, axis + 1:rnk]
        newdata = np.reshape(np.transpose(data, tuple(newdims)),
                             (N, _prod(dshape) // N))
        if not overwrite_data:
            newdata = newdata.copy()  # make sure we have a copy
        if newdata.dtype.char not in 'dfDF':
            newdata = newdata.astype(dtype)
        # Find leastsq fit and remove it for each piece
        for m in range(Nreg):
            Npts = bp[m + 1] - bp[m]
            A = np.ones((Npts, 2), dtype)
            A[:, 0] = np.cast[dtype](np.arange(1, Npts + 1) * 1.0 / Npts)
            sl = slice(bp[m], bp[m + 1])
            coef, resids, rank, s = np.linalg.lstsq(A, newdata[sl])
            newdata[sl] = newdata[sl] - np.dot(A, coef)
        # Put data back in original shape.
        tdshape = np.take(dshape, newdims, 0)
        ret = np.reshape(newdata, tuple(tdshape))
        vals = list(range(1, rnk))
        olddims = vals[:axis] + [0] + vals[axis:]
        ret = np.transpose(ret, tuple(olddims))
        return ret

def sp_fft_fftfreq(n, d=1.0):
    return np.fft.fftfreq(n, d)

def sp_fft_rfftfreq(n, d=1.0):
    return np.fft.rfftfreq(n, d)

def sp_fft_rfft(x, n=None, axis=-1, overwrite_x=False):
    return np.fft.rfft(x, n, axis, None)

def sp_fft_fft(x, n=None, axis=-1, overwrite_x=False):
    return np.fft.fft(x, n, axis, None)


from unittest import TestCase, main
import ssc2ce_cpp as m

class TestCoinbaseParser(TestCase):
    def setUp(self):
        self.parser = m.CexParser()

        self.top_prices = {}
        self.top_bid = 0
        self.top_ask = 0
        self.book_setup_count = 0
        self.parser.set_on_book_setup(self.handle_book_setup)
        self.book_update_count = 0
        self.parser.set_on_book_update(self.handle_book_update)

    def handle_book_setup(self, book):
        if book.instrument() in self.top_prices:
            top = self.top_prices[book.instrument()]
            top["bid"] = book.top_bid_price()
            top["ask"] = book.top_ask_price()
        else:
            self.top_prices[book.instrument()] = dict(
                bid=book.top_bid_price(),
                ask=book.top_ask_price()
            )

        self.book_setup_count += 1

    def handle_book_update(self, book):
        top = self.top_prices[book.instrument()]
        top["bid"] = book.top_bid_price()
        top["ask"] = book.top_ask_price()
        self.book_update_count += 1

    def test_book(self):
        book_snapshot = '{"e":"order-book-subscribe","data":{"timestamp":1592738201,"bids":[[8355.0,0.80000000],[8354.9,0.08562700],[8354.6,0.26770000]],"asks":[[8384.3,0.80000000],[8384.4,0.10000000],[8392.4,1.00000000]],"pair":"BTC:EUR","id":346101544,"sell_total":"176.22612139","buy_total":"1330266.42"},"oid":"book-1", "ok":"ok"}'
        self.assertEqual(self.parser.parse(book_snapshot), True)

        book = self.parser.get_book("BTC:EUR")
        self.assertEqual(book.top_ask_price(), 8384.3)
        self.assertEqual(book.top_bid_price(), 8355.0)

        top = self.top_prices[book.instrument()]
        self.assertEqual(top["ask"], 8384.3)
        self.assertEqual(top["bid"], 8355.0)

        self.assertEqual(self.book_setup_count, 1)
        self.assertEqual(self.book_update_count, 0)

        book_update = '{"e":"md_update","data":{"id":346101545,"pair":"BTC:EUR","time":1592738202189,"bids":[[8355.1,0.08562700],[8354.9,0.00000000]],"asks":[]}}'
        self.assertEqual(self.parser.parse(book_update), True)

        self.assertEqual(top["ask"], 8384.3)
        self.assertEqual(top["bid"], 8355.1)

        book_update = '{"e":"md_update","data":{"id":346101546,"pair":"BTC:EUR","time":1592738206257,"bids":[],"asks":[[8334.9,0.26770000],[8412.2,0.00000000]]}}'
        self.assertEqual(self.parser.parse(book_update), True)

        self.assertEqual(top["ask"], 8334.9)
        self.assertEqual(top["bid"], 8355.1)

        self.assertEqual(self.book_setup_count, 1)
        self.assertEqual(self.book_update_count, 2)

if __name__ == '__main__':
    main()


from __future__ import division
from models.nade.nade_keras import RNade
import numpy as np
import unittest

__author__ = 'theopavlakou'

rng = np.random
np.set_printoptions(precision=4)

def sample(N):
    """
    Returns a vector of dimension 2 which has been sampled from a mixture of Gaussians
    with the following parameters:
        mean = [[1, 1], [-1, -1]]
        Covariances = [[[0.5, 0],
                        [0, 0.5]],
                        [[0.5, 0],
                        [0, 0.5]]]
        mixing coefficients = [0.25, 0.75]
    :param: N - Number of samples
    :return: an (N, 3) numpy array
    """
    X_1 = rng.multivariate_normal([1, 1], [[0.5, 0], [0, 0.5]], N)
    X_2 = rng.multivariate_normal([-1, -1], [[0.5, 0], [0, 0.5]], N)
    p = (rng.random((N, 1)) < 0.25).astype(int)
    return X_1*p + X_2*(1-p)

def log_probability_density_gaussian(X, mu, Sigma):
    """
    Returns the log probability density of a multivariate Gaussian with
    mean mu and covariance matrix Sigma.
    :param X:   (N, D) numpy array of data, with N being the number of
                examples and D being the dimension of the Gaussian.
    :param mu:  (D, ) numpy array: the mean of the Gaussian.
    :param Sigma: (D, D) numpy array: the covariance matrix.
    :return:    (N, ) numpy array with the log probability density of each
                example.
    """
    X = X - mu
    temp = np.linalg.solve(Sigma, X.T).T
    return -.5*(X*temp).sum(axis=1) - X.shape[1]/2*np.log(2*np.pi) - .5*np.linalg.slogdet(Sigma)[1]

def differential_entropy_under_mogs(X):
    """
    Gets the (sample) differential entropy of the data under the mixture
    of Gaussians defined in the function sample. This is given as the
    mean of the negative log probability of the data under the mixture
    of Gaussians' distribution.

    :param X:   (N, D) numpy array of data, with N being the number of
                examples and D being the dimension of the Gaussian.
    :return: a scalar.
    """
    p_x_1 = np.exp(log_probability_density_gaussian(X, np.array([1, 1]), np.array([[0.5, 0], [0, 0.5]])))
    p_x_2 = np.exp(log_probability_density_gaussian(X, np.array([-1, -1]), np.array([[0.5, 0], [0, 0.5]])))
    p_x = 0.25*p_x_1 + 0.75*p_x_2
    return -np.log(p_x).mean()

class TestRNade(unittest.TestCase):

    def test_works(self):
        ####################################
        # Load the data
        ####################################
        training_epoch_size = 100000
        X_train = sample(training_epoch_size).astype(np.float32)

        ####################################
        # Set up some variables
        ####################################
        D = X_train.shape[1]
        H = 20
        K = 2
        minibatch_size = 25

        ####################################
        # Train the network
        ####################################
        rnade = RNade(D, H, K)
        rnade.compile('adam', loss=rnade.cost)
        rnade.fit(X_train, X_train, batch_size=minibatch_size, nb_epoch=10)

        ####################################
        # Record costs
        ####################################
        print("")
        print("\n=============================================")
        print("===== Final cost for NADE {0} =====".format(rnade.evaluate(X_train, X_train)))
        print("=============================================\n")
        entropy = differential_entropy_under_mogs(X_train)
        print("Entropy of distribution is: {0}".format(entropy))
        self.assertLess(abs(entropy - rnade.evaluate(X_train, X_train)), 0.01)


import os
import zipfile
from conftest import RESOURCES_DIR

def test_zip_file():
    with zipfile.ZipFile(os.path.join(RESOURCES_DIR, 'file_hello.zip')) as zip_file:
        zip_file.extract('file_hello.txt', path=RESOURCES_DIR)
        name_list = zip_file.namelist()
        print(name_list)
        text = zip_file.read('file_hello.txt')
        print(text)
        assert 'file_hello.txt' in name_list
        assert text == b'Hello'
        assert os.path.isfile(os.path.join(RESOURCES_DIR, 'file_hello.txt'))

        os.remove(os.path.join(RESOURCES_DIR, 'file_hello.txt'))


import basf2 as b2
import modularAnalysis as ma
import variables.collections as vc
import sys

mode = sys.argv[1]
print("passed mode:", mode)

nfs_path = "/nfs/dust/belle2/user/axelheim/MC_studies/my6modes"
root_subdir = "wSim_wReco"

events_num_identifier = "_15000_events"
# create path
path = b2.create_path()

# load input ROOT file
ma.inputMdst(environmentType='default',
             filename=b2.find_file(nfs_path + "/rootfiles/" + root_subdir + f"/mode{mode}" + events_num_identifier + ".root"),
             path=path)

ma.fillParticleListsFromMC([('K+:gen', ''),# ('K-:gen', ''),
                    ('pi+:gen', ''),# ('pi-:gen', ''),
                    ('gamma:gen', "")], path=path)
# generate the decay string
#path.add_module('ParticleMCDecayString', listName='J/psi', fileName='hashmap_Jpsi_from_B2A502.root')

#ma.copyLists('Upsilon(4S):all', ['K+:gen','K-:gen','pi+:gen','pi-:gen','gamma:gen'], path=path)

# write out ntuples
var = ['M',
       'x', 'y', 'z'
       ]

ma.matchMCTruth("gamma:gen", path=path)
ma.matchMCTruth("pi+:gen", path=path)
ma.matchMCTruth("K+:gen", path=path)
var +=  vc.kinematics
var.append("kaonID")
var.append("pionID")
#var +=  "pionID"

var += vc.mc_truth
var.append("mcPhotos")
var.append("mcPrimary")
var.append("mcInitial")
var.append("charge")
var.append("uniqueParticleIdentifier")

var += ['genMotherID', 'genMotherPDG']
for i in range(4): # 4 deepest decay tree number of decays
    tmp_var = "genMotherPDG({})".format(i)
    #print(tmp_var)
    var.append(tmp_var)

#ma.combineAllParticles(['K+:gen','K-:gen','pi+:gen','pi-:gen','gamma:gen'], 'all:gen', path=path)

#ma.variablesToNtuple('Upsilon(4S):all', variables=var, filename='myFSP_nTuples_mode0.root', path=path)
file_extension = f"_nTuples_mode{mode}" + events_num_identifier + ".root"
print("example path to save data:", nfs_path + '/rootfiles/' + root_subdir + '/gamma' + file_extension)
ma.variablesToNtuple('gamma:gen',
                     variables=var,
                     filename=nfs_path + '/rootfiles/' + root_subdir + '/gamma' + file_extension,
                     path=path)
ma.variablesToNtuple('K+:gen',
                     variables=var,
                     filename=nfs_path + '/rootfiles/' + root_subdir + '/K' + file_extension,
                     path=path)
ma.variablesToNtuple('pi+:gen',
                     variables=var,
                     filename=nfs_path + '/rootfiles/' + root_subdir + '/pi' + file_extension,
                     path=path)
#ma.variablesToNtuple('all:gen',  variables=var, filename='allP_nTuples_mode0.root',  path=path)
# process the events
b2.process(path)

# print out the summary
print(b2.statistics)


""" Module for tables of the Auto Typing paper
"""

# Imports
from __future__ import print_function, absolute_import, division, unicode_literals

import numpy as np
import glob, os, sys
import warnings
import pdb

from pkg_resources import resource_filename

from astropy import units as u
from astropy.table import Table
from astropy.coordinates import SkyCoord, match_coordinates_sky
from astropy.time import Time

from linetools import utils as ltu

from spit import labels as spit_lbl

ddict = {'JAN': 1, 'FEB': 2, 'MAR': 3, 'APR': 4, 'MAY': 5,
    'JUN': 6, 'JUNE': 6, 'JUL': 7, 'JULY': 7, 'AUG': 8,
    'SEP': 9, 'SEPT': 9, 'OCT': 10, 'NOV': 11, 'DEC': 12}

# Local
#sys.path.append(os.path.abspath("../Analysis/py"))
#sys.path.append(os.path.abspath("../Vetting/py"))
#from vette_dr7 import load_ml_dr7

def mktab_images(outfil='tab_images.tex', sub=False):

    # Path
    path = os.getenv('SPIT_DATA')+'/Kast/FITS/'
    if sub:
        outfil = 'tab_images_sub.tex'

    # Scan image sets
    types, dates, frames, pis, flags, sets = [], [], [], [], [], []
    ntest, ntrain, nvalid = 0, 0, 0
    for iset in ['test', 'train', 'validation']:
        for itype in ['arc', 'bias', 'flat', 'science', 'standard']:
            files = glob.glob(path+'{:s}/{:s}/*fits.gz'.format(iset,itype))
            nimg = len(files)
            print("There are {:d} images of type {:s} in set {:s}".format(nimg, itype, iset))
            #
            types += [itype]*nimg
            sets += [iset]*nimg
            if iset == 'test':
                ntest += nimg
            elif iset == 'train':
                ntrain += nimg
            elif iset == 'validation':
                nvalid += nimg
            # Loop on the images
            for ipath in files:
                # Parse
                ifile = os.path.basename(ipath)
                if ifile[0] == '2':
                    pis += ['Prochaska']
                    # Find date
                    year = ifile[0:4]
                    try:
                        month = ddict[ifile[4:7].upper()]
                    except KeyError:
                        pdb.set_trace()
                    day = ifile[7:9]
                    dates.append('{:s}-{:d}-{:s}'.format(year,month,day))
                    # Frame
                    i1 = ifile.find('.fits')
                    frames.append(ifile[10:i1])
                else:
                    pis += ['Hsyu']
                    # Find date
                    i0 = ifile.find('_20')
                    year = ifile[i0+1:i0+5]
                    try:
                        month = ddict[ifile[0:4].upper()]
                    except:
                        month = ddict[ifile[0:3].upper()]
                        day = ifile[3:i0]
                    else:
                        day = ifile[4:i0]
                    dates.append('{:s}-{:d}-{:s}'.format(year,month,day))
                    # Frame
                    i1 = ifile.find('.fits')
                    frames.append(ifile[i0+6:i1])

    # Summarize
    print('-----------------------------------------')
    print('There are a total of {:d} training images'.format(ntrain))
    print('There are a total of {:d} test images'.format(ntest))
    print('There are a total of {:d} validation images'.format(nvalid))
    print('There are a total of {:d} images!'.format(nvalid+ntrain+ntest))

    # Build the table
    tbl = Table()
    tbl['Type'] = types
    tbl['Date'] = dates
    tbl['Frame'] = frames
    tbl['PI'] = pis
    tbl['set'] = sets
    # Sort
    tbl.sort(['Type', 'Date', 'Frame'])
    # Time
    t = Time(tbl['Date'], out_subfmt='date')

    # Make the LateX Table
    # Open
    tbfil = open(outfil, 'w')

    # tbfil.write('\\clearpage\n')
    tbfil.write('\\begin{deluxetable}{lccccc}\n')
    # tbfil.write('\\rotate\n')
    tbfil.write('\\tablewidth{0pc}\n')
    tbfil.write('\\tablecaption{Training Set\\label{tab:images}}\n')
    tbfil.write('\\tabletypesize{\\small}\n')
    tbfil.write('\\tablehead{\\colhead{Type?} & \\colhead{Date} \n')
    tbfil.write('& \\colhead{Frame} \n')
    tbfil.write('& \\colhead{Usage} \n')
    tbfil.write('} \n')

    tbfil.write('\\startdata \n')

    for ii,row in enumerate(tbl):
        if (ii > 15) & sub:
            break

        # Line
        iline = '{:s} & {:s} & {:s} & {:s}'.format(row['Type'], t[ii].value,
                                                   row['Frame'], row['set'])

        # End line
        tbfil.write(iline)
        tbfil.write('\\\\ \n')

    # End Table
    # End
    tbfil.write('\\enddata \n')
    #tbfil.write('\\tablenotetext{a}{Star/galaxy classifier from SExtractor with S/G=1 a star-like object.  Ignored for $\\theta < \\theta_{\\rm min}$.}\n')
    # tbfil.write('\\tablecomments{Units for $C_0$ and $C_1$ are erg/s/cm$^2$/\\AA\ and erg/s/cm$^2$/\\AA$^2$ respecitvely.}\n')
    # End
    tbfil.write('\\end{deluxetable} \n')
    #tbfil.write('\\hline \n')
    #tbfil.write('\\end{tabular} \n')
    #tbfil.write('\\end{minipage} \n')
    #tbfil.write('{$^a$}Restricted to systems with $\mzabs < \mzem$.\\\\ \n')
    #tbfil.write('{$^b$}Quasar is reported to exhibit BAL features by \cite{shen11} (1=True).  We caution that additional BAL features exist in the purported non-BAL quasars.\\\\ \n')
    #tbfil.write('{$^c$}DLA is new (0) or is also reported by N09 (1), PW09 (2), or both (3).\\\\ \n')
    #tbfil.write('\\end{table*} \n')

    #tbfil.write('\\enddata \n')
    #tbfil.write('\\tablenotetext{a}{Flag describing the continuum method applied: 0=Analysis based only on Lyman series lines; 1=Linear fit; 2=Constant fit; 3=Continuum imposed by hand.}\n')
    #tbfil.write('\\tablecomments{Units for $C_0$ and $C_1$ are erg/s/cm$^2$/\\AA\ and erg/s/cm$^2$/\\AA$^2$ respecitvely.}\n')
    # End
    #tbfil.write('\\end{deluxetable*} \n')

    tbfil.close()
    print('Wrote {:s}'.format(outfil))

#### ########################## #########################
def main(flg_tab):

    if flg_tab == 'all':
        flg_tab = np.sum( np.array( [2**ii for ii in range(5)] ))
    else:
        flg_tab = int(flg_tab)

    # DR7 Table
    if flg_tab & (2**0):
        mktab_images(sub=True)# outfil='tab_dr7_dlas_sub.tex', sub=True)
        mktab_images()# outfil='tab_dr7_dlas_sub.tex', sub=True)

# Command line execution
if __name__ == '__main__':

    if len(sys.argv) == 1:
        flg_tab = 0
        flg_tab += 2**0   # Image table
        #flg_tab += 2**1   # DR12
    else:
        flg_tab = sys.argv[1]

    main(flg_tab)


import os

from flask import Blueprint, jsonify

from ..decorators import required_login
from ..utilities import create_jwt

jwt_rest_bp = Blueprint('jwt_rest_bp', __name__)

@jwt_rest_bp.route('/api/v1/user', methods=['GET'])
@required_login
def jwt(user):
    username = user.username
    email = user.email
    token = create_jwt(username, email)
    return jsonify(token=token.decode('utf-8')), 200

@jwt_rest_bp.route('/api/v1/service_get_pub', methods=['GET'])
def get_pub():
    pub = os.environ.get('public_key')
    return jsonify(pub=pub), 200


#!/usr/bin/python3
import arcade

screen_width = 600
screen_height = 600

arcade.open_window(screen_width, screen_width, "drawing example")
arcade.set_background_color(arcade.color.WHITE)
arcade.start_render()

# draw the face
x = 300
y = 300
radius = 200
arcade.draw_circle_filled(x, y, radius, arcade.color.YELLOW)
# draw the right eye
x = 370
y = 350
radius = 20
arcade.draw_circle_filled(x, y, radius, arcade.color.BLACK)
# draw the LEFT EYE
x = 230
y = 350
radius = 20
arcade.draw_circle_filled(x, y, radius, arcade.color.BLACK)
# draw the smile
x = 300
y = 280
width = 120
height = 100
start_angle = 190
end_angle = 350
radius = 200
arcade.draw_arc_outline(x, y, width, height, arcade.color.BLACK, start_angle, end_angle, 10)
arcade.finish_render()
arcade.run()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Yijia Zheng
# @email : yj.zheng@siat.ac.cn
# @Time  : 2019/11/29 11:20:37

import rdkit
import rdkit.Chem as Chem
import copy
import sys
import argparse
from multiprocessing import Pool

from util.chemutils import get_clique_mol, tree_decomp, get_mol, get_smiles, set_atommap, enum_assemble, decode_stereo
from branch_jtnn.mol_tree import MolTree

lg = rdkit.RDLogger.logger()
lg.setLevel(rdkit.RDLogger.CRITICAL)

parser = argparse.ArgumentParser()
parser.add_argument('--mol_file', required=True)
parser.add_argument('--save_vocab_file', required=True)
parser.add_argument('--ncpu', type=int, default=8)
args = parser.parse_args()

cset = set()
with open(args.mol_file, 'r') as f:
    lines = f.readlines()
lines = [line[:-1] for line in lines]

def get_tree(smiles):
    return MolTree(smiles, 0)

pool = Pool(args.ncpu)
trees = pool.map(get_tree, lines)

for smiles in lines:
    mol = Chem.MolFromSmiles(smiles)
    for i in range(mol.GetNumAtoms()):
        cmol = get_clique_mol(mol, [i])
        cset.add(get_smiles(cmol))
for tree in trees:
    for c in tree.nodes:
        cset.add(c.smiles)

result = '\n'.join(sorted(cset))
with open(args.save_vocab_file, 'w') as f:
    f.write(result)

print('done', flush=True)


from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import inspect

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///portfolio.db'
db = SQLAlchemy(app)

class Portfolio(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    link = db.Column(db.String(100))

    def __init__(self, title, link):
        self.title = title
        self.link = link

@app.route('/')
def index():
    portfolios = Portfolio.query.all()
    return render_template('index.html', portfolios=portfolios)

@app.route('/drop', methods=['GET', 'POST'])
def drop_db():
    if request.method == 'POST':
        db.drop_all()
        db.session.commit()
        dbInit()

    portfolios = Portfolio.query.all()
    return render_template('index.html', portfolios=portfolios)

@app.route('/add', methods=['GET', 'POST'])
def add_portfolio():
    if request.method == 'POST':
        title = request.form['title']
        link = request.form['link']
        portfolio = Portfolio(title=title, link=link)
        db.session.add(portfolio)
        db.session.commit()
    return render_template('add.html')

def dbInit():
    with app.app_context():
        inspector = inspect(db.engine)
        if not inspector.has_table('portfolio'):
            db.create_all()
            print('Таблица "portfolio" создана')
        else:
            print('Таблица "portfolio" уже существует')

if __name__ == '__main__':
    dbInit()
    app.run(debug=True)


A=input()
B=input()

arr = [[0]*(len(B)+1) for _ in range(len(A)+1)]
for i in range(1, len(A)+1):
    for j in range(1, len(B)+1):
        if A[i-1] == B[j-1]:
            arr[i][j] = arr[i-1][j-1] + 1

ans=0
for i in arr:
    ans=max(max(i),ans)
print(ans)