# Créditos: código del equipo "Rodi Balboa", ganador del torneo de robot-sumo (RoDI)

import rodi
import time
import keyboard

robot = rodi.RoDI()
# for i in range(4):
#   robot.move_forward()
#  time.sleep(1.5)
# robot.move_stop()
# robot.move_left()
# time.sleep(0.55)
# robot.move_stop()
# RODI CANTA
doremi_hz = ["2093", "2349", "2637", "2794", "3136", "3520", "3951", "4699", "4186"]
do = doremi_hz[0]
re = doremi_hz[1]
mi = doremi_hz[2]
fa = doremi_hz[3]
sol = doremi_hz[4]
la = doremi_hz[5]
si = doremi_hz[6]
re1 = doremi_hz[7]
do1 = doremi_hz[8]
cumple = [
    sol,
    sol,
    la,
    sol,
    do,
    si,
    sol,
    sol,
    la,
    sol,
    re1,
    do1,
    do,
    mi,
    sol,
    mi,
    do,
    si,
    la,
    fa,
    fa,
    mi,
    do,
    re,
    do,
]
rodi_entrada = [mi, sol, sol, la, la, la, la]
# print(len(cumple))
# RODI ESQUIVA AUTOMATICO
# for i in range(4):
#   print(robot.see())
#  time.sleep(0.1)
# def ataque():
#    if int(robot.see()) < 10:
#        robot.move_stop()
#        robot.move_left()
#        time.sleep(0.5)

# while True:
#    robot.move_forward()
#    print(robot.see())
#    ataque()
#    time.sleep(0.2)
"""def al_frente():
  if keyboard.is_pressed('w'):
    robot.move_forward()
def izquierda():
  if keyboard.is_pressed('a'):
    robot.move_left()"""

def entrada():
    robot.sing(mi, 250)
    time.sleep(0.25)
    robot.sing(sol, 500)
    time.sleep(0.5)
    robot.sing(la, 2000)
    time.sleep(2)
    robot.sing(la, 250)
    time.sleep(0.25)
    robot.sing(si, 500)
    time.sleep(0.5)
    robot.sing(mi, 2000)
    time.sleep(2)
    # robot.move_forward()
    """for i in range(len(rodi_entrada)):
    robot.sing(int(rodi_entrada[i]),250)
    time.sleep(0.250)
  robot.move_stop()"""

# entrada()

while True:
    if keyboard.is_pressed("w"):
        robot.move_forward()
    elif keyboard.is_pressed("a"):
        robot.move_left()
    elif keyboard.is_pressed("d"):
        robot.move_right()
    elif keyboard.is_pressed("s"):
        robot.move_backward()
    elif keyboard.is_pressed("p"):
        entrada()
    else:
        robot.move_stop()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Compress model with our ternary compressed algorithm and
using compressed network to classify data sampled from CIFAR10 data.

Network can be customed, see class My_Model for more details about how to custome model,
which will be added with a classification layer.  Note that VGG net will first be
trained with all CIFAR10 dataset for a better classification.
"""

__author__ = "Model_compression"
__copyright__ = "Copyright 2021, Lossless compression"
__license__ = "GPL"
__version__ = "1.0.1"
__email__ = "yongqi_du@hust.edu.cn"
__status__ = "Production"
import sys
import os

sys.path.append(
    os.path.dirname(
        os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
import math
from collections import Counter, OrderedDict

import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, Dataset
from model_define.model import My_Model
from equation_solve.solve_equation import solve_equation

from vgg_net_cifar10 import VGG

device = "cuda:1" if torch.cuda.is_available() else "cpu"

class Feature_Dataset(Dataset):

    def __init__(self, X, Y) -> None:
        super().__init__()
        self.X, self.Y = X, Y

    def __getitem__(self, idx):
        return self.X[idx, :], self.Y[idx]

    def __len__(self):
        return self.X.shape[0]

class sample_ternary_weight(object):

    def __init__(self, kesi) -> None:
        self.kesi = kesi

    def sample(self):
        init = torch.distributions.uniform.Uniform(0,
                                                   1).sample(torch.Size([1]))
        if init < self.kesi:
            init = 0
        else:
            mask = torch.distributions.bernoulli.Bernoulli(0.5).sample(
                torch.Size([1]))
            if mask == 0:
                init = 1 / np.sqrt(1 - self.kesi)
            else:
                init = -1 / np.sqrt(1 - self.kesi)
        return init

    def sample_n(self, number):
        init = [self.sample() for _ in range(number)]
        init = np.array(init)
        return init

if __name__ == '__main__':
    # data
    # gpu_usage()
    # ------------------------------Data Preparing------------------------------------
    model_vgg = VGG('VGG19')
    model_vgg.load_state_dict(torch.load('./model_vgg'))
    # load data
    transform_train = transforms.Compose([
        transforms.RandomCrop(32, padding=4),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize((0.4914, 0.4822, 0.4465),
                             (0.2023, 0.1994, 0.2010)),
    ])

    transform_test = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize((0.4914, 0.4822, 0.4465),
                             (0.2023, 0.1994, 0.2010)),
    ])

    train_data = torchvision.datasets.CIFAR10(root='./data',
                                              train=True,
                                              download=True,
                                              transform=transform_train)
    trainloader = torch.utils.data.DataLoader(train_data,
                                              batch_size=50000,
                                              shuffle=False)

    test_data = torchvision.datasets.CIFAR10(root='./data',
                                             train=False,
                                             download=True,
                                             transform=transform_test)
    testloader = torch.utils.data.DataLoader(test_data,
                                             batch_size=10000,
                                             shuffle=False)

    classes = ('Airplane', 'Car', 'Bird', 'Cat', 'Deer', 'Dog', 'Frog',
               'Horse', 'Ship', 'Truck')

    # ------------------------------Feature Extration----------------------------------
    # output of feature
    train_data, train_label = next(iter(trainloader))
    test_data, test_label = next(iter(testloader))
    with torch.no_grad():
        feature_train = model_vgg.features(train_data)
        feature_train = feature_train.view(feature_train.shape[0], -1)
        feature_test = model_vgg.features(test_data)
        feature_test = feature_test.view(feature_test.shape[0], -1)
        p = feature_train.shape[1]
        N = feature_train.shape[0]
        mean_selected_data = torch.mean(feature_train, dim=0)
        norm2_selected_data = torch.sum(
            (feature_train - mean_selected_data)**2, (0, 1)) / N
        feature_train = feature_train - mean_selected_data
        feature_train = feature_train / np.sqrt(norm2_selected_data)

        p = feature_test.shape[1]
        N = feature_test.shape[0]
        mean_selected_data = torch.mean(feature_test, dim=0)
        norm2_selected_data = torch.sum((feature_test - mean_selected_data)**2,
                                        (0, 1)) / N
        feature_test = feature_test - mean_selected_data
        feature_test = feature_test / np.sqrt(norm2_selected_data)

    # dataset for future training testing
    feature_train_dataset = Feature_Dataset(feature_train, train_label)
    feature_test_dataset = Feature_Dataset(feature_test, test_label)

    tau_zero = torch.sqrt(
        torch.mean(torch.diag(torch.mm(feature_train,
                                       feature_train.t())))).detach().numpy()

    # tau_zero = 1
    print(tau_zero)

    # -------------------------------- Network Setting---------------------------------
    # origin network setting
    layer_num = 3  # layer number for network
    input_num = 512  # input dimension for network 784/256
    weight_num_list = [400, 400, 200]  # number for neurons for each layer
    activation_list = [
        {
            'name': 'ReLU',
            'args': None
        },
        # {'name' : 'Binary_Zero', 'args' : {'s1':1, 's2': 2, 'b1': 1}},
        {
            'name': 'ReLU',
            'args': None
        },
        # {'name' : 'Sign', 'args' : None},
        # {'name' : 'Sign', 'args' : None}]
        {
            'name': 'ReLU',
            'args': None
        }
    ]  # activation for each layer, if with param, write as Binary_Zero here

    #  define origin model
    model = My_Model(layer_num=layer_num,
                     input_num=input_num,
                     weight_num_list=weight_num_list,
                     activation_list=activation_list,
                     tau_zero=tau_zero)
    res = solve_equation(model, tau_zero, loop=10)
    activation_list = res
    # define compressed model!!!!!!!!!!!
    new_model = My_Model(layer_num=layer_num,
                         input_num=input_num,
                         weight_num_list=weight_num_list,
                         activation_list=activation_list,
                         tau_zero=tau_zero)
    model_new = nn.Sequential(
        OrderedDict([
            ('feature', new_model),
            ('classification',
             nn.Linear(model.weight_num_list[-1], 10, bias=False)),
            ('activation', nn.Softmax()),
        ]))

    # --------------------------------Model Initilization-------------------------------
    # model initialization
    initialization_way = 'ternary'  # select from ['normal', 'random_sparsity', 'ternary']
    kesi = 0.95  # change from 0 to 1, only used for ['random sparsity', 'ternary']

    if initialization_way == 'normal':
        # normal initialization
        for fc in model_new.feature.fc_layers:
            nn.init.normal_(fc.weight)
            fc.weight.requires_grad = False
    elif initialization_way == 'random_sparsity':
        # random sparse gaussian weight(break assumption1)
        for fc in model_new.feature.fc_layers:
            mask = np.zeros(fc.weight.shape).flatten()
            mask[:round((1 - kesi) * mask.size)] = 1
            np.random.shuffle(mask)
            mask = torch.tensor(mask.reshape(fc.weight.shape)).float()
            nn.init.normal_(fc.weight)
            with torch.no_grad():
                fc.weight = torch.nn.Parameter(mask * fc.weight.data,
                                               requires_grad=False)
    elif initialization_way == 'ternary':
        # tarnary weight with sparsity kesi
        for fc in model_new.feature.fc_layers:
            init = np.zeros(fc.weight.shape).flatten()
            init[:round(1 / 2 * (1 - kesi) *
                        init.size)] = 1 / np.sqrt(1 - kesi)
            init[round(1 / 2 * (1 - kesi) * init.size):2 *
                 round(1 / 2 *
                       (1 - kesi) * init.size)] = -1 / np.sqrt(1 - kesi)
            # c = Counter(init)
            np.random.shuffle(init)
            init = torch.tensor(init.reshape(fc.weight.shape)).float()
            with torch.no_grad():
                fc.weight = torch.nn.Parameter(init, requires_grad=False)

    # --------------------------------Preparing-------------------------------------------
    batch_size = 128
    # define data
    feature_train_dataloader = DataLoader(feature_train_dataset,
                                          batch_size=batch_size,
                                          shuffle=False,
                                          num_workers=10,
                                          pin_memory=True)
    feature_test_dataloader = DataLoader(feature_test_dataset,
                                         batch_size=batch_size,
                                         shuffle=False,
                                         num_workers=10,
                                         pin_memory=True)

    # you can load model origin as the initialization values for model new(the classification layer)
    # path = "./model_origin[5000, 5000, 2500]"
    # # '''load origin parameters!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'''
    # state_dict= torch.load(path)
    # model_new.classification.weight = torch.nn.Parameter(state_dict['classification.weight'].detach().cpu())
    net = model_new
    criterion = nn.CrossEntropyLoss()
    net = net.to(device)
    net.eval()
    loss_record = []
    accuracy_record = []
    # ---------------------------Origin Loading Validation(optional)-----------------------------
    # Validation the initial accuracy for model(after loading parameters from origin model)
    # validation
    for val_data, val_label in feature_test_dataloader:
        val_data, val_label = val_data.to(device), val_label.to(device)
        with torch.no_grad():
            pred = net(val_data)
            loss = criterion(pred, val_label)
        loss_record.append(loss.item())
        # accuracy
        _, index = pred.data.cpu().topk(1)
        index_label = val_label.data.cpu()
        accuracy_batch = np.sum((index.squeeze(dim=1) == index_label).numpy())
        accuracy_batch = accuracy_batch / len(val_label)
        accuracy_record.append(accuracy_batch)
    val_loss = sum(loss_record) / len(feature_test_dataloader)
    val_accuracy = sum(accuracy_record) / len(accuracy_record)

    model_new_noretrain_accuracy, model_new_noretrain_loss = val_accuracy, val_loss
    print(
        f'compressed model(without retrain): Valid loss: {model_new_noretrain_loss:.4f}, Valid accuracy: {model_new_noretrain_accuracy:.4f}'
    )

    # --------------------------------Preparing------------------------------------------
    net = model_new
    net = net.to(device)
    if device == 'cuda:1':
        cudnn.benchmark = True
    batch_size = 128
    lr = 0.01
    config = {"save_path": "./model_origin", "early_stop": 20, 'n_epochs': 500}
    early_stop_count = 0
    epochs, best_loss, step, early_stop_count = config[
        'n_epochs'], math.inf, 0, 0
    optimizer = torch.optim.SGD(net.parameters(),
                                lr=lr,
                                momentum=0.9,
                                weight_decay=5e-4)
    criterion = nn.CrossEntropyLoss()

    # ------------------------------Training and Validation-------------------------------
    for epoch in range(epochs):
        # Training
        net.train()
        loss_record = []
        accuracy_record = []
        for train_data, train_label in feature_train_dataloader:
            optimizer.zero_grad()
            train_data, train_label = train_data.to(device), train_label.to(
                device)
            pred = net(train_data)
            loss = criterion(pred, train_label)
            loss.backward()
            optimizer.step()
            loss_record.append(loss.item())
            # accuracy
            _, index = pred.data.cpu().topk(1, dim=1)
            index_label = train_label.data.cpu()
            accuracy_batch = np.sum(
                (index.squeeze(dim=1) == index_label).numpy())
            accuracy_batch = accuracy_batch / len(train_label)
            accuracy_record.append(accuracy_batch)
        train_loss = sum(loss_record) / len(loss_record)
        train_accuracy = sum(accuracy_record) / len(accuracy_record)
        # validation
        net.eval()
        loss_record = []
        accuracy_record = []
        for val_data, val_label in feature_test_dataloader:
            val_data, val_label = val_data.to(device), val_label.to(device)
            with torch.no_grad():
                pred = net(val_data)
                loss = criterion(pred, val_label)
            loss_record.append(loss.item())
            # accuracy
            _, index = pred.data.cpu().topk(1, dim=1)
            index_label = val_label.data.cpu()
            accuracy_batch = np.sum(
                (index.squeeze(dim=1) == index_label).numpy())
            accuracy_batch = accuracy_batch / len(val_label)
            accuracy_record.append(accuracy_batch)
        val_loss = sum(loss_record) / len(loss_record)
        val_accuracy = sum(accuracy_record) / len(accuracy_record)

        print(
            f'Epoch [{epoch+1}/{epochs}]: Train loss: {train_loss:.4f},Train accuracy: {train_accuracy:.4f}, Valid loss: {val_loss:.4f}, Valid accuracy: {val_accuracy:.4f}'
        )

        if val_loss < best_loss:
            best_loss = val_loss
            torch.save(net.state_dict(), "./model_new")  # Save your best model
            print('Saving model with loss {:.3f}...'.format(best_loss))
            early_stop_count = 0
        else:
            early_stop_count += 1

        if early_stop_count >= config['early_stop']:
            print('\nModel is not improving, so we halt the training session.')
            break

    # --------------------------------Calculate Memories---------------------------------------
    # calculate origin model's memory
    me_org = (input_num * weight_num_list[0] + weight_num_list[0] *
              weight_num_list[1] + weight_num_list[1] * weight_num_list[2] +
              2 * weight_num_list[2]) * 32 + (sum(weight_num_list)) * 32
    print('MEM_origin = ', me_org)

    # calculate new model's memory
    me_new = (input_num * weight_num_list[0] + weight_num_list[0] *
              weight_num_list[1] + weight_num_list[1] * weight_num_list[2] +
              2 * weight_num_list[2]) * (1 - kesi) + (sum(weight_num_list))
    print('MEM_new = ', me_new)

    print(str(weight_num_list))
    print(kesi)
    print(
        f'compressed model(without retrain): Valid loss: {model_new_noretrain_loss:.4f}, Valid accuracy: {model_new_noretrain_accuracy:.4f}'
    )
    print(
        f'compressed model(with retrain): Valid loss: {val_loss:.4f}, Valid accuracy: {val_accuracy:.4f}'
    )

    # try:
    #     # print(path)
    # except:
    #     pass
    # print(f'origin model: Valid loss: {model_origin_final_loss:.4f}, Valid accuracy: {model_origin_final_accuracy:.4f}')


from chalice.test import Client
from pytest import fixture
from app import app
import json

@fixture
def test_client():
    with Client(app) as client:
        yield client

def test_start_game(test_client):
    result = test_client.http.post(
        "/jogo/novo",
        headers={
            "Content-type": "application/json"
        },
        body=json.dumps({
            'nick_name': 'pepo'
        })
    )
    assert result.status_code == 201

def test_start_game_header_location(test_client):
    result = test_client.http.post(
        "/jogo/novo",
        headers={
            "Content-type": "application/json"
        },
        body=json.dumps({
            'nick_name': 'Alisson'
        })
    )
    headers = list(map(lambda x: x.lower(), result.headers))
    assert 'location' in headers

def test_start_game_get_game_id(test_client):
    result = test_client.http.post(
        "/jogo/novo",
        headers={
            "Content-type": "application/json"
        },
        body=json.dumps({
            'nick_name': 'Alisson'
        })
    )

    headers = {k.lower(): v for k, v in result.headers.items()}
    uriSplitted = headers['location'].split('/')

    assert len(uriSplitted) > 3


from .constant import COLORS, LightColors, DarkColors, FontSize
from omni import ui
import carb.settings

def get_ui_style():
    settings = carb.settings.get_settings()
    style = settings.get_as_string("/persistent/app/window/uiStyle")
    if not style:
        style = "NvidiaDark"
    return style

class DefaultWidgetStyle:
    LIGHT = {
        "Button": {
            "background_color": LightColors.Button,
            "border_radius": 2.0,
            "stack_direction": ui.Direction.LEFT_TO_RIGHT,
        },
        "Button.Label": {"color": LightColors.Background},
        "Button:hovered": {"background_color": LightColors.ButtonHovered},
        "Button:pressed": {"background_color": LightColors.ButtonPressed},
        "CollapsableFrame": {
            "color": COLORS.TRANSPARENT,
            "background_color": COLORS.TRANSPARENT,
            "secondary_color": COLORS.TRANSPARENT,
        },
        "CollapsableFrame:hovered": {"secondary_color": COLORS.TRANSPARENT},
        "CollapsableFrame:pressed": {"secondary_color": COLORS.TRANSPARENT},
        "ComboBox": {
            "color": LightColors.Text,
            "background_color": LightColors.Background,
            "selected_color": LightColors.BackgroundSelected,
            "border_radius": 1,
            "padding_width": 0,
            "padding_height": 4,
            "secondary_padding": 8,
        },
        "ComboBox:disabled": {"color": LightColors.TextDisabled},
        "Field": {"background_color": LightColors.Background, "color": LightColors.Text, "border_radius": 2},
        "Plot": {"background_color": LightColors.Background, "color": LightColors.TextSelected, "border_radius": 1},
        "Triangle": {"background_color": LightColors.Background},
    }

    DARK = {
        "Button": {
            "background_color": DarkColors.Button,
            "border_radius": 2.0,
            "stack_direction": ui.Direction.LEFT_TO_RIGHT,
        },
        "Button.Label": {"color": DarkColors.Text},
        "Button:hovered": {"background_color": DarkColors.ButtonHovered},
        "Button:pressed": {"background_color": DarkColors.ButtonPressed},
        "CollapsableFrame": {
            "color": COLORS.TRANSPARENT,
            "background_color": COLORS.TRANSPARENT,
            "secondary_color": COLORS.TRANSPARENT,
        },
        "CollapsableFrame:hovered": {"secondary_color": COLORS.TRANSPARENT},
        "CollapsableFrame:pressed": {"secondary_color": COLORS.TRANSPARENT},
        "ComboBox": {
            "color": DarkColors.Text,
            "background_color": DarkColors.Background,
            "selected_color": DarkColors.BackgroundSelected,
            "border_radius": 1,
        },
        "ComboBox:disabled": {"color": DarkColors.TextDisabled},
        "Field": {"background_color": DarkColors.Background, "color": DarkColors.Text, "border_radius": 2},
        "Plot": {"background_color": DarkColors.Background, "color": DarkColors.TextSelected, "border_radius": 1},
        "Triangle": {"background_color": DarkColors.Background},
    }

    @staticmethod
    def get_style(ui_style=None):
        if ui_style is None:
            ui_style = get_ui_style()

        if ui_style == "NvidiaDark":
            return DefaultWidgetStyle.DARK
        else:
            return DefaultWidgetStyle.LIGHT


import sys
import pygame
from bullet import Bullet
from alien import Alien
from time import sleep

def checkHighScore(stats, sb):
    if stats.score > stats.highScore:
        stats.highScore = stats.score
        sb.prepHighScore()

def shipHit(aiSettings, stats, screen, ship, aliens, bullets, sb):
    if stats.shipsLeft > 0:
        stats.shipsLeft -= 1
        sb.prepShips()
        aliens.empty()
        bullets.empty()
        createFleet(aiSettings, screen, aliens, ship)
        ship.centerShip()
        sleep(0.5)
    else:
        stats.gameActive = False
        pygame.mouse.set_visible(True)

def checkBulletAlienCollisions(aiSettings, screen, ship, aliens, bullets, stats, sb):
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
    if collisions:
        for aliens in collisions.values():
            stats.score += aiSettings.alienPoints * len(aliens)
            sb.prepScore()
        checkHighScore(stats, sb)
    if len(aliens) == 0:
        bullets.empty()
        aiSettings.increaseSpeed()
        stats.level += 1
        sb.prepLevel()
        createFleet(aiSettings, screen, aliens, ship)

def updateBullets(aiSettings, bullets, aliens, screen, ship, stats, sb):
    bullets.update()
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)
    checkBulletAlienCollisions(aiSettings, screen, ship, aliens, bullets, stats, sb)

def fireBullet(aiSettings, bullets, screen, ship):
    if len(bullets) < aiSettings.bulletsAllowed:
        newBullet = Bullet(aiSettings, screen, ship)
        bullets.add(newBullet)

def getNumRows(aiSettings, shipHeight, alienHeight):
    availableHeight = aiSettings.screenHeight - 3 * alienHeight - shipHeight
    return int(availableHeight / (2 * alienHeight))

def createAlien(aiSettings, screen, aliens, alienNum, rowNum):
    alien = Alien(aiSettings, screen)
    alienWidth = alien.rect.width
    alien.x = alienWidth + 2 * alienWidth * alienNum
    alien.rect.x = alien.x
    alien.rect.y = alien.rect.height + 2 * alien.rect.height * rowNum
    aliens.add(alien)

def getNumAliens(aiSettings, alienWidth):
    availableSpace = aiSettings.screenWidth - (2 * alienWidth)
    numAliens = int(availableSpace / (2 * alienWidth))
    return numAliens

def createFleet(aiSettings, screen, aliens, ship):
    alien = Alien(aiSettings, screen)
    numRows = getNumRows(aiSettings, ship.rect.height, alien.rect.height)
    numAliensPerRow = getNumAliens(aiSettings, alien.rect.width)
    for rowNum in range(numRows):
        for alienNum in range(numAliensPerRow):
            createAlien(aiSettings, screen, aliens, alienNum, rowNum)

def checkKeyDownEvents(event, aiSettings, screen, ship, bullets):
    """ Responds to key presses """
    if event.key == pygame.K_RIGHT:
        ship.movingRight = True
    elif event.key == pygame.K_LEFT:
        ship.movingLeft = True
    elif event.key == pygame.K_SPACE:
        fireBullet(aiSettings, bullets, screen, ship)
    elif event.key == pygame.K_q:
        sys.exit()

def checkKeyUpEvents(event, ship):
    """ Responds to key releases """
    if event.key == pygame.K_RIGHT:
        ship.movingRight = False
    elif event.key == pygame.K_LEFT:
        ship.movingLeft = False

def checkPlayButton(aiSettings, screen, ship, aliens, bullets, stats, playButton, mouseX, mouseY, sb):
    buttonClicked = playButton.rect.collidepoint(mouseX, mouseY)
    if buttonClicked and not stats.gameActive:
        aiSettings.initializeDynamicSettings()
        pygame.mouse.set_visible(False)
        stats.resetStats()
        stats.gameActive = True
        sb.prepScore()
        sb.prepHighScore()
        sb.prepLevel()
        sb.prepShips()
        aliens.empty()
        bullets.empty()
        createFleet(aiSettings, screen, aliens, ship)
        ship.centerShip()

def checkEvents(aiSettings, screen, ship, bullets, aliens, stats, playButton, sb):
    """ Respond to key presses and mouse events"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            checkKeyDownEvents(event, aiSettings, screen, ship, bullets)
        elif event.type == pygame.KEYUP:
            checkKeyUpEvents(event, ship)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouseX, mouseY = pygame.mouse.get_pos()
            checkPlayButton(aiSettings, screen, ship, aliens, bullets, stats, playButton, mouseX, mouseY, sb)

def updateScreen(aiSettings, screen, ship, bullets, aliens, stats, playButton, sb):
    """ Update images on the screen and flip to the new screen. """
    screen.fill(aiSettings.screenBgColor)
    for bullet in bullets.sprites():
        bullet.drawBullet()
    ship.blitme()
    aliens.draw(screen)
    sb.showScore()
    if not stats.gameActive:
        playButton.drawButton()
    pygame.display.flip()

def checkAliensBottom(aiSettings, stats, screen, ship, aliens, bullets, sb):
    screenRect = screen.get_rect()
    for alien in aliens.sprites():
        if alien.rect.bottom >= screenRect.bottom:
            shipHit(aiSettings, stats, screen, ship, aliens, bullets, sb)
            break

def updateAliens(aiSettings, stats, screen, aliens, bullets, ship, sb):
    checkFleetEdges(aiSettings, aliens)
    aliens.update()
    if pygame.sprite.spritecollideany(ship, aliens):
        shipHit(aiSettings, stats, screen, ship, aliens, bullets, sb)
    checkAliensBottom(aiSettings, stats, screen, ship, aliens, bullets, sb)

def changeFleetDirection(aiSettings, aliens):
    for alien in aliens.sprites():
        alien.rect.y += aiSettings.fleetDropSpeed
    aiSettings.fleetDirection *= -1

def checkFleetEdges(aiSettings, aliens):
    for alien in aliens.sprites():
        if alien.checkEdges():
            changeFleetDirection(aiSettings, aliens)
            break


#
# @lc app=leetcode.cn id=1744 lang=python3
#
# [1744] 你能在你最喜欢的那天吃到你最喜欢的糖果吗？
#
# https://leetcode-cn.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day/description/
#
# algorithms
# Medium (26.98%)
# Likes:    107
# Dislikes: 0
# Total Accepted:    23.3K
# Total Submissions: 64.6K
# Testcase Example:  '[7,4,5,3,8]\n[[0,2,2],[4,2,4],[2,13,1000000000]]'
#
# 给你一个下标从 0 开始的正整数数组 candiesCount ，其中 candiesCount[i] 表示你拥有的第 i
# 类糖果的数目。同时给你一个二维数组 queries ，其中 queries[i] = [favoriteTypei, favoriteDayi,
# dailyCapi] 。
#
# 你按照如下规则进行一场游戏：
#
#
# 你从第 0 天开始吃糖果。
# 你在吃完 所有 第 i - 1 类糖果之前，不能 吃任何一颗第 i 类糖果。
# 在吃完所有糖果之前，你必须每天 至少 吃 一颗 糖果。
#
#
# 请你构建一个布尔型数组 answer ，满足 answer.length == queries.length 。answer[i] 为 true
# 的条件是：在每天吃 不超过 dailyCapi 颗糖果的前提下，你可以在第 favoriteDayi 天吃到第 favoriteTypei 类糖果；否则
# answer[i] 为 false 。注意，只要满足上面 3 条规则中的第二条规则，你就可以在同一天吃不同类型的糖果。
#
# 请你返回得到的数组 answer 。
#
#
#
# 示例 1：
#
#
# 输入：candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]]
# 输出：[true,false,true]
# 提示：
# 1- 在第 0 天吃 2 颗糖果(类型 0），第 1 天吃 2 颗糖果（类型 0），第 2 天你可以吃到类型 0 的糖果。
# 2- 每天你最多吃 4 颗糖果。即使第 0 天吃 4 颗糖果（类型 0），第 1 天吃 4 颗糖果（类型 0 和类型 1），你也没办法在第 2 天吃到类型
# 4 的糖果。换言之，你没法在每天吃 4 颗糖果的限制下在第 2 天吃到第 4 类糖果。
# 3- 如果你每天吃 1 颗糖果，你可以在第 13 天吃到类型 2 的糖果。
#
#
# 示例 2：
#
#
# 输入：candiesCount = [5,2,6,4,1], queries =
# [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]]
# 输出：[false,true,true,false,false]
#
#
#
#
# 提示：
#
#
# 1
# 1
# 1
# queries[i].length == 3
# 0 i < candiesCount.length
# 0 i
# 1 i
#
#
#

# @lc code=start

# accumulate
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120

# 对于区间 [x_1, y_1][x 1  ,y 1  ] 以及 [x_2, y_2][x 2  ,y 2  ]
# 它们没有交集当且仅当 x_1 > y_2x 1  >y 2  或者 y_1 < x_2y 1  <x 2

# T:O(N+Q) S:O(N)
class Solution:
    def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:
        # 前缀和
        total = list(accumulate(candiesCount))

        ans = list()
        for favoriteType, favoriteDay, dailyCap in queries:
            x1 = favoriteDay + 1
            y1 = (favoriteDay + 1) * dailyCap
            x2 = 1 if favoriteType == 0 else total[favoriteType - 1] + 1
            y2 = total[favoriteType]

            ans.append(not(x1 > y2 or y1 < x2))

        return ans
# @lc code=end

PythonSolution/1744.你能在你最喜欢的那天吃到你最喜欢的糖果吗？.py

1744.你能在你最喜欢的那天吃到你最喜欢的糖果吗？.py


#Project 1!
from p0 import Molecule
import numpy as np
import math
import masses
np.set_printoptions(suppress=True)

with open("hessian.dat", "r") as f:
    hess = f.readlines()

with open("molecule.xyz", "r") as f:
    coordinates = [line.rstrip() for line in f]

#1 Reading in the hessian
H = []
for i in hess:
    H.append(list(map(float, i.split())))
H = np.matrix(H)

#2 Building my molecule with the previously-made Molecule class

mol = Molecule("molecule.xyz")

def freq(mol, H):

    #3 Mass-Weighted Hessian math (this was hard)
    mass_lst = mol.mass_list
    N = len(mass_lst)
    M = np.zeros( (3*N,3*N), dtype = float )
    mw = [ mass_lst[int(i)] for i in range(N) for j in range(3) ]
    for i in range(len(mw)):
        M[i,i] = mw[i] ** -0.5

    F = M * H * M

    #4 Eigenvector and Eigenvalue time. Thanks numpy.

    Val, Vec = np.linalg.eigh(F)

    #5 I do believe this will unmass the evecs!!
    UwH = np.dot(M, Vec)

    #6 Figure out how to multiply these equations

    #Let's make some easy unit conversion variables:

    HtJ = 4.3597482e-18
    AMUtkg = 1.6603145e-27
    c = 29979245800 #cm/s (cause we want frequency!)
    BRtm = 5.29177e-11

    #k time

    k_1 = np.sqrt((abs(Val)*HtJ)/((BRtm**2)*AMUtkg))/(2*math.pi)
    k_2 = k_1/c

    #Output!

    output = ""
    output_format = '{:2s}' + '{:  >15.10f}'*6 + '\n'
    for i in range(3*N):
        output +='{:d}\n{: >7.2f}  cm^-1\n'.format(N, np.absolute(k_2[i]))
        for j in range(N):
            atom = mol.atom_labels[j]
            x, y, z = mol.geom[j]
            x_1, y_1, z_1 = UwH[3*j:3*j+3, i]
            x_1, y_1, z_1 = float(x_1), float(y_1), float(z_1)
            output += '{:<2s}{:>20.12f}{:>20.12f}{:>20.12f}{:>20.12f}{:>20.12f}{:>20.12f}'.format(atom, x, y, z, x_1, y_1, z_1)
            output += "\n"
        output += "\n"

    filetime = open("FreqOutput.xyz", 'w')
    filetime.write(output)
    filetime.close

freq(mol, H)


import sys

N = int(sys.stdin.readline())

dp = [0]*(N+1)

# 피보나치 함수
def fibonacci(num):
    if (num==0):
        return 0
    elif (num==1):
        return 1
    elif (num==2):
        return 1
    else:
        return dp[num-1] + dp[num-2]

for i in range(N+1):
    dp[i] = fibonacci(i)

print(dp[N])


from enum import Enum, IntEnum

class Level(Enum):
    """
    Error levels.
    """

    ERROR = "E"
    WARNING = "W"
    INFO = "I"

    def __str__(self):
        return self.value

class PoolMaintenanceErrorCode(IntEnum):
    """
    Maintenance error codes for the pool.
    """

    NO_IPC_REQUESTS = 1
    NO_POOL_CHANGES = 2

    def __str__(self):
        return f"{Level.ERROR}M{str(self.value).zfill(3)}"

    @staticmethod
    def from_str(code_str):
        """
        Discover the code, if any, from the code string.

        :returns: the code if it finds a match, otherwise None
        :rtype: PoolMaintenanceErrorCode or NoneType
        """
        return next(
            (code for code in PoolMaintenanceErrorCode if code_str == str(code)), None
        )

    def explain(self):
        """
        Return an explanation of the error return code.
        """
        if self is PoolMaintenanceErrorCode.NO_IPC_REQUESTS:
            return (
                "The pool will return an error on any IPC request that could "
                "cause a change in the pool state, for example, a request to "
                "rename a filesystem. It will still be able to respond to "
                "purely informational requests."
            )

        if self is PoolMaintenanceErrorCode.NO_POOL_CHANGES:
            return (
                "The pool is unable to manage itself by reacting to events, "
                "such as devicemapper events, that might require it to take "
                "any maintenance operations."
            )

        assert False, "impossible error code reached"  # pragma: no cover

    def summarize(self):
        """
        Return a short summary of the return code.
        """
        if self is PoolMaintenanceErrorCode.NO_IPC_REQUESTS:
            return "Pool state changes not possible"

        if self is PoolMaintenanceErrorCode.NO_POOL_CHANGES:
            return "Pool maintenance operations not possible"

        assert False, "impossible error code reached"  # pragma: no cover

class PoolAllocSpaceErrorCode(IntEnum):
    """
    Code if the pool has run out of space to allocate.
    """

    NO_ALLOC_SPACE = 1

    def __str__(self):
        return f"{Level.WARNING}S{str(self.value).zfill(3)}"

    def explain(self):
        """
        Return an explanation of the return code.
        """
        if self is PoolAllocSpaceErrorCode.NO_ALLOC_SPACE:
            return (
                "Every device belonging to the pool has been fully allocated. "
                "To increase the allocable space, add additional data devices "
                "to the pool."
            )

        assert False, "impossible error code reached"  # pragma: no cover

    def summarize(self):
        """
        Return a short summary of the return code.
        """
        if self is PoolAllocSpaceErrorCode.NO_ALLOC_SPACE:
            return "All devices fully allocated"

        assert False, "impossible error code reached"  # pragma: no cover

    @staticmethod
    def from_str(code_str):
        """
        Discover the code, if any, from the code string.

        :returns: the code if it finds a match, otherwise None
        :rtype: PoolAllocSpaceErrorCode or NoneType
        """
        return next(
            (code for code in PoolAllocSpaceErrorCode if code_str == str(code)), None
        )

class PoolDeviceSizeChangeCode(IntEnum):
    """
    Codes for identifying for a pool if a device that belongs to the pool has
    been detected to have increased or reduced in size.
    """

    DEVICE_SIZE_INCREASED = 1
    DEVICE_SIZE_DECREASED = 2

    def __str__(self):
        if self is PoolDeviceSizeChangeCode.DEVICE_SIZE_INCREASED:
            return f"{Level.INFO}DS{str(self.value).zfill(3)}"

        if self is PoolDeviceSizeChangeCode.DEVICE_SIZE_DECREASED:
            return f"{Level.WARNING}DS{str(self.value).zfill(3)}"

        assert False, "impossible error code reached"  # pragma: no cover

    def explain(self):
        """
        Return an explanation of the return code.
        """
        if self is PoolDeviceSizeChangeCode.DEVICE_SIZE_INCREASED:
            return (
                "At least one device belonging to this pool appears to have "
                "increased in size."
            )

        if self is PoolDeviceSizeChangeCode.DEVICE_SIZE_DECREASED:
            return (
                "At least one device belonging to this pool appears to have "
                "decreased in size."
            )

        assert False, "impossible error code reached"  # pragma: no cover

    def summarize(self):
        """
        Return a short summary of the return code.
        """
        if self is PoolDeviceSizeChangeCode.DEVICE_SIZE_INCREASED:
            return "A device in this pool has increased in size."

        if self is PoolDeviceSizeChangeCode.DEVICE_SIZE_DECREASED:
            return "A device in this pool has decreased in size."

        assert False, "impossible error code reached"  # pragma: no cover

    @staticmethod
    def from_str(code_str):
        """
        Discover the code, if any, from the code string.

        :returns: the code if it finds a match, otherwise None
        :rtype: PoolAllocSpaceErrorCode or NoneType
        """
        return next(
            (code for code in PoolDeviceSizeChangeCode if code_str == str(code)), None
        )

class PoolErrorCode:
    """
    Summary class for all pool error codes.
    """

    CLASSES = [
        PoolMaintenanceErrorCode,
        PoolAllocSpaceErrorCode,
        PoolDeviceSizeChangeCode,
    ]

    @staticmethod
    def codes():
        """
        Return all pool error codes.
        """
        return [code for c in PoolErrorCode.CLASSES for code in list(c)]

    @staticmethod
    def error_from_str(error_code):
        """
        Obtain an error object from a distinguishing error string.

        :param str error_code:
        :returns: error object
        :raises: StopIteration if no match found
        """
        return next(
            (
                code
                for code in (c.from_str(error_code) for c in PoolErrorCode.CLASSES)
                if code is not None
            )
        )

    @staticmethod
    def explain(error_code):
        """
        Return explanation for error code, else None.

        :param str error_code:
        """
        return PoolErrorCode.error_from_str(error_code).explain()


from __future__ import absolute_import, division, print_function
from iotbx.regression.ncs.tst_mtrix_biomt_cmdl import pdb_str_0
import mmtbx.model
import iotbx.pdb

def test_1():
  """
  Chains A,B,C are present in the model. The rest of them are being generated
  by expansion. The problem is that iotbx/pdb/utils.py:all_chain_ids()
  generate chain ids with leading white space for single character ids.
  This results in inconsistent selection behavior demonstrated in this test.

  Many instruments quote chain ID when generate selection strings such as:
  iotbx/pdb/secondary_structure.py
  nqh_flip in mmtbx/validation/clashscore.py

  maybe others

  Therefore they don't work properly when the model is expanded using MTRIX
  and/or BIOMT matrices internally.

  To reproduce nqh_flip problem:
  phenix.fetch_pdb 1qgt
  phenix.molprobity 1qgt.pdb
  """
  # Loading and expanding the model
  inp = iotbx.pdb.input(lines=pdb_str_0, source_info=None)
  model = mmtbx.model.manager(model_input=inp)
  model.expand_with_BIOMT_records()
  h = model.get_hierarchy()
  asc = model.get_atom_selection_cache()
  chain_ids = [chain.id for chain in h.only_model().chains()]
  print (chain_ids)
  # Note leading whitespaces starting with chain D:
  # assert chain_ids == ['A', 'B', 'C', ' D', ' E', ' F', ' G', ' H', ' I', ' J', ' K', ' L', ' M', ' N', ' O', ' P', ' Q', ' R', ' S', ' T', ' U', ' V', ' W', ' X', ' Y', ' Z', ' 0']
  assert chain_ids == ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0']

  # Set of test cases
  A_selections = ["chain A", "chain 'A'", "chain ' A'"]
  D_selections = ["chain D", "chain 'D'", "chain ' D'"]

  n_atoms_A = []
  for a_sel in A_selections:
    chA = asc.selection(a_sel)
    n_atoms = h.select(chA).atoms_size()
    print("chA:", n_atoms)
    n_atoms_A.append(n_atoms)
  assert n_atoms_A == [44, 44, 0]

  n_atoms_D = []
  for d_sel in D_selections:
    chD = asc.selection(d_sel)
    n_atoms = h.select(chD).atoms_size()
    print("chD:", n_atoms)
    n_atoms_D.append(n_atoms)
  assert n_atoms_D == [44, 44, 0]
  print ("Is intenal expansion consistent?", n_atoms_A == n_atoms_D)
  assert n_atoms_A == n_atoms_D

  # BUT!!!! if we dump the expanded model and re-load it, everyting is consistent.
  expanded_lines = model.model_as_pdb()
  exp_h = iotbx.pdb.input(lines=expanded_lines, source_info=None).construct_hierarchy()

  exp_asc = exp_h.atom_selection_cache()
  # literally copy-paste from above
  n_atoms_A = []
  for a_sel in A_selections:
    chA = exp_asc.selection(a_sel)
    n_atoms = exp_h.select(chA).atoms_size()
    print("exp chA:", n_atoms)
    n_atoms_A.append(n_atoms)
  assert n_atoms_A == [44, 44, 0]

  n_atoms_D = []
  for d_sel in D_selections:
    chD = exp_asc.selection(d_sel)
    n_atoms = exp_h.select(chD).atoms_size()
    print("exp chD:", n_atoms)
    n_atoms_D.append(n_atoms)
  assert n_atoms_D == [44, 44, 0]
  print ("Is reading from pdb consistent?", n_atoms_A == n_atoms_D)
  assert n_atoms_A == n_atoms_D

if (__name__ == "__main__"):
  test_1()


from tkinter import *
import tkinter

from tkinter import messagebox

root = Tk()

# def to_display():
#     global entry
#     string = entry.get()
#     # label.configure(text= string)
#     filename = 'names.txt'
#     f = open(filename,'a')
#     f.write(string)
#     f.close()

# entry = Entry(root)
# entry.focus_set()
# entry.grid()

# # label = tkinter.Label(root,text='name')
# # label.grid()

# btn = tkinter.Button(root,text='OK',command=to_display)
# btn.grid()

def add():
    global entry
    string = entry.get()
    lstbox.insert(END,string)
    entry.delete(0,'end')

def dele():
    lstbox.delete(ANCHOR) # lstboard has a inbuilt 'ANCHOR' which selects when hover on an item in listbox.

root.geometry()
root.config(background='black',border='10')
root.title('to_do_list')
root.resizable(width=False,height=False)

frame = Frame(root)
frame.pack(pady=10)

lstbox = Listbox(frame,width=25,height=8,font=('Times New Roman',14),bd= 0,fg='black')
lstbox.pack(side = LEFT,fill=BOTH)

list_items = []

for item in list_items:
    lstbox.insert(END,item)

scrol = Scrollbar(frame)
scrol.pack(padx=10,side=RIGHT,fill=BOTH)
lstbox.config(yscrollcommand=scrol.set)  # to configuer the scroll bar , used y scrolle command to move up and down , else x scroll command left /right
scrol.config(command=lstbox.yview) # this command sets to help movment of lstbox when ever the scroller os scrolled.

entry = Entry(frame,font=('Times New Roman',14))
entry.pack(pady=20,padx=20)  # any number

btn = Button(frame,text='ADD TEXT',font='times',command=add)
btn.pack(pady=20)

btn1 = Button(frame,text='DEL TEXT',font='times',command=dele)
btn1.pack(pady=20)

root.mainloop()


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

from keras.models import *
from keras.layers import *
from keras.optimizers import *
from keras.callbacks import ModelCheckpoint
import keras.backend as K
import cv2
from data_camvid import *
from myData import *

def iou(y_true, y_pred, label: int):
    """
    Return the Intersection over Union (IoU) for a given label.
    Args:
        y_true: the expected y values as a one-hot
        y_pred: the predicted y values as a one-hot or softmax output
        label: the label to return the IoU for
    Returns:
        the IoU for the given label
    """
    # extract the label values using the argmax operator then
    # calculate equality of the predictions and truths to the label
    y_true = K.cast(K.equal(K.argmax(y_true), label), K.floatx())
    y_pred = K.cast(K.equal(K.argmax(y_pred), label), K.floatx())
    # calculate the |intersection| (AND) of the labels
    intersection = K.sum(y_true * y_pred)
    # calculate the |union| (OR) of the labels
    union = K.sum(y_true) + K.sum(y_pred) - intersection
    # avoid divide by zero - if the union is zero, return 1
    # otherwise, return the intersection over union
    return K.switch(K.equal(union, 0), 1.0, intersection / union)

def mean_iou(y_true, y_pred):
    """
    Return the Intersection over Union (IoU) score.
    Args:
        y_true: the expected y values as a one-hot
        y_pred: the predicted y values as a one-hot or softmax output
    Returns:
        the scalar IoU value (mean over all labels)
    """
    # get number of labels to calculate IoU for
    num_labels = K.int_shape(y_pred)[-1] - 1
    # initialize a variable to store total IoU in
    mean_iou = K.variable(0)

    # iterate over labels to calculate IoU for
    for label in range(num_labels):
        mean_iou = mean_iou + iou(y_true, y_pred, label)

    # divide total IoU by number of labels to get mean IoU
    return mean_iou / num_labels

class myUnet(object):
    def __init__(self, img_rows=512, img_cols=512):
        self.img_rows = img_rows
        self.img_cols = img_cols

    '''
    def load_data(self):
        mydata = dataProcess(self.img_rows, self.img_cols)
        imgs_train, imgs_mask_train = mydata.load_train_data()
        imgs_test = mydata.load_test_data()
        return imgs_train, imgs_mask_train, imgs_test

    '''
    def load_data(self):
        mydata = dataProcess(self.img_rows, self.img_cols)

        #train
        gene = mydata.trainGen()
        return gene

        '''
        #test
        valGen = mydata.valGen()
        return valGen
        '''

        '''
        imgs_train, imgs_mask_train = mydata.trainGen()
        imgs_test = mydata.valGen()
        return imgs_train,imgs_mask_train,imgs_test
        '''

    def get_unet(self):
        inputs = Input((self.img_rows, self.img_cols, 3))

        conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(inputs)
        # print(conv1)
        #print "conv1 shape:", conv1.shape
        conv1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv1)
        #print "conv1 shape:", conv1.shape
        pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
        #print "pool1 shape:", pool1.shape

        conv2 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool1)
        #print "conv2 shape:", conv2.shape
        conv2 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv2)
        #print "conv2 shape:", conv2.shape
        pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
        #print "pool2 shape:", pool2.shape

        conv3 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool2)
        #print "conv3 shape:", conv3.shape
        conv3 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv3)
        #print "conv3 shape:", conv3.shape
        pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
        #print "pool3 shape:", pool3.shape

        conv4 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool3)
        conv4 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv4)
        drop4 = Dropout(0.5)(conv4)
        pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)

        conv5 = Conv2D(1024, 3, activation='relu', padding='same', kernel_initializer='he_normal')(pool4)
        conv5 = Conv2D(1024, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv5)
        drop5 = Dropout(0.5)(conv5)

        up6 = Conv2D(512, 2, activation='relu', padding='same', kernel_initializer='he_normal')(
            UpSampling2D(size=(2, 2))(drop5))
        merge6 = concatenate([drop4,up6], axis = 3)
        print(up6)
        print(merge6)
        conv6 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge6)
        print(conv6)
        conv6 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv6)
        print(conv6)
        up7 = Conv2D(256, 2, activation='relu', padding='same', kernel_initializer='he_normal')(
            UpSampling2D(size=(2, 2))(conv6))
        merge7 = concatenate([conv3,up7], axis = 3)
        print(up7)
        print(merge7)
        conv7 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge7)
        print(conv7)
        conv7 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv7)
        print(conv7)
        up8 = Conv2D(128, 2, activation='relu', padding='same', kernel_initializer='he_normal')(
            UpSampling2D(size=(2, 2))(conv7))
        merge8 = concatenate([conv2,up8], axis = 3)
        conv8 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge8)
        conv8 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv8)

        up9 = Conv2D(64, 2, activation='relu', padding='same', kernel_initializer='he_normal')(
            UpSampling2D(size=(2, 2))(conv8))
        merge9 = concatenate([conv1,up9], axis = 3)
        print(up9)
        print(merge9)
        conv9 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(merge9)
        print(conv9)
        conv9 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv9)
        print(conv9)
        conv9 = Conv2D(3, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv9)
        #print "conv9 shape:", conv9.shape

        conv10 = Conv2D(3, 1, activation='softmax')(conv9)
        print(conv10)
        model = Model(input=inputs, output=conv10)

        model.compile(optimizer=Adam(lr=2e-5), loss='categorical_crossentropy', metrics=['accuracy',mean_iou])

        return model

    def train(self):
        print("loading data")
        #imgs_train, imgs_mask_train, imgs_test = self.load_data()
        myGene = self.load_data()
        print("loading data done")
        model = self.get_unet()
        print("got unet")
        model_checkpoint = ModelCheckpoint('bbbSeg.hdf5', monitor='loss', verbose=1, save_best_only=True)
        print('Fitting model...')
        model.fit_generator(myGene, steps_per_epoch=3947,epochs=1,verbose = 1,shuffle= True,callbacks=[model_checkpoint],)
        '''
        model.fit(imgs_train, imgs_mask_train, batch_size=1, epochs=50, verbose=1,
                  validation_split=0.1, shuffle=True, callbacks=[model_checkpoint])
        '''
        print('predict test data')
        '''
        imgs_mask_test = model.predict(imgs_test, batch_size=1, verbose=1)
        np.save('./results/camvid_mask_test.npy', imgs_mask_test)
        '''

    def predictImg(self):
        valimg = self.load_data()
        print("loading the model")
        model = load_model("E:/WYQ/unet-rgb-master/bbbSeg.hdf5")
        print("loading model done")
        results = model.predict(valimg,batch_size = 2, verbose = 1)
        piclist = []
        for line in open("./te.txt"):
            line = line.strip()
            picname = line.split("\\")[-1]
            piclist.append(picname)
        for i in range(results.shape[0]):
            path = "./results/" + piclist[i]
            img = np.zeros((results.shape[1],results.shape[2],3),dtype=np.uint8)
            for k in range(len(img)):
                for j in range(len(img[k])):
                    num = np.argmax(results[i][k][j])
                    if num == 0:
                        img[k][j] = [128, 128, 128]
                    elif num == 1:
                        img[k][j] = [128, 0, 0]
                    elif num == 2:
                        img[k][j] = [192, 192, 128]
            img = cv2.resize(img, (480, 360), interpolation=cv2.INTER_CUBIC)
            cv2.imwrite(path, img)
        print("the predicted img have saved")

    def save_img(self):
        print("array to image")
        imgs = np.load('./results/camvid_mask_test.npy')
        piclist = []
        for line in open("./results/camvid.txt"):
            line = line.strip()
            picname = line.split('/')[-1]
            piclist.append(picname)
        for i in range(imgs.shape[0]):
            path = "./results/" + piclist[i]
            img = np.zeros((imgs.shape[1], imgs.shape[2], 3), dtype=np.uint8)
            for k in range(len(img)):
                for j in range(len(img[k])):  # cv2.imwrite也是BGR顺序
                    num = np.argmax(imgs[i][k][j])
                    if num == 0:
                        img[k][j] = [128, 128, 128]
                    elif num == 1:
                        img[k][j] = [128, 0, 0]
                    elif num == 2:
                        img[k][j] = [192, 192, 128]
                        '''
                    elif num == 3:
                        img[k][j] = [255, 69, 0]
                    elif num == 4:
                        img[k][j] = [128, 64, 128]
                    elif num == 5:
                        img[k][j] = [60, 40, 222]
                    elif num == 6:
                        img[k][j] = [128, 128, 0]
                    elif num == 7:
                        img[k][j] = [192, 128, 128]
                    elif num == 8:
                        img[k][j] = [64, 64, 128]
                    elif num == 9:
                        img[k][j] = [64, 0, 128]
                    elif num == 10:
                        img[k][j] = [64, 64, 0]
                    elif num == 11:
                        img[k][j] = [0, 128, 192]
                        '''
            img = cv2.resize(img, (480, 360), interpolation=cv2.INTER_CUBIC)
            cv2.imwrite(path, img)

if __name__ == '__main__':

    myunet = myUnet()
    model = myunet.get_unet()
    # model.summary()
    # plot_model(model, to_file='model.png')
    myunet.train()

    '''
    #predict
    myunet = myUnet()
    myunet.predictImg()
    '''


import os
from flask import Blueprint, make_response, request, g
from flask.wrappers import Response
import pyproj
from ..context import get_session
from geometry_service.database.postgis import Postgis
from geometry_service.database.actions import db_add_dataset, db_log_action
from geometry_service.database.model import Datasets
from geometry_service.loggers import logger
from ..forms.filter import FilterFileForm, FilterStringForm, FilterBufferForm

def _before_requests():
    """Executed before each request for this blueprint.

    Get the session details of the corresponding token, validates the form, and retrieves the dataset from database. The dataset and the form are stored as global flask objects, to be accessible from the requests.

    Returns:
        (None|Response): In case of validation error, returns a Flask response, None otherwise.
    """
    response = get_session()
    logger.info('API request [endpoint: "%s", token: "%s"]', request.endpoint, g.session['token'])
    if isinstance(response, Response):
        return response
    if request.endpoint == 'filter.within_buffer':
        form = FilterBufferForm()
    else:
        form = FilterFileForm() if 'wkt' in request.files.keys() else FilterStringForm()
    if not form.validate_on_submit():
        return make_response(form.errors, 400)
    if form.src.data == '':
        dataset = Datasets().get(uuid=g.session['active_instance'])
        if dataset is None:
            return make_response({"status": "No active dataset found."}, 404)
    else:
        dataset = Datasets().get(session=session['uuid'], label=form.src.data, deleted=False)
    g.dataset = dataset
    g.form = form

def _filter(action, label, dataset, wkt=None, arg=None, crs=None):
    """Creates a new dataset with filtered records.

    Creates a new DB View with the new dataset, and logs the action to the DB. All the records of the dataset that fulfil the condition of the PostGIS function (action) will be included in the view. The argument of the function is either supplied directly with the arg parameter either constructed from the geometry of the wkt parameter.

    Arguments:
        action (str): The PostGIS function that will be used to filter the table.
        label (str): The label given to the new dataset.
        dataset (dict): The dataset DB record.

    Keyword Arguments:
        wkt (str): The WKT to supply to the filter function (required if arg is None; default: {None})
        arg (str): The explicit argument of the filter function (required if wkt is None; default: {None})
        crs (str): The CRS of the WKT; if None the dataset CRS will be assumed (default: {None})

    Returns:
        (dict): Metadata for the new view dataset.

    Raises:
        TypeError: When none of wkt, arg is given.
    """
    meta = dataset['meta']
    if wkt is not None:
        srid = pyproj.crs.CRS.from_user_input(crs).to_epsg() if crs is not None and crs != '' else meta['epsg']
        arg = "ST_GeomFromText('{wkt}', {srid})".format(wkt=wkt, srid=srid)
    if arg is None:
        raise TypeError("_filter() missing one of arguments 'wkt', 'arg'")
    postgis = Postgis(g.session['db_schema'])
    view = postgis.create_view_filter(label, dataset['table'], action, arg, column='geom')
    tgt = db_add_dataset(session=g.session['uuid'], label=label, table=view, meta=meta)
    db_log_action(session=g.session['uuid'], action=request.endpoint, src_ds=dataset['uuid'], result_ds=tgt['uuid'])
    return meta

# FLASK ROUTES

bp = Blueprint('filter', __name__, url_prefix='/filter')
bp.before_request(_before_requests)

@bp.route('/contains', methods=['POST'])
def contains():
    """**Flask POST rule**.

    Apply contains filter on the dataset with a given geometry.
    ---
    post:
        summary: Apply contains filter on the dataset with a given geometry.
        description: Creates a new dataset, subset of the source, with the condition that the given geometry is completely inside the geometry of every feature in this dataset. The geometry is provided either as a WKT string either as a text file containing the WKT.
        tags:
            - Filter
        parameters:
            - sessionToken
        requestBody:
            required: true
            content:
                application/x-www-form-urlencoded:
                    schema: filterForm
                multipart/form-data:
                    schema: filterFormMultipart
        responses:
            200: newDatasetResponse
            400: validationErrorResponse
            401: noSessionResponse
            404: datasetNotFoundResponse
    """
    meta = _filter('ST_Contains', g.form.label.data, g.dataset, wkt=g.form.wkt.data, crs=g.form.crs.data)
    return make_response(meta, 200)

@bp.route('/contains_properly', methods=['POST'])
def contains_properly():
    """**Flask POST rule**.

    Apply contains_properly filter on the dataset with a given geometry.
    ---
    post:
        summary: Apply contains_properly filter on the dataset with a given geometry.
        description: Creates a new dataset, subset of the source, with the condition that the given geometry intersect the geometry of every feature in this dataset, **but** not its boundary (or exterior). The geometry is provided either as a WKT string either as a text file containing the WKT.
        tags:
            - Filter
        parameters:
            - sessionToken
        requestBody:
            required: true
            content:
                application/x-www-form-urlencoded:
                    schema: filterForm
                multipart/form-data:
                    schema: filterFormMultipart
        responses:
            200: newDatasetResponse
            400: validationErrorResponse
            401: noSessionResponse
            404: datasetNotFoundResponse
    """
    meta = _filter('ST_ContainsProperly', g.form.label.data, g.dataset, wkt=g.form.wkt.data, crs=g.form.crs.data)
    return make_response(meta, 200)

@bp.route('/covers', methods=['POST'])
def covers():
    """**Flask POST rule**.

    Apply covers filter on the dataset with a given geometry.
    ---
    post:
        summary: Apply covers filter on the dataset with a given geometry.
        description: Creates a new dataset, subset of the source, with the condition that no point in the given geometry is outside the geometry of every feature in this dataset. The geometry is provided either as a WKT string either as a text file containing the WKT.
        tags:
            - Filter
        parameters:
            - sessionToken
        requestBody:
            required: true
            content:
                application/x-www-form-urlencoded:
                    schema: filterForm
                multipart/form-data:
                    schema: filterFormMultipart
        responses:
            200: newDatasetResponse
            400: validationErrorResponse
            401: noSessionResponse
            404: datasetNotFoundResponse
    """
    meta = _filter('ST_Covers', g.form.label.data, g.dataset, wkt=g.form.wkt.data, crs=g.form.crs.data)
    return make_response(meta, 200)

@bp.route('/covered_by', methods=['POST'])
def covered_by():
    """**Flask POST rule**.

    Apply covered_by filter on the dataset with a given geometry.
    ---
    post:
        summary: Apply covered_by filter on the dataset with a given geometry.
        description: Creates a new dataset, subset of the source, with the condition that no point in the geometry of every feature in this dataset is outside the given geometry. The geometry is provided either as a WKT string either as a text file containing the WKT.
        tags:
            - Filter
        parameters:
            - sessionToken
        requestBody:
            required: true
            content:
                application/x-www-form-urlencoded:
                    schema: filterForm
                multipart/form-data:
                    schema: filterFormMultipart
        responses:
            200: newDatasetResponse
            400: validationErrorResponse
            401: noSessionResponse
            404: datasetNotFoundResponse
    """
    meta = _filter('ST_CoveredBy', g.form.label.data, g.dataset, wkt=g.form.wkt.data, crs=g.form.crs.data)
    return make_response(meta, 200)

@bp.route('/crosses', methods=['POST'])
def crosses():
    """**Flask POST rule**.

    Apply crosses filter on the dataset with a given geometry.
    ---
    post:
        summary: Apply crosses filter on the dataset with a given geometry.
        description: Creates a new dataset, subset of the source, with the condition that the intersection of the given geometry and the geometry of each feature in this dataset *spatially crosses*, that is, the geometries have some, but not all interior points in common. The geometry is provided either as a WKT string either as a text file containing the WKT.
        tags:
            - Filter
        parameters:
            - sessionToken
        requestBody:
            required: true
            content:
                application/x-www-form-urlencoded:
                    schema: filterForm
                multipart/form-data:
                    schema: filterFormMultipart
        responses:
            200: newDatasetResponse
            400: validationErrorResponse
            401: noSessionResponse
            404: datasetNotFoundResponse
    """
    meta = _filter('ST_Crosses', g.form.label.data, g.dataset, wkt=g.form.wkt.data, crs=g.form.crs.data)
    return make_response(meta, 200)

@bp.route('/disjoint', methods=['POST'])
def disjoint():
    """**Flask POST rule**.

    Apply disjoint filter on the dataset with a given geometry.
    ---
    post:
        summary: Apply disjoint filter on the dataset with a given geometry.
        description: >-
            Creates a new dataset, subset of the source, with only those features that their geometry respects all of the following conditions:

            * **Do not spatially overlap** with the given geometry. Two geometries spatially overlap when they intersect, but one does not completely contain the other.

            * **Do not touch** the given geometry, i.e. if the two geometries have common points, these are not belong only on their exteriors (boundaries).

            * **Do not contain** the given geometry, i.e. there is at least one point of the given geometry outside the feature's geometry.

            > The geometry is provided either as a WKT string either as a text file containing the WKT.
        tags:
            - Filter
        parameters:
            - sessionToken
        requestBody:
            required: true
            content:
                application/x-www-form-urlencoded:
                    schema: filterForm
                multipart/form-data:
                    schema: filterFormMultipart
        responses:
            200: newDatasetResponse
            400: validationErrorResponse
            401: noSessionResponse
            404: datasetNotFoundResponse
    """
    meta = _filter('ST_Disjoint', g.form.label.data, g.dataset, wkt=g.form.wkt.data, crs=g.form.crs.data)
    return make_response(meta, 200)

@bp.route('/intersects', methods=['POST'])
def intersects():
    """**Flask POST rule**.

    Apply intersects filter on the dataset with a given geometry.
    ---
    post:
        summary: Apply intersects filter on the dataset with a given geometry.
        description: Creates a new dataset, subset of the source, with the condition that the given geometry and the geometry of each feature in this dataset share any portion of space. The geometry is provided either as a WKT string either as a text file containing the WKT.
        tags:
            - Filter
        parameters:
            - sessionToken
        requestBody:
            required: true
            content:
                application/x-www-form-urlencoded:
                    schema: filterForm
                multipart/form-data:
                    schema: filterFormMultipart
        responses:
            200: newDatasetResponse
            400: validationErrorResponse
            401: noSessionResponse
            404: datasetNotFoundResponse
    """
    meta = _filter('ST_Intersects', g.form.label.data, g.dataset, wkt=g.form.wkt.data, crs=g.form.crs.data)
    return make_response(meta, 200)

@bp.route('/within', methods=['POST'])
def within():
    """**Flask POST rule**.

    Apply within filter on the dataset with a given geometry.
    ---
    post:
        summary: Apply within filter on the dataset with a given geometry.
        description: Creates a new dataset, subset of the source, with the condition that each feature in this dataset is completely inside the given geometry. The geometry is provided either as a WKT string either as a text file containing the WKT.
        tags:
            - Filter
        parameters:
            - sessionToken
        requestBody:
            required: true
            content:
                application/x-www-form-urlencoded:
                    schema: filterForm
                multipart/form-data:
                    schema: filterFormMultipart
        responses:
            200: newDatasetResponse
            400: validationErrorResponse
            401: noSessionResponse
            404: datasetNotFoundResponse
    """
    meta = _filter('ST_Within', g.form.label.data, g.dataset, wkt=g.form.wkt.data, crs=g.form.crs.data)
    return make_response(meta, 200)

@bp.route('/within_buffer', methods=['POST'])
def within_buffer():
    """**Flask POST rule**.

    Apply within_buffer filter on the dataset with a given buffer.
    ---
    post:
        summary: Apply within_buffer filter on the dataset with a given buffer.
        description: Creates a new dataset, subset of the source, with the condition that each feature in this dataset is within a given *radius* from a given point defined by *center_x*, *center_y*.
        tags:
            - Filter
        parameters:
            - sessionToken
        requestBody:
            required: true
            content:
                application/x-www-form-urlencoded:
                    schema: filterBufferForm
        responses:
            200: newDatasetResponse
            400: validationErrorResponse
            401: noSessionResponse
            404: datasetNotFoundResponse
    """
    crs = g.form.crs.data
    srid = pyproj.crs.CRS.from_user_input(crs).to_epsg() if crs is not None and crs != '' else g.dataset['meta']['epsg']
    point = "ST_SetSRID( ST_Point( {center_x}, {center_y}), {srid})".format(center_x=g.form.center_x.data, center_y=g.form.center_y.data, srid=srid)
    if srid != g.dataset['meta']['epsg']:
        point = "ST_Transform({point}, {srid})".format(point=point, srid=g.dataset['meta']['epsg'])
    arg = "{point}, {radius}".format(point=point, radius=g.form.radius.data)
    meta = _filter('ST_DWithin', g.form.label.data, g.dataset, arg=arg)
    return make_response(meta, 200)


str_length = input("Please ENTER THE Length : \n")
str_Width = input("Please EMTER THE Width : \n")
# لازم أحول دلوقتي علشان استحالة تكون أرقام الطول و العرض بالضبط #
Length = float(str_length)
Width = float(str_Width)
str_Total_Cost = input(" HOW MUCH IT COST FOR 1 METER ? : \n ")
NEW_Total_Cost = float(str_Total_Cost)
AREA = Length * Width
STR_AREA = str(AREA)
Float_Total_Cost = NEW_Total_Cost * AREA
str_float_total_cost = str(Float_Total_Cost)
print(" THE TOTAL AREA IS " + STR_AREA)
print(" GIVE THE GUY THE COST FOR HIS WORK  :  $" + (str_float_total_cost))


import json
import structlog
import pika
import config
from multiprocessing import Process
from ServiceManager import ServiceInfo, cleanupService

logger = structlog.get_logger()

def cleanupCallback(ch, method, properties, body):
    """Take service off of queue and delete its corresponding container"""

    logger.info("cleanupCallback", msg="Recieved Message", body=body)
    body = json.loads(body)
    service = ServiceInfo(body)
    log = logger.bind(service=service.__dict__)
    log.info("cleanupCallback", msg="Cleaning Up Service")
    cleanupService(service)
    ch.basic_ack(delivery_tag=method.delivery_tag)
    log.info("cleanupCallback", msg="Service Cleanup Done")

def cleanupWorker():
    """Declare cleanup queue and callback"""

    connection = pika.BlockingConnection(pika.ConnectionParameters(config.RABBITMQ_SERVER))
    channel = connection.channel()
    channel.queue_declare(queue='cleanupQueue', durable=True)
    logger.info("cleanupWorker", msg="Starting Cleanup Worker", queue="cleanupQueue")
    channel.basic_consume(cleanupCallback, queue='cleanupQueue')
    channel.start_consuming()

def startCleanupWorkers(numThreads):
    """Start numThreads cleanup workers"""
    for i in range(numThreads):
        t = Process(target=cleanupWorker)
        t.daemon = True
        t.start()


from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from utils import authenticate
import pandas as pd

class BaseVision:
    def __init__(
        self, service_endpoint: str, service_key: str = None, cognitive_key: str = None
    ) -> None:

        self.vision_key = service_key
        self.url = service_endpoint
        credentials = authenticate(service_key, cognitive_key)
        self.service_client = ComputerVisionClient(self.url, credentials)

    def get_metadata(self, response):
        """
        Collects metadata for each image
        in the response object to pandas.data.frame
        """

        tmp = {k: pd.DataFrame(v["metadata"], index=[0]) for k, v in response.items()}
        for k, v in tmp.items():
            tmp[k]["image"] = k
            tmp[k]["request_id"] = v["request_id"]

        metadata = pd.concat(tmp.values(), ignore_index=True, sort=False)

        return metadata


import sys
import os
from os.path import join
from ngspipedbcli.common import *

def gui_main(args):
    #step1 = 'export FLASK_ENV=development'
    #step2 = 'export FLASK_APP={}'.format(join(guiwebapp_dir, 'runpipeapp.py'))
    #step2 = 'export FLASK_APP=ngspipedb:guiwebapp:runpipeapp'
    env_dict = {
        'FLASK_ENV': 'development',
        'FLASK_APP': join(guiwebapp_dir, 'runpipeapp.py')
    }
    step3 = 'flask run -h {} -p {}'.format(args['ip'], args['port'])
    if args['printshell']:
        #ngspipedb_print_command('flask env', step1)
        #ngspipedb_print_command('flask env', step2)
        ngspipedb_print_command('flask run', step3)
    else:
        print('start flask server')
        #call_step1 = subprocess.call(step1, shell=True, encoding='utf-8')
        #call_step2 = subprocess.call(step2, shell=True, encoding='utf-8')
        os.putenv('FLASK_ENV', 'development')
        os.putenv('FLASK_APP', join(guiwebapp_dir, 'runpipeapp.py'))
        call_step3 = subprocess.call(step3, shell=True, encoding='utf-8')


def __appendActivities(self, periodicActivities):
    """
    periodicActivities: A sequence of PeriodicActivityRequest elements
    """

    for req in periodicActivities:
      act =   self.Activity(repeating=req.repeating,
                            period=req.period,
                            cb=req.cb,
                            iteratorHolder=[iter(xrange(req.period-1))])
      self.__activities.append(act)

    return


# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 22:19:55 2018

@author: Suhyun
"""

f = open("8CM00054(input1).txt", 'rt', encoding='utf-16')
name = ""
talk = []
speak = {}
not_person = ['al', 'ot']

while(True):
    data = f.readline()
    if not data: break

    if("<u who=" in data or "<s n=" in data):
        # 발화자 구분
        if "who" in data:
            name = data[8:10]
            if name in not_person:
                continue
            if not (name in speak):
               speak[name] = []

        # 대화 추출
        temp = data.split(">")
        s = ""
        for v in temp:
            idx = v.find('<')
            if idx < 2: continue
            speak[name].append(v[:idx])

for who, s in speak.items():
    print("발화자: ",who)
    print(s)


import pygame
from classes import Lab_lvl
from settings import screen, width, height, BUTTON_STYLE, BUTTON_STYLE2
from button import Button
class Player:
    def __init__(self):
        self.image = pygame.image.load("images/pc3.png")
        self.geometry = self.image.get_rect()
        self.geometry.x=10
        self.geometry.y=15
        self.shift = 0
        self.shift2=0

    def check_edges(self):
        if self.geometry.top <= 0 or self.geometry.bottom >= height:
            self.shift = 0
            self.shift2 = 0
        if self.geometry.left <= 0 or self.geometry.right >= width:
            self.shift = 0
            self.shift2 = 0

    def move(self):
        self.geometry.y += self.shift
        self.geometry.x += self.shift2
        self.check_edges()

    def move_to_start(self):
        self.geometry.x = 10
        self.geometry.y = 15

    def process_event(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                self.shift = -2
                self.shift2 = 0
            elif event.key == pygame.K_s:
                self.shift = 2
                self.shift2 = 0
            elif event.key == pygame.K_a:
                self.shift2 = -2
                self.shift = 0
            elif event.key == pygame.K_d:
                self.shift2 = 2
                self.shift = 0
        elif event.type == pygame.KEYUP:
            self.shift = 0
            self.shift2=0

class Enemy:
    def __init__(self):
        self.image = pygame.image.load("images/pac.png")
        self.geometry = self.image.get_rect()
        self.geometry.x=10
        self.geometry.y=15
        self.shift = 0
        self.shift2= 1

    def check_edges(self):
        if self.geometry.top <= 0 or self.geometry.bottom >= height:
            self.shift = 0
            self.shift2 = 0
        if self.geometry.left <= 0 or self.geometry.right >= width:
            self.shift = 0
            self.shift2 = 0

    def move(self):
        self.geometry.y += self.shift
        self.geometry.x += self.shift2
        self.check_edges()

    def move_to_start(self):
        self.geometry.x = 110
        self.geometry.y = 265

class Labyrinth:
    def __init__(self):
        self.walls = []
        self.walls2 = []
        wallx=0
        wally=0
        wallx2=0
        w_all=Lab_lvl.lvl_1()
        self.walls=w_all.return_of_y()
        self.walls2=w_all.return_of_x()
        for i in range(13):
            self.walls.append(Lab_lvl.Wall(wallx, wally))
            wally+=60
        for i in range(3):
            self.walls2.append(Lab_lvl.Wall2(wallx, 180))
            wallx+=60
        for i in range(15):
            self.walls2.append(Lab_lvl.Wall2(wallx2, wally))
            wallx2+=60
        wallx=1010
        wally=0
        for i in range(13):
            self.walls.append(Lab_lvl.Wall(wallx, wally))
            wally+=60
        wallx2=80
        for i in range(17):
            self.walls2.append(Lab_lvl.Wall2(wallx2, 0))
            wallx2+=60
        wallx=0
        for i in range(3):
            self.walls2.append(Lab_lvl.Wall2(wallx, 395))
            wallx+=60

    def get_walls(self):
        return self.walls
    def get_walls2(self):
        return self.walls2

class Menu:
    def __init__(self):
        pygame.font.init()
        self.active = True
        self.bg = pygame.image.load("images/menu_pict.png").convert()
        self.bg = pygame.transform.smoothscale(self.bg, screen.get_size())
        self.font = pygame.font.Font(None, width * height * 3 // 20000)
        self.text = self.font.render("PACMAN", True, pygame.Color('yellow'))
        self.text_rect = self.text.get_rect(center=(width / 2, height / 10))
        button_NewGame = pygame.Rect(250, height / 1.5 + height / 10, 200, 150)
        button_Exit = pygame.Rect(550, height / 1.5 + height / 10, 200, 150)
        self.new_game_button = Button(button_NewGame, pygame.Color('gray'), self.change_sceene, text='New game', **BUTTON_STYLE)
        self.exit_button = Button(button_Exit, pygame.Color('gray'), exit, text='Exit', **BUTTON_STYLE)
    def print_menu(self):
        screen.blit(self.bg, (0, 0))
        screen.blit(self.text, self.text_rect)
        self.new_game_button.update(screen)
        self.exit_button.update(screen)

    def button_clicked(self, event):
        self.new_game_button.check_event(event)
        self.exit_button.check_event(event)

    def change_sceene(self):
        self.active = False

class Game:
    def __init__(self):
        self.walls = Labyrinth().get_walls()
        self.walls2 = Labyrinth().get_walls2()
        self.player = Player()
        self.enemy = Enemy()
        self.active = False

    def print_labyrinth(self):
        screen.fill(pygame.Color('black'))
        screen.blit(self.enemy.image, self.enemy.geometry)
        screen.blit(self.player.image, self.player.geometry)
        for i in self.walls:
            screen.blit(i.image, i.geometry)
        for i in self.walls2:
            screen.blit(i.image, i.geometry)

    def check_collision(self):
        for i in self.walls:
            if self.player.geometry.colliderect(i.geometry):
                self.player.geometry.x += -self.player.shift2
                self.player.shift2 = 0
                self.player.geometry.y += -self.player.shift
                self.player.shift = 0
        for i in self.walls:
            if self.enemy.geometry.colliderect(i.geometry):
                self.enemy.shift=-self.enemy.shift

        for i in self.walls2:
            if self.player.geometry.colliderect(i.geometry):
                self.player.geometry.y += -self.player.shift
                self.player.shift = 0
                self.player.geometry.x += -self.player.shift2
                self.player.shift2 = 0
        for i in self.walls2:
            if self.enemy.geometry.colliderect(i.geometry):

                self.enemy.shift2=-self.enemy.shift2
    def new_game(self):
        self.active = True
        self.enemy.move_to_start()
        self.player.move_to_start()
        self.print_labyrinth()
        pygame.display.flip()
        self.player.shift = 0
        self.player.shift2 = 0

class Death:
    def __init__(self):
        self.active = False
        self.bg = pygame.image.load("images/game_over.jpg").convert()
        self.bg = pygame.transform.smoothscale(self.bg, screen.get_size())
        button_NewGame = pygame.Rect(250, height / 1.5 + height / 10, 200, 150)
        button_Exit = pygame.Rect(550, height / 1.5 + height / 10, 200, 150)
        self.new_game_button = Button(button_NewGame, pygame.Color('gray'), self.change_sceene, text='New game', **BUTTON_STYLE2)
        self.exit_button = Button(button_Exit, pygame.Color('gray'), exit, text='Exit', **BUTTON_STYLE2)

    def print_death(self):
        screen.blit(self.bg, (0, 0))
        self.new_game_button.update(screen)
        self.exit_button.update(screen)

    def button_clicked(self, event):
        self.new_game_button.check_event(event)
        self.exit_button.check_event(event)

    def change_sceene(self):
        self.active = False


from stable_baselines.common.policies import ActorCriticPolicy
from stable_baselines.a2c.utils import linear
from transformer import vision_transformer

class TransformerPolicy(ActorCriticPolicy):

    def __init__(self, sess, ob_space, ac_space, n_env, n_steps, n_batch, feature_extraction="vision_transformer", reuse=False, **kwargs):
        super(TransformerPolicy, self).__init__(sess, ob_space, ac_space, n_env,
                                                n_steps, n_batch, reuse)

        self._kwargs_check(feature_extraction, kwargs)

        hidden_size = 32
        mlp_dim = 32
        num_layers = 4
        dff = 32#mlp_dim * num_layers

        vison_transformer_params ={
            "classifier": "token",
            "hidden_size": hidden_size,
            "patches": [4, 4],
            "representation_size": None,
            "transformer": {
                "attention_dropout_rate": 0.0,
                "dropout_rate": 0.1,
                "mlp_dim": mlp_dim,
                "num_heads": 4,
                "num_layers": num_layers,
                "dff": dff
            }
        }

        with tf.variable_scope("model", reuse=reuse):
            pi_latent = vf_latent = vision_transform(self.processed_obs, vison_transformer_params, **kwargs)

            self._value_fn = linear(vf_latent, 'vf', 1)

            self._proba_distribution, self._policy, self.q_value = \
                self.pdtype.proba_distribution_from_latent(pi_latent, vf_latent, init_scale=0.01)

        self._setup_init()

    def step(self, obs, state=None, mask=None, deterministic=False):
        if deterministic:
            action, value, neglogp = self.sess.run([self.deterministic_action, self.value_flat, self.neglogp],
                                                   {self.obs_ph: obs})
        else:
            action, value, neglogp = self.sess.run([self.action, self.value_flat, self.neglogp],
                                                   {self.obs_ph: obs})
        return action, value, self.initial_state, neglogp

    def proba_step(self, obs, state=None, mask=None):
        return self.sess.run(self.policy_proba, {self.obs_ph: obs})

    def value(self, obs, state=None, mask=None):
        return self.sess.run(self.value_flat, {self.obs_ph: obs})


import os

from azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClient
from azure.cognitiveservices.vision.customvision.training.models import ImageFileCreateBatch, ImageFileCreateEntry
from msrest.authentication import ApiKeyCredentials

os.chdir("../..")
# Replace with valid values
endpoint = os.environ["AZURE_CUSTOM_VISION_ENDPOINT"]
training_key = os.environ["AZURE_CUSTOM_VISION_SUBSCRIPTION_KEY"]

# Authenticate

# Create a new project

for root, dirs, files in os.walk("images", topdown=False):
    try:
        root_dir, category = root.split('/')
        if category != "Test":
            image_list = []
            tag_type = 'Regular' if category != 'Negative' else 'Negative'
            # Create tag for those images folder
            for image in files:
                if image != ".DS_Store":
                    print(f"Dealing with {category}/{image}")
                    with open(os.path.join(root_dir, category, image), "rb") as image_contents:
                        image_entry = None  # Create image entry
                        image_list.append(image_entry)
            print(f'Going to upload images from {category}')
            # Upload the images to project
    except ValueError:
        pass  # base directory


from durgod import Keyboard, Matrix
import time

def main():
    kb = Keyboard.find()

    if kb is None:
        raise ValueError('keyboard not found')

    keys = [Matrix.D, Matrix.U, Matrix.R, Matrix.G, Matrix.O, Matrix.D]

    kb.disable_rgb()

    for key in keys:
        colormap = kb.get_default_colormap()

        colormap.colors[key] = 0xff0000

        kb.apply_colormap(colormap)

        time.sleep(0.5)

    kb.disable_rgb()

if __name__ == '__main__':
    main()


##########################################################################
# File Name: finish/384.py
# Author: Charliegean
# mail: wht905@gmail.com
# Created Time: Mon Nov 22 00:21:05 2021
#########################################################################
#!/usr/bin/env python3
# coding=utf-8
class Solution:

    def __init__(self, nums: List[int]):
        self.nums=nums.copy()
        self.begnums=nums.copy()

    def reset(self) -> List[int]:
        return self.begnums

    def shuffle(self) -> List[int]:
        import random
        if len(self.begnums)==1:
            return self.begnums
        else:
            for i in range(len(self.nums)):
                ind=random.randint(i,len(self.nums)-1)
                temp=self.nums[i]
                self.nums[i]=self.nums[ind]
                self.nums[ind]=temp
            return self.nums

# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()


from selenium.webdriver.common.by import By
from core.helpers.app_sections_helper import AppSectionsHelper

class EventTabsCommon(AppSectionsHelper):
    # Locators
    BUTTON_EDIT = (By.XPATH, "//div[@class='action-buttons']//span[contains(text(), 'Редактировать')]/parent::button")
    BUTTON_BACK = (By.XPATH, "//div[@class='buttons-container']//span[contains(text(), 'Назад')]/parent::button")
    BUTTON_CANCEL = (By.XPATH, "//div[@class='buttons-container']//span[contains(text(), 'Отмена')]/parent::button")
    BUTTON_SAVE = (By.XPATH, "//div[@class='buttons-container']//span[contains(text(), 'Сохранить')]/parent::button")
    MESSAGE_SAVE_SUCCESS = (By.XPATH, "//div[contains(text(), 'Сохранено успешно')]")

    def _check_buttons(self, edit: bool):
        if edit:
            self._check_element_visible(locator=self.BUTTON_EDIT, visibility=True)
            self._check_element_editable(locator=self.BUTTON_EDIT, disabled=True)
            self._check_element_visible(locator=self.BUTTON_BACK, visibility=False)
            self._check_element_visible(locator=self.BUTTON_CANCEL, visibility=True)
            self._check_element_editable(locator=self.BUTTON_CANCEL, disabled=False)
            self._check_element_visible(locator=self.BUTTON_SAVE, visibility=True)
            self._check_element_editable(locator=self.BUTTON_SAVE, disabled=False)
        else:
            self._check_element_visible(locator=self.BUTTON_EDIT, visibility=True)
            self._check_element_editable(locator=self.BUTTON_EDIT, disabled=False)
            self._check_element_visible(locator=self.BUTTON_BACK, visibility=True)
            self._check_element_editable(locator=self.BUTTON_BACK, disabled=False)
            self._check_element_visible(locator=self.BUTTON_CANCEL, visibility=False)
            self._check_element_visible(locator=self.BUTTON_SAVE, visibility=True)
            self._check_element_editable(locator=self.BUTTON_SAVE, disabled=True)


import os,argparse
from PIL import Image
from PIL import ImageEnhance

def main():
	parser = argparse.ArgumentParser(description="This program crops and saves a series of images.")

	parser.add_argument('-p', '--path', nargs='+', help="Path of original images.")
	parser.add_argument('-r', '--rows', type=int, nargs='+', help="Row range to choose.")
	parser.add_argument('-c', '--columns', type=int, nargs='+', help="Column range to choose.")

	args = parser.parse_args()

	currentPath = os.path.split(os.path.abspath(__file__))[0]
	filePath = os.path.join(currentPath, *args.path)
	fileNames = [os.path.join(filePath, x) for x in os.listdir(filePath)]
	outputPath = os.path.join(currentPath, 'cropped_images')

	try:
		os.mkdir(outputPath)
		print("Directory made!")
	except:
		print("Directory already exists!")

	im = Image.open(fileNames[0])
	shape = im.size

	if not args.rows:
		r_1, r_2 = 0, shape[1]
	else:
		r_1, r_2  = args.rows

	if not args.columns:
		c_1, c_2 = 0, shape[0]
	else:
		c_1, c_2 = args.columns

	box = (c_1, r_1, c_2, r_2)
	size = (180, 230)

	for file in fileNames:
		outputName = os.path.split(file)[1].split('.')[0] + '_cropped.jpg'
		im = Image.open(file)
		im_cropped = im.crop(box)
		im_cropped.thumbnail(size)

		# Adjust image brightness
		# An enhancement factor of 0.0 gives a black image. A factor of 1.0
		# gives the original image.
		enhancer_1 = ImageEnhance.Brightness(im_cropped)
		enhanced_1 = enhancer_1.enhance(1.5)

		# Adjust image color balance
		# An enhancement factor of 0.0 gives a black and white image. A factor
		# of 1.0 gives the original image.
		enhancer_2 = ImageEnhance.Color(enhanced_1)
		enhanced_2 = enhancer_2.enhance(1.1)

		# Adjust image contrast
		# An enhancement factor of 0.0 gives a solid grey image. A factor of 1.0
		# gives the original image.
		enhancer_3 = ImageEnhance.Contrast(enhanced_2)
		enhanced_3 = enhancer_3.enhance(1.1)

		# Adjust image sharpness
		# An enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives
		# the original image, and a factor of 2.0 gives a sharpened image.
		enhancer_4 = ImageEnhance.Sharpness(enhanced_3)
		enhanced_4 = enhancer_4.enhance(1.3)

		# Save the image
		enhanced_4.save(os.path.join(outputPath, outputName))

	print("Done!")

if __name__ == "__main__":
	main()


"""\
Loop over 530 conventional settings of the 230 space groups,
show symmetry operations in various formats.

See also:
  List of 530 settings:
    Shmueli U, Hall SR, Grosse-Kunstleve RW:
    Space-Group Symbols for numeric and symbolic computations.
    In International Tables for Crystallography, Volume B:
    Reciprocal space, U. Shmueli, Ed.,
    Kluwer Academic Publishers (Dordrecht), 2001, 107-119.

  Universal Hermann-Mauguin symbols: section 2.1 of:
    Zwart P, Grosse-Kunstleve RW, Lebedev AA, Murshudov GN, Adams PD:
    Surprises and pitfalls arising from(pseudo)symmetry
    Acta Cryst. 2008, D64, 99-107.
    http://scripts.iucr.org/cgi-bin/paper?ba5111
"""
from __future__ import absolute_import, division, print_function

from cctbx import sgtbx

def run():
  for symbols in sgtbx.space_group_symbol_iterator():
    symbol = symbols.universal_hermann_mauguin()
    print(symbol)
    space_group_info = sgtbx.space_group_info(symbol=symbol)
    for s in space_group_info.group():
      print(s.as_xyz())
    for s in space_group_info.group():
      sr = s.as_rational()
      print(sr.r.elems, sr.t.elems)
    for s in space_group_info.group():
      print(s.r().num(), s.r().den(), s.t().num(), s.t().den())
    print()

if (__name__ == "__main__"):
  run()


class BitsAndBinary():
    def __init__(self) -> None:
        pass

    def convert_decimal_to_base(self, dec, base):
        if dec == 0:
            return [0]
        digits = []
        while dec:
            digits.append(int(dec%base))
            dec //= base
        return digits[::-1]

    def convert_base_to_decimal(self, num, base):
        return int(str(num), base)

    def convert_base_to_base(self, num, base, new_base):
        dec = self.convert_base_to_decimal(str(num), base)
        return self.convert_decimal_to_base(dec, new_base)

if __name__ == "__main__":
    obj = BitsAndBinary()
    print(obj.convert_decimal_to_base(8, 2))
    print(obj.convert_base_to_decimal(1000, 2))
    print(obj.convert_base_to_base(7, 10, 4))


import msal
import jwt
import json
import sys
import requests
from datetime import datetime
from msal_extensions import *

clientID = 'yyy'
clientSecret = 'xxx'
tenantID = 'zzz'

graphURI = 'https://graph.microsoft.com'
authority = 'https://login.microsoftonline.com/' + tenantID
scope = ["User.Read"]
username = 'aaa@aaa.com'
result = None
tokenExpiry = None

def msal_persistence(location, fallback_to_plaintext=False):
    """Build a suitable persistence instance based your current OS"""
    if sys.platform.startswith('win'):
        return FilePersistenceWithDataProtection(location)
    if sys.platform.startswith('darwin'):
        return KeychainPersistence(location, "my_service_name", "my_account_name")
    return FilePersistence(location)

def msal_cache_accounts(clientID, authority):
    # Accounts
    persistence = msal_persistence("token_cache.bin")
    print("Is this MSAL persistence cache encrypted?", persistence.is_encrypted)
    cache = PersistedTokenCache(persistence)

    app = msal.PublicClientApplication(
        client_id=clientID, authority=authority, token_cache=cache)
    accounts = app.get_accounts()
    print(accounts)
    return accounts

def msal_delegated_refresh(clientID, scope, authority, account):
    persistence = msal_persistence("token_cache.bin")
    cache = PersistedTokenCache(persistence)

    app = msal.PublicClientApplication(
        client_id=clientID, authority=authority, token_cache=cache)
    result = app.acquire_token_silent_with_error(
        scopes=scope, account=account)
    return result

def msal_delegated_refresh_force(clientID, scope, authority, account):
    persistence = msal_persistence("token_cache.bin")
    cache = PersistedTokenCache(persistence)

    app = msal.PublicClientApplication(
        client_id=clientID, authority=authority, token_cache=cache)
    result = app.acquire_token_silent_with_error(
        scopes=scope, account=account, force_refresh=True)
    return result

def msal_delegated_device_flow(clientID, scope, authority):
    print("Initiate Device Code Flow to get an AAD Access Token.")
    print("Open a browser window and paste in the URL below and then enter the Code. CTRL+C to cancel.")

    persistence = msal_persistence("token_cache.bin")
    cache = PersistedTokenCache(persistence)

    app = msal.ConfidentialClientApplication(client_id=clientID, client_credential=clientSecret, authority=authority, token_cache=cache)
    flow = app.initiate_device_flow(scopes=scope)

    if "user_code" not in flow:
        raise ValueError("Fail to create device flow. Err: %s" % json.dumps(flow, indent=4))

    print(flow["message"])
    sys.stdout.flush()

    result = app.acquire_token_by_device_flow(flow)
    return result

def msal_jwt_expiry(accessToken):
    print(accessToken)
    alg = jwt.get_unverified_header(accessToken['access_token'])['alg']
    decodedAccessToken = jwt.decode(accessToken['access_token'], algorithms=[alg], options={"verify_signature": False})
    accessTokenFormatted = json.dumps(decodedAccessToken, indent=2)

    # Token Expiry
    tokenExpiry = datetime.fromtimestamp(int(decodedAccessToken['exp']))
    print("Token Expires at: " + str(tokenExpiry))
    return tokenExpiry

def msgraph_request(resource, requestHeaders):
    # Request
    results = requests.get(resource, headers=requestHeaders).json()
    return results

accounts = msal_cache_accounts(clientID, authority)

if accounts:
    for account in accounts:
        if account['username'] == username:
            myAccount = account
            print("Found account in MSAL Cache: " + account['username'])
            print("Obtaining a new Access Token using the Refresh Token")
            result = msal_delegated_refresh(clientID, scope, authority, myAccount)

            if result is None:
                # Get a new Access Token using the Device Code Flow
                result = msal_delegated_device_flow(clientID, scope, authority)
            # else:
            #     if result["access_token"]:
            #         msal_jwt_expiry(result["access_token"])
else:
    # Get a new Access Token using the Device Code Flow
    result = msal_delegated_device_flow(clientID, scope, authority)
    # print("got this from msal_delegated_device_flow:")
    # print(result)

    # if result["access_token"]:
    #     msal_jwt_expiry(result["access_token"])

# Query AAD Users based on voice query using DisplayName
print(graphURI + "/v1.0/me")
requestHeaders = {'Authorization': 'Bearer ' + result["access_token"],'Content-Type': 'application/json'}
queryResults = msgraph_request(graphURI + "/v1.0/me",requestHeaders)

print(json.dumps(queryResults, indent=2))

# Force Token Refresh
result =  msal_delegated_refresh_force(clientID, scope, authority, myAccount)
if result is None:
    # Get a new Access Token using the Device Code Flow
    result = msal_delegated_device_flow(clientID, scope, authority)
else:
    if result["access_token"]:
        msal_jwt_expiry(result["access_token"])

print(json.dumps(queryResults, indent=2))