import random
import pickle
import argparse
import numpy as np

class TicTacToe:
    def __init__(self):
        self.board = [' '] * 64
        self.p1 = None
        self.p2 = None
        self.done = False

    def resetBoard(self):
        self.board = [' '] * 64

    # Helper function
    def printBoard(self):
        print(np.reshape(self.board, (4, 4, 4)))

    def evaluateReward(self, isPlayer1, move):

        # Player tries to overwrite
        if self.board[move] != ' ':
            return -5.0, True

        if isPlayer1:
            mark = 'X'
        else:
            mark = '0'

        # Mark board
        self.board[move] = mark

        # Check each horizontal plane
        for j in range(4):

            offset = j * 16

            # Check rows in plane
            for i in range(4):
                if (self.board[offset + i * 4] == mark and self.board[offset + i * 4 + 1] == mark
                        and self.board[offset + i * 4 + 2] == mark and self.board[offset + i * 4 + 3] == mark):
                    return 1.0, True

            # Check cols in plane
            for i in range(4):
                if (self.board[offset + i + 0] == mark and self.board[offset+i + 4] == mark
                        and self.board[offset + i + 8] == mark and self.board[offset + i + 12] == mark):
                    return 1.0, True

            # Check diagonals in plane
            if (self.board[offset + 0] == mark and self.board[offset + 5] == mark
                    and self.board[offset + 10] == mark and self.board[offset + 15] == mark):
                return 1.0, True

            if (self.board[offset + 3] == mark and self.board[offset + 6] == mark
                    and self.board[offset + 9] == mark and self.board[offset + 12] == mark):
                return 1.0, True

        # Check vertical lines
        for i in range(16):
            if (self.board[i] == mark and self.board[i + 16] == mark
                    and self.board[i + 32] == mark and self.board[i + 48] == mark):
                return 1.0, True

        # Check first row in cube
        for i in range(4):
            if (self.board[i] == mark and self.board[i + 20] == mark
                    and self.board[i + 40] == mark and self.board[i + 60] == mark):
                return 1.0, True

        # Check first col in cube
        for i in range(0, 16, 4):
            if (self.board[i] == mark and self.board[i + 17] == mark
                    and self.board[i + 34] == mark and self.board[i + 51] == mark):
                return 1.0, True

        # Check last row in cube
        for i in range(12, 16):
            if (self.board[i] == mark and self.board[i + 12] == mark
                    and self.board[i + 24] == mark and self.board[i + 36] == mark):
                return 1.0, True

        # Check last col in cube
        for i in range(3, 19, 4):
            if (self.board[i] == mark and self.board[i + 15] == mark
                    and self.board[i + 30] == mark and self.board[i + 45] == mark):
                return 1.0, True

        # Check 4 diagonals in cube
        if (self.board[0] == mark and self.board[21] == mark
                and self.board[42] == mark and self.board[63] == mark):
            return 1.0, True

        if (self.board[3] == mark and self.board[22] == mark
                and self.board[41] == mark and self.board[60] == mark):
            return 1.0, True

        if (self.board[12] == mark and self.board[25] == mark
                and self.board[38] == mark and self.board[51] == mark):
            return 1.0, True

        if (self.board[15] == mark and self.board[26] == mark
                and self.board[37] == mark and self.board[48] == mark):
            return 1.0, True

        # Draw, if all filled slots are filled
        if not any(slot == ' ' for slot in self.board):
            return 0.5, True

        return 0.0, False

    def getPossibleMoves(self):
        return [i for i, mark in enumerate(self.board) if mark == ' ']

    # Begin training
    def startTraining(self, p1, p2, iterations):
        if isinstance(p1, player) and isinstance(p2, player):
            self.p1 = p1
            self.p2 = p2
            self.train(iterations)

    # Training function
    def train(self, iterations):
        for i in range(iterations):
            self.p1.startGame()
            self.p2.startGame()
            self.resetBoard()
            done = False
            isPlayer1 = random.choice([True, False])
            while not done:
                if isPlayer1:
                    move = self.p1.pickMove(self.board, self.getPossibleMoves())
                else:
                    move = self.p2.pickMove(self.board, self.getPossibleMoves())

                reward, done = self.evaluateReward(isPlayer1, move)

                if reward == 1.0:  # Won
                    if isPlayer1:
                        self.p1.updateQVal(reward, self.board, self.getPossibleMoves())
                        self.p2.updateQVal(-1 * reward, self.board, self.getPossibleMoves())
                    else:
                        self.p1.updateQVal(-1 * reward, self.board, self.getPossibleMoves())
                        self.p2.updateQVal(reward, self.board, self.getPossibleMoves())

                elif reward == 0.5:  # Draw
                    self.p1.updateQVal(reward, self.board, self.getPossibleMoves())
                    self.p2.updateQVal(reward, self.board, self.getPossibleMoves())

                elif reward == -5.0:  # Illegal move
                    if isPlayer1:
                        self.p1.updateQVal(reward, self.board, self.getPossibleMoves())
                    else:
                        self.p2.updateQVal(reward, self.board, self.getPossibleMoves())

                elif reward == 0.0:
                    if isPlayer1:
                        self.p1.updateQVal(reward, self.board, self.getPossibleMoves())
                    else:
                        self.p2.updateQVal(reward, self.board, self.getPossibleMoves())

                isPlayer1 = not isPlayer1  # Switch player

    def saveQtables(self, iterations):
        self.p1.saveQtable("./player1Qtable" + str(iterations) + ".txt")
        self.p2.saveQtable("./player2Qtable" + str(iterations) + ".txt")

    def saveQvals(self, iterations):
        self.p1.saveFinalQVals("./player1Qvals" + str(iterations) + ".txt")
        self.p2.saveFinalQVals("./player2Qvals" + str(iterations) + ".txt")

    def printQTables(self, iterations):
        with open("./player1Qtable" + str(iterations) + ".txt", 'rb') as file1:
            print(pickle.load(file1))
        with open("./player2Qtable" + str(iterations) + ".txt", 'rb') as file2:
            print(pickle.load(file2))

    def printQVals(self, iterations):
        with open("./player1Qvals" + str(iterations) + ".txt", 'rb') as file1:
            print(pickle.load(file1))
        with open("./player2Qvals" + str(iterations) + ".txt", 'rb') as file2:
            print(pickle.load(file2))

class player:
    def __init__(self):
        self.epsilon = 0.25
        self.alpha = 0.35
        self.gamma = 0.85
        self.q_table = {}  # Q table
        self.prev_state = None
        self.prev_state_action = None
        self.prev_q = 0.0

    def startGame(self):
        self.prev_state = None
        self.prev_state_action = None
        self.prev_q = 0.0

    # Returns move using a combination of exploration (random) and exploitation (greedy)
    def pickMove(self, state, possible_moves):
        self.prev_state = tuple(state)
        if random.random() < self.epsilon:
            next_move = random.choice(possible_moves)
            self.prev_state_action = (self.prev_state, next_move)
            self.prev_q = self.getQVal(self.prev_state, next_move)
            return next_move
        else:
            q_list = []
            for move in possible_moves:
                q_list.append(self.getQVal(self.prev_state, move))
            max_q = max(q_list)

            # Chooses among them randomly if there's more than 1 best option
            if q_list.count(max_q) > 1:
                best_options = [i for i in range(len(possible_moves)) if q_list[i] == max_q]
                i = random.choice(best_options)
            else:
                i = q_list.index(max_q)

            self.prev_state_action = (self.prev_state, possible_moves[i])
            self.prev_q = self.getQVal(self.prev_state, possible_moves[i])
            return possible_moves[i]

    def getQVal(self, state, action):  # get Q states
        if self.q_table.get((state, action)) is None:
            self.q_table[(state, action)] = 1.0
        return self.q_table.get((state, action))

    def updateQVal(self, reward, state, possible_moves):  # update Q states using Qlearning
        q_list = []
        for moves in possible_moves:
            q_list.append(self.getQVal(tuple(state), moves))

        if q_list:
            max_q_next = max(q_list)
        else:
            max_q_next = 0.0

        max_future_q = (reward + self.gamma * max_q_next) - self.prev_q
        self.q_table[self.prev_state_action] = self.prev_q + self.alpha * (max_future_q)

    def saveQtable(self, filename):
        Qtable = self.getFinalQtable()
        with open(filename, 'wb') as file:
            pickle.dump(Qtable, file)

    # For same states, compare q values and pick the largest one.
    def getFinalQtable(self):
        state_action_value = self.q_table
        temp_Qtable = {}
        for state_action, value in state_action_value.items():
            curr_state = state_action[0]
            try:
                temp_value = temp_Qtable[curr_state]
                if temp_value < value:
                    temp_Qtable[curr_state] = value
            except:
                temp_Qtable[curr_state] = value
        return temp_Qtable

    def saveFinalQVals(self, filename):
        Qvals = self.getFinalQVals()
        with open(filename, 'wb') as file:
            pickle.dump(Qvals, file)

    def getFinalQVals(self):
        state_action_value = self.q_table
        temp_Qtable = {}
        for state_action, value in state_action_value.items():
            curr_state = state_action[0]
            try:
                temp_value = temp_Qtable[curr_state]
                if temp_value < value:
                    temp_Qtable[curr_state] = value
            except:
                temp_Qtable[curr_state] = value
        return list(temp_Qtable.values())

if __name__ == '__main__':
    # CLI format: python 3D_Tic_Tac_Toe.py -n1 100 -n2 500 -n3 2000
    parser = argparse.ArgumentParser(description='num iterations')
    parser.add_argument('-n1', type=int, required=False, default=100, help='smallest num iterations')
    parser.add_argument('-n2', type=int, required=False, default=500, help='medium num iterations')
    parser.add_argument('-n3', type=int, required=False, default=2000, help='largest num iterations')
    args = parser.parse_args()

    game = TicTacToe()  # game instance, True means training
    player1 = player()  # player1 learning agent
    player2 = player()  # player2 learning agent

    print(">>>starting training 1...")
    game.startTraining(player1, player2, args.n1)  # start training
    game.saveQtables(args.n1)
    game.printQTables(args.n1)

    game.saveQvals(args.n1)
    game.printQVals(args.n1)

    print(">>>starting training 2...")
    game.startTraining(player1, player2, args.n2)  # start training
    game.saveQtables(args.n2)
    game.printQTables(args.n2)

    game.saveQvals(args.n2)
    game.printQVals(args.n2)

    print(">>>starting training 3...")
    game.startTraining(player1, player2, args.n3)  # start training
    game.saveQtables(args.n3)
    game.printQTables(args.n3)

    game.saveQvals(args.n3)
    game.printQVals(args.n3)

    # game.printQTables(args.n3)


import pyrealsense2 as rs
import numpy as np

class Video(object):
    def __init__(self):
        self.points = rs.points()
        self.pipeline = rs.pipeline()
        self.dirname = ""
        self.config = rs.config()

    def start(self):
        print("Starting the video" + self.dirname)
        if self.dirname == "":
            print("Invalid Filename!")
            return
        self.config.enable_device_from_file(self.dirname, repeat_playback=False)
        profile = self.pipeline.start(self.config)
        profile.get_device().as_playback().set_real_time(False)

    def stop(self):
        self.pipeline.stop()
        print("Stopped the video")

    def get_frame(self):
        frames = self.pipeline.wait_for_frames()
        color_frame = frames.get_color_frame()
        nir_frame = frames.get_infrared_frame()
        color_out = np.asanyarray(color_frame.get_data())
        nir_out = np.asanyarray(nir_frame.get_data(), dtype='uint8')
        return color_out, nir_out


import socket
import sys
import numbers

HOST = socket.gethostname()
PORT = int(sys.argv[1])
num_of_players=int(sys.argv[3])
socket_list=[]
s=socket.socket()
s.bind((HOST, PORT))
s.listen(0)

error = "TEXT ERROR bad input. try again"
byteGO = bytes ("GO", 'utf-8')
byteError = bytes (error, 'utf-8')
newSum = 0
win = "TEXT You win!"
byteWin = bytes (win, 'utf-8')
print ("Waiting for client connections")

for i in range(num_of_players):
	connection, address=s.accept()
	msg = "TEXT Welcome to the game"
	bytemsg =  bytes(msg,'utf-8')
	connection.send(bytemsg)
	socket_list.append(connection)

run = True
while run == True:
	for i in range(num_of_players):
		turn = "TEXT sum is %d enter number" %newSum
		byteTurn = bytes (turn, 'utf-8')
		num_of_errors = 0
		socket_list[i].send(byteTurn)
		socket_list[i].send(byteGO)
		socket_list[i].settimeout(10)
		data = socket_list[i].recv(1024)
		decodeData = data.decode('utf-8')
		if decodeData[:4]!= "MOVE":
			socket_list[i].close()
			socket_list.pop(i)
		good = numbers.checkValid(decodeData[4:])
		if good == "close socket":
			socket_list.pop(i)
			decodeData = "quit"
			num_of_players -= 1
			if num_of_players == 1:
				socket_list[0].send(byteWin)
				check == True
		while good == False:
			num_of_errors += 1
			if num_of_errors<5:
				socket_list[i].send(byteError)
				socket_list[i].send(byteGO)
				newdata = socket_list[i].recv(1024)
				decodeData = newdata.decode('utf-8')
				good = numbers.checkValid(decodeData[4:])
			else:
				socket_list[i].close()
				socket_list.pop(i)
				good = True
				decodeData = "5 errors"
				num_of_players -= 1
				if num_of_players == 1:
					socket_list[0].send(byteWin)
					check == True
		if decodeData!="5 errors" and decodeData != "quit":
			newSum = numbers.scoreboard(int(decodeData[4:]), newSum)
			check = numbers.isFinished(newSum)
		if check==True:
			socket_list[i].send(byteWin)
			s.close()
			run = False
			break


import numpy as np
import matplotlib.pyplot as plt
from math import log
from math import pow
from matplotlib.ticker import FuncFormatter
import matplotlib

def to_percent(y, position):
    # Ignore the passed in position. This has the effect of scaling the default
    # tick locations.
    s = str(100 * y)

    # The percent symbol needs escaping in latex
    if matplotlib.rcParams['text.usetex'] == True:
        return s + r'$\%$'
    else:
        return s + '%'

def entropy(kill1, kill2, die1, die2):
	e = []
	for i in range(len(kill1)):
		e += [eval_entropy(kill1[i], kill2[i], die1[i], die2[i])]
	return e

def eval_entropy(kill_1, kill_2, die_1, die_2):
	kill1 = kill_1
	kill2 = kill_2
	total = kill1 + kill2

	e1 = kill1/total*log(kill1/total, 2) if kill1 != 0 else 0
	e2 = kill2/total*log(kill2/total,2) if kill2 != 0 else 0

	e = -(e1 + e2)

	#e += total/40
	#e += pow(0.9, suicides)

	return e

def main():

	statistics_file = open("statistics.txt", "r")

	content = statistics_file.readlines()

	i = 0

	statistics = {}
	data = [[] for _ in range(8)]

	for string in content:
		if "[" in string:
			split_spaces = string.split(" ")
			for splitted in split_spaces :
				splitted = splitted.replace("[", "")
				splitted = splitted.replace("]", "")
				splitted = splitted.replace(",", "")
				splitted = splitted.replace("\n", "")
				try:
					val = int(splitted)
				except :
					val = float(splitted)
				data[i] += [val]

			i += 1
			if i == 8 :
				i = 0

	statistics.update({0 : data[:4]})
	statistics.update({1 : data[4:]})

	plt.figure(figsize=(16, 9))

	#plt.subplot(221)
	#plt.title("time kill")
	#plt.boxplot([val[0] for key, val in statistics.items()], labels=[str(i + 1) + "° weapon" for i in range(2)])
	plt.subplot(221)
	plt.title("distance")
	plt.ylabel("Unreal Unit")
	plt.boxplot([val[1] for key, val in statistics.items()], labels=[str(i + 1) + "° weapon" for i in range(2)])
	plt.subplot(222)
	plt.title("kill streak")
	plt.ylabel("Kill")
	plt.boxplot([val[2] for key, val in statistics.items()], labels=[str(i + 1) + "° weapon" for i in range(2)])
	plt.subplot(223)
	plt.title("precision")
	formatter = FuncFormatter(to_percent)
	plt.boxplot([val[3] for key, val in statistics.items()], labels=[str(i + 1) + "° weapon" for i in range(2)])
	plt.gca().yaxis.set_major_formatter(formatter)

	plt.savefig("statistics.png", bbox_inches='tight', dpi = 200)
	plt.close()

main()


from misc import TreeNode

class Solution:
    def max_ancestor_diff(self, root: TreeNode) -> int:
        self.max_diff = 0

        def dfs(node, biggest, smallest):
            if not node:
                return

            if node.val > biggest:
                biggest = node.val
            if node.val < smallest:
                smallest = node.val

            self.max_diff = max(self.max_diff, abs(biggest - smallest))

            dfs(node.left, biggest, smallest)
            dfs(node.right, biggest, smallest)

        dfs(root, root.val, root.val)
        return self.max_diff


import numpy as np
import tensorflow as tf
from tensorflow.contrib.slim import fully_connected as fc
import matplotlib
import math
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.ioff()
import logging
from time import strftime, gmtime
import random

logger = logging.getLogger('GMMM_VAE')

# from get_mnist import get_number_mnist, get_small_test_batch
#
# train_values, train_labels, test_values, test_labels = get_small_test_batch(10)
# input_dim = 784

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
num_sample = mnist.train.num_examples
input_dim = mnist.train.images[0].shape[0]
w = h = 28

class VariantionalAutoencoder(object):

    def __init__(self, learning_rate=1e-3, batch_size=100, latent_size=10, gmm_n_feat=10, pretrain=False):

        self.batch_size = batch_size
        self.latent_size = latent_size
        self.gmm_n_feat = gmm_n_feat
        self.gmm_pi = tf.Variable(tf.ones([self.gmm_n_feat]) / gmm_n_feat, trainable=not pretrain, dtype=tf.float32, constraint=tf.keras.constraints.min_max_norm(min_value=1, max_value=1, rate=1))
        print(self.gmm_pi)
        self.layer_sizes = [500, 500, 2000]

        mu_numpy = np.reshape((np.random.randn(latent_size * gmm_n_feat) + 2) * [[-1,1][random.randrange(2)] for _ in range(latent_size * gmm_n_feat)], [self.latent_size, self.gmm_n_feat])

        self.gmm_mu = tf.Variable(mu_numpy, trainable=not pretrain, dtype=tf.float32)
        print(self.gmm_mu)

        rand_sig = np.abs(np.random.randn(self.latent_size, self.gmm_n_feat)) * 0.25 + 1

        self.gmm_sigma = tf.Variable(rand_sig, trainable=not pretrain, dtype=tf.float32, constraint=tf.keras.constraints.non_neg())
        self.learning_rate = learning_rate
        self.saver = tf.train.Saver()

        print('start build')
        self.build()

        self.sess = tf.InteractiveSession()
        self.sess.run(tf.global_variables_initializer())

        amount = len(tf.trainable_variables())

        print("amount of trainable vars: " + str(amount))

    # Build the network and the loss functions
    def build(self):
        self.debug_dict = {}
        self.debug_dict['gmm_pi'] = self.gmm_pi
        self.debug_dict['gmm_mu'] = self.gmm_mu
        self.debug_dict['gmm_sigma'] = self.gmm_sigma

        self.x = tf.placeholder(name='x', dtype=tf.float32, shape=[self.batch_size, input_dim])

        # Encode
        # x -> z_mean, z_sigma -> z
        f1 = fc(self.x, self.layer_sizes[0], scope='enc_fc1', activation_fn=tf.nn.relu)
        f2 = fc(f1, self.layer_sizes[1], scope='enc_fc2', activation_fn=tf.nn.relu)
        f3 = fc(f2, self.layer_sizes[2], scope='enc_fc3', activation_fn=tf.nn.relu)

        self.z_mu = fc(f3, self.latent_size, scope='enc_fc4_mu', activation_fn=None)
        self.z_log_sigma_sq = fc(f3, self.latent_size, scope='enc_fc4_sigma', activation_fn=None)
        eps = tf.random_normal(shape=tf.shape(self.z_log_sigma_sq),
                               mean=0, stddev=1, dtype=tf.float32)

        self.z = self.z_mu + tf.sqrt(tf.exp(self.z_log_sigma_sq)) * eps

        # Decode
        # z -> x_hat
        g1 = fc(self.z, self.layer_sizes[2], scope='dec_fc1', activation_fn=tf.nn.relu)
        g2 = fc(g1, self.layer_sizes[1], scope='dec_fc2', activation_fn=tf.nn.relu)
        g3 = fc(g2, self.layer_sizes[0], scope='dec_fc3', activation_fn=tf.nn.relu)
        self.x_hat = fc(g3, input_dim, scope='dec_fc4', activation_fn=tf.sigmoid)

        # Loss
        # Reconstruction loss, cross entropy
        recon_loss = 0.9 * tf.reduce_mean(tf.reduce_sum(tf.square(self.x - self.x_hat), -1))

        # change to shape (batch_dim, latent_dim, n_feat)
        gmm_mu_3 = tf.ones([self.batch_size, self.latent_size, self.gmm_n_feat]) * self.gmm_mu
        gmm_pi_3 = tf.ones([self.batch_size, self.latent_size, self.gmm_n_feat]) * self.gmm_pi
        gmm_pi_2 = tf.ones([self.batch_size, self.gmm_n_feat]) * self.gmm_pi
        gmm_sigma_3 = tf.ones([self.batch_size, self.latent_size, self.gmm_n_feat]) * self.gmm_sigma

        # Now make sure the network output are also that shape
        z_3 = tf.tile(tf.expand_dims(self.z, -1), [1, 1, self.gmm_n_feat])
        mu_3 = tf.tile(tf.expand_dims(self.z_mu, -1), [1, 1, self.gmm_n_feat])
        var_3 = tf.tile(tf.expand_dims(self.z_log_sigma_sq, -1), [1, 1, self.gmm_n_feat])

        # shape = (batch, n_feat)
        p_c_z = tf.exp(tf.reduce_sum(
            tf.log(gmm_pi_3) - 0.5 * tf.log(2 * math.pi * gmm_sigma_3) - tf.square(z_3 - gmm_mu_3) / (2 * gmm_sigma_3),
            1)) + 1e-10
        # same shape because broadcasting
        gamma = p_c_z / tf.reduce_sum(p_c_z, -1, keepdims=True)

        gamma_3 = tf.tile(tf.expand_dims(gamma, 1), [1, self.latent_size, 1])

        # these should all be shape=(batch_dim)
        loss1 = tf.reduce_sum(0.5 * gamma_3 * (self.latent_size * tf.log(math.pi * 2) + tf.log(gmm_sigma_3) + tf.exp(
            var_3) / gmm_sigma_3 + tf.square(mu_3 - gmm_mu_3) / gmm_sigma_3), [1, 2])
        loss2 = -0.5 * tf.reduce_sum(self.z_log_sigma_sq + 1, -1)
        loss3 = -1 * tf.reduce_sum(tf.log(gmm_pi_2) * gamma, -1)
        loss4 = tf.reduce_sum(tf.log(gamma) * gamma, -1)

        # create the gmm loss with shape = (batch) and then the gmm_loss as just a value (reduce_mean)

        gmm_loss = tf.reduce_mean(loss1 + loss2 + loss3 + loss4)

        self.total_loss = recon_loss + gmm_loss
        self.debug_dict['recon_loss'] = recon_loss
        self.debug_dict['gmm_loss'] = gmm_loss
        self.train_op = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.total_loss)

    def save(self, name):
        self.saver.save(self.sess, './' + name + ".ckpt")

    # Execute the forward and the backward pass
    def run_single_step(self, single_batch):
        _, debug_dict = self.sess.run(
            [self.train_op, self.debug_dict],
            feed_dict={self.x: single_batch}
        )
        return debug_dict

    def update_learning_rate(self, alpha, under):
        new_value = self.learning_rate * alpha
        if new_value > under:
            self.learning_rate = new_value
        else:
            self.learning_rate = under

    # x -> x_hat
    def reconstructor(self, x):
        x_hat = self.sess.run(self.x_hat, feed_dict={self.x: x})
        return x_hat

    # z -> x
    def generator(self, z):
        x_hat = self.sess.run(self.x_hat, feed_dict={self.z: z})
        return x_hat

    # x -> z
    def transformer(self, x):
        z = self.sess.run(self.z, feed_dict={self.x: x})
        return z

    def restore(self, restore_place):
        self.saver.restore(self.sess, restore_place)

def trainer(learning_rate=1e-4, batch_size=100, num_epoch=75, latent_size=10, gmm_n_feat=5, model_info_string="", pretrain=False, model=None, restore_model=False, momentum=True):
    if model is None:
        train_model = VariantionalAutoencoder(learning_rate=learning_rate, batch_size=batch_size, latent_size=latent_size, gmm_n_feat=gmm_n_feat, pretrain=pretrain)
    else:
        train_model = model

    if restore_model:
        train_model.restore('./pretrain/pretrain_mnist.ckpt')

    time_string = strftime("%Y_%m_%d_%H_%M_%S", gmtime())

    for epoch in range(num_epoch):
        for iter in range(num_sample // batch_size):
            # Obtina a batch
            batch = mnist.train.next_batch(batch_size)
            # Execute the forward and the backward pass and report computed losses
            debug_dict = train_model.run_single_step(batch[0])

        print('===============================================================')
        print("==============================={}===============================".format(epoch))
        print('===============================================================')

        for k, v in debug_dict.items():
            print(k)
            print(v)
        print('pretraining: ' + str(pretrain))
        print("===============================End of {}===============================".format(epoch))

        if epoch % 5 == 0:
            # model.save(str(epoch))

            batches = np.empty((0, 784))
            numbers = np.empty((0, 10))
            z_s = np.empty((0, 2))

            # Test the trained model: transformation
            for i in range(30):
                batch = mnist.test.next_batch(batch_size)
                z = train_model.transformer(batch[0])
                z_s = np.concatenate((z_s, z))
                batches = np.concatenate((batches, batch[0]))
                numbers = np.concatenate((numbers, batch[1]))

            fig = plt.figure()
            plt.scatter(z_s[:, 0], z_s[:, 1], c=np.argmax(numbers, 1))
            plt.colorbar()
            plt.grid()
            if pretrain:
                plt.savefig('results/pretrain_' + model_info_string + '_' + time_string + 'I_' + str(epoch) + '_transformed.png')
            else:
                plt.savefig('results/' + model_info_string + '_' + time_string + 'I_' + str(epoch) + '_transformed.png')
            plt.close(fig)

        if epoch % 10 and epoch > 0 and momentum:
            train_model.update_learning_rate(0.95, 0.00002)

    print('Done!')
    if pretrain:
        train_model.save("pretrain/pretrain_mnist")
    return train_model

batch_size = 100

model_info_string = ""
# model_2d = trainer(learning_rate=2e-3,  batch_size=batch_size, num_epoch=20, latent_size=2, gmm_n_feat=5, model_info_string=model_info_string, pretrain=True, momentum=False)
model_2d = trainer(learning_rate=2e-3,  batch_size=batch_size, num_epoch=80, latent_size=2, gmm_n_feat=5, model_info_string=model_info_string, pretrain=False, restore_model=True, momentum=True)


import random
import pygame

from settings import Settings
from cell import Cell

# settings = Settings()

def life_cycle(cell, cell_list, settings):
    """Main circle of events in cells life"""

    location = nearby_objects(cell, cell_list, settings)
    action = genome_action(cell.genome)

    if action in ('u', 'd', 'r', 'l'):
        square_moving(cell, cell_list, location, action, settings)

    if 'b' in action and cell.energy > settings.start_energy:
        birth(cell, cell_list, action, settings)
        # cell.energy -= int(action[-2:]) * 5
        cell.energy -= cell.energy * 0.5

    if action == 'c':
        collect(cell, settings)

    if "e" in action:
        eat(cell, location, cell_list, action, settings)
        cell.energy -= (cell.genome.count('er') + cell.genome.count('el') + cell.genome.count('ed') + cell.genome.count('eu')) * 3

    energy_reduce(cell, location)

    cell.life_time -= 1
    killer(cell, cell_list, location)

def square_moving(cell, cell_list, location, action, settings):
    if action == 'u' and location[0][1] == '0':
        # print(cell.y, cell.x, action, location[0][1])
        if cell.y > 0:
            cell_list[cell.y - 1][cell.x] = cell
            cell_list[cell.y][cell.x] = '0'
            cell.y -= 1
        elif cell.y == 0:
            cell_list[cell.y][cell.x] = '0'
            cell_list[settings.y_size][cell.x] = cell
            cell.y = settings.y_size

    if action == 'd' and location[2][1] == '0':
        if cell.y < settings.y_size:
            cell_list[cell.y + 1][cell.x] = cell
            cell_list[cell.y][cell.x] = '0'
            cell.y += 1
        elif cell.y == settings.y_size:
            cell_list[0][cell.x] = cell
            cell_list[cell.y][cell.x] = '0'
            cell.y = 0

    if action == 'l' and location[1][0] == '0':
        if cell.x > 0:
            cell_list[cell.y][cell.x - 1] = cell
            cell_list[cell.y][cell.x] = '0'
            cell.x -= 1
        elif cell.x == 0:
            cell_list[cell.y][cell.x] = '0'
            cell_list[cell.y][cell.settings.x_size] = cell
            cell.x = settings.x_size

    if action == 'r' and location[1][1] == '0':
        if cell.x < settings.x_size:
            cell_list[cell.y][cell.x + 1] = cell
            cell_list[cell.y][cell.x] = '0'
            cell.x += 1
        elif cell.x == settings.x_size:
            cell_list[cell.y][0] = cell
            cell_list[cell.y][cell.x] = '0'
            cell.x = 0

    cell.object = pygame.Rect((cell.x * cell.width, cell.y * cell.height, cell.width, cell.height))

def collect(cell, settings):
    if settings.y_size - settings.I_y_start_more_energy > cell.y > settings.I_y_start_more_energy and \
            settings.x_size - settings.I_x_start_more_energy > cell.x > settings.I_x_start_more_energy:
        if settings.y_size - settings.I_y_start_anymore_energy > cell.y > settings.I_y_start_anymore_energy and \
                settings.x_size - settings.I_x_start_anymore_energy > cell.x > settings.I_x_start_anymore_energy:
            cell.energy += 0.25 * settings.energy_coef

        cell.energy += 0.75 * settings.energy_coef
    else:
        cell.energy += 0.5 * settings.energy_coef

def nearby_objects(cell, cell_list, settings):
    top = ['-', '0', '-']
    middle = ['0', '0']
    bottom = ['-', '0', '-']

    # top[0] = try_to_see(cell_list, cell.y - 1, cell.x - 1)
    top[1] = try_to_see(cell_list, cell.y - 1, cell.x, settings)
    # top[2] = try_to_see(cell_list, cell.y - 1, cell.x + 1)
    middle[0] = try_to_see(cell_list, cell.y, cell.x - 1, settings)
    middle[1] = try_to_see(cell_list, cell.y, cell.x + 1, settings)
    # bottom[0] = try_to_see(cell_list, cell.y + 1, cell.x - 1)
    bottom[1] = try_to_see(cell_list, cell.y + 1, cell.x, settings)
    # bottom[2] = try_to_see(cell_list, cell.y + 1, cell.x + 1)
    return [top, middle, bottom]

def try_to_see(cell_list, original_y, original_x, settings):
    try:
        a = cell_list[original_y][original_x]
        return a
    except IndexError:
        y = original_y
        x = original_x
        if y > settings.y_size:
            y = 0
        if y < 0:
            y = settings.y_size
        if x > settings.x_size:
            x = 0
        if x < 0:
            x = settings.x_size

        return cell_list[y][x]

def birth(cell, cell_list, action, settings):
    '''Надо помнить, что мутирует ячейка только вврех, ввиду того что при мутации координата указана как у - 1'''

    if settings.y_size > cell.y > 0:
        new_genome = cell.genome.copy()
        random.shuffle(new_genome)
        y = cell.y
        cell_n = Cell(y - 1, cell.x, cell.color, new_genome, cell.kind, cell.energy * 0.5)

        if random.randint(1, 20) == 20:
            genome, kind = mutation(cell.genome, cell.kind)
            cell_n = Cell(y - 1, cell.x, color(genome, settings), genome, kind, cell.energy * 0.5)  # random.choice(settings.colors)

            try:
                if cell_list[y - 1][cell.x] == '0':
                    cell_list[y - 1][cell.x] = cell_n
            except IndexError:
                if cell_list[settings.y_size][cell.x] == '0':
                    cell_list[settings.y_size][cell.x] = cell_n
        else:
            try:
                if cell_list[y - 1][cell.x] == '0':
                    cell_list[y - 1][cell.x] = cell_n
            except IndexError:
                if cell_list[settings.y_size][cell.x] == '0':
                    cell_list[settings.y_size][cell.x] = cell_n

def energy_reduce(cell, location):
    # energy_reduce = 0  # 0 default
    # for raw in location:
    #     energy_reduce += raw.count('-') + raw.count('0')
    # cell.energy -= 1 + (8 - energy_reduce) + round(cell.energy * 0.01)
    cell.energy -= 1 + round(cell.energy * 0.01)

def killer(cell, cell_list, location):
    if cell.energy <= 0 or cell.life_time <= 0:
        # or ("b10" not in cell.genome and "b20" not in cell.genome and "b30" not in cell.genome):
        cell_list[cell.y][cell.x] = '0'

def genome_action(genome):
    action = genome.pop(0)
    genome.append(action)
    return action

def mutation(genome, kind):
    new_gen = random.choice(
        ('b10', 'b20', 'b30', 'b40', 'b50', 'u', 'd', 'l', 'r', 'c', 'el', 'er', 'el', 'ed'))
    new_genome = genome.copy()

    new_genome.pop(random.randint(0, len(new_genome) - 1))
    new_genome.append(new_gen)

    '''Добавить добавление рождаемости при его отсутсвтии'''
    kind_new = kind[:4] + chr(random.randint(65, 90)) + str(random.randint(0, 100))
    return new_genome, kind_new

def eat(cell, location, cell_list, action, settings):
    if action[-1] == 'l' and location[1][0] != '0':
        if location[1][0].kind != cell.kind:
            try:
                cell.energy += cell_list[cell.y][cell.x - 1].energy * settings.eat_coef
                cell_list[cell.y][cell.x - 1] = '0'

            except IndexError:
                pass

    if action[-1] == 'r' and location[1][1] != '0':
        if location[1][1].kind != cell.kind:
            try:
                cell.energy += cell_list[cell.y][cell.x + 1].energy * settings.eat_coef
                cell_list[cell.y][cell.x + 1] = '0'

            except IndexError:
                pass

    if action[-1] == 'u' and location[0][1] != '0':
        if location[0][1].kind != cell.kind:
            try:
                cell.energy += cell_list[cell.y - 1][cell.x].energy * settings.eat_coef
                cell_list[cell.y - 1][cell.x] = '0'

            except IndexError:
                pass

    if action[-1] == 'd' and location[2][1] != '0':
        if location[2][1].kind != cell.kind:
            try:
                cell.energy += cell_list[cell.y + 1][cell.x].energy * settings.eat_coef
                cell_list[cell.y + 1][cell.x] = '0'

            except IndexError:
                pass

def color(genome, settings):
    colozing_count = genome.count('c') + genome.count('er') + genome.count('el') + genome.count('ed') +\
                     genome.count('eu') + genome.count('b10') + genome.count('b20') + genome.count('b30') + \
                     genome.count('b40') + genome.count('b50')
    if colozing_count == 0:
        colozing_count = 1
    collect = (255 // colozing_count) * genome.count('c')
    eat = (255 // colozing_count) * (genome.count('er') + genome.count('el') + genome.count('ed')
                                          + genome.count('eu'))
    birth = (255 // colozing_count) * (genome.count('b10') + genome.count('b20') + genome.count('b30') +
                                       genome.count('b40') + genome.count('b50'))
    if eat > 255:
        eat = 255
    if collect > 255:
        collect = 255
    if birth > 255:
        birth = 255

    return [0 + eat, 0 + collect, 0 + birth]


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        a = 0
        b = 0
        i = 0

        while l1 != None:
            a =  a + l1.val * pow(10,i)
            i = i + 1
            l1 = l1.next
        print ("first number" + str(a))

        i= 0;
        while l2 != None:
            b =  b + l2.val * pow(10,i)
            i = i + 1
            l2 = l2.next

        print ("Second number" + str(b))
        total = a + b

        stringTotal = str(total)

        headOfList = ListNode(int(stringTotal[-1:]))
        listIterator = headOfList
        for c in range(len(stringTotal)-2, -1, -1):
                              newElem = ListNode(int(stringTotal[c]))
                              listIterator.next = newElem
                              listIterator = newElem
        return headOfList


import pytest
from h_matchers import Any

from checkmatelib.url import Domain
from checkmatelib.url.domain.enums import SuffixType

class TestDomain:
    # These methods are quite often really just combinations of other things
    # so we'll be giving some a quite light touch

    @pytest.mark.parametrize(
        "domain,is_public",
        (
            ("www.example.com", True),
            ("  www.whitespace.com", True),
            ("216.58.212.206", True),
            ("192.168.34.11", False),
            ("bad.-hyphen.com", False),
            ("plausable.but-wrong.dato", False),
            ("random_hostname", False),
            ("<html>", False),
        ),
    )
    def test_is_public(self, domain, is_public):
        assert Domain(domain).is_public == is_public

    @pytest.mark.parametrize(
        "domain,is_fqdn",
        (
            ("com", False),
            ("co.uk", False),
            ("more.com", True),
            ("www.example.com", True),
            ("  www.whitespace.com", True),
            ("216.58.212.206", False),  # IPs are not fully qualified
            ("bad.-hyphen.com", False),
            ("plausable.but-wrong.dato", False),
            ("random_hostname", False),
            ("<html>", False),
        ),
    )
    def test_is_fully_qualified(self, domain, is_fqdn):
        assert Domain(domain).is_fully_qualified == is_fqdn

    @pytest.mark.parametrize(
        "domain,tld",
        (
            ("www.example.com", "com"),
            ("com", "com"),
            ("www.example.not_a_tld", None),
            ("10.0.0.1", None),
        ),
    )
    def test_tld(self, domain, tld):
        assert Domain(domain).tld == tld

    @pytest.mark.parametrize(
        "domain,public_suffix",
        (
            ("com", "com"),
            ("co.uk", "co.uk"),
            ("www.example.com", "com"),
            ("www.example.co.uk", "co.uk"),
            ("page.github.io", "github.io"),
            ("nonsense", None),
            ("10.0.0.1", None),
        ),
    )
    def test_public_suffix(self, domain, public_suffix):
        assert Domain(domain).public_suffix == public_suffix

    @pytest.mark.parametrize(
        "domain,icann_suffix",
        (
            ("com", "com"),
            ("co.uk", "co.uk"),
            ("www.example.com", "com"),
            ("www.example.co.uk", "co.uk"),
            ("page.github.io", "io"),
            ("nonsense", None),
            ("10.0.0.1", None),
        ),
    )
    def test_icann_suffix(self, domain, icann_suffix):
        assert Domain(domain).icann_suffix == icann_suffix

    @pytest.mark.parametrize(
        "domain,suffix_type",
        (
            ("com", SuffixType.ICANN),
            ("www.example.com", SuffixType.ICANN),
            ("www.example.co.uk", SuffixType.ICANN),
            ("page.github.io", SuffixType.PRIVATE),
            ("github.io", SuffixType.PRIVATE),
            ("nonsense", None),
            ("10.0.0.1", None),
        ),
    )
    def test_suffix_type(self, domain, suffix_type):
        assert Domain(domain).suffix_type == suffix_type

    @pytest.mark.parametrize(
        "domain,icann_only,sub_domains,root_domain",
        (
            ("www.example.com", False, ["www"], "example.com"),
            ("a.page.github.io", False, ["a"], "page.github.io"),
            ("github.io", False, [], "github.io"),
            ("a.page.github.io", True, ["a", "page"], "github.io"),
            # Lets say IPs are their own root domain
            ("10.0.0.1", False, [], "10.0.0.1"),
            # Is there any sensible way to deal with things without public
            # suffixes? We don't know where to start or stop here
            ("my_home_pc", False, [], "my_home_pc"),
            ("a.b.c.d.e.my_home_pc.local", False, [], "a.b.c.d.e.my_home_pc.local"),
        ),
    )
    def test_split_domain(self, domain, icann_only, sub_domains, root_domain):
        values = Domain(domain).split_domain(icann_only)

        assert values == (sub_domains, root_domain)

    @pytest.mark.parametrize(
        "domain,root_domain",
        (
            ("www.example.com", "example.com"),
            ("www2.example.com", "example.com"),
            ("a.b.example.com", "example.com"),
            ("a.b.c.page.github.io", "page.github.io"),
            # Lets say IPs are their own root domain
            ("10.0.0.1", "10.0.0.1"),
            # Is there any sensible way to deal with things without public
            # suffixes? We don't know where to start or stop here
            ("my_home_pc", "my_home_pc"),
            ("a.b.c.d.e.my_home_pc.local", "a.b.c.d.e.my_home_pc.local"),
        ),
    )
    def test_root_domain(self, domain, root_domain):
        assert Domain(domain).root_domain == root_domain

    def test_as_dict(self):
        # Not really going to go to town on this just yet, the exact contents
        # aren't used by anyone. It's just a good way to dump them right now.
        assert Domain("www.example.com").as_dict() == Any.dict()


from flask import Blueprint, jsonify, request, session, redirect, url_for, send_file

from werkzeug.utils import secure_filename
from app import db
import os

api = Blueprint('api', __name__, url_prefix="/api")

UPLOAD_FOLDER = os.path.abspath("app/static/attachments")

@api.route("/execute", methods=["POST"])
def execute():
    try:
        code = request.json.get("code")
        result = db.engine.execute(code).all()
        if len(result) == 0:
            return jsonify({
                "status": "no_result"
            }), 200
        else:
            keys, values = result[0].keys()._keys, []
            for result_obj in result:
                temp_values = []
                for result_value in result_obj:
                    temp_values.append(result_value)
                values.append(temp_values)
            return jsonify({
                "status": "success",
                "keys": keys,
                "values": values
            }), 200
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 400

@api.route("/get-customer")
def get_customer():
    try:
        customer_id = request.args.get("id")
        query = f"select * from customers where id={customer_id}"
        customer = db.engine.execute(query).first()
        return jsonify({
            "status": "success",
            "data": {
                "first_name": customer["first_name"],
                "last_name": customer["last_name"],
                "company_name": customer["company_name"],
                "address": customer["address"],
                "city": customer["city"],
                "county": customer["county"],
                "state": customer["state"],
                "zip_code": customer["zip_code"],
                "phone_1": customer["phone_1"],
                "phone_2": customer["phone_2"],
                "email": customer["email"],
                "web": customer["web"]
            }
        }), 200
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 400


import os
import random
from libultimate import Console, Controller, EnvAction, UltimateEnv

action_list = [
    EnvAction.NONE,
    EnvAction.JAB,
    EnvAction.TILT_U,
    EnvAction.TILT_L,
    EnvAction.TILT_D,
    EnvAction.TILT_R,
    EnvAction.SMASH_U,
    EnvAction.SMASH_L,
    EnvAction.SMASH_D,
    EnvAction.SMASH_R,
    EnvAction.SPECIAL_U,
    EnvAction.SPECIAL_L,
    EnvAction.SPECIAL_D,
    EnvAction.SPECIAL_R,
    EnvAction.DASH_ATTACK_L,
    EnvAction.DASH_ATTACK_R,
    EnvAction.SPOT_DODGE,
    EnvAction.ROLL_L,
    EnvAction.ROLL_R,
    EnvAction.JUMP,
    EnvAction.JUMP_L,
    EnvAction.JUMP_R,
    EnvAction.SHORT_HOP,
    EnvAction.SHORT_HOP_L,
    EnvAction.SHORT_HOP_R,
    EnvAction.WALK_L,
    EnvAction.WALK_R,
    EnvAction.DASH_L,
    EnvAction.DASH_R,
    EnvAction.GUARD,
    EnvAction.GRAB,
]

if __name__ == "__main__":
    SDCARD_PATH = "~/YOUR_SDCARD_PATH" # ex: if Ryujinx: ~/.config/Ryujinx, if Yuzu: ~/.local/share/yuzu/sdmc
    with Console(sdcard_path=SDCARD_PATH) as console:
        controller_1p = Controller(player_id=0)
        console.add_controller(controller_1p)
        with UltimateEnv(console, controller_1p, hz=6, action_space=len(action_list)) as env:
            for k in range(10):
                done = False
                obs = env.reset()
                step = 0
                while not done:
                    action = random.choice(action_list)
                    next_obs, reward, done, info = env.step(action)
                    print("episode: {}, step: {}, done: {}, reward: {}, action: {}".format(k, step, done, reward, action.name))
                    step += 1
            print("finished!")


# test code for trimming stuff

from pydub import AudioSegment

def detect_leading_silence(sound, silence_threshold=-50.0, chunk_size=10):
    '''
    sound is a pydub.AudioSegment
    silence_threshold in dB
    chunk_size in ms

    iterate over chunks until you find the first one with sound
    '''
    trim_ms = 0 # ms

    assert chunk_size > 0 # to avoid infinite loop
    print(sound[trim_ms:trim_ms+chunk_size].dBFS)
    while sound[trim_ms:trim_ms+chunk_size].dBFS < silence_threshold and trim_ms < len(sound):
        trim_ms += chunk_size
        print(sound[trim_ms:trim_ms+chunk_size].dBFS)

    return trim_ms

def print_db_values(sound, silence_threshold=-50.0, chunk_size=10):
    '''
    sound is a pydub.AudioSegment
    silence_threshold in dB
    chunk_size in ms

    iterate over chunks until you find the first one with sound
    '''
    trim_ms = 0 # ms

    assert chunk_size > 0 # to avoid infinite loop
    while trim_ms < len(sound):
        trim_ms += chunk_size
        print(sound[trim_ms:trim_ms+chunk_size].dBFS)

sound = AudioSegment.from_file("test1.wav", format="wav")

print_db_values(sound)

print("leading")
start_trim = detect_leading_silence(sound)
print("reverse")
end_trim = detect_leading_silence(sound.reverse())

duration = len(sound)
trimmed_sound = sound[start_trim:duration-end_trim]


# readInClassesFile.py

import csv
#import pandas as pd

# Class for storing distribution information cleanly within a class
class classVitals:

    def __init__(self):

        self.grade = {
            "6": 0,
            "7": 0,
            "8": 0
        }

        self.gender = { # male, female, other
            "M": 0,
            "F": 0,
            "O": 0
        }

        self.acidemics = {
            "1": 0,
            "2": 0,
            "3": 0
        }

        self.behvior = {
            "1": 0,
            "2": 0,
            "3": 0
        }

        self.spedFlag = False
        self.TAG = False
        self.fiveOfour = False

        self.migrantED = False
        self.homeLanguage = ""

class classSection:

    """
    SCHOOL ID:

    SECTION NUMBER:
    COURSE NUMBER:

    TERM ID:

    COURSE NAME:

    TEACHER:
    TEACHER NUMBER:

    PERIOD:
    ROOM NUMBER:

    """

    # Initiate the class section given all the infromation of that section / period
    def __init__(self, classPeriod):

        self.schoolID = classPeriod[0]
        self.sectionNumber = classPeriod[1]
        self.courseNumber = classPeriod[2]
        self.termID = classPeriod[3]
        self.courseName = classPeriod[4]
        self.teacher = classPeriod[5]
        self.teacherNumber = classPeriod[6]
        self.period = classPeriod[7]
        self.roomNumber = classPeriod[8]

        self.classSize = 0

        self.classRoster = []

        # CLASS VITALS - DISTRIBUTION NUMBERS FOR CHECKING CLASS
        self.classVitals = classVitals()

    # Add student to the class roster
    def addStudent(self, student):
        self.classRoster.append(student)
        self.classSize = self.classSize + 1

class masterSchedule:

    # Function to print out all the read in classes information
    def printClasses(allClasses, classCategory, short=False):

        # Write to classes.txt file
        with open("src/printOuts/classes.txt", "a") as newFile:

            newFile.write(f'\n \n {classCategory} \n \n')

            for classSec in allClasses:

                # Print classes and relevent info
                print(f'CLASS: {classSec} | COURESE NUM: {allClasses[classSec].courseNumber} | COURSE NAME: {allClasses[classSec].courseName}')

                if short:
                    newFile.write(f'CLASS: {classSec} | COURSE NAME: {allClasses[classSec].courseName} | PERIOD: {allClasses[classSec].period}')
                else:
                    newFile.write(f'CLASS: {classSec} | SECTION NUM: {allClasses[classSec].sectionNumber} | COURESE NUM: {allClasses[classSec].courseNumber} | TERM ID: {allClasses[classSec].termID} COURSE NAME: {allClasses[classSec].courseName} TEACHER: {allClasses[classSec].teacher} PERIOD: {allClasses[classSec].period} CLASS SIZE: {allClasses[classSec].classSize} ')

                newFile.write('\n')

    # Sort class sections by type
    def sortClassSectionsByType(allClasses):

        # Dictionaries for sorted class types
        coreClasses = {}
        homeRooms = {}
        yearClasses = {}
        trimesterClasses = {}

        # Sort the class sections
        for classSec in allClasses:

                if allClasses[classSec].sectionNumber[-2] == 'C':   # FIND CORE CLASSES

                    coreClasses[classSec] = allClasses[classSec]

                elif 'HR' in allClasses[classSec].courseNumber:    # FIND HOMEROOMS

                    homeRooms[classSec] = allClasses[classSec]

                elif allClasses[classSec].termID == '3200':

                    yearClasses[classSec] = allClasses[classSec]

                else:

                    trimesterClasses[classSec] = allClasses[classSec]

        return [coreClasses, homeRooms, yearClasses, trimesterClasses]

    # Sort class sections by team
    def sortClassSectionsByTeam(classesByType):

        # Dictionaries for team classes
        manzanita = {}
        sequoia = {}
        aspen = {}
        siskiyous = {}
        cascades = {}
        unknown = {}

        for classSec in classesByType:

            if classesByType[classSec].sectionNumber[:2] == 'SY':

                siskiyous[classSec] = classesByType[classSec]

            elif classesByType[classSec].sectionNumber[0] == 'S':

                sequoia[classSec] = classesByType[classSec]

            elif classesByType[classSec].sectionNumber[0] == 'M':

                manzanita[classSec] = classesByType[classSec]

            elif classesByType[classSec].sectionNumber[0] == 'A':

                aspen[classSec] = classesByType[classSec]

            elif classesByType[classSec].sectionNumber[0] == 'C':

                cascades[classSec] = classesByType[classSec]

            else:

                unknown[classSec] = classesByType[classSec]

        sortedByTeam = {
            "M" : manzanita,
            "S" : sequoia,
            "A" : aspen,
            "SY" : siskiyous,
            "C" : cascades,
            "U" : unknown
            }

        return sortedByTeam

    # Sort class sections by INC
    def sortClassSectionsByINC(classes):

        # Dictionaries to store INC
        INCClasses = {}
        nonINCClasses = {}

        for classSec in classes:

            if ('INC' in  classes[classSec].courseNumber) or ('INC' in classes[classSec].sectionNumber):

                INCClasses[classSec] = classes[classSec]

            else:

                nonINCClasses[classSec] = classes[classSec]

        return [INCClasses, nonINCClasses]

    # Sort class sections by trimester
    def sortClassesByTrimester(classes):

        # Define Dictionaries to store by trimester
        trimesterOne = {}
        trimesterTwo = {}
        trimesterThree = {}

        for classSec in classes:

            if 'T1' in  classes[classSec].sectionNumber:

                trimesterOne[classSec] = classes[classSec]

            if 'T2' in  classes[classSec].sectionNumber:

                trimesterTwo[classSec] = classes[classSec]

            if 'T3' in  classes[classSec].sectionNumber:

                trimesterThree[classSec] = classes[classSec]

        return [trimesterOne, trimesterTwo, trimesterThree]

    # Sort classes by periods
    def sortClassesByPeriod(classes):

        # Dictionanaries for each period
        _1B, _2B, _3B, _4B, _5B, _6B, _7B, _8B = {}, {}, {}, {}, {}, {}, {}, {}
        _1G, _2G, _3G, _4G, _5G, _6G, _7G, _8G = {}, {}, {}, {}, {}, {}, {}, {}

        blueDay = [_1B, _2B, _3B, _4B, _5B, _6B, _7B, _8B]
        goldDay = [_1G, _2G, _3G, _4G, _5G, _6G, _7G, _8G]

        for classSec in classes:

            if 'B-G' in  classes[classSec].period:

                blueDay[int(classes[classSec].period[0]) - 1][classSec] = classes[classSec]
                goldDay[int(classes[classSec].period[0]) - 1][classSec] = classes[classSec]

            elif 'B' in  classes[classSec].period:

                blueDay[int(classes[classSec].period[0]) - 1][classSec] = classes[classSec]

            elif 'G' in  classes[classSec].period:

                goldDay[int(classes[classSec].period[0]) - 1][classSec] = classes[classSec]

        return {'B': blueDay, 'G': goldDay}

    # Initiate a new masterSchedule instance
    def __init__(self, allClasses):

        # Sort class sections
        sortedClassesByType = masterSchedule.sortClassSectionsByType(allClasses)

        # Sort core classes by team
        coreClasses = masterSchedule.sortClassSectionsByTeam(sortedClassesByType[0])

        # Sort homeroom classes by team
        homeroomClasses = masterSchedule.sortClassSectionsByTeam(sortedClassesByType[1])

        # Sort out the INC classes from year and trimester classes
        yearINCSortedClasses = masterSchedule.sortClassSectionsByINC(sortedClassesByType[2])
        trimesterINCSortedClasses = masterSchedule.sortClassSectionsByINC(sortedClassesByType[3])

        # Sort the trimester based classes by trimester
        trimesterINCClasses = masterSchedule.sortClassesByTrimester(trimesterINCSortedClasses[0])
        trimesterNonINCClasses = masterSchedule.sortClassesByTrimester(trimesterINCSortedClasses[1])

        # Sort the trimester based INC classes by team
        trimesterOneINCClasses = masterSchedule.sortClassSectionsByTeam(trimesterINCClasses[0])
        trimesterTwoINCClasses = masterSchedule.sortClassSectionsByTeam(trimesterINCClasses[1])
        trimesterThreeINCClasses = masterSchedule.sortClassSectionsByTeam(trimesterINCClasses[2])

        ### CORE CLASSES ###
        # Core classes 7 / 8 grade teams
        self.manzanitaCores = coreClasses['M']
        self.sequoiaCores = coreClasses['S']
        self.aspenCores = coreClasses['A']
        # Core classes 6 grade teams
        self.siskiyousCores = coreClasses['SY']
        self.cascadesCores = coreClasses['C']
        # Core classes unknown
        self.unknownCores = coreClasses['U']  ### NOTE NEED TO DEAL WITH

        ### HOMEROOM CLASSES ###
        # Homeroom classes 7 / 8 grade teams
        self.manzanitaHomerooms = homeroomClasses['M']
        self.sequoiaHomerooms = homeroomClasses['S']
        self.aspenHomerooms = homeroomClasses['A']
        # Homeroom classes 6 grade teams
        self.siskiyousHomerooms = homeroomClasses['SY']
        self.cascadesHomerooms = homeroomClasses['C']
        # Homeroom classes unknown
        self.unknownHomerooms = homeroomClasses['U']  ### NOTE NEED TO DEAL WITH

        ### YEAR LONG CLASSES ###
        # Year long Non-INC classes - NOTE: full schoool
        self.yearNonINCClasses = yearINCSortedClasses[1]
        # Year long INC classes - NOTE: full schoool
        self.yearINCClasses = yearINCSortedClasses[0]

        ### TRIMESTER LONG CLASSES ###
        # Trimester Non-INC classes - NOTE: full schoool
        self.trimesterOneNonINCClasses = trimesterNonINCClasses[0]
        self.trimesterTwoNonINCClasses = trimesterNonINCClasses[1]
        self.trimesterThreeNonINCClasses = trimesterNonINCClasses[2]

        # Trimester One INC classes 7 / 8 grade teams
        self.manzanitaTrimesterOneINC = trimesterOneINCClasses['M']
        self.sequoiaTrimesterOneINC = trimesterOneINCClasses['S']
        self.aspenTrimesterOneINC = trimesterOneINCClasses['A']

        # Trimester Two INC classes 7 / 8 grade teams
        self.manzanitaTrimesterTwoINC = trimesterTwoINCClasses['M']
        self.sequoiaTrimesterTwoINC = trimesterTwoINCClasses['S']
        self.aspenTrimesterTwoINC = trimesterTwoINCClasses['A']

        # Trimester Three INC classes 7 / 8 grade teams
        self.manzanitaTrimesterThreeINC = trimesterThreeINCClasses['M']
        self.sequoiaTrimesterThreeINC = trimesterThreeINCClasses['S']
        self.aspenTrimesterThreeINC = trimesterThreeINCClasses['A']

        # Trimester One INC classes 6 grade teams
        self.siskiyousTrimesterOneINC = trimesterOneINCClasses['SY']
        self.cascadesTrimesterOneINC = trimesterOneINCClasses['C']

        # Trimester Two INC classes 6 grade teams
        self.siskiyousTrimesterTwoINC = trimesterTwoINCClasses['SY']
        self.cascadesTrimesterTwoINC = trimesterTwoINCClasses['C']

        # Trimester Three INC classes 6 grade teams
        self.siskiyousTrimesterThreeINC = trimesterThreeINCClasses['SY']
        self.cascadesTrimesterThreeINC = trimesterThreeINCClasses['C']

        # Trimester Unknown Team INC Classes
        self.unknownTriOneINC = trimesterOneINCClasses['U']  ### NOTE NEED TO DEAL WITH
        self.unknownTriTwoINC = trimesterTwoINCClasses['U']  ### NOTE NEED TO DEAL WITH
        self.unknownTriThreeINC = trimesterThreeINCClasses['U']  ### NOTE NEED TO DEAL WITH

        #### REDUNDANT BUT HELPS FOR ORGANIZING FOR NOW
        self.teamManzanita = {
            "CORES": self.manzanitaCores,
            "HOMEROOMS": self.manzanitaHomerooms,
            "T1 INC": self.manzanitaTrimesterOneINC,
            "T2 INC": self.manzanitaTrimesterTwoINC,
            "T3 INC": self.manzanitaTrimesterThreeINC

        }

        self.teamSequoia = {
            "CORES": self.sequoiaCores,
            "HOMEROOMS": self.sequoiaHomerooms,
            "T1 INC": self.sequoiaTrimesterOneINC,
            "T2 INC": self.sequoiaTrimesterTwoINC,
            "T3 INC": self.sequoiaTrimesterThreeINC
        }

        self.teamAspen = {
            "CORES": self.aspenCores,
            "HOMEROOMS": self.aspenHomerooms,
            "T1 INC": self.aspenTrimesterOneINC,
            "T2 INC": self.aspenTrimesterTwoINC,
            "T3 INC": self.aspenTrimesterThreeINC

        }

        self.teamSiskiyous = {
            "CORES": self.siskiyousCores,
            "HOMEROOMS": self.siskiyousHomerooms,
            "T1 INC": self.siskiyousTrimesterOneINC,
            "T2 INC": self.siskiyousTrimesterTwoINC,
            "T3 INC": self.siskiyousTrimesterThreeINC
        }

        self.teamCascades = {
            "CORES": self.cascadesCores,
            "HOMEROOMS": self.cascadesHomerooms,
            "T1 INC": self.cascadesTrimesterOneINC,
            "T2 INC": self.cascadesTrimesterTwoINC,
            "T3 INC": self.cascadesTrimesterThreeINC

        }

        self.teamUnknown = { ### NOTE NEED TO DEAL WITH
            "CORES": self.unknownCores,
            "HOMEROOMS": self.unknownHomerooms,
            "T1 INC": self.unknownTriOneINC,
            "T2 INC": self.unknownTriTwoINC,
            "T3 INC": self.unknownTriThreeINC
        }

        self.teamWholeSchool = {
            "YEAR NON INC": self.yearNonINCClasses,
            "YEAR INC": self.yearINCClasses,

            "T1 NON INC": self.trimesterOneNonINCClasses,
            "T2 NON INC": self.trimesterTwoNonINCClasses,
            "T3 NON INC": self.trimesterThreeNonINCClasses

        }

        # Dictionary of all team dictionaries
        self.wholeSchool = {
            "A": self.teamAspen,
            "M": self.teamManzanita,
            "S": self.teamSequoia,
            "SY": self.teamSiskiyous,
            "C": self.teamCascades,
            "U": self.teamUnknown,
            "W": self.teamWholeSchool

        }

    # Function to print out all sorted class sections
    def printSortedClasses(self, toPrint):

        for p in toPrint:
            masterSchedule.printClasses(p[0], p[1])

    # Get or print classes of a specific team
    def getOrPrintTeamClasses(self, team='', print=False):

        toPrint = []

        if team == '':
            toPrint = [
            [self.manzanitaCores, 'manzanitaCores'],
            [self.sequoiaCores, 'sequoiaCores'],
            [self.aspenCores, 'aspenCores'],
            [self.siskiyousCores, 'siskiyousCores'],
            [self.cascadesCores, 'cascadesCores'],
            [self.unknownCores, 'unknownCores'],
            [self.manzanitaHomerooms, 'manzanitaHomerooms'],
            [self.sequoiaHomerooms, 'sequoiaHomerooms'],
            [self.aspenHomerooms, 'aspenHomerooms'],
            [self.siskiyousHomerooms, 'siskiyousHomerooms'],
            [self.cascadesHomerooms, 'cascadesHomerooms'],
            [self.unknownHomerooms, 'unknownHomerooms'],
            [self.yearINCClasses, 'yearINCClasses'],
            [self.yearNonINCClasses, 'yearNonINCClasses'],

            [self.trimesterOneNonINCClasses, 'trimesterOneNonINCClasses'],
            [self.trimesterTwoNonINCClasses, 'trimesterTwoNonINCClasses'],
            [self.trimesterThreeNonINCClasses, 'trimesterThreeNonINCClasses'],

            [self.manzanitaTrimesterOneINC, 'manzanitaTrimesterOneINC'],
            [self.sequoiaTrimesterOneINC, 'sequoiaTrimesterOneINC'],
            [self.aspenTrimesterOneINC, 'aspenTrimesterOneINC'],

            [self.manzanitaTrimesterTwoINC, 'manzanitaTrimesterTwoINC'],
            [self.sequoiaTrimesterTwoINC, 'sequoiaTrimesterTwoINC'],
            [self.aspenTrimesterTwoINC, 'aspenTrimesterTwoINC'],

            [self.manzanitaTrimesterThreeINC, 'manzanitaTrimesterThreeINC'],
            [self.sequoiaTrimesterThreeINC, 'sequoiaTrimesterThreeINC'],
            [self.aspenTrimesterThreeINC, 'aspenTrimesterThreeINC'],

            [self.siskiyousTrimesterOneINC, 'siskiyousTrimesterOneINC'],
            [self.cascadesTrimesterOneINC, 'cascadesTrimesterOneINC'],

            [self.siskiyousTrimesterTwoINC, 'siskiyousTrimesterTwoINC'],
            [self.cascadesTrimesterTwoINC, 'cascadesTrimesterTwoINC'],

            [self.siskiyousTrimesterThreeINC, 'siskiyousTrimesterThreeINC'],
            [self.cascadesTrimesterThreeINC, 'cascadesTrimesterThreeINC'],

            [self.unknownTriOneINC, 'unknownTriOneINC'],
            [self.unknownTriTwoINC, 'unknownTriTwoINC'],
            [self.unknownTriThreeINC, 'unknownTriThreeINC'],
            ]
        else:
            for cl in self.wholeSchool[team]:
                toPrint.append([self.wholeSchool[team][cl], cl])
            for cl in self.wholeSchool['W']:
                toPrint.append([self.wholeSchool['W'][cl], cl])
            # for cl in self.wholeSchool['U']:
            #     toPrint.append([self.wholeSchool['U'][cl], cl])

        if print:
            masterSchedule.printSortedClasses(self,toPrint)

        return toPrint

    # Function to get or print out classes by period
    def getOrPrintClassesByPeriod(allClasses, print=False):

        # Dictionanaries for each period
        _1B, _2B, _3B, _4B, _5B, _6B, _7B, _8B = {}, {}, {}, {}, {}, {}, {}, {}
        _1G, _2G, _3G, _4G, _5G, _6G, _7G, _8G = {}, {}, {}, {}, {}, {}, {}, {}
        # List to store periods
        blueDay = [_1B, _2B, _3B, _4B, _5B, _6B, _7B, _8B]
        goldDay = [_1G, _2G, _3G, _4G, _5G, _6G, _7G, _8G]

        # sort by periods
        for p in allClasses:
            blueAndGold = masterSchedule.sortClassesByPeriod(p[0])
            # blueDay += blueAndGold['B']
            # goldDay += blueAndGold['G']
            for i, b in enumerate(blueAndGold['B']):
                for cl in b:
                    blueDay[i][cl] = b[cl]
            for i, g in enumerate(blueAndGold['G']):
                for cl in g:
                    goldDay[i][cl] = g[cl]

        # Print all the classes sorted
        if print:
            for i, period in enumerate(blueDay):
                masterSchedule.printClasses(period, f'{i + 1}B', True)
            for i, period in enumerate(goldDay):
                masterSchedule.printClasses(period, f'{i + 1}B', True)

        return {'B': blueDay, 'G': goldDay}

# def readInClassSupplementals():

#     masterBellSchedule = pd.read_excel('AMS Spreadsheets/Master Bell.xlsx')

# Function to read in all the classes from CSV file into an array
def readInClasses(filename='MAZ-CSV/CLASSES-CSV.csv'):

    allClassesDic = {}

    # Open classes csv
    with open(filename, newline = '', encoding='utf-8-sig') as file:

        classReader = csv.reader(file, delimiter = ',')

        for row in classReader:

            # Add classes to dictionary with section numbers as their Keys
            allClassesDic[row[1]] = classSection(row)

    return allClassesDic

# Function to clean previous classes.txt
def cleanClassesTXT():

    # Clean classes.txt file
    with open("src/printOuts/classes.txt", "w") as newFile:

            newFile.write(f'\n')

# # MAIN EXECUTION
# def main():

#     # Clean classes.txt file
#     cleanClassesTXT()

#     # Read in classes and sort class sections
#     classesDic = readInClasses()
#     AMSMasterSchedule = masterSchedule(classesDic)

#     # Print all classes of desired team or of whole school (if no team specified)
#     #masterSchedule.getOrPrintTeamClasses(AMSMasterSchedule)
#     masterSchedule.getOrPrintTeamClasses(AMSMasterSchedule, 'M', True)

#     # Get the classes for manzanita
#     manzanitaClasses = masterSchedule.getOrPrintTeamClasses(AMSMasterSchedule, 'M')

#     # Print the classes for manzanita by period
#     #manzClassesByPeriod = masterSchedule.getOrPrintClassesByPeriod(manzanitaClasses, True)

# # RUN MAIN
# if __name__ == '__main__':

#     main()


import configparser

class CheckWordsPipeline:
    def __init__(self, bad_title_file_path, domain_parking_file_path, maintenance_file_path, flash_file_path):
        config = configparser.ConfigParser()
        config.read('./config.ini')
        wordlists_config = config['wordlists']
        self.bad_title_file_path = wordlists_config['badtitle']
        self.domain_parking_file_path = wordlists_config['domainparking']
        self.maintenance_file_path = wordlists_config['maintainance']
        self.flash_file_path = wordlists_config['flash']
        with open(bad_title_file_path, "r") as f:
            self.bad_title_words = [word.strip() for word in f.readlines()]
        with open(domain_parking_file_path, "r") as f:
            self.domain_parking_words = [word.strip() for word in f.readlines()]
        with open(maintenance_file_path, "r") as f:
            self.maintenance_words = [word.strip() for word in f.readlines()]
        with open(flash_file_path, "r") as f:
            self.flash_words = [word.strip() for word in f.readlines()]

    def process_item(self, item, spider):
        content = item["content"]
        url = item["url"]

        results = {
            "badTitle": self.check_words(self.bad_title_words, item["title"], url, "title"),
            "Domainparking": self.check_words(self.domain_parking_words, content, url, "domainparking"),
            "Maintenance": self.check_words(self.maintenance_words, content, url, "maintenance"),
            "foundFlash": self.check_words(self.flash_words, content, url, "flash"),
        }

    def split_domain(domain):
        if domain.startswith("http://"):
            domain = domain[7:]
        elif domain.startswith("https://"):
            domain = domain[8:]

        # Extract the domain name
        return domain.split("/")[0]

    def check_words(self, words, content, url, mode):
        try:
            if mode == "domainparking":
                alfa_target = f'Die Domain "{split_domain(url)}" ist nicht verfügbar.'
                if alfa_target in content:
                    print(f"found: {url} - {mode} - {alfa_target}")
                    return True
                else:
                    for word in words:
                        if word in content:
                            print(f"found: {url} - {mode} - {word}")
                            return True
                    return False
            for word in words:
                if word in content:
                    print(f"found: {url} - {mode} - {word}")
                    return True
            return False
        except TypeError as e:
            pass


#!/usr/bin/env python
# coding=utf-8
"""
Author: Deean
Date: 2022-02-01 22:20:44
LastEditTime: 2022-02-01 22:29:07
Description:
FilePath: 1974.使用特殊打字机键入单词的最少时间.py
"""
#
# @lc app=leetcode.cn id=1974 lang=python3
#
# [1974] 使用特殊打字机键入单词的最少时间
#

# @lc code=start
from string import ascii_lowercase

class Solution:
    def minTimeToType(self, word: str) -> int:
        count, cur = 0, "a"
        for letter in word:
            step = abs(ascii_lowercase.index(letter) -
                       ascii_lowercase.index(cur))
            count += min(step, 26 - step)
            cur = letter
        return count + len(word)

# @lc code=end

if __name__ == "__main__":
    s = Solution()
    print(s.minTimeToType("bza"))
    print(s.minTimeToType("zjpc"))

P1974. 使用特殊打字机键入单词的最少时间.py


import unittest
from at_client.common import AtSign
from at_client.exception import *
from at_client.connections import AtRootConnection

class AtRootConnectionTest(unittest.TestCase):
    verbose = False

    def test_root_connection_objects(self):
        """
        Test single instance of root connection.
        """
        instance1 = AtRootConnection.get_instance()
        instance2 = AtRootConnection.get_instance()
        instance3 = AtRootConnection.get_instance()

        self.assertIs(instance1, instance2)
        self.assertIs(instance2, instance3)

    def test_root_connection(self):
        """
        Test root connection establishment.
        """
        root_connection = AtRootConnection.get_instance(verbose=self.verbose)
        root_connection.connect()
        self.assertTrue(root_connection.is_connected())

    def test_find_secondary(self):
        """
        Test finding a secondary server address.
        """
        root_connection = AtRootConnection.get_instance(verbose=self.verbose)
        secondary_address = root_connection.find_secondary(AtSign("@27barracuda"))
        self.assertIsNotNone(secondary_address)

    def test_find_secondary_failure(self):
        """
        Test finding a secondary server address for a non-existent AtSign.
        """
        with self.assertRaises(AtSecondaryNotFoundException):
            root_connection = AtRootConnection.get_instance(verbose=self.verbose)
            root_connection.find_secondary(AtSign("@wrongAtSign"))

    def test_find_multiple_secondary_addresses(self):
        """
        Test finding multiple secondary server addresses.
        """
        root_connection = AtRootConnection.get_instance(verbose=self.verbose)
        secondary_address1 = root_connection.find_secondary(AtSign("@27barracuda"))
        secondary_address2 = root_connection.find_secondary(AtSign("@19total67"))
        secondary_address3 = root_connection.find_secondary(AtSign("@wildgreen"))
        secondary_address4 = root_connection.find_secondary(AtSign("@colin"))

        self.assertIsNotNone(secondary_address1)
        self.assertIsNotNone(secondary_address2)
        self.assertIsNotNone(secondary_address3)
        self.assertIsNotNone(secondary_address4)

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


import numpy as np
from numpy import linalg as LA

def sectionA():
	print("\nAnswers of sectionA:\n")
	A, B, C = np.matrix('1; 2; 3'), np.matrix('4; 5; 6'), np.matrix('-1; 1; 3')
	#1
	print("1. 2A - B =\n", (2 * A - B))
	#2
	normA = LA.norm(A)
	angleA = np.rad2deg(np.arccos(1 / normA))
	print("2. |A| = %f ,the angle of A relative to the positive X axis is %f" % (normA,angleA))
	#3
	unitA = 1 / normA * A
	print("3. The unit vector in the direction of A is:\n", unitA)
	#4
	a1 = float(A[0])
	a2 = float(A[1])
	a3 = float(A[2])
	dirctionC = (a1, a2, a3) / normA
	print("4. The dircetion cosines of A are:", dirctionC)
	#5
	AdotB = float(np.dot(A.T, B))
	BdotA = float(np.dot(B.T, A))
	print("5. AdotB = ", AdotB,"BdotA = ", BdotA)
	#6
	normB = LA.norm(B)
	angleAB = np.rad2deg(np.arccos(AdotB / (normA * normB)))
	print("6. the angle between A and B:", angleAB)
	#7
	x = 1
	y = 1
	z = -(x + 2 * y) / 3
	print("7. A vector which is perpendicular to A is:", (x, y ,z))
	#8
	b1 = float(B[0])
	b2 = float(B[1])
	b3 = float(B[2])
	AxB = np.cross(A.T, B.T)
	BxA = - AxB
	print("8. AxB = ", AxB, "BxA = ", BxA)
	#9
	print("9. A vector perpendicular to A and B is: A x B = ", AxB)
	#10
	AB = np.column_stack([A, B])
	x = np.linalg.lstsq(AB, C)
	##len(x[0]) > 0 means 3A - B - C = 0 has answers.
	if len(x[0] > 0):
		print("10. A, B, C is linear dependency.")
	else:
		print("10. A, B, C is not linear dependency.")
	#11
	AtB = np.dot(A.T, B)
	BtA = np.dot(A, B.T)
	print("11. AtB = ", AtB, "\nBtA = ", BtA)

def sectionB():
	print("\nAnswers of sectionB:\n")
	A, B, C = np.matrix('1, 2, 3; 4, -2, 3; 0, 5, -1'), np.matrix('1, 2, 1; 2, 1, -4; 3, -2, 1'), np.matrix('1, 2, 3; 4, 5, 6; -1, 1, 3')
	#1
	print("1. 2A - B = ", 2 * A - B)
	#2
	AB = np.dot(A, B)
	BA = np.dot(B, A)
	print("2. AB = ", AB, "\nBA = ", BA)
	#3
	ABt =(AB).T
	BtAt = ABt
	print("3. (AB)t = ", ABt, "\nBtAt = ", BtAt)
	#4
	detA = np.linalg.det(A)
	print("4. |A| = ", detA, "|C| = 0, Because of the A10, we know the three row of this matrix is linear dependency.")
	#5
	print("5. The matrix in which the row vectors form an orthogonal set is B")
	for i in range(0, len(B)):
		for j in range(i + 1, len(B)):
			if np.dot(B[i], B[j].T) == 0:
				print("orthogonal set: ", B[i],B[j].T)

	#6
	invA = np.linalg.inv(A)
	invB = np.linalg.inv(B)
	print("6. invA =", invA,"\n invB =", invB)

def sectionC():
	print("\nAnswers of sectionC:\n")
	A, B = np.matrix('1, 2; 3, 2'), np.matrix('2, -2; -2, 5')
	#1
	eigvalA, V = np.linalg.eig(A)
	print("1. eigenvalue of A = ",eigvalA, "\n eigenvector of A = ", V)
	#2
	invVAV = np.round(np.dot(np.dot(np.linalg.inv(V), A), V))
	print("2. invVAV = ", invVAV)
	#3
	v1 = np.matrix([V[0, 0],V[1, 0]])
	v2 = np.matrix([V[0, 1],V[1, 1]])
	dotEigA = np.dot(v1, v2.T)
	print("3. dot product between the eigenvector of A is ", dotEigA)

	#4
	eigvalB, eigB = np.linalg.eig(B)
	v3 = np.matrix([eigB[0, 0],eigB[1, 0]])
	v4 = np.matrix([eigB[0, 1],eigB[1, 1]])
	dotEigB = np.dot(v3, v4.T)
	print("4. dot product between the eigenvector of B is ", dotEigB)
	#5
	print("5. The eignvectors of B are orthogonal matrix, because B is a symmetric real matrix.")

def main():
	sectionA()
	sectionB()
	sectionC()

if __name__ == '__main__':
	main()


from tkinter import *
from PIL import Image,ImageTk
import time
from tkinter import ttk,messagebox
import sqlite3
import os

class Feedback:
    def __init__(self,root):
        self.root=root
        self.root.title("Feedback  Management  System !!")
        self.root.geometry("1900x1080+0+0")

        # ====Title of the Project======

        title=Label(self.root,text="Feedback Management System",font=("times new roman",40,"bold"),bg="#c7f1f4",fg="#fc2a99",anchor='w',padx=450).place(x=0,y=0,relwidth=1,height=70)
        # ==============Buttton Logout=============

        btn_logout=Button(self.root, command=self.logout_feed,text="Logout", font=("times new roman",15,"bold"),bg="#f8dcfb",cursor="hand2").place(x=1350,y=10,height=50,width=100)

#         # ================Time==========================
        self.lbl_clock=Label(self.root,text="  You are Heartly Welcomed in Feedback Management System !!\t\t  Date: DD-MM-YYYY\t\t Time: HH-MM-SS\t\t",font=("times new roman",15),bg="#4d636d",fg="#ffffff")
        self.lbl_clock.place(x=0,y=70,relwidth=1,height=30)

        # ======================================================

        #  All variables========================
        self.var_searchby=StringVar()
        self.var_searchtxt=StringVar()
        self.fac_id=StringVar()
        self.fac_name=StringVar()
        self.var_sem=StringVar()
        self.var_q1=StringVar()
        self.var_q2=StringVar()
        self.var_q3=StringVar()
        self.var_q4=StringVar()
        self.var_q5=StringVar()
        self.var_btn=StringVar()

        searchFrame=LabelFrame(self.root,text="Search Faculty",font=("goudy old style",15,"bold"),bd=4,relief=RIDGE,bg="#ecf8f9",fg="#f30f0f")
        searchFrame.place(x=500,y=120,width=600,height=70)

        # ==========Option================
        cmb_search=ttk.Combobox(searchFrame,textvariable=self.var_searchby,values=("Select","FAC_ID","FAC_NAME"),state='readonly',justify=CENTER,font=("goudy old style", 13,"bold"))
        cmb_search.place(x=10,y=10,width=180)
        cmb_search.current(0)

        txt_search=Entry(searchFrame,textvariable=self.var_searchtxt,font=("goudy old style",15,"bold"),bg="lightyellow",fg="#f51435").place(x=200,y=10)

        btn_search=Button(searchFrame,text="Search",cursor="hand2",command=self.search,font=("goudy old style",15,"bold"),bg="#ffdab9",fg="#ff00ff").place(x=420,y=8,width=150,height=30)

        btn_clear=Button(self.root,text="Clear",cursor="hand2",command=self.clear,font=("goudy old style",15,"bold"),bg="red",fg="white").place(x=1150,y=150,width=100,height=35)

        #============ Row 1 ==============================
        lbl_facid=Label(self.root,text="Faculty ID",font=("times new roman" ,18,"bold")).place(x=50,y=225)

        lbl_name=Label(self.root,text="Faculty Name",font=("times new roman" ,18,"bold")).place(x=450,y=225)

        lbl_sem=Label(self.root,text="Student Sem",font=("times new roman" ,18,"bold")).place(x=900,y=225)

        txt_facid=Entry(self.root,textvariable=self.fac_id,font=("goudy old style",15,"bold"),bg="lightyellow",fg="#f51435").place(x=200,y=225)

        txt_facname=Entry(self.root,textvariable=self.fac_name,font=("goudy old style",15,"bold"),bg="lightyellow",fg="#f51435").place(x=630,y=225)

        cmb_sem=ttk.Combobox(self.root,textvariable=self.var_sem,values=("Select","1st SEM","2nd SEM","3rd SEM","4th SEM","5th SEM","6th SEM","7th SEM","8th SEM"),state='readonly',justify=CENTER,font=("goudy old style", 13,"bold"))

        cmb_sem.place(x=1080,y=225,width=180)
        cmb_sem.current(0)

        #============ feedback ques ==============================

        lbl_q1=Label(self.root,text="1. Presentation of Subject matter",font=("times new roman" ,18,"bold")).place(x=250,y=300)

        cmb_q1=ttk.Combobox(self.root,textvariable=self.var_q1,values=("Select","Excellent","Very Good","Good","Satisfactory","Poor"),state='readonly',justify=CENTER,font=("goudy old style", 18,"bold"))

        cmb_q1.place(x=800,y=295,width=180)
        cmb_q1.current(0)

        lbl_q2=Label(self.root,text='''2. Communication Skills &
            Interaction with the students''',font=("times new roman" ,18,"bold")).place(x=203,y=350)

        cmb_q2=ttk.Combobox(self.root,textvariable=self.var_q2,values=("Select","Excellent","Very Good","Good","Satisfactory","Poor"),state='readonly',justify=CENTER,font=("goudy old style", 18,"bold"))

        cmb_q2.place(x=800,y=355,width=180)
        cmb_q2.current(0)

        lbl_q3=Label(self.root,text="3. Punctuality & Regularity",font=("times new roman" ,18,"bold")).place(x=250,y=430)

        cmb_q3=ttk.Combobox(self.root,textvariable=self.var_q3,values=("Select","Excellent","Very Good","Good","Satisfactory","Poor"),state='readonly',justify=CENTER,font=("goudy old style", 18,"bold"))

        cmb_q3.place(x=800,y=420,width=180)
        cmb_q3.current(0)

        lbl_q4=Label(self.root,text='''4. Ability to motivate the students &
    Clarification of doubts''',font=("times new roman" ,18,"bold")).place(x=250,y=480)

        cmb_q4=ttk.Combobox(self.root,textvariable=self.var_q4,values=("Select","Excellent","Very Good","Good","Satisfactory","Poor"),state='readonly',justify=CENTER,font=("goudy old style", 18,"bold"))

        cmb_q4.place(x=800,y=485,width=180)
        cmb_q4.current(0)

        lbl_q5=Label(self.root,text="5. Teacher’s approach towards students",font=("times new roman" ,18,"bold")).place(x=250,y=550)

        cmb_q5=ttk.Combobox(self.root,textvariable=self.var_q5,values=("Select","Excellent","Very Good","Good","Satisfactory","Poor"),state='readonly',justify=CENTER,font=("goudy old style", 18,"bold"))

        cmb_q5.place(x=800,y=550,width=180)
        cmb_q5.current(0)

        #======= Faculty Details  Frame ========================

        FacultyFrame=Frame(self.root,bd=4,relief=RIDGE)
        FacultyFrame.place(x=1050,y=300,width=398,height=300)

        scrollx=Scrollbar(FacultyFrame,orient=HORIZONTAL)
        scrolly=Scrollbar(FacultyFrame,orient=VERTICAL)

        self.facultyTable=ttk.Treeview(FacultyFrame,columns=("fac_id","fac_name"),yscrollcommand=scrolly.set,xscrollcommand=scrollx.set)
        scrollx.pack(side=BOTTOM,fill=X)
        scrolly.pack(side=RIGHT,fill=Y)
        scrollx.config(command=self.facultyTable.xview)
        scrolly.config(command=self.facultyTable.yview)

        self.facultyTable.heading("fac_id",text="FACULTY ID")
        self.facultyTable.heading("fac_name",text="FACULTY NAME")

        self.show()

        self.facultyTable["show"]="headings"

        self.facultyTable.column("fac_id",width=50)
        self.facultyTable.column("fac_name",width=100)
        self.facultyTable.pack(fill=BOTH,expand=1)
        self.facultyTable.bind("<ButtonRelease-1>",self.get_data)
        self.show()

        btn_submit=Button(self.root,text="Submit",cursor="hand2",command=self.feedback,font=("goudy old style",20,"bold"),bg="#ff4500",fg="#ffffff").place(x=810,y=650,width=150,height=40)

        # Footer
        lbl_footer=Label(self.root,text="FMS: Feedback Management System  | Developed by PRASHANT KUMAR & SHOAIB REHMAN ",font=("times new roman",18),bg="#008b8b",fg="#ffffff").pack(side=BOTTOM,fill=X)

        self.update_content()
#====================functions============================

    def feedback(self):
        con=sqlite3.connect(database=r'fms.db' )
        cur=con.cursor()
        try:
            if self.fac_id.get()=="":
                messagebox.showerror("Error","Faculty ID Must be Required",parent=self.root)
            elif self.fac_name.get()=="":
                messagebox.showerror("Error","Faculty Name Must be Required",parent=self.root)
            elif self.var_sem.get()=="Select":
                messagebox.showerror("Error","Semester column Must Be Filled",parent=self.root)
            elif self.var_q1.get()=="Select":
                messagebox.showerror("Error","Question 1 Must be Filled",parent=self.root)
            elif self.var_q2.get()=="Select":
                messagebox.showerror("Error","Question 2 Must be Filled",parent=self.root)
            elif self.var_q3.get()=="Select":
                messagebox.showerror("Error","Question 3 Must be Filled",parent=self.root)
            elif self.var_q4.get()=="Select":
                messagebox.showerror("Error","Question 4 Must be Filled",parent=self.root)
            elif self.var_q5.get()=="Select":
                messagebox.showerror("Error","Question 5 Must be Filled",parent=self.root)

            else:

                cur.execute("Insert into feedback( fac_id , fac_name ,  sem , q1,q2,q3,q4,q5  ) values(?,?,?,?,?,?,?,?)",(
                                                        self.fac_id.get(),
                                                        self.fac_name.get(),
                                                        self.var_sem.get(),
                                                        self.var_q1.get(),
                                                        self.var_q2.get(),
                                                        self.var_q3.get(),
                                                        self.var_q4.get(),
                                                        self.var_q5.get(),

                ))
                con.commit()
                messagebox.showinfo("Success","Feedback Given SUCCESSFULLY !!",parent=self.root)
                self.show()
        except Exception as ex:
            messagebox.showerror("Error",f"Error due to : {str(ex)}",parent=self.root)

    def update_content(self):
        time_=time.strftime('%I:%M:%S')
        date_=time.strftime('%d:%m:%Y')
        self.lbl_clock.config(text=f"  You are Heartly Welcomed by PRASHANT KUMAR & SHOAIB REHMAN !!\t\t  Date: {str(date_)}\t\t Time:{str(time_)}")
        self.lbl_clock.after(200,self.update_content)

    def search(self):
        con=sqlite3.connect(database=r'fms.db' )
        cur=con.cursor()
        try:
            if self.var_searchby.get()=="Select":
                messagebox.showerror("Error","Select a valid Option",parent=self.root)
            elif self.var_searchtxt.get()=="":
                messagebox.showerror("Error","Give  Search Area Input",parent=self.root)
            else:
                cur.execute("select * from faculty where "+self.var_searchby.get()+" LIKE '%"+self.var_searchtxt.get()+"%'")
                rows=cur.fetchall()
                if len(rows)!=0:
                    self.facultyTable.delete(*self.facultyTable.get_children())
                    for row in rows:
                        self.facultyTable.insert('',END,values=row)
                else:
                    messagebox.showerror("Error","No Record Found !!!",parent=self.root)
        except Exception as ex:
            messagebox.showerror("Error",f"Error due to : {str(ex)}",parent=self.root)

    def get_data(self,ev):
        f=self.facultyTable.focus()
        content=(self.facultyTable.item(f))
        row=content['values']
        self.fac_id.set(row[0])
        self.fac_name.set(row[1])

    def show(self):
        con=sqlite3.connect(database=r'fms.db' )
        cur=con.cursor()
        try:
            cur.execute("Select * from faculty")
            rows=cur.fetchall()
            self.facultyTable.delete(*self.facultyTable.get_children())
            for row in rows:
                self.facultyTable.insert('',END,values=row)
        except Exception as ex:
            messagebox.showerror("Error",f"Error due to : {str(ex)}",parent=self.root)

    def clear(self):
        self.fac_id.set("")
        self.fac_name.set("")
        self.var_sem.set("Select")
        self.var_searchtxt.set("")
        self.var_searchby.set("Select")
        self.var_q1.set("Select")
        self.var_q2.set("Select")
        self.var_q3.set("Select")
        self.var_q4.set("Select")
        self.var_q5.set("Select")

        self.show()

    def logout_feed(self):
        self.root.destroy()
        os.chdir(r"Feedback System")
        os.system("python login.py")

if  __name__=="__main__":
    root=Tk()
    obj=Feedback(root)
    root.resizable(True,False)
    root.mainloop()


from django.urls import path
from base.views import product_views as views

urlpatterns = [
    path("getproducts/", views.getProducts, name="get-products"),
    path("register/", views.register, name="register"),
    path("getproduct/<str:pk>/", views.getProduct, name="get-product"),
    path("update/<str:pk>/", views.update, name="update-product"),
    path("delete/<str:pk>/", views.delete, name="delete-product"),
    path("search/<str:querie>/", views.search, name="search-product"),
]


import json
from difflib import get_close_matches

data = json.load(open("data.json"))

def translate(w):
    w = w.lower()
    if w in data:
        return data[w]
    elif len(get_close_matches(w, data.keys())) > 0:
        valid = input(f"Did you mean %s instead of {w}. Please write Y for yes and N for no." %get_close_matches(w, data.keys())[0])
        if valid == "Y":
            return get_close_matches(w, data.keys())[0]
        elif valid == "N":
            return "We can't understand you."
        else:
            return "Try a valid word"
    else:
        return "You inseted an invalid word.."

user_word = input("Write a word: ")
output = translate(user_word)

if type(output) == list:
    for item in output:
        print(item)
else:
    print(output)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import transformers
import textwrap
from transformers import LlamaTokenizer, LlamaForCausalLM
import os
import sys
from typing import List

from peft import (
    LoraConfig,
    get_peft_model,
    get_peft_model_state_dict,
    prepare_model_for_int8_training,
)

import fire
import torch
from datasets import load_dataset
import pandas as pd

import matplotlib.pyplot as plt
import matplotlib as mpl

import seaborn as sns
from pylab import rcParams

device = "cuda" if torch.cuda.is_available() else "cpu"

CUTOFF_LEN = 50

df = pd.read_csv("./data/BTC_Tweets_Updated.csv")

# df.New_Sentiment_State.value_counts().plot(kind="bar")

def sentiment_score_to_name(score: float):
    if score > 0:
        return "Positive"
    elif score <0:
        return "Negative"
    return "Neutral"

dataset_data = [
    {
        "instruction": "Detect the sentiment of the tweet.",
        "input": row_dict["Tweet"],
        "output": sentiment_score_to_name(row_dict["New_Sentiment_State"])
    }
    for row_dict in df.to_dict(orient="records")
]

with open("./data/alpaca-bitcoin-sentiment-dataset.json", "w") as f:
    json.dump(dataset_data, f)

data = load_dataset("json", data_files="./data/alpaca-bitcoin-sentiment-dataset.json")
print(data["train"])

BASE_MODEL = "../llama-7b-hf"
model = LlamaForCausalLM.from_pretrained(
    BASE_MODEL,
    torch_dtype=torch.float16,
    device_map="auto",
    offload_folder="./data/llama"
)

tokenizer = LlamaTokenizer.from_pretrained(BASE_MODEL)
tokenizer.pad_token_id = (0)
tokenizer.padding_side = "left"

def generate_prompt(data_point):
    return f"""Below is an instruction that describes a task, paired with an input that provide future context.
      Write a responce that appropriately completes the request. #noqa:
      ### Instruct:
      {data_point["instruction"]}
      ### Input
      {data_point["input"]}
      ### Response
      {data_point["output"]}
    """

def tokenize(prompt, add_eos_token=True):
    result = tokenizer(
        prompt,
        truncation=True,
        max_length=CUTOFF_LEN,
        padding=False,
        return_tensors=None,
    )
    if (result["input_ids"][-1] != tokenizer.eos_token_id and len(result["input_ids"]) < CUTOFF_LEN and add_eos_token):
        result["input_ids"].append(tokenizer.eos_token_id)
        result["attention_mask"].append(1)

    result["labels"] = result["input_ids"].copy()

    return result

def generate_and_tokenize_prompt(data_point):
    full_prompt = generate_prompt(data_point)
    tokenized_full_prompt = tokenize(full_prompt)
    return tokenized_full_prompt

train_val = data["train"].train_test_split(
    test_size=200, shuffle=True, seed=42
)

train_data = (
    train_val["train"].map(generate_and_tokenize_prompt)
)
val_data = (
    train_val["test"].map(generate_and_tokenize_prompt)
)

# Training
LORA_R = 8
LORA_ALPHA = 16
LORA_DROPOUT = 0.05
LORA_TARGET_MODULES = [
    "q_proj",
    "v_proj",
]

BATCH_SIZE = 128
MICRO_BATCH_SIZE = 4
GRADIENT_ACCUMULATION_STEPS = BATCH_SIZE // MICRO_BATCH_SIZE
LEARNING_RATE = 3e-4
TRAIN_STEPS = 300
OUTPUT_DIR = "experiments"

# We can now prepare model for training
model = prepare_model_for_int8_training(model)
config = LoraConfig(
    r = LORA_R,
    lora_alpha=LORA_ALPHA,
    target_modules=LORA_TARGET_MODULES,
    lora_dropout=LORA_DROPOUT,
    bias="none",
    task_type="CAUSAL_LM",
)

model = get_peft_model(model, config)
model.print_trainable_parameters()

training_arguments = transformers.TrainingArguments(
    per_device_train_batch_size=MICRO_BATCH_SIZE,
    gradient_accumulation_steps=GRADIENT_ACCUMULATION_STEPS,
    warmup_steps=100,
    max_steps=TRAIN_STEPS,
    no_cuda=True,
    learning_rate=LEARNING_RATE,
    logging_steps=10,
    optim="adamw_torch",
    evaluation_strategy="steps",
    save_strategy="steps",
    eval_steps=50,
    save_steps=50,
    output_dir=OUTPUT_DIR,
    save_total_limit=3,
    load_best_model_at_end=True,
    report_to="tensorboard"
)

data_collector = transformers.DataCollatorForSeq2Seq(
    tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True
)

trainer = transformers.Trainer(
    model=model,
    train_dataset=train_data,
    eval_dataset=val_data,
    args=training_arguments,
    data_collator=data_collector
)

model.config.use_cache = False
old_state_dict = model.state_dict
model.state_dict = (
    lambda self, *_, **__: get_peft_model_state_dict(
        self, old_state_dict()
    )
).__get__(model, type(model))

trainer.train()
model.save_pretrained(OUTPUT_DIR)


import os
import joblib
import time
import argparse
from PIL import Image
from config import Config
from torchvision import datasets, transforms
from attack.mask_attack import shaped_mask_attack
from yolov3.detect import load_model, detect
# from yolov7.detect_attack import load_model, detect
# from yolov5.detect_attack import load_model, detect

# import os
# os.environ['CUDA_LAUNCH_BLOCKING'] = '1'

loader = transforms.Compose([
    transforms.ToTensor()
])
conf_thre = 0.5

def attack_process(H, W, img, threat_model, device, emp_iterations, max_pertubation_mask, content, folder_path, name, grad_avg):
    input = loader(img)
    bbox, prob = detect(threat_model, input) # 在攻击前检测原目标的置信度
    begin = time.time()
    adv_img_ts, adv_img, mask = shaped_mask_attack(H, W, bbox, threat_model, img, device, emp_iterations, max_pertubation_mask, content, grad_avg) # 调用攻击函数进行攻击
    _, prob = detect(threat_model,adv_img_ts) # 在攻击后检测目标的置信度
    end = time.time()
    print("optimization time: {}".format(end - begin))
    print("obj score after attack: ",prob.item())
    if prob.item() < conf_thre:
        imgs_dir = os.path.join(folder_path, "adv_imgs")
        msks_dir = os.path.join(folder_path, "infrared_masks")
        img_path = os.path.join(imgs_dir, name)
        adv_img.save(img_path,quality=99)
        msk_path = os.path.join(msks_dir, name)
        mask.save(msk_path,quality=99)
        return True
        # joblib.dump(adv_img_ts,folder_path+"/res/adv_ts" + str(args.number) + "+" + str(args.max_pertubation_mask) + "/{}_pedestrian&params.pkl".format(name))
        # joblib.dump(mask,folder_path+"/res/mask" + str(args.number) + "+" + str(args.max_pertubation_mask) + "/{}_mask&params.pkl".format(name))
    else: return False

if __name__=="__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument('--victim_imgs',type=str,default="", help='the folder with victim images to conduct attacks')
    args = parser.parse_args()
    ## 加载攻击参数 ##
    opt = Config()
    if args.victim_imgs == "":
        folder_path = opt.attack_dataset_folder
        if not os.path.join(folder_path):
            print("please prepare the dataset correctly")
            assert False
    else: folder_path = args.victim_imgs

    ## 加载待攻击模型 ##
    threat_model = load_model()
    threat_model.eval()

    suc = 0
    sum = 0
    for i,name in enumerate(os.listdir(folder_path)):
        file_path = os.path.join(folder_path, name)
        img = Image.open(file_path)
        input = loader(img)
        bbox, prob = detect(threat_model, input) # 在攻击前检测原目标的置信度
        print("{}th image".format(i))
        if prob.item()<0.5: # 本身检测分数较低的跳过
            print("detector cannot detect any pedestrian in the image")
            continue
        else:
            print("obj score before attack: ", prob.item())
        sum += 1
        for k in range(opt.iterations):
            print("{}th attack".format(k))
            flag = attack_process(opt.height, opt.width, img, threat_model, opt.device, opt.emp_iterations, opt.max_pertubation_mask, opt.content, opt.save_folder, name, opt.grad_avg)
            if flag:
                suc += 1
                break
    print("ASR: ", float(suc)/sum)


# Given a list of non negative integers, arrange them such that they form the largest number.
#
# For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
#
# Note: The result may be very large, so you need to return a string instead of an integer.
#
# Credits:
# Special thanks to @ts for adding this problem and creating all test cases.
#
# Subscribe to see which companies asked this question
import  functools
class Solution:
    # @param {integer[]} nums
    # @return {string}

    def _cmp(self,x, y):
        a = int(str(x) + str(y))
        b = int(str(y) + str(x))
        if a > b:
            return 1
        elif b < a:
            return -1
        else:
            return 0

    def largestNumber(self, nums):
        result = [str(ele) for ele in nums]
        def _cmp( x, y):
            a = x + y
            b = y + x
            if a > b:
                return -1
            elif b < a:
                return 1
            else:
                return 0
        result.sort(key = functools.cmp_to_key(_cmp))
        index = len(result)-1
        for i in range(len(result)):
            if result[i]!= '0':
                index = i
                break
        result[:index] = []
        return ''.join(result)

hh = Solution()
nums = [0,0]
print(hh.largestNumber(nums))