"""
Simple script for take off and control with arrow keys
"""

import time
from dronekit import connect, VehicleMode, LocationGlobalRelative, Command, LocationGlobal
from pymavlink import mavutil

#- Importing Tkinter: sudo apt-get install python-tk
import Tkinter as tk

#-- Connect to the vehicle
print('Connecting...')
vehicle = connect('udp:127.0.0.1:14551')

#-- Setup the commanded flying speed
gnd_speed = 5 # [m/s]

#-- Define arm and takeoff
def arm_and_takeoff(altitude):

   while not vehicle.is_armable:
      print("waiting to be armable")
      time.sleep(1)

   print("Arming motors")
   vehicle.mode = VehicleMode("GUIDED")
   vehicle.armed = True

   while not vehicle.armed: time.sleep(1)

   print("Taking Off")
   vehicle.simple_takeoff(altitude)

   while True:
      v_alt = vehicle.location.global_relative_frame.alt
      print(">> Altitude = %.1f m"%v_alt)
      if v_alt >= altitude - 1.0:
          print("Target altitude reached")
          break
      time.sleep(1)

 #-- Define the function for sending mavlink velocity command in body frame
def set_velocity_body(vehicle, vx, vy, vz):
    """ Remember: vz is positive downward!!!
    http://ardupilot.org/dev/docs/copter-commands-in-guided-mode.html

    Bitmask to indicate which dimensions should be ignored by the vehicle
    (a value of 0b0000000000000000 or 0b0000001000000000 indicates that
    none of the setpoint dimensions should be ignored). Mapping:
    bit 1: x,  bit 2: y,  bit 3: z,
    bit 4: vx, bit 5: vy, bit 6: vz,
    bit 7: ax, bit 8: ay, bit 9:

    """
    msg = vehicle.message_factory.set_position_target_local_ned_encode(
            0,
            0, 0,
            mavutil.mavlink.MAV_FRAME_BODY_NED,
            0b0000111111000111, #-- BITMASK -> Consider only the velocities
            0, 0, 0,        #-- POSITION
            vx, vy, vz,     #-- VELOCITY
            0, 0, 0,        #-- ACCELERATIONS
            0, 0)
    vehicle.send_mavlink(msg)
    vehicle.flush()

#-- Key event function
def key(event):
    if event.char == event.keysym: #-- standard keys
        if event.keysym == 'r':
            print("r pressed >> Set the vehicle to RTL")
            vehicle.mode = VehicleMode("RTL")

    else: #-- non standard keys
        if event.keysym == 'Up':
            set_velocity_body(vehicle, gnd_speed, 0, 0)
        elif event.keysym == 'Down':
            set_velocity_body(vehicle,-gnd_speed, 0, 0)
        elif event.keysym == 'Left':
            set_velocity_body(vehicle, 0, -gnd_speed, 0)
        elif event.keysym == 'Right':
            set_velocity_body(vehicle, 0, gnd_speed, 0)

#---- MAIN FUNCTION
#- Takeoff
arm_and_takeoff(10)

#- Read the keyboard with tkinter
root = tk.Tk()
print(">> Control the drone with the arrow keys. Press r for RTL mode")
root.bind_all('<Key>', key)
root.mainloop()


#Universidad del Valle de Guatemala
#Fisica 3 Proyecto 1
#Graficador de trayectoria de una particula
#Bryann Alfaro
#Diego de Jesus Arredondo

#Importacion de librerias
import matplotlib.pyplot as pyplot
import math as math
import numpy

k=input("Press to start...")
#Masas de particulas
masas = [1.67E-27 , 9.1E-31 , 9.11E-31 , 6.64E-27, 1.9E-28, 1.67E-27, 3.34E-27, 3.2E-27, 1.9E-28, 3.2E-27]

#Cargas de particulas
cargas = [1.6E-19,  -1.6E-19, 1.6E10-19, 3.21E-19, -1.6E-19, 0.0, 1.6E-19, -1.6E-19, 1.6E-19, 1.6E-19]
coordenadasX = []
coordenadasY = []

print("**********TRAYECTORIA DE UNA PARTICULA****************")
print("1. Proton ")
print("2. Electron")
print("3. Positron")
print("4. Alfa")
print("5. Muon")
print("6. Neutron")
print("7. Nucleo de Deuterio")
print("8. Tauon")
print("9. Antimuon")
print("10. Antitauon")
print("****************************************************")

#Peticion de datos
particula = int(input("Ingrese la opcion de la particula que desea evaluar [1-10]: "))
velocidad= float(input("Ingrese la velocidad inicial en m/s: "))
velAngulo = float(input("Ingrese el angulo de la trayectoria en grados [0-90]: "))
campoElectrico= float(input("Ingrese la magnitud del campo con signo: "))

#aceleracion = carga*campo/masa
aceleracion = (cargas[particula-1]*campoElectrico)/masas[particula-1]
print("Aceleracion: ",aceleracion)
if(aceleracion==0):
  #velocidad coordenada x=  v*cos thetha
  velocidadx = velocidad*math.cos(velAngulo/180)
  print (velocidadx)

  #velocidad coordenada y= v*sin thetha
  velocidady = velocidad*math.sin(velAngulo/180)
  print (velocidady)

  tiempoSubida = 0 #Tiempo en que llega al tope
  tiempoTotal = tiempoSubida*2
  print("Tiempo de subida: ",tiempoSubida)
  print("Tiempo total del recorrido:",tiempoTotal)

  for t in numpy.arange(0, 5):
    coordenadaX = velocidadx*t #Cuanto recorrio
    coordenadaY = 0
    coordenadasX.append(coordenadaX)
    coordenadasY.append(coordenadaY)

  pyplot.plot(coordenadasX, coordenadasY)
  pyplot.ylabel("Y position")
  pyplot.xlabel("X position")
  pyplot.title('Movement of particle')
  pyplot.show()

else:
  #velocidad coordenada x=  v*cos thetha
  velocidadx = velocidad*math.cos(velAngulo/180)
  print (velocidadx)

  #velocidad coordenada y= v*sin thetha
  velocidady = velocidad*math.sin(velAngulo/180)
  print (velocidady)

  tiempoSubida = velocidady/aceleracion #Tiempo en que llega al tope
  tiempoTotal = tiempoSubida*2
  print("Tiempo de subida: ",tiempoSubida)
  print("Tiempo total del recorrido:",tiempoTotal)

  for t in numpy.arange(0, tiempoTotal, tiempoTotal/20):
    coordenadaX = velocidadx*t #Cuanto recorrio
    coordenadaY = velocidady*t - ((aceleracion * t**2)/2)
    coordenadasX.append(coordenadaX)
    coordenadasY.append(coordenadaY)

  pyplot.plot(coordenadasX, coordenadasY)
  pyplot.ylabel("Y position")
  pyplot.title('Movement of particle')
  pyplot.xlabel("X position")
  pyplot.show()
  k=input("Press to finish..")


from PyQt5 import QtGui, QtWidgets, QtCore

from MapGenerator import MapGen
from MapCanvas import Canvas, MAPSIZE
from PyQt5.QtGui import QColor
from PyQt5.QtCore import Qt, QTimer
import PyQt5
import threading
import time
import win32api
import win32gui
import math

def get_pixel_colour(i_x, i_y):
    i_desktop_window_id = win32gui.GetDesktopWindow()
    i_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id)
    long_colour = win32gui.GetPixel(i_desktop_window_dc, i_x, i_y)
    i_colour = int(long_colour)
    return (i_colour & 0xff), ((i_colour >> 8) & 0xff), ((i_colour >> 16) & 0xff)

def is_pointer_on_color(rgb, pos):
    act_color = get_pixel_colour(pos[0], pos[1])
    return (abs(act_color[0] - rgb[0]) + abs(act_color[1] - rgb[1]) + abs(act_color[2] - rgb[2])) < 10

def is_pointer_on_black_pixel(pos):
    return is_pointer_on_color(QColor(Qt.black).getRgb(), pos)

def is_pointer_on_green_pixel(pos):
    return is_pointer_on_color(QColor(Qt.green).getRgb(), pos)

def is_pointer_on_red_pixel(pos):
    return is_pointer_on_color(QColor(Qt.red).getRgb(), pos)

class Map(QtWidgets.QMainWindow):

    def __after_generate_act_map_callback(self, tiles):
        self.act_map_tiles = tiles
        self.generating_map_act = False
        print('act map generated, tiles=%d' % len(tiles))

    def __after_generate_next_map_callback(self, tiles):
        self.next_map_tiles = tiles
        self.generating_map_next = False
        print('next map generated, tiles=%d' % len(tiles))

    def __after_generate_prev_map_callback(self, tiles):
        self.prev_map_tiles = tiles
        self.generating_map_prev = False
        print('prev map generated, tiles=%d' % len(tiles))

    def __generate_random_map_next(self):
        self.generating_map_next = True
        tmp_tile_size = 0.1 - (((self.score + 1) // 3) / 100)
        if tmp_tile_size < 0.03:
            tmp_tile_size = 0.03
        if ((self.score + 1) // 3) == (self.score // 3):
            self.generating_map_next = False
        else:
            print('generating next map')
            generated = MapGen(round(MAPSIZE / (MAPSIZE * tmp_tile_size)), 'NEXT')
            generated.generate_map(self.__after_generate_next_map_callback)

    def __generate_random_map_act(self):
        print('generating act map')
        self.generating_map_act = True
        self.tile_size = 0.1 - ((self.score // 3) / 100)
        if self.tile_size < 0.03:
            self.tile_size = 0.03
        elif self.tile_size > 0.1:
            self.tile_size = 0.1
        self.canvas.tile_size = self.tile_size
        generated = MapGen(round(MAPSIZE / (MAPSIZE * self.tile_size)), 'ACT')
        generated.generate_map(self.__after_generate_act_map_callback)

    def __generate_random_map_prev(self):
        self.generating_map_prev = True
        tmp_tile_size = 0.1 - (((self.score - 1) // 3) / 100)
        if tmp_tile_size > 0.1:
            tmp_tile_size = 0.1
        elif tmp_tile_size < 0.03:
            tmp_tile_size = 0.03
        if ((self.score - 1) // 3) == (self.score // 3):
            self.generating_map_prev = False
        else:
            print('generating prev map')
            generated = MapGen(round(MAPSIZE / (MAPSIZE * tmp_tile_size)), 'PREV')
            generated.generate_map(self.__after_generate_prev_map_callback)

    def __init_intro_ui(self):
        self.setWindowTitle('MouseRunner')
        self.l = QtWidgets.QGridLayout()
        w = QtWidgets.QWidget()
        w.setLayout(self.l)
        btn = QtWidgets.QPushButton()
        btn.setText('Graj')
        btn.clicked.connect(self.on_start_click)
        self.l.addWidget(btn, 1, 0)

        btn = QtWidgets.QPushButton()
        btn.setText('Wyjdź')
        btn.clicked.connect(self.on_exit_click)
        self.l.addWidget(btn, 1, 2)

        label = QtWidgets.QLabel()
        label.setText('Gra MouseRunner, polegająca na poruszaniu się kursorem po losowo wygenerowanej mapie')
        self.l.addWidget(label, 0, 1)
        self.setCentralWidget(w)

    def __init_ui(self):
        self.canvas = Canvas(self.tile_size)
        self.l = QtWidgets.QVBoxLayout()
        w = QtWidgets.QWidget()
        w.setLayout(self.l)
        self.l.addWidget(self.canvas)
        self.setCentralWidget(w)
        w.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)
        self.update()

    def __del__(self):
        print('destroying MapEngine')
        self.destroying = True
        print('waiting for generating prev map thread')
        while self.generating_map_prev:
            time.sleep(0.1)
        print('generate prev map thread destroyed')
        print('waiting for generating act map thread')
        while self.generating_map_act:
            time.sleep(0.1)
        print('generate act map thread destroyed')
        print('waiting for generating next map thread')
        while self.generating_map_next:
            time.sleep(0.1)
        print('generate next map thread destroyed')
        print('MapEngine destroyed')

    def __init__(self,):
        super().__init__()
        self.map_tiles = []
        self.act_map_tiles = []
        self.next_map_tiles = []
        self.prev_map_tiles = []
        self.tile_size = 0.1
        self.__init_intro_ui()
        self.setMouseTracking(True)
        self.score = 0
        self.prev_dist = 0
        self.generating_map_act = False
        self.generating_map_next = False
        self.generating_map_prev = False
        self.map_generated = False
        self.timer = QTimer()
        self.timer.timeout.connect(self.__on_timer_tick)
        self.game_won = False
        self.game_lost = False
        self.refresh_game = False
        self.destroying = False
        self.waited_for_sec = False

    def show(self):
        super(Map, self).show()
        self.__center()

    def on_exit_click(self):
        self.close()

    def on_start_click(self):
        self.__init_ui()
        frame_gm = self.frameGeometry()
        screen = PyQt5.QtWidgets.QApplication.desktop().screenNumber(
            PyQt5.QtWidgets.QApplication.desktop().cursor().pos())
        center_point = PyQt5.QtWidgets.QApplication.desktop().screenGeometry(screen).center()
        frame_gm.moveCenter(center_point)
        self.move(frame_gm.left(), frame_gm.top() - (MAPSIZE // 2))
        self.window_pos = self.pos()
        self.canvas.show_loading_map_info()
        self.timer.start(1000)
        self.__first_game()

    def __on_timer_tick(self):
        if self.destroying:
            pass
        else:
            if (not self.generating_map_next) and (len(self.next_map_tiles) == 0):
                threading.Thread(target=self.__generate_random_map_next).start()
            if (not self.generating_map_act) and (len(self.act_map_tiles) == 0):
                threading.Thread(target=self.__generate_random_map_act).start()
            if (not self.generating_map_prev) and (len(self.prev_map_tiles) == 0):
                threading.Thread(target=self.__generate_random_map_prev).start()

            if self.game_won:
                if self.waited_for_sec:
                    if (self.score // 3) == ((self.score - 1) // 3):
                        if (not self.generating_map_act) and (len(self.act_map_tiles) > 0):
                            self.__draw_act_map()
                            self.game_won = False
                            self.waited_for_sec = False
                    else:
                        if (not self.generating_map_next) and (len(self.next_map_tiles) > 0):
                            self.__draw_next_map()
                            self.game_won = False
                            self.waited_for_sec = False
                else:
                    self.waited_for_sec = True
            elif self.game_lost:
                if self.waited_for_sec:
                    if (self.score // 3) == ((self.score + 1) // 3):
                        if (not self.generating_map_act) and (len(self.act_map_tiles) > 0):
                            self.__draw_act_map()
                            self.game_lost = False
                            self.waited_for_sec = False
                    else:
                        if (not self.generating_map_prev) and (len(self.prev_map_tiles) > 0):
                            self.__draw_prev_map()
                            self.game_lost = False
                            self.waited_for_sec = False
                else:
                    self.waited_for_sec = True
            elif self.refresh_game:
                if self.waited_for_sec:
                    if (not self.generating_map_act) and (len(self.act_map_tiles) > 0):
                        self.__draw_act_map()
                        self.refresh_game = False
                        self.waited_for_sec = False
                else:
                    self.waited_for_sec = True

    def __center(self):
        frame_gm = self.frameGeometry()
        screen = PyQt5.QtWidgets.QApplication.desktop().screenNumber(
            PyQt5.QtWidgets.QApplication.desktop().cursor().pos())
        center_point = PyQt5.QtWidgets.QApplication.desktop().screenGeometry(screen).center()
        frame_gm.moveCenter(center_point)
        self.move(frame_gm.topLeft())

    def __set_start_pos_pointer(self):
        self.act_pos = (self.mapToGlobal(self.centralWidget().pos()).x() + self.canvas.pos().x() + round(MAPSIZE // len(self.map_tiles)),
                          self.mapToGlobal(self.centralWidget().pos()).y() + self.canvas.pos().y() + round(MAPSIZE // len(self.map_tiles)))
        try:
            win32api.SetCursorPos(self.act_pos)
        except Exception:
            pass

    def __set_score_text(self):
        self.setWindowTitle("MouseRunner - Wynik: %d" % self.score)

    def __first_game(self):
        self.__set_score_text()
        self.refresh_game = True

    def __draw_act_map(self):
        print('drawing act map')
        while len(self.act_map_tiles) == 0:
            print('act map, waiting for generate, generating?=%s' % self.generating_map_act)
            time.sleep(0.5)
        self.map_tiles = self.act_map_tiles
        self.act_map_tiles = []
        self.canvas.draw_map(self.map_tiles)
        self.update()
        self.__set_start_pos_pointer()
        self.map_generated = True
        print('act map generated')

    def __draw_next_map(self):
        print('drawing next map')
        while len(self.next_map_tiles) == 0:
            print('next map, waiting for generate, generating?=%s' % self.generating_map_next)
            time.sleep(0.5)
        self.map_tiles = self.next_map_tiles
        self.next_map_tiles = []
        self.act_map_tiles = []
        self.prev_map_tiles = []
        self.canvas.draw_map(self.map_tiles)
        self.update()
        self.__set_start_pos_pointer()
        self.map_generated = True
        print('next map generated')

    def __draw_prev_map(self):
        print('drawing previous map')
        while len(self.prev_map_tiles) == 0:
            print('prev map, waiting for generate, generating?=%s' % self.generating_map_prev)
            time.sleep(0.5)
        self.map_tiles = self.prev_map_tiles
        self.next_map_tiles = []
        self.act_map_tiles = []
        self.prev_map_tiles = []
        self.canvas.draw_map(self.map_tiles)
        self.update()
        self.__set_start_pos_pointer()
        self.map_generated = True
        print('prev map generated')

    def __did_pointer_jump(self, pos):
        try:
            prev_x = abs(self.act_pos[0] - self.window_pos.x())
            prev_y = abs(self.act_pos[1] - self.window_pos.y())
            act_x = abs(pos[0] - self.pos().x())
            act_y = abs(pos[1] - self.pos().y())
            act_dist = math.sqrt(pow(abs(prev_x - act_x), 2) + pow(abs(prev_y - act_y), 2))
            if self.prev_dist < act_dist:
                self.prev_dist = act_dist - self.prev_dist
            else:
                self.prev_dist = act_dist
            if self.prev_dist > (abs(prev_x - act_x) + abs(prev_y - act_y)):
                self.prev_dist = abs((abs(prev_x - act_x) + abs(prev_y - act_y)) - self.prev_dist)
            else:
                self.prev_dist = (abs(prev_x - act_x) + abs(prev_y - act_y))
            print('distance: %d' % self.prev_dist)
            return (self.prev_dist > (MAPSIZE // len(self.map_tiles))) and (not is_pointer_on_red_pixel(pos))
        except Exception:
            return False

    def __do_on_new_game(self):
        self.map_generated = False
        self.canvas.show_loading_map_info()
        self.update()
        self.refresh_game = True

    def __do_on_game_lost(self):
        print('game lost')
        self.map_generated = False
        self.canvas.show_lost_map_info()
        if self.score > 0:
            self.score = self.score - 1
        self.update()
        self.game_lost = True
        self.__set_score_text()

    def __do_on_game_won(self):
        print('game won')
        self.map_generated = False
        self.canvas.show_won_map_info()
        self.score = self.score + 1
        self.update()
        self.game_won = True
        self.__set_score_text()

    def mouseMoveEvent(self, e):
        if not self.map_generated:
            pass
        else:
            x = e.globalPos().x()
            y = e.globalPos().y()

            if (x < (self.mapToGlobal(self.centralWidget().pos()).x() + 15)) or (x > (self.mapToGlobal(self.centralWidget().pos()).x() + self.centralWidget().height()) - 15) or (y < (self.mapToGlobal(self.centralWidget().pos()).y() + 15)) or (y > (self.mapToGlobal(self.centralWidget().pos()).y() + self.centralWidget().height()) - 15):
                pass
            elif is_pointer_on_black_pixel((x, y)) or self.__did_pointer_jump((x, y)):
                print('pointer on black pixel')
                self.__do_on_game_lost()
            elif is_pointer_on_green_pixel((x, y)):
                self.__do_on_game_won()
            else:
                self.act_pos = (x, y)
                self.window_pos = self.pos()

    def keyPressEvent(self, ev):
        if not self.map_generated:
            pass
        else:
            if ev.key() == QtCore.Qt.Key_R:
                self.canvas.show_loading_map_info()
                self.__do_on_new_game()
            elif ev.key() == QtCore.Qt.Key_W:
                self.__do_on_game_won()
            elif ev.key() == QtCore.Qt.Key_L:
                self.__do_on_game_lost()


import socket
import threading
import UI

connection = None

def receive():
   global connection
   try:
      while not UI.endGame:
         msg = connection.recv(1024).decode()
         if (msg):
            print("received message:", msg)
            msg = msg.split(":")
            newBoard = []
            for info in msg:
               newBoard.append(list(info))
            UI.boardInfo = newBoard
            UI.updateBoard()
            UI.my_turn = True
            if (UI.endGame):
               break
   finally:
      print("closing connection...")
      connection.close()

def send(connection):
   msg = ""
   for ele in UI.boardInfo:
      msg += "".join(ele)
      msg += ":"
   print (msg[:-1])
   connection.send(msg[:-1].encode())

def main():
   global connection
   s = socket.socket()

   port = 12345

   s.bind(('', port))

   s.listen(0)
   print ("Socket is listening at port", port)

   connection, addr = s.accept()

   print ('Got connection from', addr)

   t = threading.Thread(target=receive)
   t.start()

   UI.start(connection)

if __name__ == "__main__":
   main()


# -*- coding: utf-8 -*-
"""
Created on Fri Nov  6 21:29:57 2020

@author: Nick Brusco
"""
import tkinter as tk

class Dgui:
    name = "Drifter GUI"
    description = "Puts all your settings in a seperate tkinter window."

    def __init__ (self, config):

        self.fields = ['Population']
        ''', 'Activation Mutate Rate', 'Aggregation Mutate Rate',
                       'bias_max_value', 'bias_min_value', 'bias_mutate_power','bias_mutate_rate',
                       'bias_replace_rate']
        '''
        self.new_config = config.pop_size

        self.root = tk.Tk()
        ents = self.makeform(self.fields)
        self.root.bind('<Return>', (lambda event, e=ents: self.fetch(e)))
        b1 = tk.Button(self.root, text='Show',
                      command=(lambda e=ents: self.fetch(e)))
        b1.pack(side=tk.LEFT, padx=5, pady=5)
        b2 = tk.Button(self.root, text='Quit', command=self.root.quit)
        b2.pack(side=tk.LEFT, padx=5, pady=5)

    def fetch(self, entries):
        for entry in entries:
            field = entry[0]
            text  = entry[1].get()
            print('%s: "%s"' % (field, text))
        self.new_config = int(text)

    def makeform(self, fields):
        entries = []
        for field in fields:
            row = tk.Frame(self.root)
            lab = tk.Label(row, width=25, text=field, anchor='w')
            ent = tk.Entry(row)
            row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
            lab.pack(side=tk.LEFT)
            ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)
            entries.append((field, ent))
        return entries

    def step(self, config):
        config.pop_size = self.new_config
        self.root.update()


import asyncio
from pytgcalls import StreamType as ya
from pytgcalls.types.input_stream import AudioPiped as rambot
from pytgcalls.exceptions import (
    NoActiveGroupCall as memek,
    AlreadyJoinedError as asu,
    NotInGroupCallError as ajg
)
from telethon.tl import types
from telethon.utils import get_display_name
from telethon.tl.functions.users import GetFullUserRequest as ngentod
from userbot import call_py, DEVS
from userbot.utils import edit_delete, edit_or_reply
from userbot.events import register as boy

from userbot.utils.queues.queues import clear_queue

def vcmention(user):
    full_name = get_display_name(user)
    if not isinstance(user, types.User):
        return full_name
    return f"[{full_name}](tg://user?id={user.id})"

# credits by @vckyaz < vicky \>
# recode by @lahsiajg < starboy \>

@boy(outgoing=True, pattern=r"^\.joinvc(?: |$)(.*)")
@boy(incoming=True, from_users=DEVS, pattern=r"^\.cjoinvc(?: |$)(.*)")
async def join_(event):
    await edit_or_reply(event, f"**Hoiiii Pasti Ngeghibahin Gua Yah......**")
    if len(event.text.split()) > 1:
        chat = event.chat_id
        chats = event.pattern_match.group(1)
        try:
            chat = await event.client(ngentod(chats))
        except asu as e:
            await call_py.leave_group_call(chat)
            clear_queue(chat)
            await asyncio.sleep(3)
            return await edit_delete(event, f"**ERROR:** `{e}`", 30)
        except (NodeJSNotInstalled, TooOldNodeJSVersion):
            return await edit_or_reply(event, "NodeJs is not installed or installed version is too old.")
    else:
        chat_id = event.chat_id
        chats = event.pattern_match.group(1)
        vcmention(event.sender)
    if not call_py.is_connected:
        await call_py.start()
    await call_py.join_group_call(
        chat_id,
        rambot(
            'http://duramecho.com/Misc/SilentCd/Silence01s.mp3'
        ),
        chats,
        stream_type=ya().pulse_stream,
    )
    await edit_delete(event, f"**Berhasil Join Obrolan Suara**\n**Dalam Group {chat_id}**", 2)

@boy(outgoing=True, pattern="^\.leavevc(?: |$)(.*)")
@boy(incoming=True, from_users=DEVS, pattern=r"^\.cleavevc(?: |$)(.*)")
async def leavevc(event):
    """ leave video chat """
    await edit_or_reply(event, "**Gua cabut Dulu Lah Tod....**")
    chat_id = event.chat_id
    from_user = vcmention(event.sender)
    if from_user:
        try:
            await call_py.leave_group_call(chat_id)
        except (memek, ajg):
            await edit_or_reply(event, f"Eh {from_user}, Lo ga ada di os ngentot!!!!!")
        await edit_delete(event, f"**Berhasil Keluar Obrolan Suara**\n**Dari Group {chat_id}**", 1)


def main():
    s = open('day09.txt', 'r').read().rstrip()

    curDepth = 0
    score = 0
    inGarbage = False
    exclamation = -1
    garbageCount = 0

    i = 0
    while i < len(s):
        c = s[i]
        if exclamation == i:
            exclamation = -1
        elif c == '!':
            exclamation = i+1
        elif c == '>':
            inGarbage = False
        elif inGarbage:
            garbageCount += 1
        elif c == '{':
            curDepth += 1
        elif c == '}':
            score += curDepth
            curDepth -= 1
        elif c == '<':
            inGarbage = True

        i += 1

    print(garbageCount)

if __name__ == "__main__":
    main()


import os
import bpy
import math
import bmesh
import blenderbim.tool as tool
import ifcopenshell.util.element
from mathutils import Vector, Matrix

class Annotator:
    @staticmethod
    def add_text(related_element=None):
        curve = bpy.data.curves.new(type="FONT", name="Text")
        curve.body = "TEXT"
        obj = bpy.data.objects.new("Text", curve)
        obj.matrix_world = bpy.context.scene.camera.matrix_world
        if related_element is None:
            location, _, _, _ = Annotator.get_placeholder_coords(bpy.context)
        else:
            obj.data.BIMAssignedProductProperties.related_element = related_element
            location = related_element.location
        obj.location = location
        obj.hide_render = True
        font = bpy.data.fonts.get("OpenGost TypeB TT")
        if not font:
            font = bpy.data.fonts.load(
                os.path.join(bpy.context.scene.BIMProperties.data_dir, "fonts", "OpenGost Type B TT.ttf")
            )
            font.name = "OpenGost Type B TT"
        obj.data.font = font
        obj.data.BIMTextProperties.font_size = "2.5"
        collection = bpy.context.scene.camera.BIMObjectProperties.collection
        collection.objects.link(obj)
        Annotator.resize_text(obj)
        return obj

    @staticmethod
    def resize_text(text_obj):
        camera = None
        group = tool.Drawing.get_drawing_group(tool.Ifc.get_entity(text_obj))
        for element in tool.Drawing.get_drawing_elements(group):
            if element.is_a("IfcAnnotation") and element.ObjectType == "DRAWING":
                camera = tool.Ifc.get_object(element)
                break
        if not camera:
            return
        # This is a magic number for OpenGost
        font_size = 1.6 / 1000
        font_size *= float(text_obj.data.BIMTextProperties.font_size)

        font_size /= tool.Drawing.get_scale_ratio(tool.Drawing.get_diagram_scale(camera)["Scale"])

        text_obj.data.size = font_size

    @staticmethod
    def add_line_to_annotation(obj, co1=None, co2=None):
        if co1 is None:
            co1, co2, _, _ = Annotator.get_placeholder_coords()
        co1 = obj.matrix_world.inverted() @ co1
        co2 = obj.matrix_world.inverted() @ co2

        if isinstance(obj.data, bpy.types.Mesh):
            obj.data.vertices.add(2)
            obj.data.vertices[-2].co = co1
            obj.data.vertices[-1].co = co2
            obj.data.edges.add(1)
            obj.data.edges[-1].vertices = (obj.data.vertices[-2].index, obj.data.vertices[-1].index)

        if isinstance(obj.data, bpy.types.Curve):
            polyline = obj.data.splines.new("POLY")
            polyline.points.add(1)
            polyline.points[-2].co = list(co1) + [1]
            polyline.points[-1].co = list(co2) + [1]

        return obj

    @staticmethod
    def add_vertex_to_annotation(obj):
        verts_world_space = Annotator.get_placeholder_coords()
        vert_local = obj.matrix_world.inverted() @ verts_world_space[0]
        bm = tool.Blender.get_bmesh_for_mesh(obj.data, clean=True)
        bm.verts.new(vert_local)
        tool.Blender.apply_bmesh(obj.data, bm, obj)
        return obj

    @staticmethod
    def add_plane_to_annotation(obj, remove_face=False):
        # default order = bot left, top left, bot right, top right
        # therefore we redefine the order
        face_verts = [0, 2, 3, 1]

        verts_world_space = Annotator.get_placeholder_coords()
        verts_local = [obj.matrix_world.inverted() @ v for v in verts_world_space]
        bm = tool.Blender.get_bmesh_for_mesh(obj.data, clean=True)
        new_verts = [bm.verts.new(v) for v in verts_local]

        face = bm.faces.new([new_verts[i] for i in face_verts])
        if remove_face:
            bmesh.ops.delete(bm, geom=[face], context="FACES_ONLY")
        tool.Blender.apply_bmesh(obj.data, bm, obj)
        return obj

    @staticmethod
    def get_annotation_obj(drawing, object_type, data_type):
        camera = tool.Ifc.get_object(drawing)
        co1, _, _, _ = Annotator.get_placeholder_coords(camera)
        matrix_world = tool.Drawing.get_camera_matrix(camera)
        matrix_world.translation = co1
        collection = camera.BIMObjectProperties.collection

        if object_type == "TEXT":
            obj = bpy.data.objects.new(object_type, None)
            obj.matrix_world = matrix_world
            collection.objects.link(obj)
            return obj

        elif object_type in ("TEXT_LEADER", "SECTION_LEVEL"):
            data = bpy.data.curves.new(object_type, type="CURVE")
            data.dimensions = "3D"
            data.resolution_u = 2
            obj = bpy.data.objects.new(object_type, data)
            obj.matrix_world = matrix_world
            collection.objects.link(obj)
            return obj

        if object_type != "ANGLE":
            for obj in collection.objects:
                element = tool.Ifc.get_entity(obj)
                if element and element.ObjectType == object_type and obj.type == object_type.upper():
                    return obj

        if data_type == "mesh":
            data = bpy.data.meshes.new(object_type)
        elif data_type == "curve":
            data = bpy.data.curves.new(object_type, type="CURVE")
            data.dimensions = "3D"
            data.resolution_u = 2
        elif data_type == "empty":
            data = None

        obj = bpy.data.objects.new(object_type, data)
        obj.matrix_world = matrix_world
        collection.objects.link(obj)
        return obj

    @staticmethod
    def get_placeholder_coords(camera=None):
        if not camera:
            camera = bpy.context.scene.camera

        z_offset = camera.matrix_world.to_quaternion() @ Vector((0, 0, -1))

        if (
            ifcopenshell.util.element.get_pset(tool.Ifc.get_entity(camera), "EPset_Drawing", "TargetView")
            == "REFLECTED_PLAN_VIEW"
        ):
            z_offset *= -1

        y = camera.data.ortho_scale / 4

        res_x = bpy.context.scene.render.resolution_x
        res_y = bpy.context.scene.render.resolution_y
        if res_x > res_y:
            y *= res_y / res_x

        y_offset = camera.matrix_world.to_quaternion() @ Vector((0, y, 0))
        x_offset = camera.matrix_world.to_quaternion() @ Vector((y / 2, 0, 0))

        center = camera.matrix_world.inverted() @ bpy.context.scene.cursor.location
        center.z = 0
        center = camera.matrix_world @ center

        return (
            center + z_offset,
            center + z_offset + y_offset,
            center + z_offset + x_offset,
            center + z_offset + x_offset + y_offset,
        )


from utils.utils import *
import math
import itertools
import sys

class Solution:
    def __init__(self):
        self.length = None
        self.penultimateVertexIndex = None

class BellmanHeldKarp:
    def __init__(self, graph: Graph):
        # the input graph is a complete graph
        self.graph = graph

    def run(self):
        n = len(self.graph.nodes)
        # create index to vertax name map
        # create vertax name to index map
        indexNameDict = dict()
        nameIndexDict = dict()
        i = - 1
        for nodeName in self.graph.nodes.keys():
            i += 1
            indexNameDict[str(i)] = nodeName
            nameIndexDict[nodeName] = i
        #create matrix graph
        matrixGraph = [[0 for i in range(n)] for j in range(n)]
        for i in range(0, n):
            matrixGraph[i][i] = 0
        for value in self.graph.nodes.values():
            node: Node = value
            srcIndex = nameIndexDict[node.name]
            for name, length in node.outflowEdges.items():
                targetIndex = nameIndexDict[name]
                matrixGraph[srcIndex][targetIndex] = length
                matrixGraph[targetIndex][srcIndex] = length

        # assume vertex with index as 0 as the start vertex
        rows = int(math.pow(2, n - 1) - 1)
        columns = n - 1
        subProblems = [[0 for i in range(columns)] for j in range(rows)]

        # base case, set size as 1
        for i in range(0, n - 1):
            solution = Solution()
            solution.length = matrixGraph[0][i + 1]
            solution.penultimateVertexIndex = indexNameDict[str(i + 1)]
            subProblems[(1 << i) - 1][i] = solution

        vertexIndicesArray = [i for i in range(0, n - 1)]
        # set size 2 and beyond case
        for size in range(2, n):
            for indices in itertools.combinations(vertexIndicesArray, size):
                index = 0
                for i in indices:
                    index |= (1 << i)
                for j in indices:
                    solution = Solution()
                    solution.length = sys.maxsize
                    s = index & (~(1 << j))
                    for k in indices:
                        if k == j:
                            continue
                        subProblemSolution: Solution = subProblems[s - 1][k]
                        curLength = subProblemSolution.length + matrixGraph[k + 1][j + 1]
                        if curLength < solution.length:
                            solution.length = curLength
                            solution.penultimateVertexIndex = k
                    subProblems[index - 1][j] = solution
        lastStop = None
        minTourLength = sys.maxsize
        for j in range(0, n - 1):
            subProblemSolution: Solution = subProblems[rows - 1][j]
            length = subProblemSolution.length + matrixGraph[0][j + 1]
            if length < minTourLength:
                lastStop = j
                minTourLength = length
        # reconstruct tour
        edgeTemplate = "{} --> {}  :: {}"
        print(edgeTemplate.format(indexNameDict[str(lastStop + 1)], indexNameDict["0"], matrixGraph[0][lastStop + 1]))
        curProblemSize = n - 1
        curProblemSet = rows
        curVertaxIndex = lastStop
        while curProblemSize > 1:
            solution: Solution = subProblems[curProblemSet - 1][curVertaxIndex]
            print(edgeTemplate.format(indexNameDict[str(solution.penultimateVertexIndex + 1)], indexNameDict[str(curVertaxIndex + 1)], matrixGraph[solution.penultimateVertexIndex + 1][curVertaxIndex + 1]))
            curProblemSize -= 1
            curProblemSet &= ~(1 << curVertaxIndex)
            curVertaxIndex = solution.penultimateVertexIndex
        print(edgeTemplate.format(indexNameDict["0"], indexNameDict[str(curVertaxIndex + 1)], matrixGraph[0][curVertaxIndex + 1]))
        return minTourLength


def result(t):
    '''if(a==0 and b==0 and c==0):
        return 0'''
    a=t//2
    b=t//3
    c=t//4
    s=a+b+c
    print(a,b,c,s,t)
    if(a==0 and b==0 and c==0):
        return 0
    if(t>=s):
        return(t)
    else:
        return (result(a)+result(b)+result(c))
    #print(a,b,c,s,t)

inputs=[]
c=0
while True:
    if(c==10):
        break
    inp=input()
    if(inp=="" or int(inp)>1000000000 or int(inp)<0):
        break
    inputs.append(int(inp))
    c=c+1

for i in inputs:
    p=result(i)
    if(p>i):
        print(p)
    else:
        print(i)


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
  def nextLargerNodes(self, head: ListNode) -> List[int]:
    res = []
    node = head

    while node:
      res.append(node.val)
      node = node.next

    stack = [0]

    for i in range(len(res) - 1, -1, -1):
      val = res[i]

      while stack[-1] != 0 and stack[-1] <= val:
        stack.pop()

      res[i] = stack[-1]
      stack.append(val)

    return res


from flask import Blueprint, request, render_template
from app.db import get_db
from . import API

bp = Blueprint('view', __name__)

@bp.route('/index', methods=('GET', 'POST'))
def index():
    string = "
"
    db = get_db()
    i = 1
    if request.method == 'GET':
        API.Load_Database('http://api-rg-esiea-tp.westeurope.azurecontainer.io/flights', db)
        return render_template('view/index.html')
    if request.method == 'POST':
        code = request.form['code']
        departure = request.form['departure']
        arrival = request.form['arrival']

        # Retrieving Data from file
        if db.execute('SELECT * FROM flights WHERE code = ?', (code,)).fetchone() is not None:
            rowCode = db.execute('SELECT * FROM flights WHERE code = ?', (code,)).fetchone()
        else:
            rowCode = db.execute("select * from flights where arrival=:a and departure=:b",
                                 {"a": arrival, "b": departure}).fetchall()

        if rowCode is not None:
            for i in range(len(rowCode)):
                db.execute("INSERT INTO reservations (code,departure,arrival,price) VALUES (?,?,?,?);",
                           (rowCode[i][0], rowCode[i][1], rowCode[i][2], rowCode[i][3]))
            db.commit()
        else:
            return "No Flights for your entries, maybe come next time"

        for i in range(len(rowCode)):
            string += str(rowCode[i][0]) + " " + str(rowCode[i][1]) + " " + str(rowCode[i][2]) + " " + str(
                rowCode[i][3]) + "
"

        return f"Transaction Done, You can go check your reservations for the flight {string}"

@bp.route('/list')
def list():
    db = get_db()
    data = db.execute("SELECT * FROM reservations").fetchall()
    print(db.execute("SELECT * FROM reservations").fetchall())
    return render_template('view/list.html', rowQ=data)


import torch
import pytest
import warnings

from brocolli.testing.common_utils import OnnxBaseTester as Tester

def test_Linear_basic(
    shape=[1, 3],
):
    model = torch.nn.Linear(3, 5, bias=True)
    Tester("Linear_basic", model, shape)

def test_Linear_nobias(
    shape=[1, 3],
):
    model = torch.nn.Linear(3, 5, bias=False)
    Tester("Linear_nobias", model, shape)

if __name__ == "__main__":
    warnings.filterwarnings("ignore")
    pytest.main(["-p", "no:warnings", "-v", "test/op_test/onnx/linear/test_linear.py"])


# -*- coding: utf-8 -*-
"""File management utilities."""
import sys
import logging
import pathlib
import tarfile
from typing import Optional, Union

import lhapdf
import numpy as np
import pygit2
import yaml

# Package location, wherever it is installed
pkg = pathlib.Path(__file__).parent.absolute()

_logger = logging.getLogger(__name__)

ROUNDING = 6

def add_git_info(runcard_dict: dict):
    """Add the git version from which the fit was generated to the
    run card. This could later on be compared to the git version
    from which the report will be generated in order to make everything
    fully consistent.

    Parameters:
    -----------
    runcard_dict: dict
        dictionary containing information on the run card
    """
    try:
        import nnusf

        repo = pygit2.Repository(nnusf.__path__[0])
        # repo = pygit2.Repository(pathlib.Path().cwd())
        commit = repo[repo.head.target]
        runcard_dict["git_info"] = str(commit.id)
    except pygit2._pygit2.GitError as msg:
        runcard_dict["git_info"] = ""
        _logger.warning(f"Git version could not be retrieved! {msg}")

def compare_git_versions(runcard_dict: dict) -> None:
    """Compare the git versions from a fit card and the current
    local. If they are not the same then raises an error. This is
    relevant when it comes to generating report. This ensures that
    the report and subsequent LHAPDF grids are generated consistently.

    Parameters:
    -----------
    runcard_dict: dict
        dictionary containing information on the run card
    """
    try:
        import nnusf

        fit_version = runcard_dict["git_info"]
        repo = pygit2.Repository(nnusf.__path__[0])

        # Check if there are unstaged files in repository
        if repo.diff().stats.files_changed > 0:
            _logger.warning("There are unstaged files in the repository.")
        # repo = pygit2.Repository(pathlib.Path().cwd())
        commit = str(repo[repo.head.target].id)
        _logger.info("Git versions checked successfully.")

        if fit_version != commit:
            _logger.error(
                f"The git version '{fit_version}' from which the fit was produced"
                f" and the current git version '{commit}' from which the report is"
                f" about to be generated are different. Please switch to the branch"
                f" from the fit was generated."
            )
            sys.exit()
    except pygit2._pygit2.GitError as msg:
        _logger.warning(f"Git version could not be retrieved! {msg}")

def read(path: pathlib.Path, what=None) -> dict:
    """Read a file, the suitable way."""
    # autodetect
    if what is None:
        what = path.suffix[1:]

    if what == "yaml":
        return yaml.safe_load(path.read_text(encoding="utf-8"))
    else:
        raise ValueError(
            f"Format to be read undetected (attempted for '{what}')"
        )

def write(content: dict, path: pathlib.Path, what=None):
    """Write a file, the suitable way."""
    # autodetect
    if what is None:
        what = path.suffix[1:]

    if what == "yaml":
        path.write_text(yaml.dump(content), encoding="utf-8")
    else:
        raise ValueError(
            f"Format to be read undetected (attempted for '{what}')"
        )

def extract_tar(
    path: pathlib.Path, dest: pathlib.Path, subdirs: Optional[int] = None
):
    """Extract a tar archive to given directory."""
    with tarfile.open(path) as tar:
        tar.extractall(dest)

    if subdirs is not None:
        count = len(list(dest.iterdir()))
        if count == subdirs:
            return

        expected = (
            f"{subdirs} folders are" if subdirs > 1 else "A single folder is"
        )
        found = f"{count} files" if count > 1 else "a single file"
        raise ValueError(
            f"{expected} supposed to be contained by the tar file,"
            f" but more {found} have been detected"
        )

def mkdest(destination: pathlib.Path):
    """Make sure destination exists.

    Create it if does not exist, else make sure it is a directory.

    Parameters
    ----------
    destination: pathlib.Path
        path to check

    Raises
    ------
    NotADirectoryError
        if it exists but it is not a directory

    """
    if destination.exists():
        if not destination.is_dir():
            raise NotADirectoryError(
                f"The given destination exists, but is not a"
                f" directory - '{destination}'"
            )
    else:
        destination.mkdir(parents=True)

def split_data_path(ds: pathlib.Path) -> tuple[str, pathlib.Path]:
    """Extract dataset name, and commondata folder.

    Parameters
    ----------
    ds: pathlib.Path
        path to dataset

    Returns
    -------
    str
        dataset name
    pathlib.Path
        commondata base folder

    """
    name = ds.stem.strip("DATA_")

    return name, ds.parents[1]

def compute_lhapdf(
    pdfname: str,
    xgrid: Optional[Union[list, np.ndarray]] = None,
    q2grid: Optional[Union[list, np.ndarray]] = None,
    pid: Optional[list] = None,
):
    """Compute the high-Q2 Yadism predictions from a LHAPDF set.

    Returns:
    --------
        tuple(np.ndarray, dict)
            a tuple containing the predictions that has a shape
            (nrep, n_q2, n_x, n_pid) and a dictionary containing
            some metadata.
    """

    _logger.info("Computing the LHAPDF predictions.")
    input_pdfset = lhapdf.mkPDFs(pdfname)
    pdfinfo, n_rep = input_pdfset[0], len(input_pdfset)

    if xgrid is None:
        xgrid = np.geomspace(pdfinfo.xMin, pdfinfo.xMax, 100)

    if q2grid is None:
        q2grid = np.geomspace(pdfinfo.q2Min, pdfinfo.q2Max, 200)

    pid = pdfinfo.flavors() if pid is None else pid

    xmesh, q2mesh = np.meshgrid(xgrid, q2grid)
    store_replicas = []
    for replica in input_pdfset:
        pred = replica.xfxQ2(pid, xmesh.flatten(), q2mesh.flatten())
        pred = np.asarray(pred).reshape((*xmesh.shape, len(pid)))
        store_replicas.append(pred)

    if not isinstance(xgrid, list):
        xgrid = xgrid.tolist()

    if not isinstance(q2grid, list):
        q2grid = q2grid.tolist()

    q2grid = [round(q, ROUNDING) for q in q2grid]

    metadata = dict(x_grids=xgrid, q2_grids=q2grid, pid=pid, nrep=n_rep)
    return store_replicas, metadata


import setuptools

with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()

setuptools.setup(
    name="CurrencyPy",
    version="0.1.0",
    author="Lucas de Angelo Frassetto",
    author_email="lucasfrassetto8@gmail.com",
    description="Some tools for currency values, such as conversion sanitization and validation",
    keywords="currency tools converter",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/LucasFrassetto/CurrencyPy",
    project_urls={
        "Documentation": "",
        "Source Code": "https://github.com/LucasFrassetto/CurrencyPy",
    },
    classifiers=[
        "Development Status :: 1 - Planning",
        "Intended Audience :: Developers",
        "Intended Audience :: Education",
        "Natural Language :: Portuguese (Brazilian)"
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Topic :: Software Development",
        "Topic :: Utilities",
    ],
    package_dir={"": "currencypy"},
    packages=setuptools.find_packages(where="currencypy"),
    include_package_data=True,
    zip_safe=True,
    test_requires=[],
    install_requires=[],
    extras_require={
        'coverage'
    },
    python_requires=">=3.6",

)


from __future__ import print_function
import time
import hashlib
from collections import OrderedDict
import requests

def make_sign(token, key_values):
  args = []
  for k, v in key_values:
    args.append('%s=%s' % (k, v))

  a = '&'.join(args)
  print("a=", a)

  b = hashlib.md5(a).hexdigest()
  print("b=", b)
  return b.upper()

def callback( test_url):
  #api_url = "http://3.35.119.172:9410/pay"
  #api_url = "http://52.79.37.229:8080/pay"
  post_data = {
    #"pid": pid,
    #"money": money,
    #"sn": sn,
    #"notify_url": notify_url,
    #"pay_type_group": pay_type_group,
    #"remark": 'remark',
    #'sign': sign,
  }
  headers = {'content-type':'application/json; utf-8'}
  #  rep = requests.post( url, headers = headers , data = json.dumps(params) )
  req = requests.post(test_url, headers = headers, data=post_data)
  a = req.content
  print("*" * 100)
  print("call", req.status_code)
  print("response", a)

def main():
  callback("http://syo.vgs999.net")
  callback("http://www.test.com")

if __name__ == "__main__":
  main()


"""Pre-defined commands for cli."""
import textwrap
from pathlib import Path
from typing import List, Optional

from dosh_core.commands.base import Task
from dosh_core.logger import get_logger

logger = get_logger()

def init_config(config_path: Path) -> None:
    """Initialize dosh config in the current working directory."""
    if config_path.exists():
        logger.error(
            "The file `%s` already exists in current working directory.",
            config_path.name,
        )

    content = textwrap.dedent(
        """\
            local name = "there"                         -- you can use all features of Lua programming language.

            local function hello(there)                  -- even you can define your custom functions.
                there = there or name
                local message = "Hello, " .. there .. "!"
                cmd.run("osascript -e 'display notification \\"" .. message .. "\\" with title \\"Hi!\\"'")
            end

            cmd.add_task{                                -- cmd comes from dosh.
               name="hello",                             -- task name, or subcommand for your cli.
               description="say hello",                  -- task description for the help output.
               required_commands={"osascript"},          -- check if the programs exist before running the task.
               environments={"development", "staging"},  -- DOSH_ENV variable should be either development or staging to run this task.
               command=hello                             -- run hello function with its parameters when the task ran.
            }
        """
    )
    config_path.write_text(content)
    logger.info("The file `%s` is created.", config_path.name)

def generate_help(
    tasks: List[Task],
    description: Optional[str] = None,
    epilog: Optional[str] = None,
) -> str:
    """Generate a help output looking at available commands."""
    line_len = 79
    lines = []

    # DESCRIPTION
    if description is not None:
        lines.append(description)

    # TASKS
    if tasks:
        lines.extend(["", "Tasks:"])

        task_names = [t.name for t in tasks]
        max_len = min(max(map(len, task_names)), line_len)

        for task in tasks:
            command_init = f"  > {task.name.ljust(max_len)}"
            desc_first, *desc_list = task.description.split("\n")

            if not desc_first:
                lines.append(command_init)
                continue

            line_first, *line_list = textwrap.wrap(desc_first, line_len - max_len)
            lines.append(f"{command_init}   {line_first}")
            lines.extend(map(lambda l: f"{' ' * (max_len + 7)}{l}", line_list))

            for desc in desc_list:
                line_list = textwrap.wrap(desc, line_len - max_len)
                lines.extend(map(lambda l: f"{' ' * (max_len + 7)}{l}", line_list))
    else:
        lines.extend(
            [
                "",
                "There's no task.",
                "Create a file `dosh.lua` and write your tasks first.",
            ]
        )

    # DOSH COMMANDS
    lines.extend(
        [
            "",
            "Dosh commands:",
            "  > help                 print this output",
            "  > init                 initialize a new config in current working directory",
            "  > version              print version of DOSH",
            "",
            "  -c, --config PATH      specify config path (default: dosh.lua)",
            "  -d, --directory PATH   change the working directory",
            "  -v|vv|vvv, --verbose   increase the verbosity of messages:",
            "                         1 - default, 2 - detailed, 3 - debug",
        ]
    )

    # EPILOG
    if epilog:
        lines.extend(["", epilog])

    return "\n".join(lines)


import sys

import highlight_io
from highlight_io.integrations import Integration

try:
    from django import VERSION as DJANGO_VERSION
    from django.conf import settings as django_settings
    from django.core import signals
    from django.core.handlers.wsgi import WSGIHandler

    try:
        from django.urls import resolve
    except ImportError:
        from django.core.urlresolvers import resolve
except ImportError:
    raise NotImplementedError("Django not installed")

class DjangoIntegration(Integration):
    HIGHLIGHT_HEADER = "HTTP_X_HIGHLIGHT_REQUEST"
    INTEGRATION_KEY = "django"

    def __init__(self):
        self._orig_django = None

    def enable(self):
        self._orig_django = WSGIHandler.__call__

        def wrapped_call(app, environ, start_response):
            session_id, request_id = "", ""
            try:
                session_id, request_id = str(
                    environ[DjangoIntegration.HIGHLIGHT_HEADER]
                ).split("/")
            except (KeyError, ValueError):
                pass

            with highlight_io.H.get_instance().trace(session_id, request_id):
                return self._orig_django(app, environ, start_response)

        WSGIHandler.__call__ = wrapped_call

        signals.got_request_exception.connect(self._exception_handler)

    def disable(self):
        signals.got_request_exception.disconnect(self._exception_handler)
        WSGIHandler.__call__ = self._orig_django
        self._orig_django = None

    @staticmethod
    def _exception_handler(*args, **kwargs):
        _, exc, _ = sys.exc_info()
        highlight_io.H.get_instance().record_exception(exc)


import utils
import validate

def get_geometries_of_countries(country_codes):
    """
    Return a geopandas DataFrame with the geometries for the specified countries
    """
    assert validate.is_country_code_list(country_codes, code_type="nuts2")

    # Get a list of all included geographic units and all excluded geographic subunits
    included_geographic_units = []
    excluded_geographic_subunits = []
    countries = utils.read_yaml(utils.path("input", "countries.yaml"))
    relevant_countries = [country for country in countries if country["nuts2"] in country_codes]
    for country in relevant_countries:
        included_geographic_units.extend(country.get("included_geographic_units", []))
        excluded_geographic_subunits.extend(country.get("excluded_geographic_subunits", []))

    # Get a Geopandas DataFrame with the relevant rows
    map_df = utils.read_shapefile(utils.path("input", "gis", "ne_10m_admin_0_map_subunits.shp"))
    map_df = map_df[map_df.GU_A3.isin(included_geographic_units)]
    map_df = map_df[~map_df.SU_A3.isin(excluded_geographic_subunits)]

    # Merge the regions for each country and set the nuts2 country code as the index
    map_df = map_df.dissolve(by="SOV_A3")
    map_df["nuts2"] = map_df.apply(lambda row: utils.get_country_property(row.ADM0_A3, "nuts2", code_type="alpha3"), axis=1)
    map_df = map_df.set_index("nuts2")

    # Return a DataFrame with only the 'geometry' column
    return map_df[["geometry"]]


#!/usr/bin/env python
#encoding: utf8

# 上田本のフェイストラッキングを参考にクラスをまるごと書き換える
# カスケード分類器を作るのは失敗したので，色相からボールを抽出して重心を求める
# 隙間はモルフォロジーで埋める

#todo
# 重心の方を向く
# 凸包
# ノイズ除去
# ボールの大きさによって前進後退

import rospy, cv2, math
import numpy as np
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from geometry_msgs.msg import Twist
from std_srvs.srv import Trigger

LOWER_PERCENT = 0.01

class ObjectTracker():
    def __init__(self):
        sub = rospy.Subscriber("/cv_camera/image_raw", Image, self.get_image)
        self.bridge = CvBridge()
        self.image_org = None
        self.area_max = 0
        self.area_default = 0
        self.disp_default_now = 0
        self.area_whole = None
        self.pub = rospy.Publisher("object", Image, queue_size=1)
        self.hough = rospy.Publisher("hough", Image, queue_size=1)
        self.cmd_vel = rospy.Publisher("/cmd_vel", Twist, queue_size=1)
        rospy.wait_for_service("/motor_on")
        rospy.wait_for_service("/motor_off")
        rospy.on_shutdown(rospy.ServiceProxy("/motor_off", Trigger).call)
        rospy.ServiceProxy("/motor_on", Trigger).call()

    # どうもハフ変換は重いし上手く検出出来ない
    def test_hough(self, img):
        #img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        img = cv2.medianBlur(img,5)
        circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20, param1=50,param2=30,minRadius=0,maxRadius=0)
        for i in circles[0,:]:
            cv2.circle(img,(i[0],i[1]),i[2],(0,255,0),2)
            cv2.circle(img,(i[0],i[1]),2,(0,0,255),3)
        self.hough.publish(self.bridge.cv2_to_imgmsg(img, "mono8"))

    def get_image(self, img):
        try:
            # この時点でnparray型になっている
            self.image_org = self.bridge.imgmsg_to_cv2(img, "bgr8")
            # ついでに面積計算
            self.area_whole = self.image_org.shape[0] * self.image_org.shape[1]
        except CvBridgeError as e:
            rospy.logerr(e)

    def detect_orange(self):
        if self.image_org is None:
            return None
        org = self.image_org

        hsv = cv2.cvtColor(org, cv2.COLOR_BGR2HSV)

        # HSV色空間を用いてオレンジ色を抽出
        min_hsv_orange = np.array([15, 150, 40])
        max_hsv_orange = np.array([20, 255, 255])
        binary = cv2.inRange(hsv, min_hsv_orange, max_hsv_orange)
        # 遅いが円形のカーネル
        # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7,7))
        # 速いが矩形のカーネル
        # 不要かもしれない
        kernel = np.ones((5, 5), np.uint8)
        binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel, iterations = 2)
        center_img, point_cog = self.detect_center(binary)
        self.monitor(center_img)
        return point_cog

    # 2値画像の輪郭からモーメントを求める
    def detect_center(self, binary):
        _, contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        self.area_max = 0
        self.area_max_num = 0
        point_cog = (self.image_org.shape[1], self.image_org.shape[0])
        # 最大面積のインデックスを求める
        for i, cnt in enumerate(contours):
                area = cv2.contourArea(cnt)

                if(self.area_max < area):
                    self.area_max = area
                    self.area_max_num = i

        if(self.area_default == 0 and self.area_max != 0):
            self.area_default = self.area_max
        self.disp_default_now = (self.area_default - self.area_max) / self.area_whole
        #print("self.area_max_percentage: {}".format(self.area_max/self.area_whole))
        #print("disp_default_now: {}".format(self.disp_default_now))

        center_img = cv2.drawContours(self.image_org, contours, self.area_max_num, (0, 255, 0), 5)

        if(self.area_max/self.area_whole > LOWER_PERCENT):
            self.area_old = self.area_max
            M = cv2.moments(contours[self.area_max_num])
            cog_x = int(M['m10'] / M['m00'])
            cog_y = int(M['m01'] / M['m00'])
            point_cog = (cog_x, cog_y)
            center_img = cv2.circle(center_img, point_cog, 15, (255, 0, 0), thickness=-1)
        return center_img, point_cog

    def monitor(self, org):
        self.pub.publish(self.bridge.cv2_to_imgmsg(org, "bgr8"))
        return "detected"

    def rot_vel(self):
        point_cog = self.detect_orange()
        if (self.area_max/self.area_whole < LOWER_PERCENT):
            return 0.0
        wid = self.image_org.shape[1]/2
        pos_x_rate = (point_cog[0] - wid)*1.0/wid
        rot = -0.25*pos_x_rate*math.pi
        rospy.loginfo("detect %f", rot)
        return rot

    def control(self):
        m = Twist()
        if(self.area_max/self.area_whole > LOWER_PERCENT):
            if(self.disp_default_now > 0.01):
                m.linear.x = 0.1
                print("adv")
            elif(self.disp_default_now < -0.01):
                m.linear.x = -0.1
                print("back")
            else:
                m.linear.x = 0
                print("stay")
        m.angular.z = self.rot_vel()
        self.cmd_vel.publish(m)

if __name__ == '__main__':
    rospy.init_node('object_tracking')
    ot = ObjectTracker()

    rate = rospy.Rate(10)
    rate.sleep()
    while not rospy.is_shutdown():
        ot.control()
        rate.sleep()


import os,sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,parentdir)

import xmind
from xmind.core.markerref import MarkerId
xmind_name="redis"
w = xmind.load(os.path.dirname(os.path.abspath(__file__))+"\\"+xmind_name+".xmind")
s2=w.createSheet()
s2.setTitle("与spring结合")
r2=s2.getRootTopic()
r2.setTitle("与spring结合")

content={
'与spring结合':[
    'RedisTemplate:自动从RedisConnectionFactory工厂中获取连接，然后执行对应的Redis命令，在最后还会关闭Redis的连接',
    {'序列化器':[
        'Spring提供了RedisSerializer接口,它有两个方法:',
        'serialize：把那些可以序列化的对象转换为二进制字符串',
        'deserialize：通过反序列化把二进制字符串转换为Java对象'
    ]},
    'StringRedisSerializer和JdkSerializationRedisSerializer(RedisTemplate默认的序列化器)',
    {'对Redis数据类型操作的封装':[
        '获取地理位置操作接口:redisTemplate.opsForGeo()',
        '获取散列操作接口:redisTemplate.opsForHash()',
        '获取基数操作接口:redisTemplate.opsForHyperLogLog()',
        '获取列表操作接口 redisTemplate.opsForList()',
        '获取集合操作接口 redisTemplate.opsForSet()',
        '获取字符串操作接口 redisTemplate.opsForValue()',
        '获取有序集合操作接口 redisTemplate.opsForZSet()'
    ]},
    '对某一个键值对（key-value）做连续的操作:BoundXXXOperations接口',
    {'回调':[
        'SessionCallback接口:提供了良好的封装，对于开发者比较友好，因此在实际的开发中应该优先选择使用它',
        'RedisCallback接口:接口比较底层，需要处理的内容也比较多，可读性较差，所以在非必要的时候尽量不选择使用它'
    ]}
],
'与springboot结合':[
    'https://blog.csdn.net/qq_39172525/article/details/106343275',
],
'Lua脚本':[
    'RedisScript接口',
    '获取脚本的Sha1 String getSha1()',
    '获取脚本返回值 Class<T> getResultType()',
    '获取脚本的字符串 String getScriptAsString()'
]
}

#构建xmind
xmind.build(content,r2)
#保存xmind
xmind.save(w,os.path.dirname(os.path.abspath(__file__))+"\\"+xmind_name+".xmind")


__author__ = 'dany'
TEXTURE_PATH = "./src/textures/"

'''Os delays'''
MACOS_DELAY = 0
WINDOWS_DELAY = 50
LINUX_DELAY = 50

'''Screen sizes'''

DISPLAY_WIDTH = 1200
DISPLAY_HEIGHT = 700

projectiles_min_give = 7
projectiles_max_give = 12

ufo_min_hp = 7
ufo_max_hp = 12


import cv2
import numpy as np
import math
import matplotlib.pyplot as plt
import utils
import os   # read folder
import detector

def dist(p1,p2):
    return detector.euclidean_distance(p1,p2)

def calDistancesToGlints(img, c, realGlints, distThisImg, differenceNumberOfGlints, threshold=0, useThreshold=False):
    glints = []
    if useThreshold:
        glints = detector.find_glints(img, c, debug=False, threshold=threshold)
    else:
        glints = detector.find_glints(img, c, debug=False)
    differenceNumberOfGlints.append(len(realGlints) - len(glints))
    for g in glints:
        first,gDistMin = True, None
        for realG in realGlints:
            gDist = dist(realG, g)
            if first or gDistMin > gDist:
                gDistMin = gDist
                first=False
        distThisImg.append(gDist)

def mean(lst):
    sum = 0.0
    for i in lst:
        sum +=i
    return sum/len(lst)
def median(lst):
    lstC = lst.copy()
    lstC.sort()
    return lstC[int(len(lst)/2)-1]

def histShowAxis(value, axis):
    (distance, label) = value
    print(label+ " Means, Median")
    print(mean(distance), median(distance))
    axis.hist(distance, alpha=0.5, label=label, fill=False)
    axis.set_title(label)

def histShow(values):
    """param: values = [(distance1, label1), (distance2, label2)] """

    fig, axes = plt.subplots(nrows=1, ncols=3)
    ax0, ax1, ax2 = axes.flatten()
    print("Pupils:")
    histShowAxis(values[0],ax0)
    print("Glints:")
    histShowAxis(values[1],ax1)
    histShowAxis(values[2],ax2)
    fig.tight_layout()
    plt.show()
    """
    for (distance, label) in values:
        plt.hist(distance, density=True, bins=30, label=label)
    plt.show()"""

def getDistances():
    dirs = ["pattern0", "pattern1", "pattern2"]
    dirs = [(utils.load_images(d), utils.load_json(d, "glints"), utils.load_json(d, "pupils"), d) for d in dirs]

    distancesPupils = []
    distancesGlints = []
    differenceNumberOfGlints = []
    for (imgs, glints, pupils, d) in dirs:
        for i in range(len(imgs)):
            c, ax, angle = detector.find_pupil(imgs[i], debug=False)
            distancesPupils.append(dist(c, [pupils[i]['cx'], pupils[i]['cy'] ]))
            calDistancesToGlints(imgs[i], c, glints[i], distancesGlints, differenceNumberOfGlints, useThreshold=False)
    return distancesPupils, distancesGlints, differenceNumberOfGlints

def getBestDistancesPupils(threshold):
    dirs = ["pattern0", "pattern1", "pattern2"]
    dirs = [(utils.load_images(d), utils.load_json(d, "glints"), utils.load_json(d, "pupils"), d) for d in dirs]
    distancesPupils = []
    for (imgs, glints, pupils, d) in dirs:
        for i in range(len(imgs)):
            c, ax, angle = detector.find_pupil(imgs[i], debug=False, threshold=threshold)
            distancesPupils.append(dist(c, [pupils[i]['cx'], pupils[i]['cy'] ]))
    return distancesPupils

def computeBestThreshold():
    bestTPupils, bestDistancesPupils = 0, []
    first, bestMedianPupils, bestMedianGlints = True, 0,0
    for t in range(40, 80):
        print(t)
        distPupiils = getBestDistancesPupils(t)
        medPupils = median(distPupiils) + mean(distPupiils)
        if first:
            first=False
            bestTPupils = t
            bestDistancesPupils = distPupiils
            bestMedianPupils = medPupils
        if medPupils<bestMedianPupils:
            bestMedianPupils = medPupils
            bestTPupils = t
            bestDistancesPupils = distPupiils

    return (bestTPupils, bestDistancesPupils)

def main():
    """
    t1, distancesPupils = computeBestThreshold()
    print(t1)
    """
    distancesPupils, distancesGlints, differenceNumberOfGlints = getDistances()
    histShow([[distancesPupils, "distancespupils"], [distancesGlints, "distancesGlints"], [differenceNumberOfGlints, "differenceNumberOfGlints"]])

if __name__ == '__main__':
    main()


class Config(object):

    # get a token from @BotFather
    BOT_TOKEN = ""

    # Get these values from my.telegram.org
    API_ID = 1234567
    API_HASH = ""

    # No need to change
    DOWNLOAD_LOCATION = "./DOWNLOADS"
    ADL_BOT_RQ = {}
    CHUNK_SIZE = 128
    TG_MAX_FILE_SIZE = 4194304000
    HTTP_PROXY = ""
    PROCESS_MAX_TIMEOUT = 3700

    # TG Ids
    LOG_CHANNEL = -1007119867241
    OWNER_ID = 1288398723

    # bot username without @
    BOT_USERNAME = "AdvanceUrlUploaderBot"

    # auth users
    AUTH_USERS = [OWNER_ID]


import numpy as np
from qiskit import QuantumCircuit, Aer
from qiskit.visualization import plot_histogram
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import Statevector
import tensorflow as tf
from qiskit.utils import QuantumInstance
from qiskit_machine_learning.neural_networks import CircuitQNN
from qiskit.quantum_info import state_fidelity
import pickle
from qiskit_finance.circuit.library import NormalDistribution
from qiskit.opflow import (StateFn, PauliSumOp, Gradient, AerPauliExpectation)
from qiskit_machine_learning.neural_networks import OpflowQNN
import matplotlib.pyplot as plt

# Function for generator's loss function
def generator_cost(gen_params):
        curr_params = np.append(disc_params.numpy(),
                                gen_params.numpy())
        state_probs = Statevector(gen_disc_circuit.bind_parameters(curr_params)).probabilities()
        prob_fake_true = np.sum(state_probs[0b100:])
        cost = -prob_fake_true
        return cost

# Function for layerwise-circuit drawing for discriminator
def layer(qubits, num_layers, circ, disc_weights):
        for i in range(qubits):
                circ.h(i)
        for i in range(num_layers):
                for j in range(qubits):
                        circ.rx(disc_weights[(3 * j) + ((3 * qubits) * i)], j)
                        circ.ry(disc_weights[(3 * j) + 1 + ((3 * qubits) * i)], j)
                        circ.rz(disc_weights[(3 * j) + 2 + ((3 * qubits) * i)], j)
                for k in range(qubits):
                        if k != qubits - 1:
                                circ.cx(k, qubits - 1)
        circ.rx(disc_weights[-3], qubits-1)
        circ.ry(disc_weights[-2], qubits-1)
        circ.rz(disc_weights[-1], qubits-1)

        return circ

# Function for discriminator's loss function
def discriminator_cost(disc_params):
        curr_params = np.append(disc_params.numpy(),
                                gen_params.numpy())
        gendisc_probs = Statevector(gen_disc_circuit.bind_parameters(curr_params)).probabilities()
        realdisc_probs = Statevector(real_disc_circuit.bind_parameters(disc_params.numpy())).probabilities()
        prob_fake_true = np.sum(gendisc_probs[0b100:])
        prob_real_true = np.sum(realdisc_probs[0b100:])
        cost = prob_fake_true - prob_real_true
        return cost

def calculate_kl_divergence(model_distribution: dict, target_distribution: dict):
        kl_div = 0
        for bitstring, p_data in target_distribution.items():
                if np.isclose(p_data, 0, atol=1e-8):
                        continue
                if bitstring in model_distribution.keys():
                        kl_div += (p_data * np.log(p_data) - p_data * np.log(model_distribution[bitstring]))

                else:
                        kl_div += p_data * np.log(p_data) - p_data * np.log
        return kl_div

if __name__=="__main__":
        EPOCHS = 300 # Number of iterations / training epochs
        REAL_DIST_NQUBITS = 3 # Number of qubits
        measurement = 'Z' + ('I' * REAL_DIST_NQUBITS)
        real_circuit = NormalDistribution(REAL_DIST_NQUBITS, mu=0, sigma=0.15) # This is the circuit for target state
        layers = 2 # Number of layers in discriminator
# For generator circuit, we have taken an in-built function 'TwoLocal'
# 'TwoLocal' consists of alternating rotation and entanglement gates
        generator = TwoLocal(REAL_DIST_NQUBITS,
                        ['ry', 'rz'],
                        'cz',
                        'full',
                        reps=2,
                        parameter_prefix='θ_g',
                        name='Generator')

# Parameter Vector for discriminator
        disc_weights = ParameterVector('θ_d', (3 * (REAL_DIST_NQUBITS + 1) * layers) + 3)

        circuit = QuantumCircuit(REAL_DIST_NQUBITS+1, name="Discriminator")
# Discriminator circuit using function 'layer' indicating how many layers of block are being used
        discriminator = layer(REAL_DIST_NQUBITS+1, layers, circuit, disc_weights)

        N_GPARAMS = generator.num_parameters
        N_DPARAMS = discriminator.num_parameters

        gen_disc_circuit = QuantumCircuit(REAL_DIST_NQUBITS+1)
        gen_disc_circuit.compose(generator, inplace=True)
        gen_disc_circuit.compose(discriminator, inplace=True)

        real_disc_circuit = QuantumCircuit(REAL_DIST_NQUBITS+1)
        real_disc_circuit.compose(real_circuit, inplace=True)
        real_disc_circuit.compose(discriminator, inplace=True)

        expval = AerPauliExpectation() # method to calculate expectation value
        gradient = Gradient()
# Creating a Quantum Instance (statevector)
        qi_sv = QuantumInstance(Aer.get_backend('aer_simulator_statevector'))
# Circuit's wavefunction using 'StateFn' method
        gen_disc_sfn = StateFn(gen_disc_circuit)
        real_disc_sfn = StateFn(real_disc_circuit)

        H1 = StateFn(PauliSumOp.from_list([(measurement, 1.0)]))

# Combine operator and circuit
        gendisc_op = ~H1 @ gen_disc_sfn
        realdisc_op = ~H1 @ real_disc_sfn

# Calling QNN for updating the generator's weights
        gen_opqnn = OpflowQNN(gendisc_op,
            gen_disc_circuit.parameters[:N_DPARAMS], # input parameters (generator weights)
            gen_disc_circuit.parameters[N_DPARAMS:], # differentiable parameters (discriminator weights)
            expval,
            gradient,
            qi_sv)

# Calling QNN for updating the discriminator's weights
        disc_fake_opqnn = OpflowQNN(gendisc_op,
            gen_disc_circuit.parameters[N_DPARAMS:], # input parameters (generator weights)
            gen_disc_circuit.parameters[:N_DPARAMS], # differentiable parameters (discriminator weights)
            expval,
            gradient,
            qi_sv)

        disc_real_opqnn = OpflowQNN(realdisc_op,
            [],
            gen_disc_circuit.parameters[:N_DPARAMS], # differentiable parameters (discriminator weights)
            expval,
            gradient,
            qi_sv)

        init_gen_params = tf.Variable(np.random.uniform(low=-np.pi,
                                                    high=np.pi,
                                                    size=(N_GPARAMS)))
        init_disc_params = tf.Variable(np.random.uniform(low=-np.pi,
                                                    high=np.pi,
                                                    size=(N_DPARAMS)))
        gen_params = init_gen_params
        disc_params = init_disc_params
        generator_optimizer = tf.keras.optimizers.Adam(learning_rate=0.02)
        discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate=0.02)

        best_gen_params = init_gen_params
        gloss, dloss, kl_div, fidelity = [], [], [], []
        for epoch in range(EPOCHS):
                D_STEPS = 5
                for disc_train_step in range(D_STEPS):
                        # Differential with respect to discriminator weights (considering input parameters of generator circuit)
                        grad_dcost_fake = disc_fake_opqnn.backward(gen_params,
                                disc_params)[1][0, 0]
                        # Differential with respect to discriminator weights (considering input parameters of target circuit)
                        grad_dcost_real = disc_real_opqnn.backward([],
                                disc_params)[1][0, 0]
                        # Evaluate the discriminator's cost
                        grad_dcost = grad_dcost_real - grad_dcost_fake
                        grad_dcost = tf.convert_to_tensor(grad_dcost)
                        discriminator_optimizer.apply_gradients(zip([grad_dcost],
                                [disc_params]))
                        if disc_train_step % D_STEPS == 0:
                                dloss.append(discriminator_cost(disc_params))
                for gen_train_step in range(1):
                        # Differential with respect to generator weights
                        grad_gcost = gen_opqnn.backward(disc_params,
                                gen_params)[1][0, 0]
                        grad_gcost = tf.convert_to_tensor(grad_gcost)
                        generator_optimizer.apply_gradients(zip([grad_gcost],
                                [gen_params]))
                        gloss.append(generator_cost(gen_params))

                gen_checkpoint_circuit = generator.bind_parameters(gen_params.numpy())
                # Evaluating the state from generator in 'Statevector'
                gen_prob_dict = Statevector(gen_checkpoint_circuit).probabilities_dict()
                real_prob_dict = Statevector(real_circuit).probabilities_dict()
                current_kl = calculate_kl_divergence(gen_prob_dict, real_prob_dict)
                kl_div.append(current_kl)
                # Measuring the fidelities between generated and target state using 'state_fidelity' method
                fidelity.append(state_fidelity(Statevector(gen_checkpoint_circuit), Statevector(real_circuit)))

        plt.rcParams["font.family"] = "serif"
        plt.rcParams["mathtext.fontset"] = "dejavuserif"

        val = []
        val.append(gloss)
        val.append(dloss)
        val.append(fidelity)
        res = np.array(val)

        np.save('./result_data.npy', res)

# Plotting
        fig, (loss, fid) = plt.subplots(2, sharex=True,
                                        gridspec_kw={'height_ratios': [1, 1]},
                                        figsize = (12,12))
        fig.supxlabel('Training Epochs')
        loss.plot(range(len(gloss)), gloss, label="Generator Loss")
        loss.plot(range(len(dloss)), dloss, label="Discriminator Loss")
        loss.legend()
        loss.set(ylabel='Loss')
        loss.grid(ls='-.')
        fid.plot(range(len(fidelity)), fidelity, label="Fidelity", color="C3")
        fid.set(ylabel='Fidelity')
        fid.legend()
        fid.grid(ls='-.')
        fig.tight_layout();
        fig.savefig('./figure.png')


import logging
from typing import Any, Generator

import pytest

from screenpy import (
    NORMAL,
    Narrator,
    StdOutAdapter,
    act,
    aside,
    beat,
    scene,
    the_narrator,
)
from screenpy.narration.stdout_adapter import settings

TEST_ACT = "Three"
TEST_SCENE = "The Scene Where He Uses It"
TEST_BEAT = "Don't make me use this!"
TEST_ASIDE = "You made me use it!!"
TEST_RETVAL = ">:("
INDENT = settings.INDENT_CHAR * settings.INDENT_SIZE

@act(TEST_ACT, gravitas=NORMAL)
@scene(TEST_SCENE)
def prop():
    pass

class Prop:
    @beat(TEST_BEAT)
    def use(self) -> str:
        aside(TEST_ASIDE)
        return TEST_RETVAL

def _assert_stdout_correct(caplog) -> None:
    """Assert the correctness of logged messages to stdout."""
    assert len(caplog.messages) == 5
    assert caplog.messages[0] == f"ACT {TEST_ACT.upper()}"
    assert caplog.messages[1] == f"Scene: {TEST_SCENE.title()}"
    assert caplog.messages[2] == TEST_BEAT
    assert caplog.messages[3] == f"{INDENT}{TEST_ASIDE}"
    assert caplog.messages[4] == f"{INDENT}=> {TEST_RETVAL!r}"

class TestNarrateToStdOut:
    @pytest.fixture(autouse=True)
    def narrator_has_stdout(self) -> Generator[Narrator, Any, None]:
        old_adapters = the_narrator.adapters
        the_narrator.adapters = [StdOutAdapter()]
        yield the_narrator
        the_narrator.adapters = old_adapters

    def test_narrations(self, caplog) -> None:
        with caplog.at_level(logging.INFO):
            prop()
            Prop().use()

        _assert_stdout_correct(caplog)

    def test_flushed_narrations(self, caplog) -> None:
        with caplog.at_level(logging.INFO):
            with the_narrator.mic_cable_kinked():
                prop()
                Prop().use()

        _assert_stdout_correct(caplog)


# coding: utf-8
# @Time   : 2021/05/24
# @Author : enoche
# @Email  : enoche.chow@gmail.com
#
"""
##########################
"""

import numpy as np
import torch
import torch.nn as nn

class GeneralModel(nn.Module):
    r"""Base class for all models
    """
    def __init__(self, config, dataloader):
        super(GeneralModel, self).__init__()
        # load parameters info
        self.batch_size = config['train_batch_size']
        self.device = config['device']
        self.dataloader = dataloader

    def fit(self, epoch):
        raise NotImplementedError

    def predict(self, orders):
        r"""Predict the scores between users and items.
        Args:
            interaction (Interaction): Interaction class of the batch.
        Returns:
            torch.Tensor: Predicted scores for given users and items, shape: [batch_size]
        """
        raise NotImplementedError

    def __str__(self):
        """
        Model prints with number of trainable parameters
        """
        model_parameters = filter(lambda p: p.requires_grad, self.parameters())
        params = sum([np.prod(p.size()) for p in model_parameters])
        return super().__str__() + '\nTrainable parameters: {}'.format(params)

class AbstractDataPreprocessing:
    r"""Base class for all models to preprecessing data
        """
    def __init__(self):
        pass

    def preprocessing(self, config, df):
        """This function is used to do some data preprocess."""
        # full columns
        # ['seller_id', 'express_code', 'accept_city', 'accept_county',
        # 'accept_county_lon', 'accept_county_lat', 'receiver_county', 'receiver_county_lon', 'receiver_county_lat',
        # 'receiver_city', 'receiver_prov',
        # 'pay_hour',
        # 'pay_accept_inter', 'accept_hour', 'accept_ac1_inter', 'ac1_hour', 'ac1_ac2_inter', 'ac2_hour',
        # 'ac2_ac3_inter', 'ac3_hour', 'ac3_deliver_inter', 'deliver_station_hour', 'deliver_out_inter',
        # 'deliver_sign_inter', 'sign_hour', 'accept_fac_id', 'ac1_fac_id', 'ac2_fac_id', 'ac3_fac_id', 'deliver_fac_id',
        # 'date',
        # 'sin_pay_hour', 'cos_pay_hour', 'sin_dt_dayofweek', 'cos_dt_dayofweek', 'sin_dt_day', 'cos_dt_day',
        # 'sin_dt_month', 'cos_dt_month',
        # 'express_  one hot code',
        # 'total_cost']

        # not graph model, only keep features
        drop_columns = ['f1', 'seller_id', 'express_code', 'accept_city', 'accept_county',
                        'receiver_county', 'receiver_city', 'receiver_prov',
                        'pay_accept_inter', 'accept_hour', 'accept_ac1_inter', 'ac1_hour', 'ac1_ac2_inter', 'ac2_hour',
                        'ac2_ac3_inter', 'ac3_hour', 'ac3_deliver_inter', 'deliver_station_hour', 'deliver_out_inter',
                        'deliver_sign_inter', 'sign_hour', 'accept_fac_id', 'ac1_fac_id', 'ac2_fac_id', 'ac3_fac_id',
                        'deliver_fac_id', 'date']
        # keep latitude and longitude, and total_cost
        df.drop(drop_columns, inplace=True, axis=1)
        return df