from tkinter import *
import tkinter.messagebox
import threading
import random
import time
from pyvis.network import Network
from PetriNet import PetriNet

class qs34(PetriNet):
    def createWidgets(self):
        # ----------------------------------------------------------------------------------
        # CREATE GUI
        self.canvas = Canvas(self.master, bg="white", height="550")
        self.canvas.pack()
        self.canvas.grid(row=0, column=0, columnspan=12, sticky=W + E + N + S, padx=3, pady=3)
        # ----------------------------------------------------------------------------------

        # ----------------------------------------------------------------------------------
        # CREATE PLACE AND LABEL IT
        self.canvas.create_oval(370, 50, 440, 120)  # WAIT
        self.canvas.create_oval(510, 190, 580, 260)  # INSIDE
        self.canvas.create_oval(650, 50, 720, 120)  # DONE
        self.canvas.create_oval(230, 190, 300, 260)  # FREE
        self.canvas.create_oval(510, 330, 580, 400)  # BUSY
        self.canvas.create_oval(510, 470, 580, 540)  # DOCU

        widget = Label(self.canvas, text='WAIT', bg="white")
        widget.pack()
        self.canvas.create_window(405, 35, window=widget)

        self.label_wait = Label(self.canvas, text="0", bg="white")
        self.label_wait.pack()
        self.canvas.create_window(405, 85, window=self.label_wait)

        widget = Label(self.canvas, text='INSIDE', bg="white")
        widget.pack()
        self.canvas.create_window(545, 175, window=widget)

        self.label_inside = Label(self.canvas, text="0", bg="white")
        self.label_inside.pack()
        self.canvas.create_window(545, 225, window=self.label_inside)

        widget = Label(self.canvas, text='DONE', bg="white")
        widget.pack()
        self.canvas.create_window(685, 35, window=widget)

        self.label_done = Label(self.canvas, text="0", bg="white")
        self.label_done.pack()
        self.canvas.create_window(685, 85, window=self.label_done)

        widget = Label(self.canvas, text='FREE', bg="white")
        widget.pack()
        self.canvas.create_window(265, 175, window=widget)

        self.label_free = Label(self.canvas, text="0", bg="white")
        self.label_free.pack()
        self.canvas.create_window(265, 225, window=self.label_free)

        widget = Label(self.canvas, text='BUSY', bg="white")
        widget.pack()
        self.canvas.create_window(545, 315, window=widget)

        self.label_busy = Label(self.canvas, text="0", bg="white")
        self.label_busy.pack()
        self.canvas.create_window(545, 365, window=self.label_busy)

        widget = Label(self.canvas, text='DOCU', bg="white")
        widget.pack()
        self.canvas.create_window(545, 455, window=widget)

        self.label_docu = Label(self.canvas, text="0", bg="white")
        self.label_docu.pack()
        self.canvas.create_window(545, 505, window=self.label_docu)
        # ----------------------------------------------------------------------------------

        # ----------------------------------------------------------------------------------
        # CREATE TRANSITION, ADD USER CLICK AND LABEL IT
        self.canvas.create_rectangle(370, 190, 440, 260, tag="start")  # START
        self.canvas.create_rectangle(650, 190, 720, 260, tag="change")  # CHANGE
        self.canvas.create_rectangle(230, 470, 300, 540, tag="end")  # END

        widget = Label(self.canvas, text='START', bg="white", padx=0, pady=0)
        widget.pack()
        self.canvas.create_window(405, 250, window=widget)

        widget = Label(self.canvas, text='CHANGE', bg="white", padx=0, pady=0)
        widget.pack()
        self.canvas.create_window(685, 250, window=widget)

        widget = Label(self.canvas, text='END', bg="white", padx=0, pady=0)
        widget.pack()
        self.canvas.create_window(265, 530, window=widget)
        # ----------------------------------------------------------------------------------

        # ----------------------------------------------------------------------------------
        # FLOW RELATION
        self.canvas.create_line(440, 225, 510, 225, arrow=tkinter.LAST)  # START -> INSIDE
        self.canvas.create_line(580, 225, 650, 225, arrow=tkinter.LAST)  # INSIDE -> CHANGE
        self.canvas.create_line(405, 120, 405, 190, arrow=tkinter.LAST)  # WAIT -> START
        self.canvas.create_line(685, 190, 685, 120, arrow=tkinter.LAST)  # CHANGE -> DONE
        self.canvas.create_line(300, 225, 370, 225, arrow=tkinter.LAST)  # FREE -> START
        self.canvas.create_line(405, 260, 405, 365)  # START -> BUSY
        self.canvas.create_line(405, 365, 510, 365, arrow=tkinter.LAST)  # START -> BUSY
        self.canvas.create_line(685, 365, 685, 260, arrow=tkinter.LAST)  # BUSY -> CHANGE
        self.canvas.create_line(580, 365, 685, 365)  # BUSY -> CHANGE
        self.canvas.create_line(720, 225, 790, 225)  # CHANGE -> DOCU
        self.canvas.create_line(790, 225, 790, 505)  # CHANGE -> DOCU
        self.canvas.create_line(790, 505, 580, 505, arrow=tkinter.LAST)  # CHANGE -> DOCU
        self.canvas.create_line(510, 505, 300, 505, arrow=tkinter.LAST)  # DOCU -> END
        self.canvas.create_line(265, 470, 265, 260, arrow=tkinter.LAST)  # END -> FREE
        # ----------------------------------------------------------------------------------

        # ----------------------------------------------------------------------------------
        # FORM
        Label(self.master, text="FREE").grid(row=1, column=0)
        self.input_free = Entry(self.master)
        self.input_free.grid(row=1, column=1)

        Label(self.master, text="BUSY").grid(row=1, column=2)
        self.input_busy = Entry(self.master)
        self.input_busy.grid(row=1, column=3)

        Label(self.master, text="DOCU").grid(row=1, column=4)
        self.input_docu = Entry(self.master)
        self.input_docu.grid(row=1, column=5)

        Label(self.master, text="WAIT").grid(row=1, column=6)
        self.input_wait = Entry(self.master)
        self.input_wait.grid(row=1, column=7)

        Label(self.master, text="INSIDE").grid(row=1, column=8)
        self.input_inside = Entry(self.master)
        self.input_inside.grid(row=1, column=9)

        Label(self.master, text="DONE").grid(row=1, column=10)
        self.input_done = Entry(self.master)
        self.input_done.grid(row=1, column=11)
        # ----------------------------------------------------------------------------------

        # ----------------------------------------------------------------------------------
        # BUTTON
        self.run_button = Button(self.master, width=16, padx=3, pady=3)
        self.run_button['text'] = "RUN FIRE"
        self.run_button['command'] = self.run_fire
        self.run_button.grid(row=2, column=5, padx=2, pady=2)

        self.stop_button = Button(self.master, width=16, padx=3, pady=3)
        self.stop_button['text'] = "STOP FIRE"
        self.stop_button['command'] = self.stop_fire
        self.stop_button.grid(row=2, column=6, padx=2, pady=2)

        self.ts_button = Button(self.master, width=16, padx=3, pady=3)
        self.ts_button['text'] = "TRANSITION"
        self.ts_button['command'] = self.transition_system
        self.ts_button.grid(row=2, column=7, padx=2, pady=2)
        # ----------------------------------------------------------------------------------
        # LABEL MARKING
        self.label_marking = Label(self.canvas, text="MARKING M = [" + str(self.wait) + ".wait, "
                                                     + str(self.inside) + ".inside, " + str(self.done) + ".done, "
                                                     + str(self.free) + ".free, " + str(self.busy) + ".busy, "
                                                     + str(self.docu) + ".docu]"
                                   , bg="white")
        self.label_marking.pack()
        self.canvas.create_window(490, 10, window=self.label_marking)
        # ----------------------------------------------------------------------------------
    def run_fire(self):
        if (self.input_free.get() == "" and self.input_busy.get() == "" and self.input_docu.get() == ""
                    and self.input_wait.get()=="" and self.input_inside.get()== ""
                    and self.input_done.get()==""):
            tkinter.messagebox.showwarning("Error","Please fill parameter before run mode!")
            print("FAILED\n" + "-" * 30)
        elif (not (self.input_wait.get().isnumeric() and self.input_inside.get().isnumeric()
                    and self.input_done.get().isnumeric() and self.input_free.get().isnumeric()
                    and self.input_busy.get().isnumeric() and self.input_docu.get().isnumeric())):
            tkinter.messagebox.showwarning("Error","Please fill parameter >0!")
            print("FAILED\n" + "-" * 30)

        else:
            self.free = self.init_free = int(self.input_free.get())
            self.busy = self.init_busy = int(self.input_busy.get())
            self.docu = self.init_docu = int(self.input_docu.get())
            self.wait = self.init_wait = int(self.input_wait.get())
            self.inside = self.init_inside = int(self.input_inside.get())
            self.done = self.init_done = int(self.input_done.get())

            self.label_free.configure(text=str(self.init_free))
            self.label_busy.configure(text=str(self.init_busy))
            self.label_docu.configure(text=str(self.init_docu))
            self.label_wait.configure(text=str(self.init_wait))
            self.label_inside.configure(text=str(self.init_inside))
            self.label_done.configure(text=str(self.init_done))
            self.label_marking.configure(text="MARKING M_0 = [" + str(self.wait) + ".wait, "
                                              + str(self.inside) + ".inside, " + str(self.done) + ".done, "
                                              + str(self.free) + ".free, " + str(self.busy) + ".busy, "
                                              + str(self.docu) + ".docu]")
            print("SUCCESSFUL")
            print("Initial Marking: M0 = [" + str(self.wait) + ".wait, "
                  + str(self.inside) + ".inside, " + str(self.done) + ".done, "
                  + str(self.free) + ".free, " + str(self.busy) + ".busy, "
                  + str(self.docu) + ".docu]\n" + "-" * 30)

            if self.flag_auto == 1:
                pass
            else:
                self.flag_auto *= -1
                print("AUTO FIRE MODE ON\n" + "-" * 30)
                if self.flag_auto == 1:
                    self.input_free.configure(state = tkinter.DISABLED)
                    self.input_busy.configure(state = tkinter.DISABLED)
                    self.input_docu.configure(state = tkinter.DISABLED)
                    self.input_wait.configure(state=tkinter.DISABLED)
                    self.input_done.configure(state=tkinter.DISABLED)
                    self.input_inside.configure(state=tkinter.DISABLED)
                self.thread_auto_fire = threading.Thread(target=self.handle_fire)
                self.thread_auto_fire.start()

    def stop_fire(self):
        if self.flag_auto == -1:
            pass
        else:
            self.flag_auto *= -1
            if self.flag_auto == -1:
                self.input_free.configure(state = tkinter.NORMAL)
                self.input_busy.configure(state = tkinter.NORMAL)
                self.input_docu.configure(state = tkinter.NORMAL)
                self.input_wait.configure(state=tkinter.NORMAL)
                self.input_done.configure(state=tkinter.NORMAL)
                self.input_inside.configure(state=tkinter.NORMAL)
            print("AUTO FIRE MODE OFF\n" + "-" * 30)
    def transition_system(self):
        if (self.input_free.get() == "" and self.input_busy.get() == "" and self.input_docu.get() == ""
                and self.input_wait.get() == "" and self.input_inside.get() == ""
                and self.input_done.get() == ""):
            tkinter.messagebox.showwarning("Error", "Please fill parameter before run mode!")
        else:
            # FORM MARKING: [x.wait, y.inside, z.done, a.free, b.busy, c.docu]
            print("TRANSITION SYSTEM")
            self.markings = []
            self.state = 0
            self.transition = 0
            self.graph = Network(directed=True)

            current_marking = [self.init_free, self.init_busy, self.init_docu,
                               self.init_wait, self.init_inside, self.init_done]
            self.markings.append(current_marking)
            self.graph.add_node(0, label=str("[" + str(current_marking[3]) + ", "
                                             + str(current_marking[4]) + ", " + str(current_marking[5]) + ", "
                                             + str(current_marking[0]) + ", "
                                             + str(current_marking[1]) + ", " + str(current_marking[2]) + "]"))
            self.state += 1

            self.find_transition_relation(self.markings[0])

            self.graph.show_buttons(filter_='physics')
            self.graph.show('Transition System.html')

            print(str(self.state) + " states")
            print(str(self.transition) + " transitions\n" + "-" * 30)
    def find_transition_relation(self, current_marking):
        near_marking = self.find_near_marking(current_marking)
        for i in range (0, len(near_marking)):
            self.find_transition_relation(near_marking[i])

    def find_near_marking(self, current_marking):
        near = []
        if (current_marking[0] > 0 and current_marking[3] > 0):
            self.transition += 1
            marking = [current_marking[0] - 1, current_marking[1] + 1, current_marking[2]
                , current_marking[3] - 1, current_marking[4] + 1, current_marking[5]]

            node = str("[" + str(marking[3]) + ", "
                       + str(marking[4]) + ", " + str(marking[5]) + ", "
                       + str(marking[0]) + ", "
                       + str(marking[1]) + ", " + str(marking[2]) + "]")

            if not (marking in self.markings):
                self.graph.add_node(len(self.markings), label=node)
                near.append(marking)
                self.markings.append(marking)
                self.state += 1

            self.graph.add_edge(self.markings.index(current_marking), self.markings.index(marking), label="START")

            print("[" + str(current_marking[0]) + ".FREE, " + str(current_marking[1]) + ".BUSY, "
                  + str(current_marking[2]) + ".DOCU, "
                  + str(current_marking[3]) + ".WAIT, " + str(current_marking[4]) + ".INSIDE, "
                  + str(current_marking[5]) + ".DONE]"
                  + "; ---START---> "
                  + "[" + str(marking[0]) + ".FREE, " + str(marking[1]) + ".BUSY, "
                  + str(marking[2]) + ".DOCU, "
                  + str(marking[3]) + ".WAIT, " + str(marking[4]) + ".INSIDE, "
                  + str(marking[5]) + ".DONE]")

        if (current_marking[1] > 0 and current_marking[4] > 0):
            self.transition += 1
            marking = [current_marking[0], current_marking[1] - 1, current_marking[2] + 1
                , current_marking[3], current_marking[4] - 1, current_marking[5] + 1]

            node = str("[" + str(marking[3]) + ", "
                       + str(marking[4]) + ", " + str(marking[5]) + ", "
                       + str(marking[0]) + ", "
                       + str(marking[1]) + ", " + str(marking[2]) + "]")

            if not (marking in self.markings):
                self.graph.add_node(len(self.markings), label=node)
                near.append(marking)
                self.markings.append(marking)
                self.state += 1

            self.graph.add_edge(self.markings.index(current_marking), self.markings.index(marking), label="CHANGE")

            print("[" + str(current_marking[0]) + ".FREE, " + str(current_marking[1]) + ".BUSY, "
                  + str(current_marking[2]) + ".DOCU, "
                  + str(current_marking[3]) + ".WAIT, " + str(current_marking[4]) + ".INSIDE, "
                  + str(current_marking[5]) + ".DONE]"
                  + "; ---CHANGE---> "
                  + "[" + str(marking[0]) + ".FREE, " + str(marking[1]) + ".BUSY, "
                  + str(marking[2]) + ".DOCU, "
                  + str(marking[3]) + ".WAIT, " + str(marking[4]) + ".INSIDE, "
                  + str(marking[5]) + ".DONE]")

        if (current_marking[2] > 0):
            self.transition += 1
            marking = [current_marking[0] + 1, current_marking[1], current_marking[2] - 1
                , current_marking[3], current_marking[4], current_marking[5]]

            node = str("[" + str(marking[3]) + ", "
                       + str(marking[4]) + ", " + str(marking[5]) + ", "
                       + str(marking[0]) + ", "
                       + str(marking[1]) + ", " + str(marking[2]) + "]")

            if not (marking in self.markings):
                self.graph.add_node(len(self.markings), label=node)
                near.append(marking)
                self.markings.append(marking)
                self.state += 1

            self.graph.add_edge(self.markings.index(current_marking), self.markings.index(marking), label="END")

            print("[" + str(current_marking[0]) + ".FREE, " + str(current_marking[1]) + ".BUSY, "
                  + str(current_marking[2]) + ".DOCU, "
                  + str(current_marking[3]) + ".WAIT, " + str(current_marking[4]) + ".INSIDE, "
                  + str(current_marking[5]) + ".DONE]"
                  + "; ---END---> "
                  + "[" + str(marking[0]) + ".FREE, " + str(marking[1]) + ".BUSY, "
                  + str(marking[2]) + ".DOCU, "
                  + str(marking[3]) + ".WAIT, " + str(marking[4]) + ".INSIDE, "
                  + str(marking[5]) + ".DONE]")
        return near

    def handle_fire(self):
        while (self.flag_auto == 1 and self.flag_fire_start != 1 and self.flag_fire_change != 1 and self.flag_fire_end != 1):
            self.check_deadlock()
            self.fire()
            time.sleep(1.8)

    def check_deadlock(self):
        if (not self.is_start_enable()) and (not self.is_change_enable()) and (not self.is_end_enable()):
            print("DEADLOCK")
            self.stop_fire()

    def fire(self):
        if ((self.is_start_enable() and (not self.is_change_enable()) and (not self.is_end_enable())) or
                ((not self.is_start_enable()) and (self.is_change_enable()) and (not self.is_end_enable())) or
                ((not self.is_start_enable()) and (not self.is_change_enable()) and (self.is_end_enable()))):
            if self.is_start_enable():
                self.fire_start()
            elif self.is_change_enable():
                self.fire_change()
            elif self.is_end_enable():
                self.fire_end()

        elif self.is_start_enable() and (self.is_change_enable()) and (not self.is_end_enable()):
            self.fire_start()
            time.sleep(0.5)
            self.fire_change()
            time.sleep(0.5)

        elif self.is_start_enable() and (not self.is_change_enable()) and (self.is_end_enable()):
            self.fire_start()
            time.sleep(0.5)
            self.fire_end()

        elif (not self.is_start_enable()) and (self.is_change_enable()) and (self.is_end_enable()):
            self.fire_end()
            time.sleep(0.5)
            self.fire_change()

        elif self.is_start_enable() and self.is_change_enable() and self.is_end_enable():
            self.fire_start()
            time.sleep(0.5)
            self.fire_change()
            time.sleep(0.5)
            self.fire_end()

    def is_start_enable(self):
        if self.wait > 0 and self.free > 0:
            return True
        else:
            return False

    def is_change_enable(self):
        if self.inside > 0 and self.busy > 0:
            return True
        else:
            return False

    def is_end_enable(self):
        if self.docu > 0:
            return True
        else:
            return False

    def fire_start(self):
        if self.flag_fire_start == -1:
            self.start_dot_1 = self.canvas.create_oval(300, 220, 310, 230, fill="blue")
            self.start_dot_2 = self.canvas.create_oval(400, 120, 410, 130, fill="blue")

            self.flag_fire_start *= -1
            self.wait -= 1
            self.free -= 1

            self.label_wait.configure(text=str(self.wait))
            self.label_free.configure(text=str(self.free))

        if self.canvas.coords(self.start_dot_1)[0] < 500.0:
            self.canvas.move(self.start_dot_1, 100.0 / 24, 0)

        if self.canvas.coords(self.start_dot_2)[1] < 219.0:
            self.canvas.move(self.start_dot_2, 0, 100.0 / 24)
        elif self.canvas.coords(self.start_dot_2)[1] < 355.0:
            self.canvas.move(self.start_dot_2, 0, 10)
        else:
            self.canvas.move(self.start_dot_2, 10, 0)

        if self.canvas.coords(self.start_dot_2)[0] <= 500.0:
            self.canvas.after(20, self.fire_start)
        else:
            self.canvas.delete(self.start_dot_1)
            self.canvas.delete(self.start_dot_2)

            self.inside += 1
            self.busy += 1

            self.label_inside.configure(text=str(self.inside))
            self.label_busy.configure(text=self.busy)

            self.label_marking.configure(text="MARKING M = [" + str(self.wait) + ".WAIT, "
                                              + str(self.inside) + ".INSIDE, " + str(self.done) + ".DONE, "
                                              + str(self.free) + ".FREE, " + str(self.busy) + ".BUSY, "
                                              + str(self.docu) + ".DOCU]")

            self.flag_fire_start *= -1

    def fire_change(self):
        if self.flag_fire_change == -1:
            self.change_dot_1 = self.canvas.create_oval(580, 220, 590, 230, fill="blue")
            self.change_dot_2 = self.canvas.create_oval(580, 360, 590, 370, fill="blue")

            self.flag_fire_change *= -1
            self.inside -= 1
            self.busy -= 1

            self.label_inside.configure(text=str(self.inside))
            self.label_busy.configure(text=str(self.busy))

        if (self.canvas.coords(self.change_dot_1)[0] < 680.0
                and self.canvas.coords(self.change_dot_1)[1] == 220.0):
            self.canvas.move(self.change_dot_1, 10, 0)
        elif (self.canvas.coords(self.change_dot_1)[0] < 785.0
              and self.canvas.coords(self.change_dot_1)[1] == 220.0):
            self.canvas.move(self.change_dot_1, 10, 0)
        elif self.canvas.coords(self.change_dot_1)[1] < 500.0:
            self.canvas.move(self.change_dot_1, 0,10)
        elif self.canvas.coords(self.change_dot_1)[0] > 580.0:
            self.canvas.move(self.change_dot_1, -10, 0)

        if self.canvas.coords(self.change_dot_2)[0] < 680.0:
            self.canvas.move(self.change_dot_2, 10, 0)
        elif self.canvas.coords(self.change_dot_2)[1] > 220.0:
            self.canvas.move(self.change_dot_2, 0, -10)
        elif self.canvas.coords(self.change_dot_2)[1] > 120.0:
            self.canvas.move(self.change_dot_2, 0, -10)

        if (self.canvas.coords(self.change_dot_1)[0] != 580.0
                or self.canvas.coords(self.change_dot_1)[1] != 500.0):
            self.canvas.after(20, self.fire_change)
        else:
            self.canvas.delete(self.change_dot_1)
            self.canvas.delete(self.change_dot_2)

            self.done += 1
            self.docu += 1

            self.label_done.configure(text=str(self.done))
            self.label_docu.configure(text=str(self.docu))

            self.label_marking.configure(text="MARKING M = [" + str(self.wait) + ".WAIT, "
                                              + str(self.inside) + ".INSIDE, " + str(self.done) + ".DONE, "
                                              + str(self.free) + ".FREE, " + str(self.busy) + ".BUSY, "
                                              + str(self.docu) + ".DOCU]")

            self.flag_fire_change *= -1

    def fire_end(self):
        if self.flag_fire_end == -1:
            self.end_dot = self.canvas.create_oval(510, 500, 500, 510, fill="blue")

            self.flag_fire_end *= -1
            self.docu -= 1

            self.label_docu.configure(text=str(self.docu))

        if self.canvas.coords(self.end_dot)[0] > 260.0:
            self.canvas.move(self.end_dot, -10, 0)
        elif self.canvas.coords(self.end_dot)[1] > 260.0:
            self.canvas.move(self.end_dot, 0, -10)

        if self.canvas.coords(self.end_dot)[1] != 260.0:
            self.canvas.after(20, self.fire_end)
        else:
            self.canvas.delete(self.end_dot)

            self.free += 1
            self.label_free.configure(text=str(self.free))

            self.label_marking.configure(text="MARKING M = [" + str(self.wait) + ".WAIT, "
                                              + str(self.inside) + ".INSIDE, " + str(self.done) + ".DONE, "
                                              + str(self.free) + ".FREE, " + str(self.busy) + ".BUSY, "
                                              + str(self.docu) + ".DOCU]")

            self.flag_fire_end *= -1

    def handler(self):
        if self.flag_auto == 1:
            self.stop_fire()

        if self.flag_fire_change == 1 or self.flag_fire_end == 1 or self.flag_fire_start == 1:
            tkinter.messagebox.showwarning('Error', "Mode Run Firing is Running!")

        if tkinter.messagebox.askokcancel("Quit app ?", "Are you sure to quit"):
            self.isClosed = 1
            self.master.destroy()


from gns3server.web.route import Route
from gns3server.controller import Controller
from gns3server.schemas.node import NODE_OBJECT_SCHEMA
from gns3server.schemas.template import TEMPLATE_USAGE_SCHEMA

import hashlib
import json

from gns3server.schemas.template import (
    TEMPLATE_OBJECT_SCHEMA,
    TEMPLATE_UPDATE_SCHEMA,
    TEMPLATE_CREATE_SCHEMA
)

import logging
log = logging.getLogger(__name__)

class TemplateHandler:
    """
    API entry points for template management.
    """

    @Route.post(
        r"/templates",
        description="Create a new template",
        status_codes={
            201: "Template created",
            400: "Invalid request"
        },
        input=TEMPLATE_CREATE_SCHEMA,
        output=TEMPLATE_OBJECT_SCHEMA)
    def create(request, response):

        controller = Controller.instance()
        template = controller.template_manager.add_template(request.json)
        # Reset the symbol list
        controller.symbols.list()
        response.set_status(201)
        response.json(template)

    @Route.get(
        r"/templates/{template_id}",
        status_codes={
            200: "Template found",
            400: "Invalid request",
            404: "Template doesn't exist"
        },
        description="Get an template",
        output=TEMPLATE_OBJECT_SCHEMA)
    def get(request, response):

        request_etag = request.headers.get("If-None-Match", "")
        controller = Controller.instance()
        template = controller.template_manager.get_template(request.match_info["template_id"])
        data = json.dumps(template.__json__())
        template_etag = '"' + hashlib.md5(data.encode()).hexdigest() + '"'
        if template_etag == request_etag:
            response.set_status(304)
        else:
            response.headers["ETag"] = template_etag
            response.set_status(200)
            response.json(template)

    @Route.put(
        r"/templates/{template_id}",
        status_codes={
            200: "Template updated",
            400: "Invalid request",
            404: "Template doesn't exist"
        },
        description="Update an template",
        input=TEMPLATE_UPDATE_SCHEMA,
        output=TEMPLATE_OBJECT_SCHEMA)
    def update(request, response):

        controller = Controller.instance()
        template = controller.template_manager.get_template(request.match_info["template_id"])
        # Ignore these because we only use them when creating a template
        request.json.pop("template_id", None)
        request.json.pop("template_type", None)
        request.json.pop("compute_id", None)
        request.json.pop("builtin", None)
        template.update(**request.json)
        response.set_status(200)
        response.json(template)

    @Route.delete(
        r"/templates/{template_id}",
        parameters={
            "template_id": "template UUID"
        },
        status_codes={
            204: "Template deleted",
            400: "Invalid request",
            404: "Template doesn't exist"
        },
        description="Delete an template")
    def delete(request, response):

        controller = Controller.instance()
        controller.template_manager.delete_template(request.match_info["template_id"])
        response.set_status(204)

    @Route.get(
        r"/templates",
        description="List of template",
        status_codes={
            200: "Template list returned"
        })
    def list(request, response):

        controller = Controller.instance()
        response.json([c for c in controller.template_manager.templates.values()])

    @Route.post(
        r"/templates/{template_id}/duplicate",
        parameters={
            "template_id": "Template UUID"
        },
        status_codes={
            201: "Template duplicated",
            400: "Invalid request",
            404: "Template doesn't exist"
        },
        description="Duplicate an template",
        output=TEMPLATE_OBJECT_SCHEMA)
    async def duplicate(request, response):

        controller = Controller.instance()
        template = controller.template_manager.duplicate_template(request.match_info["template_id"])
        response.set_status(201)
        response.json(template)

    @Route.post(
        r"/projects/{project_id}/templates/{template_id}",
        description="Create a node from a template",
        parameters={
            "project_id": "Project UUID",
            "template_id": "Template UUID"
        },
        status_codes={
            201: "Node created",
            404: "The project or template doesn't exist"
        },
        input=TEMPLATE_USAGE_SCHEMA,
        output=NODE_OBJECT_SCHEMA)
    async def create_node_from_template(request, response):

        controller = Controller.instance()
        project = controller.get_project(request.match_info["project_id"])
        node = await project.add_node_from_template(request.match_info["template_id"],
                                                    x=request.json["x"],
                                                    y=request.json["y"],
                                                    name=request.json.get("name"),
                                                    compute_id=request.json.get("compute_id"))
        response.set_status(201)
        response.json(node)


import torch
import utils
import argparse
from torch.utils.tensorboard import SummaryWriter
import os
import torchvision
import tqdm
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
import pytorch_warmup as warmup
from sklearn.metrics import f1_score
import torch.nn.functional as F
import torch.nn as nn
import math

parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--config_file',required=True,type=str)
parser.add_argument('--local_rank',type=int,default=-1)
parser.add_argument('--use_ddp',action='store_true',default=False)

class selfattention(nn.Module):
    def __init__(self, inplanes):
        super(selfattention, self).__init__()

        self.interchannel = inplanes
        self.inplane = inplanes
        self.g = nn.Conv2d(inplanes, inplanes, kernel_size=1, stride=1, padding=0)
        self.theta = nn.Conv2d(inplanes, self.interchannel, kernel_size=1, stride=1, padding=0)
        self.phi = nn.Conv2d(inplanes, self.interchannel, kernel_size=1, stride=1, padding=0)
        self.act = nn.LeakyReLU(0.1)

    def forward(self, x):
        b, c, h, w = x.size()
        g_y = self.g(x).view(b, c, -1)  # BXcXN
        theta_x = self.theta(x).view(b, self.interchannel, -1)
        theta_x = F.softmax(theta_x, dim=-1)  # softmax on N
        theta_x = theta_x.permute(0, 2, 1).contiguous()  # BXNXC'

        phi_x = self.phi(x).view(b, self.interchannel, -1)  # BXC'XN

        similarity = torch.bmm(phi_x, theta_x)  # BXc'Xc'

        g_y = F.softmax(g_y, dim=1)
        attention = torch.bmm(similarity, g_y)  # BXCXN
        attention = attention.view(b, c, h, w).contiguous()
        y = self.act(x + attention)
        return y

class BasicBlockNormal(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlockNormal, self).__init__()

        # Both self.conv1 and self.downsample layers downsample the input when stride != 1
        self.conv1 = nn.Conv2d(inplanes,planes,3,stride,1)
        self.relu = nn.LeakyReLU(negative_slope=0.1,inplace=True)
        self.conv2 = nn.Conv2d(planes,planes,3,1,1)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        identity = x

        out = self.conv1(x)
        out = self.relu(out)

        out = self.conv2(out)
        #out = self.relu(out)
        if self.downsample is not None:
            identity = self.downsample(x)
        out = (out + identity)
        return self.relu(out)

class FaceCycleBackboneSwapCLR(torch.nn.Module):
    def __init__(self):
        super(FaceCycleBackboneSwapCLR, self).__init__()

        self.conv1 = nn.Sequential(nn.Conv2d(3, 64, 7, 2, 3, bias=True),
                                   nn.LeakyReLU(negative_slope=0.1),
                                   nn.Conv2d(64, 64, 3, 1, 1, bias=True),
                                   nn.LeakyReLU(negative_slope=0.1))

        self.layer1 = nn.Sequential(nn.Conv2d(64, 64, 3, 1, 1, bias=True),
                                    nn.LeakyReLU(negative_slope=0.1),
                                    selfattention(64),
                                    nn.Conv2d(64, 64, 3, 1, 1, bias=True),
                                    nn.LeakyReLU(negative_slope=0.1))  # 64

        self.layer2_1 = nn.Sequential(nn.Conv2d(64, 128, 3, 2, 1, bias=True),
                                      nn.LeakyReLU(negative_slope=0.1),
                                      selfattention(128),
                                      nn.Conv2d(128, 128, 3, 1, 1, bias=True),
                                      nn.LeakyReLU(negative_slope=0.1), )  # 64

        self.resblock1 = BasicBlockNormal(128, 128)
        self.resblock2 = BasicBlockNormal(128, 128)

        self.layer2_2 = nn.Sequential(nn.Conv2d(128, 128, 3, 2, 1, bias=True),
                                      nn.LeakyReLU(negative_slope=0.1),
                                      nn.Conv2d(128, 128, 3, 1, 1, bias=True),
                                      nn.LeakyReLU(negative_slope=0.1), )  # 64

        self.layer3_1 = nn.Sequential(nn.Conv2d(128, 256, 3, 2, 1, bias=True),
                                      nn.LeakyReLU(negative_slope=0.1),
                                      nn.Conv2d(256, 128, 3, 1, 1, bias=True),
                                      nn.LeakyReLU(negative_slope=0.1), )  # 64

        self.layer3_2 = nn.Sequential(nn.Conv2d(128, 256, 3, 1, 1, bias=True),  # stride 2 for 128x128
                                      nn.LeakyReLU(negative_slope=0.1),
                                      nn.Conv2d(256, 128, 3, 1, 1, bias=True),
                                      nn.LeakyReLU(negative_slope=0.1),
                                      )  # 64
        #self.fc = nn.Identity()
        # self.exp_fc = nn.Sequential(nn.Linear(2048, 2048),
        #                             nn.ReLU(),
        #                             nn.Linear(2048, 512),
        #                             nn.BatchNorm1d(512))
        #
        # self.pose_fc = nn.Sequential(nn.Linear(2048, 2048),
        #                              nn.ReLU(),
        #                              nn.Linear(2048, 512),
        #                              nn.BatchNorm1d(512))

        #self.decoder = Generator(d_model=512)
        self.linear_classifier = torch.nn.Sequential(torch.nn.BatchNorm1d(config['linear_dim']),nn.Linear(6272, 3)).cuda()

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
                if m.bias is not None:
                    m.bias.data.zero_()
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, nn.Linear):
                m.weight.data.normal_(0, 0.01)
                m.bias.data.zero_()

    def forward(self, x):
        #encoder
        '''

        :param x: [batch,3,64,64]
        :return:
        '''
        out_1 = self.conv1(x) # [batch,64,32,32]
        out_1 = self.layer1(out_1) # [batch,64,32,32]
        out_2 = self.layer2_1(out_1) # [batch,128,16,16]
        out_2 = self.resblock1(out_2) # [batch,128,16,16]
        out_2 = self.resblock2(out_2) # [batch,128,16,16]
        out_2 = self.layer2_2(out_2) # [batch,128,8,8]
        out_3 = self.layer3_1(out_2) # [batch,256,4,4]
        out_3 = self.layer3_2(out_3).view(x.size()[0],-1)

        red = self.linear_classifier(out_3)
        #print(out_3.size())
        # expcode = self.fc(out_3) # [batch,256]
        #out_3 = self.fc(out_3)
        #exp_fea = self.exp_fc(out_3)
        #pose_fea = self.pose_fc(out_3)
        #fea = torch.cat([exp_fea,pose_fea],dim=1)
        #fea = exp_fea + pose_fea
        #return fea
        #return out_3
        #return exp_fea
        #return pose_fea
        #return exp_fea,pose_fea
        #return expcode
        return red

def eval(config,val_loader,model):
    cos_dis = torch.nn.CosineSimilarity(dim=1, eps=1e-6)
    label_list = []
    pred_list = []
    prob = []
    theta = config['theta']

    for i, data in tqdm.tqdm(enumerate(val_loader)):
        label = data['label']

        fea1, fea2 = model.linear_eval_id(data)
        pred = cos_dis(fea1, fea2)
        pred_bool = torch.zeros_like(pred)

        pred_bool[pred >= theta] = 1.
        pred_bool[pred<theta] = -1.
        pred_list.extend(pred_bool.tolist())
        prob.extend(pred.tolist())
        label_list.extend(label.tolist())

    acc_count = 0
    for i in range(len(label_list)):
        print('index: {},\t pred: {},\t prob: {},\t label: {}'.format(i + 1, pred_list[i], prob[i], label_list[i]))
        if pred_list[i] == label_list[i]:
            acc_count += 1

    linear_acc = acc_count / len(label_list)
    return linear_acc

def linear_eval(config,train_loader,val_loader,model,logger):
    best_linear_acc = 100.
    #theta = config['theta']
    if config['pose'] == 'all':
        config['out_dim']=3
    #linear_classifier = torch.nn.Linear(in_features=config['linear_dim'],out_features=config['out_dim']).cuda()
    #linear_classifier = FaceCycleBackboneSwapCLR().cuda()
    linear_classifier = torch.nn.Sequential(torch.nn.BatchNorm1d(num_features=config['linear_dim']),torch.nn.Linear(in_features=config['linear_dim'],out_features=config['out_dim'])).cuda()
    #linear_classifier.weight.data.normal_(mean=0.0,std=0.01)
    #linear_classifier.bias.data.zero_()
    optimizer = torch.optim.AdamW(linear_classifier.parameters(),lr=config['linear_lr'])
    #model = torchvision.models.resnet18(pretrained=False).cuda()
    #optimizer = torch.optim.Adam(model.model.parameters(), lr=config['linear_lr'])
    #optimizer = torch.optim.Adam(model.model.parameters(),lr=config['linear_lr'])
    lr_schduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=config['eval_epochs'])
    #criterizer = torch.nn.CosineEmbeddingLoss(margin=theta).cuda()
    #criterizer = torch.nn.MSELoss().cuda()
    criterizer = torch.nn.L1Loss()

    if config['linear_eval']:
        for eval_step in range(config['eval_epochs']):
            train_count = 0.
            train_loss = 0.
            cos_dis = torch.nn.CosineSimilarity(dim=1, eps=1e-6)
            label_list = []
            pred_list = []
            prob = []
            linear_classifier.train()
            model.model.train()
            train_loss_list = []
            for i, data in tqdm.tqdm(enumerate(train_loader)):
                label = data['label'].float().cuda()
                #print(label)
                #print(label.size())
                fea = model.linear_forward(data)
                pred = linear_classifier(fea)
                #print(fea1.size())
                loss = criterizer(pred,label)
                #print(loss.item())
                #print(loss)

                optimizer.zero_grad()
                loss.backward()
                optimizer.step()
                #train_loss += loss.item()
                train_loss_list.append(loss.item())

            #avg_train_loss = train_loss / train_count
            #acc_count = 0.
            #lr_schduler.step()
            #for i in range(len(label_list)):
            #    if pred_list[i] == label_list[i]:
            #        acc_count += 1
            #train_linear_acc = acc_count / len(label_list)

            linear_classifier.eval()
            model.model.eval()
            eval_loss_list = []
            eval_pitch_loss_list = []
            eval_yaw_loss_list = []
            eval_roll_loss_list = []
            for i,data in tqdm.tqdm(enumerate(val_loader)):
                label = data['label'].float().cuda()

                #fea1,fea2 = model.linear_forward_id(data)

                with torch.no_grad():
                    #fea = data['img_normal'].cuda()
                    fea = model.linear_forward(data)
                    #fea1 = F.normalize(fea1,dim=1)
                    #fea2 = F.normalize(fea2,dim=1)
                    #fea1 = model(data['img_normal1'].cuda())
                    #fea2 = model(data['img_normal2'].cuda())
                    pred = linear_classifier(fea)

                    #label_angle = label * 180 / np.pi
                    #fea = fea * 180 / np.pi
                    loss = criterizer(pred,label)
                    eval_loss_list.append(loss.item())

                    loss_pitch = criterizer(pred[:,0],label[:,0])
                    loss_yaw = criterizer(pred[:,1],label[:,1])
                    loss_roll = criterizer(pred[:,2],label[:,2])
                    eval_pitch_loss_list.append(loss_pitch.item())
                    eval_yaw_loss_list.append(loss_yaw.item())
                    eval_roll_loss_list.append(loss_roll.item())

            avg_train_loss = np.mean(train_loss_list)
            avg_eval_loss = np.mean(eval_loss_list)
            avg_eval_pitch_loss = np.mean(eval_pitch_loss_list)
            avg_eval_yaw_loss = np.mean(eval_yaw_loss_list)
            avg_eval_roll_loss = np.mean(eval_roll_loss_list)
            txt = 'eval step: {},\t train loss: {},\t eval loss: {},\t pitch loss: {},\t yaw loss: {},\t roll loss: {}'.format(eval_step,avg_train_loss,avg_eval_loss,avg_eval_pitch_loss,avg_eval_yaw_loss,avg_eval_roll_loss)
            print(txt)
            #logger.add_scalar('linear_train_acc_id',train_linear_acc,eval_step)
            logger.add_scalar('linear_train_loss_pose',avg_train_loss,eval_step)
            #logger.add_scalar('linear_eval_acc_id',eval_acc,eval_step)
            logger.add_scalar('linear_eval_loss_pose',avg_eval_loss,eval_step)

            if avg_eval_loss < best_linear_acc:
                best_linear_acc = avg_eval_loss
                model_state = model.model.state_dict()
                linear_state = linear_classifier.state_dict()
                for k in list(linear_state.keys()):
                    model_state[k] = linear_state[k]
                utils.save_checkpoint({
                    'epoch': eval_step + 1,
                    'state_dict': model_state,
                }, config)
    else:
        best_linear_acc = eval(config,val_loader,model)
    return best_linear_acc

def main(config,logger):
    model = utils.create_model(config)

    train_dataset = utils.create_dataset(config,'train')
    test_dataset = utils.create_dataset(config,'test')

    train_loader = torch.utils.data.DataLoader(
        train_dataset,
        batch_size=config['batch_size'],
        num_workers=config['num_threads'],
        pin_memory=True,
        drop_last=False,
        shuffle=True
    )
    test_loader = torch.utils.data.DataLoader(
        test_dataset,
        batch_size=config['batch_size'],
        num_workers=config['num_threads'],
        pin_memory=True,
        drop_last=False,
        shuffle=True
    )
    linear_acc = linear_eval(config,train_loader,test_loader,model,logger)
    print('test linear acc is : {}'.format(linear_acc))
    exit(0)

if __name__ == '__main__':
    opt = parser.parse_args()

    config = utils.read_config(opt.config_file)
    utils.init(config,opt.local_rank,opt.use_ddp)
    logger = SummaryWriter(log_dir=os.path.join(config['log_path'], config['experiment_name']),
                           comment=config['experiment_name'])

    main(config, logger)

    logger.close()


import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

url = "http://[2605:fd00:4:1001:f816:3eff:feb2:3536]/"

class TestInvitationReceived(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_invitation_received(self):
        driver = self.driver
        # login first
        driver.get(url)
        # enter Username credential
        elem1 = driver.find_element_by_xpath("/html/body/div/div/div/div/div[2]/div[2]/div/div/div[2]/div/input")
        assert elem1 != None
        elem1.send_keys("zuhao")
        elem1.send_keys(Keys.ENTER)
        # enter Password credential
        elem2 = driver.find_element_by_xpath("/html/body/div/div/div/div/div[2]/div[2]/div/div/div[3]/div/input")
        assert elem2 != None
        elem2.send_keys("5201314mwxely")
        elem2.send_keys(Keys.ENTER)
        # click Log in button
        elem3 = driver.find_element_by_xpath("/html/body/div/div/div/div/div[2]/div[2]/div/div/button/span[1]")
        assert elem3 != None
        elem3.click()
        # wait for redirection to the homepage
        driver.implicitly_wait(10)
        # go to invitation_received component
        elem4 = driver.find_element_by_xpath("/html/body/div/div/div[2]/div[1]/div/div[3]/a")
        elem4.click()
        # check if received invitations exist in the table
        elem5 = driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div[2]/div/div[2]/div[2]/div/div/div/table/tbody/tr[1]/td[1]")
        assert elem5 != None
        assert elem5.text != None   # check by Invitation Id
        # check Accept button
        # elem6 = driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div[2]/div/div[2]/div[2]/div/div/div/table/tbody/tr[1]/td[5]/div/button[1]/span[1]")
        # assert elem6 != None
        # assert elem6.text == "Accept"
        # check Decline button
        # elem7 = driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div[2]/div/div[2]/div[2]/div/div/div/table/tbody/tr[1]/td[5]/div/button[2]/span[1]")
        # assert elem7 != None
        # assert elem7.text == "Decline"

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()


import numpy as np
import matplotlib.pyplot as plt
import os
import sys

data = np.load("mnist.npz")
traind = data["arr_0"]
trainl = data["arr_2"]

# 1a)
print(np.argmax(traind[:, 0, 0]))  # --> 0
# 1b)
print(traind.mean(axis=2))  # long output! shape (60000,28)
# 1c)
print(traind.sum(axis=1))  # long output! shape (60000,28)

# 2a)
f, ax = plt.subplots(1, 1)
x_data = np.linspace(1, 5, 100)
y_data = 1. / x_data
ax.plot(x_data, y_data)
plt.show()
# 2b)
f, ax = plt.subplots(1, 1)
x_data = np.linspace(1, 5, 100)
y_data = 1. / x_data
ax.bar(x_data, y_data)
plt.show()
# 2c)
f, ax = plt.subplots(1, 1)
x_data = np.linspace(1, 5, 100)
y_data_1 = 1. / x_data
y_data_2 = np.sqrt(x_data)
ax.plot(x_data, y_data_1)
ax.plot(x_data, y_data_2)
plt.show()

# 3a)
indices = [5, 6, 7]
f, ax = plt.subplots(1, 3)

for i, index in enumerate(indices):
    ax[i].imshow(traind[index])
plt.show()

# 3b)
means = traind.mean(axis=(1, 2))
x_data = np.linspace(0, 60000, 60000)
f, ax = plt.subplots(1, 1)
ax.scatter(x_data, means)
plt.show()

# 3c)
means = traind.mean(axis=(1, 2))
mask = (means > 0.3)
strongImgs = traind[mask, :, :]

f, ax = plt.subplots(1, 3)
for i in range(0, 3):
    ax[i].imshow(strongImgs[i])
plt.show()

# 3d)
indices = np.random.randint(0, 60000, 10)
f, ax = plt.subplots(1, 10)

for i, index in enumerate(indices):
    ax[i].imshow(traind[index])
plt.show()

# 3e)
# create mask for images of class 5
numerical_classes = trainl.argmax(axis=1)
# gives a boolean array of 60000 entries
mask = (numerical_classes == 5)

# copy out all samples using the boolean array: mask indexing!
samples5 = traind[mask, :, :]

# display first 5 images of class 5
f, ax = plt.subplots(1, 10)
for i in range(0, 10):
    ax[i].imshow(samples5[i])
plt.show()


# Import TKinter module to build the GUI
import tkinter as tk
from tkinter import *

from Jacob_Backend import Backend

main = tk.Tk()

# these global variables are needed so that I can continously check them, becuase they are not attributes of the GUI I must have
# them be global, otherwise they would be local variables and I would be unable to compare them across iterations
global val1, val2, val3
global ol_val1, ol_val2, ol_val3

val1 = 0
val2 = 0
val3 = 0

class GUI:
    # this function is responsible for detecting if a change has been made on the sliders every .5 seconds and tells the pump to actuate
    #if the volumes have been changed, else nothing
    def update_after(self):
        global val1, val2, val3
        global ol_val1, ol_val2, ol_val3

        ol_val1 = val1
        ol_val2 = val2
        ol_val3 = val3

        val1 = self.c1.get()
        val2 = self.c2.get()
        val3 = self.c3.get()

        #check if cural and old_val are different if they r actuate that pump
        self.check_different()

        main.after(500, self.update_after) #this function is in here because I need access to main(that why its not in backend)
        #every .5 sec it recursively calls itself and checks the values if they r diff pumps get moved

    # check if curval and old_val are different if they r, actuate that pump
    # this is really the driver of the program,
    # if the slider values are different it will run that task for the apprppritate task
    def check_different(self):
        if val1 != ol_val1:
            self.backend.pump_1_thread_task()
        if val2 != ol_val2:
            self.backend.pump_2_thread_task()
        if val3 != ol_val3:
            self.backend.pump_3_thread_task()
        #print(val1, val2, val3)

    def __init__(self):
        # Import the Backend code to communicate with the pumps
        self.backend = Backend(self)

        # Initialize sliders at 0
        self.c1 = 0
        self.c2 = 0
        self.c3 = 0

        # Initialize syringe pump parameters at 0
        self.diam = 0
        self.vol = 0
        self.rate = 0
        self.max = 0

        # Title
        self.title = Label(main, text = "Syringe Control Panel")
        self.title.grid(row = 1, column = 2)

        # Chamber 1 controls
        # ------------------#
        self.up1 = Button(main, text = "\u2B99", command = lambda: self.c1.set(self.c1.get()+1))
        self.up1.grid(row = 2, column = 1)

        self.c1 = Scale(main, from_ = 100, to = 0, length = 300, showvalue = 0, command = lambda x: self.c1_label.configure(text = "Chamber 1:" + " " + x + "%"))

        self.c1.grid(row = 3, column = 1)

        self.down1 = Button(main, text = "\u2B9B", command = lambda: self.c1.set(self.c1.get()-1))
        self.down1.grid(row = 4, column = 1)

        self.c1_label = Label(main, text = "Chamber 1:" + " " + str(self.c1.get()) + "%")
        self.c1_label.grid(row = 5, column = 1)
        # ------------------#

        # Chamber 2 controls
        # ------------------#
        self.up2 = Button(main, text = "\u2B99", command = lambda: self.c2.set(self.c2.get()+1))
        self.up2.grid(row = 2, column = 2)

        self.c2 = Scale(main, from_ = 100, to = 0, length = 300, showvalue = 0, command = lambda x: self.c2_label.configure(text = "Chamber 2:" + " " + x + "%"))
        self.c2.grid(row = 3, column = 2)

        self.down2 = Button(main, text = "\u2B9B", command = lambda: self.c2.set(self.c2.get()-1))
        self.down2.grid(row = 4, column = 2)

        self.c2_label = Label(main, text = "Chamber 2:" + " " + str(self.c2.get()) + "%")
        self.c2_label.grid(row = 5, column = 2)
        # ------------------#

        # Chamber 3 controls
        # ------------------#
        self.up3 = Button(main, text = "\u2B99", command = lambda: self.c3.set(self.c3.get()+1))
        self.up3.grid(row = 2, column = 3)

        #self.c3 = Scale(main, from_=100, to=0, length=300, showvalue=0,command=self.backend.cmd_3())
        self.c3 = Scale(main, from_ = 100, to = 0, length = 300, showvalue = 0, command = lambda x: self.c3_label.configure(text = "Chamber 3:" + " " + x + "%"))
        self.c3.grid(row = 3, column = 3)

        self.down3 = Button(main, text = "\u2B9B", command = lambda: self.c3.set(self.c3.get()-1))
        self.down3.grid(row = 4, column = 3)

        self.c3_label = Label(main, text = "Chamber 3:" + " " + str(self.c3.get()) + "%")
        self.c3_label.grid(row = 5, column = 3)
        # ------------------#

        #im going to add a textbox instead of the slider becuase the slider is causing some issues because of the update freq

        #self.c3_text = Button(main, height = 1, width = 5, text = "enter desired % of volume", command = lambda: self.c3_text.set(self.c3_text.get()))
       # self.c3_text.grid(row = 5, column = 3)

        # Go button controls
        self.go_button = Button(main, text = "Play", command = lambda: self.backend.buttonPush())
        self.go_button.grid(row = 6, column = 2)

        # Syringe settings text boxes
        # ------------------#
        self.diam_label = Label(main, text = "Syringe Diameter:    ")
        self.diam_label.grid(row = 1, column = 4)

        self.diam_entry = Entry(main, width = 5)
        self.diam_entry.grid(row = 2, column = 4, sticky = W)

        self.diamunit = Label(main, text = "[mm]")
        self.diamunit.grid(row = 2, column = 4)

        #---#

        self.vol_label = Label(main, text = "Syringe Volume:    ")
        self.vol_label.grid(row = 1, column = 5)

        self.vol_entry = Entry(main, width = 5)
        self.vol_entry.grid(row = 2, column = 5, sticky = W)

        self.volunit = Label(main, text = "[mL]")
        self.volunit.grid(row = 2, column = 5)

        #---#

        self.rate_label = Label(main, text = "Syringe Rate:           ")
        self.rate_label.grid(row = 1, column = 6)

        self.rate_entry = Entry(main, width = 5)
        self.rate_entry.grid(row = 2, column = 6, sticky = W)

        self.rateunit = Label(main, text = "[mL/min]")
        self.rateunit.grid(row = 2, column = 6)

        #---#

        self.maxvol_label = Label(main, text = "Max Volume:        ")
        self.maxvol_label.grid(row = 1, column = 7)

        self.maxvol_entry = Entry(main, width = 5)
        self.maxvol_entry.grid(row = 2, column = 7, sticky = W)

        self.maxvolunit = Label(main, text = "[mL]")
        self.maxvolunit.grid(row = 2, column = 7)

        #Check Button Controls#

        self.check_button = Button(main, text="Check Pumps", command=lambda: self.backend.check_button())
        self.check_button.grid(row=6, column=4)

        self.display_vol_button = Button(main, text="Display Volume", command=lambda: self.backend.display_vol_button())
        self.display_vol_button.grid(row=6, column=6)

        # Stop Button Controls#
        self.stop_button = Button(main, text="Stop Pumps", command=lambda: self.backend.stop_button())
        self.stop_button.grid(row=6, column=8)

if __name__ == "__main__":
    GUI()
    main.mainloop()


import square
print("Select the desired shape for the calculation")
choice=input("If you want to calculate a triangle, enter 1, if circle 2 and rectangle 3:")
if choice=='1': #For circle
    print (square.circle(r=float(input("enter radius:"))))
elif choice=='2': #For rectangle
    print (square.rectangle(a=float(input("enter one side of the rectangle:")),
                                 b=float(input("enter the other side of the rectangle:"))))
elif choice=='3': #For triangle
    print(square.triangle(a=float(input("enter the length of the side of the triangle:")),
                          h=float(input("enter the height of the triangle:"))))
else:
    print ("mistake! Invalid input!")


from django.urls import path, include
from .views import *

urlpatterns = [
    path("register/", register_view, name="register"),
    path("login/", login_view, name="login"),
    path("logout/", user_logout, name="logout"),
    path('edit_profile/', edit_profile, name='edit_profile'),
    path('profile/<str:username>/', profile, name='profile'),
    path('laboratory_seven/', laboratory_seven, name='lab7'),
    path('create_record/', create_record, name='create_record'),
    path('delete_record/<int:el_id>', delete_rec, name='delete_rec'),
    path('update_record/<int:pk>/', UpdateRecord.as_view(), name='update_record'),
]


import streamlit as st
import functions

todos = functions.get_todos()

def add_todo():
    this_todo = st.session_state["new_todo"] + "\n"
    todos.append(this_todo)
    functions.write_todos(todos)
    st.session_state["new_todo"] = ""

st.title("My todo app")
for i, todo in enumerate(todos):
    checkbox = st.checkbox(todo, key=todo)
    if checkbox == True:
        todos.pop(i)
        functions.write_todos(todos)
        del st.session_state[todo]
        st.experimental_rerun()
st.text_input(label="Enter a todo", placeholder="Add a new todo",
              on_change=add_todo, key="new_todo",value=st.session_state.get("new_todo",""))


import urllib
from bs4 import BeautifulSoup
from functools import reduce

class Webpage_content:
    """
        Instantiate a webpage_content.
        In **kwargs, need to be passed :
            - target url
            - html tag for which we want to retrieve text
            - and criterias to define html subset to look data within (optional, if not specified, entire html)
    """
    url = None
    tag_to_retrieve = None
    html_subset = None

    def __init__(self, **kwargs):
        # set class attributes, and check mandatory ones are there
        for key, value in kwargs.items():
            setattr(self, key, value)

        if not self.url or not self.tag_to_retrieve:
            raise ValueError('Target URL and target HTML tag must be provided')

        # get html
        response = urllib.request.urlopen(self.url)
        my_html = response.read()
        soup = BeautifulSoup(my_html, "html5lib", from_encoding="ISO-8859-16")
        # get html subset we want to get data from, if any specified
        if self.html_subset:
            self.html_subset = soup.find(*self.html_subset)

        #my_list = self.get_all_matching_html_children(self)

    def get_all_matching_html_children(self, *args):
        """
            Iterate over a given html and return a list with all smallest html children matching a given tag.
            Finally return an output_list of all smallest htmls children.
        """
        if not args:
            my_list = [self.html_subset] #first time the recursive function in launched, use html_subset
        else:
            my_list = args
            my_list = my_list[1:] # to exclude 'self'
            my_list = my_list[0] # to get back to a list, and not

        temp_list = []
        available_children_in_list = False  # to track existence of possible child within output_list
        for my_html in my_list:
            available_children_in_given_item = False  # to track existence of possible child for a given item
            list_of_children = [item for item in my_html.children]
            for child in list_of_children:
                try:
                    child[self.tag_to_retrieve]
                    temp_list.append(child)
                    available_children_in_list = True
                    available_children_in_given_item = True
                except (KeyError, TypeError):
                    pass
            if not available_children_in_given_item:  # if for a given item there is no possible child, keep original one in the list
                temp_list.append(my_html)

        if not available_children_in_list:  # repeat operation until there are no remaining possible child
            return temp_list
        else:
            return self.get_all_matching_html_children(self, temp_list)

    def get_text_data(self, input_list_html):
        """
            From a list of htlm elements, returns all text contained.
            Output_list = 1 list item per html element in input_list (input list and output list of same length)
        """
        output_list = []
        for child in input_list_html:
            data_in_child = [i for i in child.stripped_strings]
            if len(data_in_child):
                # print(child[html_tag])
                output_list.append(reduce(lambda x, y: x + ' ' + y, data_in_child))  # to get 1 list item whatever number of items in data_in_child
        return output_list

    def build_output_dict(self, list_of_keys, list_of_values):
        my_dict = {}
        if len(list_of_keys) == len(list_of_values):
            for key in list_of_keys:
                my_dict[key] = list_of_values[list_of_keys.index(key)]
            return my_dict
        else:
            print('\n'+'-'*5)
            print('Warning, in webpage dict : list of keys provided is of different length that list of values provided')
            min_args = min(len(list_of_keys), len(list_of_values))
            for key in list_of_keys[0:min_args]:
                my_dict[key] = list_of_values[list_of_keys.index(key)]
            return my_dict

class Webpage_content_lbc(Webpage_content):
    """
        Instantiate a webpage_content for Le Bon Coin website.
        Gets attributes and methods from Webpage content.
    """
    output_dict_list_of_keys = []
    output_dict_list_of_values = []
    output_dict = {}

    def __init__(self, **kwargs):
        Webpage_content.__init__(self, **kwargs)
        my_html_list = self.get_all_matching_html_children()
        my_text = self.get_text_data(my_html_list)

        # specific to lbc website (depending of what is in my_text)
        self.output_dict_list_of_keys = ['Date', 'Vendeur']
        self.output_dict_list_of_values = []
        self.output_dict_list_of_keys.extend(my_text[2::2])
        self.output_dict_list_of_values = my_text[0:2]
        self.output_dict_list_of_values.extend(my_text[3::2])

        self.output_dict = self.build_output_dict(self.output_dict_list_of_keys, self.output_dict_list_of_values)

#--------------------
#TESTS
#--------------------
#my_url = 'https://www.leboncoin.fr/ventes_immobilieres/1097856199.htm?ca=12_s'
#my_tag_to_retrieve = 'class'
#args_html_subset_tags = ('section', {'class':'properties lineNegative'})
#kwargs_input = {'url': my_url, 'tag_to_retrieve': my_tag_to_retrieve, 'html_subset': args_html_subset_tags}

#kwargs_input_lbc = {'url': my_url, 'tag_to_retrieve': my_tag_to_retrieve, 'html_subset': args_html_subset_tags}
#my_webpage_lbc = Webpage_content_lbc(**kwargs_input_lbc)
#print(my_webpage_lbc.output_dict)

#my_webpage = Webpage_content(**kwargs_input)
#my_list = my_webpage.get_all_matching_html_children()
#my_text = my_webpage.get_text_data(my_list)
#print(my_text)
#import pdb; pdb.set_trace()
# define keys for output_dict
#OUTPUT_DICT_LIST_OF_KEYS = ['date_mise_en_ligne', 'vendeur']
#OUTPUT_DICT_LIST_OF_KEYS.extend(my_text[2::2])

# building of values to pass in output_dict and building output dict
#output_dict_list_of_values = my_text[0:2]
#output_dict_list_of_values.extend(my_text[3::2])

#output_dict = my_webpage.build_output_dict(OUTPUT_DICT_LIST_OF_KEYS, output_dict_list_of_values)
#print(output_dict)


import asyncio
import contextlib
import os
import sys
from asyncio import Queue

from Util import write_util, read_util, write_from_queue
import aiofiles.threadpool as nbt

async def read_handler(reader):
    """Read handler for concurrent read"""
    async for data in read_util(reader):
        print(f'Received: {data.decode()!r}')

async def stream_to_queue(file, write_queue):
    """Function to save streams to queue"""
    loop = asyncio.get_event_loop()
    async for message in nbt.wrap(file, loop=loop):  # non blocking io read
        await write_queue.put(message.encode())

async def main(file):
    reader, writer = await asyncio.open_connection(
        os.environ["SERVER_HOST"],
        os.environ["SERVER_PORT"])

    write_queue = Queue()
    rh = asyncio.create_task(read_handler(reader))  # concurrent reading
    wh = asyncio.create_task(write_from_queue(writer, write_queue))  # concurrent write from queue
    ch = asyncio.create_task(stream_to_queue(file, write_queue))  # concurrent stdin to queue

    done, pending = await asyncio.wait([rh,
                                        wh,
                                        ch],
                                       return_when=asyncio.FIRST_COMPLETED)

    print("Closing connection")  # reaches when we cancel the connection
    for task in pending:  # closing the pending connections
        task.cancel()

if __name__ == "__main__":
    asyncio.run(main(sys.stdin))  # check why stdin works not input, does not strip new line


import numpy as np
from collections import Counter
import random
import datetime

def wordcounter(text):
    # 返回词典、词典位置、词频。
    with open(text, 'r', encoding="utf-8") as fp:
        res = fp.read().splitlines()
    res = '/'.join(res)
    doc = res.split('/')  # doc 是由词组成的语料，类型是列表
    voc = list(set(doc))  # voc 是词典。
    freq = Counter(doc)  # freq是个字典，保存词频
    freq_dict = dict(zip(voc, [pow(freq[item], 0.75) for item in voc]))
    freq_length = sum(freq_dict.values())
    return doc, voc, freq, freq_length, freq_dict

def negtive_sampling(word, freq, v, length, fd):
    # word 是窗口内容，freq词频，v词表
    # 返回一个列表，包含window个负采样到的词
    neg = []
    m = pow(10, 8)
    for i in range(len(word) - 1):
        sum_len = 0
        r = random.randint(1, m) * length / m
        for item in v:
            sum_len += fd[item]
            if r < sum_len:
                if item not in word:
                    neg.append(item)
                    break
    return neg

def sigmoid(z):
    return 1/(1 + np.exp(-z))

def skip_gram(text):  # 基于负采样算法的实现
    # 输入text是分好词的列表。词之间用'/'隔开，可以有换行。
    # 例如 text=
    # '我/以前/在/东京/打/篮球/但/我的/技术/没有/很好
    # 中国/的/上海/美丽/城市/我/喜欢/去/上海/旅行/我/昨天/坐/火车/到达/上海/火车站
    # 返回值：vector是词向量矩阵，vocabulary是词汇列表，用'/'分割。
    corpus, vocabulary, freq, freq_length, freq_dict = wordcounter(text)
    pos = [i for i in range(len(vocabulary))]
    v_dict = dict(zip(vocabulary, pos))  # v_dict是个字典，给每个词编一个独立的号。
    index = 50  # 词向量的维度
    w = np.random.random((len(vocabulary), index))  # w的每一行是一个参数向量
    vector = np.random.random((len(vocabulary), index))
    alpha = 0.01
    window = 3  # 窗口大小，最小为2。
    print('语料长度：', len(corpus), '词典大小：', len(vocabulary))
    for iters in range(100):
        start = 0
        while start+window <= len(corpus):
            current = corpus[start + int(window/2)]
            context = [corpus[temp] for temp in range(start, start+window)]
            neg_s = negtive_sampling(context, vocabulary, freq, freq_length, freq_dict)
            context.pop(int(window/2))
            u = [v_dict[item] for item in neg_s+context]
            L = lambda x: x >= window - 1  # 前几个是负采样的单词 定义lambda函数判断样本正负
            e = 0
            for i in range(len(u)):
                q = sigmoid(np.dot(vector[v_dict[current]], w[u[i]].T))
                g = alpha * (L(i) - q)
                e = e + g * w[u[i]]
                w[u[i]] += g * vector[v_dict[current]]
                vector[v_dict[current]] += e
            start += window
    return vector, vocabulary  # word 是词向量矩阵，v是词表

print('修改时间：', datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
word, v = skip_gram('城市.txt')
np.savetxt('词向量.csv', word, delimiter=',')
with open('词表.txt', 'w') as fp:
    fp.write('/'.join(v))
print('保存参数！')
print('结束时间：', datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))


from django.conf.urls import url

from . import views

# 去除硬编码（名称任意，但是需要与命名空间的名称一致，一般取名为项目名称）
app_name = "booklist"
# 去除硬编码 在应用的urlconf中添加url别名(name=)
urlpatterns = [
    # url('index/', views.index),
    # url('index/$', views.index),
    url(r'^$', views.index, name='index'),
    url(r'^booklist/$', views.list, name='list'),
    # url(r'$', views.index),
    url(r'^bookdetail/(\d+)/$', views.detail, name='detail'),
    url(r'^bookinfoss/(\d+)/$', views.infoss, name='infoss'),
    url(r'^add/$', views.add, name='add'),
    url(r'^delete/(\d+)/$', views.delete, name='delete'),
]


# map

def miles_to_km(miles):
    return miles*1.6

mail_dist=[1.0,1.6,2.3]

# km_dist=map(miles_to_km,mail_dist)
# print(km_dist)

km_dist=list(map(lambda x: x*1.6, mail_dist))
print(km_dist)

list1=[1,2,3]
list2=[4,5,6]
list3=list(map(lambda x,y:x+y,list1,list2))
print(list3)

# reduce

from functools import reduce

list_temp=[5,345,65,76]
max=reduce(lambda x,y: x if x>y else y,list_temp)
print(max)

#filter

list_proba=[134,234,324,5,56,67,123]
list_50=list(filter(lambda x: x>50,list_proba))
print(list_50)

#sort

list_temp_sort=(list_temp.reverse())
print(list_temp_sort)

list_names=['Kate','Dima','Ivan','Mike']
sort_name=sorted(list_names, key= lambda x: x[1])
print(sort_name)


import json
import boto3
import os
from kafka import KafkaConsumer
from datetime import datetime
from dotenv import load_dotenv
from ast import literal_eval

load_dotenv()

BUCKET_NAME = os.getenv('BUCKET_NAME')
AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY')
KAFKA_BROKER = os.getenv('KAFKA_BROKER').split(',')

consumer = KafkaConsumer ('demo-kafka-topic',bootstrap_servers = KAFKA_BROKER)

s3 = boto3.resource('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)

for message in consumer:
    print(message)
    s3object = s3.Object(
        BUCKET_NAME,
        '{today}/kafka_test_{now}.json'.format(
            today=datetime.today().strftime('%Y-%m-%d'),
            now=str(datetime.now())
        )
    )
    data = eval(literal_eval(message[6].decode('utf-8'))['data'])
    s3object.put(
        Body=(json.dumps(data, indent=4, sort_keys=True))
    )


import pylab as plt
import numpy as np
import simlib1 as sim
import leveldensities as lden

"""
(19/12/2017)
Copied from uct2017b/Sm154
"""

def DefineParameters(sig,sign,sigw):
    global sigexpt,sigsmn,sigsm
    sigexpt=sig
    sigsmn=sign
    sigsm=sigw

def PlotSpectrum(nfig,X,G,Gs,ROIlo,ROIhi,A,incounts=True):
    incounts=True
    curfig=plt.figure(nfig)
    curfig.clf()
    # plot spectrum
    #plt.subplot(221)
    plt.plot(X,G,'b-',drawstyle='steps-mid')
    plt.xlabel('Energy [MeV]')
    if incounts:
        plt.ylabel('counts per channel')
    else:
        plt.ylabel(r'$d^2\sigma/d\Omega dE$ [mb/sr MeV]')
    # plot smoothed
    plt.plot(X,Gs,'r-')
    plt.xlim(X[0],X[-1])
    plt.legend(('spectrum','smooth'))
    #plt.axvline(X[ROIlo+AClo])
    #plt.xlim(X[ROIlo],X[ROIhi])
    plt.axvline(X[ROIlo+0], color="m")
    plt.axvline(X[ROIhi+0], color="m")
    ## plt.axvline(X[ROIlo+AChi-1], color="m")
    plt.text(0.1,0.8,r"$^{%i}$Sm"%A,fontsize=16,transform=plt.gca().transAxes)
    plt.title("Data")
    #if M1fractions: plt.plot(em1,m1fraction*10000,'g-',drawstyle='steps-mid')
    #plt.ylim(0.0,20000)

def PlotACs(nfig, i, X,Ac, Act, NACbins, Nac, meanE, targetname, NarrowSmooth):
    plt.figure(nfig+i)
    plt.suptitle(targetname)
    #axx=plt.subplot(int(NACbins/3),3,1+i)
    Nacd2=Nac#//2
    plt.plot(X[0:Nacd2]-X[0],Ac[0:Nacd2],'b-',lw=0.9,drawstyle='steps-mid',label="mean E=%4.1f"%(meanE,))
    if not NarrowSmooth: plt.plot(X[0:2]-X[0],Ac[0:2],'bo')
    plt.xlabel('Energy offset [MeV]')
    plt.ylabel('Autocorrelation')

    # plot Hansen formula
    plt.plot(X[0:Nacd2]-X[0],Act[0:Nacd2],'r-',lw=0.9)
    plt.xlim(X[0]-X[0],X[Nacd2-1]-X[0])
    plt.legend()

def PlotFullAC(nfig, Xratio,allAC,popt,alpha,sig,sigsm,initialD,A):
    plt.figure(nfig)
    ax=plt.subplot(211)
    plt.plot(Xratio[0:120]-Xratio[0], allAC[0:120],drawstyle='steps-mid') # was 100
    #plt.plot(Xratio[0:120]-Xratio[0], allAC2[800:920]+0.0000,'c-',drawstyle='steps-mid') # was 100
    plt.plot(Xratio[0:120]-Xratio[0], sim.Hansen2(Xratio[0:120]-Xratio[0], popt[0],popt[1],alpha,sigsm),'g-')
    plt.plot(Xratio[0:120]-Xratio[0], sim.Hansen2(Xratio[0:120]-Xratio[0], initialD,sig,alpha,sigsm),'m-',alpha=0.6)
    plt.text(0.8,0.8,r"$^{%i}$Sm"%A,fontsize=16,transform=ax.transAxes)
    plt.title(r"Autocorrelation of full region of interest")
    plt.ylabel("Autocorrelation")
    plt.xlabel("Energy offset [MeV]")
    plt.subplot(212)
    plt.plot(Xratio[0:750]-Xratio[0], allAC[0:750],drawstyle='steps-mid') # was 100
    plt.plot(Xratio[0:750]-Xratio[0], sim.Hansen2(Xratio[0:750]-Xratio[0], popt[0],popt[1],alpha,sigsm))

    plt.ylabel("Autocorrelation")
    plt.xlabel("Energy offset [MeV]")

def PlotLevelDensities(nfig,N,Z,A,Ed,Dd,Ddl,Ddh,Ex, Exlo, Exhi):
    Spin=1.0
    rhoRauscher=lden.LevelDenRauscher(Ex, Z, N, Spin)
    rhovonEg=lden.LevelDenvonEgidy(Ex, Z, N, Spin)
    rhoGorf=lden.HFBCS(Z,N,Spin,'-')
    rhoGor=rhoGorf(Ex)
    # level density plot
    curfig=plt.figure(nfig)
    curfig.clf()
    yerrs=np.array([Ddl,Ddh])
    #if len(Ed)<1 or len(Dd)<1: continue
    plt.errorbar(Ed,Dd,yerr=yerrs,fmt='o',label='Data')
    ###plt.plot(Ed,Dr,'co',label='alt.') # direct from AC[iAC]
    plt.gca().set_yscale('log')
    ###plt.semilogy(Ed,Dd,'bo')
    plt.semilogy(Ex,rhoRauscher,'g-',label='BSFG (Rauscher)')
    plt.semilogy(Ex,rhovonEg,'g--',label='vonEgidy')
    plt.semilogy(Ex,rhoGor,'m-',label='HFB')
    plt.xlabel('Excitation Energy [MeV]')
    plt.ylabel(r'Level density [Mev$^{-1}$]')
    plt.xlim(Exlo,Exhi)
    ##plt.xlim(11.0,20.0) #40Ca
    plt.text(0.1,0.9,r"$^{%i}$Sm(p,p')"%A,fontsize=18,transform=plt.gca().transAxes)
    plt.text(0.1,0.82,r"Preliminary",fontsize=18,color='r',transform=plt.gca().transAxes)
    plt.text(0.05,0.75,
             r"$\sigma=%5.3f, \sigma_</\sigma=%5.3f, \sigma_>/\sigma=%5.3f$"%(sigexpt,sigsmn/sigexpt/2.3,sigsm/sigexpt),
             transform=plt.gca().transAxes)
    plt.legend(loc=4)
    plt.title(r"Level densities")
    #plt.savefig(os.path.join(outputdirname,"%s%sfig3.png"%(targetbase,targetangle)))

    ## # histogram fluctuations
    ## plt.subplot(222)
    ## #plt.hist(Gratio,bins=20)
    ## # plot spectrum
    ## plt.plot(X,G,'b-')
    ## plt.xlabel('Energy [MeV]')
    ## plt.ylabel(r'$d^2\sigma/d\Omega dE$ [mb/sr MeV]')
    ## #plt.ylabel('counts per channel')
    ## # plot smoothed
    ## plt.plot(X,Gs+bkg,'r-')
    ## plt.plot(X,bkg,'g-')
    ## plt.xlim(X[0],X[-1])
    ## plt.ylim(min(G),max(G[ROIlo:ROIlo+AChi-1]))
    ## ###plt.legend(('spectrum','smooth','background'))
    ## #plt.axvline(X[ROIlo+AClo])
    ## plt.axvline(X[ROIlo+0], color="m")
    ## plt.axvline(X[ROIlo+AChi-1], color="m")

    ## plt.savefig(os.path.join(outputdirname,"%s%sfig1.png"%(targetbase,targetangle)))

def PlotAnalysisROI(nfig, Xratio, TG, TGs, TGn, A):
    plt.figure(nfig)
    #plt.plot(Xratio,Gratio)
    plt.plot(Xratio,TG,drawstyle='steps-mid',label='data')
    plt.plot(Xratio,TGs,label='smoothed')
    if TGn is not None:
        plt.plot(Xratio,TGn,label='narrow sm.')
    plt.xlabel("Excitation energy [MeV]")
    plt.ylabel("Cross section")
    plt.ylabel("Counts per 5 keV")
    plt.title("Region of interest")
    plt.text(0.1,0.8,r"$^{%i}$Sm"%A,fontsize=16,transform=plt.gca().transAxes)
    plt.legend(loc=4)
    #plt.plot(Xratio,G0[ROIlo:ROIhi])
    #plt.xlim(8,25)
    #plt.ylim(0,15)

def PlotStationarySpectrum(nfig, Xratio, TG0, TS, A):
    plt.figure(nfig)
    Gratio = TG0 if TS==None else TG0/TS
    plt.plot(Xratio,Gratio)
    plt.xlabel(r"Excitation energy [MeV]")
    plt.ylabel(r"$g_</g_>$")
    plt.text(0.8,0.8,r"$^{%i}$Sm"%A,fontsize=16,transform=plt.gca().transAxes)
    plt.title("stationary spectrum")

    """
    plt.figure(19)
    #plot_imfs(imfs)
    plt.subplot(511)
    plt.plot(Xratio,imfs[0])
    plt.subplot(512)
    plt.plot(Xratio,imfs[1])
    plt.subplot(513)
    plt.plot(Xratio,imfs[2])
    plt.subplot(514)
    plt.plot(Xratio,imfs[3])
    plt.subplot(515)
    plt.plot(Xratio,imfs[4])
    """

def PlotTrends(nfig, Ed,Sigfit, ACzero, fitpoints, A):
    plt.figure(nfig)
    plt.subplot(211)
    plt.plot(Ed, Sigfit, 'bo')
    plt.plot(Ed,fitpoints,'g-')
    plt.xlabel(r"Excitation energy [MeV]")
    plt.ylabel(r"Fitted AC sigma")
    plt.subplot(212)
    plt.semilogy(Ed,ACzero,'bo')
    plt.xlabel(r"Excitation energy [MeV]")
    plt.ylabel(r"AC at zero offset")

"""
plt.figure(15)
    yerrs=plt.array([Ddl,Ddh])
    if len(Ed)<1 or len(Dd)<1: continue
    plt.errorbar(Ed,Ddcorr,yerr=yerrs,fmt='o',label='Data')
    ###plt.plot(Ed,Dr,'co',label='alt.') # direct from AC[iAC]
    plt.gca().set_yscale('log')
    ###plt.semilogy(Ed,Dd,'bo')
    plt.semilogy(Ex,rhoRauscher,'g-',label='BSFG (Rauscher)')
    plt.semilogy(Ex,rhovonEg,'g--',label='vonEgidy')
    plt.semilogy(Ex,rhoGor,'m-',label='HFB')
    plt.xlabel('Excitation Energy [MeV]')
    plt.ylabel(r'Level density [Mev$^{-1}$]')
    plt.xlim(Exlo,Exhi)
    ##plt.xlim(11.0,20.0) #40Ca
    plt.text(0.1,0.8,r"$^{%i}$Sm(p,p')"%A,fontsize=18,transform=plt.gca().transAxes)
    plt.text(0.1,0.7,r"Preliminary",fontsize=22,color='r',transform=plt.gca().transAxes)
    #plt.text(0.1,0.7,
    #         r"$\sigma=%5.3f, \sigma_</\sigma=%5.3f, \sigma_>/\sigma=%5.3f$"%(sigexpt,sigsmn/sigexpt/2.3,sigsm/sigexpt),
    #         transform=plt.gca().transAxes)
    plt.legend(loc=4)
    plt.title(r"Level densities")
    #plt.savefig(os.path.join(outputdirname,"%s%sfig3.png"%(targetbase,targetangle)))
"""


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from .models_base import glorot
from .models_base import Model
import tensorflow as tf

# Global unique layer ID dictionary for layer name assignment.
_LAYER_UIDS = {}

def get_layer_uid(layer_name=''):
  """Helper function, assigns unique layer IDs."""
  if layer_name not in _LAYER_UIDS:
    _LAYER_UIDS[layer_name] = 1
    return 1
  else:
    _LAYER_UIDS[layer_name] += 1
    return _LAYER_UIDS[layer_name]

def sparse_dropout(x, keep_prob, noise_shape):
  """Dropout for sparse tensors."""
  random_tensor = keep_prob
  random_tensor += tf.random_uniform(noise_shape)
  dropout_mask = tf.cast(tf.floor(random_tensor), dtype=tf.bool)
  pre_out = tf.sparse_retain(x, dropout_mask)
  return tf.SparseTensor(
      indices=pre_out.indices,
      values=pre_out.values / keep_prob,
      dense_shape=pre_out.dense_shape)

def dot(x, y, sparse=False):
  """Wrapper for tf.matmul (sparse vs dense)."""
  if sparse:
    res = tf.sparse_tensor_dense_matmul(x, y)
  else:
    res = tf.matmul(x, y)
  return res

class GCN(Model):
  """Graph Convolution Networks.

  Attributes:
    input_dim: Integer representing the number of input features.
    output_dim: Integer representing the number of classes.
    hidden: Integer representing the number of hidden units in the first layer
      of the network.
    dropout: Float representing the dropout probability during training.
    aggregation: String representing an aggregation operation, that is applied
      on the two inputs of the agreement model, after they are encoded through
      the convolution layers. See superclass attributes for details.
    activation: An activation function to be applied to the outputs of each
      fully connected layer of the aggregation network.
    is_binary_classification: Boolean specifying if this is model for binary
      classification. If so, it uses a different loss function and returns
      predictions with a single dimension, batch size.
    name: String representing the model name.
  """

  def __init__(self,
               input_dim,
               output_dim,
               hidden,
               dropout=0.5,
               aggregation=None,
               hidden_aggregation=(),
               activation=tf.nn.leaky_relu,
               is_binary_classification=False,
               name='GCN'):
    super(GCN, self).__init__(
        aggregation=aggregation,
        hidden_aggregation=hidden_aggregation,
        activation=activation)

    dropout = 0.5 if dropout is None else dropout

    self.input_dim = input_dim
    self.output_dim = output_dim
    self.num_supports = 1
    self.hidden = hidden
    self.dropout = dropout
    self.name = name
    self.is_binary_classification = is_binary_classification

  def get_encoding_and_params(self, inputs, is_train, support,
                              num_features_nonzero, **unused_kwargs):
    """Creates the model hidden representations and prediction ops.

    For this model, the hidden representation is the last layer of the MLP,
    before the logit computation. The predictions are unnormalized logits.

    Args:
      inputs: A tensor containing the model inputs. The first dimension is the
        batch size.
      is_train: A boolean placeholder specifying if this is a training or
        testing setting.
      support: TODO(dattias, kvis-google): add.
      num_features_nonzero: Number of non-zero features.
      **unused_kwargs: Other unused keyword arguments.

    Returns:
      encoding: A tensor containing an encoded batch of samples. The first
        dimension corresponds to the batch size.
      all_vars: A dictionary mapping from variable name to TensorFlow op
        containing all variables used in this model.
      reg_params: A dictionary mapping from a variable name to a Tensor of
        parameters which will be used for regularization.
    """
    # Build layers.
    with tf.variable_scope(self.name + '/encoding'):
      hidden, reg_params = self._construct_encoding(inputs, is_train, support,
                                                    num_features_nonzero)

      # Store model variables for easy access.
      variables = tf.get_collection(
          tf.GraphKeys.GLOBAL_VARIABLES,
          scope=tf.get_default_graph().get_name_scope())
      all_vars = {var.name: var for var in variables}

    return hidden, all_vars, reg_params

  def _construct_encoding(self, inputs, is_train, support,
                          num_features_nonzero):
    """Create weight variables."""
    dropout = (
        tf.constant(self.dropout, tf.float32) * tf.cast(is_train, tf.float32))

    layer_1 = GraphConvolution(
        input_dim=self.input_dim,
        output_dim=self.hidden,
        activation=tf.nn.relu,
        dropout=dropout,
        sparse_inputs=True,
        num_features_nonzero=num_features_nonzero,
        support=support,
        name='GraphConvolution1')
    encoding = layer_1(inputs)
    reg_params = layer_1.vars

    return encoding, reg_params

  def get_predictions_and_params(self, encoding, is_train, **kwargs):
    """Creates the model prediction op.

    For this model, the hidden representation is the last layer of the MLP,
    before the logit computation. The predictions are unnormalized logits.

    Args:
      encoding: A tensor containing the model inputs. The first dimension is the
        batch size.
      is_train: A placeholder representing a boolean value that specifies if
        this model will be used for training or for test.
      **kwargs: Other keyword arguments.

    Returns:
      predictions: A tensor of logits. For multiclass classification its
        shape is (num_samples, num_classes), where the second dimension contains
        a logit per class. For binary classification, its shape is
        (num_samples,), where each element is the probability of class 1 for
        that sample.
      all_vars: A dictionary mapping from variable name to TensorFlow op
        containing all variables used in this model.
      reg_params: A dictionary mapping from a variable name to a Tensor of
        parameters which will be used for regularization.
    """
    reg_params = {}
    support = kwargs['support']
    num_features_nonzero = kwargs['num_features_nonzero']

    # Build layers.
    with tf.variable_scope(self.name + '/prediction'):
      dropout = (
          tf.constant(self.dropout, tf.float32) * tf.cast(is_train, tf.float32))

      layer_2 = GraphConvolution(
          input_dim=self.hidden,
          output_dim=self.output_dim,
          activation=lambda x: x,
          dropout=dropout,
          num_features_nonzero=num_features_nonzero,
          support=support,
          name='GraphConvolution2')
      predictions = layer_2(encoding)

      if self.is_binary_classification:
        predictions = predictions[:, 0]

      # Store model variables for easy access.
      variables = tf.get_collection(
          tf.GraphKeys.GLOBAL_VARIABLES,
          scope=tf.get_default_graph().get_name_scope())
      all_vars = {var.name: var for var in variables}

    return predictions, all_vars, reg_params

  def get_loss(self,
               predictions,
               targets,
               name_scope='loss',
               reg_params=None,
               **kwargs):
    """Returns a loss between the provided targets and predictions.

    For binary classification, this loss is sigmoid cross entropy. For
    multi-class classification, it is softmax cross entropy.
    A weight decay loss is also added to the parameters passed in reg_params.

    Args:
      predictions: A tensor of predictions. For multiclass classification its
        shape is (num_samples, num_classes), where the second dimension contains
        a logit per class. For binary classification, its shape is
        (num_samples,), where each element is the probability of class 1 for
        that sample.
      targets: A tensor of targets of shape (num_samples,), where each row
        contains the label index of the corresponding sample.
      name_scope: A string containing the name scope used in TensorFlow.
      reg_params: A dictonary of parameters, mapping from name to parameter, for
        the variables to be included in the weight decay loss. If None, no
        weight decay is applied.
      **kwargs: Keyword arguments, potentially containing the weight of the
        regularization term, passed under the name `weight_decay`. If this is
        not provided, it defaults to 0.0.

    Returns:
      loss: The cummulated loss value.
    """
    reg_params = reg_params if reg_params is not None else {}
    weight_decay = kwargs['weight_decay'] if 'weight_decay' in kwargs else None

    with tf.name_scope(name_scope):
      # Cross entropy error.
      if self.is_binary_classification:
        loss = tf.reduce_sum(
            tf.nn.sigmoid_cross_entropy_with_logits(
                labels=targets, logits=predictions))
      else:
        loss = tf.losses.softmax_cross_entropy(targets, predictions)
      # Weight decay loss.
      if weight_decay is not None:
        for var in reg_params.values():
          loss = loss + weight_decay * tf.nn.l2_loss(var)
    return loss

  def normalize_predictions(self, predictions):
    """Converts predictions to probabilities.

    Args:
      predictions: A tensor of logits. For multiclass classification its shape
        is (num_samples, num_classes), where the second dimension contains a
        logit per class. For binary classification, its shape is (num_samples,),
        where each element is the probability of class 1 for that sample.

    Returns:
      A tensor of the same shape as predictions, with values between [0, 1]
    representing probabilities.
    """
    if self.is_binary_classification:
      return tf.nn.sigmoid(predictions)
    return tf.nn.softmax(predictions, axis=-1)

class GraphConvolution(object):
  """Graph convolution layer."""

  def __init__(self,
               input_dim,
               output_dim,
               support,
               num_features_nonzero,
               dropout=0.,
               sparse_inputs=False,
               activation=tf.nn.relu,
               bias=False,
               featureless=False,
               name=None):
    if not name:
      layer = self.__class__.__name__.lower()
      name = layer + '_' + str(get_layer_uid(layer))

    self.name = name
    self.vars = {}
    self.dropout = dropout
    self.act = activation
    self.support = support
    self.sparse_inputs = sparse_inputs
    self.featureless = featureless
    self.bias = bias

    # Helper variable for sparse dropout.
    self.num_features_nonzero = num_features_nonzero

    with tf.variable_scope(self.name + '_vars'):
      self.vars['weights'] = tf.get_variable(
          name='weights', initializer=glorot([input_dim, output_dim]))
      if self.bias:
        self.vars['bias'] = tf.get_variable(
            name='bias', initializer=tf.zeros(shape=[output_dim]))

  def __call__(self, inputs):
    with tf.name_scope(self.name):
      outputs = self._call(inputs)
      return outputs

  def _call(self, inputs):
    """Run over inputs."""
    x = inputs

    # Dropout.
    if self.sparse_inputs:
      x = sparse_dropout(x, 1 - self.dropout, self.num_features_nonzero)
    else:
      x = tf.nn.dropout(x, 1 - self.dropout)

    # Convolve.
    if not self.featureless:
      pre_sup = dot(x, self.vars['weights'], sparse=self.sparse_inputs)
    else:
      pre_sup = self.vars['weights']
    support = dot(self.support, pre_sup, sparse=True)
    output = support

    # Bias.
    if self.bias:
      output += self.vars['bias']

    return self.act(output)


#!/usr/bin/python3
#Above line is only if you try to run it on Linux. This is originally meant for Windows.

import sys
from PyQt5.QtCore import QCoreApplication #For getting to the application instance
from PyQt5.QtWidgets import (QApplication, QWidget,
	QPushButton, QToolTip, QMessageBox,
	QDesktopWidget, QMainWindow, QAction, qApp,
	QTextEdit)

	#QWidget is for windows other than main window
	#Main window allows for menu bars and such
from PyQt5.QtGui import (QIcon, QFont, QTextCursor)

#My modules
from BADataObjects import Battle, HumanCombatant, AICombatant
from BAHelpFunctions import createMoveset, createMoveGuide
from PartialObserveArena import Partial_Observe

class Arena(QMainWindow):

	def __init__(self):
		super().__init__() #call the superclass's __init__ function.
		self.initUI() #then call the initUI function you design
		#self.createGame()

	def initUI(self):
		QToolTip.setFont(QFont('SansSerif', 10))

		#Output Widget
		battleStatus = QTextEdit()
		battleStatus.setReadOnly(True)
		battleStatus.moveCursor(QTextCursor.End)
		sb = battleStatus.verticalScrollBar()
		sb.setValue(sb.maximum())
		self.setCentralWidget(battleStatus)

		startAct = QAction(QIcon('startBattle.png'), '&New Game', self)
		startAct.setShortcut('Ctrl+N')
		startAct.setStatusTip('New Game')
		startAct.triggered.connect(qApp.quit)

		exitAct = QAction(QIcon('shattered-sword.png'), '&Exit', self)
		exitAct.setShortcut('Ctrl+Q')
		exitAct.setStatusTip('Exit Application')
		exitAct.triggered.connect(qApp.quit)

		gameMenu = self.addToolBar('&Main Menu')
		gameMenu.addAction(startAct)
		gameMenu.addAction(exitAct)

		self.statusBar()

		self.resize(600, 400)
		self.center()
		self.setWindowTitle('Battle Arena RPG')
		self.setWindowIcon(QIcon('sword.ico'))
		self.show()

	def center(self):
		qr = self.frameGeometry()
		#We get a rectangle specifying the geometry of the main window. This includes any window frame.
		cp = QDesktopWidget().availableGeometry().center()
		#We figure out the screen resolution of our monitor. And from this resolution, we get the center point.
		qr.moveCenter(cp)
		#Our rectangle has already its width and height. Now we set the center of the rectangle to the center
		#of the screen. The rectangle's size is unchanged.
		self.move(qr.topLeft())
		#Finally, we move the top-left point of the application window to the top-left point of the qr rectangle,
		#thus centering the window on our screen.

	def closeEvent(self, event):

		reply = QMessageBox.question(self, 'Leaving so soon?',
			"Are you sure you want to forefeit?", QMessageBox.Yes |
			QMessageBox.No, QMessageBox.No)

		'''
		From zetcode.com/gui/pyqt5/firstprograms:
		We show a message box with two buttons: Yes and No. The first string appears on the titlebar. The second string
		is the message text displayed by the dialog. The third argument specifies the combination of buttons appearing
		in the dialog. The last parameter is the default button. It is the button which has initially the keyboard focus.
		The return value is stored in the reply variable.
		'''

		if reply == QMessageBox.Yes:
			event.accept()
		else:
			event.ignore()

	#def createGame(self):

if __name__== '__main__':

	#Create the necessary objects for attack moves and store them
	Available_Moves = createMoveset()
	#Create human player stats
	Human = HumanCombatant("Stefan")
	#Create AI player stats
	ai_algo = Partial_Observe(2)
	AI = AICombatant(ai_algo, "Computer")

	'''Create game object and operate.'''
	ArenaMatch = Battle( Available_Moves, [Human, AI])
	'''Need to functionally convert this to the GUI version.
	while not ArenaMatch.is_over():
		print("\n")
		ArenaMatch.show()
		print("\n")
		if ArenaMatch.nplayer==1:  # we are assuming player 1 is a Human_Player
			poss = ArenaMatch.possible_moves()
			for index, move in enumerate(poss):
				print("{} : {}".format(index, move.NAME))
			print("\n")
			index = int(input("Choose attack number: "))
			move = poss[index]
			print("\n")
			print("You used '{}'.".format(move.NAME))
			print("\n")
		else:  # we are assuming player 2 is an AI_Player
			move = ArenaMatch.get_move()
			print("\n")
			print("The Computer used '{}'.".format(move.NAME))
			print("\n")

		damage = ArenaMatch.play_move(move) #Method returns damage for us.
		print("It did {} points in {} and {} damage.".format(damage, move.ELEMENT, move.TYPE))

		if move.ELEMENT == ArenaMatch.player.ELEMENTAL_WEAKNESS and move.ELEMENT == ArenaMatch.opponent.ELEMENTAL_AFFINITY:
			print("It was super effective and enhanced!")
		elif move.ELEMENT == ArenaMatch.player.ELEMENTAL_WEAKNESS:
			print("It was super effective!")
		elif move.ELEMENT == ArenaMatch.opponent.ELEMENTAL_AFFINITY:
			print("It was enhanced!")
	print("\n")
	if AI.HP == 0:
		print("Congratulations, human. You beat me.")
	elif Human.HP == 0:
		print("Game Over. You lost.")

	'''
	app = QApplication(sys.argv)
	#An application is a superclass provided the system arguments
	#w = QWidget() #A default widget like this is a window.
	ba = Arena()
	statusArea = ba.centralWidget()
	statusArea.append("Hello")
	statusArea.append("\nI am working.")

	sys.exit(app.exec_()) #Execution loop wrapped inside a safe exit method.
	#Will keep track of reasons for application closing


# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：     WordFrequencyPy3
   Description :
   Author :        Liangz
   Date：          2018/9/11
-------------------------------------------------
   Change Activity:
                   2018/9/11:
-------------------------------------------------
"""
__author__ = 'Liangz'

import string

path = './Walden.txt'
with open(path, 'r', encoding='utf-8') as file:
    words = [fixed_word.strip(string.punctuation).lower() for fixed_word in file.read().split()]
    words_index = set(words)    # 转换为集合，去除重复单词
    count_word = {word_index:words.count(word_index) for word_index in words_index}
    # for word in words:
    #     print('{} : {} times'.format(word, words.count(word)))

for word in sorted(count_word, key=lambda x:count_word[x], reverse=True):
    print('{} : {} times'.format(word, count_word[word]))

print('\nTotal length : {}'.format(len(words)))
# print(words)
# print(words_index)
# print(len(words))
# print(string.punctuation)


from typing import Dict
from superagi.tools.base_tool import BaseTool
from alpaca.trading.client import TradingClient

# Define the main tool
class AlpacaGetAccountInformationTool(BaseTool):
    name = "alpaca_get_account_information"
    description = "Retrieve the account information from Alpaca using alpaca-py."

    def _execute(self, api_key: str, api_secret: str, paper: bool = True) -> Dict:
        """
        Execute the Alpaca Get Account Information tool to retrieve account details.

        Parameters:
        - api_key: API key for Alpaca authentication.
        - api_secret: API secret for Alpaca authentication.
        - paper: Flag to indicate whether to use paper trading environment. Default is True.

        Returns:
        - A dictionary with account details.
        """
        trading_client = TradingClient(api_key, api_secret, paper=paper)
        account = trading_client.get_account()
        # Convert the account object to a dictionary for return
        return {
            "id": account.id,
            "status": account.status,
            "currency": account.currency,
            "buying_power": float(account.buying_power),
            "cash": float(account.cash),
            "portfolio_value": float(account.portfolio_value),
            "pattern_day_trader": bool(account.pattern_day_trader),
            "trading_blocked": bool(account.trading_blocked),
            "transfers_blocked": bool(account.transfers_blocked),
            "account_blocked": bool(account.account_blocked),
            "created_at": account.created_at,
            "trade_suspended_by_user": bool(account.trade_suspended_by_user),
            "multiplier": float(account.multiplier),
            "shorting_enabled": bool(account.shorting_enabled),
            "equity": float(account.equity),
            "last_equity": float(account.last_equity),
            "long_market_value": float(account.long_market_value),
            "short_market_value": float(account.short_market_value),
            "initial_margin": float(account.initial_margin),
            "maintenance_margin": float(account.maintenance_margin),
            "last_maintenance_margin": float(account.last_maintenance_margin),
            "sma": float(account.sma),
            "daytrade_count": int(account.daytrade_count),
        }

    def _execute(self, api_key: str, api_secret: str, paper: bool = True) -> Dict:
        return self._execute(api_key, api_secret, paper)