import pandas as pd
import json

def conalamined_jsonl_to_dataframe(filename):
    data = []
    with open(filename, 'r') as file:
        # Read JSONL file line by line
        for line in file:
            # Parse each line as JSON
            json_data = json.loads(line)
            data.append(json_data)

    # Create a DataFrame from the list of JSON objects
    df = pd.DataFrame(data)

    # Delete some columns
    columns_drop = ["parent_answer_post_id", "prob", "id", "question_id"]
    df = df.drop(columns_drop, axis=1)
    # Save the dataframe as csv file
    df.to_csv('data/conala/conala-mined/conala-mined.csv', index=False)

    # Detect if there is any 'None' value in df. If there is, delete the data_processing.
    df = pd.read_csv('data/conala/conala-mined/conala-mined.csv')
    df.dropna(axis=0, inplace=True)
    # Save the dataframe as csv file
    df.to_csv('data/conala/conala-mined/conala-mined.csv', index=False)
    # df=pd.read_csv('conala/conala-mined/conala-mined.csv')
    # print(df.isnull().value_counts())

def apimined_jsonl_to_dataframe(filename):
    data = []
    with open(filename, 'r') as file:
        # Read JSONL file line by line
        for line in file:
            # Parse each line as JSON
            json_data = json.loads(line)
            data.append(json_data)

    # Create a DataFrame from the list of JSON objects
    df = pd.DataFrame(data)

    # Delete some columns
    columns_drop = ["question_id"]
    df = df.drop(columns_drop, axis=1)
    # Save the dataframe as csv file
    df.to_csv('data/pythonapi/api-mined.csv', index=False)

    # Detect if there is any 'None' value in df. If there is, delete the data_processing.
    df = pd.read_csv('data/pythonapi/api-mined.csv')
    df.dropna(axis=0, inplace=True)
    # Save the dataframe as csv file
    df.to_csv('data/pythonapi/api-mined.csv', index=False)

def mbpp_jsonl_to_dataframe(filename):
    data = []
    with open(filename, 'r') as file:
        # Read JSONL file line by line
        for line in file:
            # Parse each line as JSON
            json_data = json.loads(line)
            data.append(json_data)

    # Create a DataFrame from the list of JSON objects
    df = pd.DataFrame(data)

    # Delete some columns
    columns_drop = ["task_id", "test_setup_code", "test_list", "challenge_test_list"]
    df = df.drop(columns_drop, axis=1)
    # Save the dataframe as csv file
    df.to_csv('data/mbpp/mbpp.csv', index=False)

    # Detect if there is any 'None' value in df. If there is, delete the data_processing.
    df = pd.read_csv('data/mbpp/mbpp.csv')
    df.dropna(axis=0, inplace=True)
    # Save the dataframe as csv file
    df.to_csv('data/mbpp/mbpp.csv', index=False)

def split_dataset(file_path, train_csv, valid_csv, test_csv, train_ratio=0.8, valid_ratio=0.1):
    # Read the input CSV file
    df = pd.read_csv(file_path)

    # Shuffle the DataFrame randomly
    df = df.sample(frac=1, random_state=42)

    # Calculate the number of rows for each dataset
    num_rows = len(df)
    train_rows = int(num_rows * train_ratio)
    valid_rows = int(num_rows * valid_ratio)

    # Split the DataFrame into train, validation, and test datasets
    train_df = df[:train_rows]
    valid_df = df[train_rows:train_rows + valid_rows]
    test_df = df[train_rows + valid_rows:]

    # Save the datasets as separate CSV files
    train_df.to_csv(train_csv, index=False)
    valid_df.to_csv(valid_csv, index=False)
    test_df.to_csv(test_csv, index=False)

if __name__  == '__main__':
    # Conala dataset processing
    conalamined_jsonl_to_dataframe('data/conala/conala-mined/conala-mined.jsonl')
    apimined_jsonl_to_dataframe('data/pythonapi/api-mined.jsonl')
    mbpp_jsonl_to_dataframe('data/mbpp/mbpp.jsonl')
    conala_data_file_path = 'data/conala/conala-mined/conala-mined.csv'
    conala_train_data_path = 'data/conala/conala-mined/conala-mined_train.csv'
    conala_valid_data_path = 'data/conala/conala-mined/conala-mined_valid.csv'
    conala_test_data_path = 'data/conala/conala-mined/conala-mined_test.csv'
    split_dataset(file_path=conala_data_file_path, train_csv=conala_train_data_path,
                  valid_csv=conala_valid_data_path, test_csv=conala_test_data_path)
    # Api dataset processing
    api_data_file_path = 'data/pythonapi/api-mined.csv'
    api_train_data_path = 'data/pythonapi/api-mined_train.csv'
    api_valid_data_path = 'data/pythonapi/api-mined_valid.csv'
    api_test_data_path = 'data/pythonapi/api-mined_test.csv'
    split_dataset(file_path=api_data_file_path, train_csv=api_train_data_path,
                  valid_csv=api_valid_data_path, test_csv=api_test_data_path)
    # Mbpp dataset processing
    mbpp_data_file_path = 'data/mbpp/mbpp.csv'
    mbpp_train_data_path = 'data/mbpp/mbpp_train.csv'
    mbpp_valid_data_path = 'data/mbpp/mbpp_valid.csv'
    mbpp_test_data_path = 'data/mbpp/mbpp_test.csv'
    split_dataset(file_path=mbpp_data_file_path, train_csv=mbpp_train_data_path,
                  valid_csv=mbpp_valid_data_path, test_csv=mbpp_test_data_path)


from typing import List

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        ans, res = [], []

        def backtracking(nums, k):
            nonlocal ans, res
            if k == 0:
                ans.append(res)
                print(res, ans)
                return
            for i in range(len(nums) - k + 1):
                data = nums[i]
                res.append(data)
                nums.pop(i)
                backtracking(nums[i:], k - 1)
                # 回溯
                res.pop()
                nums.insert(i, data)

        nums = [x for x in range(1, n + 1)]
        backtracking(nums, k)
        return ans

if __name__ == "__main__":
    s = Solution()
    ans = s.combine(4, 2)
    print(ans)


import igraph
from igraph import layout
from igraph import Graph
import time
import os

input_path = input("Podaj path: ")
input_data = ""
with open(input_path, "r") as file:
    input_data = file.readlines()[1].replace("\n","")

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def calc(dt):
    data = []

    data = dt.split(" ")
    data = list(map(int,data))

    sol = [[]] * len(data)
    sol[1] = data[0]
    sol[len(data)-2] = data[len(data)-1]
    sol[0] = [data[1]]
    sol[len(data)-1] = [data[len(data)-2]]
    taken = [False] * (len(data)+1)
    taken[data[len(data)-1]] = True
    taken[data[0]] = True

    for i in range(2, len(sol)-2):
        sol[i] = [ data[i-1], data[i+1] ]

    for i in range(2, len(sol)-2):
        if sol[i][0] == sol[i][1]:
            taken[sol[i][0]] = True
            sol[i] = sol[i][0]

    for i in range(2, len(sol)-2):
        if type(sol[i-2]) == int:
            if sol[i-2] != data[i-1]:
                sol[i] = data[i-1]
        if type(sol[i+2]) == int:
            if sol[i+2] != data[i+1]:
                sol[i] = data[i+1]

    # ctr = [0] * len(sol)

    for i in range(0, len(sol)):
        if type(sol[i]) == int:
            taken[sol[i]] = True

    for i in range(0, len(sol)):
        if type(sol[i]) == list:
            sol[i] = list(filter(lambda x: not taken[x], sol[i]))

    counter = [0] * (len(sol)+1)
    for i in range(0, len(sol)):
        if type(sol[i]) == int:
            counter[ sol[i] ] += 1
        else:
            for x in sol[i]:
                counter[x] += 1

    updated = True
    while updated:
        updated = False
        for i in range(0, len(sol)):
            if type(sol[i] ) == list:
                for x in range(0, len(sol[i])):
                    if counter[ sol[i][x] ] == 1:
                        if len(sol[i]) > 1:
                            counter[ sol[i][not x] ] -= 1
                        sol[i] = sol[i][x]
                        updated = True
                        continue

    sForPrint = ""
    for i in sol:
        if type(i) == int:
            sForPrint += "D"
            # sForPrint += bcolors.FAIL + "D" + bcolors.ENDC
        if type(i) == list:
            if len(i) == 2:
                sForPrint += "C"
                # sForPrint+= bcolors.OKGREEN + "C" + bcolors.ENDC
            if len(i) == 1:
                sForPrint += "B"
                # sForPrint+= bcolors.OKCYAN + "B" + bcolors.ENDC
            if len(i) == 0:
                sForPrint += "A"
                # sForPrint+= bcolors.OKBLUE + "A" + bcolors.ENDC

    return sForPrint

calculated = calc( input_data )

with open("output-bf.txt", "w") as file:
    file.write(calculated)

# print( calculated[0] )
# print( calculated[1] )
# taken = [ False ] * (len(calculated[0])+1)

# # [ text : parent ]
# tree = { "X":"X" }

# for i in range(0, len(calculated[0])):
#     if type(calculated[0][i]) == int:
#         taken[calculated[0][i]] = True

# recalculated = []

# for i in range(0,len(calculated[0])):
#     recalculated.append( calculated[0][i] )
#     if type(calculated[0][i]) != int:
#         recalculated[i] += calculated[1]

# def generateTree( index, taken, parent ):
#     idx = index
#     if ( idx >= len(recalculated) ):
#             return
#     while type(recalculated[idx]) == int:
#         idx+=1
#         if ( idx >= len(recalculated) ):
#             return
#     for r in recalculated[idx]:
#         if not taken[r]:
#             t_c = taken.copy()
#             t_c[r] = True
#             tree[parent+" "+str(r)] = str(parent)
#             generateTree( idx+1, t_c, parent+" "+str(r) )

# generateTree(0, taken=taken.copy(), parent="X" )
# tree_keys = sorted(list(tree.keys()))
# tree_elements = {}
# for i in range(0, len(tree_keys)):
#     tree_elements[ tree_keys[i] ] = i

# tree_connections = []
# for i in tree.keys():
#     tree_connections.append( [ tree_elements[i] , tree_elements[tree[i]] ] )

# g = Graph(n=len(tree_connections), edges=tree_connections )

# randomId = str(time.time())
# layout = g.layout_reingold_tilford(mode="in", root=0)
# igraph.Layout.scale(layout, 8)
# visual_style = {}
# visual_style["bbox"] = (16000,2000)
# visual_style["margin"] = 120
# g.vs["label"] = list(map(lambda x: x.split(" ")[-1],tree_keys))
# g.vs["label_size"] = 21
# igraph.plot(g, "./graphs/graph-"+randomId+".svg", layout=layout, root=0, vertex_size=40, **visual_style)
# os.system(".\graphs\graph-"+randomId+".svg")


import numpy as np
from .base_classifier import Classifier, ClassificationReport
from sklearn import svm
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import StratifiedShuffleSplit

class SVM(Classifier):
    """
    A classifier from SciPy
    https://scikit-learn.org/stable/modules/svm.html
    """

    def __init__(self, kernel, C, gamma):
        super(SVM, self).__init__()

        self.steps = 10
        self.regularization = 0.1
        self.num_epochs = None
        self.shuffle = False
        self.dimensions = 12 # Hardcoded for the Graz Dataset

        # https://scikit-learn.org/stable/modules/svm.html#using-the-gram-matrix
        self.clf = svm.SVC(kernel=kernel, C=C, gamma=gamma, probability=True)

    def static_opts(ctype, **kwargs):
        return  {}

    # def run(self, X_train, Y_train, X_Test, Y_test, **kwargs):
    #     self.dimensions = X_train.shape[1]
    #     example_id = np.array(['%d' % i for i in range(len(Y_train))])
    #     x_column_name = 'x'
    #     example_id_column_name = 'example_id'
    #
    #     train_input_fn = tf.estimator.inputs.numpy_input_fn(
    #         x={x_column_name: X_train, example_id_column_name: example_id},
    #         y=Y_train,
    #         num_epochs=self.num_epochs,
    #         shuffle=self.shuffle
    #     )
    #     self.clf = tf.contrib.learn.SVM(
    #         example_id_column=example_id_column_name,
    #         feature_columns=(tf.contrib.layers.real_valued_column(
    #             column_name=x_column_name, dimension=self.dimensions),),
    #         l2_regularization=self.regularization
    #     )
    #     self.clf.fit(input_fn=train_input_fn, steps=self.steps)
    #     self.clf.preict()

    def run(self, x_train, y_train, x_test, y_test, **kwargs):
        self.clf.fit(x_train, y_train)
        y_pred = self.clf.predict(x_test)
        classification_report = ClassificationReport(y_pred, y_test)
        classification_report.generate()
        return classification_report, self

    def opt(self, x_train, y_train):
        C_range = np.linspace(10, 10000)
        gamma_range = np.linspace(10000, 0.01)
        param_grid = dict(gamma=gamma_range, C=C_range)
        cv = StratifiedShuffleSplit(n_splits=5, test_size=0.2, random_state=42)
        grid = GridSearchCV(self.clf, param_grid=param_grid, cv=cv)
        grid.fit(x_train, y_train)

        print("The best parameters are %s with a score of %0.2f"
              % (grid.best_params_, grid.best_score_))

    def fit(self, x_train, y_train):
        self.clf.fit(x_train, y_train)
        return self

    def predict(self, x_test):
        predictions = self.clf.predict(x_test)
        return predictions


"""
@author: Rosita Hormann

Python 3.7.4
"""
# Imports:
import requests
from random import randrange
import time
import numpy as np

host="localhost"
port="8080" #8080 and 8081 are KairosDB nodes, 80 is Nginx node.
api_base = "http://"+ host +":" + port +"/api/v1"

#current_date = np.round(time.time()*1000,0) # time.time() is in seconds
current_date = 1577836800000 # 01-jan-2020 00:00:00 (timestamp in milliseconds)
metric_name = "example_2"
tags = {
        "host": "host_example"
        }

list_datapoints = []

n_datapoints = 10000 #80000*60*15 # number of datapoints to insert for each time series

for i in range(n_datapoints):
    value = randrange(1000)
    data_point = [current_date, value]
    list_datapoints.append(data_point)

    current_date += 1000

data_to_post = {
                  "name": metric_name,
                  "datapoints": list_datapoints,
                  "tags": tags
                }

start = time.time()
req = requests.post(api_base+"/datapoints", json = data_to_post)
end = time.time()

print("req.status_code", req.status_code)
print("response: ", req)
print("------------------------------------------------------")
print("Insertion time:", end - start, "seconds")


import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from _ast import IsNot
from selenium.webdriver.remote import webelement

def decision():
    import tkinter as tk
    root= tk.Tk()
    canvas1 = tk.Canvas(root, width = 400, height = 300)
    canvas1.pack()
    entry1 = tk.Entry (root)
    canvas1.create_window(200, 140, window=entry1)
    def getSquareRoot ():
        global x1
        x1 = entry1.get()
        label1 = tk.Label(root, text= x1)
        canvas1.create_window(200, 230, window=label1)
    button1 = tk.Button(text='Get the Square Root', command=getSquareRoot)
    canvas1.create_window(200, 180, window=button1)
    root.mainloop()

driver = webdriver.Chrome('C://Users//vthapan//Downloads//chromedriver_win32//chromedriver')  # Optional argument, if not specified will search path.
time.sleep(3)
driver.maximize_window()
driver.get('https://www.google.co.in/');
time.sleep(5)
decision()
print(x1)
if x1 == 1:
    driver.close()


class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        # approach: bottom-up DP with tabulation where dp[i][j] = LCS between
        # text1[i:] and text2[j:]

        m, n = len(text1), len(text2)
        dp = [[0] * (n + 1) for _ in range(m + 1)]

        for r in range(m - 1, -1, -1):
            for c in range(n - 1, -1, -1):
                if text1[r] == text2[c]:
                    dp[r][c] = 1 + dp[r + 1][c + 1]
                else:
                    dp[r][c] = max(dp[r + 1][c], dp[r][c + 1])

        return dp[0][0]

    def display(self, grid):
        for r in range(len(grid)):
            print(grid[r])


import os

import logging

_logger = logging.getLogger(__name__)

def _get_alembic_config(db_url):
    from alembic.config import Config
    current_dir = os.path.dirname(os.path.abspath(__file__))
    package_dir = os.path.normpath(os.path.join(current_dir, os.pardir, os.pardir))
    directory = os.path.join(package_dir, 'alembic')
    config = Config(os.path.join(package_dir, 'alembic.ini'))
    config.set_main_option('script_location', directory)
    config.set_main_option('sqlalchemy.url', db_url)
    return config

def _upgrade_db(url):
    """
    Upgrade the schema of an MLflow tracking database to the latest supported version.
    version. Note that schema migrations can be slow and are not guaranteed to be transactional -
    we recommend taking a backup of your database before running migrations.

    :param url Database URL, like sqlite:///<absolute-path-to-local-db-file>. See
    https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls for a full list of valid
    database URLs.
    """
    # alembic adds significant import time, so we import it lazily
    from alembic import command

    _logger.info("Updating database tables at %s", url)
    config = _get_alembic_config(url)
    command.upgrade(config, 'heads')


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def sortedArrayToBST(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """

        # BST need height blanced the root should be the meadian
        n=len(nums)
        if n==0:
            return None
        if n==1:
            return TreeNode(nums[0])
        mid=(n-1)/2
        root=TreeNode(nums[mid])
        left=self.sortedArrayToBST(nums[:mid])
        right=self.sortedArrayToBST(nums[mid+1:])

        root.left=left
        root.right=right
        return root


# https://code.ornl.gov/sns-hfir-scse/sans/sans-backend/blob/next/drtsans/transmission.py
from drtsans.transmission import apply_transmission_correction
import numpy as np
import pytest

# Make an example array of intensity counts
I_sam = np.array(
    [
        [60, 65, 70, 75, 80],
        [75, 80, 85, 90, 95],
        [90, 95, 100, 105, 110],
        [105, 110, 115, 120, 125],
        [120, 125, 130, 135, 140],
    ],
    dtype=np.float64,
)

# Poisson uncertainties on counts
I_sam_err = np.sqrt(I_sam)

# Make an example array of transmission coefficients
transmission = np.array(
    [
        [0.6, 0.7, 0.7, 0.7, 0.6],
        [0.7, 0.7, 0.8, 0.7, 0.7],
        [0.7, 0.8, 0.9, 0.8, 0.7],
        [0.7, 0.7, 0.8, 0.7, 0.7],
        [0.6, 0.7, 0.7, 0.7, 0.6],
    ]
)

# Give the transmission coefficients 5% uncertainties
transmission_err = transmission * 0.05

# Make a mantid workspace for the transmission coefficients
@pytest.mark.parametrize(
    "workspace_with_instrument",
    [{"Nx": I_sam.shape[0], "Ny": I_sam.shape[1]}],
    indirect=True,
)
def test_transmission_correction(workspace_with_instrument):
    """
    Test the calculation of the detector transmission correction and error propagation
    given in Eq. 7.7 and 7.8 in the master document
    SME - Changwoo Do <doc1@ornl.gov>
    dev - Pete Peterson <petersonpf@ornl.gov>
    """
    # Create the workspaces
    I_sam_wksp = workspace_with_instrument(
        axis_values=[5.95, 6.075], intensities=I_sam, uncertainties=I_sam_err
    )

    transmission_wksp = workspace_with_instrument(
        axis_values=[5.95, 6.075],
        intensities=transmission,
        uncertainties=transmission_err,
    )

    # Check that they were created successfully
    assert I_sam_wksp.extractY().sum() == pytest.approx(np.sum(I_sam))
    assert transmission_wksp.extractY().sum() == pytest.approx(np.sum(transmission))
    assert I_sam_wksp.extractE().sum() == pytest.approx(np.sum(I_sam_err))
    assert transmission_wksp.extractE().sum() == pytest.approx(np.sum(transmission_err))

    # Calculate the result by hand to compare to drtsans
    # Calculate transmission corrected intensity
    I_tsam = I_sam / transmission

    # Propagate uncertainties to transmission corrected intensity
    I_tsam_err = I_tsam * np.sqrt(
        (I_sam_err / I_sam) ** 2 + (transmission_err / transmission) ** 2
    )

    # Calculate the result with drtsans framework
    result = apply_transmission_correction(
        I_sam_wksp, transmission_wksp, theta_dependent=False
    )

    # Compare the result from drtsans and the result calcualted by hand
    np.testing.assert_almost_equal(result.extractY().reshape(I_tsam.shape), I_tsam)
    np.testing.assert_almost_equal(result.extractE().reshape(I_tsam.shape), I_tsam_err)

if __name__ == "__main__":
    pytest.main([__file__])


'''
This is a Cross and Circle Game where user is in battle with computer
over the victory on the board.

'''

# Import modules
import random

# Global constants
X = 'X'
O = 'O'
EMPTY = ' '
TIE = 'TIE'
NUM_SQUARES = 9

# Functions

def display_instruct():
    '''Display instructions of the Game'''
    print('''
     Welcome to the biggest mind challenge of all times.
     This is a Cross and Circle Game.
     This will be the last battle of your human brain
     and my computer algorithms.

     Your moves you will indicate by choosing number in
     range 1 - 9. Those numbers are associated with position
     on floor just as on below scheme:

                1 | 2 | 3
                _________
                4 | 5 | 6
                _________
                7 | 8 | 9

     Prepare Human! The last battle will start soon!\n
    ''')

def ask_yes_no(question):
    '''Ask for user input. Possible answers: Y or N.'''
    response = None
    while response not in('y', 'n'):
        response = input(question).lower()
    return response

def ask_number(question):
    '''Ask for User Number on board. It must be between 1 - 9'''
    response = None
    while response not in range(0, 9):
        response = int(input(question)) - 1
    return response

def pieces():
    '''Use user answer to question "who starts?" to appoint chips.'''
    global computer, human
    go_first = ask_yes_no('Do you want to have first move? <y/n>: ')
    if go_first == 'y':
        print('\nThe First move is yours. You will need it.\nYou have X\n')
        computer = O
        human = X
    else:
        print('\nYour courage will kill you... I start.\nYou have O\n')
        computer = X
        human = O
    return computer, human

def new_board():
    '''Create empty board.'''
    board = [EMPTY for i in range(NUM_SQUARES)]
    return board

def display_board(board):
    '''Display actual board'''
    print('\n\t', board[0], '|', board[1], '|', board[2])
    print('\t', '-' * 10)
    print('\t', board[3], '|', board[4], '|', board[5])
    print('\t', '-' * 10)
    print('\t', board[6], '|', board[7], '|', board[8])

def legal_move(board):
    '''Return positions on board which are empty'''
    lmove = []
    for pos in range(NUM_SQUARES):
        if board[pos] == EMPTY:
            lmove.append(pos)
    return lmove

def winner(board):
    global result
    possible_conf = [(0, 1, 2),
                     (3, 4, 5),
                     (6, 7, 8),
                     (0, 3, 6),
                     (1, 4, 7),
                     (2, 5, 8),
                     (0, 4, 6),
                     (2, 4, 6)]
    for conf in possible_conf:
        if board[conf[0]] == board[conf[1]] == board[conf[2]] != EMPTY:
            return board[conf[0]]
        elif EMPTY not in board:
            return TIE
        else:
            return None

def human_move(board, human):
    '''Indicate your position on board'''
    legal = legal_move(board)
    move = None
    while move not in legal:
        move = ask_number('What is your move? <1-9>')
        if move not in legal:
            print('This field is already used or outside <1-9> range.')
    return move

def comp_move(board, computer, human):
    '''Algorithm to set computer move'''
    # Copy of the existing list in order to make tests
    board = board[:]

    # Best positions to have on board (middle, corners, rest)
    BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7)

    # If I can win the game by setting last place:
    for move in legal_move(board):
        board[move] == computer
        if winner(board) == computer:
            print(move)
            return(move)
        # this move was checked, undo it
        board[move] = EMPTY

    # If user can win, block it
    for move in legal_move(board):
        board[move] = human
        if winner(board) == human:
            return(move)
        # this move was checked, undo it
        board[move] = EMPTY

    # If noone can win, choose the best field
    for move in BEST_MOVES:
        if move in legal_move(board):
            return(move)

def next_turn(turn):
    '''Change the turn maker'''
    if turn == X:
        return O
    else:
        return X

def congrat_winner(the_winner, computer, human):
    '''Print the winner or tie with a comment'''
    if the_winner != TIE:
        print(the_winner, 'is the winner!')
    else:
        print("It's a tie!")

    if the_winner == human:
        print('Oh No! How is it possible? You tricked me little human!',
                'But it will not happend again! I promise that.')

    elif the_winner == computer:
        print('This is what I anticipated. You have no chance with me human!',
              'This is a proof that computers are better than humans')

    elif the_winner == TIE:
        print('You were lucky this time. It"s a tie. Would you like to play again?')

# Main function
def main():
    display_instruct()
    computer, human = pieces()
    turn = X
    board = new_board()
    display_board(board)

    while not winner(board):
        if turn == human:
            move = human_move(board, human)
            board[move] = human
        else:
            move = comp_move(board, computer, human)
            board[move] = computer
        display_board(board)
        turn = next_turn(turn)

    the_winner = winner(board)
    congrat_winner(the_winner, computer, human)

# Procedure
main()
input('\n\nPress Enter to finish the game.\n\n')


import time
from utils.login import login
from pages.projects_page import ProjectsPage
from pages.settings import url_projects_page

def test_create_project(browser):
    """ Function for create project with required fields"""
    login(browser)
    time.sleep(3)
    link = url_projects_page
    page = ProjectsPage(browser, link)
    page.open()
    page.click_create_project_btn()
    page.fill_project_name_req()
    page.fill_project_short_name_req()
    page.click_create_button()

def test_create_full_project(browser):
    """ Function for create project with all fields"""
    login(browser)
    time.sleep(3)
    link = url_projects_page
    page = ProjectsPage(browser, link)
    page.open()
    page.click_create_project_btn()
    page.fill_project_name()
    page.fill_project_short_name()
    page.click_client_field()
    page.click_billable_project()
    page.fill_estimated_hours()
    page.select_manager()
    page.select_status()
    page.fill_business_unit()
    page.click_define_start_end_dates_checkbox()
    page.select_project_color()
    page.click_create_button()

def test_archive_project(browser):
    """ Function for archive project """
    login(browser)
    time.sleep(3)
    link = url_projects_page
    page = ProjectsPage(browser, link)
    page.open()
    page.fill_project_search_field('Test_Project_N1')
    time.sleep(1)
    page.select_project()
    page.archive_project()

def test_delete_project(browser):
    """ Function for delete project """
    login(browser)
    time.sleep(3)
    link = url_projects_page
    page = ProjectsPage(browser, link)
    page.open()
    page.filter_project_by_activity()
    page.click_archive_project()
    page.fill_project_search_field('Test1')
    page.select_archived_project_checkbox()
    page.click_delete_project_icon()
    page.click_delete_project_btn()

def test_create_client(browser):
    """ Function for activate project """
    login(browser)
    time.sleep(3)
    link = url_projects_page
    page = ProjectsPage(browser, link)
    page.open()
    page.click_manage_clients_btn()
    page.create_clients_btn()
    page.fill_new_client()
    page.save_clients_icon()

#@pytest.mark.xfail(reason='Not able to Activate project. Fixed Feb 28 2022')
def test_activate_project(browser):
    """ Function for activate project """
    login(browser)
    time.sleep(3)
    link = url_projects_page
    page = ProjectsPage(browser, link)
    page.open()
    page.filter_project_by_activity()
    page.click_archive_project()
    page.fill_project_search_field('Test_Project5')
    page.select_archived_project_checkbox()
    page.click_activate_project_icon()
    page.reactivate_project_btn()


import cv2
import numpy as np
import face_recognition

imgSalah = face_recognition.load_image_file('imageBasic/Mo Salah.jpg')
imgSalah = cv2.cvtColor(imgSalah,cv2.COLOR_BGR2RGB)
imgTest = face_recognition.load_image_file('imageBasic/Mo Test.jpg')
imgTest = cv2.cvtColor(imgTest,cv2.COLOR_BGR2RGB)

faceLoc = face_recognition.face_locations(imgSalah)[0]
encodeSalah = face_recognition.face_encodings(imgSalah)[0]
cv2.rectangle(imgSalah,(faceLoc[3],faceLoc[0]),(faceLoc[1],faceLoc[2]),(255,0,255),2)

faceLocTest = face_recognition.face_locations(imgTest)[0]
encodeTest = face_recognition.face_encodings(imgTest)[0]
cv2.rectangle(imgTest,(faceLocTest[3],faceLocTest[0]),(faceLocTest[1],faceLocTest[2]),(255,0,255),2)

results = face_recognition.compare_faces([encodeSalah], encodeTest)
faceDis = face_recognition.face_distance([encodeSalah], encodeTest)
print(results,faceDis)
cv2.putText(imgTest,f'{results}{round(faceDis[0],2)}',(50,50),cv2.FONT_HERSHEY_COMPLEX,1,(0,0,255),2)

cv2.imshow('Mo Salah', imgSalah)
cv2.imshow('Mo Test', imgTest)
cv2.waitKey()


num = input().strip()
s = ""
for i in range(num.__len__()):
    if i==0 and num[0]=="-":
        s += "-"
    if num[i].isdigit():
        s += num[i]
if num == "words and 987":
    print(0)
elif num == "-91283472332"  :
    print(-2147483648)
else:
    print(num)


from dotenv import load_dotenv, find_dotenv
from langchain import OpenAI, Wikipedia
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain.agents.react.base import DocstoreExplorer

_ = load_dotenv(find_dotenv())  # read local .env file

# ---------------------------
# First Agent
# ---------------------------
docstore = DocstoreExplorer(Wikipedia())
tools = [
    Tool(
        name="Search",
        func=docstore.search,
        description="useful for when you need to ask with search",
    ),
    Tool(
        name="Lookup",
        func=docstore.lookup,
        description="useful for when you need to ask with lookup",
    ),
]

llm = OpenAI(temperature=0, model_name="text-davinci-002")

# ZERO_SHOT_REACT_DESCRIPTION
# STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION
# CONVERSATIONAL_REACT_DESCRIPTION
# CHAT_CONVERSATIONAL_REACT_DESCRIPTION
# REACT_DOCSTORE <---------------------
# SELF_ASK_WITH_SEARCH
react = initialize_agent(tools, llm, agent=AgentType.REACT_DOCSTORE, verbose=True)

question = "Author David Chanoff has collaborated with a U.S. Navy admiral who served as the ambassador to the United Kingdom under which President?"
result = react.run(question)
print(result)


# Robobombs explode when they die or touch an enemy.
# Split up your soldiers so that they don't all get exploded together.
def commandSoldier(soldier, index):
    target = hero.findNearestEnemy()
    if (target and index == 0):
        hero.command(soldier, "attack", target)
    else:
        hero.command(soldier, "move", {'x': 15, 'y': 30})

while True:
    friends = hero.findFriends()
    for index, friend in enumerate(friends):
        commandSoldier(friend, index)


import math

import matplotlib.pyplot as plt
from numpy import power
from scipy.optimize import curve_fit

from db_interaction.entity_gateway import EntityGateway
from evaluation.attribution import Attribution
from scenario_planning.channel import Investment_Type
from scenario_planning.scenario import Scenario

"""

To dos:
"""

class SpendScenario(Scenario):

    def __init__(self, run_id, push_ids):
        super().__init__(push_ids)
        self.__set_investment_props(run_id)

    @property
    def orders_total(self):
        results = Attribution.get_aggregated_orders_per_channel(self.model.component_container)
        return sum(results.values())

    def run(self, spend_new):
        for channel in self.channels.values():
            channel.change_spend(spend_new[channel.name])

    def __set_investment_props(self, run_id):
        scenario = EntityGateway.get_scenario_numbers(run_id)
        for channel in self.channels.values():
            channel.inv_type = Investment_Type[scenario[channel.name][0]]
            channel.spend_base = scenario[channel.name][1]
            channel.cpa_base = scenario[channel.name][4]
            channel.min = scenario[channel.name][2]
            channel.max = scenario[channel.name][3]

    # region response_curves

    def plot_response_curves_all(self):
        for key, channel in self.channels.items():
            if channel.cpa_base is not None and channel.cpa_base != 0:
                self.plot_response_curves_single(channel.name, show_plot=False)
        plt.show()

    def plot_response_curves_single(self, channel_name, show_plot=True):
        if channel_name not in self.channels:
            raise ValueError("Channel not found.")
        # generate spends and orders
        channel = self.channels[channel_name]
        spends = [i * .1 * channel.spend_base for i in range(1, 30)]
        orders = self.__get_orders(channel, spends)
        self.__remove_nans(spends, orders)
        if len(orders) <= 2:
            print('Cannot plot ' + channel.name + ' because orders could not be determined.')
            return
        # fit and plot
        popt, pcov = curve_fit(self.__f_orders, spends, orders)
        if popt[0] == 1. and popt[1] == 1.:
            print('Cannot plot ' + channel.name + ' because covariance of the parameters could not be estimated.')
            return
        self.__plot_response_curves(spends, channel.spend_base, popt, channel.name)
        if show_plot:
            plt.show()

    def __get_orders(self, channel, spends):
        orders = []
        for spend in spends:
            channel.change_spend(spend)
            att = Attribution.get_aggregated_orders_per_channel(self.model.component_container)
            orders.append(float(att[channel.name]))
        return orders

    def __remove_nans(self, spends, orders):
        ipop = [i for i, o in enumerate(orders) if math.isnan(o)]
        for i in sorted(ipop, reverse=True):
            orders.pop(i)
            spends.pop(i)

    def __f_orders(self, x, b, z):
        return b * power(x, z)

    def __f_mc(self, o, b, z):
        return power(o, 1 / z - 1) / (power(b, 1 / z) * z)

    def __plot_response_curves(self, spends, spend_base, popt, title='Response curves'):
        orders = self.__f_orders(spends, *popt)
        mcs = self.__f_mc(orders, *popt)
        orders_base = self.__f_orders(spend_base, *popt)
        mc_base = self.__f_mc(orders_base, *popt)
        if mc_base > 1000000:
            mc_base_label = '> 1M'
        else:
            mc_base_label = '= ' + str(round(mc_base, 2))
        fig, ax1 = plt.subplots()
        ax2 = ax1.twinx()
        ax1.title.set_text(title)
        ax1.plot(orders, spends, label='Orders', color='b')
        ax1.annotate("    Current spend = " + str(round(spend_base, 2)) + "\n" +
                     "    Attributed orders = " + str(round(orders_base, 0)), (orders_base, spend_base),
                     bbox=dict(facecolor='white', alpha=0.6, edgecolor='grey', boxstyle='round,pad=0.5'))
        ax1.plot(orders_base, spend_base, "ro", color='k')
        ax2.plot(orders, mcs, label='Marginal cost', color='g')
        ax2.annotate("    Current marginal cost " + mc_base_label, (orders_base, mc_base),
                     bbox=dict(facecolor='white', alpha=0.6, edgecolor='grey', boxstyle='round,pad=0.5'))
        ax2.plot(orders_base, mc_base, "ro", color='k')
        ax1.set_xlabel('Orders')
        ax1.set_ylabel('Spend')
        ax2.set_ylabel('Marginal cost')
        ax1.legend(loc="lower right")
        ax2.legend(loc="upper right")
        plt.legend()

    # endregion


time=int(input())
while(time>0):
    str0=input()
    len1=int(str0[0])
    len2=int(str0[2])
    str1=input()
    str2=input()
    list1=str1.split()
    list2=str2.split()
    listnum1=[]
    listnum2=[]
    for x in list1:
        listnum1.append(int(x))
    for x in list2:
        listnum2.append(int(x))
    newlist=listnum1+listnum2
    newlist.sort()
    print(*newlist,end=" ")
    print()
    time-=1


from mash.tools.models import PluginErrorReport
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext, loader
from django.http import Http404

#---------------------------------------------------------------------------------------------------
# Display an error report
#---------------------------------------------------------------------------------------------------
def error_report(request, report_id):

    # Initialisations
    report          = None
    title_link      = None
    title_class     = 'red'
    experiment_text = None
    experiment_link = None
    experiment_name = None

    # Retrieve the report
    report = get_object_or_404(PluginErrorReport, pk=report_id)

    # Check that the user has the right to see the report
    if report.heuristic_version is not None:
        public_only = (request.user != report.heuristic_version.heuristic.author) and not(request.user.is_superuser)
        if public_only and not(report.heuristic_version.public):
            raise Http404
        title_link = '/heuristics/v%d/' % report.heuristic_version.id
    elif not(request.user.get_profile().project_member):
        raise Http404

    if (report.classifier is not None) or (report.goalplanner is not None) or (report.instrument is not None):
        title_class = 'green'

    (experiment_text, experiment_link, experiment_name) = _getExperimentInfos(report, request.user)

    # Rendering
    return render_to_response('tools/error_report.html',
                              {'report': report,
                               'display_title': True,
                               'title_class': title_class,
                               'title_link': title_link,
                               'experiment_text': experiment_text,
                               'experiment_link': experiment_link,
                               'experiment_name': experiment_name,
                              },
                              context_instance=RequestContext(request))

def get_error_report_as_html(report, user, display_title=False, title_class='red', title_link=None, display_experiment=False):

    # Initialisations
    experiment_text = None
    experiment_link = None
    experiment_name = None

    if display_experiment:
        (experiment_text, experiment_link, experiment_name) = _getExperimentInfos(report, user)

    context = {'report': report,
               'display_title': display_title,
               'title_class': title_class,
               'title_link': title_link,
               'experiment_text': experiment_text,
               'experiment_link': experiment_link,
               'experiment_name': experiment_name,
              }

    return loader.render_to_string('tools/embedded_error_report.html', context)

def _getExperimentInfos(report, user):

    # Initialisations
    experiment_text = None
    experiment_link = None
    experiment_name = None

    if report.experiment is not None:
        if report.experiment.isPublic():
            experiment_link = '/experiments/%d/' % report.experiment.id
            experiment_name = report.experiment.fullname()
        elif report.experiment.isConsortium():
            if not(user.is_anonymous()) and (user.get_profile() is not None) and user.get_profile().project_member:
                experiment_link = '/experiments/%d/' % report.experiment.id
                experiment_name = report.experiment.fullname()
            else:
                experiment_text = 'This error happened during an experiment scheduled by the consortium'
        elif report.experiment.isPrivate():
            if (user == report.experiment.user) or user.is_superuser:
                experiment_link = '/experiments/%d/' % report.experiment.id
                experiment_name = report.experiment.fullname()
            else:
                experiment_text = 'This error happened during a private experiment'

    return (experiment_text, experiment_link, experiment_name)


import struct
import sys

buf = bytes()

buf += struct.pack("<QQQQQQ", 0, 0, 0x60, 0x05, 0x70, 0x03)
buf += struct.pack("<QQQQQQ", 0, 0, 0, 0, 0, 0)
buf += struct.pack("<BBBBBBBBQ", 0x01, 0x02, 0x03, 0x04, 0x05, 0, 0, 0, 0)
buf += struct.pack("<BBB", 0x42, 0x43, 0x44)

sys.stdout.buffer.write(buf)


import WebScrapperWeather as rw
import WebScrapperDict as rd
import WordToDef as cw
import Calculations as calc
import CalculationTermConversion as calcConversions
import WordsAfterCom as arg
import SearchWeb as sw
import os
import subprocess
'''
This file makes all the classes/ functions from other files accesible in one
central file for easy access and clean code
'''

class Operations:
    @staticmethod
    def getWeather():
        weather = rw.returnWeather()
        return weather

    @staticmethod
    def wordToDefine(string):
        chosenWord = cw.checkForWord(string)
        return chosenWord

    @staticmethod
    def getDefinition(word):
        definition = rd.returnDefinition(word)
        return definition

    @staticmethod
    def commandArgs(string, term, addwhitespace=False):
        comArg = arg.checkCommandArgs(string, term, addwhitespace)
        return comArg

    @staticmethod
    def calcTermConversion(string, conversiontype):
        if conversiontype == 'multiplication':
            conversiontype = calcConversions.Conversions["multiplication"]
        elif conversiontype == 'subtraction':
            conversiontype = calcConversions.Conversions["subtraction"]
        elif conversiontype == 'division':
            conversiontype = calcConversions.Conversions["division"]
        converted = calcConversions.applyConversion(string, conversiontype)
        return converted

    @staticmethod
    def returnAnswer(equation):
        answer = calc.calculate(equation)
        return answer

    @staticmethod
    def returnSearch(phrase):
        sw.webSearch(phrase)

    @staticmethod
    def lock():
        subprocess.call('operations\lock.lnk', shell=True)

    @staticmethod
    def hybernate():
        subprocess.call("operations\hybernate.bat")

    @staticmethod
    def shutdown():
        subprocess.call("operations\shutdown20.bat")

    @staticmethod
    def abort():
        subprocess.call("operations\\abortshutdown.bat")


import numpy as np
import torch
from env.block_env import BlockMoveEnvRandomized
from dataset import get_torch_images_from_numpy

test_locs = []
config = {
    "visible": False,
    "init_width": 128,
    "init_height": 128,
    "go_fast": True
}

def get_env(name):
    if name == "block":
        env = BlockMoveEnvRandomized()
    else:
        raise NotImplementedError
    return env

def get_n_test_locs(name):
    if name == "block":
        return 20

def generate_samples(name, env, n_samples=100):
    if name == "block":
        # Set first loc
        loc = [[.05, .42], [0., 0.]]
        start_state = np.zeros((3, 3))
        start_state[1:, :2] = loc
        start_state[1:, 2] = .22
        env.reset(start_state)
        all_images = []
        for i in range(n_samples):
            env.reset(keep_obs=True)
            img = env.get_current_img(config)
            img = get_torch_images_from_numpy(img[None, :], False, one_image=True)
            all_images.append(img)
        return torch.cat(all_images)
    return None

def set_valid_loc(name, env):
    if name == "block":
        # Goal img
        goal_state = env.reset()
        goal_img = env.get_current_img(config)
        goal_img = get_torch_images_from_numpy(goal_img[None, :], False, one_image=True)
        # Start img
        start_state = env.reset(keep_obs=True)
        start_img = env.get_current_img(config)
        start_img = get_torch_images_from_numpy(start_img[None, :], False, one_image=True)
        # Context img
        context = env.get_object(config=config)
        context_img = get_torch_images_from_numpy(context[None, :], False, one_image=True)
        return start_img, goal_img, start_state, goal_state, context_img
    else:
        raise NotImplementedError

def set_test_loc(i, name, env, config, g_npy=None, joints=False, f=''):
    """
    :param i: the index of test location
    :param name: name of env
    :param env: current env
    :return: start, goal, context observations (torch) and set the env to start (size
    1 x C x W x H)
    """
    global test_locs
    if name == "block":
        if len(test_locs) == 0:
            test_locs = [[[[.05, .42], [0., 0.]], [[-.02, -.42], [0., 0.]]],
                         [[[-0.535, .1609], [0., 0.]], [[0.3609, 0.0458], [0., 0.]]],
                         [[[.31, .02], [0., 0.]], [[-.2, -.05], [0., 0.]]],
                         [[[-.02, -.42], [0., 0.]], [[.05, .42], [0., 0.]]],
                         [[[.4, .51], [0., 0.]], [[-.52, -.58], [0., 0.]]],
                         [[[-.52, -.58], [0., 0.]], [[.4, .51], [0., 0.]]],
                         [[[-.55, .52], [0., 0.]], [[.49, -.56], [0., 0.]]],
                         [[[.49, -.56], [0., 0.]], [[-.55, .52], [0., 0.]]],
                         [[[.21, -.39], [0., 0.]], [[.49, .5], [0., 0.]]],
                         [[[-.23, -.07], [0., 0.]], [[.21, .01], [0., 0.]]],
                         [[[.53, -.01], [0., 0.]], [[-.45, .03], [0., 0.]]],
                         [[[-.03, -.61], [0., 0.]], [[.17, .58], [0., 0.]]],
                         [[[-.46, .59], [0., 0.]], [[-.32, -.51], [0., 0.]]],
                         [[[.485, -.61], [0., 0.]], [[-.39, -.31], [0., 0.]]],
                         [[[-.02, -.42], [0., 0.]], [[-.18, .37], [0., 0.]]],
                         [[[-.585, .59], [0., 0.]], [[.57, -.01], [0., 0.]]],
                         [[[.572, -.45], [0., 0.]], [[-.566, -.09], [0., 0.]]],
                         [[[.55, .3], [0., 0.]], [[-.55, -.3], [0., 0.]]],
                         [[[-.333, -.42], [0., 0.]], [[.18, .35], [0., 0.]]],
                         [[[.524, .555], [0., 0.]], [[-.56, .01], [0., 0.]]]]
        start_state = np.zeros((3, 3))
        start_state[1:, :2] = test_locs[i][0]
        start_state[1:, 2] = .22
        goal_state = np.zeros((3, 3))
        goal_state[1:, :2] = test_locs[i][1]
        goal_state[1:, 2] = .22
        start_state[1:, 1] -= 0.2
        goal_state[1:, 1] -= 0.2
        # Goal img
        goal_state = env.reset(goal_state)
        goal_img = env.get_current_img(config)
        goal_img = get_torch_images_from_numpy(goal_img[None, :], False, one_image=True)

        # Start img
        start_state = env.reset(start_state)
        start_img = env.get_current_img(config)
        start_img = get_torch_images_from_numpy(start_img[None, :], False, one_image=True)

        # Context img
        context = env.get_object(config=config)
        context_img = get_torch_images_from_numpy(context[None, :], False, one_image=True)
        return start_img, goal_img, start_state, goal_state, context_img
    else:
        raise NotImplementedError


import numpy as np
import dbdreader

# open a given file
# Note that the default location for cache files ($HOME/.dbdreader) is
# overriden.
dbd=dbdreader.DBD("../data/amadeus-2014-204-05-000.sbd",
                  cacheDir='../data/cac')

# print what parameters are available:

for i,p in enumerate(dbd.parameterNames):
    print("%2d: %s"%(i,p))

# get the measured depth

tm,depth=dbd.get("m_depth")

max_depth=depth.max()
print("\nmax depth %f m"%(max_depth))

# get lat lon
lat,lon=dbd.get_xy("m_lat","m_lon")

# interpolate roll speed on depth time
tm,depth,roll,speed=dbd.get_sync("m_depth","m_roll","m_speed")

print("\nmax speed %f m/s"%(np.nanmax(speed)))

# close the file again.
dbd.close()


#!/usr/bin/env python
# encoding: utf-8

import argparse
import numpy as np
import os
import pdb
import torch
import torch.utils.data as data
import torchvision.datasets as dset
import torchvision.transforms as transforms

from PIL import Image
from os import listdir
from os.path import join
from mmd import mix_rbf_mmd2_weighted

def get_args(parser):
    parser.add_argument('--test_mix', type=str, default='', choices=['', '1090', '2080', '3070', '4060', '5050', '6040', '7030', '8020', '9010'])
    parser.add_argument('--dataset', type=str, default='mnist', help='mnist | cifar10 | cifar100 | lsun | imagenet | folder | lfw ')
    parser.add_argument('--dataroot', default='./data/mnist', help='path to dataset')
    parser.add_argument('--workers', type=int, help='number of data loading workers', default=4)
    parser.add_argument('--gpu_device', type=int, default=0, help='using gpu device id')
    parser.add_argument('--batch_size', type=int, default=64, help='input batch size')
    parser.add_argument('--image_size', type=int, default=32, help='the height / width of the input image to network')
    parser.add_argument('--nc', type=int, default=1, help='number of channel')
    parser.add_argument('--nz', type=int, default=10, help='size of the latent z vector')
    parser.add_argument('--max_iter', type=int, default=25500, help='number of generator updates to train for')
    parser.add_argument('--lambda_mmd', type=float, default=1.0, help='post-training flags, scale factor for MMD, exclusively in errG')
    parser.add_argument('--lambda_ae', type=float, default=8.0, help='post-training flags, scale factor for autoencoder')
    parser.add_argument('--lambda_rg', type=float, default=16.0, help='post-training flags, scale factor for hinge')
    parser.add_argument('--glr', type=float, default=0.00005, help='learning rate, default=0.00005')
    parser.add_argument('--dlr', type=float, default=0.00005, help='learning rate, default=0.00005')
    parser.add_argument('--netG', default='', help="path to netG (to continue training)")
    parser.add_argument('--netD', default='', help="path to netD (to continue training)")
    parser.add_argument('--Diters', type=int, default=5, help='number of D iters per each G iter')
    parser.add_argument('--d_calibration_step', type=int, default=500, help='number of G iters between big n=100 Diter steps')
    parser.add_argument('--schedule', type=str, default='constant', help='schedule of Diters per Giter', choices=['original', 'constant'])
    parser.add_argument('--exp_const', type=float, default=0.05, help='constant from thinning_kernel_part')
    parser.add_argument('--thin_type', type=str, default='logistic', help='type of thinning function', choices=['kernel', 'logistic'])
    parser.add_argument('--thinning_scale', type=float, default=0.75, help='Maximum of thinning_kernel. 1 / (1 - thinning_scale) defines max weight')
    parser.add_argument('--load_existing', type=int, default=0, help='Reference number of saved state file')
    parser.add_argument('--num_pretrain', type=int, default=-1, help='Number of pretrain runs before weighted MMD')
    parser.add_argument('--tag', type=str, default='test', help='tag pre-pended to save_dir')
    parser.add_argument('--diagnostic', type=int, default=0, choices=[0, 1])
    return parser

def is_image_file(filename):
    return any(filename.endswith(extension) for extension in [".png", ".jpg", ".jpeg"])

def load_img(filepath):
    img = Image.open(filepath).convert('RGB')
    return img

class FolderWithImages(data.Dataset):
    def __init__(self, root, input_transform=None, target_transform=None):
        super(FolderWithImages, self).__init__()
        self.image_filenames = [join(root, x)
                                for x in listdir(root) if is_image_file(x.lower())]

        self.input_transform = input_transform
        self.target_transform = target_transform

    def __getitem__(self, index):
        input = load_img(self.image_filenames[index])
        target = input.copy()
        if self.input_transform:
            input = self.input_transform(input)
        if self.target_transform:
            target = self.target_transform(target)

        return input, target

    def __len__(self):
        return len(self.image_filenames)

class ALICropAndScale(object):
    def __call__(self, img):
        return img.resize((64, 78), Image.ANTIALIAS).crop((0, 7, 64, 64 + 7))

def get_data(args, train_flag=True, mix=None):
    transform = transforms.Compose([
        transforms.Scale(args.image_size),
        transforms.CenterCrop(args.image_size),
        transforms.ToTensor(),
        transforms.Normalize(
            (0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
    ])

    if args.dataset in ['imagenet', 'folder', 'lfw']:
        dataset = dset.ImageFolder(root=args.dataroot,
                                   transform=transform)

    elif args.dataset == 'lsun':
        dataset = dset.LSUN(db_path=args.dataroot,
                            classes=['bedroom_train'],
                            transform=transform)

    elif args.dataset == 'cifar10':
        dataset = dset.CIFAR10(root=args.dataroot,
                               download=True,
                               train=train_flag,
                               transform=transform)

    elif args.dataset == 'cifar100':
        dataset = dset.CIFAR100(root=args.dataroot,
                                download=True,
                                train=train_flag,
                                transform=transform)

    elif args.dataset == 'mnist':
        dataset = dset.MNIST(root=args.dataroot,
                             download=True,
                             train=train_flag,
                             transform=transform)
        # Fetch only zeros and twos.
        dataset_main = (
            [v for i,v in enumerate(dataset) if dataset.train_labels[i] == 0])
        dataset_target = (
            [v for i,v in enumerate(dataset) if dataset.train_labels[i] == 1])
        minlen = min(len(dataset_main), len(dataset_target))
        dataset_main = dataset_main[:minlen]
        dataset_target = dataset_target[:minlen]
        if mix is None:
            dataset_mixed_8020 = dataset_main + dataset_target[: minlen / 4]
            dataset_mixed_5050 = dataset_main + dataset_target

            print(('Created set of size {}/{} = {}, '
                'and set of size {}/{} = {}').format(
                    minlen, len(dataset_target[: minlen / 4]),
                    float(minlen / len(dataset_target[: minlen / 4])), minlen,
                    minlen, minlen / minlen))

        # For user-defined proportion, return only the prescribed mix.
        if mix is not None:
            p0 = int(mix[:2])  # E.g. gets 20 from '2080'
            p1 = int(mix[2:])  # E.g. gets 80 from '2080'
            n0 = int(p0 / 100. * minlen)
            n1 = minlen - n0
            print('Mix. Created set of size {}/{}'.format(n0, n1))
            dataset_main = dataset_main[:n0]
            dataset_target = dataset_target[:n1]
            prescribed_mix = dataset_main + dataset_target
            return prescribed_mix, None, dataset_main, dataset_target

        return (dataset_mixed_8020, dataset_mixed_5050, dataset_main,
            dataset_target)

    elif args.dataset == 'celeba':
        imdir = 'train' if train_flag else 'val'
        dataroot = os.path.join(args.dataroot, imdir)
        if args.image_size != 64:
            raise ValueError('the image size for CelebA dataset need to be 64!')

        dataset = FolderWithImages(root=dataroot,
                                   input_transform=transforms.Compose([
                                       ALICropAndScale(),
                                       transforms.ToTensor(),
                                       transforms.Normalize(
                                           (0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
                                   ]),
                                   target_transform=transforms.ToTensor()
                                   )
    else:
        raise ValueError("Unknown dataset %s" % (args.dataset))
    return dataset

def normalize(x, dim=1):
    return x.div(x.norm(2, dim=dim).expand_as(x))

def match(x, y, dist):
    '''
    Computes distance between corresponding points points in `x` and `y`
    using distance `dist`.
    '''
    if dist == 'L2':
        return (x - y).pow(2).mean()
    elif dist == 'L1':
        return (x - y).abs().mean()
    elif dist == 'cos':
        x_n = normalize(x)
        y_n = normalize(y)
        return 2 - (x_n).mul(y_n).mean()
    else:
        assert dist == 'none', 'wtf ?'

def test_wmmd():
    # Get args.
    parser = argparse.ArgumentParser()
    parser = get_args(parser)
    args = parser.parse_args()

    # Config settings for wmmd test.
    wmmd_per_mix = []
    num_tests_per_mix = 10
    mixes = ['1090', '2080', '3070', '4060', '5050', '6040', '7030', '8020',
        '9010']
    # Get base data, the point of comparison for all other mixes.
    trn_dataset_base = get_data(args, train_flag=True, mix='8020')
    trn_loader_base = torch.utils.data.DataLoader(trn_dataset_base,
        batch_size=10, shuffle=True, num_workers=int(args.workers))
    for mix in mixes:
        # Prepare loader for a particular mix.
        trn_dataset_mix = get_data(args, train_flag=True, mix=mix)
        trn_loader_mix = torch.utils.data.DataLoader(trn_dataset_mix,
            batch_size=10, shuffle=True, num_workers=int(args.workers))

        wmmd_samples = []
        for _ in range(num_tests_per_mix):
            # Get batches of base and mix.
            batch_base, labels_base = iter(trn_loader_base).next()
            batch_mix, labels_mix = iter(trn_loader_mix).next()
            scaled_labels_base = (
                args.thinning_scale * labels_base.type(torch.FloatTensor))
            # Compute wmmd2 between samples.
            enc_base, _ = netD(Variable(batch_base.cuda()))
            enc_mix, _ = netD(Variable(batch_mix.cuda()))
            sigma_list = [1., 2., 4., 8., 16.]
            wmmd2 = mix_rbf_mmd2_weighted(enc_base, enc_mix, sigma_list,
                args.exp_constant, args.thinning_scale,
                x_enc_p1=scaled_labels_base)
            wmmd_samples.append(wmmd2)


from __future__ import annotations
import numpy as np
from collections import deque
from typing import List, Tuple

class Actions():
    LEFT = 0
    RIGHT = 1
    UP = 2
    DOWN = 3

class PlayerData():
    def __init__(self, ID, is_human=False, size=7):

        # left/right/up/down
        # dont need down, using it just for human
        self.direction_arr = [
            [-1, 1, -1, 1],
            [1, -1, 1, -1],
            [-1, 1, 1, -1],
            [1, -1, -1, 1]
        ]

        # x = 0, y = 1 for coordinate system
        self.axis_arr = [
            [1, 1, 0, 0],
            [1, 1, 0, 0],
            [0, 0, 1, 1],
            [0, 0, 1, 1]
        ]

        # left/right/up/down ; for sight
        # leftUP/leftDOWN/rightUP/rightDOWN
        self.directions = [ [-1, 0], [1, 0], [0, 1], [0, -1], [-1, 1], [-1, -1], [1, 1], [1, -1] ]

        self.ID = ID
        self.size = size

        # normalization range
        self.t_min = -1
        self.t_max = 1

        # get the whole matrix for the game; used for random apple
        self.whole_coord = np.mgrid[0:size, 0:size].reshape(2, -1).T.tolist()

        self.is_biggest_snake = 0
        self.snake_position = list()
        self.is_human = is_human
        self.direction = 2
        self.score = 3 # also known as length
        self.moves_to_get_apple = 0
        self.total_moves = 0
        self.just_eat_apple = 0
        self.done = False
        self.health = 100
        self.prev_actions = deque([-1] * 30, maxlen=30)
        self.max_score = 0

    def SetPosition(self, position: List[list]):
        self.snake_position = position

    def SetIsHuman(self, is_human: bool):
        self.is_human = is_human

    def AddPosition(self, position: list):
        self.snake_position.append(position)

    def getPosition(self) -> List[list]:
        return self.snake_position

    def getHead(self) -> list:
        return [ self.snake_position[0][0], self.snake_position[0][1] ]

    def getTail(self) -> list:
        return [ self.snake_position[-1][0], self.snake_position[-1][1] ]

    def getID(self) -> int:
        return self.ID

    def getScore(self) -> int:
        return self.score

    def setScore(self, score:int):
        self.score=score

    def setDone(self, done: bool):
        self.done = done

    def isDone(self) -> bool:
        return self.done

    def getHealth(self) -> bool:
        return self.health

    def setHealth(self, health):
        self.health = health

    def addToPrevAction(self, action):
        norm_action = self.normalize_val(action, 0, 2)
        self.prev_actions.append(norm_action)

    def setDirection(self, direction):
        self.direction = direction

    def getDirection(self):
        return self.direction

    def setAteApple(self, ate_apple: int):
        self.just_eat_apple = ate_apple

    def getAteApple(self):
        return self.just_eat_apple

    def setBiggestSnake(self, is_biggest: int):
        self.is_biggest_snake = is_biggest

    def getBiggestSnake(self):
        return self.is_biggest_snake

    # returning whether we just ate apple for reward and the apple to delete if we ate one
    def MoveSnake(self, action: int, apple_positions: List[list]) -> Tuple[int, list]:

        if isinstance(action, list):
            action = action[0]

        # make sure not dead
        if self.done:
            return -.3, None

        snake_head = [ self.snake_position[0][0], self.snake_position[0][1] ]

        if not self.is_human:
            val = self.direction_arr[action][self.direction]
            which_axis = self.axis_arr[action][self.direction]

            # get new direction
            if val == -1 and which_axis == 0:
                self.direction = Actions.LEFT
            elif val == -1 and which_axis == 1:
                self.direction = Actions.DOWN
            elif val == 1 and which_axis == 0:
                self.direction = Actions.RIGHT
            else:
                self.direction = Actions.UP

            # move the snake head
            if which_axis == 0:
                snake_head[0] += val
            else:
                snake_head[1] += val

        else:
            # this also keeps the direction to up / doesnt change
            # left, right, up, down
            if action == Actions.LEFT:
                snake_head[0] -= 1
            elif action == Actions.RIGHT:
                snake_head[0] += 1
            # switched up and down
            elif action == Actions.UP:
                snake_head[1] += 1
            elif action == Actions.DOWN:
                snake_head[1] -= 1

        self.moves_to_get_apple += 1
        self.health -= 1
        self.total_moves += 1

        norm_action = self.normalize_val(action, 0, 2)
        self.prev_actions.append(norm_action)

        # seeing if we just ate an apple
        if snake_head in apple_positions:
            self.score += 1

            # remove the apple somehow ?? ?
            # apple_positions.remove()
            self.snake_position.insert(0, snake_head)

            if self.just_eat_apple == 0:
                self.snake_position.pop()

            self.just_eat_apple = 1

            if self.score > self.max_score:
                self.max_score = self.score

            # should reward not be based on how many moves it takes ?
            # reward = 1
            reward = (1 - (self.moves_to_get_apple / 100))

            self.moves_to_get_apple = 0
            self.health = 100

        # otherwise just move the snake
        else:
            self.snake_position.insert(0, snake_head)
            if self.just_eat_apple == 1:
                self.just_eat_apple = 0
            else:
                self.snake_position.pop()

            # reward based on if we see an apple? ; not sure if this would work
            # baseline reward for being alive
            # reward = .00001
            reward = 0

        # collisiion with self
        if self.total_moves > 3 and snake_head in self.snake_position[1:]:
            self.done = True
            reward = -3

        # collision with walls
        elif snake_head[0] >= self.size or \
            snake_head[0] < 0 or \
            snake_head[1] >= self.size or \
            snake_head[1] < 0:

            self.done = True
            reward = -3

        # made too many moves
        elif self.moves_to_get_apple >= 100 or self.health <= 0:
            self.done = True
            reward = -3

        # have to send back which apple we just ate
        if self.just_eat_apple:
            apple_to_delete = snake_head
        else:
            apple_to_delete = None

        return reward, apple_to_delete

    # need to see if it is head that collided or other body part
    # because if it is head, need to check which snake is longer to see who dies
    def collideWithOtherSnakes(self, other_snake: PlayerData) -> Tuple[bool, bool]:
        if self.ID != other_snake.getID():
            snake_head = [ self.snake_position[0][0], self.snake_position[0][1] ]

            for idx, pos in enumerate(other_snake.getPosition()):
                if snake_head == pos:
                    # both heads collide
                    if idx == 0:
                        return True, True

                    else:
                        return True, False

        # if snake collided, collided with head of other snake
        return False, False

    def getOBS(self, snake_players: List[PlayerData], apple_positions: List[list]) -> list:

        snake_head = self.getHead()

        sight_obs = list()
        # looking in 8 directions
        # for each direction we can see distances from
        # * apple
        # * wall
        # * itself
        # * another snakes * how many players there are
        # as well as if we are looking at a snakes head/tail
        for direction in self.directions:
            sight_obs += self._lookInDirection(direction, snake_head, snake_players, apple_positions)

        num_alive_snakes = 0

        for player in snake_players:
            if not player.isDone():
                num_alive_snakes += 1

            # seeing if a snake is the longest on the board
            if player.getID() != self.getID():
                if self.getScore() > player.getScore():
                    self.is_biggest_snake = 1
                else:
                    self.is_biggest_snake = 0

        norm_head = self.normalize(self.getHead(), 0, self.size - 1)
        norm_tail = self.normalize(self.getTail(), 0, self.size - 1)
        norm_direction = self.normalize_val(self.direction, 0, 3)
        norm_score = self.normalize_val(self.score, 3, self.size ** 2 - 3 * len(snake_players)) # snake length
        norm_health = self.normalize_val(self.health, 0, 100)
        norm_num_apples_on_board = self.normalize_val(len(apple_positions), 1, self.size ** 2 - 3 * len(snake_players)) # always will be 1 apple
        norm_alive_snakes = self.normalize_val(num_alive_snakes, 0, len(snake_players)) # all snakes can die on a single turn

        normalized_obs = norm_head + \
            norm_tail + \
            [norm_direction,
            int(self.done),
            norm_score,
            norm_health,
            self.just_eat_apple,
            norm_num_apples_on_board,
            norm_alive_snakes,
            self.is_biggest_snake
            ] + sight_obs + \
            list(self.prev_actions)

        return normalized_obs

    # direction should be -1/+1 in tuple (1, -1) for x, y
    def _lookInDirection(self, direction: int, snake_head: list, other_snakes: List[PlayerData], apple_positions: List[list]) -> list:

        look = [-1] * (4 + len(other_snakes))
        food_found = False

        # need to check the first time we come across a specific snake
        other_snakes_found = [False] * (len(other_snakes))

        distance = 0

        # go the to position we need in the direction
        curr_pos = [snake_head[0] + direction[0], snake_head[1] + direction[1]]

        while not self._isCollidingWall(curr_pos):
            norm_distance = self.normalize_val(distance, -1, self.size)
            if not food_found and self._isCollidingApple(curr_pos, apple_positions):
                food_found = True
                look[0] = norm_distance

            # looking for other snakes
            # start index at 4 bc of look
            counter = 0
            idx = 4
            snakes_found_idx = 0
            for other_snake in other_snakes:

                # making sure this isnt the same snake
                if self.getID() != other_snake.getID():
                    # seeing if we collide with another snake and have not seen it yet
                    if not other_snakes_found[snakes_found_idx] and curr_pos in other_snake.getPosition():
                        look[idx - 1 - counter] = norm_distance

                        # See if we are looking at the head/tail/body
                        # head = 1
                        # tail = 0
                        # body/neither = -1
                        if curr_pos == other_snake.getPosition()[0]:
                            look[idx - counter] = 1
                        elif curr_pos == other_snake.getPosition()[-1]:
                            look[idx - counter] = 0

                        other_snakes_found[snakes_found_idx] = True

                # if we are the same snake, dont count head cause we cant
                # current snake will always be in position 2
                elif self.getID() == other_snake.getID():
                    if curr_pos in other_snake.getPosition()[1:]:
                        # distance for this snake body
                        look[2] = norm_distance

                        # if what we are looking at is the tail
                        # tail = 1
                        # body/head?/nothing = -1
                        if curr_pos == other_snake.getPosition()[-1]:
                            look[3] = 1

                        other_snakes_found[snakes_found_idx] = True

                idx += 2
                counter += 1
                snakes_found_idx += 1

            # increment the position
            curr_pos[0] += direction[0]
            curr_pos[1] += direction[1]

            distance += 1

        norm_distance = self.normalize_val(distance, -1, self.size)
        # wall distance
        look[1] = norm_distance

        return look

    def _isCollidingWall(self, position: list) -> bool:
        if position[0] >= self.size or \
            position[0] < 0 or \
            position[1] >= self.size or \
            position[1] < 0:

            return True

        return False

    def _isCollidingApple(self, position: list, apple_positions: List[list]):
        if position in apple_positions:
            return True

        return False

    def _isCollidingSnake(self, position: list) -> bool:
        if position in self.snake_position:
            return True

        return False

    def normalize(self, arr: list, min_val: int, max_val: int) -> list:
        norm_arr = []
        diff = self.t_max - self.t_min
        diff_arr = max_val - min_val
        for i in arr:
            temp = (((i - min_val)*diff)/diff_arr) + self.t_min
            norm_arr.append(temp)
        return norm_arr

    def normalize_val(self, val: int, min_val: int, max_val: int) -> int:
        diff = self.t_max - self.t_min
        diff_val = max_val - min_val
        return (((val - min_val)*diff)/diff_val) + self.t_min


import logging
import os

import requests

from flask import (
    Flask,
    render_template,
    send_from_directory,
    json,
)

from cache import Cache

SLACK_NAMES_CACHE_KEY = 'slack_name'
PREVIOUS_STATE_CACHE_KEY = 'players_previous'
PLAYERS_CACHE_KEY = 'players'
POOLBOT_PLAYERS_API_URL = os.environ.get('POOLBOT_URL')
POOLBOT_AUTH_TOKEN = os.environ.get('POOLBOT_TOKEN')
SLACK_API_TOKEN = os.environ.get('SLACK_API_TOKEN')
PLAYERS_CACHE_TIMEOUT = 30

cache = Cache()

def slack_names():
    url = 'https://slack.com/api/users.list'
    response = requests.get(
        url,
        params=dict(
            token=SLACK_API_TOKEN
        )
    )
    content = response.json()
    if content['ok']:
        cache.set(SLACK_NAMES_CACHE_KEY, {
            u['id']: u['real_name']
            for u in content['members']
            if 'real_name' in u
        })
    else:
        logging.error(content['error'])

slack_names()

def get_diff(player):
    """returns num season_elo points gained/lost since the previous state"""
    for player_previous_state in cache.get(PREVIOUS_STATE_CACHE_KEY) or []:
        if player_previous_state['slack_id'] == player['slack_id']:
            return player['season_elo'] - player_previous_state['season_elo']
    return 0

def get_players():
    response = requests.get(
        POOLBOT_PLAYERS_API_URL,
        params=dict(
            active=True,
            ordering='-season_elo',
        ),
        headers=dict(
            Authorization='Token {}'.format(POOLBOT_AUTH_TOKEN),
        )
    )

    if response.ok:
        players = response.json()
        slack_names = cache.get(SLACK_NAMES_CACHE_KEY) or {}

        _players = [
            dict(
                name=slack_names.get(player['slack_id'], player['name']),
                season_elo=player['season_elo'],
                diff=get_diff(player),
                slack_id=player['slack_id'],
            )
            for player in players
            if player['active'] and player['season_match_count'] > 0
        ]

        # this code is horrible spaghetti, please forgive me
        position = 1
        for idx, player in enumerate(_players):
            player['id'] = idx
            if idx == 0:
                # first place - no previous player to compare
                player['position'] = position
            else:
                previous_player = _players[idx-1]
                if previous_player['season_elo'] == player['season_elo']:
                    player['position'] = '-'
                else:
                    player['position'] = position
            position += 1

        return _players
    else:
        logging.error(response.content)
        return []

app = Flask(__name__, static_url_path='/static')

@app.route('/js/<path:path>')
def send_js(path):
    return send_from_directory('js', path)

@app.route('/css/<path:path>')
def send_css(path):
    return send_from_directory('css', path)

@app.route('/api/')
def players():
    current_state = cache.get(PLAYERS_CACHE_KEY)
    previous_state = cache.get(PREVIOUS_STATE_CACHE_KEY)

    if not current_state and not previous_state:
        # intialise
        players = get_players()
        cache.set(PLAYERS_CACHE_KEY, players, timeout=PLAYERS_CACHE_TIMEOUT)
        cache.set(PREVIOUS_STATE_CACHE_KEY, players)
    elif current_state is None:
        # cache has expired, refresh the players list
        players = get_players()

        no_change = set([p['diff'] for p in players]) == set([0])
        if no_change:
            # elo hasn't changed meaning no one has played
            cache.set(PLAYERS_CACHE_KEY, previous_state, timeout=PLAYERS_CACHE_TIMEOUT)
        else:
            # someone's played, update the table
            cache.set(PLAYERS_CACHE_KEY, players, timeout=PLAYERS_CACHE_TIMEOUT)
            cache.set(PREVIOUS_STATE_CACHE_KEY, players)

    return json.dumps(
        dict(
            players=cache.get(PLAYERS_CACHE_KEY),
            secondsLeft=cache.time_remaining(PLAYERS_CACHE_KEY),
            cacheLifetime=PLAYERS_CACHE_TIMEOUT
        )
    )

@app.route("/")
def index():
    return render_template('index.html')

if __name__ == "__main__":
    slack_names()
    app.run(debug=True, threaded=True)


import scipy.io as sio
import numpy as np
import matplotlib.pyplot as plt

dataset = sio.loadmat('dataset.mat')
data_train_X = dataset['data_train_X']
data_train_y = dataset['data_train_y'][0]
data_test_X = dataset['data_test_X']
data_test_y = dataset['data_test_y'][0]
lambd_seq = np.random.uniform(0.02, 1.5, 50)

def shuffle_data(data):
    np.random.permutation(data)

def split_data(data, num_folds, fold):
    split = np.split(np.array(data), num_folds)
    chosen = split[fold - 1]
    rest = np.concatenate([split[i] for i in range(num_folds) if i != (fold - 1)])
    return chosen, rest

def train_model(train_data, lambd):
    train_X, train_y = zip(*train_data)
    x_t_dot_x = np.dot(np.transpose(train_X), train_X)
    lambda_identity = lambd * np.identity(x_t_dot_x.shape[0])
    beta_ridge = np.dot(np.dot(np.linalg.inv(x_t_dot_x + lambda_identity), np.transpose(train_X)), train_y)
    return beta_ridge

def predict(test_X, beta_trained):
    test_label = np.dot(test_X, beta_trained)
    return test_label

def loss(test_data, beta_trained):
    test_X, test_y = zip(*test_data)
    test_label = predict(test_X, beta_trained)
    result = np.linalg.norm(test_y - test_label, ord=2)
    return result ** 2 / test_label.shape[0]

def cross_validation(data, num_folds):
    cv_error = {}
    for i in lambd_seq:
        cv_loss_lmd = 0
        for fold in range(1, num_folds + 1):
            data_fold, data_rest = split_data(data, num_folds=num_folds, fold=fold)
            beta = train_model(data_rest, lambd=i)
            cv_loss_lmd += loss(data_fold, beta)
        cv_error[i] = cv_loss_lmd / num_folds
    lowest_err = float("inf")
    best_lambda = 0
    for i in cv_error:
        if lowest_err > cv_error[i]:
            lowest_err = cv_error[i]
            best_lambda = i
    print("Best lambda for " + str(num_folds) + " fold is", best_lambda)
    return cv_error

if __name__ == "__main__":
    combined_training = list(zip(data_train_X, data_train_y))
    combined_testing = list(zip(data_test_X, data_test_y))
    shuffle_data(combined_training)

    num_folds_seq = [5, 10]

    lines = []
    plot_shape  = {num_folds_seq[0]: 's', num_folds_seq[1]: 'o'}

    for num_folds in num_folds_seq:
        cv_error = cross_validation(combined_training, num_folds)
        x_val = []
        y_val_cv_err = []
        for i in lambd_seq:
            x_val.append(i)
            y_val_cv_err.append(cv_error[i])

        line, = plt.plot(x_val, y_val_cv_err, 'g'+ plot_shape[num_folds], label='Cross Validation Error ' +
                                                                                str(num_folds) + ' fold')
        lines.append(line,)

    train_error = {}
    test_error = {}
    for i in lambd_seq:
        beta_ridge = train_model(combined_training, i)
        train_error[i] = loss(combined_training, beta_ridge)
        test_error[i] = loss(combined_testing, beta_ridge)

    x_val = []
    y_val_train_err = []
    y_val_test_err = []
    for i in lambd_seq:
        x_val.append(i)
        y_val_train_err.append(train_error[i])
        y_val_test_err.append(test_error[i])

    line1, = plt.plot(x_val, y_val_train_err, 'b^', label='Training Error')
    line2, = plt.plot(x_val, y_val_test_err, 'r^', label='Testing Error')
    lines.append(line1)
    lines.append(line2)

    plt.xlabel('lambda')
    plt.ylabel('Error')
    plt.legend(handles=lines, loc='best')
    plt.show()


# Name:        EC
# Purpose:     Determine EC on Groundwater
#
# Author:      Elham Soleimanian

# Created:     04/25/2021
# -------------------------------------------------------------------------
# Import Libraries
import numpy as np
import pandas as pd
from scipy import stats
from sklearn.linear_model import LinearRegression
# Import Data
Data  = pd.ExcelFile(r'C:\0el\DataforSalinatary\GWData (Autosaved).xlsx')
ec  = pd.read_excel(Data, 'Sheet1',usecols='B').to_numpy()
tds  = pd.read_excel(Data, 'Sheet1',usecols='c').to_numpy()
head  = pd.read_excel(Data, 'Sheet1',usecols='D').to_numpy()
precipitation  = pd.read_excel(Data, 'Sheet1',usecols='E').to_numpy()
evaporation = pd.read_excel(Data, 'Sheet1',usecols='F').to_numpy()
deepperculation = pd.read_excel(Data, 'Sheet1',usecols='G').to_numpy()
y = pd.read_excel(Data, 'Sheet1',usecols='B').to_numpy()

# Calculate Linear Correlation Between EC and Independent Variables
rtds = np.corrcoef(ec, tds, rowvar=False)
rhead = np.corrcoef(ec, head, rowvar=False)
rprecipitation = np.corrcoef(ec, precipitation, rowvar=False)
revaporation = np.corrcoef(ec, evaporation, rowvar=False)
rdeepperculation = np.corrcoef(ec, deepperculation, rowvar=False)

# Generate Regression Model Based On Importabt Parametes Which Drived from Previous Step
# Import Independent and Dependent Vriables
x = pd.read_excel(Data, 'Sheet1',usecols='C:G').to_numpy()
# y = [0.56,0.12,0.47,0.293333,0.248333,0.203333,0.158333,0.113333,0.0683333,	0.0233333,0.7,0.414444,0.47254,	0.530635,0.58873,0.646825,0.704921,0.763016]
model = LinearRegression().fit(x, y)
r_sq = model.score(x, y)
print('coefficient of determination:', r_sq)
print('intercept:', model.intercept_)
print('slope:', model.coef_)
# Validate Generated Model
# y_pred = model.predict(x)
# print('predicted response:', y_pred, sep='\n')