# -*- coding: utf-8 -*-
import os
import json
import pymysql
import sys

#   获取当前路径下的所有json文件
def listdir(path, list_name):  # 传入存储的list
    for file in os.listdir(path):
        file_path = os.path.join(path, file)
        if os.path.isdir(file_path):
            listdir(file_path, list_name)
        else:
            list_name.append(file_path)

        #print(file_path)
    return list_name

#   读取json文件写入到sql数据库中
def readjson(list_name):

    db = pymysql.connect("127.0.0.1","root","1011","hacker",use_unicode=True, charset="utf8")   #   连接数据库
    cursor = db.cursor()
    sql1 = "INSERT INTO hack_user(username)\
             VALUES ('%s')"
    sql2 = "INSERT INTO hack_record(record)\
                 VALUES ('%s')"
    count = 0
    row = 0
    for i in list_name:
        print(i)
        f = open(i,"rb")
        readcontent = f.read()
        content = json.loads(readcontent)
        user = content['user']
        print(user)
        cursor.execute(sql1 % (user))
        history = list(set(content['history']))
        for x in range(len(history)):
            print(history[x])
            row += 1
            try:
                if(history[x] != ''):
                    cursor.execute(sql2 %(history[x]))
            except pymysql.err.ProgrammingError:
                pass
        count = count + 1
    print(count)
    print(row)

if __name__ == '__main__':

    filename_list = []
    path = "//Volumes//Study//课题//代码/0x00sec_forums//user//"
    filelist = listdir(path,filename_list)
    print(filelist)
    # readjson(filelist)


__author__ = 'ssven'
# easy12.py
# Sam Svenningsen (sjs382@cornell.edu)
# November 8, 2014

def permutations_helper(word_list):
    output = ""
    length = len(word_list)
    if length > 1:
        for i in range(length):
            x = word_list.pop(i)
            for j in permutations_helper(word_list).split(", "):
                output += x + j + ", "
            word_list.insert(i,x)
    else:
        output = word_list[0]
    return output

"""Enter word with no commas to get every combination of every
character within it, including the spaces."""
def permutations(word):
    text = list(word)
    return permutations_helper(text)


import sys
import csv

#NAME CLASS
class name_obj():
    '''Represents all attributes of a given name. For use on name_one and name_two.
    Attributes: full_name, title, name, first_name, gender, lastname_yn '''
    def __init__(self, name_one, rank_thresh):
        self.full_name = name_one
        self.title, self.name = self.check_title(self.full_name, titles)
        self.first_name = self.name[0]
        self.gender = self.firstname_gender(self.name)
        self.lastname_yn = self.has_lastname_yn(self.name, rank_thresh)

    def check_title(self, name_one, titles):
        if name_one[0] in titles:
            title = [name_one[0]]
            name_one = name_one[1:]
            return title, name_one
        else:
            title = ''
            return title, name_one

    def firstname_gender(self, name_one):
        '''Classify if first_name has gender = 'male' | 'female'
        Called within name class.'''
        #get female likelihood
        female_percent = gender_dicts[0].get(name_one[0])
        if female_percent == None: female_percent = 0

        #get male likelihood
        male_percent = gender_dicts[1].get(name_one[0])
        if male_percent == None: male_percent = 0

        #Check which likelihood is higher
        if female_percent >= male_percent: gender = 'female'
        else: gender = 'male'
        return gender

    def has_lastname_yn(self, name_one, rank_thresh):
        '''Checks if last word in name is a last_name
        rank_thresh (int) - the rank threshold under which to consider valid last names
        NOTE: There are around 162K last names in total'''
        if len(name_one) == 1:
            return 0
        else:
            if name_one[-1] in surname_dict:
                last_name_rank = surname_dict.get(name_one[-1])
                if last_name_rank < rank_thresh:
                    return 1
                else: return 0
            else: return 0

#FUNCTIONS - OUTCOMES TO APPLY
add_last_name = lambda name_one, name_two : ' '.join(name_one + [name_two[-1]])
add_last_two_name = lambda name_one, name_two : ' '.join(name_one + name_two[-2:])
add_nothing = lambda name_one : ' '.join(name_one)

#FUNCTIONS - RULES
def predict(name_one, name_two):
    '''Rules used to predict the full name of name_one
    name_one <obj> - represented as a class_obj
    name_two <obj> - represented as a class_obj'''
    if len(name_one.name) == 1:
        if name_one.gender != name_two.gender or len(name_two.name) == 2:
#         if len(name_two.name) == 2: acc=70%
            result = add_last_name(name_one.name, name_two.name)
            #print('rule 1.1, 1.2, or 1.3')
            return result
        else:
            result = add_last_two_name(name_one.name, name_two.name)
            #print('rule 1.N')
            return result

    elif len(name_one.name) == 2:
        if name_one.lastname_yn == 1:
            result = add_nothing(name_one.name)
            #print('rule 2.1')
            return result
        else:
            result = add_last_name(name_one.name, name_two.name)
            #print('rule 2.N')
            return result

    elif len(name_one.name) >= 3:
        result = add_nothing(name_one.name)
        #print('rule 3.1')
        return result

#DRIVER - PREPROCESSING
#Create dicts of male and female names with key = name, value = percent

#PARAMETERS
female_file = 'dist.female.first.txt'
male_file = 'dist.male.first.txt'
surname_file = 'Names_2010Census.csv'

gender_files = [female_file, male_file]
gender_dicts = [dict(), dict()]

for file, d in zip(gender_files, gender_dicts):
    fd = open(file, 'r')
    lines = fd.readlines()
    for line in lines:
        line = line.split()
        name = line[0]
        percent = float(line[1])
        d[name] = percent

#Create surname_dict where key = lastname, value = rank
surname_dict = {}
fd = open(surname_file, 'r')
lines = fd.readlines()
for line in lines[1:]:
    line = line.split(',')
    surname_dict[line[0]] = int(line[1])

#DRIVER - MAIN
#PARAMETERS
rank_thresh = 150
titles = {'REVEREND', 'DOCTOR', 'PROFESSOR'}

#Pull out arguments from command line
test_file = sys.argv[1]
output_file = 'full-name-output.csv'

#Open the test file
fd = open(test_file, 'r')
lines = fd.readlines()

#PREDICT
with open(output_file, 'w', newline='') as file:
    writer = csv.writer(file)
    for line in lines:
        #Parse each name into a list, combine into a list of lists
        line = line.strip()
        name_list_str = line.split(' AND ')

        #Create a name object for name_one and name_two
        #Name object consists of: full_name, title, name, first_name, gender, lastname_yn
        name_objects = []
        for idx, name in enumerate(name_list_str):
            name_list = name.split(' ')
            name_object = name_obj(name_list, rank_thresh)
            name_objects.append(name_object)

        name_one = name_objects[0]
        name_two = name_objects[1]
        result = predict(name_one, name_two)
        result_final = [line, result]
        writer.writerow(result_final)


# coding=utf-8

from character import Character
import random
import pygame
from pygame.locals import *

# this two variables will be the graphic reference
WIDTH = 1080
HEIGHT = 660

def set_item_position(map, item_string):
    '''this function give a random position to the game's items'''
    x = random.randint(0, len(map) - 2)
    y = random.randint(0, len(map[0]) - 2)
    if map[x][y] == "path":
        map[x][y] = item_string
        return x, y
    else:
        return set_item_position(map, item_string)

def start():
    '''this fonction create 2D array from a txt file'''
    x = 1  # abscissa
    y = 1  # orderly

    map_dict = ""  # this dict will concatenate the model of the list

    # this line read the txt file and transcrib it into dict
    map_txt = open("map.txt")
    start.col = 0
    start.line = 0
    for number in map_txt:  # we run through line of the file
        number = number if "\n" in number else number + "\n"
        map_dict += number
        start.line = start.line + 1
        # verification that every column have the same amount of character
        if start.col == len(number) or start.col == 0:
            start.col = len(number)
        # if not the same amount, we raise errors message
        else:
            raise "Le nombre de colonnes doit être égal pour chaque lignes."
    # creation of the 2D array
    start.map_overview = [[0 for i in range(start.line)] for j in range(start.col)]

    map_txt.close()

    start.fenetre = pygame.display.set_mode((WIDTH, HEIGHT))

    # assignation of the characters to their function in the map
    for number in map_dict:
        poswidth = (
            (x - 1) * WIDTH / (start.col - 1)
        )  # this two variable give the graphic placement of the objects
        posheight = (y - 1) * HEIGHT / (start.line - 1)
        wall = pygame.image.load("image/mur.png").convert_alpha()
        wall = pygame.transform.scale(
            wall, (int(WIDTH / (start.col - 1)), int(HEIGHT / (start.line - 1)))
        )
        if number == "1":
            start.map_overview[x - 1][y - 1] = "wall"
            start.fenetre.blit(wall, (poswidth, posheight))
        elif number == "M":
            start.map_overview[x - 1][y - 1] = "MacGyver"
            start.macGyver = Character("MacGyver", (x - 1, y - 1))
            start.position_macgyver = (poswidth, posheight)
        elif number == "G":
            start.map_overview[x - 1][y - 1] = "Guardian"
            start.x_y_guard = (x - 1, y - 1)
            start.position_guard = (poswidth, posheight)
        elif number == "0":
            start.map_overview[x - 1][y - 1] = "path"

        if x == start.col:  # counter
            y += 1
            x = 1
        else:
            x += 1

def display_layout():
    '''this function glue the images to their graphic place'''
    display_layout.scale_col_general = int(WIDTH / (start.col - 1))
    display_layout.scale_line_general = int(HEIGHT / (start.line - 1))

    display_layout.black = pygame.image.load("image/carre_noir.png").convert_alpha()
    display_layout.black = pygame.transform.scale(display_layout.black, (display_layout.scale_col_general, display_layout.scale_line_general))

    display_layout.mac_gyver = pygame.image.load("image/MacGyver.png").convert_alpha()
    display_layout.mac_gyver = pygame.transform.scale(
        display_layout.mac_gyver, (display_layout.scale_col_general, display_layout.scale_line_general)
    )
    start.fenetre.blit(display_layout.mac_gyver, start.position_macgyver)

    guard = pygame.image.load("image/Gardien.png").convert_alpha()
    guard = pygame.transform.scale(guard, (display_layout.scale_col_general, display_layout.scale_line_general))
    start.fenetre.blit(guard, start.position_guard)

    position = set_item_position(start.map_overview, "aiguille")
    x, y = position
    position = (x * display_layout.scale_col_general, y * display_layout.scale_line_general)
    aiguille = pygame.image.load("image/aiguille.png").convert_alpha()
    aiguille = pygame.transform.scale(aiguille, (display_layout.scale_col_general, display_layout.scale_line_general))
    start.fenetre.blit(aiguille, (position))

    position = set_item_position(start.map_overview, "tube")
    x, y = position
    position = (x * display_layout.scale_col_general, y * display_layout.scale_line_general)
    tube = pygame.image.load("image/tube_plastique.png").convert_alpha()
    tube = pygame.transform.scale(tube, (display_layout.scale_col_general, display_layout.scale_line_general))
    start.fenetre.blit(tube, (position))

    position = set_item_position(start.map_overview, "éther")
    x, y = position
    position = (x * display_layout.scale_col_general, y * display_layout.scale_line_general)
    ether = pygame.image.load("image/ether.png").convert_alpha()
    ether = pygame.transform.scale(ether, (display_layout.scale_col_general, display_layout.scale_line_general))
    start.fenetre.blit(ether, (position))

    display_layout.x, display_layout.y = start.macGyver.get_position()

    pygame.display.flip()

def key_order():
    # this loop make take the deplacement order and make macgyver move
    continuer = 1
    while continuer:
        for event in pygame.event.get():
            if event.type == QUIT:
                continuer = 0
            if event.type == KEYDOWN:
                start.fenetre.blit(
                    display_layout.black, (display_layout.x * display_layout.scale_col_general, display_layout.y * display_layout.scale_line_general)
                )

                if event.key == K_UP:
                    order = "up"
                    pos = start.macGyver.move(start.map_overview, order)
                if event.key == K_LEFT:
                    order = "left"
                    pos = start.macGyver.move(start.map_overview, order)
                if event.key == K_DOWN:
                    order = "down"
                    pos = start.macGyver.move(start.map_overview, order)
                if event.key == K_RIGHT:
                    order = "right"
                    pos = start.macGyver.move(start.map_overview, order)
                if order:
                    display_layout.x = pos[0]
                    display_layout.y = pos[1]

                    start.fenetre.blit(
                        display_layout.mac_gyver, (display_layout.x * display_layout.scale_col_general, display_layout.y * display_layout.scale_line_general)
                    )
                    pygame.display.flip()

                # when you step on the guard, this condition decide if you win or lose
                if start.x_y_guard == (display_layout.x, display_layout.y):
                    continuer = 0
                    if start.macGyver.inventory(start.map_overview) == True:
                        print("You win !")
                    else:
                        print("You lose !")


import os
import argparse
import sys
from glob import glob
import numpy as np
import time
import copy
from multiprocessing import Pool
import json
from scipy.stats import norm, gengamma
from models import *
device = torch.device("cpu")

db_low, db_high = -5, 39
state_dim = db_high - db_low + 1 # -5-39 dB
action_dim = 41 # 0~39 dB, stop
db_length = state_dim
locations = [10,11,18,19,20]

def load_data():
    normal_file_test = '../data/test/normal.txt'
    normal_sens_test = []
    f = open(normal_file_test, 'r')
    for line in f.readlines():
        line = np.array(eval(line))
        normal_sens_test.append(list(line[locations]))
    f.close()

    abnormal_file_test = '../data/test/abnormal.txt'
    abnormal_sens_test = []
    f = open(abnormal_file_test, 'r')
    for line in f.readlines():
        line = np.array(eval(line))
        abnormal_sens_test.append(list(line[locations]))
    f.close()
    return normal_sens_test, abnormal_sens_test

def create_nn_graph():
    def find_edges_nn(points):
        edges = dict()
        for (x,y) in points:
            edges[(x,y)] = []
            for point in [(x-1, y-1), (x-1, y), (x, y-1), (x-1, y+1), (x+1, y-1), (x+1, y), (x+1, y+1), (x, y+1)]:
                if point in points:
                    edges[(x,y)].append(point)
        return edges
    points = [(7,1), (6,1), (8,0), (7,0), (6,0)]
    edges = find_edges_nn(points)
    return edges, points

def responseProb(stim, sens):
    FP, FN = 0.03, 0.03 # FP: patient does not see the stimulus, but responses accidently
    SD = min(np.exp(-0.081 * sens + 3.27), 6)
    response_prob =  1 - FN - (1 - FN - FP) * norm.cdf(stim,loc=sens,scale=SD) # cdf: cummulative density distribution
    return response_prob

def responseOrNot(stim, sens):
    response_prob =  responseProb(stim, sens) # probability between 0 and 1
    random_number = np.random.uniform(0, 1) # gaussian distributed between 0 and 1
    if random_number < response_prob and sens > 0:
        return True
    else:
        return False

def responseTime(stim, sens, response):
    def muvarfunc(d):
        if d <= 2:
            mu = 3.86 + 1.44*np.exp(d/2.04)
            var = 0.2 + 4.0*np.exp(d/2.0)
        else:
            mu, var = muvarfunc(2)
        return mu, var

    def GammaFunc(d):
        mu, var = muvarfunc(d)
        h, c = mu**2/var, mu/var
        ps = []
        for i in np.arange(0,16, 0.1):
            ps.append(gengamma.pdf(i,h,c))
        ps = ps/sum(ps)
        time = max(0.05, np.random.choice(np.arange(0,1.6,0.01), p=ps))
        return time

    d = stim - sens
    time = GammaFunc(d) if response else 1.5
    if time > 1.5:
        time = 1.5
        response = False
    return time, response

def get_state(obs):
    state = np.array(obs)
    state = torch.from_numpy(state)
    return state.unsqueeze(0)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='DCorr Testing')
    parser.add_argument('--c', default=1., type=float, help='Time Cost Factor Alpha')
    args = parser.parse_args()

    # hyperparameters
    c = args.c

    # alpha to delta; these numbers are obtained by comparing DREST and ZEST
    if args.c == 0.5:
        sd_crit = 2.45
    elif args.c == 1.0:
        sd_crit = 2.82
    else:
        sd_crit = 3.27

    # Load data and graph
    normal_test, abnormal_test = load_data()
    edges, points = create_nn_graph()

    # Load models
    models = dict()
    policy_net = DQN(state_dim, action_dim)
    for i,location in enumerate(locations):
        model_path = '../weights/{}/{}/model.pth'.format(location, c)
        policy_net_copy = copy.deepcopy(policy_net)
        policy_net_copy.load_state_dict(torch.load(model_path, map_location=device))
        policy_net_copy.to(device)
        models[points[i]] = policy_net_copy

    def sim_exp(VF):
        pdfs, sens_graph, pdf_stds = dict(), dict(), dict()
        for i,point in enumerate(points):
            sens_graph[point] = VF[i]
            pdfs[point] = np.load('../data/train/PMF_VF/pmf%d.npy'%locations[i])
            pdf_mean = np.sum(np.arange(db_low, db_high + 1) * pdfs[point])
            pdf_stds[point] = np.sqrt(np.sum(pdfs[point] * (np.arange(db_low, db_high + 1) - pdf_mean) ** 2))
        n_presentation, total_time = 0, 0
        points_remain = list(sens_graph.keys())
        while True:
            if len(points_remain) == 0:
                break
            point = points_remain[0]
            for p in pdf_stds:
                if p in points_remain and pdf_stds[p] > pdf_stds[point]:
                    point = p
            if pdf_stds[point] > sd_crit and n_presentation <= 50:
                policy_net = models[point]
                state = get_state(pdfs[point])
                stim = int(policy_net(state).max(1)[1].view(1,1))
                if stim != action_dim - 1:
                    likelihood = np.zeros(db_length)
                    response = responseOrNot(stim, sens_graph[point])
                    time, response = responseTime(stim, sens_graph[point], response)
                    if response:
                        for i in range(db_length):
                            likelihood[i] = responseProb(stim, i + db_low)
                    else:
                        for i in range(db_length):
                            likelihood[i] = 1 - responseProb(stim, i + db_low)
                    pdf = pdfs[point] * likelihood
                    pdf = pdf / np.linalg.norm(pdf, ord=1)
                    pdfs[point] = pdf
                    pdf_mean = np.sum(np.arange(db_low, db_high + 1) * pdf)
                    pdf_stds[point] = np.sqrt(np.sum(pdf * (np.arange(db_low, db_high + 1) - pdf_mean) ** 2))
                    likelihood_connect = (likelihood - 0.5) * 0.2 + 0.5
                    for point_connect in edges[point]:
                        if point_connect in points_remain:
                            pdf = pdfs[point_connect] * likelihood_connect
                            pdf = pdf / np.linalg.norm(pdf, ord=1)
                            pdfs[point_connect] = pdf
                            pdf_mean = np.sum(np.arange(db_low, db_high + 1) * pdf)
                            pdf_stds[point_connect] = np.sqrt(np.sum(pdf * (np.arange(db_low, db_high + 1) - pdf_mean) ** 2))
                    n_presentation += 1
                    total_time += time
                    for p in pdf_stds:
                        if pdf_stds[p] <= sd_crit and p in points_remain:
                            points_remain.remove(p)
                else:
                    points_remain.remove(point)
            else:
                break
        errors, preds = [], dict()
        for point in pdfs:
            pred = max(0, np.sum(np.arange(db_low, db_high + 1) * pdfs[point]))
            preds[point] = pred
            error = np.abs(sens_graph[point] - pred)
            errors.append(error)
        return np.mean(errors), n_presentation / len(locations), total_time / len(locations)

    # write to logs
    log_dir = '../logs'
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    log_file = os.path.join(log_dir, 'DCorr_{}.txt'.format(c))
    f = open(log_file, 'w', buffering=1)

    with Pool(processes=64) as pool:
        result_n = pool.map(sim_exp, normal_test*10)
    result_n = np.array(result_n)
    errors_n = result_n[:,0]
    ns_n = result_n[:,1]
    ts_n = result_n[:,2]
    with Pool(processes=64) as pool:
        result_a = pool.map(sim_exp, abnormal_test*10)
    result_a = np.array(result_a)
    errors_a = result_a[:,0]
    ns_a = result_a[:,1]
    ts_a = result_a[:,2]

    # Normal
    f.write('MAE Normal = %.3f \n'%np.mean(errors_n))
    f.write('N Normal = %.3f \n'%np.mean(ns_n))
    f.write('T Normal = %.3f \n'%np.mean(ts_n))

    # Abnormal
    f.write('MAE Abnormal = %.3f \n'%np.mean(errors_a))
    f.write('N Abnormal = %.3f \n'%np.mean(ns_a))
    f.write('T Abnormal = %.3f \n'%np.mean(ts_a))
    f.close()


#%%
import os
import sys
import random
import warnings

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from tqdm import tqdm
from itertools import chain
from skimage.io import imread, imshow, imread_collection, concatenate_images
from skimage.transform import resize
from skimage.morphology import label

from keras.models import load_model
from utils.dice import dice_coef
from utils.models import combined_loss, mean_iou, MaxUnpooling2D, MaxPoolingWithArgmax2D
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

# Set some parameters
IMG_WIDTH = 128
IMG_HEIGHT = 128
IMG_CHANNELS = 3
TRAIN_PATH = "./data-science-bowl-2018/stage1_train/"
TEST_PATH = "./data-science-bowl-2018/stage1_test/"

warnings.filterwarnings("ignore", category=UserWarning, module="skimage")
seed = 42
random.seed = seed
np.random.seed = seed
#%%
train_ids = next(os.walk(TRAIN_PATH))[1]
test_ids = next(os.walk(TEST_PATH))[1]

#%%
# Get and resize train images and masks
X_train = np.zeros(
    (len(train_ids), IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS), dtype=np.uint8
)
Y_train = np.zeros((len(train_ids), IMG_HEIGHT, IMG_WIDTH, 1), dtype=np.bool)
print("Getting and resizing train images and masks ... ")
sys.stdout.flush()
for n, id_ in tqdm(enumerate(train_ids), total=len(train_ids)):
    path = TRAIN_PATH + id_
    img = imread(path + "/images/" + id_ + ".png")[:, :, :IMG_CHANNELS]
    img = resize(img, (IMG_HEIGHT, IMG_WIDTH), mode="constant", preserve_range=True)
    X_train[n] = img
    mask = np.zeros((IMG_HEIGHT, IMG_WIDTH, 1), dtype=np.bool)
    for mask_file in next(os.walk(path + "/masks/"))[2]:
        mask_ = imread(path + "/masks/" + mask_file)
        mask_ = np.expand_dims(
            resize(
                mask_, (IMG_HEIGHT, IMG_WIDTH), mode="constant", preserve_range=True
            ),
            axis=-1,
        )
        mask = np.maximum(mask, mask_)
    Y_train[n] = mask

# Get and resize test images
X_test = np.zeros((len(test_ids), IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS), dtype=np.uint8)
sizes_test = []
print("Getting and resizing test images ... ")
sys.stdout.flush()
for n, id_ in tqdm(enumerate(test_ids), total=len(test_ids)):
    path = TEST_PATH + id_
    img = imread(path + "/images/" + id_ + ".png")[:, :, :IMG_CHANNELS]
    sizes_test.append([img.shape[0], img.shape[1]])
    img = resize(img, (IMG_HEIGHT, IMG_WIDTH), mode="constant", preserve_range=True)
    X_test[n] = img

print("Done!")

#%%
fig = plt.figure(figsize=(9,24), dpi=200)
for ix in range(5,8):
    a = fig.add_subplot(7, 3, ix-4)
    plt.imshow(X_train[int(X_train.shape[0] * 0.9) :][ix])
    a.set_title("Original_"+str(ix-5))
for ix in range(8,11):
    a = fig.add_subplot(7, 3, ix-4)
    plt.imshow(np.squeeze(Y_train[int(Y_train.shape[0] * 0.9) :][int(ix-3)]))
    a.set_title("Ground Truth_"+str(int(ix-8)))

# Predict on train, val and test
counter = 0
names = ["Unet", "SegNet", "SegUnet", "UnetPP", "ResUNet"]

for name in names:
    model=load_model(
        "h5/" + name + ".h5",
        custom_objects={
            "mean_iou": mean_iou,
            "combined_loss": combined_loss,
            "MaxPoolingWithArgmax2D": MaxPoolingWithArgmax2D,
            "MaxUnpooling2D": MaxUnpooling2D,
        },
    )
    preds_train = model.predict(X_train[: int(X_train.shape[0] * 0.9)], verbose=1)
    preds_val = model.predict(X_train[int(X_train.shape[0] * 0.9) :], verbose=1)
    preds_test = model.predict(X_test, verbose=1)

    # Threshold predictions
    preds_train_t = (preds_train > 0.5).astype(np.uint8)
    preds_val_t = (preds_val > 0.5).astype(np.uint8)
    preds_test_t = (preds_test > 0.5).astype(np.uint8)

    # Create list of upsampled test masks
    preds_test_upsampled = []
    for i in range(len(preds_test)):
        preds_test_upsampled.append(
            resize(
                np.squeeze(preds_test[i]),
                (sizes_test[i][0], sizes_test[i][1]),
                mode="constant",
                preserve_range=True,
            )
        )

    for ix in range(11,14):
        a = fig.add_subplot(7, 3, ix-4+counter)
        plt.imshow(np.squeeze(preds_val_t[ix-6]))
        a.set_title(name +"_"+str(ix-11))
    counter+=3

    dice_coefs = []
    for i in range(len(preds_val_t)):
        dice_coefs.append(
            dice_coef(
                np.squeeze(Y_train[int(Y_train.shape[0] * 0.9) :][i]),
                np.squeeze(preds_val_t[i]),
            )
        )
    print("The mean dice coeffient of " + name + ": " + str(np.mean(dice_coefs)))
fig.savefig('./model_plot/SegmentationResults.png')
# %%


# -*- coding: UTF-8 -*-
# 面向对象编程
# 面向对象编程——Object Oriented Programming，简称OOP，是一种程序设计思想。OOP把对象作为程序的基本单元，一个对象包含了数据和操作数据的函数。
#
# 面向过程的程序设计把计算机程序视为一系列的命令集合，即一组函数的顺序执行。为了简化程序设计，面向过程把函数继续切分为子函数，
#
# 即把大块函数通过切割成小块函数来降低系统的复杂度。
#
# 而面向对象的程序设计把计算机程序视为一组对象的集合，而每个对象都可以接收其他对象发过来的消息，并处理这些消息，
#
# 计算机程序的执行就是一系列消息在各个对象之间传递。
#
# 在Python中，所有数据类型都可以视为对象，当然也可以自定义对象。自定义的对象数据类型就是面向对象中的类（Class）的概念。
#
# 我们以一个例子来说明面向过程和面向对象在程序流程上的不同之处。
#
# 假设我们要处理学生的成绩表，为了表示一个学生的成绩，面向过程的程序可以用一个dict表示：
std1 = {'name': 'Michael', 'score': 81}
std1 = {'name': 'Bob', 'score': 91}

# 而处理学生成绩可以通过函数实现，比如打印学生的成绩：
def print_score(std):
    print('%s:%s' % (std['name'], std['score']))

print(std1)  # =>{'name': 'Bob', 'score': 91}

# 如果采用面向对象的程序设计思想，我们首选思考的不是程序的执行流程，而是Student这种数据类型应该被视为一个对象，
# 这个对象拥有name和score这两个属性（Property）。如果要打印一个学生的成绩，首先必须创建出这个学生对应的对象，
# 然后，给对象发一个print_score消息，让对象自己把自己的数据打印出来。
class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def print_score(self):
        print('%s:%s' % (self.name, self.score))

# 给对象发消息实际上就是调用对象对应的关联函数，我们称之为对象的方法（Method）。面向对象的程序写出来就像这样：
bart = Student('Bart Simpson', 88)
lisa = Student('Lisa Simpson', 99)

bart.print_score()  # =>Bart Simpson:88
lisa.print_score()  # =>Lisa Simpson:99

# 面向对象的设计思想是从自然界中来的，因为在自然界中，类（Class）和实例（Instance）的概念是很自然的。
# Class是一种抽象概念，比如我们定义的Class——Student，是指学生这个概念，而实例（Instance）则是一个个具体的Student，
# 比如，Bart Simpson和Lisa Simpson是两个具体的Student。
#
# 所以，面向对象的设计思想是抽象出Class，根据Class创建Instance。
#
# 面向对象的抽象程度又比函数要高，因为一个Class既包含数据，又包含操作数据的方法。
#
# 小结
# 数据封装、继承和多态是面向对象的三大特点，我们后面会详细讲解。

# 类和实例
# 面向对象最重要的概念就是类（Class）和实例（Instance），必须牢记类是抽象的模板，比如Student类，
# 而实例是根据类创建出来的一个个具体的“对象”，每个对象都拥有相同的方法，但各自的数据可能不同。
#
# 仍以Student类为例，在Python中，定义类是通过class关键字：
class Student(object):
    pass

# class后面紧接着是类名，即Student，类名通常是大写开头的单词，紧接着是(object)，表示该类是从哪个类继承下来的，继承的概念我们后面再讲，
# 通常，如果没有合适的继承类，就使用object类，这是所有类最终都会继承的类。
#
# 定义好了Student类，就可以根据Student类创建出Student的实例，创建实例是通过类名+()实现的：
bart = Student()
print(bart)  # =><__main__.Student object at 0x000001A523799908>
# 可以看到，变量bart指向的就是一个Student的实例，后面的0x10a67a590是内存地址，每个object的地址都不一样，而Student本身则是一个类。
#
# 可以自由地给一个实例变量绑定属性，比如，给实例bart绑定一个name属性：
bart.name = 'Abbot'
print(bart.name)  # =>Abbot

# 由于类可以起到模板的作用，因此，可以在创建实例的时候，把一些我们认为必须绑定的属性强制填写进去。通过定义一个特殊的__init__方法，
# 在创建实例的时候，就把name，score等属性绑上去：
class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.score = score

# 注意到__init__方法的第一个参数永远是self，表示创建的实例本身，因此，在__init__方法内部，就可以把各种属性绑定到self，
# 因为self就指向创建的实例本身。
#
# 有了__init__方法，在创建实例的时候，就不能传入空的参数了，必须传入与__init__方法匹配的参数，但self不需要传，
# Python解释器自己会把实例变量传进去：
bart = Student('Tom', 89)
print(bart.name, bart.score)  # =>Tom 89

# 和普通的函数相比，在类中定义的函数只有一点不同，就是第一个参数永远是实例变量self，并且，调用时，不用传递该参数。
# 除此之外，类的方法和普通函数没有什么区别，所以，你仍然可以用默认参数、可变参数、关键字参数和命名关键字参数。
# 数据封装
# 面向对象编程的一个重要特点就是数据封装。在上面的Student类中，每个实例就拥有各自的name和score这些数据。
# 我们可以通过函数来访问这些数据，比如打印一个学生的成绩：
def print_score(std):
    print('%s: %s' % (std.name, std.score))

print_score(bart)  # => Tom: 89

# 但是，既然Student实例本身就拥有这些数据，要访问这些数据，就没有必要从外面的函数去访问，可以直接在Student类的内部定义访问数据的函数，
# 这样，就把“数据”给封装起来了。这些封装数据的函数是和Student类本身是关联起来的，我们称之为类的方法：
class Student(object):
    def __init__(self,name,score):
        self.name=name
        self.score = score
    def print_score(self):
        print('%s: %s'%(self.name,self.score))

# 要定义一个方法，除了第一个参数是self外，其他和普通函数一样。要调用一个方法，只需要在实例变量上直接调用，除了self不用传递，其他参数正常传入：
bart = Student('Bart Simpson',99)
bart.print_score() #=>Bart Simpson: 99

# 这样一来，我们从外部看Student类，就只需要知道，创建实例需要给出name和score，而如何打印，
# 都是在Student类的内部定义的，这些数据和逻辑被“封装”起来了，调用很容易，但却不用知道内部实现的细节。
#
# 封装的另一个好处是可以给Student类增加新的方法，比如get_grade：

class Student(object):
    def __init__(self,name,score):
        self.name=name
        self.score = score
    def print_score(self):
        print('%s: %s'%(self.name,self.score))
    def print_grade(self):
        if self.score>90:
            return 'A'
        if self.score>=60:
            return 'B'
        else:
            return 'C'
# 同样的，get_grade方法可以直接在实例变量上调用，不需要知道内部实现细节：
lisa = Student('lisa math',89)
tom = Student('Tom math',99)
print(lisa.print_grade()) # => B
print(tom.print_grade())  # => A

# 小结
# 类是创建实例的模板，而实例则是一个一个具体的对象，各个实例拥有的数据都互相独立，互不影响；
#
# 方法就是与实例绑定的函数，和普通函数不同，方法可以直接访问实例的数据；
#
# 通过在实例上调用方法，我们就直接操作了对象内部的数据，但无需知道方法内部的实现细节。
#
# 和静态语言不同，Python允许对实例变量绑定任何数据，也就是说，对于两个实例变量，虽然它们都是同一个类的不同实例，但拥有的变量名称都可能不同：
#
# >>> bart = Student('Bart Simpson', 59)
# >>> lisa = Student('Lisa Simpson', 87)
# >>> bart.age = 8
# >>> bart.age
# 8
# >>> lisa.age
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# AttributeError: 'Student' object has no attribute 'age'


# this is version 3 of the image manipulation lab. It involves drawing a stick figure.

from PIL import Image, ImageDraw

width = 500
height = 500

img = Image.new('RGB', (width, height))

draw = ImageDraw.Draw(img)

# the origin (0, 0) is at the top-left corner

draw.rectangle(((0, 0), (width, height)), fill="white")
#this is basically creating a blank canvas to draw on

# draw a rectangle from x0, y0 to x1, y1
# draw.rectangle(((100, 100), (300, 300)), fill="green")

# draw a line from x0, y0, x1, y1
# using the color pink
# color = (256, 128, 128)  # pink
draw.line((width - 325, (height - 375), width - 175, (height - 375)), fill="black")#shoulders
draw.line((width - 325, (height - 375), width - 325, (height - 250)), fill="black")#right arm
draw.line((width - 175, (height - 375), width - 175, (height - 250)), fill="black")#left arm
draw.line((width/2, (height - 450), width/2, (height - 250)), fill= "black") #body
draw.line((width/2, (height - 250), (width - 225), (height )), fill= "black")#right leg
draw.line((width/2, (height - 250), (width - 275), (height )), fill= "black")#left leg

circle_x = width/2
circle_y = height - 450
circle_radius = 50
draw.ellipse((circle_x-circle_radius, circle_y-circle_radius, circle_x+circle_radius, circle_y+circle_radius), fill='black')

img.show()


import numpy as np
import cv2

class Szachy:
	def __init__(self):
		self.współrzędne = { 'x9': [1000000,1000000]}   # dziennik współrzędnych pól oraz ich współrzędnych liczbowych (tabelarycznych)
														# na wykrytej szachownicy
		self.lokalizacja= 'x9' #nieużywane z racji na złe działanie kodu
	def przypisanie_pól(self, dół, góra, x, y, w, h): #funkcja wykonuje działania mające na celu odpowiednie przypisanie współrzędnych pól

		if (góra.mean()>dół.mean()):#jeśli góra jest biała

			skok_pionowy = h / 8
			skok_poziomy = w / 8

			x = x + (skok_poziomy / 2)
			y = y + (skok_pionowy / 2)
			schowek_x = x
			kolumny = 'hgfedcba'
			for i in range(len(kolumny)):
				for j in range(1, 9):
					klucz = kolumny[i] + str(j)
					self.współrzędne.update({klucz: [x, y]})
					x = x + skok_poziomy
				x = schowek_x
				y = y + skok_pionowy

		else: #jeśli dół jest biały
			skok_pionowy = h / 8
			skok_poziomy = w / 8

			x = x + (skok_poziomy / 2)
			y = y + (skok_pionowy / 2)
			schowek_x = x
			kolumny = 'abcdefgh'
			for i in range(len(kolumny)):
				for j in range(1, 9):
					klucz = kolumny[i] + str(9-j)

					self.współrzędne.update({klucz: [x, y]})
					x = x + skok_poziomy

				x = schowek_x
				y = y + skok_pionowy ##
	def skalowanie_ekranu(self, obraz, wsp): #przeskalowanie ekranu do rozmiarów stałych, niepozwalających na błędną interpretację danych liczbowych
		wysokość = int(obraz.shape[0] * wsp)
		szerokość = int(obraz.shape[1] * wsp)
		interpolacja_ekranu = cv2.INTER_AREA

		return cv2.resize(obraz, (szerokość, wysokość), interpolacja_ekranu)
	def obrót_szachownicy(self, thresh, x,y,w,h):# funkcja określa strony tj. czy białe znajdują się na górze, czy na dole

		h=h/4
		góra=np.mean(thresh[y:y+int(h),x:x+w],(0,1))
		dół=np.mean(thresh[y+int(3*h):int(y+h*4),x:x+w],(0,1))
		#print(góra,'    ', dół)
		#print(góra.mean())
		#print(dół.mean())
		h=4*h
		self.przypisanie_pól( dół, góra, x, y, w, h)

		return
	def wstaw_bierkę(self, nazwa_bierki, x, y, w, h,  kolor, obraz, kolor_bierki):  # funkcja opisująca bierkę na podglądzie kończowym

		cv2.rectangle(obraz, (x, y), (x + w, y + h), kolor, 1)
		kolumny='abcdefgh'
		for i in range(len(kolumny)):  #niedziałający fragment kodu, mający na celu rzeczywiste
										# w czasie rozpoznawanie pola na którym stoi dana bierka
			for j in range(1, 9):
				klucz=kolumny[i]+str(j)
				wsp=self.współrzędne[klucz]
				#print(klucz)

				#if(wsp[1]<(x+w) and wsp[1] >(x) and wsp[0]<(x+w)  and wsp[0]>(y)):

		cv2.putText(obraz, kolor_bierki + " " + nazwa_bierki, (x, y),cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 0), 1)
	def rozpoznanie_bierki(self, kontury, obraz, thresh): #rozpoznawanie figur szachowych

		for kontur in kontury:  #znalezienie konturu szachownicy
			if (cv2.arcLength(kontur, True) > 800):
				x, y, w, h = cv2.boundingRect(kontur)
				cv2.putText(obraz, "Szachownica", (x+w+20, y + h), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 200, 255), 2)

			if (cv2.arcLength(kontur, True) < 150 or cv2.arcLength(kontur, True) > 300): #pominięcie zbyt małych konturów
				continue
			kolor_bierki = "B"
			approx = cv2.approxPolyDP(kontur, 0.03 * cv2.arcLength(kontur, True),True)
			area = cv2.contourArea(kontur)    # powierzchnia bierki
			x, y, w, h = cv2.boundingRect(approx)
			rect_area = w * h #powierzchnia wykreślonego prostokąta
			s_pola = float(area) / rect_area  # stosunek pola powierzchni rect i konturu
			s_wymiarów = float(w) / h         # stosunek wymiarów szerokość długość

			kolor_pola = np.array(cv2.mean(thresh[y:y + h, x:x + w])) #okreslenie koloru bierki

			if ((area<2000)&(s_pola>0.7)&(s_wymiarów<0.8)): #rozpoznanie pionka
				kolor_ramki = (255, 255, 255)
				if kolor_pola[0] > 65:
					kolor_bierki='Cz'
					kolor_ramki = (0, 0, 0)
				self.wstaw_bierkę("Pionek", x, y, w, h,  kolor_ramki, obraz, kolor_bierki)

			if ((2700<area and area<2800)&(s_pola<0.8)&(s_wymiarów>0.9)): #Rozpoznanie Skoczka
				kolor_ramki= (255, 255, 255)
				if kolor_pola[0] > 100:
					kolor_bierki='Cz'
					kolor_ramki=(0,0,0)

				self.wstaw_bierkę("Skoczek", x, y, w, h,  kolor_ramki, obraz, kolor_bierki)

			if ((2020<area and area<2150)&(s_pola<0.65)&(s_wymiarów>0.91)): #Rozpoznanie gońca
				kolor_ramki = (255, 255, 255)
				# print('kolor - ', colors)
				# print('powierzchnia - ', area)
				# print('stosunek powierzchni - ', s_pola)
				# print('stosunek wymiarów - ', s_wymiarów)
				# print('długość konturu', float(cv2.arcLength(kontur, True)))
				if kolor_pola[0] > 74.5: #gdzieś tutuaj jest granica, ciężko złabac dla białego gońca na czarnym
					kolor_bierki='Cz'
					kolor_ramki = (0, 0, 0)
				self.wstaw_bierkę("Goniec", x, y, w, h,  kolor_ramki, obraz, kolor_bierki)

			if ((2200<area and area<2320)&(s_pola>0.78 and s_pola<0.84)&(s_wymiarów<0.9)): #Rozpozanie wieży
				kolor_ramki = (255, 255, 255)
				if kolor_pola[0] > 90:
					kolor_bierki='Cz'
					kolor_ramki = (0, 0, 0)

				self.wstaw_bierkę("Wieza", x, y, w, h, kolor_ramki, obraz, kolor_bierki)

			if ((2780<area and area<3000)&(s_pola>0.79)&(s_wymiarów>0.99)): #Rozpoznanie hetmana
				kolor_ramki = (255, 255, 255)
				if kolor_pola[0] > 106.3: #105,88 jak biały hetman stoi na czarnym polu
					kolor_bierki='Cz'
					kolor_ramki = (0, 0, 0)
				self.wstaw_bierkę("Hetman", x, y, w, h, kolor_ramki, obraz, kolor_bierki)

			if ((2300<area and area<2450)&(s_pola<0.75)&(s_wymiarów>0.93)): #Rozpoznanie króla
				kolor_ramki=(255, 255, 255)
				if kolor_pola[0] > 78: #77,5 jak biały król stoi na czarnym polu
					kolor_bierki='Cz'
					kolor_ramki= (0, 0, 0)

				self.wstaw_bierkę("Krol", x, y, w, h,  kolor_ramki, obraz, kolor_bierki)

		cv2.imshow('Przebieg partii', obraz)
	def start(self):
		cap = cv2.VideoCapture('nagrania/Chess.com.mkv')

		ret, obraz = cap.read() #Zebranie kratki do określenia wymiarów szachownicy
		if ret: #obróbka orbazu
			obraz = self.skalowanie_ekranu(obraz, 0.6)
			gray = cv2.cvtColor(obraz, cv2.COLOR_BGR2GRAY)
			thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 3)
			_, threshold_otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)
			morfo = cv2.morphologyEx(threshold_otsu, cv2.MORPH_ERODE, np.ones((7, 7), np.uint8))
			kontury, hierarchia = cv2.findContours(morfo, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

			for kontur in kontury:
				if (cv2.arcLength(kontur, True) > 900):
					x, y, w, h = cv2.boundingRect(kontur)
					#cv2.rectangle(obraz, (x, y), (x + w, y + h), (255,0,0), 5)
					#cv2.imshow('o',obraz)

					self.obrót_szachownicy(obraz, x, y, w, h)

		while (True):#pętla programu

			ret, obraz = cap.read()
			if ret:
				obraz = self.skalowanie_ekranu(obraz, 0.6)
				gray = cv2.cvtColor(obraz, cv2.COLOR_BGR2GRAY)
				thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 3)
				_, threshold_otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)
				morfo = cv2.morphologyEx(threshold_otsu, cv2.MORPH_ERODE, np.ones((7,7), np.uint8))
				kontury, hierarchia = cv2.findContours(morfo, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

				self.rozpoznanie_bierki(kontury, obraz.copy(), thresh.copy())

				if cv2.waitKey(1) and 0xFF == ord('q'):
					break
			else:
				break
	cv2.destroyAllWindows()

program = Szachy()
program.start()


class Assembler:

    def __init__(self):
        self.ic = 0  # instruction counter
        self.arr1 = []  # stores instructions
        self.result = []

    def start(self):
        x = ""
        while self.ic < 16:
            print(self.ic, end='')
            print(' ', end='')
            x = input()
            self.ic = self.ic + 1
            if x == 'quit':
                break
            else:
                self.arr1.append(x)

        self.assemble()

    def assemble(self):
        self.result = []
        for i in self.arr1:
            tmp = i.split()
            if len(tmp) == 0:
                op = 'NOP'
                addr = 0

            elif len(tmp) == 1:
                op = tmp[0]
                addr = 0

            else:
                op = tmp[0]
                addr = int(tmp[1])

            if op == 'NOP':
                op = hex(0)
                self.result.append(op)

            elif op == 'LDA':
                op = 0b00010000
                op = hex(op | addr)
                self.result.append(op)

            elif op == 'ADD':
                op = 0b00100000
                op = hex(op | addr)
                self.result.append(op)

            elif op == 'SUB':
                op = 0b00110000
                op = hex(op | addr)
                self.result.append(op)

            elif op == 'STA':
                op = 0b01000000
                op = hex(op | addr)
                self.result.append(op)

            elif op == 'LDI':
                op = 0b01010000
                op = hex(op | addr)
                self.result.append(op)

            elif op == 'JMP':
                op = 0b01100000
                op = hex(op | addr)
                self.result.append(op)

            elif op == 'JC':
                op = 0b01110000
                op = hex(op | addr)
                self.result.append(op)

            elif op == 'JZ':
                op = 0b10000000
                op = hex(op | addr)
                self.result.append(op)

            elif op == 'OUT':
                op = 0b11100000
                op = hex(op | addr)
                self.result.append(op)

            elif op == 'HLT':
                op = 0b11110000
                op = hex(op | addr)
                self.result.append(op)

            else:
                try:
                    op = hex(int(op) % 256)
                    self.result.append(op)
                except Exception as inst:
                    pass

        for idx, val in enumerate(self.result):
            self.result[idx] = int(val, 16)
        #self.out_code()

def out_code(self):
    print("Successfully assembled!")
    for i in self.result:
        print(i)
    print("----------------------")

class Process:
    def __init__(self):
        self.ar = Assembler()
        # self.ar.start()
        self.mem = self.ar.result
        # self.mem=[0]*16
        # for i in range(len(self.mem)):
        #    self.mem[i] = int(self.mem[i], 16)
        self.curadr = 0  # address register, current ram address. I
        self.instreg = 0  # I/O
        self.accum = 0  # I/O
        self.breg = 0  # I
        self.lcd = 0  # I
        self.pc = 0  # I(j)/O
        self.zflag = 0  # C
        self.cflag = 0  # C
        self.sumreg = 0  # O
        self.step = 0  # keeping track of stages for micro-op
        self.inp = [1, 0, 0, 0, 0, 0, 0]  # MI,RI,II,AI,BI,OI,J
        self.out = [0, 0, 0, 0, 1]  # RO,IO,AO,EO,CO
        self.ctrl = [0, 0, 0, 0]  # HLT,Sub,CE,FI
        self.bus = 0
        self.switch = 0  # 1 for 2's complement mode

    def clock(self):  # every data processed during a clock cycle. advance everytime called.
        # ALU
        if self.ctrl[1] == 1:
            di = self.accum - self.breg
            if di < 0:
                self.sumreg = (256 - (self.accum - self.breg) % 129) % 256  # this isn't how it works..
            else:
                self.sumreg = self.accum - self.breg
            if self.ctrl[3] == 1:
                self.cflag = 1
                if self.sumreg == 0:
                    self.zflag = 0
        else:
            su = self.accum + self.breg
            self.sumreg = su % 256
            if self.ctrl[3] == 1:
                if su > 255:
                    self.cflag = 1
                else:
                    self.cflag = 0
                if self.sumreg == 0:
                    self.zflag = 1
                else:
                    self.zflag = 0

        # output to bus sequence
        self.bus = self.mem[self.curadr] * self.out[0] + (self.instreg & 0x0F) * self.out[1] + self.accum * self.out[
            2] + self.sumreg * self.out[3] + self.pc * self.out[4]

        # input from bus sequence
        self.curadr += -(self.curadr * self.inp[0]) + (self.bus & 0x0F) * self.inp[0]
        self.mem[self.curadr] += -(self.mem[self.curadr] * self.inp[1]) + self.bus * self.inp[1]
        self.instreg += -(self.instreg * self.inp[2]) + self.bus * self.inp[2]
        self.accum += -(self.accum * self.inp[3]) + self.bus * self.inp[3]
        self.breg += -(self.breg * self.inp[4]) + self.bus * self.inp[4]
        self.lcd += -(self.lcd * self.inp[5]) + self.bus * self.inp[5]
        self.pc += -(self.pc * self.inp[6]) + (self.bus & 0x0F) * self.inp[6]
        # this will set every component to zero except for one getting input! Better solution needed.....

        # program counter
        self.pc = (self.pc + self.ctrl[2]) % 16

        # step advance
        self.step = (self.step + 1) % 5  # if you want to add instruction with more than 5 steps...

        # print output
        self.lcd_out(self.switch)

    def lcd_out(self, mode):  # switch for 2's complement mode
        if mode == 0:
            print("unsigned mode")
            print(self.lcd)

        else:
            print("signed mode")
            if self.lcd < 128:
                print(self.lcd)
            else:
                print(((256 - self.lcd) * -1) % 256)

    def ctrl(self, opcode):
        # 0HLT 1MI 2RI 3RO 4IO 5II 6AI 7AO 8EO 9SU 10BI 11OI 12CE 13CO 14J 15FI
        cword = [0]*16
        # fetch
        if self.step == 0:
            cword[1], cword[13] = 1, 1
        elif self.step == 1:
            # cword = '0001010000001000'
            cword[3], cword[5], cword[12] = 1, 1, 1
        # op specific
        elif self.step == 2:
            if opcode == 0:  # NOP
                # cword = '0000000000000000'
                self.step = 0
                pass
            elif opcode == 1 or 2 or 3 or 4:  # LDA or ADD or SUB or STA
                # cword = '0100100000000000'  # IO|MI
                cword[1], cword[4] = 1, 1
            elif opcode == 5:  # LDI
                cword[4], cword[6] = 1, 1  # IO|AI
                self.step = 0
            elif opcode == 6:  # JMP
                # cword = '0100000000000010'
                cword[1], cword[14] = 1, 1
                self.step = 0
            elif opcode == 14:  # OUT
                # cword = '0000000100010000'  # AO|OI
                cword[7], cword[11] = 1, 1
            elif opcode == 15:
                cword[0] = 1
                self.step = 0
        elif self.step == 3:
            if opcode == 1:  # LDA
                cword[3], cword[6] = 1, 1  # RO|AI
            elif opcode == 2 or 3:  # ADD or SUB
                cword[3], cword[10] = 1, 1  # RO|BI
            elif opcode == 4:  # STA
                cword[2], cword[7] = 1, 1  # RI|AO
        elif self.step == 4:
            if opcode == 2:  # ADD
                opcode[6], opcode[8], opcode[15] = 1, 1, 1
                self.step = 0
            elif opcode == 3:  # SUB
                opcode[6], opcode[8], opcode[9], opcode[15] = 1, 1, 1, 1
                self.step = 0
        return cword


import pymysql
from tkinter import *
from time import strftime
from tkinter import messagebox
from PIL import ImageTk, Image

window = Tk()
window.configure(background='red')
window.geometry("1000x700")
window.wm_title("Pizza Shop")

img = ImageTk.PhotoImage(Image.open("pizza.png"))
panel = Label(window, image = img,bg='light blue',height=120,width=200)
panel.place(x=10, y=10)

global total_p

pizza_var = 0
Largepizza_var = 0
cheesepizza_var = 0
nonvegpizza_var = 0
deluxeveggie_var= 0

total_p=0
p1=145
p2=170
p3=160
p4=165
p5=180

#The time function
def time():

    string1 = strftime('%H:%M:%S %p')
    lbl.config(text = string1)
    lbl.after(1000, time)

lbl = Label(window, font = ('calibri', 20, 'bold'),background = 'blue',foreground = 'white')

lbl.place(x=350,y=80)

time()

def create_window():

    new_window = Toplevel(window)
    new_window.configure(background='light blue')

    customer_name=Label(new_window,font=15,text="Customer Name:  "+ str (e_name.get())).pack()
    customer_phone=Label(new_window,font=15,text="Customer Phone:  "+str (e_phone.get())).pack()
    tp=Label(new_window,font=15,text="Total Price:  "+ str(total_p)).pack()

    confirm=Button(new_window,text="Done",bg="green",fg="white",command=new_window.destroy,height=2,width=10).pack()
    new_window.geometry("500x150")

#headind

pizza_shop=Label(window,bg="light blue", text = 'Pizza Shop', font =('Verdana', 30))
pizza_shop.pack(side = TOP, pady = 10)

def quantity_1():
    global pizza_var

    pizza_var += 1
    e1['text'] = "Quantity: " + str(pizza_var )

def quantity_2():
    global Largepizza_var

    Largepizza_var += 1
    e2['text'] = "Quantity: " + str(Largepizza_var)

def quantity_3():
    global cheesepizza_var

    cheesepizza_var += 1
    e3['text'] = "Quantity: " + str(cheesepizza_var)

def quantity_4():
    global nonvegpizza_var

    nonvegpizza_var += 1
    e4['text'] = "Quantity: " + str(nonvegpizza_var)

def quantity_5():
    global deluxeveggie_var

    deluxeveggie_var += 1
    e5['text'] = "Quantity: " + str(deluxeveggie_var)

def total_price():
    global total_p
    global p1
    global p2
    global p3
    global p4
    global p5
    p1=(p1*pizza_var)
    p2=(p2*Largepizza_var)
    p3=(p3*cheesepizza_var)
    p4=(p4*nonvegpizza_var)
    p5=(p5*deluxeveggie_var)
    total_p=(p1+p2+p3+p4+p5)
    etotal['text'] = "Total: " + str(total_p)

def insert():
    global total_p
    con=pymysql.connect(host="localhost",user="root",password="",database="pizza")
    cursor=con.cursor()

    cursor.execute('INSERT INTO `order1` VALUES (%s,%s,%s)', (e_name.get(),e_phone.get(),e_tol.get()))

    sucess=Label(text="Data Inserted Into the Database Successfully!",bg='light green')
    sucess.place(x=650,y=125)

    con.commit()
# Creating a photoimage object to use image
photo1 = PhotoImage(file = r"veg_pizza.png")
photo2 = PhotoImage(file = r"Large_pizza.png")
photo3 = PhotoImage(file = r"cheese_pizza.png")
photo4 = PhotoImage(file = r"non_pizza.png")
photo5 = PhotoImage(file = r"deluxe_veggie.png")
#Pizza images

veg_pizza_b1=Button(window,bg="light blue",image = photo1,height=180,width=200,bd=4,command=quantity_1,activeforeground = "blue",activebackground = "green",border="0")
veg_pizza_b1.place(x=10,y=150)

Large_pizza_b2=Button(window,bg="light blue", image = photo2,height=180,width=200,bd=4,command=quantity_2,activeforeground = "blue",activebackground = "blue",border="0")
Large_pizza_b2.place(x=400,y=150)

cheese_pizza_b3=Button(window,bg="light blue", image = photo3,height=180,width=200,bd=4,command=quantity_3,activeforeground = "blue",activebackground = "red",border="0")
cheese_pizza_b3.place(x=10,y=380)

non_pizza_b4=Button(window,bg="light blue", image = photo4,height=180,width=200,bd=4,command=quantity_4,activeforeground = "blue",activebackground = "yellow",border="0")
non_pizza_b4.place(x=400,y=380)

deluxe_veggie_b5=Button(window,bg="light blue", image = photo5,height=180,width=200,bd=4,command=quantity_5,activeforeground ="blue",activebackground ="green",border="0")
deluxe_veggie_b5.place(x=780,y=150)
#total Button
b_order=Button(window, text="Order",bg="blue",height=3,width=12,command=create_window,fg="white")
b_order.place(x=500,y=600)
b_close=Button(window, text="Close",height=3,width=12,command=window.destroy,bg="blue",fg="white")
b_close.place(x=650,y=600)
b_total=Button(window, text="Total",height=4,width=10,command=total_price,bg="blue",fg="white")
b_total.place(x=150,y=600)

#total amount displayed
etotal=Label(window,width=20,height=4)
etotal.place(x=270,y=600)

# Creating entries

e1=Label(window,width=15)
e1.place(x=230,y=210,height=50)

l1=Label(window,text="Price: 145",bg="yellow")
l1.place(x=270,y=280)

l2=Label(window,text="Veg Pizza",bg="yellow")
l2.place(x=270,y=310)

e2=Label(window,width=15)
e2.place(x=620,y=210,height=50)

l3=Label(window,text="Price: 170",bg="yellow")
l3.place(x=630,y=280)

l4=Label(window,text="Large Pizza",bg="yellow")
l4.place(x=630,y=310)

e3=Label(window,width=15)
e3.place(x=230,y=430,height=50)

l5=Label(window,text="Price: 160",bg="yellow")
l5.place(x=270,y=500)

l6=Label(window,text="cheese Pizza",bg="yellow")
l6.place(x=270,y=530)

e4=Label(window,width=15)
e4.place(x=620,y=430,height=50)

l7=Label(window,text="Price: 165",bg="yellow")
l7.place(x=630,y=500)

l8=Label(window,text="Non-Veg Pizza",bg="yellow")
l8.place(x=630,y=530)

e5=Label(window,width=15)
e5.place(x=820,y=350,height=50)

l9=Label(window,text="Price: 180",bg="yellow")
l9.place(x=820,y=410)

l10=Label(window,text="Deluxe veggie",bg="yellow")
l10.place(x=820,y=440)
#insert function

name=Label(window,text="Name:")
name.place(x=650,y=10)

e_name=Entry(window)
e_name.place(x=700,y=10)

phone=Label(window,text="Phone:")
phone.place(x=650,y=40)

e_phone=Entry(window)
e_phone.place(x=700,y=40)

total=Label(window,text="Total:")
total.place(x=650,y=70)

e_tol=Entry(window)
e_tol.place(x=700,y=70)

b_insert=Button(window,text="Submit",command=insert)
b_insert.place(x=720,y=95)

mainloop()


import random

import cocotb
from cocotb.clock import Clock
from cocotb.triggers import Timer, RisingEdge, ReadOnly
from cocotb.binary import BinaryValue

import wd_cocotil

@cocotb.test()
async def test(dut):

    dut.i_v = 0
    dut.o_r = 0
    dut.max_pending = 100

    q_i_sha_modq_meta = list()
    q_o_sha_modq_meta = dict()

    clk = dut.clk
    await cocotb.start(Clock(dut.clk, 1, 'ns').start())
    await cocotb.start(wd_cocotil.toggle_reset(dut.clk, dut.rst, 32, active_high=True))
    await cocotb.start(wd_cocotil.random_toggle(dut.clk, dut.o_r, 50))
    await cocotb.start(wd_cocotil.mon_sha_modq_meta(dut, dut, clk, q_i=q_i_sha_modq_meta, q_o=q_o_sha_modq_meta, do_log=True))

    M = int(dut.META_W)

    # wait for xpm post reset
    # then wait more for key-store to initialize
    for i in range(1024+1024):
        await RisingEdge(clk)

    min_l = 0
    max_l = 1280
    mlens = list()

    tid = wd_cocotil.random_int(64)

    for _ in range(max_l * 2):

        # backpressured
        while str(dut.i_v) == '1' and str(dut.i_r) != '1':
            await RisingEdge(clk)

        tid += 1

        # random gap
        while random.randint(0, 100) > 50:
            dut.i_v = 0
            await RisingEdge(clk)

        if len(mlens) == 0:
            mlens = list(range(min_l, max_l+1))
        mlen = random.choice(mlens)
        mlens.remove(mlen)

        tr = wd_cocotil.random_tr(
            tid = tid,
            mlen = mlen,
            sha_modq_meta = wd_cocotil.random_int(M)
        )

        q_i_sha_modq_meta.append(tr)
        q_o_sha_modq_meta[tr['tid']] = tr

        blks = wd_cocotil.build_sha_modq_meta_i(tr)
        for f, l, c, t, m, d in blks:

            # backpressured
            while str(dut.i_v) == '1' and str(dut.i_r) != '1':
                await RisingEdge(clk)

            b_m = BinaryValue(bits=M, bigEndian=False)
            b_d = BinaryValue(bits=1024, bigEndian=False)
            b_m[M-1:0] = m
            b_d[1023:0] = d
            dut.i_v = 1
            dut.i_f = f
            dut.i_l = l
            dut.i_c = c
            dut.i_t = t
            dut.i_m = b_m
            dut.i_d = b_d

            await RisingEdge(clk)

    while True:
        if len(q_o_sha_modq_meta) == 0:
            break
        await RisingEdge(clk)


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

from datetime import datetime as dt
import json
from os import listdir
from os.path import dirname
from os.path import join
from tws_equities.tws_clients import extractor
from tws_equities.tws_clients import extract_historical_data
from tws_equities.data_files import create_csv_dump
from tws_equities.settings import CACHE_DIR
from tws_equities.settings import HISTORICAL_DATA_STORAGE
from tws_equities.settings import MONTH_MAP
import pytest

"""
    HistoricalDataExtractor is a TWS Client that extracts data from the API
    and stores it in a dictionary using input ticker ID(s) as keys.
    "extractor" method is a much easier to use wrapper around the same and
    this module tries to test it's functionality on high-level.

    Here's how you can trigger these tests:
        - Simple run: Trigger all tests
            - pytest tests/tws_clients_tests.py
        - Parameterized Run: Trigger specific tests
            - pytest tests/tws_clients_tests.py -m positive
            - pytest tests/tws_clients_tests.py -m negative

    NOTE:
        - Tests are marked as positive and negative inside the module.
        - Custom grouping can be done by specifying new groups inside "pytest.ini".
"""
# TODO: include tests for bar timestamps

_PROJECT_ROOT = dirname(dirname(__file__))
_HISTORICAL_DATA = join(_PROJECT_ROOT, 'historical_data')
positive_test_tickers = [1301, 5386, 7203]
negative_test_tickers = [1743, 3437, 4628, 1234]

date_format = r'%Y%m%d'
end_date = dt.today().date().strftime(date_format)  # current date
end_time = '09:01:00'  # after market close
bar_size = '1 min'

def validate_bar_data(data, ticker):
    bar_keys = ['average', 'close', 'count', 'high', 'low', 'open', 'session', 'time_stamp', 'volume']
    for bar in data:
        assert isinstance(bar, dict), f'Found invalid bar data for ticker: {ticker}'
        assert bar_keys == sorted(list(bar.keys())), f'Found invalid keys in bar data for ticker: {ticker}'
        average, close, count, high, low = bar['average'], bar['close'], bar['count'], bar['high'], bar['low']
        open_, session, time_stamp, volume = bar['open'], bar['session'], bar['time_stamp'], bar['volume']
        assert isinstance(average, float), 'Average value in bar is not a float.'
        assert isinstance(close, float), 'Close value in bar is not a float.'
        assert isinstance(count, int), 'Count value in bar is not a int.'
        assert isinstance(high, float), 'High value in bar is not a float.'
        assert isinstance(low, float), 'Low value in bar is not a float.'
        assert isinstance(open_, float), 'Open value in bar is not a float.'
        assert isinstance(session, int), 'Session value in bar is not a int.'
        assert session in [1, 2], 'Session value is invalid'
        assert isinstance(time_stamp, str), 'Timestamp value in bar is not a str.'
        assert isinstance(volume, int), 'Volume value in bar is not a int.'

def validate_meta_data(data, ticker):
    meta_keys = ['_error_stack', 'attempts', 'ecode', 'end', 'start', 'status', 'total_bars']
    assert sorted(data.keys()) == meta_keys, 'Meta data has bad keys.'
    error_stack, attempts, ecode = data['_error_stack'], data['attempts'], data['ecode']
    end, start, status, total_bars = data['end'], data['start'], data['status'], data['total_bars']
    assert isinstance(error_stack, list), 'Error stack is not a list'
    assert isinstance(attempts, int), 'Attempts value is not int'
    assert 0 < attempts <= 3, 'Invalid value for number of attempts.'
    assert isinstance(ecode, int), 'Ecode is not an integer.'
    assert ecode == ticker, 'Ecode is not equal to given ticker ID'
    assert isinstance(status, bool), 'Status value is not a boolean.'
    assert isinstance(total_bars, int), 'Total bars value is not an integer.'

    if status:
        assert isinstance(end, str), 'End value is not a string.'
        assert isinstance(start, str), 'Start value is not a string.'

    if not status:
        error_keys = ['code', 'message']
        for error in error_stack:
            assert isinstance(error, dict), 'Error object is not a dictonary.'
            assert sorted(error.keys()) == error_keys, 'Invalid error keys.'

def validate_data_positive(input_tickers, extracted_data):
    assert isinstance(extracted_data, dict), 'Extracted data is not a dictionary.'
    assert all(ticker in input_tickers for ticker in extracted_data.keys()), 'Extracted data does not ' \
                                                                             'contain all the tickers.'
    for ticker, data in extracted_data.items():
        assert 'bar_data' in data, f'Bar data has not been extracted for ticker: {ticker}'
        assert 'meta_data' in data, f'Meta data not available for ticker: {ticker}'
        bar_data = data['bar_data']
        assert isinstance(bar_data, list), f'Bar data is not a list for ticker: {ticker}'
        validate_bar_data(bar_data, ticker)

def validate_data_negative(input_tickers, extracted_data):
    assert isinstance(extracted_data, dict), 'Extracted data is not a dictionary.'
    assert all(ticker in input_tickers for ticker in extracted_data.keys()), 'Extracted data does not ' \
                                                                             'contain all the tickers.'
    for ticker, data in extracted_data.items():
        assert 'bar_data' in data, f'Bar data has not been extracted for ticker: {ticker}'
        assert 'meta_data' in data, f'Meta data not available for ticker: {ticker}'
        meta_data = data['meta_data']
        assert isinstance(meta_data, dict), f'Meta data is not a dictionary for ticker: {ticker}'
        validate_meta_data(meta_data, ticker)

def validate_data_caching_positive(input_tickers):
    target_path = join(CACHE_DIR, bar_size.replace(' ', ''), end_date, end_time.replace(':', '_'), 'success')
    cached_files = listdir(target_path)
    cached_ticker_ids = list(map(lambda x: int(x.split('.')[0]), cached_files))
    assert all(x in input_tickers for x in cached_ticker_ids), 'Not all tickers have been cached properly.'
    for ticker in cached_ticker_ids:
        file_path = join(target_path, f'{ticker}.json')
        with open(file_path, 'r') as f:
            data = json.loads(f.read())
            validate_bar_data(data['bar_data'], ticker)
            validate_meta_data(data['meta_data'], ticker)

@pytest.mark.positive
def test_extractor_positive():
    positive_data = extractor(positive_test_tickers, end_date, end_time=end_time)
    validate_data_positive(positive_test_tickers, positive_data)

@pytest.mark.negative
def test_extractor_negative():
    negative_data = extractor(negative_test_tickers, end_date, end_time=end_time)
    validate_data_negative(negative_test_tickers, negative_data)

@pytest.mark.positive
def test_data_caching_positive():
    extract_historical_data(tickers=positive_test_tickers,
                            end_date=end_date,
                            end_time=end_time,
                            bar_size=bar_size)
    validate_data_caching_positive(positive_test_tickers)

@pytest.mark.positive
def test_csv_creation_positive():
    create_csv_dump(end_date, end_time=end_time, bar_size=bar_size)
    target_directory = join(HISTORICAL_DATA_STORAGE, bar_size.replace(' ', ''),
                            end_date[:4], MONTH_MAP[int(end_date[4:6])], end_date)
    assert 'success.csv' in listdir(target_directory), f'success.csv was not created at: {target_directory}'
    # TODO: add more tests for success file


r"""Train Onsets and Frames piano transcription model."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import functools
import os

from magenta.models.onsets_frames_transcription import configs
from magenta.models.onsets_frames_transcription import data
from magenta.models.onsets_frames_transcription import train_util

import tensorflow.compat.v1 as tf

FLAGS = tf.app.flags.FLAGS

tf.app.flags.DEFINE_string('master', '',
                           'Name of the TensorFlow runtime to use.')
tf.app.flags.DEFINE_string('tpu_cluster', None,
                           'Name of the TPU Cluster to use.')
tf.app.flags.DEFINE_string('config', 'onsets_frames',
                           'Name of the config to use.')
tf.app.flags.DEFINE_string(
    'examples_path', None,
    'Path to a TFRecord file of train/eval examples.')
tf.app.flags.DEFINE_boolean(
    'preprocess_examples', True,
    'Whether to preprocess examples or assume they have already been '
    'preprocessed.')
tf.app.flags.DEFINE_string(
    'model_dir', '~/tmp/onsets_frames',
    'Path where checkpoints and summary events will be located during '
    'training and evaluation.')
tf.app.flags.DEFINE_string(
    'warm_start_from', None,
    'Optional string filepath to a checkpoint,  then all variables are '
    'warm-started during training')
tf.app.flags.DEFINE_string('eval_name', None, 'Name for this eval run.')
tf.app.flags.DEFINE_integer('num_steps', 1000000,
                            'Number of training steps or `None` for infinite.')
tf.app.flags.DEFINE_integer(
    'eval_num_steps', None,
    'Number of eval steps or `None` to go through all examples.')
tf.app.flags.DEFINE_integer(
    'keep_checkpoint_max', 100,
    'Maximum number of checkpoints to keep in `train` mode or 0 for infinite.')
tf.app.flags.DEFINE_string(
    'hparams', '',
    'A comma-separated list of `name=value` hyperparameter values.')
tf.app.flags.DEFINE_boolean('use_tpu', False,
                            'Whether training will happen on a TPU.')
tf.app.flags.DEFINE_enum('mode', 'train', ['train', 'eval'],
                         'Which mode to use.')
tf.app.flags.DEFINE_string(
    'log', 'INFO',
    'The threshold for what messages will be logged: '
    'DEBUG, INFO, WARN, ERROR, or FATAL.')

def run(config_map, data_fn, additional_trial_info):
  """Run training or evaluation."""
  tf.logging.set_verbosity(FLAGS.log)

  config = config_map[FLAGS.config]
  model_dir = os.path.expanduser(FLAGS.model_dir)

  hparams = config.hparams

  # Command line flags override any of the preceding hyperparameter values.
  hparams.parse(FLAGS.hparams)

  if FLAGS.mode == 'train':
    train_util.train(
        model_fn=config.model_fn,
        data_fn=data_fn,
        additional_trial_info=additional_trial_info,
        master=FLAGS.master,
        tpu_cluster=FLAGS.tpu_cluster,
        model_dir=model_dir,
        use_tpu=FLAGS.use_tpu,
        preprocess_examples=FLAGS.preprocess_examples,
        hparams=hparams,
        keep_checkpoint_max=FLAGS.keep_checkpoint_max,
        num_steps=FLAGS.num_steps,
        warm_start_from=FLAGS.warm_start_from
    )
  elif FLAGS.mode == 'eval':
    train_util.evaluate(
        model_fn=config.model_fn,
        data_fn=data_fn,
        additional_trial_info=additional_trial_info,
        master=FLAGS.master,
        model_dir=model_dir,
        name=FLAGS.eval_name,
        preprocess_examples=FLAGS.preprocess_examples,
        hparams=hparams,
        num_steps=FLAGS.eval_num_steps)
  else:
    raise ValueError('Unknown/unsupported mode: %s' % FLAGS.mode)

def main(argv):
  del argv
  tf.app.flags.mark_flags_as_required(['examples_path'])
  data_fn = functools.partial(data.provide_batch, examples=FLAGS.examples_path)
  additional_trial_info = {'examples_path': FLAGS.examples_path}
  run(config_map=configs.CONFIG_MAP, data_fn=data_fn,
      additional_trial_info=additional_trial_info)

def console_entry_point():
  tf.disable_v2_behavior()
  tf.app.run(main)

if __name__ == '__main__':
  console_entry_point()


# numpy provide trigonometric ufunc sin(), cos(), tan()
# that takes values in radians and produce corresponding sin, cos, tan values
import numpy as np
x = np.sin(np.pi/2)            # np.sin function does operation sin() on values in array
print(x)

y = np.array([np.pi/2, np.pi/3, np.pi/4, np.pi/5])
z = np.sin(y)                  # putting whole array in sin() function
print(z)

a = np.array([360, 540, 720, 900])
b = np.deg2rad(a)                      # converting degree values to radian
print(b)

c = np.array([1, 2, 3, 4])
d = np.rad2deg(c)                      # converting radian values to degree
print(d)

e = np.array([1.0, 0.1, 1, -1])                     # converting sin, cos, tan values into radian values
f = np.arcsin(e)
print(f)

base = 3
perp = 4
h = np.hypot(base, perp)                     # finding hypotenuse length of pythagoras triangle
print(h)

Python/Numpy/numpy 41 - ufunc trigonometric function.py


class Game:

    def __init__(self, game_id, player1, player2):
        self.game_id = game_id
        self.player1 = player1
        self.player2 = player2
        self.board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
        self.turn = 1
        self.winner = 0

    def __str__(self):
        return f"Game({self.game_id}, {self.player1}, {self.player2})"

    def __repr__(self):
        return f"Game({self.game_id}, {self.player1}, {self.player2})"

    def hand(self, p1, p2):

        p1_recv = p1.connection.recv(1024).decode()
        p2_recv = p2.connection.recv(1024).decode()

        if p1_recv == 'N1':
            self.put('N1')
        if p1_recv == 'S1':
            self.put('S1')
        if p1_recv == 'W1':
            self.put('W1')
        if p1_recv == 'E1':
            self.put('E1')
        if p1_recv == 'NW1':
            self.put('NW1')
        if p1_recv == 'SW1':
            self.put('SW1')
        if p1_recv == 'NE1':
            self.put('NE1')
        if p1_recv == 'SE1':
            self.put('SE1')
        if p1_recv == 'C1':
            self.put('C1')
        if p1_recv == 'win1 ?':
            self.win('win1 ?')

        if p2_recv == 'N2':
            self.put('N2')
        if p2_recv == 'S2':
            self.put('S2')
        if p2_recv == 'W2':
            self.put('W2')
        if p2_recv == 'E2':
            self.put('E2')
        if p2_recv == 'NW2':
            self.put('NW2')
        if p2_recv == 'SW2':
            self.put('SW2')
        if p2_recv == 'NE2':
            self.put('NE2')
        if p2_recv == 'SE2':
            self.put('SE2')
        if p2_recv == 'C2':
            self.put('C2')
        if p2_recv == 'win2 ?':
            self.win('win2 ?')

    def put(self, bt):

        if bt == 'N1':
            self.board[0][1] = self.player1.button
            self.show(self.player1.connection)
        if bt == 'N2':
            self.board[0][1] = self.player2.button
            self.show(self.player2.connection)

        if bt == 'S1':
            self.board[2][1] = self.player1.button
            self.show(self.player1.connection)
        if bt == 'S2':
            self.board[2][1] = self.player2.button
            self.show(self.player2.connection)

        if bt == 'W1':
            self.board[1][0] = self.player1.button
            self.show(self.player1.connection)
        if bt == 'W2':
            self.board[1][0] = self.player2.button
            self.show(self.player2.connection)

        if bt == 'E1':
            self.board[1][2] = self.player1.button
            self.show(self.player1.connection)
        if bt == 'E2':
            self.board[1][2] = self.player2.button
            self.show(self.player2.connection)

        if bt == 'NW1':
            self.board[0][0] = self.player1.button
            self.show(self.player1.connection)
        if bt == 'NW2':
            self.board[0][0] = self.player2.button
            self.show(self.player2.connection)

        if bt == 'SW1':
            self.board[2][0] = self.player1.button
            self.show(self.player1.connection)
        if bt == 'SW2':
            self.board[2][0] = self.player2.button
            self.show(self.player2.connection)

        if bt == 'NE1':
            self.board[0][2] = self.player1.button
            self.show(self.player1.connection)
        if bt == 'NE2':
            self.board[0][2] = self.player2.button
            self.show(self.player2.connection)

        if bt == 'SE1':
            self.board[2][2] = self.player1.button
            self.show(self.player1.connection)
        if bt == 'SE2':
            self.board[2][2] = self.player2.button
            self.show(self.player2.connection)

        if bt == 'C1':
            self.board[1][1] = self.player1.button
            self.show(self.player1.connection)
        if bt == 'C2':
            self.board[1][1] = self.player2.button
            self.show(self.player2.connection)

    def show(self, conn):
        b1 = self.board[0][0]
        b2 = self.board[0][1]
        b3 = self.board[0][2]
        b4 = self.board[1][0]
        b5 = self.board[1][1]
        b6 = self.board[1][2]
        b7 = self.board[2][0]
        b8 = self.board[2][1]
        b9 = self.board[2][2]
        displaying = '\n {} | {} | {} \n ---------- \n {} | {} | {} \n ---------- \n {} | {} | {} \n'.format(b1, b2, b3, b4, b5, b6, b7, b8, b9)
        conn.send(displaying.encode())

    def win(self, msg):
        b1 = self.board[0][0]
        b2 = self.board[0][1]
        b3 = self.board[0][2]
        b4 = self.board[1][0]
        b5 = self.board[1][1]
        b6 = self.board[1][2]
        b7 = self.board[2][0]
        b8 = self.board[2][1]
        b9 = self.board[2][2]
        if msg == 'win1 ?':
            if (b1 == b2 == b3 and b1 == self.player1.button) or (b4 == b5 == b6 and b4 == self.player1.button) or (b7 == b8 == b9 and b7 == self.player1.button)\
                or (b1 == b5 == b9 and b1 == self.player1.button) or (b3 == b5 == b7 and b3 == self.player1.button) or (b1 == b4 == b7 and b1 == self.player1.button)\
                or (b2 == b5 == b8 and b2 == self.player1.button) or (b3 == b6 == b9 and b3 == self.player1.button):
                self.player1.connection.send('Win1 :) '.encode())

            else:
                self.player1.connection.send('game over1 :( '.encode())

        if msg == 'win2 ?':
            if (b1 == b2 == b3 and b1 == self.player2.button) or (b4 == b5 == b6 and b4 == self.player2.button) or (b7 == b8 == b9 and b7 == self.player2.button) \
                or (b1 == b5 == b9 and b1 == self.player2.button) or (b3 == b5 == b7 and b3 == self.player2.button) or (b1 == b4 == b7 and b1 == self.player2.button) \
                or (b2 == b5 == b8 and b2 == self.player2.button) or (b3 == b6 == b9 and b3 == self.player2.button):
                self.player2.connection.send('Win2 :) '.encode())
            else:
                self.player2.connection.send('game over2 :( '.encode())

            pass


import json
from typing import IO
from io import BytesIO, StringIO
import requests
import os
from flask import abort

class MobSFAdapter:
    def __init__(self,configRepository):
        self.config = configRepository.get()
    def safeRequest(func):
        def wrapper(*args, **kwargs):
            try:
                result = func(*args, **kwargs)
            except requests.exceptions.ConnectionError as e:
                abort(400,description=f"Cannot connect to MobSF API")
            except requests.exceptions.MissingSchema as e:
                abort(400,description="Invalid MobSF API URL")
            return result
        return wrapper
    @safeRequest
    def upload(self,filename:str,file:IO):
        file.seek(0)
        files=[
        ('file',(filename,file,'application/octet-stream'))
        ]
        headers = {'Authorization': self.config['MOBSF_API_KEY']}
        url = self.config['MOBSF_URL']
        response = requests.post(f'{url}/api/v1/upload', files=files,headers=headers)

        if response.status_code == 200:
            print(response.json())
            return response.json()
        else:
            print(response.json())
            abort(response.status_code,description=f'Error sending file to MobSF: {response.status_code} {response.reason}')
    @safeRequest
    def scan(self,hash,scanType,filename):
        headers = {'Authorization': self.config['MOBSF_API_KEY']}
        url = self.config['MOBSF_URL']
        data = {
            "hash":hash,
            "scan_type":scanType,
            "file_name":filename
        }
        response = requests.post(f'{url}/api/v1/scan',data=data,headers=headers)

        if response.status_code == 200:
            return response.content
        else:
            print(response.json())
            abort(response.status_code,description=f'Error scanning file with MobSF: {response.status_code} {response.reason}')
    @safeRequest
    def getPDFReport(self,hash):
        url = self.config['MOBSF_URL']
        headers = {'Authorization': self.config['MOBSF_API_KEY']}
        response = requests.post(f'{url}/api/v1/download_pdf',data={
            "hash":hash,
        },headers=headers)
        if response.status_code == 200:
            return BytesIO(response.content)
        else:
            print(response.json())
            abort(response.status_code,description=f'Error getting report from MobSF: {response.status_code} {response.reason}')


# -*- coding:utf-8 -*-
# DQN homework.
import os
import sys
import gym
import pylab
import random
import numpy as np
from collections import deque
from keras.layers import Dense
from keras.optimizers import Adam
from keras.models import Sequential
from gym import wrappers
from utils import *
import math

# hyper-parameter.
EPISODES = 5000

class SumTree:
    def __init__(self, capacity):
        # sum tree 能存储的最多优先级个数
        self.capacity = capacity
        # 顺序表存储二叉树
        self.tree = [0] * (2 * capacity - 1)
        # 每个优先级所对应的经验片段
        self.data = [None] * capacity
        self.size = 0
        self.curr_point = 0

    # 添加一个节点数据，默认优先级为当前的最大优先级+1
    def add(self, data):
        self.data[self.curr_point] = data
        #这是计算新进来的经验的优先级吗？这后面什么意思呀没有动
        #噢 好像就是如果是新加入的一个经验把优先级设置到最大以便每一个经验都被抽到一遍呢
        self.update(self.curr_point, max(self.tree[self.capacity - 1:self.capacity + self.size]) + 1)

        self.curr_point += 1
        if self.curr_point >= self.capacity:
            self.curr_point = 0

        if self.size < self.capacity:
            self.size += 1

    # 更新一个节点的优先级权重
    def update(self, point, weight):
        idx = point + self.capacity - 1
        change = weight - self.tree[idx]

        self.tree[idx] = weight

        parent = (idx - 1) // 2
        while parent >= 0:
            self.tree[parent] += change
            parent = (parent - 1) // 2

    def get_total(self):
        return self.tree[0]

    # 获取最小的优先级，在计算重要性比率中使用
    def get_min(self):
        return min(self.tree[self.capacity - 1:self.capacity + self.size - 1])

    # 根据一个权重进行抽样
    def sample(self, v):
        idx = 0
        while idx < self.capacity - 1:
            l_idx = idx * 2 + 1
            r_idx = l_idx + 1
            if self.tree[l_idx] >= v:
                idx = l_idx
            else:
                idx = r_idx
                v = v - self.tree[l_idx]

        point = idx - (self.capacity - 1)
        # 返回抽样得到的 位置，transition信息，该样本的概率
        return self.data[point]#point, self.data[point], self.tree[idx] / self.get_total()

class Memory(object):
    def __init__(self, batch_size, max_size, beta):
        self.batch_size = batch_size  # mini batch大小
        self.max_size = 2 ** math.floor(math.log2(max_size))  # 保证 sum tree 为完全二叉树
        self.beta = beta

        self._sum_tree = SumTree(max_size)

    def store_transition(self, s, a, r, s_, done):
        self._sum_tree.add((s, a, r, s_, done))

    def get_mini_batches(self):
        n_sample = self.batch_size if self._sum_tree.size >= self.batch_size else self._sum_tree.size
        total = self._sum_tree.get_total()

        # 生成 n_sample 个区间
        step = total // n_sample
        points_transitions_probs = []
        # 在每个区间中均匀随机取一个数，并去 sum tree 中采样
        for i in range(n_sample):
            v = np.random.uniform(i * step, (i + 1) * step - 1)
            t = self._sum_tree.sample(v)
            points_transitions_probs.append(t)

        #points, transitions, probs = zip(*points_transitions_probs)

        # 计算重要性比率
       # max_impmortance_ratio = (n_sample * self._sum_tree.get_min()) ** -self.beta
        #importance_ratio = [(n_sample * probs[i]) ** -self.beta / max_impmortance_ratio
                           # for i in range(len(probs))]

        return points_transitions_probs
       # return tuple(np.array(e) for e in zip(*transitions))#points, tuple(np.array(e) for e in zip(*transitions)), importance_ratio
       # return points_transitions_probs
    def update(self, points, td_error):
        for i in range(len(points)):
            self._sum_tree.update(points[i], td_error[i])

class DQNAgent:
    def __init__(self, state_size, action_size):
        # if you want to see MsPacman learning, then change to True
        self.render = False

        # get size of state and action
        self.state_size = state_size
        self.action_size = action_size

        # These are hyper parameters for the DQN
        self.discount_factor = 0.9
        self.learning_rate = 0.02
        self.epsilon = 1.0
        self.epsilon_min = 0.002
        self.epsilon_decay = (self.epsilon-self.epsilon_min) / 5000
        self.batch_size = 128
        self.train_start = 128
        self.beta=0.1
        # create replay memory using deque
        self.maxlen = 25000
        self.memory = Memory(self.batch_size,self.maxlen,self.beta)#deque(maxlen=self.maxlen)

        # create main model
        self.model_target = self.build_model()
        self.model_eval = self.build_model()

    # approximate Q function using Neural Network
    # you can modify the network to get higher reward.
    def build_model(self):
        model = Sequential()
        model.add(Dense(128, input_dim=self.state_size, activation='relu',
                        kernel_initializer='he_uniform'))
        model.add(Dense(32, activation='relu',
                        kernel_initializer='he_uniform'))
        model.add(Dense(self.action_size, activation='linear',
                        kernel_initializer='he_uniform'))
        model.summary()
        model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate))
        return model

    # get action from model using epsilon-greedy policy
    def get_action(self, state):
        if np.random.rand() <= self.epsilon:
            return random.randrange(self.action_size)
        else:
            q_value = self.model_eval.predict(state)
            return np.argmax(q_value[0])

    # save sample <s,a,r,s'> to the replay memory
    def append_sample(self, state, action, reward, next_state, done):
        self.memory.store_transition(state, action, reward, next_state, done)
        # epsilon decay.
        if self.epsilon > self.epsilon_min:
            self.epsilon -= self.epsilon_decay

    # pick samples randomly from replay memory (with batch_size)
    def train_model(self):
        if self.memory._sum_tree.size < self.train_start:
            return
        batch_size = min(self.batch_size, self.memory._sum_tree.size)
        mini_batch = self.memory.get_mini_batches()#random.sample(self.memory, batch_size)
        update_input = np.zeros((batch_size, self.state_size))
        update_target = np.zeros((batch_size, self.state_size))
        action, reward, done = [], [], []

        for i in range(self.batch_size):
            update_input[i] = mini_batch[i][0]
            action.append(mini_batch[i][1])
            reward.append(mini_batch[i][2])
            update_target[i] = mini_batch[i][3]
            done.append(mini_batch[i][4])

        target = self.model_eval.predict(update_input)
        target_val = self.model_target.predict(update_target)

        for i in range(self.batch_size):
            # Q Learning: get maximum Q value at s' from model
            if done[i]:
                target[i][action[i]] = reward[i]
            else:
                target[i][action[i]] = reward[i] + self.discount_factor * (
                    np.amax(target_val[i]))

        # and do the model fit!
        self.model_eval.fit(update_input, target, batch_size=self.batch_size,
                       epochs=1, verbose=0)

    def eval2target(self):
        self.model_target.set_weights(self.model_eval.get_weights())

if __name__ == "__main__":
    # load the gym env
    env = gym.make('MsPacman-ram-v0')
    # set  random seeds to get reproduceable result(recommended)
    set_random_seed(0)
    # get size of state and action from environment
    state_size = env.observation_space.shape[0]
    action_size = env.action_space.n
    # create the agent
    agent = DQNAgent(state_size, action_size)
    # log the training result
    scores, episodes = [], []
    graph_episodes = []
    graph_score = []
    avg_length = 10
    sum_score = 0
    iteration=0

    # train DQN
    for e in range(EPISODES):
        done = False
        score = 0
        state = env.reset()
        state = np.reshape(state, [1, state_size])
        lives = 3
        while not done:
            dead = False
            while not dead:
                # render the gym env
                if agent.render:
                    env.render()
                # get action for the current state
                action=agent.get_action(state)
                # take the action in the gym env, obtain the next state
                next_state, reward, done, info = env.step(action)
                next_state = np.reshape(next_state, [1, state_size])
                # judge if the agent dead
                dead = info['ale.lives']<lives
                lives = info['ale.lives']
                # update score value
                score+=reward
                # save the sample <s, a, r, s'> to the replay memory
                agent.append_sample(state,action,reward,next_state,done)
                # train the evaluation network
                agent.train_model()
                # go to the next state
                state = next_state

            # update the target network after some iterations.
            iteration += 1
            if iteration >= 10:
                iteration = 0
                agent.eval2target()
        # print info and draw the figure.
        if done:
            scores.append(score)
            sum_score += score
            episodes.append(e)
            # plot the reward each episode
            # pylab.plot(episodes, scores, 'b')
            print("episode:", e, "  score:", score, "  memory length:",
                  agent.memory._sum_tree.curr_point   , "  epsilon:", agent.epsilon)
        if e%avg_length == 0:
            graph_episodes.append(e)
            graph_score.append(sum_score / avg_length)
            sum_score = 0
            # plot the reward each avg_length episodes
            pylab.plot(graph_episodes, graph_score, 'r')
            pylab.savefig("./pacman_avg.png")

        # save the network if you want to test it.

HW2 Reinforcement Learning/HW2-2 Reinforcement Learning on Atari Game/atariDQN.py


"""
Ejercicio 2
Escribir una función mas_larga() que tome una lista de palabras y devuelva la mas larga.
"""

def palabraMasLarga(lista: iter) -> str:
    palabraMasLarga = ""
    for palabra in lista:
        if len(palabra) > len(palabraMasLarga):
            palabraMasLarga = palabra
    return palabraMasLarga

palabras = [
    "Una palabrita",
    "Una prueba una moneda",
    "Una palabra muy largaaaaaaaaaaa",
    "Palabra cortita",
    "Otra palabrota",
]
print(f"Palabra más larga: {palabraMasLarga(palabras)}")


import math
import numpy as np
from matplotlib import pyplot as plt

def von_karman(L, D, xarr):
    yarr = np.empty(0)  # Creates an empty array for y values
    zarr = np.zeros(len(xarr))  # Creates an array full of zeros for z axis
    r = D / 2  # Calculates radius
    phis = np.arccos(1 - (2 * xarr / L))  # Used the x array to calculates angles relative to the origin y-axis
    for i in phis:
        y = (r / math.sqrt(math.pi)) * math.sqrt(i - ((math.sin(2 * i)) / 2))  # Calculates y values from angle values
        yarr = np.append(yarr, np.array([y]))  # Appends y values to y array
    arr = [xarr, yarr, zarr]  # Combines all x,y, z arrays to be one matrix
    arr = np.transpose(arr)
    f = open("von_karman_points.dat", 'w')  # Creates/opens point.dat file and saves matrix values inside
    np.savetxt("von_karman_points.dat", arr)
    f.close()

    plt.title("Von Karman Nose Cone")  # Plots nose cone
    plt.xlabel("Length (in)")
    plt.ylabel("Radius (in)")
    plt.plot(xarr, yarr)
    plt.show()

if __name__ == '__main__':
    L = 15  # Input length
    D = 3.12  # Input base diameter
    res = 200  # Resolution of points, small = accuracy

    xarr = np.linspace(0, L, res)  # Generates length array

    von_karman(L, D, xarr)


# Address Matching with k-Nearest Neighbors
#----------------------------------
#
# This function illustrates a way to perform
# address matching between two data sets.
#
# For each test address, we will return the
# closest reference address to it.
#
# We will consider two distance functions:
# 1) Edit distance for street number/name and
# 2) Euclidian distance (L2) for the zip codes

import random
import string
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
ops.reset_default_graph()

# First we generate the data sets we will need
# n = Size of created data sets
n = 10
street_names = ['abbey', 'baker', 'canal', 'donner', 'elm']
street_types = ['rd', 'st', 'ln', 'pass', 'ave']

random.seed(31)  # make results reproducible
rand_zips = [random.randint(65000, 65999) for i in range(5)]

# Function to randomly create one typo in a string w/ a probability
def create_typo(s, prob=0.75):
    if random.uniform(0, 1) < prob:
        rand_ind = random.choice(range(len(s)))
        s_list = list(s)
        s_list[rand_ind] = random.choice(string.ascii_lowercase)
        s = ''.join(s_list)
    return s

# Generate the reference dataset
numbers = [random.randint(1, 9999) for _ in range(n)]
streets = [random.choice(street_names) for _ in range(n)]
street_suffs = [random.choice(street_types) for _ in range(n)]
zips = [random.choice(rand_zips) for _ in range(n)]
full_streets = [str(x) + ' ' + y + ' ' + z for x, y, z in zip(numbers, streets, street_suffs)]
reference_data = [list(x) for x in zip(full_streets,zips)]

# Generate test dataset with some typos
typo_streets = [create_typo(x) for x in streets]
typo_full_streets = [str(x) + ' ' + y + ' ' + z for x, y, z in zip(numbers, typo_streets, street_suffs)]
test_data = [list(x) for x in zip(typo_full_streets, zips)]

# Now we can perform address matching
# Create graph
sess = tf.Session()

# Placeholders
test_address = tf.sparse_placeholder(dtype=tf.string)
test_zip = tf.placeholder(shape=[None, 1], dtype=tf.float32)
ref_address = tf.sparse_placeholder(dtype=tf.string)
ref_zip = tf.placeholder(shape=[None, n], dtype=tf.float32)

# Declare Zip code distance for a test zip and reference set
zip_dist = tf.square(tf.subtract(ref_zip, test_zip))

# Declare Edit distance for address
address_dist = tf.edit_distance(test_address, ref_address, normalize=True)

# Create similarity scores
zip_max = tf.gather(tf.squeeze(zip_dist), tf.argmax(zip_dist, 1))
zip_min = tf.gather(tf.squeeze(zip_dist), tf.argmin(zip_dist, 1))
zip_sim = tf.div(tf.subtract(zip_max, zip_dist), tf.subtract(zip_max, zip_min))
address_sim = tf.subtract(1., address_dist)

# Combine distance functions
address_weight = 0.5
zip_weight = 1. - address_weight
weighted_sim = tf.add(tf.transpose(tf.multiply(address_weight, address_sim)), tf.multiply(zip_weight, zip_sim))

# Predict: Get max similarity entry
top_match_index = tf.argmax(weighted_sim, 1)

# Function to Create a character-sparse tensor from strings
def sparse_from_word_vec(word_vec):
    num_words = len(word_vec)
    indices = [[xi, 0, yi] for xi,x in enumerate(word_vec) for yi,y in enumerate(x)]
    chars = list(''.join(word_vec))
    return tf.SparseTensorValue(indices, chars, [num_words,1,1])

# Loop through test indices
reference_addresses = [x[0] for x in reference_data]
reference_zips = np.array([[x[1] for x in reference_data]])

# Create sparse address reference set
sparse_ref_set = sparse_from_word_vec(reference_addresses)

for i in range(n):
    test_address_entry = test_data[i][0]
    test_zip_entry = [[test_data[i][1]]]

    # Create sparse address vectors
    test_address_repeated = [test_address_entry] * n
    sparse_test_set = sparse_from_word_vec(test_address_repeated)

    feeddict = {test_address: sparse_test_set,
                test_zip: test_zip_entry,
                ref_address: sparse_ref_set,
                ref_zip: reference_zips}
    best_match = sess.run(top_match_index, feed_dict=feeddict)
    best_street = reference_addresses[best_match[0]]
    [best_zip] = reference_zips[0][best_match]
    [[test_zip_]] = test_zip_entry
    print('Address: ' + str(test_address_entry) + ', ' + str(test_zip_))
    print('Match  : ' + str(best_street) + ', ' + str(best_zip))


import DataParser
import time
import random
import csv
from collections import Counter
import pathlib

url = 'https://your-url.com/parameters'

Data = DataParser.dataparser(url)

#Get relevant sales data from the html pasrsing
Title = Data[0]
Price = Data[1]
Size = Data[2]
Brand = Data[3]
Words =  Data[4]

#write sales data to file
with open('FileName.csv', mode='a') as FileName:
    csv_writer = csv.writer(FileName, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    csv_writer.writerow(Title)
    csv_writer.writerow(Price)
    csv_writer.writerow(Size)
    csv_writer.writerow(Brand)

#check to see if the keyword file exists
path = pathlib.Path('FileNameWords.csv')
if path.exists() == True:

#if the keywords file exists, get the data from it
    with open('FileNameWords.csv', newline='') as csvfile:
        reader = csv.reader(csvfile)
        wordFreqDic = {}
        for row in reader:
            if row != []:
                wordFreqDic.update( {row[0] : int(row[1])})

#combine the keywords from the csv file with the ones extracted from the html
    Words =  Counter(Words) + Counter(wordFreqDic)

#write to keyword csv file

csv_writer = csv.writer(open("FileNameWords.csv", 'w'))
for key, val in Words.items():
    csv_writer.writerow([key, val])