import os
import numpy as np
np.random.seed(0)
import h5py
import tensorflow as tf
np.random.seed(0)
import matplotlib.pyplot as plt
from pylab import *
from keras.models import Sequential
from keras.optimizers import Adam
from keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate, LeakyReLU, Dropout, Conv2DTranspose
from keras.models import Model
from keras.layers.normalization import BatchNormalization
from keras.engine.topology import Layer
from keras.layers.pooling import MaxPooling2D
from keras.layers.merge import Concatenate
from keras.layers.core import Lambda, Flatten, Dense
from keras.initializers import glorot_uniform,he_uniform
from keras.utils import plot_model,normalize
from keras.regularizers import l2
import random
from keras import backend as K

'''def encoder_layer(num_filters, apply_batchnorm=True,apply_dropout=False, dropout_prob=0.5):
    #initializer = tf.random_normal_initializer(0., 0.02)
    model = Sequential()
    model.add(Conv2D(num_filters,3,strides=1,padding='same',kernel_initializer='he_uniform',use_bias=False))
    model.add(MaxPooling2D(pool_size=(2, 2), strides=None, padding='valid'))

    if apply_batchnorm:
        model.add(BatchNormalization())
    model.add(LeakyReLU())
    if apply_dropout:
        model.add(Dropout(dropout_prob))
    return model

def decoder_layer(num_filters, apply_batchnorm=True,apply_dropout=False, dropout_prob=0.5):
    #initializer = tf.random_normal_initializer(0., 0.02)
    model = Sequential()
    model.add(Conv2DTranspose(num_filters,3,strides=2,padding='same',kernel_initializer='he_uniform',use_bias=False))

    if apply_batchnorm:
        model.add(BatchNormalization())
        model.add(LeakyReLU())
    if apply_dropout:
        model.add(Dropout(dropout_prob))
    return model

def build_EncoderP2E_dep(input_shape):
    inputs = Input(shape=input_shape)
    outputs = inputs
    for i in range(2):
        layer = encoder_layer(256, apply_batchnorm=False, apply_dropout=True, dropout_prob=0.2)
        outputs = layer(outputs)
    for i in range(3):
        layer = encoder_layer(128, apply_dropout=True, dropout_prob=0.2)
        outputs = layer(outputs)
    for i in range(2):
        layer = encoder_layer(64, apply_dropout=True, dropout_prob=0.2)
        outputs = layer(outputs)
    layer = Conv2D(1,3,strides=2,padding='same',kernel_initializer=tf.random_normal_initializer(0., 0.02),
        activation='sigmoid') #Make fully connected
    outputs = layer(outputs)
    return Model(inputs=inputs, outputs=outputs, name = "EncoderP2E")

def build_EncoderD2E_dep(input_shape):
    inputs = Input(shape=input_shape)
    outputs = inputs
    for i in range(2):
        layer = encoder_layer(256, apply_batchnorm=False, apply_dropout=True, dropout_prob=0.2)
        outputs = layer(outputs)
    for i in range(3):
        layer = encoder_layer(128, apply_dropout=True, dropout_prob=0.2)
        outputs = layer(outputs)
    for i in range(2):
        layer = encoder_layer(64, apply_dropout=True, dropout_prob=0.2)
        outputs = layer(outputs)
    layer = Conv2D(1,3,strides=2,padding='same',kernel_initializer=tf.random_normal_initializer(0., 0.02),
        activation='sigmoid') #Make fully connected
    outputs = layer(outputs)
    return Model(inputs=inputs, outputs=outputs,  name = "EncoderD2E")
'''

def build_EncoderD2E(input_shape, embeddingsize=128):
    '''
    Define the neural network to learn image similarity
    Input :
            input_shape : shape of input images
            embeddingsize : vectorsize used to encode our picture
    '''
     # Convolutional Neural Network
    network = Sequential()
    network.add(Conv2D(32, (7,7), activation='relu',
                     input_shape=input_shape,
                     kernel_initializer='he_uniform',
                     kernel_regularizer=l2(2e-4)))
    network.add(MaxPooling2D())
    network.add(Conv2D(64, (3,3), activation='relu', kernel_initializer='he_uniform',
                     kernel_regularizer=l2(2e-4)))
    network.add(MaxPooling2D())
    network.add(Conv2D(128, (3,3), activation='relu', kernel_initializer='he_uniform',
                     kernel_regularizer=l2(2e-4)))
    network.add(Flatten())
    network.add(Dense(128, activation='relu',
                   kernel_regularizer=l2(1e-3),
                   kernel_initializer='he_uniform'))

    network.add(Dense(embeddingsize, activation=None,
                   kernel_regularizer=l2(1e-3),
                   kernel_initializer='he_uniform'))

    #Force the encoding to live on the d-dimentional hypershpere
    network.add(Lambda(lambda x: K.l2_normalize(x,axis=-1)))

    return network

def build_EncoderP2E(input_shape, embeddingsize=128):
    '''
    Define the neural network to learn image similarity
    Input :
            input_shape : shape of input images
            embeddingsize : vectorsize used to encode our picture
    '''
     # Convolutional Neural Network
    network = Sequential()
    network.add(Conv2D(32, (7,7), activation='relu',
                     input_shape=input_shape,
                     kernel_initializer='he_uniform',
                     kernel_regularizer=l2(2e-4)))
    network.add(MaxPooling2D())
    network.add(Conv2D(64, (3,3), activation='relu', kernel_initializer='he_uniform',
                     kernel_regularizer=l2(2e-4)))
    network.add(MaxPooling2D())
    network.add(Conv2D(128, (3,3), activation='relu', kernel_initializer='he_uniform',
                     kernel_regularizer=l2(2e-4)))
    network.add(Flatten())
    network.add(Dense(128, activation='relu',
                   kernel_regularizer=l2(1e-3),
                   kernel_initializer='he_uniform'))

    network.add(Dense(embeddingsize, activation=None,
                   kernel_regularizer=l2(1e-3),
                   kernel_initializer='he_uniform'))

    #Force the encoding to live on the d-dimentional hypershpere
    network.add(Lambda(lambda x: K.l2_normalize(x,axis=-1)))

    return network

def load_minibatch(num=1000, start=-1):
    #Assuming this loads a minibatch of 1000 (picture + doodles + augment pairs) * 3 (examples positive and negative, indicated by y_train)
    # Assumes the in output.hdf5 pairs are already shuffled and randomized. negative examples are created by adding a
    train_dataset = h5py.File('output.hdf5', "r")
    if start < 0:
        start = random.randint(0,18000)
    train_set_P_orig = np.array(train_dataset["image_dataset"][start:start+num],dtype='float32')
    train_set_D_orig = np.array(train_dataset["sketch_dataset"][start:start+num],dtype='float32')

    train_set_P_anchor = train_set_P_orig
    train_set_D_positive = train_set_D_orig
    y_train = np.ones([num,1],dtype='float32')

    #for i in range(1, n):
    train_set_D_negative =  np.array(train_dataset["bad_sketch_dataset"][start:start+num],dtype='float32') # your train set labels
    #train_set_P = tf.concat([train_set_P,train_set_D_positive train_set_P_orig], 0)
    #train_set_D = tf.concat([train_set_D, train_set_D_orig_false], 0)
    #y_train = tf.concat([y_train, np.zeros([num,1],dtype='float32')],axis=0)
    #print("y_train:",y_train.shape)

    triplets = np.zeros((3,train_set_P_orig.shape[0],train_set_P_orig.shape[1],train_set_P_orig.shape[2],train_set_P_orig.shape[3]))
    triplets[0][:,:,:,:] = train_set_P_anchor/255
    triplets[1][:,:,:,:] = train_set_D_positive/255
    triplets[2][:,:,:,:] = train_set_D_negative/255
    #train_set_P_anchor/255, train_set_D_positive/255, train_set_D_negative/255

    return triplets

def load_testset():
    dataset = h5py.File('output.hdf5', 'r')
    test_set_P = np.array(dataset["test_images"],dtype="float32")
    test_set_D = np.array(dataset["test_images"],dtype="float32")
    return test_set_P, test_set_D

class TripletLossLayer(Layer):
    def __init__(self, alpha, **kwargs):
        self.alpha = alpha
        super(TripletLossLayer, self).__init__(**kwargs)

    def triplet_loss(self, inputs):
        anchor, positive, negative = inputs
        p_dist = K.sum(K.square(anchor-positive), axis=-1)
        n_dist = K.sum(K.square(anchor-negative), axis=-1)
        return K.sum(K.maximum(p_dist - n_dist + self.alpha, 0), axis=0)

    def call(self, inputs):
        loss = self.triplet_loss(inputs)
        self.add_loss(loss)
        return loss

def build_model(input_shape,EncoderP2E, EncoderD2E, margin=20):
        anchor_P_input = Input(input_shape, name="anchor_P_input")
        positive_D_input = Input(input_shape, name="positive_D_input")
        negative_D_input = Input(input_shape, name="negative_D_input")

        # Generate the encodings (feature vectors) for the three images
        encoded_P_anchor = EncoderP2E(anchor_P_input)
        encoded_D_pos = EncoderD2E(positive_D_input)
        encoded_D_neg = EncoderD2E(negative_D_input)

        loss_layer = TripletLossLayer(alpha=margin,name='triplet_loss_layer')([encoded_P_anchor,encoded_D_pos,encoded_D_neg])

        # Connect the inputs with the outputs
        network_train = Model(inputs=[anchor_P_input,positive_D_input,negative_D_input],outputs=loss_layer)
        return network_train

def main():
        #noise = tf.random.normal([1,256,256,3])
        batch_size = 1000 #Normally 1000
        batch_num = 1 #Normally 100
        nCP = 10 #Save checkpoint every nCP epochs
        nSM = 100 #Save model every nSM checkpoints
        #n = tf.constant(1.0) #Number of negative examples per positive example
        #CHANGE: Assuing n is always 1train_set_p_orig
        margin = tf.constant(20.0) #triplet margin
        #test_x, test_y = load_minibatch(num=5, start=0)
        img_rows, img_cols, nc = 256, 256, 3
        input_shape = (img_rows, img_cols, nc)

        EncoderD2E = build_EncoderD2E(input_shape)
        EncoderP2E = build_EncoderP2E(input_shape)

        #EncoderD2E.save("./EncoderModel_Saves/EncoderD2E_" + str(5) + ".h5")
        #EncoderP2E.save("./EncoderModel_Saves/EncoderP2E_" + str(5) + ".h5")

        optimizer = Adam(0.0001, beta_1=0.9)

        network_train = build_model(input_shape,EncoderP2E, EncoderD2E, margin)

        network_train.compile(loss=None,optimizer=optimizer)
        network_train.summary()

        network_json = network_train.to_json()
        mode = 'a' if os.path.exists('checkpoints_triplet/model.json') else 'w'
        with open('checkpoints_triplet/model.json', mode) as json_file:
            json_file.write(network_json)

        #checkpoint_dir = "./checkpoints_triplets"
        #checkpoint_prefix = os.path.join(checkpoint_dir, "triplet")
        #checkpoint = tf.train.Checkpoint(optimizer=optimizer, network_train=network_train)
        #manager = tf.train.CheckpointManager(checkpoint, checkpoint_dir, max_to_keep=3)
        #print("checkpoints: ", manager.checkpoints)

        answer = input("Restore from checkpoint? (y/n)")
        if answer == 'y' or answer == 'yes':
            which_epoch = input("which epoch? (int)")
            network_train.load_weights("checkpoints_triplet/weights_" + str(which_epoch) + ".h5")
            print("loaded weights from disk")
            # test_set_P, test_set_D = load_testset()
            test_set_P, test_set_D, test_set_bad_D = load_minibatch(num=100, start=0)

            while True:
                which_image = input("Which test image would you like to see? (int)")
                dist_real = EncoderP2E.predict(test_set_P[int(which_image):int(which_image) + 1]) - EncoderD2E.predict(test_set_D[int(which_image):int(which_image) + 1])
                dist_fake = EncoderP2E.predict(test_set_P[int(which_image):int(which_image) + 1]) - EncoderD2E.predict(test_set_bad_D[int(which_image):int(which_image) + 1])
                print("dist_real: ", np.sum(np.square(dist_real)))
                print("dist_fake: ", np.sum(np.square(dist_fake)))
                plt.imshow(test_set_P[int(which_image)])
                plt.show()
                plt.imshow(test_set_D[int(which_image)])
                plt.show()
                plt.imshow(test_set_bad_D[int(which_image)])
                plt.show()

        elif answer == 'n' or answer == 'no':
            for iteration in range(1000):
                images_per_step = 1000

                #First choose positive and negative examples
                batch = load_minibatch(num=batch_size)
                for i in range(0,batch_size,images_per_step):
                    print("iteration: ", i)
                    print("input shape: ", np.array([batch[0,i:i+images_per_step,:,:,:], batch[1,i:i+images_per_step,:,:,:], batch[2,i:i+images_per_step,:,:,:]]).shape)
                    network_train.fit([batch[0,i:i+images_per_step,:,:,:], batch[1,i:i+images_per_step,:,:,:], batch[2,i:i+images_per_step,:,:,:]], epochs=5)

                    if iteration % nCP == 0:
                        network_train.save_weights("./checkpoints_triplet/weights_" + str(iteration) + ".h5")

                    if iteration % nSM == 0:
                        EncoderD2E.save("./EncoderModel_Saves/EncoderD2E_" + str(iteration) + ".h5")
                        EncoderP2E.save("./EncoderModel_Saves/EncoderP2E_" + str(iteration) + ".h5")

if __name__ == "__main__":
    main()


import speech_recognition as sr
import pyttsx3

engine = pyttsx3.init()

def speak(audio):
    engine.say(audio)
    engine.runAndWait()
def takeCommand():
    re = sr.Recognizer()
    with sr.Microphone() as sor:
        print("Listening....")
        re.pause_threshold = 1
        audio = re.listen(sor)
    try:
        print("Recognizing....")
        quer = re.recognize_google(audio,language='en-GB')
        print(quer)

    except Exception as e:
        print(e)
        speak("Please Repeat again...")

        return "None"
    return quer
takeCommand()


import scrapy
from zimucatcher.items import ZimucatcherItem

class ZimuSpider(scrapy.spiders.Spider):
    name = "zimuzu"
    allowed_domains = ["zimuzu.tv"]
    start_urls = [
        "http://www.zimuzu.tv/subtitle"
    ]

    def parse(self, response):
        #pageHrefs = response.selector.xpath('//div[@class="pages"]/div/b/a/@href').extract()
        for s in range(8, 2189):
            href = "?page=%d&category=&format=&lang=&sort=" % (s)
            url = response.urljoin(href)
            request = scrapy.Request(url, callback=self.sub_parse)
            yield request

    def sub_parse(self, response):
        hrefs = response.selector.xpath('//div[@class="box subtitle-list"]/ul/li/dl/dt/strong/a/@href').extract()
        for href in hrefs:
            url = response.urljoin(href)
            request = scrapy.Request(url, callback=self.parse_detail)
            yield request

    def parse_detail(self, response):
        url = response.selector.xpath('//div[@class="subtitle-links tc"]/h3/a/@href').extract()[0]
        title = response.selector.xpath('//div[@class="subtitle-links tc"]/h3/a/text()').extract()[0]
        desc = response.selector.xpath('//div[@class="box subtitle-con"]/h2[@class="subtitle-tit"]/text()').extract()[0]
        item = ZimucatcherItem()
        item['title'] = title
        item['desc'] = desc
        print( "downloading: ", url)
        request = scrapy.Request(url, callback=self.parse_file, dont_filter = True)
        yield request

    @staticmethod
    def parse_file(response):
        body = response.body
        item = ZimucatcherItem()
        item['link'] = response.url
        item['body'] = body

        file_name = response.url.replace('/', '_').replace(':', '_')
        print("file_name: ", file_name)
        fp = open('result/' + file_name, 'wb')
        fp.write(item['body'])
        fp.close()
        return item


# coding=utf-8
import pygame
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QLCDNumber, QLineEdit
from game_2 import *
from PyQt5.QtGui import QPixmap

class Menu(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(500, 500, 500, 500) # создаем окно
        self.setWindowTitle('Главное меню')

        self.btn = QPushButton('Начать игру', self)  # создаем кнопку начать игру
        self.btn.resize(150, 150)
        self.btn.move(170, 30)
        self.btn.setStyleSheet("background-color: #98FF98")
        self.btn.clicked.connect(self.start_game)

        self.btn = QPushButton('Выйти из игры', self)  # создаем кнопку выйти из игры
        self.btn.resize(150, 150)
        self.btn.move(330, 30)
        self.btn.setStyleSheet("background-color: #008000")
        self.btn.clicked.connect(self.finish_game)

        self.btn = QPushButton('Информация:', self)  # создаем кнопку информация
        self.btn.resize(150, 150)
        self.btn.move(10, 30)
        self.btn.setStyleSheet("background-color: #008000")
        self.btn.clicked.connect(self.info_game)

        self.label = QLabel(self)  # поле, в которм появится текст
        self.label.resize(700, 150)
        self.label.move(30, 150)

        pixmap = QPixmap('L1.png')  # фото справа
        self.image = QLabel(self)
        self.image.setPixmap(pixmap)
        self.image.resize(300, 300)
        self.image.move(380, 200)

        pixmap1 = QPixmap('tower.png')  # фото слева
        self.image = QLabel(self)
        self.image.setPixmap(pixmap1)
        self.image.resize(200, 200)
        self.image.move(140, 220)

        pixmap2 = QPixmap('R1.png')  # фото слева
        self.image = QLabel(self)
        self.image.setPixmap(pixmap2)
        self.image.resize(300, 300)
        self.image.move(40, 200)

    def finish_game(self):
        self.close()  # закрытие окна
        quit()
    def start_game(self):
        main()  # запускает игру

    def info_game(self):
        self.label.setText("Игра довольно простая, в ней считается количество сделанных персонажем шагов и\n "
                           "пройденное расстояние в пикселях.Если хотите начать игру, нажмите 'Начать игру'")
        # выводит текст

if __name__ == '__main__':
    app = QApplication(sys.argv)
    m = Menu()
    m.show()
    sys.exit(app.exec())

def main():
    pygame.init()
    window = pygame.display.set_mode((1920, 1080))  # создаем окно
    pygame.display.set_caption('Game for YL')  # добавляем имя игры
    font = pygame.font.SysFont("comicsans", 30, True)
    steps = 0

    class Player(object):  # создаем класс игрока с параметрами
        def __init__(self, x, y, width, height, step):  # координаты по x и y ширина и высота
            self.x = x
            self.y = y
            self.width = width
            self.height = height
            self.vel = 5  # скорость игрока
            self.left = False
            self.right = False
            self.walkCount = 0
            self.standing = True
            self.steps = step

        def draw(self, window):  # рисуем героя в зависимости от положения
            if self.walkCount + 1 >= 27:
                self.walkCount = 0
            if self.left and self.steps > 500:
                window.blit(walkLeft[self.walkCount // 3], (self.x, self.y))
                self.walkCount += 1
            elif self.right and self.steps > 500:
                window.blit(walkRight[self.walkCount // 3], (self.x, self.y))
                self.walkCount += 1
            elif self.right is False and self.right is False and self.steps > 500:
                window.blit(playerStand, (self.x, self.y))
            elif self.left and self.steps < 500:
                window.blit(walkLeft_B[self.walkCount // 3], (self.x, self.y))
                self.walkCount += 1
            elif self.right and self.steps < 500:
                window.blit(walkRight_B[self.walkCount // 3], (self.x, self.y))
                self.walkCount += 1
            elif self.right is False and self.right is False and self.steps < 500:
                window.blit(playerStand_B, (self.x, self.y))

    PLATFORM_WIDTH = 64  # высота блока
    PLATFORM_HEIGHT = 64  # ширина блока
    ROAD = pygame.image.load('platformPack_tile016.png')  # дорга
    KUST = pygame.image.load('foliagePack_019.png')  # куст
    TREE = pygame.image.load('foliagePack_009.png')  # дерево
    TOWER = pygame.image.load('tower.png')  # башня
    GAME_OVER = pygame.image.load('game_over.png')

    walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'),
                 pygame.image.load('R3.png'), pygame.image.load('R4.png'),
                 pygame.image.load('R5.png'), pygame.image.load('R6.png'),
                 pygame.image.load('R7.png'), pygame.image.load('R8.png'),
                 pygame.image.load('R9.png')]

    walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'),
                pygame.image.load('L3.png'), pygame.image.load('L4.png'),
                pygame.image.load('L5.png'), pygame.image.load('L6.png'),
                pygame.image.load('L7.png'), pygame.image.load('L8.png'),
                pygame.image.load('L9.png')]
    # моделька игрока в движении
    playerStand = pygame.image.load('standing.png')  # игрок стоит
    walkRight_B = [pygame.image.load('R1_B.png'), pygame.image.load('R2_B.png'),
                   pygame.image.load('R3_B.png'), pygame.image.load('R4_B.png'),
                   pygame.image.load('R5_B.png'), pygame.image.load('R6_B.png'),
                   pygame.image.load('R7_B.png'), pygame.image.load('R8_B.png'),
                   pygame.image.load('R9_B.png')]

    walkLeft_B = [pygame.image.load('L1_B.png'), pygame.image.load('L2_B.png'),
                  pygame.image.load('L3_B.png'), pygame.image.load('L4_B.png'),
                  pygame.image.load('L5_B.png'), pygame.image.load('L6_B.png'),
                  pygame.image.load('L7_B.png'), pygame.image.load('L8_B.png'),
                  pygame.image.load('L9_B.png')]
    # моделька игрока в движении
    playerStand_B = pygame.image.load('standing_B.png')  # игрок стоит
    clock = pygame.time.Clock()

    # карта уровня
    level = [
        "  !!                          ",
        "  !!      ^           ^       ",
        "  !!!!!!!!!!!!!!  ^      @    ",
        "  !!!!!!!!!!!!!!         ^    ",
        "   @    ^    !!!  @    ^      ",
        "       @     !!!    ^ @       ",
        "             !!! ^       @    ",
        "    @   @    !!!        ^     ",
        "  ^   @      !!!    @    @    ",
        "   @     &   !!! &            ",
        "       ^     !!!      ^  ^    ",
        "     ^       !!!    ^         ",
        "             !!!         @    ",
        "  ^    @     !!!         ^    ",
        "      ^      !!!    ^   ^     ",
        "             !!!              "]

    def draw_game_window():  # рисуем карту
        window.fill((62, 117, 59))
        x_block = y_block = 0  # координаты
        for row in level:  # вся строка в level
            for col in row:  # каждый символ в level
                if col == '^' and hero.x != x_block and hero.y != y_block:  # рисуем кусты
                    window.blit(KUST, (x_block, y_block))
                elif col == '&':  # рисуем башню
                    window.blit(TOWER, (x_block, y_block))
                elif col == '!':  # рисуем дорогу
                    window.blit(ROAD, (x_block, y_block))
                elif col == '@':  # рисуем деревья
                    window.blit(TREE, (x_block, y_block))

                x_block += PLATFORM_WIDTH  # блоки платформы ставятся на ширине блоков
            y_block += PLATFORM_HEIGHT  # то же самое и с высотой
            x_block = 0
        hero.draw(window)

        text = font.render("STEPS: " + str(hero.steps // 5), 1,
                           (255, 255, 255))  # Arguments are: text, anti-aliasing, color
        window.blit(text, (1700, 10))
        distance = font.render("DISTANCE: " + str(hero.steps * 5) + "px", 1,
                               (255, 255, 255))  # Arguments are: text, anti-aliasing, color
        window.blit(distance, (1700, 30))

    hero = Player(120, 90, 64, 64, steps)  # создаем игрока, используя консьруктор класса Player
    run = True
    while run:  # основной цикл игры
        clock.tick(27)  # 27 кадров в секунду

        for event in pygame.event.get():
            if event.type == pygame.QUIT:  # если нажать крестик игра завершается без ошибки
                run = False

        keys = pygame.key.get_pressed()  # все клавиши

        if keys[pygame.K_a] and hero.x > hero.vel + 5:  # двжение влево
            hero.x -= hero.vel
            hero.left = True  # направление игрока
            hero.right = False  # направление игрока
            hero.standing = False
            hero.steps += 1

        elif keys[pygame.K_d] and hero.x < 1920 - hero.width - 10 :  # двжение вправо
            hero.x += hero.vel
            hero.left = False  # направление игрока
            hero.right = True  # направление игрока
            hero.standing = False
            hero.steps += 1

        elif keys[pygame.K_w] and hero.y > hero.vel + 5:  # двжение вверх
            hero.y -= hero.vel
            hero.left = False  # направление игрока
            hero.right = True  # направление игрока
            hero.standing = False
            hero.steps += 1

        elif keys[pygame.K_s] and hero.y < 1080 - hero.height - 10:  # движение вниз
            hero.y += hero.vel
            hero.left = True  # направление игрока
            hero.right = False  # направление игрока
            hero.standing = False
            hero.steps += 1

        else:
            hero.left = False  # направление игрока
            hero.right = False  # направление игрока
            hero.walkCount = 0

        draw_game_window()  # рисуем элементы
        pygame.display.update()  # обновляем окно

    pygame.quit()  # обязательная строчка

игра для лицея/game_2.py


#! /usr/bin/env python3

# import modules - always before the code (at the top)
import argparse
import csv

# create ArgumentParser object - description calls for an output when help is called
parser = argparse.ArgumentParser(description='This script parses a GFF file')

# add positional (required) arguments; when running the ./file -h the -h will display this message saying how the argument was positioned

# add positional arguments
parser.add_argument('gff_file', help = 'The name of GFF file to parse', type= str)
parser.add_argument('fasta', help = 'The name of FASTA file to parse', type= str)

# parse the actual arguments
# access argument values via 'args' variable
args = parser.parse_args()

#WHAT I DID
#reading the file

#GFF_file = open(args.gff_file, 'r')
#GFF_lines = GFF_file.readlines()
#GFF_file.close()
#GFF_lines.remove(GFF_lines[-1])

# GFF_lines2 = []

#for line in GFF_lines:
 #   stripped_line = line.strip()
 #   stripped_line2 = stripped_line.split('\t')
 #   length = (int(stripped_line2[4]) - int(stripped_line2[3]) + 1)
 #   print(stripped_line2[2] + '\t' + str(length))

# ---- CLASS VERSION

#open the GFF file (with function automatically closes the file and the lines become a list)
with open (args.gff_file) as gff_file:

	# create a csv reader object
	reader = csv.reader(gff_file, delimiter = '\t')

	#loop over all the lines in the file
	for line in reader:

 		#skip blank lines
 		if not line:
 			continue #this take us to the next line

 		#else it's not a blank line
 		else:
 			#print(line)
 			#line = line.strip() #remove the line breaks
 			#split line on tab character
 			#columns = line.split('\t')
			# print(line)

			#give variable names to the column
 			organism = line[0]
 			source = line[1]
 			feature_type = line[2]
 			start = int(line[3])
 			end = int(line[4])
 			length = line[5]
 			strand = line[6]
 			attributes = line[8]

 			#add the length to column 5
 			line[5] = str(int(end) - int(start) + 1)

 			new_line = '\t'.join(line)

 			print(new_line)

 # ./nameofthefile.py gff3_file fasta_file | less -S (the less -S will show it organized by columns)


from typing import Dict, Optional, Union, TYPE_CHECKING

if TYPE_CHECKING:
    from chj.index.AppAccess import AppAccess
    from chj.index.DataDictionary import DataDictionary

import chj.util.printutil as UP

import chj.index.Taint as T

class TaintOrigins():

    def __init__(self,app: "AppAccess"):
        self.app = app
        self.jd: "DataDictionary" = app.jd

    def as_dictionary(self) -> Dict[str, str]:
        results = {}
        def f(origin: T.TaintBase) -> None:
            results[str(origin.index)] = str(origin)
        self.jd.iter_taint_origins(f)
        return results

    def tostring(self, source: Optional[str]) -> str:
        header = [('index',8)]
        headerline = ''.join([UP.cjust(str(t[0]),8) for t in header]) + ' taint origin site'
        result = []
        lines= []
        def f(origin: T.TaintBase) -> None:
            if (source is None) or (source in str(origin)):
                result.append(str(origin.index).rjust(6) + '  ' + str(origin))
        self.jd.iter_taint_origins(f)
        lines.append(headerline)
        lines.append('-' * 80)
        for t in sorted(result):
            lines.append(t)
        return '\n'.join(lines)


from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem

engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine # connection between classes and tables
Session = sessionmaker(bind=engine)
session = Session()

veggieBurgers = session.query(MenuItem).filter_by(name = 'Veggie Burger')
for veggieBurger in veggieBurgers:
    print(veggieBurger.id)
    print(veggieBurger.price)
    print(veggieBurger.restaurant.name)
    print('\n')

x = session.query(MenuItem).filter_by(id=3).one()
print(x.price)
x.price = '$2.99'
session.add(x)
session.commit()
x = session.query(MenuItem).filter_by(id=3).one()
print(x.price)

veggieBurgers = session.query(MenuItem).filter_by(name = 'Veggie Burger')
for veggieBurger in veggieBurgers:
    if veggieBurger.price != '$2.99':
        veggieBurger.price = '$2.99'
        session.add(veggieBurger)
        session.commit()


import time
import subprocess
from itertools import product
from multiprocessing import cpu_count

def system_cpu_freqs():
    result = subprocess.run(
        ["cat", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies"], stdout=subprocess.PIPE)
    steps = reversed(
        list(map(int, result.stdout.decode().rstrip().split(" "))))
    return steps

def system_cpu_config():

    steps = system_cpu_freqs()
    num_cores = cpu_count()
    config = {}

    for i, (n, step) in enumerate(product(range(num_cores), steps)):
        config[i] = {
            "#id": i,
            "freq": step,
            "cores": n
        }

    return config

def set_scaling_governor():
    subprocess.run(["echo", "userspace", "|", "tee",
                    "/sys/devices/system/cpu/*/cpufreq/scaling_governor"], shell=True).check_returncode()

def set_cpu_freq(freq):
    result = subprocess.run(
        ["cpupower", "frequency-set", "-f", str(freq)], stdout=subprocess.PIPE)
    result.check_returncode()

    time.sleep(3)

    # check if cpu frequency change was successfull
    result = subprocess.run(
        ["cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq"], stdout=subprocess.PIPE)
    current_freq = int(result.stdout.decode("utf-8"))
    if freq != current_freq:
        raise Exception(
            f"setting CPU frequency changed (target=={freq},current_freq={current_freq})")
    print(f"changed CPU frequency to {freq}")


import cv2
import numpy as np
import HandTrackingModule as htm
import time
import autopy
import os
import pyautogui

#############################
wCam, hCam = 640, 480
frameR = 100 # frame Reduction
smoothening = 7
##############################

pTime = 0
plocX, plocY = 0, 0
clocX, clocY = 0, 0

# Volume variables
previous_length = 0
previous_vol = 0
volume_muted = False

cap = cv2.VideoCapture(0)
cap.set(3,wCam)
cap.set(4,hCam)

detector = htm.handDetector(maxHands=1)
wScr, hScr = autopy.screen.size()
#print(wScr, hScr)
while True:
    #1. Find hand landmarks
    success, img = cap.read()
    img = detector.findHands(img)
    lmList, bbox = detector.findPosition(img)

    #2. Get the tip of the index and the middle fingers
    if len(lmList)!=0:
        x1, y1 = lmList[8][1:]
        x2, y2 = lmList[12][1:]
        #print(x1, y1, x2, y2)

    #3. Check which finger are up
        fingers = detector.fingersUp()
        #print(fingers)
        cv2.rectangle(img, (frameR, frameR), (wCam-frameR, hCam-frameR), (255,0,255), 2)

    #4. Only index finger: Moving mode
        if fingers[1]==1 and fingers[2]==0:

            #5. Convert Coordinates
            x3 = np.interp(x1, (frameR,wCam-frameR), (0,wScr))
            y3 = np.interp(y1, (frameR,hCam-frameR), (0,hScr))

            #6. Smoothen Valuse
            clocX = plocX + (x3 - plocX) / smoothening
            clocY = plocY + (y3 - plocY) / smoothening

            #7. Move mouse
            autopy.mouse.move(wScr-clocX, clocY)
            cv2.circle(img, (x1, y1), 15, (255, 0, 255), cv2.FILLED)
            plocX, plocY = clocX, clocY

    #Volume control

        if fingers[1] == 1 and fingers[2] == 1:
    # 15. Find distance between fingers
            length, img, lineInfo = detector.findDistance(4, 8, img)

    # 6. Volume Range 0 - 100
            vol = np.interp(length, [20, 200], [0, 100])

    # 7. Set volume
            if vol < previous_vol:
                for i in range(int(previous_vol - vol)):
                    pyautogui.press('volumedown')
                previous_vol = int(vol)
            elif vol > previous_vol:
                for i in range(int(vol - previous_vol)):
                    pyautogui.press('volumeup')
                previous_vol = int(vol)

            # if int(vol) != previous_vol:
            #     pyautogui.press(['volumedown', 'volumeup'][int(vol) > previous_vol])
            #     previous_vol = int(vol)

    #11. Frame rate
    cTime = time.time()
    fps = 1/(cTime-pTime)
    pTime = cTime
    cv2.putText(img, str(int(fps)), (20, 50), cv2.FONT_HERSHEY_PLAIN, 3, (255,0,0),3)

    #12. Display

    cv2.imshow("AI Virtual Mouse", img)
    if cv2.waitKey(1)  == 27:
        break
cap.release()
cv2.destroyAllWindows()


"""
Calculate Flight Path
Get upcoming prediction
"""

import collections
import datetime
import json
import numpy
from numpy import ndarray
from skyfield.positionlib import Geometric, Geocentric, Barycentric, ICRF
from skyfield.toposlib import wgs84, GeographicPosition
from skyfield.api import EarthSatellite, load
from skyfield.timelib import Time, Timescale

def getPath(
    data: dict[str, dict[str, str | datetime.datetime]],
    mode: str = "latLng",
    duration: float = 10 * 3600,
    resolution: float = 4.0,
) -> dict:
    return (
        getSphericalPath(data, duration, resolution)
        if mode == "latLng"
        else getCartesianPath(data, duration, resolution)
    )

def getSphericalPath(
    data: dict[str, dict[str, str | datetime.datetime]],
    duration: float,
    resolution: float,
) -> dict[str, object]:
    satellite: EarthSatellite = EarthSatellite(
        data["tle1"], data["tle2"], data["tle0"], load.timescale()
    )
    ts: Timescale = load.timescale()
    t: Time = ts.now()
    start = t.utc.second

    interval: Time = ts.utc(
        t.utc.year,
        t.utc.month,
        t.utc.day,
        t.utc.hour,
        t.utc.minute,
        numpy.arange(start, start + duration, resolution * 60),
    )
    location: Geometric | Geocentric | Barycentric | ICRF = satellite.at(interval)
    path: GeographicPosition = wgs84.subpoint(location)

    response: dict[str, object] = dict()
    response["timestamp"]: datetime.time = t.utc
    response["identifier"]: str = data["tle0"]
    response["origin"]: tuple = (
        wgs84.subpoint(satellite.at(t)).latitude.degrees,
        wgs84.subpoint(satellite.at(t)).longitude.degrees,
    )
    response["latArray"]: numpy.array = path.latitude.degrees
    response["lngArray"]: numpy.array = path.longitude.degrees
    response["latLngArray"]: list = [
        [response["latArray"][index], response["lngArray"][index]]
        for index in range(len(response["latArray"]))
    ]
    response["elevationArray"]: numpy.array = path.elevation.au
    response["interval"]: datetime.time = interval

    return response

def getCartesianPath(
    data: dict[str, dict[str, str | datetime.datetime]],
    duration: float,
    resolution: float,
) -> dict[str, object]:
    satellite: EarthSatellite = EarthSatellite(
        data["tle1"], data["tle2"], data["tle0"], load.timescale()
    )
    ts: Timescale = load.timescale()
    t: Time = ts.now()
    start = t.utc.second

    interval: Time = ts.utc(
        t.utc.year,
        t.utc.month,
        t.utc.day,
        t.utc.hour,
        t.utc.minute,
        numpy.arange(start, start + duration, resolution * 60),
    )
    location: Geometric | Geocentric | Barycentric | ICRF = satellite.at(interval)
    d: ndarray = numpy.array([])

    for i in range(len(location.position.km[0])):
        numpy.append(
            d,
            (
                numpy.linalg.norm(
                    numpy.array(
                        [
                            location.position.km[0][i],
                            location.position.km[1][i],
                            location.position.km[2][i],
                        ]
                    )
                    - numpy.array([0, 0, 0])
                )
            ),
        )

    response: dict[str, object] = dict()
    response["identifier"]: str = data["tle0"]
    response["x"]: numpy.array = location.position.km[0]
    response["y"]: numpy.array = location.position.km[1]
    response["z"]: numpy.array = location.position.km[2]
    response["d"]: numpy.array = d  # euclidean distance
    response["interval"]: datetime.time = interval

    return response

def getSerializedPath(data: dict[str, object]) -> dict[str, object]:
    for k in data.keys():
        if isinstance(data[k], numpy.ndarray):
            data[k] = data[k].tolist()
        else:
            data[k] = str(data[k])

    return data

def findHorizonTime(
    data: dict[str, dict[str, str | datetime.datetime]],
    duration: float,
    receiverLocation: wgs84.latlon,
) -> json:
    satellite: EarthSatellite = EarthSatellite(
        data["tle1"], data["tle2"], data["tle0"], load.timescale()
    )
    timestamp: Timescale = load.timescale()
    start: Time = load.timescale().now()

    end: Time = timestamp.utc(
        start.utc.year,
        start.utc.month,
        start.utc.day,
        start.utc.hour,
        start.utc.minute,
        start.utc.second + duration,
    )
    condition: dict[str, float] = {
        "bare": 1.0,
        "marginal": 30.0,
        "good": 45.0,
        "excellent": 60.0,
    }
    degree: float = condition["bare"]  # peak is at 90
    timestampUtc, events = satellite.find_events(
        receiverLocation, start, end, altitude_degrees=degree
    )

    if not numpy.array_equal(events[:1], [0]):
        start = timestamp.utc(
            start.utc.year,
            start.utc.month,
            start.utc.day,
            start.utc.hour,
            start.utc.minute,
            start.utc.second - 15 * 60,
        )
        timestampUtc, events = satellite.find_events(
            receiverLocation, start, end, altitude_degrees=degree
        )

    if not numpy.array_equal(events[-1:], [2]):
        end = timestamp.utc(
            start.utc.year,
            start.utc.month,
            start.utc.day,
            start.utc.hour,
            start.utc.minute,
            start.utc.second + duration + 15 * 60,
        )
        timestampUtc, events = satellite.find_events(
            receiverLocation, start, end, altitude_degrees=degree
        )
    timestampUtc = list(timestampUtc)

    if events.size == 0:
        pass
    elif events.size == 1:
        events = numpy.array([])
    elif events.size == 2:  # [0,1], [1,2], [2,0]
        if numpy.array_equal(events, [0, 1]):
            events = numpy.append(events, 2)
            timestampUtc.append(timestampUtc[-1])
        elif numpy.array_equal(events, [1, 2]):
            events = numpy.insert(events, 0, 0)
            timestampUtc = numpy.insert(timestampUtc, 0, timestampUtc[0])
        elif numpy.array_equal(events, [2, 0]):
            events = numpy.array([])
            timestampUtc = numpy.array([])
    else:
        if not numpy.array_equal(events[:1], [0]):
            # startswith 1 [1,2,0,1,2,0] ==> [1,1,2,0,1,2,0]
            if events[0] == 1:
                events = numpy.insert(events, 0, 0)
                timestampUtc.insert(0, timestampUtc[0])
            # startswith 2 ==> delete
            elif events[0] == 2:
                events = numpy.delete(events, 0)
                timestampUtc.pop(0)

        if not numpy.array_equal(events[-1:], [2]):  # [1,1,2,0,1,2,0,1]
            # endswith 1 ==> 0,1 ==> []
            if events[-1] == 1:
                events = numpy.append(events, 2)
                timestampUtc.append(timestampUtc[-1])
            # endswith 0 ==> delete
            elif events[-1] == 0:
                events = numpy.delete(events, -1)
                timestampUtc.pop(-1)

    # what if events contains multiple 1s?
    removedIndex = []
    for i in range(1, events.size - 1):
        previous = events[i - 1]
        if events[i] == previous:
            removedIndex.append(i)
    formattedEvents = []
    formattedTimeStamps = []
    for i in range(events.size):
        if i not in removedIndex:
            formattedEvents.append(events[i])
            formattedTimeStamps.append(timestampUtc[i])

    # FOR DEBUG
    # SEE HOW IT NORMALLY ALWAYS HAVE [riseabove, culminate, setbelow]
    # print(start.utc_strftime('%Y %b %d %H:%M:%S'), "-", end.utc_strftime('%Y %b %d %H:%M:%S'))
    # for ti, event in zip(t_utc, events):
    #     name = (f'rise above {degree}°', 'culminate', f'set below {degree}°')[event]
    #     print(f'{ti.utc_strftime("%Y %b %d %H:%M:%S")} {name}', end="")
    #     if "set below" in name:
    #         print("")
    #     else:
    #         print(", ", end="")
    # END DEBUG

    response = collections.OrderedDict()
    for index in range(0, len(formattedEvents), 3):
        try:
            formattedTimeStamps[index + 2]
        except IndexError:
            raise IndexError
        else:
            datetime_rise = Time.utc_datetime(formattedTimeStamps[index])
            datetime_peak = Time.utc_datetime(formattedTimeStamps[index + 1])
            datetime_set = Time.utc_datetime(formattedTimeStamps[index + 2])
            t0 = timestamp.utc(
                datetime_rise.year,
                datetime_rise.month,
                datetime_rise.day,
                datetime_rise.hour,
                datetime_rise.minute,
                datetime_rise.second,
            )

            diff = numpy.float64((datetime_set - datetime_rise).total_seconds())
            t0Sec = t0.utc.second
            t1Sec = t0Sec + diff
            eventDuration = timestamp.utc(
                t0.utc.year,
                t0.utc.month,
                t0.utc.day,
                t0.utc.hour,
                t0.utc.minute,
                numpy.arange(t0Sec, t1Sec, 60),
            )
            skyfieldTimeFormat = "%Y %b %d %H:%M:%S"
            eventTimeArray = eventDuration.utc_strftime(skyfieldTimeFormat)

            riseUtc = datetime.datetime.strptime(
                eventTimeArray[0], skyfieldTimeFormat
            ).replace(tzinfo=datetime.timezone.utc)
            setUtc = datetime.datetime.strptime(
                eventTimeArray[-1], skyfieldTimeFormat
            ).replace(tzinfo=datetime.timezone.utc)
            peakUtc = datetime_peak
            riseIso = riseUtc.isoformat(sep="T", timespec="auto")
            setIso = setUtc.isoformat(sep="T", timespec="auto")
            peakIso = peakUtc.isoformat(sep="T", timespec="auto")
            eventInterval = [
                (
                    datetime.datetime.strptime(e, skyfieldTimeFormat).replace(
                        tzinfo=datetime.timezone.utc
                    )
                ).isoformat(sep="T", timespec="auto")
                for e in eventTimeArray
            ]

            response[peakIso] = dict(
                rise=riseIso,
                set=setIso,
                duration=len(eventTimeArray),
                interval=eventInterval,
            )

    return response


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import serial.tools.list_ports
from rplidar import RPLidar
from math import pi, cos, sin

# Find the port name for the RPLidar A1 scanner
PORT_NAMES = [port.device for port in serial.tools.list_ports.comports() if 'USB' in port.name]
if not PORT_NAMES:
    raise IOError("RPLidar A1 not found on any USB ports.")
PORT_NAME = PORT_NAMES[0]
lidar = RPLidar(PORT_NAME)

# Set the motor speed and start the lidar
lidar.set_pwm(750)
lidar.start_motor()

# Set up the figure and axis for the polar plot
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
ax.set_rmax(5000)
ax.grid(True)

# Define the update function for the animation
def update(scan):
    # Convert the scan data to polar coordinates
    angles = np.array([np.radians(meas[1]) for meas in scan])
    distances = np.array([meas[2] for meas in scan])

    # Plot the polar data
    ax.clear()
    ax.set_rmax(5000)
    ax.scatter(angles, distances, s=5, linewidth=0.5)

    # Process the scan data
    for (_, angle, distance) in scan:
        radians = angle * pi / 180.0
        x = distance * cos(radians)
        y = distance * sin(radians)
        point = (x, y)
        # Do something with the point, such as add it to a list or draw it on another plot

    return ax

# Set up the animation
ani = animation.FuncAnimation(fig, update, frames=lidar.iter_scans(),
                              repeat=False, interval=50)

# Show the plot
plt.show()

# Stop the lidar and disconnect from it
lidar.stop_motor()
lidar.stop()
lidar.disconnect()


# Dependencies
import sys
import traceback
import datetime
import logging
import logging.handlers
import time
from flask import Flask, request, jsonify

# Flask
app = Flask(__name__)

# Logger
log_formatter = logging.Formatter('%(levelname)s %(asctime)s %(module)s(line: %(lineno)d): %(message)s')
log_file_handler = logging.handlers.TimedRotatingFileHandler('logs/template.log', when='midnight', encoding='utf-8')
log_file_handler.setFormatter(log_formatter)
log_file_handler.suffix = '%Y-%m-%d'
logger = logging.getLogger(__name__)
logger.addHandler(log_file_handler)
logger.setLevel(logging.DEBUG)

@app.route('/hello', methods=['GET', 'POST'])
def hello():
    log_id = str(time.time())
    text = 'Buddy'
    if 'text' in request.args:
        text = request.args.get("text")
    logger.info('{}: Hello {}'.format(log_id, text))
    return jsonify({'hello': text})

@app.route('/forgive', methods=['GET', 'POST'])
def forgive():
    log_id = str(time.time())
    text = 'me'
    if 'text' in request.args:
        text = request.args.get("text")
        logger.info('{}: Please forgive {}'.format(log_id, text))
        return jsonify({'sorry': text})
    else:
        logger.info('{}: Get error about {}'.format(log_id, text))
        return jsonify({'error_about': text})

@app.route('/sample', methods=['GET', 'POST'])
def sample():
    # Put your logic here !!
    return jsonify({'response': 'OK'})

if __name__ == '__main__':
    if len(sys.argv) < 2:
        raise Exception('Invalid arguments')
    port = int(sys.argv[1])
    app.run(host='0.0.0.0', port=port, debug=True)


import pandas as pd
import geopandas as gpd
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
import warnings

from . import helper_funcs
from . import diagnostics

def crosswalk(source_shape_or_filepath, source_shape_id, target_shape_or_filepath, target_shape_id,
				source_col_id_weights = None, source_col_id_to_be_weighted = None,
				tolerance_percent = 10, tolerance_units = None,
				export = False, export_filename = None):
	# ------------------------------------additional error handling for columns required

	# ---------------------- read in files
	# rudimentary handling of arguments but suffices for now
	if type(source_shape_or_filepath) == 'str' or isinstance(source_shape_or_filepath, str):
		source_shape = gpd.GeoDataFrame.from_file(source_shape_or_filepath)
	else:
		source_shape = source_shape_or_filepath
	if type(target_shape_or_filepath) == 'str' or isinstance(target_shape_or_filepath, str):
		target_shape = gpd.GeoDataFrame.from_file(target_shape_or_filepath)
	else:
		target_shape = target_shape_or_filepath
	source_shape['area_base_source'] = source_shape.area
	target_shape = target_shape.to_crs(source_shape.crs) # kinda important this one
	target_shape['area_base_target'] = target_shape.area

	if source_shape_id == target_shape_id:
		shape_id_old = source_shape_id
		source_shape_id = f'source_{source_shape_id}'
		target_shape_id = f'target_{target_shape_id}'
		source_shape.rename(columns={shape_id_old: source_shape_id}, inplace=True)
		target_shape.rename(columns={shape_id_old: target_shape_id}, inplace=True)
		warnings.warn(f'The source_shape_id provided is the same as the target_shape_id (=\'{shape_id_old}\'). These will be renamed to \'{source_shape_id}\' and \'{target_shape_id}\', respectively.')

	# ---------------------------------intersect
	intersect = gpd.overlay(source_shape, target_shape, how='intersection', keep_geom_type=False)
	intersect['intersect_area'] = intersect.area
	# intersect['geom_type'] = intersect['geometry'].geom_type
	intersect['INTERSECT_ID'] = intersect[source_shape_id].astype(str) + '_' + intersect[target_shape_id].astype(str)

	intersect_unedited = intersect.copy() # preserving just in case - used for user stats below

	# ----------------------------filter intersection based on tolerance
	intersect_smallest_area_from_source_and_target = min(min(intersect['area_base_source']), min(intersect['area_base_target']))

	if tolerance_units is not None and not(np.isnan(tolerance_units)):
		tolerance_percent = (tolerance_units / intersect_smallest_area_from_source_and_target)*100
	elif not(np.isnan(tolerance_percent)):
		tolerance_units = intersect_smallest_area_from_source_and_target*(tolerance_percent/100)
	else:
		raise ToleranceException("Tolerance could not be calculated.")

	intersect_smallest_area_postfilter = tolerance_units

	intersect = intersect[intersect['intersect_area'] > intersect_smallest_area_postfilter]

	# ----------------------------add weights and adjust the desired variable, if provided

	intersect['weight'] = intersect['intersect_area'] / intersect['area_base_source']
	# intersected['weight'+source_col_id_weights] = intersect['weight']
	if source_col_id_weights is not None:
		# calculate weights-providing variable (e.g. population) by target
		# MUST RAISE ERROR HERE IN CASE SOURCE_COL_ID_WEIGHTS is non-number in excel, e.g. if it has commas as thousands operator, this must raise a proper error
		intersect['intersect_'+source_col_id_weights] = intersect['weight'] * intersect[source_col_id_weights]
		intersect['target_shape_'+source_col_id_weights] = intersect.groupby(target_shape_id)['intersect_'+source_col_id_weights].transform('sum')

		if source_col_id_to_be_weighted is not None:
			intersect['intersect_'+source_col_id_to_be_weighted] = (intersect['weight'] * intersect[source_col_id_to_be_weighted]) * (intersect['intersect_'+source_col_id_weights] / intersect['target_shape_'+source_col_id_weights])
			intersect['target_shape_'+source_col_id_to_be_weighted] = intersect.groupby(target_shape_id)['intersect_'+source_col_id_to_be_weighted].transform('sum')

	# ------------------------------get diagnostics
	tolerance_values_sim_prop = [0.00001, 0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2, 0.5, 0.9, 1, 1.5]
	if tolerance_percent/100 not in tolerance_values_sim_prop:
		tolerance_values_sim_prop.append(tolerance_percent/100)
		tolerance_values_sim_prop.sort()

	diagnostics_obj = diagnostics.get_diagnostics_obj(source_shape, source_shape_id, target_shape, target_shape_id, intersect_unedited, intersect, tolerance_percent, tolerance_units, tolerance_values_sim_prop)

	#-------------------------------------------------------------------------------EXPORT--------------------------
	if export:
		if export_filename is None:
			time_now = datetime.now().strftime('%H%M%S-%Y%m%d')
			filename = 'crosswalk_'+time_now+'.csv'
		else:
			filename = export_filename

		if not(filename.endswith('.csv')):
			filename = filename+'.csv'

		# dropping geometry to save space and time
		intersect.drop('geometry', axis='columns', inplace=False).to_csv(filename, index=False)

	return intersect, diagnostics_obj


from datetime import datetime

from flask_login import current_user, UserMixin
from flaskz import res_status_codes
from flaskz.log import flaskz_logger
from flaskz.models import ModelBase, ModelMixin, BaseModelMixin
from flaskz.rest import get_rest_log_msg
from flaskz.utils import find_list, get_app_cache, set_app_cache, get_ins_mapping
from sqlalchemy import Column, Integer, String, Table, ForeignKey, DateTime, Boolean, Text, desc
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import relationship
from werkzeug.security import generate_password_hash, check_password_hash

from ..modules import AutoModelMixin

# 模块&动作关联
# #module#      #action#
# user          add
# user          update
# user          config_email
sys_module_actions = Table('sys_module_actions', ModelBase.metadata,
                           Column('module', String(100), ForeignKey('sys_modules.module', ondelete='CASCADE', onupdate='CASCADE')),
                           Column('action', String(100), ForeignKey('sys_actions.action', ondelete='CASCADE', onupdate='CASCADE')))

class SysAction(ModelBase, ModelMixin):
    """
    系统所有操作列表

    action: 操作, 用于权限控制和角色管理模块 ex)add/update/edit/config
    label: 操作名称,用于角色管理模块 ex)Config Email
    """
    __tablename__ = 'sys_actions'

    action = Column(String(100), primary_key=True, unique=True, index=True)  # add/delete
    label = Column(String(100), nullable=False)  # Add/Delete
    description = Column(String(255))

class SysModule(ModelBase, ModelMixin):
    """
    系统模块列表，模块不一定是菜单，有path属性的模块才会是菜单(SysRole.get_menus)

    name: 模块名字, 用于角色管理模块和系统菜单导航 ex)角色管理
    parent_id: 父模块id
    module: 模块, 用于权限控制和角色管理模块 ex)roles
    path: 路径, 用于前端页面导航和页面返回 ex)roles
    category: 模块分类, 用于平台多业务管理  ex)VPN
    actions: 模块操作列表
    """
    __tablename__ = 'sys_modules'

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(255), nullable=False)
    parent_id = Column(Integer)
    module = Column(String(100), unique=True)  # 用于api和权限控制, path可能为空, 但是module不能为空(例如:只通过api调用的模块)
    path = Column(String(100), unique=True)  # 用于页面导航(前端hash & main/page.py)
    category = Column(String(100))  # 用于模块分类, 多系统整合
    description = Column(String(255))

    actions = relationship('SysAction', secondary=sys_module_actions, lazy='joined')  # 模块操作列表, 不同的模块有不同的操作列表

class SysRoleModule(ModelBase, ModelMixin):
    """
    角色对应的模块和操作列表
    一个角色对应多条记录

    role_id: 角色ID
    module_id: 模块ID
    action: 操作权限
    """
    __tablename__ = 'sys_role_modules'

    id = Column(Integer, primary_key=True, autoincrement=True)
    role_id = Column(Integer, ForeignKey('sys_roles.id', ondelete='CASCADE'), nullable=False)
    module_id = Column(Integer, ForeignKey('sys_modules.id', ondelete='CASCADE'), nullable=False)
    action = Column(String(100), ForeignKey('sys_actions.action', ondelete='CASCADE'))

class SysRole(ModelBase, ModelMixin, AutoModelMixin):
    """
    角色列表

    name: 角色名称
    default: 是否是默认角色(常用于第三方用户校验)
    modules: 模块+操作权限列表
    """
    __tablename__ = 'sys_roles'

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(100), unique=True, nullable=False)
    default = Column(Boolean, default=False)
    description = Column(String(255))
    created_at = Column(DateTime(), default=datetime.now)
    updated_at = Column(DateTime(), default=datetime.now, onupdate=datetime.now)

    modules = relationship('SysRoleModule', cascade='all,delete-orphan')

    def check_permission(self, module, action):
        """
        权限检查
        :param module: 要检查的模块名称
        :param action: 要检查的操作
        :return:
        """
        checked_module_id = SysRole._find_module_id(module)
        if checked_module_id:
            for role_module_ins in self.modules:
                if SysRole._check_module_action_permission(role_module_ins, checked_module_id, action) is True:
                    return True
        return False

    @staticmethod
    def _find_module_id(module_name):
        """返回module名对应的module对象"""
        module_json_list = get_app_cached_modules()
        for item in module_json_list:
            if item.get('module') == module_name:
                return item.get('id')
        return None

    @staticmethod
    def _check_module_permission(menu_json_item, module):
        """检查是否是指定的模块"""
        return menu_json_item.get('module') == module

    @staticmethod
    def _check_module_action_permission(role_module_ins, module_id, action):
        """检查是否包含指定的操作权限"""
        if role_module_ins.module_id != module_id:
            return False

        if action is not None:
            if action == 'add' or action == 'update' or action == 'delete':  # 简化操作，只检查是否有编辑权限，根据需求设置
                action = 'update'
            return role_module_ins.action == action
        return True

    def get_menus(self):
        """
        返回角色的菜单列表(包括父菜单)
        :return:
        """
        all_modules = SysModule.query_all()
        if all_modules[0] is False:
            return all_modules
        all_modules = all_modules[1]
        module_ins_map = get_ins_mapping(all_modules, 'id')

        menus = []
        added_map = {}
        for item in self.modules:
            SysRole._add_menu_item(item.module_id, module_ins_map, menus, added_map)
        menus.sort(key=lambda i: i.id)

        return menus

    @staticmethod
    def _add_menu_item(module_id, module_map, menus, added, is_parent=False):
        if module_id is None:
            return
        module_ins = module_map.get(module_id)
        if module_ins:
            if is_parent is not True and module_ins.path is None:  # @2023-03-10 add to filter menus without path
                return
            if module_id not in added:
                menus.append(module_ins)
                added[module_id] = module_ins
            SysRole._add_menu_item(module_ins.parent_id, module_map, menus, added, True)

    @staticmethod
    def to_client_json(role_model_json):
        modules = []
        for item in role_model_json.get('modules', []):
            module_id = item.get('module_id')
            action = item.get('action')
            _item = find_list(modules, lambda _i: _i.get('module_id') == module_id)
            if _item is None:
                _item = {
                    'module_id': module_id,
                    'actions': []
                }
                modules.append(_item)
            if action is not None:
                _item.get('actions').append(action)

        role_model_json['modules'] = modules
        return role_model_json

    @staticmethod
    def to_server_json(role_client_json):
        model_json = {}
        model_json.update(role_client_json)
        modules = []
        for item in role_client_json.get('modules', []):
            actions = item.get('actions')
            if not actions:
                actions = [None]

            for action in actions:
                modules.append({
                    'module_id': item.get('module_id'),
                    'action': action
                })
        model_json['modules'] = modules
        return model_json

class SysUser(ModelBase, ModelMixin, UserMixin, AutoModelMixin):
    """
    用户列表

    type: 账号类型, local-本地账号, ldap-LDAP账号, aaa-3A认证账号
    username: 账号, 不可重复
    password_: hash以后的密码, 如果不是本地校验的话, 可能为空
    status: 账号状态, 停用或启用
    role_id: 角色ID, 为了简化操作, 使用的是单角色模式
    last_login_at: 上次登录时间(for 管理员)
    """
    __tablename__ = 'sys_users'

    id = Column(Integer, primary_key=True, autoincrement=True)
    type = Column(String(100), nullable=False, default='local')  # local/ldap/aaa
    username = Column(String(100), unique=True, nullable=False)  # account
    password_ = Column('password', String(255))  # hash password
    status = Column(String(100), default='enable')  # disable/enable
    email = Column(String(100))  # @2023-09-18修改，nullable=False-->nullable=True, aaa用户email为空
    name = Column(String(100))  # full name
    phone = Column(String(100))
    role_id = Column(Integer, ForeignKey('sys_roles.id'), nullable=False)
    last_login_at = Column(DateTime())
    description = Column(String(255))
    created_at = Column(DateTime(), default=datetime.now)
    updated_at = Column(DateTime(), default=datetime.now, onupdate=datetime.now)

    role = relationship('SysRole', uselist=False)
    option = relationship('SysUserOption', cascade='all,delete-orphan', uselist=False, lazy='joined')

    @hybrid_property
    def password(self):
        return self.password_

    @password.setter
    def password(self, pwd):
        if self.type == 'local' or self.type is None:
            self.password_ = generate_password_hash(pwd)
        else:
            self.password_ = None

    @staticmethod
    def verify_password(username, password):
        """
        verify username and password

        重载以实现外部登录 & 自动添加账号功能

        :param username:
        :param password:
        :return:
        """
        try:
            user = SysUser.query_by({'username': username.strip()}, return_first=True)
            if not user:
                return False, res_status_codes.account_not_found
            if user.status != 'enable':
                return False, res_status_codes.account_disabled
            if user.password_ is None:  # @2023-09-18添加，密码不存在(aaa)
                return False, res_status_codes.account_verify_err

            if check_password_hash(user.password_, password) is True:  # 移除password.strip()
                return True, user
            else:
                return False, res_status_codes.account_verify_err
        except Exception as e:
            flaskz_logger.exception(e)
            return False, res_status_codes.db_query_err

    @classmethod
    def to_dict_field_filter(cls, field):
        """过滤属性"""
        return field not in ['password'] and super().to_dict_field_filter(field)

    @classmethod
    def check_delete_data(cls, pk_value):
        if current_user and (current_user.id == int(pk_value)):  # 不能删除当前用户
            return res_status_codes.db_data_in_use
        return super().check_delete_data(pk_value)

    @classmethod
    def check_update_data(cls, data):
        if data.get('status') == 'disable' and (current_user and current_user.id == int(data.get('id'))):  # 不能禁用当前用户
            return res_status_codes.db_data_in_use
        return super().check_update_data(data)

    # @classmethod
    # def filter_attrs_by_columns(cls, data):
    #     attrs = super().filter_attrs_by_columns(data)
    #     if data.get('_update_updated_at') is not False:
    #         attrs['updated_at'] = datetime.now()
    #     return attrs

    def can(self, module, action):  # 权限检查
        return self.role.check_permission(module, action)

class SysUserOption(ModelBase, BaseModelMixin):
    """用户选项(内部使用)"""
    __tablename__ = 'sys_user_options'

    id = Column(Integer, primary_key=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey('sys_users.id', ondelete='CASCADE'), nullable=False)
    previous_login_at = Column(DateTime())  # 上次登录时间
    last_login_at = Column(DateTime())  # 最后登录时间
    login_times = Column(Integer, default=0)  # 登录次数
    preferences = Column(Text)  # 偏好设置(replace)

    @classmethod
    def update(cls, option):
        try:
            ins = SysUserOption.query_by({'user_id': option.get('user_id')}, True)
            if ins:
                option['id'] = ins.id
                SysUserOption.update_db(option)
            else:
                ins = SysUserOption.add_db(option)
                flaskz_logger.info(get_rest_log_msg('Update User options', option, True, None))
                return True, ins
        except Exception as e:
            flaskz_logger.exception(e)
        return False, res_status_codes.db_update_err

    @classmethod
    def update_login(cls, user_id, last_login_at=None):
        ins = SysUserOption.query_by({'user_id': user_id}, True)
        previous_login_at = None
        if ins:
            previous_login_at = ins.last_login_at
            login_times = ins.login_times + 1
        else:
            login_times = 1
        return cls.update({
            'user_id': user_id,
            'last_login_at': last_login_at or datetime.now(),
            'previous_login_at': previous_login_at,
            'login_times': login_times
        })

class SysActionLog(ModelBase, ModelMixin):
    """
    操作日志

    username: 操作人员账号
    user_name: 操作人员姓名
    user_ip: 操作IP
    module: 模块名
    action: 操作名
    req_data: 请求数据
    res_data: 结果数据
    result: 操作结果, 成功/失败
    like_columns: 模糊查询列
    """
    __tablename__ = 'sys_action_logs'

    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(100))  # 如果不登录，账号为空
    user_name = Column(String(100))  #
    user_ip = Column(String(100))  #

    module = Column(String(100))  # The name of the module, ex Role Mgmt/User Mgmt
    action = Column(String(100))  # add/remove/update

    req_data = Column(Text())  # request data
    res_data = Column(Text())  # response data
    result = Column(String(100))  # success/fail

    description = Column(Text())  #

    created_at = Column(DateTime(), default=datetime.now)  #

    like_columns = ['module', 'description']

    @classmethod
    def check_add_data(cls, json_data):
        """not check"""
        return True

    @classmethod
    def get_query_default_order(cls):
        """
        Return the default query order.
        :return:
        """

        return desc(cls.created_at)

def get_app_cached_modules():
    """
    返回系统模块列表，为了提高效率，对系统模块进行了缓存
    :return:
    """
    modules = get_app_cache('sys_modules')
    if modules is None:
        modules = []
        all_modules = SysModule.query_all()
        if all_modules[0] is True:
            all_modules = all_modules[1]
            for item in all_modules:
                modules.append(item.to_dict())
        set_app_cache('sys_modules', modules, expire_minutes=60)
    return modules


import matplotlib.pyplot as plt#plotting graph
import matplotlib
import tkinter as tk
#import numpy as np
import math
import random
from matplotlib.pyplot import figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
figure(num=None, figsize=(18, 12), dpi=80, facecolor='w', edgecolor='k')

root = tk.Tk()
root.title("Problem Statement")
text1 = tk.Text(root, height=40, width=100)

text1.pack()
# declaring variables
year = 2011
year_population = 6997990000
pop_inrease_rate = 0.012
e = 2.71828
yearlist = []
poplist = []

print("Welcome to group 4's Modelling and Simulation Project\nThe year is 2011 and the total world population is 6,997,990,000\n")

for x in range(60):

	yearlist.append(year)
	poplist.append(year_population)
	epidemic = random.uniform(0.1,0.9)
	epidemic_severity = random.uniform(0.1,1)
	world_end_disaster = random.uniform(0,1)
	print ("The population for the year " + str(year) +" is " + str(math.trunc(year_population)))
	year_population = (year_population) * e**(pop_inrease_rate)

	text1.insert(tk.INSERT,"The population for the year " + str(year) +" is " + str(math.trunc(year_population))+"\n")
	year = year + 1
	pop_inrease_rate = 0.012

plt.style.use("ggplot")
plt.plot(yearlist,poplist, color='green', linewidth =1)
plt.ylim(6000000000,15000000000)
plt.xlim(2010,2070)
plt.title("year and populace")
plt.xlabel("year")
plt.ylabel("total_population")
plt.grid(True)
plt.show()
root.mainloop()


"""
Modificações na base de dados de extratos
- reformata mes de referenência
- cria a data corrigida (data real da transação
- cria o mês da data corrigida
- cria algumas variáveis sempre fixas
"""

import datetime as dt
from dateutil.relativedelta import relativedelta

def cria_variaveis(dados):
    """
    cria novas variáveis
    @dados: base pd.DataFrame que quero transformar.
    """
    data_base = dados.copy()

    # PARCELA ATUAL E TOTAL
    # procura no memo 2 o número de parcelas

    df1 = data_base[['data', 'memo2', 'mes_ref']].loc[
        data_base['tipo_conta'].isin(['Cartão'])
        & data_base['memo2'].str.contains('^PARC [0-9]{2}/[0-9]{2}$')
    ]
    df1['parc_atual'] = df1['memo2'].str.replace('PARC ', '')
    df1['parc_atual'] = df1['parc_atual'].str.split('/', 1)
    df1['parc_total'] = [int(x[1]) for x in df1['parc_atual']]
    df1['parc_atual'] = [int(x[0]) for x in df1['parc_atual']]

    # DataN
    # data da transação corrigida pelo número de parcelas
    # em trans. parcelada, a data é o momento que a transação foi realizada originalmente

    temp = []
    for index, value in enumerate(df1['data']):
        desloca = value + relativedelta(months=+df1['parc_atual'].iloc[index] - 1)
        if desloca > df1['mes_ref'].iloc[index]:
            temp.append(value)
        else:
            temp.append(desloca)

    df1['dataN'] = temp
    data_base['dataN'] = data_base['data']
    data_base['dataN'].update(df1['dataN'])

    # MES DA DATA DA TRANSAÇÃO
    data_base['mesN'] = [x + relativedelta(day=1) for x in data_base['dataN']]

    # OUTRAS VARIÁVEIS (fixas)
    data_base['moeda'] = 'BRL'
    data_base['tipo_entrada'] = 'OFX'
    data_base['valorN'] = data_base['valor']
    data_base['data_import'] = dt.date.today()

    return data_base


#!/usr/bin/env python
#coding=utf-8
import os
import openai
import sys
prompt = sys.argv[1:]
msg = sys.argv[2:]
print("输入的prompt是:", prompt)
print("输入的msg是:",msg )
exit()
openai.api_key = os.getenv('OPENAI-KEY')
completion = openai.Completion.create(
          model="text-davinci-003",
            prompt="你将扮演一个电商产品编辑，帮我修改一个标题，这是一个产品信息的标题，帮我改的更好一些，这个标题是：",
                temperature=0,
                max_tokens=2048,
    )
print(completion)
print(completion.choices[0].text)


import numpy as np
from math import sqrt, sin, pi, cos, log, exp
import matplotlib.pyplot as plt
import pylab
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D

aa, bb = [0,1]
T = 0.1 # in our case
N = 20 #, 10,20
M = 120 #,10,20,40,80
h = (bb-aa)/N
tau = T/M
# tau = 0.5/(M**2)
nu = tau/h**2
sigma = 1 #, 0.5, 0

x = [i*h for i in range((N)+1)]
# t = [i*tau*M/5 for i in range((M)+1)]
t = [i*tau for i in range((M)+1)]

def solution(x,t):
	return x**3 + t**3
	# return x + t

phi = lambda x: solution(x,0)
fi = lambda x,t: -6*x - 3*x**4 - 3*x*x + 3*t*t
a = lambda x,t: 1
b = lambda x,t: x*x + 1
c = lambda x,t: 0
alfa = lambda t: 0
alfa1 = lambda t: 0
alfa2 = lambda t: -1
beta = lambda t: 3
beta1 = lambda t: 0
beta2 = lambda t: 1

# phi = lambda x: solution(x,0)
# fi = lambda x,t: - x**2
# a = lambda x,t: 1
# b = lambda x,t: x**2 + 1
# c = lambda x,t: 0
# alfa = lambda t: 1
# alfa1 = lambda t: 0
# alfa2 = lambda t: -1
# beta = lambda t: 1
# beta1 = lambda t: 0
# beta2 = lambda t: 1

def Lh(i,k,h,U):
	x = [i*h for i in range((N)+1)]
	t = [i*tau for i in range((M)+1)]
	L1 = (U[i+1][k-1] - 2*U[i][k-1] + U[i-1][k-1])/(h**2)
	L2 = (U[i+1][k-1] - U[i-1][k-1])/(2*h)
	L = a(x[i],t[k])*L1 + b(x[i],t[k])*L2 + c(x[i],t[k])*U[i][k-1]
	return L

def tkst(t,k,sigma):
	if sigma == 1:
		return t[k]
	if sigma == 0:
		return t[k-1]
	if sigma == 0.5:
		return t[k] - tau/2

def explicit_method():
	# x = [i*h for i in range((N)+1)]
	# t = [i*tau for i in range((M)+1)]
	U = np.zeros((N+1, M+1))
	for i in range(N+1):
		U[i][0] =  phi(x[i])
	for k in range(1,M+1):
		for i in range(1, N):
			U[i][k] = U[i][k-1] + tau*(Lh(i,k,h,U) + fi(x[i],t[k-1]))
		U[0][k] = (alfa(t[k]) + alfa2(t[k])*(4*U[1][k] - U[2][k])/(2*h)) / (alfa1(t[k]) + (3*alfa2(t[k]))/(2*h))
		U[N][k] = (beta(t[k]) + beta2(t[k])*(4*U[N-1][k] - U[N-2][k])/(2*h)) / (beta1(t[k]) + (3*beta2(t[k]))/(2*h))
	return U

def progonka(k,U):
	A = np.zeros(N+1); B = np.zeros(N+1); C = np.zeros(N+1); D = np.zeros(N+1)

	A[0] = 0
	B[0] = - (alfa1(t[k]) + alfa2(t[k])/h)
	C[0] = - alfa2(t[k])/h
	D[0] = alfa(t[k])
	B[N] = - (beta1(t[k]) + beta2(t[k])/h)
	A[N] = - beta2(t[k])/h
	C[N] = 0
	D[N] = beta(t[k])

	for i in range(1,N):
		A[i] = sigma*(a(x[i],tkst(t,k,sigma))/h**2 - b(x[i],tkst(t,k,sigma))/(2*h))
		C[i] = sigma*(a(x[i],tkst(t,k,sigma))/h**2 + b(x[i],tkst(t,k,sigma))/(2*h))
		B[i] = sigma*(2*a(x[i],tkst(t,k,sigma))/h**2 - c(x[i],tkst(t,k,sigma))) + 1/tau
		D[i] = - (1/tau)*U[i][k-1] - (1-sigma)*Lh(i,k-1,h,U) - fi(x[i],tkst(t,k,sigma))

	s = np.zeros(N+1); p = np.zeros(N+1); UU = np.zeros(N+1)
	s[0] = C[0]/B[0]; p[0] = -D[0]/B[0]
	for i in range(1,N+1):
		s[i] = C[i]/(B[i] - A[i]*s[i-1])
		p[i] = (A[i]*p[i-1]-D[i])/(B[i]-A[i]*s[i-1])

	UU[N]=p[N]
	for i in range(N-1,-1,-1):
		UU[i] = s[i]*UU[i+1] + p[i]
	return UU

def implicit_method():
	# x = [i*h for i in range((N)+1)]
	# t = [i*tau for i in range((M)+1)]
	U = np.zeros((N+1, M+1))
	for i in range(N+1):
		U[i][0] = phi(x[i])

	A = np.zeros(N+1); B = np.zeros(N+1); C = np.zeros(N+1); D = np.zeros(N+1)
	for k in range(1,M+1):
		Y = progonka(k,U)
		for i in range(N+1):
			U[i][k] = Y[i]
	return U

def plot_surface(x, t, U):
	fig = pylab.figure()
	ax = Axes3D(fig)
	x, t = np.meshgrid(x, t)
	ax.plot_surface(x, t, U,cmap = cm.jet)
	ax.set_xlabel('t')
	ax.set_ylabel('x')
	ax.set_zlabel('U(x,t)')
	pylab.show()

def main():
# 	x = [i*h for i in range((N)+1)]
# 	t = [i*tau for i in range((M)+1)]
	Q = np.zeros((N+1, M+1))
	norm1 = np.zeros((N+1, M+1))
	J_ex1 = np.zeros((N+1, M+1))
	J_ex2 = np.zeros((N+1, M+1))
	U = explicit_method()
	U2 = explicit_method()
	Y = implicit_method()
	for i in range(N+1):
		for k in range(M+1):
			Q[i][k] = solution(x[i],t[k])
			J_ex1[i][k] = abs(Q[i][k] - U[i][k])
			norm1[i][k] = abs(U[i][k] - U2[i][k])
			J_ex2[i][k] = abs(Q[i][k] - Y[i][k])

	# print(J_ex1)
	# print(J_ex2)
	maxx = 0
	Jex = 0
	for i in range(N+1):
		for k in range(M+1):
			if Jex >= maxx:
				Jex = abs(Q[i][k] - U[i][k])
				maxx = Jex
	print(maxx)

	print(h, tau)
	print('sigma = ', sigma)
	# print('N = ', N)
	# print('M = ', M)
	# plot_surface(t, x, Q)
	# plot_surface(t, x, U)
	# plot_surface(t, x, Y)

	i=0.0;k=0; res1 = np.zeros((6, 6)); res2 = np.zeros((6, 6)); res3 = np.zeros((6, 6))
	for j in range(6):
		k = 0.0
		for l in range(6):
			number1 = int(N*i)
			number2 = int(M*k*10)
			res1[l][j] = Q[number1][number2]
			res2[l][j] = U[number1][number2]
			res3[l][j] = Y[number1][number2]
			# print(Q[i][k], U[i][k], Y[i][k])
			# print('x = ',"{0:.7f}".format(x[number1]),'  ','t = ',"{0:.7f}".format(t[number2]),'  ',"{0:.7f}".format(Q[number1][number2]),'  ',"{0:.7f}".format(U[number1][number2]),'  ',"{0:.7f}".format(Y[number1][number2]))
			print(x[number1], t[number2])
			# print   (t)
			k = k + 0.02
		i = i + 0.2
#
	for i in range(6):
		print(res1[i])
		# for k in range(6):
		# 	print(res1[i][k])

main()

Parabolic partial differential equation/Grid method.py


#%%
import pygame
from pygame.sprite import Sprite
class paddle(Sprite):
    #paddle creation
    def __init__(self,game):
        self.screen = game.screen
        self.screen_rect = game.screen.get_rect()
        #getting paddle image
        self.image = pygame.image.load("Paddle.bmp")
        self.rect = self.image.get_rect()
        #positioning paddle in screen
        self.rect.centerx = self.screen_rect.centerx
        self.rect.y = 570
        #defining moving_right and left
        self.moving_right = False
        self.moving_left = False
        #setting default paddle speed
        self.paddle_speed = 0.9
        self.updating_paddle_speed = self.paddle_speed
        self.center = float(self.rect.centerx)

    def blitme(self):
        #creating image
        self.screen.blit(self.image, self.rect)

    def update(self):
        #moving paddle
        if self.moving_right and self.rect.right <= self.screen_rect.right:
            self.center += self.updating_paddle_speed
        if self.moving_left and self.rect.left >= self.screen_rect.left:
            self.center -= self.updating_paddle_speed
        self.rect.centerx = self.center


import os
import shlex
import argparse
import subprocess
from pathlib import Path

if __name__ == "__main__":

    parser = argparse.ArgumentParser(description="Wrapper for selection")

    parser.add_argument(
        "--path_field", type=str, default="./S82sub8_tmpl", help="Path to field",
    )
    parser.add_argument(
        "--path_out", type=str, default="./Fink_outputs", help="Path to outputs",
    )
    parser.add_argument(
        "--debug", action="store_true", help="Debug: files processed in loop",
    )
    parser.add_argument(
        "--test", action="store_true", help="Debug: one file processed only",
    )

    args = parser.parse_args()
    path_field = args.path_field
    path_out = args.path_out

    os.makedirs(args.path_out, exist_ok=True)

    # 0. process data
    cmd = (
        "python -W ignore 0_get_Fink_features_xmatch.py "
        f"--path_field {path_field} --path_out {path_out}"
    )
    if args.debug:
        cmd += "--debug"
    if args.test:
        cmd += "--test"
    subprocess.check_call(shlex.split(cmd))

    # 1. Filtering
    tmp = Path(path_field).name
    fname = f"{tmp}.pickle"
    print(f"Features from {fname}")
    cmd = (
        "python -W ignore 1_filter_top_candidates.py "
        f"--fname {fname} --path_out {path_out} "
    )
    subprocess.check_call(shlex.split(cmd))


import os

from starlette import status

async def test_download_document_works_as_expected(
    authorized_client,
    app_context,
    env_settings,
    new_pet,
    markdown_file,
    aws_credentials,
    s3_storage,
    s3_client,
):
    files = {"file": ("readme.md", markdown_file, "text/markdown")}
    resp = await authorized_client.post(f"/pets/{new_pet.id}/document", files=files)
    assert resp.status_code == status.HTTP_201_CREATED

    doc_id = resp.json()["id"]
    resp = await authorized_client.get(f"/documents/stream/{doc_id}")
    assert resp.status_code == status.HTTP_200_OK
    markdown_file.seek(0)
    assert resp.content == markdown_file.read()
    assert resp.headers == {
        "content-disposition": 'text/markdown; filename="readme.md"',
        "content-type": "text/markdown; charset=utf-8",
    }

async def test_delete_document_works_as_expected(
    authorized_client,
    app_context,
    env_settings,
    new_pet,
    markdown_file,
    aws_credentials,
    s3_storage,
    s3_client,
):
    files = {"file": ("readme.md", markdown_file, "text/markdown")}
    resp = await authorized_client.post(f"/pets/{new_pet.id}/document", files=files)
    assert resp.status_code == status.HTTP_201_CREATED

    doc_id = resp.json()["id"]
    folder_path = os.path.join(env_settings.storage_root, env_settings.documents_path, str(new_pet.id))
    documents = await app_context.storage.ls(folder_path)
    assert len(documents) == 1

    resp = await authorized_client.delete(f"/documents/{doc_id}")
    assert resp.status_code == status.HTTP_204_NO_CONTENT

    documents = await app_context.storage.ls(folder_path)
    assert len(documents) == 0


"""
Code level tests for get_message_contents method pf pto_detector lambda
"""
import ast
import collections
from parameterized import parameterized, parameterized_class
from pto_detector import pto_detector

def get_class_name(cls, num, params_dict):
    """
    multiple parameters being included in the generated class name:
    """
    return "%s_%s_%s%s" %(
        cls.__name__,
        num,
        parameterized.to_safe_name(params_dict['event']),
        parameterized.to_safe_name(params_dict['expected_message_contents']),
    )

@parameterized_class([
   { "event":str({"Records": [{"body": "{\"Message\":\"{\\\"msg\\\": \\\"Test: I am on PTO today\\\", \\\"chat_id\\\": \\\"19:f33e901e871d4c3c9ebbbbee66e59ebe@thread.skype\\\", \\\"user_id\\\":\\\"blah\\\"}\"}"}]}), "expected_message_contents": str({'msg': 'Test: I am on PTO today', 'chat_id': '19:f33e901e871d4c3c9ebbbbee66e59ebe@thread.skype','user_id': 'blah'})},
   { "event":str({"Records": [{"body": "{\"Message\":\"{\\\"msg\\\": \\\"Test: I am on PTO tomorrow\\\", \\\"chat_id\\\": \\\"19:f33e901e871d4c3c9ebbbbee66e59ebe@thread.skype\\\", \\\"user_id\\\":\\\"blah\\\"}\"}"}]}), "expected_message_contents": str({'msg': 'Test: I am on PTO tomorrow', 'chat_id': '19:f33e901e871d4c3c9ebbbbee66e59ebe@thread.skype','user_id': 'blah'})}
   ], class_name_func=get_class_name)

class TestWriteMessage(object):
    """
    Test class for get message contents
    """
    def get_event_data_structure(self, event_string):
        """
        Method used for converting nested dictionary/list to data similar to tabular form
        """
        obj = collections.OrderedDict()
        def recurse(dataobject,parent_key=""):
            """
            Method will recurse through object
            """
            if isinstance(dataobject,list):
                # loop through list and call recurse()
                for i in range(len(dataobject)):
                    recurse(dataobject[i],parent_key + "_" + str(i) if parent_key else str(i))
            elif isinstance(dataobject,dict):
                # loop through dictionary and call recurse()
                for key,value in dataobject.items():
                    recurse(value,parent_key + "_" + key if parent_key else key)
            else:
                # use the parent_key and store the value to obj
                obj[parent_key] = dataobject

        recurse(event_string)

        return obj

    def extract_event_from_event_string(self):
        """
        Method to get event dict
        """
        event_structure = self.get_event_data_structure(self.event)
        event =ast.literal_eval(event_structure[''])

        return event

    def test_pto_detector_get_message_contents(self):
        """
        Code level test for pto_detctor
        """
        event = self.extract_event_from_event_string()
        actual_message = pto_detector.get_message_contents(event)
        assert str(actual_message) == self.expected_message_contents


import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler, OneHotEncoder, OrdinalEncoder
from sklearn.compose import ColumnTransformer
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import scikitplot as skplt
import matplotlib.pyplot as plt

# Load data
df = pd.read_csv("data/HR_comma_sep.csv")
X = df.drop(['left'], axis=1)
y = df['left']
# Split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

ordinal = ['salary']
onehot = ['sales']
numeric = ['satisfaction_level', 'last_evaluation', 'number_project', 'average_montly_hours', 'time_spend_company']

# Data transformation
ct = ColumnTransformer(
    [
        ("ordinal", OrdinalEncoder(categories=[['low', 'medium', 'high']]), ordinal),
        ("onehot", OneHotEncoder(), onehot),
        ("stdscal", StandardScaler(), numeric)
    ], remainder='passthrough')

df_tr = ct.fit_transform(X_train)

# Build the model
def build_nn_binclassifier():
    model = Sequential()
    model.add(Dense(20, activation="relu"))
    model.add(Dense(1, activation="sigmoid"))
    model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
    return model

nn_binaryclassifier = KerasClassifier(build_fn=build_nn_binclassifier, nb_epoch=10)

# Cross-validation
scores = cross_val_score(estimator=nn_binaryclassifier, X=df_tr, y=y_train, cv=5, n_jobs=-1,verbose=False)

# Evaluate model on test set
nn_binaryclassifier.fit(df_tr, y_train,verbose=False)
X_test_tr = ct.transform(X_test)
test_predictions = nn_binaryclassifier.predict(X_test_tr)
y_classes = (test_predictions > 0.5)

with open("metrics.txt", 'w') as outfile:
    outfile.write(f"Test accuracy score : {100 * nn_binaryclassifier.score(X_test_tr, y_test):.2f}\n")
skplt.metrics.plot_confusion_matrix(y_test, y_classes, normalize=True)
plt.savefig("test_confusion_matrix.png")


import pickle
import numpy as np
import matplotlib.pyplot as plt
import sys

def load_history(path):
    with open(path, 'rb') as f:
        data = pickle.load(f)
    return data

def plot_graph(x, y, xticks, yticks, x_label, y_label, title):
    plt.figure(figsize=(10, 10))
    plt.title(title)
    plt.plot(x, y, linewidth=2, marker='o', markersize=2)
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    plt.xticks(xticks)
    plt.yticks(yticks)
    plt.grid(True)
    plt.show()

def plot_metrics(history_data):
    epochs = np.arange(len(history_data['loss'])) + 1
    for key in history_data:
        if 'loss' in key:
            plot_graph(epochs, history_data[key], epochs, np.linspace(0, 0.7, num=15), "Epochs", key, key+" per Epoch")
        elif 'acc' in key:
            plot_graph(epochs, history_data[key], epochs, np.linspace(0, 1, num=15), "Epochs", key, key+"per Epoch")

plot_metrics(load_history(sys.argv[1]))


from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Person
from .serializers import PersonSerializer
from django.shortcuts import get_object_or_404

@api_view(['GET', 'POST', 'PUT', 'DELETE'])
def person_list(request, format=None):
    if request.method == 'GET':
        email = request.GET.get('email')
        if email:
            person = Person.objects.filter(email=email)
        else:
            person = Person.objects.all()
        serializer = PersonSerializer(person, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = PersonSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'PUT':
        email = request.GET.get('email')
        if email:
            person = Person.objects.get(email=email)
            serializer = PersonSerializer(person, data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        email = request.GET.get('email')
        person = Person.objects.filter(email=email)
        if person:
            person.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


from torch.utils.data import Dataset
import pandas as pd

class LivedoorDataset(Dataset):
    def __init__(
        self,
        tokenizer,
        file_path=None,
        data_frame: pd.DataFrame = None,
        input_max_len=512,
        target_max_len=512,
    ):
        # file_path か data_frameは設定する必要があるため、設定していない場合は例外を発火
        if file_path is None and data_frame is None:
            raise DatasetError(
                "file_path and data_frame are None! please set file_path or data_frame!"
            )

        self.file_path = file_path
        self.data_frame = data_frame

        self.input_max_len = input_max_len
        self.target_max_len = target_max_len
        self.tokenizer = tokenizer
        self.inputs = []
        self.targets = []

        self._build()

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

    def __getitem__(self, index):
        source_ids = self.inputs[index]["input_ids"].squeeze()
        target_ids = self.targets[index]["input_ids"].squeeze()

        source_mask = self.inputs[index]["attention_mask"].squeeze()
        target_mask = self.targets[index]["attention_mask"].squeeze()

        return {
            "source_ids": source_ids,
            "source_mask": source_mask,
            "target_ids": target_ids,
            "target_mask": target_mask,
        }

    def _build(self):
        def make_record(title, body):
            # ニュースタイトル生成タスク用の入出力形式に変換する。
            input = f"{body}"
            target = f"{title}"
            return input, target

        def append_item(title, body, genre_id):
            input, target = make_record(title, body)

            tokenized_inputs = self.tokenizer.batch_encode_plus(
                [input],
                max_length=self.input_max_len,
                truncation=True,
                padding="max_length",
                return_tensors="pt",
            )

            tokenized_targets = self.tokenizer.batch_encode_plus(
                [target],
                max_length=self.target_max_len,
                truncation=True,
                padding="max_length",
                return_tensors="pt",
            )

            self.inputs.append(tokenized_inputs)
            self.targets.append(tokenized_targets)

        if self.file_path is not None:
            with open(self.file_path, "r", encoding="utf-8") as f:
                for line in f:
                    line = line.strip().split("\t")
                    assert len(line) == 3
                    assert len(line[0]) > 0
                    assert len(line[1]) > 0
                    assert len(line[2]) > 0

                    title = line[0]
                    body = line[1]
                    genre_id = line[2]

                    append_item(title=title, body=body, genre_id=genre_id)
        elif self.data_frame is not None:
            assert (
                len(self.data_frame.columns) == 3
            ), "data frame columns count is not 3. columns is {}".format(
                self.data_frame.columns
            )
            for index, row in self.data_frame.iterrows():
                append_item(
                    title=row["title"],
                    body=row["body"],
                    genre_id=row["genre_id"],
                )
        else:
            raise DatasetError(
                "file_path and data_frame are None! please set file_path or data_frame!"
            )

class WikihowDataset(Dataset):
    pass

class DatasetError(Exception):
    pass