import os

DIFFICULTYMAP = {}
COMPANYWISEPROBLEMSETLIST = []
COMPANYWISEPROBLEMLISTLIST = []
SOLVEDPROBLEMSET = set()
SOLVEDPROBLEMLIST = []
HITCOUNTER = {}
SORTEDHITS = []

def readSolvedProblems(filename):
	f = open(filename)
	for line in f:
		probId = int(line)
		SOLVEDPROBLEMLIST.append(probId)
		SOLVEDPROBLEMSET.add(probId)
	f.close()
	SOLVEDPROBLEMLIST.sort()

def readAllCompanyData(filenames):
	for filepaths in filenames:
		companyName, problemList, problemSet = readData(filepaths)
		COMPANYWISEPROBLEMSETLIST.append(problemSet)
		COMPANYWISEPROBLEMLISTLIST.append(problemList)
	for key, value in HITCOUNTER.items():
		SORTEDHITS.append((value, key))
	SORTEDHITS.sort(key=lambda tup: tup[0], reverse=True )

def difficultyStringtoId(str):
	str = str.strip()
	if str=='Easy':
		return 0
	elif str == 'Medium':
		return 1
	else:
		return 2

def classifyProblemListByDifficulty(probIds):
	easy = []
	medium = []
	hard = []
	for probs in probIds:
		if DIFFICULTYMAP[probs]==1:
			medium.append(probs)
		elif DIFFICULTYMAP[probs]==2:
			hard.append(probs)
		else:
			easy.append(probs)
	return [easy, medium, hard]

def classifyProblemListBySolved(probIds):
	solved = []
	unsolved = []
	for probs in probIds:
		if probs in SOLVEDPROBLEMSET:
			solved.append(probs)
		else:
			unsolved.append(probs)
	return [solved, unsolved]

def getTopKUnsolved(k):
	counter = 0
	topKUnsolved = []
	for items in SORTEDHITS:
		if items[1] in SOLVEDPROBLEMSET:
			continue
		topKUnsolved.append(items[1])
		counter += 1
		if (counter==k):
			break
	topKUnsolved.sort()
	return topKUnsolved

def analytics():

	#most frequently occuring problems
	topkUnsolved =  getTopKUnsolved(40) #list(set.intersection(*COMPANYWISEPROBLEMSETLIST))
	[tEasy, tMedium, tHard] = classifyProblemListByDifficulty(topkUnsolved)
	print('\nMOST FREQUENTLY OCCURING UNSOLVED PROBLEMS')
	print('*************EASY*******************************')
	print([ (t, HITCOUNTER[t]) for t in tEasy])
	print('*************MEDIUM*****************************')
	print([ (t, HITCOUNTER[t]) for t in tMedium])
	print('*************HARD*******************************')
	print([ (t, HITCOUNTER[t]) for t in tHard])

	#next find the union of all problems
	unionList = list(set.union(*COMPANYWISEPROBLEMSETLIST))
	unionList.sort()
	[uEasy, uMedium, uHard] = classifyProblemListByDifficulty(unionList)
	print('\nALL PROBLEMS (UNION OF ALL COMPANIES)')
	print('*************EASY*******************************')
	# print(uEasy)
	[ueSolved, ueUnsolved] = classifyProblemListBySolved(uEasy)
	print('Solved({}/{}) {}'.format(len(ueSolved), len(uEasy), ueSolved))
	print('Unsolved({}/{}) {}'.format(len(ueUnsolved), len(uEasy), ueUnsolved))
	print('*************MEDIUM*****************************')
	# print(uMedium)
	[umSolved, umUnsolved] = classifyProblemListBySolved(uMedium)
	print('Solved({}/{}) {}'.format(len(umSolved), len(uMedium), umSolved))
	print('Unsolved({}/{}) {}'.format(len(umUnsolved), len(uMedium), umUnsolved))
	print('*************HARD*******************************')
	# print(uHard)
	[uhSolved, uhUnsolved] = classifyProblemListBySolved(uHard)
	print('Solved({}/{}) {}'.format(len(uhSolved), len(uHard), uhSolved))
	print('Unsolved({}/{}) {}'.format(len(uhUnsolved), len(uHard), uhUnsolved))

def readData(filename):
	#try to obtain the filename
	basename = os.path.basename(filename)
	#remove the .txt portion
	dotIdx = basename.find('.')
	companyName = basename[0:dotIdx].upper()
	f = open(filename, 'r')
	problemList = []
	problemSet = set()
	for line in f:
		data = line.split(' ')
		problemID = int(data[0])
		difficultyString = data[-1]
		if problemID not in DIFFICULTYMAP:
			DIFFICULTYMAP[problemID] = difficultyStringtoId(difficultyString)
		HITCOUNTER[problemID] = HITCOUNTER.get(problemID,0) + 1
		problemList.append(problemID)
		problemSet.add(problemID)
	f.close()
	print('Finished processing company {}'.format(companyName))
	return [companyName, problemList, problemSet]

def getAllFiles(dir_path):
	files = []
	for f in os.listdir(dir_path):
		if os.path.isfile(os.path.join(dir_path,f)):
			if not f.startswith('.'):
				files.append(os.path.join(dir_path,f))
	return files

CURRENTPATH = os.getcwd()
DATADIRECTORYPATH = os.path.join(CURRENTPATH, 'data')
#remember you need to ignore any files that start with . or is a directory
COMPANYFILES = getAllFiles(DATADIRECTORYPATH)
SOLVEDPROBLEMFILE = os.path.join(CURRENTPATH, 'solved.txt')

readAllCompanyData(COMPANYFILES)
readSolvedProblems(SOLVEDPROBLEMFILE)
analytics()


class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        def solve(target, nums):
            for i,num in enumerate(nums):
                if num == target:
                    yield [num]
                elif num < target:
                    for ans in solve(target-num,nums[i:]):
                        yield [num]+ans
        candidates.sort()
        while len(candidates)>0 and candidates[-1]>target:
            candidates.pop()
        if len(candidates)==0:
            return []
        canidates = candidates[::-1]
        result = []
        for ans in solve(target,candidates):
            result.append(ans)
        return result


# 计算变量之间的互信息
"""
怎么计算故障之间的互信息啊？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？

"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cap

data = pd.read_csv('TE_Train_data.csv')  # 导入原始数据
data.iloc[:, :52] = cap.normalize(data.iloc[:, :52])  # 特征归一化

MI = []  # 储存每个特征的互信息
for j in range(52):
    a = np.log(np.var(data.iloc[:, j]))

    b = 0
    for i in range(22):
        data_x = data.loc[data['V52'] == i].iloc[:, j]  # 第i个类别的第j个特征
        b += data_x.shape[0] / data.shape[0] * np.log(np.var(data_x))

    MI.append(1/2 * (a - b))

plt.bar(range(len(MI)), MI)
plt.xlabel('Variables')
plt.ylabel('Mutual Information')
plt.show()


from tkinter import *

top = Tk()

beeList = []

def results():
    print(beeList)

def addToList():
    newItem = E1.get()
    beeList.append(newItem)
#Label widget
L1 = Label(top, text = "Bee hit list")
L1.grid(column = 0, row = 1)

#Entry widget
E1 = Entry(top, bd = 5)
E1.grid(column = 0, row = 2)

#This is a Button widget
B1 = Button(text = "  Print list  ", bg = "white", command = results)
B1.grid(column = 0, row = 3)

B2 = Button(text = "  Add to list  " , bg = "white", command = addToList)
B2.grid(column = 1, row = 2)

top.mainloop()


import tensorflow as tf
from .yolov4 import YOLO, decode, filter_boxes
from .utils import load_config, load_weights

def convert_darknet_to_tf(model_files, weights="yolov4-tiny_best.weights", input_size=416, score_threshold=.2, tiny=False, framework="tf"):
    strides, anchors, num_class, xyscale = load_config(f"{model_files}obj.names", tiny)
    input_layer = tf.keras.layers.Input([input_size, input_size, 3])
    feature_maps = YOLO(input_layer, num_class, tiny)
    bbox_tensors = []
    prob_tensors = []
    if tiny:
        for i, fm in enumerate(feature_maps):
            if i == 0:
                output_tensors = decode(fm, input_size // 16, num_class, strides, anchors, i, xyscale, framework)
            else:
                output_tensors = decode(fm, input_size // 32, num_class, strides, anchors, i, xyscale, framework)
            bbox_tensors.append(output_tensors[0])
            prob_tensors.append(output_tensors[1])
    else:
        for i, fm in enumerate(feature_maps):
            if i == 0:
                output_tensors = decode(fm, input_size // 8, num_class, strides, anchors, i, xyscale, framework)
            elif i == 1:
                output_tensors = decode(fm, input_size // 16, num_class, strides, anchors, i, xyscale, framework)
            else:
                output_tensors = decode(fm, input_size // 32, num_class, strides, anchors, i, xyscale, framework)
            bbox_tensors.append(output_tensors[0])
            prob_tensors.append(output_tensors[1])
    pred_bbox = tf.concat(bbox_tensors, axis=1)
    pred_prob = tf.concat(prob_tensors, axis=1)
    if framework == "tflite":
        pred = (pred_bbox, pred_prob)
    else:
        boxes, pred_conf = filter_boxes(
            pred_bbox, pred_prob, score_threshold=score_threshold,
            input_shape=tf.constant([input_size, input_size]))
        pred = tf.concat([boxes, pred_conf], axis=-1)
    model = tf.keras.Model(input_layer, pred)
    load_weights(model, f"{model_files}{weights}", tiny)
    model.summary()
    if framework == "tf":
        output = f"{model_files}{weights.replace('.weights', '_tf')}"
    elif framework == "tflite":
        output = f"{model_files}{weights.replace('.weights', '_tflite')}"
    else:
        output = f"{model_files}{weights.replace('.weights', '_trt')}"
    model.save(output)


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
import re
import pandas as pd
import json
import time
from bs4 import BeautifulSoup as BSoup

start_time = time.time()

def create_driver():
    driver_path = "/home/louis/Desktop/drivers/geckodriver"
    firefoxOptions = webdriver.FirefoxOptions()
    firefoxOptions.add_argument("--headless")
    return webdriver.Firefox(executable_path=driver_path, options=firefoxOptions)

driver = create_driver()
driver.get("https://www.immoweb.be/fr/recherche/maison-et-appartement/a-vendre?countries=BE")
cookie_button = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.XPATH, "//button[@id='uc-btn-accept-banner']")))
cookie_button.click()

first_listing = driver.find_element(By.XPATH,"/html/body/div[1]/div[1]/div/main/div/div[2]/div/div[3]/div/div[1]/div[1]/div[1]/ul/li[1]/article/div[1]/h2/a")
first_listing.click()

def split_url():
    url = driver.current_url
    split_url = re.split('/|\?', url)
    return split_url

print(split_url())

def get_next_url():
    link = driver.find_element(By.XPATH, '/html/body/div[1]/div[1]/div/div/main/div[1]/div[2]/div/div/div[1]/div/div[1]/ul/li[2]/a')
    next_url = link.get_attribute('href')
    return next_url

def get_houses():

    houses_list = []
    bs_obj = BSoup(driver.page_source, 'html.parser')

    for j in range (0,10):
        list_from_url = split_url()
        find_all_ths = bs_obj.find_all('th')
        ths = []
        for th in find_all_ths:
            ths.append(re.sub('\s\s+', '', th.get_text()))
        tds = []
        find_all_tds = bs_obj.find_all('td')
        for td in find_all_tds:
            tds.append(re.sub('\s\s+', '', td.get_text()))

        house_id = list_from_url[9]
        post_code = list_from_url[8]
        locality = list_from_url[7]
        type_of_property = list_from_url[5]
        type_of_sale = ' '.join(list_from_url[5].split('-'))

        house_list = []

        for i in range(len(ths)):
            house_list.append([ths[i],tds[i]])

        house_list.insert(0,["id",house_id])
        house_list.insert(0,["locality",locality])
        house_list.insert(0,["post code",post_code])
        house_list.insert(0,["type of property",type_of_property])
        house_list.insert(0,["type of sale",type_of_sale])

        house_dict = dict(house_list)
        houses_list.append(house_dict)

        next_button = get_next_url()
        print(f'house number {j} register at time: {"--- %s seconds ---" % (time.time() - start_time)}')
        driver.get(next_button)
        j += 1

    driver.close()
    return houses_list

all_houses = get_houses()
print(all_houses)
print("--- %s seconds ---" % (time.time() - start_time))
df = pd.DataFrame(all_houses)

# df = pd.DataFrame.from_dict({(i,j): houses_dict[i][j]
#                            for i in houses_dict.keys()
#                            for j in houses_dict[i].keys()},
#                        orient='index')
out_file = open("houses_dict.json", "w")
json.dump(all_houses, out_file, default=lambda o: '<not serializable>', indent = 4)
out_file.close()
print('json file write')

df.to_csv('houses_infos_test.csv')
print('csv file write')
# # pd.read_csv('houses_infos.csv', header=None).T.to_csv('output.csv', header=False, index=False)


#
# aggregate_video.py
#
# Aggregate results and render output video for a video that's already been run through MD
#

#%% Constants

import os
import json
from detection.process_video import ProcessVideoOptions
from detection.video_utils import frames_to_video, video_to_frames
from visualization import visualize_detector_output

video_file = os.path.expanduser('~/1_fps_20211216_101100.mp4')
results_file_raw = os.path.expanduser('~/1_fps_20211216_101100.mp4.json')
allowed_categories = ['1']
max_box_size = 0.15
min_box_size = 0.03

results_file = results_file_raw.replace('.json','_animals_only.json')

#%% Processing

with open(results_file_raw,'r') as f:

    n_detections = 0
    n_valid_detections = 0
    min_valid_confidence = 1.0

    d = json.load(f)
    # im = d['images'][0]

    for im in d['images']:

        valid_detections = []
        max_detection_conf = 0

        for det in im['detections']:
            n_detections += 1
            det_size = None
            if 'bbox' in det:
                bbox = det['bbox']
                det_size = bbox[2] * bbox[3]
            if det['category'] in allowed_categories and \
                ((det_size is not None) and (det_size < max_box_size) and \
                 (det_size > min_box_size)):
                if det['conf'] > max_detection_conf:
                    max_detection_conf = det['conf']
                if det['conf'] < min_valid_confidence:
                    min_valid_confidence = det['conf']
                valid_detections.append(det)
                n_valid_detections += 1

        # ...for each detection

        im['detections'] = valid_detections

        # This is no longer included in output files by default
        if 'max_detection_conf' in im:
            im['max_detection_conf'] = max_detection_conf

    print('Kept {} of {} detections (min conf {})'.format(
        n_valid_detections,n_detections,min_valid_confidence))

    with open(results_file,'w') as f:
        json.dump(d,f,indent=2)

base_dir = os.path.expanduser('~/frame_processing')
min_confidence = 0.001

assert os.path.isfile(video_file) and os.path.isfile(results_file)
os.makedirs(base_dir,exist_ok=True)

## Split into frames

options = ProcessVideoOptions()
options.input_video_file = video_file
options.output_json_file = results_file
options.output_video_file = options.input_video_file + '.detections.mp4'

frame_output_folder = os.path.join(
    base_dir, os.path.basename(options.input_video_file) + '_frames')
if os.path.isdir(frame_output_folder):
    print('Frame output folder exists, skipping frame extraction')
else:
    os.makedirs(frame_output_folder, exist_ok=True)

    frame_filenames, Fs = video_to_frames(
        options.input_video_file, frame_output_folder)

## Render output video

### Render detections to images

rendering_output_dir = os.path.join(
    base_dir, os.path.basename(options.input_video_file) + '_detections')
os.makedirs(rendering_output_dir,exist_ok=True)
detected_frame_files = visualize_detector_output.visualize_detector_output(
    detector_output_path=options.output_json_file,
    out_dir=rendering_output_dir,
    images_dir=frame_output_folder,
    confidence=min_confidence)

### Combine into a video

Fs = 20
frames_to_video(detected_frame_files, Fs, options.output_video_file)


import numpy
import pandas
from keras.models import Sequential
from keras.layers import Dense
from keras import backend as K
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn import preprocessing
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix, classification_report, accuracy_score
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler, MinMaxScaler, Normalizer
from sklearn.pipeline import Pipeline
import matplotlib.pyplot as plt
import keras.layers.advanced_activations
import tensorflow as tf;
from tensorflow.python.tools import freeze_graph, optimize_for_inference_lib

MODEL_NAME = 'regression_model'

# load dataset
columns = ['dayOfWeek', 'hour', 'operationType', 'fileType', 'parentFolder', 'fileSize',
           'predessorFile1', 'predessorFile2', 'predessorFile3', 'predessorFile4', 'filename',
           'successorFile1', 'successorFile2', 'successorFile3', 'successorFile4']

dataframe = pandas.read_csv("/home/anuradha/PycharmProjects/data/fyp/final/test-after-filtered.csv", header=None, names=columns)
# dataset = dataframe.values
dataset = dataframe.values

dataframe.drop(dataframe.columns[[0, 1,5]], axis=1, inplace=True)

print(dataframe.describe())

# split into input (X) and output (Y) variables
X = dataset[:, 0:9]
Y = dataset[:, 8]

# fix random seed for reproducibility
seed = 7

# evaluate model with standardized dataset
numpy.random.seed(seed)

scaler = Normalizer().fit(X)
normalizedX = scaler.transform(X)

# normalizedX = preprocessing.scale(X)

# summarize transformed data
# numpy.set_printoptions(precision=3)
print(normalizedX[0:7,:])

# create model
model = Sequential()
model.add(Dense(9, input_dim=9, kernel_initializer='normal', activation="relu", use_bias= True))
model.add(Dense(1, kernel_initializer='normal', activation="relu"))

model.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])

X_train, X_test, y_train, y_test = train_test_split(normalizedX, Y)

model.fit(X_train, y_train, batch_size=20, epochs=2000, verbose=2)
score = model.evaluate(X_test, y_test, batch_size=1, verbose=2)

print("score : ",score)
model.save("models/regression_model.h5")

prediction = model.predict(X_test)
print (prediction)
prediction = prediction.astype(int)

plt.show()

print(prediction[:10])
print (y_test[:10])

def export_model(saver, model, input_node_names, output_node_name):
    tf.train.write_graph(K.get_session().graph_def, 'out', \
                         MODEL_NAME + '_graph.pbtxt')

    saver.save(K.get_session(), 'out/' + MODEL_NAME + '.chkp')

    freeze_graph.freeze_graph('out/' + MODEL_NAME + '_graph.pbtxt', None, \
                              False, 'out/' + MODEL_NAME + '.chkp', output_node_name, \
                              "save/restore_all", "save/Const:0", \
                              'out/frozen_' + MODEL_NAME + '.pb', True, "")

    input_graph_def = tf.GraphDef()
    with tf.gfile.Open('out/frozen_' + MODEL_NAME + '.pb', "rb") as f:
        input_graph_def.ParseFromString(f.read())

    output_graph_def = optimize_for_inference_lib.optimize_for_inference(
        input_graph_def, input_node_names, [output_node_name],
        tf.float32.as_datatype_enum)

    with tf.gfile.FastGFile('out/opt_' + MODEL_NAME + '.pb', "wb") as f:
        f.write(output_graph_def.SerializeToString())

    print("graph saved!")

    return


import os
import random
import torch
import numpy as np
import pandas as pd
from types import SimpleNamespace
import time
from utils import PairDataset
from torch_geometric.loader import DataLoader
from models import GNNPair

random.seed(42); np.random.seed(42)

class LRDataset(PairDataset):
    def __init__(self, pair_info_df, single_data_pool, reduce_form):
        super().__init__(pair_info_df, single_data_pool, reduce_form)

    def __getitem__(self, idx):
        row = self.info.iloc[idx, ]
        ligand_file = row['ligand_file']
        receptor_file = row['receptor_file']

        ligand_data = self.single_data_pool[ligand_file]
        receptor_data = self.single_data_pool[receptor_file]

        # emb
        ligand_data.emb = torch.tensor(
            np.load(os.path.join(self.emb_path, f'{ligand_file}.npy')), dtype=torch.float32)
        receptor_data.emb = torch.tensor(
            np.load(os.path.join(self.emb_path, f'{receptor_file}.npy')), dtype=torch.float32)
        if self.reduce_func is not None:
            ligand_data.emb = self.reduce_func(ligand_data.emb, dim=0, keepdim=True)
            receptor_data.emb = self.reduce_func(receptor_data.emb, dim=0, keepdim=True)

        return ligand_data, receptor_data, row['ligand'], row['receptor']

if __name__ == '__main__':
    species = "Human"
    args = {
        'device': 'cuda',
        'batch_size': 80
    }
    args = SimpleNamespace(**args)

    # dataloader
    df_potential_lr = pd.read_csv(r'./data/df/df_potential_lr.csv')
    df_ligand = df_potential_lr.query('lr_type == "ligand"').reset_index(drop=True)[['gene', 'name']]
    df_ligand.columns = ['ligand', 'ligand_file']
    df_receptor = df_potential_lr.query('lr_type == "receptor"').reset_index(drop=True)[['gene', 'name']]
    df_receptor.columns = ['receptor', 'receptor_file']
    df_comb = df_ligand.merge(df_receptor, how='cross')

    single_data_pool = {data['name']: data for data in torch.load('./data/graph/human_v4_6_alpha.pt')}

    comb_data = LRDataset(df_comb, single_data_pool, 'sum')
    dataloader = DataLoader(comb_data, batch_size=args.batch_size)
    print('total combinations:', len(dataloader.dataset))

    # model related
    model = GNNPair(input_dim=128, hidden_dim=128, num_layers=1, reduce_form='sum')
    weight_path = r'./result/human_v4_6_alpha_GNNPair/4_acc0.900_roc0.965_prc0.959_recall0.893.pt'
    model.load_state_dict(torch.load(weight_path))
    print('load weight:', weight_path)
    model.to(args.device)
    model.eval()
    print(model)

    # get result
    ligand_ls = []
    receptor_ls = []
    pred_ls = []
    result_file_path = f'../network_filtering/lr_database_raw.csv'
    for batch_idx, (ligand, receptor, l_gene, r_gene) in enumerate(dataloader):
        ligand = ligand.to(args.device)
        receptor = receptor.to(args.device)

        ligand_ls += l_gene
        receptor_ls += r_gene
        with torch.no_grad():
            pred = model(ligand, receptor).reshape(-1).detach().cpu().numpy().tolist()
            pred_ls += pred

        condition1 = len(ligand_ls) >= 20000
        condition2 = batch_idx == len(dataloader)-1  # final batch
        if condition1 or condition2:
            if os.path.exists(result_file_path):
                df0 = pd.read_csv(result_file_path)
            else:
                df0 = pd.DataFrame(columns=['ligand', 'receptor', 'pred'])
            df = pd.DataFrame({'ligand': ligand_ls, 'receptor': receptor_ls, 'pred': pred_ls})
            df = pd.concat((df0, df), ignore_index=True)
            df.to_csv(result_file_path, index=False)

            print(time.strftime('%H:%M:%S'), 'finished num: ', len(df))
            ligand_ls = []
            receptor_ls = []
            pred_ls = []


#-------------------------------------------------------------------------
# AUTHOR: Sara Nersisian
# FILENAME: find_s.py
# SPECIFICATION: find_s program for machine learning
# FOR: CS 4210- Assignment #1
# TIME SPENT: 2 hours
#-----------------------------------------------------------*/

#IMPORTANT NOTE: DO NOT USE ANY ADVANCED PYTHON LIBRARY TO COMPLETE THIS CODE SUCH AS numpy OR pandas. You have to work here only with standard vectors and arrays

#importing some Python libraries
import csv

num_attributes = 4
db = []
print("\n The Given Training Data Set \n")

#reading the data in a csv file
with open('contact_lens.csv', 'r') as csvfile:
  reader = csv.reader(csvfile)
  for i, row in enumerate(reader):
      if i > 0: #skipping the header
         db.append (row)
         print(row)

print("\n The initial value of hypothesis: ")
hypothesis = ['0'] * num_attributes #representing the most specific possible hypothesis
print(hypothesis)

#find the first positive training data in db and assign it to the vector hypothesis
#Selecting only the positive
for row in db:
        if row[4] == 'Yes':
            hypothesis = row
            break
#updating hypothesis to have 4 main features only
hypothesis = hypothesis[0:4]
# print("h1:", hypothesis)

#find the maximally specific hypothesis according to your training data in db and assign it to the vector hypothesis (special characters allowed: "0" and "?")

#creating an array to only hold the postive attributes
dbYes=[]
for row in db:
    if row[4] == "Yes":
        dbYes.append(row[:4])
# print(dbYes)

# comparing each value of dbYes to hypothesis
# if they are not equal print "?"

i = 0               #index for printing steps of hypothesis
for row in dbYes:
    for col in row:
        if col != hypothesis[row.index(col)]:
            hypothesis[row.index(col)] = "?"
    i+=1
    print("h",i,":", hypothesis)

print("\n The Maximally Specific Hypothesis for the given training examples found by Find-S algorithm:\n")
print(hypothesis)


import operator

from llvmlite import ir
from numba.core import cgutils
from numba.core.typing import signature as nb_signature
from numba.cuda.cudaimpl import (
    lower as cuda_lower,
    registry as cuda_lowering_registry,
)
from numba.extending import lower_builtin, types

from cudf.core.udf import api
from cudf.core.udf._ops import (
    arith_ops,
    bitwise_ops,
    comparison_ops,
    unary_ops,
)
from cudf.core.udf.masked_typing import (
    MaskedType,
    NAType,
    _supported_masked_types,
)

@cuda_lowering_registry.lower_constant(NAType)
def constant_na(context, builder, ty, pyval):
    # This handles None, etc.
    return context.get_dummy_value()

# In the typing phase, we declared that a `MaskedType` can be
# added to another `MaskedType` and specified what kind of a
# `MaskedType` would result. Now we have to actually fill in
# the implementation details of how to do that. This is where
# we can involve both validities in constructing the answer

def make_arithmetic_op(op):
    """
    Make closures that implement arithmetic operations. See
    register_arithmetic_op for details.
    """

    def masked_scalar_op_impl(context, builder, sig, args):
        """
        Implement `MaskedType` <op> `MaskedType`
        """
        # MaskedType(...), MaskedType(...)
        masked_type_1, masked_type_2 = sig.args
        # MaskedType(...)
        masked_return_type = sig.return_type

        # Let there be two actual LLVM structs backing the two inputs
        # https://mapping-high-level-constructs-to-llvm-ir.readthedocs.io/en/latest/basic-constructs/structures.html
        m1 = cgutils.create_struct_proxy(masked_type_1)(
            context, builder, value=args[0]
        )
        m2 = cgutils.create_struct_proxy(masked_type_2)(
            context, builder, value=args[1]
        )

        # we will return an output struct
        result = cgutils.create_struct_proxy(masked_return_type)(
            context, builder
        )
        # compute output validity
        valid = builder.and_(m1.valid, m2.valid)
        result.valid = valid
        with builder.if_then(valid):
            # Let numba handle generating the extra IR needed to perform
            # operations on mixed types, by compiling the final core op between
            # the two primitive values as a separate function and calling it
            result.value = context.compile_internal(
                builder,
                lambda x, y: op(x, y),
                nb_signature(
                    masked_return_type.value_type,
                    masked_type_1.value_type,
                    masked_type_2.value_type,
                ),
                (m1.value, m2.value),
            )
        return result._getvalue()

    return masked_scalar_op_impl

def make_unary_op(op):
    """
    Make closures that implement unary operations. See register_unary_op for
    details.
    """

    def masked_scalar_unary_op_impl(context, builder, sig, args):
        """
        Implement <op> `MaskedType`
        """
        # MaskedType(...)
        masked_type_1 = sig.args[0]
        # MaskedType(...)
        masked_return_type = sig.return_type

        m1 = cgutils.create_struct_proxy(masked_type_1)(
            context, builder, value=args[0]
        )

        # we will return an output struct
        result = cgutils.create_struct_proxy(masked_return_type)(
            context, builder
        )

        # compute output validity
        result.valid = m1.valid
        with builder.if_then(m1.valid):
            # Let numba handle generating the extra IR needed to perform
            # operations on mixed types, by compiling the final core op between
            # the two primitive values as a separate function and calling it
            result.value = context.compile_internal(
                builder,
                lambda x: op(x),
                nb_signature(
                    masked_return_type.value_type,
                    masked_type_1.value_type,
                ),
                (m1.value,),
            )
        return result._getvalue()

    return masked_scalar_unary_op_impl

def register_arithmetic_op(op):
    """
    Register a lowering implementation for the
    arithmetic op `op`.

    Because the lowering implementations compile the final
    op separately using a lambda and compile_internal, `op`
    needs to be tied to each lowering implementation using
    a closure.

    This function makes and lowers a closure for one op.

    """
    to_lower_op = make_arithmetic_op(op)
    cuda_lower(op, MaskedType, MaskedType)(to_lower_op)

def register_unary_op(op):
    """
    Register a lowering implementation for the
    unary op `op`.

    Because the lowering implementations compile the final
    op separately using a lambda and compile_internal, `op`
    needs to be tied to each lowering implementation using
    a closure.

    This function makes and lowers a closure for one op.

    """
    to_lower_op = make_unary_op(op)
    cuda_lower(op, MaskedType)(to_lower_op)

def masked_scalar_null_op_impl(context, builder, sig, args):
    """
    Implement `MaskedType` <op> `NAType`
    or `NAType` <op> `MaskedType`
    The answer to this is known up front so no actual operation
    needs to take place
    """

    return_type = sig.return_type  # MaskedType(...)
    result = cgutils.create_struct_proxy(MaskedType(return_type.value_type))(
        context, builder
    )

    # Invalidate the struct and leave `value` uninitialized
    result.valid = context.get_constant(types.boolean, 0)
    return result._getvalue()

def make_const_op(op):
    def masked_scalar_const_op_impl(context, builder, sig, args):
        return_type = sig.return_type
        result = cgutils.create_struct_proxy(return_type)(context, builder)
        result.valid = context.get_constant(types.boolean, 0)
        if isinstance(sig.args[0], MaskedType):
            masked_type, const_type = sig.args
            masked_value, const_value = args

            indata = cgutils.create_struct_proxy(masked_type)(
                context, builder, value=masked_value
            )
            nb_sig = nb_signature(
                return_type.value_type, masked_type.value_type, const_type
            )
            compile_args = (indata.value, const_value)
        else:
            const_type, masked_type = sig.args
            const_value, masked_value = args
            indata = cgutils.create_struct_proxy(masked_type)(
                context, builder, value=masked_value
            )
            nb_sig = nb_signature(
                return_type.value_type, const_type, masked_type.value_type
            )
            compile_args = (const_value, indata.value)
        with builder.if_then(indata.valid):
            result.value = context.compile_internal(
                builder, lambda x, y: op(x, y), nb_sig, compile_args
            )
            result.valid = context.get_constant(types.boolean, 1)
        return result._getvalue()

    return masked_scalar_const_op_impl

def register_const_op(op):
    to_lower_op = make_const_op(op)
    cuda_lower(op, MaskedType, types.Number)(to_lower_op)
    cuda_lower(op, types.Number, MaskedType)(to_lower_op)
    cuda_lower(op, MaskedType, types.Boolean)(to_lower_op)
    cuda_lower(op, types.Boolean, MaskedType)(to_lower_op)
    cuda_lower(op, MaskedType, types.NPDatetime)(to_lower_op)
    cuda_lower(op, types.NPDatetime, MaskedType)(to_lower_op)
    cuda_lower(op, MaskedType, types.NPTimedelta)(to_lower_op)
    cuda_lower(op, types.NPTimedelta, MaskedType)(to_lower_op)

# register all lowering at init
for binary_op in arith_ops + bitwise_ops + comparison_ops:
    register_arithmetic_op(binary_op)
    register_const_op(binary_op)
    # null op impl can be shared between all ops
    cuda_lower(binary_op, MaskedType, NAType)(masked_scalar_null_op_impl)
    cuda_lower(binary_op, NAType, MaskedType)(masked_scalar_null_op_impl)

# register all lowering at init
for unary_op in unary_ops:
    register_unary_op(unary_op)
register_unary_op(abs)

@cuda_lower(operator.is_, MaskedType, NAType)
@cuda_lower(operator.is_, NAType, MaskedType)
def masked_scalar_is_null_impl(context, builder, sig, args):
    """
    Implement `MaskedType` is `NA`
    """
    if isinstance(sig.args[1], NAType):
        masked_type, na = sig.args
        value = args[0]
    else:
        na, masked_type = sig.args
        value = args[1]

    indata = cgutils.create_struct_proxy(masked_type)(
        context, builder, value=value
    )
    result = cgutils.alloca_once(builder, ir.IntType(1))
    with builder.if_else(indata.valid) as (then, otherwise):
        with then:
            builder.store(context.get_constant(types.boolean, 0), result)
        with otherwise:
            builder.store(context.get_constant(types.boolean, 1), result)

    return builder.load(result)

# Main kernel always calls `pack_return` on whatever the user defined
# function returned. This returns the same data if its already a `Masked`
# else packs it up into a new one that is valid from the get go
@cuda_lower(api.pack_return, MaskedType)
def pack_return_masked_impl(context, builder, sig, args):
    return args[0]

@cuda_lower(api.pack_return, types.Boolean)
@cuda_lower(api.pack_return, types.Number)
@cuda_lower(api.pack_return, types.NPDatetime)
@cuda_lower(api.pack_return, types.NPTimedelta)
def pack_return_scalar_impl(context, builder, sig, args):
    outdata = cgutils.create_struct_proxy(sig.return_type)(context, builder)
    outdata.value = args[0]
    outdata.valid = context.get_constant(types.boolean, 1)

    return outdata._getvalue()

@cuda_lower(operator.truth, MaskedType)
@cuda_lower(bool, MaskedType)
def masked_scalar_bool_impl(context, builder, sig, args):
    indata = cgutils.create_struct_proxy(sig.args[0])(
        context, builder, value=args[0]
    )
    result = cgutils.alloca_once(builder, ir.IntType(1))
    with builder.if_else(indata.valid) as (then, otherwise):
        with then:
            builder.store(
                context.cast(
                    builder,
                    indata.value,
                    sig.args[0].value_type,
                    types.boolean,
                ),
                result,
            )
        with otherwise:
            builder.store(context.get_constant(types.boolean, 0), result)
    return builder.load(result)

@cuda_lower(float, MaskedType)
@cuda_lower(int, MaskedType)
def masked_scalar_cast_impl(context, builder, sig, args):
    input = cgutils.create_struct_proxy(sig.args[0])(
        context, builder, value=args[0]
    )
    result = cgutils.create_struct_proxy(sig.return_type)(context, builder)

    casted = context.cast(
        builder,
        input.value,
        sig.args[0].value_type,
        sig.return_type.value_type,
    )
    result.value = casted
    result.valid = input.valid
    return result._getvalue()

# To handle the unification, we need to support casting from any type to a
# masked type. The cast implementation takes the value passed in and returns
# a masked type struct wrapping that value.
@cuda_lowering_registry.lower_cast(types.Any, MaskedType)
def cast_primitive_to_masked(context, builder, fromty, toty, val):
    casted = context.cast(builder, val, fromty, toty.value_type)
    ext = cgutils.create_struct_proxy(toty)(context, builder)
    ext.value = casted
    ext.valid = context.get_constant(types.boolean, 1)
    return ext._getvalue()

@cuda_lowering_registry.lower_cast(NAType, MaskedType)
def cast_na_to_masked(context, builder, fromty, toty, val):
    result = cgutils.create_struct_proxy(toty)(context, builder)
    result.valid = context.get_constant(types.boolean, 0)

    return result._getvalue()

@cuda_lowering_registry.lower_cast(MaskedType, MaskedType)
def cast_masked_to_masked(context, builder, fromty, toty, val):
    """
    When numba encounters an op that expects a certain type and
    the input to the op is not of the expected type it will try
    to cast the input to the appropriate type. But, in our case
    the input may be a MaskedType, which numba doesn't natively
    know how to cast to a different MaskedType with a different
    `value_type`. This implements and registers that cast.
    """

    # We will
    operand = cgutils.create_struct_proxy(fromty)(context, builder, value=val)
    casted = context.cast(
        builder, operand.value, fromty.value_type, toty.value_type
    )
    ext = cgutils.create_struct_proxy(toty)(context, builder)
    ext.value = casted
    ext.valid = operand.valid
    return ext._getvalue()

# Masked constructor for use in a kernel for testing
def masked_constructor(context, builder, sig, args):
    ty = sig.return_type
    value, valid = args
    masked = cgutils.create_struct_proxy(ty)(context, builder)
    masked.value = value
    masked.valid = valid
    return masked._getvalue()

for ty in _supported_masked_types:
    lower_builtin(api.Masked, ty, types.boolean)(masked_constructor)

# Allows us to make an instance of MaskedType a global variable
# and properly use it inside functions we will later compile
@cuda_lowering_registry.lower_constant(MaskedType)
def lower_constant_masked(context, builder, ty, val):
    masked = cgutils.create_struct_proxy(ty)(context, builder)
    masked.value = context.get_constant(ty.value_type, val.value)
    masked.valid = context.get_constant(types.boolean, val.valid)
    return masked._getvalue()


load("//python/pip_install:pip_repository.bzl", "pip_repository", _package_annotation = "package_annotation")
load("//python/pip_install:requirements.bzl", _compile_pip_requirements = "compile_pip_requirements")
load("//python/private:bzlmod_enabled.bzl", "BZLMOD_ENABLED")
load("//python/private:full_version.bzl", "full_version")
load("//python/private:render_pkg_aliases.bzl", "NO_MATCH_ERROR_MESSAGE_TEMPLATE")

compile_pip_requirements = _compile_pip_requirements
package_annotation = _package_annotation
pip_parse = pip_repository

def pip_install(requirements = None, name = "pip", allow_pip_install = False, **kwargs):
    """Will be removed in 0.28.0

    Args:
        requirements (Label): A 'requirements.txt' pip requirements file.
        name (str, optional): A unique name for the created external repository (default 'pip').
        allow_pip_install (bool, optional): change this to keep this rule working (default False).
        **kwargs (dict): Additional arguments to the [`pip_repository`](./pip_repository.md) repository rule.
    """

    if allow_pip_install:
        pip_parse(requirements = requirements, name = name, **kwargs)
    else:
        fail("pip_install support has been disabled, please use pip_parse as a replacement.")

def _multi_pip_parse_impl(rctx):
    rules_python = rctx.attr._rules_python_workspace.workspace_name
    load_statements = []
    install_deps_calls = []
    process_requirements_calls = []
    for python_version, pypi_repository in rctx.attr.pip_parses.items():
        sanitized_python_version = python_version.replace(".", "_")
        load_statement = """\
load(
    "@{pypi_repository}//:requirements.bzl",
    _{sanitized_python_version}_install_deps = "install_deps",
    _{sanitized_python_version}_all_requirements = "all_requirements",
)""".format(
            pypi_repository = pypi_repository,
            sanitized_python_version = sanitized_python_version,
        )
        load_statements.append(load_statement)
        process_requirements_call = """\
_process_requirements(
    pkg_labels = _{sanitized_python_version}_all_requirements,
    python_version = "{python_version}",
    repo_prefix = "{pypi_repository}_",
)""".format(
            pypi_repository = pypi_repository,
            python_version = python_version,
            sanitized_python_version = sanitized_python_version,
        )
        process_requirements_calls.append(process_requirements_call)
        install_deps_call = """    _{sanitized_python_version}_install_deps(**whl_library_kwargs)""".format(
            sanitized_python_version = sanitized_python_version,
        )
        install_deps_calls.append(install_deps_call)

    requirements_bzl = """\
# Generated by python/pip.bzl

load("@{rules_python}//python:pip.bzl", "whl_library_alias")
{load_statements}

_wheel_names = []
_version_map = dict()
def _process_requirements(pkg_labels, python_version, repo_prefix):
    for pkg_label in pkg_labels:
        workspace_name = Label(pkg_label).workspace_name
        wheel_name = workspace_name[len(repo_prefix):]
        _wheel_names.append(wheel_name)
        if not wheel_name in _version_map:
            _version_map[wheel_name] = dict()
        _version_map[wheel_name][python_version] = repo_prefix

{process_requirements_calls}

def _clean_name(name):
    return name.replace("-", "_").replace(".", "_").lower()

def requirement(name):
    return "@{name}_" + _clean_name(name) + "//:pkg"

def whl_requirement(name):
    return "@{name}_" + _clean_name(name) + "//:whl"

def data_requirement(name):
    return "@{name}_" + _clean_name(name) + "//:data"

def dist_info_requirement(name):
    return "@{name}_" + _clean_name(name) + "//:dist_info"

def entry_point(pkg, script = None):
    fail("Not implemented yet")

def install_deps(**whl_library_kwargs):
{install_deps_calls}
    for wheel_name in _wheel_names:
        whl_library_alias(
            name = "{name}_" + wheel_name,
            wheel_name = wheel_name,
            default_version = "{default_version}",
            version_map = _version_map[wheel_name],
        )
""".format(
        name = rctx.attr.name,
        install_deps_calls = "\n".join(install_deps_calls),
        load_statements = "\n".join(load_statements),
        process_requirements_calls = "\n".join(process_requirements_calls),
        rules_python = rules_python,
        default_version = rctx.attr.default_version,
    )
    rctx.file("requirements.bzl", requirements_bzl)
    rctx.file("BUILD.bazel", "exports_files(['requirements.bzl'])")

_multi_pip_parse = repository_rule(
    _multi_pip_parse_impl,
    attrs = {
        "default_version": attr.string(),
        "pip_parses": attr.string_dict(),
        "_rules_python_workspace": attr.label(default = Label("//:WORKSPACE")),
    },
)

def _whl_library_alias_impl(rctx):
    rules_python = rctx.attr._rules_python_workspace.workspace_name
    if rctx.attr.default_version:
        default_repo_prefix = rctx.attr.version_map[rctx.attr.default_version]
    else:
        default_repo_prefix = None
    version_map = rctx.attr.version_map.items()
    build_content = ["# Generated by python/pip.bzl"]
    for alias_name in ["pkg", "whl", "data", "dist_info"]:
        build_content.append(_whl_library_render_alias_target(
            alias_name = alias_name,
            default_repo_prefix = default_repo_prefix,
            rules_python = rules_python,
            version_map = version_map,
            wheel_name = rctx.attr.wheel_name,
        ))
    rctx.file("BUILD.bazel", "\n".join(build_content))

def _whl_library_render_alias_target(
        alias_name,
        default_repo_prefix,
        rules_python,
        version_map,
        wheel_name):
    # The template below adds one @, but under bzlmod, the name
    # is canonical, so we have to add a second @.
    if BZLMOD_ENABLED:
        rules_python = "@" + rules_python

    alias = ["""\
alias(
    name = "{alias_name}",
    actual = select({{""".format(alias_name = alias_name)]
    for [python_version, repo_prefix] in version_map:
        alias.append("""\
        "@{rules_python}//python/config_settings:is_python_{full_python_version}": "{actual}",""".format(
            full_python_version = full_version(python_version),
            actual = "@{repo_prefix}{wheel_name}//:{alias_name}".format(
                repo_prefix = repo_prefix,
                wheel_name = wheel_name,
                alias_name = alias_name,
            ),
            rules_python = rules_python,
        ))
    if default_repo_prefix:
        default_actual = "@{repo_prefix}{wheel_name}//:{alias_name}".format(
            repo_prefix = default_repo_prefix,
            wheel_name = wheel_name,
            alias_name = alias_name,
        )
        alias.append('        "//conditions:default": "{default_actual}",'.format(
            default_actual = default_actual,
        ))

    alias.append("    },")  # Close select expression condition dict
    if not default_repo_prefix:
        supported_versions = sorted([python_version for python_version, _ in version_map])
        alias.append('    no_match_error="""{}""",'.format(
            NO_MATCH_ERROR_MESSAGE_TEMPLATE.format(
                supported_versions = ", ".join(supported_versions),
                rules_python = rules_python,
            ),
        ))
    alias.append("    ),")  # Close the select expression
    alias.append('    visibility = ["//visibility:public"],')
    alias.append(")")  # Close the alias() expression
    return "\n".join(alias)

whl_library_alias = repository_rule(
    _whl_library_alias_impl,
    attrs = {
        "default_version": attr.string(
            mandatory = False,
            doc = "Optional Python version in major.minor format, e.g. '3.10'." +
                  "The Python version of the wheel to use when the versions " +
                  "from `version_map` don't match. This allows the default " +
                  "(version unaware) rules to match and select a wheel. If " +
                  "not specified, then the default rules won't be able to " +
                  "resolve a wheel and an error will occur.",
        ),
        "version_map": attr.string_dict(mandatory = True),
        "wheel_name": attr.string(mandatory = True),
        "_rules_python_workspace": attr.label(default = Label("//:WORKSPACE")),
    },
)

def multi_pip_parse(name, default_version, python_versions, python_interpreter_target, requirements_lock, **kwargs):
    """NOT INTENDED FOR DIRECT USE!

    This is intended to be used by the multi_pip_parse implementation in the template of the
    multi_toolchain_aliases repository rule.

    Args:
        name: the name of the multi_pip_parse repository.
        default_version: the default Python version.
        python_versions: all Python toolchain versions currently registered.
        python_interpreter_target: a dictionary which keys are Python versions and values are resolved host interpreters.
        requirements_lock: a dictionary which keys are Python versions and values are locked requirements files.
        **kwargs: extra arguments passed to all wrapped pip_parse.

    Returns:
        The internal implementation of multi_pip_parse repository rule.
    """
    pip_parses = {}
    for python_version in python_versions:
        if not python_version in python_interpreter_target:
            fail("Missing python_interpreter_target for Python version %s in '%s'" % (python_version, name))
        if not python_version in requirements_lock:
            fail("Missing requirements_lock for Python version %s in '%s'" % (python_version, name))

        pip_parse_name = name + "_" + python_version.replace(".", "_")
        pip_parse(
            name = pip_parse_name,
            python_interpreter_target = python_interpreter_target[python_version],
            requirements_lock = requirements_lock[python_version],
            **kwargs
        )
        pip_parses[python_version] = pip_parse_name

    return _multi_pip_parse(
        name = name,
        default_version = default_version,
        pip_parses = pip_parses,
    )


from heapq import heappop, heappush
from math import inf
from sys import stdin
input = stdin.readline

def Dijkstra(v) :
    dist = [inf] * (n + 1)
    dist[v] = 0
    pq = [(0, v)]
    while pq :
        w, v = heappop(pq)
        if v == t : return dist
        if dist[v] < w : continue
        for nv, nw in edges[v].items() :
            nw += w
            if nw < dist[nv] :
                dist[nv] = nw
                heappush(pq, (nw, nv))
    return dist

if __name__ == "__main__" :
    n, m = map(int, input().split())
    edges = [dict() for _ in range(n + 1)]
    for _ in range(m) :
        a, b, c = map(int, input().split())
        edges[a][b] = min(edges[a][b], c) if b in edges[a].keys() else c
        edges[b][a] = min(edges[b][a], c) if a in edges[b].keys() else c
    s, t = map(int, input().split())
    dist = Dijkstra(s)
    print(dist[t])


# main.py
from operator import itemgetter

FONT_BOLD = "\033[1m"
FONT_RESET = "\033[0m"

input_data: list = [[1, 3, 3, 4], [2, 1, 3, 5],
                    [4, 0, 1, 7], [5, 2, 1, 0], [0, 4, 8, 3]]

def main():
    print("%s%-30s%s" % (FONT_BOLD, "Input data:", FONT_RESET), input_data)
    sorted_list: list = sort_list(input_data)
    print("%s%-30s%s" %
          (FONT_BOLD, "Sort by second element:", FONT_RESET), sorted_list)
    mapped_dict: dict = map_to_dictonary(sorted_list)
    print("%s%-30s%s" % (FONT_BOLD, "Map to dictonary:", FONT_RESET), mapped_dict)
    sorted_dict: dict = sort_dictonary(mapped_dict)
    print("%s%-30s%s" %
          (FONT_BOLD, "Sort dictonary values desc:", FONT_RESET), sorted_dict)
    generated_set: set = to_set(sorted_dict)
    print("%s%-30s%s" %
          (FONT_BOLD, "Map dictonary values to set:", FONT_RESET), generated_set)
    result_str: str = set_to_str(generated_set)
    print("%s%-30s%s" %
          (FONT_BOLD, "Convert set to string:", FONT_RESET), result_str)

def sort_list(input_list: list):
    return sorted(input_list, key=itemgetter(1))

def map_to_dictonary(input_list: list):
    return dict((item[1], [item[0]] + item[2:4]) for item in input_list)

def sort_dictonary(input_dict: dict):
    output_dict: dict = input_dict.copy()
    for _, value in output_dict.items():
        value.sort(reverse=True)
    return output_dict

def to_set(input_dict: dict):
    output_set: set = set()
    for _, value in input_dict.items():
        output_set.update(value)
    return output_set

def set_to_str(input_set: set):
    return ", ".join(map(str, input_set))

main()


#User function Template for python3

class Solution:

    def buildLowestNumber(self, S,N):
        i=0
        stack=[]
        while(i<len(S)):
            if(len(stack)==0 or stack[-1]<=S[i] or N==0):
                stack.append(S[i])
            else:
                while(len(stack)!=0 and stack[-1]>S[i] and N>0):
                    stack.pop()
                    N-=1
                stack.append(S[i])
            i+=1
        while(N>0 and len(stack)!=0):
            stack.pop()
            N-=1
        i=0
        while(i<len(stack) and stack[i]=='0'):
            i+=1
        stack=stack[i:]
        if(len(stack)==0):
            return "0"
        return "".join(stack)

#{
 # Driver Code Starts
#Initial Template for Python 3

if __name__ == '__main__':

    t = int(input())

    for _ in range(t):
        N = int(input())
        S = input()

        solObj = Solution()

        print(solObj.buildLowestNumber(S,N))
# } Driver Code Ends

Build the smallest - GFG/build-the-smallest.py


# -*- coding: utf-8 -*-
#

from .ansible.inventory import BaseInventory
from assets.utils import get_assets_by_id_list, get_system_user_by_id

__all__ = [
    'JMSInventory'
]

class JMSInventory(BaseInventory):
    """
    JMS Inventory is the manager with jumpserver assets, so you can
    write you own manager, construct you inventory
    """
    def __init__(self, assets, run_as_admin=False, run_as=None, become_info=None):
        """
        :param host_id_list: ["test1", ]
        :param run_as_admin: True 是否使用管理用户去执行, 每台服务器的管理用户可能不同
        :param run_as: 是否统一使用某个系统用户去执行
        :param become_info: 是否become成某个用户去执行
        """
        self.assets = assets
        self.using_admin = run_as_admin
        self.run_as = run_as
        self.become_info = become_info

        host_list = []

        for asset in assets:
            info = self.convert_to_ansible(asset, run_as_admin=run_as_admin)
            host_list.append(info)

        if run_as:
            run_user_info = self.get_run_user_info()
            for host in host_list:
                host.update(run_user_info)

        if become_info:
            for host in host_list:
                host.update(become_info)
        super().__init__(host_list=host_list)

    def convert_to_ansible(self, asset, run_as_admin=False):
        info = {
            'id': asset.id,
            'hostname': asset.hostname,
            'ip': asset.ip,
            'port': asset.port,
            'vars': dict(),
            'groups': [],
        }
        if asset.domain and asset.domain.has_gateway():
            info["vars"].update(self.make_proxy_command(asset))
        if run_as_admin:
            info.update(asset.get_auth_info())
        for node in asset.nodes.all():
            info["groups"].append(node.value)
        for label in asset.labels.all():
            info["vars"].update({
                label.name: label.value
            })
            info["groups"].append("{}:{}".format(label.name, label.value))
        if asset.domain:
            info["vars"].update({
                "domain": asset.domain.name,
            })
            info["groups"].append("domain_"+asset.domain.name)
        return info

    def get_run_user_info(self):
        system_user = self.run_as
        if not system_user:
            return {}
        else:
            return system_user._to_secret_json()

    @staticmethod
    def make_proxy_command(asset):
        gateway = asset.domain.random_gateway()
        proxy_command_list = [
            "ssh", "-p", str(gateway.port),
            "-o", "StrictHostKeyChecking=no",
            "{}@{}".format(gateway.username, gateway.ip),
            "-W", "%h:%p", "-q",
        ]

        if gateway.password:
            proxy_command_list.insert(
                0, "sshpass -p '{}'".format(gateway.password)
            )
        if gateway.private_key:
            proxy_command_list.append("-i {}".format(gateway.private_key_file))

        proxy_command = "'-o ProxyCommand={}'".format(
            " ".join(proxy_command_list)
        )
        return {"ansible_ssh_common_args": proxy_command}


import requests, praw, time, logging
from datetime import timezone, datetime
from authenticate import getToken
from secret import credentials
from database import Post, PostScores, Comments, CommentsClosure, CommentScores, getSession

format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")

user_agent = "canaryScanner by verykarmamuchreddit"

reddit = praw.Reddit(client_id=credentials["clientId"],
    client_secret=credentials["clientSecret"],
    user_agent=user_agent)

def addNewPosts(subredditName, session):

    subreddit = reddit.subreddit(subredditName)

    newPosts = []
    existingPosts = [pId for pId, in session.query(Post.postId)]

    for submission in subreddit.new(limit=100):
        if submission.id not in existingPosts:
            post = Post(postId=submission.id, title=submission.title, subreddit=submission.subreddit.display_name,
            created=int(submission.created_utc), author=submission.author.name)
            newPosts.append(post)

    session.add_all(newPosts)
    session.commit()
    logging.info(f"{subredditName}: added {len(newPosts)} new posts")

def addPostScores(subredditName, session):

    existingPosts = [p for p in session.query(Post).filter(Post.subreddit==subredditName)]

    #get a list of posts
    for existingPost in existingPosts:
        now = int(datetime.now(tz=timezone.utc).timestamp())
        count = len(existingPost.postScores)

        if count > 0:
            postScoreTime = existingPost.postScores[count - 1].age + existingPost.created
            if (now - postScoreTime > 10*60) and (now - existingPost.created < 60*60*24):
                post = reddit.submission(id=existingPost.postId)
                age = now - post.created_utc
                currentPostScore = PostScores(postId=existingPost.postId, score=post.score,
                age=age, numberOfComments=post.num_comments)
                existingPost.postScores.append(currentPostScore)
                session.add(existingPost)
                logging.info(f"{subredditName}: updating score for {post.title}")
        else:
            post = reddit.submission(id=existingPost.postId)
            age = now - post.created_utc
            currentPostScore = PostScores(postId=existingPost.postId, score=post.score,
            age=age, numberOfComments=post.num_comments)
            existingPost.postScores.append(currentPostScore)
            session.add(existingPost)
            logging.info(f"{subredditName}: initial score for {post.title}")

    session.commit()

def addNewComments(subredditName, session):
    now = int(datetime.now(tz=timezone.utc).timestamp())
    commentsAdded = 0

    existingPosts = [p for p in session.query(Post).filter(Post.subreddit==subredditName)]
    for existingPost in existingPosts:
        if (now - existingPost.created) < 60*60*24:

            existingComments = [com.commentId for com in session.query(Comments).filter(Comments.postId==existingPost.postId)]

            post = reddit.submission(id=existingPost.postId)
            post.comments.replace_more(limit=None)
            commentList = post.comments.list()

            levelMap = {}
            for comment in commentList:
                if comment not in existingComments:
                    parentId = comment.parent_id[3:] #trim off prefix of t1_ or t3_
                    levelMap[comment.id] = levelMap.get(parentId, 0) + 1

                    #this is lazy nonetype reference handling. don't judge.
                    try:
                        author = "" if comment.author is None else comment.author.name
                    except:
                        author = ""

                    newComment = Comments(commentId=comment.id, parentId=parentId, level=levelMap[comment.id], commentText=comment.body,
                    author=author, postId=comment.submission, created=int(comment.created_utc), edited=bool(comment.edited))

                    existingPost.comments.append(newComment)
                    commentsAdded += 1

                #logic to add to closure table goes here
                parentId = comment.parent_id[3:] #starts at the existing parent
                existingComment = session.query(Comments).filter(Comments.commentId == comment.id).one()
                while(parentId != existingComment.postId):
                    newCommentClosure = CommentsClosure(parentId=parentId, childId=existingComment.commentId, postId=existingComment.postId)

                    isInClosureAlready = False
                    for dClosure in existingComment.commentsClosures:
                        if dClosure.parentId == newCommentClosure.parentId and dClosure.childId == newCommentClosure.childId:
                            isInClosureAlready = True

                    if not isInClosureAlready:
                        existingComment.commentsClosures.append(newCommentClosure)

                    parentComment = session.query(Comments).filter(Comments.commentId == parentId).one()
                    if parentComment is None:
                        break

                    parentId = parentComment.parentId

                session.add(existingComment)

            session.add(existingPost)

    session.commit()
    logging.info(f"{subredditName}: {commentsAdded} comments added")

def addCommentScores(subredditName, session):
    existingComments = session.query(Comments).join(Comments.post).filter(Post.subreddit==subredditName).all()

    #get a list of posts
    for existingComment in existingComments:
        now = int(datetime.now(tz=timezone.utc).timestamp())
        count = len(existingComment.commentScores)

        if count > 0:
            commentScoreTime = existingComment.commentScores[count - 1].age + existingComment.created
            if (now - commentScoreTime > 10*60) and (now - existingComment.created < 60*60*24):
                feedComment = reddit.comment(id=existingComment.commentId)
                age = now - existingComment.created
                newCommentScore = CommentScores(commentId=existingComment.commentId, score=feedComment.score,
                age=age)
                existingComment.commentScores.append(newCommentScore)
                session.add(existingComment)
                logging.info(f"{subredditName}: updating score for {existingComment.commentId}")

        else:
            feedComment = reddit.comment(id=existingComment.commentId)
            age = now - existingComment.created
            newCommentScore = CommentScores(commentId=existingComment.commentId, score=feedComment.score,
            age=age)
            existingComment.commentScores.append(newCommentScore)
            session.add(existingComment)
            logging.info(f"{subredditName}: initial score for {existingComment.commentId}")

    session.commit()

def quick():
    # begin = int(datetime.now(tz=timezone.utc).timestamp())
    # time.sleep(5)
    # end = int(datetime.now(tz=timezone.utc).timestamp())
    # print(f'end is {end}, begin is {begin} and diff is {end - begin}')
    reddit = praw.Reddit(client_id=credentials["clientId"],
    client_secret=credentials["clientSecret"],
    user_agent=user_agent)

    submission = reddit.comment(id="g1dpr0t")
    print(submission.score)

#need to find out how to get comment Id, parent comment Id

def monitoring():
    #os.path.getsize("canary.db")

    #texts number of posts and comments added, as well as file size of database

    #on error text error hit
    pass

def runUpdate(subreddit, session):
    addNewPosts(subreddit, session)
    addPostScores(subreddit, session)
    addNewComments(subreddit, session)
    addCommentScores(subreddit, session)

if __name__ == "__main__":
    # quick()
    runUpdate("ProgrammerHumor")


import os
import sys

HERE = os.path.dirname(os.path.realpath(__file__))
BUILD_DIR = os.path.join(HERE, "../../")
CORE_DIR = os.path.join(BUILD_DIR, "pybmix/core/")
sys.path.insert(0, os.path.realpath(BUILD_DIR))
sys.path.insert(0, os.path.realpath(CORE_DIR))

import numpy as np
import matplotlib.pyplot as plt
from pybmix.core.mixing import DirichletProcessMixing
from pybmix.core.hierarchy import PythonHierarchy
from pybmix.core.mixture_model import MixtureModel
from pybmix.estimators.density_estimator import DensityEstimator

np.random.seed(2021)

def sample_from_mixture(weights, means, sds, n_data):
    n_comp = len(weights)
    clus_alloc = np.random.choice(np.arange(n_comp), p=[0.5, 0.5], size=n_data)
    return np.random.normal(loc=means[clus_alloc], scale=sds[clus_alloc])

y = sample_from_mixture(np.array([0.5, 0.5]), np.array([-3, 3]), np.array([1, 1]), 200)

plt.hist(y, bins=20)
plt.show()

mixing = DirichletProcessMixing(total_mass=5)  # DP mixing

hierarchy = PythonHierarchy("LapNIG_Hierarchy")

mixture = MixtureModel(mixing, hierarchy)

niter = 110
nburn = 10
mixture.run_mcmc(y, algorithm="Neal8", niter=niter, nburn=nburn)

grid = np.linspace(-6, 6, 500)
dens_est = DensityEstimator(mixture)
densities = dens_est.estimate_density(grid)

plt.hist(y, density=True, bins=20)
plt.plot(grid, np.mean(densities, axis=0), lw=3, label="predictive density")
plt.legend()
plt.show()
idxs = [int((niter - nburn) * 0.1), int((niter - nburn) * 0.2), int((niter - nburn) * 0.9)]

for idx in idxs:
    plt.plot(grid, densities[idx, :], "--", label="iteration: {0}".format(idx))
    plt.legend()
    plt.show()


import pandas as pd

def estrai_voto(x):
    return x not in ["Voto", "6*"]

def voto_troncato(x):
    return 0.5 * round(int(x * 100 / 25) / 2 + 0.1)

def squadra(valore):
    try:
        int(valore)
        return False
    except ValueError:
        return valore != 'Cod.'

def dataframe_corretto(file: str) -> pd.DataFrame:
    dataframe = pd.DataFrame([])
    colonne = [
        "COD",
        "RUOLO",
        "NOME",
        "VOTO",
        "GOL_FATTI",
        "GOL_SUBITI",
        "RIGORI_PARATI",
        "RIGORI_SBAGLIATI",
        "RIGORI_FATTI",
        "AUTOGOL",
        "AMMONIZIONI",
        "ESPULSIONI",
        "ASSIST"
    ]
    squadre = pd.read_excel(file).iloc[:, :1].loc[3:]
    squadre = squadre.loc[squadre[squadre.columns[0]].apply(squadra)]
    squadre = squadre[squadre.columns[0]].values.tolist()
    dataframe[colonne] = pd.read_excel(file).dropna().iloc[:, :13]
    dataframe = dataframe.loc[dataframe.RUOLO != 'ALL']
    dataframe = dataframe.loc[dataframe.VOTO.apply(estrai_voto)]
    fantavoti = [voto + 3 * (Gf + Rp - Rs + Rf) - 2 * Au - Gs - Esp + Ass - 0.5 * Amm for
                 _, _, _, voto, Gf, Gs, Rp, Rs, Rf, Au, Amm, Esp, Ass in dataframe.values]
    dataframe["FANTAVOTO"] = fantavoti
    dataframe["NOME"] = dataframe.NOME.str.upper()
    indice = 0
    colonnaSquadra = []
    vecchioRuolo = 'P'
    for el in dataframe.values:
        s = squadre[indice]
        if el[1] == 'P' and vecchioRuolo != 'P':
            indice += 1
            s = squadre[indice]
        vecchioRuolo = el[1]
        colonnaSquadra.append(s)
    dataframe["SQUADRA"] = colonnaSquadra
    return dataframe

def coefficiente_binomiale(n, k):
    if n < k or k < 0:
        raise ValueError(f"n deve essere maggiore o uguale a k ed entrambi non possono essere negativi"
                         f":\nn = {n}, k = {k}")
    delta = n - k
    k = min(delta, k)
    if k == 0:
        return 1
    return int(n / k * coefficiente_binomiale(n - 1, k - 1))

def binomiale(n, k, p):
    return coefficiente_binomiale(n, k) * p ** k * (1 - p) ** (n - k)

def estrai_probabilita(numero_possibili_voti, voto, voto_minimo, media):
    k = 2 * (voto - voto_minimo)
    p = 2 * (media - voto_minimo) / numero_possibili_voti
    return binomiale(numero_possibili_voti, k, p)

def voto_centrale(lista):
    media = sum(lista) / len(lista)
    minimo, massimo = min(lista), max(lista)
    numero_possibili_voti = int(2 * (massimo - minimo)) + 1
    voti_possibili = [minimo + 0.5 * i for i in range(numero_possibili_voti)]
    probabilita = [estrai_probabilita(numero_possibili_voti, voto_possibile, minimo, media) for voto_possibile in
                   voti_possibili]
    occorrenze = [probabilita.count(x) for x in probabilita]
    z = list(zip(probabilita, voti_possibili, occorrenze))
    z.sort(reverse=True)
    voto_centrale = sum(list(map(lambda x: x[1], z[:z[0][2]]))) / z[0][2]
    return voto_centrale

def media(lista):
    return sum(lista) / len(lista)

def maiuscolo(el):
    return el.upper()

def estrai_sfidante(df, squadra):
    if df.HomeTeam.apply(maiuscolo).values[0] == squadra:
        return df.AwayTeam.apply(maiuscolo).values[0]
    return df.HomeTeam.apply(maiuscolo).values[0]

def estrai_voti(df, squadra):
    df_all = df.loc[df["Ruolo"] == "ALL"]
    index_start = df.loc[df["Cod."] == squadra].index[0]
    index_end = list(filter(lambda x: x > index_start + 1, df_all.index.tolist()))[0]
    return df.iloc[index_start + 2:index_end].loc[df.Voto.apply(voto_valido) == True]

def voto_valido(x):
    if isinstance(x, str):
        return False
    return True

def ottieni_fantavoto(row):
    return 3 * (row[1] + row[3] - row[4] + row[5]) - 2 * row[6] + row[0] - row[2] - row[8] + row[9] - 0.5 * row[7]

def inserisci(diz, col_media, squadra, media_voto):
    try:
        diz[col_media][squadra] += media_voto
    except KeyError:
        diz[col_media][squadra] = media_voto

def voto_con_modificatore(lista_v_fv):
    a = 2
    b = -21
    c = 55
    return [(a * v ** 2 + b * v + c) / 4 + fv for v, fv in lista_v_fv]

def voto_potenziale(voto, fanta_voto, ruolo):
    if ruolo in ["D", "P"]:
        return (2 * voto ** 2 - 21 * voto + 55) / 4 + fanta_voto
    return fanta_voto


# Author: Allen Anker
# Created by Allen Anker on 20/09/2018
"""
Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array,
and it should return false if every element is distinct.
"""
from collections import defaultdict

class Solution:
    def contains_duplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        seen = defaultdict()
        for i in nums:
            if seen.get(i):
                return True
            else:
                seen[i] = 1
        return False

solution = Solution()
nums = [1, 2, 3]
print(solution.contains_duplicate(nums))


from gekko import GEKKO
import numpy as np
#import matplotlib.pyplot as plt
m = GEKKO()
m.solver_options = ['max_iter 500']#,'max_cpu_time 100']
nt = 501
tm = np.linspace(0,1,nt)
m.time = tm
#m.options.SOLVER=1 #compare all solvers

#variables

#initialMass = m.Const(value=10)
v = m.Var(name='v',value=0.) #speed
h = m.Var(name='h', value=50.) #height
mass = m.Var(name='m', value=10, lb=0., ub=10) #mass
g = m.Const(value=1.625) #gravitational acceleration
k = m.Const(value=0.1)
power = m.Const(value=10.)

#MV

alpha = m.MV(value=0.2, lb=0.2, ub=1.) #control variable
alpha.STATUS = 1

#FV

tf = m.FV(value=12, lb=0.01)#, ub=100000)
tf.STATUS = 1 # the value can be adjusted by the optimizer

p = np.zeros(nt)
p[-1] = 1.
final = m.Param(value=p)

#print(tf.value*(-g+2*alpha*g*power/mass).value)

#Equations

m.Equation(v.dt() == tf*(-g+2*alpha*g*power/mass))
m.Equation(h.dt() == tf*v)
m.Equation(mass.dt() == -tf*k*alpha)

m.Equation(h*final == 0.)
#m.fix_final(h, 0.0)
m.Equation(v*final == 0.)
#m.fix_final(v, 0.0)
m.Equation(mass*final >= 0.)

m.Obj(tf)
#m.Obj(10-mass)
#m.Maximize(10-mass)

m.options.IMODE = 6#6
m.solve(disp=False)

print('Solution')
print('Final time: '+str(tf.value[0]))

#plt.figure(1)
#plt.plot(tm,h.value,'k-')#,LineWidth=2,label=r'$h$')
#plt.plot(tm,v.value,'b-')#,LineWidth=2,label=r'$v$')
#plt.plot(tm,mass.value,'g--')#,LineWidth=2,label=r'$m$')
#plt.plot(tm,alpha.value,'r--')#,LineWidth=2,label=r'$\alpha$')
#plt.legend(loc='best')
#plt.xlabel('Time')
#plt.ylabel('Value')
#plt.show()


from typing import Any, Sequence, Union, Iterable, Optional
import functools

from flax import linen as nn
from flax.linen import partitioning as nn_partitioning
from flax import struct
import jax.numpy as jnp
from t5x.contrib.gpu.t5.layers import MultiHeadDotProductAttention, make_attention_mask
from flax.linen import DenseGeneral, Conv, LayerNorm, GroupNorm
import jax
from einops import rearrange

param_with_axes = nn_partitioning.param_with_axes
OptionalArray = Optional[jnp.ndarray]
Array = jnp.ndarray

default_embed_init = nn.initializers.variance_scaling(
    1.0, 'fan_in', 'normal', out_axis=0)

@struct.dataclass
class DiffusionConfig:
  dtype: Any = jnp.float32
  model_dim: int = 64
  attn_cond_dim: int = 512
  cond_dim: Optional[int] = None #timestep/pooled text embedding channels. Defaults to model_dim*4
  resblocks_per_level: Union[int, Sequence[int]] = 2
  width_multipliers: Sequence[int] = (1, 2, 3, 4)
  attn_resolutions: Sequence[int] = (32, 16, 8)
  mha_head_dim: int = 64
  attn_heads: Union[int, Sequence[int]] = 2
  unified_qkv_norm: bool = False
  deepfloyd_attnpooling: bool = False
  resblock_activation: str = 'swish'
  resblock_scale_skip: bool = False
  output_ch: int = 3
  dropout_rate: float = 0.1

  # modes are 'shuffle', 'conv' and 'resize'.
  #            (upsampling   , downsampling)
  # shuffle -> pixel shuffle / unshuffle
  # conv    -> resize + conv / strided conv
  # resize  -> interpolation / average pool
  upsample_mode: str = 'shuffle'
  downsample_mode: str = 'shuffle'

  # If True, block will use a 3x3 conv instead of 1x1 conv to correct
  # channel dim mismatch in skip connection (if one exists)
  spatial_skip: bool = False

  # 'shift_scale' or 'addition'. Strategy for incorporating the conditioning vector.
  cond_strategy: str = 'shift_scale'

  # force groupnorm in fp32
  norm_32: bool = True

  # scale attention logits by \sqrt(head_dim)
  scale_attn_logits: bool = True
  float32_attention_logits: bool =False
  text_conditionable: bool = True
  null_text_emb_ct: int = 0

def single_or_idx(possibly_iter, idx):
    if isinstance(possibly_iter, Sequence):
        return possibly_iter[idx]
    else:
        return possibly_iter

class ImagenUNet(nn.Module):
  """ An Imagen diffusion U-net """
  config: DiffusionConfig

  @nn.compact
  def __call__(self, images, time,
               text_enc: OptionalArray=None,
               text_lens: OptionalArray=None,
               low_res_images: OptionalArray=None,
               noise_aug_level: OptionalArray=None,
               enable_dropout=True):
    """
    Args:
    images: samples to denoise. [b, h, w, c]
    time:   time conditioning. [b, 1]
    text_enc: text embeddings (required for text_conditionable) [b, seq_len, embed]
    text_lens: text sequence lengths in binary mask format      [b, seq_len]
    """
    from rosetta.projects.imagen import layers  # to avoid circular import
    cfg = self.config
    activation = layers._convert_to_activation_function(cfg.resblock_activation)
    deterministic=not enable_dropout
    linear = functools.partial(DenseGeneral,
                               axis=-1,
                               use_bias=True,
                               dtype=cfg.dtype,
                               kernel_axes=('embed',))

    spatial_conv = functools.partial(Conv,
                                     kernel_size=(3,3),
                                     strides=1,
                                     padding='SAME',
                                     dtype=cfg.dtype)
    input_ch = images.shape[-1]

    # create time embedding
    if cfg.cond_dim is None:
        time_embed_dim = cfg.model_dim * 4
    else:
        time_embed_dim = cfg.cond_dim
    cond_embed = layers.get_timestep_embedding(time, cfg.model_dim, dtype=jnp.float32)
    cond_embed = linear(features=time_embed_dim, name='time_dense_1')(cond_embed)
    cond_embed = activation(cond_embed)
    cond_embed = linear(features=time_embed_dim, name='time_dense_2')(cond_embed)

    if low_res_images is not None:
        print('Low res images available. Running as a superresolution network')
        if noise_aug_level is None:
            jax.debug.print('noise_aug not given but it *really* should be')
            noise_aug_level = jnp.ones_like(time) * (.25 * jnp.log(0.002)) # fallback EDM c_noise_fn on minimal noise
        aug_embed = layers.get_timestep_embedding(noise_aug_level, cfg.model_dim, dtype=jnp.float32)
        aug_embed = linear(features=time_embed_dim, name='aug_dense_1')(aug_embed)
        aug_embed = activation(aug_embed)
        aug_embed = linear(features=time_embed_dim, name='aug_dense_2')(aug_embed)

        cond_embed = cond_embed + aug_embed

        scaled_low_res = jax.image.resize(low_res_images, images.shape, "bicubic")
        images = jnp.concatenate([images, scaled_low_res], axis=-1)

    # create attn pooled text embedding and project text to cond_dim
    if cfg.text_conditionable:
        assert text_lens is not None, "text_lens cannot be None. If you're trying to null condition, pass in a 0 mask"
        assert text_enc is not None, "text_enc cannot be None. If you're trying to null condition, pass in 0s of appropriate shape. This network will add in the requisite null tokens"

        # setup null tokens
        if cfg.null_text_emb_ct > 0:
            null_text_mask = jnp.sum(text_lens, axis=1, keepdims=True)

            embedding_init = nn.initializers.variance_scaling(1.0, 'fan_in', 'normal', out_axis=0)
            null_text_embedding = param_with_axes(
                'null_text_embeddings',
                embedding_init,
                (cfg.null_text_emb_ct, text_enc.shape[-1]),
                jnp.float32,
                axes=('vocab', 'embed'))

            # first null_text_emb_ct tokens to null_text_embedding
            null_text_enc = jnp.zeros_like(text_enc[0:1]).at[:, :cfg.null_text_emb_ct].set(null_text_embedding)
            null_text_lens = jnp.zeros_like(text_lens[0:1]).at[:, :cfg.null_text_emb_ct].set(1)
            text_enc = jnp.where(jnp.expand_dims(null_text_mask, axis=-1) > 0, text_enc, null_text_enc)
            text_lens = jnp.where(null_text_mask > 0, text_lens, null_text_lens)

        # attention pooling
        if isinstance(cfg.attn_heads, Iterable):
            num_heads = text_enc.shape[-1] // cfg.mha_head_dim
        else:
            num_heads = None

        if cfg.deepfloyd_attnpooling:
            attn_pooled = LayerNorm(dtype=jnp.float32 if cfg.norm_32 else cfg.dtype, name='attn_pool_ln_0')(text_enc)
            attn_pooled = layers.DeepFloydAttentionPoolingBlock(cfg=cfg, num_heads=num_heads)(attn_pooled, text_lens)
            attn_pooled = linear(features=cfg.attn_cond_dim, name='attn_pool_dense_0')(attn_pooled)
            attn_pooled = LayerNorm(dtype=jnp.float32 if cfg.norm_32 else cfg.dtype, name='attn_pool_ln_1')(attn_pooled)
        else:
            attn_pooled = layers.AttentionPoolingBlock(cfg=cfg, num_heads=num_heads)(text_enc, text_lens)
            attn_pooled = LayerNorm(dtype=jnp.float32 if cfg.norm_32 else cfg.dtype, name='attn_pool_ln_0')(attn_pooled)
            attn_pooled = linear(features=cfg.attn_cond_dim, name='attn_pool_dense_0')(attn_pooled)
            attn_pooled = LayerNorm(dtype=jnp.float32 if cfg.norm_32 else cfg.dtype, name='attn_pool_ln_1')(attn_pooled)
            attn_pooled = linear(features=time_embed_dim, name='attn_pool_dense_1')(attn_pooled)
            attn_pooled = activation(attn_pooled)
            attn_pooled = linear(features=time_embed_dim, name='attn_pool_dense_2')(attn_pooled)

        cond_embed = attn_pooled + cond_embed # Has dimension of time_embed_dim

        # text embedding projection to cond_dim
        text_enc = linear(features=cfg.attn_cond_dim, name='text_enc_projection')(text_enc)

    # make image_channel -> model_dim convolution
    x = spatial_conv(features=cfg.model_dim * cfg.width_multipliers[0], name='unet_in_conv')(images)

    # down branch resblocks + attn on designated resolutions
    down_outputs = [x]
    for level, width_mult in enumerate(cfg.width_multipliers):
        level_channels = cfg.model_dim * width_mult
        img_res = images.shape[1] // (2 ** level)

        for res_idx in range(single_or_idx(cfg.resblocks_per_level, level)):
            x = layers.ResBlock(cfg=cfg, out_channels=level_channels, up_down_sample='none',
                                name='resblock_enc_{}_{}'.format(img_res, res_idx)) \
                                (x, cond_embed, deterministic=deterministic)
            print("Encoder ResBlock #", res_idx, " at resolution: ", img_res, " level: ", level, " width: ", level_channels)

            # attend if image is of designated resolution
            if img_res in cfg.attn_resolutions:
                attn_idx = level - (len(cfg.width_multipliers) - len(cfg.attn_resolutions))
                x = layers.ImgAttentionBlock(cfg=cfg, num_heads=single_or_idx(cfg.attn_heads, attn_idx), name='attnblock_enc_{}_{}'.format(img_res, res_idx)) \
                                            (x, text_enc, text_lens, deterministic=deterministic)
                print("SelfAttentionBlock #", res_idx, " at resolution: ", img_res, " level: ", level, " width: ", level_channels)

            down_outputs.append(x)

        # if not on the last level, downsample
        if level != len(cfg.width_multipliers) - 1:
            x = layers.ResBlock(cfg=cfg, out_channels=level_channels, up_down_sample='down',
                                name='resblock_enc_downsampling_{}_{}'.format(img_res, res_idx)) \
                                (x, cond_embed, deterministic=deterministic)
            print("Downsampling ResBlock at resolution (to half): ", img_res, " level: ", level, " width: ", level_channels)
            down_outputs.append(x)

    # middle layers
    mid_channels = cfg.model_dim * cfg.width_multipliers[-1]
    x = layers.ResBlock(cfg=cfg, out_channels=mid_channels, up_down_sample='none',
                        name='resblock_mid_1')(x, cond_embed, deterministic=deterministic)
    x = layers.ImgAttentionBlock(cfg=cfg, num_heads=single_or_idx(cfg.attn_heads, -1),name='attnblock_mid_1')(x, text_enc, text_lens, deterministic=deterministic)
    x = layers.ResBlock(cfg=cfg, out_channels=mid_channels, up_down_sample='none',
                        name='resblock_mid_2')(x, cond_embed, deterministic=deterministic)

    print('Encoder Skip Shapes: ',list(map(lambda x : x.shape, down_outputs)))
    # up branch resblocks + attn on designated resolutions + skip connections
    for level, width_mult in list(enumerate(cfg.width_multipliers))[::-1]:
        level_channels = cfg.model_dim * width_mult
        img_res = images.shape[1] // (2 ** level)

        for res_idx in range(single_or_idx(cfg.resblocks_per_level, level) + 1):
            u_skip = down_outputs.pop()
            print("Decoder ResBlock #", res_idx, " at resolution: ", img_res, " level: ", level, " width: ", level_channels, " skip shape: ", u_skip.shape)
            x = jnp.concatenate([x, u_skip], axis=-1)
            x = layers.ResBlock(cfg=cfg, out_channels=level_channels, up_down_sample='none',
                                name='resblock_dec_{}_{}'.format(img_res, res_idx)) \
                                (x, cond_embed, deterministic=deterministic)

            # attend if image is of designated resolution
            if img_res in cfg.attn_resolutions:
                print("SelfAttentionBlock #", res_idx, " at resolution: ", img_res, " level: ", level, " width: ", level_channels)
                attn_idx = level - (len(cfg.width_multipliers) - len(cfg.attn_resolutions))
                x = layers.ImgAttentionBlock(cfg=cfg, num_heads=single_or_idx(cfg.attn_heads, attn_idx), name='attnblock_dec_{}_{}'.format(img_res, res_idx))\
                                            (x, text_enc, text_lens, deterministic=deterministic)

            # upsample if on last resblock and not the highest level
            if res_idx == single_or_idx(cfg.resblocks_per_level, level) and level != 0:
                print("Upsamling ResBlock at resolution (to double): ", img_res, " level: ", level, " width: ", level_channels, " no skip")
                x = layers.ResBlock(cfg=cfg, out_channels=level_channels, up_down_sample='up',
                                    name='resblock_dec_upsampling_{}_{}'.format(img_res, res_idx)) \
                                    (x, cond_embed, deterministic=deterministic)

    # out convolution model_dim -> image_channels
    x = layers.FP32Wrap(GroupNorm(num_groups=32, name='unet_out_gn'))(x)
    x = activation(x)
    # x = spatial_conv(features=cfg.output_ch, name='unet_out_conv', kernel_init=nn.initializers.zeros, no_embed_axis=True)(x)
    x = spatial_conv(features=cfg.output_ch, name='unet_out_conv', kernel_init=nn.initializers.zeros)(x)
    return x


#SWEA1223<계산기2>

tc = 10

for _ in range(1,tc+1):
    n = int(input())
    arr = list(input())
    std = {'*':2, '+':1}

    stack = []
    ans = []
    for i in range(len(arr)):
        if arr[i] in '0123456789':
            ans.append(int(arr[i]))
        else:
            if not stack:
                stack.append(arr[i])
            else:
                if std[stack[-1]] >= std[arr[i]]:
                    while std[stack[-1]] >= std[arr[i]]:
                        result = stack.pop()
                        ans.append(result)
                        if not stack:
                            break
                    stack.append(arr[i])
                else:
                    stack.append(arr[i])
    while stack:
        result = stack.pop()
        ans.append(result)

    stack2 = []
    for i in range(len(ans)):
        if ans[i] in range(10):
            stack2.append(ans[i])
        else:
            a1 = stack2.pop()
            a2 = stack2.pop()
            if ans[i] == '+':
                stack2.append(a1+a2)
            else:
                stack2.append(a1*a2)
    fin_ans = stack2.pop()
    print(f'#{_} {fin_ans}')


class Solution(object):
    def openLock(self, deadends, target):
        visited = set()
        step = 0
        que = []
        que.append("0000")
        visited.add("0000")
        while len(que) > 0:
            size = len(que)
            while size > 0:
                curr_position = que.pop()
                if curr_position.__eq__(target):
                    return step
                if curr_position in deadends:
                    size -= 1
                    continue
                for i in range(4):
                    x = curr_position[i]
                    s1 = curr_position[0:i] + ('0' if x.__eq__('9') else chr(ord(x) + 1)) + curr_position[i + 1:]
                    s2 = curr_position[0:i] + ('9' if x.__eq__('0') else chr(ord(x) - 1)) + curr_position[i + 1:]
                    if s1 not in visited and s1 not in deadends:
                        que.append(s1)
                        visited.add(s1)
                    if s2 not in visited and s2 not in deadends:
                        que.append(s2)
                        visited.add(s2)
                size -= 1
            step += 1
        return -1

deadends = ["0201","0101","0102","1212","2002"]
target = "0202"
a = Solution()
#print(a.openLock(deadends, target))
b = set()
b.add((1,2))
c = (1,2)

print(*c)


import asyncio
import json
import time
import re
from send_message import *

def build(message,client):
	asyncio.create_task(_build(message,client))

async def _build(message,client):
	try:
		file_name = message[1]
	except IndexError:
		file_name = "G:\\python\\projects\\minecraft\\function\\files\\fun1.mcfunction"

	fps = "50"
	try:
		for each in message[2:]:
			each = each.split(":")
			if each[0] == "":
				pass
			elif each[0] == "t":
				fps = each[1]
			else:
				await client.send(command(alert("错误的参数:"+each[0])))
				await client.recv()
				await client.recv()
	except IndexError:
		fps = "50"

	try:
		fps = float(fps)
	except:
		await client.send(command(alert("错误的值:"+fps)))
		await client.recv()
		await client.recv()
		return

	try:
		open(file_name,"r").close()
	except:
		await client.send(command(alert("您的文件路径输入有误,无法找到您的文件!")))
		await client.recv()
		await client.recv()
		return

	with open(file_name,"r") as f:
		lines = f.readlines()

		# 获取玩家坐标
		await client.send(command("tp @s ~~~"))
		result = json.loads(await client.recv())
		try:
			player_pos = result["body"]["destination"]
		except:
			await client.send(command(alert("请稍等一会，您的世界处理不了这么多方块~~~")))
			return
		for each in player_pos:
			player_pos[each] = int(player_pos[each])

		await client.send(command(status("正在将相对坐标转换为绝对坐标...")))
		for i in range(len(lines)):
			time = 0		# 用来计算坐标是 x , y 还是 z
			cmd = lines[i].split(" ")
			# cmd = [setblock,~-8,~-32,~-4,stained_hardened_clay,10]
			for each in cmd:
				# each = "~-8"
				if "~" in each:
					# pos = ["-8"]
					pos = each.split("~")
					pos.pop(0)
					for j in pos:
						# i = -8
						try:
							j = int(j)
						except:
							j = 0
						# x 轴
						if time == 0 or time == 3:
							j = player_pos["x"] + j
							pos
						if time == 1 or time == 4:
							j = player_pos["y"] + j
						if time == 2 or time == 5:
							j = player_pos["z"] + j

						cmd_span = re.search(r"~-*\d*",lines[i]).span()
						cmd_pos = lines[i][cmd_span[0]:cmd_span[1]]
						lines[i] = lines[i].replace(cmd_pos,str(j)+" ",1)
						time += 1
		await client.send(command(status("转换完毕! 正在导入建筑... 期间您可以自由活动")))

		while True:
			recvs = []
			most = False			# 指令未被拒绝
			for each in lines:
				await client.send(command(each))
				print(await client.recv())
				"""
				recvs.append(await client.recv(),each)
	# 			await asyncio.sleep(fps/1000)
			# 检查是否有遗漏
			for each in recvs:
				if "请求" in each[0]:
					await client.send(command(each[1]))
					most = True
			if not most:
				break
			"""
			break

		await client.send(command((ok("导入完毕!"))))


import tensorflow as tf
import numpy as np
import pickle
from sqlalchemy import create_engine
import pandas as pd
import time
from tensorflow.keras.preprocessing.sequence import pad_sequences
import tensorflow
import youtokentome as yttm

def multi_pred(model,query,neg_list,anchor_pos_list,anchor_neg_list):
    """
    Needs refactoring(for handling triplet loss model) and additional
    analysis to determine stability in prediction, i.e. relative
    distances in the learned metric space can have significant
    variances depending on the positive anchor chosen.
    """
    predictions = model.predict([len(neg_list)*[query],neg_list,anchor_pos_list,anchor_neg_list])
    #mean_dist = predictions[:,0].mean()
    mean_rel = (predictions[:,0]>predictions[:,3]).mean()
    #print('Dist',mean_dist,'Rel',mean_rel)
    return mean_rel#np.min([mean_dist,mean_rel])

def load_gravity(dir='/etc/pihole/',table='gravity'):
    db_connect = create_engine('sqlite:///'+dir+'gravity.db')
    connection = db_connect.raw_connection()
    df = pd.read_sql("SELECT * FROM {}".format(table), con=connection)
    connection.close()
    return df

def load_query_list(timestamp=None):
    if not timestamp:
        timestamp = 0
    db_connect = create_engine('sqlite:////etc/pihole/pihole-FTL.db')
    connection = db_connect.raw_connection()
    df = pd.read_sql("SELECT * FROM queries WHERE timestamp > {0}".format(timestamp), con=connection)
    connection.close()
    df['blocked'] = df.status.apply(lambda x: 0 if x in [2,3] else 1)
    return df

def update_gravity(df):
    """
    Not advisable to use. Simultaneous writing to the sql db
    causes corruption isses. Adding domains by command line
    is recommended.
    """
    db_connect = create_engine('sqlite:////etc/pihole/gravity.db', connect_args={'timeout': 15})
    connection = db_connect.raw_connection()
    df.to_sql('domainlist', con=connection,if_exists='replace',index=None)
    connection.close()

def create_dframe(domains,timestamp):
    new_dataframe = pd.DataFrame({'id':len(domains)*[1],'type':len(domains)*[1],'domain':domains,
                                  'enabled':len(domains)*[1],'date_added':len(domains)*[timestamp],
                                  'date_modified':len(domains)*[timestamp],
                                  'comment':len(domains)*['Added by Photon Sphere.']})
    return new_dataframe

def load_yttm():
    model_path = './yttm_model/yttm_ads.model'
    bpe = yttm.BPE(model=model_path)
    return bpe

def prep_data(df,timestamps,tokenizer=None):
    """Needs to be refactored for a triplet loss based model."""
    encoded_queries = pad_sequences(tokenizer.encode(list(df.loc[df.timestamp>timestamps[1]].domain.values), output_type=yttm.OutputType.ID),30,padding='post')
    df_neg = df.loc[(df.blocked==1)&(df.timestamp<timestamps[1])].domain.values
    df_pos_anchors = df.loc[(df.blocked==0)&(df.timestamp<timestamps[1])].domain.values
    df_neg_anchors = df.loc[(df.blocked==1)&(df.timestamp<timestamps[1])].domain.values
    df_pos = df.loc[(df.blocked==0)&(df.timestamp<timestamps[1])].domain.values
    min_len = np.min([len(encoded_queries),len(df_neg),len(df_pos_anchors),len(df_neg_anchors)])
    df_neg = df_neg[:min_len]
    df_pos = df_pos[-min_len:]
    df_pos_anchors = df_pos_anchors[:min_len]
    df_neg_anchors = df_neg_anchors[-min_len:]
    encoded_neg = pad_sequences(tokenizer.encode(list(df_neg), output_type=yttm.OutputType.ID),30,padding='post')
    encoded_pos_anchors = pad_sequences(tokenizer.encode(list(df_pos_anchors), output_type=yttm.OutputType.ID),30,padding='post')
    encoded_neg_anchors = pad_sequences(tokenizer.encode(list(df_neg_anchors), output_type=yttm.OutputType.ID),30,padding='post')
    encoded_pos = pad_sequences(tokenizer.encode(list(df_pos), output_type=yttm.OutputType.ID),30,padding='post')
    return encoded_queries,encoded_pos,encoded_neg,encoded_pos_anchors,encoded_neg_anchors

def run_all(tokenizer=None,timestamp=None):
    if not tokenizer:
        tokenizer = load_tokenizer()
    buffer_timestamp = str(int(timestamp)-1000)
    dframe = load_query_list(timestamp=buffer_timestamp)
    new_entries = np.sum(dframe.timestamp>timestamp)
    i = 0
    while new_entries < 1:
        if i == 0:
            print('Awaiting additional matter...')
        time.sleep(2)
        dframe = load_query_list(timestamp=buffer_timestamp)
        new_entries = np.sum(dframe.timestamp>timestamp)
        i+=1
    most_recent_timestamp = dframe.timestamp.iloc[-1]
    token_queries,token_pos,token_neg,token_pos_anchor,token_neg_anchor = prep_data(dframe,timestamps=[buffer_timestamp,timestamp],tokenizer=tokenizer)
    dframe = dframe.loc[dframe.timestamp > timestamp].reset_index()
    return token_queries,token_pos,token_neg,token_pos_anchor,token_neg_anchor,dframe,most_recent_timestamp

def triplet_loss(true,pred):
    M = 1.
    loss = tf.reduce_mean(tf.maximum(pred[:,0]**2 - pred[:,1]**2 + M,0))
    return loss

def quadruplet_loss(true,pred):
    """Modified quadruplet loss with online semi-hard negative mining."""
    m1 = 1.
    m2 = .5
    mask1 = tf.cast((pred[:,3] < pred[:,0] + m1) & (pred[:,1] < pred[:,2] + m2),tf.float32)
    loss = tf.reduce_sum(tf.maximum(tf.multiply(pred[:,0]**2 - pred[:,1]**2 + m1,mask1),0)) +\
               tf.reduce_sum(tf.maximum(tf.multiply(pred[:,2]**2 - pred[:,3]**2 + m2,mask1),0))
    return loss

def custom_acc(true,pred):
    """Needs refactoring."""
    try:
        pred_compare = tf.where(pred[:,0] < pred[:,1],True,False) & tf.where(pred[:,2] < pred[:,1],True,False)
        total = tf.keras.backend.sum(tf.cast(pred_compare,tf.float32))
        return total/tf.cast(tf.size(pred_compare),tf.float32)
    except:
        return 0

def load_model():
    """Needs refactoring."""
    model = tf.keras.models.load_model('./models/siamese_metric_quadruplet_loss_v1.h5',custom_objects={'quadruplet_loss':quadruplet_loss,'custom_acc':custom_acc})
    return model

def online_learn(learner,ref,eps=0.1):
    """Developmental."""
    ref_labels = np.where(ref > 0.5, 1, 0)
    print('Models diverge: {0}'.format(np.sum(learner_labels==ref_labels)/ref_labels.size < 1))
    if np.random.rand() > eps:
        candidate_labels = np.where(ref > 0.5, 1, 0)
    else:
        print('Epsilon!')
        candidates = np.argmin(masks[test][i:i+1])
        candidate_labels = make_multilabel(' '.join([str(int(i)) for i in np.random.randint(0,2,size=(candidates))])).reshape(1,-1)
    return candidate_labels

if __name__=='__main__':
    print('Success.')
#    df = load_gravity(table='domainlist')
#    test_df = pd.DataFrame({'id':[1],'type':[1],'domain':'old.reddit.com','enabled':[1],'date_added':1600316117,
#                            'date_modified':1600316117,'comment':'just a test domain'})
#    update_gravity(pd.concat([df,test_df]))