# -*- coding: utf-8 -*-
### Modélisation SetUp1 test 2 implentation
#reprise du code main_glacier_test8
# pour afficher le graphe 2D de la déformation u(x,t)
# avec schéma de Verlet initial
# avec implémentation de la nouvelle géométrie - glacier qui repose sur le
# avec loi de Weertman
# close all

## import des modules utiles
import numpy as np
import os
import time

## construction class Glacier pour initialisation des valeurs et fonctions
class Glacier:

# Paramètre de construction physique:
#   masse volumique glace : rho_glace [kg.m^-3]
#   masse volumique eau : rho_eau [kg.m^-3]
#   épaisseur du glacier : H [m]
#   pente du glacier : alpha_ground [deg]
#   accélaration de la pesanteur : g [m.s^-2]
#   coeff de friction Weertman : Cw [Pa]
#   coeff de friction Budd : Cb [Pa]
#   coeff de friction Schoof : Cs [Pa]
#   exposant de vitesse de glissement : m
#   coeff de glissement max Schoof : Cmax [Pa]
#   loi utilisée : type_law =0 Weertman, =1 Tsai, =2 sans frottement

# Lecture des fichiers utiles récupération des données
#   nom du fichier avec liste temps T : T_filename
#   nom du fichier avec liste force contact Fc : Fc_filename
#   nom du fichier avec Nt_retour indice du retournement : Nt_retour_filename
#   nom du fichier avec T_retour durée du retournement : T_retour_filename

# Construction de la géométrie du glacier et discrétisation
#   nombre de bloc : Np
#   longueur du glacier : Ltot
#   profondeur d'immergement au front du glacier : h_imm

# Initialisation des paramètres d'optimisation
#   pas d'indice de bloc gardé pour affichage : Np_r
#   pas d'indice de temps gardé pour affichage : Nt_r
    def __init__(self,rho_glace,rho_eau,H,alpha_ground,alpha_surface,g,E,Np,Ltot,h_im):

        ## Paramètre de construction physique:
        # paramètres géométrique et physique élémentaires
        self.rho_glace=rho_glace #masse volumique glace
        self.rho_eau=rho_eau #masse volumique eau
        self.alpha_ground=alpha_ground #pente du glacier
        self.alpha_surface=alpha_surface
        self.g=g #accélération pesanteur
        self.E=E #module d'young de la glace

        ## Construction élémentaire de la géométrie du glacier et discrétisation
        # discrétisation du glacier
        self.H=H #épaisseur du glacier
        self.Ltot=Ltot #longueur du glacier
        self.Np=Np #nombre de blocs

        ## Setting of the glacier geometrie
        self.l_def()
        self.H_def()

        ## Mass matrix and mass of the blocs array
        self.M_bloc_def()
        self.M_def()

        ## Construction of matrxi stiffness
        self.K_def() #enregistrement utile pour calcul de Fe

    ## stiffness matrix
    def K_def(self):

        K_ = np.zeros((self.Np+1,self.Np+1))
        for i in range(self.Np):
            Ke = (self.E*self.H_l[i+1]/self.dl) * np.array([[1,-1],[-1,1]])
            K_[i:i+2,i:i+2] = K_[i:i+2,i:i+2] + Ke

        self.K = K_

    ## Length array for each bloc
    def l_def(self):

        l_init = np.linspace(0,self.Ltot,self.Np+1) #definition of the borders of the bloc

        dl_ = l_init[1] - l_init[0] #bloc length
        dl_l_ = np.zeros(self.Np+1)
        l_= np.zeros(self.Np+1)
        dl_l_[0] = dl_/2
        l_[0] = dl_l_[0]
        for k in range(1,self.Np):
            dl_l_[k] = dl_
            l_[k] = l_[k-1] + dl_l_[k]
        dl_l_[self.Np] = dl_/2
        l_[self.Np] = l_[self.Np-1] + dl_l_[self.Np]

        self.dl = dl_
        self.l = l_
        self.dl_l = dl_l_

    ## Heigth of borders
    def H_def(self):

        Y_down_ = np.zeros(self.Np+2)
        Y_up_ = np.zeros(self.Np+2)

        Y_down_[0] = 0
        Y_up_[0] = self.H
        for k in range(1,self.Np+2):
            Y_down_[k] = np.sin(self.alpha_ground)*self.l[k-1]
            Y_up_[k] = np.sin(self.alpha_surface)*self.l[k-1] + self.H

        H_ = Y_up_ - Y_down_
        self.H_l = H_

    ## Mass for each bloc function
    def M_bloc_def(self):

        M_bloc_ = np.zeros(self.Np+1)
        for k in range(self.Np+1):
            M_bloc_[k] = (self.H_l[k]+self.H_l[k+1])/2 * self.rho_glace * self.dl_l[k]

        self.M_bloc = M_bloc_

    ## Mass matrix construction
    def M_def(self):

        M_ = np.diag(self.M_bloc)

        self.M = M_

    ## Matrice de réduction des déplacements de Np+1 à Np_plot+1
    def R_plot(self):

        R_plot_=np.zeros((self.Np_plot+1 ,self.Np+1))
        R_plot_[0][0] = 1
        R_plot_[self.Np_plot][self.Np] = 1
        for i in range(self.Np_plot-1):
            lp = self.lp_plot[i]+1
            R_plot_[i+1 ][lp]=1

        self.R_plot = R_plot_

    ## reduction matrix for sliding force
    def Rf_plot(self):

        Rf_plot_=np.zeros((self.Np_plot+1,self.Np+1))
        dl_mean = self.Ltot/(self.Np_plot + 1)
        Rf_plot_[0][0] = dl_mean*(2/self.dl)
        Rf_plot_[self.Np_plot][self.Np] = dl_mean*(2/self.dl)
        for i in range(self.Np_plot-1):
            lp = self.lp_plot[i]+1
            Rf_plot_[i+1][lp]= dl_mean/self.dl_l[lp]

        self.Rf_plot = Rf_plot_

    ## force elastique
    def Fe(self,U_i_):

        return(-np.dot(self.K,U_i_))

    ## force de perturbation
    def Fpertur(self,Fc_i_):

        # retourne la force de perturbation - avec le contact avec l'iceberg
        # i itération du temps, Fc_i_ force de contact à l'instant ti, self.Np longueur du vecteur

        Fpertur = np.zeros(self.Np+1)
        Fpertur[0] = Fc_i_

        return(Fpertur)

## Lecture de la liste T temps
def T_lecture(T_filename,path):

    os.chdir(path)
    T_file=open(T_filename,'r')
    T_txt=T_file.read()
    T_file.close()
    T_txt_list=T_txt.splitlines()
    Nt=len(T_txt_list) #longueur nombre d'itération en temps
    T=[]
    for k in range(Nt):
        T.append(float(T_txt_list[k]))

    dt=T[1]-T[0] #pas de temps
    Ttot=T[-1] #temps de simulation

    return(T, dt, Ttot, Nt)

## Lecture de la Force de contact a la longueur Nt avec Ttot dt paramètre de T
def Fc_lecture(Fc_filename,path,dt,Ttot):

    # lecture de la liste
    Ttot_fc = 300
    os.chdir(path)
    Fc_file=open(Fc_filename,'r')
    Fc_txt=Fc_file.read()
    Fc_file.close()
    Fc_txt_list=Fc_txt.splitlines()
    Fc_init=[]
    Len_Fc_load = int(Ttot*len(Fc_txt_list)/Ttot_fc)
    for k in range(Len_Fc_load):
        Fc_init.append(float(Fc_txt_list[k]))

    Nt_init = len(Fc_init)
    T_init = np.linspace(0,Ttot,Nt_init)
    dt_init = T_init[1]-T_init[0]

    # construction de la liste Fc lonugueur Nt
    T = np.arange(0,Ttot,dt)
    Nt = len(T)
    Fc = np.zeros(Nt)
    i = 0
    for k in range(Nt):
        tk = T[k]

        while T_init[i+1]<tk and i<Nt_init-1:
            i+=1

        ti = T_init[i]
        ti1 = T_init[i+1]
        Fc[k] = (ti1-tk)/dt_init *Fc_init[i] + (tk-ti)/dt_init *Fc_init[i+1]

    return(Fc)

## Lecture de valeur dans fichier - Nt_retour et T_retour
def Value_lecture(Value_filename,type_value,path):

    os.chdir(path)
    #type_value pour différencier Nt_retour de T_retour - int=0 et float=1
    Value_file = open(Value_filename,'r')
    Value_txt = Value_file.read()

    if type_value==0: #Nt_retour
        return(int(Value_txt.lstrip()))
    if type_value==1 : #T_retour
        return(float(Value_txt.lstrip()))
    else :
        T_max_read = Value_txt.splitlines()
        return(float(T_max_read[0]),float(T_max_read[1]))

## Construction des paramètres de réduction du temps pour affichage
def R_temps(Nt_,Nt_r_,Ttot):

    li_plot_ = np.arange(0,Nt_+Nt_r_,Nt_r_)
    Nt_plot_ = len(li_plot_)
    T_plot_ = np.linspace(0,Ttot,Nt_plot_)

    return(Nt_plot_,li_plot_,T_plot_)

## research the excited file names and writing of a new one
def create_file_result(glacier,results_path,theme_name):

    results_filename = "Results" + theme_name + "dl"+ str(int(glacier.dl))+ "Ltot" + str(int(glacier.Ltot/1000)) + "kmHHTsansFrott.npz"

    os.chdir(results_path)
    file_list = os.listdir(results_path)

    i = 2
    while results_filename in file_list :
        results_filename = "Results" + theme_name + "dl"+ str(int(glacier.dl))+ "Ltot" + str(int(glacier.Ltot/1000)) + "kmHHTsansFrottV" + str(i) +".npz"
        i +=1

    return(results_filename)

def create_folder_figure(glacier,save_figure_path,theme_name):

    os.chdir(save_figure_path)
    folder_list = os.listdir(save_figure_path)

    date = time.asctime(time.localtime())[0:10].replace(" ", "_")
    save_folder_name = date + "_" + theme_name

    i=2
    while save_folder_name in folder_list :
        save_folder_name = date + "_" + theme_name + "_V" + str(i)
        i +=1

    os.makedirs(save_folder_name)
    return(save_folder_name)

## Fonction pour intégration temporelle et simulation
def simu_alpha(glacier,Fc,dt,Nt,alpha,eps,Nt_r):

    # définition des vecteurs de calcul et de l'état initial du système
    Un = np.zeros(glacier.Np+1) # displacement
    Udn = np.zeros(glacier.Np+1) # vitesse
    Uddn = np.zeros(glacier.Np+1) # acceleration

    # arrays to return and at plotting
    Ut_plot = [[0 for k in range(glacier.Np+1)]] # displacement
    Udt_plot = [[0 for k in range(glacier.Np+1)]] # vitesse affichée
    Uddt_plot = [[0 for k in range(glacier.Np+1)]] # acceleration
    Ftf_plot = [0] # force
    Ftsismique_plot = [0] # force de frottement comparée au frottement statique
    Ftsismique_map = [[0 for k in range(glacier.Np+1)]]

    Niter_implicite = []

    # matrix and coefficient
    mc = (1+alpha)*(0.5-alpha)*dt
    mk = (1+alpha)*0.25*((1-alpha)*dt)**2
    uiai = 0.25*((1-alpha)*dt)**2
    udiai = (0.5-alpha)*dt
    p_alpha = -alpha
    p_alpha1 = (1+alpha)

    M = glacier.M
    K = glacier.K

    for n in range(Nt-1):

        un_i = Un + dt*Udn + 0.5*(dt**2)*Uddn
        udn_i = Udn + dt*Uddn
        uddn_i = Uddn

        Ms_i = M + mk*K

        P_n = glacier.Fpertur(Fc[n]) + glacier.Fe(Un)
        P_nalpha = glacier.Fpertur(Fc[n+1]) + glacier.Fe(un_i)

        r_i = p_alpha*(P_n) + p_alpha1*(P_nalpha) - np.dot(M,uddn_i)
        delta_uddn_i = np.dot(np.linalg.inv(Ms_i),r_i)

        un_i1 = un_i + uiai*delta_uddn_i
        udn_i1 = udn_i + udiai*delta_uddn_i
        uddn_i1 = uddn_i + delta_uddn_i

        un_i1[-1] = 0

        i = 0

        while i<100 and np.max(np.abs(udn_i1 - udn_i))>eps :

            un_i = un_i1
            udn_i = udn_i1
            uddn_i = uddn_i1

            Ms_i = M + mk*K

            P_nalpha = glacier.Fpertur(Fc[n+1]) + glacier.Fe(un_i)

            r_i = p_alpha*(P_n) + p_alpha1*(P_nalpha) - np.dot(M,uddn_i)
            delta_uddn_i = np.dot(np.linalg.inv(Ms_i),r_i)

            un_i1 = un_i + uiai*delta_uddn_i
            udn_i1 = udn_i + udiai*delta_uddn_i
            uddn_i1 = uddn_i + delta_uddn_i

            un_i1[-1] = 0

            i +=1

        # state vector at n+1
        Un = un_i1
        Udn = udn_i1
        Uddn = uddn_i1

        Niter_implicite.append(i)

        # enregistrement des données pour affichage
        if n%Nt_r==0:
            print(n)

        Ut_plot.append( Un )
        Udt_plot.append( Udn )
        Uddt_plot.append( Uddn )

    return(np.array(Ut_plot), np.array(Udt_plot), np.array(Uddt_plot),np.array(Niter_implicite))


import os
import sys

from django.conf import settings

BASE_DIR = os.path.dirname(__file__)
DEBUG = os.environ.get('DEBUG', 'on') == 'on'
SECRET_KEY = os.environ.get('SECRET_KEY', '$!69dui-gry6r9ozn96%yt#21_dxyx!g=986dhulpf+m0q=pfz')

settings.configure(
    DEBUG=DEBUG,
    SECRET_KEY=SECRET_KEY,
    ROOT_URLCONF='sitebuilder.urls',
    MIDDLEWARE_CLASSES=(),
    INSTALLED_APPS=(
        'django.contrib.staticfiles',
        'django.contrib.admindocs',
        'sitebuilder',
    ),
    STATIC_URL='/static/',
    SITE_PAGES_DIRECTORY=os.path.join(BASE_DIR, 'pages')
)

if __name__ == "__main__":
    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)


from random import shuffle
import numpy as np

from os import system
cls = lambda: system("clear")

def rndBitLength(n, bl):
    if n <= 2**n:
        seq = [s for s in range(2**bl)]
        shuffle(seq)
        return seq[:n]
    return [0]

def dispDF(df):
    for d in df:
        print('\t', d, '\t', df[d])
    print('\n')

def bitmatch(sq):
    res = []
    for n in range(len(sq)-1):
        cell = []
        for d, f in zip(sq[n], sq[n+1]):
            x = d^f
            if(bin(x).count("1") == 1):
                cell.append((d, f))
        res.append(cell)
    return res

seq = lambda bl: [n for n in range(2**bl)]
#shuffle(seq)

sq4 = seq(4)
shuffle(sq4)
sq4n = np.array(sq4, dtype=int)

# blsort = {c:sq4n[[bin(n).count("1") == c for n in sq4n]] for c in range(max(seq.bit_length()))}

bitSort = lambda sq: {c:sq[[bin(n).count("1") == c for n in sq]] for c in range(int(max(sq)).bit_length()+1)}


def solution():
    n=int(input())
    arr=list(map(int,input().split()))
    judge=0
    for i in range(1,n-1):
        if arr[i]==max(arr[0:i+1]) and arr[i]==min(arr[i:len(arr)]):
            judge=1
            result=arr[i]
            break
        else:
            continue
    if judge==1:
        print(result)
    else:
        print(-1)

def main():
    T=int(input())
    for i in range(T):
        solution()

main()


from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from oneplayer.logic import *

# Logic for tic-tac-toe in logic.py
def home(request):
	return render(request,'index.html')

@csrf_exempt
def twoplayergame(request):
	if(request.method == 'POST'):
		board = request.POST.getlist('board[]')
		a = [[0 for x in range(3)] for x in range(3)]
		for i in range(3):
			for j in range(3):
				a[i][j] = int(board[3*i+j])
		s = valboard(a,1,2,1)
		n = valboard(a,1,2,2)
		if(s == 10):
			return JsonResponse({'res':1,'winner':1})
		elif(n == -10):
			return JsonResponse({'res':1,'winner':2})
		elif(checkdraw(a) == 1):
			return JsonResponse({'res':1,'winner':0})
		else:
			return JsonResponse({'res':0,'winner':10})
	else:
		return JsonResponse({'val':"error"})

@csrf_exempt
def oneplayergame(request):
	if(request.method == 'POST'):
		board = request.POST.getlist('board[]')
		diff = request.POST.get('diff')
		diff = int(diff)
		a = [[0 for x in range(3)] for x in range(3)]
		for i in range(3):
			for j in range(3):
				a[i][j] = int(board[3*i+j])
		s = valboard(a,1,2,2)                                                       # valboard(board, computer, player, turn)
		if(s == -10):
			return JsonResponse({'val':0,'res':1,'winner':'player'})
		elif(checkdraw(a) == 1):
			return JsonResponse({'val':0,'res':1,'winner':'draw'})
		mat = tictac(a,1,2,1,0,diff)														#  tictactoe(array, computer ,player ,turn, depth)
		xpos = mat[1]
		ypos = mat[2]
		a[xpos][ypos] = 1
		s = valboard(a,1,2,1)	                                                     # valboard(board, computer, player ,turn)
		if(s == 10):
			return JsonResponse({'val':xpos*3+ypos,'res':1,'winner':'comp'})
		elif(checkdraw(a) == 1):
			return JsonResponse({'val':xpos*3+ypos,'res':1,'winner':'draw'})
		return JsonResponse({'val':xpos*3+ypos,'res':0,'winner':'none'})
	else:
		return JsonResponse({'val':"error"})


"""
Вывести количество космонавтов в настоящий момент.
Можно вывести как минимум просто цифру с результатом. Можно добавить ещё
текст, описывающий смысл этой цифры.
При желании, можно также вывести дополнительную информацию.
Что явно запрещено, так это просто выводить полученный JSON. Нужно его
обработать, взять нужные данные и передать на вывод.
"""

import json

import requests

def get_astro():
    url = "http://api.open-notify.org/astros.json"
    response = requests.get(url)
    text_json = response.text
    ready_json = json.loads(text_json)

    return ready_json

if __name__ == "__main__":
    get_astro()


# Capture Regions on Board
# https://www.interviewbit.com/problems/capture-regions-on-board/
from collections import deque
class Solution:
    # @param A : list of list of chars
    ### Time Complexity is (n*n)
    ### Space complexity is O(n*n)
    def solve(self, A):
        def solveRange(A,row_range,col_range):
            for i in row_range:
                for j in col_range:
                    if A[i][j] == 'O':
                        q = deque()
                        q.append((i,j))
                        while q:
                            curr_i, curr_j = q.popleft()
                            A[curr_i][curr_j]='B'
                            if curr_i != 0 and A[curr_i-1][curr_j] =='O':
                                q.append((curr_i-1,curr_j))
                            if curr_i != len(A)-1 and  A[curr_i+1][curr_j]=='O' :
                                q.append((curr_i+1,curr_j))
                            if curr_j != 0 and A[curr_i][curr_j-1] =='O' :
                                q.append((curr_i,curr_j-1))
                            if curr_j != len(A[0])-1 and A[curr_i][curr_j+1] =='O':
                                q.append((curr_i,curr_j+1))

        rows,cols = len(A),len(A[0])
        solveRange(A,(0,rows-1),range(0,cols))
        solveRange(A,range(0,rows),(0,cols-1))
        for i in range (0, rows):
            for j in range (0,cols):
                if A[i][j] =='O': A[i][j]='X'
                elif  A[i][j] =='B': A[i][j]='O'


import sys
import os
import json
import pandas as pd
import matplotlib.pyplot as plt

exec(open('./../../perfline.conf').read())

class TaskInfo():
    METADATA_FILE = "perfline_metadata.json"
    RESULTS_FILE  = "s3bench_report.csv"
    def __init__(self, folder):
        self.folder = folder
        self.tid = None
        self.date = None
        self.motr = None
        self.s3server = None
        self.hare = None
        self.results = None

    def read(self):
        with open(os.path.join(self.folder, self.METADATA_FILE)) as f:
            data = json.load(f)
            self.date = data["enqueue_time"]
            self.motr = data["conf"]["custom_build"]["motr"]["branch"]
            self.s3server = data["conf"]["custom_build"]["s3server"]["branch"]
            self.hare = data["conf"]["custom_build"]["hare"]["branch"]
            self.tid = data["artifacts_dir"].split("_")[1]
            df = pd.read_csv(os.path.join(self.folder, "client", self.RESULTS_FILE))
            df = df[['numClients', 'objectSize (MB)', 'numSamples', 'Errors Count', 'Total Throughput (MB/s)', 'Errors Count.1', 'Total Throughput (MB/s).1']]
            df.rename(columns = {'Errors Count': 'Write Errors', 'Total Throughput (MB/s)': 'Write Throughput (MB/s)', 'Errors Count.1': 'Read Errors', 'Total Throughput (MB/s).1': 'Read Throughput (MB/s)'}, inplace=True)
            df['TID'] = self.tid
            df['motr'] = self.motr
            df['s3server'] = self.s3server
            df['hare'] = self.hare
            df['date'] = self.date
            self.results = df

    def get_results(self):
        return self.results

    def __str__(self):
        return "TID: {}, Date: {}, motr: {}, s3server: {}, hare: {}".format(
            self.tid, self.date, self.motr, self.s3server, self.hare)

def usage():
    use = """
fetch.py - Fetch build and performance data from list of tasks results.
Information is stored in default night-builds daemon artifacts in
form of bandwidth plots and json dumps.

Usage:
\tpython3 fetch.py "$list_of_tasks_results_dirs" main
\tpython3 fetch.py "$list_of_tasks_results_dirs" stable

for main and stable builds respectively.
    """
    print(use)

def plot_stable(df, filename, size, sessions):
    # TODO: Implement me!
    pass

def plot_main(df, filename, size, sessions):
    commit_domain = df[['motr', 's3server']].drop_duplicates()

    dots = []
    for _, row in commit_domain.iterrows():
        fd = df[(df['motr'] == row['motr']) & (df['s3server'] == row['s3server'])]
        writes = fd['Write Throughput (MB/s)'].tolist()
        reads = fd['Read Throughput (MB/s)'].tolist()

        dots.append({(str(row['motr']), str(row['s3server'])) : {'write': writes, 'read': reads}})

    plot = plt.figure(figsize=(16, 8))

    avgs_x = []
    avgs_write = []
    avgs_read = []
    for d in dots:
        x = next(iter(d))
        y1 = d[x]['write']
        y2 = d[x]['read']
        x = "motr {}\ns3 {}".format(x[0], x[1])

        plt.scatter([x]*len(y1), list(y1), color='red')
        plt.scatter([x]*len(y2), y2, color='green')

        avgs_x.append(x)
        avgs_write.append(sum(y1)/len(y1))
        avgs_read.append(sum(y2)/len(y2))

    plt.scatter(avgs_x, avgs_write, marker='X', color='black')
    plt.scatter(avgs_x, avgs_read, marker='X', color='black')

    plt.plot(avgs_x, avgs_write, color='red', label = 'Write')
    plt.plot(avgs_x, avgs_read, color='green', label = 'Read')

    plt.ylim(bottom=0.0)
    plt.xticks(rotation=45)
    plt.margins(0.5)
    plt.subplots_adjust(bottom=0.2)
    plt.grid()
    plt.title(f"Main branch throughput, {size}, {sessions} sessions")
    plt.ylabel("Throughput, MB/s")
    plt.xlabel("Motr, s3server commit IDs", fontsize=16)
    plt.legend()

    print("Will save to {}".format(filename))
    plt.savefig(filename)
    plt.close(plot)

def plot_img(df, build, filename, size, sessions):
    if build == "main":
        plot_main(df, filename, size, sessions)
    elif build == "stable":
        plot_stable(df, filename, size, sessions)

def main():
    if len(sys.argv) != 3:
        usage()
        exit(1)
    build = sys.argv[1]
    dirs = sys.argv[2].split()

    if build not in ["main", "stable"]:
        usage()
        exit(2)

    tasks = []
    for d in dirs:
        task = TaskInfo(d)
        task.read()
        tasks.append(task)

    df = pd.concat([t.get_results() for t in tasks])
    df.sort_values(by=["date"], inplace=True)

    for size in df['objectSize (MB)'].unique():
        for sessions in df['numClients'].unique():
            fd = df[(df['objectSize (MB)'] == size) & (df['numClients'] == sessions)][['date', 'TID', 'motr', 's3server', 'hare',
                                                                                'Write Errors', 'Write Throughput (MB/s)',
                                                                                'Read Errors', 'Read Throughput (MB/s)']]

            size_lookup = {
                "0.0009765625" : "1KB",
                "0.00390625"   : "4KB",
                "0.015625"     : "16KB",
                "0.0625"       : "64KB",
                "0.25"         : "256KB",
                "1.0"          : "1MB",
                "4.0"          : "4MB",
                "16.0"         : "16MB",
                "32.0"         : "32MB",
                "64.0"         : "64MB",
                "128.0"        : "128MB",
                "256.0"        : "256MB",
            }

            # Save json
            base = "_".join([size_lookup[str(size)], str(sessions)])
            filename = os.path.join(NIGHT_ARTIFACTS, build, "data", base + ".json")
            print("Will save to {}".format(filename))
            fd.to_json(filename, orient="split")

            # Save png
            filename = os.path.join(NIGHT_ARTIFACTS, build, "img", base + ".png")
            plot_img(fd, build, filename, size_lookup[str(size)], str(sessions))

if __name__=="__main__":
    main()


###############################################################################

"""
Django URLs for the checkout app
"""

###############################################################################

# IMPORTED RESOURCES #

# EXTERNAL:
from django.urls import path

# INTERNAL:
from . import views
from .webhooks import webhook

###############################################################################

# URLs resulting from the bag app
urlpatterns = [
    path('', views.checkout, name='checkout'),
    path('checkout_success/<order_number>',
         views.checkout_success, name='checkout_success'),
    path('cache_checkout_data/',
         views.cache_checkout_data, name='cache_checkout_data'),
    path('wh/', webhook, name='webhook'),
]


#! /usr/bin/env python3

import argparse
import numpy as np
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
import xarray as xr
import netCDF4 as nc
import os

def writeRstCICE(fileCICE, pathCICE, data, var, defaultExp):
   dsCICE=xr.open_dataset(pathCICE+'/'+fileCICE)
   if (var == "utic"):
       id_var="strwvx"
   elif (var == "vtic"):
       id_var="strwvy"
   elif (var == 'efreq'):
       id_var='efreq'
   else:
       print("Unknown WW3 variable")
#   data=np.ones((data.shape[0], data.shape[1]))*5
#   data1=np.zeros((data.shape[0], data.shape[1]))
   #Only zonal stress.
   if defaultExp == "wimgx3" or defaultExp == "wimgx1" or defaultExp == "wimtx1":
       if (id_var == 'strwvx'):
           dsCICE[id_var]=(['lat', 'lon'], data)
       elif (id_var == 'strwvy'):
           dsCICE[id_var]=(['lat', 'lon'], data)
       elif (id_var == 'efreq'):
           dsCICE[id_var]=(['f', 'lat', 'lon'], data)
   elif defaultExp == "wim2p5":
       if (id_var == 'strwvx'):
           dsCICE[id_var]=(['y', 'x'], data)
       elif (id_var == 'strwvy'):
           dsCICE[id_var]=(['y', 'x'], data)
       elif (id_var == 'efreq'):
           dsCICE[id_var]=(['f', 'y', 'x'], data)

   os.system("mv "+pathCICE+'/'+fileCICE+" "+pathCICE+"/temp")
   dsCICE.to_netcdf(pathCICE+'/'+fileCICE)
   print(id_var+" has been added to "+pathCICE+'/'+fileCICE)

def get_geomWW3(path, file, defaultExp):
    '''
    This function reads the ni, nj, tlat, and tlon variables from a netcdf file
    '''
    fid = nc.Dataset("{}/{}".format(path, file), 'r')
    if defaultExp == "wim2p5":
        tlat = fid.variables['y'][:]
        tlon = fid.variables['x'][:]
        ni = fid.dimensions['y'].size #ni is for lat, nj for lon
        nj = fid.dimensions['x'].size
    elif defaultExp == "wimgx3" or defaultExp == "wimgx1" or defaultExp == "wimtx1":
        tlat = fid.variables['latitude'][:]
        tlon = fid.variables['longitude'][:]
        ni = fid.dimensions['lon'].size #ni is for lat, nj for lon
        nj = fid.dimensions['lat'].size
    return nj, ni, tlat, tlon

def read_stressWW3(path_a, files_a, var, nj, ni):
    '''
    Read the baseline and test data for sea ice thickness.  The calculate
    the difference for all locations where sea ice thickness is greater
    than 0.01 meters.
    '''
    def fill_data_array(path, files, nj, ni):
        '''Function to fill the data arrays'''
        # Initialize the data array
        data = np.zeros((nj, ni),dtype=np.float32)
        # Read in the data
        fname=files[0]
        nfid = nc.Dataset("{}/{}".format(path, fname), 'r')
        fill_value = nfid.variables[var]._FillValue
        data[:, :] = nfid.variables[var][:]
        nfid.close()
        data[data == fill_value] = 0.0

        return data

    data_a = fill_data_array(path_a, files_a, nj, ni)

    return data_a

def read_specWW3(path_a, files_a, var, nj, ni, nf):
    '''
    Read the baseline and test data for sea ice thickness.  The calculate
    the difference for all locations where sea ice thickness is greater
    than 0.01 meters.
    '''
    def fill_data_array(path, files, nj, ni):
        '''Function to fill the data arrays'''
        # Initialize the data array
        data = np.zeros((nf, nj, ni),dtype=np.float32)
        # Read in the data
        fname=files[0]
        nfid = nc.Dataset("{}/{}".format(path, fname), 'r')
        fill_value = nfid.variables[var]._FillValue
        data[:, :, :] = nfid.variables[var][:]
        nfid.close()
        data[data == fill_value] = 0.0

        return data

    data_a = fill_data_array(path_a, files_a, nj, ni)

    return data_a

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("case", help="Name of the case (e.g. case01).")
    parser.add_argument("repOutW3", help="Path for WW3 output file.")
    parser.add_argument("fileOutW3", help="Name of WW3 output file.")
    parser.add_argument("repRstCI", help="Path for CICE restart file.")
    parser.add_argument("fileRstCI", help="Path for CICE restart file.")
    parser.add_argument("defaultExp", help="wim2p5, wimgx3, wimgx1, wimtx1")
    args = parser.parse_args()

    #Define variables
    case=args.case
    repOutW3=args.repOutW3
    repRstCI=args.repRstCI
    defaultExp=args.defaultExp
    fileOutW3=args.fileOutW3
    fileRstCI=args.fileRstCI
    nlon, nlat, t_lat, t_lon = get_geomWW3(repOutW3, fileOutW3, defaultExp)
#    listVar=['utic', 'vtic', 'efreq']
    listVar=['utic', 'vtic']
 #   fileOutSpec="ww3.2005-01-01-03600_efreq.nc"
 #   fileOutW3="ww3.2005-01-01-03600.nc"
    fileOutSpec=fileOutW3[:-3]+"_efreq.nc"
    print("File :"+repOutW3+"/"+fileOutW3+" is read")
    for var in listVar:
       if var == 'efreq':
#          varWW3=read_specWW3(repOutW3, ['ww3.2005-01-01-07200_efreq.nc'], var, nlon, nlat, 20)
           varWW3=read_specWW3(repOutW3, [fileOutSpec], var, nlon, nlat, 20)
       else:
           varWW3=read_stressWW3(repOutW3, [fileOutW3], var, nlon, nlat)
       writeRstCICE(fileRstCI, repRstCI, varWW3, var, defaultExp)
#Call main
if __name__ == "__main__":
    main()


#Pedir dos nombres y edades respectivas y luego construir una sola cadena con un texto que muestre el nombre #del mayor y cuanto le lleva al menor.
#(Ejemplo:  entrada -> 'Juan' 30 'Pedro' 23 / salida -> 'Juan le lleva 7 años a Pedro')

lista_nombres = []
lista_edades = []

for i in range(2):
    nombre = input("Ingrese nombre: ")
    edad = int(input("Ingrese edad de "+ nombre +":"))
    lista_nombres.append(nombre)
    lista_edades.append(edad)

# mayor=0
# for i in lista_edades:
#     if lista_edades[i] > mayor:
#         mayor = lista_edades[i]
lista_edades.sort()

diferencia = lista_edades[1] - lista_edades[0]

print(lista_nombres[0] + " le lleva " + str(diferencia) + " años a " + lista_nombres[1])


#!/usr/bin/env python
# -*- coding: utf-8 name> -*-

"""This script animates a GIF image, from the web, in text art."""

from io import BytesIO
import time

from PIL import Image
from picharsso import new_drawer
from picharsso.utils import clear_screen, terminal_size

import requests

if __name__ == "__main__":
    # Set URL of image
    image_url = "https://bit.ly/3hs2Vxr"

    # Open Image from respose content
    response = requests.get(image_url)
    image = Image.open(BytesIO(response.content))

    # Get terminal height
    height, _ = terminal_size()

    # Choose an art style
    style = "gradient"  # or "braille"

    # Define drawer
    drawer = new_drawer(style, height=height, colorize=True)

    # Iterate over frames
    texts = []
    for frame_id in range(image.n_frames):
        # Select frame
        image.seek(frame_id)

        # Save output for frame
        texts.append(drawer(image))

    # Iterate over saved outputs in a circular manner
    num_frames = len(texts)
    counter = 0
    while True:
        # Refresh
        clear_screen()

        # Print output
        print(texts[counter])

        # Set a delay between frames
        time.sleep(1 / num_frames)

        # Circular increment
        counter = (counter + 1) % num_frames


import argparse

import pandas as pd
import torch
from torch_geometric.loader import DataLoader

from benchmark import UnlabeledData, Descriptors
from models import squeeze_if_needed, get_model

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('config', type=str, default='./configs/ace.yml')
    parser.add_argument('--data', metavar='DATA', type=str, default='CHEMBL214_Ki')
    parser.add_argument('--model', metavar='MODEL', type=str, default='GIN', choices=['MPNN', 'GAT', 'GCN', 'GIN'])

    parser.add_argument('--target_path', type=str, default='./CHEMBL_214')   # ./250k_zinc
    parser.add_argument('--model_path', type=str, default='./results/GIN_CHEMBL214_Ki_best_0.pt')
    args = parser.parse_args()
    algorithm = get_model(args.model)
    ckpt = torch.load(args.model_path)
    config = ckpt['config']

    target_data = UnlabeledData(args.target_path, size_limit=-1)
    if target_data.x is None:
        target_data(Descriptors.GRAPH, save_mode=False)
    x_target = target_data.x
    loader = DataLoader(x_target, batch_size=config.train.batch + 1 if len(x_target) % config.train.batch == 1 else config.train.batch, shuffle=False)
    print(f'Model weight: {args.model_path} | Unlabeled Size: {len(x_target)}')

    algorithm = get_model(args.model)

    model = algorithm(mean=ckpt['mean'], mad=ckpt['mad'], config=config, **config.model)
    model.model.load_state_dict(ckpt['model'])
    model.critic.load_state_dict(ckpt['critic'])

    y_pred, p_pred = [], []
    model.model.eval()
    model.critic.eval()
    with torch.no_grad():
        for batch in loader:
            batch.to(model.device)
            y_hat = model.model(batch.x.float(), batch.edge_index, batch.edge_attr.float(), batch.batch).detach() * ckpt['mad'] + ckpt['mean']

            # assume some sort of loss
            p = model.critic(batch.x.float(), batch.edge_index, batch.edge_attr.float(), batch.batch, y_hat.detach().clone(), torch.ones_like(y_hat).squeeze(-1))

            y_hat = squeeze_if_needed(y_hat).tolist()
            p = squeeze_if_needed(p).tolist()
            if type(y_hat) is list:
                y_pred.extend(y_hat)
            else:
                y_pred.append(y_hat)
            if type(p) is list:
                p_pred.extend(p)
            else:
                p_pred.append(p)

    df = pd.DataFrame({'smiles': target_data.smiles, 'Ki': [10 ** (-x) / 5 for x in y_pred], 'confidence': p_pred})  #
    df.to_csv(f'./{args.target_path}_inference.csv')


#!/usr/bin/python3
# Copyright (c) 2022 Innodisk Crop.
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT

import os
import argparse
import time
import numpy as np
import queue
import logging
import datetime
import sys

from mod.predictor import PREDICTOR
from mod.util import open_json

DISPLAY_CARD_PATH = '/dev/dri/by-path/platform-fd4a0000.zynqmp-display-card'

version = "1.0.0"
date = datetime.date.today()

CFG     = 'config.json'
DISPLAY = "DISPLAY"
WIDTH   = "WIDTH"
HEIGHT  = "HEIGHT"
divider = '------------------------------------'

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('-c', '--camera', type=str, help='Camera type, default is /dev/video0')
    ap.add_argument('-i', '--image' , type=str, help='Path to a image which you would like to inference.')
    ap.add_argument('-t', '--target', type=str, help='Output type, default is dp')
    ap.add_argument('-v', '--video' , type=str, help='Path to a video which you would like to inference.')
    ap.add_argument('-x', '--xmodel', type=str, default='yolo', help='Type of xmodel, default is yolo')
    ap.add_argument('-l', '--lpr'   , type=str, help='Enable LPR mode. This is base on yolo object detection.')

    args = ap.parse_args()
    cfg = open_json(CFG)
    pred = PREDICTOR(args, cfg)

    logging.basicConfig(level=logging.INFO)

    logging.info(divider)
    logging.info(" Command line options:")
    logging.info(" Version: {}".format(version))
    logging.info(" Date:    {}".format(date))

    ''' Select Input '''
    # if args.camera == 'g4':
    #     logging.info(' --input     : {}'.format('g4'))
    #     pred.get_frame = pred.g4cam_get

    if args.camera:
        if (args.camera.isdigit()):
            logging.info(' --input     : {}'.format('web-cam'))
            pred.get_frame = pred.cam_get

        else:
            print("string, please input digital number")
            return

    elif args.image:
        if os.path.isfile(args.image):
            logging.info(' --input     : {}'.format('image'))
            pred.get_frame = pred.image_get

        else:
            print("Could not find the file {}.".format(args.image))
            return

    elif args.video:
        if os.path.isfile(args.video):
            logging.info(' --input     : {}'.format('video'))
            pred.get_frame = pred.video_get

        else:
            print("Could not find the file {}.".format(args.image))
            return

    ''' Select Xmodel '''
    if args.xmodel == 'cnn':
        logging.info(' --model     : {}'.format('cnn'))
        pred.init_model = pred.init_cnn
        pred.run_model = pred.run_cnn

    else:
        logging.info(' --model     : {}'.format('yolo'))
        pred.init_model = pred.init_yolo

        if args.lpr:
            logging.info(' --lpr     : {}'.format('enable'))
            pred.run_model = pred.run_yolo_lpr
        else:
            pred.run_model = pred.run_yolo

    ''' Select Output '''
    if args.target == 'dp':
        if not os.path.exists(DISPLAY_CARD_PATH):
            logging.info('Error: zynqmp-display device is not ready.')
            return

        ''' Resolution check '''
        width = int(pred.cfg[DISPLAY][WIDTH])
        height = int(pred.cfg[DISPLAY][HEIGHT])

        resolution = "{}x{}".format(width, height)
        all_res = os.popen("modetest -M xlnx -c| awk '/name refresh/ {f=1;next}  /props:/{f=0;} f{print $1 \"@\" $2}'").read()

        if all_res.find(resolution) == -1:
            os.environ["DISPLAY"] = ":0"

        logging.info(' --output    : {}'.format('dp'))
        pred.output = pred.dp_out

    elif args.target == 'image':
        logging.info(' --output    : {}'.format('image'))
        pred.output = pred.image_out

    elif args.target == 'video':
        logging.info(' --output    : {}'.format('video'))
        pred.output = pred.video_out

    pred.predict()

if __name__ == '__main__':
    main()


#!/usr/bin/env python
import requests
import httplib2
import base64
import datetime
import os
import cronus.beat as beat
from cronus.timeout import timeout,TimeoutError
import ssl
import json
import sys
import logging
import time
import getopt
import thingspeak

def getSecret(name):
    path = 'run/secrets/' + name
    with open(path, 'r') as f:
        secret = f.readline()
    return secret.rstrip()

#@timeout(10)
def getSensorValue(IP):
    try:
        logger.info("Sending http request to arduino")
        response = requests.get("http://" + IP + "/")
    except requests.exceptions.RequestException as e:
        logger.error("Failed to get request from arduino: %s",e)
        return None
    else:
        logger.info("Got response from arduino")
        logger.debug("Response received: %s",response.json())
        return response
    ##    sys.exit()

#@timeout(3)
def formatMessage(arduinoResponse,api_key):
    resp = arduinoResponse.json()
    humidity = resp['variables']['humidity']
    logger.debug("Collected humidity value: %s",str(humidity))
    #message1 = base64.b64encode(str(humidity))
    data = {}
    data['api_key'] = api_key
    data['field1'] = humidity
    return data

if __name__ == "__main__":

    # Configure logging
    logger = logging.getLogger("humidityReader")
    logger.setLevel(logging.DEBUG)
    streamHandler = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    streamHandler.setFormatter(formatter)
    logger.addHandler(streamHandler)
    logger.debug("Logger initialized")

    arduinoIP = getSecret("arduino1")
    api_key = getSecret("THINGSPEAK_API_KEY")
    channel_id = getSecret("THINGSPEAK_CHANNEL_ID")
    channel = thingspeak.Channel(channel_id,'api_key={api}'.format(api=api_key))

    beat.set_rate(0.016666667)

    # Publish to the same topic in a loop forever
    while beat.true():
#    while True:
        try:
            humidity = getSensorValue(arduinoIP)
        except TimeoutError:
            pass
            logger.error("Timeout error reading arduino humidity sensor")
        else:
            logger.debug("Trying to send humidity to ThingSpeak")
            channel.update(formatMessage(humidity,api_key))
        beat.sleep()


#encoding:utf8
__author__ = 'gold'

'''
416. Partition Equal Subset Sum

Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

Note:
Each of the array element will not exceed 100.
The array size will not exceed 200.
Example 1:

Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:

Input: [1, 2, 3, 5]

Output: false

Explanation: The array cannot be partitioned into equal sum subsets.
'''

class Solution:
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums) <= 1:
            return False

        totalSum = sum(nums)
        half = totalSum // 2
        if half * 2 != totalSum:
            return False

        nums.sort(reverse = True)
        if half < nums[0]:
            return False
        if half == nums[0]:
            return True

        remainder = half - nums[0]
        for index in range(1,len(nums)):
            if remainder < nums[index]:
                continue
            if self.__helper(nums,remainder,index):
                return True

        return False

    def __helper(self,nums,remainder,index):
        if index == len(nums):
            return False

        if remainder == nums[index]:
            return True

        if remainder < nums[index]:
            return False

        result = False
        remainder -= nums[index]
        for j in range(index + 1,len(nums)):
            if remainder == nums[j]:
                return True
            if remainder < nums[j]:
                continue
            result = self.__helper(nums,remainder - nums[j],j + 1)
            if result:
                break

        return result

if __name__ == '__main__':
    print(Solution().canPartition([1, 5, 11, 5]))
    print(Solution().canPartition([1, 2, 3, 5]))
    print(Solution().canPartition([3,3,3,4,5]))
    print(Solution().canPartition([1,3,4,4]))
    print(Solution().canPartition([99,2,3,98]))


import copy
import time
from abc import abstractmethod
from queue import Empty

import cv2
import numpy as np
import torch
from PIL import ImageFont, Image, ImageDraw
from PyQt5.QtGui import QPixmap, QImage

from model.core.base_module import BaseModule, TASK_DATA_OK, DictData
from utils.vis import draw_keypoints136

box_color = (0, 255, 0)  #
cheating_box_color = (0, 0, 255)
draw_keypoints_default = False

# 绘制图片
def draw_frame(data, draw_keypoints=draw_keypoints_default, fps=-1):
    frame = data.frame.copy()  # 图片赋值给frame
    pred = data.detections  # 将data中处理后的数据赋值给pred
    preds_kps = data.keypoints  # 将data中的关键点赋值给preds_kps
    preds_scores = data.keypoints_scores  # 将data中的关键点成绩赋值给preds_scores
    if pred.shape[0] > 0:
        # 绘制骨骼关键点
        if draw_keypoints and preds_kps is not None:
            draw_keypoints136(frame, preds_kps, preds_scores)
        # 绘制目标检测框和动作分类
        frame_pil = Image.fromarray(frame)
        draw = ImageDraw.Draw(frame_pil)
        for det, class_prob, best_pred in zip(pred, data.classes_probs, data.best_preds):
            det = det.to(torch.int)  # 转换类型
            class_name = data.classes_names[best_pred]  # 选择类名
            show_text = f"{class_name}"  # 设置要展示的类名
            show_color = box_color if best_pred == 0 else cheating_box_color  # 设置要展示颜色
            draw.rectangle((det[0], det[1], det[2], det[3]), outline=show_color, width=2)  # 绘制矩形
            # 文字
            fontText = ImageFont.truetype("resource/font/NotoSansCJKkr-Black.otf",
                                          int(40 * (min(det[2] - det[0], det[3] - det[1])) / 200),
                                          encoding="utf-8")  # 加载文字
            draw.text((det[0], det[1]), show_text, show_color, font=fontText)  # 在给定位置绘制字符串
        frame = np.asarray(frame_pil)
        # 头部姿态估计轴
        for (r, t) in data.head_pose:
            data.draw_axis(frame, r, t)
    # 绘制fps
    cv2.putText(frame, "FPS: %.2f" % fps, (0, 52), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 255))
    data.frame_anno = frame  # 保存绘制过的图像

# 绘制模块
class DrawModule(BaseModule):
    def __init__(self):
        super(DrawModule, self).__init__()
        self.last_time = time.time()  # 最终时间

    def process_data(self, data):
        # 数据预处理
        print("显示图片")
        current_time = time.time()  # 当前时间
        fps = 1 / (current_time - self.last_time)  # fps计算
        frame = data.frame  # 框
        pred = data.detections
        preds_kps = data.keypoints
        preds_scores = data.keypoints_scores
        for det in pred:
            show_text = "person: %.2f" % det[4]
            cv2.rectangle(frame, (det[0], det[1]), (det[2], det[3]), box_color, 2)  # 绘制矩形
            cv2.putText(frame, show_text,  # 绘制文字
                        (det[0], det[1]),
                        cv2.FONT_HERSHEY_COMPLEX,
                        float((det[2] - det[0]) / 200),
                        box_color)
        if preds_kps is not None:
            draw_keypoints136(frame, preds_kps, preds_scores)
        # 记录fps
        cv2.putText(frame, "FPS: %.2f" % fps, (0, 52), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 255))
        # 显示图像
        cv2.imshow("yolov5", frame)
        cv2.waitKey(40)
        self.last_time = current_time
        return TASK_DATA_OK

    def open(self):
        super(DrawModule, self).open()
        pass

# 保存模块
class FrameDataSaveModule(BaseModule):
    def __init__(self, app):
        super(FrameDataSaveModule, self).__init__()
        self.last_time = time.time()
        self.app = app

    def process_data(self, data):
        current_time = time.time()
        fps = 1 / (current_time - self.last_time)
        frame = data.frame
        pred = data.detections
        preds_kps = data.keypoints
        preds_scores = data.keypoints_scores
        for det in pred:
            show_text = "person: %.2f" % det[4]
            cv2.rectangle(frame, (det[0], det[1]), (det[2], det[3]), box_color, 2)
            cv2.putText(frame, show_text,
                        (det[0], det[1]),
                        cv2.FONT_HERSHEY_COMPLEX,
                        float((det[2] - det[0]) / 200),
                        box_color)
        if preds_kps is not None:
            draw_keypoints136(frame, preds_kps, preds_scores)
        # 记录fps
        cv2.putText(frame, "FPS: %.2f" % fps, (0, 52), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 255))
        self.app.video_screen.setPixmap(self.cvImg2qtPixmap(frame))
        time.sleep(0.04)
        self.last_time = current_time
        return TASK_DATA_OK

    @staticmethod
    def cvImg2qtPixmap(frame):
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        image_height, image_width, image_depth = frame.shape
        frame = QImage(frame.data, image_width, image_height,  # 创建QImage格式的图像，并读入图像信息
                       image_width * image_depth,
                       QImage.Format_RGB888)
        return QPixmap.fromImage(frame)

    def open(self):
        super(FrameDataSaveModule, self).open()
        pass

# 数据传输模块
class DataDealerModule(BaseModule):
    def __init__(self, push_frame_func, interval=0.06, skippable=False):
        super(DataDealerModule, self).__init__(skippable=skippable)
        self.last_time = time.time()
        self.push_frame_func = push_frame_func
        self.last_data = None
        self.interval = interval  # 间隔
        self.size_waiting = True
        self.queue_threshold = 10  # 队列的阈值

    # 跳过大量数据
    @abstractmethod
    def deal_skipped_data(self, data: DictData, last_data: DictData) -> DictData:
        pass

    # 绘制框
    @abstractmethod
    def draw_frame(self, data, fps):
        pass

    # 数据预处理
    def process_data(self, data):
        # hasattr() 函数用于判断对象是否包含对应的属性。
        if hasattr(data, 'skipped') and self.last_data is not None:
            data = self.deal_skipped_data(data, copy.copy(self.last_data))
        else:
            self.last_data = data
        current_time = time.time()
        interval = (current_time - self.last_time)
        fps = 1 / interval
        data.fps = fps
        self.draw_frame(data, fps=fps)
        data.interval = interval
        self.last_time = current_time  # 更新时间
        self.push_frame_func(data)
        if hasattr(data, 'source_fps'):
            time.sleep(1 / data.source_fps * (1 + self.self_balance_factor()))
        else:
            time.sleep(self.interval)
        return TASK_DATA_OK

    # 平衡因子
    def self_balance_factor(self):
        factor = max(-0.999, (self.queue.qsize() / 20 - 0.5) / -0.5)
        # print(factor)
        return factor

    # 产生工作数据
    def product_task_data(self):
        # print(self.queue.qsize(), self.size_waiting)
        if self.queue.qsize() == 0:
            self.size_waiting = True
        if self.queue.qsize() > self.queue_threshold or not self.size_waiting:
            self.size_waiting = False
            try:
                task_data = self.queue.get(block=True, timeout=1)
                return task_data
            except Empty:
                return self.ignore_task_data
        else:
            time.sleep(1)
            return self.ignore_task_data

    # 存入工作数据
    def put_task_data(self, task_data):
        self.queue.put(task_data)

    # 打开
    def open(self):
        super(DataDealerModule, self).open()
        pass

# 作弊检测模块
class CheatingDetectionVisModule(DataDealerModule):

    def __init__(self, push_frame_func, interval=0.06, skippable=False):
        super(CheatingDetectionVisModule, self).__init__(push_frame_func, interval, skippable)

    # 跳过大量数据
    def deal_skipped_data(self, data: DictData, last_data: DictData) -> DictData:
        frame = data.frame  # 帧图片
        data = last_data  # 最终数据
        data.skipped = None  # 跳过
        data.frame = frame  # 帧图片
        # 返回一个和源张量同shape、dtype和device的张量，与源张量不共享数据内存，但提供梯度的回溯
        data.detections = data.detections.clone()
        # 添加抖动 返回一个张量，其大小与填充区间上均匀分布的随机数的张量相同
        data.detections[:, :4] += torch.rand_like(data.detections[:, :4]) * 3
        return data

    # 绘制框
    def draw_frame(self, data, fps):
        draw_frame(data, fps=fps)


ARR = list(map(int, input().split()))
result = set()
import sys
sys.setrecursionlimit(10000000)
def calculate(arr):
    dfs(arr[0], 0, 1, arr, 3)
    dfs(0, 0, 0, arr, 3)

    print(sorted(result, key=lambda x: -x)[2])

def dfs(currentSum, currentIndex, currentK, arr, maxK):
    if currentK == maxK:
        result.add(currentSum)
        return

    if currentIndex == (len(arr) - 1):
        return

    dfs(currentSum + arr[currentIndex + 1], currentIndex + 1, currentK + 1, arr, maxK)
    dfs(currentSum, currentIndex + 1, currentK, arr, maxK)

calculate(ARR)


import pymysql

# 打开数据库连接
db = pymysql.connect("rdsd51v1a87ixlc6uu5uo.mysql.rds.aliyuncs.com","db_mamahao_root","db_mamahao_pwd_123987","db_gd" )

# 使用cursor()方法获取操作游标
cursor = db.cursor()

fileheader='/Users/wangguannan/Downloads/单据明细'
ID="MMH2018103110000395"

header="单据编号,商品货号,商品条码,商品名称,规格,剩余库存,申请调货数量,同意调货数量"
# SQL 查询语句
sql = "SELECT id AS '单据编号',style_code AS '商品货号',barcode AS '商品条码',style_title AS '商品名称',one_value AS '规格'," \
      "p_qty AS '剩余库存',apply_from_num AS '申请调货数量' ,from_num as '同意调货数量'FROM u_stock_log_detail WHERE id = '"+ID+"'";

data=header+"\n"
try:
    # 执行SQL语句
    cursor.execute(sql)
    # 获取所有记录列表
    results = cursor.fetchall()
    for row in results:
        row=list(row)
        for j in range(len(row)):
            row[j]=str(row[j]).replace("\"","\\\"")
        data+=",".join(row)+"\n"
        print(row)
except:
    print ("Error: unable to fetch data")

# 关闭数据库连接
db.close()

fp = open(fileheader+ID+".csv",'w')
fp.write(data)
fp.close()


#!/usr/bin/env python3

points = set([])

# read data

for y, line in enumerate(open('input.txt')):
    for x, c in enumerate(line):
        if c == "#": points.add( (x,y) )

cnt = 0

# 0 - north 1 -south 2- west 3 - east

moves = [ (0,-1), (0,1), (-1,0), (1,0)]

rounds = 0

while True:

    rounds += 1

    proposals = {}

    for p in points:
        x, y = p
        d = [False for i in range(4)]
        # check north
        d[0] = (x-1, y-1) in points or (x, y-1) in points or (x+1, y-1) in points
        # check south
        d[1] = (x-1, y+1) in points or (x, y+1) in points or (x+1, y+1) in points
        # check west
        d[2] = (x-1, y-1) in points or (x-1, y) in points or (x-1, y+1) in points
        # check east
        d[3] = (x+1, y-1) in points or (x+1, y) in points or (x+1, y+1) in points

        if not any(d):
            # no neightbors
            continue

        for i in range(4):
            s = (cnt + i) % 4
            if not d[s]:
                new_p = ( x + moves[s][0], y + moves[s][1] )
                if not new_p in proposals:
                    proposals[new_p] = [p]
                else:
                    proposals[new_p].append(p)
                break

    nomoves = True
    # process proposals
    for p in proposals:
        if len(proposals[p]) == 1:
            points.add(p)
            points.remove(proposals[p][0])
            nomoves = False

    if nomoves: break

    cnt = (cnt + 1) % 4

# count empty squares
print(rounds)


from sqlite3 import connect
from contextlib import contextmanager
from student import Student

""" with connect('testfiles/school.db') as conn:
    # creating a cursor object - read about cursor ????
    cur = conn.cursor()
    cur.execute('CREATE TABLE IF NOT EXISTS students(id int PRIMARY KEY, name text, cpr text)')
    cur.execute('INSERT INTO students(id, name, cpr) VALUES (1, "Claus", "223344-5566")')
    cur.execute('INSERT INTO students(id, name, cpr) VALUES (2, "Julie", "111111-1111")')
    cur.execute('INSERT INTO students(id, name, cpr) VALUES (3, "Hannah", "222222-2222")')

    for i in cur.execute('SELECT * FROM students'):
        print(i)

    cur.execute('DROP TABLE students')
 """

@contextmanager
def write_to_db(path):
        connection = connect(path)
        cursor = connection.cursor()
        cursor.execute('CREATE TABLE IF NOT EXISTS students(id int PRIMARY KEY, name text, cpr text)')
        yield connection

        cursor.execute('DROP TABLE students')
        connection.close()

students = [Student(1, 'Bob', 'CPR123'), Student(2, 'B', 'CPR123'), Student(3, 'C', 'CPR123')]

with write_to_db('./testfiles/schoo.db') as connection:
    cursor = connection.cursor()
    for student in students:
            cursor.execute(f'INSERT INTO students(id, name, cpr) VALUES ({student.id}, "{student.name}", "{student.cpr}")')

    for i in cursor.execute('SELECT * FROM students'):
        print(i)


import math

buckets = int(input())
minutesToDie = int(input())
minutesToTest = int(input())
time = math.floor(minutesToTest / minutesToDie)
time_valid = time + 1
i = 0
while pow(time_valid, i) < buckets:
    i = i + 1
print(i)


"""Permutation test function as described in CellPhoneDB 2.0."""
from __future__ import annotations

from abc import ABC
from collections import namedtuple
from functools import partial
from itertools import product
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Iterable, Literal, Mapping, Sequence, Union

import numpy as np
import pandas as pd
from anndata import AnnData
from numba import njit, prange  # noqa: F401
from scanpy import logging as logg
from scipy.sparse import csc_matrix
from spatialdata import SpatialData

from squidpy._constants._constants import ComplexPolicy, CorrAxis
from squidpy._constants._pkg_constants import Key
from squidpy._docs import d, inject_docs
from squidpy._utils import NDArrayA, Signal, SigQueue, _get_n_cores, parallelize
from squidpy.gr._utils import (
    _assert_categorical_obs,
    _assert_positive,
    _check_tuple_needles,
    _create_sparse_df,
    _genesymbols,
    _save_data,
)

__all__ = ["ligrec", "PermutationTest"]

StrSeq = Sequence[str]
SeqTuple = Sequence[tuple[str, str]]
Interaction_t = Union[pd.DataFrame, Mapping[str, StrSeq], StrSeq, tuple[StrSeq, StrSeq], SeqTuple]
Cluster_t = Union[StrSeq, tuple[StrSeq, StrSeq], SeqTuple]

SOURCE = "source"
TARGET = "target"

TempResult = namedtuple("TempResult", ["means", "pvalues"])

_template = """
@njit(parallel={parallel}, cache=False, fastmath=False)
def _test_{n_cls}_{ret_means}_{parallel}(
    interactions: NDArrayA,  # [np.uint32],
    interaction_clusters: NDArrayA,  # [np.uint32],
    data: NDArrayA,  # [np.float64],
    clustering: NDArrayA,  # [np.uint32],
    mean: NDArrayA,  # [np.float64],
    mask: NDArrayA,  # [np.bool_],
    res: NDArrayA,  # [np.float64],
    {args}
) -> None:

    {init}
    {loop}
    {finalize}

    for i in prange(len(interactions)):
        rec, lig = interactions[i]
        for j in prange(len(interaction_clusters)):
            c1, c2 = interaction_clusters[j]
            m1, m2 = mean[rec, c1], mean[lig, c2]

            if np.isnan(res[i, j]):
                continue

            if m1 > 0 and m2 > 0:
                {set_means}
                if mask[rec, c1] and mask[lig, c2]:
                    # both rec, lig are sufficiently expressed in c1, c2
                    res[i, j] += (groups[c1, rec] + groups[c2, lig]) > (m1 + m2)
                else:
                    res[i, j] = np.nan
            else:
                # res_means is initialized with 0s
                res[i, j] = np.nan
"""

def _create_template(n_cls: int, return_means: bool = False, parallel: bool = True) -> str:
    if n_cls <= 0:
        raise ValueError(f"Expected number of clusters to be positive, found `{n_cls}`.")

    rng = range(n_cls)
    init = "".join(
        f"""
    g{i} = np.zeros((data.shape[1],), dtype=np.float64); s{i} = 0"""
        for i in rng
    )

    loop_body = """
        if cl == 0:
            g0 += data[row]
            s0 += 1"""
    loop_body = loop_body + "".join(
        f"""
        elif cl == {i}:
            g{i} += data[row]
            s{i} += 1"""
        for i in range(1, n_cls)
    )
    loop = f"""
    for row in prange(data.shape[0]):
        cl = clustering[row]
        {loop_body}
        else:
            assert False, "Unhandled case."
    """
    finalize = ", ".join(f"g{i} / s{i}" for i in rng)
    finalize = f"groups = np.stack(({finalize}))"

    if return_means:
        args = "res_means: NDArrayA,  # [np.float64]"
        set_means = "res_means[i, j] = (m1 + m2) / 2.0"
    else:
        args = set_means = ""

    return _template.format(
        n_cls=n_cls,
        parallel=bool(parallel),
        ret_means=int(return_means),
        args=args,
        init=init,
        loop=loop,
        finalize=finalize,
        set_means=set_means,
    )

def _fdr_correct(
    pvals: pd.DataFrame,
    corr_method: str,
    corr_axis: Literal["interactions", "clusters"] | CorrAxis,
    alpha: float = 0.05,
) -> pd.DataFrame:
    """Correct p-values for FDR along specific axis in ``pvals``."""
    from pandas.core.arrays.sparse import SparseArray
    from statsmodels.stats.multitest import multipletests

    def fdr(pvals: pd.Series) -> SparseArray:
        _, qvals, _, _ = multipletests(
            np.nan_to_num(pvals.values, copy=True, nan=1.0),
            method=corr_method,
            alpha=alpha,
            is_sorted=False,
            returnsorted=False,
        )
        qvals[np.isnan(pvals.values)] = np.nan

        return SparseArray(qvals, dtype=qvals.dtype, fill_value=np.nan)

    corr_axis = CorrAxis(corr_axis)

    if corr_axis == CorrAxis.CLUSTERS:
        # clusters are in columns
        pvals = pvals.apply(fdr)
    elif corr_axis == CorrAxis.INTERACTIONS:
        pvals = pvals.T.apply(fdr).T
    else:
        raise NotImplementedError(f"FDR correction for `{corr_axis}` is not implemented.")

    return pvals

@d.get_full_description(base="PT")
@d.get_sections(base="PT", sections=["Parameters"])
@d.dedent
class PermutationTestABC(ABC):
    """
    Class for receptor-ligand interaction testing.

    The expected workflow is::

        pt = PermutationTest(adata).prepare()
        res = pt.test("clusters")

    Parameters
    ----------
    %(adata)s
    use_raw
        Whether to access :attr:`anndata.AnnData.raw`.
    """

    def __init__(self, adata: AnnData, use_raw: bool = True):
        if not isinstance(adata, AnnData):
            raise TypeError(f"Expected `adata` to be of type `anndata.AnnData`, found `{type(adata).__name__}`.")
        if not adata.n_obs:
            raise ValueError("No cells are in `adata.obs_names`.")
        if not adata.n_vars:
            raise ValueError("No genes are in `adata.var_names`.")

        self._adata = adata
        if use_raw:
            if adata.raw is None:
                raise AttributeError("No `.raw` attribute found. Try specifying `use_raw=False`.")
            if adata.raw.n_obs != adata.n_obs:
                raise ValueError(f"Expected `{adata.n_obs}` cells in `.raw` object, found `{adata.raw.n_obs}`.")
            adata = adata.raw

        self._data = pd.DataFrame.sparse.from_spmatrix(
            csc_matrix(adata.X), index=adata.obs_names, columns=adata.var_names
        )

        self._interactions: pd.DataFrame | None = None
        self._filtered_data: pd.DataFrame | None = None

    @d.get_full_description(base="PT_prepare")
    @d.get_sections(base="PT_prepare", sections=["Parameters", "Returns"])
    @inject_docs(src=SOURCE, tgt=TARGET, cp=ComplexPolicy)
    def prepare(
        self, interactions: Interaction_t, complex_policy: Literal["min", "all"] | ComplexPolicy = ComplexPolicy.MIN.v
    ) -> PermutationTestABC:
        """
        Prepare self for running the permutation test.

        Parameters
        ----------
        interactions
            Interaction to test. The type can be one of:

                - :class:`pandas.DataFrame` - must contain at least 2 columns named `{src!r}` and `{tgt!r}`.
                - :class:`dict` - dictionary with at least 2 keys named `{src!r}` and `{tgt!r}`.
                - :class:`typing.Sequence` - Either a sequence of :class:`str`, in which case all combinations are
                  produced, or a sequence of :class:`tuple` of 2 :class:`str` or a :class:`tuple` of 2 sequences.

            If `None`, the interactions are extracted from :mod:`omnipath`. Protein complexes can be specified by
            delimiting the components with `'_'`, such as `'alpha_beta_gamma'`.
        complex_policy
            Policy on how to handle complexes. Valid options are:

                - `{cp.MIN.s!r}` - select gene with the minimum average expression. This is the same as in
                  :cite:`cellphonedb`.
                - `{cp.ALL.s!r}` - select all possible combinations between `{src!r}` and `{tgt!r}` complexes.

        Returns
        -------
        Sets the following attributes and returns :attr:`self`:

            - :attr:`interactions` - filtered interactions whose `{src!r}` and `{tgt!r}` are both in the data.
        """
        complex_policy = ComplexPolicy(complex_policy)

        if isinstance(interactions, Mapping):
            interactions = pd.DataFrame(interactions)

        if isinstance(interactions, pd.DataFrame):
            if SOURCE not in interactions.columns:
                raise KeyError(f"Column `{SOURCE!r}` is not in `interactions`.")
            if TARGET not in interactions.columns:
                raise KeyError(f"Column `{TARGET!r}` is not in `interactions`.")

            self._interactions = interactions.copy()
        elif isinstance(interactions, Iterable):
            interactions = tuple(interactions)
            if not len(interactions):
                raise ValueError("No interactions were specified.")

            if isinstance(interactions[0], str):
                interactions = list(product(interactions, repeat=2))
            elif len(interactions) == 2:
                interactions = tuple(zip(*interactions))

            if not all(len(i) == 2 for i in interactions):
                raise ValueError("Not all interactions are of length `2`.")

            self._interactions = pd.DataFrame(interactions, columns=[SOURCE, TARGET])
        else:
            raise TypeError(
                f"Expected either a `pandas.DataFrame`, `dict` or `iterable`, found `{type(interactions).__name__}`"
            )
        if TYPE_CHECKING:
            assert isinstance(self.interactions, pd.DataFrame)

        if self.interactions.empty:
            raise ValueError("The interactions are empty")

        # first uppercase, then drop duplicates
        self._data.columns = self._data.columns.str.upper()
        self.interactions[SOURCE] = self.interactions[SOURCE].str.upper()
        self.interactions[TARGET] = self.interactions[TARGET].str.upper()

        logg.debug("DEBUG: Removing duplicate interactions")
        self.interactions.dropna(subset=(SOURCE, TARGET), inplace=True, how="any")
        self.interactions.drop_duplicates(subset=(SOURCE, TARGET), inplace=True, keep="first")

        logg.debug("DEBUG: Removing duplicate genes in the data")
        n_genes_prior = self._data.shape[1]
        self._data = self._data.loc[:, ~self._data.columns.duplicated()]
        if self._data.shape[1] != n_genes_prior:
            logg.warning(f"Removed `{n_genes_prior - self._data.shape[1]}` duplicate gene(s)")

        self._filter_interactions_complexes(complex_policy)
        self._filter_interactions_by_genes()
        self._trim_data()

        # this is necessary because of complexes
        self.interactions.drop_duplicates(subset=(SOURCE, TARGET), inplace=True, keep="first")

        return self

    @d.get_full_description(base="PT_test")
    @d.get_sections(base="PT_test", sections=["Parameters"])
    @d.dedent
    @inject_docs(src=SOURCE, tgt=TARGET, fa=CorrAxis)
    def test(
        self,
        cluster_key: str,
        clusters: Cluster_t | None = None,
        n_perms: int = 1000,
        threshold: float = 0.01,
        seed: int | None = None,
        corr_method: str | None = None,
        corr_axis: Literal["interactions", "clusters"] | CorrAxis = CorrAxis.INTERACTIONS.v,
        alpha: float = 0.05,
        copy: bool = False,
        key_added: str | None = None,
        numba_parallel: bool | None = None,
        **kwargs: Any,
    ) -> Mapping[str, pd.DataFrame] | None:
        """
        Perform the permutation test as described in :cite:`cellphonedb`.

        Parameters
        ----------
        %(cluster_key)s
        clusters
            Clusters from :attr:`anndata.AnnData.obs` ``['{{cluster_key}}']``. Can be specified either as a sequence
            of :class:`tuple` or just a sequence of cluster names, in which case all combinations considered.
        %(n_perms)s
        threshold
            Do not perform permutation test if any of the interacting components is being expressed
            in less than ``threshold`` percent of cells within a given cluster.
        %(seed)s
        %(corr_method)s
        corr_axis
            Axis over which to perform the FDR correction. Only used when ``corr_method != None``. Valid options are:

                - `{fa.INTERACTIONS.s!r}` - correct interactions by performing FDR correction across the clusters.
                - `{fa.CLUSTERS.s!r}` - correct clusters by performing FDR correction across the interactions.
        alpha
            Significance level for FDR correction. Only used when ``corr_method != None``.
        %(copy)s
        key_added
            Key in :attr:`anndata.AnnData.uns` where the result is stored if ``copy = False``.
            If `None`, ``'{{cluster_key}}_ligrec'`` will be used.
        %(numba_parallel)s
        %(parallelize)s

        Returns
        -------
        %(ligrec_test_returns)s
        """
        _assert_positive(n_perms, name="n_perms")
        _assert_categorical_obs(self._adata, key=cluster_key)

        if corr_method is not None:
            corr_axis = CorrAxis(corr_axis)
        if TYPE_CHECKING:
            assert isinstance(corr_axis, CorrAxis)

        if len(self._adata.obs[cluster_key].cat.categories) <= 1:
            raise ValueError(
                f"Expected at least `2` clusters, found `{len(self._adata.obs[cluster_key].cat.categories)}`."
            )
        if TYPE_CHECKING:
            assert isinstance(self.interactions, pd.DataFrame)
            assert isinstance(self._filtered_data, pd.DataFrame)

        interactions = self.interactions[[SOURCE, TARGET]]
        self._filtered_data["clusters"] = self._adata.obs.copy()[cluster_key].astype("string").astype("category").values

        if clusters is None:
            clusters = list(map(str, self._adata.obs[cluster_key].cat.categories))
        if all(isinstance(c, str) for c in clusters):
            clusters = list(product(clusters, repeat=2))  # type: ignore[assignment]
        clusters = sorted(
            _check_tuple_needles(
                clusters,  # type: ignore[arg-type]
                self._filtered_data["clusters"].cat.categories,
                msg="Invalid cluster `{0!r}`.",
                reraise=True,
            )
        )
        clusters_flat = list({c for cs in clusters for c in cs})

        data = self._filtered_data.loc[np.isin(self._filtered_data["clusters"], clusters_flat), :]
        data["clusters"] = data["clusters"].cat.remove_unused_categories()
        cat = data["clusters"].cat

        cluster_mapper = dict(zip(cat.categories, range(len(cat.categories))))
        gene_mapper = dict(zip(data.columns[:-1], range(len(data.columns) - 1)))  # -1 for 'clusters'

        data.columns = [gene_mapper[c] if c != "clusters" else c for c in data.columns]
        clusters_ = np.array([[cluster_mapper[c1], cluster_mapper[c2]] for c1, c2 in clusters], dtype=np.uint32)

        data["clusters"] = cat.rename_categories(cluster_mapper)
        # much faster than applymap (tested on 1M interactions)
        interactions_ = np.vectorize(lambda g: gene_mapper[g])(interactions.values)

        n_jobs = _get_n_cores(kwargs.pop("n_jobs", None))
        start = logg.info(
            f"Running `{n_perms}` permutations on `{len(interactions)}` interactions "
            f"and `{len(clusters)}` cluster combinations using `{n_jobs}` core(s)"
        )
        res = _analysis(
            data,
            interactions_,
            clusters_,
            threshold=threshold,
            n_perms=n_perms,
            seed=seed,
            n_jobs=n_jobs,
            numba_parallel=numba_parallel,
            **kwargs,
        )
        res = {
            "means": _create_sparse_df(
                res.means,
                index=pd.MultiIndex.from_frame(interactions, names=[SOURCE, TARGET]),
                columns=pd.MultiIndex.from_tuples(clusters, names=["cluster_1", "cluster_2"]),
                fill_value=0,
            ),
            "pvalues": _create_sparse_df(
                res.pvalues,
                index=pd.MultiIndex.from_frame(interactions, names=[SOURCE, TARGET]),
                columns=pd.MultiIndex.from_tuples(clusters, names=["cluster_1", "cluster_2"]),
                fill_value=np.nan,
            ),
            "metadata": self.interactions[self.interactions.columns.difference([SOURCE, TARGET])],
        }
        res["metadata"].index = res["means"].index.copy()

        if TYPE_CHECKING:
            assert isinstance(res, dict)

        if corr_method is not None:
            logg.info(
                f"Performing FDR correction across the `{corr_axis.v}` "
                f"using method `{corr_method}` at level `{alpha}`"
            )
            res["pvalues"] = _fdr_correct(res["pvalues"], corr_method, corr_axis, alpha=alpha)

        if copy:
            logg.info("Finish", time=start)
            return res

        _save_data(self._adata, attr="uns", key=Key.uns.ligrec(cluster_key, key_added), data=res, time=start)

    def _trim_data(self) -> None:
        """Subset genes :attr:`_data` to those present in interactions."""
        if TYPE_CHECKING:
            assert isinstance(self._data, pd.DataFrame)
            assert isinstance(self.interactions, pd.DataFrame)

        logg.debug("DEBUG: Removing genes not in any interaction")
        self._filtered_data = self._data.loc[:, list(set(self.interactions[SOURCE]) | set(self.interactions[TARGET]))]

    def _filter_interactions_by_genes(self) -> None:
        """Subset :attr:`interactions` to only those for which we have the data."""
        if TYPE_CHECKING:
            assert isinstance(self.interactions, pd.DataFrame)

        logg.debug("DEBUG: Removing interactions with no genes in the data")
        self._interactions = self.interactions[
            self.interactions[SOURCE].isin(self._data.columns) & self.interactions[TARGET].isin(self._data.columns)
        ]

        if self.interactions.empty:
            raise ValueError("After filtering by genes, no interactions remain.")

    @inject_docs(src=SOURCE, tgt=TARGET, cp=ComplexPolicy)
    def _filter_interactions_complexes(self, complex_policy: ComplexPolicy) -> None:
        """
        Filter the :attr:`interactions` by extracting genes from complexes.

        Parameters
        ----------
        complex_policy
            Policy on how to handle complexes. Valid options are:

                - `{cp.MIN.s!r}` - select gene with the minimum average expression. This is the same as in
                  :cite:`cellphonedb`.
                - `{cp.ALL.s!r}` - select all possible combinations between `{src!r}` and `{tgt!r}` complexes.

        Returns
        -------
        Nothing, just updates the following fields:

            - :attr:`interactions` - filtered interactions whose `{src!r}` and `{tgt!r}` are both in the data.

        Note that for ``complex_policy={cp.ALL.s!r}``, all pairwise comparisons within a complex are created,
        but no filtering happens at this stage - genes not present in the data are filtered at a later stage.
        """

        def find_min_gene_in_complex(_complex: str | None) -> str | None:
            # TODO(michalk8): how can this happen?
            if _complex is None:
                return None
            if "_" not in _complex:
                return _complex
            complexes = [c for c in _complex.split("_") if c in self._data.columns]
            if not len(complexes):
                return None
            if len(complexes) == 1:
                return complexes[0]

            df = self._data[complexes].mean()
            try:
                return str(df.index[df.argmin()])
            except ValueError as e:
                if "attempt to get argmin of an empty sequence" in str(e):
                    return str(df.index[0])
                else:
                    logg.error(e)

        if TYPE_CHECKING:
            assert isinstance(self._interactions, pd.DataFrame)
            assert isinstance(self.interactions, pd.DataFrame)

        if complex_policy == ComplexPolicy.MIN:
            logg.debug("DEBUG: Selecting genes from complexes based on minimum average expression")
            self.interactions[SOURCE] = self.interactions[SOURCE].apply(find_min_gene_in_complex)
            self.interactions[TARGET] = self.interactions[TARGET].apply(find_min_gene_in_complex)
        elif complex_policy == ComplexPolicy.ALL:
            logg.debug("DEBUG: Creating all gene combinations within complexes")
            src = self.interactions.pop(SOURCE).apply(lambda s: str(s).split("_")).explode()
            src.name = SOURCE
            tgt = self.interactions.pop(TARGET).apply(lambda s: str(s).split("_")).explode()
            tgt.name = TARGET

            self._interactions = pd.merge(self.interactions, src, how="left", left_index=True, right_index=True)
            self._interactions = pd.merge(self.interactions, tgt, how="left", left_index=True, right_index=True)
        else:
            raise NotImplementedError(f"Complex policy {complex_policy!r} is not implemented.")

    @property
    def interactions(self) -> pd.DataFrame | None:
        """The interactions."""  # noqa: D401
        return self._interactions

    def __repr__(self) -> str:
        return (
            f"<{self.__class__.__name__}"
            f"[n_interaction={len(self.interactions) if self.interactions is not None else None}]>"
        )

    def __str__(self) -> str:
        return repr(self)

@d.dedent
class PermutationTest(PermutationTestABC):
    """
    %(PT.full_desc)s

    Parameters
    ----------
    %(PT.parameters)s
    """  # noqa: D400

    @d.get_sections(base="PT_prepare_full", sections=["Parameters"])
    @d.dedent
    def prepare(
        self,
        interactions: Interaction_t | None = None,
        complex_policy: Literal["min", "all"] = ComplexPolicy.MIN.v,
        interactions_params: Mapping[str, Any] = MappingProxyType({}),
        transmitter_params: Mapping[str, Any] = MappingProxyType({"categories": "ligand"}),
        receiver_params: Mapping[str, Any] = MappingProxyType({"categories": "receptor"}),
        **_: Any,
    ) -> PermutationTest:
        """
        %(PT_prepare.full_desc)s

        Parameters
        ----------
        %(PT_prepare.parameters)s
        interactions_params
            Keyword arguments for :func:`omnipath.interactions.import_intercell_network` defining the interactions.
            These datasets from :cite:`omnipath` are used by default: `omnipath`, `pathwayextra`, `kinaseextra` and
            `ligrecextra`.
        transmitter_params
            Keyword arguments for :func:`omnipath.interactions.import_intercell_network` defining the transmitter
            side of intercellular connections.
        receiver_params
            Keyword arguments for :func:`omnipath.interactions.import_intercell_network` defining the receiver
            side of intercellular connections.

        Returns
        -------
        %(PT_prepare.returns)s
        """  # noqa: D400
        if interactions is None:
            from omnipath.interactions import import_intercell_network

            start = logg.info("Fetching interactions from `omnipath`")
            interactions = import_intercell_network(
                interactions_params=interactions_params,
                transmitter_params=transmitter_params,
                receiver_params=receiver_params,
            )
            if TYPE_CHECKING:
                assert isinstance(interactions, pd.DataFrame)

            logg.info(f"Fetched `{len(interactions)}` interactions\n    Finish", time=start)

            # we don't really care about these
            if SOURCE in interactions.columns:
                interactions.pop(SOURCE)
            if TARGET in interactions.columns:
                interactions.pop(TARGET)
            interactions.rename(
                columns={"genesymbol_intercell_source": SOURCE, "genesymbol_intercell_target": TARGET}, inplace=True
            )

            interactions[SOURCE] = interactions[SOURCE].str.replace("^COMPLEX:", "", regex=True)
            interactions[TARGET] = interactions[TARGET].str.replace("^COMPLEX:", "", regex=True)

        _ = super().prepare(interactions, complex_policy=complex_policy)
        return self

@d.dedent
def ligrec(
    adata: AnnData | SpatialData,
    cluster_key: str,
    interactions: Interaction_t | None = None,
    complex_policy: Literal["min", "all"] = ComplexPolicy.MIN.v,
    threshold: float = 0.01,
    corr_method: str | None = None,
    corr_axis: Literal["interactions", "clusters"] = CorrAxis.CLUSTERS.v,
    use_raw: bool = True,
    copy: bool = False,
    key_added: str | None = None,
    gene_symbols: str | None = None,
    **kwargs: Any,
) -> Mapping[str, pd.DataFrame] | None:
    """
    %(PT_test.full_desc)s

    Parameters
    ----------
    %(PT.parameters)s
    %(PT_prepare_full.parameters)s
    %(PT_test.parameters)s
    gene_symbols
        Key in :attr:`anndata.AnnData.var` to use instead of :attr:`anndata.AnnData.var_names`.

    Returns
    -------
    %(ligrec_test_returns)s
    """  # noqa: D400
    if isinstance(adata, SpatialData):
        adata = adata.table
    with _genesymbols(adata, key=gene_symbols, use_raw=use_raw, make_unique=False):
        return (  # type: ignore[no-any-return]
            PermutationTest(adata, use_raw=use_raw)
            .prepare(interactions, complex_policy=complex_policy, **kwargs)
            .test(
                cluster_key=cluster_key,
                threshold=threshold,
                corr_method=corr_method,
                corr_axis=corr_axis,
                copy=copy,
                key_added=key_added,
                **kwargs,
            )
        )

@d.dedent
def _analysis(
    data: pd.DataFrame,
    interactions: NDArrayA,
    interaction_clusters: NDArrayA,
    threshold: float = 0.1,
    n_perms: int = 1000,
    seed: int | None = None,
    n_jobs: int = 1,
    numba_parallel: bool | None = None,
    **kwargs: Any,
) -> TempResult:
    """
    Run the analysis as described in :cite:`cellphonedb`.

    This function runs the mean, percent and shuffled analysis.

    Parameters
    ----------
    data
        Array of shape `(n_cells, n_genes)`.
    interactions
        Array of shape `(n_interactions, 2)`.
    interaction_clusters
        Array of shape `(n_interaction_clusters, 2)`.
    threshold
        Percentage threshold for removing lowly expressed genes in clusters.
    %(n_perms)s
    %(seed)s
    n_jobs
        Number of parallel jobs to launch.
    numba_parallel
        Whether to use :class:`numba.prange` or not. If `None`, it's determined automatically.
    kwargs
        Keyword arguments for :func:`squidpy._utils.parallelize`, such as ``n_jobs`` or ``backend``.

    Returns
    -------
    Tuple of the following format:

        - `'means'` - array of shape `(n_interactions, n_interaction_clusters)` containing the means.
        - `'pvalues'` - array of shape `(n_interactions, n_interaction_clusters)` containing the p-values.
    """

    def extractor(res: Sequence[TempResult]) -> TempResult:
        assert len(res) == n_jobs, f"Expected to find `{n_jobs}` results, found `{len(res)}`."

        meanss: list[NDArrayA] = [r.means for r in res if r.means is not None]
        assert len(meanss) == 1, f"Only `1` job should've calculated the means, but found `{len(meanss)}`."
        means = meanss[0]
        if TYPE_CHECKING:
            assert isinstance(means, np.ndarray)

        pvalues = np.sum([r.pvalues for r in res if r.pvalues is not None], axis=0) / float(n_perms)
        assert means.shape == pvalues.shape, f"Means and p-values differ in shape: `{means.shape}`, `{pvalues.shape}`."

        return TempResult(means=means, pvalues=pvalues)

    groups = data.groupby("clusters")
    clustering = np.array(data["clusters"].values, dtype=np.int32)

    mean = groups.mean().values.T  # (n_genes, n_clusters)
    mask = groups.apply(lambda c: ((c > 0).sum() / len(c)) >= threshold).values.T  # (n_genes, n_clusters)
    # (n_cells, n_genes)
    data = np.array(data[data.columns.difference(["clusters"])].values, dtype=np.float64, order="C")
    # all 3 should be C contiguous

    return parallelize(  # type: ignore[no-any-return]
        _analysis_helper,
        np.arange(n_perms, dtype=np.int32).tolist(),
        n_jobs=n_jobs,
        unit="permutation",
        extractor=extractor,
        **kwargs,
    )(
        data,
        mean,
        mask,
        interactions,
        interaction_clusters=interaction_clusters,
        clustering=clustering,
        seed=seed,
        numba_parallel=numba_parallel,
    )

def _analysis_helper(
    perms: NDArrayA,
    data: NDArrayA,
    mean: NDArrayA,
    mask: NDArrayA,
    interactions: NDArrayA,
    interaction_clusters: NDArrayA,
    clustering: NDArrayA,
    seed: int | None = None,
    numba_parallel: bool | None = None,
    queue: SigQueue | None = None,
) -> TempResult:
    """
    Run the results of mean, percent and shuffled analysis.

    Parameters
    ----------
    perms
        Permutation indices. Only used to set the ``seed``.
    data
        Array of shape `(n_cells, n_genes)`.
    mean
        Array of shape `(n_genes, n_clusters)` representing mean expression per cluster.
    mask
        Array of shape `(n_genes, n_clusters)` containing `True` if the a gene within a cluster is
        expressed at least in ``threshold`` percentage of cells.
    interactions
        Array of shape `(n_interactions, 2)`.
    interaction_clusters
        Array of shape `(n_interaction_clusters, 2)`.
    clustering
        Array of shape `(n_cells,)` containing the original clustering.
    seed
        Random seed for :class:`numpy.random.RandomState`.
    numba_parallel
        Whether to use :class:`numba.prange` or not. If `None`, it's determined automatically.
    queue
        Signalling queue to update progress bar.

    Returns
    -------
    Tuple of the following format:

        - `'means'` - array of shape `(n_interactions, n_interaction_clusters)` containing the true test
          statistic. It is `None` if ``min(perms)!=0`` so that only 1 worker calculates it.
        - `'pvalues'` - array of shape `(n_interactions, n_interaction_clusters)`  containing `np.sum(T0 > T)`
          where `T0` is the test statistic under null hypothesis and `T` is the true test statistic.
    """
    rs = np.random.RandomState(None if seed is None else perms[0] + seed)

    clustering = clustering.copy()
    n_cls = mean.shape[1]
    return_means = np.min(perms) == 0

    # ideally, these would be both sparse array, but there is no numba impl. (sparse.COO is read-only and very limited)
    # keep it f64, because we're setting NaN
    res = np.zeros((len(interactions), len(interaction_clusters)), dtype=np.float64)
    numba_parallel = (
        (np.prod(res.shape) >= 2**20 or clustering.shape[0] >= 2**15) if numba_parallel is None else numba_parallel  # type: ignore[assignment]
    )

    fn_key = f"_test_{n_cls}_{int(return_means)}_{bool(numba_parallel)}"
    if fn_key not in globals():
        exec(
            compile(_create_template(n_cls, return_means=return_means, parallel=numba_parallel), "", "exec"), globals()  # type: ignore[arg-type]
        )
    _test = globals()[fn_key]

    if return_means:
        res_means: NDArrayA | None = np.zeros((len(interactions), len(interaction_clusters)), dtype=np.float64)
        test = partial(_test, res_means=res_means)
    else:
        res_means = None
        test = _test

    for _ in perms:
        rs.shuffle(clustering)
        test(interactions, interaction_clusters, data, clustering, mean, mask, res=res)

        if queue is not None:
            queue.put(Signal.UPDATE)

    if queue is not None:
        queue.put(Signal.FINISH)

    return TempResult(means=res_means, pvalues=res)


'''

	Written by Azorfus
	Github: @azorfus

'''

import socket
import threading
import time
import os
import csv

host = "192.168.1.11" # str(input("Enter Host IP: "))
port = 8080
MAX_LISTEN_TIME = 2
exit_flag = threading.Event()

client_sockets = []
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(20)

print(f"[*] Listening as {host}:{port}")

def send_file(cs, file_name):
	try:
		file = open(file_name, "rb")
		file_size = os.path.getsize(file_name)

		rem = int(file_size % 1024)
		quo = int((file_size - rem)/1024)
		file_name_back = file_name.split("__")[1]

		# Packet with file size and name information.
		packet_info = str(quo) + ":@!" + str(rem) + ":@!" + file_name_back + ":@!"
		send_packet = packet_info.ljust(256, "#")
		cs.send(send_packet.encode())
		cs.sendall(file.read())

		file.close()

	except Exception as e:
		print(f"[!] Error: {e}")
		return 0

	return 0

def recv_file(kcs):
	cs_ip = kcs.getpeername()

	packet_info = kcs.recv(256).decode('utf-8', errors='ignore')
	packet_struct = packet_info.split(":@!$")

	rem = int(packet_struct[1])
	quo = int(packet_struct[0])

	with open(f"{packet_struct[3]}__{packet_struct[2]}", "wb") as file:

		count = 0
		packet = 0
		while count <= quo:
			if count == quo:
				packet = kcs.recv(rem)
			else:
				packet = kcs.recv(1024)
				print("Receiving... ", count*1024)
			file.write(packet)
			count += 1

		file.close()

	now = time.time()
	pong_recv = ""

	while pong_recv != "PONG":
		if time.time() > now + 5:
			print("Timed out FTS...")
			break

		confirmation = "file!upload!success!@$:"
		confirmation = confirmation.ljust(1024, "#")
		kcs.send(confirmation.encode())

		pong_recv = kcs.recv(1024).decode()
		pong_recv = pong_recv.split("!@$:")[0]

	upload_info = f"{packet_struct[3]} uploaded file {packet_struct[2]} size: {quo*4096+rem} bytes.\nType \"!download\" and\n then enter the file name in the format <username>__<file name>\ni.e. \"{packet_struct[3]}__{packet_struct[2]}\" to download the file.\n"
	for client_socket in client_sockets:
		client_socket.send(upload_info.encode())

	return 0

def establish_conn(cs, file_name, FPORT, FLAG):

	# Start time of the server
	start_time = time.time()

	fs = socket.socket()
	fs.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	fs.bind((host, fport))
	fs.settimeout(120)
	print("[*] Listening for file tunnel connection...")

	# Listen for file tunnel connections within the time limit
	fs.listen(5)
	print("[*] Receiving connection requests to FTP server...")

	now = time.time()
	pong_recv = ""

	while pong_recv != "PONG":
		if time.time() > now + 5:
			print("Timed out FTS...")
			return 0

		confirmation = "file!tunnel!open!@$:"
		confirmation = confirmation.ljust(1024, "#")
		cs.send(confirmation.encode())

		pong_recv = cs.recv(1024).decode()
		pong_recv = pong_recv.split("!@$:")[0]

	print("[!] Received Pong message from client.")

	while (time.time() - start_time) <= MAX_LISTEN_TIME:
		try:

			if FLAG == "DOWN":
				fcs, fcaddr = fs.accept()
				print(f"[*] File transfer tunnel established with {fcaddr}")
				send_file(fcs, file_name)
				print(f"[*] File transfer tunnel successfully closing...")
				break

				confirmation = s.recv(1024).decode()
				confirmation = confirmation.split("!@$:")[0]

				while confirmation != "file!download!success":
					time.sleep(2)
					print("[*] Waiting for download to finish....")
					confirmation = s.recv(1024).decode()
					confirmation = confirmation.split("!@$:")[0]

				fcs.close()
				fs.close()

			elif FLAG == "UP":
				fcs, fcaddr = fs.accept()
				print(f"[*] File transfer tunnel established with {fcaddr}")
				recv_file(fcs)
				print(f"[*] File transfer tunnel successfully closing...")
				fcs.close()
				fs.close()
				break

		except Exception as e:
			if e == socket.timeout:
				print("Timing out...")
				pass  # Ignore timeout and continue listening

			elif e == ConnectionResetError:
				print("BRUH")
				pass

	return 0

def listen_for_client(cs):
	global log_writer
	while not exit_flag.is_set():
		try:
			msg_R = cs.recv(1024).decode('utf-8', errors='ignore')
			msg = msg_R.split("!@$:")[0]

			if msg == "client!exit!code":
				print(f"[*] Client: {cs.getpeername()[0]} has closed the connection.")
				client_sockets.remove(cs)
				cs.close()
				break

			elif msg == "file!transfer!code":
				FPORT = int(msg_R.split("!@$:")[1])
				connThread = threading.Thread(target = establish_conn, args = (cs, "", FPORT, "UP" ))
				connThread.daemon = True
				connThread.start()

			elif msg.split("!@$:")[0] == "file!download!request":
				FPORT = int(msg_R.split("!@$:")[1])
				file_name = msg_R.split("!@$:")[2]
				connThread = threading.Thread(target = establish_conn, args = (cs, file_name, FPORT, "DOWN" ))
				connThread.daemon = True
				connThread.start()

			else:
				info = msg_R.split("!@$#:")
				log_writer.writerow([info[0], info[1], info[2].split("!@$:")[0], cs.getpeername()[0], 0])
				msg_R = f"[{info[0]}] {info[1]}: {info[2]}!@$:"
				msg = msg_R.ljust(1024, "#")
				for client_socket in client_sockets:
					client_socket.send(msg.encode())

		except Exception as e:
			print(f"[!] Error: {e}")
			client_sockets.remove(cs)
			cs.close()
			break

def server_term():
	global logfile
	while not exit_flag.is_set():
		cmd = input("$ ")
		if cmd == "ABORT":
			exit_flag.set()
			for i in threading.enumerate():
				i.join()
			for cs in client_sockets:
				abort_code = "server!abort!code!abort!@$:".ljust(1024, "#")
				cs.send(abort_code.encode())
				cs.close()
			s.close()
			break
		if cmd == "logflush":
			logfile.flush()

with open("logging_file.csv", "w+") as logfile:
	log_writer = csv.writer(logfile, delimiter=",")

	term = threading.Thread(target = server_term)
	term.daemon = True
	term.start()

	while True:
		client_socket, client_address = s.accept()
		print(f"[+] {client_address} connected.")
		client_sockets.append(client_socket)

		fport = 8081 + client_sockets.index(client_socket)
		sport = f"{fport}!@$:".ljust(256, "#")
		client_socket.send(sport.encode())

		client_t = threading.Thread(target=listen_for_client, args=(client_socket,))
		client_t.daemon = True
		client_t.start()

s.close()


#
# @lc app=leetcode id=235 lang=python3
#
# [235] Lowest Common Ancestor of a Binary Search Tree
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        cur = root
        while cur:
            if p.val < cur.val and q.val < cur.val:
                cur = cur.left
            elif p.val > cur.val and q.val > cur.val:
                cur = cur.right
            else:
                return cur
# @lc code=end


from django.urls import path, re_path

from . import consumers
from . import views

urlpatterns = [
    path('character/all', views.get_all_characters, name='get_all_characters'),
    path('character/<int:id>', views.get_character, name='get_character'),
    path('character/create', views.create_character, name='create_character'),
    path('character/<int:id>/update', views.update_character, name='update_character'),
    path('character/<int:id>/delete', views.delete_character, name='delete_character'),

    path('question/<int:library_id>/all', views.get_all_questions_in_library, name='get_all_questions_in_library'),
    path('question/<int:id>', views.get_question, name='get_question'),
    path('question/create', views.create_question, name='create_question'),
    path('question/<int:id>/delete', views.delete_question, name='delete_question'),
    path('question/<int:id>/update', views.update_question, name='update_question'),
    path('library/question/all', views.get_all_question_libraries, name='get_all_question_libraries'),
    path('library/question/create', views.create_question_library, name='create_question_library'),

    path('speech/<int:library_id>/all', views.get_all_speeches_in_library, name='get_all_speeches_in_library'),
    path('speech/<int:id>', views.get_speech, name='get_speech'),
    path('speech/create', views.create_speech, name='create_speech'),
    path('speech/<int:id>/delete', views.delete_speech, name='delete_speech'),
    path('speech/<int:id>/update', views.update_speech, name='update_speech'),
    path('library/speech/all', views.get_all_speech_libraries, name='get_all_speech_libraries'),
    path('library/speech/create', views.create_speech_library, name='create_speech_library'),

    path('words/<int:library_id>/all', views.get_all_words_in_library, name='get_all_words_in_library'),
    path('words/<int:id>', views.get_word, name='get_word'),
    path('words/create', views.create_word, name='create_word'),
    path('words/<int:id>/delete', views.delete_word, name='delete_word'),
    path('words/<int:id>/update', views.update_word, name='update_word'),
    path('library/words/<str:library_type>/all', views.get_all_words_libraries_by_type, name='get_all_words_libraries_by_type'),
    path('library/words/create', views.create_words_library, name='create_words_library'),

    path('lens/all', views.get_all_lenses, name='get_all_lenses'),
    path('lens/<int:id>', views.get_lens, name='get_lens'),
    path('lens/create', views.create_lens, name='create_lens'),
    path('lens/<int:id>/update', views.update_lens, name='update_lens'),
    path('lens/<int:id>/delete', views.delete_lens, name='delete_lens'),

    path('image/all', views.get_all_images, name='get_all_images'),
    path('image/create', views.create_image, name='create_image'),
    path('image/<int:image_id>/bind', views.bind_user_image, name='bind_user_image'),
    path('image/<int:image_id>/update', views.update_image, name='update_image'),
    path('image/<int:image_id>/delete', views.delete_image, name='delete_image'),

    path('environment/all', views.get_all_environments, name='get_all_environments'),
    path('environment/create', views.create_environment, name='create_environment'),
    path('environment/<int:environment_id>/bind', views.bind_user_environment, name='bind_user_environment'),
    path('environment/<int:environment_id>/update', views.update_environment, name='update_environment'),
    path('environment/<int:environment_id>/delete', views.delete_environment, name='delete_environment'),

    path('get_alipay_url_image/<int:image_id>', views.get_alipay_payment_url_image),
    path('get_alipay_url_environment/<int:environment_id>', views.get_alipay_payment_url_environment),

    path('live_config', views.get_live_config, name='get_live_config'),
    path('live_config/update', views.update_live_config, name='update_live_config'),

]

websocket_urlpatterns = [
    re_path(r'(?P<mode>chat|speech)/generate$', consumers.AiGeneratorWsConsumer.as_asgi()),
]


t=int(input())
for i in range(0,t):
    n=int(input())
    list1=input().split()
    list1=list(map(int,list1))
    num=[0]*n
    for j in list1:
        num[j-1]=num[j-1]+1
    if(0 in num):
        a=num.index(0)
    else:
        a=-1
    if(2 in num):
        b=num.index(2)
    else:
        b=-1
    print(b+1,a+1)


# 13. Escreva um programa em Python para calcular o salário semanal de uma pessoa,
# determinado pelas seguintes condições. Se o número de horas trabalhadas for menor ou
# igual a 40, a pessoa recebe 8 reais por hora trabalhada, se não a pessoa recebe 320 reais
# fixos e mais 12 reais para cada hora trabalhada que excede 40 horas. (Exemplo: uma
# pessoa que trabalha 42 horas deve receber 344 reais). Seu programa deve ler o número
# de horas trabalhadas e deve imprimir na tela o salário semanal.

tempTrabalhado = int(input("Digite o tempo trabalhado em horas: "))

if tempTrabalhado <= 40 and tempTrabalhado > 0:
    salario = tempTrabalhado * 8
    print("O seu salário é R$", salario)

elif tempTrabalhado > 40:
    salario = 320 + ((tempTrabalhado - 40) * 12)
    print("O seu salário é R$", salario)

Senai/Lista de atividade/Lista 2 - Condicionais/ex13.py