# import pygame library
import pygame
import math
import player
import menu
import background
import projectile_temp
import threading
import projectile2
import weapon
import enemy_holder

# initializing pygame
pygame.init()

print(str(pygame.mixer.get_num_channels()))
# Color definitions
BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)
GREEN    = (   0, 255,   0)
RED      = ( 255,   0,   0)
BLUE     = (   0,   0, 255)

#defins max ups
GAME_UPS = 60

#difficulty enhancer
diff = 400 #10 = hard 10000 = casual

#player move speed
PLAYER_VEL = 10

# creating the window
size = (600, 800)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("PySho!")

# music loader
#menu_music = pygame.mixer.music.load("Assets/Music/main_menu.mp3")
pygame.mixer.music.load("Assets/Music/main_menu.mp3")
#game_session_music = pygame.mixer.music.load("Assets/Music/gmPly.mp3")
print("Music loaded!")

# soundFX loader
player_shoot_laser_sound = pygame.mixer.Sound("Assets/SoundFX/Laser_Shoot7.wav")
explosion_death_sound    = pygame.mixer.Sound("Assets/SoundFX/Explosion4.wav")
hull_damage_sound        = pygame.mixer.Sound("Assets/SoundFX/Explosion2.wav")
shield_damage_sound      = pygame.mixer.Sound("Assets/SoundFX/Hit_Hurt82.wav")
burning_death_sound      = pygame.mixer.Sound("Assets/SoundFX/Danger2.wav")
print("SoundFX loaded!")

# art loader
# ships
player_ship    = pygame.image.load("Assets/Art/player_ship.png")#.convert()
enemy_ship     = pygame.image.load("Assets/Art/enemy_ship.png")#.convert()
kamina_ship    = pygame.image.load("Assets/Art/kamina_ship.png")#.convert()
boss_ship      = pygame.image.load("Assets/Art/enemy_ship_mb0.png")#.convert()

#enemy ship arrays
enemy_ship_arr = []
enemy_ship_arr.append(enemy_ship)
enemy_ship_arr.append(kamina_ship)
enemy_ship_arr.append(boss_ship)

menu_art = []
menu_art.append(boss_ship)
menu_art.append(enemy_ship)
menu_art.append(kamina_ship)
menu_art.append(player_ship)
# shields
shield         = pygame.image.load("Assets/Art/shield_dmg_0.png")#.convert()
shield_dmg     = pygame.image.load("Assets/Art/shield_dmg_1.png")#.convert()

# projectiles
p_proj_art_arr = [] #order is player proj
e_proj_art_arr = [] #order is eproj, eproj2
p_proj_art_arr.append(pygame.image.load("Assets/Art/projectile.png"))#.convert())
e_proj_art_arr.append(pygame.image.load("Assets/Art/Eprojectile_2.png"))#.convert())
e_proj_art_arr.append(pygame.image.load("Assets/Art/Eprojectile.png"))#.convert())
print("Art loaded!")

# spawn a proj every other frame, returning 1.5 * pi ("up") when returning an angle
def mvmtPtrn1(x):
    if x % 16 == 0: # fire proj
        return (1.5 * math.pi)
    else:
        return None

proj1    = projectile2.Projectile(0, 0, 35, 1.5 * math.pi, 10, p_proj_art_arr[0])
weap1    = weapon.weapon((0,0), proj1, mvmtPtrn1, screen, size)

# object initialization

menu               = menu.menu_object(menu_art,size,screen)
player             = player.player_object(player_ship,size,screen,weap1)
starfield          = background.starfield_object(size)
enemy_hldr         = enemy_holder.enemy_holder(enemy_ship_arr,e_proj_art_arr,size,screen)

#tracks if the player is alive
player_alive = True

#tracks frames for timers
frame_counter = 0

#value to determine if the player is shooting or not
spawn_proj = False

# value to keep the program running or exit
done = False

#value to track whether a game is in session or not
running = False

#value to track whether a game is in paused or not
paused = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# counts of number of WASD/arrow keys of given direction pushed
lcount = 0
rcount = 0
ucount = 0
dcount = 0

# holds menu button positions and sizes
menu_pos = [(90,120,420,200),(175,460,250,100),(175,590,250,100)]
pygame.mixer.music.play(-1)

while not done:
    # Main event loop

    #updates the mouse position
    mouse_pos = pygame.mouse.get_pos()

    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done = True # Flag that we are done so we exit this loop
        elif event.type == pygame.KEYDOWN:
            # Figure out if it was an arrow key. If so
            # adjust speed.
            # escape to pause/unpause the game
            if event.key == pygame.K_ESCAPE:
                if not paused:
                    running = False
                    paused  = True
                    pygame.mixer.music.pause()
                else:
                    pygame.mixer.music.unpause()
                    paused = False
                    running = True
            if event.key in (pygame.K_a, pygame.K_LEFT):
                if lcount == 0:
                    player.mod_x_vel(-1*PLAYER_VEL)
                lcount += 1
            if event.key in (pygame.K_d, pygame.K_RIGHT):
                if rcount == 0:
                    player.mod_x_vel(PLAYER_VEL)
                rcount += 1
            if event.key in (pygame.K_w, pygame.K_UP):
                if ucount == 0:
                    player.mod_y_vel(-1*PLAYER_VEL)
                ucount += 1
            if event.key in (pygame.K_s, pygame.K_DOWN):
                if dcount == 0:
                    player.mod_y_vel(PLAYER_VEL)
                dcount += 1
            if event.key == pygame.K_SPACE:
                spawn_proj = True
            #print("User pressed a key.")
        elif event.type == pygame.KEYUP:
            # If it is an arrow key, reset vector back to zero
            if event.key in (pygame.K_a, pygame.K_LEFT):
                lcount -= 1
                if lcount == 0:
                    player.mod_x_vel(PLAYER_VEL)
            if event.key in (pygame.K_d, pygame.K_RIGHT):
                rcount -= 1
                if rcount == 0:
                    player.mod_x_vel(-1*PLAYER_VEL)
            if event.key in (pygame.K_w, pygame.K_UP):
                ucount -= 1
                if ucount == 0:
                    player.mod_y_vel(PLAYER_VEL)
            if event.key in (pygame.K_s, pygame.K_DOWN):
                dcount -= 1
                if dcount == 0:
                    player.mod_y_vel(-1*PLAYER_VEL)
            if event.key == pygame.K_SPACE:
                spawn_proj = False
            #print(lcount,rcount,ucount,dcount)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if not running:
                if mouse_pos[0]<426 and mouse_pos[0]>174:
                    if mouse_pos[1]<559 and mouse_pos[1]>459:
                        if paused:
                            paused = False
                            pygame.mixer.music.unpause()
                        elif player_alive:
                            pygame.mixer.music.stop()
                            pygame.mixer.music.load("Assets/Music/gmPly.mp3")
                            pygame.mixer.music.play(-1)
                        running=True;
                    elif mouse_pos[1]<689 and mouse_pos[1]>589:
                        if paused:
                            paused = False
                            player_alive = True
                            menu.set_hp(100)
                            menu.set_points(0)
                            weap1.reset()
                            player.__init__(player_ship,size,screen,weap1)
                            enemy_hldr.reset()
                            pygame.mixer.music.load("Assets/Music/main_menu.mp3")
                            pygame.mixer.music.play(-1)
                        else:
                            done= True  # Flag that we are done so we exit this loop
                        #print("User wants to leave...")
            #print("User pressed a mouse button")

    # Game logic should go here

    #update starfield background
    if not paused:
        #threading usage example. I'd like to contain the big
        starfield_t=threading.Thread(target=starfield.update)
        starfield_t.start()

    if not running:
        pass
        #call menu class and do menu things
    else:
        #call game class and do game things and update game variables and stuff

        #updates player loc
        player_t=threading.Thread(target=player.update)
        player_t.start()
        #player.update()

        # update coords for player projectile, have spawn_proj be pass to update_proj
        proj_t=threading.Thread(target=player.update_proj,args =(spawn_proj,))
        proj_t.start()
        enemy_t=threading.Thread(target=enemy_hldr.update)
        enemy_t.start()
        enemy_proj_t=threading.Thread(target=enemy_hldr.update_proj)
        enemy_proj_t.start()

    # Drawing code should go here
    # clear the screen to black. Don't put other drawing commands
    # above this, or they will be erased with this command.
    screen.fill(BLACK)

    #draw starfield background
    starfield_t.join()

    starfield.draw(screen)

    #the process of thread joining should be double checked and cleaned up
        # if not running, call pause/main menu, otherwise do game stuff
    if not running:
        if not paused:
            menu.draw_menu()
        else:
            player_t.join()
            proj_t.join()
            enemy_proj_t.join()
            enemy_t.join()

            #drawing for the pause menu
            enemy_hldr.draw_proj()
            enemy_hldr.draw()
            player.draw_proj()
            if player_alive:
                menu.draw_pause(player.get_pos())
            else:
                pygame.mixer.music.fadeout(500)
                menu.draw_game_over(player.get_pos())

    else:
        # fire weapon if space bar is held down
        # put colision detection here
        player_t.join()
        proj_t.join()
        enemy_proj_t.join()
        enemy_t.join()

        #begin the final updates and drawing
        # collision detection & update points
        points = enemy_hldr.update_coll(player.get_weapon().get_proj_pos(),player.get_weapon().get_proj_art_size())
        # print(points)
        menu.add_points(points)

        if enemy_hldr.update_proj_coll(player.get_pos()):
            menu.dec_hp()
        enemy_hldr.draw_proj()
        enemy_hldr.draw()
        player.draw_proj()
            #call game class and do game things and update game variables and stuff
        player.draw(screen)
            # adds hud
        menu.draw_hud()

        # Go ahead and update the screen with what we've drawn.
    if not menu.get_hp():
    #if not True:
        player_alive = False
        paused = True
        running = False

    pygame.display.flip()
    # --- Limit to 60 frames per second
    frame_counter = frame_counter+1
    if frame_counter >= diff :
        if running:
            enemy_hldr.update_spawn_rate()
        frame_counter = 0

    clock.tick_busy_loop(GAME_UPS)
pygame.quit()


##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to non-U.S. persons whether in the United States or abroad requires
# an export license or other authorization.
#
# Contractor Name:        Raytheon Company
# Contractor Address:     6825 Pine Street, Suite 340
#                         Mail Stop B8
#                         Omaha, NE 68106
#                         402.291.0100
#
# See the AWIPS II Master Rights File ("Master Rights File.pdf") for
# further licensing information.
##
## @file presWeather.py

from numpy import zeros
from numpy import where
from numpy import greater_equal

precipDict1 = {-9999:'RA',0:'',1:'FZRA',2:'SN',3:'RA'} # Precip type (always rain in summer)
precipDict2 = {-9999:'',0:'',1:'FZRA',2:'SN',3:'RA',4:'RASN'}
precipDict3 = {-9999:'P',0:'',1:'FZRA',2:'SN',3:'RA'}
obsStructDict1 = {-9999:'',1:'BL',2:'HZ',3:'FG',4:'',5:'BR'} # Obstruction code
obsStructDict3 = {-9999:'',1:'SS',2:'HZ',3:'FG',4:'',5:'BR'} # Obstruction code

def execute1(QPF6hr_bestCat, obVis_bestCat, precipType,tstorm6hr, severe6hr):
    "Calculate present weather."

    sixHourPlotCheck = QPF6hr_bestCat >= 0
    qpfYes = QPF6hr_bestCat >= 1

    obsTypeAtAll = zeros(obVis_bestCat.shape, dtype='|S10')
    wxTypeAtAll = zeros(precipType.shape, dtype='|S10')

    precipTransform = typeTransform(precipType, precipDict1)
    obsTransform = typeTransform(obVis_bestCat, obsStructDict1)

    tstormYes = tstorm6hr >= 20
    severeYes = severe6hr >= 10

    storms = zeros(severeYes.shape,dtype='|S10')
    storms[tstormYes] = 'TS'
    storms[severeYes] = '+TS'

    wxTypeAtAll[qpfYes] = precipTransform[qpfYes]
    obsTypeAtAll[sixHourPlotCheck] = obsTransform[sixHourPlotCheck]
    return concatArrays([obsTypeAtAll, wxTypeAtAll, storms])

def execute2(precipType, QPF12hr_bestCat, POP12hr, tstorm12hr):
    "Calculate present weather."

    qpfYes = QPF12hr_bestCat >= 1
    popYes = POP12hr >= 30

    precipTransform = typeTransform(precipType, precipDict2)

    wxType = zeros(precipType.shape, dtype='|S10')
    wxType[qpfYes] = precipTransform[qpfYes]
    wxType[popYes] = precipTransform[popYes]

    tstormYes = tstorm12hr >= 20
    storms = zeros(tstormYes.shape,dtype='|S10')
    storms[tstormYes] = 'TS'

    storms = where(greater_equal(precipType, 0), storms, '')

    return concatArrays([wxType, storms])

def execute3(obVis_bestCat, precipType, POP_hour_bestCat):
    "Calculate present weather."

    popYes = POP_hour_bestCat == 1
    obsTransform = typeTransform(obVis_bestCat, obsStructDict3)

    precipTransform = typeTransform(precipType, precipDict3)

    wxType = zeros(precipType.shape, dtype='|S10')
    wxType[popYes] = precipTransform[popYes]

    return concatArrays([wxType, obsTransform])

def typeTransform(dataArray, lookup):
    sDataArray = dataArray.astype('|S10')
    for value in lookup:
        search = dataArray == value
        sDataArray[search] = lookup[value]
    return sDataArray

def concatArrays(stringArrays, delimiter=" "):
    finalStringArray = list()
    for num in xrange(len(stringArrays)):
        flatArray = list(stringArrays[num])
        for stringLoc in xrange(len(flatArray)):
            if num == 0:
                finalStringArray.append('');
            if flatArray[stringLoc].itemsize > 0:
                if num > 0:
                    finalStringArray[stringLoc] += delimiter
                finalStringArray[stringLoc] += flatArray[stringLoc]
    return finalStringArray


import sys
import pandas as pd
import plotly.express as px
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import pandas_profiling

matplotlib.use('TkAgg')

# Config warning settings
plt.rcParams.update({'figure.max_open_warning': 0})

# Wprowadzenie danych
covid_data = pd.read_csv("./inputs/covid-variants.csv")

def analysis():
    if len(covid_data.select_dtypes("object").columns) > 0:
        print("Object Variables:", "\n",
              len(covid_data.select_dtypes("object").columns), "\n",
              covid_data.select_dtypes("object").columns.tolist(), "\n")

    if len(covid_data.select_dtypes("integer").columns) > 0:
        print("Integer Variables:", "\n",
              len(covid_data.select_dtypes("integer").columns), "\n",
              covid_data.select_dtypes("integer").columns.tolist(), "\n")

    if len(covid_data.select_dtypes("float").columns) > 0:
        print("Float Variables:", "\n",
              len(covid_data.select_dtypes("float").columns), "\n",
              covid_data.select_dtypes("float").columns.tolist(), "\n")

    if len(covid_data.select_dtypes("bool").columns) > 0:
        print("Bool Variables:", "\n",
              len(covid_data.select_dtypes("bool").columns), "\n",
              covid_data.select_dtypes("bool").columns.tolist(), "\n")

# Sprawdzenie, czy występują braki
# Sprawdzamy, czy zbiór danych nie ma zduplikowanych wierszy
def profileDataset():
    profiling = pandas_profiling.ProfileReport(covid_data)
    profiling.to_file("outputs/profiling.html")
    print(covid_data.head())

# Lista najbardziej zainfekowanych krajów (przez Covid-19)
def generateCountryInfectionTreemap():
    sample = covid_data.rename(
        columns={"location": "Kraj", "num_sequences_total": "Liczba przypadków"})
    fig = px.treemap(sample, path=[px.Constant('Liczba przypadków'), 'Kraj'],
                     values='Liczba przypadków', hover_data=['Kraj'], )
    fig.show()
    # fig.write_image('./outputs/infection_treemap.png', format='.png')

def generateMoreThanOthersDiagram():
    for virus in covid_data.variant.unique():
        dataframe = covid_data.loc[covid_data['variant'] == virus].groupby('location')[
                        'num_sequences'].agg('sum').sort_values(ascending=False)[:10]
        dataframe = pd.DataFrame(
            {'Kraj': dataframe.index, 'Liczba przypadków': dataframe.values})
        plt.figure(figsize=(8, 2), dpi=200)
        sns.barplot(y='Kraj', x="Liczba przypadków",
                    data=dataframe, palette="Blues_d")
        plt.title(
            'KRAJE, KTÓRE MAJĄ WIĘCEJ PRZYPADKÓW {} OD INNYCH WARIANTÓW'.format(virus),
            loc='center',
                  fontweight="bold")
        plt.savefig('./outputs/variants/{}.png'.format(virus))

def generateOmicronVariantWorld():
    sample = covid_data.loc[covid_data['variant'] == 'Omicron'].groupby('date')[
        'num_sequences'].agg('sum')
    dataframe = pd.DataFrame({'Data': sample.index, 'Liczba przypadków': sample.values})
    fig = px.area(dataframe, y="Liczba przypadków", x='Data')
    fig.show()
    # fig.write_image('./outputs/omicron_world.png', format='.png')

def generateOmicronVariantPoland():
    sample = covid_data.loc[covid_data['variant'] == 'Omicron'].loc[
        covid_data['location'] == 'Poland'].groupby('date')['num_sequences'].agg('sum')
    dataframe = pd.DataFrame({'Data': sample.index, 'Liczba przypadków': sample.values})
    fig = px.area(dataframe, y="Liczba przypadków", x='Data')
    fig.show()
    # fig.write_image('./outputs/omicron_poland.png', format='.png')

def progressionOfCovidVariantsDiagramWorld():
    variant_totals = covid_data.groupby([
        "variant", "date"], as_index=False).sum()
    progressionOfCovidVariantsDiagram(
        variant_totals=variant_totals, plottitle='Statystyki globalne')

def progressionOfCovidVariantsDiagramPoland():
    variant_totals = covid_data.loc[
        covid_data['location'] == 'Poland'].groupby([
        "variant", "date"],as_index=False).sum()
    progressionOfCovidVariantsDiagram(
        variant_totals=variant_totals, plottitle='Statystyki dla Polski')

def progressionOfCovidVariantsDiagram(variant_totals, plottitle):
    variant_totals["perc_sequences"] = (
            100 * variant_totals["num_sequences"] / variant_totals["num_sequences_total"]
    )

    fig = px.line(
        variant_totals,
        x="date",
        y="num_sequences",
        color="variant",
        color_discrete_sequence=px.colors.qualitative.Light24,
        custom_data=["perc_sequences"],
        markers=True,
        height=600,
        width=960,
        title="Postęp zakażeń wariantami wirusa COVID
({})".format(plottitle),
    )
    fig.update_layout(
        font_family="serif", plot_bgcolor="#fff", title_font_size=20, title_x=0.5
    )
    fig.update_traces(
        hovertemplate="%{x}: %{y} (%{customdata[0]:.2f}%)",
        marker=dict(symbol="square", size=5)
    )
    fig.update_yaxes(
        fixedrange=True, gridcolor="#ddd", tickformat=",", title="Liczba przypadków"
    )
    fig.update_xaxes(fixedrange=True, title="Data")
    fig.show()

def main():
    print("Python version")
    print(sys.version)
    # analysis()

    # # Waliduje zestawienie danych i zapisuje wynik do pliku /outputs/profiling.html
    # #######################
    # profileDataset()
    #
    # # Generowanie listy najbardziej zainfekowanych krajów (przez Covid-19)
    # # Na podstawie poniższego wykresu możemy łatwo zauważyć, że Stany Zjednoczone wraz z Wielką Brytanią
    # # stanowią czołówkę, jeżeli chodzi o liczbę przypadków zarażenia koronawirusem
    # #######################
    # generateCountryInfectionTreemap()
    #
    # generateMoreThanOthersDiagram()
    # generateOmicronVariantWorld()
    # generateOmicronVariantPoland()
    # progressionOfCovidVariantsDiagramWorld()
    # progressionOfCovidVariantsDiagramPoland()

main()

BigData i Hurtownie Danych/praca_semestralna/main.py


# %% Import package to use
import numpy as np
from numpy.lib.function_base import disp
import seaborn as sns
import datatable
import pandas as pd
from my_module import *
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from IPython.display import display
pd.set_option("display.max_columns", None)
import os
import kaplanmeier as km

# %%
DATA_PATH = '/home/lkh256/Studio/VO2max_Prediction/Data/Survival_set'
df_init = datatable.fread(os.path.join(DATA_PATH, 'MF_general_eq_survival.csv'), encoding='utf-8-sig', na_strings=['', 'NA']).to_pandas()
display(df_init.head())
# %%
#### make input variable for kaplanmeier curve
time_event = df_init['delta_time'].astype(int)
censoring = df_init['death'].astype(int)
labx = df_init['CRF_tertile']

out = km.fit(time_event, censoring, labx)

km.plot(out, cmap='Set2', cii_lines='line', cii_alpha=0.05)
plt.show()

# %%
from lifelines import datasets, CoxPHFitter
from patsy import dmatrices

df_init[['delta_time', 'death', 'sex', 'Smoke', 'ALC', 'MVPA', 'Diabetes', 'Hypertension', 'Hyperlipidemia', 'Hepatatis']] = df_init[['delta_time', 'death', 'sex', 'Smoke', 'ALC', 'MVPA', 'Diabetes', 'Hypertension', 'Hyperlipidemia', 'Hepatatis']].astype(int)

# model_expr = "delta_time ~ AGE + sex + BMI + Smoke + ALC + MVPA + Diabetes \
#     + Hypertension + Hyperlipidemia + Hepatatis + max_heart_rate \
#     + MBP + ABRP_CRF_tertile + death + delta_time"

model_expr = "delta_time ~ ABRP_CRF_tertile + death + delta_time"

y, X = dmatrices(model_expr, df_init, return_type='dataframe')

cph = CoxPHFitter().fit(X, 'delta_time', 'death')
print(cph.print_summary(style='ascii'))
#cph.plot_partial_effects_on_outcome('ABRP_CRF', values=range(0, 14, 1) , cmap='coolwarm')
plt.figure(figsize=(20, 20))
ax = cph.plot_partial_effects_on_outcome(covariates=['ABRP_CRF_tertile[T.T2]', 'ABRP_CRF_tertile[T.T3]'],
                                    values=[(1, 0), (0, 1)])
ax.plot(line_width=2)

# %%

# %%
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111)
cph = CoxPHFitter().fit(X, 'delta_time', 'death')
cph.plot_partial_effects_on_outcome(covariates=['ABRP_CRF_tertile[T.T2]', 'ABRP_CRF_tertile[T.T3]'],
                                    values=[(1, 0), (0, 1)], ax=ax)
plt.legend(['T2', 'T3', 'T1'])
plt.show()

fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111)
cph = CoxPHFitter().fit(X, 'delta_time', 'death')
cph.plot(ax=ax, hazard_ratios=True)
plt.show()
# %%
print(cph.log_likelihood_ratio_test())
# %%
cph.check_assumptions(X, show_plots=True)
# %%
cph.plot(hazard_ratios=True)
# %%


#Servidor Mutltithread
import socket
from threading import Thread

# Teste commit
#Pool
class ClientThread(Thread):

	def __init__(self, ip, port, con, jogadorID):
		Thread.__init__(self)
		self.ip = ip
		self.port = port
		self.con = con
		self.jogadorID = jogadorID
		print('[+] Jogador Conectou ', ip, ' ', port)

	def run(self):
		while True:
			try:
				msg = self.con.recv(1024)
				if not(msg): break
				text = msg.decode("utf-8")
				print(text, 'Jogador ', self.jogadorID)
				self.con.send(bytes(self.jogadorID))
			except (ConnectionResetError, BrokenPipeError):
				break
		print('[-] Jogador Desconectou' , self.ip, ' ', self.port)

#Stub
HOST = ''
PORT = 5001

tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
orig = (HOST, PORT)
tcp.bind(orig)
threads = []
contJogador = 1;

try:
    tcp.listen(4)
    print('Esperado por jogador...')
    (con, (ip,  port)) = tcp.accept()
    jogadorX = ClientThread(ip, port, con, contJogador)
    contJogador = contJogador+1
    #jogadorX.start()
    jogadorX.con.send(bytes('X','utf-8'))

    tcp.listen(4)
    print('Esperado por segundo jogador...')
    (con, (ip,  port)) = tcp.accept()
    jogadorO = ClientThread(ip, port, con, contJogador)
    contJogador = contJogador+1
    #jogadorO.start()
    jogadorO.con.send(bytes('O','utf-8'))

    while True:
        msg = jogadorX.con.recv(1024).decode("utf-8")
        jogadorO.con.send(bytes(msg,'utf-8'))
        msg = jogadorO.con.recv(1024).decode("utf-8")
        jogadorX.con.send(bytes(msg,'utf-8'))

except KeyboardInterrupt:
    tcp.close()


import cv2
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
#set image to variable
out = cv2.imread("red.png",-1)
#get height and width of original image
height,width,channels = out.shape
#reduce image size by weight and blur image
weight = 7
smaller_img = cv2.resize(out, (int(width/weight),int(height/weight)))
blurred_img = cv2.GaussianBlur(smaller_img, (3, 3), 0)
#new heights of modified image
height_2, width_2, channels_2 = blurred_img.shape
#instantiate lists to be used later for regression analysis
left_x = []
right_x = []
right_y = []
left_y = []

#find the cones and split them into right side and left side
for y in range(height_2):
    for x in range(width_2):
        g = blurred_img[y,x][1]
        b = blurred_img[y,x][0]
        r = blurred_img[y,x][2]
        if r > 150 and g < 60 and b < 60:
            if x > int(width_2/2):
                        right_x.append(x*weight)
                        right_y.append(y*weight)
            else:
                left_x.append(x*weight)
                left_y.append(y*weight)

rx = np.array(right_x)
ry = np.array(right_y)

lx = np.array(left_x)
ly = np.array(left_y)
#regression for right side
slope, intercept, r_value, p_value, std_err = stats.linregress(rx, ry)
#regression for left side
slopel, interceptl, r_valuel, p_valuel, std_errl = stats.linregress(lx, ly)

#overlay lines onto image
for h in range(height):
     for w in range(width):
        if (h <= slope * w + intercept +5) and (h >= slope * w + intercept - 5):
            out[h,w] = [225,0,0]
        if (h <= slopel * w + interceptl + 5) and (h >= slopel*w + interceptl - 5):
             out[h,w] = [225,0,0]

cv2.imwrite('answer.png', out)
cv2.imshow('image',out)
cv2.waitKey(0)
cv2.destroyAllWindows()


import sys
import PySimpleGUI as sg
from pathlib import Path
from docxtpl import DocxTemplate
import datetime

today=datetime.datetime.today()

document_path = Path(__file__).parent / "Inventory_Template.docx"
doc = DocxTemplate(document_path)

# ----------- Set the Theme -----------
sg.theme('DarkGrey5')

# ----------- Set Certain Keys for DOCXTPL -----------
context = {
    'RESIDENTIAL':'RESIDENTIAL', 'CSAM':'CSAM', 'GANG':'GANG', 'NARCOTICS':'NARCOTICS', 'MURDER':'MURDER', 'BAC':'BAC',
    'ATT':'ATT', 'VERIZON':'VERIZON', 'INFO':'INFO'
    }

# ----------- Create Different Columns for Different Warrants -----------
col1 = sg.Column([[sg.Frame('Case Identifiers:',
                            [[sg.Column([[sg.Text('What would you like to name this file?'), sg.Input(key='REF')],
                            [sg.Text('What is your assigned Case Number?'), sg.Input(key='CASE')],
                            ])]])]])

col2 = sg.Push(), sg.Column([[sg.Frame('Information:',[[sg.Text(), sg.Column([
    [sg.Text('What County are you in?')],
    [sg.Input(key='COUNTY')],
    [sg.Text('What is your Name?')],
    [sg.Input(key='NAME')],
    [sg.Text('Who do you work for?')],
    [sg.Input(key='AGENCY')],
    [sg.Text('What Date was the Warrant served? (DD/MM/YYYY)')],
    [sg.Input(key='DATE')]
    ])]])]]), sg.Push()

col0 = sg.Column([[sg.Frame('Actions:',
                            [[sg.Column([[sg.Button('Save'), sg.Exit()]])]])]])

# ----------- Create Different Windows -----------
def make_welcome():
    layout = [
    [sg.Text('Sikeston Department of Public Safety', font=('helvetica', '14'), pad=(100,10))],
    [sg.Text('Criminal Investigations Unit', font=('helvetica', '13'))],
    [sg.Image('Patch.png', pad=(50,10))],
    [sg.Text('Return and Inventory', font=('helvetica', '12'))],
    [sg.Button('Begin', font=('helvetica', '12'), pad=(10,10))],
    [sg.Text('Search Warrant Creation Tool', font=('helvetica', '12'))],
    [sg.Text('Version: 1.0', font=('helvetica', '12'))],
    [sg.Button('Exit', font=('helvetica', '12'), pad=(10,10))]]

    return sg.Window('UNCLASSIFIDED // LAW ENFORCEMENT SENSITIVE', layout, element_justification='c', finalize=True)

def make_begin():
    layout = [sg.Push(), col1, sg.Push()], [col2], [sg.Push(), col0, sg.Push()]

    return sg.Window('UNCLASSIFIDED // LAW ENFORCEMENT SENSITIVE', layout, font=('helvetica', '12'), element_padding=(5,5), finalize=True)

window1, window2, window3 = make_welcome(), None, None

# ----------- Event Loop -----------
while True:
    window, event, context = sg.read_all_windows()
    if window == window2 and event in (sg.WIN_CLOSED, 'Exit'):
        break

    if window == window1:
        if event == 'Begin':
            window1.close()
            window2 = make_begin()

    if event == "Save":
        # Add calculated fields to our dict

        context["TODAY"] = today.strftime("%m/%d/%Y")

        # Render the template, save new word document & inform user
        doc.render(context)

        output_path = Path(__file__).parent / 'Complete/' / f"{context['REF']}-SW-Inventory.docx"
#        output_path = Path(__file__).parent / f"{context['REF']}-SW-Inventory.docx"
        doc.save(output_path)
        sg.popup("File saved", f"File has been saved here: {output_path}")
        break

    if event == 'Exit':
        break

window.close()


from enum import Enum

# Entity IDs
WALL_ID = 1
FRUIT_ID = 2

# Entity Scores
FRUIT_SCORE = 1

# Action IDs
NOTHING = 0
LEFT = 1
RIGHT = 2
UP = 3
DOWN = 4

class Result(Enum):
    FAIL = "failed to act"
    NOTHING = "did nothing"
    LEFT = "moved left"
    RIGHT = "moved right"
    UP = "moved up"
    DOWN = "moved down"
    FRUIT = "ate fruit"

class Agent:
    """Agent class that interacts in the environment."""
    def __init__(self, idx=9, x=1, y=1):
        """
        Initialise the agent with fixed parameters.
        """
        self.idx = idx
        self.x, self.y = x, y
        self.score = 0

    def nothing(self, state):
        """
        Do nothing as the action taken.
        Args:
            state:

        Returns:

        """
        return [Result.NOTHING]

    def left(self, state):
        """
        Move left as the action taken.
        Args:
            state: np.array - 2D array representing game state
        Returns:
            0 if failure, 1 if success
        """
        if self.check_wall(state, LEFT):
            return [Result.FAIL]
        results = [Result.LEFT]
        self.x -= 1
        if self.check_fruit(state):
            results.append(Result.FRUIT)
            self.eat_fruit(state)
        return results

    def right(self, state):
        """
        Move right as the action taken.
        Args:
            state: np.array - 2D array representing game state

        Returns:
            0 if failure, 1 if success
        """
        if self.check_wall(state, RIGHT):
            return [Result.FAIL]
        results = [Result.RIGHT]
        self.x += 1
        if self.check_fruit(state):
            results.append(Result.FRUIT)
            self.eat_fruit(state)
        return results

    def up(self, state):
        """
        Move up as the action taken.
        Args:
            state: np.array - 2D array representing game state

        Returns:
            0 if failure, 1 if success
        """
        if self.check_wall(state, UP):
            return [Result.FAIL]
        results = [Result.UP]
        self.y -= 1
        if self.check_fruit(state):
            results.append(Result.FRUIT)
            self.eat_fruit(state)
        return results

    def down(self, state):
        """
        Move down as the action taken.
        Args:
            state: np.array - 2D array representing game state

        Returns:
            0 if failure, 1 if success
        """
        if self.check_wall(state, DOWN):
            return [Result.FAIL]
        results = [Result.DOWN]
        self.y += 1
        if self.check_fruit(state):
            results.append(Result.FRUIT)
            self.eat_fruit(state)
        return results

    def act(self, action, state):
        """
        Take the action
        Args:
            action: int - action taken by the agent
            state: np.array - 2D array representing game state

        Returns:
            string - result having taken the action
        """
        results = [Result.FAIL]
        state[self.y][self.x] = 0  # clear past position
        if action == NOTHING:
            results = self.nothing(state)
        elif action == LEFT:
            results = self.left(state)
        elif action == RIGHT:
            results = self.right(state)
        elif action == UP:
            results = self.up(state)
        elif action == DOWN:
            results = self.down(state)
        self.update_state(state)
        return ", ".join([r.value for r in results])

    def eat_fruit(self, state):
        """
        Eat fruit to obtain score of 1.
        Args:
            state: np.array - 2D array representing game state
        """
        self.score += FRUIT_SCORE

    def check_wall(self, state, action):
        """
        Check if taking an action in a given state would lead to a wall.
        Args:
            state: np.array - 2D array representing game state
            action: int - action taken by the agent

        Returns:
            True if agent would hit a wall else False
        """
        if action == LEFT:
            return state[self.y, self.x - 1] == WALL_ID
        elif action == RIGHT:
            return state[self.y, self.x + 1] == WALL_ID
        elif action == UP:
            return state[self.y - 1, self.x] == WALL_ID
        elif action == DOWN:
            return state[self.y + 1, self.x] == WALL_ID
        raise Exception(f"Action movement invalid. Expected: [1, 2, 3, 4], Given: {action}")

    def check_fruit(self, state):
        """
        Check if there exists a fruit at the agent's current position.
        Args:
            state: np.array - 2D array representing game state

        Returns:
            True if agent is on a fruit else False
        """
        return state[self.y, self.x] == FRUIT_ID

    def update_state(self, state):
        """
        Update the state with agent's identifier
        Args:
            state: np.array - 2D array representing game state
        """
        state[self.y, self.x] = self.idx


import pytest
from typer.testing import CliRunner

import main

@pytest.fixture
def runner():
    return CliRunner()

@pytest.fixture
def valid_requests():
    return [
        ('5 5\n1 2 N\nLFLFLFLFF\n3 3 E\nFFRFFRFRRF',
         'DONE\n1 3 N\n5 1 E'),
        ('5 5\n1 3 N\nRFFF\n2 3 S\nRFFF',
         'FAILED\n1 3 E\n2 3 W'),
        ('5 5\n1 3 N\nRFFF\n2 3 S\nLLFF',
         'DONE\n4 3 E\n2 5 N'),
        ('5 5\n1 3 N\nRFFFFF\n2 3 S\nLLFFFF',
         'FAILED\n5 3 E\n2 5 N'),
    ]

@pytest.fixture
def invalid_requests():
    return [
        ('abc',
         'Request is not well formatted:\nabc'),
        ('5 5\n1 2 N\nLFLFLFLFF\n3 3 E',
         'Request is not well formatted:\n5 5\n1 2 N\nLFLFLFLFF\n3 3 E'),
    ]

@pytest.fixture
def invalid_surface_coordinates():
    return [
        ('0 5\n1 2 N\nLFLFLFLFF\n3 3 E\nFFRFFRFRRF',
         'Surface coordinates are not valid: 0 5'),
        ('5 -1\n1 2 N\nLFLFLFLFF\n3 3 E\nFFRFFRFRRF',
         'Surface coordinates are not valid: 5 -1'),
    ]

@pytest.fixture
def invalid_vacuum_coordinates():
    return [
        ('5 5\n-1 2 N\nLFLFLFLFF\n3 3 E\nFFRFFRFRRF',
         'Position outside the surface limits: -1 2'),
        ('5 5\n1 -2 N\nLFLFLFLFF\n3 3 E\nFFRFFRFRRF',
         'Position outside the surface limits: 1 -2'),
        ('5 5\n10 2 N\nLFLFLFLFF\n3 3 E\nFFRFFRFRRF',
         'Position outside the surface limits: 10 2'),
        ('5 5\n1 20 N\nLFLFLFLFF\n3 3 E\nFFRFFRFRRF',
         'Position outside the surface limits: 1 20'),
        ('5 5\n1 2 N\nLFLFLFLFF\n1 2 E\nFFRFFRFRRF',
         'Position occupied by another vacuum: 1 2'),
    ]

@pytest.fixture
def invalid_cardinal_points():
    return [
        ('5 5\n1 2 Q\nLFLFLFLFF\n3 3 E\nFFRFFRFRRF',
         "'Q' is not a valid CardinalPoint"),
        ('5 5\n1 2 e\nLFLFLFLFF\n3 3 E\nFFRFFRFRRF',
         "'e' is not a valid CardinalPoint"),
    ]

@pytest.fixture
def invalid_instructions():
    return [
        ('5 5\n1 2 N\nQRQRQRQRR\n3 3 E\nFFRFFRFRRF',
         "'Q' is not a valid Instruction"),
        ('5 5\n1 2 N\nlflflflff\n3 3 E\nFFRFFRFRRF',
         "'l' is not a valid Instruction"),
    ]

def test_valid_requests(runner, valid_requests):
    for request, response in valid_requests:
        result = runner.invoke(main.app, [request])
        assert 0 == result.exit_code
        assert f'{response}\n' == result.stdout

def test_invalid_requests(runner, invalid_requests):
    for request, response in invalid_requests:
        result = runner.invoke(main.app, [request])
        assert 1 == result.exit_code
        assert f'{response}\n' == result.stdout

def test_invalid_surface_coordinates(runner, invalid_surface_coordinates):
    for request, response in invalid_surface_coordinates:
        result = runner.invoke(main.app, [request])
        assert 1 == result.exit_code
        assert f'{response}\n' == result.stdout

def test_invalid_vacuum_coordinates(runner, invalid_vacuum_coordinates):
    for request, response in invalid_vacuum_coordinates:
        result = runner.invoke(main.app, [request])
        assert 1 == result.exit_code
        assert f'{response}\n' == result.stdout

def test_invalid_cardinal_points(runner, invalid_cardinal_points):
    for request, response in invalid_cardinal_points:
        result = runner.invoke(main.app, [request])
        assert 1 == result.exit_code
        assert f'{response}\n' == result.stdout

def test_invalid_instructions(runner, invalid_instructions):
    for request, response in invalid_instructions:
        result = runner.invoke(main.app, [request])
        assert 1 == result.exit_code
        assert f'{response}\n' == result.stdout


class Solution:
    def isAnagram(self, s: str, t: str) -> bool:

        if len(s) != len(t):
            return False
        s_dict = {}
        t_dict = {}
        for char in s:
            if char not in s_dict:
                s_dict[char] = 1
            else:
                s_dict[char] += 1

        for char in t:
            if char not in t_dict:
                t_dict[char] = 1
            else:
                t_dict[char] += 1

        return True if s_dict == t_dict else False

# This solution has 0(1) space complexity since once we create our Hash MAP we arent inputing more characters. It will remain constant

# The Big O(n)


"""
ID: thanhti1
LANG: PYTHON3
TASK: ride
"""

with open('ride.in', 'r') as fin:
    line_a = fin.readline().strip()
    line_b = fin.readline().strip()

def hask(line):
    result = 1
    for j in line:
        result *= ord(j) - 64
    result %= 47
    return result

if hask(line_a) == hask(line_b):
    out='GO\n'
else:
    out='STAY\n'

with open('ride.out', 'w') as fout:
    fout.write(out)


import pandas as pd

from Components.EditableDataFrame.EditableDataFrameView import create_editable_df
from SQL.SqlControl.SqlDataSelectAndUpdateControl import SqlDataSelectAndUpdateControl
from SQL.SqlModel.SqlConnector import SqlConnector
from InputView.InputViewControl import InputViewControl
from SQL.SqlView.AddSQLTableView import AddSQLTableView
from Upload.UploadLayout import UploadLayout
import streamlit as st

class SqlToolsControl:
	def __init__(self, upload_layout: UploadLayout, key, connector=SqlConnector.conn_sql):
		self.upload_layout = upload_layout
		self.key = key
		self.connector = connector

	def create_sql_tools_panel(self):
		self._create_input_sql_tools_view()
		tab_agg, tab_df_editable = st.tabs(["Selected Table", "Excel like Table"])
		if self.table_name:
			with tab_agg:
				try:
					self.sql_table_control = SqlDataSelectAndUpdateControl(self.input_df, self.table_name)
					self.selected_table_value = self.sql_table_control.create_agg_table()
					self._create_sql_tools()
				except Exception as e:
					st.warning(e)
					self.selected_table_value = pd.DataFrame()
			with tab_df_editable:
				df = create_editable_df(self.table_name, self.upload_layout, key="editable df")

				col = st.columns(3)
				with col[0]:
					new_view_table_name = st.text_input("Enter New View Table Name",
					                                         key=f"new_view_table_name {self.key} editable table")
					create_table_db_button = st.button("Create Table DB",
					                                        key=f"create_table_db button {self.key} editable table")
					from Session.UpdateDbSession import UpdateDbSession
					st.button("Update db", key=f"update_table_db button {self.key} editable table update",
					          on_click=UpdateDbSession.Update_sql_sessionData)
					if create_table_db_button:
						try:
							df_dicts = df.to_dict()
							pd.DataFrame(df_dicts).to_sql(new_view_table_name,if_exists="replace", con=self.connector)
							st.success(f"You create new table {new_view_table_name}")
						except Exception as e:
							st.warning(e)

	def _create_sql_tools(self):
		with st.sidebar:
			self.sql_table_control.create_sql_table_tools(self.selected_table_value)

	def _create_input_sql_tools_view(self):

		self.input_view_control = InputViewControl(self.upload_layout, self.key)
		self.input_view_control.create_input_view()
		self.input_df = self.input_view_control.input_df
		self.table_name = self.input_view_control.sheet_name


import os
import argparse
from pydub import AudioSegment
from pydub.silence import split_on_silence
import speech_recognition as sr

def split_audio(file_path, target_duration=7, min_silence_len=500, silence_thresh=-32):
    audio = AudioSegment.from_wav(file_path)
    audio_chunks = split_on_silence(
        audio,
        min_silence_len=min_silence_len,
        silence_thresh=silence_thresh,
    )

    target_length = target_duration * 1000
    output_chunks = []
    temp_chunk = AudioSegment.empty()

    for chunk in audio_chunks:
        if len(temp_chunk) + len(chunk) < target_length:
            temp_chunk += chunk
        else:
            output_chunks.append(temp_chunk)
            temp_chunk = chunk

    if temp_chunk:
        output_chunks.append(temp_chunk)

    return output_chunks

def save_chunks(chunks, output_dir):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    for i, chunk in enumerate(chunks):
        output_file = os.path.join(output_dir, f"chunk_{i}.wav")
        chunk.export(output_file, format="wav")

def main():
    parser = argparse.ArgumentParser(description="Split a WAV file into shorter clips.")
    parser.add_argument("--input", required=True, help="Path to the input WAV file.")
    parser.add_argument("--output", required=True, help="Path to the output directory.")
    parser.add_argument("--duration", type=int, default=7, help="Target duration of the clips in seconds.")
    parser.add_argument("--min_silence_len", type=int, default=500, help="Minimum silence length in milliseconds.")
    parser.add_argument("--silence_thresh", type=int, default=-32, help="Silence threshold in dB.")

    args = parser.parse_args()

    input_file = args.input
    output_directory = args.output

    target_duration = args.duration
    min_silence_len = args.min_silence_len
    silence_thresh = args.silence_thresh

    audio_chunks = split_audio(input_file, target_duration, min_silence_len, silence_thresh)
    save_chunks(audio_chunks, output_directory)

if __name__ == "__main__":
    main()


from PicImageSearch import SauceNAO
from environs import Env
import os
from flask import Flask, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
import base64

# SET YOUR FOLDER
UPLOAD_FOLDER = 'anisource/img'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def saucenao_search(filename=None, link=None):
    env = Env()
    env.read_env()

    api_key = env.str("SAUCE_API")
    saucenao = SauceNAO(api_key=api_key)
    if filename:
        res = saucenao.search(f"anisource/img/{filename}")
        os.remove(f"anisource/img/{filename}")
    else:
        res = saucenao.search(link)
    try:
        est_time = res.origin['results'][0]['data']['est_time']
    except (KeyError, AttributeError):
        est_time = None

    try:
        part = res.origin['results'][0]['data']['part']
    except (KeyError, AttributeError):
        part = None

    try:
        res = res.raw[0]
    except AttributeError:
        return render_template("error.html", error="Not found")
    return render_template(
        "search_image.html",
        title=res.title,
        est_time=est_time,
        part=part,
        author=res.author,
        photo=res.thumbnail,
        similarity=res.similarity,
        url=res.url
    )

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file, text = None, None
        if 'text' in request.form:
            text = request.form['text']
        if 'fileUpload' in request.files:
            file = request.files['fileUpload']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('search_by_image',
                                    filename=filename))
        if text:
            bytes_text = base64.b64encode(text.encode("UTF-8"))
            decoded_text = bytes_text.decode("utf-8")
            return redirect(url_for('search_by_link', link=decoded_text))
    return render_template("index.html")

@app.route('/search_image/<filename>')
def search_by_image(filename):
    return saucenao_search(filename=filename)

@app.route('/search_link/<link>')
def search_by_link(link):
    bytes_text = base64.b64decode(link.encode("utf-8"))
    link = bytes_text.decode('utf-8')
    return saucenao_search(link=link)

@app.route('/about')
def show_about():
    return render_template("about.html")

@app.route('/examples')
def show_examples():
    return render_template("examples.html")

@app.errorhandler(404)
def page_not_found(e):
    # note that we set the 404 status explicitly
    return render_template('error.html', error=e), 404

if __name__ == '__main__':
    app.run()


from django import template
import inflect

register = template.Library()

p = inflect.engine()

@register.simple_tag
def number_to_words(num, capitalize=False):
    word = p.number_to_words(num)
    if capitalize:
        return word.capitalize()
    return word

@register.simple_tag
def format_duration(td, singular=False):
    result = ''

    hours = td.seconds // 60 // 60
    if hours > 0:
        hr_separator = ' hour' if not singular else '-hour'
        plural = 's' if hours > 1 and not singular else ''
        result = result + str(hours) + hr_separator + plural

    minutes = (td.seconds - hours * 3600) // 60
    if minutes > 0:
        hr_min_separator = ' and ' if hours > 0 else ''
        min_separator = ' minute' if not singular else '-minute'
        plural = 's' if minutes > 0 and not singular else ''
        result = result + hr_min_separator + str(minutes) + min_separator + plural

    return result


import pygame
import piece

nums = [0, 60, 120, 180, 240, 300, 360, 420]
horizontal = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
vertical = ['8', '7', '6', '5', '4', '3', '2', '1']

whitePawn = pygame.image.load("Images/whitePawn.png")
blackPawn = pygame.image.load("Images/blackPawn.png")
whiteBish = pygame.image.load("Images/whiteBishop.png")
blackBish = pygame.image.load("Images/blackBishop.png")
whiteKnight = pygame.image.load("Images/whiteKnight.png")
blackKnight = pygame.image.load("Images/blackKnight.png")
whiteRook = pygame.image.load("Images/whiteRook.png")
blackRook = pygame.image.load("Images/blackRook.png")
whiteQueen = pygame.image.load("Images/whiteQueen.png")
blackQueen = pygame.image.load("Images/blackQueen.png")
whiteKing = pygame.image.load("Images/whiteKing.png")
blackKing = pygame.image.load("Images/blackKing.png")

def init(screen):
    wpa = piece.Pawn(screen.blit(whitePawn, (0, 360)), whitePawn, 'w')
    wpb = piece.Pawn(screen.blit(whitePawn, (60, 360)), whitePawn, 'w')
    wpc = piece.Pawn(screen.blit(whitePawn, (120, 360)), whitePawn, 'w')
    wpd = piece.Pawn(screen.blit(whitePawn, (180, 360)), whitePawn, 'w')
    wpe = piece.Pawn(screen.blit(whitePawn, (240, 360)), whitePawn, 'w')
    wpf = piece.Pawn(screen.blit(whitePawn, (300, 360)), whitePawn, 'w')
    wpg = piece.Pawn(screen.blit(whitePawn, (360, 360)), whitePawn, 'w')
    wph = piece.Pawn(screen.blit(whitePawn, (420, 360)), whitePawn, 'w')
    bpa = piece.Pawn(screen.blit(blackPawn, (0, 60)), blackPawn, 'b')
    bpb = piece.Pawn(screen.blit(blackPawn, (60, 60)), blackPawn, 'b')
    bpc = piece.Pawn(screen.blit(blackPawn, (120, 60)), blackPawn, 'b')
    bpd = piece.Pawn(screen.blit(blackPawn, (180, 60)), blackPawn, 'b')
    bpe = piece.Pawn(screen.blit(blackPawn, (240, 60)), blackPawn, 'b')
    bpf = piece.Pawn(screen.blit(blackPawn, (300, 60)), blackPawn, 'b')
    bpg = piece.Pawn(screen.blit(blackPawn, (360, 60)), blackPawn, 'b')
    bph = piece.Pawn(screen.blit(blackPawn, (420, 60)), blackPawn, 'b')
    wk = piece.King(screen.blit(whiteKing, (240, 420)), whiteKing, 'w')
    wq = piece.Queen(screen.blit(whiteQueen, (180, 420)), whiteQueen, 'w')
    bk = piece.King(screen.blit(blackKing, (240, 0)), blackKing, 'b')
    bq = piece.Queen(screen.blit(blackQueen, (180, 0)), blackQueen, 'b')
    wra = piece.Rook(screen.blit(whiteRook, (0, 420)), whiteRook, 'w')
    wrh = piece.Rook(screen.blit(whiteRook, (420, 420)), whiteRook, 'w')
    wbc = piece.Bishop(screen.blit(whiteBish, (120, 420)), whiteBish, 'w')
    wbf = piece.Bishop(screen.blit(whiteBish, (300, 420)), whiteBish, 'w')
    wknb = piece.Knight(screen.blit(whiteKnight, (60, 420)), whiteKnight, 'w')
    wkng = piece.Knight(screen.blit(whiteKnight, (360, 420)), whiteKnight, 'w')
    bra = piece.Rook(screen.blit(blackRook, (0, 0)), blackRook, 'b')
    brh = piece.Rook(screen.blit(blackRook, (420, 0)), blackRook, 'b')
    bbc = piece.Bishop(screen.blit(blackBish, (120, 0)), blackBish, 'b')
    bbf = piece.Bishop(screen.blit(blackBish, (300, 0)), blackBish, 'b')
    bknb = piece.Knight(screen.blit(blackKnight, (60, 0)), blackKnight, 'b')
    bkng = piece.Knight(screen.blit(blackKnight, (360, 0)), blackKnight, 'b')

    gridArr = [[Square() for _ in range(8)] for _ in range(8)]
    for i in range(8):
        for j in range(8):
            gridArr[i][j].set_y(nums[i])
            gridArr[i][j].set_x(nums[j])
            gridArr[i][j].set_algebraic(horizontal[j] + vertical[i])

    gridArr[0][0].set_contains(True, bra)
    gridArr[0][1].set_contains(True, bknb)
    gridArr[0][2].set_contains(True, bbc)
    gridArr[0][3].set_contains(True, bq)
    gridArr[0][4].set_contains(True, bk)
    gridArr[0][5].set_contains(True, bbf)
    gridArr[0][6].set_contains(True, bkng)
    gridArr[0][7].set_contains(True, brh)
    gridArr[1][0].set_contains(True, bpa)
    gridArr[1][1].set_contains(True, bpb)
    gridArr[1][2].set_contains(True, bpc)
    gridArr[1][3].set_contains(True, bpd)
    gridArr[1][4].set_contains(True, bpe)
    gridArr[1][5].set_contains(True, bpf)
    gridArr[1][6].set_contains(True, bpg)
    gridArr[1][7].set_contains(True, bph)
    gridArr[6][0].set_contains(True, wpa)
    gridArr[6][1].set_contains(True, wpb)
    gridArr[6][2].set_contains(True, wpc)
    gridArr[6][3].set_contains(True, wpd)
    gridArr[6][4].set_contains(True, wpe)
    gridArr[6][5].set_contains(True, wpf)
    gridArr[6][6].set_contains(True, wpg)
    gridArr[6][7].set_contains(True, wph)
    gridArr[7][0].set_contains(True, wra)
    gridArr[7][1].set_contains(True, wknb)
    gridArr[7][2].set_contains(True, wbc)
    gridArr[7][3].set_contains(True, wq)
    gridArr[7][4].set_contains(True, wk)
    gridArr[7][5].set_contains(True, wbf)
    gridArr[7][6].set_contains(True, wkng)
    gridArr[7][7].set_contains(True, wrh)

    return gridArr

class Board:
    def __init__(self, screen):
        self.board = init(screen)

    def get_at_cords(self, cords):
        for col in self.board:
            for item in col:
                if cords[0] in range(item.x, item.x + 60) and cords[1] in range(item.y, item.y + 60):
                    return item

    def get(self, color, target_piece):
        pieces = []
        for col in self.board:
            for item in col:
                if item.contains and item.contained_piece.color == color \
                        and type(item.contained_piece) == target_piece:
                    pieces.append(item.contained_piece)
        if len(pieces) == 1:
            return pieces[0]
        else:
            return pieces

class Square:
    def __init__(self, x=0, y=0, cont=False, contained=None, algebraic=''):
        self.x = x
        self.y = y
        self.cords = (x, y)
        self.contains = cont
        self.contained_piece = contained
        self.algebraic = algebraic

    def get_algebraic(self):
        return self.algebraic

    def set_algebraic(self, algebraic):
        self.algebraic = algebraic

    def set_x(self, x):
        self.x = x

    def set_y(self, y):
        self.y = y

    def set_contains(self, cont=False, contained=None):
        self.contains = cont
        self.contained_piece = contained


from constants import dateFormat, timeFormat

reply_unreg_user0 = "Привет!\n" \
                    "Как тебя зовут?\n"

reply_settings_change_name = "Хорошо!\n" \
                             "Как тебя зовут теперь?\n"

empty_msg = "хмех"
error_msg = "Упс бот словил неожиданный эксепшн! Сорян"
reply_already_admin = "Друг, так ты ж уже админ\nТочнее, уже нет"

help_note = "Привет!\nЭтот бот позволит оставаться в курсе ближайших событий и поможет регистрироваться на них!" \
            "\n\nБоту доступны следующие команды:\n" \
            "/start - начать работу\n" \
            "/menu - если ты потерялся, эта команда вызовет основное меню опций\n" \
            "/admin - если ты по счастливой случайности оказался членом нашей тимы " \
            "с помощью этой команды можно стать мэйкером ивентов!\n\n" \
            "Увидимся! ⛈💘🥰 "

reply_choose_command = "Выберите одну из возможных опций"
reply_reg_FIO = "Как тебя зовут?"
reply_main_options = "В общем опции: "
reply_event_markup = "{}\nКогда: {} {}\nКак долго: {}\nПроводит: {}\n{}\n"
reply_nothing_found = "Кажись ничего не будет!"
reply_choose_day_of_the_week = "Выбери кнопочкой день недели чтобы посмотреть что будет!"
reply_empty_week = "Кажись мы ничего не планируем на ближайшие 7 дней, залетай попозже"

# Запись на ивент
reply_event_choosing_part = "Хочу сюда: "
reply_choose_event = "Крутяк! Записаться можно на неделю вперед, выбери куда ты хочешь из списка ниже:"
reply_success_registration = "Шикарный выбор! Записали тебя на {}!\nУвидимся там елки-палки 😉"
inline_reg_button_text = "{} {}"
reply_already_reged = "Воу! Ты кажется уже сюда зареган!"

# Отмена реги
reply_guest_reged_events_offer = "Вы сейчас зарегестрированы на следующие ивенты: "
reply_choose_event_to_cancel = "Ты сейчас зарегестрирован на вот эти ивенты. На какой из них решил не идти?"
reply_event_cancel_choosing_part = "Я не пойду сюда: "
reply_success_unregistration = "Эх! Отменили твою запись на {}!\nУвидимся в другой раз"
reply_unsuccess_unregistration = "Странно, кажется не получилось отменить регестрацию"
reply_no_hay_events_to_cancel = "А ты еще не регестрировался ни на один ивент!"

# админ
reply_admin_password = "Чтобы стать админом надо знать особое слово...\n" \
                       "Знаешь его?"
reply_admin_change_succ = "Вау...ты теперь админ еклм! \U0001f604\nПри повторном вызове команды статус админа " \
                          "превратится в тыкву! "
reply_admin_change_denied = "Не тот пассворд..🙀🙎"

# админ
reply_choose_stat_to_show = "Выбери что-то из доступного"
reply_choose_months_to_show_stats = "Выбери месяц чтобы посмотреть статистику"
reply_event_markup_advanced = "№: {}\nНазвание: {}\nДата: {}\nВремя: {}\nПроводит: {}\nСтатус: {}\nОписание: {}\n"

reply_stats = "Статистика по ивентам:\n\n"
reply_stats_row = "{:10}    👌{:5}  | 🚫{:5}\n"
reply_no_stat_for_month = "За этот месяц нет ивентов!"
reply_del = "\n--------\n"
reply_event_add_remind = "Круть! Напоминаю, пришли ивент в формате:"
reply_event_add = "Название: 🤤 мой ивент!\nДата: {}\nВремя: {}\n" \
                  "Проводит: @daniil_toro\nКак долго: сколько времени?\nОписание: что-нить\n".format(dateFormat, timeFormat)
reply_event_edit_part = "✏"
reply_event_edit = "Вот ближайшие ивенты:"
reply_event_edit1 = "Пришли ивент в том же формате, что и выше, но замени необходимое"
reply_event_succ_upd = "Оки! Обновили"
reply_event_unsucc_upd = "Почему-то не получилось обновить ивент"


import re

# Broadest alternatives first
_JUNK_TAGS_CORE = r'''
(
[^()[\]\/-]*re-?master.*|
[^()[\]\/-]+\smix\s\d{4}|
(?:f(ea)?t\.|with|vs\.)\s.+|
live(?:\s.+)?|
(?:re-?)?recorded(?:\s.+)?|
(?:(?:album|single)\sversion)|
(?:(?:mono|stereo)(?:\sversion)?)|
original(?:[^()[\]\/-]*version.*)?|
(?:\d{4}|ultimate|(?:new\s)?(?:mono|stereo)|special)\smix|
explicit|
clean|
b-side|
bonus\strack|
parody\sof\s.+|
from\s".+".*
)
'''

# " (Junk Tag)" or " [Junk Tag]" or " - Junk Tag" or " / Junk Tag"
_JUNK_TAGS_FULL = r'\s(\({0}\)|\[{0}\]|-\s{0}|\/\s{0}).*$'.format(_JUNK_TAGS_CORE)

TITLE_JUNK = [(re.compile(x[0], flags=re.IGNORECASE | re.VERBOSE), x[1]) for x in [
    (_JUNK_TAGS_FULL, ''),
]]

ARTIST_JUNK = [(re.compile(x[0], flags=re.IGNORECASE), x[1]) for x in [
    # Unlike the one in _JUNK_TAGS_CORE, also allows "X feat. Y"
    (r'\s[([]?(f(ea)?t\.|with|vs\.)\s.+$', ''),
]]

GENIUS_CYRILLIC = [(re.compile(x[0], flags=re.IGNORECASE), x[1]) for x in [
    # Кириллическое название (Latin Translation)
    (r'(.*[\u0400-\u04ff].*)\s\([^\u0400-\u04ff]+\)$', r'\1'),
]]

GENIUS_ARTIST_ALIAS = [(re.compile(x[0], flags=re.IGNORECASE), x[1]) for x in [
    # When Genius has a different name for the artist (obviously super incomplete)
    (r'^Queen & David Bowie$', r'Queen'),
    (r'^Freddie Mercury and Montserrat Caballé$', r'Freddie Mercury'),
    (r'^Paul McCartney & Wings$', r'Wings'),
    (r'^Silk Sonic$', r'Bruno Mars'),
    (r'^Ariana Grande & Doja Cat$', r'Ariana Grande'),
    (r'^Young Stoner Life & Young Thug$', r'Young Stoner Life'),
]]

BRACKETS = [(re.compile(x[0], flags=re.IGNORECASE), x[1]) for x in [
    # Remove (these) and [these] brackets with their contents
    # 2x to allow one level of nesting
    (r'\([^()]*\)|\[[^[\]]\]]', ''),
]] * 2

CLEANUP = [(re.compile(x[0], flags=re.IGNORECASE), x[1]) for x in [
    # Remove leading and trailing spaces/dashes/slashes
    (r'^[\s/-]+|[\s/-]+$', ''),
    # Collapse multiple spaces in a row
    (r'\s+', r' '),
]]

def apply(s, filters):
    for pattern, replacement in filters:
        s = pattern.sub(replacement, s)
    return s

if __name__ == '__main__':
    # Test main regex
    print(_JUNK_TAGS_FULL.replace('\n', ''))


# Snail Sort
# Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.

# array = [[1,2,3],
#          [4,5,6],
#          [7,8,9]]
# snail(array) #=> [1,2,3,6,9,8,7,4,5]
# For better understanding, please follow the numbers of the next array consecutively:

# array = [[1,2,3],
#          [8,9,4],
#          [7,6,5]]
# snail(array) #=> [1,2,3,4,5,6,7,8,9]
# This image will illustrate things more clearly:

# NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.

# NOTE 2: The 0x0 (empty matrix) is represented as en empty array inside an array [[]].

def snail(snail_map):
    snail_array = []
    top, bottom = 0, len(snail_map)
    left, right = 0, len(snail_map[0])

    while top < bottom and left < right:

        [snail_array.append(snail_map[top][i]) for i in range(left, right)]
        top += 1

        [snail_array.append(snail_map[j][right - 1]) for j in range(top, bottom)]
        right -= 1

        if top < bottom:
            [snail_array.append(snail_map[bottom -1][k]) for k in range(right - 1, left - 1, -1)]
            bottom -= 1

        if left < right:
            [snail_array.append(snail_map[l][left]) for l in range(bottom - 1, top - 1, -1)]
            left += 1

    return snail_array


import sys
input = sys.stdin.readline

t = int(input())
for tc in range(1, t+1):
    n = int(input())
    case = [list(map(int, input().split())) for _ in range(n+2)]
    # print(case)
    check = True
    for i in range(1, n+2):
        if abs(case[i][0] - case[i-1][0]) + abs(case[i][1] - case[i-1][1]) > 1000:
            check = False
            break

    if check:
        print('happy')
    else:
        print('sad')


import numpy as np
import inspect
import operator
from functools import reduce
from itertools import combinations_with_replacement
from collections import Counter
from math import sqrt, factorial
from numpy.linalg import norm

from .utils.data_utils import add_cons
from .utils.polynomial_util import C, H, get_poly_coef
from .utils.print_utils import format_repr

class Kernel():
    def __init__(self):
        pass

    def transform(self, x):
        pass

    def inner_product(self, x1, x2):
        pass

    def __call__(self, x1, x2):
        return self.inner_product(x1, x2)

    def __repr__(self):
        init_sig = inspect.signature(self.__init__)
        param_names = [param.name for param in init_sig.parameters.values()
                                  if  param.name != "self" and
                                      param.kind != param.VAR_KEYWORD ]
        output = {}
        for p_name in param_names:
            p_object = getattr(self, p_name)
            output[p_name] = p_object
        return format_repr(self.__class__.__name__, output)

class Linear(Kernel):
    def transform(self, x):
        return x

    def inner_product(self, x1, x2):
        return  x1 @ x2.T

class SimplePoly2(Kernel):
    def transform(self, x, return_label=False):
        d = x.shape[1]
        result = np.empty((len(x), 1+d+d**2))
        label = list(range(0, d+1))
        result[:, 0:(d+1)] = add_cons(x)

        for i in range(d):
            for j in range(d):
                xi_xj = x[:, i] * x[:, j]
                label.append((i+1, j+1))
                result[:, len(label)-1] = xi_xj

        if return_label:
            return result, label
        else:
            return result

    def inner_product(self, x1, x2):
        xx = x1 @ (x2.T)
        return 1 + xx + xx**2

class Polynomial(Kernel):
    def __init__(self, degree=2, beta=1, gamma=1):
        self.degree = degree
        self.beta = beta
        self.gamma = gamma

    def transform(self, x, return_label=False):
        x = add_cons(x)

        beta = self.beta
        gamma = self.gamma
        degree = self.degree
        num_features = x.shape[1]

        label = list(combinations_with_replacement(range(num_features), degree))
        result = np.empty((len(x), len(label)))

        for i in range(len(label)):
            count = dict(Counter(label[i]))

            cons_deg = count.get(0, 0)
            noncons_deg = degree - cons_deg
            poly_coef = get_poly_coef(deg=degree, terms=count)
            coef = sqrt((beta**cons_deg) * (gamma**noncons_deg) * poly_coef)

            x_product = coef * reduce(np.multiply,
                                        [np.power(x[:, k], v) for k, v in count.items()])
            result[:, i] = x_product

        if return_label:
            return result, label
        else:
            return result

    def inner_product(self, x1, x2):
        b = self.beta
        r = self.gamma
        k = self.degree
        xx = x1 @ (x2.T)
        return (r * xx + b)**k

class Gaussian(Kernel):
    def __init__(self, gamma=1, inf_dim=3):
        self.gamma = gamma
        self.inf_dim = inf_dim  # max dimension if taylor expansion is conducted

    def transform(self, x, return_label=False):
        """
        Ref:　https://arxiv.org/pdf/0904.3664v1.pdf (p.39)
        """
        x = add_cons(x)

        gamma = self.gamma
        max_dim = self.inf_dim
        num_features = x.shape[1]
        norm_square = (x @ x.T)[range(len(x)), range(len(x))]

        label = list(combinations_with_replacement(range(num_features), max_dim))
        result = np.empty((len(x), len(label)))

        for i in range(len(label)):
            count = dict(Counter(label[i]))

            deg = sum(count.values()) - count.get(0, 0)
            poly_coef = get_poly_coef(terms=count)

            if deg == 0:
                coef = np.exp(-sqrt(gamma) * norm_square)
            else:
                coef = sqrt(2**deg / factorial(deg))**(1/deg) * \
                   sqrt(poly_coef) * \
                   np.exp(-sqrt(gamma) * norm_square)**(1/deg)

            x_product = coef * reduce(np.multiply, [x[:, k]**v for k, v in count.items()])
            result[:, i] = x_product

        if return_label:
            return result, label
        else:
            return result

    def inner_product(self, x1, x2):
        gamma = self.gamma

        if len(x2.shape) == 1:
            x2 = x2.reshape((1, -1))

        x1_sqr = np.einsum('ij, ij -> i', x1, x1).reshape((-1, 1))
        x2_sqr = np.einsum('ij, ij -> i', x2, x2)
        norm_sqr = x1_sqr - 2*x1@(x2.T) + x2_sqr
        return np.exp(-gamma * norm_sqr)


import numpy as np
import torch
import torch.autograd as ag
import torch.nn as nn
import torch.optim as optim
from torchsummary import summary
import torchvision
import torchvision.transforms as transforms
import torchvision.datasets as datasets

from scipy.optimize import minimize, NonlinearConstraint
import random

import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error

from math import sqrt
import time

def random_graph(p, size=(100,100)):
    """
    Generate a random bipartite graph of size (size[0], size[1]), with a
    probability p to have connections on each pair of nodes. It returns
    an adjacency matrix.
    """
    return(np.array([[int(random.random() < p) for i in range(size[1])] for j in range(size[0])]))

def random_undirected_graph(p, size=(100,100)):
    """
    Same as random_graph but it makes sure that the returned graph is
    undirected.
    """

    graph = random_graph(p, size=size)
    graph[np.arange(size[0]),np.arange(size[1])]=0 #nullify the diagonal
    graph = np.maximum(graph, graph.T) #make it symmetric

    return(graph)

def random_graph_with_fixed_components(p, nodes_per_component=[50,50]):
    """
    Produce a random graph with components of chosen sizes.
    """
    nodes_per_component = np.array(nodes_per_component)
    n_nodes = nodes_per_component.sum()
    n_cmp = nodes_per_component.shape[0]

    graph = np.zeros((n_nodes, n_nodes))
    nodes = np.arange(n_nodes)
    np.random.shuffle(nodes)

    cmp_nodes = []
    acc=0

    for i in range(n_cmp):
        cmp = nodes[acc:(acc+nodes_per_component[i])]
        cmp_nodes.append(cmp)
        acc += nodes_per_component[i]

        size = cmp.shape[0]
        submatrix=np.ix_(cmp,cmp)

        graph[submatrix] = random_undirected_graph(p, (size,size))

    return(graph)

def neighbors(adj, i):
    """
    Given an unweighted adjacency matrix, returns a node i's neighbors.
    """
    return (np.where(adj[i,:]==1)[0])

def dfs(adj, i):
    """
    Depth First Search, starting from node i.

    """
    n = adj.shape[0] #number of nodes in the graph
    visited = [False for k in range(n)]

    stack = [i]

    while(len(stack)>0):
        k = stack.pop()
        neighborhood = neighbors(adj, k)
        visited[k] = True

        for n in neighborhood:
            if not visited[n]:
                stack.append(n)

    return(np.where(visited))

def connected_components(adj):
    """
    Returns components of a given grah (via its adjacency matrix adj).

    """
    n = adj.shape[0]

    visited = np.array([0 for k in range(n)])
    s = np.sum(visited)

    comp=[]

    while s<n:
        i = np.where(1-visited)[0][0]

        cmp = dfs(adj, i)
        visited[cmp] = 1
        s = np.sum(visited)

        comp.append(list(cmp[0]))

    return(np.array(comp))

if __name__ == '__main__':
    pass


#Copyright (C) 2018  Seyed Mehran Kazemi, Licensed under the GPL V3; see: <https://www.gnu.org/licenses/gpl-3.0.en.html>
from tensor_factorizer import *
from reader import *
import numpy as np
import gensim
class TransE(TensorFactorizer):

	def __init__(self, params, dataset="dmda"):
		TensorFactorizer.__init__(self, model_name="TransE", loss_function="margin", params=params, dataset=dataset)

	def setup_weights(self):
		# 初始化实体和关系向量，并做归一化处理
		sqrt_size = 6.0 / math.sqrt(self.params.emb_size)
		# self.rel_emb = tf.get_variable(name="rel_emb", initializer=tf.random_uniform(shape=[self.num_rel, self.params.emb_size], minval=-sqrt_size, maxval=sqrt_size))
		self.ent_emb = tf.get_variable(name="ent_emb", initializer=tf.random_uniform(shape=[self.num_ent, self.params.emb_size], minval=-sqrt_size, maxval=sqrt_size))
		new_model = gensim.models.Word2Vec.load('w2v.model')
		vocab = ['pathogenic', 'host', 'group', 'locate', 'genus', 'family', 'order', 'class']
		vector_dim = 100

		# with open("./dmda/entities.dict", 'r', encoding="utf8") as df:
		# 	st = []
		# 	for li in df.readlines():
		# 		li = li.strip('\n')
		# 		st.append(li.split('\t'))
		#
		rel_embedding_matrix = np.zeros((len(vocab), vector_dim))
		# ent_embedding_matrix = np.zeros((len(st), vector_dim))

		for i in range(len(vocab)):
			embedding_vector = new_model.wv[vocab[i]]
			if embedding_vector is not None:
				rel_embedding_matrix[i] = embedding_vector
		#
		# for i in range(len(st)):
		# 	try:
		# 		embedding_vector = new_model.wv[st[i]]
		# 		if embedding_vector is not None:
		# 			ent_embedding_matrix[i] = embedding_vector
		# 	except:
		# 		ent_embedding_matrix[i] = np.ones((1, 300), dtype=int)

		rel_saved_embeddings = tf.constant(rel_embedding_matrix, dtype=tf.float32)
		# ent_saved_embeddings = tf.constant(ent_embedding_matrix, dtype=tf.float32)
		# self.ent_emb = tf.Variable(name="ent_emb",initial_value=ent_saved_embeddings, trainable=False)
		self.rel_emb = tf.Variable(initial_value=rel_saved_embeddings, trainable=False)
		self.var_list = [self.rel_emb, self.ent_emb]

	def define_regularization(self):
		self.regularizer = tf.reduce_sum(tf.nn.relu(tf.square(tf.norm(self.ent_emb, axis=1, ord=2)) - 1.0))

	def gather_train_embeddings(self):
		# 用一个一维的数组，将张量中对应索引的向量提取出来
		self.ph_emb = tf.gather(self.ent_emb, self.ph)
		# print(self.ph)
		# print("111111111111", self.ent_emb, self.ph)
		self.pt_emb = tf.gather(self.ent_emb, self.pt)
		self.nh_emb = tf.gather(self.ent_emb, self.nh)
		self.nt_emb = tf.gather(self.ent_emb, self.nt)
		self.r_emb  = tf.gather(self.rel_emb, self.r)
		# print("111111111111",self.r_emb,self.r)

	def gather_test_embeddings(self):
		self.h_emb = tf.gather(self.ent_emb, self.head)
		self.r_emb = tf.gather(self.rel_emb, self.rel)
		self.t_emb = tf.gather(self.ent_emb, self.tail)

	def create_train_model(self):
		self.pos_dissims = tf.norm(self.ph_emb + self.r_emb - self.pt_emb, axis=1, ord=self.params.p_norm)
		self.neg_dissims = tf.norm(self.nh_emb + self.r_emb - self.nt_emb, axis=1, ord=self.params.p_norm)

	def create_test_model(self):
		self.dissims = tf.norm(self.h_emb + self.r_emb - self.t_emb, axis=1, ord=self.params.p_norm)


# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import django
import collections

#def square_mass(height):
#    list_ = []
#    for i in range(len(height)):
#        for j in range(len(height)):
#            m = min(height[i], height[j])
#            index = j - i
#            list_.append(m * index)
#    return max(list_)

nums = [3,4,5,6,7,0,1,2]
target = 2

ind = int(len(nums) / 2)

left_ = 0
right_ = 0
end_ = 0
start_ = 0

if nums[ind] < nums[ind + 1]:
    ind += 1

start_ = nums[0]
left_ = nums[ind - 1]

end_ = nums[len(nums) - 1]
right_ = nums[ind + 1]

if target >= start_:
    if 0 == right_ and -(ind - target) <= ind:
        print("index: ",  (-(ind - target - 1)))

if target >= end_:
    if 0 == left_:
        print("index: ", -(ind + target - 1))


#!/usr/bin/env python3
""" Unittest utils """
import unittest
from parameterized import parameterized
from utils import access_nested_map, get_json, memoize
from unittest.mock import patch, Mock

class TestAccessNestedMap(unittest.TestCase):
    """class that inherits from unittest.TestCase"""

    @parameterized.expand(
        [
            ({"a": 1}, ("a",), 1),
            ({"a": {"b": 2}}, ("a",), {"b": 2}),
            ({"a": {"b": 2}}, ("a", "b"), 2),
        ]
    )
    def test_access_nested_map(self, nested_map, path, expected):
        """method to test that the method returns what it is supposed to."""
        self.assertEqual(access_nested_map(nested_map, path), expected)

    @parameterized.expand([({}, ("a",)), ({"a": 1}, ("a", "b"))])
    def test_access_nested_map_exception(self, nested_map, path):
        """
        test that a KeyError is raised for
        the following inputs (use @parameterized.expand)
        """
        with self.assertRaises(KeyError):
            access_nested_map(nested_map, path)

class TestGetJson(unittest.TestCase):
    """
    implement the TestGetJson.test_get_json
    method to test that utils.get_json returns the expected result.
    """

    @parameterized.expand(
        [
            ("http://example.com", {"payload": True}),
            ("http://holberton.io", {"payload": False}),
        ]
    )
    def test_get_json(self, url, payload):
        """
        method to test that the method returns what it is supposed to.
        """

        class Mocked(Mock):
            """
            class that inherits from Mock
            """

            def json(self):
                """
                json returning a payload
                """
                return payload

        with patch("requests.get") as MockClass:
            MockClass.return_value = Mocked()
            self.assertEqual(get_json(url), payload)

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


import torch
import torch.nn as nn
import os
import random
from collections import namedtuple, deque

Transition = namedtuple('Transition',
                        ('state', 'action', 'next_state', 'reward', 'cur_phase', 'next_phase', ))

class ReplayMemory(object):

    def __init__(self, capacity):
        self.memory = deque([], maxlen=capacity)

    def push(self, *args):
        """Save a transition"""
        self.memory.append(Transition(*args))

    def sample(self, batch_size):
        return random.sample(self.memory, batch_size)

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

class DQN(nn.Module):
    def __init__(self, inputs, outputs, num_phases, hidden_dim):
        super(DQN, self).__init__()
        self.shared_layer = nn.Linear(inputs, hidden_dim)
        # self.device = 'cuda:0'
        # self.seperate0_layer = nn.Linear(20, 20)
        # self.seperate1_layer = nn.Linear(20, 20)
        # self.out_layer0 = nn.Linear(20, outputs)
        # self.out_layer1 = nn.Linear(20, outputs)
        self.seperate_layers = nn.ModuleList([nn.Linear(hidden_dim, hidden_dim) for i in range(num_phases)])
        self.out_layers = nn.ModuleList([nn.Linear(hidden_dim, outputs) for i in range(num_phases)])

    def forward(self, inputs, cur_phase, num_actions):
        activate = nn.Sigmoid()
        x = activate(self.shared_layer(inputs))
        q_value = torch.zeros(len(cur_phase), num_actions)
        # x_0 = activate(self.seperate0_layer(x))
        # x_1 = activate(self.seperate1_layer(x))
        # x = activate(self.seperate_layers[cur_phase](x))
        for idx in range(len(cur_phase)):
            x_mid = activate(self.seperate_layers[cur_phase[idx]](x))
            q_value += self.out_layers[cur_phase[idx]](x_mid)

        # q_value = self.out_layers[cur_phase](x)

        # q0_value, q1_value = self.out_layer0(x_0), self.out_layer1(x_1)
        # selector0, selector1 = torch.sum((1 - cur_phase)), torch.sum(cur_phase)
        # q_value = selector0 * q0_value + selector1 * q1_value
        return q_value.view(q_value.size(0), -1)

class NetAgent:
    def __init__(self, args, sumo_agent):
        self.args = args
        # self.num_phases = args.num_phases
        # self.num_actions = args.num_actions
        self.num_phases = sumo_agent.get_num_phases()
        self.num_actions = sumo_agent.get_num_actions()
        self.state_dim = sumo_agent.get_state_dim()
        self.memory_size = args.memory_size
        self.memory = self.build_memory()
        self.batch_size = args.batch_size
        # self.device = args.device
        self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
        self.EPSILON, self.GAMMA = 0.05, 0.9
        self.q_target_outdated = 0
        self.UPDATE_Q_TAR = 5
        self.q_network, self.q_target = DQN(self.state_dim, self.num_actions,self.num_phases, args.hidden_dim).to(self.device), DQN(self.state_dim, self.num_actions, self.num_phases, args.hidden_dim).to(self.device)
        self.lr = args.lr

    def load_model(self, root_path):
        checkpoint = torch.load(root_path)
        self.q_network.load_state_dict(checkpoint['q_state_dict'])
        # self.q_network.eval()

    def save_model(self, root_path):
        saving_dict = {'q_state_dict': self.q_network.state_dict(),
                       'is_best': 1}
        torch.save(saving_dict, root_path)

    def build_memory(self):
        memory_list = []
        for i in range(self.num_phases):
            memory_list.append([ReplayMemory(self.memory_size) for j in range(self.num_actions)])
        return memory_list

    def choose(self, count, state, cur_phase, is_val):

        ''' choose the best action for current state '''
        state = state.to(self.device)
        cur_phase = torch.tensor(cur_phase).to(self.device)
        self.num_actions = torch.tensor(self.num_actions).to(self.device)
        q_values = self.q_network(state, cur_phase, self.num_actions)
        # print(q_values)
        if random.random() <= self.EPSILON and not is_val:  # continue explore new Random Action
            self.action = torch.tensor(random.randrange(q_values.shape[0]))
            print("##Explore")
        else:  # exploitation
            self.action = torch.argmax(q_values)
        if self.EPSILON > 0.001 and count >= 20000:
            self.EPSILON = self.EPSILON * 0.9999
        return self.action

    def remember(self, state, action, reward, next_state, cur_phase, next_phase):

        """ log the history """
        cur_phase_num = self.bin2dec(cur_phase, len(cur_phase)).long()
        self.memory[cur_phase_num.item()][action].push(state, action, next_state, reward, cur_phase, next_phase)

    def forget(self):

        """ remove the old history if the memory is too large """

        for phase_i in range(self.num_phases):
            for action_i in range(self.num_actions):
                if len(self.memory[phase_i][action_i]) > self.memory_size:
                    # print("length of memory (state {0}, action {1}): {2}, before forget".format(
                    #     phase_i, action_i, len(self.memory[phase_i][action_i])))
                    self.memory[phase_i][action_i] = self.memory[phase_i][action_i][-self.memory_size:]
                # print("length of memory (state {0}, action {1}): {2}, after forget".format(
                #     phase_i, action_i, len(self.memory[phase_i][action_i])))

    def define_criterion_and_opti(self, device, weight_decay=1e-5):
        self.optimizer_DQN = torch.optim.Adam(params=self.q_network.parameters(),
                                              lr=self.lr,
                                              weight_decay=weight_decay)
        # self.scheduler_DQN = torch.optim.lr_scheduler.MultiStepLR(self.optim_DQN,
        #                                                           milestones=self.opt.schdr_step_size,
        #                                                           gamma=self.opt.schdr_gamma)

    def reset_update_count(self):

        self.q_target_outdated = 0

    def train_net(self, transitions):
        batch = Transition(*zip(*transitions))

        # Compute a mask of non-final states and concatenate the batch elements
        # (a final state would've been the one after which simulation ended)
        # non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,
        #                                         batch.next_state)), device=self.device, dtype=torch.bool)
        #
        # non_final_next_states = torch.cat([s for s in batch.next_state
        #                                    if s is not None])

        state_batch = torch.cat(batch.state).to(self.device).view(self.batch_size, -1)
        action_batch = torch.cat(batch.action).to(self.device).view(self.batch_size, -1)
        reward_batch = torch.cat(batch.reward).to(self.device).view(self.batch_size, -1)
        cur_phase_batch = torch.cat(batch.cur_phase).to(self.device).view(self.batch_size, -1)

        # Compute Q(s_t, a) - the model computes Q(s_t), then we select the
        # columns of actions taken. These are the actions which would've been taken
        # for each batch state according to policy_net
        state_action_values = self.q_network(state_batch, cur_phase_batch, self.num_actions).gather(1, action_batch)
        # Compute V(s_{t+1}) for all next states.
        # Expected values of actions for non_final_next_states are computed based
        # on the "older" target_net; selecting their best reward with max(1)[0].
        # This is merged based on the mask, such that we'll have either the expected
        # state value or 0 in case the state was final.
        # next_state_values = torch.zeros(self.batch_size, device=self.device)
        next_phase_batch = torch.cat(batch.next_phase).to(self.device).view(self.batch_size, -1)
        next_state_batch = torch.cat(batch.next_state).to(self.device).view(self.batch_size, -1)
        next_state_values = self.q_target(next_state_batch, next_phase_batch, self.num_actions).max(1)[0].detach().unsqueeze(1)
        # next_state_values[non_final_mask] = self.q_target(non_final_next_states).max(1)[0].detach()
        # Compute the expected Q values

        expected_state_action_values = (next_state_values * self.GAMMA) + reward_batch

        # Compute Huber loss
        criterion = nn.SmoothL1Loss().to(self.device)
        loss = criterion(state_action_values, expected_state_action_values)

        # Optimize the model
        self.optimizer_DQN.zero_grad()
        loss.backward()
        # for param in self.q_network.parameters():
        #     param.grad.data.clamp_(-1, 1)
        self.optimizer_DQN.step()
        return loss.item()

    def trainer(self):
        if self.batch_size > self.memory_size:
            return

        transitions = deque()

        for phase_i in range(self.num_phases):
            for action_i in range(self.num_actions):
                transitions.extend(self.memory[phase_i][action_i].memory)
        # add
        if len(transitions) > self.batch_size:
            transitions = random.sample(transitions, self.batch_size)
            self.define_criterion_and_opti(self.device)
            loss = self.train_net(transitions)
            self.q_target_outdated += 1
            self.forget()
            self.update_network_bar()
            return loss

    def update_network_bar(self):

        ''' update Q bar '''

        if self.q_target_outdated >= self.UPDATE_Q_TAR:
            self.q_target.load_state_dict(self.q_network.state_dict())
            self.q_target_outdated = 0

    @staticmethod
    def _cal_priority(sample_weight):
        pos_constant = 0.0001
        alpha = 1
        sample_weight = torch.Tensor(sample_weight)
        sample_weight_pr = torch.pow(sample_weight + pos_constant, alpha) / sample_weight.sum()
        return sample_weight_pr

    @staticmethod
    def bin2dec(b, bits):
        mask = 2 ** torch.arange(0, bits, 1)
        return torch.sum(mask * b, -1)


import pytest
import numpy as np

def test_gofr(analisi_traj,num_regression):
    import pyanalisi
    startr=0.0
    endr=3.8
    nbin=200
    gofr=pyanalisi.Gofrt(analisi_traj,startr,endr,nbin,10,4,10,False,1)
    gofr.reset(700)
    gofr.calculate(0)
    gr=np.array(gofr,copy=True)
    print(gr)
    num_regression.check({'g_of_r_and_t':gr.flatten()})


import numpy as np
import re

characters = '-.,!?aăâbcdefghiîjklmnopqrsștțuvwxyzAĂÂBCDEFGHIÎJKLMNOPQRSȘTȚUVWXYZ '

def clean(file):
    text = open(file).read().splitlines()
    text = [re.sub(r'\s([?.!,"](?:\s|$))', r'\1', re.sub(r'(\[[^)]*\])|([^' + characters + '])|(?:(?<=-) | (?=-))', '', line)) for line in text]
    # text = list(filter(None, text))
    # text = [line for line in text if len(line)>=25 and len(line)<=100]

    # print((text[:20]))

    # text = [re.sub(' +', ' ', line) for line in text]
    # text = [re.sub(r'\.{2,}', '.', line) for line in text]
    text = [line for line in text if 'px' not in line]

    with open('clean_text6.txt', 'w') as out_file:
        out_file.write('\n'.join(text))
    print(len(text))
file_path = './clean_text5.txt'
clean(file_path)