#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@ author: Hubery
@ create on: 2018/11/8 14:03
@ file: protocol.py
@ site:
@ purpose:
"""
from RunFast.Common.pack import *

class Encrypt2ParseData:
    def __init__(self, update_data, method=None):
        self.update_data = update_data
        self.method = method

    #   Update protocol data and perform different processing of data according to requirements.
    def get_update_data(self):
        if self.method == "pack":
            return self.pack_data()
        elif self.method == "unpack":
            return self.unpack_data()
        else:
            return None

    #   pack data
    def pack_data(self):
        package = net_package(self.update_data["protocol_num"][1])

        if len(self.update_data) > 0:
            for k, v in self.update_data.items():
                if k != "protocol_num":
                    if v[0] == "INT32":
                        package.write_int32(v[1])
                    elif v[0] == "INT64":
                        package.write_int32(v[1])
                    elif v[0] == "INT16":
                        package.write_int16(v[1])
                    elif v[0] == "STRING":
                        if self.update_data["protocol_num"][1] == 2523:
                            if type(v[1]) == list:
                                for i in v[1]:
                                    if '\x00' in i:
                                        package.write_string(i[: len(i) - 1])
                                    else:
                                        package.write_string(i)
                            else:
                                # print(u"单张出牌操作数据: %s" % str(v[1]))
                                package.write_string(str(v[1]))
                        else:
                            package.write_string(str(v[1]))
        # print("package.encode: %s" % package.encode())
        return package.encode()

    #   unpack data
    def unpack_data(self):
        pass

#   Update protocol data.
class CommonUtils2UpdateData:
    def __init__(self, original_data, original_data_keys_list, update_data, method):
        self.original_data = original_data
        self.original_data_keys_list = original_data_keys_list
        self.data = update_data
        self.method = method

    def update_data(self):
        if len(self.data) > 0:
            for k, v in self.data.items():
                if k in self.original_data_keys_list:
                    self.original_data[k][1] = v

        # print("data: %s" % self.original_data)
        ud = Encrypt2ParseData(self.original_data, self.method)
        return ud.get_update_data()

#   common api to call update data
class CallUpdateApi:
    def __init__(self, original_data, original_data_keys_list, update_data, method):
        self.original_data = original_data
        self.original_data_keys_list = original_data_keys_list
        self.update_data = update_data
        self.method = method
        self.real_data = None
        self.get_real_data()

    def get_real_data(self):
        cu = CommonUtils2UpdateData(self.original_data, self.original_data_keys_list, self.update_data, self.method)
        self.real_data = cu.update_data()

######################
### 登录
######################

#   login entity --> CS
class CSLogin:
    def __init__(self, data={}):
        self.cs_login_entity = {"protocol_num": ["INT32", 1000], "mid": ["INT32", 0], "sesskey": ["STRING", ""],
                                "gp": ["INT32", 0], "sid": ["INT32", 1500]}
        self.cs_keys_list = self.cs_login_entity.keys()
        self.update_data = data
        self.method = "pack"
        self.real_data = CallUpdateApi(self.cs_login_entity, self.cs_keys_list, self.update_data, self.method).real_data

#   login entity --> SC
class SCLogin:
    def __init__(self, data={}):
        self.sc_entity_data = {"ErrorCode": ["INT32", 0], "UnUsed1": ["INT32", 100], "UnUsed2": ["INT32", 100]}
        self.sc_login_keys_list = self.sc_entity_data.keys()
        self.update_data = data
        self.method = "unpack"

class SCReconnect:
    def __init__(self):
        self.sc_entity_data = {"playType": ["INT32", 0],"RoomID": ["INT32", 0], "SID": ["INT32", -100]}
class SCOffline:
    def __init__(self):
        self.sc_entity_data = {"SeatID": ["INT32", 0]}

######################
### 房间内容
######################

#   创建房间 --1010
class CSCreateRoom():
    def __init__(self, data={}):
      self.entity = {
          "protocol_num": ["INT32", 1010],
          "GameType": ["STRING", "81"],  # 游戏类型
          "GameInnings": ["INT32", 0],  # 局数
          "GamePaiNum": ["INT32", 0],  #  牌的张数
          "GameFirstRule": ["INT32", 0],  #  首局规则
          "GameShouJu3cFirst": ["INT32", 0],  # 黑桃3首出规则 -- 0无要求 1 黑桃3先出
          "GameShowRest": ["INT32", 0],  # 显示剩余牌数
          "GameSelectWanFa1": ["INT32", 0],  #  多选1
          "GameSelectWanFa2": ["INT32", 0],  # 多选2
          "GamePlayers": ["INT32", 3],  # 人数 -- 几人(2,3,4)
          "GamePiao": ["INT32", 0],  # 飘
          "GameJoinGame": ["INT32", 0],  # 0普通创房 1代理开房 3茶馆
          "GameClunId": ["INT32", 0],  #
          "GamePaytype": ["INT32", 0],  #是否AA制开房，0否，1是
          "GameCoverCard": ["INT32", 0],  #是否首轮盖牌，0否，1是
          "GameClubName": ["STRING", ""],  #俱乐部名字，代理商名字
          "GameIsCreateEmptyRoom": ["INT32", 0],  # 俱乐部名字，代理商名字
          "GamePassWord": ["INT32", 0],  # 密码
          "GameFZB": ["INT32", 0],  # 防作弊
          "GameAgentDRoom": ["INT32", 0],  #  所有人同意解散
          "GameWanFaIndex": ["INT32", 0],  #  玩法下标
          "GameKoFangKa": ["INT32", 0],  # 是否使用自己房卡开房(0用自己的)
          "GameBaodi": ["INT32", 0],  # 报单是否保底 0保底 1不保底
          "GameIsGuanPai": ["INT32", 0],  # 关牌
      }
      self.cs_keys_list = self.entity.keys()
      self.update_data = data
      self.method = "pack"
      self.real_data = CallUpdateApi(self.entity, self.cs_keys_list, self.update_data, self.method).real_data

#   创建房间回包 --1010
class SCCreateRoom():
    def __init__(self):
        self.sc_entity_data = {
            "Type": ["INT32", 0],
            "ErrorCode": ["INT32", 0],
            "RoomID": ["INT32", 0],
            "RoomType": ["STRING", ""],
            "GameInnings": ["INT32", 0],
            "GamePlayers": ["INT32", 3],
            "GamePlayOptions": ["INT32", 0],
            "GameBaseScore": ["INT32", 0],
            "GameDouble": ["INT32", 0],  # 加倍
            "GameDoubleCondition": ["INT32", 0],
            "GameClubID": ["INT32", 0],
            "GameClubName": ["STRING", ""],
            "GameFixedPlay": ["INT32", 0],
            "GameFixedIndex": ["INT32", -1],
            "GameLimitIP": ["INT32", 0],
        }

#   申请加入房间 --1001
class CSApplyToEnterRoom:
    def __init__(self, data):
        self.entity = {
            "protocol_num": ["INT32", 1001],
            "RoomID": ["INT32", 0],         # 房间ID
            "Version": ["INT32", 0],        # 版本
            "NetWork": ["INT32", 0],        # 网络
            "PassWord": ["INT32", 0],       # 密码
            "Source": ["INT32", 0],         # 0:来自app，1:来自h5
            "ClubPay": ["INT32", 0]       # 0 普通 1代开 3俱乐部
        }
        self.cs_keys_list = self.entity.keys()
        self.update_data = data
        self.method = "pack"
        self.real_data = CallUpdateApi(self.entity, self.cs_keys_list, self.update_data,
                                       self.method).real_data

#   申请加入房间回包 --1001
class SCApplyToEnterRoom:
    def __init__(self):
        self.sc_entity_data = {
            "playType":["INT32", 0],
            "SeatID": ["INT32", 0],
            "RoomID": ["INT32", 0]
            #"RoomType": ["STRING", ""],
            #"RoomID": ["INT32", 0],
            #"GameFixedIndex": ["INT32", 0],
            #"GameClubID": ["INT32", 0],
            #"RoomState": ["INT32", 0]       # 房间状态(0:进入房间（等待开始） 1:游戏中 2:空闲状态)
        }

#   room snapshot 1002 快照   -->SC
class SCRoomSnapshot:
    def __init__(self):
        self.sc_entity_data = {"room_owner": ['INT32', 0], "room_state": ["INT32",0],"total_ju": ["INT32",0],"players_num": ["INT32",0],
                               "_player_info": ["INT32",{"seat_id": ['INT32', 0],"ip": ["STRING", ""], "mid": ['INT32', 0],"gp": ['INT32', 0],
                                                 "sex": ['INT32', 0], "name": ["STRING", ""],
                                                 "icon": ["STRING", ""], "city": ['STRING', 0],
                                                 "json_str": ["STRING", 0]}],
                               "banker_seatno": ["INT32", 0], "seats_size": ["INT32", 0], "banker_seatno": ["STRING", 0]}
#   desktop snapshot --> SC
class SCDesktopSnapshot:
    def __init__(self):
        self.sc_entity_data = {"room_num": ["INT32", 0], "room_type": ["STRING", ""], "total_times": ["INT32", 0],
                               "banker_seat_id": ["INT32", 0], "current_player_seat_id": ["INT32", 0],
                               "current_card": ["STRING", ""], "current_send_card_seat_id": ["INT32", 0],
                               "hupai_type": ["INT32", 0], "player_num": ["INT32", 0], "player_info": ["INT32", {
                "seat_id": ["INT32", 0], "mid": ["INT32", 0], "zanli": ["INT32", 0], "isready": ["INT32", 0],
                "huxi": ["INT32", 0], "send_card_num": ["INT32", 0], "_card_list": ["STRING", ""],
                "molding_card": ["INT32", 0], "_card_type_list": ["INT32", {"shoupai_type": ["INT32", 0],
                                                                            "card_num": ["INT32", 0],
                                                                            "_card": ["STRING", ""], }]}],
                               "homer_seat_id": ["INT32", 0], "game_start_type": ["INT32", 0],
                               "player_number": ["INT32", 0],
                               "_player": ["INT32", {"seat_id": ["INT32", 0], "jiatuo_daniao": ["STRING", ""]}]}

#   解散房间 --1008
class CSDissolveRoom:
    def __init__(self):
        self.entity = {"protocol_num": ["INT32", 1008]}
        self.cs_keys_list = self.entity.keys()
        self.update_data = {}
        self.method = "pack"
        self.real_data = CallUpdateApi(self.entity, self.cs_keys_list, self.update_data,
                                       self.method).real_data

#   解散房间回包 --1008
class SCDissolveRoom:
    def __init__(self):
        self.sc_entity_data = {
            "ErrorCode": ["INT32", -100],
            "DismissSeatID": ["INT32", 0],  # 申请解散座位ID
            "AutoAgreeDissolveTime": ["INT32", 0],  # 剩余自动解散时间
            "RoomPlayers": ["INT32", -100],
            "RoomDissolveInfo": [
                "INT32",
                {
                    "SeatID": ["INT32", -100],
                    "IsAgree": ["INT32", -100]
                }
            ]
        }

#   同意解散 --1012
class CSAgreeDissolve:
    def __init__(self):
        self.cs_club_game_list_data = {
            "protocol_num": ["INT32", 1012],
            "Agree": ["INT32", 1]
        }
        self.cs_keys_list = self.cs_club_game_list_data.keys()
        self.update_data = {}
        self.method = "pack"
        self.real_data = CallUpdateApi(self.cs_club_game_list_data, self.cs_keys_list, self.update_data,
                                       self.method).real_data

#   同意解散回包 --1012
class SCAgreeDissolve:
    def __init__(self):
        self.sc_entity_data = {"ErrorCode": ["INT32", -100]}

#   解散房间原因 --5013
class SCDissolveReason:
    def __init__(self):
        self.sc_entity_data = {"RoomId": ["INT32", -100], "RoomType": ["STRING", ""], "DissolveType": ["INT32", -100]}

#   申请离开房间 --5009
class CSLeaveRoom:
    def __init__(self):
        self.entity = {
            "protocol_num": ["INT32", 4009]
        }
        self.cs_keys_list = self.entity.keys()
        self.update_data = {}
        self.method = "pack"
        self.real_data = CallUpdateApi(self.entity, self.cs_keys_list, self.update_data,
                                       self.method).real_data

#   申请离开房间 --5009
class SCLeaveRoom:
    def __init__(self):
        self.sc_entity_data = {"Mid": ["INT32", 00], "SeatID": ["INT32", 99]}
#写牌 --65534
class CSMakeCardsType:
    def __init__(self, data):
        #self.cs_make_cards_type_data = {"protocol_num": ["INT32", 32766], "mid": ["INT32", 0], "cards_list": ["STRING", ""]}
        self.entity = {"protocol_num": ["INT32", 65534],"cards_list": ["STRING", ""]}
        self.cs_keys_list = self.entity.keys()
        self.update_data = data
        self.method = "pack"
        self.real_data = CallUpdateApi(self.entity, self.cs_keys_list, self.update_data,
                                       self.method).real_data

##########################
### 开始牌局
##########################

#   准备 --1005
class CSReadyForGame:
    def __init__(self, data={}):
        self.entity = {"protocol_num": ["INT32", 1005]}
        self.cs_keys_list = self.entity.keys()
        self.update_data = data
        self.method = "pack"
        self.real_data = CallUpdateApi(self.entity, self.cs_keys_list, self.update_data,
                                       self.method).real_data

#   准备回包 --1005
class SCReadyForGame:
    def __init__(self):
        self.sc_entity_data = {"SeatID": ["INT32", 0]}

#   游戏开始回包 --1007
class SCGameStart:
    def __init__(self):
        self.sc_entity_data = {"ErrorCode": ["INT32", -100], "CurrentInnings":["INT32", 0]}

#   发牌回包 --2520
class SCReceiveCards:
    def __init__(self):
        self.sc_entity_data = {
            "CardsNum": ["INT32", 0],
            "CardsInfo": ["INT32", {"Card":["STRING", ""]}]
        }

#   通知玩家出牌 --1021
class SCInformPlayerToDo:
    def __init__(self):
        self.sc_entity_data = {
            "SeatID": ["INT32", 0],
            "OpSize": ["INT32", 0],
            "op": ["INT32", 0]
        }

#   通知用户做相应的操作回包 --1022
class SCPlayerCanDo:
    def __init__(self):
        self.sc_entity_data = {
            "SeatID": ["INT32", 0],
            "OperateNum": ["INT32", 0],
            "OperateInfo": ["INT32", -100], # 1 无效  89:过牌 100:出牌 104:取消
            "OperateSequence": ["STRING", ""],
            "NotByYao": ["INT32", 0]
        }

#   用户请求出牌 --2523
class CSPlayerOperate:
    def __init__(self, data={}):
        self.entity = {"protocol_num": ["INT32", 2523], "OperateSequence": ["STRING", ""], "CardNum": ["INT32", 0], "Cards": ["STRING", ""]}
        self.cs_keys_list = self.entity.keys()
        self.update_data = data
        self.method = "pack"
        self.real_data = CallUpdateApi(self.entity, self.cs_keys_list, self.update_data,
                                       self.method).real_data

#   用户请求回包 --2523
class SCPlayerOperate:
    def __init__(self):
        self.sc_entity_data = {
            # "ErrorCode": ["INT32", -100],
            "SeatID": ["INT32", -100],
            "HandCardNum": ["INT32", -100],  # 手牌数
            "CardNum": ["INT32", -100],
            "Cards": ["STRING", ""],
            #"IsAutoSendCard": ["INT32", -100],
        }

#   小局结算 --2531
class SCSettlement:
    def __init__(self):
        self.sc_entity_data = {
            "Type": ["INT32", -100],
            "BankerSeatID": ["INT32", -100],
            "RemainInnings": ["INT32", -100],
            "GamePlayers": ["INT32", -100],
            "PlayerInfo":["INT32",
                          {
                              "SeatID": ["INT32", -100],
                              "Mid": ["INT32", -100],
                              "Name": ["STRING", ""],
                              "Icon": ["STRING", ""],
                              "BombCount": ["INT32", -100],     # 炸弹次数
                              "CurrentScore": ["INT32", -100],  # 当局得分
                              #"SeatScore": ["INT64", -100],     # 座位分
                              "PiaoFenScore": ["INT32", 0],  #飘分得分
                              "PiaoFen": ["INT32", 0],  #是否飘分
                              "SeatScore": ["INT64", -100],  # 总分
                              "HandCardNum": ["INT32", -100],   # 手牌牌数
                              "Cards": ["STRING", ""],          # 牌
                          }
            ],
            "RoomInfo": ["STRING", ""],         # 房间信息
            "ZhongBirdSeatID": ["INT32", -100], # 中鸟座位号
            "ReservedParam": ["STRING", ""],    # 预留字段
        }

#   总结算 --2535
class SCTotalSettlement:
    def __init__(self):
        self.sc_entity_data = {
            "type": ["INT32", -100],
            "RoomOwner": ["INT32", -100],
            "GamePlayers": ["INT32", 0],
            "PlayerInfo": ["INT32",
                           {
                               "SeatID": ["INT32", -100],
                               "Mid": ["INT32", -100],
                               "Name": ["STRING", ""],
                               "Icon": ["STRING", ""],
                               "SeatScore": ["INT64", -100],  # 座位分
                               "BombCount": ["INT32", -100],  # 炸弹次数
                               "WinCount": ["INT32", -100],  # 赢得局数
                               "LoseCount": ["INT32", -100],  # 输的局数
                               "OneGameMaxScore": ["INT32", -100],  # 当局最高得分
                               "NSpringCount": ["INT32", -100] #被春天数

                           }
                           ],
            "RoomInfo": ["STRING", ""]
        }


def wordBreak(self, s, wordDict):
    hMap = set(wordDict)
    dp = [False for i in range(len(s) + 1)]
    dp[0] = True

    for i in range(1, len(s) + 1):
        for j in range(i - 1, -1, -1):
            if dp[j] and s[j:i] in hMap:
                dp[i] = True
                break
    return dp[-1]


from django.contrib import admin
from django.urls import path,include
from . import views

urlpatterns = [
    path('',views.index,name="index"),
    path('add/',views.add,name="add"),
    path('view/',views.view,name="view"),
    path('delete/<int:id>',views.delete,name="delete"),
    path('update/<int:id>',views.update,name="update"),
]


import os
from azureml.pipeline.steps import PythonScriptStep
from azureml.core.runconfig import RunConfiguration
from azureml.core.conda_dependencies import CondaDependencies
from azureml.pipeline.core import PipelineData
from azureml.pipeline.core import PipelineParameter
from azureml.pipeline.steps import EstimatorStep
from azureml.train.dnn import PyTorch

def evaluate_step(model_dir, test_dir, compute_target):
    '''
    This step evaluates the trained model on the testing data and outputs the accuracy.

    :param model_dir: The reference to the directory containing the trained model
    :type model_dir: DataReference
    :param test_dir: The reference to the directory containing the testing data
    :type test_dir: DataReference
    :param compute_target: The compute target to run the step on
    :type compute_target: ComputeTarget

    :return: The evaluate step, step outputs dictionary (keys: accuracy_file)
    :rtype: EstimatorStep, dict
    '''

    accuracy_file = PipelineData(
        name='accuracy_file',
        pipeline_output_name='accuracy_file',
        datastore=test_dir.datastore,
        output_mode='mount',
        is_directory=False)

    outputs = [accuracy_file]
    outputs_map = { 'accuracy_file': accuracy_file }

    estimator = PyTorch(
        source_directory=os.path.dirname(os.path.abspath(__file__)),
        entry_script='evaluate.py',
        framework_version='1.3',
        compute_target=compute_target,
        use_gpu=True)

    step = EstimatorStep(
        name="Evaluate Model",
        estimator=estimator,
        estimator_entry_script_arguments=[
            '--test_dir', test_dir,
            '--model_dir', model_dir,
            '--accuracy_file', accuracy_file
        ],
        inputs=[model_dir, test_dir],
        outputs=outputs,
        compute_target=compute_target,
        allow_reuse=True)

    return step, outputs_map


import csv, random, nltk

ids =[]
sentiments =[]

ids1 = []
texts = []
def read_csv_file(filename, delimiter = ','):
    ids = []
    values =[]
    with open(filename, 'rb') as csvfile:
        reader = csv.reader(csvfile,delimiter=delimiter)
        for row in reader:
            ids.append(row[0])
            values.append(row[1])
        csvfile.close()
    return (ids, values)

ids, sentiments = read_csv_file('./data/sentiment_labels.txt', '|')

ids1, texts = read_csv_file('./data/sentlex_exp12.txt')

print(len(sentiments))
print(len(texts))

data = []
for i in range(len(texts)):
    data.append((texts[i], 'neg' if float(sentiments[i]) <= 0.4
    else ('pos' if float(sentiments[i]) > 0.6 else 'nut')  ))

tweets =[]

for(words, sentiment) in data:
    words_filtered = [e.lower() for e in words.split() if len(e) >= 3]
    tweets.append((words_filtered, sentiment))

random.shuffle(tweets)

print(tweets[:1])


# -*- coding: utf-8 -*-
"""
Created on Fri Apr 07 19:26:23 2017

@author: Noah
"""

from PyQt4 import QtCore, QtGui
from CustomMViewTiles.tetrix import TetrixWindow as tetrix
class tetris(QtGui.QFrame):
    def __init__(self):
        super(tetris, self).__init__(None)
        self.setObjectName("myParentWidget");
        self.setStyleSheet("QFrame#myParentWidget{background: rgb(52, 73, 94);"
                           "margin:0px; border:2px solid rgb(0, 0, 0);}"
                           "QPushButton{color:rgb(189,195, 199); background: rgb(70,80,88)}"
                           "QLabel{color:rgb(189,195, 199); background: rgb(52, 73, 94)}"
                           )
        self.hidden = True
        self.font = QtGui.QFont()
        self.font.setBold(False)
        self.font.setWeight(50)
        self.font.setKerning(True)
        self.font.setPointSize(20)
        self.label = QtGui.QLabel("Tetris")
        self.label.setStyleSheet("QLabel{color:rgb(189,195, 199); background : rgb(52, 73, 94)}")
        self.label.setFont(self.font)
        self.button = QtGui.QPushButton("Tetris")

        self.button.clicked.connect(self.toggleTetris)
        self.layout = QtGui.QHBoxLayout()
        self.vlayout = QtGui.QVBoxLayout()
        self.setLayout(self.vlayout)
        self.vlayout.addWidget(self.label)
        self.buttonLayout = QtGui.QHBoxLayout()

        self.buttonLayout.addWidget(self.button)
        self.buttonLayout.addStretch()
        self.vlayout.addLayout(self.buttonLayout)
        self.vlayout.addLayout(self.layout)
        self.tet = tetrix()
        self.tet.hide()
        self.layout.addWidget(self.tet)
        self.layout.addStretch()

    def toggleTetris(self):
        if self.hidden:
            self.tet.show()
            self.hidden = False
            self.button.setText("Hide Tetris")
        else:
            self.tet.hide()
            self.hidden = True
            self.button.setText("Show Tetris")


import numpy as np
import pandas as pd
import statsmodels.api as sm

loansData = pd.read_csv('loansData.csv')
intrate = loansData['Interest.Rate']
loanamt = loansData['Amount.Requested']
fico = loansData['FICO.Score']

# The dependent variable
y = np.matrix(intrate).transpose()
# The independent variables shaped as columns
x1 = np.matrix(fico).transpose()
x2 = np.matrix(loanamt).transpose()
x = np.column_stack([x1,x2])

X = sm.add_constant(x)
model = sm.OLS(y,X)
f = model.fit()


def bfs(rows, cols, startrow, startcol, endrow, endcol):
    grid = [[-1 for j in range(cols)] for i in range(rows)]
    xmoves = [2, 2, 1, 1, -2, -2, -1, -1]

    ymoves = [1, -1, 2, -2, 1, -1, 2, -2]

    def getneighbors(x, y):
        neighbors = []

        for i in range(len(xmoves)):
            if x + xmoves[i] < rows and x + xmoves[i] >= 0 and y + ymoves[i] < cols and y + ymoves[i] >= 0 and grid[ x + xmoves[i]][y + ymoves[i]]==-1:
                neighbors.append((x + xmoves[i], y + ymoves[i]))
        print(x,y,neighbors)
        return neighbors

    queue = []
    count = 0

    if startrow == endrow and startcol == endcol:
        return count
    else:
        queue.append((startrow, startcol))

        while queue and count < rows * cols:
            currrow,currcol = queue.pop(0)

            count+=1
            if currrow == endrow and currcol == endcol:
                return grid[currrow][currcol]+1
            else:
                    for nextrow, nextcol in getneighbors(currrow, currcol):
                        grid[nextrow][nextcol]=grid[currrow][currcol]+1
                        queue.append((nextrow, nextcol))

    return -1

rows = 5
cols = 5
start_row = 0
start_col = 0
end_row = 4
end_col = 1
#print(get_neighbours((0,0),grid))
'''
rows = 2
cols = 50000
start_row = 1
start_col = 997
end_row = 0
end_col = 49997
'''

rows = 3
cols = 8
start_row = 0
start_col = 6
end_row = 2
end_col = 0

#print(find_minimum_number_of_moves(rows, cols, start_row, start_col, end_row, end_col))
#print(find_minimum_number_of_moves_bfs(rows, cols, start_row, start_col, end_row, end_col))
print(bfs(rows,cols,start_row,start_col,end_row,end_col))


#hmm_CAD
#Author: Sarah A. Mounho
#Created: 11/18/2019
#Last edited: 12/9/2019
#Description:
#Script to create a bar chart to compare sampled sequences to predicted sequences
#for validation of model
#input:
#transition state matrix where one variable is manipulated to test response to treatment

#Package dependencies: numpy (1.16.4), matplotlib (3.1.1), hmmlearn (0.2.2)
#download instructions for hmmlearn: https://pypi.org/project/hmmlearn/
#Python 3.7.0

#load packages
import numpy as np
from hmmlearn import hmm
import matplotlib.pyplot as plt
import pandas as pd

#set up transition matrixes
#transition matrix
#states:
#healthy_start(0), high bp(1), high ldl(2), smoker(3), heart attack(4), stable/no stent(5), stent(6)
transmat_nobp = np.array([[0.162944787, 0.335688062, 0.329781527, 0.15553875, 0.001300225, 0.014746649, 0],#0
                          [1.0, 0, 0, 0, 0, 0, 0],#1
                          [0.354175611, 0, 0.60305577, 0, 0.003464699, 0.03930392, 0], #2
                          [0.292883373, 0, 0, 0.683394538, 0.001921803, 0.021800286, 0],#3
                          [0, 0, 0, 0, 0.003619055, 0.149457142, 0.846923803],#4
                          [0.612, 0, 0, 0, 0.081, 0, 0.307],#5
                          [0.697, 0, 0, 0, 0.089, 0, 0.214]])#6
transmat_noldl = np.array([[0.162944787, 0.335688062, 0.329781527, 0.15553875, 0.001300225, 0.014746649, 0],#0
                           [0.634635493, 0.298651997, 0, 0, 0.005404855, 0.061307655, 0],#1
                           [1.0, 0, 0, 0, 0, 0, 0], #2
                           [0.292883373, 0, 0, 0.683394538, 0.001921803, 0.021800286, 0],#3
                           [0, 0, 0, 0, 0.003619055, 0.149457142, 0.846923803],#4
                           [0.612, 0, 0, 0, 0.081, 0, 0.307],#5
                           [0.697, 0, 0, 0, 0.089, 0, 0.214]])#6
transmat_nosmoker = np.array([[0.162944787, 0.335688062, 0.329781527, 0.15553875, 0.001300225, 0.014746649, 0],#0
                              [0.634635493, 0.298651997, 0, 0, 0.005404855, 0.061307655, 0],#1
                              [0.354175611, 0, 0.60305577, 0, 0.003464699, 0.03930392, 0], #2
                              [1.0, 0, 0, 0, 0, 0, 0],#3
                              [0, 0, 0, 0, 0.003619055, 0.149457142, 0.846923803],#4
                              [0.612, 0, 0, 0, 0.081, 0, 0.307],#5
                              [0.697, 0, 0, 0, 0.089, 0, 0.214]])#6

def hmm_CAD_inverse(transmat, name):

    #settings for plots
    plt.rcParams.update({'font.size': 25})
    plt.rc('xtick', labelsize=30)
    plt.rc('ytick', labelsize=30)

    #set seed
    np.random.seed(1998)

    #always start healthy
    #when setting random seed, observed that starting state
    #did not have an impact on samples/predictions
    startprob = np.array([1.0, 0, 0, 0, 0, 0, 0])

    #emission states healthy_end(1), hospitilization(2), death(3)
    emission_prob = np.array([[0, 0, 0], #1
                              [0, 0, 0], #2
                              [0, 0, 0], #3
                              [0, 0, 0], #4
                              [0, 0, 0.14], #5
                              [0.279, 0.325, 0.091], #6
                              [0.35, 0.357, 0.089]]) #7
    #create an instance of the model
    model = hmm.MultinomialHMM(n_components=7)
    model.startprob_ = startprob
    model.transmat_ = transmat
    model.emissionprob_ = emission_prob
    #draw samples given the startprob, transmat and emissionprob
    X, Z = model.sample(100)
    X_array = np.array(X)

    #plt the emmission data
    plt.plot(X, '.-', label='observations', ms=6,
             mfc='orange', alpha=0.7)
    #indicate emission
    emit = ['Healthy', 'Hospitalized', 'Dead']
    plt.xlabel('Iteration')
    ticks = [0, 1, 2]
    plt.yticks(ticks, emit, rotation = 60)
    plt.legend(loc='best')
    plt.title('Observation Sampled Sequence')
    plt.show()

    #train the model
    #training HMM parameters and inferring the hidden state sequence
    #based on the sampled outcome sequence
    remodel = hmm.MultinomialHMM(n_components=7, n_iter=100)
    remodel.fit(X)

    #predict hidden states
    prob, sequence = remodel.decode(X)
    #log probabilitity of the produced state sequence (only meaningful in comparison of models)
    #may use to discern differences in different random seeds on model accuracy
    ##print('prob:\n',prob) #uncomment if testing different random seeds.

    #visualize sampled hidden state sequence and predicted hidden state sequence
    #plot the sampled data (transition-hidden states)
    plt.plot(Z, '.-', label='sampled', ms=6,
             mfc = 'orange', alpha=0.7)
    plt.plot(sequence, '.-', label='predicted', ms=6,
              mfc='black', alpha=0.7)
    #indicate component numbers
    states = ['Healthy', 'High BP', 'High LDL', 'Smoker', 'Heart\nattack', 'Stable\nno stent', 'Stent']
    plt.xlabel('Iteration')
    ticks = [0, 1, 2, 3, 4, 5, 6]
    plt.yticks(ticks, states)
    plt.legend(loc='best')
    plt.title('Hidden State Sampled and Predicted Sequence')
    plt.show()

    #validate the results
    print()
    sample_outcome_count = pd.value_counts(X_array.flatten())
    print('Counts for', name,':')
    print('Counts for sampled outcomes:\n', sample_outcome_count)
    print()
    sample_state_count = pd.value_counts(Z)
    print('Counts for sampled states:\n', sample_state_count)
    print()
    predict_state_count = pd.value_counts(sequence)
    print('Counts for predicted outcomes:\n', predict_state_count)
hmm_CAD_inverse(transmat_nobp, 'Managed BP')
hmm_CAD_inverse(transmat_noldl, 'Managed LDL Cholesterol')
hmm_CAD_inverse(transmat_nosmoker, 'Managed Smoking')

#Function Treatment_Response
#input: counts for [healthy, hospitalized, dead] for
#normal, managed bp, managed ldl, and managed smoking
#outputs from hmm_CAD.py and inverseMC_CAD hmm_CAD_inverse
#output:
#bar chart comparing observation count

#inputs
all_risk = [93, 6, 1]
no_bp = [95, 4, 1]
no_ldl = [96, 3, 1]
no_smoke = [93, 6, 1]

def Treatment_Response(all_risk, no_bp, no_ldl, no_smoke):
    #bar charts
    import matplotlib
    import matplotlib.pyplot as plt
    import numpy as np
    #settings for plots
    plt.rcParams.update({'font.size': 25})
    plt.rc('xtick', labelsize=30)
    plt.rc('ytick', labelsize=30)

    labels = ['Healthy', 'Hospitalized', 'Dead']
    x = np.arange(len(labels))
    width = 0.1

    fig, ax = plt.subplots()
    rects1 = ax.bar(x -0.15, all_risk, width, label='Normal')
    rects2 = ax.bar(x-0.05, no_bp, width, label='Managed blood pressure')
    rects3 = ax.bar(x+0.05, no_ldl, width, label='Managed LDL cholesterol')
    rects4 = ax.bar(x+0.15, no_smoke, width, label='Managed smoking')

    ax.set_ylabel('Count')
    ax.set_title('Counts of observations')
    ax.set_xticks(x)
    ax.set_xticklabels(labels)
    ax.legend()

    def autolabel(rects):
        for rect in rects:
            height = rect.get_height()
            ax.annotate('{}'.format(height),
                        xy=(rect.get_x() + rect.get_width() / 2, height),
                        xytext=(0, 3),  # 3 points vertical offset
                        textcoords="offset points",
                        ha='center', va='bottom')
    autolabel(rects1)
    autolabel(rects2)
    autolabel(rects3)
    autolabel(rects4)
    plt.show()

Treatment_Response(all_risk, no_bp, no_ldl, no_smoke)


# %%
import pyspark
from pyspark import SparkContext
from pyspark.sql import SparkSession, Row
from pyspark.sql.types import StructField, StringType, StructType, LongType
from pyspark.sql.functions import col, column, expr

# %%
def get_spark_context():
    sc = SparkContext()
    sc.stop()
    conf = pyspark.SparkConf().setAll(
        [('spark.executor.cores', '4'),
         ('spark.cores.max', '4'),
         ('spark.executor.memory', '16g'),
         ('spark.driver.extraJavaOptions', '-Xms4096m -Xmx4096m -XX:MaxPermSize=4096m -XX:MaxNewSize=4096')])
    spark = SparkSession.builder.config(conf=conf).getOrCreate()
    return spark

# %%
sc = get_spark_context()

# %%
my_manual_schema = StructType([
    StructField('DEST_COUNTRY_NAME', StringType(), True),
    StructField('ORIGIN_COUNTRY_NAME', StringType(), True),
    StructField('count', LongType(), False, metadata={'hello': 'world'})
])
df = sc.read.format('json').schema(my_manual_schema).load('data/flight-data/json/2015-summary.json')
# %%
df.printSchema()
print(df.schema)
# %%
df.columns
# %%
df.first()
# %%
r_1 = Row('Hejka', 12, 1, False, None)
r_1[0]
r_1[2]
# %%


import numpy as np
import matplotlib as mpl
mpl.use('agg')
import sys
from matplotlib import pyplot as plt
from os import listdir, makedirs
from typing import List
from os.path import exists

class Histogram:
    values = None
    n = None
    nbins = None
    data = None
    binwidth = None
    mean = None
    stdev = None

    def __init__(self, values:list):
        # entries
        self.values = values
        self.n = len(self.values)

        # bin number
        scale = 500
        self.nbins = int(scale * (self.values.max()-self.values.min()))

        # compute histogram data
        bins, ranges = np.histogram(self.values, self.nbins)

        middles = []
        for lower, upper in zip( ranges[:-1], ranges[1:]):
            middles.append((upper + lower) / 2)
        self.data = list(zip(middles, bins))
        self.binwidth = middles[1] - middles[0]

        # calculate mean and standard deviation
        Px = 0
        Px2 = 0

        for m, b in self.data:
            Px += b * m
            Px2 += b * (m ** 2)
        self.mean = Px / self.n
        self.stdev = np.sqrt(Px2 / self.n - (self.mean) ** 2)

    def PlotHistogram(self, title:str, xlabel:str, ylabel:str, filename:str):
        # plots histogram of loaded data
        x, y = zip(*self.data)
        plt.bar(x, y, width = self.binwidth, align = 'center', color = '#1f77b4', edgecolor = '#1f77b4')

        # formatting
        plt.ylim(0,)
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
        plt.title('%s\nMean: %.4e | Std: %.4e | Entries: %i | Bins: %i' % (title, self.mean, self.stdev, self.n, self.nbins))

        if not exists('plots/histograms/%s' % filename):
            makedirs('plots/histograms/%s' % filename)

        plt.savefig('plots/histograms/%s/%s.png' % (filename, title))
        print('Histogram saved at: plots/histograms/%s/%s.png' % (filename, title))
        plt.clf()

    def SaveResults(self, filename:str, team:str):
        path:str = 'results/summaries/%s/' % filename
        results = [self.mean, self.stdev]

        if not exists(path):
            makedirs(path)
        np.savetxt('%s%s.sum' % (path, team), results)

def LoadMatches(filename:str):
    datafiles:List[str] = [file for file in listdir('data_files/csvs/%s' % filename) if file.split('.')[-1] == 'sum']
    num_files:int = len(datafiles)
    print('%s: %i csv files found' % (filename, num_files))
    data = None

    for i, datafile in enumerate(datafiles):
        dat = np.loadtxt('data_files/csvs/%s/%s' % (filename, datafile), dtype=float)
        dat = np.reshape(dat, (1,2))

        if i == 0:
            data = dat
        else:
            data = np.concatenate((data, dat), 0)

    print('%s: %i csv files loaded' % (filename, num_files))
    print(data.shape)
    return(data)

def main(date:str, run_name:str):
    filename:str = '%s.%s' % (date, run_name)
    data:np.ndarray = LoadMatches(filename)
    homedata:List[float] = data[:,0]
    awaydata:List[float] = data[:,1]

    # create histograms
    homehist = Histogram(homedata)
    awayhist = Histogram(awaydata)

    # save histograms and results
    homehist.PlotHistogram('%s | Home' % filename, 'Team Spatial Control', 'Counts', filename)
    homehist.SaveResults(filename, 'Home')

    awayhist.PlotHistogram('%s | Away' % filename, 'Team Spatial Control', 'Counts', filename)
    awayhist.SaveResults(filename, 'Away')

if __name__ == '__main__':
    # process sys args
    if len(sys.argv) == 3:
        run_name:str = sys.argv[1]
        date:str = sys.argv[2]

    else:
        print('''
    %s - Plots histograms of mean spatial control per match
        Args:
        [1] - Run Name (MatchType:HomeTeam:AwayTeam)
        [2] - Date (DD.MM)
        ''' % sys.argv[0])
        exit()

    # args complete, run main function
    main(date, run_name)


# -*- coding: utf-8 -*-
"""
@author: Philipp Temminghoff
"""

from prettyqt import gui

class CompositeValidator(gui.Validator):

    def __repr__(self):
        return f"CompositeValidator({self.validators})"

    def __init__(self, validators=None, parent=None):
        super().__init__(parent)
        self.validators = validators if validators is not None else []

    def __getstate__(self):
        return dict(validators=self.validators)

    def __setstate__(self, state):
        self.__init__()
        self.validators = state.get("validators", [])

    def validate(self, text, pos=0):
        vals = [v.validate(text, pos)[0] for v in self.validators]
        return (min(vals), text, pos)

if __name__ == "__main__":
    from prettyqt import widgets
    from prettyqt import custom_validators
    val1 = custom_validators.NotEmptyValidator()
    val2 = custom_validators.PathValidator()
    val = CompositeValidator([val1, val2])
    app = widgets.app()
    widget = widgets.LineEdit("This is a test")
    widget.setValidator(val)
    widget.show()
    app.exec_()


import sys
sys.path.append('../')

from schmactions import schmactions

import astropy.units as u
import pickle

import matplotlib.pyplot as plt
from scipy.stats import sigmaclip
import numpy as np

import matplotlib as mpl
from matplotlib import rc
rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
rc('text', usetex=True)
mpl.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath} \usepackage{bm}']

textwidth = 7.10000594991
columnwidth = 3.35224200913

tb_c = ['#4e79a7', '#f28e2b', '#e15759', '#76b7b2', '#59a14f',
        '#edc948', '#b07aa1', '#ff9da7', '#9c755f', '#bab0ac']

xmin = 0
xmax = 1000

y0min = 20
y0max = 40
y1min = -1800
y1max = -1000
y2min = 10
y2max = 30

histmin = 15
histmax = 30

histmin_thin = 0
histmax_thin = 5

def sclip(a, s=4):
    _, low0, high0 = sigmaclip(a[:,0], low=s, high=s)
    _, low1, high1 = sigmaclip(a[:,1], low=s, high=s)
    _, low2, high2 = sigmaclip(a[:,2], low=s, high=s)
    a0bool = np.logical_and(a[:,0] > low0, a[:,0] < high0)
    a1bool = np.logical_and(a[:,1] > low1, a[:,1] < high1)
    a2bool = np.logical_and(a[:,2] > low2, a[:,2] < high2)
    k0 = np.where(a0bool)[0]
    k1 = np.where(a1bool)[0]
    k2 = np.where(a2bool)[0]
    return k0, k1, k2

zout = pickle.load(open('zout.p', 'rb'))
xout = pickle.load(open('xout.p', 'rb'))
res = pickle.load(open('true_res.p', 'rb'))
J0, J1, J2 = res['actions'].to_value(u.kpc*u.km/u.s)

zout_thin = pickle.load(open('zout_thin.p', 'rb'))
xout_thin = pickle.load(open('xout_thin.p', 'rb'))
res_thin = pickle.load(open('true_res_thin.p', 'rb'))
J0_thin, J1_thin, J2_thin = res_thin['actions'].to_value(u.kpc*u.km/u.s)

init_pos = [8, 0, 0] * u.kpc
init_vel = [0, -190, 50] * u.km/u.s
init_vel_thin = [0, -190, 10] * u.km/u.s

s = schmactions(init_pos, init_vel)
sthin = schmactions(init_pos, init_vel_thin)

zact = s.extract_actions(zout)
xact = s.extract_actions(xout)

ztime = s.extract_time(zout)
xtime = s.extract_time(xout)

zact_thin = sthin.extract_actions(zout_thin)
ztime_thin = sthin.extract_time(zout_thin)

fig, ax = plt.subplots(2, 3, figsize=(textwidth, 4), sharex=True)

for x,t,a in zip(ax, (ztime, xtime), (zact, xact)):
    # get keys corresponding to 4 sigmaclip
    k0, k1, k2 = sclip(a)
    x[0].plot(t[k0], a[:,0][k0], c=tb_c[0])
    x[1].plot(t[k1], a[:,1][k1], c=tb_c[0])
    x[2].plot(t[k2], a[:,2][k2], c=tb_c[0])

    x[0].plot(t, np.full(len(t), J0), c=tb_c[0], ls='dashed')
    x[1].plot(t, np.full(len(t), J1), c=tb_c[0], ls='dashed')
    x[2].plot(t, np.full(len(t), J2), c=tb_c[0], ls='dashed')

    # set limits on plots
    x[0].set_ylim(y0min, y0max)
    x[1].set_ylim(y1min, y1max)
    x[2].set_ylim(y2min, y2max)
    for xx in x:
        xx.set_xlim(xmin, xmax)

for x in ax[1]:
    x.set_xlabel(r'$t\,[\,\text{Myr}\,]$')
    x.set_xticks(np.arange(0,1000,100), minor=True)

for x in ax[:,0]:
    x.set_ylabel(r'$J_{R,\text{obs}}\,[\,\text{kpc}\,\text{km}/\text{s}\,]$')
for x in ax[:,1]:
    x.set_ylabel(r'$J_{\phi,\text{obs}}\,[\,\text{kpc}\,\text{km}/\text{s}\,]$')
for x in ax[:,2]:
    x.set_ylabel(r'$J_{z,\text{obs}}\,[\,\text{kpc}\,\text{km}/\text{s}\,]$')

ax[0][1].set_title(r'$z\,\text{offset}=100\,\text{pc}$')
ax[1][1].set_title(r'$x\,\text{offset}=100\,\text{pc}$')

fig.tight_layout()
plt.savefig('schmactions_one_orbit.pdf')
plt.close()

fig, ax = plt.subplots(2,1, figsize=(columnwidth,6.5))

k0, k1, k2 = sclip(zact)
dJzJz = 0.5*(np.percentile(zact[:,2][k2], 95) - np.percentile(zact[:,2][k2], 5))

ax[0].hist(zact[:,2][k2], bins=np.linspace(histmin, histmax, 60),
        edgecolor='k', fc='none', histtype='stepfilled')
ax[0].arrow(J2, 60, dJzJz, 0, head_width=1, head_length=0.4, length_includes_head=True, color='k')
ax[0].text(J2+dJzJz/3.5, 61, r'$\Delta J_z$', color='k')

ax[0].axvline(x=J2, color='k', ls='dashed', lw=1)
ax[0].set_ylabel(r'$\text{count}$')
ax[0].text(14.5, 75, r'\text{thick-disk orbit}', color='k')

k0t, k1t, k2t = sclip(zact_thin)
dJzJz_thin = 0.5*(np.percentile(zact_thin[:,2][k2t], 95) - np.percentile(zact_thin[:,2][k2t], 5))

ax[1].hist(zact_thin[:,2][k2t], bins=np.linspace(histmin_thin, histmax_thin, 60),
        edgecolor='k', fc='none', histtype='stepfilled')
ax[1].arrow(J2_thin, 60, dJzJz_thin, 0, head_width=1, head_length=0.15, length_includes_head=True, color='k')
ax[1].text(J2_thin+dJzJz_thin/3.5, 61.5, r'$\Delta J_z$', color='k')

ax[1].axvline(x=J2_thin, color='k', ls='dashed', lw=1)
ax[1].set_ylabel(r'$\text{count}$')
ax[1].text(1.3, 100, r'\text{thin-disk orbit}', color='k')

ax[1].set_xlabel(r'$J_{z,\text{obs}}\,[\,\text{kpc}\,\text{km}/\text{s}\,]$')

fig.tight_layout()
plt.savefig('schmactions_Jz_hist.pdf')


"""
This program only supports python 3.
"""

from sys import argv
from os import path
from search_strategies import strategy_by_name
import time

def parse_args():
	assert len(argv) == 3, "Must be called in form: search filename method"
	filename, method = argv[1], argv[2]
	return filename, method

def puzzle_from_file(filename):
	"""
	Converts a puzzle file into type ([][], [][]), where the first element of the tuple is the
	  initial_state and the second is the desired_state.
	Example file:
	2x3          | width x height
	1 2 3 4 0 5  | initial_state
	3 1 2 4 5 0  | desired_state
	"""
	def state_from_line(line):
		"""
		Converts a single line of a puzzle file that represents a state into a 2d array.
		Example: "1 2 3 4 0 5" is converted into [[1,2],[3,4],[0,5]] if puzzle dimensions are 2x3
		"""
		state = [[] for x in range(width)]
		for x in range(width):
			for y in range(height):
				state[x].append(line[x + y*width])
		return state

	assert path.isfile(filename), "File '" + filename + "' does not exist!"
	with open(filename) as file:
		contents = file.read().split('\n')
		dimensions = contents[0].split('x')
		width, height = int(dimensions[0]), int(dimensions[1])
		initial_state = state_from_line(contents[1].split(' '))
		desired_state = state_from_line(contents[2].split(' '))
		return initial_state, desired_state

def _main():
	filename, method = parse_args()
	initial_state, desired_state = puzzle_from_file(filename)

	start_time = time.process_time() # does not include time process was swapped out
	number_of_nodes, solution = strategy_by_name(method)(initial_state, desired_state)
	print("Time taken: " + str(time.process_time() - start_time) + " secs")

	print(filename, method, number_of_nodes)
	if solution != None:
		for action in solution:
			print(action, end='')
	else:
		print("No solution found.")

if __name__ == "__main__":
	_main()


from django.db import models
from api.managers import InvitationManager
from django.contrib.auth.models import User
from api.models import Curso

class Invitation(models.Model):

    code = models.CharField(max_length=50, unique=True)

    issued_by = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='issued_by'
    )
    used_by = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        null=True,
    )

    curso = models.ForeignKey(Curso, on_delete=models.CASCADE)

    used = models.BooleanField(default=False)
    used_at = models.DateTimeField(blank=True, null=True)

    # Manager
    objects = InvitationManager()

    def __str__(self):

        return '#{}: {}'.format(self.curso.curso, self.code)


# programme permettant de créer, écouter et jouer à des histoires intéractives

# fait par Didier Mathias

import tkinter as tk
from tkinter import messagebox
from modules import module_lecture_fichier as read
"""
ajouter un menu d'aide et d'option
"""

def choix(dossier, root = None):
    """
    fonction qui affiche la liste des choix possibles dans un dossier
    parametres:
        dossier, une chaine de caracteres avec le nom du dossier
        root, optionnel, à mentionner si on ne souhaite pas changer de fenetre
    renvoie une fenetre tkinter avec la liste des choix possibles
    """
    liste = read.lister_fichier(dossier)

    if root == None:
        root = tk.Tk()
    else:
        # on nettoie la fenetre
        for c in root.winfo_children():
            c.destroy()

    root.title("Listes des Histoires")
    root.config(bg = "#87CEEB")

    zoneMenu = tk.Frame(root, borderwidth=3, bg='darkblue')
    zoneMenu.grid(row = 0, column = 0, columnspan = len(liste), sticky="NSEW")

    voix = tk.BooleanVar()
    ChoixVoix = tk.Checkbutton(zoneMenu, text='Voix', width='10', borderwidth=2, bg='gray', activebackground='darkorange', relief = "raised",variable = voix, onvalue = True, offvalue = False)
    ChoixVoix.grid(row=0, column=0, sticky="NSEW")

    Ajout = tk.Button(zoneMenu, text = 'Ajout', width='10', borderwidth=2, bg='gray', relief = "raised", command = lambda x=[root, dossier] : ajout(x[0], x[1]))
    Ajout.grid(row=0, column=1, sticky="NSEW")

    """
    ajouter un menu pour changer le font des textes : voir font dans histoire
    changer grid(zoneMenu)
    """

    for i_titre in range(len(liste)):
        # on ouvre un pack.png avec une image a afficher en row 1 column i_titre
        tk.Button(root, height = 5, width = 20, text = liste[i_titre], command = lambda x=[liste[i_titre], voix] : histoire(root, dossier + "/" + x[0], x[1].get())).grid(row = 2, column = i_titre, sticky="NSEW")

    grid(root, 3, len(liste))
    grid(zoneMenu, 1, 2)

    root.mainloop()

def histoire(root, dossier, voix = False):
    """
    fonction qui permet de raconter une histoire au format tkinter
    parametres:
        root, le fenetre tkinter dans laquelle se déroule l'histoire
        dossier, une chaine de caracteres avec le nom du dossier
        voix, optionnel, permet de d'activer la voix synthétique, par défaut False
    """
    root.title(dossier)

    # on nettoie la fenetre
    for c in root.winfo_children():
        c.destroy()

    narration = read.lire_fichier(dossier + "/narration.md")

    def detail_etapes(narration):
        etapes = {}
        i_ligne = 0
        while i_ligne < len(narration):

            if narration[i_ligne][0] == "#":
                numero = narration[i_ligne].split("\r")[0]

                etapes[numero] = []
                i_ligne += 1
                if ":" in narration[i_ligne]:
                    image = narration[i_ligne].split(" : ")[1]
                else:
                    image = ""
                etapes[numero] += [image]
                i_ligne += 1

                texte = ""
                while narration[i_ligne][0] not in ["/", "!"]:
                    texte += narration[i_ligne]
                    i_ligne += 1

                etapes[numero] += [texte]

                choix = []
                while narration[i_ligne][0] != "!":
                    separation = narration[i_ligne][1:].split("/")
                    texte = separation[0]

                    nbr = separation[1].split("\r")[0]
                    choix += [[texte, nbr]]
                    i_ligne += 1

                etapes[numero] += [choix]

            i_ligne += 1
        return etapes

    etapes = detail_etapes(narration)

    i = tk.StringVar()
    i.set("#0")
    forme = [("Comic Sans MS", 15, "bold"), ("Comic Sans MS", 10, "bold")]

    while True:
        nbr = i.get()
        for c in root.winfo_children():
            c.destroy()

        etape = etapes[nbr]
        nbr_column = len(etape[2])

        """
        image en 0-nbr_column 0
        """
        titre = tk.Label(root, text = etape[1], font = forme[0], bg = "#87CEEB")

        if voix:
            parole = ""
            for j in etape[1].split("\r"):
                parole += j + " "
            parler(parole)

            parole_fin = {}
            for j in etape[2]:
                parole_fin[j[1]] = j[0]

        if nbr_column > 0:
            titre.grid(row = 1, column = 0, columnspan = nbr_column, sticky="NSEW")
        else:
            titre.grid(row = 1, column = 0, sticky="NSEW")

        if nbr_column == 0:
            break

        else:
            taille =  "%dp" % (titre.winfo_reqwidth() // nbr_column)
            for i_choix in range(nbr_column):
                tk.Button(root,text = etape[2][i_choix][0], wraplength = taille, font = forme[1], command = lambda x=etape[2][i_choix][1] : i.set(x), bg = "#87CEEB", activebackground = "#87CEEB").grid(row = 2, column = i_choix, sticky="NSEW")

        """
        grid() ne fonctionne pas :
            peut-être taille fenetre : modifier la taille de la fenetre à chaque fois
            grille déjà grande avant : créer une frame le contenu de la fenetre et on le supprime à la place d'enlever chaque élément / changer les zones de création et les suppressions et les grid(root)
        """
        grid(root, 1, nbr_column)

        root.wait_variable(i)
        if voix:
            parole = parole_fin[i.get()]
            parler(parole)

    # FIN
    if voix:
        parler("   FIN")

    tk.Button(root, text = "Fin", font = forme[1], command = lambda x=[dossier, root] : choix(x[0].split("/")[0], x[1]), bg = "#87CEEB", activebackground = "#87CEEB").grid(row = 2, column = 0, sticky="NSEW")

def ajout(root, dossier):
    """
    fonction permettant d'ajouter une histoire
    parametres:
        root, une fenetre tkinter
    """
    def plus():
        """
        sous-fonction qui permet d'ajouter un morceau à l'histoire
        """
        lettres = caracteres(texte.get("1.0", "end"))

        dif_choix = [i.split("/") for i in choice.get("1.0", "end").split("\n")][:-1]
        faire = []
        good = True
        if not fin.get():
            for i in dif_choix:
                if len(i) != 2: # trouver pour éviter qu'il n'y ait pas de reference
                    good = False

        if numero.get() == "":
            messagebox.showerror("Erreur numéro", "Mauvais numéro")
            """
            si checkbox image, vérifier qu'une image a été mise
            """
        elif len(lettres) < 2 and (" " in lettres or "\n" in lettres):
            messagebox.showerror("Erreur texte", "Il faut un texte")
        elif not good:
            messagebox.showerror("Erreur choix", 'Un choix par ligne avec le choix et le numero séparés par "/"')
        elif numero.get() in etapes.keys():
            if messagebox.askyesno("Changement", "Voulez-vous modifier ce numéro ?"):
                etapes[numero.get()] = [texte.get("1.0", "end"), choice.get("1.0", "end")]
        else:
            tk.Button(schema, text=numero.get(), command = lambda x="%s" % numero.get() : restaurer(x, etapes[x][0], etapes[x][1])).grid(row=ligne.get(), column=0, sticky="NSEW")
            grid(schema,ligne.get() ,0)
            ligne.set(ligne.get() + 1)
            if fin.get():
                etapes[numero.get()] = [texte.get("1.0", "end"), False]
            else:
                etapes[numero.get()] = [texte.get("1.0", "end"), choice.get("1.0", "end")]
            """
            si image, la mettre en 3
            """

    def restaurer(N, T, C):
        """
        sous-fonction qui permet d'afficher un morceau dans la fenetre
        parametres:
            N, la référence
            T, le texte
            C, les choix
        """
        numero.set(N)
        texte.delete("1.0", "end")
        if C == False:
            choice.configure(state = "normal")
            choice.delete("1.0", "end")
            choice.configure(state = "disabled")
            fin.set(True)
            f.select()
        else:
            fin.set(False)
            f.deselect()
            choice.configure(state = "normal")
            choice.delete("1.0", "end")
            choice.insert("1.0", C)

        texte.insert("1.0", T)
        """
        restaurez image
        """

    def valider():
        """
        sous-fonction qui permet de construire le dossier qui contiendrat l'histoire
        """
        if not "0" in etapes.keys():
            messagebox.showerror("Pas de début", "Il manque le début d'indice 0")
            """
            vérifier si tous peut fonctionner :
                les references dites existe dans etapes sinon erreur
                les images sont ouvrables
                # il y a une fin
            """
        else:
            titre = str(input("Quel est le titre de votre histoire ?"))
            while read.fichier_existe(dossier + "/" + titre):
                titre = str(input("Ce titre existe déjà, choissisez-en un autre."))
            """
            demander image de l'histoire
            """
            chemin = dossier + "/" + titre
            read.add_repertoire(dossier, titre)

            read.add_repertoire(chemin, "images")

            """
            mettres les images enregistrées
            """

            # changer etapes en 1 fichier
            narration = ""

            for reference, contenu in etapes.items():
                narration += "#" + reference + "\r"
                narration += "False"
                """
                remplacer "False" par "image" si checkbox image
                """
                for L in contenu[0].split("\n"):
                    if L != "":
                        narration += "\r" + L

                if contenu[1] != False:
                    for C in [i.split("/") for i in contenu[1].split("\n")][:-1]:
                        if C != ['']:
                            narration += "\r/ " + C[0] + " /#" + C[1]

                narration += "\r!\r\r"

            read.add_fichier(chemin, "narration.md", narration)
            choix(dossier.split("/")[0], root)

    def vue():
        if fin.get():
            choice.configure(state = "normal")
            fin.set(False)
        else:
            choice.configure(state = "disabled")
            fin.set(True)

    etapes = {}
    root.title("Ajout")

    # on nettoie la fenetre
    for c in root.winfo_children():
        c.destroy()

    """
    schema visuel a  implementer
    schema sous forme de Canvas
    """
    schema = tk.Frame(root, bg = "#87CEEB", borderwidth=3)
    ligne = tk.IntVar()
    ligne.set(0)

    schema.grid(row = 0, rowspan = 6, column = 1, sticky='NSEW')

    # numero
    tk.Label(root, text = "Numéro :", bg = "#87CEEB").grid(row = 0, column = 0, sticky="w")
    numero = tk.StringVar()
    tk.Entry(root, textvariable = numero, width = 40).grid(row = 1, column = 0, sticky='NSEW')

    """
    mettre checkbox image
    si cocher, il faut ouvrir une image
    sinon case désactiver

    on ouvre l'image avec un ouvrir puis on parcours les fichiers
    """

    # texte
    label_texte = tk.Label(root, text = "Texte :", bg = "#87CEEB").grid(row = 2, column = 0, sticky="w")
    texte = tk.Text(root, height = 10, width = 30)
    texte.grid(row = 3, column = 0, sticky='NSEW')

    # choix
    fin = tk.BooleanVar()
    fin.set(False)
    f = tk.Checkbutton(root, text='Choix possible :', width='10', borderwidth=2, bg='#87CEEB', command = lambda x=fin : vue())
    f.grid(row=4, column=0, sticky="w")

    tk.Label(root, text="texte_choix / reference", bg = "#87CEEB").grid(row = 4, column = 0, sticky="e")

    choice = tk.Text(root, height = 10, width = 30)
    choice.grid(row = 5, column = 0, sticky='NSEW')

    # plus
    tk.Button(root, text="+", bg = "#87CEEB", command=plus).grid(row=6, column=0, sticky="NSEW")

    # validation
    tk.Button(root, text="Valider", bg = "#87CEEB", command=valider).grid(row=6, column=1, sticky="NSEW")

    grid(root, 6, 2)
    root.minsize(width=700, height=600)

def grid(root, R, C):
    for i in range(R):
        root.grid_rowconfigure(i, weight=1)
    for i in range(C):
        root.grid_columnconfigure(i, weight=1)

def parler(texte):
    """
    fonction permettant de dire un texte --> Text-to-Speech
    parametres:
        texte, une chaine de caracteres à dire
    """
    import pyttsx3

    engine = pyttsx3.init()
    engine.setProperty('rate', 150) # mettre rate à 150 permet d'avoir un débit raisonnable

    engine.say(texte)
    engine.runAndWait()

def caracteres(texte):
    """
    fonction permettant d'obtenir une liste de tous les caracteres distinct présent dans une chaine de caracteres
    parametres:
        texte, une chaine de caracteres
    renvoie une liste de caracteres
    """
    lettres = []

    for caractere in texte:
        if caractere not in lettres:
            lettres += [caractere]

    return lettres

if __name__ == '__main__':
    choix("histoires")


import hashlib, random, time, json

def convert_base(num, to_base=10, from_base=10):
    # first convert to decimal number
    if isinstance(num, str):
        n = int(num, from_base)
    else:
        n = int(num)
    # now convert decimal to 'to_base' base
    alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    if n < to_base:
        return alphabet[n]
    else:
        return convert_base(n // to_base, to_base) + alphabet[n % to_base]

block_time = 5 * 60
start = time.time()
finish = start + block_time

print(start)
print(finish)

#exit()

hash_arr = []
obj = json.loads('{"miner_adress": "XIhhtD5BprFlsnObmDyxL5xc5QUCX4uKn6839Y4DBpKsnZRMtmhdeMDfVtkKRIZn", "hash_last_block": "hashaaaaaaaaa", "timestamp": 1513948552.0508235, "difficulty": 50, "bust": 87700948419, "transaction": {"from": "XIhhtD5BprFlsnObmDyxL5xc5QUCX4uKn6839Y4DBpKsnZRMtmhdeMDfVtkKRIZn", "to": "yMqqoiz28LIvvyvJ2VDFOHbd2ggASSTiEBssUSkC9QRZ7Fy3p6LCySh/ok4yWqH0", "count": 10, "fee": 0, "sign": "wnERxJEqC5OWxOGBwelJx0CgDSDpv3T6iFmsK2AOiMG8mSisXKbHieDvVJHwxwyQ"}}')

print(obj)

a = -1

while True:
    a += 1

    obj['bust'] = str(a)
    msg = json.dumps(obj)

    m = hashlib.sha1()
    m.update(msg.encode('utf-8'))
    hash = m.hexdigest()

    digit = convert_base(hash, 10, 16)
    print(digit)
    hash_arr.append(int(digit))

    if (time.time() > finish):
        break

print(len(hash_arr))
print(a)
hash_arr.sort()
print(hash_arr[0])


import numpy as np

from sort.sort import *

from pylot.perception.detection.utils import BoundingBox2D, DetectedObstacle
from pylot.perception.tracking.multi_object_tracker import MultiObjectTracker

class MultiObjectSORTTracker(MultiObjectTracker):
    def __init__(self, flags):
        self.tracker = Sort()

    def reinitialize(self, frame, obstacles):
        """ Reinitializes a multiple obstacle tracker.

        Args:
            frame (:py:class:`~pylot.perception.camera_frame.CameraFrame`):
                Frame to reinitialize with.
            obstacles : List of perception.detection.utils.DetectedObstacle.
        """
        detections = self.convert_detections_for_sort_alg(obstacles)
        self.tracker.update(detections)

    def track(self, frame):
        """ Tracks obstacles in a frame.

        Args:
            frame (:py:class:`~pylot.perception.camera_frame.CameraFrame`):
                Frame to track in.
        """
        # each track in tracks has format ([xmin, ymin, xmax, ymax], id)
        obstacles = []
        for track in self.tracker.trackers:
            coords = track.predict()[0].tolist()
            # changing to xmin, xmax, ymin, ymax format
            bbox = BoundingBox2D(int(coords[0]), int(coords[2]),
                                 int(coords[1]), int(coords[3]))
            obstacles.append(DetectedObstacle(bbox, 0, "", track.id))
        return True, obstacles

    def convert_detections_for_sort_alg(self, obstacles):
        converted_detections = []
        for obstacle in obstacles:
            bbox = [
                obstacle.bounding_box.x_min, obstacle.bounding_box.y_min,
                obstacle.bounding_box.x_max, obstacle.bounding_box.y_max,
                obstacle.confidence
            ]
            converted_detections.append(bbox)
        return np.array(converted_detections)


import unittest
from datetime import datetime

from dateutil.tz import tzutc, tzlocal

from t77_date.tz import to_utc

class ToUtcTestCase(unittest.TestCase):
    def test_datetime_in_utc(self):
        value_in = datetime.now(tz=tzutc())
        value_out = to_utc(value_in)
        self.assertIsInstance(value_out, datetime)
        self.assertEqual(value_out.tzinfo, tzutc())
        self.assertEqual(value_out, value_in)

    def test_datetime_in_local(self):
        value_in = datetime.now(tz=tzlocal())
        value_out = to_utc(value_in)
        self.assertIsInstance(value_out, datetime)
        self.assertEqual(value_out.tzinfo, tzutc())

    def test_datetime_without_tzinfo(self):
        value_in = datetime.now()
        value_out = to_utc(value_in)
        self.assertIsInstance(value_out, datetime)
        self.assertEqual(value_out.tzinfo, tzutc())

    def test_invalid_input(self):
        now = datetime.now()
        with self.assertRaises(ValueError):
            to_utc(None)
        with self.assertRaises(ValueError):
            to_utc(now.toordinal())
        with self.assertRaises(ValueError):
            to_utc(now.isoformat())


# -*- coding: utf-8 -*-

from io import open
from re import sub
from os import listdir
from collections import Counter

from nltk.stem.snowball import SnowballStemmer
from nltk import sent_tokenize, word_tokenize, ngrams

from utils import constants

stemmer = SnowballStemmer("english")

def filter_stop_words(words):
    return filter(lambda w: w not in constants.stopWords, words)

def stem_all_words(words):
    stems = [stemmer.stem(w) for w in words]
    return stems

def get_all_words(all_docs):
    all_words = set()
    for doc in all_docs:
        [all_words.add(k) for k in doc.keys()]

    return all_words

def read_all_documents():
    all_docs = []
    # i = 0
    for file in listdir("training_data"):
        # if i == 2: break

        with open("training_data/"+file, 'r', encoding='utf8') as f:
            doc = f.read().lower()
            f.close()

            if file == "englishText_0_10000":
                doc = doc.split("endofarticle.")
                all_docs += doc
            else:
                all_docs.append(doc)

    return all_docs

def tokenize_document(document):
    sentences = sent_tokenize(document)
    tokens = []
    for sentence in sentences:
        sentence = sub(r'[^\w\s]', ' ', sentence)

        tokens += [w for w in filter_stop_words(word_tokenize(sentence))]

    stemmed_tokens = stem_all_words(tokens)

    return tokens, stemmed_tokens

def get_tokenized_document(filename):
    """
    Tokenizer for test data
    :param filename: Name of file presesnt in test_data directory
    :return: returns tokenized data
    """

    with open(filename, 'r', encoding='utf8') as f:
        doc = f.read().lower()
        f.close()

    # doc, stemmed = tokenize_document(doc)
    doc, stemmed = tokenize_document_v2(doc)
    doc = Counter(stemmed)

    # print doc

    return doc

def joiner(words):
    tokens = []
    for w in words:
        x = filter_stop_words(w)

        if len(x) != 2:
            continue

        x = ' '.join(x)
        tokens.append(x)

    tokens = filter(lambda x1: x1 != '', tokens)
    return tokens

def get_bigrams(sentence):
    words = word_tokenize(sentence)
    bigrams = list(ngrams(words, 2))
    bigrams = joiner(bigrams)

    return bigrams

def tokenize_document_v2(document):
        sentences = sent_tokenize(document)
        tokens = []
        for sentence in sentences:
            sentence = sub(r'[^\w\s]', ' ', sentence)
            bigrams = get_bigrams(sentence)
            tokens += [w for w in filter_stop_words(word_tokenize(sentence))]
            tokens += bigrams

        stemmed_tokens = stem_all_words(tokens)
        return tokens, stemmed_tokens


# Object Oriented Programming

"""Class is the blueprint of how object will be created
    Object is the real life entity for the given class"""

'''There are 2 types of attributes associated to python classes
    1. class attributes
    2. instance attributes'''

class Employee:
    company = "Google"

    def __init__(self, name):
        print("\nConstructor run -> Employee created\n")
        self.name = name

    def getSalary(self, signature):
        print(f"\nSalary is ${self.salary} for leo working at company {self.company}, not in {Employee.company}"
              f"\n{signature}")
        # Here self.salary is not defined yet so there might be a runtime error if not defined later
        # In any function, 'self' can be changed to any other valid identifier and will work fine, bu writing self is
        # a best practice

    @staticmethod
    def greet():
        print("Good morning from leo")
    # Here self is not required as @staticmethod makes this method static, hence not related to an object but the class
    # @staticmethod is a decorator which modifies a function

leo = Employee("leo")
leo.company = "Facebook"
leo.salary = 5000

print("Name is: ", leo.name)
print("Company is: ", leo.company)  # This is an instance attribute as it has preference over class attribute
print("Salary is: ", leo.salary)  # This is an instance attribute
print("Employee company is: ", Employee.company)  # This is a class attribute
'''Whenever object.attribute is called, the attribute is searched as an instance attribute, if it is not present
    then it is searched as a class attribute. Instance attribute takes preference over class attribute during
    assignment and retrieval'''

# 'self' parameter
'''self refers to the instance of the class which is automatically passed with a function call from an object

    Internally, leo.getSalary() is converted to Employee.getSalary(leo)
    Hence the self parameter is always passed and it will receive the object through which it is called'''

leo.getSalary("Cheers!")
leo.greet()

# Constructor (__init__())

'''__init__() is the first method which runs as soon as an object is created.
    It takes self as an argument and can also take other arguments'''


import math
import time
from PIL import ImageGrab
import pytesseract
import winsound
import os

#---------------USER-CUSTOMIZABLE-SETTINGS---------------#
pytesseract.pytesseract.tesseract_cmd = r'C:\Users\Evan\AppData\Local\Tesseract-OCR\tesseract.exe'
    #path of tesseract.exe (should just have to change USERSNAME if installed in default location

ExecutableCodeFileLocation = r'C:\Users\Evan\Desktop\Fortnite Build Warning Bot'
    #Location of 'Executable Code'
    #Can be found by right click on 'Executable Code' file > Properties > Then highlight and copy Location
    #YOU MUST LEAVE 'Executable Code' file in the folder with the 3 sound files
    #You can rename the folder if desired

RES = (2560, 1440) #must be 16:9
    #resolution of your monitor
#--------------------------------------------------------#

running = ''
winsound.Beep(300, 300)

CommonZero = ['QO', 'Q0', 'Oo', '0o', 'Q', 'O', 'o', '0']
Wood, Brick, Metal, Builds = 0, 0, 0, 0
Ready20, Ready10, Ready5 = False, False, False

HorizontalConst = ((2310/2560), (2880/2880)) #factors found in photoshopr
VerticalConst = ((1020/1440), (1060/1440))

X1 = math.floor(RES[0] * HorizontalConst[0]) #round down to make sure nothing is cut off
X2 = math.floor(RES[0] * HorizontalConst[1]) #round down to make sure not outside of the screen
Y1 = math.floor(RES[1] * VerticalConst[0])
Y2 = math.floor(RES[1] * VerticalConst[1])

while True:
    time.sleep(0.5)

    screenshot = ImageGrab.grab(bbox=(X1, Y1, X2, Y2))
    screenshot = screenshot.point(lambda x: 255 if x<255 else 0)
    #screenshot.show()

    Materials = pytesseract.image_to_string(screenshot, lang='eng', config='--psm 7')

    if len(Materials.split()) == 3: #just ignore if we do not find 3 strings
        Materials = Materials.split()

        if Materials[0].isdigit() == True:
            Wood = int(Materials[0])
        elif Materials[0] in CommonZero:
            Wood = 0

        if Materials[1].isdigit() == True:
            Brick = int(Materials[1])
        elif Materials[1] in CommonZero:
            Brick = 0

        if Materials[2].isdigit() == True:
            Metal = int(Materials[2])
        elif Materials[2] in CommonZero:
            Metal = 0

        Builds = math.floor(Wood/10) + math.floor(Brick/10) + math.floor(Metal/10)

    if Builds < 20 and Ready20 == True:
        winsound.PlaySound(ExecutableCodeFileLocation + r'\20builds.wav', winsound.SND_ASYNC)
        Ready20 = False
    elif Builds < 10 and Ready10 == True:
        winsound.PlaySound(ExecutableCodeFileLocation + r'\10builds.wav', winsound.SND_ASYNC)
        Ready10 = False
    elif Builds < 5 and Ready5 == True:
        winsound.PlaySound(ExecutableCodeFileLocation + r'\5builds.wav', winsound.SND_ASYNC)
        Ready5 = False

    if Builds > 30:
        Ready20, Ready10, Ready5 = True, True, True

    if len(running) == 3:
        running = "."
    else:
        running = running + '.'
    os.system('cls')
    print("Bot is running" + running)
    print("Current Builds: " + str(Builds))

Fortnite Build Warning Bot/Executable Code.py


import sys
import os,datetime,time,fileinput
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from ConfRead import Conf
from PyQt5.QtGui import *
#from Program import SecondWindow

class UI_FifthTab(object):
    def setupUi(self, Form):
        self.LabelSrc=QLabel('请选择源路径',self)
        self.LineSrc =QLineEdit(Conf().GetLastFile_LabelSrc)
        self.BtnSrc = QPushButton('Src', self)
        #self.BtnSrc.clicked.connect(self.ButtonSrcShowDialog)

        self.LabelDst=QLabel('请选择目标路径',self)
        self.LineDst =QLineEdit(Conf().GetLastFile_LabelDst,self)
        self.BtnDst = QPushButton('Dst', self)
        #self.BtnDst.clicked.connect(self.ButtonDstShowDialog)

        self.CheckBoxKeyFile=QCheckBox('仅提取指定文件(文件名请用逗号隔开)',self)
        self.LineKeyFile=QLineEdit('',self)

        upgrid=QGridLayout()
        #grid.setSpacing(10)
        upgrid.addWidget(self.LabelSrc,1,0)
        upgrid.addWidget(self.LineSrc,1,1)
        upgrid.addWidget(self.BtnSrc,1,2)
        upgrid.addWidget(self.LabelDst,2,0)
        upgrid.addWidget(self.LineDst,2,1)
        upgrid.addWidget(self.BtnDst,2,2)
        upgrid.addWidget(self.CheckBoxKeyFile,3,0,Qt.AlignRight)
        upgrid.addWidget(self.LineKeyFile,3,1,)
        upgrid.setColumnStretch(0,1)
        upgrid.setColumnStretch(1,3)

        self.LabelTime=QLabel('请输入时间差，单位：小时',self)
        self.SpinBoxTime=QDoubleSpinBox()
        self.SpinBoxTime.setValue(1.00)
        self.SpinBoxTime.setMaximum(720.00)
        self.BtnGetLastFile=QPushButton('GetLastFile',self)
        #self.BtnGetLastFile.clicked.connect(self.FirstSinalEmit)

        h0layout=QHBoxLayout()
        h0layout.addWidget(self.LabelTime)
        h0layout.addWidget(self.SpinBoxTime)
        h0layout.addWidget(self.BtnGetLastFile)

        vlayout=QVBoxLayout()
        vlayout.addLayout(h0layout)

        MainGrid=QGridLayout()
        MainGrid.addLayout(upgrid,0,0)
        MainGrid.addLayout(vlayout,1,0)
        self.setLayout(MainGrid)

        #self.setWindowIcon(QIcon('image/icon.png'))
        self.setWindowTitle('DFRZ DeployTool')


import math
a0=-1
t=-1
w10=float(input("Enter weight first network"))
b10=float(input("Enter base first network:"))
w20=float(input("Enter weight second network:"))
b20=float(input("Enter base second network:"))
c=float(input("Enter learning coefficient:"))
n1=float(w10*c+b10)
a1=math.tanh(n1)
n2=float(w20*a1+b20)
a2=math.tanh(float(n2))
e=t-a2
s2=-2*(1-a2*a2)*e
s1=(1-a1*a1)*w20*s2

w21=w20-(c*s2*a1)
w11=w10-(c*s1*a0)
b21=b20-(c*s2)
b11=b10-(c*s1)
print("The updated weight of first n/w w11=",w11)
print("The uploaded weight of second n/w w21= ",w21)
print("The updated base of first n/w b10=",b10)
print("The updated base of second n/w b20= ",b20)


# -*- coding: utf-8 -*-
#----------------------------------------------------------------------------
#
#    Copyright (C) 2017  .
#    Coded by : Mohsen Dhifallah
#
#----------------------------------------------------------------------------
from openerp.report import report_sxw
import time
from openerp.osv import osv

class report_declaration_employer(report_sxw.rml_parse):

    def __init__(self, cr, uid, name, context):
            super(report_declaration_employer, self).__init__(cr, uid, name, context=context)
            self.localcontext.update({
            'time': time,
            'get_declaration_employer':self._get_declaration_employer
          #  'get_foprolos':self._get_foprolos,
        })

#     def _get_declaration_employer(self,fiscalyear_id) :
#         bulletin_obj = self.pool.get('hr.payroll.bulletin')
#         bulletin_ids = bulletin_obj.search(self.cr, self.uid,
#                                            [('month_id.period_id.fiscalyear_id','=',fiscalyear_id)],
#
#                                            )
#         salaire_brute_imposable=0.0
#         total_salaire_brute_imposable=0.0
#
#         for line in bulletin_obj.browse(self.cr,self.uid,bulletin_ids) :
#             employee_id = line.employee_id.name
#             salaire_brute_imposable += line.salaire_brute_imposable
#             total_salaire_brute_imposable += line.salaire_brute_imposable
#
#         return { 'employee_id' : employee_id,
#                 'salaire_brute_imposable' : salaire_brute_imposable,
#                 'total_salaire_brute_imposable' : salaire_brute_imposable,
#
#               }

    def _get_total_salaire_imposable(self,fiscalyear_id,context=None):
        salaire_obj=self.pool.get('hr.payroll.bulletin')
        search_ids=salaire_obj.search(self.cr,self.uid,[('month_id.period_id.fiscalyear_id','=',fiscalyear_id)],context)
        total=0.0
        for line in salaire_obj.browse(self.cr,self.uid,search_ids) :
            total += line.salaire_brute_imposable
        return total

    def _get_declaration_employer(self,fiscalyear_id,context=None):
        salaire_obj=self.pool.get('hr.payroll.bulletin')
        search_ids=salaire_obj.search(self.cr,self.uid,[('month_id.period_id.fiscalyear_id','=',fiscalyear_id)],context)
        employees={}
        for sal in salaire_obj.browse(self.cr,self.uid,search_ids) :
            if sal.employee_id.id in employees:
                employees[sal.employee_id.id]['salaire_brute_imposable'] += sal.salaire_brute_imposable
                employees[sal.employee_id.id]['irpp'] += sal.igr
            else :
                val={'employee_id':sal.employee_id.name,'salaire_brute_imposable':sal.salaire_brute_imposable,'irpp':sal.igr}
                employees[sal.employee_id.id] = val

        result=[]
        for key, val in employees.items():
            result.append(val)

        return result

#     def _get_foprolos(self,month_id,context=None):
#         payement_obj=self.pool.get('hr.payroll.bulletin')
#         search_ids=payement_obj.search(self.cr,self.uid,[('month_id', '=', month_id[0])],context)
#         total=0.0
#         for paymnt in payement_obj.browse(self.cr,self.uid,search_ids) :
#             total += paymnt.salaire_brute/100
#         return total

class declaration_employer_report(osv.AbstractModel):
    _name = 'report.devplus_hr_payroll_tn.declaration_employer_report'
    _inherit = 'report.abstract_report'
    _template = 'devplus_hr_payroll_tn.declaration_employer_report'
    _wrapped_report_class = report_declaration_employer