import pandas as pd
import numpy as np
import StrategySignal as signal
import LoadHistoryData as getData

class Strategy:
    account = None
    database = None
    volume = 10
    stopPoint = 0
    initial_stopPoint = 0.02
    reset = False
    profitPoint = 4
    assetList = ['Asset'+ str(i) for i in range(1,28)]
    freq = 'M' #frequency
    gain = 0
    maxGain = 0

    def __init__(self,account):
        self.account = account
        self.database = account.database

    def strategy(self):
    ################### order ###############################
        #filter the assets whose prices does not change
        self.account.cancellAllOrder()
        assetTradeList = []
        for asset in self.assetList:
            if sum(self.account.currentPrice[asset].values()) != 4:
                assetTradeList.append(asset)

        entryList = []
        exitList = []
        holdList = []
        stop_profit_List = []

        for asset in assetTradeList:
            position = self.account.position[asset]
            self.cal_gain(asset) #calculate gain
            self.setStopPoint(asset) #reset stop point
            #signal
            entrySig = self.entrySignal(asset)
            exitSig = self.exitSignal(asset)

            if entrySig==exitSig:
                exitSig = 0 #in case of redundant exit

            if entrySig != 0:
                #opposition position signal
                if not ((entrySig == 1 and self.account.position[asset]>0) \
                    and (entrySig == -1 and self.account.position[asset]<0)):
                    entryList.append(asset) #in asset
            if exitSig != 0:
                exitList.append(asset) # out asset
            if position != 0:
                holdList.append(asset)

            #stop loss & take profit
            if entrySig==0 and exitSig==0: #exit
                stop = self.stopLoss(asset)
                profit = self.takeProfit(asset)
                if stop or profit:
                    stop_profit_List.append(asset)

            #exit
            self.exit(asset,exitSig,abs(position)) #should use abs in case of short position

        #after exit
        now_holdList = list(set(holdList)-set(exitList)-set(stop_profit_List))

        #at this time should hold
        finalList = list((set(now_holdList)|set(entryList)))
        new_holdList = list(set(entryList)-set(now_holdList))
        unchangeList = list(set(now_holdList)-set(entryList))

        #1/n should hold this value for each in asset
        seperated_value = 0.9 * self.account.value/len(finalList)

        if entryList: #new entry
            disp_bal = self.account.disposable_balance
            if disp_bal < seperated_value*len(new_holdList):
                self.rebalance(unchangeList,seperated_value)

            for asset in entryList:
                close = self.account.currentPrice[asset]['close']
                #opposite order does not change other assets
                if asset in now_holdList:
                    self.volume = int(abs(self.account.position[asset])/1.1)
                else:
                    self.volume = seperated_value//close #should hold this volume
                if self.volume == 0:
                    continue
                #entry
                entrySig = self.entrySignal(asset) #signal
                self.entry(asset,entrySig)

    #########################################################

    def onBar(self):
        self.strategy()

    def entrySignal(self,asset):
        bar = self.account.currentData[asset]
        maSignal, _ = signal.maBreak(bar,15)
        atrStatus, _, _ = signal.atrStatus(bar,10,50)
        entrySignal = 0
        if maSignal == 1 and atrStatus == 1:
            entrySignal = 1
        elif maSignal == -1 and atrStatus == 1:
            entrySignal = -1
        else:
            entrySignal = 0
        return entrySignal

    def exitSignal(self,asset):
        bar = self.account.currentData[asset]
        MACD, _, _ = signal.MACD(bar,20,50)
        maStatus, _ = signal.maStauts(bar,20)
        exitSignal = 0
        if MACD == 1 and maStatus==1:
            exitSignal = 1
        elif MACD == -1 and maStatus==-1:
            exitSignal = -1
        else:
            exitSignal = 0
        return exitSignal

    def entry(self,asset,entrySig):
        position = self.account.position[asset]
        close = self.account.currentPrice[asset]['close']
        if entrySig == 1:
            if position<0:
                self.account.cover(asset,abs(position)) #positon < 0
                self.account.buy(asset,close*1.01,self.volume)
            elif position==0:
                self.account.buy(asset,close*1.01,self.volume)
        elif entrySig == -1:
            if position>0:
                self.account.sell(asset,position)
                self.account.short(asset,close*0.99,self.volume)
            elif position==0:
                self.account.short(asset,close*0.99,self.volume)

    def exit(self,asset,exitSig,volume):
        position = self.account.position[asset]
        if exitSig == 1:
            if position<0:
                self.account.cover(asset,volume)
        elif exitSig == -1:
            if position>0:
                self.account.sell(asset,volume)

    def stopLoss(self,asset):
        position = self.account.position[asset]
        #trailing stoploss
        if position>0:
            transaction = self.account.transaction[asset]
            if (self.maxGain-self.gain)/transaction > self.stopPoint:
                self.account.sell(asset,position)
                return True
        elif position<0:
            transaction = self.account.transaction[asset]
            if (self.maxGain-self.gain)/transaction > self.stopPoint:
                self.account.cover(asset,-position)
                return True
        return False

    def takeProfit(self,asset):
        close = self.account.currentPrice[asset]['close']
        position = self.account.position[asset]
        if position>0:
            transaction = self.account.transaction[asset]
            if (close - transaction)/transaction > self.profitPoint:
                self.account.sell(asset,position)
                return True
        elif position<0:
            transaction = self.account.transaction[asset]
            if (close - transaction)/transaction < -self.profitPoint:
                self.account.cover(asset,-position)
                return True
        return False

    def setStopPoint(self,asset):
        bar = self.account.currentData[asset]
        position = self.account.position[asset]
        rsiStatus, _ = signal.rsiStatus(bar, 10)

        if position != 0:
            transaction = self.account.transaction[asset]
            if not self.reset:
                if (position>0 and rsiStatus == 1) or (position<0 and rsiStatus == -1)\
                or ((self.gain/transaction)>0.2): #narrow stop point
                    self.stopPoint = round(self.stopPoint*0.5,3)
                    self.reset = True
        else: #reset
            self.stopPoint = self.initial_stopPoint
            self.reset = False

    def rebalance(self,hold,seperated_value):
        for asset in hold:
            close = self.account.currentPrice[asset]['close']
            position = self.account.position[asset]
            #reset volume
            self.volume = seperated_value//close #should hold this volume
            #excess volume
            exitVolume = 0
            if position!=0:
                if self.volume<abs(position):
                    exitVolume = abs(position)-self.volume
                    #exit
                    if position > 0:
                        self.exit(asset,-1,exitVolume)
                    else:
                        self.exit(asset,1,exitVolume)

    def cal_gain(self,asset):
        high = self.account.currentPrice[asset]['high']
        low = self.account.currentPrice[asset]['low']
        position = self.account.position[asset]

        if position==0:
            self.maxGain = 0
            self.gain = 0
        elif position>0:
            transaction = self.account.transaction[asset]
            self.gain = high-transaction
            self.maxGain = max(self.maxGain,self.gain)
        elif position<0:
            transaction = self.account.transaction[asset]
            self.gain = transaction-low
            self.maxGain = max(self.maxGain,self.gain)


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:
        res = []
        prev = None
        curr = head
        index = 0

        while curr:
            index += 1
            if prev and curr.next:
                p, n = prev.val, curr.next.val
                if curr.val > p and curr.val > n or curr.val < p and curr.val < n:
                    res.append(index)

            prev = curr
            curr = curr.next

        if len(res) < 2: return [-1, -1]

        mmin = float('inf')
        for i in range(1, len(res)):
            mmin = min(mmin, res[i] - res[i - 1])

        return [mmin, max(res) - min(res)]


name = input("Name of File:")
text_file = open(name)
lines = text_file.read().split('\n')
text_file.close()

name += "_Output"
text_file = open(name, 'w')

def Reg(s): #takes the register name, returns the binary representation
    if (s == "$0"):
        return "000"
    elif (s == "$gp"):
        return "001"
    elif (s == "$sp"):
        return "010"
    elif (s == "$ra8"):
        return "011"
    elif (s == "$r0"):
        return "100"
    elif (s == "$r1"):
        return "101"
    elif (s == "$r2"):
        return "110"
    elif (s == "$r3"):
        return "111"
    else:
        return "error"

varname = []
varaddress = []
i = int(0) #byte of output
x = int(0) #line of input

while lines[x][0]=="-": #.data section

    words = lines[x].split(" ")

    if (words[0].lower() == "-string"):
        varname.append(words[1])
        varaddress.append(int(i/2))

        for ch in words[2]:
            text_file.write('{0:08b}'.format(ord(ch)))
            i = i+1

            if (i%2 == 0):
                text_file.write("\n")

        x = x+1
        text_file.write("00000000") #end string with newline
        i = i+1

        if (i%2 == 1): #if odd number of bytes printed, print 00000000 to make it even
            text_file.write("00000000\n")
            i = i+1
        else:
            text_file.write("\n")

    elif (words[0].lower() == "-int"):
        varname.append(words[1])
        varaddress.append(int(i/2))
        text_file.write("00000000"+ words[2]+"\n") #8 bit binary number in 16 bits
        x = x+1
        i = i+2

i = int(i/2) #change from byte of output to line of output

if (i>=256):
    print ("Data too large")
    exit

text_file.write("@100\n") #tells verilog that the next section is the instruction section

i = 256

while (lines[x].split(" ")[0].lower() != "eof"): #instruction section

    words = lines[int(x)].split(" ")
    new_line = ""
    word = ""
    word += words[0].lower() #lowercase

    if (word == "add"):
        new_line += "00"
        new_line += Reg(words[1])
        new_line += Reg(words[2])
        new_line += "00000000"

    if (word == "nand"):
        new_line += "01"
        new_line += Reg(words[1])
        new_line += Reg(words[2])
        new_line += "00000000"

    if (word == "slt"):
        new_line += "10"
        new_line += Reg(words[1])
        new_line += Reg(words[2])
        new_line += "00000000"

    if (word == "move"):
        new_line += "11000"
        new_line += Reg(words[1])
        new_line += "00000000"

    if (word == "srl"):
        new_line += "11001"
        new_line += '{0:03b}'.format(int(words[1]))[-3:]
        new_line += "00000000"

    if (word == "jrra"):
        new_line += "11010"
        a = Reg(words[1])

        if (a=="error"):
            new_line += words[1]

        else:
            new_line += a

        new_line += "00000000"

    if (word == "jal"):
        new_line += "11011"
        new_line += '{0:011b}'.format(int(words[1]))[-11:]

    if (word == "sw"):
        new_line += "11100"
        new_line += Reg(words[1])
        new_line += Reg(words[2])
        new_line += words[3]

    if (word == "addi"):
        new_line += "11101"
        new_line += Reg(words[1])
        new_line += words[2]

    if (word == "lw"):
        new_line += "11110"
        new_line += Reg(words[1])
        new_line += Reg(words[2])
        new_line += words[3]

    if (word == "beq"):
        new_line += "11111"
        new_line += Reg(words[1])
        new_line += Reg(words[2])
        new_line += words[3]
        new_line += Reg(words[4])

    if (word == "printstr"):
        new_line += "11101000"
        new_line += '{0:b}'.format(varaddress[varname.index(words[1])]).zfill(8)
        new_line += "1101000100000000"
        i+=1

    if (word == "printint"):
        new_line += "11101000"
        new_line += '{0:b}'.format(varaddress[varname.index(words[1])]).zfill(8)
        new_line += "1101001000000000"

    if (word == "la"):
        new_line += "11101000"
        new_line += '{0:b}'.format(varaddress[varname.index(words[1])]).zfill(8)

    text_file.write(new_line[8:16])
    text_file.write(new_line[0:8])
    text_file.write("\n")

    if (word == "printstr" or word == "printint"): #second line of two line pseudoinstructions
        text_file.write(new_line[24:32])
        text_file.write(new_line[16:24])
        text_file.write("\n")
        i+=1

    if (i>=2048):
        print ("Instructions too long")
        exit
    x+=1
    i+=1

text_file.close()


l = [11, 35, 17, 15, 5]
print(l)

# TO-DO: Complete the selection_sort() function below
def selection_sort(l=l):
    # loop through n-1 elements
    for i in range(0, len(l) - 1):
        cur_index = i
        smallest_index = cur_index
        for j in range(cur_index, len(l)):
            if l[smallest_index] > l[j]:
                l[smallest_index],l[j] = l[j],l[smallest_index]
    return l

# TO-DO:  implement the Bubble Sort function below
def bubble_sort(l=l):
    swapped = True
    while swapped == True:
        swapped = False
        for index in range(len(l)-1):
            # print(index)
            if l[index] > l[index+1]:
                # print("before:",l[index],l[index+1])
                l[index],l[index+1] = l[index+1],l[index]
                swapped = True
            #     print("after:",l[index],l[index+1])
            #     print("bigger:",index)
            # else:
            #     print("smaller:",index)
    return l

# STRETCH: implement the Count Sort function below
def count_sort( arr, maximum=-1 ):

    return arr

if __name__ == "__main__":

    print(selection_sort())
    print(bubble_sort())


#!/usr/bin/env python
# encoding: utf-8
'''
@File  : 002_number_factorial.py
@Date  : 2021/11/1 22:30
@Author: Cxs
@Email: Cxs1103@163.com
@Desc  :
'''

def factorial(number):
    result = 1
    while number > 0:
        result *= number
        number -= 1
    return result

print(f'6 的阶乘是：', factorial(6))
print(f'10 的阶乘是：', factorial(10))


#coding:utf-8
from PIL import Image

import overfeat
import tensorflow as tf
from tensorflow.python.platform import test
from common import read_data
import numpy as np
from tensorflow.python import debug as tfdbg
import os

num_classes = 5749
train_batch_size = 50
train_height, train_width = 231, 231
train_channel = 3

# 测试overfeat
class OverFeatTest(test.TestCase):
 def testTrainEvalWithReuse(self):
     train_batch_size = 2
     eval_batch_size = 1
     train_height, train_width = 231, 231
     eval_height, eval_width = 281, 281
     num_classes = 1000
     with self.test_session():
         # 训练阶段
         train_inputs = tf.Variable(tf.random_uniform(
             [train_batch_size, train_height, train_width, 3]))
         logits, _ = overfeat.overfeat(train_inputs)
         self.assertListEqual(logits.get_shape().as_list(),
                              [train_batch_size, num_classes])
         tf.get_variable_scope().reuse_variables()
         # 评估阶段
         eval_inputs = tf.random_uniform(
             (eval_batch_size, eval_height, eval_width, 3))
         logits, _ = overfeat.overfeat(
             eval_inputs, is_training=False, spatial_squeeze=False)
         self.assertListEqual(logits.get_shape().as_list(),
                              [eval_batch_size, 2, 2, num_classes])
         # 评估获得正确率
         logits = tf.reduce_mean(logits, [1, 2])
         predictions = tf.argmax(logits, 1)
         self.assertEquals(predictions.get_shape().as_list(), [eval_batch_size])

def get_inputs(n = None):
    """
    获取输入
    :return:
    """
    labels, filenames = read_data.get_lfw_paths(n) #[index, path]
    # 文件名的queue，已经包含了enqueue_many操作，已经定义了一个queue runner处理enqueue操作
    filenames_queue = tf.train.string_input_producer(filenames, shuffle=False)
    labels_queue = tf.train.input_producer(labels, shuffle=False)
    # filename = filenames_queue.dequeue()
    # 从queue中dequeue一个文件名，并读取数据
    reader = tf.WholeFileReader()
    filename, image = reader.read(filenames_queue)
    label = labels_queue.dequeue()
    # 解码数据
    #  tf.image.decode_jpeg对图片进行解码，如果用decode_raw结果是不一样的
    image = tf.image.decode_jpeg(image)
    image = tf.cast(image, tf.float32)
    image = tf.reshape(image, [250, 250, train_channel])
    image = tf.random_crop(image, [train_height, train_width, train_channel])
    label = tf.cast(label, tf.int32)
    # 创建一个shuffle queue，并添加enqueue以及dequeue操作
    images, filenames, labels = tf.train.shuffle_batch(
        [image, filename, label],
        batch_size=train_batch_size,
        num_threads=4,
        capacity=2 + 3 * train_batch_size,
        min_after_dequeue=0
    )
    return images, filenames, labels
    #return filename, image, label

def train_LFW():
    # 读取数据
    images, filenames, labels0 = get_inputs()

    images = tf.nn.batch_normalization(images, 0, 1, 0, 1, 10e-8)
    coord = tf.train.Coordinator()
    with tf.Session() as sess:
        #sess = tfdbg.LocalCLIDebugWrapperSession(sess)
        # 前向传播
        logits, fc8 = overfeat.overfeat(images, num_classes)
        # 计算loss函数
        cross_entropy = overfeat.loss(logits, labels0, train_batch_size, num_classes)
        # 反向求导，梯度下降
        train_step = tf.train.AdamOptimizer(0.05).minimize(cross_entropy)

        # 保存数据
        saver = tf.train.Saver(tf.all_variables())
        merged = tf.summary.merge_all()
        tb_writer = tf.summary.FileWriter("../result/overfeat")
        # 执行
        sess.run(tf.global_variables_initializer())
        qrs = tf.train.start_queue_runners(sess=sess, coord=coord)
        for i in range(1000):
            cross_entropy_, summary, _ = sess.run([cross_entropy, merged, train_step])
            print(cross_entropy_)
            # 保存数据
            if i % 100 == 0:
                tb_writer.add_summary(summary, i)
            if i % 100 == 0 or (i + 1) == 1000:
                checkpoint_path = os.path.join("./result/overfeat/model", 'model.ckpt')
                saver.save(sess, checkpoint_path, global_step=i)

        tb_writer.close()
        coord.request_stop()
        coord.join(qrs)

if __name__ == '__main__':
    #test.main()
    train_LFW()


import numpy as np
import cv2
import os
from planarH import computeH
from matplotlib import pyplot as plt

def compute_extrinsics(K, H):
    '''
    INPUTS:
        K - intrinsic parameters matrix
        H - estimated homography
    OUTPUTS:
        R - relative 3D rotation
        t - relative 3D translation

    '''

    #############################
    # We want to get the new homography that eliminatesthe effect of the intrinsic parameters
    # by pre-multiplying the estimated homography by the inverse of the intrinsic matrix
    # Follow instructions in the Prince textbook
    H_new = np.dot(np.linalg.inv(K), H)
    U, L, Vt = np.linalg.svd(H_new[:, 0:2], full_matrices=True)
    w = np.dot(U, np.array([[1, 0], [0, 1], [0, 0]]))
    w = np.dot(w, Vt)

    w = np.concatenate((w, np.cross(w[:, 0], w[:, 1]).reshape((3,1))),axis=1)

    if np.linalg.det(w) == -1:
        w[:, 2] = w[:, 2] * (-1)

    sum = 0
    for i in range(3):
        for j in range(2):
            sum += H_new[i, j] / w[i, j]
    scale = sum / 6

    R = w
    t = (H_new[:, 2] / scale).T

    return R, t

def project_extrinsics(K, W, R, t):
    '''
    INPUTS:
        K - intrinsic parameters matrix
        W - 3D planar points of textbook
        R - relative 3D rotation
        t - relative 3D translation
    OUTPUTS:
        X - computed projected points
    '''

    #############################
    extrinsic = np.concatenate((R, t), axis=1)
    intrin_extrin = np.dot(K, extrinsic)
    x = np.dot(intrin_extrin, W)

    proj = np.zeros((2, W.shape[1]))
    for i in range(x.shape[1]):
        # remember scaling
        proj[0, i] = int(x[0, i] / x[2, i])
        proj[1, i] = int(x[1, i] / x[2, i])

    return proj

if __name__ == "__main__":
    # image
    im = cv2.imread('../data/prince_book.jpeg')
    book_im = cv2.imread('../data/prince_book.jpeg')
    # plt.imshow(im, cmap='gray')
    # plt.show()
    #############################
    # TO DO ...
    # perform required operations and plot sphere

    # Four corners of book in real life
    W = np.array([[0, 18.2, 18.2, 0], [0, 0, 26, 26], [0, 0, 0, 0]])
    # Four corners of the book on image
    X = np.array([[483, 1704, 2175, 67], [810, 781, 2217, 2286]])
    # Intrinsic matrix for image
    K = np.array([[3043.72, 0, 1196], [0, 3043.72, 1604], [0, 0, 1]])

    H = computeH(X, W[0:2, :])
    R, t = compute_extrinsics(K, H)

    # Open sphere file
    file = open('../data/sphere.txt', "r")
    str = file.read()
    str_array = str.split('\n')
    sphere_x = str_array[0].split('  ')
    sphere_y = str_array[1].split('  ')
    sphere_z = str_array[2].split('  ')
    tmp_coord_list = []
    for i in range(1, len(sphere_x)):
        tmp_coord_list.append([float(sphere_x[i]), float(sphere_y[i]), float(sphere_z[i])])

    W_sphere = np.array(tmp_coord_list).T
    W_sphere = np.concatenate((W_sphere, np.ones((1, W_sphere.shape[1]))), axis=0)

    # With the sphere coordinates, project extrinsics!
    proj_sphere = project_extrinsics(K, W_sphere, R, t.reshape(3, 1)) + (np.array((320, 650))).T.reshape(2, 1)

    fig = plt.figure()
    plt.imshow(im)
    plt.plot(proj_sphere[0, :], proj_sphere[1, :], 'y.', markersize=2)
    plt.draw()
    plt.waitforbuttonpress(0)
    plt.close(fig)


import os
import openpyxl
from lxml import etree

class HtmlProcess(object):
    """处理SAP.ZDER里面导出的htm文件，并把结果写入到对应的excel文件中"""

    def __init__(self):
        self.dc_list = ["A668", "A672", "A673", "A680", "A681", "A715", "A716", "B194"]

    def get_data(self, fname, code_list):
        """接受文件名和Code列表来处理数据"""

        src = open(fname).read()
        htm = etree.HTML(src)
        p = htm.xpath("//blockquote/p[2]")[0]
        trs = p.findall(".//tr")
        # 开头行是表头，结尾行是表尾，中间还有位于第2页的表头，是第41个tr
        # 这3行都不要
        trs = trs[1:41] + trs[42:50]

        dc_list = self.dc_list
        # 创建字典以存放库存数据
        result_dict = {}
        for d in dc_list:
            result_dict[d] = {}
            for c in code_list:
                result_dict[d][c] = {"dc": 0, "intransit": 0}

        for tr in trs:
            code = tr.find(".//td[3]/font/nobr").text.strip()                         # Material Code
            dc = tr.find(".//td[5]/font/nobr").text.strip()                           # DC
            unres_inv = int(float(tr.find(".//td[7]/font/nobr").text.strip().replace(",", "")))        # Unrestrict Inventory
            qi_inv = int(float(tr.find(".//td[9]/font/nobr").text.strip().replace(",", "")))           # Quality Inventory
            block_inv = int(float(tr.find(".//td[10]/font/nobr").text.strip().replace(",", "")))       # Block Inventory
            intransit_inv = int(float(tr.find(".//td[13]/font/nobr").text.strip().replace(",", "")))   # Intransit Inventory
            result_dict[dc][code]["dc"] = unres_inv + qi_inv + block_inv
            result_dict[dc][code]["intransit"] = intransit_inv

        return result_dict

    def get_ws(self, fname):
        wb = openpyxl.load_workbook(fname, keep_vba=True)
        ws = wb.get_sheet_by_name("Sheet2")
        return (wb, ws)

    def write_to_excel(self, ws, code_list, result_dict):
        '''把结果写入到ws中，ws是一个Excel的工作表对象'''
        dc_list = self.dc_list
        for col, code in zip(range(2, 14, 2), code_list):
            for r, dc in zip(range(8, 16), dc_list):
                ws.cell(row=r, column=col).value = result_dict[dc][code]["dc"]
                ws.cell(row=r, column=col+1).value = result_dict[dc][code]["intransit"]

if __name__ == "__main__":
    htmlProcess = HtmlProcess()

    # 处理koala数据
    koala_htm = "C:/users/xian.jr/Documents/SAP/SAP GUI/ka.htm"
    koala_inv = "C:/Users/xian.jr/Documents/PG/Jacqueline/Koala/Koala Inventory Template.xlsm"
    koala_code_list = ["82261753", "82261756", "82261762", "82261951", "82263780", "82264483"]
    koala_result_dict = htmlProcess.get_data(koala_htm, koala_code_list)
    koala_inv_wb, koala_inv_ws = htmlProcess.get_ws(koala_inv)
    htmlProcess.write_to_excel(koala_inv_ws, koala_code_list, koala_result_dict)
    koala_inv_wb.save(koala_inv)

    # 处理tampax数据
    # tampax_htm = "C:/users/xian.jr/Documents/SAP/SAP GUI/ta.htm"
    # tampax_inv = "C:/Users/xian.jr/Documents/PG/Jacqueline/Tampax/Inventory Template.xlsm"
    # tampax_code_list = ["82255634", "82258740", "82259122", "82258746", "82258747", "82261076"]
    # tampax_result_dict = htmlProcess.get_data(tampax_htm, tampax_code_list)
    # tampax_inv_wb, tampax_inv_ws = htmlProcess.get_ws(tampax_inv)
    # htmlProcess.write_to_excel(tampax_inv_ws, tampax_code_list, tampax_result_dict)
    # tampax_inv_wb.save(tampax_inv)


#!/usr/bin/env python3
n, k, q = map(int,input().split())
a = [int(input()) for _ in range(q)]

scores = [0]*n

for itm in a:
    scores[itm-1] +=  1

for itm in scores:
    if k - q + itm <= 0:
        print('No')
    else:
        print('Yes')

## AC


import csv
with open("sample.csv", 'r')as fh:
    avg = 0
    res = csv.reader(fh)
    list1 = list(res)
    dict1 = {}
    for row in list1[1::]:
        sum1 = 0
        n = 0
        for marks in row:
            if marks.isdigit():
                n += 1
                sum1 = sum1 + int(marks)
        avg = sum1/n
        dict1[row[0]] = ["sum: ", sum1, "avg: ", avg]
    print(dict1)
    a = {}
    rank1 = 0
    for i in sorted(dict1, key=dict1.get, reverse=True):
        rank1 += 1
        a[i] = rank1
    print("ranks: ", a)

    # c=sorted(dict1, key=itemgetter(1), reverse=True)
    #
    # # for i in enumerate(sorted(dict1, key=itemgetter(1), reverse=True)):
    # #     print(dict1[i])

"""difference between two dictionaries and the count of common values in a dictionary"""
# dict1 = {'a': 10, 'b': 11}
# dict2 = {'a': 10, 'k': 13, 'c': 3}
# dict3 = {}
# for i in dict1:
#     if i not in dict2:
#         dict3[i] = dict1[i]
#     if i in dict2:
#         dict3[i] = dict1[i]+dict2[i]
# for i in dict2:
#     if i not in dict1:
#         dict3[i] = dict2[i]
# print(dict3)

# value = set(dict1)^set(dict2)
# print(value)
# res=set(dict1)
# print(res)


from itertools import count
from tkinter import *
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
from tkinter import messagebox

import os

class EncryptDecryptFolder:
    def __init__(self, controller):
        # Instance Controlleur
        self.controller = controller
        self.stop_process_bool = False

    def stop_process(self):
        self.stop_process_bool = True

    def start_encrypt_folder(self, path, type_encryption, key_size, mode, delete, key):
        try:
            # Si le dossier n'existe pas on lance une exception
            if not os.path.exists(path):
                raise FileNotFoundError("Folder path does not exist: {}".format(path))

            # Si la clé est False alors on génére
            if not key:
                # Générer une clé de cryptage
                key_size = int(key_size)
                key = os.urandom(key_size // 8)

                # Sauvegarder la clé dans un fichier
                key_file_path = self.controller.save_key_file()

                with open(key_file_path, 'wb') as key_file:
                    key_file.write(key)

            # Parcourir tous les fichiers et dossiers récursivement
            for root, dirs, files in os.walk(path):
                for file_name in files:
                    # Si l'utilisateur arrête le processus on arrête
                    if self.stop_process_bool:
                        raise Exception("The process was terminated by the user.")

                    # Construire le chemin complet du fichier
                    file_path = os.path.join(root, file_name)

                    # Encrypter le fichier
                    self.encrypt_file(file_path, type_encryption, key, mode, delete)

            self.controller.update_task(100, 'Encryption complete.')

            if delete:
                self.controller.show_message(
                    'Finished task', 'The files have been successfully encrypted and the original files have been deleted.')
            else:
                self.controller.show_message(
                    'Finished task', 'The files were successfully encrypted, but the original files were not deleted.')
            # Arrêter la barre de progression
            self.controller.stop_task()
            self.stop_process_bool = False

        except Exception as e:
            # Stopper la barre
            self.controller.stop_task()
            # Si l'utilisateur a arrêté le processus on rentre
            if self.stop_process_bool:
                self.controller.show_message('Stopping the process', str(e))
            else:
                messagebox.showerror('Error', str(e))
            self.stop_process_bool = False

    # Méthode qui sera appelée pour chaque fichier
    def encrypt_file(self, file_path, type_encryption, key, mode, delete):
        try:

            self.controller.update_task(10, 'Encrypting: ' + file_path + ' ...')

            # Extraire le nom de fichier et l'extension
            file_name_without_extension, file_extension = os.path.splitext(file_path)

            # Initialiser le vecteur d'initialisation (IV) aléatoire ou nonce
            iv_nonce = os.urandom(16)  # Générer un IV aléatoire

            # Ouvrir le fichier source en mode lecture binaire
            with open(file_path, 'rb') as file:
                plaintext = file.read()

            self.controller.update_task(50, 'Encrypting: ' + file_path + ' ...')

            # Initialiser le chiffreur avec le mode de cryptage sélectionné
            if type_encryption == "AES":
                if mode in ['CBC', 'CFB', 'OFB']:
                    cipher = Cipher(algorithms.AES(key), getattr(modes, mode)(iv_nonce), backend=default_backend())
                else:
                    cipher = Cipher(algorithms.AES(key), getattr(modes, mode)(), backend=default_backend())

                # Remplir le texte en clair pour qu'il soit un multiple de la taille du bloc
                padder = padding.PKCS7(algorithms.AES.block_size).padder()
                padded_plaintext = padder.update(plaintext) + padder.finalize()

                encryptor = cipher.encryptor()
                ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()

            elif type_encryption == "ChaCha20":
                cipher = Cipher(algorithms.ChaCha20(key, iv_nonce), mode=None, backend=default_backend())
                encryptor = cipher.encryptor()
                ciphertext = encryptor.update(plaintext) + encryptor.finalize()

            # Construire le nouveau nom de fichier chiffré
            encrypted_file_name = f"{file_name_without_extension}{file_extension}.enc"

            # Chemin complet du fichier chiffré
            encrypted_file_path = os.path.join(os.path.dirname(file_path), encrypted_file_name)

            # Écrire le fichier chiffré
            with open(encrypted_file_path, 'wb') as file:
                if mode in ['CBC', 'CFB', 'OFB']:
                    # Écrire le vecteur d'initialisation en premier
                    file.write(iv_nonce)

                file.write(ciphertext)

            self.controller.update_task(100, 'Encrypting: ' + file_path + ' ...')
            # Supprimer le fichier source si l'option de suppression est activée
            if delete:
                os.remove(file_path)

        except Exception as e:
            # Stopper la barre
            self.controller.stop_task()
            # Si l'utilisateur a arrêté le processus on rentre
            if self.stop_process_bool:
                self.controller.show_message('Stopping the process', str(e))
            else:
                messagebox.showerror('Error', str(e))
            self.stop_process_bool = False

    # Décrypter les dossiers
    def start_decrypt_folder(self, path, type_encryption, key, mode, delete):
        try:
            # Ouvrir le fichier contenant la clé
            with open(key, 'rb') as key_file:
                key = key_file.read()

            # Parcourir récursivement tous les fichiers et dossiers
            for root, dirs, files in os.walk(path):
                # Parcourir tous les fichiers du dossier actuel
                for file_name in files:
                    # Si l'utilisateur arrête le processus on arrête
                    if self.stop_process_bool:
                        raise Exception("The process was terminated by the user.")

                    # Chemin complet du fichier source
                    file_path = os.path.join(root, file_name)

                    self.controller.update_task(10, 'Decrypting: ' + file_path + ' ...')

                    # Vérifier si le chemin correspond à un fichier avec l'extension .enc
                    if file_name.endswith(".enc"):
                        # Extraire le nom de fichier et l'extension
                        file_name_without_extension, _ = os.path.splitext(file_name)

                        # Ouvrir le fichier chiffré en mode lecture binaire
                        with open(file_path, 'rb') as file:
                            # Le vecteur d'initialisation est stocké dans les 16 premiers octets
                            iv_nonce = file.read(16)
                            ciphertext = file.read()

                        self.controller.update_task(50, 'Decrypting: ' + file_path + ' ...')

                        if type_encryption == "AES":
                            # Initialiser le déchiffreur AES avec la clé et le mode choisi
                            cipher = Cipher(algorithms.AES(key), getattr(modes, mode)(iv_nonce), backend=default_backend())
                            # Créer le déchiffreur AES en mode de déchiffrement
                            decryptor = cipher.decryptor()
                            # Déchiffrer le texte chiffré
                            padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize()
                            # Créer un unpadder pour enlever le padding du texte déchiffré
                            unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
                            # Enlever le padding du texte déchiffré
                            plaintext = unpadder.update(padded_plaintext) + unpadder.finalize()

                        elif type_encryption == "ChaCha20":
                            # Initialiser le déchiffreur ChaCha20 avec la clé et le nonce
                            cipher = Cipher(algorithms.ChaCha20(key, iv_nonce), mode=None, backend=default_backend())
                            # Créer le déchiffreur ChaCha20 en mode de déchiffrement
                            decryptor = cipher.decryptor()
                            # Déchiffrer le texte chiffré
                            plaintext = decryptor.update(ciphertext) + decryptor.finalize()

                        self.controller.update_task(70, 'Decrypting: ' + file_path + ' ...')

                                                # Construire le nouveau nom de fichier déchiffré
                        decrypted_file_name = f"{file_name_without_extension}"

                        # Chemin complet du fichier déchiffré
                        decrypted_file_path = os.path.join(root, decrypted_file_name)

                        # Écrire le fichier déchiffré
                        with open(decrypted_file_path, 'wb') as file:
                            file.write(plaintext)

                        self.controller.update_task(90, 'Decrypting: ' + file_path + ' ...')

                        # Supprimer le fichier chiffré si l'option de suppression est activée
                        if delete:
                            os.remove(file_path)

            self.controller.update_task(100, 'Decryption complete.')
             # Message box
            if delete:
                self.controller.show_message(
                    'Finished task', 'The files were successfully decrypted and the encrypted file was deleted.')
            else:
                self.controller.show_message(
                    'Finished task', 'The files were successfully decrypted, but the encrypted files were not deleted.')

            # Stopper la barre
            self.controller.stop_task()
            self.stop_process_bool = False

        except Exception as e:
            # Stopper la barre
            self.controller.stop_task()
            # Si l'utilisateur a arrêté le processus on rentre
            if self.stop_process_bool:
                self.controller.show_message('Stopping the process', str(e))
            else:
                messagebox.showerror('Error', str(e))
            self.stop_process_bool = False


# -*- coding: utf-8 -*-
import getpass
import logging
import os
import shutil
import xml.dom.minidom

import maya.cmds as mc
import maya.mel as mel
import maya.utils as mu

import pipeGlobal
from miraLibs.mayaLibs import set_image_size, get_maya_version

logger = logging.getLogger(u"MIRA MAIN")
logger.setLevel(logging.DEBUG)

conf_dir = pipeGlobal.conf_dir

# ------------------------------------------------------------------------------------------#
# ----------------------------------load menu  ---------------------------------------------#
# ------------------------------------------------------------------------------------------#

def get_menu_conf_path():
    menu_conf_path = os.path.join(conf_dir, "mayaMenu.xml")
    return menu_conf_path

def run_mel_cmd(mel_path):
    mel.eval("source \"%s\"" % mel_path)

def load_menu():
    try:
        mc.delteUI("[MIRA]")
    except:
        pass
    menu_conf_path = get_menu_conf_path()
    dom_tree = xml.dom.minidom.parse(menu_conf_path)
    collection = dom_tree.documentElement
    maya_version = get_maya_version.get_maya_version()
    main_maya_menu = mc.menu('test', label=collection.getAttribute("name"), tearOff=True,
                             parent='MayaWindow', version=maya_version)

    sub_menus = collection.getElementsByTagName("submenu")
    for sub_menu in sub_menus:
        name = sub_menu.getAttribute("name")
        menu_type = sub_menu.getAttribute("type")
        if menu_type == "submenu":
            sub_maya_menu = mc.menuItem(sm=1, label=name, tearOff=True, parent=main_maya_menu)
            cmd_menues = sub_menu.getElementsByTagName("command")
            for cmd_menu in cmd_menues:
                cmd_menu_name = cmd_menu.getAttribute("name")
                cmd = cmd_menu.getAttribute("cmd")
                mode = cmd_menu.getAttribute("mode")
                if mode == "python":
                    mc.menuItem(label=cmd_menu_name, tearOff=True, parent=sub_maya_menu, c=cmd)
                elif mode == "mel":
                    mel_path = os.path.join(pipeGlobal.mira_dir, cmd)
                    mel_path = mel_path.replace("\\", "/")
                    mc.menuItem(label=cmd_menu_name, tearOff=True, parent=sub_maya_menu,
                                c=lambda *args: run_mel_cmd(mel_path))

        elif menu_type == "command":
            mc.menuItem(label=name, tearOff=True, parent=main_maya_menu, c=sub_menu.getAttribute('cmd'))

        elif menu_type == "separator":
            mc.menuItem(parent=main_maya_menu, divider=1)
    logger.debug("Load menu done")

# ------------------------------------------------------------------------------------------#
# ----------------------------------reload shelves -----------------------------------------#
# ------------------------------------------------------------------------------------------#

def reload_shelves():
    from miraPipeline.maya.shelf import reload_shelves
    reload_shelves.main()
    logger.info("Reload shelves done.")

# ------------------------------------------------------------------------------------------#
# ----------------------------------init user setup-----------------------------------------#
# ------------------------------------------------------------------------------------------#

def init_user_setup():
    init_maya_background_style()
    init_maya_saver_timer()
    # close_panel_when_open_and_save()
    init_wireframe_when_open()
    init_current_project()
    load_plugins()
    init_render_setting()
    init_scene_break_down()
    add_system_python_path_env()
    # init_shotgun()
    open_port()
    # remove_invalid_clipboard_data()

def init_maya_saver_timer():
    from miraPipeline.maya.maya_save_timer import maya_save_timer
    maya_save_timer.maya_save_timer()
    logger.info("Initialize maya save timer done.")

def init_scene_break_down():
    from miraPipeline.maya.scene_break_down import auto_tip_update
    auto_tip_update.auto_tip_update()
    logger.info("Initialize scene break down done.")

def init_render_setting():
    import pipeGlobal
    current_project = pipeGlobal.current_project
    resolution = pipeGlobal.Project(current_project).resolution
    set_image_size.set_image_size(*resolution)
    # renderer = pipeGlobal.Project(current_project).renderer
    # user = getpass.getuser()
    # if user in ["lvxiaolong", "xuwenliang", "liwenyang", "fengjingshi", "heshuai"]:
    #     mel.eval('unifiedRenderGlobalsWindow')
    #     mc.setAttr("defaultRenderGlobals.ren", renderer, type="string")
    #     logger.info("Initialize render settings done.")

def close_panel_when_open_and_save():
    from miraLibs.mayaLibs import close_panel_open_and_save
    close_panel_open_and_save.close_panel_open_and_save()
    logger.info("Initialize close panel done.")

def remove_invalid_clipboard_data():
    from miraLibs.mayaLibs import remove_invalid_clipboard_data
    remove_invalid_clipboard_data.remove_invalid_clipboard_data()
    logger.info("Can copy from PyCharm to maya done")

def init_wireframe_when_open():
    from miraLibs.mayaLibs import display_wireframe
    import maya.OpenMaya as OpenMaya
    OpenMaya.MEventMessage.addEventCallback("SceneOpened", display_wireframe.display_wireframe)
    logger.info("Initialize when open file wireframe display done.")

def init_maya_background_style():
    mc.displayPref(displayGradient=1)
    logger.info("Initialize maya background style done.")

def load_plugins():
    from miraLibs.pipeLibs.pipeMaya.plugins import plugins
    plugins.load_plugins()
    plugins.unload_plugins()

def init_current_project():
    from miraPipeline.maya.switch_project import switch_project
    switch_project.main()
    logger.info("Initialize current project done.")

def open_port():
    import subprocess
    from miraPipeline.pipeline.port_operation import add_user_info_to_db
    add_user_info_to_db.add_user_info_to_db()
    open_port_path = os.path.join(pipeGlobal.mira_dir, "miraPipeline/pipeline/port_operation/run_open_port.py")
    open_port_path = open_port_path.replace("\\", "/")
    if not os.path.isfile(open_port_path):
        return
    os.popen("tskill pythonw")
    python_path = "C:/Python27/pythonw"
    command = "%s %s" % (python_path, open_port_path)
    subprocess.Popen(command)
    user = getpass.getuser()
    startup_dir = "C:/Users/%s/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup" % user
    startup_path = "%s/%s" % (startup_dir, "mira.bat")
    if os.path.isfile(startup_path):
        os.remove(startup_path)
    with open(startup_path, "w") as f:
        f.write("start %s" % command)
    logger.info("Initialize open port done.")

def add_system_python_path_env():
    user = getpass.getuser()
    if user in ["heshuai", "zhaopeng"]:
        return
    startup_dir = "C:/Users/%s/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup" % user
    mira_batch_dir = pipeGlobal.batch_dir
    python_path_bat = os.path.join(mira_batch_dir, "PYTHONPATH.bat").replace("\\", "/")
    startup_python_path_bat = os.path.join(startup_dir, "PYTHONPATH.bat")
    try:
        os.system(python_path_bat)
        shutil.copyfile(python_path_bat, startup_python_path_bat)
        logger.info("add system python path env done.")
    except:
        logger.info("add system python path env failed.")

def init_shotgun():
    from miraPipeline.maya.init_shotgun import init_shotgun
    init_shotgun.main()
    logger.info("Initialize shotgun done.")

# ------------------------------------------------------------------------------------------#
# -------------------------------------main-------------------------------------------------#
# ------------------------------------------------------------------------------------------#

def main():
    mu.executeDeferred("import mira_main;mira_main.load_menu()")
    mu.executeDeferred("import mira_main;mira_main.init_user_setup()")
    mu.executeDeferred("import mira_main;mira_main.reload_shelves()")

if __name__ == "__main__":
    main()


from typing import List

class Solution:
    def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
        sum = 0
        for i in range(1, len(points)):
            sum += max(abs(points[i][0] - points[i-1][0]), abs(points[i][1] - points[i-1][1]))
        return sum

points = [[1,1],[3,4],[-1,0]]
sol1 = Solution()
result = sol1.minTimeToVisitAllPoints(points)
print(result)


_init_url="$URL$"

# NOTE: releaselevel should be left at 'invalid' for trunk development
#     and set to 'final' for releases.  During development, the
#     major.minor.micro should point ot the NEXT release (generally, the
#     next micro release after the current release).
#
# Note: When cutting a release, also update the major/minor/micro in
#
#     pyomo/RELEASE.txt
#
# The VOTD zipbuilder will automatically change releaselevel to "VOTD
# {hash}" and set the serial number to YYMMDDhhmm.  The serial number
# should generally be left at 0, unless a downstream package is tracking
# main and needs a hard reference to "suitably new" development.
major=6
minor=2
micro=0
#releaselevel='invalid'
releaselevel='final'
serial=0

if releaselevel == 'final':
    pass
elif '/tags/' in _init_url:                #pragma:nocover
    releaselevel = 'final'
elif releaselevel == 'invalid':
    from os.path import abspath, dirname, exists, join
    if __file__.endswith('setup.py'):
        # This file is being sources (exec'ed) from setup.py.
        # dirname(__file__) setup.py's scope is the root sourec directory
        _rootdir = os.path.dirname(__file__)
    else:
        # Eventually this should import PYOMO_ROOT_DIR from
        # pyomo.common instead of reimplementing that logic here.
        #
        # __file__ fails if script is called in different ways on Windows
        # __file__ fails if someone does os.chdir() before
        # sys.argv[0] also fails because it doesn't not always contains the path
        from inspect import getfile, currentframe
        _rootdir = join(dirname(abspath(getfile(currentframe()))), '..', '..')

    if exists(join(_rootdir, '.git')):
        try:
            with open(join(_rootdir, '.git', 'HEAD')) as _FILE:
                _ref = _FILE.readline().strip()           #pragma:nocover
            releaselevel = 'devel {%s}' % (
                _ref.split('/')[-1].split('\\')[-1], )    #pragma:nocover
        except:
            releaselevel = 'devel'         #pragma:nocover
    elif exists(join(_rootdir, '.svn')):
        releaselevel = 'devel {svn}'       #pragma:nocover
    else:
        releaselevel = 'VOTD'              #pragma:nocover

version_info = (major, minor, micro, releaselevel, serial)

version = '.'.join(str(x) for x in version_info[:(3 if micro else 2)])
__version__ = version
if releaselevel != 'final':
    version += ' ('+releaselevel+')'
if releaselevel.startswith('devel'):
    __version__ += ".dev%d" % (serial,)
elif releaselevel.startswith('VOTD'):
    __version__ += "a%d" % (serial,)


#!/usr/bin/python3
""" device_wemo.py:
"""

# Import Required Libraries (Standard, Third Party, Local) ****************************************
import copy
import datetime
import logging
from .device import Device
from rpihome.modules.message import Message

# Authorship Info *********************************************************************************
__author__ = "Christopher Maue"
__copyright__ = "Copyright 2016, The RPi-Home Project"
__credits__ = ["Christopher Maue"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Christopher Maue"
__email__ = "csmaue@gmail.com"
__status__ = "Development"

# Device class ************************************************************************************
class DeviceWemo(Device):
    def __init__(self, name, address, msg_out_queue, logger=None):
        # Configure logger
        self.logger = logger or logging.getLogger(__name__)
        super().__init__(name, msg_out_queue, self.logger)
        self.name = name
        self.address = address
        self.msg_out_queue = msg_out_queue
        self.discover_device()

    def discover_device(self):
        self.logger.debug("Sending command to wemo gateway to find device at address: %s", self.address)
        self.msg_to_send = Message(source="11", dest="16", type="160", name=self.name, payload=self.address)
        self.msg_out_queue.put_nowait(self.msg_to_send.raw)

    def command(self):
        """ This method is used to send a single command to various devices when necessary instead
        of sending the same command over and over again """
        if self.state != self.state_mem:
            if self.state is True:
                self.msg_to_send = Message(source="11", dest="16", type="161", name=self.name, payload="on")
                self.msg_out_queue.put_nowait(self.msg_to_send.raw)
                self.logger.debug("Sending command to wemo gateway to turn ON device: %s", self.name)
            else:
                self.msg_to_send = Message(source="11", dest="16", type="161", name=self.name, payload="off")
                self.msg_out_queue.put_nowait(self.msg_to_send.raw)
                self.logger.debug("Sending command to wemo gateway to turn OFF device: %s", self.name)
            pass
            # Snapshot new device state in memory so the command is only sent once
            self.state_mem = copy.copy(self.state)


import cv2
import numpy as np

read_img = cv2.imread("files/fmh2.jpg")

# define a kernel #np.ones- all value is 1, size of matrix = 5x5
kernel = np.ones((5,5), np.uint8) # unsigned int of 8 bits(0-255)

# # convert img in greyscale
# # cvtColor() converts img into different color spaces
# imgGray = cv2.cvtColor(read_img, cv2.COLOR_BGR2GRAY)  # cv2.COLOR - color space you want to convert into

# imgBlur = cv2.GaussianBlur(imgGray, (7,7), 0) #ksize - kernal size - has to be odd no, sigmax =0

# finding edges in our image - we will use Canny func
imgCanny = cv2.Canny(read_img, 100, 100)  # threshold values 100,100 - can be any no.
# to increase thickness of edge, iteration= how much thickness we need
imgDialation = cv2.dilate(imgCanny,kernel, iterations = 1 ) # add a kernel - size of and value of(use matrix)

# erosion - to make img edge thiner
imgEroded = cv2.erode(imgDialation, kernel, iterations=1)

# cv2.imshow("Gray Image", imgGray)
# cv2.imshow("Blur Image", imgBlur)
cv2.imshow("Blur Image", imgCanny)
cv2.imshow("Dialation Image", imgDialation)
cv2.imshow("Eroded Image", imgEroded)
cv2.waitKey(0)


import os.path
import subprocess

import osgeo.osr as osr
import osgeo.gdal as gdal

import math
import numpy

import sen1_ard_gamma.sen1_ard_utils

import logging

logger = logging.getLogger(__name__)

gdal.UseExceptions()

def subset_reproj_utm_dem_file(in_dem_file, bbox_wgs84, out_res_x, out_res_y, out_proj_epsg, out_dem_file,
                               out_dem_par_file, tmp_dir, no_dem_check=False, eResampleAlg=gdal.GRA_CubicSpline):
    """
    Function to subset and reproject a DEM provided in a GDAL compatiable format (e.g., GTIFF) into a format
    compatiable with Gamma.

    :param in_dem_file: file path to input image file.
    :param bbox_wgs84: the bbox (MinX, MaxX, MinY, MaxY) in WGS84 (lat/long)
    :param out_res_x: the output resolution (in metres) in the x axis.
    :param out_res_y: the output resolution (in metres) in the y axis.
    :param out_proj_epsg: EPSG code for the output UTM zone
    :param out_dem_file: output DEM binary file
    :param out_dem_par_file: output DEM parameter file
    :param tmp_dir: directory for temporary outputs.
    :param no_dem_check: If True the DEM is not checked for no data value and minimum value for Gamma compatibility
    :param eResampleAlg: specify the gdal resampling method for the DEM processing (if DEM being subsetted and
                         reprojected). Default: gdal.GRA_CubicSpline
    """
    logger.debug("Starting to run subset_reproj_utm_dem_file")
    in_dem_file_ds = gdal.Open(in_dem_file, gdal.GA_ReadOnly)
    if in_dem_file_ds == None:
        raise Exception('Could not open raster image: \'' + in_dem_file + '\'')
    in_dem_band = in_dem_file_ds.GetRasterBand(1)
    if in_dem_band == None:
        raise Exception('Could not open DEM raster band: \'' + in_dem_file + '\'')

    no_data_val = in_dem_band.GetNoDataValue()

    logger.debug("Calculating UTM BBox.")
    in_spat_ref = osr.SpatialReference()
    in_spat_ref.ImportFromEPSG(4326)

    out_spat_ref = osr.SpatialReference()
    out_spat_ref.ImportFromEPSG(out_proj_epsg)

    utm_zone = out_spat_ref.GetUTMZone()

    tlX = bbox_wgs84[0]
    tlY = bbox_wgs84[3]
    brX = bbox_wgs84[1]
    brY = bbox_wgs84[2]

    out_tlX = 0.0
    out_tlY = 0.0
    out_brX = 0.0
    out_brY = 0.0

    out_tlX, out_tlY = sen1_ard_gamma.sen1_ard_utils.reproj_point(in_spat_ref, out_spat_ref, tlX, tlY)
    out_brX, out_brY = sen1_ard_gamma.sen1_ard_utils.reproj_point(in_spat_ref, out_spat_ref, brX, brY)
    """
    out_tlX, out_tlY = sen1_ard_gamma.sen1_ard_utils.reproj_point(in_spat_ref, out_spat_ref, tlY, tlX)
    out_brX, out_brY = sen1_ard_gamma.sen1_ard_utils.reproj_point(in_spat_ref, out_spat_ref, brY, brX)
    """
    logger.debug("Calculated UTM BBox: [{}, {}, {}, {}]".format(out_tlX, out_brX, out_brY, out_tlY))

    # Snap TL to whole pixel so outputs on whole pixel grid.
    n_pxl_tl_x = math.floor(out_tlX / out_res_x)
    n_pxl_tl_y = math.ceil(out_tlY / ((-1) * out_res_y))
    logger.debug("N Pixels to TL: [{}, {}]".format(n_pxl_tl_x, n_pxl_tl_y))

    out_tlX = (n_pxl_tl_x * out_res_x) - (out_res_x / 2)
    out_tlY = (n_pxl_tl_y * ((-1) * out_res_y)) + (((-1) * out_res_y) / 2)
    logger.debug("Calculated UTM BBox (whole num grid): [{}, {}, {}, {}]".format(out_tlX, out_brX, out_brY, out_tlY))

    x_pxls = math.ceil((out_brX - out_tlX) / out_res_x)
    y_pxls = math.ceil((out_tlY - out_brY) / ((-1) * out_res_y))

    logger.debug("Output DEM image size (pixels): [{} x {}]".format(x_pxls, y_pxls))

    out_dem_tmp_file = os.path.join(tmp_dir ,os.path.splitext(os.path.basename(out_dem_file))[0] + '_tmpdem.dem')
    logger.debug("Output DEM tmp file: {}".format(out_dem_tmp_file))
    out_dem_file_ds = gdal.GetDriverByName('ENVI').Create(out_dem_tmp_file, x_pxls, y_pxls, 1, gdal.GDT_Int16)
    if out_dem_file_ds == None:
        raise Exception('Could not create output raster image: \'' + out_dem_tmp_file + '\'')
    out_dem_file_ds.SetGeoTransform((out_tlX, out_res_x, 0, out_tlY, 0, out_res_y))
    out_dem_file_ds.SetProjection(out_spat_ref.ExportToWkt())
    out_dem_band = out_dem_file_ds.GetRasterBand(1)
    if out_dem_band == None:
        raise Exception('Could not open DEM raster band: \'' + out_dem_tmp_file + '\'')
    out_dem_band.SetNoDataValue(no_data_val)
    logger.debug("Created output DEM tmp file: {}".format(out_dem_tmp_file))

    logger.debug("Start gdal warp for: {}".format(out_dem_tmp_file))
    wrpOpts = gdal.WarpOptions(resampleAlg=eResampleAlg, srcNodata=no_data_val, dstNodata=no_data_val,
                               multithread=False, callback=gdal.TermProgress)

    gdal.Warp(out_dem_file_ds, in_dem_file_ds, options=wrpOpts)
    logger.debug("Finished gdal warp for: {}".format(out_dem_tmp_file))
    in_dem_file_ds = None
    out_dem_file_ds = None

    if not no_dem_check:
        logger.debug("Going to check DEM if no data value is not zero.")
        if no_data_val != 0:
            out_dem_tmp_chk_file = os.path.join(tmp_dir,
                                                os.path.splitext(os.path.basename(out_dem_file))[0] + '_tmpdem_chk.dem')
            logger.debug("Checking DEM as no data value is not zero; output image: {}".format(out_dem_tmp_chk_file))
            check_dem_for_gamma_compat(out_dem_tmp_file, out_dem_tmp_chk_file, no_data_val)
            out_dem_tmp_file = out_dem_tmp_chk_file

    logger.debug("Start byte swap to create: {}".format(out_dem_file))
    cmd = 'swap_bytes {0} {1} 2'.format(out_dem_tmp_file, out_dem_file)
    try:
        logger.debug("Running following command using subprocess '{}'".format(cmd))
        cmd = sen1_ard_gamma.sen1_ard_utils.preappend_cmd(cmd)
        subprocess.call(cmd, shell=True)
    except OSError as e:
        logger.error('Cmd Failed: {}'.format(cmd))
        raise e
    logger.debug("Finished byte swap creating: {}".format(out_dem_file))

    logger.debug("Creating dem par file.")
    out_par_file = open(out_dem_par_file, 'w')
    imageparameters = dict()
    imageparameters['title'] = os.path.basename(in_dem_file)
    imageparameters['datatype'] = 'INTEGER*2'
    imageparameters['width'] = x_pxls
    imageparameters['nlines'] = y_pxls
    imageparameters['corner_north'] = out_tlY
    imageparameters['corner_east'] = out_tlX
    imageparameters['post_north'] = out_res_y
    imageparameters['post_east'] = out_res_x
    imageparameters['zone'] = utm_zone
    imageparameters['center_longitude'] = (utm_zone * 6) - 183.0

    out = '''Gamma DIFF&GEO DEM/MAP parameter file
title: {title}
DEM_projection:     UTM
data_format:        {datatype}
DEM_hgt_offset:          0.00000
DEM_scale:               1.00000
width:               {width}
nlines:              {nlines}
corner_north:  {corner_north}   m
corner_east:   {corner_east}   m
post_north:    {post_north}   m
post_east:     {post_east}   m

ellipsoid_name: WGS 84
ellipsoid_ra:        6378137.000   m
ellipsoid_reciprocal_flattening:  298.2572236

datum_name: WGS 1984
datum_shift_dx:              0.000   m
datum_shift_dy:              0.000   m
datum_shift_dz:              0.000   m
datum_scale_m:         0.00000e+00
datum_rotation_alpha:  0.00000e+00   arc-sec
datum_rotation_beta:   0.00000e+00   arc-sec
datum_rotation_gamma:  0.00000e+00   arc-sec
datum_country_list Global Definition, WGS84, World

projection_name: UTM
projection_zone:                 {zone}
false_easting:           500000.000   m
false_northing:          0000000.000   m
projection_k0:            0.9996000
center_longitude:         {center_longitude}   decimal degrees
center_latitude:          0.0000000   decimal degrees\n'''.format(**imageparameters)

    # false_northing:          10000000.000   m  # For Southern Hemisphere
    out_par_file.write(out)
    out_par_file.close()
    logger.debug("Created dem par file.")
    logger.debug("Finished running subset_reproj_utm_dem_file")

def check_dem_for_gamma_compat(input_dem_img, output_dem_img, no_data_val):
    """
    DEM is checked for no data value (will be 0) and minimum value of 1 for Gamma compatibility.
    The DEM will be outputted in ENVI format.

    :param input_dem_img: Input DEM image
    :param output_img: Output DEM image
    :param no_data_val: The current no data value for the DEM.

    """
    logger.debug("Starting to check DEM for Gamma compatibility.")
    img_ds = gdal.Open(input_dem_img)
    if img_ds is None:
        raise Exception("Could not open image: {}".format(input_dem_img))

    # Get Header information.
    geotransform = img_ds.GetGeoTransform()
    x_pxls = img_ds.RasterXSize
    y_pxls = img_ds.RasterYSize
    proj_str = img_ds.GetProjection()

    out_img_ds = gdal.GetDriverByName('ENVI').Create(output_dem_img, x_pxls, y_pxls, 1, gdal.GDT_Int16)
    if out_img_ds == None:
        raise Exception("Could not create DEM image output raster: '{}'.".format(output_dem_img))
    out_img_ds.SetGeoTransform(geotransform)
    out_img_ds.SetProjection(proj_str)

    img_band = img_ds.GetRasterBand(1)
    if img_band is None:
        raise Exception("Could not open image band 1 from {}".format(input_dem_img))
    val_arr = img_band.ReadAsArray()

    out_img_band = out_img_ds.GetRasterBand(1)
    if out_img_band == None:
        raise Exception("Could not open image band 1 from {}".format(output_dem_img))
    out_img_band.SetNoDataValue(0)
    logger.debug("Created output file and read input data.")

    val_arr[val_arr == 0] = 1
    val_arr[val_arr == no_data_val] = 0
    val_arr[val_arr < 0] = 0

    out_img_band.WriteArray(val_arr)

    img_ds = None
    out_img_ds = None
    logger.debug("Written revised DEM to output image file - finished Gamma DEM compatibility function .")


import tensorflow as tf
from word_seg_model import WordSegModel

def simple_model_fn(mode, input_reader, model_path, network_params,
                    epoch_no=None, iteration_no=None, pretrained=None, eval_input_fn=None):
    if mode == 'TRAIN':
        pass
    elif mode == 'PREDICT':
        epoch_no = 1
    else:
        raise Exception('Invalid mode: ' + mode)

    iteration_count = 0
    epoch_count = 0

    with tf.Session() as sess:
        model = WordSegModel(network_params)

        # init model
        sess.run(model.init_model())
        emb_feed_dict = {model.emb_pl['word']: pretrained['word'], model.emb_pl['char']: pretrained['char']}
        sess.run(model.init_embeddings(), feed_dict=emb_feed_dict)

        while True:
            epoch_end = False
            while not epoch_end:
                data_dict, epoch_end = input_reader.get_next()
                feed_dict = get_feed_dict(model, data_dict, labels=data_dict['action_label'])
                loss = sess.run([model.simple_loss], feed_dict=feed_dict)
                iteration_count += 1

            epoch_count += 1

def beam_model_fn(mode, input_reader, network_params, model_path,
                  beam_size, decode_size, summaries_path=None,
                  epoch_no=None, iteration_no=None, pretrained=None, eval_input_fn=None, eval_every_epoch=1):
    """
    :param mode: TRAIN or EVALUATE or PREDICT
    :param input_reader: An instance of input_reader.BeamInputReader
    :param network_params:
    :param model_path: path for a model to be saved or restored
    :param beam_size:
    :param decode_size:
    :param epoch_no: int or None
    :param iteration_no: int or None (if both epoch_no and iteration_no are None, it will run infinitely)
    :param pretrained: pre-trained embeddings
    :param eval_input_fn: An instance of input_reader.BeamInputReader for evaluation (in training process)
    :param eval_every_epoch: In training mode, specify that eval_input_fn should be run every x epoch
    :return: in TRAIN mode return nothing,
            in PREDICT mode return decoded sentences (first decode_size scored sequences for each sentence)
    """
    end_epoch = False
    end_process = False
    iteration_count = 0
    epoch_count = 0
    decoded_results = list()

    if mode == 'TRAIN':
        if model_path is None or summaries_path is None:
            raise Exception('TRAIN mode: use must define model_save_path, summaries_path')
    elif mode == 'PREDICT':
        pass
    else:
        raise Exception('Mode can be only TRAIN or PREDICT')

    with tf.Session() as sess:
        model = WordSegModel(network_params)
        sess.run(model.init_model())

        saver = tf.train.Saver()
        model_save_path = model_path + '/model.ckpt'
        ckpt = tf.train.get_checkpoint_state(model_path)
        if ckpt and ckpt.model_checkpoint_path:
            saver.restore(sess, ckpt.model_checkpoint_path)
        else:
            # ----------------------
            emb_feed_dict = {model.emb_pl['word']: pretrained['word'], model.emb_pl['char']: pretrained['char']}
            sess.run(model.init_embeddings(), feed_dict=emb_feed_dict)
            sess.run(model.reset_accumulated_gradients())
            # ----------------------

        writer = tf.summary.FileWriter(summaries_path, sess.graph)
        initial_index = sess.run(model.global_step)
        print(initial_index)

        while not end_process:
            while not end_epoch:
                # ----------------------
                beam, end_epoch, states = input_reader.get_sentence()
                sentence_len = len(beam[0]['buffer_char'])
                loss_sum = 0.0

                for _ in range(sentence_len):
                    # training
                    batch_beam, label, mask = input_reader.make_batch(beam)
                    feed_dict = get_feed_dict(model, batch_beam, label, mask)

                    operating_ops = [model.accumulate_gradient(model.max_margin_loss_fn),
                                     model.max_margin_loss, model.score_sep, model.score_app]
                    _, loss, score_sep, score_app = sess.run(operating_ops, feed_dict=feed_dict)
                    loss_sum += loss

                    # beam search
                    new_beam = list()
                    for i, state in enumerate(beam):
                        last_score = state['score']
                        new_beam.append({'state': state, 'next_action': 'SEP', 'score': last_score + score_sep[i]})
                        new_beam.append({'state': state, 'next_action': 'APP', 'score': last_score + score_app[i]})

                    sorted_beam = sorted(new_beam, key=lambda x: x['score'], reverse=True)
                    pruned_beam = sorted_beam[0: beam_size]
                    beam = input_reader.get_next_beam(pruned_beam)

                # summary
                train_summary = dict()
                train_summary['loss'] = loss_sum / sentence_len
                write_summary(writer, train_summary, iteration_count)

                sess.run(model.average_gradients(), feed_dict={model.no_steps: float(sentence_len)})
                sess.run(model.apply_gradients())
                sess.run(model.reset_accumulated_gradients())

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

                if mode == 'PREDICT':
                    # put results to the list
                    results = [state['stack_word'] for state in beam[0:decode_size]]
                    decoded_results.append(results)
                elif mode == 'TRAIN':
                    iteration_count += 1
                    if iteration_no % eval_every_epoch == 0:
                        pass
                    if iteration_no is not None and iteration_count >= iteration_no:
                        end_process = True
                        break

            if mode == 'TRAIN':
                saver.save(sess, model_save_path, global_step=(initial_index + epoch_count))
                epoch_count += 1
                if epoch_no is not None and epoch_count >= epoch_no:
                    end_process = True
            else:
                end_process = True

    if mode == 'PREDICT':
        return decoded_results

def get_feed_dict(model, input_dict, labels=None, mask=None):
    feed_dict = dict()
    for input_tag in model.input:
        feed_dict[model.input[input_tag]] = input_dict[input_tag]
    if labels is not None:
        feed_dict[model.labels] = labels
    if mask is not None:
        feed_dict[model.mask] = mask
    return feed_dict

def write_summary(writer, value_pair, global_step):
    summary = tf.Summary()
    for key in value_pair:
        summary.value.add(tag=key, simple_value=value_pair[key])

    writer.add_summary(summary, global_step)


"""
글자 크기를 키우는 코드 만들기
"""

import tkinter
import tkinter.font

# window 객체 생성
window = tkinter.Tk()

# 타이틀을 정의
window.title("가상화폐 금액표시")

# GUI의 사이즈를 설정
window.geometry("400x200")

# 가로세로의 크기를 조절하지 못하도록 설정
window.resizable(False, False)

# 폰트를 적용하여 hello의 문자열을 출력
font = tkinter.font.Font(size=30)
label = tkinter.Label(window, text="hello", font=font)
label.pack()

# GUI를 계속 실행하기 위해 mainloop를 살행
window.mainloop()


import torch
import argparse
import numpy as np
import torch.nn as nn
import torch.optim as optim

from net import GraphSage
from data import CoraData
from sampling import multihop_sampling

# 训练setting，超参设置
parser = argparse.ArgumentParser()
parser.add_argument('--no-cuda', action='store_true', default=False,
                    help='无法用cuda训练')
parser.add_argument('--fastmode', action='store_true', default=False,
                    help='使用训练网络来求验证集的正确率')
parser.add_argument('--seed', type=int, default=42,
                    help='torch的随机种子')
parser.add_argument('--epochs', type=int, default=20,
                    help='训练代数')
parser.add_argument('--btach_size', type=int, default=16,
                    help='批处理大小')
parser.add_argument('--num_batch_per_epoch', type=int, default=20,
                    help='每个epoch循环的批次数')
parser.add_argument('--hidden_dim', type=list, default=[128, 7],
                    help='隐藏单元节点数')
parser.add_argument('--num_neighbors_list', type=list, default=[10, 10],
                    help='每阶采样邻居的节点数')
parser.add_argument('--weight_decay', type=float, default=5e-4,
                    help='权重衰减，L2正则化前面的参数')
parser.add_argument('--lr', type=float, default=0.01,
                    help='初始学习率')

# 如果程序不禁止cuda且当前主机有的gpu可调用,arg.cuda就为True
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()

DEVICE = "cuda" if args.cuda else "cpu"

# Note: 采样的邻居阶数需要与GCN的层数保持一致
assert len(args.hidden_dim) == len(args.num_neighbors_list)

np.random.seed(args.seed)
torch.manual_seed(args.seed)

if args.cuda:
    torch.cuda.manual_seed(args.seed)

data = CoraData().data

x = data.x / data.x.sum(1, keepdims=True)  # 归一化数据，使得每一行和为1

train_index = np.where(data.train_mask)[0]
train_label = data.y
test_index = np.where(data.test_mask)[0]
val_index = np.where(data.val_mask)[0]

input_dim = x.shape[1]    # 输入维度

model = GraphSage(input_dim=input_dim,
                  hidden_dim=args.hidden_dim,
                  num_neighbors_list=args.num_neighbors_list).to(DEVICE)
print(model)
criterion = nn.CrossEntropyLoss().to(DEVICE)
optimizer = optim.Adam(model.parameters(),
                       lr=args.lr,
                       weight_decay=args.weight_decay)

def train():
    model.train()
    for e in range(args.epochs):
        for batch in range(args.num_batch_per_epoch):
            batch_src_index = np.random.choice(train_index,
                                               size=(args.btach_size,))
            batch_src_label = torch.from_numpy(train_label[batch_src_index]).long().to(DEVICE)
            batch_sampling_result = multihop_sampling(
                src_nodes=batch_src_index,
                sample_nums=args.num_neighbors_list,
                neighbor_table=data.adjacency_dict)
            batch_sampling_x = [torch.from_numpy(x[idx]).float().to(DEVICE)
                                for idx in batch_sampling_result]
            batch_train_logits = model(batch_sampling_x)
            loss_train = criterion(batch_train_logits, batch_src_label)
            accuarcy_train = torch.eq(batch_train_logits.max(1)[1], batch_src_label).float().mean().item()
            optimizer.zero_grad()  # 先将梯度归零
            loss_train.backward()  # 反向传播计算得到每个参数的梯度值
            optimizer.step()  # 最后通过梯度下降执行一步参数更新
            accuarcy_val, loss_val = val()

            print('Epoch: {:03d}'.format(e),
                  'Batch: {:03d}'.format(batch),
                  'Loss_train: {:.4f}'.format(loss_train.item()),
                  'accuarcy_train：{:.4f}'.format(accuarcy_train),
                  'Loss_val: {:.4f}'.format(loss_val),
                  'acc_val：{:.4f}'.format(accuarcy_val))
        if e % 10 == 0:
            torch.save(model.state_dict(), 'model/model.pkl')
            print('第%d epoch，保存模型' % e)
    torch.save(model.state_dict(), 'model/model.pkl')

def val():
    with torch.no_grad():
        val_sampling_result = multihop_sampling(
            src_nodes=val_index,
            sample_nums=args.num_neighbors_list,
            neighbor_table=data.adjacency_dict)
        val_x = [torch.from_numpy(x[idx]).float().to(DEVICE)
                 for idx in val_sampling_result]
        val_label = torch.from_numpy(data.y[val_index]).long().to(DEVICE)
        if not args.fastmode:
            # 使用完整网络来求验证集的正确率
            model.eval()
            # 不启用 Batch Normalization 和 Dropout
            val_logits = model(val_x)
        else:
            val_logits = model(val_x)

        loss_val = criterion(val_logits, val_label).item()
        predict_y = val_logits.max(1)[1]
        accuarcy = torch.eq(predict_y, val_label).float().mean().item()
        return accuarcy, loss_val

def test():
    model.eval()
    with torch.no_grad():
        checkpoint = torch.load('model/model.pkl')
        model.load_state_dict(checkpoint)

        # 强制之后的内容不进行计算图构建
        test_sampling_result = multihop_sampling(
            src_nodes=test_index,
            sample_nums=args.num_neighbors_list,
            neighbor_table=data.adjacency_dict)
        test_x = [torch.from_numpy(x[idx]).float().to(DEVICE)
                  for idx in test_sampling_result]
        test_logits = model(test_x)
        test_label = torch.from_numpy(data.y[test_index]).long().to(DEVICE)
        predict_y = test_logits.max(1)[1]
        accuarcy = torch.eq(predict_y, test_label).float().mean().item()
        print("Test Accuracy: ", accuarcy)

if __name__ == '__main__':
    train()
    test()


#a
nii,mii=map(int,input().split())
tem=[]
x=0
for m in range(nii):
    tem.append(list(map(int,input().split())))
for m in range(nii):
    for j in range(mii-1):
        for k in range(j+1,mii+1):
            if tem[m][j:k]==[1]*len(tem[m][j:k]):
                 if all(tem[p+m][j:k]==[1]*len(tem[p+m][j:k]) for p in range(len(tem[m][j:k])-1)):
                     if len(tem[m][j:k])>x:
                        x=len(tem[m][j:k])
if len(tem)==1 and len(tem[0])==1 and tem[0][0]==1:
    print(1)
for m in range(x):
    print(*[1]*x)


# this file was created by Chris Cozort
# Sources: goo.gl/2KMivS - thanks Chris Bradfield!
# now available in github

'''
Curious, Creative, Tenacious(requires hopefulness)

**********Gameplay ideas:
Shoot feathers out of wings to dFefeat enemies
Health bar

**********Cosmetics
Change hero images (5 images), platforms, clouds, enemies(2 images), bg image? DONE

**********Bugs
when you get launched by powerup or head jump player sometimes snaps to platform abruptly
happens when hitting jump during power up boost

**********Gameplay fixes
Platform randomness leaves player in limbo for extended periods
Lower spawn location so player can get out of random stuck situations

**********Features
Varied powerups that add ammo to your feather
'''
import pygame as pg
import random
from settings import *
from sprites import *
from os import path

class Game:
    ##### INIT METHOD
    def __init__(self):
        #init game window
        # init pygame and create window
        pg.init()
        # init sound mixer
        pg.mixer.init()
        self.screen = pg.display.set_mode((WIDTH, HEIGHT))
        pg.display.set_caption("jumpy")
        self.clock = pg.time.Clock()
        self.running = True
        self.font_name = pg.font.match_font(FONT_NAME)
        self.load_data()
    ##### LOAD DATA METHOD
    def load_data(self):
        # print("load data is called...")
        # sets up directory name for images
        self.dir = path.dirname(__file__)
        img_dir = path.join(self.dir, 'img')
        # opens file with write options
        ''' with is a contextual option that handles both opening and closing of files to avoid
        issues with forgetting to close
        '''
        try:
            # changed to r to avoid overwriting error
            with open(path.join(self.dir, "highscore.txt"), 'r') as f:
                self.highscore = int(f.read())
                # print(self.highscore)
        except:
            with open(path.join(self.dir, HS_FILE), 'w') as f:
                self.highscore = 0
                print("exception")
        # load spritesheet image
        self.spritesheet = Spritesheet(path.join(img_dir, SPRITESHEET))
        #load cloud images
        self.cloud_images = []
        for i in range(1,4):
            self.cloud_images.append(pg.image.load(path.join(img_dir, 'cloud{}.png'.format(i))).convert())
        self.ground_image = pg.image.load(path.join(img_dir, 'ground.png')).convert()
        self.ground_rect = self.ground_image.get_rect()
        self.g_scroll_start = 0
        # load sounds
        # great place for creating sounds: https://www.bfxr.net/
        self.snd_dir = path.join(self.dir, 'snd')
        self.jump_sound = [pg.mixer.Sound(path.join(self.snd_dir, 'Jump18.wav')),
                            pg.mixer.Sound(path.join(self.snd_dir, 'Jump24.wav'))]
        self.boost_sound = pg.mixer.Sound(path.join(self.snd_dir, 'Jump29.wav'))
        self.head_jump_sound = pg.mixer.Sound(path.join(self.snd_dir, 'Jump39.wav'))
    ##### NEW METHOD
    def new(self):
        self.score = 0
        self.paused = False
        # add all sprites to the pg group
        # below no longer needed - using LayeredUpdate group
        # self.all_sprites = pg.sprite.Group()
        self.all_sprites = pg.sprite.LayeredUpdates()
        # create platforms group
        self.platforms = pg.sprite.Group()
        # create mplatforms group
        self.platforms = pg.sprite.Group()
        # create ground
        # create clouds group
        self.clouds = pg.sprite.Group()
        # add powerups
        self.powerups = pg.sprite.Group()
        # add cacti
        self.cacti = pg.sprite.Group()
        self.mob_timer = 0
        # add a player 1 to the group
        self.player = Player(self)
        # add a player 1 to the group
        self.featherblades = pg.sprite.Group()
        self.ground = Ground(self, self.screen)
        # add mobs
        self.mobs = pg.sprite.Group()
        # no longer needed after passing self.groups in Sprites library file
        # self.all_sprites.add(self.player)
        # instantiate new platform
        for plat in PLATFORM_LIST:
            # no longer need to assign to variable because we're passing self.groups in Sprite library
            # p = Platform(self, *plat)
            Platform(self, *plat)
        # for plat in MOVEPLAT_LIST:
        #     # no longer need to assign to variable because we're passing self.groups in Sprite library
        #     # p = Platform(self, *plat)
        #     Moveplat(self, *plat)

        for i in range(8):
            c = Cloud(self)
            c.rect.y += 500
        # load music
        # pg.mixer.music.load(path.join(self.snd_dir, 'happy.ogg'))
        # call the run method
        self.run()
    ##### RUN METHOD
    def run(self):
        # game loop
        # play music
        # pg.mixer.music.play(loops=-1)
        # set boolean playing to true
        self.playing = True
        while self.playing:
            self.clock.tick(FPS)
            self.events()
            self.update()
            self.draw()
        # pg.mixer.music.fadeout(1000)
        # other things that happen when not playing anymore
    ##### UPDATE METHOD
    def update(self):
        self.all_sprites.update()
        now = pg.time.get_ticks()
        # scroll ground
        self.rel_g_start =  self.g_scroll_start % self.ground_rect.width
        self.screen.blit(self.ground_image, (self.rel_g_start - self.ground_rect.width, HEIGHT-50))
        if self.rel_g_start < WIDTH:
            self.screen.blit(self.ground_image, (self.rel_g_start, HEIGHT-50))
        # detect the ground or ceiling
        self.player.rect.y += 2
        if self.player.pos.y >= HEIGHT:
            # print("Flying " + str(self.player.flying))
            self.player.vel.y = 0
            self.player.pos.y = HEIGHT-150
            self.player.jumping = False
            # print("should be stopping")
        elif self.player.pos.y <= 225:
            self.player.vel.y = 0
            # print("should be stopping then falling...")
        self.player.rect.y -= 2
        # shall we spawn a mob?
        if now - self.mob_timer > 5000 + random.choice([-1000, -500, 0, 500, 1000]):
            self.mob_timer = now
            Mob(self)
        # check for feather collisions
        # now using collision mask to determine collisions
        # can use rectangle collisions here first if we encounter performance issues
        feather_hits = pg.sprite.groupcollide(self.mobs, self.featherblades, False, False)
        if feather_hits:
            feather_mask_hits = pg.sprite.groupcollide(self.mobs, self.featherblades, True, True, pg.sprite.collide_mask)
            if feather_mask_hits:
                print("That's great kid, don't get cocky...")
        # check for mob collisions
        # now using collision mask to determine collisions
        # can use rectangle collisions here first if we encounter performance issues
        mob_hits = pg.sprite.spritecollide(self.player, self.mobs, False)
        if mob_hits:
            mob_mask_hits = pg.sprite.spritecollide(self.player, self.mobs, False, pg.sprite.collide_mask)
            if mob_mask_hits:
                # can use mask collide here if mob count gets too high and creates performance issues
                ''' I created the below code as an added feature:
                    I wanted to create an option to jump on the enemies'
                    heads to prevent getting stuck...'''
                if self.player.pos.y - 35 < mob_hits[0].rect.top:
                    # print("hit top")
                    print("player is " + str(self.player.pos.y))
                    print("mob is " + str(mob_hits[0].rect.top))
                    # self.head_jump_sound.play()
                    # self.player.vel.y = -BOOST_POWER
                else:
                    print("player is " + str(self.player.pos.y))
                    print("mob is " + str(mob_hits[0].rect.top))
                    # self.playing = False
        # check to see if player collides with plats and can jump - if falling
        if self.player.vel.y > 0:
            hits = pg.sprite.spritecollide(self.player, self.platforms, False)
            if hits:
                ''' set var to be current hit in list to find which to 'pop' to
                when two or more collide with player'''
                find_lowest = hits[0]
                for hit in hits:
                    if hit.rect.bottom > find_lowest.rect.bottom:
                        # print("hit rect bottom " + str(hit.rect.bottom))
                        find_lowest = hit
                # fall if center is off platform
                if self.player.pos.x < find_lowest.rect.right + 5 and self.player.pos.x > find_lowest.rect.left - 5:
                    if self.player.pos.y < find_lowest.rect.centery:
                        self.player.pos.y = find_lowest.rect.top
                        self.player.vel.y = 0
                        self.player.jumping = False
                        # print(str(self.player.vel.x) + " vel x from main...")
            # check for on ground
        # control HORIZONTAL scrolling updates
        # if player reaches right left 1/4 of screen...
        if self.player.pos.x >= WIDTH / 1.25:
            self.player.pos.x = WIDTH / 1.25
            # spawn a cloud
            if randrange(100) < 13:
                Cloud(self)
            # set player location based on velocity
            self.player.pos.x += self.player.vel.x
            for cloud in self.clouds:
                cloud.rect.x -= self.player.vel.x / randrange(2,10)
            # creates slight scroll at the top based on player y velocity
            # scroll platswith player
            for cactus in self.cacti:
                # creates slight scroll based on player y velocity
                cactus.rect.x -= self.player.vel.x
            for plat in self.platforms:
                # creates slight scroll based on player y velocity
                plat.rect.x -= self.player.vel.x
                if plat.rect.right <= 0:
                    plat.kill()
                    self.score += 10
        # if player hits a power up
        pow_hits = pg.sprite.spritecollide(self.player, self.powerups, True)
        for pow in pow_hits:
            if pow.type == 'boost':
                self.boost_sound.play()
                # self.player.vel.y = -BOOST_POWER
                # self.player.jumping = False
        cacti_hits = pg.sprite.spritecollide(self.player, self.cacti, False)
        if cacti_hits:
            if self.player.vel.x > 0 and self.player.pos.x > cacti_hits[0].rect.top:
                    # print("falling")
                    print("player is " + str(self.player.pos.x))
                    print("mob is " + str(cacti_hits[0].rect.top))
          # generate new random platforms
        # this is where new plats are generated
        while len(self.platforms) <  5:
            ''' removed widths and height params to allow for sprites '''
            """ changed due to passing into groups through sprites lib file """
            # p = Platform(self, random.randrange(0,WIDTH-width),
            #                 random.randrange(-75, -30))
            if self.player.rect.x > WIDTH / 2:
                for i in range(5):
                    Platform(self, random.randrange(0,WIDTH + 1000),
                                random.randrange(HEIGHT/2, HEIGHT ))
    ##### EVENTS METHOD
    def events(self):
        for event in pg.event.get():
                now = pg.time.get_ticks()
                flytimer = 200
                if event.type == pg.QUIT:
                    if self.playing:
                        self.playing = False
                    self.running = False
                if event.type == pg.KEYDOWN:
                    if event.key == pg.K_SPACE:
                        if self.player.flying == True:
                            self.player.flying = False
                            # print("Flying " + str(self.player.flying))
                        else:
                            self.player.flying = True
                            # print("Flying " + str(self.player.flying))
                # if event.type == pg.KEYUP:
                #     if event.key == pg.K_SPACE:
                #         """ # cuts the jump short if the space bar is released """
                #         self.player.jump_cut()

                if event.type == pg.KEYDOWN:
                    if event.key == pg.K_p:
                        """ pause """
                        self.paused = True
    ##### DRAW METHOD
    def draw(self):
        self.screen.fill(SKY_BLUE)
        self.all_sprites.draw(self.screen)
        """ # not needed now that we're using LayeredUpdates """
        # self.screen.blit(self.player.image, self.player.rect)
        self.draw_text(str(self.score), 22, WHITE, WIDTH / 2, 15)
        # double buffering - renders a frame "behind" the displayed frame
        pg.display.flip()
    ##### WAIT FOR KEY METHOD
    def wait_for_key(self):
        waiting = True
        while waiting:
            self.clock.tick(FPS)
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    waiting = False
                    self.running = False
                if event.type ==pg.KEYUP:
                    waiting = False
    ##### SHOW START SCREEN METHOD
    def show_start_screen(self):
        """ # game splash screen """
        self.screen.fill(BLACK)
        self.draw_text(TITLE, 48, WHITE, WIDTH/2, HEIGHT/4)
        self.draw_text("WASD to move, Space to jump", 22, WHITE, WIDTH/2, HEIGHT/2)
        self.draw_text("Press any key to play...", 22, WHITE, WIDTH / 2, HEIGHT * 3/4)
        self.draw_text("High score " + str(self.highscore), 22, WHITE, WIDTH / 2, 15)
        pg.display.flip()
        self.wait_for_key()
    ##### SHOW GO SCREEN METHOD
    def show_go_screen(self):
        """ # game splash screen """
        if not self.running:
            print("not running...")
            return
        self.screen.fill(BLACK)
        self.draw_text(TITLE, 48, WHITE, WIDTH/2, HEIGHT/4)
        self.draw_text("WASD to move, Space to jump", 22, WHITE, WIDTH/2, HEIGHT/2)
        self.draw_text("Press any key to play...", 22, WHITE, WIDTH / 2, HEIGHT * 3/4)
        self.draw_text("High score " + str(self.highscore), 22, WHITE, WIDTH / 2, HEIGHT/2 + 40)
        if self.score > self.highscore:
            self.highscore = self.score
            self.draw_text("new high score!", 22, WHITE, WIDTH / 2, HEIGHT/2 + 60)
            with open(path.join(self.dir, HS_FILE), 'w') as f:
                f.write(str(self.score))

        else:
            self.draw_text("High score " + str(self.highscore), 22, WHITE, WIDTH / 2, HEIGHT/2 + 40)

        pg.display.flip()
        self.wait_for_key()
    ##### DRAW TEXT METHOD
    def draw_text(self, text, size, color, x, y):
        font = pg.font.Font(self.font_name, size)
        text_surface = font.render(text, True, color)
        text_rect = text_surface.get_rect()
        text_rect.midtop = (x, y)
        self.screen.blit(text_surface, text_rect)

g = Game()

g.show_start_screen()

while g.running:
    g.new()
    try:
        g.show_go_screen()
    except:
        print("can't load go screen...")


#!/usr/bin/env python
# encoding: utf-8
"""
@author: youfeng
@email: youfeng243@163.com
@license: Apache Licence
@file: view.py
@time: 2017/10/17 23:22
"""
import json

from flask import Blueprint
from flask import request
from flask_login import login_required

from exts.common import log, HTTP_OK, fail, success
from service.charge.impl import ChargeService
from service.charge.model import Charge

bp = Blueprint('charge', __name__, url_prefix='/admin')

# 创建费率
@bp.route('/charge', methods=['POST'])
@login_required
def new_charge():
    if not request.is_json:
        log.warn("参数错误...")
        return fail(HTTP_OK, u"need application/json!!")

    # json = {
    #     'name': 'xxx',
    #     'charge_mode': 'xxxx',
    # }

    name = request.json.get('name', None)
    charge_mode = request.json.get('charge_mode', None)
    if name is None or not isinstance(charge_mode, int) or charge_mode <= 0:
        log.warn("参数错误: name = {} charge_mode = {}".format(name, charge_mode))
        return fail(HTTP_OK, u"name or charge_mode 参数错误!")

    if ChargeService.find_by_name(name) is not None:
        log.warn("费率命名冲突, 数据库中已存在名字相同的费率模板: name = {}".format(name))
        return fail(HTTP_OK, u"费率命名冲突, 数据库中已存在名字相同的费率模板: name = {}".format(name))

    charge, is_success = ChargeService.create(name, charge_mode)
    if not is_success:
        log.warn("创建费率模板失败: name = {} charge_mode = {}".format(name, charge_mode))
        return fail(HTTP_OK, u"创建费率模板失败: name = {} charge_mode = {}".format(name, charge_mode))

    return success(charge.to_dict())

# 获得费率列表
@bp.route('/charge/list', methods=['POST'])
@login_required
def get_charge_list():
    return Charge.search_list()

# 删除费率
# 批量删除设备
@bp.route('/charge', methods=['DELETE'])
@login_required
def delete_charges():
    if not request.is_json:
        log.warn("参数错误...")
        return fail(HTTP_OK, u"need application/json!!")

    id_list = request.json.get('list', None)
    if not isinstance(id_list, list):
        log.warn("参数错误: id_list = {}".format(id_list))
        return fail(HTTP_OK, u"传入不是id列表")

    result_list = []
    for charge_id in id_list:
        charge = Charge.get(charge_id)
        if charge is None:
            log.warn("当前ID设备信息不存在: {}".format(charge_id))
            continue

        if not charge.delete():
            log.warn("费率信息删除失败: {}".format(json.dumps(charge.to_dict(), ensure_ascii=False)))
            continue

        result_list.append(charge_id)

    # 如果当前费率有被成功删除的，则需要更新redis中的费率信息
    # if len(result_list) > 0:
    #     charge = ChargeService.update_charge_to_redis()
    #     if charge is not None:
    #         log.info("完成一次 redis 中费率更新: 最新费率 charge_mode = {}".format(charge.charge_mode))
    #     else:
    #         log.info("更新费率到redis失败!")

    return success(result_list)

# 修改费率
@bp.route('/charge', methods=['PUT'])
@login_required
def update_charges():
    if not request.is_json:
        log.warn("参数错误...")
        return fail(HTTP_OK, u"need application/json!!")

    charge_id = request.json.get('id', None)
    if charge_id is None:
        log.warn("参数错误: charge_id 为None")
        return fail(HTTP_OK, u"参数错误: charge_id 为None")

    charge = Charge.get(charge_id)
    if charge is None:
        log.warn("当前费率模板不存在: charge_id = {}".format(charge_id))
        return fail(HTTP_OK, u"当前费率模板不存在: charge id = {}".format(charge))

    name = request.json.get('name', None)
    charge_mode = request.json.get('charge_mode', None)
    if not isinstance(name, basestring) and not isinstance(charge_mode, int):
        return fail(HTTP_OK, u"需要修改的参数错误，至少需要传入一个需要修改的参数")

    if isinstance(name, basestring) and name.strip() != '':
        other_charge = ChargeService.find_by_name(name.strip())
        if other_charge is not None and other_charge.id != charge.id:
            log.error("修改名称重复: charge_id = {} charge_name = {}".format(charge_id, name))
            return fail(HTTP_OK, u"需要修改的模板名称重复!")
        charge.name = name.strip()
    else:
        return fail(HTTP_OK, u'费率模板名称不能为空字符串!')

    if isinstance(charge_mode, int) and charge_mode > 0:
        charge.charge_mode = charge_mode
    else:
        return fail(HTTP_OK, u"charge_mode 参数类型错误!")

    if not charge.save():
        return fail(HTTP_OK, u"费率模板存储错误!")

    return success(charge.to_dict())

# 获得当前最新费率
# @bp.route('/charge/newest', methods=['GET'])
# @login_required
# def newest_charge():
#     charge = ChargeService.update_charge_to_redis()
#     if charge is not None:
#         log.info("完成一次 redis 中费率更新: 最新费率 charge_mode = {} ctime = {} ".format(
#             charge.charge_mode, charge.ctime.strftime('%Y-%m-%d %H:%M:%S')))
#         return success(charge.to_dict())
#
#     log.info("更新费率到redis失败!")
#     return fail(HTTP_OK, u"费率更新失败!")