import numpy as np
import matplotlib.pyplot as plt

def f(x,y):
    return np.sin(x+y-1) + (x-y-1)**2- 1.5*x+2.5*y+1

X = (np.linspace(1.0 , 5.0, num=1000))
Y = (np.linspace(-3.0 , 4.0, num=1000))

from mpl_toolkits.mplot3d import Axes3D

a, b = np.meshgrid(X,Y)
c = f(a,b)
fig = plt.figure(figsize=(5, 5))
ax = fig.gca(projection='3d')
surf = ax.plot_surface(a, b, c, alpha=0.5)
#plt.show()

import sympy
x, y = sympy.symbols('x y')

dif_x  = sympy.diff((sympy.sin(x+y-1) + (x-y-1)*(x-y-1)- 1.5*x+2.5*y+1), x)
dif_y = sympy.diff((sympy.sin(x+y-1) + (x-y-1)*(x-y-1)- 1.5*x+2.5*y+1), y)

xs_q, ys_q = np.meshgrid(np.linspace(1.0, 5.0,num=10), np.linspace(-3.0, 4.0,num=10))

#xs_q_grad = [float(dif_x.subs(x, xv).subs(y, yv)) for xv, yv in zip(xs_q.ravel(), ys_q.ravel())]
#ys_q_grad = [float(dif_y.subs(x, xv).subs(y, yv)) for xv, yv in zip(xs_q.ravel(), ys_q.ravel())]

#print(len(xs_q_grad))
init_x= float(np.random.randn(1))+np.random.randint(2,4)
init_y= float(np.random.randn(1))+np.random.randint(-2,3)
xk = np.array([init_x, init_y])
lam = 0.1
number = 0

while True:
    dist = lam*np.array([float(dif_x.subs(x, xk[0]).subs(y, xk[1])),float(dif_y.subs(x, xk[0]).subs(y, xk[1]))])
    xk= xk - dist
    number+=1
    ax.scatter(xk[0], xk[1], f(xk[0], xk[1]), marker='o', s=10)
    if np.sqrt(dist[0]**2+dist[1]**2)< 0.00001:
        print(xk)
        print(number)
        print(f(xk[0], xk[1]))
        break

number = 0
H = np.array([[sympy.diff(dif_x, x), sympy.diff(dif_x, y), ],[sympy.diff(dif_y, x) , sympy.diff(dif_y, y)]])
xk = np.array([init_x, init_y])
while True:
    hk = np.array([[float(H[0, 0].subs(x, xk[0]).subs(y, xk[1])),
                    float(H[0, 1].subs(x, xk[0]).subs(y, xk[1]))],
                   [float(H[1, 0].subs(x, xk[0]).subs(y, xk[1])),
                    float(H[1, 1].subs(x, xk[0]).subs(y, xk[1]))]])
    invhk = np.linalg.pinv(hk)
    dist = invhk @ np.array([float(dif_x.subs(x, xk[0]).subs(y, xk[1])), float(dif_y.subs(x, xk[0]).subs(y, xk[1]))])
    xk = xk - dist
    number +=1
    ax.scatter(xk[0], xk[1], f(xk[0], xk[1]), marker='x', s=10)
    if np.sqrt(dist[0]**2+dist[1]**2)< 0.00001:
        print(xk)
        print(number)
        print(f(xk[0], xk[1]))
        break

plt.show()


'''
Feature Extractor for Ner

@author: Lorenzo
'''
from it.ds4biz.obj.TextObject import TextObject
from it.ds4biz.util.Windows import context
from it.ds4biz.feature.FeatureUtils import getBaseWordFeatures,\
    getBaseTargetWordFeatures
from it.ds4biz.obj.FeatureDictionary import FeatureDictionary

class FeatureExtractor:

    def __init__(self):
        raise Exception("Not implemented")

    def extract(self, object):
        raise Exception("Not implemented: extract")

class TextFeatureExtractor(FeatureExtractor):

    def extract(self, tokens):
        if not isinstance(tokens, list):
            raise Exception("tokens must be list")

class uniqwordTexxtFea(TextFeatureExtractor):

    def extract(self, tokens):
        feat_dict=FeatureDictionary()
        for t in tokens:
            feat_dict=getBaseTargetWordFeatures(t,0,feat_dict,"target")

class WindowsTextFeatureExtractor(TextFeatureExtractor):

    def __init__(self,pre_size=2,post_size=2):
        self.pre_size=pre_size
        self.post_size=post_size

    def extract(self, tokens):
        super().extract(tokens)
        for word_target,pox,pre_words,post_words in context(tokens,self.pre_size, self.post_size):
            feat_dict=FeatureDictionary()

            feat_dict=getBaseTargetWordFeatures(word_target,pox,feat_dict,"target")
            feat_dict=getBaseWordFeatures(word_target,feat_dict,'target')

            for ind, word in enumerate(pre_words):
                feat_dict["pred_word_" + str(ind)+"_t"] = word
                feat_dict= getBaseWordFeatures(word,feat_dict, "pred_word_" + str(ind))

            for ind, word in enumerate(post_words):
                feat_dict["foll_word_" + str(ind)+"_t"] = word
                feat_dict= getBaseWordFeatures(word, feat_dict,"foll_word_" + str(ind))

            yield feat_dict

if __name__ == '__main__':
    w=WindowsTextFeatureExtractor(pre_size=3)
    for d in  w.extract("ciao amici miei sono proprio io".split(" ")):
     print(d.get_target_word())


from sklearn.cross_validation import train_test_split
from sklearn import metrics
import numpy as np
from adaboost_trees import AdaboostTrees

# load data
X = np.loadtxt('../feature/5grams_count_mc_features')
y = np.loadtxt('../data/tag_mc')
X -= X.min()
X /= X.max()
X_train, X_test, y_train, y_test = train_test_split(X, y)

#instanciate forest
forest = AdaboostTrees(20)
forest.train(X_train, y_train)
expected = y_test
predicted = forest.predict(X_test)

# summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))


from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
from keras.models import Sequential, Model
from keras.layers import Dense, Input

x = np.array([np.arange(1, 101), np.arange(101, 201), np.arange(301, 401)])
x2 = np.array([np.arange(1001, 1101), np.arange(1101, 1201), np.arange(1301, 1401)])

y = np.array([np.arange(1, 101), np.arange(101, 201), np.arange(301, 401)])
y2 = np.array([np.arange(1001, 1101), np.arange(1101, 1201), np.arange(1301, 1401)])
y3 = np.array([np.arange(1001, 1101), np.arange(1101, 1201), np.arange(1301, 1401)])

# y2 = np.array([np.arange(1001, 1101)])

# x3 = np.array([np.arange(1, 101), np.arange(101, 201), np.arange(301, 401)])
# y3 = np.array([np.arange(1, 101)])

x = x.reshape(-1, 3)
x2 = x2.reshape(-1, 3)

y = np.transpose(y)
y2 = np.transpose(y2)
y3 = np.transpose(y3)

print(x.shape, y.shape)

# x = np.transpose(x)

# concat_x = np.concatenate((x, x2), axis=1)

x_train, x_test, x2_train, x2_test, y_train, y_test, y2_train, y2_test, y3_train, y3_test = train_test_split(x, x2, y, y2, y3, test_size=0.4, random_state=0)
x_val, x_test, x2_val, x2_test, y_val, y_test, y2_val, y2_test, y3_val, y3_test = train_test_split(x_test, x2_test, y_test, y2_test, y3_test, test_size=0.5, random_state=0)

print(len(x2_train) / len(x2))
print(len(x2_val) / len(x2))
print(len(x2_test) / len(x2))
# quit()

# model = Sequential()
# model.add(Dense(32, input_shape=(3, )))
# model.add(Dense(128))
# model.add(Dense(32))
# model.add(Dense(1))

#   Functional API
input = Input(shape=(3,))
model = Dense(32)(input)
model = Dense(32)(model)
model = Dense(32)(model)
output = Dense(1)(model)
# model = Model(inputs=input, outputs=output)

#   Second Model for Ensemble
input2 = Input(shape=(3,))
model2 = Dense(64)(input2)
model2 = Dense(64)(model2)
model2 = Dense(64)(model2)
output2 = Dense(5)(model2) # merge 하는 경우 마지막 노드 수는 상관없다. hidden cell 이기 때문

from keras.layers.merge import concatenate

merge = concatenate([output, output2])

merge = Dense(4)(merge)
merge = Dense(4)(merge)
merge = Dense(1)(merge)

output_1 = Dense(16)(merge)
output_1 = Dense(3)(output_1)

output_2 = Dense(16)(merge)
output_2 = Dense(3)(output_2)

output_3 = Dense(16)(merge)
output_3 = Dense(3)(output_3)

#   merge 의 경우 model 을 정의하는 방법
model = Model(inputs=[input, input2], outputs=[output_1, output_2, output_3])
model.summary()
# quit()

from keras.callbacks import TensorBoard

callback1 = TensorBoard(log_dir='./graph',
                          histogram_freq=0,
                          write_graph=True,
                          write_images=True)

model.compile(loss='mse', optimizer='adam', metrics=['mse'])
model.fit([x_train, x2_train], [y_train, y2_train, y3_train], epochs=100, batch_size=1, \
    validation_data=([x_val, x2_val], [y_val, y2_val, y3_val]), callbacks=[callback1])

result = model.evaluate([x_test, x2_test], [y_test, y2_test, y3_test], batch_size=1)
print(result)

y_pred, y2_pred, y3_pred = model.predict([x_test, x2_test], batch_size=1)
print(y_test.shape, y_pred.shape)
# quit()

from sklearn.metrics import mean_squared_error, r2_score

def RMSE(y_test, y_pred):
    return np.sqrt(mean_squared_error(y_test, y_pred))

rmse = RMSE(y_test, y_pred)
rmse2 = RMSE(y2_test, y2_pred)
rmse3 = RMSE(y3_test, y3_pred)
print('RMSE :', rmse)
print('RMSE :', rmse2)
print('RMSE :', rmse3)
print('Mean_RMSE :', (rmse + rmse2 + rmse3) / 3)

R2_score = r2_score(y_test, y_pred)
# print('R2_score :', R2_score)


import cv2
import os
import dlib
import numpy as np
from PIL import Image
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import models, datasets, transforms
import matplotlib.pyplot as plt
import copy
from scipy import optimize
import json
import time
from torch.autograd import Variable

# function : 利用pytorch预训练的alexnet模型创建自定义的alexnet，取原模型的倒数第二层输出作为自定义模型的输出
class alex(nn.Module):
    def __init__(self):
        super(alex, self).__init__()
        alexnet = models.alexnet(pretrained=True)
        self.feature = alexnet.features
        self.classifier = nn.Sequential(*list(alexnet.classifier.children())[:-2])
        pretrained_dict = alexnet.state_dict()
        model_dict = self.classifier.state_dict()
        pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
        model_dict.update(pretrained_dict)
        self.classifier.load_state_dict(model_dict)

    def forward(self, x):
        output = self.feature(x)
        output = output.view(output.size(0), -1)
        output = self.classifier(output)
        return output

# 自定义数据集
class MyDataset(torch.utils.data.Dataset): #创建自己的类：MyDataset,这个类是继承的torch.utils.data.Dataset
    def __init__(self, Listdataset, transform=None, target_transform=None): #初始化一些需要传入的参数
        super(MyDataset,self).__init__()
        timelist = []
        for key,value in Listdataset.items():
            tra = torch.tensor(value[0])
            label = value[1]
            timelist.append((tra,int(label)))

        self.timelist = timelist
        self.transform = transform
        self.target_transform = target_transform

    def __getitem__(self, index):    #这个方法是必须要有的，用于按照索引读取每个元素的具体内容
        tra = self.timelist[index][0]
        label = self.timelist[index][1]
        return tra,label     #return很关键，return回哪些内容，那么我们在训练时循环读取每个batch时，就能获得哪些内容

    def __len__(self): #这个函数也必须要写，它返回的是数据集的长度，也就是多少张图片，要和loader的长度作区分
        return len(self.timelist)

def create_dataset(net, name, savepath, train_or_test, allpicture):
    start_time = time.time()
    Listdataset = {}

    if name == "aiban":
        label = 0
    elif name == "minzhu":
        label = 1
    elif name == "hexie" :
        label = 2
    elif name == "zgm":
        label = 3

    if train_or_test == "train":
        for index in range(1,161):
            feature_frame_folder = "E:\\lip_tracking_project\\cnn_and_lstm_0822\\" + "allpics=10\\" + train_or_test + "\\" + name + str(index) + "\\tezhengdiantiqu\\"
            frame = np.zeros([1, 4096], dtype=float)  # 该视频提取到的frame,刚开始只有维度1只有1行

            for i in range(0,allpicture):
                # 生成单个视频的特征矩阵
                image_path = feature_frame_folder + str(i) + "lip.jpg"
                result = extractor(image_path, net)     # 返回某一张图片的特征矩阵
                if i==0 :
                    # 如果是第一张帧
                    frame[0] = result
                else :
                    # 如果不是第一帧，则按行往下增加一帧
                    frame = np.row_stack((frame, result))

            Listdataset[str(index)] = [frame.tolist(), label]

    elif train_or_test == "test":
        for index in range(1,41):
            feature_frame_folder = "E:\\lip_tracking_project\\cnn_and_lstm_0822\\" + "allpics=10\\" + train_or_test + "\\" + name + str(index) + "\\tezhengdiantiqu\\"
            frame = np.zeros([1, 4096], dtype=float)  # 该视频提取到的frame,刚开始只有维度1只有1行

            for i in range(0,allpicture):
                # 生成单个视频的特征矩阵
                image_path = feature_frame_folder + str(i) + "lip.jpg"
                result = extractor(image_path, net)     # 返回某一张图片的特征矩阵
                if i==0 :
                    # 如果是第一张帧
                    frame[0] = result
                else :
                    # 如果不是第一帧，则按行往下增加一帧
                    frame = np.row_stack((frame, result))

            Listdataset[str(index)] = [frame.tolist(), label]

    else : print("plz input correct type!")

    with open(savepath, "w") as f :
        f.write(json.dumps(Listdataset))

    end_time = time.time()

    print(name + "的" + train_or_test + "集构建耗时时间 {} seconds".format(end_time-start_time))

# function : 将图片转换为可用输入已pretrained的alexnet模型
# input : 图片地址，
#         pytorch已经pretrained好的神经网络模型
# return : alexnet的倒数第二层输出的array
def extractor(img_path, net):
    transform = transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                 std=[0.229, 0.224, 0.225])]
    )

    img = Image.open(img_path)
    img = img.convert("RGB")
    img = transform(img)

    x = Variable(torch.unsqueeze(img, dim=0).float(), requires_grad=False)
    y = net(x)
    y = torch.squeeze(y)
    y = y.data.numpy()

    return y

if __name__ == "__main__":

    namelist = {"0": "爱班",
            "1": "民主",
            "2": "和谐",
            "3": "中国梦",
            }

    net = alex()    # 实例化一个alexnet模型
    if not os.path.exists("E:\\lip_tracking_project\\cnn_and_lstm_0822\\数据集\\"):  # 检查是否存在文件夹
        os.makedirs("E:\\lip_tracking_project\\cnn_and_lstm_0822\\数据集\\")  # 不存在则新建

    for name_of_label in namelist:
        savepath = "E:\\lip_tracking_project\\cnn_and_lstm_0822\\数据集\\" + name_of_label + "训练集0822_四个词.txt"
        create_dataset(net=net, name=name_of_label, savepath=savepath, train_or_test="train",allpicture=10)
        print(name_of_label + "训练集构造完成！")

    for name_of_label in namelist:
        savepath = "E:\\lip_tracking_project\\cnn_and_lstm_0822\\数据集\\" + name_of_label + "测试集0822_四个词.txt"
        create_dataset(net=net, name=name_of_label, savepath=savepath, train_or_test="test",allpicture=10)
        print(name_of_label + "测试集构造完成！")


import requests
import pandas as pd

numberOfPages = 100

jobs = ['Python','HTML']

for job in jobs:
	data = []
	for i in range(numberOfPages):
		print(f'...page:{i}...')
		url = 'https://api.hh.ru/vacancies'
		par = {'text': {job}, 'area':'113','per_page':10, 'page':i}
		r = requests.get(url, params=par)
		if r.status_code == 200:
			print('OK')
		else:
			print('...something went wrong...')
			continue
		data.append(r.json())
	vacancyDetails = data[0]['items'][0].keys()
	df = pd.DataFrame(columns=list(vacancyDetails))
	ind = 0
	for i in range(len(data)):
		for j in range(len(data[i]['items'])):
			df.loc[ind] = data[i]['items'][j]
			ind += 1
	csvName = job+'.csv'
	df.to_csv(csvName)


import unittest, json
from mock import patch, MagicMock, Mock
from strava import client, athlete, activity

class TestActivityInit(unittest.TestCase):

    mock_athlete = Mock()
    mock_athlete.__class__ = 'athlete.Athlete'
    mock_athlete_id = 227615
    mock_activity_id = '321934'
    mock_activity_summary_json = '{}'
    mock_activity_summary_dict = json.loads(mock_activity_summary_json)
    mock_activity_streams = 'mock_stream_object'

    @patch.object(activity.Activity, '_retrieve_activity_streams', return_value=mock_activity_streams)
    @patch.object(activity.Activity, '_retrieve_activity_summary',
                  return_value=(mock_activity_summary_json, mock_activity_summary_dict))
    @patch.object(activity.Activity, '_init_athlete', return_value = mock_athlete)
    def test_init_athlete_is_called(self,
                                    mock_init_athlete, mock_retrieve_activity_summary, mock_retrieve_activity_streams):
        test_activity = activity.Activity(self.mock_activity_id)
        mock_init_athlete.assert_called_with(None)
        self.assertEqual(test_activity.athlete, self.mock_athlete)

    @patch.object(activity.Activity, '_retrieve_activity_streams', return_value=mock_activity_streams)
    @patch.object(activity.Activity, '_retrieve_activity_summary',
                  return_value=(mock_activity_summary_json, mock_activity_summary_dict))
    @patch('strava.athlete.Athlete', return_value = mock_athlete)
    def test_athlet_instantiation_if_no_athlete_provided(self,
                                                         mock_class_Athlete, mock_retrieve_activity_summary, mock_retrieve_activity_streams):
        test_activity = activity.Activity(self.mock_activity_id)
        # mock_class_Athlete.assert_called()
        self.assertEqual(test_activity.athlete, self.mock_athlete)
        self.assertEqual(test_activity.athlete.__class__, 'athlete.Athlete')

    @patch.object(activity.Activity, '_retrieve_activity_streams', return_value=mock_activity_streams)
    @patch.object(activity.Activity, '_retrieve_activity_summary',
                  return_value=(mock_activity_summary_json, mock_activity_summary_dict))
    @patch('strava.athlete.Athlete', return_value=mock_athlete)
    def test_athlete_is_passed_through_when_provided(self,
                                                     mock_class_Athlete, mock_retrieve_activity_summary, mock_retrieve_activity_streams):
        test_athlete = athlete.Athlete()
        test_activity = activity.Activity(self.mock_activity_id, _athlete=test_athlete)
        # mock_class_Athlete.assert_called_once()
        self.assertEqual(test_activity.athlete, self.mock_athlete)

    @patch.object(activity.Activity, '_retrieve_activity_streams', return_value=mock_activity_streams)
    @patch.object(activity.Activity, '_retrieve_activity_summary',
                  return_value=(mock_activity_summary_json, mock_activity_summary_dict))
    @patch('strava.athlete.Athlete', return_value=mock_athlete)
    def test_call_retrieve_current_activity_summary(self,
                                                    mock_class_Athlete, mock_retrieve_activity_summary, mock_retrieve_activity_streams):
        test_activity = activity.Activity(self.mock_activity_id)
        # mock_retrieve_activity_summary.assert_called_once()
        self.assertEqual(test_activity.activity_json, self.mock_activity_summary_json)
        self.assertEqual(test_activity.activity_dict, self.mock_activity_summary_dict)

    @patch.object(activity.Activity, '_retrieve_activity_streams', return_value=mock_activity_streams)
    @patch.object(activity.Activity, '_retrieve_activity_summary',
                  return_value=(mock_activity_summary_json, mock_activity_summary_dict))
    @patch('strava.athlete.Athlete', return_value=mock_athlete)
    def test_call_retrieve_activity_streams(self,
                                            mock_class_Athlete, mock_retrieve_activity_summary, mock_retrieve_activity_streams):
        test_activity = activity.Activity(self.mock_activity_id)
        # mock_retrieve_activity_streams.assert_called_once()
        self.assertEqual(test_activity.streams, self.mock_activity_streams)

class TestActivityMetrics(unittest.TestCase):

    #TODO Find a way to mock the actual dict
    mock_activity_id = '321934'
    mock_activity_name = 'Evening Ride'

    # Define mock for activity object
    mock_activity = Mock()
    mock_activity.__class__ = 'activity.Activity'
    mock_activity.activity_id.return_value = mock_activity_id

    # Define mock for athlete object
    mock_athlete = Mock()
    mock_athlete.__call__ = 'athlete.Athlete'

    def test(self):
        pass

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

#
# class TestActivityMetricsInit(unittest.TestCase):
#
#     def SetUp(self):
#         self.activity_id = '628508858' #mdd30
#         self.client   = client.Client() # not needed for now, but will be required for access_token exchange
#         self.athlete  = athlete.Athlete()
#         self.activity = activity.Activity(athlete=self.athlete, activity_id=self.activity_id)
#
#     # def test_init_activity_metrics_should_return_correct_class(self):
#     #     self.activity_metrics = activity.ActivityMetrics(athlete=self.athlete, activity=self.activity)
#     #     # Assert correct class init
#     #     self.assertEqual(str(self.activity_metrics.__class__), 'strava.activity.ActivityMetrics')


from flask import Flask, render_template, url_for, request, redirect, flash, make_response
from forms import StartEndDateForm, AccountDownloadForm
from plusone import app, journals, accounts, bankimport, banktransactions

from flask_debugtoolbar import DebugToolbarExtension

from logging import DEBUG

app.logger.setLevel(DEBUG)
toolbar = DebugToolbarExtension(app)

# Decorated with, route decorator, which is actually an attribute of the app
# object. Responds to requests from the /index url.
@app.route('/')
@app.route('/index')#, alias=True) # permanent redirect ok here?
# View Function
def index():
    return render_template('index.html')

# View Function
@app.route('/nz', methods=['GET', 'POST'])
def nz():
    downloadform = AccountDownloadForm()

    # Form data is only there post template render (obviously)
    if downloadform.validate_on_submit():
        accountcode = downloadform.accountcode.data

        modified_startdate = downloadform.modified_startdate.data
        modified_enddate = downloadform.modified_enddate.data

        # Create filename
        filename = ''
        filename += modified_enddate.strftime('%Y%m%d')
        filename += '_'
        filename += modified_startdate.strftime('%Y%m%d')
        filename += '_'
        filename += accountcode

        journallist = journals.get_journals(modified_startdate)
        banktransactionlist = banktransactions.get_banktransactions(
            modified_startdate)

        bankimport_rows = bankimport.pair_journals_banktransactions(
            journallist,
            banktransactionlist,
            accountcode,
            modified_startdate, modified_enddate)

        csv_string = bankimport.make_csv_string(bankimport_rows)

        response = make_response(csv_string)
        response.headers["Content-Disposition"] = "attachment; filename=" + filename + ".csv"

        return response

    display_accounts = accounts.get()

    # flash("Downloading with: ")
    # return redirect(url_for('index'))

    return render_template(
        'nz.html',
        downloadform=downloadform,
        accounts=display_accounts
    )

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

@app.errorhandler(500)
def page_not_found(e):
    return render_template('500.html'), 500


"""Perform regular monitoring of the COS FUV and NUV dark rates

"""

from __future__ import print_function, absolute_import, division

import os
import datetime
import numpy as np
import shutil
import glob

from astropy.io import fits
from astropy.time import Time

from .solar import get_solar_data
from .plotting import plot_histogram, plot_time, plot_orbital_rate

from ..utils import corrtag_image
from ..database.db_tables import open_settings, load_connection

base_dir = '/grp/hst/cos/Monitors/Darks/'
web_directory = '/grp/webpages/COS/'

#-------------------------------------------------------------------------------

def get_temp(filename):
    """Get detector temperture during observation from spt filename

    Parameters
    ----------
    filename : str
        FITS file for which the temperature is to be Found

    Returns
    -------
    temperature : float
        Detector temperature at the time of the observation

    """

    with fits.open(filename) as hdu:
        detector = hdu[0].header['DETECTOR']
        segment = hdu[0].header['SEGMENT']
        rootname = hdu[0].header['ROOTNAME']

    if detector == 'FUV' and segment == 'FUVA':
        temp_keyword = 'LDCAMPAT'
    elif detector == 'FUV' and segment == 'FUVB':
        temp_keyword = 'LDCAMPBT'
    elif detector == 'NUV':
        temp_keyword = 'LMMCETMP'
    else:
        raise ValueError('What??? {} {}'.format(detector, segment))

    path, name = os.path.split(filename)
    spt_file = os.path.join(path, rootname + '_spt.fits')

    try:
        temperature = fits.getval(spt_file, temp_keyword, ext=2)
    except IOError:
        temperature = fits.getval(spt_file + '.gz', temp_keyword, ext=2)

    return temperature

#-------------------------------------------------------------------------------

def mjd_to_decyear( time_array ):
    """ pull this out when you get it into astropy.time

    """

    times = Time( time_array, scale='tt', format='mjd' )

    out_times = []
    for value in times:
        year = value.datetime.year
        n_days = (value.datetime - datetime.datetime(value.datetime.year, 1, 1)).total_seconds()
        total_days = (datetime.datetime(value.datetime.year+1, 1, 1) - datetime.datetime(value.datetime.year, 1, 1)).total_seconds()

        fraction = float(n_days) / total_days

        out_times.append(year + fraction)

    return np.array(out_times)

#-------------------------------------------------------------------------------

def pull_orbital_info(dataset, step=25):
    """ Pull second by second orbital information from the dataset

    """

    SECOND_PER_MJD = 1.15741e-5

    info = {}
    info['obsname'] = os.path.split(dataset)[-1]

    hdu = fits.open(dataset)
    try:
        timeline = hdu['timeline'].data
        segment = hdu[0].header['segment']
    except KeyError:
        return

    if segment == 'N/A':
        segment = 'NUV'
        xlim = (0, 1024)
        ylim = (0, 1204)
        pha = (-1, 1)
    elif segment == 'FUVA':
        xlim = (1200, 15099)
        ylim = (380, 680)
        pha = (2, 23)
    elif segment == 'FUVB':
        xlim = (950, 15049)
        ylim = (440, 720)
        pha = (2, 23)
    else:
        raise ValueError('What segment is this? {}'.format(segment))

    info['rootname'] = hdu[0].header['rootname']
    info['detector'] = segment
    info['temp'] = get_temp(dataset)

    times = timeline['time'][::step].copy()
    lat = timeline['latitude'][:-1][::step].copy().astype(np.float64)
    lon = timeline['longitude'][:-1][::step].copy().astype(np.float64)
    try:
        sun_lat = timeline['sun_lat'][:-1][::step].copy().astype(np.float64)
        sun_lon = timeline['sun_lon'][:-1][::step].copy().astype(np.float64)
    except KeyError:
        sun_lat = lat.copy() * 0
        sun_lon = lat.copy() * 0

    mjd = hdu[1].header['EXPSTART'] + \
        times.copy()[:-1].astype(np.float64) * \
        SECOND_PER_MJD

    decyear = mjd_to_decyear(mjd)

    if not len(times):
        blank = np.array([0])
        return

    events = hdu['events'].data
    filtered_index = np.where((events['PHA'] > pha[0]) &
                              (events['PHA'] < pha[1]) &
                              (events['XCORR'] > xlim[0]) &
                              (events['XCORR'] < xlim[1]) &
                              (events['YCORR'] > ylim[0]) &
                              (events['YCORR'] < ylim[1]))

    ta_index = np.where((events['XCORR'] > xlim[0]) &
                        (events['XCORR'] < xlim[1]) &
                        (events['YCORR'] > ylim[0]) &
                        (events['YCORR'] < ylim[1]))

    counts = np.histogram(events[filtered_index]['time'], bins=times)[0]
    ta_counts = np.histogram(events[ta_index]['time'], bins=times)[0]

    npix = float((xlim[1] - xlim[0]) * (ylim[1] - ylim[0]))
    counts = counts / npix / step
    ta_counts = ta_counts / npix / step

    if not len( lat ) == len(counts):
        lat = lat[:-1]
        lon = lon[:-1]
        sun_lat = sun_lat[:-1]
        sun_lon = sun_lon[:-1]

    assert len(lat) == len(counts), \
        'Arrays are not equal in length {}:{}'.format(len(lat), len(counts))

    for i in range(len(counts)):
        ### - better solution than round?
        info['date'] = round(decyear[i], 3)
        info['dark'] = round(counts[i], 7)
        info['ta_dark'] = round(ta_counts[i], 7)
        info['latitude'] = round(lat[i], 7)
        info['longitude'] = round(lon[i], 7)
        info['sun_lat'] = round(sun_lat[i], 7)
        info['sun_lon'] = round(sun_lon[i], 7)

        yield info

#-------------------------------------------------------------------------------

def compile_phd():

    raise NotImplementedError("Nope, seriously can't do any of this.")

    #-- populate PHD table

    columns = ', '.join(['bin{} real'.format(pha) for pha in range(0,31)])
    c.execute("""CREATE TABLE {} ( obsname text, {})""".format(table, columns ))

    c.execute( """SELECT obsname FROM %s """ %(table))
    already_done = set( [str(item[0]) for item in c] )

    for filename in available:
        obsname = os.path.split(filename)[-1]
        if obsname in already_done:
            print(filename, 'done')
        else:
            print(filename, 'running')

        counts = pha_hist(filename)
        table_values = (obsname, ) + tuple(list(counts) )

        c.execute( """INSERT INTO %s VALUES (?{})""" % (table, ',?'*31 ),
                   table_values)

        db.commit()

#-------------------------------------------------------------------------------

def pha_hist(filename):
    hdu = fits.open( filename )
    pha_list_all = hdu[1].data['PHA']
    counts, bins = np.histogram(pha_list_all, bins=31, range=(0, 31))

    return counts

#-------------------------------------------------------------------------------

def make_plots(detector, TA=False):
    print('#-------------------#')
    print('Making plots for {}'.format(detector))
    print('#-------------------#')

    if detector == 'FUV':
        search_strings = ['_corrtag_a.fits', '_corrtag_b.fits']
        segments = ['FUVA', 'FUVB']
    elif detector == 'NUV':
        search_strings = ['_corrtag.fits']
        segments = ['NUV']
    else:
        raise ValueError('Only FUV or NUV allowed.  NOT:{}'.format(detector) )

    try:
        solar_data = np.genfromtxt(base_dir + 'solar_flux.txt', dtype=None)
        solar_date = np.array( mjd_to_decyear([line[0] for line in solar_data]) )
        solar_flux = np.array([line[1] for line in solar_data])
    except TypeError:
        solar_date = np.ones(1000)
        solar_flux = np.ones(1000)

    dark_key = 'dark'
    if TA:
        dark_key = 'ta_dark'

    SETTINGS = open_settings()
    Session, engine = load_connection(SETTINGS['connection_string'])

    for key, segment in zip(search_strings, segments):
        #-- Plot vs time
        print('Plotting Time')
        data = engine.execute("""SELECT date,{},temp,latitude,longitude FROM darks WHERE detector = '{}' """.format(dark_key, segment))
        data = [row for row in data]

        mjd = np.array([float(item.date) for item in data])
        dark = np.array([float(item[1]) for item in data])
        temp = np.array([float(item.temp) for item in data])
        latitude = np.array([float(item.latitude) for item in data])
        longitude = np.array([float(item.longitude) for item in data])

        index = np.argsort(mjd)
        mjd = mjd[index]
        dark = dark[index]
        temp = temp[index]
        latitude = latitude[index]
        longitude = longitude[index]

        index_keep = np.where((longitude < 250) | (latitude > 10))[0]
        mjd = mjd[index_keep]
        dark = dark[index_keep]
        temp = temp[index_keep]

        outname = os.path.join(base_dir, detector, '{}_vs_time_{}.png'.format(dark_key, segment))
        plot_time(detector, dark, mjd, temp, solar_flux, solar_date, outname)

        #-- Plot vs orbit
        print('Plotting Orbit')
        data = engine.execute("""SELECT {},latitude,longitude,sun_lat,sun_lon,date FROM darks WHERE detector = '{}' """.format(dark_key, segment))
        data = [row for row in data]

        dark = np.array([float(item[0]) for item in data])
        latitude = np.array([float(item[1]) for item in data])
        longitude = np.array([float(item[2]) for item in data])
        sun_lat = np.array([float(item[3]) for item in data])
        sun_lon = np.array([float(item[4]) for item in data])
        date = np.array([float(item[5]) for item in data])

        index = np.argsort(date)
        dark = dark[index]
        latitude = latitude[index]
        longitude = longitude[index]
        sun_lat = sun_lat[index]
        sun_lon = sun_lon[index]

        outname = os.path.join(base_dir, detector, '{}_vs_orbit_{}.png'.format(dark_key, segment))
        plot_orbital_rate(longitude, latitude, dark, sun_lon, sun_lat, outname)

        #-- Plot histogram of darkrates
        print('Plotting Hist')
        data = engine.execute("""SELECT {},date FROM darks WHERE detector = '{}' """.format(dark_key, segment))
        data = [item for item in data]

        dark = np.array([float(item[0]) for item in data])
        date = np.array([float(item[1]) for item in data])

        index = np.argsort(date)
        date = date[index]
        dark = dark[index]

        for year in set(map(int, date)):
            index = np.where( (date >= year) &
                              (date < year + 1))

            outname = os.path.join(base_dir, detector, '{}_hist_{}_{}.pdf'.format(dark_key, year, segment))
            plot_histogram(dark[index], outname)

        index = np.where(date >= date.max() - .5)
        outname = os.path.join(base_dir, detector, '{}_hist_-6mo_{}.pdf'.format(dark_key, segment))
        plot_histogram(dark[index], outname )

        outname = os.path.join(base_dir, detector, '{}_hist_{}.pdf'.format(dark_key, segment))
        plot_histogram(dark, outname)

#-------------------------------------------------------------------------------

def move_products():
    '''Move created pdf files to webpage directory
    '''

    print('#-------------------#')
    print('Moving products into')
    print('webpage directory')
    print('#-------------------#')

    for detector in ['FUV', 'NUV']:

        write_dir = web_directory + detector.lower() + '_darks/'
        move_list = glob.glob(base_dir + detector + '/*.p??')

        for item in move_list:
            os.chmod(item, 0o777)
            path, file_to_move = os.path.split(item)
            shutil.copy(item, write_dir + file_to_move)
            print('Moving: %s' % (file_to_move))

        os.system('chmod 777 ' + write_dir + '*.pdf')

#-------------------------------------------------------------------------------

def monitor():
    """Main monitoring pipeline"""

    get_solar_data('/grp/hst/cos/Monitors/Darks/')

    for detector in ['FUV', 'NUV']:
        make_plots(detector)

        if detector == 'FUV':
            make_plots(detector, TA=True)

    move_products()

#-------------------------------------------------------------------------------


from collections import defaultdict

from graphRepresentations import DirectedGraph, DirectedGraphWithWeights

"""
from cs161 note15
Directed Acyclic Graphs (DAG)
1. graphs with a topological ordering (every directed graph has either a cycle or a topological ordering, but not both.)
2. Topological order = sequence of all vertices so that for every edge x->y, x is before y in the sequence.
example of topological order:
"""

"""
Proof of Directed Acyclic Graph
1. proof of "topological order = sequence of all vertices so that for every edge x->y, x is before y in the sequence"
if graph G has a cycle, then G has no topological order.
because: which ever vertex of the cycle we place first in an ordering would have an incoming edge from a later vertex

2. Quick sketch: DFS-based topological ordering
	- idea: postorder traverse of DFS tree, then reverse that order

!!it does not return a correct result when there is a cycle in the graph.
"""

def DFS_based_topological_ordering(graph: DirectedGraph):
	visited = set()
	postorder = []

	def visit(v):
		visited.add(v)
		for w in graph.getNeighbors(v):
			if w not in visited:
				visit(w)
		postorder.append(v)

	for v in graph.getVertices():
		if v not in visited:
			visit(v)
	postorder.reverse()
	return postorder

"""
another topological ordering algorithm (from textbook)
1. have to start at a vertex with no incoming edges
e.g. in previous example, the only vertex with no incoming edges is a
2. once you choose the starting vertex, you keep looking for the vertex in remaining vertices with no incoming edges,
and so on.

3. total time = O(n + m)

4. when this algorithm succeeds- it finds a topological ordering
when this algorithm fails -
	get a subset of the graph(its remaining non-output vertices)
	in which every vertex has an incoming edge from another vertex in the same subset
	(else it whould have gone into C and then output)

find a cycle by
- start at any vertex
- backtrack along incoming edges until repetition
"""

def another_topological_ordering(graph: DirectedGraph):
	C = []  # collection of vertices with no incoming edges
	# D is dictionary mapping each vertex to a number, # of incoming edges that come from vertices that have not yet
	# been output. Initially D[v] = total # of incoming edges to v
	D = defaultdict(int)
	for v in graph.getVertices():
		D[v]
		for w in graph.getNeighbors(v):
			D[w] += 1
	for v in graph.getVertices():
		if D[v] == 0:
			C.append(v)

	output = []
	while C:  # happen <= n times because n vertices
		vertex = C[0]
		C = C[1:]
		output.append(vertex)
		for w in graph.getNeighbors(vertex):  # happen <= m times
			D[w] -= 1
			if D[w] == 0:
				C.append(w)
	if len(output) == len(graph):
		return output
	else:
		# print(output)
		return False  # not acyclic

def another_topological_ordering_edge_with_value(graph: DirectedGraphWithWeights):
	C = []  # collection of vertices with no incoming edges
	# D is dictionary mapping each vertex to a number, # of incoming edges that come from vertices that have not yet
	# been output. Initially D[v] = total # of incoming edges to v
	D = defaultdict(int)
	for v in graph.getVertices():
		D[v]
		for w in graph.getNeighbors(v):
			D[w] += 1
	for v in graph.getVertices():
		if D[v] == 0:
			C.append(v)

	output = []
	while C:  # happen <= n times because n vertices
		vertex = C[0]
		C = C[1:]
		output.append(vertex)
		for w in graph.getNeighbors(vertex):  # happen <= m times
			D[w] -= 1
			if D[w[0]] == 0:
				C.append(w[0])
	if len(output) == len(graph):
		return output
	else:
		# print(output)
		return False  # not acyclic

if __name__ == "__main__":
	graph = DirectedGraph()
	graph.addEdges(
		[("a", "b"), ("a", "e"), ("a", "c"), ("b", "c"), ("c", "d"), ("c", "e"), ("c", "f"), ("d", "f"), ("e", "f"),
		 ("e", "g")])
	print(DFS_based_topological_ordering(graph))  # ['a', 'b', 'c', 'e', 'g', 'd', 'f']
	graph2 = DirectedGraph()
	graph2.addEdges(
		[("a", "b"), ("a", "e"), ("a", "c"), ("b", "c"), ("c", "d"), ("c", "e"), ("c", "f"), ("d", "f"), ("e", "f"),
		 ("e", "g"), ("c", "b")])
	print(DFS_based_topological_ordering(graph2))
	print(another_topological_ordering(graph))
	print(another_topological_ordering(graph2))

	g = DirectedGraphWithWeights()
	g.addEdges(
		[("S", "A", 3), ("S", "C", 2), ("A", "B", 5), ("C", "B", 9), ("C", "D", 4), ("B", "T", 2), ("D", "T", 3)])
	print(another_topological_ordering_edge_with_value(g))  # ['S', 'C', 'A', 'D', 'B', 'T']


def verbing(s):
  if s.__len__() >= 3:
      print(s[-3:])
      if s[-3:] != 'ing':
          s+='ing'
      else:
          s+= 'ly'
  return s

def not_bad(s):
  if 'not' in s and 'bad' in s:
      a = s.find('not')
      b = s.find('bad')
      if a < b :
          return s[:a] + 'good' +s[b+3:]
  return s

# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
#  a-front + b-front + a-back + b-back
def front_back(a, b):
    if len(a) % 2 == 0:
        middleA = int(len(a)/2)
    else:
        middleA = int(len(a)/2 +1)
    if len(b) % 2 == 0:
        middleB = int(len(b)/2)
    else:
        middleB = int(len(b)/2+1)
    return a[:middleA] + b[:middleB] + a[middleA:] + b[middleB:]

# Simple provided test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
    if got == expected:
        prefix = ' OK '
    else:
        prefix = '  X '
    print(prefix+" Got : "+repr(got)+" Expected : " +repr(expected))

# main() calls the above functions with interesting inputs,
# using the above test() to check if the result is correct or not.
def main():
  print('verbing')
  test(verbing('hail'), 'hailing')
  test(verbing('swiming'), 'swimingly')
  test(verbing('do'), 'do')

  print
  print('not_bad')
  test(not_bad('This movie is not so bad'), 'This movie is good')
  test(not_bad('This dinner is not that bad!'), 'This dinner is good!')
  test(not_bad('This tea is not hot'), 'This tea is not hot')
  test(not_bad("It's bad yet not"), "It's bad yet not")

  print
  print('front_back')
  test(front_back('abcd', 'xy'), 'abxcdy')
  test(front_back('abcde', 'xyz'), 'abcxydez')
  test(front_back('Kitten', 'Donut'), 'KitDontenut')

if __name__ == '__main__':
  main()


from copy import deepcopy
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.text import Annotation
from matplotlib.widgets import Button
import re

# import the seaborn module which is based on matplotlib to make our visualization more presentable
from seaborn import set

# set the default style
set()

#plt.rcParams['figure.figsize'] = (16, 7)
plt.style.use('ggplot')
global fig, ax

# Importing the dataset
data = pd.read_csv('DataTrial.csv')
print("Input Data and Shape")
print(data.shape)
data.head()

variable1 = 'Piedras'
variable2 = 'Agua'

# Getting the values and plotting it
f1 = data[variable1].values
f2 = data[variable2].values
sessionLabel = data['id'].values
X = np.array(list(zip(f1, f2)))
# Change variable format to a properly label name
xTitle = re.sub(r"(\w)([A-Z])", r"\1 \2", variable1)
yTitle = re.sub(r"(\w)([A-Z])", r"\1 \2", variable2)
xAxisName = "Porcentaje de " + re.sub(r"(\w)([A-Z])", r"\1 \2", variable1)
yAxisName = "Porcentaje de " + re.sub(r"(\w)([A-Z])", r"\1 \2", variable2)

# Euclidean Distance Caculator
def dist(a, b, ax=1):
    return np.linalg.norm(a - b, axis=ax)

# Number of clusters
k = 4
# X coordinates of random centroids
C_x = np.random.randint(0, np.max(X)-20, size=k)
# Y coordinates of random centroids
C_y = np.random.randint(0, np.max(X)-20, size=k)
C = np.array(list(zip(C_x, C_y)), dtype=np.float32)
print("Initial Centroids")
print(C)

# To store the value of centroids when it updates
C_old = np.zeros(C.shape)
# Cluster Lables(0, 1, 2)
clusters = np.zeros(len(X))
# Error func. - Distance between new centroids and old centroids
error = dist(C, C_old, None)
# Loop will run till the error becomes zero
while error != 0:
    # Assigning each value to its closest cluster
    for i in range(len(X)):
        distances = dist(X[i], C)
        cluster = np.argmin(distances)
        clusters[i] = cluster
    # Storing the old centroid values
    C_old = deepcopy(C)
    # Finding the new centroids by taking the average value
    for i in range(k):
        points = [X[j] for j in range(len(X)) if clusters[j] == i]
        C[i] = np.mean(points, axis=0)
    error = dist(C, C_old, None)

colors = ['r', 'g', 'b', 'y', 'c', 'm']

fig = plt.figure(figsize=(16, 7))
ax = plt.subplot()
for i in range(k):
    points = np.array([X[j] for j in range(len(X)) if clusters[j] == i])
    ax.scatter(points[:, 0], points[:, 1], s=7, c=colors[i])
ax.scatter(C[:, 0], C[:, 1], marker='.', s=200, c='#050505')

'''
for session in range(len(sessionLabel)):
    ax.annotate(str(sessionLabel[session]), xy=(f1[session], f2[session]),
                xytext=(f1[session]+0.5, f2[session]+0.5))
'''

def draw_scatterplot():
    for i in range(k):
        points = np.array([X[j] for j in range(len(X)) if clusters[j] == i])
        ax.scatter(points[:, 0], points[:, 1], s=7, c=colors[i])
        ax.scatter(C[:, 0], C[:, 1], marker='.', s=200, c='#050505')
        picker=True
    '''
    for session in range(len(sessionLabel)):
        ax.annotate(str(sessionLabel[session]), xy=(f1[session], f2[session]),
                    xytext=(f1[session]+0.5, f2[session]+0.5))
    '''
draw_scatterplot()
plt.xlabel(xAxisName)
plt.ylabel(yAxisName)
plt.title(xTitle+" VS "+yTitle)

# create and add an annotation object (a text label)
def annotate(axis, text, x, y):
    text_annotation = Annotation(text, xy=(x, y), xycoords='data')
    axis.add_artist(text_annotation)

# define the behaviour -> what happens when you pick a dot on the scatterplot by clicking close to it
def onpick(event):
    print("Hola")
    # step 1: take the index of the dot which was picked
    ind = event.ind

    # step 2: save the actual coordinates of the click, so we can position the text label properly
    label_pos_x = event.mouseevent.xdata
    label_pos_y = event.mouseevent.ydata

    # just in case two dots are very close, this offset will help the labels not appear one on top of each other
    offset = 0

    # if the dots are to close one to another, a list of dots clicked is returned by the matplotlib library
    for i in ind:
        # step 3: take the label for the corresponding instance of the data
        label = id[i]

        # step 4: log it for debugging purposes

        # step 5: create and add the text annotation to the scatterplot
        annotate(
            ax,
            label,
            label_pos_x + offset,
            label_pos_y + offset
        )

        # step 6: force re-draw
        fig.canvas.draw_idle()

        # alter the offset just in case there are more than one dots affected by the click
        offset += 0.01

# connect the click handler function to the scatterplot
fig.canvas.mpl_connect('pick_event', onpick)

# create the "clear all" button, and place it somewhere on the screen
ax_clear_all = plt.axes([0.0, 0.0, 0.1, 0.05])
button_clear_all = Button(ax_clear_all, 'Clear all')

# define the "clear all" behaviour
def onclick(event):
    # step 1: we clear all artist object of the scatter plot
    plt.cla()

    # step 2: we re-populate the scatterplot only with the dots not the labels
    draw_scatterplot()

    # step 3: we force re-draw
    plt.figure.canvas.draw_idle()

# Present the scatterplot
plt.show()

def _get_sysconfigdata_name():
    return os.environ.get('_PYTHON_SYSCONFIGDATA_NAME',
        '_sysconfigdata_{abi}_{platform}_{multiarch}'.format(
        abi=sys.abiflags,
        platform=sys.platform,
        multiarch=getattr(sys.implementation, '_multiarch', ''),
    ))


class Player:
	"""Class who define the position, the movement and the lifepoint of the player"""
	def __init__(self,labyrinth,position,movement,lifepoints,pushHex,speedHex):
		self.position = [18,18]				#Initial position
		self.movement = [0,0]				#Vector initial movement
		self.lifePoints = 50				#Initial life points
		self.movementNb = 1
		self.labyrinth = labyrinth
		self.speedHex = speedHex
		self.pushHex = pushHex

	def move(self,direction):
		"""Realise the move, if the case is available"""
		#Si le mouvement est vers le Nord
		#Et que l'on n'est pas sur la première ligne
		#On définit la case d'arrivé dans une nouvelle variable
		if direction == direction.n:
			if labyrinth.board[self.position[0]] !=0:
				arrivalCase = [self.position[0]-1,self.position[1]]
		if direction == direction.w:
			if labyrinth.board[self.position[1]] !=18:
				arrivalCase = [self.position[0],self.position[1]+1]
		if direction == direction.s:
			if labyrinth.board[self.position[0]] !=18:
				arrivalCase = [self.position[0]+1,self.position[1]]
		if direction == direction.e:
			if labyrinth.board[self.position[1]] !=0:
				arrivalCase = [self.position[0],self.position[1]-1]
		if 	labyrinth.board[arrivalCase] == 0:
			self.position = arrivalCase

		self.decreaseMovementNb()

	def chooseHex(self,hex):
		"""Choisit le sort à utiliser (enfin je crois)"""
		if hex == "pushHex":
			PushHex.push()
		elif hex == "speedHex":
			SpeedHex.speed()

	def raiseMovementNb(self):
		"""Augmente le nombre de mouvements disponible immédiatement"""
		#Mistake if the movement >=2
		assert self.movementNb <= 2, "We can't raise the movement number because he is >=2 "
		#MovementNb raise  of 1
		self.movementNb += 1

	def decreaseMovementNb(self):
		"""Diminue le nombre de mouvements disponible immédiatement"""
		#Mistake if the movement =0
		assert self.movementNb != 0, "We can't decrase the movement number because he is null "
		#MovementNb decrease  of 1
		self.movementNb -= 1

	def erode(self):
		"""The life point decrease of 1 point, if the nomber of life point >0"""
		#Mistake if lifepoint = 0
		assert self.lifePoints != 0, "Le nombre de vie est nul!!!! On ne peux pas le diminuer de 1"
		#Lifepoint decrease of 1
		self.lifePoints -= 1


from graphics import *
def main():
    win=GraphWin('The regression line',500,500)
    win.setBackground('pink')
    win.setCoords(-20.0,-20.0,20.0,20.0)
    t0=Entry(Point(0.0,0.0),10)
    t0.draw(win)
    t1=Text(Point(0.0,-15.0),'Click here to enter the interface.')
    t1.draw(win)
    win.getMouse()
    t0.undraw()
    t1.undraw()
    t2=Line(Point(-19.0,0.0),Point(19.0,0.0))
    t3=Line(Point(0.0,-19.0),Point(0.0,19.0))
    t2.setArrow('last')
    t3.setArrow('last')
    t2.draw(win)
    t3.draw(win)
    k1=Text(Point(1.0,-1.0),'0')
    k2=Text(Point(1.0,19.0),'y')
    k3=Text(Point(19.0,-1.0),'x')
    k4=Text(Point(0.0,-19.5),'Click here to get out of the interface.')
    k1.draw(win)
    k2.draw(win)
    k3.draw(win)
    k4.draw(win)
    n=eval(t0.getText())
    X=0
    Y=0
    Z=0
    W=0
    for i in range(n):
        p=win.getMouse()
        p.draw(win)
        x=p.getX()
        y=p.getY()
        X=X+x
        Y=X+x
        Z=Z+x*y
        W=W+x**2
    x0=float(X)/n
    y0=float(Y)/n
    m=(Z-n*x0*y0)/(W-n*(x0**2))
    x1=x0+15.0
    y1=y0+15.0*m
    x2=x0-15.0
    y2=y0-15.0*m
    t4=Text(Point(-15.0,-15.0),'Done')
    t5=Rectangle(Point(-17.0,-16.0),Point(-13.0,-14.0))
    t4.draw(win)
    t5.draw(win)
    win.getMouse()
    l=Line(Point(x1,y1),Point(x2,y2))
    l.draw(win)
    win.getMouse()
    win.close()
main()


import threading, socket, json, time, random, sys, argparse

width = 80
height = 24

ids = ['#', '@', '&', '+', '%', '$', '£']

clients = []

game = {
  'players': [],
  'bullets': [],
  'walls': [],
  'exps': []
}

""" Example
game = {
  'players': [{pos: {x: 5, y: 5}, c: character, s: score, d: dead}, None, None, None],
  'bullets': [{pos: {x: 5, y: 5}, dir: direction, id: playerid}],
  'walls': []
}
"""

parser = argparse.ArgumentParser(description = 'Server for Text-MOBA')
parser.add_argument('address', help = 'Server bind address: [ip]:[port]')
parser.add_argument('-p', '--players', type = int, help = 'Max players')
parser.add_argument('-m', '--map', help = 'Json file containing map')
parser.add_argument('-b', '--bullets', type = int, help = 'Set max bullets in air per player, 0 to disable')
parser.add_argument('-r', '--rockets', type = int, help = 'Set max rockets in air per player, 0 to disable')
args = parser.parse_args()

ip, port = args.address.split(":")
mapFile = '../map.json' if not args.map else args.map
maxPlayers = 4 if not args.players else args.players
maxBullets = 15 if args.bullets == None else args.bullets
maxRockets = 1 if args.rockets == None else args.rockets

with open(mapFile) as f:
  mapData = json.load(f)
  game['walls'] = mapData['walls']
  width, height = mapData['size']

for index in range(0,maxPlayers): # Create player spots in game and client objects
  game['players'].append(None)
  clients.append(None)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((ip, int(port)))
s.listen(16)

def acceptClients():
  while True:
    clientsocket, address = s.accept()

    for index in range(0, len(game['players'])):
      if game['players'][index] == None:
        playerid = index
        break
      else:
        playerid = -1

    if playerid == -1:
      clientsocket.send(bytes("full;", 'utf-8'))
      clientsocket.close()
      print(f'Connection from {address} rejected.')
    else:
      print(f'Connection from {address}. Assigning to player {playerid}')
      clientsocket.send(bytes(json.dumps({'id': playerid, 'w': width, 'h': height, 'walls': game['walls']}) + ";", 'utf-8'))

      if playerid + 1 > len(ids):
        playerChar = 65 + playerid - len(ids)
      else:
        playerChar = ids[playerid]
      if not playerid == -1:
        game['players'][playerid] = {
          'pos': {'x': random.randint(1, width - 2), 'y': random.randint(1, height - 2)},
          'c': playerChar, # Character
          's': 0 # Score
          #'d': 0 # Is dead
        }
        clients[playerid] = clientsocket

        threading.Thread(target = listenToPlayer, args = (clientsocket, playerid), daemon = True).start()

def listenToPlayer(clientsocket, playerid):
    while True:
      """
      recv = {
      do: move,
      payload: dir
      }
      """
      data = ""
      try:
        while True:
          data += clientsocket.recv(1024).decode('utf-8')

          if data[-1] == ";":
            break
      except:
        print(f'Player {playerid}: Disconnected')
        game['players'][playerid] = None
        clients[playerid] = None
        clientsocket.close()
        break

      try:
        data = json.loads(data[:-1])
        action = data['a']
        payload = data['p']

        pos = game['players'][playerid]['pos']

        if action == 'm': # Move
          if payload == 0 and pos['y'] - 1 > 0 and not any([pos['x'], pos['y'] - 1] == wall for wall in game['walls']): # Up
            pos['y'] -= 1
          if payload == 1 and pos['x'] + 1 < width - 1 and not any([pos['x'] + 1, pos['y']] == wall for wall in game['walls']): # Right
            pos['x'] += 1
          if payload == 2 and pos['y'] + 1 < height - 1 and not any([pos['x'], pos['y'] + 1] == wall for wall in game['walls']): # Down
            pos['y'] += 1
          if payload == 3 and pos['x'] - 1 > 0 and not any([pos['x'] - 1, pos['y']] == wall for wall in game['walls']): # Left
            pos['x'] -= 1

        if action == 's':
          bulletsCount = [0, 0] # Bullets, rockets
          for bullet in game['bullets']:
            if bullet['id'] == playerid:
              if bullet['r']:
                bulletsCount[1] += 1
              else:
                bulletsCount[0] += 1

          if bulletsCount[0] < maxBullets and not payload[1]:
            game['bullets'].append({'pos': { 'x': pos['x'], 'y': pos['y'] }, 'dir': payload[0], 'id': playerid, 'r': payload[1]})
          elif bulletsCount[1] < maxRockets and payload[1]:
            game['bullets'].append({'pos': { 'x': pos['x'], 'y': pos['y'] }, 'dir': payload[0], 'id': playerid, 'r': payload[1]})

      except:
        pass

threading.Thread(target = acceptClients, daemon = True).start()

def explode(pos, bulletid): # pos = [x,y]
  x = pos['x']
  y = pos['y']

  areaOfEfect = [
    [x, y],
    [x, y - 1],
    [x + 1, y - 1],
    [x + 1, y],
    [x + 1, y + 1],
    [x, y + 1],
    [x - 1, y + 1],
    [x - 1, y],
    [x - 1, y - 1],
    [x + 2, y],
    [x - 2, y],
    [x, y - 2],
    [x, y + 2]
  ]

  for index in range(0, len(game['players'])):
    player = game['players'][index]

    if not player == None and any([player['pos']['x'], player['pos']['y']] == item for item in areaOfEfect):
      player['pos'] = {
        'x': random.randint(1, width - 2),
        'y': random.randint(1, height - 2)
      }

      if bulletid == index:
        player['s'] -= 1
      else:
        game['players'][bulletid]['s'] += 1

  game['exps'].append(pos)

while True: # Update clients
  try: # Sorry for the mess
    for bullet in game['bullets']: # Move bullets
      if bullet['dir'] == 0:
        bullet['pos']['y'] -= 1
      elif bullet['dir'] == 1:
        bullet['pos']['x'] += 1
      elif bullet['dir'] == 2:
        bullet['pos']['y'] += 1
      elif bullet['dir'] == 3:
        bullet['pos']['x'] -= 1

    for index in range(0, len(game['exps'])): # Remove explosions
      if random.randint(1, 100) > 90: # 10% change to clear explosion per tick
        game['exps'][index] = -1

    game['exps'] = [item for item in game['exps'] if not item == -1]

    for index in range(0, len(game['bullets'])): # Mark bullets to be removed
      if game['bullets'][index]['pos']['y'] <= 0 or game['bullets'][index]['pos']['x'] >= width - 1 or game['bullets'][index]['pos']['y'] >= height - 1 or game['bullets'][index]['pos']['x'] <= 0:
        if game['bullets'][index]['r']:
          explode(game['bullets'][index]['pos'], game['bullets'][index]['id'])

        game['bullets'][index]['pos'] = -1 # Collision with borders

      elif any([game['bullets'][index]['pos']['x'], game['bullets'][index]['pos']['y']] == wall for wall in game['walls']):
        if game['bullets'][index]['r']:
          explode(game['bullets'][index]['pos'], game['bullets'][index]['id'])

        game['bullets'][index]['pos'] = -1 # Collision with walls

    game['bullets'] = [item for item in game['bullets'] if not item['pos'] == -1] # Remove bullets

    for index in range(0, len(game['players'])): # Check if player dies
      player = game['players'][index]
      if not player == None:
        for bullet in game['bullets']:
          if player['pos'] == bullet['pos'] and not bullet['id'] == index:
            bulletid = bullet['id']

            game['players'][index]['pos'] = {
              'x': random.randint(1, width - 2),
              'y': random.randint(1, height - 2)
            } # Respawn player

            game['players'][bulletid]['s'] += 1 # Give a point

    for index in range(0, len(game['players'])): # Send game state to players
      if not clients[index] == None:
        clients[index].send(bytes(json.dumps(game) + ";", 'utf-8'))

    time.sleep(0.1)
  except KeyboardInterrupt:
    for client in clients:
      if not client == None:
        client.close()
    sys.exit()


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

""" pastetree.py
    Testing the display of pastes in a 'tree' format.
    root ->
        child1 ->
            child1
            child2
        child2 ->
            child1

    -Christopher Welborn 03-27-2014
"""

from docopt import docopt
from collections import namedtuple
import os
import sys

# A little hack to use django_init.
scriptsdir = os.path.abspath(os.path.join(sys.path[0], '../../../scripts'))
sys.path.insert(1, scriptsdir)

# Import local stuff.
try:
    import django_init
except ImportError as eximp:
    print('\nUnable to import local stuff!\n'
          'This won\'t work!\n{}'.format(eximp))
    sys.exit(1)
# Initialize Django..
try:
    if not django_init.init_django():
        print('\nUnable to initialize django environment!')
        sys.exit(1)
except Exception as ex:
    print('\nUnable to initialize django environment!\n{}'.format(ex))
    sys.exit(1)

# Import django stuff
from apps.paste.models import wp_paste, repr_header

NAME = 'pastetree.py'
VERSION = '1.0.0'
VERSIONSTR = '{} v. {}'.format(NAME, VERSION)
SCRIPT = os.path.split(sys.argv[0])[-1]

USAGESTR = """{versionstr}
    Usage:
        {script} [-h | -v]

    Options:
        -h,--help     : Show this help message.
        -v,--version  : Show version.
""".format(script=SCRIPT, versionstr=VERSIONSTR)

IterPasteResult = namedtuple('IterResult', ['level', 'paste'])

def main(argd):
    """ Main entry point, expects doctopt arg dict as argd """

    x = 0
    print(repr_header())
    for iterresult in iter_pastes():
        print_pasteresult(iterresult)
        x += 1

    print('Printed {} pastes...'.format(x))
    return 0

def iter_paste_children(paste, level=1):
    """ Iterate over all children of a paste, and children's children. """
    for p in paste.children.order_by('publish_date'):
        yield IterPasteResult(level, p)
        if p.children.count() > 0:
            yield from iter_paste_children(p, level=level + 1)

def iter_pastes(startpastes=None):
    """ Iterate over all pastes that have no parent.
        Given a 'startpastes' list, it will start from that paste only.
    """
    if startpastes is None:
        pastes = wp_paste.objects.filter(parent=None)
        pastes = pastes.order_by('publish_date')
    else:
        pastes = [startpastes]

    for p in pastes:
        yield IterPasteResult(0, p)
        if p.children.count() > 0:
            yield from iter_paste_children(p, level=1)

def print_pasteresult(iresult):
    """ Print a tuple result from iter_children/iter_pastes """
    indention = '  ' * iresult.level
    print('{}{!r}'.format(indention, iresult.paste))

if __name__ == '__main__':
    mainret = main(docopt(USAGESTR, version=VERSIONSTR))
    sys.exit(mainret)


#!/usr/bin/env python
import rospy
import sys
from std_msgs.msg import String
from std_msgs.msg import Empty
from geometry_msgs.msg import Twist

import roslib; roslib.load_manifest('ardrone_python')
from ardrone_autonomy.msg import Navdata

fw = open('BasicControlUP.txt', 'w')

# fw.write("time,battery,vx,vy,z,yaw\n")
fw.write("state,timeDrone,time, Battery,vx,vy,vz,ax,ay,az,altd,rotz,roty,rotx\n")

def callback(navdata):
    t = navdata.header.stamp.to_sec()
    #print("received odometry message: time=%f battery=%f vx=%f vy=%f z=%f RZ=%f RY=%f RX=%f" % (
    #t, navdata.batteryPercent, navdata.vx, navdata.vy, navdata.altd, navdata.rotZ, navdata.rotY, navdata.rotX))
    fw.write("%f,%f, %f, %f, %f ,%f ,%f, %f, %f,%f,%f,%f,%f,%f\n" % ( navdata.state,navdata.tm,
    t, navdata.batteryPercent, navdata.vx, navdata.vy,navdata.vz,navdata.ax,navdata.ay,navdata.az, navdata.altd, navdata.rotZ, navdata.rotY, navdata.rotX))
    # fw.write("time %f, Battery%f\n" % (t, navdata.batteryPercent))
    # fw.write("%f %f"%(t,navdata.batteryPercent))

def takeoff():
    takeoff_pub.publish(Empty())

def land():
    land_pub.publish(Empty())

def forward():
    fw.write("inside--Forward\n")
    twist = Twist()
    twist.linear.x=1.0
    velocity_pub.publish(twist)

def backward():
    fw.write("inside--backward\n")
    twist = Twist()
    twist.linear.x=-1.0
    velocity_pub.publish(twist)

def right():
    fw.write("inside--right\n")
    twist = Twist()
    twist.linear.y = 1.0
    velocity_pub.publish(twist)

def left():
    fw.write("inside--Left\n")
    twist = Twist()
    twist.linear.y =-1.0
    velocity_pub.publish(twist)

def rotatep():
    fw.write("inside--rotationPositive\n")
    twist = Twist()
    twist.angular.z = 1.0
    velocity_pub.publish(twist)

def rotaten():
    fw.write("inside--RotationNegative\n")
    twist = Twist()
    twist.angular.z = -1.0
    velocity_pub.publish(twist)

def flyUp():
    fw.write("inside_flyup\n")
    twist = Twist()
    twist.linear.z = 1.0
    velocity_pub.publish(twist)

def flyDown():
    fw.write("inside_flydown")
    twist = Twist()
    twist.linear.z = -1.0
    velocity_pub.publish(twist)

def circle():
    twist = Twist()
    twist.linear.x=1.0
    twist.angular.z=1.0
    velocity_pub.publish(twist)

def autonomous():
    twist = Twist()
    twist.linear.x=1.0
    rospy.sleep(5.0)
    velocity_pub.publish(twist)

def square():
    print("inside square")
    twist= Twist()
    twist.linear.x=1.0 #forward
    twist.angular.z=1.0 #turn left
    twist.linear.x = 1.0  # forward
    twist.angular.z = 1.0  # turn left
    twist.linear.x = 1.0  # forward
    twist.angular.z = 1.0  # turn left
    twist.linear.x = 1.0  # forward
    twist.angular.z = 1.0  # turn left
    velocity_pub.publish(twist)

    twist.linear.y=-1.0 #

    twist.linear.x=-1.0
    twist.linear.y=1.0
    twist.linear.x=1.0

def stop():
    twist = Twist()
    twist.linear.x=0.0
    twist.linear.y=0.0
    twist.angular.z=0.0
    velocity_pub.publish(twist)

def menu():
    print ("t: takeoff")
    print ("l: land")
    print("e:forward")
    print("d:backward")
    print("a:left")
    print("f:right")
    print("p:protate")
    print("o:nrotate")
    print ("c:circle")
    print ("q: square")
    print("u:flyUp")
    print("i:flyDown")
    print ("s: stop\n")

if __name__ == '__main__':
    rospy.init_node('ardrone_control_node', anonymous=True)

    takeoff_pub = rospy.Publisher("/ardrone/takeoff", Empty, queue_size=10 )
    land_pub = rospy.Publisher("ardrone/land", Empty, queue_size=10 )
    velocity_pub = rospy.Publisher("cmd_vel", Twist, queue_size=10 )
    #rate = rospy.Rate(10) # 10hz

    # subscribe to navdata (receive from quadrotor)
    rospy.Subscriber("/ardrone/navdata", Navdata, callback)

    try:
        while not rospy.is_shutdown():
            menu()
            #key= input("press a key for action")
            key=sys.stdin.read(1)
            if (key == str('t')):
                takeoff()
            elif (key == str('l')):
                land()
            elif (key == str('c')):
                circle()
            elif(key ==str('q')):
                 square()
            elif (key == str('s')):
                stop()
            elif (key == str('e')):
                forward()
            elif (key == str('d')):
                backward()
            elif (key == str('a')):
                left()
            elif (key == str('f')):
                right()
            elif (key == str('p')):
                rotatep()
            elif (key == str('o')):
                rotaten()
            elif (key == str('u')):
                flyUp()
            elif (key == str('i')):
                flyDown()
    except rospy.ROSInterruptException:
        pass


# Base CNN imports
import pandas as panda
import os
import tensorflow as tf
import numpy as np
import random
import matplotlib.pyplot as plt
from numbers import Number
from sklearn.externals import joblib

# For parameter tuning
import math

# Keras
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import InputLayer, Input, concatenate, BatchNormalization
from tensorflow.python.keras.layers import Reshape, MaxPooling2D, Lambda, TimeDistributed
from tensorflow.python.keras.layers import Conv2D, Dense, Flatten, CuDNNLSTM, ConvLSTM2D
from tensorflow.python.keras.callbacks import TensorBoard
from tensorflow.python.keras.optimizers import Adam
from tensorflow.python.keras.models import save_model, load_model, Model
from tensorflow.python.keras.utils import multi_gpu_model
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from itertools import chain

import horovod.keras as hvd

mfccsList = []
trackList = []

sequence_length = 30

for dataset in sorted(os.listdir("csvs")):
	data_dir = 'csvs/{}'.format(dataset)
	data_files = os.listdir(data_dir)
	for file in sorted(data_files):
		trackList.append(os.path.join(data_dir, file))

for dataset in sorted(os.listdir("mfccs")):
	data_dir = 'mfccs/{}'.format(dataset)
	data_files = os.listdir(data_dir)
	for file in sorted(data_files):
		mfccsList.append(os.path.join(data_dir, file))

input_first = (Input(shape=(sequence_length, 13), name='mfccInput'))
input_next = CuDNNLSTM(13, input_shape=(sequence_length, 13), return_sequences=True, name="LSTM_aggregation")(input_first)
input_next = CuDNNLSTM(13, input_shape=(sequence_length, 13), return_sequences=True, name="LSTM_aggregation2")(input_next)
input_next = CuDNNLSTM(13, input_shape=(sequence_length, 13), return_sequences=False, name="LSTM_aggregation3")(input_next)
predictions = (Dense(6, activation="linear", name="predictions", input_shape=(13,)))(input_next)

# Use the Adam method for training the network.
# We want to find the best learning-rate for the Adam method.
optimizer = Adam(lr=1e-4)
model = Model(inputs=[input_first], outputs=predictions)
# model = load_model('09_12_LSTM_Regression_Model')
# In Keras we need to compile the model so it can be trained.
#model.compile(optimizer=optimizer,
#			  loss='mean_squared_error',
#			  metrics=['mse'])

# Horovod: initialize Horovod.
hvd.init()

# Horovod: pin GPU to be used to process local rank (one GPU per process)
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.visible_device_list = str(hvd.local_rank())
K.set_session(tf.Session(config=config))

optimizer = hvd.DistributedOptimizer(optimizer)

model.compile(optimizer=optimizer,
	loss='mean_squared_error',
	metrics=['mse'])

callbacks = [
	# Horovod: broadcast initial variable states from rank 0 to all other processes.
	# This is necessary to ensure consistent initialization of all workers when
	# training is started with random weights or restored from a checkpoint.
	hvd.callbacks.BroadcastGlobalVariablesCallback(0)
]

#pmodel = multi_gpu_model(model, gpus=4)
#pmodel.compile(optimizer=optimizer,
#			  loss='mean_squared_error',
#			  metrics=['mse'])

scaler = MinMaxScaler(feature_range=(0.0, 1.0))
fitter = StandardScaler()

counter = 0
for mfcc, track in zip(mfccsList, trackList):
	mfccs = np.transpose(np.load(mfcc))
	sixDistances = np.load(track)
	fitter.partial_fit(mfccs)
	scaler.partial_fit(sixDistances)
	counter += 1

homepath = os.environ["HOME"]
path_stdscaler = '{}/11_28_StandardScaler.pkl'.format(homepath)
path_mmscaler = '{}/11_28_MinMaxScaler.pkl'.format(homepath)
joblib.dump(fitter, path_stdscaler)
joblib.dump(scaler, path_mmscaler)

fileIndex = 0
for mfcc, track in zip(mfccsList, trackList):

	if (fileIndex < counter - 3):
		print(mfcc)
		print(track)
		mfccs = np.transpose(np.load(mfcc))
		real_sixDistances_array = np.load(track)
		print(len(mfccs))
		print(real_sixDistances_array.shape)

		mfcc_array = []
		sixDistances = []

		mfccs = fitter.fit_transform(mfccs)
		real_sixDistances_array = scaler.fit_transform(real_sixDistances_array)

		for i in range(len(real_sixDistances_array)):
			if (i > sequence_length-1):

				sample_mfcc = mfccs[i-sequence_length:i]
				mfcc_array.append(sample_mfcc)

				sixDistances.append(real_sixDistances_array[i])

		real_mfcc_array = np.asarray(mfcc_array, dtype=np.float32)
		real_sixDistances_array = np.asarray(sixDistances, dtype=np.float32)

		index = np.shape(real_sixDistances_array)[0]
		crossValidation = index-500
		testingSet = index

		validation_data = (real_mfcc_array[crossValidation:testingSet], real_sixDistances_array[crossValidation:testingSet])

		history = model.fit(x=real_mfcc_array[0:crossValidation],
							y=real_sixDistances_array[0:crossValidation],
							epochs=1000,
							batch_size=2048,
							validation_data=validation_data)

		path_best_model = '{}/11_28_LSTM_Regression_Model_SAIL_SPEECH_1M.keras'.format(homepath)
		if hvd.rank() == 0:
			model.save(path_best_model)

	fileIndex += 1


import ite
import numpy as np
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F

class Optim_noise(nn.Module):
    def __init__(self, x_dim, y_dim):  # feature0 = 3, feature1 = 6
        super(Optim_noise, self).__init__()
        self.x_dim = x_dim
        self.y_dim = y_dim

        self.mlp = nn.Sequential(
            nn.Linear(self.x_dim, 100),
            # nn.ReLU(True),
            nn.Tanh(),
            nn.Dropout(p=0.2),
            nn.Linear(100, 100),
            # nn.ReLU(True),
            nn.Tanh(),
            nn.Dropout(p=0.2),
            nn.Linear(100, self.y_dim),
            # nn.ReLU(),

            )

    def forward(self, X):
        if X.dim() > 2:
            X = X.view(X.size(0), -1)
        out = self.mlp(X)
        # print(out)

        return out

from torch.autograd import Variable

def ml_inf2(emb,labels,ee,st):
    # a = e
    # print('as')

    # if (ee == 1 or ee == 10 or ee == 20 or ee == 25 or ee == 27 or ee == 29):
    # if (ee > 0) and (st == 'train'):
    if (ee==1 or ee%15==0) and (st=='train'):
        raw_emb = emb.clone()
        noise_num = emb.shape[0] * emb.shape[1]
        raw_emb = Variable(raw_emb, requires_grad=True)

        model = Optim_noise(noise_num, noise_num).cuda()
        bata1 = torch.ones(noise_num).float().cuda()
        # print(emb.shape[0]*emb.shape[1])

        emb = Variable(emb, requires_grad=True)

        optimizer = torch.optim.Adam([
            dict(params=model.parameters()),
        ], lr=0.01,weight_decay=1e-5)

        import random

        lam = 1
        a = []
        leibie = 6
        for j in range(emb.shape[0]//leibie):
            for i in range(leibie):
                a.append(i)
        # print(len(a))
        while len(a)<emb.shape[0]:
            a.append(0)
        # print(a.shape)

        random.shuffle(a)

        c = torch.tensor(a).reshape(emb.shape[0]).cuda()

        for e in range(50):

            optimizer.zero_grad()
            model.train()

            injection_noise = model(bata1).reshape(emb.shape)

            new_emb = injection_noise + emb #0.5*F.l1_loss(new_emb,raw_emb) +F.l1_loss(new_emb,raw_emb) +

            # loss1 = nn.MSELoss()(new_emb,raw_emb) +lam*nn.CrossEntropyLoss()(new_emb,c) #nn.KLDivLoss()(new_emb,raw_emb)
            loss2 = nn.MSELoss()(new_emb,raw_emb)
            loss3 = nn.CrossEntropyLoss()(new_emb,c)
            # loss3 = F.nll_loss(nn.Sigmoid()(new_emb),c)
            loss1 = 1*loss2 + lam*loss3
            loss1.backward(retain_graph=True)
            # print([x.grad for x in optimizer.param_groups[0]['params']])
            optimizer.step()
            print(loss1)

        # injection_noise = 0.5*torch.rand(emb.shape).cuda()
        # injection_noise = torch.zeros(emb.shape).cuda()
        np.save('./noise.npy',injection_noise.cpu().detach().numpy())
        # print('youhua',injection_noise)

    else:
        injection_noise = torch.from_numpy(np.load('./noise.npy')).cuda()
        # print('wuyouhua',injection_noise)
        # a=a
    # injection_noise = torch.zeros(emb.shape).cuda()

    return injection_noise

# s=ml_inf2(torch.randn([200,200]).cuda(),torch.ones([200,1]).cuda())
# print(s)


"""Functions for custom GPs.

Custom implementations of main routines used for GP regression.
"""
import numpy as np
import sklearn.metrics
from scipy.linalg import solve_triangular
from scipy.sparse.linalg import eigsh
import time
import matplotlib.pyplot as plt
from profit.sur.backend.gpfunc import gpfunc

log2pihalf = 0.5*np.log(2.0*np.pi)

def k(xa, xb, l):
    return np.exp(-(xa-xb)**2 / (2.0*l**2))

# derivatives of kernel
def dkdxa(xa, xb, l):
    return -(xa-xb)/l**2*np.exp(-(xa-xb)**2 / (2.0*l**2))

def dkdxb(xa, xb, l):
    return -(xb-xa)/l**2*np.exp(-(xa-xb)**2 / (2.0*l**2))

def dkdxadxb(xa, xb, l):
    return (1.0/l**2 - (xa-xb)**2/l**4)*np.exp(-(xa-xb)**2 / (2.0*l**2))

# compute log-likelihood according to RW, p.19
def solve_cholesky(L, b):
    return solve_triangular(
        L.T, solve_triangular(L, b, lower=True, check_finite=False),
        lower=False, check_finite=False)

def invert_cholesky(L):
    """Inverts a positive-definite matrix A based on a given Cholesky decomposition
       A = L^T*L. Arguments: L"""
    return solve_triangular(
        L.T, solve_triangular(L, np.eye(L.shape[0]), lower=True, check_finite=False),
        lower=False, check_finite=False)

def invert(K, neig=0, tol=1e-10):
    """Inverts a positive-definite matrix A using either an eigendecomposition or
       a Cholesky decomposition, depending on the rapidness of decay of eigenvalues"""
    if (neig <= 0 or neig > 0.05*K.shape[0]):
        try:
            return invert_cholesky(np.linalg.cholesky(K))
        except:
            print('Warning! Fallback to eig solver!')
    w, Q = eigsh(K, neig, tol=tol)
    while np.abs(w[0]-tol) > tol:
        if neig > 0.05*K.shape[0]:  # TODO: get more stringent criterion
            try:
                return invert_cholesky(np.linalg.cholesky(K))
            except:
                print('Warning! Fallback to eig solver!')
        neig = 2*neig
        w, Q = eigsh(K, neig, tol=tol)
    return Q.dot(np.diag(1.0/w).dot(Q.T))

def build_K(x, x0, th, K):
    gpfunc.build_k_sqexp(x.T, x0.T, th, K)

def build_dKdth(dim, x, x0, th, K, dK):
    gpfunc.build_dkdth_sqexp(dim+1, x.T, x0.T, K, dK)

def nll_chol(hyp, x, y, K, dK=None, build_K=build_K):
    """Computes the negative log-likelihood.

    hyp: Hyperparameters (sig2f, sig2n, theta)
    x: Training points
    y: Function values at training points
    K: Empty matrix to store covariance
    dK: optional empty matrix to store covariance derivatives (default: None)
    build_K: Function to build covariance matrix (default: build_K)

    Computation according to Rasmussen&Williams 2006, p. 19, 113-114 .
    Default hyperparemeters are a tuple containing inverse squared length
    scales for each dimension of x.
    """
    nd = len(hyp) - 2
    nx = len(x)
    build_K(x, x, hyp[:-2], K)
    Ky = hyp[-2]*(K + hyp[-1]*np.diag(np.ones(nx)))
    L = np.linalg.cholesky(Ky)
    alpha = solve_cholesky(L, y)
    nll = 0.5*y.T.dot(alpha) + np.sum(np.log(L.diagonal())) + nx*log2pihalf

    if dK is None:
        return nll.item()

    # This is according to Rasmussen&Williams 2006, p. 114, Eq. (5.9).
    # We try to minimize the number of additional DxD matrices to store.
    # In particular, dK contiainig derivatives is overwritten for each
    # kernel hyperparameter in hyp[:-2].
    KyinvaaT = invert_cholesky(L)
    KyinvaaT -= np.outer(alpha, alpha)

    dnll = np.empty(len(hyp))
    for i in np.arange(nd):
        build_dKdth(i, x, x, hyp[:-2], K, dK)
        dnll[i] = 0.5*np.einsum('jk,kj', KyinvaaT, dK)

    # Derivatives w.r.t. sig2f and sig2n
    # TODO: optimize
    dnll[-2] = 0.5*np.einsum('jk,kj', KyinvaaT, K + hyp[-1]*np.diag(np.ones(nx)))
    dnll[-1] = 0.5*hyp[-2]*np.einsum('jk,kj', KyinvaaT, np.diag(np.ones(nx)))

    return nll.item(), dnll

def nll(hyp, x, y, neig=0, build_K=build_K):
    K = np.empty((len(x), len(x)))
    build_K(x, x, np.abs(hyp[:-1]), K)
    Ky = K + np.abs(hyp[-1])*np.diag(np.ones(len(x)))
    if (neig <= 0 or neig > 0.05*len(x)):
        try:
            return nll_chol(hyp, x, y, build_K)
        except:
            print('Warning! Fallback to eig solver!')
    w, Q = eigsh(Ky, neig, tol=max(1e-6*np.abs(hyp[-1]), 1e-15))
    while np.abs(w[0]-hyp[-1])/hyp[-1] > 1e-6 and neig < len(x):
        if neig > 0.05*len(x):  # TODO: get more stringent criterion
            try:
                return nll_chol(hyp, x, y, build_K)
            except:
                print('Warning! Fallback to eig solver!')
        neig =  2*neig
        w, Q = eigsh(Ky, neig, tol=max(1e-6*hyp[-1], 1e-15))

    alpha = Q.dot(np.diag(1.0/w).dot(Q.T.dot(y)))
    # print("l ", hyp[0])
    # print("sigm_noise2 ", hyp[-1])
    # print("\n\nalpha", alpha)
    # print("w ", w)
    # print("log w ", np.log(w))
    # print("sum log w ", np.sum(np.log(w)))
    # print("hyp-1 ", np.abs(hyp[-1]))

    ret = 0.5*y.T.dot(alpha) + 0.5*(np.sum(np.log(w)) + (len(x)-neig)*np.log(np.abs(hyp[-1])))
    return ret.item()

def predict_f(hyp, x, y, xtest, neig=0):
    Ktest = sklearn.metrics.pairwise.rbf_kernel(xtest, x, 0.5/hyp[0]**2)
    Ktest2 = sklearn.metrics.pairwise.rbf_kernel(xtest, xtest, 0.5/hyp[0]**2)
    K = sklearn.metrics.pairwise.rbf_kernel(x, x, 0.5/hyp[0]**2)
    Ky = K + hyp[-1]*np.diag(np.ones(len(x)))
    Kyinv = invert(Ky, neig, 1e-6*hyp[-1])
    Ef = Ktest.dot(Kyinv.dot(y))
    varf = (Ktest2 - Ktest.dot(Kyinv.dot(Ktest.T)))
    return Ef, varf

def predict_dfdx(hyp, x, y, xtest, neig=8, dkdxa=dkdxa, dkdxadxb=dkdxadxb):
    Ktest = np.fromfunction(lambda i, j: dkdxa(xtest[i,0], x[j,0], hyp[0]), (len(xtest), len(x)), dtype=int)
    Ktest2 = np.fromfunction(lambda i, j: dkdxadxb(xtest[i,0], xtest[i,0], hyp[0]), (len(xtest), len(xtest)), dtype=int)
    K = sklearn.metrics.pairwise.rbf_kernel(x, x, 0.5/hyp[0]**2)
    Ky = K + hyp[-1]*np.diag(np.ones(len(x)))
    Kyinv = invert(Ky, neig, 1e-6*hyp[-1])
    Edfdx = Ktest.dot(Kyinv.dot(y))
    vardfdx = Ktest2 - Ktest.dot(Kyinv.dot(Ktest.T))
    return Edfdx, vardfdx

def dk_logdl(xa, xb, l): # derivative of the kernel w.r.t log lengthscale
    dk_dl = ((xa - xb)**2.0 * np.exp(-(xa-xb)**2.0/(2 * l**2))) / l**3
    dk_logdl = dk_dl * np.log(10) * 10**(np.log10(l)) # from log lengthscale to lengthscale
    return dk_logdl

def dkdl(xa, xb, l): # derivative of the kernel w.r.t lengthscale
    dk_dl = ((xa - xb)**2.0 * np.exp(-(xa-xb)**2.0/(2 * l**2))) / l**3
    return dk_dl

def get_marginal_variance_BBQ(hess_inv, new_hyp, ntrain, ntest, xtrain, xtest, Kyinv, ytrain, varf, plot_result = False):

    tic = time.time()
    # Step 1 : invert the res.hess_inv to get H_tilde
    H_tilde = invert(hess_inv)
    # Step 2 Get H
    H = np.zeros((len(H_tilde), len(H_tilde)))
    for i in np.arange(len(H_tilde)):
        for j in np.arange(len(H_tilde)):
            H[i,j] = (1/np.log(10)**2) * H_tilde[i,j]/(new_hyp[i]*new_hyp[j])
    # Step 3 get Sigma
    H_inv = invert(H)
    sigma_m = H_inv
    tac = time.time()
    print("time consumed : ", (tac - tic)*1000," ms")

    ######################### Build needed Kernel Matrix #########################

    # Kernel K(train, train) of shape (ntrain, ntrain)
    K = np.empty((ntrain, ntrain))
    for i in np.arange(len(xtrain)):
        for j in np.arange(len(xtrain)):
            K[i, j] = k(xtrain[i], xtrain[j], new_hyp[0])

    # Kernel K_star(test, train) of shape (ntest, ntrain)
    # note that K_star(test, train) = K_star.T(train, test)
    K_star = np.empty((ntest, ntrain))
    for i in np.arange(len(xtest)):
        for j in np.arange(len(xtrain)):
            K_star[i, j] = k(xtest[i], xtrain[j], new_hyp[0])

    # Derivative of kernel K
    K_prime = np.empty((ntrain, ntrain))
    for i in np.arange(len(xtrain)):
        for j in np.arange(len(xtrain)):
            K_prime[i, j] = dkdl(xtrain[i], xtrain[j], new_hyp[0])

    # Derivative of kernel K_star
    K_star_prime = np.empty((ntest, ntrain))
    for i in np.arange(len(xtest)):
        for j in np.arange(len(xtrain)):
            K_star_prime[i, j] = dkdl(xtest[i], xtrain[j], new_hyp[0])
    ############################################################################

    alpha = np.dot(Kyinv, ytrain) # RW p17 paragraph 4

    dalpha_dl = -Kyinv.dot(K_prime).dot(Kyinv).dot(ytrain) # Compute the alpha's derivative w.r.t. lengthscale

    dalpha_ds = -Kyinv.dot(np.eye(ntrain)).dot(Kyinv).dot(ytrain) # Compute the alpha's derivative w.r.t. sigma noise
                                                                  # square
    #print("dl ", dalpha_dl)
    #print("\nds ", dalpha_ds)

    dm = np.empty((ntest,len(new_hyp), 1))

    for nb_hyp in range(len(new_hyp)):
        if nb_hyp == 0 :
            dm[:,nb_hyp,:] = np.dot(K_star_prime, alpha) -\
                             np.dot(K_star, dalpha_dl)
        else :
            dm[:,nb_hyp,:] = np.dot(K_star, dalpha_ds)

    V = varf # set V as the result of the predict_f diagonal

    dm_transpose = np.empty((ntest, 1, len(new_hyp)))
    dmT_dot_sigma = np.empty((ntest, 1, len(new_hyp)))
    dmT_dot_sigma_dot_dm = np.empty((ntest, 1))

    for i in range(ntest):
        dm_transpose[i] = dm[i].T
        dmT_dot_sigma[i] = dm_transpose[i].dot(sigma_m)
        dmT_dot_sigma_dot_dm[i] = dmT_dot_sigma[i].dot(dm[i])

    #print("dmT_dot_sigma_dot_dm = ", dmT_dot_sigma_dot_dm)
    V_tild = V.reshape((ntest,1)) + dmT_dot_sigma_dot_dm # Osborne et al. (2012) Active learning eq.19

    if plot_result == True:
        print("\nThe marginal Variance has a shape of ", V_tild.shape)
        print("\n\n\tMarginal variance\n\n", V_tild )

    return V_tild

def get_marginal_variance_MGP(hess_inv, new_hyp, ntrain, ntest, xtrain, xtest, Kyinv, ytrain, varf, plot_result = False):

    # Step 1 : invert the res.hess_inv to get H_tilde
    H_tilde = invert(hess_inv)
    # Step 2 Get H
    H = np.zeros((len(H_tilde), len(H_tilde)))
    for i in np.arange(len(H_tilde)):
        for j in np.arange(len(H_tilde)):
            H[i,j] = (1/np.log(10)**2) * H_tilde[i,j]/(new_hyp[i]*new_hyp[j])
    # Step 3 get Sigma
    H_inv = invert(H)
    sigma_m = H_inv

    ######################### Build needed Kernel Matrix #########################

    # Kernel K(train, train) of shape (ntrain, ntrain)
    K = np.empty((ntrain, ntrain))
    for i in np.arange(len(xtrain)):
        for j in np.arange(len(xtrain)):
            K[i, j] = k(xtrain[i], xtrain[j], new_hyp[0])

    # Kernel K_star(test, train) of shape (ntest, ntrain)
    # note that K_star(test, train) = K_star.T(train, test)
    K_star = np.empty((ntest, ntrain))
    for i in np.arange(len(xtest)):
        for j in np.arange(len(xtrain)):
            K_star[i, j] = k(xtest[i], xtrain[j], new_hyp[0])

    # Derivative of kernel K
    K_prime = np.empty((ntrain, ntrain))
    for i in np.arange(len(xtrain)):
        for j in np.arange(len(xtrain)):
            K_prime[i, j] = dkdl(xtrain[i], xtrain[j], new_hyp[0])

    # Derivative of kernel K_star
    K_star_prime = np.empty((ntest, ntrain))
    for i in np.arange(len(xtest)):
        for j in np.arange(len(xtrain)):
            K_star_prime[i, j] = dkdl(xtest[i], xtrain[j], new_hyp[0])

    K_2star_prime = np.empty((ntest, ntest))
    for i in np.arange(len(xtest)):
        for j in np.arange(len(xtest)):
            K_2star_prime[i, j] = dkdl(xtest[i], xtest[j], new_hyp[0])
    ############################################################################

    dKyinv_dl = -Kyinv.dot(K_prime).dot(Kyinv) # Compute the Kyinv's derivative w.r.t. lengthscale

    dKyinv_ds = -Kyinv.dot(np.eye(ntrain)).dot(Kyinv) # Compute the Kyinv's derivative w.r.t. sigma noise
                                                                  # square

    term1 = K_star_prime.dot(Kyinv).dot(K_star.T)

    # dm = np.empty((ntest,len(new_hyp), 1))
    #
    # for nb_hyp in range(len(new_hyp)):
    #     if nb_hyp == 0 :
    #         dm[:,nb_hyp,:] = np.dot(K_star_prime, alpha) -\
    #                          np.dot(K_star, dalpha_dl)
    #     else :
    #         dm[:,nb_hyp,:] = np.dot(K_star, dalpha_ds)
    #
    #
    #
    # V = varf # set V as the result of the predict_f diagonal
    #
    # dm_transpose = np.empty((ntest, 1, len(new_hyp)))
    # dmT_dot_sigma = np.empty((ntest, 1, len(new_hyp)))
    # dmT_dot_sigma_dot_dm = np.empty((ntest, 1))
    #
    # for i in range(ntest):
    #     dm_transpose[i] = dm[i].T
    #     dmT_dot_sigma[i] = dm_transpose[i].dot(sigma_m)
    #     dmT_dot_sigma_dot_dm[i] = dmT_dot_sigma[i].dot(dm[i])
    #
    # #print("dmT_dot_sigma_dot_dm = ", dmT_dot_sigma_dot_dm)
    # V_tild = V.reshape((ntest,1)) + dmT_dot_sigma_dot_dm # Osborne et al. (2012) Active learning eq.19
    #
    # if plot_result == True:
    #     print("\nThe marginal Variance has a shape of ", V_tild.shape)
    #     print("\n\n\tMarginal variance\n\n", V_tild )
    #
    # return V_tild

def wld_get_marginal_variance(wld_hess_inv, wld_hyp, ntrain, ntest, xtrain, xtest, Kyinv, ytrain, varf, plot_result = False):

    ######################### Build needed Kernel Matrix #########################
    wld_K = np.empty((ntrain, ntrain))
    for i in np.arange(len(xtrain)):
        for j in np.arange(len(xtrain)):
            wld_K[i, j] = k(xtrain[i], xtrain[j], wld_hyp[0])

    wld_K_star = np.empty((ntest, ntrain))
    for i in np.arange(len(xtest)):
        for j in np.arange(len(xtrain)):
            wld_K_star[i, j] = k(xtest[i], xtrain[j], wld_hyp[0])

    wld_K_prime = np.empty((ntrain, ntrain))
    for i in np.arange(len(xtrain)):
        for j in np.arange(len(xtrain)):
            wld_K_prime[i, j] = dkdl(xtrain[i], xtrain[j], wld_hyp[0])

    wld_K_star_prime = np.empty((ntest, ntrain))
    for i in np.arange(len(xtest)):
        for j in np.arange(len(xtrain)):
            wld_K_star_prime[i, j] = dkdl(xtest[i], xtrain[j], wld_hyp[0])
    ############################################################################

    wld_alpha = np.dot(Kyinv, ytrain) # RW p17 paragraph 4

    wld_dalpha_dl = -Kyinv.dot(wld_K_prime)\
        .dot(Kyinv)\
        .dot(ytrain)

    wld_dalpha_ds = -Kyinv.dot(np.eye(ntrain)).dot(Kyinv).dot(ytrain) # - Kyinv x I x Kyinv x ytrain

    wld_dm = np.empty((ntest,len(wld_hyp), 1))

    for nb_hyp in range(len(wld_hyp)):
        if nb_hyp == 0 :
            wld_dm[:,nb_hyp,:] = np.dot(wld_K_star_prime, wld_alpha) -\
                             np.dot(wld_K_star, wld_dalpha_dl)
        else :
            wld_dm[:,nb_hyp,:] = np.dot(wld_K_star, wld_dalpha_ds)

    V = varf # set V as the result of the predict_f diagonal
    wld_sigma = invert(wld_hess_inv)

    wld_dm_transpose = np.empty((ntest, 1, len(wld_hyp)))
    wld_dmT_dot_sigma = np.empty((ntest, 1, len(wld_hyp)))
    wld_dmT_dot_sigma_dot_dm = np.empty((ntest, 1))

    for i in range(ntest):
        wld_dm_transpose[i] = wld_dm[i].T
        wld_dmT_dot_sigma[i] = wld_dm_transpose[i].dot(wld_sigma)
        wld_dmT_dot_sigma_dot_dm[i] = wld_dmT_dot_sigma[i].dot(wld_dm[i])

    wld_V_tild = V.reshape((ntest,1)) + wld_dmT_dot_sigma_dot_dm # Osborne et al. (2012) Active learning eq.19

    if plot_result == True :
        print("The marginal Variance has a shape of ", wld_V_tild.shape)
        print("\n\n\tMarginal variance\n\n", wld_V_tild )

    return wld_V_tild

def plot_searching_phase(scores, xtest, next_candidate, ntrain):
    max = np.linspace(0, scores[next_candidate], 3)
    #plt.figure()
    plt.subplot(2,1,2)
    plot_line = np.linspace(xtest[next_candidate], xtest[next_candidate],3)
    plt.plot(xtest, scores, 'b')
    plt.plot(plot_line, max, 'r')
    plt.title('Iteration ' + str(ntrain + 1) + ' : searching phase')
    plt.xlabel('xtest')
    plt.ylabel('score')
    plt.savefig('Active Gaussian Process with '+ str(ntrain) + ' observation(s)')
    plt.show()


from tkinter import *

root = Tk()
root.title("Basic Calculator")

screen = Entry(root,width = 35)
screen.grid(row = 0, column = 0, columnspan = 3)
index = 0
results = 0
operation = ""
#functions
def click(num):
    global index
    screen.insert(index,num)
    index += 1
def clear():
    screen.delete(0,END)
def add():
    global results
    global operation
    first_number = screen.get()
    results = float(first_number)
    operation = "+"
    screen.delete(0,END)
def sub():
    global results
    global operation
    first_number = screen.get()
    results = float(first_number)
    operation = "-"
    screen.delete(0,END)
def mul():
    global results
    global operation
    first_number = screen.get()
    results = float(first_number)
    operation = "*"
    screen.delete(0,END)
def div():
    global results
    global operation
    first_number = screen.get()
    results = float(first_number)
    operation = "/"
    screen.delete(0,END)
def result():
    global results
    global operation
    second_number = screen.get()
    screen.delete(0,END)
    if operation == "+":
        screen.insert(0,results + float(second_number))
    elif operation == "-":
        screen.insert(0,results - float(second_number))
    elif operation == "*":
        screen.insert(0,results * float(second_number))
    elif operation == "/":
        screen.insert(0,results / float(second_number))

#make buttons
button_9 = Button(root,text = "9", padx = 20, pady = 20, command = lambda:click(9))
button_8 = Button(root,text = "8", padx = 20, pady = 20, command = lambda:click(8))
button_7 = Button(root,text = "7", padx = 20, pady = 20, command = lambda:click(7))

button_6 = Button(root,text = "6", padx = 20, pady = 20, command = lambda:click(6))
button_5 = Button(root,text = "5", padx = 20, pady = 20, command = lambda:click(5))
button_4 = Button(root,text = "4", padx = 20, pady = 20, command = lambda:click(4))

button_3 = Button(root,text = "3", padx = 20, pady = 20, command = lambda:click(3))
button_2 = Button(root,text = "2", padx = 20, pady = 20, command = lambda:click(2))
button_1 = Button(root,text = "1", padx = 20, pady = 20, command = lambda:click(1))

button_0 = Button(root,text = "0", padx = 20, pady = 20, command = lambda:click(0))
button_add = Button(root,text = "+", padx = 20, pady = 20, command = lambda:add())
button_sub = Button(root,text = "-", padx = 20, pady = 20, command = lambda:sub())
button_div = Button(root,text = "/", padx = 20, pady = 20, command = lambda:div())
button_mul = Button(root,text = "*", padx = 20, pady = 20, command = lambda:mul())
button_clear = Button(root,text = "c", padx = 20, pady = 20, command = lambda:clear())
button_equal = Button(root,text = "=", padx = 90, pady = 20, command = lambda:result())

#render Buttons
button_9.grid(row = 1, column = 0)
button_8.grid(row = 1, column = 1)
button_7.grid(row = 1, column = 2)

button_6.grid(row = 2, column = 0)
button_5.grid(row = 2, column = 1)
button_4.grid(row = 2, column = 2)

button_3.grid(row = 3, column = 0)
button_2.grid(row = 3, column = 1)
button_1.grid(row = 3, column = 2)

button_0.grid(row = 4, column = 0)
button_add.grid(row = 4, column = 1)
button_sub.grid(row = 4, column = 2)
button_mul.grid(row = 5, column = 1)
button_div.grid(row = 5, column = 2)
button_clear.grid(row = 5, column = 0)
button_equal.grid(row = 6, column = 0,columnspan = 3)
root.mainloop()


# -*- coding: utf-8 -*-
# @Time    : 2019/3/14 19:47
# @Author  : Sidian
# @Email   : sidian305@163.com
# @File    : 17.py
# @Software: PyCharm
print(' 17 打印杨辉三角行')

def triangles():
    ret = [1]
    while True:
        yield ret
        for i in range(1, len(ret)):
            ret[i] = pre[i] + pre[i - 1]
        ret.append(1)
        pre = ret[:]
# 传统的杨辉三角形实现
# 利用python列表迭代的实现
def printLine(lineList,row):
    lineList = [str(tmpNum) for tmpNum in lineList]
    print("%s%s" % (" " * (row - len(lineList)), " ".join(lineList)))

def pascal(row):
    for i in range(row):
        if i < 2:
            yhList = [1] * (i + 1)
        else:
            yhList[1:-1] = [(tmpNum + yhList[j])  for j, tmpNum in enumerate(yhList[1:])]
        printLine(yhList,row)

pascal(10)


# -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
import Adafruit_DHT
import time
import pickle

sensor = Adafruit_DHT.DHT11
inputPin = 17
outputPin1 = 4
outputPin2 = 27

def inputValue() :
    setMsg = [3, 0, -1, 0, 0]
    try :
        humid, temp = Adafruit_DHT.read_retry(sensor, inputPin)
        if temp is not None and humid is not None:
            print('Temperature={0:0.1f}*C Humidity={1:0.1f}%'.format(temp, humid))
            setMsg[3] = temp
            setMsg[4] = humid

        if temp is not None:
            if temp > 20.0:
                setMsg[1] = 2
            elif temp < 10.0:
                setMsg[1] = 1
            else :
                setMsg[1] = 0
        time.sleep(2)
    except KeyboardInterrupt:
        setMsg[1] = -1
    return setMsg

def outputValue(getMsg):
    try :
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(outputPin1,GPIO.OUT)
        GPIO.setup(outputPin2,GPIO.OUT)
        if getMsg == 2:  #불빛 여러번 깜빡이게 할려고 한거임
            i = 0
            while i < 2:
                GPIO.output(outputPin1, True)
                time.sleep(1)
                i = i + 1

        elif getMsg == 1: #불빛 여러번 깜빡이게 할려고 한거임
            i = 0
            while i < 2:
                GPIO.output(outputPin2, True)
                time.sleep(1)
                i = i + 1

        elif getMsg == 0: #기본
            print("default")

        elif getMsg == -1:
            print("error")

    except KeyboardInterrupt:
        print("error")
        GPIO.cleanup()

    GPIO.cleanup()


class Solution:
    def hasPath(self, maze, start, destination):
        """
        :type maze: List[List[int]]
        :type start: List[int]
        :type destination: List[int]
        :rtype: bool
        """
        m, n = len(maze), len(maze[0])
        DIR = (-1, 0), (1, 0), (0, -1), (0, 1)
        def dfs(x, y, path):
            if (x, y) in path: return False
            path.add((x, y))
            if [x, y] == destination:
                return True
            else:
                for i, j in DIR:
                    newx, newy = x, y
                    while 0 <= newx + i < m and 0 <= newy + j < n and maze[newx + i][newy + j] != 1:
                        newx += i
                        newy += j
                    if dfs(newx, newy, path):
                        return True
                return False
        return dfs(start[0], start[1], set())

s = Solution()
mz = [
 [0, 0, 1, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 1, 0],
 [1, 1, 0, 1, 1],
 [0, 0, 0, 0, 0]
]

print(s.hasPath(mz, [0,4], [4,4]))


from rest_framework import viewsets
from rest_framework import exceptions
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.reverse import reverse

from onadata.apps.api.tools import get_accessible_forms, get_xform
from onadata.apps.logger.models import Instance
from onadata.libs.data.query import get_form_submissions_grouped_by_field

class SubmissionStatsViewSet(viewsets.ViewSet):
    """
Provides submissions counts grouped by a specified field.
It accepts query parameters `group` and `name`. Default result
is grouped by `_submission_time`, hence you get submission counts per day.
If a date field is used as the group, the result will be grouped by day.

* *group* - field to group submission counts by
* *name* - name to be applied to the group on results

Example:

    GET /api/v1/stats/submissions/ukanga/1?
    group=_submission_time&name=day_of_submission

Response:

    [
        {
            "count": 8,
            "day_of_submission": "2013-11-15",
        },
        {
            "count": 99,
            "day_of_submission": "2013-11-16",
        },
        {
            "count": 133,
            "day_of_submission": "2013-11-17",
        },
        {
            "count": 162,
            "day_of_submission": "2013-11-18",
        },
        {
            "count": 102,
            "day_of_submission": "2013-11-19",
        }
    ]
"""
    permission_classes = [permissions.IsAuthenticated, ]
    lookup_field = 'owner'
    lookup_fields = ('owner', 'formid', 'dataid')
    extra_lookup_fields = None
    queryset = Instance.objects.all()

    def _get_formlist_data_points(self, request, owner=None):
        xforms = get_accessible_forms(owner)
        # filter by tags if available.
        tags = self.request.QUERY_PARAMS.get('tags', None)
        if tags and isinstance(tags, basestring):
            tags = tags.split(',')
            xforms = xforms.filter(tags__name__in=tags).distinct()
        rs = {}
        for xform in xforms.distinct():
            point = {u"%s" % xform.id_string:
                     reverse("submissionstats-list", kwargs={
                             "formid": xform.pk,
                             "owner": xform.user.username},
                             request=request)}
            rs.update(point)
        return rs

    def list(self, request, owner=None, formid=None, **kwargs):
        if owner is None and not request.user.is_anonymous():
            owner = request.user.username

        data = []

        if formid:
            xform = get_xform(formid, request)

            field = '_submission_time'
            name = 'date_of_submission'
            group = request.QUERY_PARAMS.get('group', None)
            alt_name = request.QUERY_PARAMS.get('name', None)

            if group:
                name = field = group
            if alt_name:
                name = alt_name

            try:
                data = get_form_submissions_grouped_by_field(
                    xform, field, name)
            except ValueError as e:
                raise exceptions.ParseError(detail=e.message)
        else:
            data = self._get_formlist_data_points(request, owner)

        return Response(data)