import tkinter as tk
import requests
import json
import pyttsx3
import speech_recognition as sr
import re

API_KEY = "tJx9BcUyUome"
PROJECT_TOKEN = "tm0-6vVrJdYU"
RUN_TOKEN = "tYLJ-8Tf67Y7"

#Class for gathering information from the API
class Covid:
    #API request in function form, credits to https://towardsdatascience.com/bye-bye-beautiful-soup-how-i-scraped-covid-19-data-using-python-4dd06f930dc0
    def __init__(self, api_key, project_token):
        self.api_key = api_key
        self.project_token = project_token
        self.params ={"api_key":self.api_key}
        self.get_data()
    def get_data(self):
        response = requests.get(f'https://www.parsehub.com/api/v2/projects/{self.project_token}/last_ready_run/data', params=self.params)
        self.data = json.loads(response.text)

    #Function to get total cases in the whole world
    def get_totalcases(self):
        data = self.data['total']
        for info in data:
            if info['name'] == 'Coronavirus Cases:':
                return info['value']

    #Function to get total deaths in the whole world
    def get_totaldeaths(self):
        data = self.data['total']
        for info in data:
            if info['name'] == 'Deaths:':
                return info['value']

    #Function to get total recovered cases in the whole world
    def get_totalrecovered(self):
        data = self.data['total']
        for info in data:
            if info['name'] == 'Recovered:':
                return info['value']

    #Function to get information about a specific country
    def get_countrydata(self, country):
        data = self.data['country']
        for info in data:
            if info['name'].lower() == country.lower():
                return info

    #Countries in list form, this is used for determining a country in the dialog
    def list_of_countries(self):
        countries = []
        for country in self.data['country']:
            countries.append(country['name'].lower())
        return countries

data = Covid(API_KEY, PROJECT_TOKEN)

def talk(text):
    audio = pyttsx3.init('sapi5')
    voices = audio.getProperty('voices')
    audio.setProperty('rate', 196)
    audio.setProperty('volume', 2.7)
    audio.setProperty('voice', voices[1].id)
    audio.say(text)
    audio.runAndWait()

def mic():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        audio = r.listen(source)
        said = ""
        try:
            said = r.recognize_google(audio)
        except Exception as e:
            print("Exception:", str(e))
    return said.lower()

def ask(entry):
    data = Covid(API_KEY, PROJECT_TOKEN)
    countrylist = set(list(data.list_of_countries()))
    text = entry
    countrytext = text.split()
    pos = len(countrytext) - 1
    print(text)
    if text.startswith("") and "total cases" in text and (text.endswith("world") or text.endswith("globally")):
        response = "There is a total of " + str(data.get_totalcases()) + " covid cases \n around the globe."
        print(response)
        label2['text'] = response
    if text.startswith("") and "deaths" in text and (text.endswith("world") or text.endswith("globally")):
        response = "There is a total of " + str(data.get_totaldeaths()) + " covid deaths \n around the globe."
        print(response)
        label2['text'] = response
    if text.startswith("") and "recovered" in text and (text.endswith("world") or text.endswith("globally")):
        response = "There is a total of " + str(data.get_totalrecovered()) + " recovered covid patients \n around the globe."
        print(response)
        label2['text'] = response

        #per country
    if text.startswith("") and "total cases" in text and countrytext[pos] in countrylist:
        response = "There are " + data.get_countrydata(countrytext[pos])['total_cases'] + " covid cases in \n " + countrytext[pos]
        print(response)
        label2['text'] = response
    if text.startswith("") and "deaths" in text and countrytext[pos] in countrylist:
        response = "There are " + data.get_countrydata(countrytext[pos])['total_deaths'] + " covid deaths in \n " + countrytext[pos]
        print(response)
        label2['text'] = response
    if text.startswith("") and "recovered" in text and countrytext[pos] in countrylist:
        response = "There are " + data.get_countrydata(countrytext[pos])['total_recovered'] + " recovered covid patients in \n " + countrytext[pos]
        print(response)
        label2['text'] = response

    #country only
    if text in countrylist:
        response = countrytext[pos].upper() + ":\n" + data.get_countrydata(countrytext[pos])['total_cases'] + " covid cases \n" + data.get_countrydata(countrytext[pos])['total_deaths'] + " covid deaths \n" + data.get_countrydata(countrytext[pos])['total_recovered'] + " recovered patients"
        print(response)
        label2['text'] = response

def talking():
    data = Covid(API_KEY, PROJECT_TOKEN)
    print("Hello, I am Tracy!")
    talk("Hello, I am Tracy!")
    talk("What can I do for you?")
    END_PHRASE = "stop"
    countrylist = set(list(data.list_of_countries()))

    while True:

        print("Listening...")
        text = mic()
        countrytext = text.split()
        pos = len(countrytext) - 1
        print(text)
        if text.startswith("") and "total cases" in text and (text.endswith("world") or text.endswith("globally")):
            response = "There is a total of " + str(data.get_totalcases()) + " covid cases around the globe."
            print(response)
            talk(response)
            print()
        if text.startswith("") and "deaths" in text and (text.endswith("world") or text.endswith("globally")):
            response = "There is a total of " + str(data.get_totaldeaths()) + " covid deaths around the globe."
            print(response)
            talk(response)
            print()
        if text.startswith("") and "recovered" in text and (text.endswith("world") or text.endswith("globally")):
            response = "There is a total of " + str(data.get_totalrecovered()) + " recovered covid patients around the globe."
            print(response)
            talk(response)
            print()

        #per country
        if text.startswith("") and "total cases" in text and countrytext[pos] in countrylist:
            response = "There are " + data.get_countrydata(countrytext[pos])['total_cases'] + " covid cases in the " + countrytext[pos]
            print(response)
            talk(response)
            print()
        if text.startswith("") and "deaths" in text and countrytext[pos] in countrylist:
            response = "There are " + data.get_countrydata(countrytext[pos])['total_deaths'] + " covid deaths in the " + countrytext[pos]
            print(response)
            talk(response)
            print()
        if text.startswith("") and "recovered" in text and countrytext[pos] in countrylist:
            response = "There are " + data.get_countrydata(countrytext[pos])['total_recovered'] + " recovered covid patients in the " + countrytext[pos]
            print(response)
            talk(response)
            print()

        #country only
        if text in countrylist:
            response = countrytext[pos].upper() + ":\n" + data.get_countrydata(countrytext[pos])['total_cases'] + " covid cases \n" + data.get_countrydata(countrytext[pos])['total_deaths'] + " covid deaths \n" + data.get_countrydata(countrytext[pos])['total_recovered'] + " recovered patients"
            print(response)
            talk(response)
            print()

        if text == END_PHRASE:
            print("Thank you for using Trace-C")
            talk("Thank you for using Trace-C")
            label2['text'] = ""
            entry.delete(0, 'end')
            break

root = tk.Tk()
root.title("TRACE-C")

canvas = tk.Canvas(root, height=450, width=600)
canvas.pack()

micimg = tk.PhotoImage(file='mic.png')

bgimage = tk.PhotoImage(file='bgbg4.png')
bglabel = tk.Label(root, image=bgimage)
bglabel.place(x=0,y=0,relwidth=1, relheight=1)

frameside =tk.Frame(root, bg='#00221B', bd=2)
frameside.place(relx=.95, rely=0.03, relwidth=0.08, relheight=0.1, anchor='ne')

button2 = tk.Button(frameside, image = micimg, text="MIC", font=40, command = talking)
button2.place(relheight=0.9, relwidth=0.9, relx = 0.075, rely=0.075)

frame = tk.Frame(root, bg='#00221B', bd=5)
frame.place(relx=0.45, rely=0.05, relwidth=0.8, relheight=0.075, anchor='n')

entry = tk.Entry(frame, font =('Monaco bold', 11))
entry.place(relwidth=0.78,relheight=1)

button = tk.Button(frame, font =('Monaco bold', 11), text="Ask", command =lambda: ask(entry.get().lower()))
button.place(relx=0.80, relheight=1, relwidth=0.2)

frame2 = tk.Frame(root, bg='#00221B', bd=10)
frame2.place(relx=0.5, rely=0.15, relwidth=0.8,relheight=0.80, anchor='n')

label2 = tk.Label(frame2, font =('Monaco', 10), text = "")
label2.place(relwidth=1, relheight=1)

root.mainloop()


import numpy as np
import pybullet as p
from constants import *
import scene_builder
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, writers
import tensorflow as tf
import time
import disect_model
import os
np.random.seed(123456)

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"

walls, map_label, bodies = scene_builder.build_scene_full()

STEP_SIZE = PIXEL_FRACTION
ROBOT_RADIUS = PIXEL_FRACTION / 2
NUM_TRIES = 64
MAX_DIST = SCENE_SIZE * np.sqrt(2)
MAX_STEPS = 200
EMBEDDING_SIZE = 512

def pos_to_coords(pos):
    coords = np.floor(pos / PIXEL_FRACTION).astype(np.int)
    return (coords[0], coords[1])

def random_valid_pos(walls, map_label):
    while True:
        pos = scene_builder.random_pos(walls)
        if map_label[pos_to_coords(pos)] == 1:
            return pos

frames = []

def preprocess(img, view):
    return prepocess_image(img), normalize_view(view)

def prepocess_image(img):
    img = img[:,:,:3].astype(np.float) / 255
    img = img * 2 - 1
    return img.reshape([1] + IMG_SHAPE)

def normalize_view(view):
    view = (view - VIEW_MEANS) / VIEW_VARIATION
    return view.reshape((1, VIEW_DIM))

def get_image(pos, rot):
    pos = np.array([pos[0], pos[1], PUPPER_HEIGHT - np.random.random() * HEIGHT_VARIATION])
    pitch = (1 - 2 * np.random.random()) * PITCH_VARIATION
    roll = (1 - 2 * np.random.random()) * ROLL_VARIATION
    rot = np.array([rot, pitch, roll])
    view = scene_builder.pack_viewpoint(pos, rot)
    w, h, rgb, depth, seg = scene_builder.get_image(view)
    return rgb, view

rep_net, map_net, loc_net = disect_model.build_model()

goal = random_valid_pos(walls, map_label)
position = random_valid_pos(walls, map_label)

start = time.time()

embedding = np.zeros([1, EMBEDDING_SIZE])
img, pose = get_image(position, np.random.random() * 2 * np.pi)
pimg, pose = preprocess(img, pose)
embedding = rep_net.predict([pimg, pose, embedding])

est_map = map_net.predict(embedding)[0]
frames.append((pose, pose, goal, est_map, img))

while len(frames) < MAX_STEPS:
    best_score = np.inf
    best_pos = position
    best_rot = 0
    for i in range(NUM_TRIES):
        rot = np.random.random() * 2 * np.pi
        new_pos = STEP_SIZE * np.array([np.cos(rot), np.sin(rot)]) + position
        min_coords = pos_to_coords(new_pos - ROBOT_RADIUS)
        max_coords = pos_to_coords(new_pos + ROBOT_RADIUS)
        prob = np.min(est_map[min_coords[0]:max_coords[0]+1, min_coords[1]:max_coords[1]+1])
        prob = min((prob * 2) ** 2, 1)
        score = np.linalg.norm(goal - new_pos) * prob + MAX_DIST * (1 - prob)
        if score < best_score:
            best_score = score
            best_pos = new_pos
            best_rot = rot
    position = best_pos
    img, pose = get_image(position, best_rot)
    pimg, pose = preprocess(img, pose)
    est_pose = loc_net.predict([pimg, embedding])
    embedding = rep_net.predict([pimg, pose, embedding])
    est_map = map_net.predict(embedding)[0]
    if np.linalg.norm(goal - position) < STEP_SIZE:
        goal = random_valid_pos(walls, map_label)
    frames.append((pose, est_pose, goal, est_map, img))

print(time.time() - start, 'for pathfinding')

def plot_goal(ax, goal):
    ax.scatter(goal[1] * 8, goal[0] * 8, c='g')

def plot_pose(ax, pose, c):
    pose = pose[0]
    pos = (pose[:2] * 4 + 4) * 8
    rot = pose[3:5]
    rot = rot / np.linalg.norm(rot)
    ax.quiver(pos[1], pos[0], rot[1], rot[0], angles='xy')
    ax.scatter(pos[1], pos[0], c=c)

def animate(frame, axs):
    pose, est_pose, goal, est_map, img = frame
    for i in np.ndindex(axs.shape):
        axs[i].clear()
    axs[0, 0].matshow(map_label, extent=(0, MAP_SIZE, MAP_SIZE, 0))
    axs[1, 0].imshow(img, extent=(0, MAP_SIZE, MAP_SIZE, 0))
    axs[0, 1].imshow(est_map > 0.5, extent=(0, MAP_SIZE, MAP_SIZE, 0))
    axs[1, 1].imshow(est_map, extent=(0, MAP_SIZE, MAP_SIZE, 0))
    for i in [(0, 0), (0, 1), (1, 1)]:
        plot_goal(axs[i], goal)
        plot_pose(axs[i], est_pose, 'r')
        plot_pose(axs[i], pose, 'b')

fig, axs = plt.subplots(2, 2)
fig.set_size_inches(6.4, 6.4)
fig.tight_layout()
ani = FuncAnimation(fig, animate, frames=frames, fargs=(axs,), repeat=False)
writer = writers['ffmpeg'](fps=10, bitrate=1800)
ani.save('animation.mp4', writer=writer)


import random
from turtle import Turtle

COLOR = ["red", "blue", "yellow", "purple", "orange", "cyan", "pink", "white"]

class Food(Turtle):

    def __init__(self):
        super().__init__("circle")
        self.fillcolor("blue")
        self.penup()
        self.shapesize(stretch_wid=0.5, stretch_len=0.5)
        self.speed("fastest")
        self.relocate()

    def relocate(self):
        self.fillcolor(random.choice(COLOR))
        self.goto(random.randint(-270, 270), random.randint(-270, 270))


import uuid
import logging

log = logging.getLogger("volux operator")
log.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler("volux_operator.log")
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter(
    "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
log.addHandler(fh)
log.addHandler(ch)

class Axis:
    def __init__(self, pin, name, enabled=False):
        self.pin = pin
        self.name = name
        self.enabled = enabled
        self.UUID = uuid.uuid4()

    def enable(self):
        if self.enabled is True:
            raise RuntimeError("Axis is already enabled")
        else:
            raise NotImplementedError()

    def disable(self):
        if self.enabled is False:
            raise RuntimeError("Axis is already disabled")
        else:
            raise NotImplementedError()

    def toggle_enabled(self):
        if self.enabled is True:
            self.disable()
        elif self.enabled is False:
            self.enable()
        else:
            raise TypeError(".enabled must be boolean")


'''
Exercise 13: Split a string on hyphens
Write a program to split a given string on hyphens and display each substring.
Given:
str1 = Emma-is-a-data-scientist
Expected Output:
Displaying each substring

Emma
is
a
data
scientist

'''
mystr = "Emma-is-a-data-scientist"

i = 0
substr = ""
li = list()
while i < len(mystr):
    if mystr[i] != '-':
        substr += mystr[i]
    else:
        li.append(substr)
        substr = ""
    i = i + 1
for i in li:
     print(i)

'''
Alternate/ Easier Method
li = list(map(str,mystr.split('-')))
for i in li:
    print(i)
'''


import os
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import requests
from bs4 import BeautifulSoup

SPOTIPY_CLIENT_ID = os.environ.get('SPOTIPY_CLIENT_ID')
SPOTIPY_CLIENT_SECRET = os.environ.get('SPOTIPY_CLIENT_SECRET')
SPOTIPY_REDIRECT_URI = os.environ.get('SPOTIPY_REDIRECT_URI')

def welcome_message():
    msg = '''\033[1;33;40m
        WELCOME TO...

                   .___________. __    __   _______
                   |           ||  |  |  | |   ____|
         ______    `---|  |----`|  |__|  | |  |__
        |______|       |  |     |   __   | |   __|
                       |  |     |  |  |  | |  |____
                       |__|     |__|  |__| |_______|

        .___  ___.  __    __       _______. __    ______    .___________. __  .___  ___.  _______
        |   \/   | |  |  |  |     /       ||  |  /      |   |           ||  | |   \/   | |   ____|
        |  \  /  | |  |  |  |    |   (----`|  | |  ,----'   `---|  |----`|  | |  \  /  | |  |__
        |  |\/|  | |  |  |  |     \   \    |  | |  |            |  |     |  | |  |\/|  | |   __|
        |  |  |  | |  `--'  | .----)   |   |  | |  `----.       |  |     |  | |  |  |  | |  |____
        |__|  |__|  \______/  |_______/    |__|  \______|       |__|     |__| |__|  |__| |_______|

        .___  ___.      ___       ______  __    __   __  .__   __.  _______
        |   \/   |     /   \     /      ||  |  |  | |  | |  \ |  | |   ____|
        |  \  /  |    /  ^  \   |  ,----'|  |__|  | |  | |   \|  | |  |__       ______
        |  |\/|  |   /  /_\  \  |  |     |   __   | |  | |  . `  | |   __|     |______|
        |  |  |  |  /  _____  \ |  `----.|  |  |  | |  | |  |\   | |  |____
        |__|  |__| /__/     \__\ \______||__|  |__| |__| |__| \__| |_______|

        Type a valid date in time and we'll create you a Spotify playlist with the top songs
        playing in the world in that moment.

        OPTIONS:
        [1] - I only want the songs by the original performers (- less songs)
        [2] - I don't care who performs it (+ more songs)
        ----------------------------------------------------------------------

        Let's go for a musical ride.

\033[m'''
    print(msg)

def bye_message():
    print('\033[33m\nThanks for trying us out!\nTime to take off now.\nSee you next time!\033[m')

def is_date_format_invalid(answer_date_split):
    # The idea here is not to treat an invalid date format and keep asking the user for valid input
    if len(answer_date_split) != 3:
        return True
    if len(answer_date_split) == 3:
        first_item_is_numeric = True if answer_date_split[0].isnumeric() and len(
            answer_date_split[0]) == 4 else False
        second_item_is_numeric = True if answer_date_split[1].isnumeric() and len(
            answer_date_split[1]) == 2 else False
        third_item_is_numeric = True if answer_date_split[2].isnumeric() and len(
            answer_date_split[2]) == 2 else False
        if first_item_is_numeric and second_item_is_numeric and third_item_is_numeric:
            return False
        return True

def send_request_to_billboard(date):
    url_billboard = f'https://www.billboard.com/charts/hot-100/{date}/'

    response = requests.get(url=url_billboard, allow_redirects=False)
    if response.status_code != 200:
        raise Exception(f'Error. We expeected a status_code value of 200, but we got {response.status_code} instead.'
                        f'.\nPlease, be sure to check if the URL is active and the date provided is valid.')
    return response

def grab_music_titles_and_artist_names(response):
    soup = BeautifulSoup(response.content, 'lxml')
    containers = soup.find_all('div', {'class': 'o-chart-results-list-row-container'})
    if containers is None:
        raise Exception("Error. Please verify if the tags for each container exist in the response.")
    songs_and_artists = []
    for i, container in enumerate(containers):
        i += 1
        title_tag = container.find('h3', {'id': 'title-of-a-story'})
        artist_tag = title_tag.find_next_sibling()
        song_title = title_tag.text.strip()
        artist_name = artist_tag.text.strip()
        songs_and_artists.append((song_title, artist_name))
        # print(f'{i}) {song_title.upper()} - {artist_name}')
    return songs_and_artists

def spotify_create_playlist(answer_date='1998-11-21', songs_and_artists=None, option='1'):
    playlist_name = f"({answer_date}) Billboard top charts"
    year = answer_date.split('-')[0]
    scope = 'playlist-modify-private'

    sp = spotipy.Spotify(
        client_credentials_manager=SpotifyOAuth(
            scope=scope,
            client_id=SPOTIPY_CLIENT_ID,
            client_secret=SPOTIPY_CLIENT_SECRET,
            redirect_uri=SPOTIPY_REDIRECT_URI,
            show_dialog=True,
            cache_path="token.txt")
    )
    user_id = sp.current_user()['id']

    print(f"\n\033[1;32mWe're at Spotify.\033[m\nLet's start the creation of your playlist...\n")

    spotify_uris = []
    for song_title, artist_name in songs_and_artists:
        if option == '1':
            spotify_results = sp.search(q=f"track:{song_title} artist:{artist_name}", type="track")
        else:
            spotify_results = sp.search(q=f"track:{song_title} year:{year}", type="track")
        try:
            uri = spotify_results['tracks']['items'][0]['uri']
            spotify_uris.append(uri)
        except:
            print(f"\033[31mWe're skipping song \033[1;37;40m'{song_title.upper()}'\033[0m \033[31mbecause "
                  f"we were unable to find it. Sorry.\033[m")

    if option == '1':
        playlist_name = f"({answer_date}) Billboard top charts (original performers)"
    playlist = sp.user_playlist_create(user=user_id,
                                       name=playlist_name,
                                       public=False,
                                       description='''Created by "The Music Time Machine" developed by
                                       Barbara Calderon (github.com/barbaracalderon) in january, 2023.''')
    playlist_id = playlist["id"]
    sp.playlist_add_items(playlist_id=playlist_id, items=spotify_uris)
    print(f"\nDone.\n\033[1;32mPlaylist created successfully.\033[m")


from tools.my_request import MyRequest
from tools.wexcel import *
import os

class InterfaceTest():
    def __init__(self,file):
        self.res = get_data(file, "1")#从excel读取原始数据

#将exlce的类似'a=1,b=2,c=3'格式的，转为字典
    def dic(self,s):
        t=[]
        k=[]
        v=[]
        dic={}
        t=s.split(",")
        for i in t:
            k.append(i.split("=")[0])
            v.append(i.split("=")[1])
        dic=dict(zip(k,v))
        return dic

    def check(self,ck,res):
        fag = 1
        # for k,v in ck.items():
        #     if k in res.keys():
        #         if v==res[k]
        for i in ck.keys():
            if i in res.keys():
                if ck[i]!= str(res[i]):
                    fag=0
        if fag:
            res="校验成功"
        else:
            res="校验失败"
        return res

#将从excel读取的每行内容，提取出url，data，method，check等关键值，并生产字典返回
    def parameter(self):
        dic=[]
        for i in self.res[1:]:
            dic_={}
            dic_=dict(url=i[2],method=i[3],data=self.dic(i[4]),check=self.dic(i[5]))
            dic.append(dic_)
        return dic

#将 parameter类函数返回的字典传入，调用tools包下的MyRequest类，返回请求结果，返回响应和状态结果以list返回
    def my_request(self,data):
        par=data
        res=[]
        for i in par:
            res_=[]
            a=MyRequest(url=i.get("url"),method=i.get("method"),data=i.get("data"))

            res_.append(self.check(i.get("check"),a.response))
            res_.append(str(a.response))
            res.append(res_)
        return res

    def update_excl(self,f):
        req=f
        for i in range(len(req)):
            self.res[i+1][6]=req[i][0]
            self.res[i+1][7] = req[i][1]
        return self.res

#在原始excel目录下，生成结果文件
    def sava_excl(self):

        name1=os.path.basename(file)
        dir=os.path.dirname(file)
        name1_prefix=name1.split(".")[0]
        name=name1_prefix+"_reslut.xlsx"
        exfile=os.path.join(dir,name)
        wexcel(exfile,name1,self.res)

#整合相关请求，只需要调用该类函数即可
    def run(self):
        b = self.my_request(self.parameter())
        self.update_excl(b)
        self.sava_excl()

file = "D:\python_sted\day8\用例模板.xlsx"
cl=InterfaceTest(file)
cl.run()
# b=cl.run(cl.my_request())
# #print(b)
# cl.update_excl(b)
# #print(cl.res)


# !/usr/bin/env python3
# coding=utf-8
from datetime import datetime
from utils.db import db_query
from utils.config import Config
PAGE_SIZE = Config.get('danmaku.page_size')
RANK_SIZE = Config.get('danmaku.rank_size')

async def query_danmaku_rank_by_date(room_id, current_date=datetime.now()):
    sql = F"""
            SELECT uname, COUNT(*) AS 'danmaku' FROM bili.bili_danmaku
                WHERE timestamp > UNIX_TIMESTAMP('{current_date.strftime('%Y-%m-%d')} 00:00:00')* 1000
                AND timestamp < UNIX_TIMESTAMP( '{current_date.strftime('%Y-%m-%d')} 23:59:59' )* 1000
                AND room_id={room_id} GROUP BY uid ORDER BY danmaku DESC LIMIT {RANK_SIZE}
        """

    return await db_query(sql)

async def query_danmaku_list(room_id, query_date, uid, page=1):
    page_offset = 0 if page == 1 else (int(page) - 1) * PAGE_SIZE - 1
    sql = "SELECT DISTINCT msg,timestamp FROM bili.bili_danmaku WHERE timestamp > UNIX_TIMESTAMP(%s)*1000 " \
          "AND room_id = %s AND uid = %s ORDER BY timestamp LIMIT %s,%s"

    return await db_query(sql, (query_date, room_id, uid, page_offset, PAGE_SIZE))

async def query_random_danmaku(room_id, uid):
    sql = F"SELECT  FROM_UNIXTIME(timestamp / 1000, '%%Y-%%m-%%d') AS timestamp, msg FROM bili.bili_danmaku " \
          F"WHERE uid={uid} AND room_id={room_id} ORDER  BY rand() LIMIT {RANK_SIZE}"
    return await db_query(sql)


from Products.Zuul.form import schema
from Products.Zuul.interfaces.component import IComponentInfo
from Products.Zuul.interfaces import IFacade

# ZuulMessageFactory is the translation layer. You will see strings intended to
# been seen in the web interface wrapped in _t(). This is so that these strings
# can be automatically translated to other languages.
from Products.Zuul.utils import ZuulMessageFactory as _t

# In Zenoss 3 we mistakenly mapped TextLine to Zope's multi-line text
# equivalent and Text to Zope's single-line text equivalent. This was
# backwards so we flipped their meanings in Zenoss 4. The following block of
# code allows the ZenPack to work properly in Zenoss 3 and 4.

# Until backwards compatibility with Zenoss 3 is no longer desired for your
# ZenPack it is recommended that you use "SingleLineText" and "MultiLineText"
# instead of schema.TextLine or schema.Text.
from Products.ZenModel.ZVersion import VERSION as ZENOSS_VERSION
from Products.ZenUtils.Version import Version
if Version.parse('Zenoss %s' % ZENOSS_VERSION) >= Version.parse('Zenoss 4'):
    SingleLineText = schema.TextLine
    MultiLineText = schema.Text
else:
    SingleLineText = schema.Text
    MultiLineText = schema.TextLine

class IExampleComponentInfo(IComponentInfo):
    """
    Info adapter for ExampleComponent
    """

    devDescr = SingleLineText(title=_t(u"Device Description"), readonly=True, group='Details')
    devStatus = schema.Int(title=_t(u"Device Status"), readonly=True, group='Details')
    devErrors = schema.Int(title=_t(u"Device Errors"), readonly=True, group='Details')

class IHardDiskInfo(IComponentInfo):
    """
    Info adapter for HardDisk
    """
    description = SingleLineText(title=_t(u"Hard Disk Description"), readonly=True, group='Details')

# The name of the IFacade class here ( IExampleDeviceFacade ) must match what is defined in an
#   adapter stanza's provides=".interfaces. this_is_the_bit_that_must_match"
#   ie. IExampleDeviceFacade in configure.zcml
# The method name and parameters must match those defined for the facade that implements
#   IExampleDeviceFacade in facades.py (ie. add_ExampleDevice )

class IExampleDeviceFacade(IFacade):
    def add_ExampleDevice(self, deviceIp, community, comment):
        """Add a device of class ExampleDevice"""

# The name of the IFacade class here ( IAppFacade ) must match what is defined in an
#   adapter stanza's provides=".interfaces. this_is_the_bit_that_must_match"
#   ie. IAppFacade in configure.zcml
# The method name and parameters must match those defined for the facade that implements
#   IAppFacade in facades.py (ie. myFacadeFunc )

class ImyAppFacade(IFacade):
    def myFacadeFunc(self, ob, comments, rackSlot):
        """ Modify comments / rackSlot attributes for a device object"""


import re
import emoji
import pandas as pd
from tqdm import tqdm

def read_csv(csvfile):
    df = pd.read_csv(csvfile)
    return df

def basic_clean(text):
    #筛除无价值内容
    text = text.replace("@ ", "@")  # 统一转发格式
    text = re.sub(r"(回复)?(//)?\s*@\S*?\s*(:| |$)", " ", text)  # 去除正文中的@和回复/转发中的用户名
    text = re.sub(r"(回复)?(//)?\s*@\S*?\s*(:| |$)", " ", text)  # 去除正文中的@和回复/转发中的用户名(针对某些用户的二级@）
    text = re.sub(r"#\S+#", "", text)  # 除去话题内容
    URL_REGEX = re.compile(
        r'(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))',
        re.IGNORECASE)
    text = re.sub(URL_REGEX, "", text)  # 去除网址
    text = text.replace("转发微博", "")
    text = text.replace("轉發微博", "")
    text = text.replace("分享图片", "")
    text = text.replace("网页链接", "")
    text = text.replace("地址：网页链接", "")
    text = text.replace("Repost", "")
    text = text.replace("repost", "")  # 去除无意义的词语
    text = re.sub(r"\s+", " ", text)  # 合并正文中过多的空格
    text = emoji.demojize(text)  # 表情符重编码
    return text

def chinese_fliter(text):
    r1 = '[a-zA-Z0-9’!"#$%&\'()*+,-./:：;；|<=>?@~（）·①②③⑤④⑥⑦⑧⑨『』「」＜＞<>℃♤♡♢♧♠♥♦♣☀☀♀♂♩♪♫♬*＊✲❈❉，—。?★、…【】《》？“”‘’！[\\]^_`{|}~]+'
    r2 = '\s+'
    text = re.sub(r'[:].*?[:]', "", text)
    text = re.sub(r'[[].*?[]]', "", text)  # 过滤两种表情符号
    text = re.sub(r1, ' ', text)
    text = re.sub(r2, ' ', text)
    return text

def emoji_fliter(text):
    # 筛出emoji
    p1 = re.compile(r'[:].*?[:]', re.S)
    p2 = re.compile(r'[[].*?[]]', re.S)
    emoji_list1 = re.findall(p1, text)
    emoji_list2 = re.findall(p2, text)
    emoji_list = emoji_list1 + emoji_list2
    return ','.join(emoji_list)

def repost_clean(df):
    # 筛去无价值转发
    for i in tqdm(range(len(df) - 1)):
        origin_text = df.loc[i, "text"]
        if str(origin_text) != "nan" or "" or None or ' ':
            origin_text_list = list(origin_text)
            if origin_text_list[0] == '【':
                df.loc[i, "text"] = '1145141919810'
        else:
            continue
    return df

def df_clean(df, column):
    print("cleaning text……")
    for i in tqdm(range(len(df))):
        origin_text = df.loc[i, column]
        if str(origin_text) != "nan" or "" or None:
            df.loc[i, column] = basic_clean(origin_text)
        else:
            continue
    return df

def df_clean_nan(df):
    print("cleaning NAN data……")
    df["text"] = df["text"].fillna('1145141919810')
    for i in tqdm(range(len(df))):
        origin_text = df.loc[i, 'text']
        if str(origin_text) == ' ':
            df.loc[i, 'text'] ='1145141919810'
    empty_list = df[(df.text == '1145141919810')].index.tolist()
    df = df.drop(empty_list)
    return df

def clean_dataframe_generate(df):
    for i in tqdm(range(len(df))):
        origin_text = df.loc[i, "text"]
        if str(origin_text) != "nan" or "" or None:
            df.loc[i, "chinese_only_text"] = chinese_fliter(origin_text)
            df.loc[i, "emoji"] = emoji_fliter(origin_text)
        else:
            continue
    return df

def emoji_sum_up(df):
    emoji_list_all=[]
    sum=0
    for i in range(len(df)):
        emoji_set=str(df.loc[i,'emoji'])
        if emoji_set!='' and emoji_set!=' 'and emoji_set!='nan':
            emoji_list=emoji_set.split(",")
            sum = sum+1
            for emojis in emoji_list:
                if emojis not in emoji_list_all:
                    emoji_list_all.append(emojis)
        else:continue
    print(emoji_list_all)
    print(len(emoji_list_all))
    print(sum)
    file=open('C:/Users/surface/Desktop/final project/codes/the whole process/DICS/emoji_full_dic.txt','w',encoding="UTF-8")
    for emojis in emoji_list_all:
        file.write(str(emojis))
        file.write(",")
        file.write(emoji.emojize(emojis))
        file.write("\n")
    file.close()

if __name__ == "__main__":
    # csvfile="C:/Users/surface/Desktop/final project/codes/the whole process/normal_labled_origin.csv"
    # df=read_csv(csvfile)
    # text_clean_df=df_clean(df,"text")
    # text_clean_df.to_csv("normal_text_cleaned.csv")
    # df2 = read_csv("C:/Users/surface/Desktop/final project/codes/the whole process/normal_text_cleaned.csv")
    # df3=clean_dataframe_generate(df2)
    # df3=repost_clean(df3)
    # df3=df_clean_nan(df3)
    # df3.to_csv("normal_1.csv")

    # csvfile="C:/Users/surface/Desktop/final project/codes/the whole process/depressed.csv"
    # df = pd.read_csv(csvfile)
    # unique_id_list = df['id'].unique()
    # for i in range(len(unique_id_list)):
    # df.ix[(df.id == unique_id_list[i]),'id']=i+738
    # for i in tqdm(range(len(df))):
    # df.loc[i, "depressed"] = '1'
    # print(df)
    # df.to_csv("C:/Users/surface/Desktop/final project/codes/the whole process/depressed_used.csv")

    csvfile = "C:/Users/surface/Desktop/final project/codes/the whole process/data_using/normal_labeled.csv"
    df=pd.read_csv(csvfile)
    df=df_clean_nan(df)
    df.drop('Unnamed: 0',axis=1, inplace=True)
    print(df)
    df.to_csv("C:/Users/surface/Desktop/final project/codes/the whole process/data_using/normal_labeled_1.csv")


import argparse
import pathlib
import os
from PyPDF2 import PdfFileWriter, PdfFileReader
from pathlib import Path

class Config:
    def __init__(self, input, split, output):
        self.input = input
        self.split = split
        self.output = output

        if output is None:
            self.output = Path((os.path.basename(input))).with_suffix('')

def getConfig():
    parser = argparse.ArgumentParser(description="PDF Splitter")

    parser.add_argument("input", help="Input file name", type=pathlib.Path)
    parser.add_argument("split", help="Pages to split", action="extend", nargs="+", type=int)
    parser.add_argument("-o", "--output", help="Output file name")
    parser.add_argument('--version', action='version', version='PDF Splitter 1.0')

    arguments = parser.parse_args()

    return Config(arguments.input, arguments.split, arguments.output)

def split(configuration):
    inputPdf = PdfFileReader(open(configuration.input, "rb"))

    page = 1

    for splitPage in configuration.split:
        splitPdf(inputPdf, configuration.output, page, splitPage)

        page = splitPage + 1

    if page <= inputPdf.numPages:
        splitPdf(inputPdf, configuration.output, page, inputPdf.numPages)

def splitPdf(inputPdf, output, start, end):
    page = start

    print(start, end)

    if start > inputPdf.numPages or end > inputPdf.numPages:
        raise Exception(f"Tried splitting pdf on page {start} until {end} but it only contains {inputPdf.numPages} pages!")

    outputPdf = PdfFileWriter()

    while page <= end:
        outputPdf.addPage(inputPdf.getPage(page - 1))
        page += 1

    with open(f"{configuration.output}({start}-{end}).pdf", "wb") as outputStream:
        outputPdf.write(outputStream)

if __name__ == '__main__':
    configuration = getConfig();

    split(configuration);


class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        indexs = {}
        for i,v in enumerate(nums1):
            indexs[v]= i

        ans = [-1 for x in range(len(nums1))]
        stack = []
        for num in nums2:
            while stack and stack[-1] < num:
                vl = stack.pop()
                if vl in indexs:
                    ans[indexs[vl]] = num
            stack.append(num)
        return ans


import timeit

print(timeit.timeit('x = 2 + 2'))
# 0.0158134

print(timeit.timeit('x = sum(range(10))'))
# 0.5026959

'''Запустим модуль timeit в терминале'''
# python -m timeit -n 100 -s "import test_timeit"
# -n количество запуска кода, в нашем случае это 100 раз
# 100 loops, best of 5: 9 nsec per loop

import cProfile

def get_len(array):
    return len(array)

def get_sum(array):
    s = 0
    for i in array:
        s += i
    return s

def main():
    lst = [i for i in range(10000000)]
    a = get_len(lst)
    b = get_sum(lst)

cProfile.run('main()')
'''
         8 function calls in 1.877 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 test_timeit.py:19(get_len)
        1    0.907    0.907    0.907    0.907 test_timeit.py:23(get_sum)
        1    0.000    0.000    1.763    1.763 test_timeit.py:30(main)
        1    0.856    0.856    0.856    0.856 test_timeit.py:31(<listcomp>)
        1    0.114    0.114    1.877    1.877 <string>:1(<module>)
        1    0.000    0.000    1.877    1.877 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {built-in method builtins.len}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

'''
# 8 function calls in 1.877 seconds - Количество вывзванных функций за время
# ncalls - Количество вывзовов каждой строки
# tottime - Время выполнения данной строки
# percall - Время выполнения в процентах для одной строки
# cumtime - Время выполнения одной строки и например, функций, которые запускаются в этой строке
# percall - Время выполнения в процентах для cumtime
# filename:lineno(function) - Указание на строки, которые были проанализированы


from __future__ import annotations
from disnake.ext import commands
from disnake import ApplicationCommandInteraction, RawReactionActionEvent, Message, Member
from utils.player import Player
from utils.approvals import Approval
from utils.characters import CharacterChooseView, Character
from utils.help import Menu
from config import ENTRY_POINTS, APPROVAL_REACTION, DENIAL_REACTION, DEFAULT_PC_AVATAR
from typing import List

# TODO add variants and familiars
class CharacterCommands(commands.Cog, name='Character Commands'):

    def __init__(self, bot):
        self.bot = bot

    def get_player_characters(self, author: Member) -> (Player, List[Character]):
        me: Player = [player for player in self.bot.players if player.member.id == author.id][0]
        characters = [character for character in me.characters if character.approved]
        return me, characters

    def decode_footer(self, msg: Message) -> (str, Member):
        name = msg.embeds[0].footer.text.split("|")[0]
        approvee = msg.guild.get_member(int(msg.embeds[0].footer.text.split("|")[1]))
        return name, approvee

    @commands.slash_command()
    async def character(self, inter: ApplicationCommandInteraction):
        """ Commands dealing with player characters"""
        # this check is for the message listener to make sure the same person responds
        self.m_check = lambda m: inter.author == m.author
        pass

    # TODO: Add a check for a limit on characters? We haven't decided yet I guess,
    #  for now i just added a character count on the approval

    @character.sub_command()
    async def add(
            self,
            inter: ApplicationCommandInteraction,
            entry_point: ENTRY_POINTS,
            name: str,
            backstory: str,
            prefix: str,
            avatar: str = DEFAULT_PC_AVATAR):
        """ Command to register a new Player Character

        Parameters
        ----------
        inter: message interaction
        entry_point: The point where you will start your RP, depends on your backstory
        name: Full name of your character
        backstory: Your tragic backstory
        prefix: this is what you will use to talk as your character, Tupperbox style.
        avatar: URL to an image you want to use as the player avatar
        """
        # Get the player object from the cache
        me = [player for player in self.bot.players if player.member.id == inter.author.id][0]
        entry_point = inter.guild.get_role(int(entry_point))

        # Make a character object and add it to the player object
        new_char = Character(player=me,
                             name=name.title(),
                             backstory=backstory,
                             avatar=avatar,
                             prefix=prefix.rstrip(":"),
                             location=entry_point,
                             )
        me.add_character(new_char)

        # Create a new approval and save it to the queue
        new_approval = Approval(character=new_char)
        self.bot.pending_approvals.append(new_approval)

        # sends confirmation to the player and approval embed to the approval channel
        await inter.send(embeds=new_approval.embed, ephemeral=True)
        await inter.bot.APPROVAL_CHANNEL.send(embeds=new_approval.embed)

    @character.sub_command()
    async def list(self, inter: ApplicationCommandInteraction):
        """ List all of your approved characters"""
        e = []

        me, characters = self.get_player_characters(inter.author)

        if not characters:
            await inter.send("**You currently have no characters use `/character add` or wait for an approval. "
                             "Characters take 1 minute from approvals to be ready**", ephemeral=True)
            return
        # pull all the embeds from each character and send them back
        for character in characters:
            e.append(character.embed) if character.approved else 0
        e[0].set_footer(text=f"Kerna - Path of the Wicked | Page 1 of {len(e)}")
        await inter.send(embed=e[0], view=Menu(e), ephemeral=True)

    @character.sub_command()
    async def edit(self,
                   inter: ApplicationCommandInteraction):
        """ Edit a part of your approved character """
        # get a list of your characters
        me, characters = self.get_player_characters(inter.author)
        if not characters:
            await inter.send("**You currently have no characters use `/character add` or wait for an approval. "
                             "Characters take 1 minute from approvals to be ready**", ephemeral=True)
            return

        # calls the View to display the selections
        view = CharacterChooseView(characters, "edit")
        await inter.send(content="Character Editor", view=view, ephemeral=True)
        await view.wait()

        # awaits for the new values
        msg: Message = await self.bot.wait_for('message', check=self.m_check)
        await msg.delete()

        # makes the changes
        view.character.update(view.attribute, msg.content)

        await inter.edit_original_message(view=None, embeds=[view.character.embed])
        await inter.bot.CHANGE_LOG_CHANNEL.send(content=f'`{view.character.name}` changed `{view.attribute}` to `{msg.content}`')

    @character.sub_command()
    async def delete(self, inter: ApplicationCommandInteraction):
        """ Delete a character """
        # get a list of your characters
        me, characters = self.get_player_characters(inter.author)

        if not characters:
            await inter.send("**You currently have no characters use `/character add` or wait for an approval. "
                             "Characters take 1 minute from approvals to be ready**", ephemeral=True)
            return

        # calls the View to display the selections
        view = CharacterChooseView(characters, "delete")
        await inter.send(content="Delete a Character", view=view, ephemeral=True)
        await view.wait()

        # makes the changes, moves character to delete queue and removes that location
        self.bot.character_delete_queue.append(me.delete_character(view.character))
        if view.character.location not in [character.location for character in me.characters]:
            await me.member.remove_roles(view.character.location)
        await inter.edit_original_message(content=f'`{view.character.name}` has been deleted!', view=None)
        await inter.bot.CHANGE_LOG_CHANNEL.send(content=f'`{view.character.name}` has been deleted')

    @commands.Cog.listener()
    async def on_raw_reaction_add(self, payload: RawReactionActionEvent):
        """ Listens for a thumbs up in the #approvals channel,
        adds their starting role and removes the new player role """
        # checks to make sure that only thumbs up or down in the correct channel
        if payload.channel_id == self.bot.APPROVAL_CHANNEL.id and payload.emoji in [APPROVAL_REACTION, DENIAL_REACTION]:
            msg: Message = self.bot.get_message(payload.message_id)

            # the approvee is the Member who submitted for approval
            name, approvee = self.decode_footer(msg)
            me, _ = self.get_player_characters(approvee)

            # pulls the approval from the queue
            approval: Approval = [approval for approval in self.bot.pending_approvals if approval.character.player.member == approvee][0]

            approval.process_approval(payload)

            # remove it from the queue
            self.bot.pending_approvals.pop(self.bot.pending_approvals.index(approval))

            if approval.approved:
                await approval.character.player.member.add_roles(approval.character.location)
                await approval.character.player.member.remove_roles(self.bot.NEW_PLAYER_ROLE)
            else:
                self.bot.character_delete_queue.append(approval.character)
                for index, character in enumerate(me.characters):
                    if character.id == approval.character.id:
                        me.characters.pop(index)
                        break
            await msg.edit(embeds=approval.embed)
            await payload.member.guild.system_channel.send(content=f'{approval.character.player.member.mention} Your character was {"Approved" if approval.approved else "Denied"}')

def setup(bot):
    bot.add_cog(CharacterCommands(bot))


from flask_restful import reqparse, Resource
from application.common.util import abort_if_doesnt_exist

mates = {
    'patrick@epitech.eu': {'last_name': '...' , 'first_name': '...' , 'school': 'EPITECH'},
    'viken@epitech.eu': {'last_name': '...' , 'first_name': '...' , 'school': 'EPITECH'},
    'benoit@epitech.eu': {'last_name': '...' , 'first_name': '...' , 'school': 'emlyon'},
    'jean@epitech.eu': {'last_name': '...' , 'first_name': '...' , 'school': 'emlyon'}
}

parser = reqparse.RequestParser()
parser.add_argument('login')
parser.add_argument('last_name')
parser.add_argument('first_name')
parser.add_argument('school')

class TeamMateList(Resource):
    def get(self):
        return mates

    def post(self):
        args = parser.parse_args()
        new_mate = {
            'last_name': args['last_name'],
            'first_name': args['first_name'],
            'school': args['school']
        }
        mates[args['login']] = new_mate
        return new_mate


import numpy as np
from sklearn.preprocessing import normalize

def normalize_args(X, axis=0):
    mx = np.amax(X, axis=axis)
    mn = np.amin(X, axis=axis)
    rg = mx - mn
    rg[rg == 0] = 1.0
    return mx, mn, rg

def normalize(X, mx=None, mn=None, rg=None, axis=0):
    if mx is None or mn is None or rg is None:
        mx, mn, rg = normalize_args(X, axis=axis)

    return (X - mn) / rg


import asyncio
import os
import tomli
from pyrogram.client import Client
from caligo.core import database

def load_config(filename: str) -> dict:
    # Check if the file exists and is readable
    if os.path.isfile(filename) and os.access(filename, os.R_OK):
        # Load the configuration from the file in binary mode
        with open(filename, "rb") as config_file:
            config = tomli.load(config_file)
    else:
        # Return an empty dictionary if the file is not found or not readable
        config = {}
    return config

# Define a function to get a value from the configuration or return None
def get_config_value(config: dict, section: str, key: str) -> str:
    # Try to get the value from the configuration dictionary
    value = config.get(section, {}).get(key)
    # Return the value or None if not found or empty
    return value or None

async def create_session() -> None:
    # Load the configuration from config.toml
    config = load_config("config.toml")

    # Get the values for api_id, api_hash, and mongodb_uri from the configuration or return None
    api_id = get_config_value(config, "telegram", "api_id")
    api_hash = get_config_value(config, "telegram", "api_hash")
    mongodb_uri = get_config_value(config, "bot", "db_uri")

    # Prompt the user for input only if the value is None
    if api_id is None:
        api_id = input("Please enter Telegram API ID: ")
    if api_hash is None:
        api_hash = input("Please enter Telegram API HASH: ")
    if mongodb_uri is None:
        mongodb_uri = input("Please enter MongoDB URI: ")

    # Create a Pyrogram client with the given parameters
    client = Client(
        api_id=api_id,
        api_hash=api_hash,
        name="caligo",
        workdir="caligo",
    )

    # Create a MongoDB client with the given URI and connect lazily
    db_client = database.AsyncClient(mongodb_uri, connect=False)

    # Get the CALIGO database from the MongoDB client
    db = db_client.get_database("CALIGO")

    # Set the persistent storage for the Pyrogram client using the database
    client.storage = database.storage.PersistentStorage(db)  # type: ignore

    print("Generating session...")

    # Start and stop the Pyrogram client to generate a session file
    await client.start()
    print("Session generated successfully!")
    await client.stop()

    # Close the MongoDB client connection
    await db_client.close()

if __name__ == "__main__":
    asyncio.run(create_session())


#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
import sys
import ftrobopy  # Import the ftrobopy module
import time
from TouchStyle import *

class FtcGuiApplication(TouchApplication):
    def __init__(self, args):
        TouchApplication.__init__(self, args)

        # create the empty main window
        w = TouchWindow("Pneumatic Grabber")

        txt_ip = os.environ.get('TXT_IP')  # try to read TXT_IP environment variable
        if txt_ip is None: txt_ip = "localhost"  # use localhost otherwise
        try:
            self.txt = ftrobopy.ftrobopy(txt_ip, 65000)  # try to connect to IO server
        except:
            self.txt = None

        vbox = QVBoxLayout()

        if not self.txt:
            # display error of TXT could no be connected
            # error messages is centered and may span
            # over several lines
            err_msg = QLabel("Error connecting IO server")  # create the error message label
            err_msg.setWordWrap(True)  # allow it to wrap over several lines
            err_msg.setAlignment(Qt.AlignCenter)  # center it horizontally
            vbox.addWidget(err_msg)  # attach it to the main output area
        else:
            # initialization went fine. So the main gui
            # is being drawn
            self.grab_button = QPushButton("Grab")  # create a button labeled "Toggle O1"
            self.grab_button.clicked.connect(self.on_grab_button_clicked)  # connect button to event handler
            # self.grab_button.setEnabled(False)
            vbox.addWidget(self.grab_button)  # attach it to the main output area

            # configure all TXT outputs to normal mode
            output_config = [self.txt.C_OUTPUT, self.txt.C_OUTPUT, self.txt.C_OUTPUT, self.txt.C_OUTPUT]
            input_config = [(self.txt.C_SWITCH, self.txt.C_DIGITAL),
                            (self.txt.C_SWITCH, self.txt.C_DIGITAL),
                            (self.txt.C_SWITCH, self.txt.C_DIGITAL),
                            (self.txt.C_SWITCH, self.txt.C_DIGITAL),
                            (self.txt.C_SWITCH, self.txt.C_DIGITAL),
                            (self.txt.C_SWITCH, self.txt.C_DIGITAL),
                            (self.txt.C_SWITCH, self.txt.C_DIGITAL),
                            (self.txt.C_SWITCH, self.txt.C_DIGITAL)]
            self.txt.setConfig(output_config, input_config)
            self.txt.updateConfig()
            self.motor_x = self.txt.motor(1)
            self.input_x = self.txt.input(1)
            self.pos_x = 0
            self.motor_z = self.txt.motor(2)
            self.input_z = self.txt.input(2)
            self.pos_z = 0

            self.valve_open = self.txt.output(7)
            self.valve_closed = self.txt.output(5)

            self.init_timer = QTimer(self)
            self.init_timer.timeout.connect(self.on_init_timer)
            self.init_timer.setSingleShot(True)
            self.init_timer.start(100)

        w.centralWidget.setLayout(vbox)
        w.show()
        self.exec_()

    # an event handler for our button (called a "slot" in qt)
    # it will be called whenever the user clicks the button
    def on_grab_button_clicked(self):
        for x in range(10):
            self.move_to_pos(0, 1175)
            self.toggle_grabber(True)
            self.move_to_pos(0, 1000)
            self.move_to_pos(1000, 100, 280, 512)
            self.move_to_pos(1000, 300)
            self.toggle_grabber(False)
            self.move_to_pos(1000, 100)

    def move_to_pos_x(self, position):
        self.move_to_pos(position, self.pos_z)

    def move_to_pos_z(self, position):
        self.move_to_pos(self.pos_x, position)

    def move_to_pos(self, target_pos_x, target_pos_z, speed_x=512, speed_z=512):
        distance_x = target_pos_x - self.pos_x
        distance_z = target_pos_z - self.pos_z
        # toggle the speed if going back
        if distance_x < 0:
            distance_x = -distance_x
            speed_x = -speed_x
        if distance_z < 0:
            distance_z = -distance_z
            speed_z = -speed_z
        if distance_x != 0:
            self.motor_x.setDistance(distance_x)
            self.motor_x.setSpeed(-speed_x)
        if distance_z != 0:
            self.motor_z.setDistance(distance_z)
            self.motor_z.setSpeed(-speed_z)

        motor_x_done = False
        motor_z_done = False
        while True:
            if not motor_x_done:
                # reset the position if it hits the input.
                input_hit = False
                if self.pos_x != 0 and self.input_x.state():
                    print("Reinitialized motor x")
                    input_hit = True
                    target_pos_x = 0
                if self.motor_x.finished() or input_hit:
                    self.motor_x.stop()
                    motor_x_done = True
            if not motor_z_done:
                # reset the position if it hits the input.
                input_hit = False
                if self.pos_z != 0 and self.input_z.state():
                    print("Reinitialized motor z")
                    input_hit = True
                    target_pos_z = 0
                if self.motor_z.finished() or input_hit:
                    self.motor_z.stop()
                    motor_z_done = True

            if motor_x_done and motor_z_done:
                break

        self.pos_x = target_pos_x
        self.pos_z = target_pos_z
        print("Moved to (x,z): (" + str(self.pos_x) + "," + str(self.pos_z) + ")")

    def on_init_timer(self):
        self.grab_button.setEnabled(False)
        self.toggle_grabber(False)

        self.motor_x.setSpeed(512)
        self.motor_z.setSpeed(512)
        x_done = False
        z_done = False

        while True:
            if not x_done and self.input_x.state():
                self.motor_x.stop()
                self.pos_x = 0
                print("Motor x initialized.")
                x_done = True

            if not z_done and self.input_z.state():
                self.motor_z.stop()
                self.pos_z = 0
                print("Motor z initialized.")
                z_done = True

            if x_done and z_done:
                break

        print("Model initialized.")
        self.grab_button.setEnabled(True)

    def toggle_grabber(self, grab):
        if grab:
            print("Closing grabber")
            valve_on = self.valve_closed
            valve_off = self.valve_open
        else:
            print("Opening grabber")
            valve_on = self.valve_open
            valve_off = self.valve_closed

        valve_on.setLevel(512)
        valve_off.setLevel(0)
        time.sleep(1.0)

if __name__ == "__main__":
    FtcGuiApplication(sys.argv)


import pygame
import random
import constants as c
from bullet import Bullet
import enemy_spawner

class Enemy2(pygame.sprite.Sprite):
    def __init__(self):
        super(Enemy2, self).__init__()
        self.img_explosion_01 = pygame.image.load('images\explosion_01.png').convert_alpha()
        self.img_explosion_02 = pygame.image.load('images\explosion_02.png').convert_alpha()
        self.img_explosion_03 = pygame.image.load('images\explosion_03.png').convert_alpha()
        self.img_explosion_04 = pygame.image.load('images\explosion_04.png').convert_alpha()
        self.img_explosion_05 = pygame.image.load('images\explosion_05.png').convert_alpha()

        self.anim_explosion = [self.img_explosion_01,
                               self.img_explosion_02,
                               self.img_explosion_03,
                               self.img_explosion_04,
                               self.img_explosion_05]

        self.anim_index = 0
        self.frame_length_max = 8
        self.frame_length = self.frame_length_max
        self.image = pygame.image.load('images\enemy2.png').convert_alpha()
        self.image = pygame.transform.scale(self.image, (int(self.image.get_width() / 9), int(self.image.get_height() / 9)))
        self.is_destroyed = False
        self.is_invincible = False

        self.rect = self.image.get_rect()
        self.rect.x = random.randrange(0, c.display_width - self.rect.width)
        self.rect.y = -self.rect.height
        self.snd_hit = pygame.mixer.Sound('sounds\sound_bullet_hit.ogg')
        self.hp = 3
        self.bullets = pygame.sprite.Group()
        self.bullet_timer_max = 60
        self.bullet_timer = self.bullet_timer_max
        self.states = {'fly_down': 'fly_down',
                       'attack': 'attack'}
        self.state = self.states['fly_down']
        self.init_state = True
        self.score_value = 5
        self.velocity_x = 0
        self.velocity_y = random.randrange(3, 4)

    def update(self):
        self.bullets.update()
        if self.state == 'fly_down':
            self.state_fly_down()
        elif self.state == 'attack':
            self.state_attack()
        self.rect.x += self.velocity_x
        self.rect.y += self.velocity_y

        if self.is_destroyed:
            max_index = len(self.anim_explosion) - 1
            if self.frame_length == 0:
                self.anim_index += 1
                if self.anim_index > max_index:
                    self.kill()
                    enemy_spawner.EnemySpawner().enemies.remove([1])
                else:
                    self.image = self.anim_explosion[self.anim_index]
                    self.frame_length = self.frame_length_max
            else:
                self.frame_length -= 1

    def state_fly_down(self):
        if self.init_state:
            self.init_state = False
        if self.rect.y >= 200:
            self.state = self.states['attack']
            self.init_state = True

    def state_attack(self):
        if self.init_state:
            self.velocity_y = 0
            while self.velocity_x == 0:
                self.velocity_x = random.randrange(-4, 4)
            self.init_state = False
        if self.bullet_timer == 0:
            self.shoot()
            self.bullet_timer = self.bullet_timer_max
        else:
            self.bullet_timer -= 1
        if self.rect.x <= 0:
            self.velocity_x *= -1
        elif self.rect.x + self.rect.width >= c.display_width:
            self.velocity_x *= -1

    def shoot(self):
        new_bullet = Bullet()
        new_bullet.velocity_y = 4
        new_bullet.rect.x = self.rect.x + (self.rect.width // 2)
        new_bullet.rect.y = self.rect.y + self.rect.height
        self.bullets.add(new_bullet)

    def get_hit(self):
        if not self.is_invincible:
            self.snd_hit.play()
            self.hp -=1

            if self.hp <= 0:
                self.is_invincible = True
                self.is_destroyed = True
                self.velocity_x = 0
                self.velocity_y = 0
                self.rect.x = self.rect.x - 30
                self.rect.y = self.rect.y - 44
                self.image = self.anim_explosion[self.anim_index]
        else:
            pass


#Código para controlar via puerto serie al Monocromador desarrollado en la cátedra de
# física experimental II de la facultad de ciencias exactas y naturales - UNCuyo por:
#            M. J. V. Ventura,
#            M. Galarza Martinez,
#            L. A. Merenda,
#            G. Portillo,
#            M. Chiarpotti,
#            F. Parizek,
#            D. Illesca,
#            N. Bizzotto.

########################################################################################################################
#Importamos la librerías necesarias y algunas funciones a utilizar.

import serial   #para comunicación serial con arduino
import os       #para control visual desde la consola
import time

def mover(pos,steps_taken):
    #Esta función toma la posición a la que debe moverse y calcula cuantos pasos tiene
    #que hacer el motor en función de la posición actual. Luego escribe en el puerto serie
    #la cantidad de pasos que tiene que hacer el motor y devuelve la posición actual del motor.
    os.system('clear')
    n_step_to_take = str(pos - steps_taken)  # pasos a dar desde la posición actual del motor
    arduino_port.write(n_step_to_take.encode()) #enviamos al puerto serie los pasos a dar
    print(f"Pasos a dar: {n_step_to_take}")
    time.sleep(0.5)
    print(f"Arduino confirma que dio {arduino_port.readline()} pasos")
    steps_taken += int(n_step_to_take)  # Actualizamos la posición actual de la red
    return steps_taken

def wait():
    #Esta función espera a que el usuario del monocromador indique
    #que quiere cambiar de posición para evitar salir al menú y cambiar
    #accidentalmente de posición
    os.system('clear')
    standby = input("Moviendo red a la posición elegida...\n...\nSi desea cambiar de color, ir a modo manual  o salir ingrese \"cam\":  ")

    while standby != "cam":
        standby = input("Si desea cambiar de color, ir a modo manual  o salir ingrese \"cam\":  ")

    print("Volviendo al menú principal... \n...\n")
    time.sleep(0.2)

def retorno(steps_taken):
    #Esta función solo retorna el motor a su posición inicial.

    print("Retornando la red a su posición inicial")
    steps_taken = str(-steps_taken)
    arduino_port.write(steps_taken.encode())
    print(f"Pasos a dar: {steps_taken}")
    time.sleep(0.5)
    print(f"Arduino confirma que dio {arduino_port.read()} pasos")
################################################################################################################

#Iniciamos el programa.
print("""
######################################################################################
###                           Monocromador FCEN-UNCuyo v1.0                        ###
######################################################################################
""")

#Abrimos el puerto para comunicarnos con el arduino,

puerto = "/dev/ttyUSB0"         #Por defecto en GNU/linux, en Windows ("COM3")
velocidad = 115200              #Puede ser: 50, 75, 110, 134, 150, 200, 300, 600,
                                #1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200.
arduino_port = serial.Serial(puerto,velocidad,timeout=1)  #Abrimos el puerto finalmente

#Asegurarse que la velocidad es la misma que la configurada en el arduino
#La configuración default para bit de data, bit de paridad y bits de stop
#es la misma (8N1) por defecto tanto en la libreria serial de python como
#en el serial.begin() de arduino por lo que no es necesaria configurarlo.

#Definimos algunas variables constantes a utilizar

angle_per_step = 5.625 / 64 #ángulo por paso del motor paso a paso 28BYJ-48
n_step_taken = 0  # Iniciamos la variable para llevar cuenta de cuantos pasos se han dado desde la posición inicial.
selection = 0 #iniciamos variable auxiliar de seleccion del menu.

while selection != "Sa":
    selection = input("""\n
Seleccionar un opción del menú:\n
    1)Rojo [Ro]
    2)Naranja [Na]
    3)Amarillo [Am]
    4)Verde [Ve]
    5)Turquesa [Tu]
    6)Azul [Az1]
    7)Azul [Az2]
    8)Violeta [Vi]
    9)Control manual [Cm]
    10)Salir [Sa]
    \nOpción seleccionada:   """)

    #A cada color le va a corresponder una posición en cantidad de pasos desde la posición inicial
    if selection == "Ro":
        position = 0 #valor de prueba hay que calibrar!

        #Movemos el motor y una actualizamos la posición del motor
        n_step_taken = mover(position,n_step_taken)

        #Esperamos a que el usuario quiera otro color, modo manual o salir
        wait()

    elif selection == "Na":
        position = +15  # valor de prueba hay que calibrar!

        # Movemos el motor y una actualizamos la posición del motor
        n_step_taken = mover(position, n_step_taken)

        # Esperamos a que el usuario quiera otro color, modo manual o salir
        wait()

    elif selection == "Am":
        position = +23  # valor de prueba hay que calibrar!

        # Movemos el motor y una actualizamos la posición del motor
        n_step_taken = mover(position, n_step_taken)

        # Esperamos a que el usuario quiera otro color, modo manual o salir
        wait()

    elif selection == "Ve":
        position = +33  # valor de prueba hay que calibrar!

        # Movemos el motor y una actualizamos la posición del motor
        n_step_taken = mover(position, n_step_taken)

        # Esperamos a que el usuario quiera otro color, modo manual o salir
        wait()

    elif selection == "Tu":
        position = +43  # valor de prueba hay que calibrar!

        # Movemos el motor y una actualizamos la posición del motor
        n_step_taken = mover(position, n_step_taken)

        # Esperamos a que el usuario quiera otro color, modo manual o salir
        wait()

    elif selection == "Az1":
        position = +53  # valor de prueba hay que calibrar!

        # Movemos el motor y una actualizamos la posición del motor
        n_step_taken = mover(position, n_step_taken)

        # Esperamos a que el usuario quiera otro color, modo manual o salir
        wait()

    elif selection == "Az1":
        position = +63  # valor de prueba hay que calibrar!

        # Movemos el motor y una actualizamos la posición del motor
        n_step_taken = mover(position, n_step_taken)

        # Esperamos a que el usuario quiera otro color, modo manual o salir
        wait()

    elif selection == "Vi":
        position = +69  # valor de prueba hay que calibrar!

        # Movemos el motor y una actualizamos la posición del motor
        n_step_taken = mover(position, n_step_taken)

        # Esperamos a que el usuario quiera otro color, modo manual o salir
        wait()

    elif selection == "Cm":
        #Para el modo manual volvemos el motor a su posición inicial
        retorno(n_step_taken)
        #Y empezamos nuevamente.
        n_step_taken = 0 #la volvemos a cero

        cm = True   #variable auxiliar para control manual
        while cm != False:
            #iniciamos modo manual e ingresamos la cantidad de pasos a dar
            angle_to_take = input("\nModo Manual:\nInserte Giro Horario[+] o AntiHorario[-], y ángulo a mover (Ejemplo: \"+15\") \n ó ingrese\"[s]\" para volver al menu anterior:")
            if angle_to_take != "s":
                #Traducimos de ángulo a pasos del motor
                #Redondeamos a un numero entero de pasos porque no existen pasos intermedios
                position = round(float(angle_to_take) / angle_per_step) + n_step_taken #Angles are in degrees

                #Movemos el motor y actualizamos la posición del motor
                n_step_taken = mover(position,n_step_taken)

                #Falta stand by
                # Esperamos a que el usuario quiera otro color, modo manual o salir
                wait()

            else:
                cm = False

    elif selection == "Sa":
        #retornamos la red a su posición inicial.
        retorno(n_step_taken)
        print("\nGracias por utilizar Monocromador v1.0")
        time.sleep(1.5)

    else:
        print("Opción incorrecta o no renocida")

    #Limpiamos la pantalla cada vez que mostramos el menú
    os.system('clear')


from argparse import ArgumentParser

def run():
    args = ArgumentParser(prog="cwc",description="Character Word Cloud")
    args.add_argument("--text",type=str,help="specify file of words to build the word cloud (default: stdin)")
    args.add_argument("--regex",type=str,help="override the regular expression defining what constitutes a word")
    args.add_argument("--stopwords",type=str,help="specify file of stopwords (containing one word per line) to remove from the given text after parsing")
    args.add_argument("--imagefile",type=str,help="file the completed PNG image should be written to (default: stdout)")
    args.add_argument("--fontfile",type=str,help="path to font file you wish to use (default: DroidSansMono)")
    args.add_argument("--mask",type=str,help="mask to use for the image form")
    args.add_argument("--colormask",type=str,help="color mask to use for the image form")
    args.add_argument("--contour_width",type=int,default=0,help="if greater than 0, draw mask contour (default: 0)")
    args.add_argument("--contour_color",type=str,default="black",help="use given color as mask contour color - accepts any value from PIL.ImageColor.getcolor")
    args.add_argument("--relative_scaling",type=int,default=0,help="scaling of words by frequency (0 - 1)")
    args.add_argument("--margin",type=int,default=2,help="spacing to leave around words")
    args.add_argument("--width",type=int,default=400,help="define output image width")
    args.add_argument("--height",type=int,default=200,help="define output image height")
    args.add_argument("--color",type=str,help="use given color as coloring for the image - accepts any value from PIL.ImageColor.getcolor")
    args.add_argument("--background",type=str,default="black",help="use given color as background color for the image - accepts any value from PIL.ImageColor.getcolor")
    args.add_argument("--collocations",action="store_true",help="add collocations (bigrams) to word cloud (default: add unigrams and bigrams)")
    args.add_argument("--include_numbers",action="store_false",help="include numbers in wordcloud?")
    args.add_argument("--min_word_length",type=int,default=0,help="only include words with more than X letters")
    args.add_argument("--prefer_horizontal",type=float,default=0.9,help="ratio of times to try horizontal fitting as opposed to vertical")
    args.add_argument("--scale",type=float,default=1,help="scaling between computation and drawing")
    args.add_argument("--corlormap",type=str,default="viridis",help="matplotlib colormap name")
    args.add_argument("--mode",type=str,default="RGB",help="use RGB or RGBA for transparent background")
    args.add_argument("--max_words",type=int,default=200,help="maximum number of words")
    args.add_argument("--min_font_size",type=int,default=4,help="smallest font size to use")
    args.add_argument("--max_font_size",type=int,help="maximum font size for the largest word")
    args.add_argument("--font_step",type=int,default=1, help="step size for the font")
    args.add_argument("--random_state",type=int,help="seed for the random number generator")
    args.add_argument("--normalize_plurals",action="store_true",help="whether to remove trailing ‘s’ from words")
    args.add_argument("--repeat",action="store_false", help="whether to repeat words and phrases")
    args.add_argument("--version",help="show program's version number and exit")
    args.parse_args()

if __name__ == '__main__':
    run()


# # 위의 그래프를 예시로 삼아서 인접 리스트 방식으로 표현했습니다!
# graph = {
#     1: [2, 3, 4],
#     2: [1, 5],
#     3: [1, 6, 7],
#     4: [1, 8],
#     5: [2, 9],
#     6: [3, 10],
#     7: [3],
#     8: [4],
#     9: [5],
#     10: [6]
# }
# visited = [] # 방문한 걸 저장하기 위한 배열
# queue = [1] # 시작 노드인 1을 넣어둔다.
#
# 1. 현재 큐에서 가장 처음에 넣은 1을 빼서, visited 에 추가합니다.
# # queue -> [] visited -> [1]
#
# 2. 인접한 노드들인 [2, 3, 4] 에서 방문하지 않은 것들인 [2, 3, 4]를 queue 에 추가합니다.
# # queue -> [2, 3, 4] visited -> [1]
#
# 3. 현재 큐에서 가장 처음에 넣은 2을 빼서, visited 에 추가합니다.
# # queue -> [3, 4] visited -> [1, 2]
#
# 4. 인접한 노드들인 [1, 5] 에서 방문하지 않은 것들인 [5]를 queue 에 추가합니다.
# # queue -> [3, 4, 5] visited -> [1, 2]
#
# 5. 현재 큐에서 가장 처음에 넣은 3을 빼서, visited 에 추가합니다.
# # queue -> [4, 5] visited -> [1, 2, 3]
#
# 6. 인접한 노드들인 [1, 6, 7] 에서 방문하지 않은 것들인 [6, 7]를 queue 에 추가합니다.
# # queue -> [4, 5, 6, 7] visited -> [1, 2, 3]
#
# 7. 현재 큐에서 가장 처음에 넣은 4을 빼서, visited 에 추가합니다.
# # queue -> [5, 6, 7] visited -> [1, 2, 3, 4]
#
# 8. 인접한 노드들인 [1, 8] 에서 방문하지 않은 것들인 [8]를 queue 에 추가합니다.
# # queue -> [5, 6, 7, 8] visited -> [1, 2, 3, 4]
#
# 9. 현재 큐에서 가장 처음에 넣은 5을 빼서, visited 에 추가합니다.
# # queue -> [6, 7, 8] visited -> [1, 2, 3, 4, 5]
#
# 10. 인접한 노드들인 [2, 9] 에서 방문하지 않은 것들인 [9]를 queue 에 추가합니다.
# # queue -> [6, 7, 8, 9] visited -> [1, 2, 3, 4, 5]
#
# 11. 현재 큐에서 가장 처음에 넣은 6을 빼서, visited 에 추가합니다.
# # queue -> [7, 8, 9] visited -> [1, 2, 3, 4, 5, 6]
#
# 12. 인접한 노드들인 [3, 10] 에서 방문하지 않은 것들인 [10]를 queue 에 추가합니다.
# # queue -> [7, 8, 9, 10] visited -> [1, 2, 3, 4, 5, 6]
#
# 13. 현재 큐에서 가장 처음에 넣은 7을 빼서, visited 에 추가합니다.
# # queue -> [8, 9, 10] visited -> [1, 2, 3, 4, 5, 6, 7]
#
# 14. 인접한 노드들인 [3] 에서 방문하지 않은 것들이 없으니 추가하지 않습니다.
# # queue -> [8, 9, 10] visited -> [1, 2, 3, 4, 5, 6, 7]
#
# 15. 현재 큐에서 가장 처음에 넣은 8을 빼서, visited 에 추가합니다.
# # queue -> [9, 10] visited -> [1, 2, 3, 4, 5, 6, 7, 8]
#
# 16. 인접한 노드들인 [4] 에서 방문하지 않은 것들이 없으니 추가하지 않습니다.
# # queue -> [9, 10] visited -> [1, 2, 3, 4, 5, 6, 7, 8]
#
# 17. 현재 큐에서 가장 처음에 넣은 9을 빼서, visited 에 추가합니다.
# # queue -> [10] visited -> [1, 2, 3, 4, 5, 6, 7, 8, 9]
#
# 18. 인접한 노드들인 [5] 에서 방문하지 않은 것들이 없으니 추가하지 않습니다.
# # queue -> [10] visited -> [1, 2, 3, 4, 5, 6, 7, 8, 9]
#
# 19. 현재 큐에서 가장 처음에 넣은 10을 빼서, visited 에 추가합니다.
# # queue -> [] visited -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#
# 20. 인접한 노드들인 [6] 에서 방문하지 않은 것들이 없으니 추가하지 않습니다.
# # queue -> [] visited -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#
# 21. 현재 큐에서 꺼낼 것이 없습니다. BFS 가 끝났습니다.
#
#
# 자... 어마어마한 내용들이 있었는데요!
# 이 코드를 보면 어떤 순서대로 BFS 가 이루어지는 지 조금은 이해가 가실 것 같습니다.
# 모든 순서를 외우실 필요는 없습니다 다만! 탐색의 순서와 느낌에 대해 이해가셨으면 좋겠습니다.

# 위의 그래프를 예시로 삼아서 인접 리스트 방식으로 표현했습니다!
graph = {
    1: [2, 3, 4],
    2: [1, 5],
    3: [1, 6, 7],
    4: [1, 8],
    5: [2, 9],
    6: [3, 10],
    7: [3],
    8: [4],
    9: [5],
    10: [6]
}

# 위의 그래프를 예시로 삼아서 인접 리스트 방식으로 표현했습니다!
graph = {
    1: [2, 3, 4],
    2: [1, 5],
    3: [1, 6, 7],
    4: [1, 8],
    5: [2, 9],
    6: [3, 10],
    7: [3],
    8: [4],
    9: [5],
    10: [6]
}

def bfs_queue(adj_graph, start_node):
    queue = [start_node]
    visited = []

    while queue:
        current_node = queue.pop(0)
        visited.append(current_node)
        for adjacent_node in adj_graph[current_node]:
            if adjacent_node not in visited:
                queue.append(adjacent_node)

    return visited

print(bfs_queue(graph, 1))  # 1 이 시작노드입니다!
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 이 출력되어야 합니다!


import json
import requests
import pandas as pd
import boto3

from lxml.html import fromstring
from io import StringIO
from datetime import date

from localities import S3_BUCKET, HISTORICAL_OBS_LOC

def get_today_data():
    '''Scarps the BOM website for the current max, min and rainfall
    '''
    url =  'http://reg.bom.gov.au/nsw/observations/sydney.shtml'
    page = requests.get(url)

    # Getting page data
    tree = fromstring(page.content)
    data_date = tree.xpath('//td[@headers="tSYDNEY-datetime tSYDNEY-station-sydney-observatory-hill"]/text()')[0]
    maxT = float(tree.xpath('//td[@headers="tSYDNEY-hightmp tSYDNEY-station-sydney-observatory-hill"]/text()')[0])
    minT = float(tree.xpath('//td[@headers="tSYDNEY-lowtmp tSYDNEY-station-sydney-observatory-hill"]/text()')[0])
    rain = float(tree.xpath('//td[@headers="tSYDNEY-rainsince9am tSYDNEY-station-sydney-observatory-hill"]/text()')[0])

    # Fixing up the date as it is in day/time format
    # Not using exclusively date.today() as I do want to be careful about
    # timzone problems
    day = int(data_date.split('/')[0])
    today = date.today()
    data_date = today.replace(day=day)

    # Adding it to the historical reading
    recent_obs = pd.DataFrame({'Year':data_date.year,
                               'Month':data_date.month,
                               'Day': data_date.day,
                               'Maximum temperature (°C)':maxT,
                               'Minimum temperature (°C)':minT,
                               'Rainfall (mm)':rain},
                               index=[0])
    return recent_obs

def lambda_handler(event, context):
    # Get most recent observations for this month
    recent_obs = get_today_data()

    # Read historical data from S3
    s3 = boto3.resource('s3')
    historical_obs_loc = s3.Object(bucket_name=S3_BUCKET, key=HISTORICAL_OBS_LOC)
    historical_obs = pd.read_csv(historical_obs_loc.get()['Body'])

    # To keep this data frame up to date, we concatentate it with the most
    # recent month, then drop the earliest rows
    # (assumed more recent data is correct)
    historical_obs = pd.concat([historical_obs, recent_obs])
    historical_obs = historical_obs.drop_duplicates(['Year', 'Month', 'Day'],
                                                    keep='last')

    # Finally upload back to S3
    csv_buffer = StringIO()
    historical_obs.to_csv(csv_buffer, index=False)
    s3.Object(S3_BUCKET, HISTORICAL_OBS_LOC).put(Body=csv_buffer.getvalue())

    return {
        'statusCode': 200,
        'body': json.dumps(recent_obs.to_dict('records'))
    }

if __name__=='__main__':
    lambda_handler(None, None)


import random
from croe.conf import Conf
import requests
from requests.models import PreparedRequest
from urllib.parse import urlsplit

UA = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36"
# http 请求封装函数
def http_req(url, method='get', **kwargs):
    if kwargs.get("disable_normal"):
        # 禁用 URL 规范化处理，仅仅支持GET
        kwargs.pop("disable_normal")
        return req_disable_normal(url, method, **kwargs)

    kwargs.setdefault('verify', False)
    kwargs.setdefault('timeout', (Conf.CONNECT_TIMEOUT, Conf.READ_TIMEOUT))
    kwargs.setdefault('allow_redirects', False)

    headers = kwargs.get("headers", {})
    if headers is None:
        headers = {}

    headers.setdefault("User-Agent", UA)

    random_ip = "10.0.{}.{}".format(random.randint(1, 254), random.randint(1, 254))
    headers.setdefault("X-Real-IP", random_ip)
    headers.setdefault("X-Forwarded-For", random_ip)

    kwargs["headers"] = headers

    proxies = {
        'https': Conf.PROXY_URL,
        'http': Conf.PROXY_URL
    }

    if Conf.PROXY_URL:
        kwargs["proxies"] = proxies

    conn = getattr(requests, method)(url, **kwargs)

    return conn
# 禁用规范化URL处理
# 下面这个函数在开代理的情况下依然是没有用的
def req_disable_normal(url, method='get', **kwargs):
    headers = kwargs.get("headers", {})
    if headers is None:
        headers = {}

    headers.setdefault("User-Agent", UA)

    kwargs["headers"] = headers

    req = requests.Request(method=method, url=url, **kwargs)
    prep = req.prepare()
    prep.url = url

    proxies = {}

    if Conf.PROXY_URL:
        proxies = {
            'http': Conf.PROXY_URL,
            'https': Conf.PROXY_URL
        }

    if "#" in url:
        my_prep = MyPreparedRequest()
        my_prep.prepare(method='GET', url=url)
        my_prep.url = url
        prep = my_prep

    with requests.Session() as session:
        return session.send(prep, verify=False, proxies=proxies, allow_redirects=False,
                            timeout=(Conf.CONNECT_TIMEOUT, Conf.READ_TIMEOUT))
class MyPreparedRequest(PreparedRequest):
    def __init__(self):
        super().__init__()

    @property
    def path_url(self):
        url = []

        p = urlsplit(self.url, allow_fragments=False)

        path = p.path
        if not path:
            path = '/'

        url.append(path)

        query = p.query
        if query:
            url.append('?')
            url.append(query)

        return ''.join(url)


from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QComboBox, QTextEdit

__author__ = 'Pawel'
"""
Class that represents archieve window. It allows you to see every conversation you have
"""
class ArchieveDialog(QtWidgets.QDialog):

    def __init__(self,parent, db):
        super(ArchieveDialog, self).__init__(parent)
        self.conversation = QTextEdit(self)
        self.combo = QComboBox(self)
        self.db = db
        self.initUI()

    def initUI(self):
        self.resize(300,300)
        for key, value in self.db.items():
            self.combo.addItem(key)
        self.conversation.move(0,20)
        self.combo.move(0, 0)
        self.combo.activated[str].connect(self.onActivated)

    def onActivated(self, text):
        self.conversation.clear()
        self.conversation.append(self.db[text])


from detection import object_detection
from utils import visualization_utils as vis_util
import tensorflow as tf
import numpy as np
import cv2

#webcam capture
#cap = cv2.VideoCapture(1)

#video from disk
cap = cv2.VideoCapture('./IpfMyc2OrSs.avi')
detection = object_detection()

def convert_gray_video():
  while(True):
    ret, frame = cap.read()
    #test color to gray
    image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame', image)
    if cv2.waitKey(1) & 0xFF == ord('q'):
      cv2.destroyAllWindows()
      break
  cap.release()

def convert_object_detection():
  with detection.detection_graph.as_default():
    with tf.Session(graph=detection.detection_graph) as sess:
      while True:
        ret, frame = cap.read()
        image_np_expanded = np.expand_dims(frame, axis=0)
        image_tensor = detection.detection_graph.get_tensor_by_name('image_tensor:0')

        boxes = detection.detection_graph.get_tensor_by_name('detection_boxes:0')
        scores = detection.detection_graph.get_tensor_by_name('detection_scores:0')
        classes = detection.detection_graph.get_tensor_by_name('detection_classes:0')
        num_detections = detection.detection_graph.get_tensor_by_name('num_detections:0')

        (boxes, scores, classes, num_detections) = sess.run(
            [boxes, scores, classes, num_detections],
            feed_dict={image_tensor: image_np_expanded})

        vis_util.visualize_boxes_and_labels_on_image_array(
            frame,
            np.squeeze(boxes),
            np.squeeze(classes).astype(np.int32),
            np.squeeze(scores),
            detection.category_index,
            use_normalized_coordinates=True,
            line_thickness=8)
        cv2.imshow('frame',cv2.resize(frame,(800,600)))
        if cv2.waitKey(25) & 0xFF == ord('q'):
          cv2.destroyAllWindows()
          break

if __name__=='__main__':
  #convert_gray_video()
  convert_object_detection()


import re

'''
Solution to the following:

https://www.codewars.com/kata/51b66044bce5799a7f000003
'''

class RomanNumerals:

    def __init__(self):
        self.roman_decode = {
            "I": 1,
            "V": 5,
            "X": 10,
            "L": 50,
            "C": 100,
            "D": 500,
            "M": 1000
        }
        self.arabic_decode = {v:k for k, v in self.roman_decode.items()}
        self.subtract_handler = self.subtraction_regexes()
        self.replace_handler = self.replacement_regexes()

    def subtraction_regexes(self):
        '''Compiles regex patterns to look for that represent valid subtraction
        expressions in the roman numeral systems. Returns a dict that keys each
        pattern to its compiled regular expression.

        We use this in self.from_roman() if we need to translate one of these
        patterns into a subtraction instead of using self.roman_decode directly
        '''
        valid_subtracts = ["IV","IX","XL","XC","CD","CM"]
        subtract_handler = {}
        for char_pair in valid_subtracts:
            subtract_handler[char_pair] = re.compile(char_pair)
        return subtract_handler

    def roman_subtract(self, char_pair):
        '''returns the numerical value associated with one of the valid
        subtractions determined by the two-character sequences above.'''
        larger = char_pair[1]
        smaller = char_pair[0]
        return self.roman_decode[larger] - self.roman_decode[smaller]

    def from_roman(self, roman_num):
        total = 0
        for pair in self.subtract_handler.keys():
            rgx = self.subtract_handler[pair]
            roman_num, n_matches = re.subn(rgx,"",roman_num)
            total += self.roman_subtract(pair) * n_matches
        for char in roman_num:
            total += self.roman_decode[char]
        return total

    def replacement_regexes(self):
        '''Compiles regex patterns to find four occurences of I, X, or C
        preceded by a V, L, or D, respectively.

        This sets us up to do string replacements in self.to_roman() after
        we have decoded the arabic numeral using modular arithmetic.
        '''
        tetra_letters = [r"V?I{4}",r"L?X{4}", r"D?C{4}"]
        replace_handler = {}
        for pattern in tetra_letters:
            replace_handler[pattern] = re.compile(pattern)
        return replace_handler

    def roman_replace(self, match_str):
        '''Given a matched string with four I's, four X's, or four C's, returns
        the appropriate replacement as follows:

            IIII -> IV
            VIIII -> IX
            XXXX -> XL
            LXXXX -> XC
            CCCC -> CD
            DCCCC -> CM
        '''
        four_char = len(match_str) == 4
        if "I" in match_str:
            return "IV" if four_char else "IX"
        elif "X" in match_str:
            return "XL" if four_char else "XC"
        else:
            return "CD" if four_char else "CM"

    def to_roman(self, val):
        out = ""
        for div in sorted(self.arabic_decode.keys(), reverse = True):
            quotient = val // div
            if quotient > 0:
                out = f"{out}{self.arabic_decode[div] * quotient}"
                val = val % div
        for exp in self.replace_handler.keys():
            match_exp = re.search(self.replace_handler[exp], out)
            if match_exp:
                found_tetra = match_exp.group()
                out = out.replace(found_tetra, self.roman_replace(found_tetra))
        return out

if __name__ == "__main__":

    foo = RomanNumerals()
    ROMAN_NUMS = ["CMX", "XXI", "MMVII", "DCLXVI", "MCMLXXXIX", "M", "MCMXC"]
    ARABIC_NUMS = [910, 21, 2007, 666, 1989, 1000, 1990]
    for i, roman in enumerate(ROMAN_NUMS):
        arabic = ARABIC_NUMS[i]
        print(f"Test {i+1}")
        print("\tRoman to Arabic")
        a_val = foo.from_roman(roman)
        if a_val == arabic:
            print("\t\tR to A test passed! :D")
        else:
            print(f"\t\tExpected {arabic} from {roman}, but got {a_val}...")
        print("\tArabic to Roman")
        r_val = foo.to_roman(arabic)
        if r_val == roman:
            print("\t\tA to R test passed! :D")
        else:
            print(f"\t\tExpected {roman} from {arabic}, but got {r_val}...")


#Dependencies
import os
import csv

#Specify file path
budget_data_csv = os.path.join("Resources", "budget_data.csv")

#Initialize values for results
MonthCount=[]
Total=[]

#Open the file and specify variable to hold content
with open(budget_data_csv) as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=",")

    #skip header
    csv_header = next(csvfile)

    #read through rows of data after header (+= assignment operator -> c+=a == c=c+a)
    for rows in csv_reader:
        MonthCount.append(rows[0])

        #adds up numbers (defined as integers -> use string later in print) from Profit/Losses column starting after header(row1)
        Total.append(int(rows[1]))

    #now we need to find the average change in Profit/Losses
    change = []
    for x in range(1,len(Total)):
        change.append((int(Total[x])-int(Total[x-1])))

    #calculate average change
    change_average = sum(change)/len(change)

    #calculate total length of MonthCount variable
    total_months = len(MonthCount)

    # use python functions to calculate greatest increase and decrease in revenue
    greatest_increase = max(change)
    greatest_decrease = min(change)

    #finished gathering these data, now print results
    print("Financial Analysis")
    print("..................................................")
    print(f"Total Months: {total_months}")
    print("Total: " + "$" + str(sum(Total)))
    print("Average Change: " + "$" + str(change_average))
    print("Greatest Increase in Profits: " + str(MonthCount[change.index(max(change))+1]) + "(" + " $" + str(greatest_increase) + ")")
    print("Greatest Decrease in Profits: " + str(MonthCount[change.index(min(change))+1]) + "(" + " $" + str(greatest_decrease) + ")")

    #nice! now write to a text file
    results=open("results.txt","w")
    results.write("Financial Analysis" + "\n")
    results.write("..................................."+ "\n")
    results.write(f"Total Months: {total_months}\n")
    results.write("Total: " + "$" + str(sum(Total))+ "\n")
    results.write("Average Change: " + "$" + str(change_average)+ "\n")
    results.write("Greatest Increase in Profits: " + str(MonthCount[change.index(max(change))+1]) + "(" + " $" + str(greatest_increase) + ")"+ "\n")
    results.write("Greatest Decrease in Profits: " + str(MonthCount[change.index(min(change))+1]) + "(" + " $" + str(greatest_decrease) + ")"+ "\n")