#!/usr/bin/env python3.10
import subprocess
import os
from PIL import Image
import re
import numpy as np
from datetime import datetime
from astropy.io import fits
import sys
import argparse

fitcropX=1.0
fitcropY=1.0
speedPara=1.0
downSample=2 ##default downSample=2
depthStar='11-20'
dt=datetime.now()

def solvCoord(myImage, mydepth, mydownsample):
    depthStar=mydepth
    dt=datetime.now()
    ##run solve-field again
    cmd = f'solve-field --no-plot --scale-low 0.1 --downsample {mydownsample} --depth {mydepth} --overwrite  {myImage}' #resized_img_filename
    output = subprocess.check_output(cmd, shell=True, universal_newlines=True)
    print(output)
    dt2=datetime.now()-dt
    print ("Platesolve time:", dt2)
    # Parse the output to get the RA and Dec coordinates
    ra = None
    dec = None
    for line in output.split('\n'):

        if line.startswith('simplexy:'):
            starno=line.split('simplexy: found ')[1].split(' sources.')
            print('simplyxy:',starno,' stars')
        if line.startswith('Field center: (RA,Dec) = ('):
           # ra, dec = re.findall(r"[-+]?(?:\d*\.*\d+)",(line.split(') = (')[1].split(',')))
            ra,dec=line.split(' (RA,Dec) = (')[1].split(',')
            #radd,decdd=line.split(' D:M:S) = (')[1].split(',')
            #radecnp =np.array( re.findall(r"[-+]?(?:\d*\.*\d+)",radec))
            print(ra,dec)
            ra = float(ra)
            dec = float(dec[:-6])
            #print (radd,decdd)
            #radd=radd
            #decdd=decdd[:-2]
        if line.startswith('Field size: '):
           fieldInfo = line.split('Field size: ')[1].split()
           print(fieldInfo)
           #fieldX=float(fieldInfo[0])
           #fieldY=float(fieldInfo[2])

           arcUnit=fieldInfo[3]
           #translate unit to degrees
           if arcUnit=='degrees':
              fieldX=float(fieldInfo[0])
              fieldY=float(fieldInfo[2])
           elif arcUnit[:7]=='arcminu':
              fieldX=float(fieldInfo[0])/60
              fieldY=float(fieldInfo[2])/60
           else:
              fieldX=float(fieldInfo[0])/3600
              fieldY=float(fieldInfo[2])/3600

        if line.startswith('Field rotation angle: '):
           rotateA = line.split(' up is ')[1].split()
           #rotateA=float(rotateA)
           print('rot', rotateA)
           break
    return (ra, dec, rotateA, fieldX, fieldY, starno)

def rawTotiff_resize(myImage, resizeRateX, resizeRateY):
    # Convert the raw image file to FITS format using dcraw
    dt=datetime.now()
    outfitfile=myImage[:-4]+'.fit'
    #os.system(f"rawtran -c R -o {outfitfile} {myImage}")
    os.system(f"dcraw -4 -T -h  {myImage}")
    print("dcraw img conv to tiff:",datetime.now()-dt)
    # Get the name of the FITS file that was created by dcraw
    #fits_image_file = os.path.splitext(myImage)[0] + '.fit'
    fits_image_file = os.path.splitext(myImage)[0] + '.tiff'
    print("t img:",datetime.now()-dt)
    image = Image.open(fits_image_file)
    width,height = image.size
    if (resizeRateX is not None or  resizeRateY is not None):
      if float(resizeRateX) > 1.0 or float(resizeRateX)< 0.10 or  float(resizeRateY) > 1.0 or float(resizeRateY) < 0.10  :
         resizeRateX=1.0
         resizeRateY=1.0
    else:
      resizeRateX=0.25 ##default resizeset to 0.25
      resizeRateY=0.25
    resized_img=image.resize((int(width*resizeRateX),int(height*resizeRateY)))
    resized_img_filename=os.path.splitext(myImage)[0] + '_q.jpg'
    resized_img.save(resized_img_filename)
    print("q img:",datetime.now()-dt,resized_img_filename)
    #resized_img3=img.resize((int(width/3),int(height/3)))
    #resized_img3_filename=os.path.splitext(myImage)[0] + '_s.jpg'
    #resized_img3.save(resized_img3_filename)
    outImage=resized_img_filename
    #image = fits.getdata(fits_image_file)
    return (outImage)

##for fits crop to reduce image size and solve-field speed.
def fits_crop(myImage,cropX,cropY):
    ##directly fits translate and crop into 800x800 pixels
    image = fits.getdata(myImage)

    height, width = image.shape
    ##crop fits if crop <1.0
    if cropX is not None or cropY is not None:
     if float(cropX) >1.0 or float(cropY)<0.1:
        cropX=1.0
        cropY=1.0
    #default crop=0.5
    else:
    	cropX=0.5
    	cropY=0.5
    # Calculate the coordinates of the center of the image
    center_x = width // 2
    center_y = height // 2
    fitcropXw=int(cropX*width)
    fitcropYh=int(cropY*height)
    # Calculate the coordinates of the top-left corner of the crop
    crop_x = center_x - fitcropXw // 2
    crop_y = center_y - fitcropYh // 2
    # Crop the image
    cropped_image = image[crop_y:crop_y+fitcropXw, crop_x:crop_x+fitcropYh]
    # Save the cropped image to a new file
    fitcrop2_name = myImage[:-4]+'_crop'  +myImage[-4:]  ##'.tiff'
    print ('\n',datetime.now()-dt,'\t',fitcrop2_name ,'\t',fitcropXw,'x',fitcropYh, ' pixels fits image cropped')
    fits.writeto(fitcrop2_name, cropped_image,overwrite=True)
    outImage=fitcrop2_name
    return (outImage)

#main arg parser for input parameters
def solvefield_arg_parse():
    ##input args
    #if len(sys.argv)<2:
    #    print("Usage python3 solveLocal2.py <input image (fit/fits/cr2/nef/arw)> for plate-    solve")
    #    sys.exit(1)
    parser = argparse.ArgumentParser(description='input the image, crop ratio and speed parameter')
    #group = parser.add_mutually_exclusive_group()
    parser.add_argument('-c', '--crop', type=float, help='Resize(.raw)/Crop(.fits) factor 0.02(0.1)-1.0 to make sure pixels ~ 800 pixels for shorter solve-field time.(default=1.0)')
    parser.add_argument('-z', '--downsample', type=int, help='downsample parameter in solve-field (defualt=2)')
    parser.add_argument('-d', '--depth', type=str, help='depth sequence of stars in solve-field (default=11-20)')
    #group.add_argument('-s', '--speed', type=int, help='speed for solve-field **test only**')
    parser.add_argument('imagefile', type=str, help='input image filename cr2/nef/fit')
    args = parser.parse_args()
    if args.imagefile =='':
        print("Usage python3 solveLocal6.py -c 1.0 -z 2 <input image (fit/fits/cr2/nef/arw)> for plate-solve.")
        sys.exit(1)
    else:
       raw_image_file=args.imagefile
    if args.crop is not None:
      if float(args.crop) <= 1.0 and float(args.crop)>=0.02:
        fitcropX=float(args.crop)  ##set the crop ration
        fitcropY=float(args.crop)
    else:  ##default crop=1.0
      fitcropX=1.0
      fitcropY=1.0
    #elif args.downsample is not None :
    if args.downsample is not None:
      if int(args.downsample)>1:
        downSample=int(args.downsample)
        print('downSample',downSample)
      else:
        downSample=1
    else:
      downSample=2
      print(args.crop,args.downsample)
   #elif args.speed > 1:
   #    speedPara=args.speed
    if args.depth is not None:
      depthStar=args.depth
    else:
      depthStar='11-20'
      ##default nu,ber is 11th to 20th bright stars
    return(raw_image_file, downSample, fitcropX,fitcropY, depthStar)

def main():
    dt=datetime.now()
    #input arguments truncation loop
    raw_image_file, downSample, fitcropX, fitcropY, depthStar = solvefield_arg_parse()

    ##

    # Path to the raw image file
    #raw_image_file = args.imagefile
    verifyRaw=raw_image_file.lower()[-4:]

    print(verifyRaw, downSample, fitcropX, fitcropY, depthStar)
    if verifyRaw == '.cr2' or verifyRaw == '.nef' or verifyRaw=='.arw':
      ##dslr image resize routine it will slower 7-8sec than fits file for convertion.
      outImage=rawTotiff_resize(raw_image_file,fitcropX,fitcropY)

    else:
      ##fits image croped routine
      outImage=fits_crop(raw_image_file,fitcropX,fitcropY)

    dt1=datetime.now()-dt
    print ("image translate", dt1,outImage)
    #depthStar='11-20'
    ra, dec, rotateA, fieldX, fieldY, starno = solvCoord(outImage, depthStar, downSample)

    if ra is not None and dec is not None:
        print(f'RA: {ra}, Dec: {dec}')
        print('Field:', fieldX, 'x', fieldY,'degs')
        print('Rotation angle:', rotateA[0])
        #print(f'RA: {radd}, Dec: {decdd}')
    else:
        print('Plate-solving failed.')
    print('star in croped img:',starno[0])

    if starno in (10, 20) : ##smaller 20 star
        depthStar='2-11'
        ra, dec, rotateA, fieldX, fieldY, starno = solvCoord(outImage, depthStar, downSample)

    if ra is not None and dec is not None:
        print(f'RA: {ra}, Dec: {dec}')
        print('Field:', fieldX, 'x', fieldY,'degs')
        print('Rotation angle:', rotateA[0])
        #print(f'RA: {radd}, Dec: {decdd}')
    else:
        print('Plate-solving failed.')
    print('star a croped img:',starno[0])
    ##printfinal proess time
    dt2=datetime.now()-dt
    print ("Platesolve time:", dt2)

if __name__ == "__main__":
    main()


# Una expresión generadora es sintácticamente muy similar a una lista por comprensión,
# pero utilizamos paréntesis en vez de corchetes. Se podría ver como una versión acortada
# de una función generadora. Ejemplo en el que creamos números pares hasta el 20:

evens_gen = (i for i in range(0, 20, 2))

# type(evens_gen)
# generator

for i in evens_gen:
    print(i, end=' ')

# Una expresión generadora se puede explicitar, sumar, buscar su máximo o su mínimo,
# o lo que queramos, tal y como lo haríamos con un iterable cualquiera:

list(i for i in range(0, 20, 2))
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

sum(i for i in range(0, 20, 2))
# 90

min(i for i in range(0, 20, 2))
# 0

max(i for i in range(0, 20, 2))
# 18


#!/usr/bin/env python3
# coding=utf-8

import sys
import os.path
from pylab import *

num_trucks = 0
trucks_capacities = []
num_milks = 0
milk_request = []
milk_values = []
num_farms = 0
farms = []
letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"];

def convert_array(element):
	try:
	   return int(element)
	except ValueError:
		if(element in letters):
			return letters.index(element)
		else:
			return -1

def read_instances(instance):
	file = open(os.path.dirname(__file__) + "/../inputs/" + instance + ".txt")

	global num_trucks
	global trucks_capacities
	global num_milks
	global milk_request
	global milk_values
	global num_farms

	num_trucks = int(file.readline())
	trucks_capacities = file.readline()[:-1].split("   ")
	file.readline()

	num_milks = int(file.readline())
	milk_request = file.readline()[:-1].split("    ")
	milk_values = file.readline()[:-1].split("     ")
	file.readline()

	num_farms = int(file.readline())

	for farm in range(num_farms):
		line = file.readline()[:-1]
		array = list(map(convert_array, line.split("\t")))
		farms.append(array)

def total_cost(route):
	route_cost = []
	temp_cost = 0

	for i in range(1, len(route)):
		if route[i] == 0:

			temp_cost += int(
				sqrt(
					(farms[route[i-1]][1] - farms[route[i]][1])**2 +
					(farms[route[i-1]][2] - farms[route[i]][2])**2
				) + 0.5
			)

			route_cost.append(temp_cost)

			temp_cost = 0
		else:
			temp_cost += int(
				sqrt(
					(farms[route[i-1]][1] - farms[route[i]][1])**2 +
					(farms[route[i-1]][2] - farms[route[i]][2])**2
				) + 0.5
			)

	return int(sum(route_cost))

def local_cost(route):
	route_cost = 0

	for i in range(1, len(route)):
		route_cost += int(
			sqrt(
				(farms[route[i-1]][1] - farms[route[i]][1])**2 +
				(farms[route[i-1]][2] - farms[route[i]][2])**2
			) + 0.5
		)

	return route_cost

def swap(route, index1, index2):
	temp = route[index2]
	route[index2] = route[index1]
	route[index1] = temp
	return route

def find_better(route):
	global_cost = total_cost(route)
	routes = []
	index = 0

	for i in range(1, len(route)):
		if(route[i] == 0):
			routes.append(route[index:i+1])
			index = i

	for route in routes:
		droute = route
		route_cost = local_cost(route)
		print("Route: ", route_cost, route, "\n")

		for g in range(1, len(route)-1):
			for h in range(1, len(route)-1):
				droute = route

				for i in range(1, len(droute)-1):
					for j in range(1, len(droute)-1):
						temp = swap(droute, i, j)
						temp_cost = local_cost(temp)

						if(temp_cost < route_cost):
							route_cost = temp_cost
							print(temp_cost, " -> ", temp)

	print("Finish")

#Read Args
if len(sys.argv) != 3:
	print("It is need pass the instance name")
else:
	read_instances(sys.argv[1])

	route = list(map(int, sys.argv[2][1:-1].split(",")))

	print()

	find_better(route)

'''
python3 better.py a64 [0,41,56,32,20,23,62,53,14,17,11,38,29,0,25,22,43,28,1,7,40,49,55,31,37,19,34,4,58,46,16,61,13,52,10,0,6,33,48,45,15,57,30,3,51,9,42,24,60,8,47,63,2,54,5,59,50,36,39,44,21,26,35,27,12,18,0]

python3 better.py a64 [0,41,20,56,32,23,62,53,14,17,11,38,29,0,25,22,43,28,1,7,40,49,55,31,37,19,34,4,58,46,16,61,13,52,10,0,6,33,48,45,15,57,30,3,51,9,42,24,60,8,47,63,2,54,5,59,50,36,39,44,21,26,35,27,12,18,0]
'''


# -*- coding: utf-8 -*-
"""
Created on Thu Sep  6 06:26:39 2018

@author: vishal
"""

url = 'https://www.imdb.com/india/top-rated-indian-movies/?sort=rk,asc&mode=simple&page=1'
from selenium import webdriver
driver =  webdriver.Chrome(r"C:\Users\visha\chromedriver")
driver.get(url)

#for storing all titles in a list
titles = driver.find_elements_by_class_name('titleColumn')
newtitles = []
for i in titles:
    j = i.text
    newtitles.append(j)

#looping for ratings
string_title = '//*[@id="main"]/div/span/div/div/div[3]/table/tbody/tr[1]/td[3]/strong'
ratings = []
for er in range(1,len(titles)+1):
    up_rate = string_title[0:-15] +str(er)+ string_title[-14:]
    k = driver.find_element_by_xpath(up_rate)
    ratings.append(k)

newratings = []
for k in ratings:
    q = k.text
    newratings.append(q)

'''we came to conclusion later that to access all films in rating wise
it would be great if we stick with list as dictionaries are inherently orderless '''

list1 = []
for i in range(0,249):
    k = newtitles[i] + ' : ' + newratings[i]
    list1.append(k)

a = 1
while a != 0:
    test1 = int(input('Enter a number between 1-250 to check rating of a movie: '))
    if test1>=1 and test1<=250:
        print(list1[test1-1])
    else:
        print('wrong input')
    a = input("Enter 'done' to stop or press enter to continue: ")
    if a == 'done':
        break


#https://www.acmicpc.net/problem/2580
#2580번-스도쿠
import sys
input = sys.stdin.readline
sdoku = []
zero = []
for i in range(9):
    s = list(map(int,input().split()))
    for j in range(9):
        if s[j]==0:zero.append((i,j))
    sdoku.append(s)

def check(x,y,value):
    for i in range(9):
        if i!=x and sdoku[i][y]==value: return False
    for j in range(9):
        if j!=y and sdoku[x][j]==value: return False

    if 0<=x<3: a = 0
    elif 3<=x<6: a = 3
    else: a = 6

    if 0<=y<3: b = 0
    elif 3<=y<6: b= 3
    else: b = 6

    for i in range(a,a+3):
        for j in range(b,b+3):
            if i!=x and j!=y and sdoku[i][j]==value: return False

    return True

def backtracking(cnt,idx):
    if cnt==len(zero):
        for i in range(9):
            print(*sdoku[i],sep=' ')
        exit(0)

    for j in range(1,10):
        x,y = zero[idx][0],zero[idx][1]
        if sdoku[x][y]==0 and check(x,y,j):
            sdoku[x][y]=j
            backtracking(cnt+1,idx+1)
            sdoku[x][y]=0

backtracking(0,0)


from myciphers.cipher import Cipher
import myciphers.config as config
import myciphers.utility as util

class Hill(Cipher):
	def __init__(self, matrix_string = "ABCD", alphabet = config.alphabet_upper):
		Cipher.__init__(self, alphabet)
		self.size = int(len(matrix_string) ** 0.5)
		assert len(matrix_string) == self.size ** 2
		self.matrix = Hill.make_matrix(matrix_string.upper(), self.alphabet)
		if self.detailed:
			print("\nENCRYPTION MATRIX")
			self.show_matrix(self.matrix)
		self.inverse = Hill.get_inverse(self.matrix)
		assert self.inverse != None
		if self.detailed:
			print("\nDECRYPTION MATRIX")
			self.show_matrix(self.inverse)

	def make_matrix(matrix_string, alphabet = config.alphabet_upper):
		matrix = []
		size = int(len(matrix_string) ** 0.5)
		for i in range(size):
			row = []
			for j in range(size):
				index = alphabet.index(matrix_string[i*size+j])
				row.append(index)
			matrix.append(row)
		return matrix

	def show_matrix(self, matrix):
		for row in matrix:
			print(" ".join("{0:2}".format(str(x)) for x in row))

	def encrypt(self, text):
		text = self.prep_text(text,
							  keep_spaces = False,
							  keep_punct = False,
							  keep_num = False)
		## Make sure text is multiple of size
		while len(text) % self.size != 0:
			text += "X"
		ciphertext = ""
		for i in range(0, len(text), self.size):
			old_indices = []
			for j in range(self.size):
				index = self.alphabet.index(text[i+j])
				old_indices.append([index])
			new_indices = util.matrix_multiply(self.matrix, old_indices)
			for x in new_indices:
				ciphertext += self.alphabet[x[0] % len(self.alphabet)]
		return ciphertext

	def decrypt(self, text):
		text = self.prep_text(text,
							  keep_spaces = False)
		assert len(text) % self.size == 0
		plaintext = ""
		for i in range(0, len(text), self.size):
			old_indices = []
			for j in range(self.size):
				index = self.alphabet.index(text[i+j])
				old_indices.append([index])
			new_indices = util.matrix_multiply(self.inverse, old_indices)
			for x in new_indices:
				plaintext += self.alphabet[x[0] % len(self.alphabet)]
		return plaintext

	def get_inverse(matrix, modulo = 26):
		adj_matrix = []
		det = util.matrix_determinant(matrix)
		inv_det = util.modular_inverse(det, modulo)
		if inv_det == -1:
			return None
		if len(matrix) == 2:
			## matrix in form [[a, b], [c, d]]
			a = matrix[0][0]
			b = matrix[0][1]
			c = matrix[1][0]
			d = matrix[1][1]
			adj_matrix = [[d, -b]
					    ,[-c, a]]
		else:
			adj_matrix = util.transpose_matrix(util.matrix_cofactors(matrix))
		inv_matrix = []
		for row in range(len(matrix)):
			inv_row = []
			for col in range(len(matrix)):
				inv_row.append((inv_det*(adj_matrix[row][col] % modulo)) % modulo)
			inv_matrix.append(inv_row)

		return inv_matrix


import cv2
import numpy as np
from sklearn.metrics import average_precision_score, roc_auc_score
import matplotlib.pyplot as plt
from shapely.geometry import Polygon

from scripts.utils import part_corpus_to_idxs

def compute_iou(gt_coord, c, target_width, H):
    gt_polygon = Polygon(gt_coord)
    # minx, miny, maxx, maxy = Polygon(gt_coord).bounds
    # gt_polygon = Polygon([(minx, miny), (minx, maxy), (maxx, maxy), (maxx, miny)])
    c_polygon = Polygon(
        [[c["x"], c["y"]],
         [c["x"] + target_width, c["y"]],
         [c["x"] + target_width, c["y"] + H],
         [c["x"], c["y"] + H]])
    # Calculate Intersection and union, and tne IOU
    try:
        polygon_intersection = gt_polygon.intersection(c_polygon).area
        polygon_union = gt_polygon.union(c_polygon).area
        return polygon_intersection / polygon_union
    except Exception as e:
        print(e)
        return 0

def draw_blank(axs, x_plot, H, target_width, y_offset_sim):
    blank = np.zeros((H, target_width, 3), np.uint8)
    blank[:] = (255, 255, 255)
    axs[x_plot].axis('off')
    axs[x_plot].imshow(blank, interpolation='nearest', cmap='Greys_r')
    axs[x_plot].text(0.5, y_offset_sim, "...", size=12, ha="center",
                     transform=axs[x_plot].transAxes)

def do_evaluate(images, gt_words, word, candidates, template, H, widths,
                target_width, worst_candidates, corpus_name, draw_results=False):
    gt_coords = [t["coords"] for t in gt_words]

    i = 1
    i_last_found = 0
    nbr_found = 0
    for c in candidates:
        c["found"] = False
        c["rank"] = i
        c["IOU"] = 0
        for gt_coord in gt_coords:
            c["IOU"] = max(compute_iou(gt_coord, c, target_width, H), c["IOU"])
            if c["IOU"] > 0.5:
                i_last_found = i
                nbr_found += 1
                c["found"] = True
                break

        if nbr_found == len(gt_coords):
            break
        i += 1

    if nbr_found == 0:
        return 0, 0, 0, 0, 0
    else:

        # cut the candidates list to the last found candidate
        candidates = candidates[:i_last_found]

        # Extract the predicted probabilities and ground truth labels from the candidates
        probs = [candidate['sim'] for candidate in candidates]
        labels = [candidate['found'] for candidate in candidates]
        ap = average_precision_score(labels, probs)

        # Compute the AUC
        if sum(labels) == 0:
            roc_auc = 0
        elif sum(labels) == len(labels):
            roc_auc = 1
        else:
            roc_auc = roc_auc_score(labels, probs)

        n_retrieved_relevant = sum(1 for candidate in candidates if candidate['found'])

        precision = n_retrieved_relevant / len(candidates)
        recall = n_retrieved_relevant / len(gt_coords)

        if recall > 1:
            recall = 1

        if draw_results:
            NBR_TEMPLATE = 1
            NBR_OF_CANDIDATES = min(len(candidates), 10)
            NBR_BLANK_SPACE = 1
            NBR_WORST = max(len(worst_candidates), 1)

            fig, axs = plt.subplots(1,
                                    NBR_TEMPLATE + NBR_OF_CANDIDATES + NBR_BLANK_SPACE + NBR_WORST,
                                    figsize=((NBR_TEMPLATE + NBR_OF_CANDIDATES + NBR_BLANK_SPACE + NBR_WORST) * 1.5, 3))

            fig.suptitle(
                'Page ' + template["page_name"]
                + " \"" + word + "\" : "
                + str(len(gt_words)) + " instance(s). "
                + str(sum(map(lambda x: x["found"], candidates))) + " found over the first " + str(
                    len(candidates)) + " candidates. "
                + str(round(ap * 100, 2)) + "% AP", fontsize=16)

            fig.tight_layout(pad=10.0)
            plt.axis('off')

            minx, miny, maxx, maxy = Polygon(template["coords"]).bounds

            y_offset_sim = -0.8 if widths.index(target_width) > 1 else -0.5
            y_offset_iou = 1.1 if widths.index(target_width) > 1 else 1.1
            y_offset_page_no = 1.5 if widths.index(target_width) > 1 else 1.5

            # Draw the template first
            axs[0].imshow(images[template["page_no"]][
                          int(miny):int(maxy),
                          int(minx):int(maxx)])
            axs[0].text(0.5, y_offset_page_no, "Page", size=12, ha="center", transform=axs[0].transAxes)
            axs[0].text(0.5, y_offset_sim, "Sim", size=12, ha="center", transform=axs[0].transAxes)
            axs[0].text(0.5, y_offset_iou, "IOU", size=12, ha="center", transform=axs[0].transAxes)
            axs[0].axis('off')

            for i in range(min(len(candidates), 10)):
                cdnt = candidates[i]
                page_no, x, y, sim, found, IOU = cdnt["page_no"], cdnt["x"], cdnt["y"], cdnt["sim"], \
                    cdnt["found"] if "found" in cdnt else False, cdnt["IOU"] if "IOU" in cdnt else 0

                to_draw = cv2.copyMakeBorder(
                    images[page_no][int(y):int(y + H), int(x):int(x + target_width)],
                    top=3,
                    bottom=3,
                    left=3,
                    right=3,
                    borderType=cv2.BORDER_CONSTANT,
                    value=[0, 255, 0] if found else [255, 0, 0]
                )

                axs[i + NBR_TEMPLATE].axis('off')
                axs[i + NBR_TEMPLATE].imshow(to_draw, interpolation='nearest', cmap='Greys_r')

                axs[i + NBR_TEMPLATE].text(0.5, y_offset_sim, str(round(sim, 3)), size=12, ha="center",
                                           transform=axs[i + 1].transAxes)

                axs[i + NBR_TEMPLATE].text(0.5, y_offset_iou, str(round(IOU, 3)), size=12, ha="center",
                                           transform=axs[i + 1].transAxes)

                # only write the page number for the choosen candidates (first row)
                axs[i + NBR_TEMPLATE].text(0.5, y_offset_page_no, str(page_no), size=12,
                                           ha="center",
                                           transform=axs[i + 1].transAxes)

            # Draw blank
            draw_blank(axs, NBR_TEMPLATE + NBR_OF_CANDIDATES, H, target_width, y_offset_sim)

            for i in range(len(worst_candidates)):
                worst_candidate = worst_candidates[i]
                page_no, x, y, sim = worst_candidate["page_no"], worst_candidate["x"], worst_candidate["y"], \
                    worst_candidate["sim"]

                to_draw = images[page_no][int(y):int(y + H),
                          int(x):int(x + target_width)]

                axs[NBR_TEMPLATE + NBR_OF_CANDIDATES + NBR_BLANK_SPACE + i].axis('off')
                try:

                    axs[NBR_TEMPLATE + NBR_OF_CANDIDATES + NBR_BLANK_SPACE + i].imshow(to_draw)
                except:
                    print("worst_candidates oups")

                axs[NBR_TEMPLATE + NBR_OF_CANDIDATES + NBR_BLANK_SPACE + i].text(0.5, y_offset_sim,
                                                                                str(round(sim, 3)), size=12,
                                                                                ha="center",
                                                                                transform=axs[
                                                                                NBR_TEMPLATE + NBR_OF_CANDIDATES + NBR_BLANK_SPACE + i].transAxes)

            results_folders = "/".join(['results', corpus_name])
            fig.savefig(results_folders + '/' + template["template_id"] + "_results_top10" + '.png')
            plt.draw()
            plt.clf()
            plt.close("all")

    return precision, recall, ap, roc_auc, len(word)

## ['only-from-corpus', 'only-from-non-corpus', 'intersection', 'all']
def split_train_test(images, templates, strategy, part_corpus=None):
    if part_corpus and strategy:

        idxs_corpus_images = part_corpus_to_idxs(part_corpus, len(images))
        idxs_query_images = list(set(list(range(0, len(images)))) - set(idxs_corpus_images))

        images_splitted = {"corpus": [], "query": []}
        templates_splitted = {"corpus": [], "query": []}

        if strategy == "only-from-corpus":
            for template in templates:
                if template["page_no"] in idxs_corpus_images:
                    templates_splitted["corpus"].append(template)
                    templates_splitted["query"].append(template)

            for ii in range(len(images)):
                if ii in idxs_corpus_images:
                    images_splitted["corpus"].append(images[ii])
                    images_splitted["query"].append(images[ii])

        elif strategy == 'only-from-non-corpus':
            for template in templates:
                if template["page_no"] in idxs_query_images:
                    templates_splitted["corpus"].append(template)
                    templates_splitted["query"].append(template)

            for ii in range(len(images)):
                if ii in idxs_query_images:
                    images_splitted["corpus"].append(images[ii])
                    images_splitted["query"].append(images[ii])

        elif strategy == "intersection":
            for template in templates:
                if template["page_no"] in idxs_corpus_images:
                    templates_splitted["corpus"].append(template)
                else:
                    templates_splitted["query"].append(template)

            for ii in range(len(images)):
                if ii in idxs_corpus_images:
                    images_splitted["corpus"].append(images[ii])
                else:
                    images_splitted["query"].append(images[ii])

        else:
            images_splitted = {"corpus": images, "query": images}
            templates_splitted = {"corpus": templates, "query": templates}
    else:
        images_splitted = {"corpus": images, "query": images}
        templates_splitted = {"corpus": templates, "query": templates}

    return images_splitted, templates_splitted

def filter_by_word_size(templates, template_text_limit):
    return list(filter(lambda x: len(x["word"]) > template_text_limit, templates))


import networkx as nx
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
import json
import os
from io import BytesIO
from typing import List
import openai
import PyPDF2
from langchain.embeddings import OpenAIEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter
import chainlit as cl

openai.api_key = ""
openai_api_key = ""

text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)

system_template = """Use the following pieces of context to answer the users question.
If you don't know the answer, just say that you don't know, don't try to make up an answer.
ALWAYS return a "SOURCES" part in your answer.
The "SOURCES" part should be a reference to the source of the document from which you got your answer.

And if the user greets with greetings like Hi, hello, How are you, etc reply accordingly as well.

Example of your response should be:

The answer is foo
SOURCES: xyz

Begin!
----------------
{summaries}"""

@cl.on_chat_start
async def on_chat_start():
    files = None
    # Wait for the user to upload a file
    while files == None:
        files = await cl.AskFileMessage(
            content="Please upload a text file to begin!",
            accept=["application/pdf", "text/plain"],
            max_size_mb=100,
            timeout=180,
            max_files=5
        ).send()

    chunks = []
    for file in files:
        _, ext = os.path.splitext(file.name)
        print(f"File type: {ext}")

        msg = cl.Message(
                content=f"Processing `{file.name}`...", disable_human_feedback=True
            )
        await msg.send()

        if ext == ".txt":
            tex = file.content.decode("utf-8")
            chunks.extend(text_splitter.split_text(text=tex))
        elif ext == ".pdf":
            print("entered pdf elif")
            pdf_file = PyPDF2.PdfReader(BytesIO(file.content))

            # Get the total number of pages in the PDF file.
            num_pages = len(pdf_file.pages)

            # Create a list to store the decoded text from each page.
            decoded_text = []

            # Decode each page of the PDF file and add the decoded text to the list.
            for i in range(num_pages):
                page = pdf_file.pages[i]
                decoded_text.append(page.extract_text())

            for text in decoded_text:
                chunks.extend(text_splitter.split_text(text))

    metadatas = [{"source": f"{i}-pl"} for i in range(len(chunks))]

    embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key, openai_model="text-embedding-ada-002")

    documents_embedded = embeddings.embed_documents(chunks)

    G = nx.Graph()
    if os.path.exists('graph.json'):
        with open("graph.json", "r") as f:
            data = json.load(f)
            G = data

    for idx, (text, embedding, source) in enumerate(zip(chunks, documents_embedded, metadatas)):
        G.add_node(idx, text=text, embedding=embedding, source=source)
    for idx1, data1 in G.nodes(data=True):
        for idx2, data2 in G.nodes(data=True):
            if idx1 != idx2:
                similarity = cosine_similarity([data1['embedding']], [data2['embedding']])[0][0]
                if similarity > 0.75:
                    G.add_edge(idx1, idx2, weight=similarity)
    data = nx.node_link_data(G)
    with open("graph.json", "w") as f:
        json.dump(data, f)

    msg.content = f"Processing `{file.name}` done. You can now ask questions!"
    await msg.update()

    cl.user_session.set("Graph", G)

@cl.on_message
async def main(message: cl.Message):
    graph = cl.user_session.get("Graph")  # type: ConversationalRetrievalChain

    embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key, openai_model="text-embedding-ada-002")
    userembed = embeddings.embed_documents(message.content)
    resentry, resneighbors = query_graph(userembed, graph)
    neighbor_texts = [neighbor['text'] for neighbor in resneighbors]

    # Joining neighbor texts into a single string with newline separator
    neighbor_texts_str = '\n'.join(neighbor_texts)

    # Updating the prompt to include all neighbor texts
    prompt = f"{system_template}\n\nContext: {resentry['text']}\n{neighbor_texts_str}\n\nUser: {message.content}\n"
    print(prompt)
    messages = [
        {"role": "system", "content": "You will use the context in the user input to generate factual output about new information"}
        ]
    finalprompt = {"role": "user", "content": prompt}
    messages.append(finalprompt)
    completion = openai.ChatCompletion.create(
        model = "gpt-4",
        messages = messages,
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=0.5,
    )
    result = completion["choices"][0]["message"]
    answer = result['content']
    source_documents =[]    # type: List[Document]
    source_documents.append(resentry['source'])
    for neighbor in resneighbors:
        source_documents.append(neighbor['source'])
    text_elements = []  # type: List[cl.Text]

    if source_documents:
        for source_idx, source_doc in enumerate(source_documents):
            source_name = f"source_{source_idx}"
            text_elements.append(
                cl.Text(content=source_doc['source'], name=source_name)
            )
        source_names = [text_el.name for text_el in text_elements]
        if source_names:
            answer += f"\nSources: {', '.join(source_names)}"
        else:
            answer += "\nNo sources found"
    await cl.Message(content=answer, elements=text_elements).send()

def query_graph(query_embedding, G):
    # Ensure query_embedding is a numpy array
    query_embedding = np.array(query_embedding).flatten()

    # Determine the smallest dimension among all embeddings
    min_dimension = min(
        [len(data['embedding']) for idx, data in G.nodes(data=True)],
        default=len(query_embedding)
    )

    # Slice each embedding and the query_embedding to have the same size
    similarities = [
        (
            idx,
            cosine_similarity(
                [np.array(data['embedding']).flatten()[:min_dimension]],
                [query_embedding[:min_dimension]]
            )[0][0]
        )
        for idx, data in G.nodes(data=True)
    ]
    entry_point_node_idx, _ = max(similarities, key=lambda x: x[1])

    # Gather nodes that are one relation away
    neighbors = list(G.neighbors(entry_point_node_idx))

    # Return the entry point node and its neighbors
    return G.nodes[entry_point_node_idx], [G.nodes[neighbor_idx] for neighbor_idx in neighbors]


"""
You are given a sorted unique integer array nums.

Return the smallest sorted list of ranges that cover all the numbers
in the array exactly. That is, each element of nums is covered by
exactly one of the ranges, and there is no integer x such that x is
in one of the ranges but not in nums.

Each range [a,b] in the list should be output as:

"a->b" if a != b
"a" if a == b

Example 1:
Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

Example 2:
Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The ranges are:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

Example 3:
Input: nums = []
Output: []

Example 4:
Input: nums = [-1]
Output: ["-1"]

Example 5:
Input: nums = [0]
Output: ["0"]

Constraints:
0 <= nums.length <= 20
-231 <= nums[i] <= 231 - 1
All the values of nums are unique.
"""
from typing import List

class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        summary: List[str] = []
        start_index: int = 0
        for index in range(len(nums)):
            if index + 1 < len(nums) and nums[index + 1] == nums[index] + 1:
                continue
            if start_index == index:
                summary.append(str(nums[start_index]) + "")
            else:
                summary.append(str(nums[start_index]) + "->" + str(nums[index]))

            start_index = index + 1

        return summary


import unittest
from cartoframes.viz import widgets

class TestDefaultWidget(unittest.TestCase):
    def test_widgets(self):
        "should be defined"
        self.assertNotEqual(widgets.default_widget, None)

    def test_factory(self):
        "should create a default widget"
        widget = widgets.default_widget(title='Default Widget')
        widget_info = widget.get_info()
        self.assertEqual(widget_info.get('type'), 'default')
        self.assertEqual(widget_info.get('title'), 'Default Widget')


from _csv import register_dialect, QUOTE_ALL
import csv
import codecs
import cStringIO
from HTMLParser import HTMLParser
from itertools import groupby
from django.conf import settings

def currency_converter(amount, year):
    return amount * settings.OPENAID_CURRENCY_CONVERSIONS[year]

def eur_to_usd_converter(amount, year):
    return amount / settings.OPENAID_CURRENCY_CONVERSIONS[year]

def sanitize_get_param(param_type, param, default, top=None, length=None):
    # simple sanitize of GET parameter and converting to param_type
    # if fails: return default value
    # if top is defined and the value is > than top: return default
    if not param:
        return default
    if length:
        if len(param) > length:
            param = param[:length]
    try:
        value = param_type(param)
    except ValueError:
        return default
    else:
        if top:
            if value > top:
                return default
            else:
                return value
        return value

class UTF8Recoder:
    """
    Iterator that reads an encoded stream and reencodes the input to UTF-8
    """

    def __init__(self, f, encoding):
        self.reader = codecs.getreader(encoding)(f)

    def __iter__(self):
        return self

    def next(self):
        return self.reader.next().encode("utf-8")

class UnicodeDictReader:
    """
    A CSV reader which will iterate over lines in the CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        f = UTF8Recoder(f, encoding)
        self.reader = csv.DictReader(f, dialect=dialect, **kwds)

    def next(self):
        row = self.reader.next()
        return dict((k, unicode(s, "utf-8")) for k, s in row.iteritems() if s is not None)

    def __iter__(self):
        return self

class UnicodeDictWriter(object):
    def __init__(self, f, fieldnames, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.DictWriter(self.queue, fieldnames, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, D):
        try:
            self.writer.writerow(dict([(k,v.encode("utf-8")) for k,v in D.items()]))
        except UnicodeEncodeError:
            import pprint
            pprint.pprint(D['geography'])
            return
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for D in rows:
            self.writerow(D)

class ExcelSemicolon(csv.excel):
    """Extends excel Dialect in order to set semicolon as delimiter."""
    delimiter = ';'
    quoting = QUOTE_ALL

register_dialect("excel_semicolon", ExcelSemicolon)

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []

    def handle_data(self, d):
        self.fed.append(d)

    def get_data(self):
        return ' '.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

# converts a qset into a dict using the key field
def convert2dict(queryset, key_field):
    if type(key_field) == tuple or type(key_field) == list:
        if len(key_field) == 0:
            raise Exception
        else:
            indice_keygen = lambda x: tuple(x[key] for key in key_field)

    else:
        indice_keygen = lambda x: x[key_field]

    return dict((k, list(v)) for k, v in groupby(queryset, key=indice_keygen))


import os
from PyPDF2 import PdfReader, PdfWriter

path = r"D:\python\real_python_materials\book1-exercises\chp11\practice_files"

input_file_name = os.path.join(path, 'Pride and Prejudice.pdf')
input_file = PdfReader(open(input_file_name, 'rb'))

output_pdf = PdfWriter()

for page_num in range(1, 4):
    output_pdf.add_page(input_file.pages[page_num])

with open('lecture_output.pdf', 'wb') as output_file:
    output_pdf.write(output_file)

from PyPDF2 import PdfReader, PdfWriter
import copy
import os

path = r"D:\python\real_python_materials\book1-exercises\chp11\practice_files"
input_file = PdfReader(open(path + '\\half and half.pdf', 'rb'))
output_pdf = PdfWriter()

for page_num in range(len(input_file.pages)):
    page_left = input_file.pages[page_num]
    page_right = copy.copy(page_left)
    upper_right = page_left.mediabox.upper_right

    page_left.mediabox.upper_right = (upper_right[0] / 2, upper_right[1])
    output_pdf.add_page(page_left)

    page_right.mediabox.upper_left = (upper_right[0] / 2, upper_right[1])
    output_pdf.add_page(page_right)

output_file_name = 'The little Mermaid.pdf'
output_file = open(output_file_name, 'wb')
output_pdf.write(output_file)
output_file.close()

import os
from PyPDF2 import PdfReader, PdfWriter

path = r"D:\python\real_python_materials\book1-exercises\chp11\practice_files"
input_file_name = os.path.join(path, "The Emperor.pdf")
input_file = PdfReader(open(input_file_name, "rb"))
output_PDF = PdfWriter()

watermark_file_name = os.path.join(path, "top secret.pdf")
watermark_file = PdfReader(open(watermark_file_name, "rb"))

for page_num in range(0, len(input_file.pages)):
    page = input_file.pages[page_num]
    page.merge_page(watermark_file.pages[0]) # add watermark image
    output_PDF.add_page(page)

output_PDF.encrypt("good2Bking") # add a password to the PDF file
output_file_name = "New Suit.pdf"
output_file = open(output_file_name, "wb")
output_PDF.write(output_file)
output_file.close()


# 3. Задайте список из n чисел, заполненный по формуле (1 + 1/n) ** n и выведите на экран их сумму.
# in
# 6

# out
# [2.0, 2.25, 2.37, 2.441, 2.488, 2.522]
# 14.071

number = int(input('Пожалуйста, введите количество чисел в списке -> '))
number_sum = 0
list_num = []

for i in range(1, number+1):
    res = round((1+1/i)**i, 3)
    list_num.append(res)
    number_sum = number_sum + res

print(list_num)
print('Сумма чисел равна - >', number_sum)


import pygame
import os
from pygame.math import Vector2

class Player:
    def __init__(self):
        self.animations = {}
        self.initialize_animation_frames("./assets/dwarf/")

        self.frame = 0
        self.direction = "right"
        self.animation = "wait" + "_" + self.direction
        # animations_forced are here to loop entirely through these ones before moving to a next one
        self.animations_forced = ["hattack"]
        self.can_change_next_animation = True
        self.sprite = self.animations[self.animation][self.frame]
        self.sprite_rect = self.sprite.get_rect()
        self.speed = 4

    def initialize_animation_frames(self, main_path):
        # this method initialize all animations from the main_path by itself
        # given that main_path only contains one folder per animation
        # MAIN PATH /
        #       FOLDER_1 /
        #           FRAME_1
        #           FRAME_2
        #           FRAME_3
        #       FOLDER_2 /
        #           FRAME_1
        #           FRAME_2
        animation_subdirectories = os.walk(main_path)
        for name, sub_directories, files in filter(
            lambda sub_dir: sub_dir[0] != main_path, animation_subdirectories
        ):
            # we have to take name of the directory, excluding all path from it
            # ./assets/dwarf/death, we only want death
            # split all the path
            path_names = name.split("/")
            # and get the last element
            animation_type = path_names[len(path_names) - 1]

            for index, animation_file in enumerate(sorted(files)):
                if index == 0:
                    self.animations.update(
                        {
                            animation_type: [
                                pygame.image.load("{}/{}".format(name, animation_file))
                            ]
                        }
                    )
                    continue
                self.animations[animation_type].append(
                    pygame.image.load("{}/{}".format(name, animation_file))
                )

    def animate(self, animation):
        if self.can_change_next_animation:
            # will animate player with given animation
            match_previous_animation = (
                self.animation == animation + "_" + self.direction
            )
            # if the animation changes from previous frame, we will reset frame
            self.frame = self.frame if match_previous_animation else 0

            self.animation = animation + "_" + self.direction

        if animation in self.animations_forced:
            self.can_change_next_animation = False

        animation_sprites = self.animations[self.animation]
        # modulo, to always have frame index of animation_sprites, even if self.frame is way higher than the len of animation_sprites
        self.sprite = animation_sprites[int(self.frame) % len(animation_sprites)]
        # animation is rendered in sprite, we will now update frame to next animation
        # by updating of 0.5, we will slow down animation
        # 0.5 means animation will need 2 frames rendered by pygame to pass to the next frame
        self.frame += 0.5
        # if we have finished the loop for the forced_animation, we can change the next animation
        if (
            int(self.frame) == len(self.animations[self.animation])
            and not self.can_change_next_animation
        ):
            self.frame = 0
            self.can_change_next_animation = True

    def move(self, direction, camera):
        self.direction = "left" if direction.x < 0 else "right"
        # camera follow player
        # so we move player as we moved the camera
        camera_movement = camera.update(direction)
        self.sprite_rect = self.sprite_rect.move(camera_movement)

    def input(self, camera=None):
        # get state of all keys (pressed or not)
        keys = pygame.key.get_pressed()

        vector_direction = Vector2(0, 0)

        up = keys[pygame.K_UP]
        down = keys[pygame.K_DOWN]
        left = keys[pygame.K_LEFT]
        right = keys[pygame.K_RIGHT]
        space = keys[pygame.K_SPACE]

        if up:
            vector_direction.y -= self.speed
            self.move(vector_direction, camera)
        elif down:
            vector_direction.y += self.speed
            self.move(vector_direction, camera)
        elif left:
            vector_direction.x -= self.speed
            self.move(vector_direction, camera)
        elif right:
            vector_direction.x += self.speed
            self.move(vector_direction, camera)

        # can_change_next_animation is here to avoid register too many animation when spamming escape
        if space and self.can_change_next_animation:
            self.animate("hattack")
        elif up or down or left or right:
            self.animate("run")
        else:
            self.animate("wait")


import reflex as rx

from app import style
from app.state import State

def chat() -> rx.Component:
    return rx.box(
        rx.text(State.chat_history, style=style.question_style)
        #rx.foreach(
        #    State.chat_history,
        #    lambda messages: qa(messages[0], messages[1]),
        #)
    )

def action_bar() -> rx.Component:
    return rx.hstack(
        rx.input(
            value=State.question,
            placeholder="Put in a review...",
            on_change=State.set_question,
            style=style.input_style,
        ),
        rx.button(
            "Ask",
            on_click=State.answer,
            style=style.button_style,
        ),
    )
color = "rgb(107,99,246)"

#def upload():
#    """The main view."""
#    return rx.vstack(
#        rx.upload(
#            rx.vstack(
#                rx.button(
#                    "Select File",
#                    color=color,
#                    bg="white",
#                    border=f"1px solid {color}",
#                ),
#                rx.text(
#                    "Drag and drop files here or click to select files"
#                ),
#            ),
#            border=f"1px dotted {color}",
#            padding="5em",
#        ),
#        rx.hstack(rx.foreach(rx.selected_files, rx.text)),
#        rx.button(
#            "Upload",
#            on_click=lambda: State.handle_upload(
#               rx.upload_files()
#            ),
#        ),
#        rx.button(
#            "Clear",
#            on_click=rx.clear_selected_files,
#        ),
#        rx.foreach(
#            State.img, lambda img: rx.image(src=img)
#        ),
#        padding="5em",
#    )

def index() -> rx.Component:
    return rx.container(
        action_bar(),
        chat(),
    )

app = rx.App()
app.add_page(index)
app.compile()


#6932621
#BOAKYE SEKYERE NANA YAW
#https://github.com/Wybee705
Car=["toyota land cruiser","toyota v8","honda civic","honda accord","mitshibushi","toyota rav4","lexus", "ferrari","G-Wagon","benz s-class","toyota vitz","KIA","nissan pickup","ford pickup", "bugatti","BMW","Mesarrartti", "Jeep","Toyota highlander", "wolf wagon","hyundai","toyota camry","toyota sequai v8","cheveroltt SUV","toyota SUV"]
Models=["2001","2005","2010","2015","2020"]
Price=[2453000,4453500,1645600,15035600,23566600]
CarModelPrice=[]
print("Welcome to Wybees Car Garage")
order=input("Name the car you like to buy?")
if order in Car:
   model=input(" enter the model of the car you would like to purchase.")
   if model in Models:
     if model=="2001":
      print("The price of the vehicle chosen is GHS",Price[0])
     elif model=="2005":
      print("The price of the vehicle chosen is GHS",Price[1])
     elif model=="2010":
      print("The price of the vehicle chosen is GHS",Price[2])
     elif model=="2015":
      print("The price of the vehicle chosen is GHS",Price[3])
     elif model=="2020":
      print("The price of the vehicle chosen is GHS",Price[4])
   else:
     print("This model is not available")
else:
 print("This vehicle is not available")


#-*-coding: utf-8 -*-
# 1- Definir una función max() que tome como argumento dos números
# y devuelva el mayor de ellos. (Es cierto que python tiene una función max()
# incorporada, pero hacerla nosotros mismos es un muy buen ejercicio.

# la funcion se llama "rmax" por "reto max"
def rmax(num1, num2):
	if num1 > num2:
		print("{} es mayor que {}".format(num1, num2))
	elif num1 == num2:
		print("son iguales")
	else:
		print("{} es mayor que {}".format(num2, num1))

if __name__ == '__main__':
	print("ingresa solo numeros enteros")
	try:
		number1 = int(raw_input("ingresa un numero: "))
		number2 = int(raw_input("ingresa otro numero: "))
		rmax(number1, number2)
	except Exception as e:
		print("ese no es un numero entero")


# numeric imports
import numpy as np
import torch

# typing imports
from typing import List, Tuple, Dict

def get_theta_and_V(
    daily_excess_return_series : np.ndarray,
    daily_risk_free_series : np.ndarray,
    signal : np.ndarray,
    initial_cash : float = 200_000.,
    leverage : float = 5.) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Evaluates a mean reversion strategy given a signal and returns the theta, V_asset, V_cap and V_total

    Arguments:
    ----------
    daily_excess_return_series  : {np.ndarray}
                                    > The daily excess return series
    daily_risk_free_series      : {np.ndarray}
                                    > The daily risk free rate series
    signal                      : {np.ndarray}
                                    > The signal series
    initial_cash                : {float}
                                    > The initial cash
    leverage                    : {float}
                                    > The leverage

    Returns:
    ----------
    theta                       : {np.ndarray}
                                    > The dollar values (either long or short)
    V_asset                     : {np.ndarray}
                                    > The unlevereaged value of the assets.
    V_cap                       : {np.ndarray}
                                    > The value of the unused capital.
    V_total                     : {np.ndarray}
                                    > The total value of the holdings.
    """
    # ge let n_days
    n_days = len(signal)

    # set up
    theta = np.zeros((n_days,))

    # assets
    V_t = np.zeros((n_days,))
    delta_V_t = np.zeros((n_days,))

    # money market
    V_cap = np.zeros((n_days,))
    delta_V_cap = np.zeros((n_days,))

    # total
    V_total = np.zeros((n_days,))
    delta_V_total = np.zeros((n_days,))

    # # initial values
    V_t[0] = initial_cash
    delta_V_t[0] = 0
    V_cap[0] = 0
    delta_V_cap[0] = 0
    V_total[0] = V_t[0] + delta_V_cap[0]
    delta_V_total[0] = 0

    # backtest strategy
    for i, s in enumerate(signal[:-1]):

        if i == 0:
            continue

       # get position size
        # theta[i] = V_t[i-1] * leverage * s
        theta[i] = V_total[i-1] * leverage * s

        # get V_t
        delta_V_t[i] = (daily_excess_return_series[i+1] * theta[i])
        V_t[i] = delta_V_t[i] + V_t[i-1]

        # get V_cap_t
        M = np.abs(theta[i]) / leverage
        delta_V_cap[i] = (V_total[i-1] - M) * (daily_risk_free_series[i+1])
        V_cap[i] = delta_V_cap[i] + V_cap[i-1]

        # Get V_total_t
        delta_V_total[i] = delta_V_t[i] + delta_V_cap[i]
        V_total[i] = delta_V_total[i] + V_total[i-1]

    strategy_data = {
        "theta" : theta,
        "V_t" : V_t,
        "delta_V_t" : delta_V_t,
        "V_cap" : V_cap,
        "delta_V_cap" : delta_V_cap,
        "V_total" : V_total,
        "delta_V_total" : delta_V_total}

    return strategy_data

def get_turnover_dollars(
    theta : np.ndarray,
    ) -> float:
    """
    Calculates the turnover in dollars traded over time

    Arguments:
    ----------
        theta       : {np.ndarray}
                        > The dollar values invested

    Returns:
    ----------
        turnover    : {float}
                       > The turnover in dollars traded over time
    """
    theta_delta = np.diff(theta)
    turnover = np.sum(np.abs(theta_delta))
    return turnover

def get_turnover_units(
    theta : np.ndarray,
    price_series : np.ndarray
        ) -> float:
    """
    Calculates the turnover in units traded over time

    Arguments:
    ----------
        theta           : {np.ndarray}
                            > The dollar values invested
        price_series    : {np.ndarray}
                            > The price series

    Returns:
    ----------
        turnover        : {float}
                            > The turnover in units traded over time
    """
    theta_over_price = theta / price_series
    turnover = np.sum(np.abs(np.diff(theta_over_price)))
    return turnover

def get_daily_trading_pnl(
    unleveraged_asset_holdings : np.ndarray,
    ) -> np.ndarray:
    """
    Calculates the daily trading PnL for the strategy.

    Arguments:
    ----------
    unleveraged_asset_holdings  : {np.ndarray}
                                    > The daily holdings of the asset.

    Returns:
    --------
    daily_trading_pnl           : {np.ndarray}
                                    > The daily trading PnL.
    """
    # calculate the daily trading pnl
    daily_trading_pnl = np.diff(unleveraged_asset_holdings)
    return daily_trading_pnl

def get_daily_money_market_capital_account(
    money_market_capital_account : np.ndarray,
    ) -> np.ndarray:
    """
    Calculates the daily money market capital account for unused cash for the the strategy.

    Arguments:
    ----------
    money_market_capital_account        : {np.ndarray}
                                            > The daily money market capital account for unused cash.

    Returns:
    ----------
    daily_money_market_capital_account  : {np.ndarray}
                                            > The daily money market capital account for unused cash.
    """
    # calculate the daily money market capital account
    daily_money_market_capital_account = np.diff(money_market_capital_account)
    return daily_money_market_capital_account

def get_daily_total_holdings(
    total_holdings : np.ndarray,
    ) -> np.ndarray:
    """
    Calculates the daily total holdings for the strategy.

    Arguments:
    ----------
    total_holdings      : {np.ndarray}
                            > The daily total holdings for the strategy.

    Returns:
    ----------
    daily_total_holdings : {np.ndarray}
                            > The daily total holdings for the strategy.
    """
    # calculate the daily total holdings
    daily_total_holdings = np.diff(total_holdings)
    return daily_total_holdings


import collections
import copy
from typing import Any, Mapping, Optional
from ..components.structures import ComponentSpec, ComponentReference
from ..components._components import _default_component_name, _resolve_command_line_and_paths
from ..components._naming import _sanitize_python_function_name, generate_unique_name_conversion_table
from .. import dsl

def _create_container_op_from_component_and_arguments(
    component_spec: ComponentSpec,
    arguments: Mapping[str, Any],
    component_ref: Optional[ComponentReference] = None,
) -> 'dsl.ContainerOp':
    # Check types of the reference arguments and serialize PipelineParams
    arguments = arguments.copy()
    for input_name, argument_value in arguments.items():
        if isinstance(argument_value, dsl.PipelineParam):
            input_type = component_spec._inputs_dict[input_name].type
            reference_type = argument_value.param_type
            dsl.types.verify_type_compatibility(reference_type, input_type, 'Incompatible argument passed to the input "{}" of component "{}": '.format(input_name, component_spec.name))

            arguments[input_name] = str(argument_value)
        if isinstance(argument_value, dsl.ContainerOp):
            raise TypeError('ContainerOp object was passed to component as an input argument. Pass a single output instead.')

    resolved_cmd = _resolve_command_line_and_paths(
        component_spec=component_spec,
        arguments=arguments,
    )

    container_spec = component_spec.implementation.container

    old_warn_value = dsl.ContainerOp._DISABLE_REUSABLE_COMPONENT_WARNING
    dsl.ContainerOp._DISABLE_REUSABLE_COMPONENT_WARNING = True

    # Merge output_paths and output_uris to get the file_outputs.
    file_outputs = collections.OrderedDict(resolved_cmd.output_paths or {})
    for name, output_uri in resolved_cmd.output_uris.items():
        file_outputs[name] = output_uri

    artifact_argument_paths = [
        dsl.InputArgumentPath(
            argument=arguments[input_name],
            input=input_name,
            path=path,
        )
        for input_name, path in resolved_cmd.input_paths.items()
    ]

    for input_name, input_uri in resolved_cmd.input_uris.items():
        artifact_argument_paths.append(
            dsl.InputArgumentPath(
                argument=arguments[input_name],
                input=input_name,
                path=input_uri
            ))

    task = dsl.ContainerOp(
        name=component_spec.name or _default_component_name,
        image=container_spec.image,
        command=resolved_cmd.command,
        arguments=resolved_cmd.args,
        file_outputs=file_outputs,
        artifact_argument_paths=artifact_argument_paths,
    )
    dsl.ContainerOp._DISABLE_REUSABLE_COMPONENT_WARNING = old_warn_value

    component_meta = copy.copy(component_spec)
    task._set_metadata(component_meta)
    component_ref_without_spec = copy.copy(component_ref)
    component_ref_without_spec.spec = None
    task._component_ref = component_ref_without_spec

    task._parameter_arguments = resolved_cmd.inputs_consumed_by_value

    # Previously, ContainerOp had strict requirements for the output names, so we had to
    # convert all the names before passing them to the ContainerOp constructor.
    # Outputs with non-pythonic names could not be accessed using their original names.
    # Now ContainerOp supports any output names, so we're now using the original output names.
    # However to support legacy pipelines, we're also adding output references with pythonic names.
    # TODO: Add warning when people use the legacy output names.
    output_names = [output_spec.name for output_spec in component_spec.outputs or []] # Stabilizing the ordering
    output_name_to_python = generate_unique_name_conversion_table(output_names, _sanitize_python_function_name)
    for output_name in output_names:
        pythonic_output_name = output_name_to_python[output_name]
        # Note: Some component outputs are currently missing from task.outputs (e.g. MLPipeline UI Metadata)
        if pythonic_output_name not in task.outputs and output_name in task.outputs:
            task.outputs[pythonic_output_name] = task.outputs[output_name]

    if container_spec.env:
        from kubernetes import client as k8s_client
        for name, value in container_spec.env.items():
            task.container.add_env_variable(k8s_client.V1EnvVar(name=name, value=value))

    if component_spec.metadata:
        annotations = component_spec.metadata.annotations or {}
        for key, value in annotations.items():
            task.add_pod_annotation(key, value)
        for key, value in (component_spec.metadata.labels or {}).items():
            task.add_pod_label(key, value)
        # Disabling the caching for the volatile components by default
        if annotations.get('volatile_component', 'false') == 'true':
            task.execution_options.caching_strategy.max_cache_staleness = 'P0D'

    return task


# This will be it's own function

def linear_search(search_list : list, target) -> int or None:
    """

    :param search_list: list of items
    :param target: any member of list
    :return: none or int
    """
    # A true implementation looks for the position in the list the target is
    # position if in list (success), or none if failure or -1 since that is not typically index or exception. The failure return depends on needs
    for i in range(0, len(search_list)):
        if search_list[i] == target:
            return i
    return None
    # The for loop is where we get linear runtime. Note: if we defined the list len() by going through members of the
    # list and not tracking it each time the list is edited, then the len() itself is linear already.

def verify(index: int):
    if index is not None:
        print(f"Target found at index: {index}")
    else:
        print("Target not found in list")

numbers = [a for a in range(1,11)]

result = linear_search(numbers,6)
verify(result)


from django.conf.urls import url, include
from . import views
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'tasks', views.NewTaskViewSet)
router.register(r'projects', views.ProjectViewSet)

urlpatterns = [
    url(r'^', include(router.urls))
]


from __future__ import annotations

from typing import Callable, List, Optional, Union
from copy import deepcopy

import torch

class LossWeightTree:
    def __init__(
        self, name: str,
        weight: Union[float, Callable[[int], float]],
        children: Optional[List[LossWeightTree]],
    ) -> None:
        self.name = name
        self.weight = weight
        self.children = children

    def __repr__(self):
        # if self.children is None:
        #     return f'{self.weight}_{self.name}'
        # else:
        #     return f'''{self.weight}x({"+".join([
        #         repr(x) for x in self.children
        #     ])})'''
        return f'<LossWeightTree {self.name} weight={repr(self.weight)}>'

    def __getitem__(self, key):
        for child in self.children:
            if child.name == key:
                return child
        raise KeyError(f'{key} not found.')

    def __setitem__(self, key, value):
        if isinstance(value, __class__):
            assert value.name == key
            for child in self.children:
                if child.name == key:
                    raise ValueError(f'{key} already exists.')
            self.children.append(value)
        else:
            raise TypeError(f'{__class__.__name__} can only setitem {__class__.__name__}.')

    def __contains__(self, key):
        return key in [x.name for x in self.children]

    def getWeight(self, epoch: int):
        try:
            return self.weight(epoch)
        except TypeError:
            return self.weight

    def to(self, device):
        if self.children is None:
            children = None
        else:
            children = [x.to(device) for x in self.children]
        return __class__(
            self.name,
            torch.tensor(self.weight, device=device),
            children,
        )

    def print(self, depth=0):
        print(' ' * depth, self.name, ': ', self.weight, sep='')
        for child in self.children or []:
            child.print(depth + 1)

    def __deepcopy__(self, memo):
        if self.children is None:
            children = None
        else:
            children = [deepcopy(x, memo) for x in self.children]
        return __class__(self.name, self.weight, children)

    def errorAboutWeight(*_):
        raise TypeError('You are probably forgetting `.weight`')
    def __init_class__(cls):
        for operator in (
            '__bool__', '__eq__', '__ne__',
            '__lt__', '__le__',
            '__gt__', '__ge__',
        ):
            setattr(cls, operator, cls.errorAboutWeight)

LossWeightTree.__init_class__(LossWeightTree)


#!/usr/bin/env python
import asyncio
import websockets

async def hello():
    async with websockets.connect("ws://localhost:8001") as websocket:
        speed = input("Enter the speed : ")
        height = input("Enter the height : ")
        while speed != str(-1) and height != str(-1):
            await websocket.send((speed,height))
            msg = await websocket.recv()
            print(msg)
            speed = input("Enter the speed : ")
            height = input("Enter the height : ")
        await websocket.send("close")
        print("client CLOSED")

asyncio.run(hello())


import scipy.cluster.hierarchy as hcluster
from sklearn.cluster import DBSCAN
import numpy as np
import pandas as pd

def get_cluster_id(clusters,route_id):
    """
        Returns the cluster_id of a given route_id
    """
    for i in range(len(clusters)):
        try:
            clusters[i].loc[route_id]
            return i
        except:
            continue

def calculate_route_similarity(routeA,routeB):
    """
        calculates the similarity between two routes
    """
    return len(list(set(routeA).intersection(routeB))) / len(list(dict.fromkeys(routeA + routeB)))

def clustering_by_similarity(routes):
    """
        NOT IMPLEMENTED YET
        clustering of routes by the factor of similarity between them
    """
    clusters = np.zeros(shape=(len(routes.items()),len(routes.items())))
    for key,route in routes.items():
        for subkey,subroute in routes.items():
            if(key>subkey):
                clusters[key][subkey]=SUMO.calculate_route_similarity(route,subroute)
            elif(key==subkey):
                clusters[key][subkey]=1
    print("implemented only to generate similarity matrix")

def clustering_by_location(coords):
    """
        Clustering points by location
    """
    kms_per_radian = 6371.0088
    # by setting epsilon, we set max distance that points can be from each other in a cluster
    # 0.2 km in this example
    epsilon = 0.2 / kms_per_radian
    db = DBSCAN(eps=epsilon, min_samples=1, algorithm='ball_tree', metric='haversine').fit(np.radians(coords))
    cluster_labels = db.labels_
    num_clusters = len(set(cluster_labels))
    clusters = pd.Series([coords[cluster_labels == n] for n in range(num_clusters)])
    return clusters


# -*- coding: utf-8 -*-
# #!/usr/bin/env python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest,re,random
from print_result import printSF
from login_ds import loginFirefox
from VerifyWords import VerifyWords
from to_log import tolog
import time

Pass = "'result': 'p'"
Fail = "'result': 'f'"

class LunmappingDel(unittest.TestCase):
    def test_lunmapping_del(self):
        ValError = []
        Failflag = False
        self.driver = loginFirefox()
        self.verificationErrors = []
        self.accept_next_alert = True
        driver = self.driver
        tolog("Start to DELETE ALL LUN Mapping entries.")
        driver.find_element_by_link_text("Volume").click()
        time.sleep(2)
        driver.find_element_by_link_text("LUN Mapping & Masking").click()
        time.sleep(4)
        if "No LUN mapping entry available." in driver.find_element_by_xpath("//table[2]/tbody").text.split("\n"):
            tolog("No lun mapping entry to be deleted")
            ValError.append("pass")
        else:
            lunmapping_count = len(driver.find_element_by_xpath("//table[2]/tbody").text.split("\n"))
            while lunmapping_count > 0:
                driver.find_element_by_xpath("//b").click()
                time.sleep(1)
                driver.find_element_by_link_text("Delete").click()
                time.sleep(1)
                driver.find_element_by_name("name").clear()
                time.sleep(1)
                driver.find_element_by_name("name").send_keys("confirm")
                time.sleep(1)
                driver.find_element_by_xpath("//button[@type='submit']").click()
                lunmapping_count -= 1
                time.sleep(3)
            if "No LUN mapping entry available." in driver.find_element_by_xpath("//table[2]/tbody").text.split("\n"):
                tolog("All LUN Mapping entrys were deleted!")
                ValError.append("pass")
            else:
                Failflag = True
                tolog("Failed to delete All lunmapping entry!")
                ValError.append("fail")
        for val in ValError:
            if val == "fail":
                Failflag = True
        if Failflag:
            tolog(Fail)
        else:
            tolog(Pass)

    def is_element_present(self, how, what):
        try:
            self.driver.find_element(by=how, value=what)
        except NoSuchElementException as e:
            return False
        return True

    def is_alert_present(self):
        try:
            self.driver.switch_to_alert()
        except NoAlertPresentException as e:
            return False
        return True

    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally:
            self.accept_next_alert = True

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

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


from abc import ABC
import os
from functools import lru_cache

import addict
from PIL import Image
import cv2
import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset

from src.utils.index import index_ego_masks

class BaseDataset(Dataset, ABC):

    def __init__(self, cfg: addict.Dict, image_load_format: str, return_raw_imgs: bool = False):
        # data load config
        self.image_load_format = image_load_format
        self.return_raw_imgs = return_raw_imgs
        # ego masks config
        self._img_mask = None
        self.img_name_to_ego_mask_paths = None
        self.base_path = cfg.base_path
        if cfg.apply_ego_mask_from:
            self.img_name_to_ego_mask_paths = index_ego_masks(cfg.apply_ego_mask_from)
            self.img_name_keys = np.array(list(self.img_name_to_ego_mask_paths.keys()))
            self.img_name_values = np.array(list(self.img_name_to_ego_mask_paths.values()))
        # model cfgs
        self.image_format = cfg.model_cfg.image_format
        self.input_shape = cfg.model_cfg.input_shape
        self.model_type = cfg.model_cfg.model_type
        assert type(cfg.model_cfg.img_mean) is type(cfg.model_cfg.img_std), \
            "both mean and std should be provided"
        self.img_mean, self.img_std = cfg.model_cfg.img_mean, cfg.model_cfg.img_std
        if cfg.model_cfg.img_mean is not None:
            self.img_mean = np.array(cfg.model_cfg.img_mean, dtype=np.float64).reshape(1, -1)
            self.img_stdinv = 1 / np.array(cfg.model_cfg.img_std, dtype=np.float64).reshape(1, -1)
            # self.img_mean = torch.FloatTensor(cfg.model_cfg.img_mean).view(1,1,1,-1)
            # self.img_std = torch.FloatTensor(cfg.model_cfg.img_std).view(1,1,1,-1)
        assert self.model_type in ['onnx', 'torch']
        assert self.image_format in ['rgb', 'bgr']

    @property
    def img_mask(self):
        return self._img_mask

    @img_mask.setter
    def img_mask(self, img_mask):
        self._img_mask = cv2.resize(img_mask, self.input_shape, interpolation=cv2.INTER_NEAREST)

    @lru_cache(maxsize=32)
    def cached_load_mask(self, mask_path: str):
        img_mask = np.array(Image.open(mask_path)) # cv2.imread(mask_path, -1)
        return cv2.resize(img_mask, self.input_shape, interpolation=cv2.INTER_NEAREST)

    def load_nearest_mask(self, img_path):
        if self.img_name_to_ego_mask_paths is None:
            return None
        ego_mask_rel_path = os.path.splitext(os.path.relpath(img_path, self.base_path))[0]
        # if indexing based on numbers
        if ego_mask_rel_path.isdigit():
            ego_mask_num = int(ego_mask_rel_path)
            mask_idx = np.searchsorted(self.img_name_keys, ego_mask_num)
            try:
                img_mask = self.cached_load_mask(self.img_name_values[mask_idx])
            except IndexError:
                img_mask = self.cached_load_mask(self.img_name_values[-1])
            self._img_mask = img_mask
            return img_mask
        # if indexing based on strings
        if ego_mask_rel_path in self.img_name_to_ego_mask_paths:
            self._img_mask = self.cached_load_mask(self.img_name_to_ego_mask_paths[ego_mask_rel_path])
        return self.img_mask

    def preprocess_numpy(self, img: np.ndarray, img_mask: np.ndarray = None,
                   resize : bool = True) -> torch.Tensor:
        # Resize
        if resize and self.input_shape is not None and (img.shape[0] != self.input_shape[1] or img.shape[1] != self.input_shape[0]):
            img = cv2.resize(img, self.input_shape, interpolation=cv2.INTER_LINEAR)
        # Convert to RGB/BGR if needed
        if self.image_format != self.image_load_format:
            cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
        # Apply mask if provided
        if img_mask is not None:
            cv2.bitwise_and(img, img, img, mask=img_mask)
        # Normalize
        if self.img_mean is not None:
            cv2.subtract(img, self.img_mean, img)
            cv2.multiply(img, self.img_stdinv, img)
        return torch.from_numpy(img.transpose((2, 0, 1)))

    def preprocess_torch(self, img: torch.Tensor, img_mask: torch.Tensor = None,
                         resize : bool = True) -> torch.Tensor:
        # Resize
        if resize and self.input_shape is not None:
            img = F.interpolate(img, self.input_shape, mode='linear')
        # Convert to RGB/BGR if needed
        if self.image_format != self.image_load_format:
            img = img[:, :, ::-1]
        # Apply mask if provided
        if img_mask is not None:
            img[img_mask] = 0
        # Normalize
        if self.img_mean is not None:
            img = (img - self.img_mean) / self.img_std
        return img.permute((2, 0, 1))

    def collate_fn(self, batch):
        images, img_masks, metadata = zip(*batch)
        img_masks = None if img_masks[0] is None else torch.stack(img_masks, 0)
        return torch.stack(images, 0), img_masks, metadata

    def collate_fn_numpy(self, batch):
        images, img_masks, metadata = zip(*batch)
        images = np.stack(images, 0)
        img_masks = None if img_masks[0] is None else np.stack(img_masks, 0)

        if self.image_format != self.image_load_format:
            images = images[..., ::-1]
        # Apply mask if provided
        if img_masks is not None:
            images[img_masks] = 0
            img_masks = torch.from_numpy(img_masks)
        # Normalize
        if self.img_mean is not None:
            images = (images - self.img_mean) / self.img_std

        images = images.transpose((0, 3, 1, 2))
        images = torch.from_numpy(images)
        return images, img_masks, metadata

    def collate_fn_torch(self, batch):
        images, img_masks, metadata = zip(*batch)
        images = torch.stack(images, 0)
        img_masks = None if img_masks[0] is None else torch.stack(img_masks, 0)

        if self.image_format != self.image_load_format:
            images = images[:, :, ::-1]
        # Apply mask if provided
        if img_masks is not None:
            images[img_masks] = 0
        # Normalize
        if self.img_mean is not None:
            images = (images - self.img_mean) / self.img_std

        images = images.permute((0, 3, 1, 2))
        return images, img_masks, metadata

    @classmethod
    def postprocess(cls, preds: torch.Tensor, metadata: dict, img_masks: torch.Tensor,
                    ego_mask_cls_id: int, resize_img: bool = False) -> torch.Tensor:
        """Reshape predictions back to original image shape."""
        assert len(preds) == len(metadata)
        # preds = preds.type(torch.uint8)
        if img_masks is not None:
            preds.masked_fill_(img_masks, ego_mask_cls_id)
            # preds[img_masks] = ego_mask_cls_id
        if resize_img and (preds.shape[1] != metadata[0]['height'] or preds.shape[2] != metadata[0]['width']):
            # FIXME: Maybe there is a better way?
            res = [cv2.resize(pred, (metadata[0]['width'], metadata[0]['height']), interpolation=cv2.INTER_NEAREST) for pred in preds.cpu().numpy()]
            preds = torch.from_numpy(np.stack(res, 0))
            # import torchvision.transforms.functional as F
            # preds = F.resize(preds, (metadata[0]['width'], metadata[0]['height']), interpolation=F.InterpolationMode.NEAREST)
        return preds


import logging
from typing import Dict, Optional

from opentrons_shared_data.pipette.dev_types import PipetteNameType
from opentrons.types import Mount

from ..protocol import AbstractProtocol
from ..legacy.legacy_protocol_core import LegacyProtocolCore
from ..legacy.legacy_labware_core import LegacyLabwareCore
from ..legacy.legacy_module_core import LegacyModuleCore
from ..legacy.load_info import InstrumentLoadInfo

from .legacy_instrument_core import LegacyInstrumentCoreSimulator

logger = logging.getLogger(__name__)

class LegacyProtocolCoreSimulator(
    LegacyProtocolCore,
    AbstractProtocol[
        LegacyInstrumentCoreSimulator, LegacyLabwareCore, LegacyModuleCore
    ],
):
    _instruments: Dict[Mount, Optional[LegacyInstrumentCoreSimulator]]  # type: ignore[assignment]

    def load_instrument(  # type: ignore[override]
        self, instrument_name: PipetteNameType, mount: Mount
    ) -> LegacyInstrumentCoreSimulator:
        """Create a simulating instrument context."""
        existing_instrument = self._instruments[mount]

        if (
            existing_instrument
            and existing_instrument.get_requested_as_name() == instrument_name.value
        ):
            # Replacing with the exact same instrument name. Just return the
            # existing instrument instance.
            return existing_instrument

        attached = {
            att_mount: instr.get("name", None)
            for att_mount, instr in self._sync_hardware.attached_instruments.items()
            if instr
        }
        attached[mount] = instrument_name.value
        self._sync_hardware.cache_instruments(attached)

        pipette_dict = self._sync_hardware.get_attached_instruments()[mount]
        new_instr = LegacyInstrumentCoreSimulator(
            protocol_interface=self,
            pipette_dict=pipette_dict,
            mount=mount,
            instrument_name=instrument_name.value,
            api_version=self._api_version,
        )
        self._instruments[mount] = new_instr

        logger.info(f"Instrument {new_instr} loaded")
        self._equipment_broker.publish(
            InstrumentLoadInfo(
                instrument_load_name=instrument_name.value,
                mount=mount,
                pipette_dict=pipette_dict,
            )
        )

        return new_instr


import asyncio
from typing import cast

import discord
from sqlalchemy import and_, delete
from sqlalchemy.ext.asyncio import AsyncSession

from ..bot import embed
from ..models import Cooldown, Egg, Hunt
from .base import EasterbotContext, controled_command, egg_command_group

@egg_command_group.command(
    name="reset", description="Réinitialiser la chasse aux œufs"
)
@controled_command(cooldown=True, administrator=True)
async def reset_command(ctx: EasterbotContext) -> None:
    await ctx.defer(ephemeral=True)
    view = discord.ui.View(timeout=None)
    cancel = discord.ui.Button(  # type: ignore
        label="Annuler", style=discord.ButtonStyle.danger
    )
    view.add_item(cancel)
    confirm = discord.ui.Button(  # type: ignore
        label="Confirmer", style=discord.ButtonStyle.success
    )
    view.add_item(confirm)
    done = False
    cancel_embed = embed(
        title="Réinitialisation annulée",
        description="Vous avez annulé la demande de réinitialisation.",
    )
    confirm_embed = embed(
        title="Réinitialisation",
        description=(
            "L'ensemble des salons, œufs "
            "et temps d'attentes ont été réinitialisatiés."
        ),
    )

    async def cancel_callback(
        interaction: discord.Interaction,
    ) -> None:
        nonlocal done
        done = True
        view.disable_all_items()
        view.stop()
        await asyncio.gather(
            message.edit(view=view),
            interaction.response.send_message(
                embed=cancel_embed,
                ephemeral=True,
            ),
        )

    async def confirm_callback(
        interaction: discord.Interaction,
    ) -> None:
        nonlocal done
        done = True
        view.disable_all_items()
        view.stop()
        await asyncio.gather(
            message.edit(view=view),
            interaction.response.defer(ephemeral=True),
        )

        async with AsyncSession(ctx.bot.engine) as session:
            await session.execute(
                delete(Hunt).where(Hunt.guild_id == ctx.guild_id)
            )
            await session.execute(
                delete(Egg).where(Egg.guild_id == ctx.guild_id)
            )
            await session.execute(
                delete(Cooldown).where(
                    and_(
                        Cooldown.guild_id == ctx.guild_id,
                        Cooldown.command != "reset",
                    )
                )
            )
            await session.commit()
        await interaction.followup.send(
            embed=confirm_embed,
            ephemeral=True,
        )

    cancel.callback = cancel_callback  # type: ignore
    confirm.callback = confirm_callback  # type: ignore
    message = cast(
        discord.WebhookMessage,
        await ctx.followup.send(
            embed=embed(
                title="Demande de réinitialisation",
                description=(
                    "L'ensemble des salons, œufs "
                    "et temps d'attentes vont être réinitialisatiés."
                ),
                footer="Vous avez 30 secondes pour confirmer",
            ),
            ephemeral=True,
            view=view,
        ),
    )
    await asyncio.sleep(30.0)
    if not done:
        view.disable_all_items()
        view.stop()
        await asyncio.gather(
            message.edit(view=view),
            ctx.followup.send(embed=cancel_embed, ephemeral=True),
        )


import os
import unittest
from unittest.mock import patch

from k8s_handle import settings
from k8s_handle import handler_deploy
from kubernetes import client

class TestDeployHandler(unittest.TestCase):

    def setUp(self):
        settings.CONFIG_FILE = 'tests/fixtures/config_with_env_vars.yaml'
        settings.TEMPLATES_DIR = 'templates/tests'
        os.environ['K8S_CONFIG_DIR'] = '/tmp/kube/'
        os.environ['SECTION1'] = 'not found'
        os.environ['SECTION'] = 'section-1'

    @patch('k8s_handle.templating.Renderer._generate_file')
    @patch('kubernetes.client.api.version_api.VersionApi.get_code_with_http_info')
    @patch('k8s_handle.k8s.provisioner.Provisioner.run')
    def test_api_exception_handling(
        self,
        mocked_provisioner_run,
        mocked_client_version_api_get_code,
        mocked_generate_file
    ):
        mocked_client_version_api_get_code.side_effect = client.exceptions.ApiException(
            'Max retries exceeded with url: /version/'
        )

        configs = {
            'section': os.environ['SECTION'],
            'config': settings.CONFIG_FILE,
        }
        # client.exceptions.ApiException should be handled
        handler_deploy(configs)


import tkinter
from tkinter import *
from tkinter import ttk
import os
from time import strftime

# Pillow Library
from PIL import Image, ImageTk

# Importing components
from student import Student
from train import Train
from face_recognition import Face_Recognition
from attendance import Attendance
from developer import Developer
from help import Help

class Face_recognition_System:
    # constructor
    def __init__(self,root):  # root is for root window
        self.root=root
        # setting geometry
        self.root.geometry("1530x790+0+0")   # 1530x790 is window size, both 0 is the coordinate of x and y i.e. start window from top-left
        self.root.title("Face Recognition System")

        #### Setting Background Image
        # width of window is 1530, for 3 img width will be 510 per img
        # 1st image
        img1 = Image.open(r"images\background_01.jpg")
        img1=img1.resize((510,130),Image.Resampling.LANCZOS)
        self.background1=ImageTk.PhotoImage(img1)
        bg1_label=Label(self.root,image=self.background1)
        bg1_label.place(x=0,y=0,width=525,height=130)
        # 2nd image
        img2 = Image.open(r"images\background_02.jpg")
        img2=img2.resize((510,130),Image.Resampling.LANCZOS)
        self.background2=ImageTk.PhotoImage(img2)
        bg2_label=Label(self.root,image=self.background2)
        bg2_label.place(x=510,y=0,width=510,height=130)
        # 3rd image
        img3 = Image.open(r"images\background_03.jpg")
        img3=img3.resize((510,130),Image.Resampling.LANCZOS)
        self.background3=ImageTk.PhotoImage(img3)
        bg3_label=Label(self.root,image=self.background3)
        bg3_label.place(x=1020,y=0,width=510,height=130)

        # bg image
        img_bg = Image.open(r"images\background.jpg")
        img_bg=img_bg.resize((1530,710),Image.Resampling.LANCZOS)
        self.background=ImageTk.PhotoImage(img_bg)
        bg_img=Label(self.root,image=self.background)
        bg_img.place(x=0,y=130,width=1530,height=710)

        # title
        title_label=Label(bg_img,text="FACE RECOGNITION ATTENDANCE SYSTEM SOFTWARE",font=("times new roman",35,"bold"),bg="white",fg="red")
        title_label.place(x=0,y=0,width=1530,height=45)

        # ============== TIME ======================
        def time():
            string=strftime('%H:%M:%S')
            lbl.config(text=string)
            lbl.after(1000,time)

        lbl=Label(bg_img,font=('time new roman',14,'bold'),background="white",foreground="blue")
        lbl.place(x=1400,y=40,width=110,height=50)
        time()

        # student button
        bt_img_student = Image.open(r"images\student_button.jpg")
        bt_img_student=bt_img_student.resize((220,220),Image.Resampling.LANCZOS)
        self.bt1_img=ImageTk.PhotoImage(bt_img_student)
        bt1=Button(bg_img,image=self.bt1_img,command=self.student_details,cursor="hand2")
        bt1.place(x=200,y=100,width=220,height=220)
        bt1_1=Button(bg_img,text="Student Details",command=self.student_details,cursor="hand2",font=("times new roman",15,"bold"),bg="darkblue",fg="white")
        bt1_1.place(x=200,y=300,width=220,height=40)

        # detect face button
        bt_img_face_decetor = Image.open(r"images\face_recognition.jpg")
        bt_img_face_decetor=bt_img_face_decetor.resize((220,220),Image.Resampling.LANCZOS)
        self.bt2_img=ImageTk.PhotoImage(bt_img_face_decetor)
        bt2=Button(bg_img,image=self.bt2_img,cursor="hand2",command=self.face_data)
        bt2.place(x=500,y=100,width=220,height=220)
        bt2_2=Button(bg_img,text="Face Detector",command=self.face_data,cursor="hand2",font=("times new roman",15,"bold"),bg="darkblue",fg="white")
        bt2_2.place(x=500,y=300,width=220,height=40)

        # attendance
        bt_img_attendance = Image.open(r"images\student_01.jpg")
        bt_img_attendance=bt_img_attendance.resize((220,220),Image.Resampling.LANCZOS)
        self.bt3_img=ImageTk.PhotoImage(bt_img_attendance)
        bt3=Button(bg_img,image=self.bt3_img,cursor="hand2",command=self.attendance_data)
        bt3.place(x=800,y=100,width=220,height=220)
        bt3_3=Button(bg_img,text="Attendance",cursor="hand2",command=self.attendance_data,font=("times new roman",15,"bold"),bg="darkblue",fg="white")
        bt3_3.place(x=800,y=300,width=220,height=40)

        # help
        bt_img_help = Image.open(r"images\help.jpg")
        bt_img_help=bt_img_help.resize((220,220),Image.Resampling.LANCZOS)
        self.bt4_img=ImageTk.PhotoImage(bt_img_help)
        bt4=Button(bg_img,image=self.bt4_img,cursor="hand2",command=self.help_data)
        bt4.place(x=1100,y=100,width=220,height=220)
        bt4_4=Button(bg_img,text="Help",cursor="hand2",command=self.help_data,font=("times new roman",15,"bold"),bg="darkblue",fg="white")
        bt4_4.place(x=1100,y=300,width=220,height=40)

        # train face button
        bt_img_train_face = Image.open(r"images\train_face.jpg")
        bt_img_train_face=bt_img_train_face.resize((220,220),Image.Resampling.LANCZOS)
        self.bt5_img=ImageTk.PhotoImage(bt_img_train_face)
        bt5=Button(bg_img,image=self.bt5_img,cursor="hand2",command=self.train_data)
        bt5.place(x=200,y=380,width=220,height=220)
        bt5_5=Button(bg_img,text="Train Data",cursor="hand2",command=self.train_data,font=("times new roman",15,"bold"),bg="darkblue",fg="white")
        bt5_5.place(x=200,y=580,width=220,height=40)

        # photo button
        bt_img_photo = Image.open(r"images\collage-of-student-photo.jpg")
        bt_img_photo=bt_img_photo.resize((220,220),Image.Resampling.LANCZOS)
        self.bt6_img=ImageTk.PhotoImage(bt_img_photo)
        bt6=Button(bg_img,image=self.bt6_img,cursor="hand2",command=self.open_img)
        bt6.place(x=500,y=380,width=220,height=220)
        bt6_6=Button(bg_img,text="Photos",cursor="hand2",command=self.open_img,font=("times new roman",15,"bold"),bg="darkblue",fg="white")
        bt6_6.place(x=500,y=580,width=220,height=40)

        # developer
        bt_img_developer = Image.open(r"images\developer.jpg")
        bt_img_developer=bt_img_developer.resize((220,220),Image.Resampling.LANCZOS)
        self.bt7_img=ImageTk.PhotoImage(bt_img_developer)
        bt7=Button(bg_img,image=self.bt7_img,cursor="hand2",command=self.developer_data)
        bt7.place(x=800,y=380,width=220,height=220)
        bt7_7=Button(bg_img,text="Developer",cursor="hand2",command=self.developer_data,font=("times new roman",15,"bold"),bg="darkblue",fg="white")
        bt7_7.place(x=800,y=580,width=220,height=40)

        # exit
        bt_img_exit = Image.open(r"images\exit.jpg")
        bt_img_exit=bt_img_exit.resize((220,220),Image.Resampling.LANCZOS)
        self.bt8_img=ImageTk.PhotoImage(bt_img_exit)
        bt8=Button(bg_img,image=self.bt8_img,cursor="hand2",command=self.exit)
        bt8.place(x=1100,y=380,width=220,height=220)
        bt8_8=Button(bg_img,text="Exit",cursor="hand2",command=self.exit,font=("times new roman",15,"bold"),bg="darkblue",fg="white")
        bt8_8.place(x=1100,y=580,width=220,height=40)

    def open_img(self):
        os.startfile("data")

    # ====================== FUNCTION BUTTONS ==========================

    def student_details(self):
        self.new_window=Toplevel(self.root)
        self.app=Student(self.new_window)

    def train_data(self):
        self.new_window=Toplevel(self.root)
        self.app=Train(self.new_window)

    def face_data(self):
        self.new_window=Toplevel(self.root)
        self.app=Face_Recognition(self.new_window)

    def attendance_data(self):
        self.new_window=Toplevel(self.root)
        self.app=Attendance(self.new_window)

    def developer_data(self):
        self.new_window=Toplevel(self.root)
        self.app=Developer(self.new_window)

    def help_data(self):
        self.new_window=Toplevel(self.root)
        self.app=Help(self.new_window)

    def exit(self):
        self.exit=tkinter.messagebox.askyesno("Face Recodnition System","Dou you wnat to Quit?")
        if self.exit>0:
            self.root.destroy()
        else:
            return

if __name__ == "__main__":
    root=Tk()
    obj=Face_recognition_System(root)
    root.mainloop()