from matplotlib import transforms
import numpy as np
import matplotlib.pyplot as plt
import sys
import os

import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib import cm
from random import random, seed
import utils

# to suppress warnings from fig.tight_layout() in some plotsFalse
# import warnings
# warnings.filterwarnings("ignore")

plt.style.use('seaborn')
plt.rc('text', usetex=True)
plt.rc('font', family='DejaVu Sans')
path_plots = '../output/plots'

def set_ax_info(ax, xlabel, ylabel, title=None, zlabel=None):
    """Write title and labels on an axis with the correct fontsizes.

    Args:
        ax (matplotlib.axis): the axis on which to display information
        title (str): the desired title on the axis
        xlabel (str): the desired lab on the x-axis
        ylabel (str): the desired lab on the y-axis
        zlabel (str): the desired lab on the z-axis

    """
    if zlabel is None:
        ax.set_xlabel(xlabel, fontsize=20)
        ax.set_ylabel(ylabel, fontsize=20)
        ax.set_title(title, fontsize=20)
        ax.tick_params(axis='both', which='major', labelsize=15)
        ax.ticklabel_format(style='plain')
        ax.legend(fontsize=15)
    else:
        ax.set_xlabel(xlabel, fontsize=18)
        ax.set_ylabel(ylabel, fontsize=18)
        ax.set_zlabel(zlabel, fontsize=18)
        ax.tick_params(axis='both', which='major', labelsize=12)

def push(file):
    os.system(f"git add {file}")
    os.system("git commit -m 'plots'")
    os.system("git push")
    print(f"Pushed to git: {file}")

def show(fig, fname, args):
    if args.dataset == "SRTM":
        print("Terrain data: \'SRTM_\' added at beginning of plot file name")
        fname = "SRTM_" + fname
    if args.save:
        print("Saving plot: ", fname + ".pdf")
        fig.savefig(os.path.join(path_plots, fname + '.pdf'))
    if args.push:
        push(os.path.join(path_plots, fname + ".pdf"))
    if args.show:
        plt.show()
    else:
        plt.clf()

def Plot_3DDataset(x, y, z, args, predict=False):
    """3D plot the data and saves the plot in the output folder
        Either Franke funcprint(cm.hot(0.3))tion or terrain data
    Args:
        x (array):  x-data
        y (array):  y-data
        z (array):  z-values
        args (argparse): argparse containing info about run
    """

    if 1 in z.shape:
        nx = x.shape[0]
        ny = x.shape[1]
        z = z.reshape((nx, ny))

    fig = plt.figure()
    ax = fig.gca(projection="3d")
    # Plot the surface.
    surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)
    # Customize the z axis.
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter("%.02f"))

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)
    # general formalities
    if predict:
        fname = "prediction_p" + str(max(args.polynomial))
        title = f"Prediction of raw data for P = {max(args.polynomial)}"
    else:
        fname = f"rawdata"
        title = "Raw data"
    if args.dataset == "Franke":
        fname += f"_eps{args.epsilon}".replace(".", "")
    fname = fname.replace('.', '')  # remove dots from fname
    xlabel = '$x$'
    ylabel = '$y$'
    zlabel = '$z$'
    set_ax_info(ax, xlabel, ylabel, title, zlabel)
    fig.tight_layout()
    show(fig, fname, args)

def Plot_error(MSE_test, MSE_train, args):
    """Plot mean square error as a function of polynomial degree
    for test and train data

    Args:
        MSE_test (array): array of test mean square error
        MSE_train (array): array of train mean square error
        args (argparse): argparse containing information of method used
    """
    # Plot the data
    fig, ax = plt.subplots()
    ax.plot(args.polynomial, MSE_test, "bo--", label="test MSE")
    ax.plot(args.polynomial, MSE_train, "ro--", label="Train MSE")

    amin = np.argmin(MSE_test)
    print(f"Lowest error is {MSE_test[amin]}, for p = {args.polynomial[amin]}")

    # general formalities
    if args.dataset == "SRTM":
        fname = 'MSE_' + args.method \
                + '_n' + str(args.num_points) \
                + '_pol' + str(max(args.polynomial))

        title = 'Terrain data MSE for ' + args.method

    else:
        fname = 'MSE_' + args.method \
                + '_n' + str(args.num_points) \
                + '_eps' + str(args.epsilon) \
                + '_pol' + str(max(args.polynomial))

        title = 'MSE for ' + args.method

    fname = fname.replace('.', '')  # remove dots from fname

    if args.resampling != "None":
        title += " using " \
                 + args.resampling \
                 + f" iter = {args.resampling_iter}"
        if args.method != "OLS":
            title += r', $\lambda$ = ' + str(args.lmb[0])
        fname += "_" + args.resampling + "_" + "re" \
                 + str(args.resampling_iter)
    if args.method != "OLS":
        fname += '_lam_'+str(args.lmb[0])
        fname = fname.replace('.', '_')
    xlabel = 'Polynomial degree'
    if args.log:
        ylabel = 'log(MSE)'
    else:
        ylabel = 'MSE'

    set_ax_info(ax, xlabel, ylabel, title)
    if args.log:
        ax.set_yscale('log')
        fname += '_log'

    # save figure
    print('Plotting error: See ' + fname + '.pdf')
    show(fig, fname, args)

def Plot_R2(R2_test, R2_train, args):
    """Plot R^2 score as a function of polynomial degree
    for test and train data

    Args:
        R2_test (array): array of test R2 score
        R2_train (array): array of train R2 score
        args (argparse): argparse containing information of method used
    """
    if args.resampling != "None":
        return
    elif args.method != "OLS":
        return
    # Plot the data
    fig, ax = plt.subplots()
    ax.plot(args.polynomial, R2_test, "bo--", label="Test R2")
    ax.plot(args.polynomial, R2_train, "ro--", label="Train R2")
    # general formalitiesiscrete uniform”
    if args.dataset == "SRTM":
        fname = 'R2_' + args.method \
                + '_n' + str(args.num_points) \
                + '_eps' + str(args.epsilon) \
                + '_pol' + str(max(args.polynomial))
        title = "Terrain data R2 score for " \
                + args.method

    else:
        fname = 'R2_' + args.method \
                + '_n' + str(args.num_points) \
                + '_eps' + str(args.epsilon) \
                + '_pol' + str(max(args.polynomial))

        title = 'R2 score for ' \
                + args.method

    fname = fname.replace('.', '')  # remove dots from fname
    xlabel = 'Polynomial degree'
    ylabel = 'R2'
    set_ax_info(ax, xlabel, ylabel, title)

    # save figure
    print('Plotting R2: See ' + fname + '.pdf')
    show(fig, fname, args)

def Plot_bias_var_tradeoff(datas, args):
    """Plot mean square error, variance and error as a function of polynomial degree

    Args:
        datas (defaultdict) contains following arrays
                test_errors
                test_biases
                test_vars
                train_errors
                train_biases
                train_vars
        args (argparse): argparse containing information of method used
    """
    # make figure and plot data
    fig, ax = plt.subplots()

    P = args.polynomial
    ax.plot(P, datas["test_errors"], "bo-", label="test MSE")
    ax.plot(P, datas["test_biases"], "ro-", label="test Bias")
    ax.plot(P, datas["test_vars"], "go-", label="test Variance")
    ax.plot(P, datas["train_errors"], "bo--", label="train MSE")
    ax.plot(P, datas["train_biases"], "ro--", label="train Bias")
    ax.plot(P, datas["train_vars"], "go--", label="train Variance")
    # General formalities
    xlabel = 'Polynomial degree'
    ylabel = 'Bias, variance and MSE'
    title = 'Bias Variance Tradeoff for ' + args.method+', '\
        + args.resampling + ' iter = '+str(args.resampling_iter)
    if args.log:
        ylabel = '(log) Bias, variance and MSE'
    set_ax_info(ax, xlabel, ylabel, title)

    # Saving figure
    if args.dataset == "SRTM":
        fname = 'BVT_' + args.method \
                + '_n' + str(args.num_points)
        title = 'Terrain data: ' + title

    else:
        fname = 'BVT_' + args.method \
                + '_n' + str(args.num_points) \
                + '_eps' + str(args.epsilon)

    if args.method != "OLS":
        fname += '_lam_'+str(args.lmb[0])

    if args.log:
        ax.set_yscale('log')
        fname += '_log'

    fname = fname.replace('.', '_')
    print('Plotting Bias variance tradeoff: See %s.pdf' % (fname))
    show(fig, fname, args)

def Plot_lambda(results, args):
    """ Plot test MSE as function of lambda, for different polynomial degrees

    Args:
        results: (defaultdict) contains 1 2D array with test errors
                First index goes over poly-degree
                2nd index goes over lambda
    """
    fig, ax = plt.subplots()

    lmbs = args.lmb
    for i, p in enumerate(args.polynomial):
        r = results["test_MSE"][i]
        if args.log:
            r = np.log10(r)
        ax.plot(np.log10(lmbs), r, label=f"Polynomial degree: {p}")

    r = results["test_MSE"]
    min_val = np.min(r)
    mp, ml = np.where(r == min_val)
    mp = args.polynomial[mp[0]]
    ml = np.log10(lmbs[ml][0])
    print(f"Min MSE is {min_val} at p={mp}, l={ml}")

    xlabel = "log10(lambda-parameter)"
    ylabel = "log10(Error)" if args.log else "Error"
    title = f"Error using {args.method} and {args.resampling} iter = {args.resampling_iter}"

    if args.dataset == "SRTM":
        title = "Terrain data: " + title
    set_ax_info(ax, xlabel, ylabel, title)

    low = str(int(np.log10(args.lmb[0]))).replace("-", "m")
    high = str(int(np.log10(args.lmb[-1]))).replace("-", "m")
    fname = f"lambdaMSE_{args.method}_{args.resampling}{args.resampling_iter}_n{args.num_points}"
    fname += f"_eps{args.epsilon}_p{args.polynomial[-1]}_l{low}_{high}"
    fname = fname.replace(".", "")
    print('Plotting lambda_analysis: See %s.pdf' % (fname))
    show(fig, fname, args)

def Plot_VarOLS(args):
    """Here we plot the parameters for different polynomials
    with confidence intervals.
    """
    p = np.array([1, 3, 5])
    n = 30
    sigma_sq = 0.2
    x = np.sort(np.random.uniform(0, 1, n))
    y = np.sort(np.random.uniform(0, 1, n))
    x, y = np.meshgrid(x, y)
    z = utils.FrankeFunction(x, y, sigma_sq)
    X_ = utils.create_X(x, y, p[-1])
    for i in p:
        X = X_[:, :utils.get_features(i)]
        XTXinverse = np.linalg.pinv(X.T @ X)
        beta = XTXinverse @ X.T @ z
        variance_beta = sigma_sq*XTXinverse
        sigma_sq_beta = np.diag(variance_beta)
        upper = beta[:, 0] + 2*np.sqrt(sigma_sq_beta)
        lower = beta[:, 0] - 2*np.sqrt(sigma_sq_beta)
        beta_index = np.arange(0, len(beta), 1)
        fig, ax = plt.subplots()
        ax.scatter(beta_index, beta, label=r'$\beta$(index)')
        ax.fill_between(beta_index, lower, upper,
                        alpha=0.2, label=r'$\pm 2\sigma$')
        xlabel = r'index'
        ylabel = r'$\beta$'
        title = r'$\beta$-values with confidence interval for p = %i' % (i)
        set_ax_info(ax, xlabel, ylabel, title)
        fname = 'Var_OLS_poldeg_' + str(i)
        show(fig, fname, args)
        print('Plotting variance in beta: See ' + fname + '.pdf')

def Plot_BVT_lambda(result, args):
    """
    Plots BVT for as function of polynomial degree for different lambda
    """
    fig, ax = plt.subplots()

    P = args.polynomial

    # c = np.linspace(0, 1, len(args.lmb))
    c = [0.1, 0.3, 0.9]
    cmap = cm.jet
    for j, lmb in enumerate(args.lmb):
        ax.plot(P, result["test_errors"][:, j], c=cmap(
            c[j]), label=f"MSE, lambda: {lmb}")
        ax.plot(P, result["test_biases"][:, j],
                "--", c=cmap(c[j]), label="bias")
        ax.plot(P, result["test_vars"][:, j], "-.",
                c=cmap(c[j]), label="variance")

    xlabel = "Polynomial degree"
    ylabel = "Bias, variance and error"
    title = f"BV-tradeoff for {args.method} using {args.resampling} iter = {args.resampling_iter}"
    set_ax_info(ax, xlabel, ylabel, title)

    fname = f"LBVT_{args.method}_{args.resampling}_n{args.num_points}"
    fname += f"_eps{args.epsilon}_p{args.polynomial[-1]}"
    low = str(int(np.log10(args.lmb[0]))).replace("-", "m")
    high = str(int(np.log10(args.lmb[-1]))).replace("-", "m")
    fname += f"_lmb{low}_{high}"
    fname = fname.replace(".", "_")
    print("Plotting lambda BVT: see ", fname, ".pdf")

    fig.tight_layout()
    show(fig, fname, args)

def Plot_2D_MSE(results, args):
    """
    Plots contour map of MSE as function of polynomial degree and lambda
    """
    fig, ax = plt.subplots()
    P, lmb = np.meshgrid(args.polynomial, np.log10(args.lmb))
    MSE = results["test_MSE"].T
    if args.log:
        MSE = np.log10(MSE)
        title = "log10(MSE)"
    else:
        title = "MSE"

    min_val = np.min(MSE)
    min_l, min_P = np.where(MSE == min_val)
    min_P = args.polynomial[min_P[0]]
    min_l = np.log10(args.lmb[min_l[0]])
    print(f"Min MSE is {min_val} at p={min_P}, l={min_l}")

    F = ax.contourf(P, lmb, MSE, cmap="jet")
    norm = mpl.colors.Normalize(vmin=F.cvalues.min(), vmax=F.cvalues.max())
    bar = mpl.cm.ScalarMappable(norm=norm, cmap=F.cmap)
    bar.set_array([])
    cbar = fig.colorbar(bar, ticks=F.levels)
    cbar.set_label("log10(Error)" if args.log else "Error",
                   rotation=90, fontsize=20, position=(1, 0.5))

    ax.scatter(min_P, min_l, s=30, c="r", marker="x")

    xlabel = "Polynomial degree"
    ylabel = "log10(lambda)"
    title += f" for {args.method} using {args.resampling} iter = {args.resampling_iter}"
    set_ax_info(ax, xlabel, ylabel, title)

    fname = f"Contour_PL_{args.method}_{args.resampling}{args.resampling_iter}_n{args.num_points}_eps{args.epsilon}"
    ph = str(args.polynomial[-1])
    pl = str(args.polynomial[0])
    lh = str(int(np.log10(args.lmb[0]))).replace("-", "m")
    ll = str(int(np.log10(args.lmb[-1]))).replace("-", "m")
    fname += f"_p{pl}_{ph}_lmb{ll}_{lh}"

    show(fig, fname, args)

if __name__ == "__main__":
    """
    Here we can plot Franke function with or withot noise,
    simply change the self.epsilon value to the desired noise.
    Then run python3 plot.py, and it will generate a file with the appropriate
    name.
    """
    class Argparse:
        def __init__(self, eps=0):
            self.show = False
            self.epsilon = eps
            self.dataset = "Franke"

    N = 30
    x = np.sort(np.random.uniform(size=N))
    y = np.sort(np.random.uniform(size=N))
    x, y = np.meshgrid(x, y)
    args = Argparse()
    z = utils.FrankeFunction(x, y, eps=args.epsilon)


# Task2
from collections import deque

input_file_2 = open("Input2.txt", "r")
input_data_2 = input_file_2.readline().split(" ")
lst_2 = list(map(int, input_data_2))
input_lines_2 = input_file_2.read().split("\n")
arr_2 = []

for line_2 in input_lines_2:
    lst1_2 = line_2.split(" ")
    arr_2.append([int(lst1_2[0]), int(lst1_2[1])])

c = lst_2[0]
r = lst_2[1]
dict2 = {}

for i_2 in arr_2:
    if i_2[0] in dict2:
        lst_2 = dict2[i_2[0]] + [i_2[1]]
        dict2[i_2[0]] = lst_2
    else:
        dict2[i_2[0]] = [i_2[1]]
    if i_2[1] in dict2:
        lst_2 = dict2[i_2[1]] + [i_2[0]]
        dict2[i_2[1]] = lst_2
    else:
        dict2[i_2[1]] = [i_2[0]]

def bfs(dic, ind):
    queue = deque([ind])
    path = []
    while queue:
        node = queue.popleft()
        if node not in path:
            path.append(node)
            for i_2 in dic[node]:
                if i_2 not in path:
                    queue.append(i_2)
    return path

path_2 = bfs(dict2, 1)
output_2 = ""
i_2 = 0
while i_2 < len(path_2):
    output_2 += f"{path_2[i_2]} "
    i_2 += 1

output_file_2 = open("Output2.txt", "w")
output_file_2.write(output_2)
output_file_2.close()


class Solution:
    # idea hella stolen, really optimized though from 580ms to 232ms
    def findKthNumber(self, m: int, n: int, k: int) -> int:
        # iterates over the length of one side, faster if smaller side
        if m > n:
            m, n = n, m
        lo, hi = 1, m*n
        while lo < hi:
            mid = (lo+hi) >> 1

            # sum of numbers in column i that are smaller than mid
            # simplified from: for i in range(1, m+1): count += n if n < mid//i else mid//i
            midDivN = (mid//n)
            count = (n * midDivN) + sum(mid//i for i in range(midDivN + 1, m + 1))

            if count >= k:
                hi = mid
            else:
                lo = mid + 1
        return lo

Hard/668. Kth Smallest Number in Multiplication Table.py


class Solution:
    def sortSentence(self, s: str) -> str:
        output = ""
        sarray = s.split()

        # Loop through all 9 possible position words
        for i in range(1, 10):

            # Find ith position word in string
            for word in sarray:

                # Insert word to output string
                if word[-1] == str(i):
                    output += " " + word[:-1]

        return output.strip()


# Import the unittest module and the IncludeTemplate class
import sys
sys.path.append('.')
import os
import unittest
from template import IncludeTemplate

# Define a test case class that inherits from unittest.TestCase
class TestIncludeTemplate(unittest.TestCase):

    # Define a setup method that runs before each test
    def setUp(self):
        # Create some sample templates and mappings for testing
        self.template1 = IncludeTemplate("Hello, ${name}!")
        self.mapping1 = {"name": "Alice"}
        self.template2 = IncludeTemplate("This is a ${include:test.txt} template.")
        self.mapping2 = {"foo": "bar"}
        # Create a file named test.txt with some content
        os.makedirs("templates",exist_ok=True)
        with open("templates/test.txt", "w") as f:
            f.write("nested ${foo}")

    # Define a teardown method that runs after each test
    def tearDown(self):
        # Delete the file named test.txt
        import os
        os.remove("templates/test.txt")

    # Define a test method that checks the basic functionality of the substitute method
    def test_substitute_basic(self):
        # Call the substitute method on the first template and mapping
        result = self.template1.substitute(self.mapping1)
        # Assert that the result is equal to the expected string
        self.assertEqual(result, "Hello, Alice!")

    # Define a test method that checks the include functionality of the substitute method
    def test_substitute_include(self):
        # Call the substitute method on the second template and mapping
        result = self.template2.substitute(self.mapping2)
        # Assert that the result is equal to the expected string
        self.assertEqual(result, "This is a nested bar template.")

# Run the tests if this file is executed as a script
if __name__ == "__main__":
    unittest.main()


#!/usr/bin/python3

import csv
import os
import string
import sys

#   ------------------------------------------------
#                   BIOSANKEY
#
#   Last modification: 16 february 2018
#
#   ------------------------------------------------

def run(DEG_DIR, EXP_DIR):

	unit=["h","m","d","w"]

	def get_expr():
		p=0
		mm={}
		header=None
		with open(EXP_DIR, 'r') as csvfile:
			spamreader = csv.reader(csvfile, delimiter=';', quotechar='|')
			for vals in spamreader:
				if(p==0):
					header=[]
					for x in range(0,len(vals)):
						if(len(vals[x])>0):
							header.append(vals[x])
				else:
					for x in range(1,len(header)):
						if(mm.get(vals[0])==None):
							mm[vals[0]]={}
						mm[vals[0]][header[x]]=str(round(float(vals[x].replace(",",".")),2))
				p=p+1
		return(mm)
	my_expr=get_expr()

	def get_all_deg():
		MAIN=DEG_DIR
		files=os.listdir(MAIN)
		freq={}
		all={}
		my_files={}
		for files_ in files:
			if(files_.endswith(".dat")):
				my_files[files_.split("_")[0]]=1
				c_f=os.path.join(MAIN,files_)
				fh=open(c_f)
				for line in fh.readlines():
					line=line.strip()
					vals=line.split()
					cur_gene=vals[0]
					all[cur_gene]=1
		all=all.keys()
		fk=my_files.keys()
		fk2={}
		for fk_ in fk:
			fk_short=fk_
			for unit_ in unit:
				fk_short=fk_short.replace(unit_,"")
			fk2[int(fk_short)]=fk_
		return(all),(fk2)

	def DEG(r_id):
		fh=open("%s/%s" % (DEG_DIR,r_id))
		deg={}
		for line in fh.readlines():
			line=line.strip()
			vals=line.split()
			deg[vals[0]]=1
		return(deg.keys())

	def get_diff(A,B,C):
		col=[]
		for A_ in A:
			if(not(A_ in B) and not(A_ in C)):
				col.append(A_)
		return col

	def calc_intersect(A,B):
		col=[]
		for A_ in A:
			if(A_ in B):
				col.append(A_)
		return col

	(all,files)=get_all_deg()
	tpsort=files.keys()
	tpsort=list(tpsort)
	tpsort.sort()

	map={}
	for tpsort_ in tpsort:
		uid1="%s_up" % files[tpsort_]
		uid2="%s_down" % files[tpsort_]
		uid3="%s_LC" % files[tpsort_]
		map[uid1]=DEG(uid1+".dat")
		map[uid2]=DEG(uid2+".dat")
		map[uid3]=get_diff(all,map[uid1],map[uid2])

	def get_deg():
		cmd2=""
		for map_ in map:
			if(len(cmd2)==0):
				comma=""
			else:
				comma=","
				cmd2=cmd2+comma+"'"+map_+"'"+":"+"'"+string.join(map[map_],",")+"'"
		cmd2="var map2={"+cmd2+"}"
		cmd=""
		opt=["up","down","LC"]

		print(tpsort)

		for opt_ in opt:
			for x in range(0,len(tpsort)-1):
				A=calc_intersect(map[files[tpsort[x]]+"_"+opt_],map[files[tpsort[x+1]]+"_up"])
				cmd=cmd+"[%s,%s,%i]" % ("'"+files[tpsort[x]]+"_"+opt_+"'","'"+files[tpsort[x+1]]+"_up'",len(A))

				A=calc_intersect(map[files[tpsort[x]]+"_"+opt_],map[files[tpsort[x+1]]+"_down"])
				cmd=cmd+"[%s,%s,%i]" % ("'"+files[tpsort[x]]+"_"+opt_+"'","'"+files[tpsort[x+1]]+"_down'",len(A))

				A=calc_intersect(map[files[tpsort[x]]+"_"+opt_],map[files[tpsort[x+1]]+"_LC"])
				cmd=cmd+"[%s,%s,%i]" % ("'"+files[tpsort[x]]+"_"+opt_+"'","'"+files[tpsort[x+1]]+"_LC'",len(A))

		cmd=cmd.replace(",,",",").replace("][","],[")
		return cmd,cmd2
	return get_deg()


# Tune learning_rate
# 1. If the system is overlearning, decrease the learning rate and/or increase the number of trees.
# 2. If the system is underlearning, speed the learning up to be more aggressive by increasing the learning rate and/or decreasing the number of trees.
from numpy import loadtxt
from xgboost import XGBClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import StratifiedKFold
from pandas import read_csv
from matplotlib import pyplot

url2 = "http://archive.ics.uci.edu/ml/machine-learning-databases/statlog/heart/heart.dat"
names2 = [
    'age',
    'sex',
    'cp',
    'trestbps',
    'chol',
    'fbs',
    'restecg',
    'thalach',
    'exang',
    'oldpeak',
    'slope',
    'ca',
    'thal',
    'num',
]
classes=["absence", "presence"]

# Loading and centering the data
data2 = read_csv(url2, names=names2, sep=' ')
array = data2.values
X = array[:,0:13]
Y = array[:,13]

# grid search
model = XGBClassifier()
learning_rate = [0.0001, 0.001, 0.01, 0.1, 0.2, 0.06]
param_grid = dict(learning_rate=learning_rate)
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=7)
grid_search = GridSearchCV(model, param_grid, scoring="neg_log_loss", cv=kfold)
grid_result = grid_search.fit(X, Y)
# summarize results
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
for mean, stdev, param in zip(means, stds, params):
	print("%f (%f) with: %r" % (mean, stdev, param))


date = "Thursday 14/07/22"
print(date)

cleanest_cities = ["Cheyenne", "cheyenne", "Santa Fe", "santa fe", "Tucson", "tucson", "Great Falls", "great falls"]
city_to_check = input("Enter your city: ")
city_to_check = city_to_check.lower()
cleanest_cities = ["cheyenne", "santa fe", "tucson", "great falls"]
for a_clean_city in cleanest_cities:
    if city_to_check == a_clean_city:
        print("Its one of the cleanest cities")

lowercase_city_to_check = city_to_check.lower()

# Thursday 14/07/22
# Enter your city: santa fe
# Its one of the cleanest cities


from flask import Flask, request, jsonify
from flask_cors import CORS
import os, sys
from os import environ
import requests
from invokes import invoke_http
import amqp_setup
import pika
import json

app = Flask(__name__)
CORS(app)

notifications_URL = environ.get("notifications_URL") or "http://localhost:5007/notifications/"
facilities_URL = environ.get("facilities_URL") or "http://localhost:5002/updateAvailability/"

@app.route("/edit_facility", methods=['POST'])
def edit_facility():
    if request.is_json:
        try:
            edit = request.get_json()
            result = processEditFacility(edit, facilities_URL)
            code = result['code']
            message = json.dumps(result)
            if result['code'] == 200:
                # return jsonify({
                #     "code": 201,
                #     "data": result
                # }), 201
                print('\n\n-----Publishing the (notifications) message with routing_key=user.notifications-----')

                try:
                    amqp_setup.channel.basic_publish(exchange=amqp_setup.exchangename, routing_key="user.notifications", body=message, properties=pika.BasicProperties(delivery_mode = 2))
                    return jsonify({
                        "code": 200,
                        "message": "Message: Uploaded to DB"
                    }), 200

                except Exception as e:
                    return jsonify({
                        "code": 500,
                        "error": str(e)
                    }),500
            else:
                return jsonify({
                    "code": 501,
                    "result": result
                }), 501
        except Exception as e:
            return jsonify({
                "code": 502,
                "message": str(e)
            }), 502

def processEditFacility(edit, facilities_URL):
    facility_id = edit["facility_id"]
    messages = edit["messages"]
    print('\n-----Invoking facilities microservice-----')
    facilities_URL = facilities_URL + facility_id
    facilities_result = invoke_http(facilities_URL, method='PUT', json=edit)
    facilities_result['data']['messages'] = messages
    facilities_result['data']['receiver'] = "user"
    return(facilities_result)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5100, debug=True)


from enum import IntEnum
import functools
from itertools import zip_longest
from queue import deque

DEBUG = False

class AccesMode(IntEnum):
    READ = 0
    WRITE = 1

class AddressingMode(IntEnum):
    POSITION = 0
    IMMEDIATE = 1

def debug_fun(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kargs):
        #if DEBUG:
        #    print(f'DEBUG fn:{fn.__name__}, args:{args}, kargs={kargs}')
        #    return fn(*args, **kargs)
        return fn(*args, **kargs)

    return wrapper

class IntCode:

    def __init__(self, prg, cpu_id=-1):
        self.pc = 0
        self.input = deque()
        self.output = deque()
        self.last_output = -1
        self.is_running = True
        self.is_waiting = False
        self.is_halted = False
        self.cpu_id = cpu_id
        self.prg = prg.copy()
        self.instructions = {
            1:(self.op_add, AccesMode.READ, AccesMode.READ, AccesMode.WRITE),
            2:(self.op_mul, AccesMode.READ, AccesMode.READ, AccesMode.WRITE),
            3:(self.op_input, AccesMode.WRITE, ),
            4:(self.op_output, AccesMode.READ,),
            5:(self.op_jmp_not_zero, AccesMode.READ, AccesMode.READ),
            6:(self.op_jmp_zero, AccesMode.READ, AccesMode.READ),
            7:(self.op_less_than, AccesMode.READ, AccesMode.READ, AccesMode.WRITE),
            8:(self.op_equals, AccesMode.READ, AccesMode.READ, AccesMode.WRITE),
            99:(self.op_halt,),
        }
        self.value_fetchers = {
            AddressingMode.POSITION:self.position_fetcher,
            AddressingMode.IMMEDIATE:self.immediate_fetcher,
        }
        self.flags = {
            'jmp':False
        }

    def __repr__(self):
        return f'<{self.__class__.__name__} #{self.cpu_id} with input {list(self.input)}'\
            f' and output {list(self.output)}' \
            f' is {"not " if not self.is_running else ""}running' \
            f', is {"not " if not self.is_halted else ""}halted'\
            f', is {"not " if not self.is_waiting else ""}waiting' \
            f', last output was {self.last_output}' \
            f', pc is {self.pc}'\
            f', prg is {self.prg}>'

    @staticmethod
    @debug_fun
    def decode_opcode(opcode):
        if opcode <= 99:
            return ([opcode, ])
        _s=str(opcode)
        # _s[-2:] gets 2 rightmost digits
        # _s[:-2][::-1] gets leftmost digits and reverse them
        return ([int(_s[-2:])] + list(map(lambda i:
                                          AddressingMode(int(i)),
                                          list(_s[:-2][::-1]))))

    @debug_fun
    def position_fetcher(self, addr):
        return self.prg[addr]

    @debug_fun
    def immediate_fetcher(self, val):
        return val

    @debug_fun
    def fn_fetch_value(self, mode):
        return self.value_fetchers[mode[0] + mode[1]]

    @debug_fun
    def fetch_values(self, modes):
        res = []
        for mode in modes:
            res.append(self.fn_fetch_value(mode)(self.prg[self.pc + 1]))
            self.inc()
        return res

    @debug_fun
    def inc(self, i=1):
        self.pc += i

    @debug_fun
    def jmp(self, addr):
        self.pc = addr

    @debug_fun
    def op_add(self, operands):
        v1, v2, addr = operands
        self.prg[addr] = v1 + v2
        self.inc()

    @debug_fun
    def op_mul(self, operands):
        v1, v2, addr = operands
        self.prg[addr] = v1 * v2
        self.inc()

    @debug_fun
    def op_input(self, operands):
        addr = operands.pop()
        if len(self.input) == 0:
            self.is_waiting = True
            self.inc(-1)
            return
        self.prg[addr] = self.input.popleft()
        self.inc()

    @debug_fun
    def op_output(self, operands):
        v = operands.pop()
        self.output.append(v)
        self.last_output = self.output[-1]
        self.inc()
        self.is_waiting = True

    @debug_fun
    def op_jmp_not_zero(self, operands):
        v1, addr = operands
        if v1 != 0:
            self.jmp(addr)
        else:
            self.inc()

    @debug_fun
    def op_jmp_zero(self, operands):
        v1, addr = operands
        if v1 == 0:
            self.jmp(addr)
        else:
            self.inc()

    @debug_fun
    def op_less_than(self, operands):
        v1, v2, addr = operands
        self.prg[addr] = 1 if v1 < v2 else 0
        self.inc()

    @debug_fun
    def op_equals(self, operands):
        v1, v2, addr = operands
        self.prg[addr] = 1 if v1 == v2 else 0
        self.inc()

    @debug_fun
    def op_halt(self, _):
        self.is_running = False
        self.is_halted = True

    def run(self, input):
        self.input = deque(input)
        if self.is_halted:
            print("IntCode computer is halted.")
            return
        self.is_waiting = False
        if DEBUG: print(f'Running {self}')
        while self.is_running and not self.is_waiting:
            self.flags['jmp'] = False
            # Get OpCode and addressing modes
            opcode, *addressing_modes=IntCode.decode_opcode(self.prg[self.pc])
            # Get operation and its operands access modes
            op, *opmodes = self.instructions[opcode]
            if DEBUG: print(80*'*')
            if DEBUG: print(f'DEBUG CPU #{self.cpu_id} pc:{self.pc}, prg:{self.prg}')
            if DEBUG: print(f'DEBUG CPU #{self.cpu_id} opcode: {opcode}, op:{op.__name__}')
            if DEBUG: print(f'DEBUG CPU #{self.cpu_id} opcode:{opmodes}, addressing_modes:{addressing_modes}')
            # Associate each operand acces mode with its addressing mode
            modes = list(zip_longest(opmodes, addressing_modes,
                                     fillvalue=AddressingMode.POSITION))
            if DEBUG: print(f'DEBUG CPU #{self.cpu_id} mode:{modes}')
            op(self.fetch_values(modes))
            if DEBUG: print(f'State {self}')
        return self.last_output

if __name__ == '__main__':
    # Day 2
    test='Day 2 - Test 1'
    IntCode([1,9,10,3,2,3,11,0,99,30,40,50]).run([])
    print(f'{test} OK')
    test='Day 2 - Test 2'
    IntCode([1,0,0,0,99]).run([])
    print(f'{test} OK')
    test='Day 2 - Test 3'
    IntCode([2,3,0,3,99]).run([])
    print(f'{test} OK')
    test='Day 2 - Test 4'
    IntCode([2,4,4,5,99,0]).run([])
    print(f'{test} OK')
    test='Day 2 - Test 5'
    IntCode([1,1,1,4,99,5,6,0,99]).run([])
    print(f'{test} OK')

    # Day 5 tests
    # Equals 8 ?
    test='Day 5 - Test 1.1 - Input equals 8? (Position mode)'
    assert 1 == IntCode([3,9,8,9,10,9,4,9,99,-1,8]).run([8]), f'{test} KO'
    print(f'{test} OK')
    test='Day 5 - Test 1.2 - Input equals 8? (Position mode)'
    assert 0 == IntCode([3,9,8,9,10,9,4,9,99,-1,8]).run([5]), f'{test} KO'
    print(f'{test} OK')

    # Less than 8 ?
    test='Day 5 - Test 2.1 - Input less than 8? (Position mode)'
    assert 0 == IntCode([3,9,7,9,10,9,4,9,99,-1,8]).run([8]), f'{test} KO'
    print(f'{test} OK')
    test='Day 5 - Test 2.2 - Input less than 8? (Position mode)'
    assert 1 == IntCode([3,9,7,9,10,9,4,9,99,-1,8]).run([5]), f'{test} KO'
    print(f'{test} OK')

    # Equals 8 ?
    test='Day 5 - Test 3.1 - Input equals 8? (Immediate mode)'
    assert 1 == IntCode([3,3,1108,-1,8,3,4,3,99]).run([8]), f'{test} KO'
    print(f'{test} OK')
    test='Day 5 - Test 3.2 - Input equals 8? (Immediate mode)'
    assert 0 == IntCode([3,3,1108,-1,8,3,4,3,99]).run([5]), f'{test} KO'
    print(f'{test} OK')

    # Less than 8 ?
    test='Day 5 - Test 4.1 - Input less than 8? (Immediate mode)'
    assert 0 == IntCode([3,3,1107,-1,8,3,4,3,99]).run([8]), f'{test} KO'
    print(f'{test} OK')
    test='Day 5 - Test 4.2 - Input less than 8? (Immediate mode)'
    assert 1 == IntCode([3,3,1107,-1,8,3,4,3,99]).run([5]), f'{test} KO'
    print(f'{test} OK')

    # Zero ?
    test='Day 5 - Test 5.1 - Input is 0? (Position mode)'
    assert 0 == IntCode([3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9]).run([0]), f'{test} KO'
    print(f'{test} OK')
    test='Day 5 - Test 5.2 - Input is 0? (Position mode)'
    assert 1 == IntCode([3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9]).run([1]), f'{test} KO'
    print(f'{test} OK')

    # Zero ?
    test='Day 5 - Test 6.1 - Input is 0? (Immediate mode)'
    assert 0 == IntCode([3,3,1105,-1,9,1101,0,0,12,4,12,99,1]).run([0]), f'{test} KO'
    print(f'{test} OK')
    test='Day 5 - Test 6.2 - Input is 0? (Immediate mode)'
    assert 1 == IntCode([3,3,1105,-1,9,1101,0,0,12,4,12,99,1]).run([1]), f'{test} KO'
    print(f'{test} OK')

    # Compare to 8
    test='Day 5 - Test 7.1 - Compare to 8'
    assert 999 == IntCode([3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,
             1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,
             999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99]).run([7]), f'{test} KO'
    print(f'{test} OK')
    test='Day 5 - Test 7.2 - Compare to 8'
    assert 1000 == IntCode([3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,
             1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,
             999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99]).run([8]), f'{test} KO'
    print(f'{test} OK')
    test='Day 5 - Test 7.3 - Compare to 8'
    assert 1001 == IntCode([3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,
             1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,
             999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99]).run([9]), f'{test} KO'
    print(f'{test} OK')

    # Amplifier
    test='Day 7 - Test 1.1 - Amplifier Feedback'
    assert 5 == IntCode([3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,
                         27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5]).run([9, 0]), f'{test} KO'
    assert 7 == IntCode([3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,
                         27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5]).run([9, 1]), f'{test} KO'


# From https://github.com/okfn/dptools/blob/master/bin/load-sqlite.py
# No license given in original. Since OKFN assumed to be have open source license.
#
# Edits by Jeffrey Arnold (2014), BSD-3
#
# - converted to Python 3
#
'''Command line tool to load a Simple Data Format Data Package into sqlite.

For usage do:

    python load-sqlite.py -h
'''
import json
import argparse
import urllib.parse
import os
import sqlite3
import urllib.request, urllib.parse, urllib.error
import urllib.request, urllib.error, urllib.parse
import csv
import codecs

# http://www.sqlite.org/datatype3.html
mappings = {
    'string': 'text',
    'number': 'real',
    'float': 'real',
    'integer': 'integer',
    'date': 'string',
    'boolean': 'integer',
    'date': 'date',
    'datetime': 'datetime'
    }

def load(dpurlOrPath, sqlitePath):
    if not dpurlOrPath.split('://')[0] in ['http', 'https', 'ftp']:
        # it's a path
        dpurl = path2url(dpurlOrPath)
    else:
        dpurl = dpurlOrPath
    # urljoin makes this work right -
    # http://docs.python.org/2/library/urlparse.html#urlparse.urljoin
    dpurl = urllib.parse.urljoin(dpurl, 'datapackage.json')
    basepath = dpurlOrPath.rstrip('datapackage.json')
    dpfo = urllib.request.urlopen(dpurl)
    reader = codecs.getreader("utf-8")
    out = json.load(reader(dpfo))
    for finfo in out['resources']:
        # normalization so we do not have to handle both alternatives
        if not 'url' in finfo:
            finfo['url'] = urllib.parse.urljoin(dpurl, finfo['path'])
        process_resource(finfo, sqlitePath)

def process_resource(finfo, dbpath):
    '''Load the resource specified by finfo into the database at dbpath
    '''
    if 'name' in finfo:
        tablename = finfo['name']
    else:
        _fname = urllib.parse.urlparse(finfo.get('url', ''))[2].split('/')[-1]
        tablename = os.path.splitext(_fname)[0]
    fields = finfo['schema']['fields']
    _columns = ','.join(
            ['"%s" %s' % (field['id'], mappings[field['type']])
                for field in fields]
            )
    conn = sqlite3.connect(dbpath)
    c = conn.cursor()
    sql = 'CREATE TABLE "%s" (%s)' % (tablename, _columns)
    c.execute(sql)

    _insert_tmpl = 'insert into "%s" values (%s)' % (tablename,
                ','.join(['?']*len(fields)))

    # could do this on but not very robust and will not work on remote urls ...
    # sqlite> .mode csv
    # sqlite> .import <filename> <table>
    req = urllib.request.urlopen(finfo['url'])
    reader = csv.reader(req.read().decode('utf-8').splitlines())
    # skip headers
    for row in reader:
        c.execute(_insert_tmpl, row)
    conn.commit()
    c.close()

def path2url(path):
    return urllib.parse.urljoin(
        'file:', urllib.request.pathname2url(os.path.abspath(path))
        )

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Load a data package into sqlite.')
    parser.add_argument('datapackage',
                       help='path to datapackage')
    parser.add_argument('sqlite',
                       help='path to sqlite db')
    args = parser.parse_args()
    load(args.datapackage, args.sqlite)


from future_diffusion.disco import *
import subprocess
import torch
import cv2
import gc
import math
import requests
from glob import glob
from types import SimpleNamespace
from torch.nn import functional as F
import torchvision.transforms as T
from CLIP import clip
import torchvision.transforms.functional as TF
from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults
import random
if is_colab:
    os.chdir('/content')
    from google.colab import files
else:
    os.chdir(f'{PROJECT_DIR}')
from IPython.display import Image as ipyimg
from numpy import asarray
import torch
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
import GPUtil
from pynvml import *

nvmlInit()
# SimpleNamespace(**self.args)

def getClipModels(args):
    print('cip models', args)
    clip_models = []
    if args.ViTB32 is True: clip_models.append(clip.load('ViT-B/32', jit=False)[0].eval().requires_grad_(False).to(device))
    if args.ViTB16 is True: clip_models.append(clip.load('ViT-B/16', jit=False)[0].eval().requires_grad_(False).to(device) )
    if args.ViTL14 is True: clip_models.append(clip.load('ViT-L/14', jit=False)[0].eval().requires_grad_(False).to(device) )
    if args.RN50 is True: clip_models.append(clip.load('RN50', jit=False)[0].eval().requires_grad_(False).to(device))
    if args.RN50x4 is True: clip_models.append(clip.load('RN50x4', jit=False)[0].eval().requires_grad_(False).to(device))
    if args.RN50x16 is True: clip_models.append(clip.load('RN50x16', jit=False)[0].eval().requires_grad_(False).to(device))
    if args.RN50x64 is True: clip_models.append(clip.load('RN50x64', jit=False)[0].eval().requires_grad_(False).to(device))
    if args.RN101 is True: clip_models.append(clip.load('RN101', jit=False)[0].eval().requires_grad_(False).to(device))

    return clip_models

class DiscoModel():
    def __init__(self):
        self.intermediate_saves = 0#@param{type: 'raw'}
        self.intermediates_in_subfolder = True #@param{type: 'boolean'}
        self.diffusion_sampling_mode = 'ddim'
        self.use_secondary_model = True
        self.use_checkpoint = True
        self.diffusion_model = "512x512_diffusion_uncond_finetune_008100"
        self.model_config = model_and_diffusion_defaults()
        self.model_config.update({
            'attention_resolutions': '32, 16, 8',
            'class_cond': False,
            'diffusion_steps': 1000, #No need to edit this, it is taken care of later.
            'rescale_timesteps': True,
            'timestep_respacing': 250, #No need to edit this, it is taken care of later.
            'image_size': 512,
            'learn_sigma': True,
            'noise_schedule': 'linear',
            'num_channels': 256,
            'num_head_channels': 64,
            'num_res_blocks': 2,
            'resblock_updown': True,
            'use_checkpoint': True,
            'use_fp16': True,
            'use_scale_shift_norm': True,
        })

        self.models = {
            'ViTB32': True,
            'ViTB16': False,
            'ViTL14': False,
            'RN101': False,
            'RN50': False,
            'RN50x4': False,
            'RN50x16': False,
            'RN50x64': False
        }
        self.models = SimpleNamespace(**self.models)

        self.clip_models = getClipModels(self.models)

        model_default = self.model_config['image_size']
        self.animation_mode = 'None'
        #@markdown ####**Basic Settings:**
        self.batch_name = 'TimeToDisco' #@param{type: 'string'}
        self.steps = 250 #@param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true}
        self.width_height = [512, 512]#@param{type: 'raw'}
        self.clip_guidance_scale = 5000 #@param{type: 'number'}
        self.tv_scale =  0#@param{type: 'number'}
        self.range_scale =   150#@param{type: 'number'}
        self.sat_scale =   0#@param{type: 'number'}
        self.cutn_batches = 1  #@param{type: 'number'}
        self.skip_augs = False#@param{type: 'boolean'}

        #@markdown ---

        #@markdown ####**Init Settings:**
        self.init_image = None #@param{type: 'string'}
        self.init_scale = 2000 #@param{type: 'integer'}
        self.skip_steps = 125 #@param{type: 'integer'}
        #@markdown *Make sure you set skip_steps to ~50% of your steps if you want to use an init image.*

        #Get corrected sizes
        self.side_x = (self.width_height[0]//64)*64;
        self.side_y = (self.width_height[1]//64)*64;
        if self.side_x != self.width_height[0] or self.side_y != self.width_height[1]:
          print(f'Changing output size to {self.side_x}x{self.side_y}. Dimensions must by multiples of 64.')

        #Update Model Settings
        self.timestep_respacing = f'ddim{self.steps}'
        self.diffusion_steps = (1000//self.steps)*self.steps if self.steps < 1000 else self.steps
        self.model_config.update({
            'timestep_respacing': self.timestep_respacing,
            'diffusion_steps': self.diffusion_steps,
        })

        #Make folder for batch
        self.batchFolder = f'{outDirPath}/{self.batch_name}'
        createPath(self.batchFolder)

        if type(self.intermediate_saves) is not list:
          if self.intermediate_saves:
            self.steps_per_checkpoint = math.floor((self.steps - self.skip_steps - 1) // (self.intermediate_saves+1))
            self.steps_per_checkpoint = self.steps_per_checkpoint if self.steps_per_checkpoint > 0 else 1
            print(f'Will save every {self.steps_per_checkpoint} steps')
          else:
            self.steps_per_checkpoint = self.steps+10
        else:
          self.steps_per_checkpoint = None

        if self.intermediate_saves and self.intermediates_in_subfolder is True:
          partialFolder = f'{self.batchFolder}/partials'
          createPath(partialFolder)

        self.args = None

        self.perlin_init = False  #@param{type: 'boolean'}
        self.perlin_mode = 'mixed' #@param ['mixed', 'color', 'gray']
        self.set_seed = 'random_seed' #@param{type: 'string'}
        self.eta = 0.8#@param{type: 'number'}
        self.clamp_grad = True #@param{type: 'boolean'}
        self.clamp_max = 0.05 #@param{type: 'number'}

        ### EXTRA ADVANCED SETTINGS:
        self.randomize_class = True
        self.clip_denoised = False
        self.fuzzy_prompt = False
        self.rand_mag = 0.05

        self.cut_overview = "[12]*400+[4]*600" #@param {type: 'string'}
        self.cut_innercut ="[4]*400+[12]*600"#@param {type: 'string'}
        self.cut_ic_pow = 1#@param {type: 'number'}
        self.cut_icgray_p = "[0.2]*400+[0]*600"#@param {type: 'string'}

        self.text_prompts = {
            0: None
        }

        self.image_prompts = {
            # 0:['ImagePromptsWorkButArentVeryGood.png:2',],
        }

        """# 4. Diffuse!"""

        #@title Do the Run!
        #@markdown `n_batches` ignored with animation modes.
        self.display_rate =  15 #@param{type: 'number'}
        self.n_batches =  1 #@param{type: 'number'}

        random.seed()
        self.seed = random.randint(0, 2**32)

        #Update Model Settings
        self.timestep_respacing = f'ddim{self.steps}'
        self.diffusion_steps = (1000//self.steps)*self.steps if self.steps < 1000 else self.steps
        self.model_config.update({
            'timestep_respacing': self.timestep_respacing,
            'diffusion_steps': self.diffusion_steps,
        })

        self.batch_size = 1

        print('Prepping model...')
        self.model, self.diffusion = create_model_and_diffusion(**self.model_config)
        self.model.load_state_dict(torch.load(f'{model_path}/{diffusion_model}.pt', map_location='cpu'))
        self.model.requires_grad_(False).eval().to(device)
        self.isBusy = False
        for name, param in self.model.named_parameters():
            if 'qkv' in name or 'norm' in name or 'proj' in name:
                param.requires_grad_()
        if self.model_config['use_fp16']:
            self.model.convert_to_fp16()

        self.resume_run = False #@param{type: 'boolean'}
        self.run_to_resume = 'latest' #@param{type: 'string'}
        self.resume_from_frame = 'latest' #@param{type: 'string'}
        self.retain_overwritten_frames = False #@param{type: 'boolean'}
        if self.retain_overwritten_frames is True:
          self.retainFolder = f'{self.batchFolder}/retained'
          createPath(self.retainFolder)

        self.skip_step_ratio = int(frames_skip_steps.rstrip("%")) / 100
        self.calc_frames_skip_steps = math.floor(self.steps * self.skip_step_ratio)

        self.base_init_path = "init_images"

        if self.steps <= self.calc_frames_skip_steps:
          sys.exit("ERROR: You can't skip more steps than your total steps")

    def move_files(self, start_num, end_num, old_folder, new_folder):
        for i in range(start_num, end_num):
            old_file = old_folder + f'/{self.batch_name}({self.batchNum})_{i:04}.png'
            new_file = new_folder + f'/{self.batch_name}({self.batchNum})_{i:04}.png'
            os.rename(old_file, new_file)

  #@markdown ---

    def showUtilizationGPU(self):
        h = nvmlDeviceGetHandleByIndex(0)
        info = nvmlDeviceGetMemoryInfo(h)
        print(f'total    : {info.total}')
        print(f'free     : {info.free}')
        print(f'used     : {info.used}')
        print()
        print()
        GPUtil.showUtilization()

    def isModelBusy(self):
      return self.isBusy

    def settings(self, id, prompt, init_image,init_scale ,skip_steps ,width ,height ,clip_guidance_scale ,tv_scale ,sat_scale,range_scale, cutn_batches):
      import re
      import urllib

      urls = []

      print("INIT IMAHE:: ", init_image, type(init_image), init_image == "")

      if init_image != "":
          print("USING RE", init_image != "")
          urls = re.findall('https?://+', init_image)

      if urls==[]:
        init_image = None

      counter = 0
      retrieved_image = False

      print("After all, init image:", init_image, urls)

      while True and counter!=3 and init_image:
        try:
          imgURL = init_image
          response = requests.get(imgURL)
          if response.status_code == 200:
              file_path = os.path.join(self.base_init_path, f"{id}.png")
              Path(file_path).touch()
              with open(file_path, 'wb') as f:
                  f.write(response.content)
              retrieved_image = True
              break
          else:
            raise Exception
        except Exception as e:
          print("Failure to download {} : {}".format(imgURL, e))
          print("Retrying download: {}/3".format(counter))
          print()
          try:
            open(file_path, 'a').close()
          except Exception as e:
            print("opening file failed.. skipping.")
            pass

        counter+=1

      if not retrieved_image and init_image:
        raise Exception("Failed to retrieved init image... passing.")

      if init_image:
        init_image = f"init_images/{id}.png"

      image_prompts = {}

      self.text_prompts[0] = prompt

      start_frame = 0
      batchNum = len(glob(self.batchFolder+"/*.txt"))
      while os.path.isfile(f"{self.batchFolder}/{self.batch_name}({batchNum})_settings.txt") is True or os.path.isfile(f"{self.batchFolder}/{self.batch_name}-{batchNum}_settings.txt") is True:
        batchNum += 1

      print(f'Starting Run: {self.batch_name}({batchNum}) at frame {start_frame}')

      print("SKIP_STEPS == ", skip_steps)

      self.args = {
          'batchNum': batchNum,
          'id' : id,
          'model' : self.model,
          'diffusion' : self.diffusion,
          'clip_models': self.clip_models,
          'prompts_series':split_prompts(self.text_prompts) if self.text_prompts else None,
          'image_prompts_series':split_prompts(image_prompts) if image_prompts else None,
          'seed': self.seed,
          'display_rate':self.display_rate,
          'n_batches':self.n_batches if self.animation_mode == 'None' else 1,
          'batch_size':self.batch_size,
          'batch_name': self.batch_name,
          'steps': self.steps,
          'diffusion_sampling_mode': self.diffusion_sampling_mode,
          'width_height': [width,height],
          'clip_guidance_scale': clip_guidance_scale,
          'tv_scale': tv_scale,
          'range_scale': range_scale,
          'sat_scale': sat_scale,
          'cutn_batches': cutn_batches,
          'init_image': init_image,
          'init_scale': init_scale,
          'skip_steps': skip_steps,
          'side_x': (int(width)//64)*64,
          'side_y':(int(height)//64)*64,
          'timestep_respacing': self.timestep_respacing,
          'diffusion_steps': self.diffusion_steps,
          'animation_mode': self.animation_mode,
          'video_init_path': video_init_path,
          'extract_nth_frame': extract_nth_frame,
          'video_init_seed_continuity': video_init_seed_continuity,
          'key_frames': key_frames,
          'max_frames': max_frames if self.animation_mode != "None" else 1,
          'interp_spline': interp_spline,
          'start_frame': start_frame,
          'midas_depth_model': midas_depth_model,
          'midas_weight': midas_weight,
          'near_plane': near_plane,
          'far_plane': far_plane,
          'fov': fov,
          'padding_mode': padding_mode,
          'sampling_mode': sampling_mode,
          'frames_scale': frames_scale,
          'calc_frames_skip_steps': self.calc_frames_skip_steps,
          'skip_step_ratio': self.skip_step_ratio,
          'calc_frames_skip_steps': self.calc_frames_skip_steps,
          'text_prompts': self.text_prompts,
          'image_prompts': image_prompts,
          'use_secondary_model': self.use_secondary_model,
          'cut_overview': eval(self.cut_overview),
          'cut_innercut': eval(self.cut_innercut),
          'cut_ic_pow': self.cut_ic_pow,
          'cut_icgray_p': eval(self.cut_icgray_p),
          'intermediate_saves': self.intermediate_saves,
          'intermediates_in_subfolder': self.intermediates_in_subfolder,
          'steps_per_checkpoint': self.steps_per_checkpoint,
          'perlin_init': self.perlin_init,
          'perlin_mode': self.perlin_mode,
          'set_seed': self.set_seed,
          'eta': self.eta,
          'clamp_grad': self.clamp_grad,
          'clamp_max': self.clamp_max,
          'skip_augs': self.skip_augs,
          'randomize_class': self.randomize_class,
          'clip_denoised': self.clip_denoised,
          'fuzzy_prompt': self.fuzzy_prompt,
          'rand_mag': self.rand_mag,
      }

      # print(self.args)

      # print("**", self.args['init_image'])

      self.args = SimpleNamespace(**self.args)

    def runModel(self):
        self.showUtilizationGPU()
        print("Run model.. setting is busy to True!")
        self.isBusy = True
        gc.collect()
        torch.cuda.empty_cache()

        print(f"Running model with width: {self.args.width_height[0]} and height {self.args.width_height[0]}")
        print("About to run model..")
        do_run(self.args)
        print("Setting is busy to false!")
        self.showUtilizationGPU()
        self.isBusy = False
        print('Seed used:', self.seed)
        gc.collect()
        torch.cuda.empty_cache()
        res = subprocess.check_output(["nvidia-smi",  "-L"])
        print(res)


from util import *

import logging as log

log.basicConfig(level=log.INFO)

server = IPC(type = zmq.REP)
variables = {'': 0}
variables['bump'] = [0,0]

while(True):
	data = server.get()
	#print("data")

	if (data != None):
		#print(data)

		if (data[1] != -1):
			variables[data[0]] = data[1]

		server.send(variables[data[0]])

server.close()


from django.shortcuts import render
from rest_framework.views import APIView
from .models import Category, Product, Review, Tag
from .serializers import (
    CategorySerializer,
    ProductSerializer,
    ReviewSerializer,
    TagSerializer,
    SaleSerializer,
)
from rest_framework.request import Request
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from django.db.models import Q, F, Count
from datetime import date
from distutils.util import strtobool
import json

# Create your views here.
class CategoriesView(APIView):
    def get(self, request):
        categories = Category.objects.all()
        serialized = CategorySerializer(categories, many=True)
        return Response(serialized.data)

class ProductIdView(APIView):
    def get(self, request, id):
        product = get_object_or_404(Product, pk=id)
        serialized = ProductSerializer(product)
        return Response(serialized.data)

class ProductIdReviewView(APIView):
    def post(self, request, id):
        product = get_object_or_404(Product, pk=id)
        data = request.data
        review = Review.objects.create(
            author=data["author"],
            email=data["email"],
            text=data["text"],
            rate=data["rate"],
            date=date.today(),
        )
        review.save()
        product.reviews.add(review)
        serialized = ReviewSerializer(review)
        return Response(serialized.data)

class TagView(APIView):
    def get(self, request):
        tag = Tag.objects.all()
        serialized = TagSerializer(tag, many=True)
        return Response(serialized.data)

class CatalogView(APIView):
    def get(self, request):
        d = {"inc": "-", "dec": ""}
        name = request.GET.get("filter[name]")
        min_price = request.GET.get("filter[minPrice]")
        max_price = request.GET.get("filter[maxPrice]")
        free_delivery = request.GET.get("filter[freeDelivery]")
        available = request.GET.get("filter[available]")
        current_page = request.GET.get("currentPage")
        sort = request.GET.get("sort")
        sort_type = request.GET.get("sortType")
        limit = request.GET.get("limit")
        # print(
        # f"name: {name}\nmin_price: {min_price}\nmax_price: {max_price}\nfree_delivery: {free_delivery}\navailable: {available}\ncurrent_page: {current_page}\nsort: {sort}\nsort_type: {sort_type}\nlimit: {limit}"
        # )
        products = Product.objects.all().order_by(f"{d[sort_type]}{sort}")

        if available == "true":
            avail_filter = Q(count__gt=0)
        elif available == "false":
            avail_filter = Q(count__lte=0)

        if name:
            name_filter = Q(title__icontains=name)
        else:
            name_filter = Q()

        products = products.filter(
            Q(price__gte=min_price),
            Q(price__lte=max_price),
            Q(freeDelivery=strtobool(free_delivery)),
            avail_filter,
            name_filter,
        )

        serialized = ProductSerializer(products, many=True)
        for d in serialized.data:
            d["reviews"] = len(d["reviews"])
        return Response(
            {"items": serialized.data, "current_page": current_page, "last_page": 10}
        )

class ProductPopularView(APIView):
    def get(self, request):
        products = Product.objects.annotate(num_reviews=Count("reviews")).order_by(
            "-num_reviews", "-rating"
        )
        serialized = ProductSerializer(products, many=True)
        for d in serialized.data:
            d["reviews"] = len(d["reviews"])
        return Response(serialized.data)

class ProductLimitedView(APIView):
    def get(self, request):
        products = Product.objects.filter(Q(count__gt=0), Q(count__lt=4))
        serialized = ProductSerializer(products, many=True)
        for d in serialized.data:
            d["reviews"] = len(d["reviews"])
        return Response(serialized.data)

class BannerView(APIView):
    def get(self, request):
        products = Product.objects.all()
        serialized = ProductSerializer(products, many=True)
        for d in serialized.data:
            d["reviews"] = len(d["reviews"])
        return Response(serialized.data)

class SaleView(APIView):
    def get(self, request):
        current_page = request.GET.get("currentPage")
        products = [product for product in Product.objects.all() if product.sale]
        serialized = SaleSerializer(products, many=True)
        return Response(
            {"items": serialized.data, "current_page": current_page, "last_page": 10}
        )


####################################################################################################################
####################################################################################################################
#########################                                                                  #########################
#########################            PLD Kinetic Monte Carlo Processes Module              #########################
#########################                                                                  #########################
####################################################################################################################
####################################################################################################################

"""
Kinetic Monte Carlo Processes Module

Contains code to create the rate catalog for thermal processes

Version: 3.4.1a

"""

# import modules
import numpy as np
from scipy.constants import physical_constants, convert_temperature

#################################
###   Process Catalog Class   ###
#################################
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------

class Process_Catalog:
    """
    Class to set up elementary processes and rates. Sets the order of Process Table and Process Lists.

    This class sets the order in the process table and corresponding moves.

    Future Goal is to be able to set processes here and have the main code automatically adapt. Not there yet.
    If changes are made here, the corresponding change must be made in corresponding "Processes" class.

    Inputs
    -------
    parameters:  activation energies and substrate temperature

    Methods:
    --------
    Create_Catalog:   Selects the process catalog based on parameter inputs
    Return_Rates:     Returns the rate_catalog, rates, moves, and keys
    Deposition_2D:
    Deposition_3D:

    Outputs
    -------
    rate_catalog:  Dictionary of Rate Names and Values
    rates:         Ordered Array of all elementary process rates
    moves:         Associated lattice moves that go with rates.
    keys:          Ordered list of keys corresponding to the rates array
    numProc:       Number of Processes for each direction (Primary and Secondary Moves)

    """

    def __init__(self,Parameters):
        self.Parameters = Parameters

        self.dim = Parameters['Dimension']
        self.type = Parameters['Simulation_Type']

        self.w0 = Parameters['w0']
        self.temperature = self.Parameters['Substrate_Temperature']

        self.diff = Parameters['Ea_diffusion']
        self.es = Parameters['Ea_ehrlich_schwoebel']
        self.detach = Parameters['Ea_detach']
        self.edge = Parameters['Ea_edge']
        self.corner = Parameters['Ea_corner']

        # constants
        self.tk = convert_temperature(self.temperature,'Celsius', 'Kelvin')
        self.kB = physical_constants[ 'Boltzmann constant in eV/K' ][0]
        self.kT = self.tk*self.kB  # in eV

        self.Create_Catalog()

    def Create_Catalog(self):
        """ Determine which catalog to create and create it """
        if self.type == 'Deposition' or self.type == 'Diffusion' or self.type == 'Density':
            if self.dim == '2D':
                self.Simulation_2D()
            elif self.dim == '3D':
                self.Simulation_3D()
        elif self.type == 'Ising':
            self.Ising_2D()

    def Return_Rates(self):
        """ Return the calculated rates """

        return (self.rate_catalog,self.rates,self.moves,self.keys,self.num_barriers_per_move)

    def Simulation_2D(self):
        """ Set up Process Table for 2D Deposition (1+1) """

        # Set Primary and Secondary Moves (order based on first secondary move being to the left of the primary move)
        Moves = ['Left','Left_Down','Left_Up',\
                 'Up','Up_Left','Up_Right',\
                 'Right','Right_Up','Right_Down',\
                 'Down','Down_Right','Down_Left']
        Moves_X = [-1,-1,-1,\
                   0,-1,1,\
                   1,1,1,\
                   0,1,-1]
        Moves_Z = [0,-1,1,\
                   1,1,1,\
                   0,1,-1,\
                   -1,-1,-1]

        # Set Barriers for Primary and Secondary Moves (name should include each barrier present)
        Primary = ['Diff','Diff_Detach1','Diff_Detach2','Edge2','Edge2_Detach1']
        Secondary = ['Diff_ES', 'Diff_Detach1_ES', 'Diff_Detach2_ES']

        Barriers = [Primary,Secondary,Secondary,Primary,Secondary,Secondary,Primary,Secondary,Secondary,Primary,Secondary,Secondary]

        self.num_barriers_per_move = len(Primary)+len(Secondary)+len(Secondary) # number of processes per primary move

        # Create Rate Catalog (keys must match the Barriers)
        self.rate_catalog = {}
        self.rate_catalog['Diff'] = self.w0*np.exp(-self.diff/self.kT)   # free edge diffusion
        self.rate_catalog['Diff_Detach1'] = self.w0*np.exp(-(self.detach+self.diff)/self.kT)  # detach from kink
        self.rate_catalog['Diff_Detach2'] = self.w0*np.exp(-(2*self.detach+self.diff)/self.kT)  # detach from edge
        self.rate_catalog['Edge2'] = self.w0*np.exp(-(self.edge+self.diff)/self.kT)  # two edge diffusion
        self.rate_catalog['Edge2_Detach1'] = self.w0*np.exp(-(self.detach+self.edge+self.diff)/self.kT)  # two edge diffusion + detach
        self.rate_catalog['Diff_ES'] = self.w0*np.exp(-(self.diff+self.es)/self.kT)   # erhlich-schwoebel barrier
        self.rate_catalog['Diff_Detach1_ES'] = self.w0*np.exp(-(self.detach+self.diff+self.es)/self.kT)   # erhlich-schwoebel barrier plus break 1 bond
        self.rate_catalog['Diff_Detach2_ES'] = self.w0*np.exp(-(2*self.detach+self.diff+self.es)/self.kT)   # erhlich-schwoebel barrier plus break 2 bonds

        # Create corresponding Process Table, Rate Table, and Move Table to send to solver
        self.rates = []  # Rate Table
        self.moves = []   # Move Table
        self.keys = []  # Table of Keys corresponding to each entry (Move_Barriers)

        for i in range(len(Moves)):
            for j in range(len(Barriers[i])):
                self.rates.append(self.rate_catalog[Barriers[i][j]])
                self.moves.append([Moves_X[i],Moves_Z[i]])
                self.keys.append((Moves[i]+'_'+Barriers[i][j]))

        self.rates = np.array(self.rates,dtype=np.double)
        self.moves = np.array(self.moves,dtype=np.int32)

    def Simulation_3D(self):
        """ Set up Process Table for 3D Deposition (2+1) """

        # Set order of moves in the process table (straight,straight-down,straight-up,straight-left,straight-right)
        Moves = ['North','North_Down','North_Up','North_West','North_East',\
                 'East','East_Down','East_Up','East_North','East_South',\
                 'South','South_Down','South_Up','South_East','South_West',\
                 'West','West_Down','West_Up','West_South','West_North']

        # set corresponding  coordinate moves
        Moves_X = [0,0,0,-1,1,\
                   1,1,1,1,1,\
                   0,0,0,1,-1,\
                   -1,-1,-1,-1,-1]
        Moves_Y = [1,1,1,1,1,\
                   0,0,0,1,-1,\
                   -1,-1,-1,-1,-1,\
                   0,0,0,-1,1]
        Moves_Z = [0,-1,1,0,0,\
                   0,-1,1,0,0,\
                   0,-1,1,0,0,\
                   0,-1,1,0,0]

        # Set Barriers for Primary and Secondary Moves (name should include each barrier present)
        Barrier_Primary = ['Diff','Diff_Detach1','Diff_Detach2','Diff_Detach3','Edge','Edge_Detach1','Edge_Detach2']
        Barrier_Down = ['Diff_ES','Diff_Detach1_ES','Diff_Detach2_ES','Diff_Detach3_ES']
        Barrier_Up = ['Diff_Detach1_ES','Diff_Detach2_ES','Diff_Detach3_ES','Diff_Detach4_ES']
        Barrier_Corner = ['Corner','Corner_Detach1','Corner_Detach2']

        # Set Barriers for each move (can have multiple barriers for each move)
        Barriers = [Barrier_Primary,Barrier_Down,Barrier_Up,Barrier_Corner,Barrier_Corner,\
                    Barrier_Primary,Barrier_Down,Barrier_Up,Barrier_Corner,Barrier_Corner,\
                    Barrier_Primary,Barrier_Down,Barrier_Up,Barrier_Corner,Barrier_Corner,\
                    Barrier_Primary,Barrier_Down,Barrier_Up,Barrier_Corner,Barrier_Corner,]

        # number of processes per primary move
        self.num_barriers_per_move = len(Barrier_Down)+len(Barrier_Up)+len(Barrier_Primary)+len(Barrier_Corner)+len(Barrier_Corner)

        # Create Rate Catalog (keys must match the Barriers)
        self.rate_catalog = {}
        self.rate_catalog['Diff'] = self.w0*np.exp(-self.diff/self.kT)   # free surface diffusion
        self.rate_catalog['Diff_Detach1'] = self.w0*np.exp(-(self.detach+self.diff)/self.kT)  # detach from island, break 1 bond
        self.rate_catalog['Diff_Detach2'] = self.w0*np.exp(-(2*self.detach+self.diff)/self.kT)  # detach from island, break 2 bonds
        self.rate_catalog['Diff_Detach3'] = self.w0*np.exp(-(3*self.detach+self.diff)/self.kT)  # detach from island, break 3 bonds
        self.rate_catalog['Diff_ES'] = self.w0*np.exp(-(self.diff+self.es)/self.kT)   # downhill barrier
        self.rate_catalog['Diff_Detach1_ES'] = self.w0*np.exp(-(self.detach+self.diff+self.es)/self.kT)   # detach, break 1 bond, down
        self.rate_catalog['Diff_Detach2_ES'] = self.w0*np.exp(-(2*self.detach+self.diff+self.es)/self.kT)   # detach, break 2 bonds, up/down
        self.rate_catalog['Diff_Detach3_ES'] = self.w0*np.exp(-(3*self.detach+self.diff+self.es)/self.kT)   # detach, break 3 bonds, up/down
        self.rate_catalog['Diff_Detach4_ES'] = self.w0*np.exp(-(4*self.detach+self.diff+self.es)/self.kT)   # detach, break 4 bonds, up only
        self.rate_catalog['Edge'] = self.w0*np.exp(-(self.diff+self.edge)/self.kT)   # free edge diffusion
        self.rate_catalog['Edge_Detach1'] = self.w0*np.exp(-(self.diff+self.edge+self.detach)/self.kT)  # detach from kink plus edge diffusion, break 1 bond
        self.rate_catalog['Edge_Detach2'] = self.w0*np.exp(-(self.diff+self.edge+2*self.detach)/self.kT)  # detach from kink plus edge diffusion, break 2 bonds
        self.rate_catalog['Corner'] = self.w0*np.exp(-(self.diff+self.edge+self.corner)/self.kT)   # free corner barrier
        self.rate_catalog['Corner_Detach1'] = self.w0*np.exp(-(self.diff+self.edge+self.corner+self.detach)/self.kT)   # corner barrier, break 1 bond
        self.rate_catalog['Corner_Detach2'] = self.w0*np.exp(-(self.diff+self.edge+self.corner+2*self.detach)/self.kT)   # corner barrier, break 2 bonds

        # Create corresponding Process Table, Rate Table, and Move Table to send to solver
        self.rates = []  # Rate Table
        self.moves = []   # Move Table
        self.keys = []  # Table of Keys corresponding to each entry (Move_Barriers)

        for i in range(len(Moves)):
            for j in range(len(Barriers[i])):
                self.rates.append(self.rate_catalog[Barriers[i][j]])
                self.moves.append([Moves_X[i],Moves_Y[i],Moves_Z[i]])
                self.keys.append((Moves[i]+'_'+Barriers[i][j]))

        self.rates = np.array(self.rates,dtype=np.double)
        self.moves = np.array(self.moves,dtype=np.int32)

    def Downward_Funneling_Moves(self):
        """ Define Downward Funneling Moves. Only in-plane coordinate changes. """

        # Array is 1D and defines move of x coordinate. Left or Right
        if self.dim == '2D':
            DF_Moves = np.array([-1,1],dtype=np.int8)

        # Array is 2D, first index is x-position, 2nd index is y-position. Order is north, east, south, west
        elif self.dim == '3D':
            DF_Moves = np.array([[0,1],[1,0],[0,-1],[-1,0]],dtype=np.int8)

        return DF_Moves

# End of Module


# 1941 소문난 칠공주
# https://www.acmicpc.net/problem/1941
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
from collections import deque

def bfs(i, j):
    q = deque()
    v2 = [[0] * 5 for _ in range(5)]

    q.append((i, j))
    v2[i][j] = 1
    cnt = 1
    while q:
        x, y = q.popleft()

        for d in range(4):
            mx = x + dx[d]
            my = y + dy[d]

            if 0 <= mx < 5 and 0 <= my < 5 and not v2[mx][my] and visited[mx][my]:
                v2[mx][my] = 1
                q.append((mx, my))
                cnt += 1

    return cnt == 7

def check():
    for i in range(5):
        for j in range(5):
            # 이미 visited에 자리를 선택해놨기에 1들이 연결 되어 있는지 판단만 하면 됨
            if visited[i][j] == 1:
                return bfs(i, j)

# 2차원 배열을 1차원 배열로 늘려서 순열을 찾는 방법
# 5X5 이기에 25 만큼의 배열을 만들어서 25명의 학생들의 순열을 찾으면 됨
def dfs(idx, cnt, s):
    global ans
    if cnt > 7:
        return

    # 종료 조건
    if idx == 25:
        # 7명 선택하고 이다솜파가 4명 이상인 경우
        if cnt == 7 and s >= 4:
            # 자리가 붙어있는지 체크 한다.
            if check():
                ans += 1
        return

    # 해당 학생을 선택하거나
    visited[idx//5][idx%5] = 1
    # 1차원 배열의 인덱스//5 는 행 인덱스%5는 열을 의미
    dfs(idx + 1, cnt + 1, s + int(arr[idx//5][idx%5] == 'S'))
    # 선택 안하거나
    visited[idx//5][idx%5] = 0
    dfs(idx + 1, cnt, s)

arr = [list(input()) for _ in range(5)]
visited = [[0] * 5 for _ in range(5)]
ans = 0
dfs(0, 0, 0)
print(ans)


import tkinter as tk
import random

words = ['apple', 'banana', 'cherry', 'grape', 'orange', 'kiwi', 'mango', 'pear', 'pineapple', 'strawberry']

class WordSearchGame:
    def __init__(self, root):
        self.root = root
        self.root.title("Word Search Game")
        self.word_to_find = random.choice(words)
        self.found_words = []

        self.word_label = tk.Label(self.root, text=f"Find the word: {self.word_to_find}", font=("Arial", 16))
        self.word_label.pack(pady=10)

        self.canvas = tk.Canvas(self.root, width=400, height=400, borderwidth=2, relief="solid")
        self.canvas.pack()

        self.canvas.bind("<Button-1>", self.check_word)
        self.canvas.bind("<B1-Motion>", self.check_word)

        self.draw_grid()
        self.place_word()

    def draw_grid(self):
        for i in range(10):
            self.canvas.create_line(i * 40, 0, i * 40, 400)
            self.canvas.create_line(0, i * 40, 400, i * 40)

    def place_word(self):
        start_row = random.randint(0, 10 - len(self.word_to_find))
        start_col = random.randint(0, 10 - len(self.word_to_find))
        for i, letter in enumerate(self.word_to_find):
            x = (start_col + i) * 40 + 20
            y = (start_row + i) * 40 + 20
            self.canvas.create_text(x, y, text=letter, font=("Arial", 16), tags="word")

    def check_word(self, event):
        item = self.canvas.find_closest(event.x, event.y)[0]
        tags = self.canvas.gettags(item)

        if "word" in tags:
            x, y = self.canvas.coords(item)
            row = int((y - 20) / 40)
            col = int((x - 20) / 40)

            word = ""
            for i in range(min(10 - row, 10 - col)):
                item = self.canvas.find_closest((col + i) * 40 + 20, (row + i) * 40 + 20)[0]
                tags = self.canvas.gettags(item)
                if "word" in tags:
                    word += self.canvas.itemcget(item, 'text')

            if word == self.word_to_find:
                if word not in self.found_words:
                    self.found_words.append(word)
                    self.canvas.itemconfig("word", fill="green")
                    self.word_label.config(text=f"Find the word: {self.word_to_find} (Found {len(self.found_words)} words)")
                    if len(self.found_words) == len(words):
                        self.word_label.config(text="Congratulations! You found all the words!")
            else:
                self.canvas.itemconfig("word", fill="black")

if __name__ == "__main__":
    root = tk.Tk()
    game = WordSearchGame(root)
    root.mainloop()


import math
from collections import deque

def solution(progresses, speeds):
    answer = []
    job_deque = deque(progresses)
    speed_deque = deque(speeds)

    while(job_deque):
        for idx in range(len(job_deque)):
            job_deque[idx] = min(job_deque[idx] + speed_deque[idx], 100)
        cnt = 0
        while(job_deque and job_deque[0] == 100):
            job_deque.popleft()
            speed_deque.popleft()
            cnt += 1
        if cnt > 0:
            answer.append(cnt)
    # answer = []
    # finish_dates = deque([math.ceil((100 - progress) / speed) for progress, speed in zip(progresses, speeds)])
    # date = 0
    # while finish_dates:
    #     count = 0
    #     if finish_dates[0] == date:
    #         while finish_dates and finish_dates[0] <= date:
    #             finish_dates.popleft()
    #             count += 1
    #         answer.append(count)
    #     date += 1

    return answer


# coding: utf-8
# 设置损失函数 loss = (w+1)^2 ,令w初值是常数5. 反向传播就是求最优w,即使求最小loss对应的w值

import tensorflow as tf

# 定义待优化w权重
w = tf.Variable(tf.constant(5, dtype=tf.float32))

# 定义损失函数
loss = tf.square(w+1)

# 定义反向传播方法
train_step = tf.train.GradientDescentOptimizer(0.3).minimize(loss)
# 生成会话,训练40轮
with tf.Session() as s:
    init_op = tf.global_variables_initializer()
    s.run(init_op)
    for i in range(40):
        s.run(train_step)
        w_ = s.run(w)
        loss_ = s.run(loss)
        print ("After %s steps: w is %f ,  loss is %f" % (i, w_, loss_))


import os
import numpy as np
import torch
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from CustomDatasetLoader import CustomDataset
from CoreModels.repository import repository
from helper import Tools
from logger import Logger
from PIL import Image
from train_gan import  Train_GAN
from train_dcgan import Train_DCGAN
from train_wgan import Train_WGAN
from train_infogan import Train_INFOGAN
import yaml

#vs2626
class Model(object):
    """ This is the entry point of the code. It will read config.yaml and accordingly call the appropriate training/testing methods on corresponding gans"""
    def __init__(self, config):
        self.config = config

    # trains the gan based on the type: dcgan, wgan, infogan
    def train(self):
        """ This will call corresponding gan for training based on gan_type set in config.yaml file"""
        if self.config['gan_type'] == 'dcgan':
            Train_DCGAN(self.config).train()
        elif self.config['gan_type'] == 'wgan':
            Train_WGAN(self.config).train()
        elif self.config['gan_type'] == 'infogan':
            Train_INFOGAN(self.config).train()

    # predicts the result
    def predict(self):
        """ This will call corresponding gan for training based on gan_type set in config.yaml file"""
        model = Train_GAN(self.config)

        #a batch of samples are loaded from dataloader
        for sample in model.data_loader:
            CorrectImages = sample['CorrectImages']
            CorrectEmbedding = sample['CorrectEmbedding']
            txt = sample['txt']

            #if path doesnot exist, path is made
            if not os.path.exists('results/{0}'.format(model.save_directory_path)):
                os.makedirs('results/{0}'.format(model.save_directory_path))

            CorrectImages = Variable(CorrectImages.float()).cuda()
            CorrectEmbedding = Variable(CorrectEmbedding.float()).cuda()

            # add random noise to generate multiple images
            noise = Variable(torch.randn(CorrectImages.size(0), 100)).cuda()
            noise = noise.view(noise.size(0), 100, 1, 1)
            Unrealimages = model.generator(CorrectEmbedding, noise)

            model.logger.draw(CorrectImages, Unrealimages)

            #results are saved
            for image, t in zip(Unrealimages, txt):
                im = Image.fromarray(image.data.mul_(127.5).add_(127.5).byte().permute(1, 2, 0).cpu().numpy())
                im.save('results/{0}/{1}.jpg'.format(model.save_directory_path, t.replace("/", "")[:100]))
                print(t)

if __name__=='__main__':
    """This is main function & entrypoint"""
    config = None
    with open('config.yaml', 'r') as myfile:
        config = yaml.load(myfile)

    # print("\nCONFIGURATION:")
    # print(config)

    if config:
        model = Model(config)
        if not config['inference']:
            model.train()
        else:
            model.predict()


import codecs
import numpy as np

def load_data(filename):
    with codecs.open(filename, "r", "utf-8") as f:
        lines = f.readlines()
        data = []
        for line in lines:
            if ',' in line:
                _split = line.strip().split(",")
                data.append(float(_split[1]))
        return data

# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back=1):
    dataset = scaler(dataset)
    dataX, dataY = [], []
    if look_back == 1:
        dataX = dataset[:-1]
        dataY = dataset[1:]
    elif look_back > 1:
        dataY = dataset[look_back:]
        for i in range(len(dataset) - look_back):
            d = []
            for j in range(look_back):
                d.append(dataset[i + j])
            dataX.append(d)
    return np.array(dataX, dtype=np.float32), dataY

# scale the element in a to (0,1)
def scaler(a):
    max_value = max(a)
    min_value = min(a)
    a = [(e - min_value) / (max_value - min_value) for e in a]
    return a


from email import message
from flask import Flask, request
import requests
import json
from twilio.twiml.messaging_response import MessagingResponse
from dic import dic1,dic2, oracion
import pandas as pd
import numpy as np

app = Flask(__name__)
@app.route('/bot', methods=['POST'])
def reply():
    incoming_msg = request.values.get('Body', '').lower()
    response=MessagingResponse()
    message=response.message()
    responded = False
    words = incoming_msg.split()
    if dic1.keys().__contains__(incoming_msg) and len(words) ==1:
        reply = dic1[incoming_msg]
        message.body(reply)
        responded = True
    elif dic2.keys().__contains__(words[0]) and len(words) >1:
        selected=words[0]
        int_selected=int(selected)
        id=int(words[1])
        reply = dic2[selected]+oracion
        data=[]
        with open('data.json',"r") as fp:
            data = json.load(fp)
        data.append({
            'id': id,
            'selected': int_selected
        })
        with open('data.json', 'w') as fp:
            json.dump(data, fp)
        message.body(reply)
        responded = True
    return str(response)
if __name__ == '__main__':
    app.run(port=4000)


from colorama import *
from random import randint
from objects import Objects
class Magnet(Objects):
    def __init__(self):
        Objects.__init__(self)
        self.__magarr=[]
        Magnet.__address=[]
        self.__times=0
    def creating_mag_shape(self):
        with open('magnet.txt','r') as f:
            myname=[line.strip('\n') for line in f]
        for i in range(5):
            temp=[]
            for j  in range(7):
                temp.append(' ')
            self.__magarr.append(temp)
        for i in range(5):
            cnt=0
            for j in myname[i]:
                self.__magarr[i][cnt]=Fore.GREEN+j+Style.RESET_ALL
                cnt=cnt+1

    def creating_magnet(self,matrix,back):
        self.__times=randint(2,2)
        for i in range(self.__times):
            self.__temp=[]
            for j in range(3):
                self.__temp.append(' ')
            Magnet.__address.append(self.__temp)

        firstco=randint(1,1)
        self.__temp=[]
        self.__temp.append(randint(25,75))
        self.__temp.append(randint(150,200))
        for i in range(self.__times):
            Magnet.__address[i][0]=1
            Magnet.__address[i][1]=self.__temp[i]
            Magnet.__address[i][2]=self.__times

    def place_mag(self,matrix,back):
        firstco=1
        for i in range(self.__times):
            secondco=self.__temp[i]
            for j in range(5):
                for k in range(7):
                    back[firstco+j][secondco+k]="a"
                    matrix[firstco+j][secondco+k]=self.__magarr[j][k]

    # def remove_mag(self,matrix,back):
    #     firstco=1
    #     for i in range(self.times):
    #         secondco=self.temp[i]
    #         for j in range(5):
    #             for k in range(7):
    #                 back[firstco+j][secondco+k]=" "
    #                 matrix[firstco+j][secondco+k]=" "

    def check_field(firstco,secondco,start):
        if(secondco<102):
            sco=Magnet.__address[0][1]
            fco=Magnet.__address[0][0]
            if(secondco > sco-24):
                if(secondco < sco+2):
                    return secondco+1
                elif secondco < sco+26:
                    return secondco-1

        elif secondco < 227:
            sco=Magnet.__address[1][1]
            fco=Magnet.__address[1][0]
            if sco < start:
                if secondco > sco-24:
                    if secondco < sco+2:
                        return secondco+1
                    elif secondco < sco+26 :
                        return secondco-1
        return secondco


from typing import List
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        d = {}
        for i in strs:
            key = tuple(sorted(i))
            d[key] = d.get(key, []) + [i]
        return list(d.values())

b = Solution()
print(b.groupAnagrams(['bat', 'cat', 'tea', 'eat']))


# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pretend

import pytest

from http11.parser import Callback, Error, HTTPParser, MessageType

def test_basic():
    parser = HTTPParser()
    assert parser.parse(b"GET / HTTP/1.1\r\n\r\n") == 18
    assert parser.finished
    assert not parser.errored

@pytest.mark.parametrize(
    ("callback", "expected"),
    [
        (Callback.request_method, b"GET"),
        (Callback.request_uri, b"/foobar/"),
        (Callback.http_version, b"HTTP/1.1"),
    ],
)
def test_element_callback_request(callback, expected):
    func = pretend.call_recorder(lambda data: None)

    parser = HTTPParser()
    parser.callback(callback, func)
    parser.parse(b"GET /foobar/ HTTP/1.1\r\n\r\n")

    assert parser.finished
    assert not parser.errored
    assert func.calls == [pretend.call(expected)]

@pytest.mark.parametrize(
    ("callback", "expected"),
    [
        (Callback.reason_phrase, b"OK"),
        (Callback.http_version, b"HTTP/1.1"),
    ],
)
def test_element_callback_response(callback, expected):
    func = pretend.call_recorder(lambda data: None)

    parser = HTTPParser()
    parser.callback(callback, func)
    parser.parse(b"HTTP/1.1 200 OK\r\n\r\n")

    assert parser.finished
    assert not parser.errored
    assert func.calls == [pretend.call(expected)]

def test_status_code_callback():
    func = pretend.call_recorder(lambda status_code: None)

    parser = HTTPParser()
    parser.callback(Callback.status_code, func)
    parser.parse(b"HTTP/1.1 200 OK\r\n\r\n")

    assert parser.finished
    assert not parser.errored
    assert func.calls == [pretend.call(200)]

def test_header_callback():
    func = pretend.call_recorder(lambda name, value: None)

    parser = HTTPParser()
    parser.callback(Callback.http_header, func)
    parser.parse(b"HTTP/1.1 200 OK\r\nFoo: Bar\r\n\r\n")

    assert parser.finished
    assert not parser.errored
    assert func.calls == [pretend.call(b"Foo", b"Bar")]

@pytest.mark.parametrize(
    ("callback", "data"),
    [
        (Callback.request_method, b"GET / HTTP/1.1\r\n\r\n"),
        (Callback.request_uri, b"GET / HTTP/1.1\r\n\r\n"),
        (Callback.http_version, b"GET / HTTP/1.1\r\n\r\n"),
        (Callback.reason_phrase, b"HTTP/1.1 200 OK\r\n\r\n"),
        (Callback.status_code, b"HTTP/1.1 200 OK\r\n\r\n"),
        (Callback.http_header, b"HTTP/1.1 200 OK\r\nFoo: Bar\r\n\r\n"),
    ],
)
def test_callback_error(callback, data):
    @pretend.call_recorder
    def raiser(*args, **kwargs):
        raise Exception

    parser = HTTPParser()
    parser.callback(callback, raiser)
    parser.parse(data)

    assert parser.finished
    assert parser.errored
    assert parser.error == Error.General

def test_error_is_none():
    parser = HTTPParser()

    assert not parser.finished
    assert not parser.errored
    assert parser.error is None

    parser.parse(b"HTTP/2.0 200 OK\r\n\r\n")

    assert parser.finished
    assert parser.errored
    assert parser.error == Error.BadVersion

def test_unknown_callback():
    parser = HTTPParser()

    with pytest.raises(ValueError):
        parser.callback("wat", lambda: None)

def test_callback_decorator():
    parser = HTTPParser()

    @parser.callback(Callback.http_version)
    @pretend.call_recorder
    def noop(*args, **kwargs):
        pass

    parser.parse(b"HTTP/1.1 200 OK\r\n\r\n")

    assert parser.finished
    assert not parser.errored

@pytest.mark.parametrize(
    ("message", "mtype"),
    [
        (b"GET / HTTP/1.1\r\n\r\n", MessageType.Request),
        (b"HTTP/1.1 200 OK\r\n\r\n", MessageType.Response),
    ],
)
def test_callback_message_type(message, mtype):
    parser = HTTPParser()
    assert parser.type is None
    parser.parse(message)
    assert parser.type == mtype

def test_message_reset():
    parser = HTTPParser()

    assert not parser.finished
    assert not parser.errored
    assert parser.error is None
    assert parser.type is None

    parser.parse(b"HTTP/1.1 200 OK\r\n\r\n")

    assert parser.finished
    assert not parser.errored
    assert parser.error is None
    assert parser.type is MessageType.Response

    parser.reset()

    assert not parser.finished
    assert not parser.errored
    assert parser.error is None
    assert parser.type is None

    parser.parse(b"GET / HTTP/1.1\r\n\r\n")

    assert parser.finished
    assert not parser.errored
    assert parser.error is None
    assert parser.type is MessageType.Request


from keras_segmentation.models.unet import vgg_unet
from keras_segmentation.data_utils.data_loader import get_image_array, class_colors
from keras_segmentation.models.config import IMAGE_ORDERING
from keras_segmentation.predict import visualize_segmentation
import cv2
import numpy as np
from pathlib import Path
from tqdm import tqdm
import os
import argparse
import itertools

def chunked_iterable(iterable, size):
    it = iter(iterable)
    while True:
        chunk = tuple(itertools.islice(it, size))
        if not chunk:
            break
        yield chunk

def gen_out_name(jpg_path, outdir):

    parts = list(jpg_path.parts)
    parts[0] = outdir
    out_path = os.path.join(*parts)

    return out_path

def dir_batch_predict(model, inp_dir=None):
    jpgs = [i for i in inp_dir.glob('*.jpg')]

    batch_predict(model, jpgs)

def batch_predict(model, jpgs, outdir, checkpoints_path=None, overlay_img=False,
                  class_names=None, show_legends=False, colors=class_colors,
                  prediction_width=None, prediction_height=None,
                  read_image_type=1):
    output_width = model.output_width
    output_height = model.output_height
    input_width = model.input_width
    input_height = model.input_height
    n_classes = model.n_classes

    out_paths = [gen_out_name(jpg_path, outdir) for jpg_path in jpgs]
    if Path(out_paths[0]).exists():
        return

    inp_example = cv2.imread(str(jpgs[0]))
    x = [get_image_array(str(inp), input_width, input_height, ordering=IMAGE_ORDERING) for inp in jpgs]

    pr = model.predict(np.array(x))
    pr = pr.reshape((len(jpgs), output_height,  output_width, n_classes)).argmax(axis=3)

    for arr, out_fname in zip(pr, out_paths):
        seg_img = visualize_segmentation(arr, inp_example, n_classes=n_classes,
                                     colors=colors, overlay_img=overlay_img,
                                     show_legends=show_legends,
                                     class_names=class_names,
                                     prediction_width=prediction_width,
                                     prediction_height=prediction_height)

        # make sure out dir exits
        Path(out_fname).parent.mkdir(parents=True, exist_ok=True)
        cv2.imwrite(out_fname, seg_img)

def main():
    global OUT_DIR
    parser = argparse.ArgumentParser()
    parser.add_argument('rnfl_model_weights')
    parser.add_argument('ilm_model_weights')
    parser.add_argument('png_dir')
    parser.add_argument('outdir')
    parser.add_argument('--nested', action='store_true')
    args = parser.parse_args()

    path = args.png_dir

    rnfl_model = vgg_unet(n_classes=2,  input_height=416, input_width=608)
    rnfl_model.load_weights(args.rnfl_model_weights)

    ilm_model = vgg_unet(n_classes=2,  input_height=416, input_width=608)
    ilm_model.load_weights(args.ilm_model_weights)

    ilm_outdir = os.path.join(args.outdir, 'ILM')
    rnfl_outdir = os.path.join(args.outdir, 'RNFL')

    if args.nested:
        scan_dirs = [i for i in Path(path).glob('*/*/*')]
        for scan_dir in tqdm(scan_dirs):
            jpgs = [i for i in scan_dir.glob('*.jpg')]
            if Path(gen_out_name(jpgs[0], rnfl_outdir)).exists(): # skip existing dirs
                continue
            else:
                dir_batch_predict(model=rnfl_model, inp_dir=scan_dir, outdir=rnfl_outdir)
                dir_batch_predict(model=ilm_model, inp_dir=scan_dir, outdir=ilm_outdir)
    else:
        files = [i for i in Path(path).rglob('*.jpg')]
        batch_size = 400
        for batch in tqdm(list(chunked_iterable(files, size=batch_size))):
            batch_predict(rnfl_model, batch, outdir=rnfl_outdir)
            batch_predict(ilm_model, batch, outdir=ilm_outdir)

if __name__=='__main__':
    main()


import numpy

import qtoolkit.utils.types as qtypes

######################################
#           PAULI MATRICES           #
######################################
# Definitions with sigma
SIGMA_X = numpy.array([[0, 1], [1, 0]], dtype=numpy.complex)
SIGMA_Y = numpy.array([[0, -1.0j], [1.0j, 0]], dtype=numpy.complex)
SIGMA_Z = numpy.array([[1, 0], [0, -1]], dtype=numpy.complex)
SIGMA_X_SU2 = SIGMA_X / numpy.lib.scimath.sqrt(numpy.linalg.det(SIGMA_X))
SIGMA_Y_SU2 = SIGMA_Y / numpy.lib.scimath.sqrt(numpy.linalg.det(SIGMA_Y))
SIGMA_Z_SU2 = SIGMA_Z / numpy.lib.scimath.sqrt(numpy.linalg.det(SIGMA_Z))
# Aliases to the definitions with sigma
P_X = SIGMA_X
P_Y = SIGMA_Y
P_Z = SIGMA_Z
P_X_SU2 = SIGMA_X_SU2
P_Y_SU2 = SIGMA_Y_SU2
P_Z_SU2 = SIGMA_Z_SU2

######################################
#           IDENTITY MATRIX          #
######################################
IDENTITY_2X2 = numpy.identity(2, dtype=numpy.complex)
ID2 = IDENTITY_2X2
# In SU(2)
IDENTITY_2X2_SU2 = IDENTITY_2X2
ID2_SU2 = ID2

######################################
#       QUANTUM GATES MATRICES       #
######################################
X = numpy.array([[0, 1], [1, 0]], dtype=numpy.complex)
Y = numpy.array([[0, -1.0j], [1.0j, 0]], dtype=numpy.complex)
Z = numpy.array([[1, 0], [0, -1]], dtype=numpy.complex)
H = numpy.array([[1, 1], [1, -1]], dtype=numpy.complex) / numpy.sqrt(2)
S = numpy.array([[1, 0], [0, 1.0j]], dtype=numpy.complex)
T = numpy.array([[1, 0], [0, numpy.exp(1.0j * numpy.pi / 4)]], dtype=numpy.complex)
CX = numpy.array(
    [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=numpy.complex
)

def Rx(parameters: numpy.ndarray) -> qtypes.SU2Matrix:
    theta = parameters[0]
    cos_theta_2 = numpy.cos(theta / 2)
    isin_theta_2 = -1.0j * numpy.sin(theta / 2)
    return numpy.array([[cos_theta_2, isin_theta_2], [isin_theta_2, cos_theta_2]])

def Ry(parameters: numpy.ndarray) -> qtypes.SU2Matrix:
    theta = parameters[0]
    cos_theta_2 = numpy.cos(theta / 2)
    sin_theta_2 = numpy.sin(theta / 2)
    return numpy.array([[cos_theta_2, -sin_theta_2], [sin_theta_2, cos_theta_2]])

def Rz(parameters: numpy.ndarray) -> qtypes.SU2Matrix:
    theta = parameters[0]
    e_itheta_2 = numpy.exp(1.0j * theta / 2)
    return numpy.array([[1 / e_itheta_2, 0], [0, e_itheta_2]])

# Quantum gates in SU(2)
X_SU2 = X / numpy.lib.scimath.sqrt(numpy.linalg.det(X))
Y_SU2 = Y / numpy.lib.scimath.sqrt(numpy.linalg.det(Y))
Z_SU2 = Z / numpy.lib.scimath.sqrt(numpy.linalg.det(Z))
H_SU2 = H / numpy.lib.scimath.sqrt(numpy.linalg.det(H))
S_SU2 = S / numpy.lib.scimath.sqrt(numpy.linalg.det(S))
T_SU2 = T / numpy.lib.scimath.sqrt(numpy.linalg.det(T))
CX_SU2 = CX / numpy.lib.scimath.sqrt(numpy.lib.scimath.sqrt(numpy.linalg.det(CX)))

P0 = numpy.array([[1, 0], [0, 0]], dtype=numpy.complex)
P1 = numpy.array([[0, 0], [0, 1]], dtype=numpy.complex)


#!/usr/bin/env python

import argparse

parser = argparse.ArgumentParser()
# A optional argument A with necessary value
parser.add_argument("-a", "--argument-A",
                    help="Information about argument with pattern [-a ARGUMENT]")
# A optional argument B without necessary value
parser.add_argument("-b", "--argument-B",
                    help="Information about b argument with pattern [-b] ",
                    action="store_true")
parser.parse_args()