import pygame as pg
from enum import Enum
from sys import exit
import os

#Set working directory
proj_folder = str(os.path.dirname((os.path.dirname(os.path.realpath(__file__)))))
os.chdir(proj_folder+"\include")

#define game states
class GameState(Enum):

    CHARACTERSELECT = 0

    #TO-DO: Implement remaining game states

class GameStateManager:
    def __init__(self):
        self.current_state = None

    def change_state(self, new_state):
        self.current_state = new_state

    def run_state(self):
        # if self.current_state == GameState.TITLESCREEN:
        #     titlescreen()
        # elif self.current_state == GameState.LOGINSCREEN:
        #     loginscreen()
        # elif self.current_state == GameState.PLAYERCONNECT:
        #     playerconnect()
        if self.current_state == GameState.CHARACTERSELECT:
            characterselect()
        # elif self.current_state == GameState.MAINGAME:
        #     maingame()

#Define player class
class Player:
    def __init__(self, name, character, hasBomb, isAlive, playernum):
        self.name = name
        self.character = character
        self.hasBomb = hasBomb
        self.isAlive = isAlive
        self.img = pg.image.load("img/"+character+".png").convert_alpha()
        if playernum == 1:
            playerpos = (screenWidth//2, screenHeight//2+200)
        if playernum == 2:
            playerpos = (screenWidth//2 - 200, screenHeight//2-100)
        if playernum == 3:
            playerpos = (screenWidth//2+200, screenHeight//2-100)
        self.img = pg.transform.scale(self.img, (150, 150))
        self.player_rect = self.img.get_rect(center = playerpos)

    def throwBomb(self, direction):
        print ("Bomb thrown to " + str(direction))

#Define Screen Functions
def characterselect():
    #  #load character images
    # characters = ["sarim", "bouganis", "naylor"]
    # player1 = Player("noor", characters[0], hasBomb = True, isAlive = True, playernum = 1)
    # player2 = Player("shaheer", characters[1], hasBomb = False, isAlive = True, playernum =  2)
    # player3 = Player("jim", characters[2], hasBomb = False, isAlive = True, playernum = 3)
    # player1 = pg.image.load("img/sarim.png").convert_alpha()
    # player2 = pg.image.load("img/sarim.png").convert_alpha()
    # player3 = pg.image.load("img/sarim.png").convert_alpha()
    # players = [player1, player2, player3]
    characters_1 = pg.image.load("img/sarim.png").convert_alpha()
    characters_2 = pg.image.load("img/bouganis.png").convert_alpha()
    characters_3 = pg.image.load("img/naylor.png").convert_alpha()

    characters_1 = pg.transform.scale(characters_1, (300, 150))
    characters_1_trans = characters_1.copy()
    characters_1_trans.set_alpha(120)#Pass 0 for invisible and 255 for fully opaque.
    characters_1rect = characters_1.get_rect(center=((screenWidth // 3)-250,(screenHeight // 3)-70))

    characters_2 = pg.transform.scale(characters_2, (300, 150))
    characters_2_trans = characters_2.copy()
    characters_2_trans.set_alpha(240)
    characters_2rect = characters_2.get_rect(center=((screenWidth // 2), (screenHeight // 3)-70))

    characters_3 = pg.transform.scale(characters_3, (300, 150))
    characters_3_trans = characters_3.copy()
    characters_3_trans.set_alpha(120)
    characters_3rect = characters_3.get_rect(center=((screenWidth // 1.5)+250,(screenHeight // 3)-70))

    # for player in players:
    #     player = pg.transform.scale(player, (300, 150))
    play=["jim","noor", "shaheer"]
    numPlayers = 3

    cc=0
    ccc1=0
    ccc2=0
    ccc3=0
    pg.display.flip()
    characters_rects=[characters_1rect,characters_2rect, characters_3rect]
    #characters_rects=[]

    while True:
        for event in pg.event.get():
            state = "Waiting"
            if cc < numPlayers:
               plays = play[cc]
            if event.type == pg.QUIT:
                pg.quit()
                exit()
            elif event.type == pg.MOUSEBUTTONUP:
                if cc <numPlayers:
                    print(cc)
                    #plays = play[cc]
                    state = "0"
                    Plays_msg = font1.render(' please connect to a character'+plays, True, black)
                    Plays_msgrect = Plays_msg.get_rect(center=((screenWidth // 2) , (screenHeight //2) +150))
                    #screen.blit(Plays_msg,Plays_msgrect)
                    print (plays)
                    if (characters_1rect.collidepoint(pg.mouse.get_pos())) and ccc1<1:
                     #       playersss.append(player)
                        state ="1"
                        #characters_rects.append(characters_1rect)
                        success_msg1 = font1.render(plays+' connected to Character1', True, black)
                        success_msg1rect = success_msg1.get_rect(center= ((screenWidth // 2) , (screenHeight //2) +150))
                        ccc1 = ccc1+1
                        cc+=1
                        #print("successfully selected")

                    elif (characters_2rect.collidepoint(pg.mouse.get_pos())) and ccc2<1:
                     #       playersss.append(player)
                        state ="2"
                        #characters_rects.append(characters_2rect)
                        success_msg2 = font1.render(plays+' connected to Character2', True, black)
                        success_msg2rect = success_msg2.get_rect(center= ((screenWidth // 2) , (screenHeight //2) +200))
                        ccc2 = ccc2+1
                        cc+=1
                       # print("successfully selected")

                    elif (characters_3rect.collidepoint(pg.mouse.get_pos())) and ccc3<1:
                     #       playersss.append(player)
                        state ="3"
                       # characters_rects.append(characters_3rect)
                        success_msg3 = font1.render(plays+' connected to Character3', True, black)
                        success_msg3rect = success_msg3.get_rect(center= ((screenWidth // 2) , (screenHeight //2) +250))
                        ccc3 = ccc3+1
                        cc+=1
                    elif  ((characters_3rect.collidepoint(pg.mouse.get_pos())) and ccc3!=0) or  ((characters_2rect.collidepoint(pg.mouse.get_pos())) and ccc2!=0) or ((characters_1rect.collidepoint(pg.mouse.get_pos())) and ccc1!=0):
                        state ="error"
                        print("error")
            elif ccc3 <1 or ccc2 <1 or ccc1 <1:
                 state = "0"
                 Plays_msg = font1.render(plays+' please connect to a character', True, black)
                 Plays_msgrect = Plays_msg.get_rect(center=((screenWidth // 2) , (screenHeight //2) +150))

            elif ccc3>0 and ccc2 >0 and ccc1>0:
                state = "All_Characters_Connected"

            if event.type == pg.KEYDOWN and state == "All_Characters_Connected":
                game_state_manager.change_state(GameState.LOGINSCREEN)
               # game_state_manager.run_state(MAINGAME)
                #print("game")

            screen.fill(light_grey)
            unsuccess_msg = font1.render("Character selected, please select another one", True, black)
            unsuccess_msgrect = unsuccess_msg.get_rect(center= ((screenWidth // 2) , (screenHeight //2) +150))
            start_msg = font1.render('Start game', True, black)
            start_msg_rect = start_msg.get_rect()
            start_msg_rect.center = ((screenWidth / 2 - start_msg.get_width() / 2), (screenHeight - 45))
            waiting_msg2 = font1.render("No Character selected yet. Press any key to start character select", True, black)
            waiting_msg2rect =  waiting_msg2.get_rect(center= ((screenWidth // 2) , (screenHeight //3) -200))

            if state == "Waiting":
               screen.blit(waiting_msg2,waiting_msg2rect)
            elif state == "All_Characters_Connected" :
               screen.blit(success_msg1,success_msg1rect)
               screen.blit(success_msg2,success_msg2rect)
               screen.blit(success_msg3,success_msg3rect)
               pg.draw.rect(screen, green, (screenWidth / 2 - 75, (screenHeight //2) +40, 150, 50), border_radius=10)
               screen.blit(start_msg, (screenWidth / 2 - start_msg.get_width() / 2, (screenHeight//2) +50))
               print("state_all")
            elif state=="0":
                screen.blit(Plays_msg,Plays_msgrect)
            elif state =="1" :
                screen.blit(success_msg1,success_msg1rect)
            elif state =="2":
               screen.blit(success_msg2,success_msg2rect)
            elif state =="3":
               screen.blit(success_msg3,success_msg3rect)
            elif state =="error":
               screen.blit(unsuccess_msg,unsuccess_msgrect)

        screen.blit(characters_1,characters_1rect)
        screen.blit(characters_2,characters_2rect)
        screen.blit(characters_3,characters_3rect)
        screen.blit(waiting_msg2,waiting_msg2rect)
        pg.display.flip()

pg.init()

#Initialize game state manager and set state = TitleScreen
game_state_manager = GameStateManager()
game_state_manager.change_state(GameState.CHARACTERSELECT)

#Setup display
screenWidth = 1280
screenHeight = 720
screen = pg.display.set_mode((screenWidth, screenHeight))
pg.display.set_caption("FoodGame")

#Define Colours:
black = (0, 0, 0)
white = (255, 255, 255)
light_grey = (200, 200, 200)
blue = (0, 0, 255)
green = (0, 255, 0)
red = (255, 0, 0)

#Set Fonts
font1 = pg.font.Font(r"fonts\retro.ttf", 20)

#Setup clock
clock = pg.time.Clock()

#Load Media
titleLogo = pg.image.load(r"img\title.png").convert_alpha()

def main():
    game_state_manager.run_state()

main()


"""

    Wrapper for a result of experiment. Load the required functions, and run evaluation episodes

"""

import json
import os
import sys
import config
import time
import numpy as np

from utils.Validation import assertFunctionExist, assertPathExists, keepPathIfExist
from core.MakeTMEnv import MakeTMEnv
from utils.Validation import load_config
from core.Telemetry import Telemetry
from utils.draw import SplittedLayoutWindow

class ExperimentWrapper:
    """
        Wrapper for a result of experiment. Load the required functions, and run evaluation episodes
    """
    def __init__(self, experiment_path):
        self.experiment_path = experiment_path
        self.name = os.path.basename(self.experiment_path)
        # Add the experiment folder to the import paths
        sys.path.append(self.experiment_path)
        # Change current directory to the experiment's
        os.chdir(self.experiment_path)
        # Get paths of required files
        self.play_script_path = None
        self.loadRequiredFilesPath()
        # Get paths of optionnal files
        self.hyperparameters_path = None
        self.tryLoadOptionnalFilesPath()
        # The user's function
        self.play = None
        # Load the user's functions
        self.loadRequiredFunctions()
        # Load the optionnal dict (hyperparameters.json)
        self.hyperparameters = None
        self.tryLoadOptionnalDict()

        # Attributes for telemetry
        self.telemetry = Telemetry([
            "Duration",
            "FPS",
            "Action Latency",
            "Episode",
            "Env step",
            "Reward",
            "Action"
        ], dump_file_path="evaluation_metrics.csv")
        # Utility to display a window with a splitted layout. The window will be splitted in 4x3 sections. We provide our telemetry so it is used as a data source
        self.ui = SplittedLayoutWindow(self.telemetry, (3, 2))

        # Define a function we will need later
        def seconds2HoursString(x):
            """
                Lambda function to convert a number of seconds in float to a formatted string: hh:mm:ss
            """
            x = round(x)

            h = x // 3600
            m = (x % 3600) // 60
            s = x % 60

            return "{}:{:02d}:{:02d}".format(
                h, m, s
            )
        ## bind the divisions of the window to the corresponding metrics
        # The (0, 0) window will display the duration of the execution of the algorithm
        self.ui.bind(0, "Duration", 'last', {"lambda": seconds2HoursString})
        # The (0, 1) window will display the current "FPS" of the algortihm
        self.ui.bind(1, "FPS", 'last')
        # The (1, 0) window will display the number of episodes
        self.ui.bind(2, "Episode", 'last')
        # The (1, 1) window will display the number of game steps
        self.ui.bind(3, "Env step", 'last')
        # The (2, 0) window will display the number of time the agent finished the map
        self.ui.bind(4, "Reward", 'last')
        # The (2, 1) window will display the last action that the agent took
        self.ui.bind(5, "Action", 'keyboard')

    def loadRequiredFilesPath(self):
        """
            Complete the paths of the required files or throw an error if it can't find them
        """
        self.experiment_path = assertPathExists(
            ".",
            error_message="{} folder doesn't exists".format(self.experiment_path)
        )

        self.train_script_path = assertPathExists(
            self.experiment_path,
            "train.py",
            "{} is an invalid algorithm path because train.py script wasn't found".format(self.experiment_path)
        )

        self.play_script_path = assertPathExists(
            self.experiment_path,
            "play.py",
            "{} is an invalid algorithm path because play.py script wasn't found".format(self.experiment_path)
        )

    def tryLoadOptionnalFilesPath(self):
        """
            Complete the paths of the optionnal files if they exists
        """
        self.hyperparameters_path = keepPathIfExist(
            self.experiment_path,
            "hyperparameters.json",
            "hyperparameters.json wasn't found, your script will run with an empty hyperparameters set"
        )

    def loadRequiredFunctions(self):
        """
            Load the user functions (play from play.py) or throw an error if it can't find them
        """
        sys.path.append(self.experiment_path)
        self.train = assertFunctionExist(
            self.train_script_path,
            "run"
        )

        self.play = assertFunctionExist(
            self.play_script_path,
            "play"
        )

    def tryLoadOptionnalDict(self):
        """
            Load the optionnal dictionnaries (hyperparameters.json) if they exists
        """
        if self.hyperparameters_path is not None:
            with open(self.hyperparameters_path) as f:
                self.hyperparameters = json.load(f)
        else:
            self.hyperparameters = {}

    def assertSameConfig(self):
        exp_config = load_config(self.experiment_path)

        actual_config_keys = [v for v in dir(config) if not v.startswith('__')]
        exp_config_keys = [v for v in dir(exp_config) if not v.startswith('__')]

        missing_in_exp = []
        diff = []
        for k in actual_config_keys:
            actual_value = getattr(config, k)
            try:
                exp_value = getattr(exp_config, k)
                if actual_value != exp_value:
                    diff.append((k, actual_value, exp_value))
            except:
                missing_in_exp.append(k)

        missing_in_actual = []
        for k in exp_config_keys:
            try:
                exp_value = getattr(config, k)
            except:
                missing_in_actual.append(k)

        if len(missing_in_exp) + len(diff) + len(missing_in_actual):
            if len(missing_in_exp):
                print("{} is/are missing in the config experiment folder.\n".format(
                    str(missing_in_exp)
                ))

            if len(diff):
                print("Some values are not the same in your experiment config.py and in the current config.py")
                for k, actual_value, exp_value in diff:
                    print("{} is different (Experiment: {} | Actual={}}".format(
                        k, exp_value, actual_value
                    ))

            if len(missing_in_actual):
                print("{} is/are missing in the current config.py\n".format(
                    str(missing_in_exp)
                ))

            raise ValueError("It could cause undetermined behaviour. If you still want to evaluate this experiment, modify the current config.py or the one of your experiment folder")

    def resume(self):
        """
            resume an experiment by calling the user's train function
        """
        # Call the user's train function
        self.train(self.hyperparameters)

    def update(self):
        """
            Here are the function to perform each step that takes time. It's wrapped in this function so it can be called during the waiting phase of the environment
        """
        if not self.ui.draw():
            raise Exception("Graphic mode Interuption")

    def test(self, n_episodes=10):
        """
            Run "n_episodes" evaluation episodes on the results of the experiment
        """
        self.assertSameConfig()
        with MakeTMEnv(manual_override=False) as tmenv:
            self.tstart = time.time()
            tmenv.attachToWaitHook(self.update)
            for i in range(n_episodes):
                state = tmenv.reset()
                total_rewards = 0
                print("Starting episode", i+1)
                s = 0
                while True:
                    s += 1
                    print("State shape:", state.shape, end=" | ")
                    action = self.play(state, tmenv)
                    state, reward, done, info = tmenv.step(action)
                    total_rewards += reward
                    print("Performed action: {} | Obtained reward: {}".format(
                        tmenv.controller.actionToString(info["performed_action"]),
                        reward
                    ))
                    self.telemetry.append({
                        "Duration": time.time() - self.tstart,
                        "FPS": tmenv.getFPS(),
                        "Action Latency": info["action_latency"],
                        "Episode": i,
                        "Env step": s,
                        "Reward": reward,
                        "Action": info["performed_action"],
                    })

                    if done:
                        break

                print("Finished ! Obtained {} rewards".format(total_rewards))


from dsa import *

# learned, with fixed n combinations of an array, we can just use a for loop
def largestTriangleArea(self, points: List[List[int]]) -> float:
    def triangle_area(x1, y1, x2, y2, x3, y3):
        return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0)

    max_area = 0
    for i in range(len(points)):
        for j in range(i + 1, len(points)):
            for k in range(j + 1, len(points)):
                print(
                    [
                        [points[i][0], points[i][1]],
                        [points[j][0], points[j][1]],
                        [points[k][0], points[k][1]],
                    ]
                )
                area = triangle_area(
                    points[i][0],
                    points[i][1],
                    points[j][0],
                    points[j][1],
                    points[k][0],
                    points[k][1],
                )
                if area > max_area:
                    max_area = area
    return max_area

largestTriangleArea("", [[0, 0], [0, 1], [1, 0], [0, 2], [2, 0]])

[
    [[0, 0], [0, 1], [1, 0]],
    [[0, 0], [0, 1], [0, 2]],
    [[0, 0], [0, 1], [2, 0]],
    [[0, 0], [1, 0], [0, 2]],
    [[0, 0], [1, 0], [2, 0]],
    [[0, 0], [0, 2], [2, 0]],
    [[0, 1], [1, 0], [0, 2]],
    [[0, 1], [1, 0], [2, 0]],
    [[0, 1], [0, 2], [2, 0]],
    [[1, 0], [0, 2], [2, 0]],
]

# MY SOLUTION
# class Solution:
#     def largestTriangleArea(self, points: List[List[int]]) -> float:
#         # generate all combs
#         combs = []

#         def rec(combs, i=0, comb=[]):
#             if len(comb) == 3:
#                 combs.append(comb[:])
#                 return
#             if i == len(points):
#                 return

#             rec(combs, i + 1, comb[:] + [points[i]])
#             rec(combs, i + 1, comb[:])

#         rec(combs)

#         # get the area of each triangle while keeping tract of the max
#         def triangle_area(x1, y1, x2, y2, x3, y3):
#             return 0.5 * abs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2))

#         maxArea = float("-inf")
#         for comb in combs:
#             x1, y1 = comb[0]
#             x2, y2 = comb[1]
#             x3, y3 = comb[2]
#             maxArea = max(triangle_area(x1, y1, x2, y2, x3, y3), maxArea)
#         return maxArea


from pyramid.config import Configurator

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.include('pyramid_jinja2')
    config.include('.models')
    config.include('.routes')
    config.scan()

    from . import crumbs
    config.add_request_method(crumbs.breadcrumbs, 'breadcrumbs', reify=True)

    app = config.make_wsgi_app()

    j_env = config.get_jinja2_environment()
    j_env.globals.update(zip=zip,len=len)

    return app


Books= []
Borrower=[]
Checkout=[]
input_str = input()
if input_str == "Books":
    while True:
        input_str = input()
        if input_str == "Borrowers":
            break
        else:
            Books.append(input_str)
while True:
    input_str = input()
    if input_str == "Checkouts":
        break
    else:
        Borrower.append(input_str)
while True:
    input_str = input()
    if input_str == "EndOfInput":
        break
    else:
        Checkout.append(input_str)
book_list=[]
borrower_list=[]
checkout_list=[]
for item in Books:
    x = item.split("~")
    book_list.append(x)
for item in Borrower:
    x = item.split("~")
    borrower_list.append(x)
for item in Checkout:
    x = item.split("~")
    checkout_list.append(x)
ans=[]
y=[]
for item in checkout_list:
    for x in borrower_list:
        if item[0] in x[0]:
            y.append([item[2],"~",x[1]])

i=0
for item in checkout_list:
    for x in book_list:
        if item[1] in x[0]:
            y[i].append('~'+item[1]+"~"+x[1])
            i += 1
ans = sorted(y, key=lambda x: x)

for item in ans:
    z = ''.join(item)
    print(z)


# -*- coding: utf-8 -*-
"""
Created on Mon Aug  6 13:18:04 2018

@author: Jack
"""
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
import sklearn.preprocessing
from sklearn.decomposition import PCA
import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_csv('data.csv')

#deleting unneeded rows
del df["Unnamed: 32"]
del df["id"]
df["diagnosis"].replace("M",1,inplace=True)
df["diagnosis"].replace("B",0,inplace=True)
df["Diagnosis"] = df["diagnosis"]
del df["diagnosis"]

#separating data into training, dev, and test sets
training_df = df.values[0:500]
dev_df = df.values[500:535]
test_df = df.values[535:]

train_x, train_y, test_x, test_y, dev_x, dev_y = [], [], [], [], [], []

#inserting data into training, dev, and test sets
for row in training_df:
    row = row.tolist()
    train_x.append(row[0:29])
    train_y.append(int(row[30]))

for row in dev_df:
    row = row.tolist()
    dev_x.append(row[0:29])
    dev_y.append(int(row[30]))

for row in test_df:
    row = row.tolist()
    test_x.append(row[0:29])
    test_y.append(int(row[30]))

#normalizing data
train_x, train_y = sklearn.preprocessing.normalize(np.array(train_x)), np.array(train_y)
dev_x, dev_y = sklearn.preprocessing.normalize(np.array(dev_x)), np.array(dev_y)
test_x, test_y = sklearn.preprocessing.normalize(np.array(test_x)), np.array(test_y)

#creating the model structure
model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=29))
model.add(Dense(units=48, activation='relu'))
model.add(Dense(units=32, activation='relu'))
model.add(Dense(units=16, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

#training the model
model.fit(train_x, train_y, epochs=5, batch_size=1, shuffle=True)
print("\n")

#using model to predict dev set
score = model.evaluate(dev_x, dev_y)
print("----Dev Set----\nLoss: " + str(score[0]) + "\nAccuracy: " + str(round(score[1]*100, 3))+"%\n")

#using model to predict test set
score = model.evaluate(test_x, test_y)
print("----Test Set----\nLoss: " + str(score[0]) + "\nAccuracy: " + str(round(score[1]*100, 3))+"%")

#separating data labels for graphing
malignant = sklearn.preprocessing.normalize(df[df["Diagnosis"]==1].values)
benign = sklearn.preprocessing.normalize(df[df["Diagnosis"]==0].values)

#using PCA to reduce dimensionality of the data to 2 features for graphing purposes
pca = PCA(n_components=2)
malignant = pca.fit_transform(malignant)
benign = pca.fit_transform(benign)

#using pyplot to graph data
for t in range(2):
    if t == 0:
        plt.scatter([pair[0] for pair in benign], [pair[1] for pair in benign], color='r', s=10, label="Benign")
    else:
        plt.scatter([pair[0] for pair in malignant], [pair[1] for pair in malignant], color='g', s=10, label="Malignant")
plt.legend()


#coding: Utf-8

import unittest
import pandas as pd
#import numpy as np
from sklearn import linear_model

#あくまで複数変数を単回帰するためのロジックということに注意
#重回帰や他の多変量解析を行う場合、dfから個々の変数を抜き出すロジックを立てなければならない（変数削除等）

dates = pd.date_range("20151111", periods=5)#df&ts用日付ラベルdates定義

s1 = pd.Series([2,3,4,5,6], index=dates)
s2 = pd.Series([10,20,30,40,50], index=dates)
s3 = pd.Series([100,200,300,400,500], index=dates)
kpi = pd.Series([1,2,3,4,5], index=dates)
df = pd.concat([kpi, s1, s2, s3], axis=1)#tsを結合してdfへ axis=0は縦結合なので変更しないで
df.columns = ["kpi","s1","s2","s3"]#変数名は結合時に反映されないので別途命名

print(df[["s1"]].as_matrix()) #重回帰分析(xは多変量)のため、説明変数は[[ ]]で取り出す必要あり
print(df["kpi"].as_matrix()) #被説明変数はdfそのまま取り出して平気

print(df)

def lm(df):
	for i in list(df.columns.values)[1:]:
		clf = linear_model.LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
		clf.fit(df[[i]].as_matrix(), df["kpi"].as_matrix())#右が被説明変数
		print("変数{0}の回帰分析結果".format(i))

		print("回帰係数：{0}".format(float(clf.coef_)))
		print("切片項：{0}".format(clf.intercept_))
		r2 = clf.score(df[[i]].as_matrix(), df["kpi"].as_matrix())
		print("決定係数R^2：{0}".format(r2))
		print( )
		#R-squareの別途計算にclf.score内の引数を再度正確に指定しないと決定係数-6.0とか出るので要注意

lm(df)


#!/usr/bin/python3
""" strict_slashes set to false in all route definitions.
    Any route with or without a trailing slash will trigger
    the specific decorated function.
"""

from flask import Flask, escape
app = Flask(__name__)

@app.route('/', strict_slashes=False)
def index():
    """ This function displays 'Hello HBNB'
        when the '/' route is visited on the
        server.
    """
    return 'Hello HBNB!'

@app.route('/hbnb', strict_slashes=False)
def hbnb():
    """ This function displays `HBNB`
        when the '/hbnb' route is visited on the
        server. <text> default is set to 'cool'.
    """
    return 'HBNB'

@app.route('/c/<text>', strict_slashes=False)
def c_text(text='cool'):
    """ This function displays `C <text>`
        when the '/c/' route is visited on the
        server. <text> default is set to 'cool'.
    """
    text = text.replace('_', ' ')
    result = "C %s" % escape(text)
    return result

@app.route('/python/', strict_slashes=False)
@app.route('/python/<text>', strict_slashes=False)
def python_text(text='is cool'):
    """ This function displays `Python <text>`
        when the '/python/' route is visited on the
        server.
    """
    text = text.replace('_', ' ')
    result = "Python %s" % escape((text))
    return result

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)


from django.db import models
from django.contrib.auth.models import User
# Create your models here.

# Use this dictionary to define attributes of fields that need to be referenced elsewhere, for example in validation
# Key's should be in the format <table name>__<field name>__<attribute>
_model_field_limits = {
    'ChatRoom__name__max_length': 20,
    'Message__message__max_length': 250
}

class ChatRoom(models.Model):
    name = models.CharField(max_length=_model_field_limits['ChatRoom__name__max_length'])

class ChatMessage(models.Model):
    user_id = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
    chat_room_id = models.ForeignKey(ChatRoom, null=True, on_delete=models.SET_NULL)
    datetime = models.DateTimeField()
    message = models.CharField(max_length=_model_field_limits['Message__message__max_length'])
    parent_message_id = models.IntegerField(null=True)


from flask import Flask, request, json, render_template, send_file
from pymongo import MongoClient
from decouple import config
from bson import json_util
from bson.objectid import ObjectId
from datetime import datetime
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.graphics.barcode import code39, code128, code93
from reportlab.graphics.barcode import eanbc, qr, usps
from reportlab.graphics.shapes import Drawing
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import mm
from reportlab.pdfgen import canvas
from reportlab.graphics import renderPDF
import os

app = Flask(__name__)

# Read the mongo_uri from the .env file
mongo_uri = config('MONGODB_URI')
db_name = config('DBNAME')

def parse_json(data):
    return json.loads(json_util.dumps(data))

@app.route('/', methods=['GET'])
def home():
    return render_template('home.html')

@app.route('/enter_doctors', methods=['GET'])
def enter_doctors():
    return render_template('enter-doctor.html')

@app.route('/enter_patients', methods=['GET'])
def enter_patients():
    return render_template('enter-patient.html')

@app.route('/get_doctors', methods=['GET'])
def get_doctors():
    client = MongoClient(mongo_uri)
    try:
        client.server_info()  # Check if connected to MongoDB
        db = client.get_database(db_name)
        doctors_collection = db.get_collection('doctors_collection')

        doctors_list = list(doctors_collection.find({}))
        return render_template("get-doctor.html", doctors_list = doctors_list)
    except Exception as e:
        print(f'Error getting doctors data: {e}')
        return parse_json({'message': 'An error occurred'}), 500
    finally:
        client.close()

@app.route('/enter_prescription', methods=['GET'])
def enter_prescription():
    client = MongoClient(mongo_uri)
    try:
        client.server_info()  # Check if connected to MongoDB
        db = client.get_database(db_name)
        medications_collection = db.get_collection('medications_collection')
        patient_collection = db.get_collection('patient_collection')
        doctors_collection = db.get_collection('doctors_collection')

        doctors_list = list(doctors_collection.find({}))
        patients_list = list(patient_collection.find({}))
        medications_list = list(medications_collection.find({}))
        return render_template('enter-prescription.html', medications_list = medications_list, doctors_list=doctors_list, patients_list=patients_list)
    except Exception as e:
        print(f'Error getting prescription data: {e}')
        return parse_json({'message': 'An error occurred'}), 500
    finally:
        client.close()

@app.route('/get_patients', methods=['GET'])
def get_patients():
    client = MongoClient(mongo_uri)
    try:
        client.server_info()  # Check if connected to MongoDB
        db = client.get_database(db_name)
        patient_collection = db.get_collection('patient_collection')

        patients_list = list(patient_collection.find({}))
        return render_template("get-patient.html", patients_list = patients_list)
    except Exception as e:
        print(f'Error getting patient data: {e}')
        return parse_json({'message': 'An error occurred'}), 500
    finally:
        client.close()

@app.route('/insert_doctor', methods=['POST'])
def insert_doctor():
    data = json.loads(request.get_data())
    client = MongoClient(mongo_uri)
    try:
        client.server_info()  # Check if connected to MongoDB
        db = client.get_database(db_name)
        doctors_collection = db.get_collection('doctors_collection')

        insert_result = doctors_collection.insert_one(data)
        return parse_json({'message': 'Doctor data inserted successfully', 'inserted_id': str(insert_result.inserted_id)})
    except Exception as e:
        print(f'Error inserting doctor data: {e}')
        return parse_json({'message': 'An error occurred'}), 500
    finally:
        client.close()

@app.route('/insert_patient', methods=['POST'])
def insert_patient():
    data = json.loads(request.get_data())
    client = MongoClient(mongo_uri)
    try:
        client.server_info()  # Check if connected to MongoDB
        db = client.get_database(db_name)
        patient_collection = db.get_collection('patient_collection')

        insert_result = patient_collection.insert_one(data)
        return parse_json({'message': 'Patient data inserted successfully', 'inserted_id': str(insert_result.inserted_id)})
    except Exception as e:
        print(f'Error inserting patient data: {e}')
        return parse_json({'message': 'An error occurred'}), 500
    finally:
        client.close()

@app.route('/insert_prescription', methods=['POST'])
def insert_prescription():
    data = json.loads(request.get_data())
    client = MongoClient(mongo_uri)
    print(data)
    try:
        client.server_info()  # Check if connected to MongoDB
        db = client.get_database(db_name)
        prescription_collection = db.get_collection('prescription_collection')
        medications_collection = db.get_collection('medications_collection')
        patient_collection = db.get_collection('patient_collection')
        doctors_collection = db.get_collection('doctors_collection')

        selected_doctor = list(doctors_collection.find({"_id":ObjectId(data['doctor_name'])}))[0]
        selected_patient = list(patient_collection.find({"_id":ObjectId(data['patient_name'])}))[0]
        selected_medication = list(medications_collection.find({"_id":ObjectId(data['prescription_name'])}))[0]

        print(selected_doctor)
        print(selected_patient)
        print(selected_medication)

        prescription_object = {
            "prescription_date": "{:%B %d, %Y}".format(datetime.now()),
            "patient_name" : "{} {}".format(selected_patient['firstName'], selected_patient['lastName']),
            "patient_age": selected_patient['age'],
            "patient_phone": selected_patient['phoneNumber'],
            "patient_dob": selected_patient['dob'],
            "patient_email": selected_patient.get('email'),
            "patient_gender": selected_patient.get('gender'),
            "patient_address": selected_patient.get('address'),
            "patient_allergies": selected_patient.get('allergies'),
            "patient_health_condition": selected_patient.get('healthCondition'),

            "selected_medication": selected_medication.get('name'),
            "purpose": data.get('purpose'),
            "dosage": data.get('dosage') ,
            "route": data.get('route'),
            "frequency": data.get('frequency'),

            "doctor_name": "{} {}".format(selected_doctor['firstName'], selected_doctor['lastName']),
            "doctor_phone": selected_doctor.get('phoneNumber'),
            "doctor_email": selected_doctor.get('email'),
        }

        insert_result = prescription_collection.insert_one(prescription_object).inserted_id
        inserted_prescription = list(prescription_collection.find({"_id":ObjectId(insert_result)}))[0]

        barcode_value = insert_result
        # barcode128 = code128.Code128(barcode_value)
        # x = 1 * mm
        # y = 285 * mm
        # x1 = 6.4 * mm

        # Load JSON data
        data = inserted_prescription

        # Create a PDF
        if not os.path.exists('cached'):
            os.makedirs('cached')
        prescription_pdf_path = "cached/prescription.pdf"
        doc = SimpleDocTemplate(prescription_pdf_path, pagesize=letter)

        elements = []

        # Styles
        styles = getSampleStyleSheet()
        style = styles["BodyText"]

        # Create a table to display the data
        data = [
            ["Prescription Date:", data["prescription_date"]],
            ["Patient Name:", data["patient_name"]],
            ["Patient Age:", data["patient_age"]],
            ["Patient Phone:", data["patient_phone"]],
            ["Patient Date of Birth:", data["patient_dob"]],
            ["Patient Email:", data["patient_email"]],
            ["Patient Gender:", data["patient_gender"]],
            ["Patient Address:", data["patient_address"]],
            ["Patient Allergies:", data["patient_allergies"]],
            ["Patient Health Condition:", data["patient_health_condition"]],
            ["Selected Medication:", data["selected_medication"]],
            ["Purpose:", data["purpose"]],
            ["Dosage:", data["dosage"]],
            ["Route:", data["route"]],
            ["Frequency:", data["frequency"]],
            ["Doctor Name:", data["doctor_name"]],
            ["Doctor Phone:", data["doctor_phone"]],
            ["Doctor Email:", data["doctor_email"]],
        ]

        table = Table(data, colWidths=120, rowHeights=20)
        table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
            ('BACKGROUND', (0, 1), (-1, -1), colors.whitesmoke),
            ('GRID', (0, 0), (-1, -1), 1, colors.black)
        ]))

        elements.append(Paragraph("Prescription Details", style))
        elements.append(table)

        # Generate a Code128 barcode
        # barcode = code128.Code128("123456789", writer=renderPDF)
        # barcode.drawOn(doc, 50, 50)  # Adjust the coordinates as needed

        # Build the PDF
        doc.build(elements)

        print("Prescription PDF created: prescription.pdf")
        return send_file(os.getcwd() + "/" + prescription_pdf_path, as_attachment=True)

        # return parse_json({'message': 'Prescription data inserted successfully', 'inserted_id': str(insert_result.inserted_id)})
    except Exception as e:
        print(f'Error inserting prescription data: {e}')
        return parse_json({'message': 'An error occurred'}), 500
    finally:
        client.close()

if __name__ == '__main__':
    app.run(debug=True)


from collections import deque

def main():
    M, N, H = map(int, input().split())
    tomatoBox = [[list(map(int, input().split())) for _ in range(N)] for _ in range(H)]
    visited = [[[False] * M for _ in range(N)] for _ in range(H)]

    startHeightRowCol = []
    for h in range(H):
        for r in range(N):
            for c in range(M):
                if tomatoBox[h][r][c] == 1:
                    visited[h][r][c] = True
                    startHeightRowCol.append((h, r, c))
    days = changingTomato(tomatoBox, visited, startHeightRowCol)

    for h in range(H):
        for r in tomatoBox[h]:
            if 0 in r:
                print(-1)
                return
    else:
        print(days)

def changingTomato(box: list, visited: list, start: list):
    x = [-1, 1, 0, 0, 0, 0]
    y = [0, 0, -1, 1, 0, 0]
    z = [0, 0, 0, 0, -1, 1]

    queue = deque(start)
    daysQueue = deque([0] * len(queue))

    days = 0
    while queue:
        currH, currR, currC = queue.popleft()
        days = daysQueue.popleft()

        for i in range(6):
            h = currH + z[i]
            r = currR + x[i]
            c = currC + y[i]
            if 0 <= h < len(box) and 0 <= r < len(box[0]) and 0 <= c < len(box[0][0]):
                if not visited[h][r][c]:
                    if box[h][r][c] == 0:
                        box[h][r][c] = 1
                        visited[h][r][c] = True
                        queue.append((h, r, c))
                        daysQueue.append(days + 1)

    return days

if __name__ == "__main__":
    main()


from django.contrib import admin

from .models import Sudoku

class SudokuAdmin(admin.ModelAdmin):
    list_display = ('pk', 'puzzle', 'difficulty',
                    'modified', 'published', 'is_published')
    list_editable = ('puzzle', 'difficulty', )
    search_fields = ('puzzle', 'pk',)
    date_hierarchy = 'modified'
    ordering = ['-modified',]
    readonly_fields = ['created', 'modified', ]
    actions_on_bottom = True
    actions_on_top = True
    save_on_top = True

admin.site.register(Sudoku, SudokuAdmin)


#coding=utf-8
from collections import OrderedDict

USERS_PER_PAGE = 20

PHOTOS_PER_PAGE = 15

MAX_PAGE = 15

MAX_FOLLOW_NUM = 450

BLOG_POSTS_PER_PAGE = 10

ACTIVITY_PER_PAGE = 20

PASSWORD_SALT = '!QAZ@WSXcde3)Okm9i'

MAX_UPLOAD_SIZE = 10

MAX_AVATAR_SIZE = 2

HOT_PHOTO_INTERVAL = 300

EVENTS = {
    'USER_ACTIVATION': 'user_activation',
    'USER_CREATE': 'user_create',
    'USER_FOLLOW': 'user_follow',
    'USER_UNFOLLOW': 'user_unfollow',
    'PHOTO_LIKE': 'photo_like',
    'PHOTO_UNLIKE': 'photo_unlike',
    'PHOTO_CREATE': 'photo_create',
    'PHOTO_UPLOAD': 'photo_upload',
    'PHOTO_DELETE': 'photo_delete',
    'PHOTO_COMMENT_ADD': 'photo_comment_add',
    'PHOTO_COMMENT_DELETE': 'photo_comment_delete',
    'BLOG_ADD': 'blog.after_insert',
    'BLOG_EDIT': 'blog.after_update',
    'BLOG_DELETE': 'blog_delete',
    'BLOG_COMMENT_ADD': 'blog_comment.after_insert',
}

ACTIVITY_ACTION = {
    'PHOTO_CREATE': 100,
    'PHOTO_LIKE': 101,
    'PHOTO_UNLIKE': 103,
    'PHOTO_COMMENT_ADD': 104,
    'PHOTO_COMMENT_DELETE': 105,
    'PHOTO_DELETE': 106,
    'USER_CREATE': 200,
    'USER_ACTIVATION': 201,
    'USER_FOLLOW': 202,
    'USER_UNFOLLOW': 203,
    'BLOG_ADD': 301,
    'BLOG_EDIT': 302,
    'BLOG_DELETE': 303,
    'BLOG_COMMENT_ADD': 304,
}

AVATAR_SIZE = {
    's': '48x48^',
    'm': '100x100^',
    'l': '160x160^',
}

PHOTO_SIZE = {
    's': '70x70^',
    'm': '215x215^',
    'l': '1200x12000',
}

REDIS_KEY = {
    'USER_PHOTO_COUNT': 'h_usr_pht_cnt',
    'USER_LIKED_COUNT': 'h_usr_lkd_cnt', # 被喜欢的次数
    'USER_LIKES_COUNT': 'h_usr_lks_cnt', # 喜欢的照片的张数
    'TABLE_ITEMS': 'h_tbl_tms:{table}',
    'USER_MESSAGE': 'l_usr_msg:{user_id}',
    'HOT_TAGS': 'set_hot_tags',
}

USER_LEVEL = [0, 10, 100, 500, 1000]
USER_LEVEL_CN = [u'小兔崽', u'功夫兔', u'普京兔', u'流氓兔', u'无敌兔']
USER_LEVEL_PHOTOS_PER_WEEK = [10, 20, 30, 40, 50]

INVITE_NUM = [5, 10, 15, 20, 25]


import csv
from matplotlib import pyplot as plt
import matplotlib
import random

class ResultReader():
    def __init__(self):

        with open('Results.csv') as csvfile:
            readCSV = csv.reader(csvfile, delimiter=',')
            rows_list = []

            count = 0
            for row in readCSV:
                for index, item in enumerate(row):
                    if count < 1:
                        rows_list.append([item, []])
                    else:
                        rows_list[index][1].append(row[index])
                #print(count)
                count += 1
            print("Rows list: ", rows_list)

            self.dates= []
            self.example_prices_all = []
            self.output_dict = {}
            for index, item in enumerate(rows_list):
                if index > 1:
                    example_prices = []
                    for i in rows_list[index][1]:
                        if len(i) > 2:
                            string = i[1:-1]
                            num = int(string)
                        else: num = 0
                        example_prices.append(num)
                    # print(example_prices)
                    self.example_prices_all.append([rows_list[index][0],example_prices])
                    self.dates.append(rows_list[index][0])

            print("Actual Dates", self.dates)

            example_dates = []
            for i in rows_list[0][1]:
                if i[4] == '/':
                    string = i[2:4]
                elif i[6] == '/':
                    #print("1st: ",i[2:6])
                    string = i[2:6]
                    #print("2nd: ",string)
                num = float(string)
                example_dates.append(num)
            print("Example Prices All: ", self.example_prices_all)
            print("Example Dates: ", example_dates)

            font = {'family': 'normal',
                    'weight': 'bold',
                    'size': 5}

            matplotlib.rc('font', **font)

            print("Dates: {}".format(example_dates))
            self.dates_dict = {}

            for index,item in enumerate(example_dates):
                self.dates_dict[index] = item
            print("Dates dictionary: {}".format(self.dates_dict))
            # self.plotting()
            self.output()

    def output(self):
        # Initialise the output
        for index, item in enumerate(self.example_prices_all):
            self.output_dict[index] = [[],[]]

        # Populate the output
        for index, item in enumerate(self.example_prices_all):
            # print("index: ", index)
            tempDates = []
            tempPrices = []
            # print(item[1])

            emptyflag = 1
            for ind, ite in enumerate(item[1]):
                if ite != 0:
                    tempDates.append(self.dates_dict[ind])
                    tempPrices.append(ite)
                    emptyflag = 0

            if emptyflag == 1:
                break
                # raise Exception("Sorry there is an empty to date to be removed: {}".format(self.dates_dict[index]))
            self.output_dict[index] = [tempDates, tempPrices]
        print("Output Dictionary", self.output_dict)
        return self.output_dict

    def plotting(self):
        for i in self.example_prices_all:
            tempDates = []
            tempPrices = []
            for ind, ite in enumerate(i[1]):
                if ite != 0:
                    tempDates.append(self.dates_dict[ind])
                    tempPrices.append(ite)

            plt.plot(tempDates, tempPrices, label = i[0])

        #     for x, y in zip(example_dates, i[1]):
        #         label = i[0]
        #
        #         plt.annotate(label,  # this is the text
        #                      (x, y),  # this is the point to label
        #                      textcoords="offset points",  # how to position the text
        #                      xytext=(random.randrange(0,20,10), 0),  # distance from text to points (x,y)
        #                      ha='center')  # horizontal alignment can be left, right or center
        #
        # plt.plot(example_dates, example_prices)
        # plt.legend()
        plt.show()

if __name__ == "__main__":
    Reader = ResultReader()
    Reader.plotting()
    output = Reader.output()


"""\
A pure Python package providing the core RDF constructs.

The packages is intended to provide the core RDF types and interfaces
for working with RDF. The package defines a plugin interface for
parsers, stores, and serializers that other packages can use to
implement parsers, stores, and serializers that will plug into the
rdflib package.

The primary interface `rdflib` exposes to work with RDF is
`rdflib.graph.Graph`.

A tiny example:

    >>> import rdflib

    >>> g = rdflib.Graph()
    >>> result = g.parse("http://www.w3.org/2000/10/swap/test/meet/white.rdf")

    >>> print("graph has %s statements." % len(g))
    graph has 19 statements.
    >>>
    >>> for s, p, o in g:
    ...     if (s, p, o) not in g:
    ...         raise Exception("It better be!")

    >>> s = g.serialize(format='n3')

"""
__docformat__ = "restructuredtext en"

# The format of the __version__ line is matched by a regex in setup.py
__version__ = "4.0.1"
__date__ = "2013/05/22"

__all__ = [
    'URIRef',
    'BNode',
    'Literal',
    'Variable',

    'Namespace',

    'Dataset',
    'Graph',
    'ConjunctiveGraph',

    'RDF',
    'RDFS',
    'OWL',
    'XSD',

    'util',
]

import sys
assert sys.version_info >= (2, 5, 0), "rdflib requires Python 2.5 or higher"
del sys

import logging
_LOGGER = logging.getLogger("rdflib")
_LOGGER.info("RDFLib Version: %s" % __version__)

NORMALIZE_LITERALS = True
"""
If True - Literals lexical forms are normalized when created.
I.e. the lexical forms is parsed according to data-type, then the
stored lexical form is the re-serialized value that was parsed.

Illegal values for a datatype are simply kept.  The normalized keyword
for Literal.__new__ can override this.

For example:

>>> from rdflib import Literal,XSD
>>> Literal("01", datatype=XSD.int)
rdflib.term.Literal(u'1', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))

This flag may be changed at any time, but will only affect literals
created after that time, previously created literals will remain
(un)normalized.

"""

DAWG_LITERAL_COLLATION = False
"""
DAWG_LITERAL_COLLATION determines how literals are ordered or compared
to each other.

In SPARQL, applying the >,<,>=,<= operators to literals of
incompatible data-types is an error, i.e:

Literal(2)>Literal('cake') is neither true nor false, but an error.

This is a problem in PY3, where lists of Literals of incompatible
types can no longer be sorted.

Setting this flag to True gives you strict DAWG/SPARQL compliance,
setting it to False will order Literals with incompatible datatypes by
datatype URI

In particular, this determines how the rich comparison operators for
Literal work, eq, __neq__, __lt__, etc.
"""

from rdflib.term import (
    URIRef, BNode, Literal, Variable)

from rdflib.namespace import Namespace

from rdflib.graph import Dataset, Graph, ConjunctiveGraph

from rdflib.namespace import RDF, RDFS, OWL, XSD

from rdflib import plugin
from rdflib import query
# tedious sop to flake8
assert plugin
assert query

from rdflib import util


from tkinter import *
import math
# ---------------------------- CONSTANTS ------------------------------- #
PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
FONT_NAME = "Courier"
WORK_MIN = 25
SHORT_BREAK_MIN = 5
LONG_BREAK_MIN = 20
reps =0
first = 0
timer = None

# ---------------------------- TIMER RESET ------------------------------- #
def reset_timer():
    global reps
    global first
    first =0
    reps=0
    window.after_cancel(timer)
    canvas.itemconfig(timer_text,text="00:00")
    label.config(text="Timer")
    check_mark.config(text="")

# ---------------------------- TIMER MECHANISM ------------------------------- #
def timer_mech():
    global reps
    reps+=1
    work_secs = WORK_MIN *60
    short_break_secs = SHORT_BREAK_MIN * 60
    long_break_secs = LONG_BREAK_MIN *60

    if reps % 8 == 0:
        label.config(text ="Break",fg=RED)
        count_down(long_break_secs)
    elif reps%2==0 :
        label.config(text ="Break",fg=PINK)
        count_down(short_break_secs)
    else:
        label.config(text ="Work",fg=GREEN)
        count_down(work_secs)

def start_timer():
    global first

    if first == 0: #if the user presses start again it will have no effect
        first = 1
        timer_mech()

# ---------------------------- COUNTDOWN MECHANISM ------------------------------- #
def count_down(count):
    global reps
    mins = math.floor(count/60)
    secs=count%60
    if secs <10:

        secs=f"0{secs}"
    if mins <10:

        mins=f"0{mins}"
    canvas.itemconfig(timer_text,text=f"{mins}:{secs}")
    if count>0:
        global timer
        timer = window.after(1000,count_down,count-1)
    else:
        timer_mech()
        marks =""
        work_sess = int(reps/2)
        for _ in range(work_sess):
            marks+="✔"
        check_mark.config(text=marks)

# ---------------------------- UI SETUP ------------------------------- #
window = Tk()
window.title("Pomodoro")
window.config(padx=100,pady=50,bg=YELLOW)

label = Label(text="Timer",fg=GREEN,bg=YELLOW,font=(FONT_NAME,40,"bold"))
label.grid(column=1,row=0)

canvas = Canvas(width=200,height =224,bg=YELLOW,highlightthickness=0)
tomato_img = PhotoImage(file="tomato.png")
canvas.create_image(100,112,image=tomato_img)
timer_text = canvas.create_text(100,130,text="00:00",fill="white",font=(FONT_NAME,35,"bold"))
canvas.grid(column=1,row=1)

start = Button(text="Start",highlightthickness=0,command= start_timer)
start.grid(column=0,row=2)

reset = Button(text="Reset",highlightthickness=0,command = reset_timer)
reset.grid(column=2,row=2)

check_mark = Label(fg=GREEN,bg=YELLOW,font=(FONT_NAME,15))
check_mark.grid(column=1,row=3)

window.mainloop()


import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np

def add_or_new(d, k, v):
    try:
        d[k] += v
    except KeyError:
        d[k] = v.copy()

def find_bin(val, ar):
    # Find the first bin which has left index geq the query.
    # The query belongs in the bin to the left of this one.
    # Assumes the bins are right-inclusive.
    try:
        return np.argmin(ar < val)
    except TypeError:
        return np.argmin([a == val for a in ar])
    raise NotImplementedError  # comparison between bins of objects that aren't exact is not supported

def only_finite(ar):
    return ar[np.isfinite(ar)]

def get_feat_vals(ebm_global, feat_id):
    good_vals = ebm_global.data(feat_id)["names"]
    return good_vals

def calc_density(
    use_density, feat_vals1, feat_vals2, feat_id1, feat_id2, X_train, laplace=0
):
    if use_density:
        density = np.zeros((len(feat_vals1), len(feat_vals2))) + laplace
        for x in X_train:
            idx1 = find_bin(x[feat_id1], feat_vals1)
            idx2 = find_bin(x[feat_id2], feat_vals2)
            density[idx1, idx2] += 1
        return density
    else:
        return None

def overlap(bounds1, bounds2):
    assert bounds1[0] < bounds1[1]
    assert bounds2[0] < bounds2[1]
    if bounds1[0] == bounds2[0] or bounds1[1] == bounds2[1]:
        return True
    if bounds1[0] > bounds2[0]:
        return bounds1[1] < bounds2[1]
    else:  # bounds1[0] < bounds2[0]
        return bounds2[1] < bounds1[1]

def merge_arrs(ar1_names, ar2_names, ar2_values):
    # Preserves the bins of ar1.
    ar_mapped = np.zeros((len(ar1_names) - 1))
    for i, val in enumerate(ar2_values):
        raw_left_boundary = ar2_names[i]
        try:
            raw_right_boundary = ar2_names[i + 1]
        except:
            raw_right_boundary = np.inf

        for j, left_boundary in enumerate(ar1_names):
            mapped_left_boundary = left_boundary
            try:
                mapped_right_boundary = ar1_names[j + 1]
            except:
                mapped_right_boundary = np.inf
            if raw_right_boundary < raw_left_boundary:
                temp = raw_right_boundary
                raw_right_boundary = raw_left_boundary
                raw_left_boundary = temp
            if overlap(
                (raw_left_boundary, raw_right_boundary),
                (mapped_left_boundary, mapped_right_boundary),
            ):
                ar_mapped[j] += val
                break
    return ar_mapped

def plot_interaction(
    val_names1,
    val_names2,
    before,
    after,
    dataset_name,
    feat_name1,
    feat_name2,
    model_name,
    move_name,
):
    # Plots an interaction effect before and after purification.
    # Set up figure and image grid
    fig = plt.figure(figsize=(9.75, 3))
    grid = ImageGrid(
        fig,
        111,  # as in plt.subplot(111)
        nrows_ncols=(1, 2),
        axes_pad=0.15,
        share_all=True,
        cbar_location="right",
        cbar_mode="single",
        cbar_size="7%",
        cbar_pad=0.15,
    )

    # Add data to image grid
    extent = (val_names2[0], val_names2[-1], val_names1[0], val_names1[-1])

    aspect = float(extent[3] - extent[2]) / float(extent[1] - extent[0])
    aspect = 1 / aspect

    im = grid[0].imshow(
        before, aspect=aspect, origin="lower", interpolation="none", extent=extent
    )
    im = grid[1].imshow(
        after, aspect=aspect, origin="lower", interpolation="none", extent=extent
    )

    # Colorbar
    ax = grid[-1]
    ax.cax.colorbar(im)
    ax.cax.toggle_label(True)

    grid[0].set_ylabel(feat_name1, fontsize=22)
    grid[0].set_xlabel(feat_name2, fontsize=22)
    grid[1].set_xlabel(feat_name2, fontsize=22)
    grid[0].tick_params(axis="both", which="major", labelsize=16)
    grid[0].tick_params(axis="both", which="minor", labelsize=12)
    grid[1].tick_params(axis="both", which="major", labelsize=16)
    grid[1].tick_params(axis="both", which="minor", labelsize=12)
    ax.cax.tick_params(axis="both", which="major", labelsize=16)
    ax.cax.tick_params(axis="both", which="minor", labelsize=12)

    plt.savefig(
        "figs/{}/interactions/{}_{}_{}".format(
            dataset_name, feat_name1, feat_name2, model_name, move_name
        )
    )


import unittest
from .context import Layup

class TestLayup(unittest.TestCase):
    """ Tests for inputs.Layup. """

    def test_Layup_omega(self):

        expected = 50
        actual = Layup(40,50,50,1).omega
        self.assertEqual(expected, actual, "Layup omega")

# unittest.main()


import requests
from bs4 import BeautifulSoup

# Set the URL of the web page to scrape
url = "https://hackerone.com"

# Make a request to the URL
response = requests.get(url)

# Parse the HTML content of the response using BeautifulSoup
soup = BeautifulSoup(response.content, "html.parser")

# Find all links in the page
links = soup.find_all("a")

# Create a list to store all links
all_links = []

# Loop through each link in the page
for link in links:
    href = link.get("href")
    if href is not None and href not in all_links:
        all_links.append(href)

# Loop through each link in the list and extract all links in the response
for link in all_links:
    try:
        response = requests.get(link)
        soup = BeautifulSoup(open(html_path, 'r'),"html.parser",from_encoding="iso-8859-1")
        links = soup.find_all("a")
        for l in links:
            href = l.get("href")
            if href is not None and href not in all_links:
                all_links.append(href)
    except:
        pass

# Save the list of all links to a file
with open("output.txt", "w", encoding="utf-8") as file:
    for link in all_links:
        file.write(link + "\n")


import torch
from torch import nn
import torch.nn.functional as F
#from torchsummary import summary
from torch.utils.model_zoo import load_url as load_state_dict_from_url
import re

class BasicConv2d(nn.Module):
    """Some Information about BasicConv2d"""
    def __init__(self, in_filters, out_filters, kernel_size=(1,1), stride=(1,1), padding=(0,0), bias=False):
        super(BasicConv2d, self).__init__()
        self.conv = nn.Conv2d(in_filters, out_filters, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias)
        self.bn = nn.BatchNorm2d(out_filters, eps=0.001, momentum=0.1, affine=True, track_running_stats=True)

    def forward(self, x):
        x = self.conv(x)
        return F.relu(self.bn(x))

class Inception(nn.Module):
    """Some Information about Inception"""
    def __init__(self, st_bconv_in_filters,b1_bconv_out_filters, b2_bconv1_out_filters,b2_bconv2_out_filters,b3_bconv1_out_filters,b3_bconv2_out_filters,b4_bconv_out_filters):
        super(Inception, self).__init__()
        self.branch1 = BasicConv2d(in_filters=st_bconv_in_filters,out_filters=b1_bconv_out_filters, kernel_size=(1,1), stride=(1,1), bias=False)
        self.branch2 = nn.Sequential(
            BasicConv2d(in_filters=st_bconv_in_filters,out_filters=b2_bconv1_out_filters, kernel_size=(1,1), stride=(1,1), bias=False),
            BasicConv2d(in_filters=b2_bconv1_out_filters,out_filters=b2_bconv2_out_filters, kernel_size=(3,3), stride=(1,1),padding=(1,1),bias=False)
        )
        self.branch3 = nn.Sequential(
            BasicConv2d(in_filters=st_bconv_in_filters,out_filters=b3_bconv1_out_filters, kernel_size=(1,1), stride=(1,1), bias=False),
            BasicConv2d(in_filters=b3_bconv1_out_filters,out_filters=b3_bconv2_out_filters, kernel_size=(3,3), stride=(1,1),padding=(1,1),bias=False)
        )
        self.branch4 = nn.Sequential(
            nn.MaxPool2d(kernel_size=3, stride=1, padding=1, dilation=1, ceil_mode=True),
            BasicConv2d(in_filters=st_bconv_in_filters,out_filters=b4_bconv_out_filters, kernel_size=(1,1), stride=(1,1), bias=False)
        )

    def forward(self, x):
        return torch.cat((self.branch1(x), self.branch2(x),self.branch3(x), self.branch4(x)),1)

class GoogLeNet(nn.Module):
    def __init__(self):
        super(GoogLeNet, self).__init__()

        self.conv1 = BasicConv2d(in_filters=3,out_filters=64, kernel_size=(7,7), stride=(2,2), padding=(3,3), bias=False)
        self.maxpool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=0,dilation=1,ceil_mode=True)

        self.conv2 = BasicConv2d(in_filters=64,out_filters=64, kernel_size=(1,1), stride=(1,1), bias=False)
        self.conv3 = BasicConv2d(in_filters=64,out_filters=192, kernel_size=(3,3), stride=(1,1),padding=(1,1), bias=False)
        self.maxpool2 = nn.MaxPool2d(kernel_size=3, stride=2, padding=0,dilation=1,ceil_mode=True)

        self.inception3a = Inception(st_bconv_in_filters=192,b1_bconv_out_filters=64,b2_bconv1_out_filters=96,b2_bconv2_out_filters=128,b3_bconv1_out_filters=16,b3_bconv2_out_filters=32,b4_bconv_out_filters=32)
        self.inception3b = Inception(st_bconv_in_filters=256,b1_bconv_out_filters=128,b2_bconv1_out_filters=128,b2_bconv2_out_filters=192,b3_bconv1_out_filters=32,b3_bconv2_out_filters=96,b4_bconv_out_filters=64)
        self.maxpool3 = nn.MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=True)

        self.inception4a = Inception(st_bconv_in_filters=480,b1_bconv_out_filters=192,b2_bconv1_out_filters=96,b2_bconv2_out_filters=208,b3_bconv1_out_filters=16,b3_bconv2_out_filters=48,b4_bconv_out_filters=64)
        self.inception4b = Inception(st_bconv_in_filters=512,b1_bconv_out_filters=160,b2_bconv1_out_filters=112,b2_bconv2_out_filters=224,b3_bconv1_out_filters=24,b3_bconv2_out_filters=64,b4_bconv_out_filters=64)
        self.inception4c = Inception(st_bconv_in_filters=512,b1_bconv_out_filters=128,b2_bconv1_out_filters=128,b2_bconv2_out_filters=256,b3_bconv1_out_filters=24,b3_bconv2_out_filters=64,b4_bconv_out_filters=64)
        self.inception4d = Inception(st_bconv_in_filters=512,b1_bconv_out_filters=112,b2_bconv1_out_filters=144,b2_bconv2_out_filters=288,b3_bconv1_out_filters=32,b3_bconv2_out_filters=64,b4_bconv_out_filters=64)
        self.inception4e = Inception(st_bconv_in_filters=528,b1_bconv_out_filters=256,b2_bconv1_out_filters=160,b2_bconv2_out_filters=320,b3_bconv1_out_filters=32,b3_bconv2_out_filters=128,b4_bconv_out_filters=128)
        self.maxpool4 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=True)

        self.inception5a = Inception(st_bconv_in_filters=832,b1_bconv_out_filters=256,b2_bconv1_out_filters=160,b2_bconv2_out_filters=320,b3_bconv1_out_filters=32,b3_bconv2_out_filters=128,b4_bconv_out_filters=128)
        self.inception5b = Inception(st_bconv_in_filters=832,b1_bconv_out_filters=384,b2_bconv1_out_filters=192,b2_bconv2_out_filters=384,b3_bconv1_out_filters=48,b3_bconv2_out_filters=128,b4_bconv_out_filters=128)

        self.avgpool = nn.AdaptiveAvgPool2d((1,1))
        self.dropout = nn.Dropout(p=0.2,inplace=False)
        self.fc = nn.Linear(in_features=1024, out_features=1000, bias=True)

    def forward(self, x):
        x = self.conv1(x)
        x = self.maxpool1(x)

        x = self.conv2(x)
        x = self.conv3(x)
        x = self.maxpool2(x)

        x = self.inception3a(x)
        x = self.inception3b(x)
        x = self.maxpool3(x)

        x = self.inception4a(x)
        x = self.inception4b(x)
        x = self.inception4c(x)
        x = self.inception4d(x)
        x = self.inception4e(x)
        x = self.maxpool4(x)

        x = self.inception5a(x)
        x = self.inception5b(x)

        x = self.avgpool(x)
        x = torch.flatten(x,1)
        x = self.dropout(x)
        return self.fc(x)

model_urls = {
    # GoogLeNet ported from TensorFlow
    'googlenet': 'https://download.pytorch.org/models/googlenet-1378be20.pth',
}

def googlenet(pretrained=False, progress=True, **kwargs):
    r"""GoogLeNet (Inception v1) model architecture from
    `"Going Deeper with Convolutions" <http://arxiv.org/abs/1409.4842>`_.
    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    model = GoogLeNet()

    if pretrained:
        state_dict = load_state_dict_from_url(model_urls['googlenet'],
                                              progress=progress)
        helper_state_dict = state_dict.copy()
        for key in helper_state_dict.keys():
            if re.match(r"aux*",key):
                del state_dict[key]

        #state_dict["conv1.conv.weight"]=state_dict["conv1.conv.weight"][:,:2,:,:]
        state_dict["fc.weight"] = _initialize_weights(model.fc.weight)
        state_dict["fc.bias"] = _initialize_weights(model.fc.bias)
        model.load_state_dict(state_dict)

    return model

def _initialize_weights(layer):
    import scipy.stats as stats
    X = stats.truncnorm(-2, 2, scale=0.01)
    values = torch.as_tensor(X.rvs(layer.numel()), dtype=layer.dtype)
    values = values.view(layer.size())
    with torch.no_grad():
        layer.copy_(values)
    return values

# def main():
#     model=googlenet(pretrained=True).cuda()
#     #summary(model,(3,224,224))

# if __name__=="__main__":
#     main()


import requests

# Get data from API. More info: https://gorest.co.in/
response = requests.get('https://gorest.co.in/public/v1/users')
# Get JSON from response
json_response = response.json()
# This JSON has two parts 'meta' and 'data'. Take just the data portion
json_data = json_response.get('data')
# Create a dictionary
gender_count = {'male': 0, 'female': 0}
# Go through the data, each user object is a JSON
for user in json_data:
    gender = user.get('gender')
    if gender == 'male':
        gender_count['male'] = gender_count['male'] + 1
    if gender == 'female':
        gender_count['female'] = gender_count['female'] + 1
# Final data
print(gender_count)


import random
import redis

pool = redis.ConnectionPool(host='localhost', port=6379, db=2)
redis_cli = redis.Redis(connection_pool=pool)

pipe = redis_cli.pipeline()

def create_data():
    user_id = 100000
    while user_id:
        redis_cli.setbit('article1:today', user_id, random.choice([1, 1, 1, 0]))
        redis_cli.setbit('article2:today', user_id, random.choice([1, 1, 1, 0, 0]))
        redis_cli.setbit('article3:today', user_id, random.choice([1, 1, 1, 0, 0, 0, 0]))
        user_id = user_id - 1

def print_users_read_article():
    print('So luong nguoi dung da xem bai bao 1: ', redis_cli.bitcount('article1:today'))

def print_users_read_a_article():
    pipe.bitcount('article1:today')
    pipe.bitcount('article2:today')
    pipe.bitcount('article3:today')
    print('Tong so nguoi da xem moi bai bao la: ', pipe.execute())

def print_num_article_123user_read():
    pipe.getbit('article1:today', 123)
    pipe.getbit('article2:today', 123)
    pipe.getbit('article3:today', 123)
    print('So bai bao nguoi dung 123 da xem ngay hom nay: ', sum(pipe.execute()))

def print_user123_read_2_article():
    # pipe.setbit('user123', 123, 1)
    # pipe.bitop('AND', '123:sawboth', 'user123', 'article1:today', 'article3:today')
    pipe.bitop('AND', '123:sawboth', 'article1:today', 'article3:today')
    pipe.getbit('123:sawboth', 123)
    # pipe.delete('123:sawboth', 'user123')
    # print('Nguoi dung 123 da xem 2 bai bao ngay hom nay? ', bool(pipe.execute()[2]))
    print('Nguoi dung 123 da xem 2 bai bao ngay hom nay? ', bool(pipe.execute()[1]))

def print_users_read_atleast_one():
    pipe.bitop('OR', 'atleastonearticle', 'article1:today', 'article2:today', 'article3:today')
    pipe.bitcount('atleastonearticle')
    pipe.delete('atleastonearticle')
    print('So nguoi xem it nhat mot bai bao hom nay: ', pipe.execute()[1])

def print_recommendation():
    pipe.bitop('XOR', 'recommendother', 'article1:today', 'article2:today')
    pipe.bitop('AND', 'recommend:article1', 'recommendother', 'article2:today')
    pipe.bitop('AND', 'recommend:article2', 'recommendother', 'article1:today')
    pipe.bitcount('recommendother')
    pipe.bitcount('recommend:article1')
    pipe.bitcount('recommend:article2')
    pipe.delete('recommendother', 'recommend:article1', 'recommend:article2')
    result = pipe.execute()
    print('So nguoi chua doc ca 2 bai bao: ', result[3])
    print('So nguoi da doc bai 2, va se gioi thieu bai 1: ', result[4])
    print('So nguoi da doc bai 1, va se gioi thieu bai 2: ', result[5])

if __name__ == '__main__':
    # create_data()
    # print_users_read_article()
    # print_users_read_a_article()
    # print_num_article_123user_read()
    print_user123_read_2_article()
    # print_users_read_atleast_one()
    # print_recommendation()


import random
import copy
import os
import time
import math
import csv

from Tree import Tree
from TreePop import TreePop
import copy

from joblib import Parallel, delayed
import joblib
"""
try:
    from tkinter import *
    from tkinter.ttk import *
except Exception as e:
    print("[ERROR]: {0}".format(e))
    from Tkinter import *
"""

class GA:

    def __init__(self,list_files,k_mut_prob = 0.4, k_crossover = 3, tournament_size=7, elitism =True, method = "swap"):
        self.k_mut_prob = k_mut_prob
        self.tournament_size = tournament_size
        self.elitism = elitism
        self.list_files = list_files
        self.k_crossover = k_crossover
        self.nodeNum = list_files[0][0][0]
        self.method = method

    @staticmethod
    def swap(tree, mut_pos1, mut_pos2):

        tmp_tree = copy.deepcopy(tree)
        # if they're the same, skip to the chase
        if mut_pos1 == mut_pos2:
            return tmp_tree

        # Otherwise swap them:
        hub1 = tmp_tree.prufer[mut_pos1]
        hub2 = tmp_tree.prufer[mut_pos2]

        tmp_tree.prufer[mut_pos2] = hub1
        tmp_tree.prufer[mut_pos1] = hub2

        return tmp_tree

    @staticmethod
    def swap_2opt(tree, mut_pos1, mut_pos2):
        tmp_tree = copy.deepcopy(tree)
        # if they're the same, skip to the chase
        if mut_pos1 == mut_pos2:
            return tmp_tree

        if(mut_pos1>mut_pos2):
            tmp = mut_pos1
            mut_pos1 = mut_pos2
            mut_pos2 = tmp

        fp = [tree.prufer[l] for l in range(mut_pos1)]
        lp = [tree.prufer[l] for l in range(mut_pos2+1, len(tree.prufer))]
        middle = [tree.prufer[l] for l in range(mut_pos2,mut_pos1-1,-1)]
        tree.prufer = fp+middle+lp
        return tree

    def tournament_select(self, population):
        '''
        TreePop() --> Tree(),TreePop()

        Randomly selects tournament_size amount of Tree() from the input population.
        Takes the fittest from the smaller number of Tree().

        Principle: gives worse Tree() a chance of succeeding, but favours good Tree()
        The first argument is the Tree with the best fitness, we call this func over and over until we have a new population
        '''

        # New smaller population (not intialised)
        tournament_pop = TreePop(self.tournament_size,self.list_files)

        # fills it with random individuals (can choose same twice)
        for i in range(self.tournament_size-1):
            tournament_pop.tree_pop.append(random.choice(population.tree_pop))

        # returns the fittest:
        return tournament_pop.get_fittest(),tournament_pop

    def crossover_kpoint(self, parent1, parent2):
        """
        Same as crossover_random. But this time there are k points and not just a start_pos and end_pos

        """
        # new child
        child_Tree = Tree(self.list_files, prufer = [None for k in range(self.nodeNum-2)])

        #k_crossover random point
        k_rd_point = []
        while((len(list(set(k_rd_point)))!= self.k_crossover) and (len(k_rd_point) !=self.k_crossover)):
            tmp = random.randint(0,len(parent1.prufer))
            if tmp not in k_rd_point:
                k_rd_point.append(tmp)
        k_rd_point.sort()

        start = 0
        cpt = 0
        parent_to_choose = [parent1, parent2]

        #Creating the child prufer sequence. If k_crossover = 3, we have [parent1,parnet2,parent1]
        for end in k_rd_point:
            for i in range(start,end):
                child_Tree.prufer[i] = parent_to_choose[cpt%2].prufer[i]
            start = end
            cpt+=1

        #Replce the last None with the parents who should be last
        for i in range(len(parent2.prufer)):
            # complete the prufer sequence with parent2
            if child_Tree.prufer[i] == None :
                child_Tree.prufer[i] = parent_to_choose[cpt%2].prufer[i]

        child_Tree.calc_fit()

        return child_Tree

    def crossover_random(self, parent1, parent2):
        '''
        Tree(), Tree() --> Tree()

        Returns a child tree Tree() after breeding the two parent Tree.
        Trees must be of same length.

        Breeding is done by selecting a random range of parent1, and placing it into the empty child route (in the same place).
        Gaps are then filled in, without duplicates, in the order they appear in parent2.

        For example:
            parent1: 0123456789
            parent1: 5487961320

            start_pos = 0
            end_pos = 4

            unfilled child: 01234*****
            filled child:   0123458796

            * = None

        '''

        # new child
        child_Tree = Tree(self.list_files, prufer = [None for k in range(self.nodeNum-2)])

        # Two random integer indices of the parent1:
        start_pos = random.randint(0,len(parent1.prufer))
        end_pos = random.randint(0,len(parent1.prufer))

        #### takes the sub-route from parent one and sticks it in itself:
        # if the start position is before the end:
        if start_pos < end_pos:
            # do it in the start-->end order
            for x in range(start_pos,end_pos):
                child_Tree.prufer[x] = parent1.prufer[x] # set the values to eachother

        # if the start position is after the end:
        elif start_pos > end_pos:
            # do it in the end-->start order
            for i in range(end_pos,start_pos):
                child_Tree.prufer[i] = parent1.prufer[i] # set the values to eachother

        # For the None values, replace it with parent2
        for i in range(len(parent2.prufer)):
            # complete the prufer sequence with parent2
            if child_Tree.prufer[i] == None :
                child_Tree.prufer[i] = parent2.prufer[i]

        # returns the child route (of type Route())
        child_Tree.calc_fit()
        return child_Tree

    def mutate(self, tree_mut):
        '''
        Tree() --> Tree()

        Swaps two random indexes in the childs prufer sequence.
        Runs k_mut_prob*100 % of the time
        '''

        tmp_tree = copy.deepcopy(tree_mut)
        # k_mut_prob %
        if random.random() < self.k_mut_prob:

            # two random indices:
            mut_pos1 = random.randint(0,len(tmp_tree.prufer)-1)
            mut_pos2 = random.randint(0,len(tmp_tree.prufer)-1)

            print("ind1 : {}".format(mut_pos1))
            print("ind2 : {}".format(mut_pos2))

            tmp_tree = GA.swap(tmp_tree,mut_pos1,mut_pos2)

        # Recalculate the length of the route (updates it's .length)
        tmp_tree.calc_fit()

        return tmp_tree

    def mutate_swap(self,tree_mut):
        '''
        Tree() --> Tree()

        Swaps two random indexes in route_to_mut.route. Here it's more intelligent since the swap is effective only if the fitness function
        after swap is lower.
        This method allows us to have a good local search on solutions
        Runs k_mut_prob*100 % of the time
        '''
        tree = copy.deepcopy(tree_mut)
        tree.calc_fit()
        # k_mut_prob %
        breakk = False
        lenn = len(tree.prufer)

        if random.random() < self.k_mut_prob:
            for i in range(lenn):
                for j in range(lenn): # i is a, i + 1 is b, j is c, j+1 is d
                    tmp_tree = GA.swap(tree,i,j)
                    tmp_tree.calc_fit()
                    if(tree.fitness > tmp_tree.fitness):
                        tree = tmp_tree
                        breakk = True
                        break
                if breakk:
                    breakk = False
                    break
            tree.calc_fit()
        return tree

    def mutate_swap_nerfed(self,tree_mut):
        '''
        Tree() --> Tree()

        Swaps two random indexes in route_to_mut.route. Here it's more intelligent since the swap is effective only if the fitness function
        after swap is lower.
        This method allows us to have a good local search on solutions
        Runs k_mut_prob*100 % of the time
        '''
        tree = copy.deepcopy(tree_mut)
        tree.calc_fit()
        # k_mut_prob %
        breakk = False
        lenn = len(tree.prufer)

        if random.random() < self.k_mut_prob:
            list_indices = list(set(random.choices(list(range(lenn)), k = int(self.nodeNum/3))))
            allposs = []
            for i in list_indices:
                for j in range(lenn):
                    tmp_tree = GA.swap(tree,i,j)
                    tmp_tree.calc_fit()
                    allposs.append(tmp_tree)
                    if(tree.fitness > tmp_tree.fitness):
                        tree = tmp_tree
                        breakk = True
                        break
                if breakk:
                    breakk = False
                    break
            if not breakk:
                tree = sorted(allposs, key=lambda x: x.fitness, reverse=False)[0]
            tree.calc_fit()
        return tree

    def fittest_swap(self,tree_mut):
        '''
        Tree() --> Tree()

        Swaps two random indexes in route_to_mut.route. Here it's more intelligent since the swap is effective only if the fitness function
        after swap is lower.
        This method allows us to have a good local search on solutions
        This is Local Search at the end of each generation
        Runs k_mut_prob*100 % of the time
        '''
        tree = copy.deepcopy(tree_mut)
        tree.calc_fit()
        lenn = len(tree.prufer)

        def toparall(i,j):
            tmp_tree = GA.swap(tree,i,j)
            tmp_tree.calc_fit()
            return tmp_tree

        if random.random() < self.k_mut_prob:
            for i in range(lenn):
                possibilities = joblib.Parallel(n_jobs=-1)(delayed(toparall)(i,j) for j in range(lenn))
                tmplist = sorted(possibilities, key=lambda x: x.fitness, reverse=False)
                tree = tmplist[0]
        return tree

    def mutate_2opt(self, tree_mut):
        '''
        Tree() --> Tree()

        Doing a 2opt swap. We're keeping the best swap among the possibles 2opt swap. The fitness can be lower than the original one
        This method allows us to have a good local search on solutions
        Runs k_mut_prob*100 % of the time
        '''
        tree = copy.deepcopy(tree_mut)
        tree.calc_fit()
        # k_mut_prob %

        lenn = len(tree.prufer)
        def parallel(i,j):
            tmp_tree = GA.swap_2opt(tree,i,j)
            tmp_tree.calc_fit()
            return tmp_tree

        if random.random() < self.k_mut_prob:
            list_indices = list(set(random.choices(list(range(lenn)), k = int(self.nodeNum/4))))
            allposs =[]

            for i in list_indices:
                possibilities = joblib.Parallel(n_jobs=-1)(delayed(parallel)(i,j) for j in range(lenn))
                tmplist = sorted(possibilities, key=lambda x: x.fitness, reverse=False)
                allposs.append(tmplist[0])

            tmplist = sorted(allposs, key=lambda x: x.fitness, reverse=False)
            tree = tmplist[0]
            tree.calc_fit()
        return tree

    def change_three_bests(self, population):
        """
        TreePop() --> TreePop()
        Change the first three best trees (in term of fitness). We're testing every swap possible.
        ### @TODO do it until there are 3 different trees
        """
        population.sort_treepop()

        #for k in range(3):
        #    population.tree_pop[k] = self.fittest_swap(population.tree_pop[k])
        cpt = 0
        k = 0
        lenn = len(population.tree_pop)
        done = []
        while(cpt< 5 and k< lenn):
            print(k)
            population.tree_pop[k] = self.fittest_swap(population.tree_pop[k])
            if(population.tree_pop[k] not in done):
                cpt+=1
                done.append(population.tree_pop[k])
            k+=1
        return population

    def evolve_population(self, init_pop):
        '''
        TreePop() --> TreePop()

        Takes a population and evolves it then returns the new population.
        '''

        #makes a new population:
        descendant_pop = TreePop(list_files = self.list_files, size=init_pop.size, initialise=True)

        # Elitism offset (amount of Tree() carried over to new population)
        elitismOffset = 0

        # if we have elitism, set the first of the new population to the fittest of the old
        if self.elitism:
            descendant_pop.tree_pop[0] = init_pop.fittest
            elitismOffset = 1

        # Goes through the new population and fills it with the child of two tournament winners from the previous populatio
        for x in range(elitismOffset,descendant_pop.size):
            # two parents:
            tournament_parent1 = self.tournament_select(init_pop)[0]
            tournament_parent2 = self.tournament_select(init_pop)[0]

            while(tournament_parent2 == tournament_parent1):
                tournament_parent2 = self.tournament_select(init_pop)[0]

            # A child:
            tournament_child = self.crossover_kpoint(tournament_parent1, tournament_parent2)

            # Fill the population up with children
            descendant_pop.tree_pop[x] = tournament_child
        # Mutates all the Tree (mutation with happen with a prob p = k_mut_prob)
        # tre_ind in range(len(descendant_pop.tree_pop)):
        #    descendant_pop.tree_pop[tre_ind] = self.mutate_2opt_nerfed(descendant_pop.tree_pop[tre_ind])

        if(self.method == "swap"):
            func = self.mutate_swap_nerfed
        elif (self.method == "opt"):
            func = self.mutate_2opt

        tmp = Parallel(n_jobs=-1)(delayed(func)(descendant_pop.tree_pop[tre_ind]) for tre_ind in range(len(descendant_pop.tree_pop)))
        descendant_pop.tree_pop = tmp

        # Update the fittest Tree:
        #descendant_pop.sort_treepop()
        #descendant_pop.tree_pop[0] = self.fittest_2opt(descendant_pop.tree_pop[0])

        descendant_pop.get_fittest()

        return descendant_pop


class Solution:
    def subdomainVisits(self, cpdomains):
        """
        :type cpdomains: List[str]
        :rtype: List[str]
        """
        s_dic = {}
        for e in cpdomains:
            pair = e.split(' ')
            count = int(pair[0])
            s = pair[1].split('.')
            temp_len = len(s)
            while temp_len >= 1:
                s_temp = '.'.join(s[-temp_len:])
                if s_temp in s_dic:
                    s_dic[s_temp] = int(s_dic[s_temp]) + count
                else:
                    s_dic[s_temp] = count
                temp_len -= 1
        return [str(s_dic[i]) + ' ' +  i for i in s_dic]


import sys, os, subprocess, re, argparse, logging

# check whether azure_operations.py exist
module_path = os.path.realpath(__file__)
module_dir = os.path.dirname(module_path)
azure_module_path = '{}/azure_operations.py'.format(module_dir)
if not os.path.exists(azure_module_path):
    raise SystemError('No azure_operations.py found')

from azure_operations import *

vm_whitelist = []
container_whitelist = ['ddvevhds', 'templates', 'ddveimgs']
#container_whitelist = []
vhd_whitelist = ['AVE-7.4.0.242-disk1.vhd', 'AVE-7.5.0.183-disk1.vhd', 'AVE-7.4.1.56-disk1.vhd']

# set logging level
logger = logging.getLogger('Logging')
logger.setLevel(logging.INFO)
# stream handler
# sh = logging.StreamHandler(stream = sys.stdout)
# sh.setFormatter(logging.Formatter(fmt = '%(message)s'))
# logger.addHandler(sh)

class delete_op:
    def __init__(self):
        self.azure_ops = azure_operations(client_id = os.environ['AZURE_CLIENT_ID'],
                secret_key = os.environ['AZURE_SECRET_KEY'],
                tenant_id = os.environ['AZURE_TENANT_ID'])

    # delete unused nics
    def delete_unused_nics(self, resource_group, delete = False):

        for nic in self.azure_ops.network_client.network_interfaces.list(resource_group):
            name = nic.name
            attached_vm = nic.virtual_machine
            if not attached_vm:
                if not delete:
                    logger.info('Unused NIC: {}'.format(name))
                else:
                    self.azure_ops.delete_nic(resource_group, name)
                    logger.info('NIC {} successfully deleted.'.format(name))

    def delete_unused_vms(self, resource_group, delete = False):

        for vm_ref in self.azure_ops.compute_client.virtual_machines.list(resource_group):
            vm = self.azure_ops.get_vm(resource_group, vm_ref.name)

            state = vm.instance_view.statuses[0].display_status
            # VM may not be successfully deployed in below case
            if state == 'Provisioning succeeded':
                state = vm.instance_view.statuses[1].display_status

            if 'running' in state:
                continue
            if '-lr' in vm.name or '-longrun' in vm.name:
                continue
            if vm.name in vm_whitelist:
                continue

            if not delete:
                logger.info('Unused VM: {}'.format(vm.name))
            else:
                self.azure_ops.delete_vm(resource_group, vm.name)
                logger.info('VM {} successfully deleted.'.format(vm.name))

    def delete_unused_vhds(self, resource_group, delete = False):

        # managed disks
        for managed_disk_ref in self.azure_ops.compute_client.disks.list_by_resource_group(resource_group):
            disk_name = managed_disk_ref.name
            logger.debug(disk_name)
            if managed_disk_ref.managed_by:
                continue
            if not delete:
                logger.info('Unused Disk: {}'.format(disk_name))
            else:
                self.azure_ops.compute_client.disks.delete(resource_group, disk_name)
                logger.info('Managed disk {} successfully deleted.'.format(disk_name))

        # unmanaged disks
        # hierarchy: storage account/container/vhd
        storage_accounts = self.azure_ops.storage_client.storage_accounts.list_by_resource_group(resource_group)
        for storage_account in storage_accounts:
            if storage_account.kind == Kind.blob_storage:
                logger.debug('Listing VHD operations will neglect Blob storage account {}.'.format(storage_account.name))
                continue

            # get storage account keys
            storage_account_keys = self.azure_ops.storage_client.storage_accounts.list_keys(resource_group, storage_account.name)
            storage_account_keys_map = {v.key_name: v.value for v in storage_account_keys.keys}
            storage_account_primary_key = storage_account_keys_map['key1']

            blob_service = BaseBlobService(account_name = storage_account.name ,account_key = storage_account_primary_key)
            for container_ref in blob_service.list_containers():
                container = container_ref.name
                if container in container_whitelist:
                    continue
                elif re.search('[0-9a-z]{16}-[0-9a-z]{16}-[cdm]0', container):
                    if delete:
                        blob_service.delete_container(container_name = container)
                        logger.info('Storage container {} successfully deleted.'.format(container))
                    else:
                        logger.error('Wrong Usage: {}/{}'.format(storage_account.name, container))
                elif 'bootdiagnostics-' in container:
                    if delete:
                        blob_service.delete_container(container_name = container)
                        logger.info('Storage container {} successfully deleted.'.format(container))
                    else:
                        logger.info('Unused Container: {}/{}'.format(storage_account.name, container))
                else:
                    blobs = blob_service.list_blobs(container_name = container)
                    for blob in blobs:
                        if re.search(r'\.vhd', blob.name):
                            if blob.properties.lease.status == 'unlocked' and blob.properties.lease.state == 'available':
                                if blob.name in vhd_whitelist:
                                    continue
                                if delete:
                                    delete_ops.azure_ops.delete_blob(resource_group, storage_account.name, container, blob.name)
                                    logger.info('Unmanaged disk {} successfully deleted.'.format(disk_name))
                                else:
                                    logger.info('Unused VHD: {}/{}/{}'.format(storage_account.name, container, blob.name))

    def delete_unused_public_ips(self, resource_group, delete = False):

        for public_ip in self.azure_ops.network_client.public_ip_addresses.list(resource_group):
            public_ip_name = public_ip.id.split('/')[-1]
            public_ip_addr = public_ip.ip_address
            if public_ip_addr:
                continue
            if not delete:
                logger.info('Unused public ip: {}'.format(public_ip_name))
            else:
                self.azure_ops.delete_public_ip(resource_group, public_ip_name)
                logger.info('Public ip {} successfully deleted.'.format(public_ip_name))

    def delete_unused_resources(self, resource_group = None, delete = False):
        if not resource_group:
            for resource_group in self.azure_ops.resource_client.resource_groups.list():
                rg_name = resource_group.name

                # list unused vms
                self.delete_unused_vms(rg_name, delete)
                # list unused vhds
                self.delete_unused_vhds(rg_name, delete)
                # list unused nics
                self.delete_unused_nics(rg_name, delete)
                # list unused public ips
                self.delete_unused_public_ips(rg_name, delete)

                logger.info('')
        else:
            # list unused vms
            self.delete_unused_vms(resource_group, delete)
            # list unused vhds
            self.delete_unused_vhds(resource_group, delete)
            # list unused nics
            self.delete_unused_nics(resource_group, delete)
            # list unused public ips
            self.delete_unused_public_ips(resource_group, delete)

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('-S', '--subscription', help='delete resources from this subscription')
    parser.add_argument('-r', '--resource_group', help='delete resources from this group')
    parser.add_argument('--delete', action='store_true', help='delete resources from this group')
    parsed_args = parser.parse_args()

    # First check whether environmental variables are set
    try:
        os.environ['AZURE_CLIENT_ID']
        os.environ['AZURE_SECRET_KEY']
        os.environ['AZURE_TENANT_ID']
    except:
        raise SystemError("Please set environmental variables for Service Principal first.")

    delete_ops = delete_op()
    # Get all subscriptions
    subscription_map = {}
    for subscription in delete_ops.azure_ops.subscription_client.subscriptions.list():
        subscription_map[subscription.subscription_id] = subscription.display_name

    if not parsed_args.subscription:
        for (sub_id, sub_name) in subscription_map.items():
            # Subscription for Azure Marketplace
            if str(sub_id) == '1919bdd0-d66c-4699-8c08-a134883a985a':
                continue
            os.environ['AZURE_SUBSCRIPTION_ID'] = str(sub_id)
            logger.info('')
            logger.info('Subscription: {} - {}'.format(sub_id, sub_name))
            delete_ops.azure_ops.init_clients(str(sub_id))
            delete_ops.delete_unused_resources(parsed_args.resource_group, parsed_args.delete)
    else:
        os.environ['AZURE_SUBSCRIPTION_ID'] = parsed_args.subscription
        logger.info('Subscription: {} - {}'.format(parsed_args.subscription, subscription_map[parsed_args.subscription]))
        delete_ops.azure_ops.init_clients(parsed_args.subscription)
        delete_ops.delete_unused_resources(parsed_args.resource_group, parsed_args.delete)


def split(string:str, separator: str=" ") -> list:
    split_words = []
    last_index = 0
    for index, char in enumerate(string):
        if char == separator:
            split_words.append(string[last_index:index])
            last_index = index + 1
        elif index == len(string)-1:
            split_words.append(string[last_index:len(string)])
    return split_words

"""
if __name__ == "__main__":
    s = split("apple#banana#cherry#orange","#")
    print(s)
    s = split("12:43:39:89",":")
    print(s)
    s = split("apple,banana,cherry,orange",",")
    print(s)
"""


from math import prod

from pyfr.backends.base.generator import BaseKernelGenerator

class OpenMPKernelGenerator(BaseKernelGenerator):
    def render(self):
        kargdefn, kargassn = self._render_args('args')

        if self.ndim == 1:
            core = f'''
                for (int _xi = 0; _xi < BLK_SZ; _xi += SOA_SZ)
                {{
                    #pragma omp simd
                    for (int _xj = 0; _xj < SOA_SZ; _xj++)
                    {{
                        {self.body}
                    }}
                }}'''
            clean = f'''
                int _xi = 0;
                #pragma omp simd
                for (int _xj = 0; _xj < _nx % BLK_SZ; _xj++)
                {{
                    {self.body}
                }}'''
        else:
            core = f'''
                for (int _y = 0; _y < _ny; _y++)
                {{
                    for (int _xi = 0; _xi < BLK_SZ; _xi += SOA_SZ)
                    {{
                        #pragma omp simd
                        for (int _xj = 0; _xj < SOA_SZ; _xj++)
                        {{
                            {self.body}
                        }}
                    }}
                }}'''
            clean = f'''
                for (int _y = 0, _xi = 0; _y < _ny; _y++)
                {{
                    #pragma omp simd
                    for (int _xj = 0; _xj < _nx % BLK_SZ; _xj++)
                    {{
                        {self.body}
                    }}
                }}'''

        return f'''
            struct {self.name}_kargs {{ {kargdefn}; }};
            void {self.name}(int _ib, const struct {self.name}_kargs *args,
                             int _disp_mask)
            {{
                {kargassn};
                #define X_IDX (_xi + _xj)
                #define X_IDX_AOSOA(v, nv)\
                    ((_xi/SOA_SZ*(nv) + (v))*SOA_SZ + _xj)
                #define BCAST_BLK(r, c, ld) ((c) % (ld) + ((c) / (ld))*(ld)*r)
                if (_nx - _ib*BLK_SZ >= BLK_SZ)
                {{
                    {core}
                }}
                else
                {{
                    {clean}
                }}
                #undef X_IDX
                #undef X_IDX_AOSOA
                #undef BCAST_BLK
            }}'''

    def ldim_size(self, name, factor=1):
        return f'{factor}*BLK_SZ' if factor > 1 else 'BLK_SZ'

    def needs_ldim(self, arg):
        return False

    def _displace_arg(self, arg):
        if arg.isview:
            return None
        elif self.ndim == 1:
            # Vector
            if arg.ncdim == 0 or arg.ismpi:
                return '_ib*BLK_SZ'
            # 2D broadcast vector
            elif arg.isbroadcast:
                return None
            # Stacked vector:
            else:
                return f'_ib*BLK_SZ*{prod(arg.cdims)}'
        else:
            # 2D broadcast vector or row broadcast matrix
            if arg.isbroadcast or arg.isbroadcastr:
                return None
            # Column broadcast matrix
            elif arg.isbroadcastc:
                return f'_ib*BLK_SZ*{prod(arg.cdims)}'
            # Matrix
            else:
                return f'_ib*BLK_SZ*{prod(arg.cdims)}*_ny'

    def _render_args(self, argn):
        # We first need the argument list; starting with the dimensions
        kargs = [('int ', d, None, None) for d in self._dims]

        # Now add any scalar arguments
        kargs.extend((sa.dtype, sa.name, None, None) for sa in self.scalargs)

        # Finally, add the vector arguments
        for va in self.vectargs:
            da = self._displace_arg(va)
            mi = len(kargs) if da else None

            if va.intent == 'in':
                kargs.append((f'const {va.dtype}*', f'{va.name}_v', da, mi))
            else:
                kargs.append((f'{va.dtype}*', f'{va.name}_v', da, mi))

            # Views
            if va.isview:
                kargs.append(('const int*', f'{va.name}_vix', '_ib*BLK_SZ',
                              None))

                if va.ncdim == 2:
                    kargs.append(('const int*', f'{va.name}_vrstri',
                                  '_ib*BLK_SZ', None))

        # Argument definitions and assignments
        kargdefn, kargassn = [], []
        for dtype, name, disp, midx in kargs:
            assn = f'{dtype} {name} = {argn}->{name}'

            # Handle displacement and potential masking thereof
            if disp and midx is not None:
                assn += f' + ((_disp_mask & {1 << midx}) ? 0 : {disp})'
            elif disp:
                assn += f' + {disp}'

            kargdefn.append(f'{dtype} {name}')
            kargassn.append(assn)

        return ';\n'.join(kargdefn), ';\n'.join(kargassn)