import cv2
import numpy as np

pic = cv2.imread('Lenna.png') # Loading original image
gray = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY) # Convering image in grayscale

rows,columns = gray.shape
#print("Shape of gray",r,c)

final_matx_3x3 = np.zeros([rows,columns])
#print("3x3",final_matx_3x3.shape)

# For 3 * 3

kernal_matx_3x3 = np.ones(3)/3
#print(kernal_matx)

kernal_length = len(kernal_matx_3x3)

for i in range(rows):
    for j in range(columns-(kernal_length-1)):
        sum = 0
        for k in range(kernal_length):
            sum = sum + (gray[i][j+k] * kernal_matx_3x3[k])
        final_matx_3x3[i][j+(kernal_length//2)] = sum  # Generalizing the pixel value based on kernal length

for p in range(columns):
    for q in range(rows-((kernal_length-1))):
        sum = 0
        for r in range(kernal_length):
            sum = sum + (final_matx_3x3[q+k][p] * kernal_matx_3x3[r])
        final_matx_3x3[q+(kernal_length//2)][p] = sum  # Generalizing the pixel value based on kernal length

final_matx_3x3 = final_matx_3x3.astype(np.uint8)

## For 5 * 5
kernal_matx_5x5 = np.ones(5)/5

final_matx_5x5 = np.zeros([rows,columns])

kernal_length = len(kernal_matx_5x5)

for i in range(rows):
    for j in range(columns-(kernal_length-1)):
        sum = 0
        for k in range(kernal_length):
            sum = sum + (gray[i][j+k] * kernal_matx_5x5[k])
        final_matx_5x5[i][j+(kernal_length//2)] = sum # Generalizing the pixel value based on kernal length

for p in range(columns):
    for q in range(rows-((kernal_length-1))):
        sum = 0
        for r in range(kernal_length):
            sum = sum + (final_matx_5x5[q+k][p] * kernal_matx_5x5[r])
        final_matx_5x5[q+(kernal_length//2)][p] = sum   # Generalizing the pixel value based on kernal length

final_matx_5x5 = final_matx_5x5.astype(np.uint8)

## For 7x7

kernal_matx_7x7 = np.ones(7)/7

final_matx_7x7 = np.zeros([rows,columns])

kernal_length = len(kernal_matx_7x7)

for i in range(rows):
    for j in range(columns-(kernal_length-1)):
        sum = 0
        for k in range(kernal_length):
            sum = sum + (gray[i][j+k] * kernal_matx_7x7[k])
        final_matx_7x7[i][j+(kernal_length//2)] = sum # Generalizing the pixel value based on kernal length

for p in range(columns):
    for q in range(rows-((kernal_length-1))):
        sum = 0
        for r in range(kernal_length):
            sum = sum + (final_matx_7x7[q+k][p] * kernal_matx_7x7[r])
        final_matx_7x7[q+(kernal_length//2)][p] = sum   # Generalizing the pixel value based on kernal length

final_matx_7x7 = final_matx_7x7.astype(np.uint8)

## For 9x9

kernal_matx_9x9 = np.ones(9)/9

final_matx_9x9 = np.zeros([rows,columns])

kernal_length = len(kernal_matx_9x9)

for i in range(rows):
    for j in range(columns-(kernal_length-1)):
        sum = 0
        for k in range(kernal_length):
            sum = sum + (gray[i][j+k] * kernal_matx_9x9[k])
        final_matx_9x9[i][j+(kernal_length//2)] = sum # Generalizing the pixel value based on kernal length

for p in range(columns):
    for q in range(rows-((kernal_length-1))):
        sum = 0
        for r in range(kernal_length):
            sum = sum + (final_matx_9x9[q+k][p] * kernal_matx_9x9[r])
        final_matx_9x9[q+(kernal_length//2)][p] = sum   # Generalizing the pixel value based on kernal length

final_matx_9x9 = final_matx_9x9.astype(np.uint8)

## For 11X11

kernal_matx_11x11 = np.ones(11)/11

final_matx_11x11 = np.zeros([rows,columns])

kernal_length = len(kernal_matx_11x11)

for i in range(rows):
    for j in range(columns-(kernal_length-1)):
        sum = 0
        for k in range(kernal_length):
            sum = sum + (gray[i][j+k] * kernal_matx_11x11[k])
        final_matx_11x11[i][j+(kernal_length//2)] = sum # Generalizing the pixel value based on kernal length

for p in range(columns):
    for q in range(rows-((kernal_length-1))):
        sum = 0
        for r in range(kernal_length):
            sum = sum + (final_matx_11x11[q+k][p] * kernal_matx_11x11[r])
        final_matx_11x11[q+(kernal_length//2)][p] = sum   # Generalizing the pixel value based on kernal length

final_matx_11x11 = final_matx_11x11.astype(np.uint8)

while(True):
    cv2.imshow("Originl_pic", pic)
    cv2.imshow("Grayscale", gray)
    cv2.imshow("After 3x3 Average Filter", final_matx_3x3)
    cv2.imshow("After 5x5 Average Filter", final_matx_5x5)
    cv2.imshow("After 7x7 Average Filter", final_matx_7x7)
    cv2.imshow("After 9x9 Average Filter", final_matx_9x9)
    cv2.imshow("After 11x11 Average Filter", final_matx_11x11)

    if cv2.waitKey(1) == 27:
       break

cv2.destroyAllWindows()


from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from . import mysqlutil
from . import movieinfo
import time

# 设置selenium使用chrome的无头模式
chrome_options = Options()
movieList = []  # 电影元组，其中append的每一个元素为一个Movie对象

# chrome_options.add_argument('headless')  # 设置option,隐藏浏览器界面
# 在启动浏览器时加入配置
browser = webdriver.Chrome(
    r'C:\Users\XDH\PycharmProjects\seleniumfirst\venv\Scripts\chromedriver.exe',
    options=chrome_options)  # 获取chrome浏览器的驱动，并启动Chrome浏览器
browser.quit()  # 清除后台进程，因为配合django时，每改动一次代码，就会加载一次项目文件，就会新建一个webdriver

def baidu():
    # 打开百度
    browser.get('https://www.baidu.com/')
    # 等待加载，最多等待20秒
    browser.implicitly_wait(20)
    browser.maximize_window()  # 窗口最大化

    su = browser.find_element_by_id("su")
    kw = browser.find_element_by_id("kw")
    su_content = su.get_attribute("value")
    print(su_content)

    browser.maximize_window()
    browser.set_script_timeout(5)
    kw.send_keys("selenium")
    su.click()

# 对照页面布局，爬取页面数据
def get_movies_info_in_current_page():
    movie = browser.find_elements_by_class_name("recommend-movie")
    for m in movie:
        order = m.find_element_by_class_name("m-t-n").text  # 排名
        name = m.find_element_by_class_name("m-t-t") .text  # 电影名
        r_m_info = m.find_element_by_class_name("r-m-info")
        score = r_m_info.find_element_by_class_name("score").text  # 评分
        info_detail = r_m_info.find_elements_by_class_name("info-detail")
        dire_info_l = info_detail[1].find_element_by_class_name("info-l")  # 第二个info-detail为导演信息
        dire = dire_info_l.find_element_by_class_name("info-value").text  # 导演名
        pub_info_m = info_detail[2].find_element_by_class_name("info-m")  # 第三个info-detail
        pub_time = pub_info_m.find_element_by_class_name("info-value").text  # 上映时间
        info_t = info_detail[2].find_element_by_class_name("info-t")  # 第三个info-detail
        movie_time = info_t.find_element_by_class_name("info-value").text  # 电影时长

        movie_obj = movieinfo.Movie(order, name, score, dire, pub_time, movie_time)
        movieList.append(movie_obj)

def douban():
    browser.get('https://www.km.com/piandan/1912.html?page=1')
    # 等待加载，最多等待20秒
    browser.implicitly_wait(20)
    browser.maximize_window()  # 窗口最大化

    # for i in range(1):
    while True:
        pages = browser.find_element_by_class_name("v_page")
        try:
            browser.implicitly_wait(10)
            get_movies_info_in_current_page()  # 获取当前网页中的电影信息
            next_page = pages.find_element_by_xpath("//*[text()='下一页']")
            next_page.click()
        except BaseException as e:
            # raise e # 如果raise异常，程序会直接停止并打印异常信息
            print("异常，未找到“下一页”，已是最后一页")
            break

def get_something_from_selenium():
    # return su_content
    all_in_one_string = ""
    for i in movieList:
        all_in_one_string = all_in_one_string + "\t" + i.movie_name

    return all_in_one_string

if __name__ == '__main__':
    browser = webdriver.Chrome(
        r'C:\Users\XDH\PycharmProjects\seleniumfirst\venv\Scripts\chromedriver.exe',
        options=chrome_options)  # 获取chrome浏览器的驱动，并启动Chrome浏览器
    douban()  # 查找第三方网站豆瓣top250
    # baidu()
    browser.execute_script("alert('浏览器将在3秒后自动关闭')")
    time.sleep(3)
    browser.quit()
    for i in movieList:
        # print(i.movie_name+i.movie_order+i.movie_score+i.movie_direct+i.movie_public_time+i.movie_time)
        mysqlutil.insert_movie(name=i.movie_name, order=i.movie_order, score=i.movie_score,
                               direct=i.movie_direct, public_time=i.movie_public_time, time=i.movie_time)


import numpy as np
from numpy import linalg as LA

from shfl.federated_aggregator import FedAvgAggregator
from multipledispatch import dispatch
from multipledispatch.variadic import Variadic

class NormClipAggregator(FedAvgAggregator):
    """
    Implementation of Average Federated Aggregator with Clipped Norm.
    It clips the norm of the client's updates and averages them.

    # Arguments:
        clip: value used to clip each client's update
    """

    def __init__(self, clip):
        self._clip = clip

    def _serialize(self, data):
        """
        It turns a list of multidimensional arrays into a list of one-dimensional arrays

        # Arguments:
            data: list of multidimensional arrays
        """
        data = [np.array(j) for j in data]
        self._data_shape_list = [j.shape for j in data]
        serialized_data = [j.ravel() for j in data]
        serialized_data = np.hstack(serialized_data)
        return serialized_data

    def _deserialize(self, data):
        """
        It turns a list of one-dimensional arrays into a list of multidimensional arrays.
        The multidimensional shape is stored when it is serialized

        # Arguments:
            data: list of one-dimensional arrays
        """

        firstInd = 0
        deserialized_data = []
        for shp in self._data_shape_list:
            if len(shp) > 1:
                shift = np.prod(shp)
            elif len(shp) == 0:
                shift = 1
            else:
                shift = shp[0]
            tmp_array = data[firstInd:firstInd+shift]
            tmp_array = tmp_array.reshape(shp)
            deserialized_data.append(tmp_array)
            firstInd += shift
        return deserialized_data

    @dispatch(Variadic[np.ndarray, np.ScalarType])
    def _aggregate(self, *params):
        """Aggregation of arrays"""
        clients_params = np.array(params)
        for i, v in enumerate(clients_params):
            norm = LA.norm(v)
            clients_params[i] = np.multiply(v, min(1, self._clip/norm))

        return np.mean(clients_params, axis=0)

    @dispatch(Variadic[list])
    def _aggregate(self, *params):
        """Aggregation of (nested) lists of arrays"""
        serialized_params = np.array([self._serialize(client) for client in params])
        serialized_aggregation = self._aggregate(*serialized_params)
        aggregated_weights = self._deserialize(serialized_aggregation)

        return aggregated_weights

class CDPAggregator(NormClipAggregator):
    """
    Implementation of Average Federated Aggregator with Differential Privacy also known \
    as Central Differential Privacy.
    It clips the norm of the client's updates, averages them and adds gaussian noise \
    calibrated to noise_mult*clip/number_of_clients.

    # Arguments:
        clip: value used to clip each client's update.
        noise_mult: quantity of noise to add. To ensure proper Differential Privacy, \
        it must be calibrated according to some composition theorem.
    """

    def __init__(self, clip, noise_mult):
        super().__init__(clip=clip)
        self._noise_mult = noise_mult

    @dispatch(Variadic[np.ndarray, np.ScalarType])
    def _aggregate(self, *params):
        """Aggregation of arrays with gaussian noise calibrated to noise_mult*clip/number_of_clients"""
        clients_params = np.array(params)
        mean = super()._aggregate(*params)
        noise = np.random.normal(loc=0.0, scale=self._noise_mult*self._clip/len(clients_params), size=mean.shape)
        return mean + noise

    @dispatch(Variadic[list])
    def _aggregate(self, *params):
        return super()._aggregate(*params)

class WeakDPAggregator(CDPAggregator):
    """
    Implementation of Average Federated Aggregator with Weak Differential Privacy.
    It clips the norm of the client's updates, averages them and adds gaussian noise \
    calibrated to 0.025*clip/number_of_clients.
    The noise multiplier 0.025 is not big enough to ensure proper Differential Privacy.

    # Arguments:
        clip: value used to clip each client's update
    """
    def __init__(self, clip, noise_mult=0.025):
        super().__init__(clip=clip, noise_mult = noise_mult)

    @dispatch(Variadic[np.ndarray, np.ScalarType])
    def _aggregate(self, *params):
        return super()._aggregate(*params)

    @dispatch(Variadic[list])
    def _aggregate(self, *params):
        return super()._aggregate(*params)


import tkinter as tk
from PIL import Image, ImageDraw
import cv2
import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets, svm

digits = datasets.load_digits()

data = digits.data
target = digits.target
images = digits.images

#64 features (pixel values)
#1797 targets

classifier = svm.SVC(gamma = 0.0001, C = 100)
classifier.fit(data, target)

##print(len(target)) #1797
##
##print(data.shape)  #(1797, 64)
##data is a 2D Array
##
##print(data[0])
##[ 0.  0.  5. 13.  9.  1.  0.  0.  0.  0. 13. 15. 10. 15.  5.  0.  0.  3.
## 15.  2.  0. 11.  8.  0.  0.  4. 12.  0.  0.  8.  8.  0.  0.  5.  8.  0.
##  0.  9.  8.  0.  0.  4. 11.  0.  1. 12.  7.  0.  0.  2. 14.  5. 10. 12.
##  0.  0.  0.  0.  6. 13. 10.  0.  0.  0.]
##
##plt.imshow(images[1], cmap = 'binary')
##plt.show()

window = tk.Tk()

width  = 500
height = 500
font   = 'Helvetica 20 bold'

def event_function(event):
    #canvas1.create_oval((20, 20, 100, 100), outline = 'red', width = 3)
    #print(event.char)
    #canvas1.create_text(20, 20, text = event.char)
    #label_predict.config(text = event.char)
    #canvas1.create_oval((20, 20, 40, 40), fill = 'black')

    x1 = event.x - 30
    y1 = event.y - 30
    x2 = event.x + 30
    y2 = event.y + 30

    canvas1.create_oval((x1, y1, x2, y2), fill = 'black')

    global image_draw
    image_draw.ellipse((x1, y1, x2, y2), fill = 'black')

def save():
    #canvas1.create_rectangle((20, 20, 100, 100), fill = 'black')
    #canvas1.create_rectangle((20, 20, 100, 100), outline = 'red', width = 5)
    #canvas1.create_oval((20, 20, 100, 150), outline = 'red', width = 3)

    global image, image_array
    image_array = np.array(image)
    image_array = cv2. resize(image_array, (8, 8))
    cv2.imwrite('digits.jpg', image_array)
    plt.imshow(image_array, cmap = 'binary')
    plt.title('Digit')
    plt.savefig('3.0 Digit.png')
    plt.show()

def predict():
    global image_array
    image_array = np.array(image)
    image_array = cv2.cvtColor(image_array, cv2.COLOR_BGR2GRAY)
    image_array = cv2.resize(image_array, (8, 8))
    image_array_flat = image_array.ravel() #converting 2D array into 1D array
    image_array_flat = 15 - ((image_array_flat / 255.0) * 15.0)

    result = classifier.predict([image_array_flat])
    label_predict.config(text = 'PREDICTED DIGIT: '+str(result[0]))

def clear():
    canvas1.delete('all')

    global image, image_draw
    image = Image.new('RGB', (width, height), (255, 255, 255))
    image_draw = ImageDraw.Draw(image)

canvas1 = tk.Canvas(window, width = width, height = height, bg = 'white')
canvas1.grid(row = 0, column = 0, padx = 2, pady = 4, columnspan = 4) #columnspan = 3 -> creates 3 columns in the below row

label_predict = tk.Label(window, text = 'PREDICTED DIGIT: NONE', bg = 'gray80', font = font)
label_predict.grid(row = 1, column = 0, pady = 4, columnspan = 4)

button_clear = tk.Button(window, text = 'Clear', bg = 'black', fg = 'white', font = font, command = clear)
button_clear.grid(row = 2, column = 0, pady = 6, padx = 5)

button_save = tk.Button(window, text = 'Save', bg = 'green', fg = 'white', font = font, command = save)
button_save.grid(row = 2, column = 1, pady = 6, padx = 5)

button_predict = tk.Button(window, text = 'Predict', bg = 'blue', fg = 'white', font = font, command = predict)
button_predict.grid(row = 2, column = 2, pady = 6, padx = 5)

button_exit = tk.Button(window, text = 'Exit', bg = 'red', fg = 'white', font = font, command = window.destroy)
button_exit.grid(row = 2, column = 3, pady = 6, padx = 5)

##widgetName.bind('event', function)
#canvas1.bind('<Button-1>', event_function)
#label_predict.bind('<Button-1>', event_function)
#button_predict.bind('<Button-1>', event_function)
#canvas1.bind('<Enter>', event_function)
#canvas1.bind('<Leave>', event_function)
#canvas1.bind('<Double-Button-1>', event_function) #left mouse button
#canvas1.bind('<Double-Button-2>', event_function) #scroll button
#canvas1.bind('<Double-Button-3>', event_function) #right mouse button
#window.bind('<Key>', event_function)

canvas1.bind('<B1-Motion>', event_function)

image = Image.new('RGB', (width, height), (255, 255, 255))
image_draw = ImageDraw.Draw(image)

3.0 GUI for Detecting Hand Written Digits.py


import pandas as pd
import numpy as np

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn import metrics

from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RANSACRegressor
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import SGDRegressor
from sklearn.svm import SVR

import warnings
warnings.filterwarnings("ignore")

# Подготовка данных

data = pd.read_csv('data/Housing_Prices.csv')

X = data[['Avg. Area Income', 'Avg. Area House Age', 'Avg. Area Number of Rooms',
          'Avg. Area Number of Bedrooms', 'Area Population']]
y = data['Price']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

pl = Pipeline([('std_scalar', StandardScaler())])

X_train = pl.fit_transform(X_train)
X_test = pl.transform(X_test)

def add_metrics_to_dataframe(true_value, predicted_value):
    mae = metrics.mean_absolute_error(true_value, predicted_value)
    mse = metrics.mean_squared_error(true_value, predicted_value)
    rmse = np.sqrt(metrics.mean_squared_error(true_value, predicted_value))
    # msle = metrics.mean_squared_log_error(true_value, predicted_value)
    r2 = metrics.r2_score(true_value, predicted_value)

    return mae, mse, rmse, r2

# Множественная регрессия

linear_regression = LinearRegression(normalize=True)
linear_regression.fit(X_train, y_train)

test_pred_linear_regression = linear_regression.predict(X_test)

# Робастная регрессия

ransac_regression = RANSACRegressor(base_estimator=LinearRegression(), max_trials=100)
ransac_regression.fit(X_train, y_train)

test_pred_ransac_regression = ransac_regression.predict(X_test)

# Регрессия гребня

ridge_regression = Ridge(alpha=5, solver='cholesky', tol=0.001, random_state=42)
ridge_regression.fit(X_train, y_train)

test_pred_ridge_regression = ridge_regression.predict(X_test)

# Регрессия LASSO

LASSO_regression = Lasso(alpha=0.1, precompute=True, positive=True, selection='random', random_state=42)
LASSO_regression.fit(X_train, y_train)

test_pred_LASSO_regression = ridge_regression.predict(X_test)

# Полиномиальная регрессия

polynomial_regression = PolynomialFeatures(degree=2)

X_train_2_d = polynomial_regression.fit_transform(X_train)
X_test_2_d = polynomial_regression.transform(X_test)

linear_regression_for_polynomial = LinearRegression(normalize=True)
linear_regression_for_polynomial.fit(X_train_2_d, y_train)

test_pred_polynomial_regression = linear_regression_for_polynomial.predict(X_test_2_d)

# Стохастический Градиентный спуск

sgd_regression = SGDRegressor(n_iter_no_change=250, penalty=None, eta0=0.0001, max_iter=100000)
sgd_regression.fit(X_train, y_train)

test_pred_sgd_regression = sgd_regression.predict(X_test)

# Метод опорных векторов

svm_regression = SVR(kernel='rbf', C=1000000, epsilon=0.001)
svm_regression.fit(X_train, y_train)

test_pred_svm_regression = svm_regression.predict(X_test)

# Формирование сводной таблицы с результатами

results_of_models = pd.DataFrame(data=[["Множественная регрессия",
                                        *add_metrics_to_dataframe(y_test, test_pred_linear_regression)],
                                       ["Робастная регрессия",
                                        *add_metrics_to_dataframe(y_test, test_pred_ransac_regression)],
                                       ["Гребневая регрессия",
                                        *add_metrics_to_dataframe(y_test, test_pred_ridge_regression)],
                                       ["Регрессия LASSO",
                                        *add_metrics_to_dataframe(y_test, test_pred_LASSO_regression)],
                                       ["Полиномиальная регрессия",
                                        *add_metrics_to_dataframe(y_test, test_pred_polynomial_regression)],
                                       ["Стохастический градиентный спуск",
                                        *add_metrics_to_dataframe(y_test, test_pred_sgd_regression)],
                                       ["Метод опорных векторов",
                                        *add_metrics_to_dataframe(y_test, test_pred_svm_regression)],
                                       ],
                                 columns=['Алгоритм', 'MAE', 'MSE', 'RMSE', 'R2 Square'])

results_of_models.to_csv('The_results_of_the_algorithms.csv', index=False)


from itertools import permutations

def solution(k, dungeons):
    answer = 0
    lst = list(permutations(dungeons))

    for i in lst:
        cnt = 0
        energy = k
        for j in range(len(i)):
            if i[j][0] <= energy:
                energy -= i[j][1]
                cnt += 1
        if cnt > answer:
            answer = cnt
        if answer == len(dungeons):
            break

    return answer


import argparse
import json

import torch
import os
from dataset.dataset import make_data_loader
from trainer.trainer import Trainer
from utils.utils import seed_everything, Mode
os.environ["CUDA_VISIBLE_DEVICES"] = "1"

def parse_args() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="PyTorch version of Ref-NeRF.")
    parser.add_argument("--test", action="store_true", help="Test mode to evaluate the network capabilities.")
    parser.add_argument("--seed", type=int, default=19260817, help="The seed for all random number generators.")
    parser.add_argument("--config", type=str, default="./config/lego.json", help="The path to the dataset.")
    return parser.parse_args()

def main():
    args = parse_args()
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    seed_everything(args.seed)

    # General + dataset configuration file.
    with open(args.config) as f:
        config = json.load(f)
    # print("[LOG] config loaded")

    trainer = Trainer(device, config)
    print("[LOG] trainer init")

    if not args.test:
        train_loader = make_data_loader(Mode.TRAIN, device, config)
        # val_loader = make_data_loader(Mode.VAL, device, config)
        # print("[LOG] loading data")
        # trainer.train(train_loader, val_loader)
        # print("[LOG] trainging finish")
        del train_loader
        # del val_loader

    # Always test the model.
    # test_loader = make_data_loader(Mode.TEST, device, config)
    # trainer.test(test_loader)

if __name__ == "__main__":
    main()


import tkinter as tk
from tkinter import ttk, filedialog
from tkinter import *
import sys
import multiprocessing as mp

sys.path.append('..')

from scripts import batch_process_to_auto_annotation

import warnings

# TODO: Make this tkinter gui OOP. It works without it, its just ugly :(

# function that will grab all user input and pass it to function

global import_path
global export_path
global exe_path
global filter_filepath

def main():

    warnings.filterwarnings('ignore')

    # create main application window
    app_window = tk.Tk()
    # create title for main window
    app_window.title('Bennotator')
    # make application resizable
    app_window.resizable(width=True, height=True)

    # define style
    style = ttk.Style()
    style.theme_use('alt')

    # define tabs
    tab_control = ttk.Notebook(app_window)
    settings_tab = ttk.Frame(tab_control)
    advanced_settings_tab = ttk.Frame(tab_control)
    filter_settings_tab = ttk.Frame(tab_control)

    # add labels to tabs
    tab_control.add(settings_tab, text='Settings')
    tab_control.add(advanced_settings_tab, text='Advanced')
    tab_control.add(filter_settings_tab, text='Filter Settings')
    tab_control.pack(expand=1, fill='both')

    # create buttons and labels in settings tab

    # functions to browse for files
    def browse_import_button():
        folder_name = filedialog.askdirectory()
        import_path.set(folder_name)

    def browse_export_button():
        folder_name = filedialog.askdirectory()
        export_path.set(folder_name)

    def browse_filter_button():
        file_name = filedialog.askopenfilename()
        filter_filepath.set(file_name)

    ## Settings Tab
    # create import path label and entry field
    lbl_import_path = ttk.Label(settings_tab, text='Import Directory').grid(column=0, row=0)
    import_path = tk.StringVar()
    btn_import_folder_path = ttk.Button(settings_tab, text='Browse', command=browse_import_button).grid(column=1, row=0, sticky='w')
    ent_import_path = ttk.Entry(settings_tab, textvariable=import_path, width=50).grid(column=2, row=0, sticky='w')

    # create export path label and entry field
    lbl_export_path = ttk.Label(settings_tab, text='Export Directory').grid(column=0, row=1)
    export_path = tk.StringVar()
    btn_export_folder_path = ttk.Button(settings_tab, text='Browse', command=browse_export_button).grid(column=1, row=1, sticky='w')
    ent_export_path = ttk.Entry(settings_tab, textvariable=export_path, width=50).grid(column=2, row=1, sticky='w')

    # create label and checkbox for using multithreading
    lbl_multiprocessing = ttk.Label(settings_tab, text='Enable Multiprocessing').grid(column=0, row=3)
    multiprocessing = BooleanVar(value=True)
    ent_multiprocessing = ttk.Checkbutton(settings_tab, variable=multiprocessing).grid(column=1, row=3, sticky='w')

    # create label and checkbox for generating triplets and statics
    lbl_generate_triplets_and_statics = ttk.Label(settings_tab, text='Generate Triplets and Statics').grid(column=0, row=4)
    generate_triplets_and_statics = BooleanVar(value=True)
    ent_generate_triplets_and_statics = ttk.Checkbutton(settings_tab, variable=generate_triplets_and_statics).grid(column=1, row=4, sticky='w')

    # create label and checkbox for generating annotations
    lbl_generate_annotations = ttk.Label(settings_tab, text='Generate Annotations').grid(column=2, row=3)
    generate_annotations = BooleanVar(value=False)
    ent_generate_annotations = ttk.Checkbutton(settings_tab, variable=generate_annotations).grid(column=3, row=3, sticky='w')

    # create label and checkbox for deleting triplets and spectral triplets after generating statics
    lbl_delete_triplets = ttk.Label(settings_tab, text='Keep Triplet and Spectrogram Files').grid(column=2, row=4)
    keep_triplets = BooleanVar(value=False)
    ent_delete_triplets = ttk.Checkbutton(settings_tab, variable=keep_triplets).grid(column=3, row=4, sticky='w')

    ## Advanced Settings Tab
    # create label and entry field for Double Trigger Threshold
    lbl_double_trigger_threshold = ttk.Label(advanced_settings_tab, text='Double Trigger Threshold').grid(column=0, row=0)
    double_trigger_threshold = tk.StringVar()
    double_trigger_threshold.set('.9')
    ent_double_trigger_threshold = ttk.Entry(advanced_settings_tab, textvariable=double_trigger_threshold).grid(column=1, row=0, sticky='w')
    lbl_double_trigger_threshold_info = ttk.Label(advanced_settings_tab, text='[0-1]').grid(column=2, row=0, sticky='w')

    # create label and entry field for Auto Trigger Threshold
    lbl_auto_trigger_threshold = ttk.Label(advanced_settings_tab, text='Auto Trigger Threshold').grid(column=0, row=1)
    auto_trigger_threshold = tk.StringVar()
    auto_trigger_threshold.set('.9')
    ent_auto_trigger_threshold = ttk.Entry(advanced_settings_tab, textvariable=auto_trigger_threshold).grid(column=1, row=1, sticky='w')
    lbl_auto_trigger_threshold_info = ttk.Label(advanced_settings_tab, text='[0-1]').grid(column=2, row=1, sticky='w')

    # create label and entry field for Delayed Termination Threshold
    lbl_delayed_termination_threshold = ttk.Label(advanced_settings_tab, text='Delayed Termination Threshold').grid(column=0, row=2)
    delayed_termination_threshold = tk.StringVar()
    delayed_termination_threshold.set('.9')
    ent_delayed_termination_threshold = ttk.Entry(advanced_settings_tab, textvariable=delayed_termination_threshold).grid(column=1, row=2, sticky='w')
    lbl_delayed_termination_threshold_info = ttk.Label(advanced_settings_tab, text='[0-1]').grid(column=2, row=2, sticky='w')

    # create label and entry field for Flow Undershoot Threshold
    lbl_flow_undershoot_threshold = ttk.Label(advanced_settings_tab, text='Flow Undershoot Threshold').grid(column=0, row=3)
    flow_undershoot_threshold = tk.StringVar()
    flow_undershoot_threshold.set('.9')
    ent_flow_undershoot_threshold = ttk.Entry(advanced_settings_tab, textvariable=flow_undershoot_threshold).grid(column=1, row=3, sticky='w')
    lbl_flow_undershoot_threshold_info = ttk.Label(advanced_settings_tab, text='[0-1]').grid(column=2, row=3, sticky='w')

    # create label and entry field for Premature Termination Threshold
    lbl_premature_termination_threshold = ttk.Label(advanced_settings_tab, text='Premature Termination Threshold').grid(column=0, row=4)
    premature_termination_threshold = tk.StringVar()
    premature_termination_threshold.set('.9')
    ent_premature_termination_threshold = ttk.Entry(advanced_settings_tab, textvariable=premature_termination_threshold).grid(column=1, row=4, sticky='w')
    lbl_premature_termination_threshold_info = ttk.Label(advanced_settings_tab, text='[0-1]').grid(column=2, row=4, sticky='w')

    # create label and entry field for Reverse Trigger Threshold
    lbl_reverse_trigger_threshold = ttk.Label(advanced_settings_tab, text='Reverse Trigger Threshold').grid(column=0, row=5)
    reverse_trigger_threshold = tk.StringVar()
    reverse_trigger_threshold.set('.9')
    ent_reverse_trigger_threshold = ttk.Entry(advanced_settings_tab, textvariable=reverse_trigger_threshold).grid(column=1, row=5, sticky='w')
    lbl_reverse_trigger_threshold_info = ttk.Label(advanced_settings_tab, text='[0-1]').grid(column=2, row=5, sticky='w')

    ## Filter Settings Tab
    # create label and checkbox for generating triplets and statics
    lbl_filter_file = ttk.Label(filter_settings_tab, text='Use Excel File for Filtering').grid(column=0, row=1)
    use_filter_file = BooleanVar(value=False)
    ent_filter_file = ttk.Checkbutton(filter_settings_tab, variable=use_filter_file).grid(column=1, row=1, sticky='w')

    # create browse button to input filtering file
    lbl_filter_browse = ttk.Label(filter_settings_tab, text='Filtering File Path').grid(column=0, row=2)
    filter_filepath = tk.StringVar()
    btn_filter_filepath = ttk.Button(filter_settings_tab, text='Browse', command=browse_filter_button).grid(column=1, row=2, sticky='w')
    ent_filter_path = ttk.Entry(filter_settings_tab, textvariable=filter_filepath, width=50).grid(column=2, row=2, sticky='w')

    def pass_user_input():
        import_path_input = import_path.get()
        export_path_input = export_path.get()
        generate_triplets_and_statics_input = generate_triplets_and_statics.get()
        generate_annotations_input = generate_annotations.get()
        keep_triplets_input = keep_triplets.get()
        multiprocessing_input = multiprocessing.get()

        # get threshold inputs, convert strings to float, set min to 0, set max to 1
        double_trigger_threshold_input = min(max(float(double_trigger_threshold.get()), 0), 1)
        auto_trigger_threshold_input = min(max(float(auto_trigger_threshold.get()), 0), 1)
        delayed_termination_threshold_input = min(max(float(delayed_termination_threshold.get()), 0), 1)
        flow_undershoot_threshold_input = min(max(float(flow_undershoot_threshold.get()), 0), 1)
        premature_termination_threshold_input = min(max(float(premature_termination_threshold.get()), 0), 1)
        reverse_trigger_threshold_input = min(max(float(reverse_trigger_threshold.get()), 0), 1)

        # turn thresholds to dict
        threshold_dict = {}
        threshold_dict['Double Trigger'] = {'Double Trigger': double_trigger_threshold_input}
        threshold_dict['Autotrigger'] = {'Autotrigger': auto_trigger_threshold_input}
        threshold_dict['Delayed Termination'] = {'Delayed Termination': delayed_termination_threshold_input}
        threshold_dict['Flow Undershoot'] = {'Flow Undershoot': flow_undershoot_threshold_input}
        threshold_dict['Premature Termination'] = {'Premature Termination': premature_termination_threshold_input}
        threshold_dict['Reverse Trigger'] = {'Reverse Trigger': reverse_trigger_threshold_input}

        # get filter inputs
        use_filter_input = use_filter_file.get()
        filter_filepath_input = filter_filepath.get()

        # make dict for filter info
        filter_info = {}
        filter_info['use'] = use_filter_input
        filter_info['filepath'] = filter_filepath_input
        # TODO: Figure out how to best have user pass this infomation
        filter_info['exclude_columns_and_values'] = {'Reviewed by:': 'NaN', 'analysis exclusion': 'not NaN'}

        batch_process_to_auto_annotation.main(
            import_path_input,
            export_directory=export_path_input,
            generate_triplets_and_statics=generate_triplets_and_statics_input,
            generate_annotations=generate_annotations_input,
            thresholds_dict=threshold_dict,
            filter_file_info=filter_info,
            keep_triplets_and_spectral_triplets=keep_triplets_input,
            multiprocessing=multiprocessing_input
        )

    # create button that will use arguments from entries and run function
    button1 = tk.Button(text='Click me to Run', command=pass_user_input).pack()

    app_window.mainloop()

# if running this file directly, only do do triplet generation
if __name__ == "__main__":

    # call this to prevent multi guis from spawning in .exe
    mp.freeze_support()
    # run main function
    main()


#Local Variables
print("---------------Local Vars-----------------")
name = "Sadegh"
print(name)
def setName():
    name = "Narges"
    print(name)
print(name)
setName()

print("--------------------------------")

def setName1():
    name = "Narges"

def getName1():
    name = "Puya"
    setName()
    return name

print(getName1())

print("---------------Global Vars-----------------")
#Global
def setScope():
    scope = "local"
    print(scope)
scope = "global"
setScope()
print(scope)

print("--------------------------------")

def setScope1():
    global scope1
    scope1 = "local"  # This is a global variable.
scope1 = "global"
setScope1()
print(scope1)

print("--------------------------------")

def setGlobalScope():
    global scope
    scope = "global" # this is the global

def setScope():
    scope = "local" # this is the local

def printScope():
    print(scope) # this is the global

scope = None # this is the global
setGlobalScope()
setScope()
printScope()


"""
Write a Python program to print the numbers of a specified list after removing even numbers from it.
"""

lst = list(map(int, input("Enter List: ").split()))
for a in lst:
    if a % 2 == 0:
        lst = list(filter(a.__ne__, lst))

print("Even numbers removed:", lst)

"""
OUTPUT
    Enter List: 1 2 3 4 5 6
    Even numbers removed: [1, 3, 5]
"""


# _*_ coding: utf-8 _*_
import torch
import torch.nn as nn
import numpy
from numpy import array
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Normal
from model import BaseModel

class BNN(BaseModel):
    """
    GUR模型，预测发电功率
    """

    def __init__(self, input_size, params={'hidden_units': 32, 'BNN_prior_var': 10}, predict_type="wind",
                 irradiance=None):
        """
        初始化。待完善
        """
        # 初始化父类
        super(BNN, self).__init__(predict_type=predict_type, irradiance=irradiance)

        # 以下为本派生类的属性。若本派生类有自身的个性化属性时，请在下方添加相应的代码
        # 根据属性的访问权限，做相应的访问权限限制（如为本类私有的属性，命名时应以两个下划线(__)开头；
        # 如为本类保护的属性即允许其派生类访问，命名时应以一个下划线(_)开头；
        # 如为公有的属性，命名时应不以下划线(_)开头
        # BNN模型
        hidden_units = params['hidden_units']
        BNN_prior_var = params['BNN_prior_var']
        # initialize the network like you would with a standard multilayer perceptron,
        # but using the BNN layer像使用标准多层感知器一样初始化网络，但使用BNN层
        self.__model_bnn = MLP_BNN(input_size=input_size, hidden_units=hidden_units, prior_var=BNN_prior_var)
        # 不带历史功率
        self.__model_bnn_withoutpower = MLP_BNN(input_size=input_size - 1, hidden_units=hidden_units, prior_var=BNN_prior_var)

    def get_model(self):
        return self.__model_bnn

    def fit(self, feature_data, target_data, *args, **kwargs):
        """
        模型训练。当有传特征集、目标集数据进来时，则使用这两个数据对模型进行训练，否则使用类自身的特征集、目标集数据进行训练
        :param feature_data: 特征集（即天气预报数据）
        :param target_data: 目标集（即功率数据）
        :param args: 个数可变的参数集，类型为元组。
                     实现该方法时，若要使用元组中的参数值，可以通过下标（如args[0]）的方式或者遍历元组的方式
                    （for item in args）来使用。建议实现时，先对元组进行判断是否大小为0，非0时才进行相应的操作
        :param kwargs: 个数可变的参数集，类型为字典。
                       实现该方法时，若要使用字典中的参数值，可以通过key的方式直接获取值（如kwargs[ke])，或者遍历字典
                       （for key, value in kwargs.items()）的方式来获取。
                       当厂家不提供辐照度阈值时，若要从天气预报数据中估算该值，则需以irradiance_col=XXX的形式指明
                       辐照度特征在feature中列序号（从0开始计算），否则将取默认值10
                       说明：本模型需要输入predict_term，会调用。
                       当预测周期predict_term为超短期ultra_short时，
                       模型单次预测结果输出长度为predict_step = 16，预测间隔predict_inter = 1；
                       当预测周期predict_term为短期short时，
                       模型单次预测结果输出长度为predict_step = 288，预测间隔predict_inter = 96；
                       当预测周期predict_term为5分钟超短期five_minute_ultra_short时，
                       模型单次预测结果输出长度为predict_step = 48，预测间隔predict_inter = 1；
        :return:
        """
        if "predict_term" in kwargs:
            predict_term = kwargs["predict_term"]
        else:
            predict_term = "ultra_short"

        if predict_term == "ultra_short":
            predict_step = 16
            predict_inter = 1
        elif predict_term == "short":
            predict_step = 288
            predict_inter = 96
        elif predict_term == "five_minute_ultra_short":
            predict_step = 48
            predict_inter = 1
        else:
            # print("预测周期输入错误")
            predict_step = 16
            predict_inter = 1

        # 不带历史功率
        X, y = list(), list()
        in_start = 0
        in_start = in_start + predict_inter
        in_end = in_start + predict_step
        while in_end in range(len(feature_data)):
            Power_the_step = feature_data[in_start:in_end, :]
            X.append(Power_the_step)
            y.append(target_data[in_start:in_end])
            in_start = in_start + predict_inter
            in_end = in_start + predict_step
        X_fit = array(X).reshape(len(X) * predict_step, feature_data.shape[1])
        Y_fit = array(y)
        Y_fitdata = Y_fit.flatten().reshape(len(X) * predict_step, 1)
        aaa = torch.tensor(X_fit)  # 变量名没有物理意义
        bbb = torch.tensor(Y_fitdata)
        # 模型适配
        optimizer = optim.Adam(self.__model_bnn_withoutpower.parameters(), lr=.1)
        epochs = 2000
        self.__model_bnn_withoutpower.double()
        for epoch in range(epochs):  # loop over the dataset multiple times
            optimizer.zero_grad()
            loss = self.__model_bnn_withoutpower.sample_elbo(aaa, bbb, 1)
            loss.backward()
            optimizer.step()

        # 带历史功率
        X, y = list(), list()
        in_start = 0
        in_start = in_start + predict_inter
        in_end = in_start + predict_step
        while in_end in range(len(feature_data)):
            Power_the_step = numpy.c_[
                feature_data[in_start:in_end, :],
                target_data[in_start-1]*numpy.ones(predict_step)
            ]
            X.append(Power_the_step)
            y.append(target_data[in_start:in_end])
            in_start = in_start + predict_inter
            in_end = in_start + predict_step
        X_fit = array(X).reshape(len(X)*predict_step, feature_data.shape[1]+1)
        Y_fit = array(y)
        Y_fitdata = Y_fit.flatten().reshape(len(X)*predict_step, 1)
        aaa = torch.tensor(X_fit)  # 变量名没有物理意义
        bbb = torch.tensor(Y_fitdata)
        # 模型适配
        optimizer = optim.Adam(self.__model_bnn.parameters(), lr=.1)
        epochs = 2000
        self.__model_bnn.double()
        for epoch in range(epochs):  # loop over the dataset multiple times
            optimizer.zero_grad()
            loss = self.__model_bnn.sample_elbo(aaa, bbb, 1)
            loss.backward()
            optimizer.step()

        # 对于光伏发电，若厂家没有提供光伏电场不发电时的辐照度阈值，需要自行计算
        if self._predict_type == "solar" and self._irradiance is None:
            if "irradiance_col" in kwargs:
                # 有提供辐照度特征在天气预报数据（特征集）中所在列的序号（序号从0开始算），按照一定算法计算辐照度阈值
                self._irradiance = self.compute_irradiance_gate(feature_data, target_data, kwargs["irradiance_col"])
            else:
                # 没有提供辐照度特征在天气预报数据（特征集）中所在列的序号，则按照经验给一个参考值（或做其他处理）
                self._irradiance = 10

    def predict_without_history_power(self, feature, *args, **kwargs):
        """
        不使用历史功率数据的功率预测。
        1、特征集（feature，即天气预报数据），不区分时段（白天黑夜）。光伏发电在处理时可能需要在方法实现的时候，注意将晚上的发电功率置为0。
        2、对于光伏发电，建议选取若干天气特征作为标准，当实际的天气特征低于标准时，则在预测的时候将相应的预测结果置0。
        3、此处不区分短期/超短期功率预测。派生类在实现时，若有需要，可通过len(feature) == 288、len(feature) == 16来
          区分短期/超短期预测
        4、此处不区分风电/光伏功率预测。若有需要，可在派生类实现。
        :param feature: （预测）特征集
        :param args: 个数可变的参数集，类型为元组。
                     实现该方法时，若要使用元组中的参数值，可以通过下标（如args[0]）的方式或者遍历元组的方式
                     （for item in args）来使用。建议实现时，先对元组进行判断是否大小为0，非0时才进行相应的操作
        :param kwargs: 个数可变的参数集，类型为字典。
                       实现该方法时，若要使用字典中的参数值，可以通过key的方式直接获取值（如kwargs[ke])，或者遍历字典
                       （for key, value in kwargs.items()）的方式来获取。
                       当预测光伏发电功率时，需要以irradiance_col=XXX的形式指明辐照度特征在feature中列序号（从0开始计算）
        :return:
        """
        input_x = torch.tensor(feature.reshape(len(feature), 1, feature.shape[1]))
        result = (self.__model_bnn_withoutpower(input_x).detach().numpy()).flatten()

        # 光伏发电时，需要对光照较弱的情况（比如夜晚）进行特殊处理（发电功率置零）
        if self._predict_type == "solar" and "irradiance_col" in kwargs:
            for index in range(len(feature)):
                if feature[index][kwargs["irradiance_col"]] <= self._irradiance:
                    result[index] = 0

        return result

    def predict_with_history_power(self, feature, history_power, *args, **kwargs):
        """
        使用历史功率数据的（单次）功率预测。本模型没有使用历史功率的功率预测实现方法，返回None。
        1、特征集（feature，即天气预报数据），不区分时段（白天黑夜）。光伏发电在处理时可能需要在方法实现的时候，注意将晚上的发电功率置为0。
        2、对于光伏发电，建议选取若干天气特征作为标准，当实际的天气特征低于标准时，则在预测的时候将相应的预测结果置0。
        3、此处不区分短期/超短期功率预测。派生类在实现时，若有需要，可通过len(feature) == 288、len(feature) == 16来
          区分短期/超短期预测
        4、此处不区分风电/光伏功率预测。若有需要，可在派生类实现。
        :param feature: （预测）特征集
        :param history_power: 上一时刻历史功率数据
        :param args: 个数可变的参数集，类型为元组。
                     实现该方法时，若要使用元组中的参数值，可以通过下标（如args[0]）的方式或者遍历元组的方式
                     （for item in args）来使用。建议实现时，先对元组进行判断是否大小为0，非0时才进行相应的操作
        :param kwargs: 个数可变的参数集，类型为字典。
                       实现该方法时，若要使用字典中的参数值，可以通过key的方式直接获取值（如kwargs[ke])，或者遍历字典
                       （for key, value in kwargs.items()）的方式来获取。
        :return:
        """
        input_x = (numpy.c_[feature, history_power*numpy.ones(len(feature))]).reshape(len(feature), 1, feature.shape[1]+1)
        input_x = torch.tensor(input_x)
        result = (self.__model_bnn(input_x).detach().numpy()).flatten()
        return result

    def predict_mix_history_power(self, feature, history_power, num_with_history_power=7, *args, **kwargs):
        """
        融合不使用与使用历史功率数据的功率预测。一般不建议派生类重新实现该方法。
        取不使用历史功率数据时的预测数据的前N个数据，以及使用历史功率数据时的预测数据排除了前N个数据的数据，组成最终结果数据并返回。
        1、特征集（feature，即天气预报数据），不区分时段（白天黑夜）。光伏发电在处理时可能需要在方法实现的时候，注意将晚上的发电功率置为0。
        2、对于光伏发电，建议选取若干天气特征作为标准，当实际的天气特征低于标准时，则在预测的时候将相应的预测结果置0。
        3、此处不区分短期/超短期功率预测。派生类在实现时，若有需要，可通过len(feature) == 288、len(feature) == 16来
          区分短期/超短期预测
        4、此处不区分风电/光伏功率预测。若有需要，可在派生类实现。
        :param feature: （预测）特征集
        :param history_power: 上一时刻历史功率数据
        :param num_with_history_power: 融合不使用历史功率的预测结果和使用历史功率的预测结果时，后者数据长度所占最终结果数据长度的比例
        :param args: 个数可变的参数集，类型为元组。
                     实现该方法时，若要使用元组中的参数值，可以通过下标（如args[0]）的方式或者遍历元组的方式
                     （for item in args）来使用。建议实现时，先对元组进行判断是否大小为0，非0时才进行相应的操作
        :param kwargs: 个数可变的参数集，类型为字典。
                       实现该方法时，若要使用字典中的参数值，可以通过key的方式直接获取值（如kwargs[ke])，或者遍历字典
                       （for key, value in kwargs.items()）的方式来获取。
        :return:
        """
        without_history_result = self.predict_without_history_power(feature)
        if num_with_history_power <= 0:
            return without_history_result

        with_history_result = self.predict_with_history_power(feature, history_power)
        if with_history_result is None:
            return without_history_result

        return numpy.hstack((with_history_result[:num_with_history_power],
                             without_history_result[num_with_history_power:]))

class Linear_BBB(nn.Module):
    """
        Layer of our BNN.
    """

    def __init__(self, input_features, output_features, prior_var=1.):
        """
            Initialization of our layer : our prior is a normal distribution
            centered in 0 and of variance 20.
        """
        # initialize layers
        super().__init__()
        # set input and output dimensions
        self.input_features = input_features
        self.output_features = output_features

        # initialize mu and rho parameters for the weights of the layer
        self.w_mu = nn.Parameter(torch.zeros(output_features, input_features))
        self.w_rho = nn.Parameter(torch.zeros(output_features, input_features))

        # initialize mu and rho parameters for the layer's bias
        self.b_mu = nn.Parameter(torch.zeros(output_features))
        self.b_rho = nn.Parameter(torch.zeros(output_features))

        # initialize weight samples (these will be calculated whenever the layer makes a prediction)
        self.w = None
        self.b = None

        # initialize prior distribution for all of the weights and biases
        self.prior = torch.distributions.Normal(0, prior_var)

    def forward(self, input):
        """
          Optimization process
        """
        # sample weights
        w_epsilon = Normal(0, 1).sample(self.w_mu.shape)
        self.w = self.w_mu + torch.log(1 + torch.exp(self.w_rho)) * w_epsilon

        # sample bias
        b_epsilon = Normal(0, 1).sample(self.b_mu.shape)
        self.b = self.b_mu + torch.log(1 + torch.exp(self.b_rho)) * b_epsilon

        # record log prior by evaluating log pdf of prior at sampled weight and bias
        w_log_prior = self.prior.log_prob(self.w)
        b_log_prior = self.prior.log_prob(self.b)
        self.log_prior = torch.sum(w_log_prior) + torch.sum(b_log_prior)

        # record log variational posterior by evaluating log pdf of normal distribution defined by parameters with respect at the sampled values
        self.w_post = Normal(self.w_mu.data, torch.log(1 + torch.exp(self.w_rho)))
        self.b_post = Normal(self.b_mu.data, torch.log(1 + torch.exp(self.b_rho)))
        self.log_post = self.w_post.log_prob(self.w).sum() + self.b_post.log_prob(self.b).sum()

        return F.linear(input, self.w, self.b)

class MLP_BNN(nn.Module):
    def __init__(self, input_size, hidden_units=50, noise_tol=.1, prior_var=1.):
        # initialize the network like you would with a standard multilayer perceptron, but using the BBB layer
        super().__init__()
        self.hidden = Linear_BBB(input_size, hidden_units, prior_var=prior_var)
        self.out = Linear_BBB(hidden_units, 1, prior_var=prior_var)
        self.noise_tol = noise_tol  # we will use the noise tolerance to calculate our likelihood

    def forward(self, x):
        # again, this is equivalent to a standard multilayer perceptron
        x = torch.sigmoid(self.hidden(x))
        x = self.out(x)
        return x

    def log_prior(self):
        # calculate the log prior over all the layers
        return self.hidden.log_prior + self.out.log_prior

    def log_post(self):
        # calculate the log posterior over all the layers
        return self.hidden.log_post + self.out.log_post

    def sample_elbo(self, input, target, samples):
        # we calculate the negative elbo, which will be our loss function
        # initialize tensors
        outputs = torch.zeros(samples, target.shape[0])
        log_priors = torch.zeros(samples)
        log_posts = torch.zeros(samples)
        log_likes = torch.zeros(samples)
        # make predictions and calculate prior, posterior, and likelihood for a given number of samples
        for i in range(samples):
            outputs[i] = self(input).reshape(-1)  # make predictions
            log_priors[i] = self.log_prior()  # get log prior
            log_posts[i] = self.log_post()  # get log variational posterior
            log_likes[i] = Normal(outputs[i], self.noise_tol).log_prob(
                target.reshape(-1)).sum()  # calculate the log likelihood
        # calculate monte carlo estimate of prior posterior and likelihood
        log_prior = log_priors.mean()
        log_post = log_posts.mean()
        log_like = log_likes.mean()
        # calculate the negative elbo (which is our loss function)
        loss = log_post - log_prior - log_like
        return loss


import requests, shutil, os
from PIL import Image

bookcode=input("Enter book code: ")
pdfname=input("What should the PDF be named? ") + ".pdf"
starting_page=1

while True:
    url="https://assets-runtime-production-oxed-oup.avallain.net/ebooks/" + bookcode + "/images/" + str(starting_page) + ".jpg"
    jpg=str(starting_page) + ".jpg"
    starting_page=starting_page + 1
    request=requests.get(url, stream=True)

    if request.status_code<=226:
        request.raw.decode_content=True
        with open(jpg,'wb') as f:
            shutil.copyfileobj(request.raw, f)
        print(jpg + " has been downloaded")
    else:
        image_list=[]
        for i in range(1, starting_page-1):
            jpg=str(i) + ".jpg"
            jpg=Image.open(jpg).convert("RGB")
            image_list.append(jpg)

        print("Saving as PDF...")
        image_list[0].save(pdfname, quality=100, save_all=True, append_images=image_list[1:])

        print("Removing leftover JPEGs...")
        for img in range(1, starting_page-1):
            os.remove(str(img) + ".jpg")
        print("All done!")


import functools

def main():

    def decor(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            do = func(*args, **kwargs)
            print('Ваша последовательность готова:')
            return do
        return wrapper

    @decor
    def func_gener(a, b, c=0):
        '''Функция генерирует последовательность от "а" до "b" включительно
        с шагом "с".'''
        if a > b:
            a, b = b, a
        try:
            for num in range(a, b+1, c):
                yield num
        except ValueError:
            print('Третье значение должно быть больше "0"')

    while True:
        try:
            x, y, z = (int(i) for i in input('Введите данные через пробел:\n').split())
            if z == 0:
                print('Третье значение должно быть больше "0"')
                continue
            my_gener = func_gener(x, y, z)
            for i in my_gener:
                print(i, end=' ')
            break
        except ValueError:
            print('Вы ввели не число либо дробное число. Введите 3 целых числа\n')

if __name__ == '__main__':
    main()


###
# Michael Buffone
# February 2nd, 2021
# COSC4106 Assignment 1 : Question 1
#
# Given a string of characters, count the number of substrings that start with an A and end with a B.
# For example, there are four such substrings in CABAAXBYA, i.e. AB, ABAAXB, AAXB, AXB.
# Write a program that uses the brute-force approach to count the number of such substrings in a
# given string.
###

# Start of countAB function #
def countAB(userString):

    count = 0

    # Let i be the A we are looking for
    # Let j be the B we are looking for
    for i in range(0, len(userString)):
        if userString[i] == "A":
            for j in range(i, len(userString)):
                if userString[j] == "B":
                    print("Substring found:", userString[i:j+1])
                    count += 1
    return count
# End countAB #

def main():
    print("-----")
    userString = input("Please enter a string: ")
    print("The number of substrings that start with an A and end with a B is", countAB(userString))
    print("-----")

if __name__ == "__main__":
    main()


import cv2

face_cascade = cv2.CascadeClassifier("face_detection/haarcascade_frontalface_default.xml")
img = cv2.imread("face_detection/sagar3.jpg")
shape = img.shape

# cv2.imshow("image", img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

face = face_cascade.detectMultiScale(img,
scaleFactor = 1.005,
minNeighbors = 5
)
for x, y, w, h in face:
    img = cv2.rectangle(img, (x, y), (x+w, y+h), (0,255,0), 4)
print(face)

resized_image = cv2.resize(img, (int(shape[1]/3), int(shape[0]/3)))

cv2.imshow("image", resized_image)
# cv2.imshow("image", img)

cv2.waitKey(0)
cv2.destroyAllWindows()


from flask import Flask, request, jsonify
import mysql.connector

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "
Hello, World!
"

# MySQL connection configuration
mysql_config = {
    'host': '<endpoint>',
    'user': 'admin',
    'password': '<password>',
    'database': 'sample',
}

# Function to create a MySQL connection
def create_connection():
    return mysql.connector.connect(**mysql_config)

# Read endpoint to get all employees
@app.route('/employees', methods=['GET'])
def get_employees():
    try:
        connection = create_connection()
        cursor = connection.cursor(dictionary=True)

        cursor.execute('SELECT * FROM EMPLOYEES')
        employees = cursor.fetchall()

        return jsonify(employees)
    except Exception as e:
        return jsonify({'error': str(e)})
    finally:
        cursor.close()
        connection.close()

# Write endpoint to add a new employee
@app.route('/employees', methods=['POST'])
def add_employee():
    try:
        connection = create_connection()
        cursor = connection.cursor()

        data = request.get_json()
        name = data['name']
        address = data['address']

        cursor.execute('INSERT INTO EMPLOYEES (NAME, ADDRESS) VALUES (%s, %s)', (name, address))
        connection.commit()

        return jsonify({'message': 'Employee added successfully'})
    except Exception as e:
        return jsonify({'error': str(e)})
    finally:
        cursor.close()
        connection.close()

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


#!/usr/bin/env python
# -*- coding: 'UTF-8' -*-

import logging
import sys

def beleženje(dnevnik: str,
              nivo_beleženja: int = 4,
              ):
    nivoji = {
        5: logging.CRITICAL,
        4: logging.ERROR,
        3: logging.WARNING,
        2: logging.INFO,
        1: logging.DEBUG
    }

    if dnevnik:
        logging.basicConfig(format="%(asctime)s %(levelname)s: %(name)s, %(funcName)s: %(message)s",
                            filename=dnevnik,
                            # encoding="utf-8",  # python >= 3.9
                            level=nivoji[nivo_beleženja])
    else:
        logging.basicConfig(format="%(asctime)s %(levelname)s: %(name)s, %(funcName)s: %(message)s",
                            stream=sys.stdout,
                            level=nivoji[nivo_beleženja])

    return logging.getLogger(__name__)


from collections import namedtuple
import os
import shlex
import subprocess
import tempfile
import time

ConfigDmgtools = namedtuple('Config', 'dmg hfsplus newfs_hfs verbose')
ConfigHdiutil = namedtuple('Config', 'hdiutil verbose')

def chunks(l, n):
	"""
	Yield successive n-sized chunks from l.

	From https://stackoverflow.com/a/312464.
	"""
	for i in range(0, len(l), n):
		yield l[i:i + n]

class Dmg:
	def __init__(self, config):
		self.config = config

	def _check_call(self, process_args, *args, **kwargs):
		if self.config.verbose >= 1:
			print("EXECUTING {}".format(" ".join(shlex.quote(x) for x in process_args)))
		if not (self.config.verbose >= 2 and "stdout" not in kwargs):
			kwargs["stdout"] = open(os.devnull, 'wb')
		subprocess.check_call(process_args, *args, **kwargs)

class Dmgtools(Dmg):
	def _mkfs_hfs(self, *args):
		self._check_call((self.config.newfs_hfs,) + args)
	def _hfs(self, *args):
		self._check_call((self.config.hfsplus,) + args)
	def _dmg(self, *args):
		self._check_call((self.config.dmg,) + args)

	def _create_hfs(self, hfs, volume_name, size):
		if self.config.verbose >= 1:
			print("TRUNCATING {} to {} bytes".format(hfs, size))
		with open(hfs, 'wb') as f:
			f.truncate(size)
		self._mkfs_hfs('-v', volume_name, hfs)

	def _symlink(self, hfs, target, link_name):
		self._hfs(hfs, 'symlink', link_name, target)

	def _add(self, hfs, directory):
		self._hfs(hfs, 'addall', directory)

	def _finish(self, hfs, dmg):
		self._dmg('build', hfs, dmg)

	def create(self, dmg, volume_name, directory, symlinks):
		input_size = sum(os.stat(os.path.join(path, f)).st_size for path, dirs, files in os.walk(directory) for f in files)
		output_size = max(input_size * 2, 1024**2)
		hfs = tempfile.mktemp(prefix=dmg + '.', suffix='.hfs')
		self._create_hfs(hfs, volume_name, output_size)
		self._add(hfs, directory)
		for target, link_name in symlinks:
			self._symlink(hfs, target, link_name)
		self._finish(hfs, dmg)
		if self.config.verbose >= 1:
			print("REMOVING {}".format(hfs))
		os.remove(hfs)

class Hdiutil(Dmg):
	def _hdiutil(self, *args):
		self._check_call((self.config.hdiutil,) + args)

	def create(self, dmg, volume_name, directory, symlinks):
		if symlinks:
			raise NotImplementedError("symlinks are not yet implemented")
		for i in range(5):
			if os.path.exists(volume_name + '.dmg'):
				os.remove(volume_name + '.dmg')
			try:
				self._hdiutil('create', '-volname', volume_name, '-srcdir', directory, dmg)
			except subprocess.CalledProcessError as e:
				if i == 4:
					raise e
				print("Retrying hdiutil create")
				time.sleep(5)
			else:
				break

def main():
	import argparse
	p = argparse.ArgumentParser(description="Manipulate dmg archives")

	subcommands = p.add_subparsers(help="Subcommand", dest='command', metavar="COMMAND")
	subcommands.required = True

	create = subcommands.add_parser("create", help="Create a dmg archive from files or directories")
	create.add_argument('-v', '--verbose', action='count', help="Verbose output")
	createx = create.add_mutually_exclusive_group(required=True)
	createx.add_argument('--dmgtools', nargs=3, help="Paths to the dmg and hfsplus executable (https://github.com/mozilla/libdmg-hfsplus) and the newfs_hfs executable (http://pkgs.fedoraproject.org/repo/pkgs/hfsplus-tools/diskdev_cmds-540.1.linux3.tar.gz/0435afc389b919027b69616ad1b05709/diskdev_cmds-540.1.linux3.tar.gz)")
	createx.add_argument('--hdiutil', help="Path to the hdiutil (only exists for macOS at time of writing)")
	create.add_argument('output', metavar="OUTPUT", help="Filename of the output dmg archive")
	create.add_argument('volume_name', metavar="VOLUME_NAME", help="Name of the dmg archive")
	create.add_argument('directory', metavar="DIR", help="Directory to create the archive from")
	create.add_argument('--symlink', metavar="SYMLINK", nargs=2, action="append", help="Symlink the first argument under the second name")
	args = p.parse_args()

	verbose = args.verbose or 0
	symlinks = args.symlink or []
	if args.dmgtools:
		dmg, hfsplus, newfs_hfs = args.dmgtools
		dmg = Dmgtools(ConfigDmgtools(dmg=dmg, hfsplus=hfsplus, newfs_hfs=newfs_hfs, verbose=verbose))
	elif args.hdiutil:
		dmg = Hdiutil(ConfigHdiutil(hdiutil=args.hdiutil, verbose=verbose))
	else:
		raise RuntimeError("unreachable")
	dmg.create(volume_name=args.volume_name, directory=args.directory, dmg=args.output, symlinks=symlinks)

if __name__ == '__main__':
	main()


from gym_novel_gridworlds2.actions import Action, PreconditionNotMetError
from gym_novel_gridworlds2.object import Entity, Object
from gym_novel_gridworlds2.state import State
from gym_novel_gridworlds2.utils import nameConversion
from gym_novel_gridworlds2.contrib.polycraft.objects.polycraft_obj import (
    PolycraftObject,
)
from gym_novel_gridworlds2.contrib.polycraft.objects.door import Door
from gym_novel_gridworlds2.contrib.polycraft.objects.chest import Chest

import numpy as np

from gym_novel_gridworlds2.state.dynamic import Dynamic
from gym_novel_gridworlds2.utils.namelogic import backConversion

class PlaceItem(Action):
    def __init__(self, **kwargs):
        self.cmd_format = r"[^\s]+ (?P<target_type>[^\s]+)"
        super().__init__(**kwargs)

    def check_precondition(
        self,
        agent_entity: Entity,
        target_type: str = None,
        target_object: Object = None,
        **kwargs,
    ):
        if target_type == None or target_type == "iron_pickaxe":
            return False
        # convert the entity facing direction to coords
        direction = (0, 0)
        if agent_entity.facing == "NORTH":
            direction = (-1, 0)
        elif agent_entity.facing == "SOUTH":
            direction = (1, 0)
        elif agent_entity.facing == "EAST":
            direction = (0, 1)
        else:
            direction = (0, -1)

        self.temp_loc = tuple(np.add(agent_entity.loc, direction))
        objs = self.state.get_objects_at(self.temp_loc)
        if len(objs[0]) == 1 or len(objs[1]) == 1:  # contains objs, not clear
            return False
        canPlace = False
        if target_type in self.dynamics.obj_types:
            ObjModule = self.dynamics.obj_types[target_type]["module"]
        elif "default" in self.dynamics.obj_types:
            ObjModule = self.dynamics.obj_types["default"]["module"]
        else:
            ObjModule = PolycraftObject

        if ObjModule.placement_reqs(self.state, self.temp_loc):
            canPlace = True

        return target_type in agent_entity.inventory and \
            agent_entity.inventory[target_type] > 0 and canPlace

    def do_action(
        self,
        agent_entity: Entity,
        target_type: str = None,
        target_object: Object = None,
        **kwargs,
    ):

        if target_type is None:
            target_type = backConversion(agent_entity.selectedItem)
        else:
            target_type = backConversion(target_type)

        if not self.check_precondition(agent_entity, target_type, target_object):
            self.result = "FAILURE"
            self.action_metadata(agent_entity, target_type, target_object)
            raise PreconditionNotMetError(
                f'Agent "{agent_entity.nickname}" cannot place item of type {target_type}.'
            )
        if target_type == "sapling":
            itemToPlace = "oak_log"
        else:
            itemToPlace = target_type

        # place object of type selectedItem on map in the direction the agent is facing
        if target_type in self.dynamics.obj_types:
            obj_info = self.dynamics.obj_types[itemToPlace]
            self.state.place_object(
                itemToPlace,
                obj_info["module"],
                properties={**obj_info["params"], "loc": self.temp_loc},
            )
        elif "default" in self.dynamics.obj_types:
            obj_info = self.dynamics.obj_types["default"]
            self.state.place_object(
                itemToPlace,
                obj_info["module"],
                properties={**obj_info["params"], "loc": self.temp_loc},
            )
        else:
            self.state.place_object(
                itemToPlace, Entity, properties={"loc": self.temp_loc},
            )
        agent_entity.inventory[target_type] -= 1

        self.result = "SUCCESS"
        return {}


import streamlit as st
import numpy as np
import pandas as pd
import plotly.express as px

st.set_page_config(
    page_title="Salesperson Performance Review",
    page_icon="ðŸ’¼",
    layout="wide",
    initial_sidebar_state="expanded",
    menu_items={
        'Get Help': 'https://github.com/mfadlili',
        'Report a bug': "https://github.com/mfadlili",
        'About': "#CAP."
    }
)

@st.cache_data
def load_data1():
    data = pd.read_csv('https://raw.githubusercontent.com/mfadlili/upload_csv/master/cap_data_ingestion_dashboard.csv')
    return data

df1 = load_data1()

st.title('Salesperson Performance Review')
st.title('')
col1, col2, col3 = st.columns(3)

def total_sales():
    total_revenue = "$ " +str(round(df1['sales'].sum()))
    st.metric(label="Total Salesperson Revenue (2011-2014)", value=total_revenue)

def total_salesperson():
    salesperson = df1.fullname.nunique()
    st.metric(label="Total Active Salesperson", value=salesperson)

def total_region():
    ter = df1.name.nunique()
    st.metric(label="Total Teritory", value=ter)

with col1:
    total_sales()

with col2:
    total_salesperson()

with col3:
    total_region()

d1 = df1.groupby(['fullname', 'salespersonid', 'year_order']).sales.sum().reset_index()
d2 = df1.groupby(['year_order', 'territoryid',	'name']).sales.sum().reset_index()

col1,col2 = st.columns([1,1])
col3,col4 = st.columns([1,1])

with col1:
    st.markdown("
Salesperson Revenue
", unsafe_allow_html=True)
    year = [int(i) for i in d1.year_order.unique()]
    year.sort()
    year.append('all')
    option = st.selectbox("Year:", year)
    if option == 'all':
        result = d1.groupby(['fullname']).sales.sum().reset_index().sort_values(by=['sales'], ascending=False)
        fig1 = px.bar(result,y='fullname',x='sales',color='fullname',color_discrete_sequence=px.colors.sequential.Darkmint,height=450,width=650, text_auto='.2s')
        fig1.update_layout(xaxis_title='Revenue Generated ($)',yaxis_title=' ', showlegend = False)
        st.plotly_chart(fig1)
    result = d1[d1.year_order==option].sort_values(by=['sales'], ascending=False)
    fig1 = px.bar(result,y='fullname',x='sales',color='fullname',color_discrete_sequence=px.colors.sequential.Darkmint,height=450,width=650, text_auto='.2s')
    fig1.update_layout(xaxis_title='Revenue Generated ($)',yaxis_title=' ', showlegend = False)
    st.plotly_chart(fig1)

with col2:
    st.markdown("
Revenue Generated per Year
", unsafe_allow_html=True)
    st.markdown("", unsafe_allow_html=True)
    st.title('')
    st.title('')
    result = d1.groupby('year_order').sales.sum().reset_index()
    fig3 = px.bar(result,y='sales',x='year_order',color='sales',color_discrete_sequence=px.colors.sequential.Darkmint,height=450,width=650, text_auto='.2s')
    fig3.update_layout(xaxis_title='Year',yaxis_title='Total Revenue Generated ($)', showlegend = False)
    st.plotly_chart(fig3)

with col3:
    st.markdown("
Revenue by Teritory
", unsafe_allow_html=True)
    year = [int(i) for i in d1.year_order.unique()]
    year.sort()
    year.append('all')
    option = st.selectbox("Year:  ", year)
    if option == 'all':
        result = d2.groupby(['name']).sales.sum().reset_index().sort_values(by=['sales'], ascending=False)
        fig1 = px.bar(result,y='name',x='sales',color='name',color_discrete_sequence=px.colors.sequential.Darkmint,height=450,width=650, text_auto='.2s')
        fig1.update_layout(xaxis_title='Revenue Generated ($)',yaxis_title=' ', showlegend = False)
        st.plotly_chart(fig1)
    result = d2[d2.year_order==option].sort_values(by=['sales'], ascending=False)
    fig1 = px.bar(result,y='name',x='sales',color='name',color_discrete_sequence=px.colors.sequential.Darkmint,height=450,width=650, text_auto='.2s')
    fig1.update_layout(xaxis_title='Revenue Generated ($)',yaxis_title=' ', showlegend = False)
    st.plotly_chart(fig1)


import abc
import json
import threading
import time
from sched import scheduler
from .debug import Debug
from framework.utils.service_logging import logger

class DependencyState(object):
    DEPS_STARTING = 0
    DEPS_FAILED = 2
    DEPS_SUCCESS = 4

class InitState(object):
    INITIALIZING = 0
    INIT_FAILED = 1
    INIT_SUCCESS = 2

class SensorThreadState(object):
    WAITING = 0
    RUNNING = 1
    FAILED = 3

class ModuleThread(metaclass=abc.ABCMeta):
    """Base Class for all Module Threads"""

    @abc.abstractmethod
    def initialize(self):
        """Initialize the module thread"""
        raise NotImplementedError("Subclasses should implement this!")

    @abc.abstractmethod
    def run(self):
        """Periodically run the module thread"""
        raise NotImplementedError("Subclasses should implement this!")

class ScheduledModuleThread(ModuleThread, Debug):
    """A module thread with an internal scheduler"""

    # Module thread states
    ACTIVE = 1
    SUSPENDED = 2
    HALTED = 3

    def __init__(self, module_name, priority):
        super(ScheduledModuleThread, self).__init__()

        self._scheduler   = scheduler(time.time, time.sleep)
        self._module_name = module_name
        self._priority    = priority
        self._running     = False

    def initialize(self, conf_reader):
        """Initialize the monitoring thread"""
        # Set the configuration file reader located in /etc/sspl-ll.conf
        self._conf_reader = conf_reader

        # Set the scheduler to fire the thread right away
        self._scheduler.enter(1, self._priority, self.run, ())

    def start(self):
        """Run the scheduler"""
        self._running = True
        self._scheduler.run()

    def start_thread(self, conf_reader, msgQlist, product):
        self.initialize(conf_reader, msgQlist, product)
        self.start()

    def _cleanup_and_stop(self):
        """Clean out the remainder of events from the scheduler queue."""
        self._log_debug("last module calling _cleanup_and_stop thread scheduler")
        for event in self._scheduler.queue:
            try:
                self._scheduler.cancel(event)
            except ValueError:
                # Being shut down so ignore
                pass
        self._log_debug("Thread scheduler cancelled successfully")

    def shutdown(self):
        """Clean up and shut down this monitor."""
        self._running = False

        # Give the module a few seconds to close down
        self._scheduler.enter(10, self._priority, self._cleanup_and_stop, ())
        self._log_debug("Scheduling shut down")

    def _getConf_reader(self):
        return self._conf_reader

    def is_running(self):
        return self._running

    def suspend(self):
        logger.debug("suspend() of {0} is called".format(self.name()))

    def resume(self):
        """Resumes the module thread. It should be non-blocking"""
        logger.debug("resume() of {0} is called".format(self.name()))

    def get_state(self):
        """Returns the current state of module thread"""
        current_state = None
        if self.is_running() and not self.is_suspended():
            current_state = ScheduledModuleThread.ACTIVE
        elif self.is_running() and self.is_suspended():
            current_state = ScheduledModuleThread.SUSPENDED
        elif not self.is_running():
            current_state = ScheduledModuleThread.HALTED
        return current_state

    def is_suspended(self):
        """Returns True if the module thread is suspended. False otherwise"""
        logger.debug("is_suspended() of {0} is called".format(self.name()))

class SensorThread(ScheduledModuleThread):
    SENSORTHREAD_INIT_WAIT_TIMEOUT = 300
    SENSORTHREAD_INIT_WAIT_INTERVAL = 10

    def __init__(self, module_name, priority):
        super(SensorThread, self).__init__(module_name, priority)

        self.lock = threading.Lock()

        self.remaining_dependees = set()
        self.num_failed_dependees = 0
        self.waiting_dependers = set()
        self.deps_status = DependencyState.DEPS_STARTING

        self.init_status = InitState.INITIALIZING

        self.has_timed_out = False
        self.current_timeout_wait = 0

        self.status = SensorThreadState.WAITING

    def initialize(self, conf_reader):
        """Initialize the monitoring thread"""
        # Set the configuration file reader located in /etc/sspl-ll.conf
        self._conf_reader = conf_reader

        # Set the scheduler to fire the thread right away
        self._scheduler.enter(1, self._priority, self.check_and_run, ())

    def get_thread_init_status(self):
        self.lock.acquire()
        s = self.status
        self.lock.release()

        return s

    def prepare(self, dependencies):
        logger.debug("{} depends on {}".format(
            self.__class__.__name__, [d.__class__.__name__ for d in dependencies]))

        self.remaining_dependees |= set(dependencies)
        for d in self.remaining_dependees:
            d.my_register(self)

    def my_register(self, depender):
        logger.debug("{} registering dependency on {}".format(
            depender.__class__.__name__, self.__class__.__name__))

        self.lock.acquire()
        self.waiting_dependers |= {depender}
        self.lock.release()

    def check_and_conclude_initialization(self):
        logger.debug("Begin {}.conclude_initialization()".format(
            self.__class__.__name__))

        # Check that self.lock is held by the caller
        if self.lock.acquire(blocking=False):
            self.lock.release()
            logger.error("SensorThread.check_and_conclude_initialization() called"\
                " without acquiring lock. Returning immediately")
            return

        if self.status != SensorThreadState.WAITING:
            return

        # It is possible that self.event() is not called at all.
        if self.num_failed_dependees:
            self.deps_status = DependencyState.DEPS_FAILED
        elif not self.remaining_dependees:
            self.deps_status = DependencyState.DEPS_SUCCESS

        definitely_failed = \
                self.deps_status == DependencyState.DEPS_FAILED or \
                self.init_status == InitState.INIT_FAILED or \
                self.has_timed_out
        definitely_succeeded = \
                self.deps_status == DependencyState.DEPS_SUCCESS and \
                self.init_status == InitState.INIT_SUCCESS

        if (definitely_failed):
            self.status = SensorThreadState.FAILED
        elif (definitely_succeeded):
            self.status = SensorThreadState.RUNNING
        # else it remains as waiting

        if self.status != SensorThreadState.WAITING:
            for d in self.waiting_dependers:
                d.event(self, self.status == SensorThreadState.RUNNING)

        logger.debug("End {}.conclude_initialization() with state {}".format(
            self.__class__.__name__, self.status))

    def event(self, dependee, running):
        logger.debug("event in {} by {} calling start() with status {}".format(
            self.__class__.__name__, dependee.__class__.__name__, running))

        self.lock.acquire()

        self.remaining_dependees -= {dependee}
        if running:
            pass
        else:
            self.num_failed_dependees += 1

        self.check_and_conclude_initialization()

        self.lock.release()

    def start_thread(self, conf_reader, msgQlist, product):
        logger.debug("Begin {}.start_thread()".format(self.__class__.__name__))
        self.init_status = InitState.INITIALIZING
        try:
            self.initialize(conf_reader, msgQlist, product)
        except Exception as err:
            self.status = self.init_status = InitState.INIT_FAILED
            raise Exception("initialize() failed. {}".format(err))

        self.init_status = InitState.INIT_SUCCESS

        self.lock.acquire()

        self.check_and_conclude_initialization()

        self.lock.release()

        self.start()
        logger.debug("End {}.start_thread()".format(self.__class__.__name__))

    def check_and_run(self):
        logger.debug("Begin {}.should_run()".format(self.__class__.__name__))
        self.lock.acquire()

        self.current_timeout_wait += self.SENSORTHREAD_INIT_WAIT_INTERVAL
        if self.current_timeout_wait > self.SENSORTHREAD_INIT_WAIT_TIMEOUT:
            self.has_timed_out = True
        self.check_and_conclude_initialization()

        should_run = self.status == SensorThreadState.RUNNING
        self.lock.release()

        if not should_run:
            self._scheduler.enter(self.SENSORTHREAD_INIT_WAIT_INTERVAL,
                    self._priority, self.check_and_run, ())
        else:
            self._scheduler.enter(1, self._priority, self.run, ())

class ThreadException(Exception):
    """Generic Exception to handle Threads errors."""

    def __init__(self, module, message):
        """Handle error msg from thread modules."""
        self._module = module
        self._desc = message

    def __str__(self):
        """Returns formated error msg."""
        return "%s: error: %s" %(self._module, self._desc)


import threading
import unittest
from dateutil import parser
from kazoo.handlers.threading import KazooTimeoutError

import storage_interface
import uss_metadata

ZK_TEST_CONNECTION_STRING = 'localhost:2181'
TESTID = 'storage-interface-test'
PARALLEL_WORKERS = 10

class InterUSSStorageInterfaceTestCase(unittest.TestCase):

  def setUp(self):
    # IMPORTANT: Puts us in a test data location
    self.mm = storage_interface.USSMetadataManager(
        ZK_TEST_CONNECTION_STRING, testgroupid=TESTID)
    self.mm.set_verbose()

  def tearDown(self):
    # IMPORTANT: Clean out your test data when you are done
    self.mm.delete_testdata()
    self.mm = None

  def testBadConnectionStrings(self):
    with self.assertRaises(ValueError):
      storage_interface.USSMetadataManager(
          'terrible:connection:1459231232133_string-#$%@',
          testgroupid=TESTID)
    with self.assertRaises(ValueError):
      storage_interface.USSMetadataManager(
          '__init__%password%', testgroupid=TESTID)
    with self.assertRaises(ValueError):
      storage_interface.USSMetadataManager(
          '\'printf();\'', testgroupid=TESTID)
    with self.assertRaises(KazooTimeoutError):
      storage_interface.USSMetadataManager(
          '123456789101112', testgroupid=TESTID)
    with self.assertRaises(KazooTimeoutError):
      storage_interface.USSMetadataManager(
          'google.com:2424,gmail.com:14566',
          testgroupid=TESTID)

  def testGetCellNegativeCases(self):
    self.assertEqual('fail', self.mm.get(2, 1, 2**2)['status'])
    # x, y, z are ints
    self.assertEqual('fail', self.mm.get(1, '1a', 1)['status'])
    self.assertEqual('fail', self.mm.get(1, 1, 'aa')['status'])
    self.assertEqual('fail', self.mm.get(None, 1, 1)['status'])
    # x and y tiles max are 2^zoom - 1
    self.assertEqual('fail', self.mm.get(1, 2, 1)['status'])
    self.assertEqual('fail', self.mm.get(2, 5478118, 1)['status'])
    self.assertEqual('fail', self.mm.get(2, 2**2, 1)['status'])
    self.assertEqual('fail', self.mm.get(12, 2**12, 1)['status'])
    self.assertEqual('fail', self.mm.get(1, 17, 1)['status'])
    self.assertEqual('fail', self.mm.get(1, 1, 11)['status'])
    self.assertEqual('fail', self.mm.get(9, 2**8, 2**11)['status'])

  def testGetCellPositiveEmptyCases(self):
    # simple 1,1,1
    r = self.mm.get(1, 1, 1)
    self.assertEqual('success', r['status'])
    self.assertEqual(r['data']['version'], 0)
    # zero case
    r = self.mm.get(0, 0, 0)
    self.assertEqual('success', r['status'])
    self.assertEqual(r['data']['version'], 0)
    r = self.mm.get(11, 0, 5)
    self.assertEqual('success', r['status'])
    self.assertEqual(r['data']['version'], 0)
    # limit in the y direction
    r = self.mm.get(10, 1, 2**10 - 1)
    self.assertEqual('success', r['status'])
    self.assertEqual(r['data']['version'], 0)
    # limit in the x direction
    r = self.mm.get(18, 2**18 - 1, 2**10 - 1)
    self.assertEqual('success', r['status'])
    self.assertEqual(r['data']['version'], 0)

  def testPositiveGetSetDeleteCycle(self):
    # 2,1,1 get empty
    g = self.mm.get(2, 1, 1)
    self.assertEqual('success', g['status'])
    self.assertEqual(g['data']['version'], 0)
    self.assertEqual(len(g['data']['operators']), 0)
    # simple set with basic values
    s = self.mm.set(2, 1, 1, g['sync_token'], 'uss', 'uss-scope', 'GUTMA',
                    'https://g.co/flight', '2018-01-01T00:00:00+00:00',
                    '2018-01-01T01:00:00+00:00')
    self.assertEqual('success', s['status'])
    self.assertEqual(s['data']['version'], 1)
    self.assertEqual(len(s['data']['operators']), 1)
    o = s['data']['operators'][0]
    self.assertEqual(o['uss'], 'uss')
    self.assertEqual(o['operation_endpoint'], 'https://g.co/flight')
    self.assertEqual(o['operation_format'], 'GUTMA')
    self.assertEqual(o['version'], 1)
    self.assertEqual(o['minimum_operation_timestamp'],
                     '2018-01-01T00:00:00+00:00')
    self.assertEqual(o['maximum_operation_timestamp'],
                     '2018-01-01T01:00:00+00:00')
    # simple delete
    d = self.mm.delete(2, 1, 1, 'uss')
    self.assertEqual('success', d['status'])
    self.assertEqual(d['data']['version'], 2)
    self.assertEqual(len(d['data']['operators']), 0)
    # simple confirm get is empty
    g = self.mm.get(2, 1, 1)
    self.assertEqual('success', g['status'])
    self.assertEqual(g['data']['version'], 2)
    self.assertEqual(len(g['data']['operators']), 0)

  def testSetCellWithOutdatedsync_token(self):
    # 3,1,1 get empty
    g = self.mm.get(3, 1, 1)
    self.assertEqual('success', g['status'])
    self.assertEqual(g['data']['version'], 0)
    self.assertEqual(len(g['data']['operators']), 0)
    # simple set with basic values
    s = self.mm.set(3, 1, 1, g['sync_token'], 'uss1', 'uss1-scope', 'GUTMA',
                    'https://g.co/flight', '2018-01-01T00:00:00+00:00',
                    '2018-01-01T01:00:00+00:00')
    self.assertEqual('success', s['status'])
    self.assertEqual(s['data']['version'], 1)
    self.assertEqual(len(s['data']['operators']), 1)
    # now try to do a set with the original sync token
    s = self.mm.set(3, 1, 1, g['sync_token'], 'uss2', 'uss2-scope', 'GUTMA',
                    'https://h.com/f/3/1/1', '2018-01-01T11:00:00+00:00',
                    '2018-01-01T12:00:00+00:00')
    self.assertEqual(s['status'], 'fail')
    # confirm version is still the first write
    g = self.mm.get(3, 1, 1)
    self.assertEqual('success', g['status'])
    self.assertEqual(g['data']['version'], 1)
    self.assertEqual(len(g['data']['operators']), 1)

  def testSetCellsInParallelWithSamesync_token(self):
    # 4,1,1 get empty
    g = self.mm.get(4, 1, 1)
    self.assertEqual('success', g['status'])
    self.assertEqual(g['data']['version'], 0)
    self.assertEqual(len(g['data']['operators']), 0)
    threads = []
    for i in range(PARALLEL_WORKERS):
      t = threading.Thread(
          target=self.SetCellWorker, args=(
              i,
              g['sync_token'],
          ))
      threads.append(t)
      t.start()
    for t in threads:
      t.join()
    # confirm there is only one update
    g = self.mm.get(4, 1, 1)
    self.assertEqual('success', g['status'])
    self.assertEqual(g['data']['version'], 1)
    self.assertEqual(len(g['data']['operators']), 1)

  def SetCellWorker(self, num, sync_token):
    self.mm.set(4, 1, 1, sync_token, 'uss' + str(num), 'uss-scope' + str(num),
                'GUTMA', 'https://' + str(num) + '.io/flight',
                '2018-01-01T00:00:00+00:00', '2018-01-01T01:00:00+00:00')
    return

  def testSetCellsWithInvalidTimestamps(self):
    # 5,1,1 get empty
    s = self.mm.get(5, 1, 1)
    token = s['sync_token']
    testsets = [('Not a valid timestamp', '215664892128621657566'),
                ('2018-01-01H00:00:00+00:00', '2019-01-01!00:00:00'),
                ('2018-01-01T00:00:00+00:00', '215664892128621657566')]
    for test in testsets:
      s = self.mm.set(5, 1, 1, token, 'uss', 'uss-scope', 'GUTMA',
                      'https://g.co/flight', test[0], test[1])
      self.assertEqual(s['status'], 'fail')

  def testSetCellsWithValidTimestamps(self):
    # 5,1,1 get empty
    s = self.mm.get(5, 1, 1)
    token = s['sync_token']
    testsets = [('2018-01-01T00:00+00', '2019-01-01T01:02:03.12345+00:00'),
                ('2018-01-01T00:00:00', '2019-01-01T01:02:03.12345'),
                ('2018-02-28T23:59:59-07:00', '2018-03-02T23:59:59+08:00'),
                ('2018-01-01T00:00:00', '2019-01-01')
               ]
    for test in testsets:
      s = self.mm.set(5, 1, 1, token, 'uss', 'uss-scope', 'GUTMA',
                      'https://g.co/flight', test[0], test[1])
      token = s['sync_token']
      self.assertEqual('success', s['status'])
      o = s['data']['operators'][0]
      # Fix up the test cases to compare, this isn't what is sent to the api
      mintest = test[0]
      maxtest = test[1]
      if len(maxtest) <= 10:
        maxtest = maxtest + 'T00:00:00Z'
      if not ('+' in mintest[-6:] or '-' in mintest[-6:] or 'Z' in mintest[-6:]):
        mintest += 'Z'
      if not ('+' in maxtest[-6:] or '-' in maxtest[-6:] or 'Z' in maxtest[-6:]):
        maxtest += 'Z'
      self.assertAlmostEqual(
        0, (parser.parse(mintest) -
            parser.parse(o['minimum_operation_timestamp'])).total_seconds(), 0)
      self.assertAlmostEqual(
        0, (parser.parse(maxtest) -
            parser.parse(o['maximum_operation_timestamp'])).total_seconds(), 0)

  def testGetCellMultipleCellCases(self):
    r1 = self.mm.get_multi(6, [(0, 0), (0, 1), (1, 1)])
    self.assertEqual('success', r1['status'])
    self.assertEqual(0, r1['data']['version'])
    # now do a write to a single cell
    g = self.mm.get(6, 0, 1)
    s = self.mm.set(6, 0, 1, g['sync_token'], 'uss1', 'uss1-scope', 'GUTMA',
                    'https://g.co/flight/0/1', '2018-01-01T00:00:00+00:00',
                    '2018-01-01T01:00:00+00:00')
    self.assertEqual('success', s['status'])
    # confirm the sync_token has changed on multi
    r2 = self.mm.get_multi(6, [(0, 0), (0, 1), (1, 1)])
    self.assertNotEqual(r1['sync_token'], r2['sync_token'])
    # add a few more writes
    g = self.mm.get(6, 1, 1)
    s = self.mm.set(6, 1, 1, g['sync_token'], 'uss1', 'uss1-scope', 'GUTMA',
                    'https://g.co/flight/1/1', '2018-01-01T00:00:00+00:00',
                    '2018-01-01T01:00:00+00:00')
    g = self.mm.get(6, 1, 1)
    s = self.mm.set(6, 1, 1, g['sync_token'], 'uss2', 'uss2-scope', 'GUTMA',
                    'https://g2.co/uss2/1/1', '2018-01-01T00:00:00+00:00',
                    '2018-01-01T01:00:00+00:00')
    self.assertEqual('success', s['status'])
    # Now get them all and confirm you have the right amount
    r3 = self.mm.get_multi(6, [(0, 0), (0, 1), (1, 1)])
    self.assertEqual('success', r3['status'])
    self.assertNotEqual(r1['sync_token'], r3['sync_token'])
    self.assertNotEqual(r2['sync_token'], r3['sync_token'])
    self.assertEqual(2, r3['data']['version'])
    self.assertEqual(3, len(r3['data']['operators']))

  def testDeleteCellMultipleCellCases(self):
    grids = [(0, 0), (0, 1), (1, 1)]
    r1 = self.mm.get_multi(7, grids)
    self.assertEqual('success', r1['status'])
    self.assertEqual(0, r1['data']['version'])
    g = self.mm.get(7, 0, 1)
    s = self.mm.set(7, 0, 1, g['sync_token'], 'uss1', 'uss1-scope', 'GUTMA',
                    'https://g.co/flight/0/1', '2018-01-01T00:00:00+00:00',
                    '2018-01-01T01:00:00+00:00')
    self.assertEqual('success', s['status'])
    # add a few more writes
    g = self.mm.get(7, 1, 1)
    s = self.mm.set(7, 1, 1, g['sync_token'], 'uss1', 'uss1-scope', 'GUTMA',
                    'https://g.co/flight/1/1', '2018-01-01T00:00:00+00:00',
                    '2018-01-01T01:00:00+00:00')
    self.assertEqual('success', s['status'])
    g = self.mm.get(7, 1, 1)
    s = self.mm.set(7, 1, 1, g['sync_token'], 'uss2', 'uss2-scope', 'GUTMA',
                    'https://g2.co/uss2/1/1', '2018-01-01T00:00:00+00:00',
                    '2018-01-01T01:00:00+00:00')
    self.assertEqual('success', s['status'])
    # Now try deleting uss1, which would delete from two different cells
    r2 = self.mm.delete_multi(7, grids, 'uss1')
    self.assertEqual('success', r2['status'])
    self.assertNotEqual(r1['sync_token'], r2['sync_token'])
    self.assertEqual(3, r2['data']['version'])
    self.assertEqual(1, len(r2['data']['operators']))

  def testInvalidMultipleCellCases(self):
    r = self.mm.get_multi(6, [])
    self.assertEqual('fail', r['status'])
    r = self.mm.get_multi(6, '0,0,1,1,0,1')
    self.assertEqual('fail', r['status'])
    r = self.mm.delete_multi(6, [(0, 0), (0, 1), (1, 1)], None)
    self.assertEqual('fail', r['status'])
    r = self.mm.delete_multi(21, [(0, 0), (0, 1), (1, 1)], 'uss')
    self.assertEqual('fail', r['status'])

  def testSetMultipleCellCases(self):
    grids = [(0, 0), (0, 1), (0, 2),
             (1, 0), (1, 1), (1, 2),
             (2, 0), (2, 1), (2, 2),
             (3, 0), (3, 1), (3, 2)]
    g = self.mm.get_multi(8, grids)
    self.assertEqual('success', g['status'])
    self.assertEqual(0, g['data']['version'])
    # now do a write to multiple cells
    s = self.mm.set_multi(8, grids, g['sync_token'], 'uss1', 'uss1-scope',
                          'GUTMA', 'https://g.co/flight/{z}/{x}/{y}',
                          '2018-01-01T00:00:00+00:00',
                          '2018-01-01T01:00:00+00:00')
    self.assertEqual('success', s['status'])
    self.assertEqual(1, s['data']['version'])
    self.assertEqual(len(grids), len(s['data']['operators']))
    g = self.mm.get_multi(8, grids)
    self.assertEqual('success', s['status'])
    self.assertEqual(1, s['data']['version'])
    self.assertEqual(len(grids), len(s['data']['operators']))

  def testFullCycleMultipleCellCases(self):
    grids = [(0, 0), (0, 1), (1, 1)]
    g = self.mm.get_multi(9, grids)
    self.assertEqual('success', g['status'])
    self.assertEqual(0, g['data']['version'])
    # now do a write to multiple cells
    s = self.mm.set_multi(9, grids, g['sync_token'], 'uss1', 'uss1-scope',
                          'GUTMA', 'https://g1.co/flight/{z}/{x}/{y}',
                          '2018-01-01T00:00:00+00:00',
                          '2018-01-01T01:00:00+00:00')
    self.assertEqual('success', s['status'])
    self.assertNotEqual(g['sync_token'], s['sync_token'])
    self.assertEqual(1, s['data']['version'])
    self.assertEqual(len(grids), len(s['data']['operators']))
    # Do a write to two other cells
    grids = [(0, 0), (1, 1)]
    g = self.mm.get_multi(9, grids)
    self.assertEqual('success', g['status'])
    self.assertEqual(1, g['data']['version'])
    s = self.mm.set_multi(9, grids, g['sync_token'], 'uss2', 'uss2-scope',
                          'GUTMA', 'https://g2.co/flight/{z}/{x}/{y}',
                          '2018-01-01T00:00:00+00:00',
                          '2018-01-01T01:00:00+00:00')
    self.assertEqual('success', s['status'])
    self.assertNotEqual(g['sync_token'], s['sync_token'])
    self.assertEqual(2, s['data']['version'])
    self.assertEqual(4, len(s['data']['operators']))
    grids = [(0, 0), (0, 1), (1, 1)]
    s = self.mm.get_multi(9, grids)
    self.assertEqual('success', s['status'])
    self.assertEqual(2, s['data']['version'])
    self.assertEqual(5, len(s['data']['operators']))
    multi_token = s['sync_token']
    # Now write to another cell singly and then update using old token
    g = self.mm.get(9, 0, 1)
    s = self.mm.set(9, 0, 1, g['sync_token'], 'uss3', 'uss3-scope', 'GUTMA',
                    'https://g3.co/f/{z}/{x}/{y}', '2018-01-01T00:00:00+00:00',
                    '2018-01-01T01:00:00+00:00')
    self.assertEqual('success', s['status'])
    s = self.mm.set_multi(9, grids, multi_token, 'ussXX', 'ussXX-scope',
                          'GUTMA', 'https://gXX.co/flight/{z}/{x}/{y}',
                          '2018-01-01T00:00:00+00:00',
                          '2018-01-01T01:00:00+00:00')
    self.assertEqual('fail', s['status'])
    grids = [(0, 0), (0, 1), (0, 2),
             (1, 0), (1, 1), (1, 2),
             (2, 0), (2, 1), (2, 2),
             (3, 0), (3, 1), (3, 2)]
    g = self.mm.get_multi(9, grids)
    s = self.mm.set_multi(9, grids, g['sync_token'], 'uss4', 'uss4-scope',
                          'GUTMA', 'https://g4.co/flight/{z}/{x}/{y}',
                          '2018-01-01T00:00:00+00:00',
                          '2018-01-01T01:00:00+00:00')

  def testUSSmetadatAddition(self):
    a = uss_metadata.USSMetadata()
    a.upsert_operator('uss-a', 'scope-a', 'NASA', 'http://a.com/uss',
                      '2018-01-01', '2018-01-02', 10, 1, 1)
    b1 = uss_metadata.USSMetadata()
    b1.upsert_operator('uss-b', 'scope-b', 'NASA', 'http://b.com/uss',
                      '2018-01-01', '2018-01-02', 10, 1, 1)
    b2 = uss_metadata.USSMetadata()
    b2.upsert_operator('uss-b', 'scope-b', 'NASA', 'http://b.com/uss',
                       '2018-01-01', '2018-01-02', 10, 1, 2)
    usss = a + b1 + b2
    self.assertEqual(3, len(usss.operators))
    with self.assertRaises(ValueError):
      usss = a + a
    ax = uss_metadata.USSMetadata()
    ax.upsert_operator('uss-a', 'scope-ax', 'NASA', 'http://ax.com/uss',
                      '2018-01-03', '2018-01-04', 10, 1, 1)
    with self.assertRaises(ValueError):
      usss = a + ax

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


#import random to select random word from the list
from operator import pos
import random

#define a function to check the letters and give clues
def processguess(theAnswer, theGuess):
    position = 0
    clue = ""
    for letter in theGuess:
        if letter == theAnswer[position]:

            clue += "()"

        elif letter == theAnswer:
            clue += '{}'
        else:
            clue += "-"
            position += 1
    print(clue)
    return clue == "()()()()()"

#Load the words onto the list
word_list = ["APPLE", "WEARY", "PILLS", "VAGUE"]

#snippet to randomly choose a word from the list
answer = random.choice(word_list)

#the variables to determine the guesses and the guessed words
num_of_guesses = 0
guess_correct = False

#use the while loop to check the conditions of the game
while num_of_guesses < 6 and not guess_correct:
    #prompt user to enter their guess
    guess = input("Input your guess:  ")
    print("Your Guess is " +guess)
    num_of_guesses += 1

    #process guesses
    guess_correct = processguess(answer, guess)

#print the game messages
if guess_correct:
    print("Congratulations! You won! The Correct word is indeed", answer)

else:
    print("Sorry you lost...The correct word is " ,answer)


# Returns array and integer.
# This function checks if passed array contains subarray which summarized element are equal to passed integer.
def caterpillar(array, number):
    # start <- index indicating begin of the subarray
    start = 0
    # end <- index indicating end of the subarray
    end = 0
    # sum <- summarized elements in subarray
    suma = 0

    while end <= len(array) and start < len(array):
        if suma < number:
            if end < len(array):
                suma += array[end]
            end += 1
        elif suma > number:
            suma -= array[start]
            start += 1
        else:
            return array[start: end], number
    return None, number

# This function prints result of caterpillar() function
def printCaterpillar(caterpi, number):
    if caterpi is None:
        print("There is no sum which is equals to ", number)
    else:
        print(caterpi, "-> sum =", sum(caterpi))

def tests():
    result, number = caterpillar([1, 3, 10, 6, 3, 5, 2], 21)
    assert result is None
    result, number = caterpillar([1, 3, 10, 6, 3, 5, 2], 7)
    assert result == [5, 2]
    result, number = caterpillar([1, 3, 10, 8, 3, 5, 2], 21)
    assert result == [3, 10, 8]
    result, number = caterpillar([0, 0, 0, 1, 0, 0, 1, 0, 0], 2)
    assert result == [0, 0, 0, 1, 0, 0, 1]
    result, number = caterpillar([], 2)
    assert result is None

tests()

arr, num = caterpillar([1, 3, 10, 6, 3, 5, 2], 21)
printCaterpillar(arr, num)
arr, num = caterpillar([1, 3, 10, 8, 3, 5, 2], 21)
printCaterpillar(arr, num)
arr, num = caterpillar([0, 0, 0, 1, 0, 0, 1, 0, 0], 2)
printCaterpillar(arr, num)
arr, num = caterpillar([], 2)
printCaterpillar(arr, num)
arr, num = caterpillar([1, 3, 10, 6, 3, 5, 2], 7)
printCaterpillar(arr, num)