Move_the_table=['driving tractor']

Touchear=['passing soccer ball']
LockHands=['playing harp']
Touchhead=['spinning poi']
Touchnose=['eating ice cream']
Rolly_Polly=['juggling fire']
Tapping=['playing maracas']
Arms_Up=['snatch weight lifting']
#LockHands=['playing laser tag',
#'playing trombone']
# 'breathing fire',
# 'tasting beer',
# 'eating burger']
#LockHands=['playing trombone']
#Touchear=['playing ice hockey',
#'blowing bubble gum']
# 'jaywalking',
# 'eating chips',
# 'tasting wine']

#Touchear=['playing ice hockey']
#Touchhead=[]
#Touchhead=['skydiving']
# 'head stand']
# 'sword swallowing',
# 'swinging baseball bat',
# 'combing hair']
#Touchnose=[]
#Touchnose=['putting on eyeliner']
#Touchnose=['disc golfing',
#'putting on eyeliner']
# 'javelin throw',
# 'diving cliff',
# 'ice climbing']
#Move_the_table=[]
#Move_the_table=['riding a bike']
#Move_the_table=['making the bed',
#'riding a bike']
# 'sanding floor',
# 'pushing cart',
# 'riding camel']
#Rolly_Polly=[]
#Rolly_Polly=['playing hand clapping games']
#Rolly_Polly=['playing hand clapping games',
#'playing rubiks cube']
# 'washing hands',
# 'shuffling cards',
# 'making balloon shapes']

#Arms_Up=[]
#Arms_Up=['cartwheeling']
#'cartwheeling']
# 'spinning poi',
# 'roller skating',
# 'standing on hands']
#Tapping=[]
#Tapping=['playing drums']
#Tapping=['playing drums',
#'dribbling basketball']
# 'playing organ',
# 'tapping guitar',
# 'playing xylophone']

# LockHands=['playing harp',
# 'using inhaler',
# 'inflating balloons',
# 'arguing',
# 'decorating the christmas tree']

# Touchear=['sucking lolly',
# 'sled dog racing',
# 'bowling',
# 'eating carrots',
# 'parasailing']

# Touchhead=['blowdrying hair',
# 'using a paint roller',
# 'using a sledge hammer',
# 'stretching leg',
# 'fixing hair']

# Touchnose=['flying kite',
# 'trimming trees',
# 'historical reenactment',
# 'putting on mascara',
# 'auctioning']

# Move_the_table=['falling off bike',
# 'jumping bicycle',
# 'pushing wheelbarrow',
# 'smelling feet',
# 'crawling baby']

# Rolly_Polly=['playing maracas',
# 'punching person (boxing)',
# 'punching bag',
# 'pillow fight',
# 'cracking knuckles']

# Arms_Up=['climbing a rope',
# 'dunking basketball',
# 'pull ups',
# 'front raises',
# 'swinging on something']

# Tapping=['flipping pancake',
# 'playing keyboard',
# 'playing bass guitar',
# 'shucking oysters',
# 'dancing charleston']
c_size=[191,192,117,147,154,121,141,183]
kin_classes =[Move_the_table,Touchear,LockHands,Touchhead,Touchnose,Rolly_Polly,Tapping, Arms_Up]
import random
import pickle
import os
import numpy as np
from random import shuffle
import random

traindata = pickle.load( open( "/DATA/crossval5_8/5050_f_train0.p", "rb" ) )
labeldata = pickle.load( open( "/DATA/crossval5_8/5050_l_train0.p", "rb" ) )
c=0
i=0
kins_traindata=[]
kins_labeldata=[]
n = 3
for folder in kin_classes:
    t=0
    flg=0
    for fld in folder:
        if(flg==1):
                break
        if not os.path.exists("/DATA/kin600/kin600_200samples_argmax_5050_flow_2secs/"+fld):
                continue
        files=os.listdir("/DATA/kin600/kin600_200samples_argmax_5050_flow_2secs/"+fld)
        ls=range(0,len(files))
        indx=random.sample(ls,c_size[kin_classes.index(folder)])
        for j in indx:
        #for file in os.listdir("/DATA/kin600/kin_600_armax_all_data_200samples_flow/"+fld):
        #files = os.listdir("/DATA/kin600/kin600_2sec_flow_agn_80/"+fld)
        #ix = np.random.randint(0,len(files),n)
        #for mx in range(0,n):
            x = "/DATA/kin600/kin600_200samples_argmax_5050_flow_2secs/"+fld+'/'+files[j]
            traindata.append(x)
            kins_traindata.append(x)
            y = np.zeros((1, 8))
            y[0,i]=1
            t=t+1
            c=c+1
            labeldata.append(y)
            kins_labeldata.append(y)
            if(t==20):
                flg=1
                break
            #print(x)
    i=i+1

flow_shuf_train = []
labels_shuf_train = []
index_shuf = [i for i in range(len(labeldata))]
shuffle(index_shuf)
flow_shuf_train = [traindata[i] for i in index_shuf]
#shuffle(index_shuf)
labels_shuf_train = [labeldata[i] for i in index_shuf]

#flow_shuf_train=np.asarray(flow_shuf_train)
#labels_shuf_train = np.asarray(labels_shuf_train)
print(c)
pickle.dump(labels_shuf_train, open("../crossval5_8/aug_l_mm_all_5050_alle"+".p", "wb"))
pickle.dump(flow_shuf_train, open("../crossval5_8/aug_f_mm_all_5050_alle"+".p", "wb"))
pickle.dump(kins_traindata, open("../crossval5_8/f_kins_mm_all_5050_alle"+".p", "wb"))
pickle.dump(kins_labeldata, open("../crossval5_8/l_kins_mm_all_5050_alle"+".p", "wb"))
#pickle.dump(labeldata, open("../crossval5_8/aug_l_all0"+".p", "wb"))
#pickle.dump(traindata, open("../crossval5_8/aug_f_all0"+".p", "wb"))
print("data created ")


import os
import glob
import numpy as np
import cv2

from sklearn .model_selection import train_test_split

def data_split(dir_path, split_range):
    folder_list = os.listdir(dir_path)

    for folder_name in folder_list:
        image_path_list = glob.glob(os.path.join(dir_path, folder_name, '*', '*'))

        if len(image_path_list) > 0:
            train_data, valid_data = train_test_split(image_path_list, test_size=0.1, shuffle=True, random_state=20230113)

            temp_dict = {
                'train': train_data,
                'valid': valid_data
            }

            for task, data in temp_dict.items():
                copy_data(task, data, split_range)
        else:
            print('List is empty!', os.path.join(dir_path, folder_name))

def copy_data(task, data, split_range):
    for index, image_path in enumerate(data):
        gender = 'M' if image_path.split('\\')[-2] == '111' else 'F'

        age_label = image_path.split('\\')[-3]
        temp_num1 = int(age_label) // split_range
        temp_num2 = split_range // 10 - 1
        tenplace = int(split_range * temp_num1 / 10)
        label = '{tensplace1}0-{tenplace2}9_{gender}'.format(
            tensplace1=tenplace, tenplace2=(tenplace + temp_num2), gender=gender)

        dataset_dir_path = os.path.join('../', '{}_age_range_dataset'. format(split_range), task, label)
        os.makedirs(dataset_dir_path, exist_ok=True)

        image_dest_path = os.path.join(dataset_dir_path, '{}_{}.png'.format(label, index))
        image = make_square_image(image_path)

        if image is None:
            print(image_path)
            continue

        cv2.imwrite(image_dest_path, image)

def make_square_image(image_path):
    origin_image = cv2.imread(image_path)

    try:
        height, width, channels = origin_image.shape
    except:
        print(image_path, '#' * 10)
        return

    x = height if height > width else width
    y = height if height > width else width

    if 224 > x and 224 > y:
        x, y = 224, 224

    squre_image = np.zeros((x, y, channels), np.uint8)
    squre_image[int((y - height) / 2):int(y - (y - height) / 2),
                int((x - width) / 2):int(x - (x - width) / 2)] = origin_image

    return squre_image

dir_path = os.path.join('./', 'AFAD-Full')
data_split(dir_path, 10)
print('first done!', '#' * 30)

data_split(dir_path, 20)
print('finish!', '#' * 30)

Classification 문제 해결/2번문제/data split(승현님).py


import os.path
import openfile
import archiver

def display_menu():
    menu_file_status = "File status: no file selected"
    menu_text = "Select an option:\n" \
                "1.Choose file\n" \
                "2.Compress chosen file\n" \
                "3.Decompress chosen file\n" \
                "4.Exit"
    menu_command = "begin"
    while menu_command != "4":
        print(f"\n{menu_file_status} \n{menu_text}")
        menu_command = str(input("Print number of option: "))
        #  Choose file
        if menu_command == "1":
            file_path = str(input("Print file name or file path: "))
            input_data = openfile.check_file(file_path)
            if input_data["file_name"]:
                menu_file_status = "File status: selected " + os.path.abspath(file_path)
        #  Compress chosen file
        elif menu_command == "2":
            if menu_file_status != "File status: no file selected":
                input_data = openfile.read_file(file_path)
                output_string = archiver.zip_string(input_data["read_string"])
                if output_string:
                    output_file_data = openfile.write_file(output_string, input_data["file_name"])
                    compress_ratio = output_file_data["file_size"] / input_data["file_size"] * 100
                    print(f"Compress done, compress ratio: {compress_ratio}%")
            else:
                print("No file selected, zip is not possible")
        #  Decompress chosen file
        elif menu_command == "3":
            if menu_file_status != "File status: no file selected":
                if input_data["file_name"].endswith("compress"):
                    input_data = openfile.read_file(file_path, zipping=False)
                    output_string = archiver.unzip_string(input_data["read_string"])
                    openfile.write_file(output_string, input_data["file_name"], zipping=False)
                    print("Decompress done")
                else:
                    print("File name is wrong, unzip is not possible")
            else:
                print("No file selected, zip is not possible")
    print("Goodbye")


import rclpy
from src.api import NodeManagerClient
from src.verb import VerbExtension

class ListNodesVerb(VerbExtension):
    """List all nodes that are managed by the node manager"""

    def add_arguments(self, parser, cli_name):
        """
        Specify arguments for the list verb
        """
        parser.add_argument("robot_name", help="Name of the robot")

    def main(self, *, args):
        """
        Main
        """
        rclpy.init()
        client = NodeManagerClient()
        print(client.list_nodes(args.robot_name).nodes)


# Бинарный поиск (Binary Search) - это алгоритм поиска элемента в упорядоченном (часто сортированном) списке данных. В отличие от линейного поиска, который проверяет элементы последовательно, бинарный поиск делит список пополам и определяет, в какой половине элемент должен находиться. Затем он сравнивает искомое значение с элементом в середине списка. Если значение меньше элемента в середине, поиск продолжается в левой половине списка; если значение больше, поиск продолжается в правой половине. Процесс деления и сравнения повторяется, пока элемент не будет найден или не будет ясно, что он отсутствует.

# Основные характеристики бинарного поиска:
#     Эффективен для упорядоченных данных.
#     Временная сложность в худшем случае составляет O(log n), где n - количество элементов в списке.
#     Требует предварительной сортировки данных.

# Функция для бинарного поиска в упорядоченном списке
def binary_search(data, target):
    left = 0                            # Устанавливаем начальный индекс левой границы массива
    right = len(data) - 1               # Определение индекса правой границы массива.

    while left <= right:                # Пока левая граница не превышает правую
        center = (left + right) // 2    # Вычисляем средний индекс
        if target == data[center]:      # Если искомое значение найдено в центре
            return f"ID = {center}"     # Возвращаем сообщение с индексом найденного элемента
        if target > data[center]:       # Если значение больше элемента в середине
            left = center + 1           # Сдвигаем левую границу вправо
        else:                           # Иначе значение меньше элемента в середине
            right = center - 1          # Сдвигаем правую границу влево

    else:                               # Если значение не найдено после всех итераций
        return "No value"               # Возвращаем сообщение о том, что значение не найдено

data = [10, 20, 30, 40, 50, 60, 70, 400]
target = 40
print(binary_search(data=data, target=target))

# Ещё одна вариация бинарного поиска
def binary_search(data, target):
    left, right = 0, len(data) - 1                 # Определяем начальные границы поиска (левую и правую)

    while left <= right:                           # Пока левая граница не превышает правую
        mid = (left + right) // 2                  # Вычисляем средний индекс
        if data[mid] == target:                    # Если элемент в середине равен искомому элементу
            return f"Элемент {target} найден по индексу {mid}"  # Возвращаем сообщение о нахождении
        elif data[mid] < target:                   # Если искомый элемент больше элемента в середине
            left = mid + 1                         # Сдвигаем левую границу
        else:                                      # Иначе искомый элемент меньше элемента в середине
            right = mid - 1                        # Сдвигаем правую границу

    return f"Элемент {target} не найден в списке"  # Если элемент не найден, возвращаем сообщение

data = [10, 20, 30, 40, 50, 60, 70, 400]
target = 400

result = binary_search(data, target)
print(result)

# Пояснение:
# Сдвигать левую границу в плюс если искомый элемент больше элемента в середине, а правую сдвигать в минус, если меньше искомого элемента


#!/usr/bin/env python3

import functools
import json
import os
import sys
import collections
import pystache
import click

FieldType = collections.namedtuple('FieldType', ['safe_name', 'name', 'type', 'required'])

@click.command()
@click.option('--output-dir')
@click.option('--input')
@click.option('--templates')
@click.option('--file-suffix')
@click.option('--case')
@click.option('--model')
def main(output_dir, input, templates, file_suffix, case, model=None):
    with open(input) as f:
        content = json.load(f)

    def basedirReducer(init, val):
        if val[1] != 'protos':
            return init
        return val[0]

    if '.' not in file_suffix:
        file_suffix = '.' + file_suffix

    protos_index = functools.reduce(basedirReducer, enumerate(input.split('/')), None)
    basedir = input.split('/')[protos_index+1:-1]
    api_name = input.split('/')[-1].split('.')[0]
    basedir[0] = "_"+basedir[0]
    result_dir = os.path.join(output_dir, *basedir)
    result_package = '.'.join(basedir)

    if model is None:
        model = "model" + file_suffix

    create_models(result_dir, result_package, content, templates, file_suffix, case, model)
    create_api(result_dir, result_package, api_name, content, templates, file_suffix, case)

def create_api(result_dir, result_package, api_name, content, templates, file_suffix, case):
    if 'paths' not in content:
        return

    paths = []
    operations = []
    for path, p_content in content['paths'].items():
        for op, op_content in p_content.items():
            operation_id = op_content['operationId']
            operations.append((operation_id, path+"", op+""))
    operations = sorted(operations, key=lambda x: x[0])

    operations_info = []

    for (operation_id, path, op) in operations:
            op_content = content['paths'][path][op]
            parameters = []
            query = []
            path_components = []
            got_body_parameter = False
            body_type = create_typedef(any=True)
            required = []

            for param_def in op_content.get('parameters', []):
                name = param_def['name']
                safe_name = to_language_case(name.replace('.', '_'), case)
                param = FieldType(safe_name, name, dict(resolve_type(param_def), var_name=safe_name), param_def.get('required', False))
                parameters.append(param)

                if param_def.get('required', False):
                    required.append(parameters[-1])

                if param_def['in'] == 'body':
                    got_body_parameter = True
                    body_type = dict(resolve_type(param_def), var_name=safe_name)
                elif param_def['in'] == 'query':
                    query.append(param)
                elif param_def['in'] == 'path':
                    path = path.replace('{%s}' % name, "$%s" % safe_name)
                else:
                    # print(path)
                    raise ValueError(param_def['in'])

            parameters = sorted(parameters, key=lambda x: (not x.required, x.safe_name))

            # TODO
            success_response = None
            code_mapping = {}
            for code, definition in op_content['responses'].items():
                if code == "200":
                    success_response = resolve_type(definition)
                else:
                    code_mapping[code] = resolve_type(definition)

            operations_info.append({
                'operation_id': operation_id,
                'success_type': success_response,
                'query': [{
                    'name': q.name,
                    'safe_name': q.safe_name,
                    'type': q.type,
                    'required': q.required,
                    'last': i == len(query)-1
                } for i, q in enumerate(query)],
                'body_present': got_body_parameter,
                'body_type': body_type,
                'parameters': [{
                    'name': p.name,
                    'safe_name': p.safe_name,
                    'type': p.type,
                    'required': p.required,
                    'last': i == len(parameters)-1
                } for i, p in enumerate(parameters)],
                'required_parameters': [{
                    'name': q.name,
                    'safe_name': q.safe_name,
                    'type': q.type,
                    'last': i == len(required)-1
                } for i, q in enumerate(required)],
                'op': op.upper(),
                'path': path,
            })

    os.makedirs(os.path.join(result_dir, 'api'), exist_ok=True)

    with open(os.path.join(templates, 'api'+file_suffix)) as f:
        template = f.read()

    info = {
        'package': result_package,
        'api_name': api_name,
        'base_path': content.get('basePath', ''),
        'operations': operations_info,
    }

    with open(os.path.join(result_dir, 'api', api_name+'Api'+file_suffix), 'w') as f:
        f.write(pystache.Renderer(partials=load_partials(templates)).render(template, info))

def load_partials(templates_folder):
    ret = {}
    for _, _, files in os.walk(templates_folder):
        for f in files:
            parts = f.split('.')
            if parts[1] == 'mustache':
                ret[parts[0]] = open(os.path.join(templates_folder, f)).read()

    return ret

def keyword_safe(s):
    if s in ['type']:
        return '`%s`' % s
    return s

def create_models(result_dir, result_package, content, templates, file_suffix, case, model):
    enums = []
    os.makedirs(os.path.join(result_dir, 'model'), exist_ok=True)
    for k, v in content['definitions'].items():
        if 'enum' in v:
            enums.append(capitalize_first(k))

    enums = sorted(enums)
    for k, v in content['definitions'].items():
        create_model(result_dir, result_package, k, v, enums, templates, file_suffix, case, model)
    if len(content['definitions']) == 0:
        filename = os.path.join(result_dir, 'model', 'dummy'+file_suffix)
        with open(filename, 'w') as f:
            f.write('''
// THIS FILE IS AUTO-GENERATED. DO NOT EDIT
package ai.verta.swagger.%s.model
case class dummy()
''' % result_package)

def create_model(result_dir, result_package, definition_name, definition, enums, templates, file_suffix, case, model):
    capitalized_definition_name = capitalize_first(definition_name)
    filename = os.path.join(result_dir, 'model', capitalized_definition_name+file_suffix)

    with open(os.path.join(templates, model)) as f:
        template = f.read()

    required = definition.get('required', list())
    properties = definition.get('properties', dict())
    properties = [{'name': keyword_safe(to_language_case(k, case)),
                   'required': k in required,
                   'type': dict(resolve_type(v), var_name=keyword_safe(to_language_case(k, case)))
                  } for k, v in properties.items()]
    properties = sorted(properties, key=lambda x: x['name'])
    for i, p in enumerate(properties):
        p.update({'last': i == len(properties)-1})

    info = {
        '__object_flag': False,
        '__enum_flag': False,
        'package': result_package,
        'class_name': capitalized_definition_name,
        'properties': properties,
        'object': True,
        'enums': [{'name': e} for e in enums],
        'enum_values': [{'name': e} for e in definition.get('enum', list())],
    }

    type_flag = "__"+definition['type']+"_flag"

    if definition['type'] == 'object':
        info['__object_flag'] = True
    elif 'enum' in definition:
        info['__enum_flag'] = True
    else:
        raise ValueError(definition['type'])

    with open(filename, 'w') as f:
        f.write(pystache.Renderer(partials=load_partials(templates)).render(template, info))

def create_typedef(**kwargs):
    return dict(kwargs, **{
        'is_list': kwargs.get('is_list', False),
        'is_basic': kwargs.get('is_basic', False),
        'is_map': kwargs.get('is_map', False),
        'string': kwargs.get('string', False),
        'integer': kwargs.get('integer', False),
        'long': kwargs.get('long', False),
        'double': kwargs.get('double', False),
        'float': kwargs.get('float', False),
        'any': kwargs.get('any', False),
        'is_custom': kwargs.get('custom', None) is not None,
    })

# TODO: generalize to types besides Scala
def resolve_type(typedef):
    if '$ref' in typedef:
        ref = typedef['$ref'].split('/')[-1]
        return create_typedef(custom={'name': capitalize_first(ref)})

    if 'schema' in typedef:
        return resolve_type(typedef['schema'])

    if typedef['type'] == 'string':
        if 'format' in typedef:
            # TODO: support long?
            if typedef['format'] == 'uint64':
                return create_typedef(long=True, is_basic=True)
            if typedef['format'] == 'int64':
                return create_typedef(long=True, is_basic=True)
        return create_typedef(string=True, is_basic=True)
    elif typedef['type'] == 'boolean':
        return create_typedef(boolean=True, is_basic=True)
    elif typedef['type'] == 'integer':
        if typedef['format'] == 'int32':
            return create_typedef(integer=True, is_basic=True)
        else:
            raise ValueError(typedef['format'])
    elif typedef['type'] == 'number':
        if typedef['format'] == 'double':
            return create_typedef(double=True, is_basic=True)
        elif typedef['format'] == 'float':
            return create_typedef(float=True, is_basic=True)
        else:
            raise ValueError(typedef['format'])
    elif typedef['type'] == 'array':
        return create_typedef(is_list=True, list_type=resolve_type(typedef['items']))
    elif typedef['type'] == 'object' and len(typedef) == 1:
        return create_typedef(generic=True)
    elif typedef['type'] == 'object' and 'additionalProperties' in typedef and 'properties' not in typedef:
        return create_typedef(is_map=True, map_key_type=resolve_type({'type': 'string'}), map_val_type=resolve_type(typedef['additionalProperties']))
    else:
        raise ValueError(typedef['type'])

def capitalize_first(s):
    return s[0].upper() + s[1:]

def to_language_case(base, case):
    if case == 'camel':
        return to_camel_case(base)
    if case == 'capital':
        return to_capital_case(base)
    if case == 'snake':
        return base
    raise ValueError(case)

def to_camel_case(snake_str):
    components = snake_str.split('_')
    # We capitalize the first letter of each component except the first one
    # with the 'title' method and join them together.
    return components[0] + ''.join(x.title() for x in components[1:])

def to_capital_case(snake_str):
    components = snake_str.split('_')
    # We capitalize the first letter of each component except the first one
    # with the 'title' method and join them together.
    return ''.join(x.title() for x in components)

if __name__ == "__main__":
    main()


import numpy as np
import math

class Applier:

    def __call__(self, eta, grads):
        raise NotImplementedError()

class SimpleApplier:

    def __call__(self, eta, *grads):
        return tuple([-eta*g for g in grads])

class MomentumApplier(Applier):

    def __init__(self, gamma = 0.95):
        self.G = gamma
        self.M = None

    def __call__(self, eta, grads):
        if self.M is None:
            self.M = [g.copy() for g in grads]
        else:
            self.M = [g*(1.0-self.G) + m*self.G for g, m in zip(grads, self.M)]
        return tuple([-eta*g for g in self.M])

class NAGApplier(Applier):

    def __init__(self, gamma = 0.5):
        self.G = gamma
        self.Dt1 = None      # D(t-1)

    def __call__(self, eta, grads):
        if self.Dt1 is None:
            self.Dt1 = [np.zeros_like(g) for g in grads]

        Dt = [self.G * dt1 - eta * g for dt1, g in zip(self.Dt1, grads)]
        deltas = [dt + self.G*(dt-dt1) for dt, dt1 in zip(Dt, self.Dt1)]
        self.Dt1 = Dt
        return tuple(deltas)

class AdaDeltaApplier(Applier):

    def __init__(self, rho = 0.95, epsilon=1.0e-6):
        self.Rho = rho
        self.Epsilon = epsilon
        self.Eg2s = None
        self.Edw2s = None
        self.EtaMA = None

    def __call__(self, eta, grads):
        if self.Eg2s is None:
            # first time
            self.Eg2s = [np.sum(np.square(g)) for g in grads]
            dws = [-eta*g for g in grads]
            self.Edw2s = [np.sum(np.square(d)) for d in dws]
            self.EtaMA = np.array([eta for g in grads])
        else:
            g2s = [np.sum(np.square(g)) for g in grads]
            self.Eg2s = [oldG*self.Rho + newG*(1.0-self.Rho) for oldG, newG in zip(self.Eg2s, g2s)]
            es = [math.sqrt((Edw2 + self.Epsilon*eta)/(Eg2 + self.Epsilon)) for Edw2, Eg2 in zip(self.Edw2s, self.Eg2s)]
            dws = [-e*g for e, g in zip(es, grads)]
            self.Edw2s = [oldDw*self.Rho + np.sum(np.square(newDw))*(1.0-self.Rho) for oldDw, newDw in zip(self.Edw2s, dws)]
            self.EtaMA = 0.99*self.EtaMA + 0.01*np.array(es)
            #print "AdaDelta: es=", es, "    eta ma=", self.EtaMA
        return tuple(dws)


import IPython
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_histogram, array_to_latex
from qiskit_aer import QasmSimulator

if __name__ == '__main__':
    # StateVector
    sv_initial: Statevector = Statevector.from_int(0, 2 ** 2)
    sv_initial.draw(output='text')
    sv_initial.draw(output='qsphere')
    sv_initial.draw(output='bloch')
    sv_initial_latex: IPython.display.Latex = array_to_latex(sv_initial)

    # Circuit
    circuit = QuantumCircuit(2, 2)
    circuit.h(0) # We apply a Hadamard gate https://quantum-computing.ibm.com/composer/docs/iqx/operations_glossary/#cnot-gate
    circuit.cx(0, 1) # We apply a CNOT gate https://quantum-computing.ibm.com/composer/docs/iqx/operations_glossary/#cnot-gate

    # StateVector after circuit
    sv_final = sv_initial.evolve(other=circuit)
    sv_final.draw(output='qsphere')

    # Measure circuit
    circuit.measure([0, 1], [0, 1])
    circuit.draw(output="mpl")

    # Simulate circuit
    simulator = QasmSimulator()
    compiled_circuit = transpile(circuit, simulator)
    job = simulator.run(compiled_circuit, shots=1000)
    result = job.result()
    counts = result.get_counts(circuit)
    plot_histogram(counts)
    print("\nTotal count for 00 and 11 are:", counts)


import os
import glob
import random
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

from sklearn.decomposition import PCA
from sklearn.metrics import confusion_matrix
from sklearn.ensemble import RandomForestClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA

# 載入資料集，從每個人的資料集中隨機取5張作為train data，並將資料集轉換為一維向量
def loadDataset(dir_name='./att_faces'):
    sampleNum = 5
    X_train, Y_train, X_test, Y_test = [], [], [], []
    for i in range(40):
        img_path = dir_name+'/s'+str(i+1)+'/'
        sampled = random.sample(range(10), sampleNum)
        data = [cv.imread(d, 0) for d in glob.glob(os.path.join(img_path, '*.pgm'))]
        X_train.extend([data[i].ravel() for i in range(10) if i in sampled])
        X_test.extend([data[i].ravel() for i in range(10) if i not in sampled])
        Y_test.extend([i] * (10 - sampleNum))
        Y_train.extend([i] * sampleNum)
    return np.array(X_train), np.array(Y_train), np.array(X_test), np.array(Y_test)

# 將資料做PCA轉換矩陣，並降維
def pca_process(X_train, Y_train, X_test, dimension):
    pca = PCA(n_components=dimension)
    pca.fit(X_train, Y_train)
    X_train_trans = pca.transform(X_train)
    X_test_trans = pca.transform(X_test)
    return X_train_trans, X_test_trans

# 將資料做FLD(LDA)轉換矩陣
def lda_process(X_train, X_test, Y_train):
    lda = LDA()
    X_train_trans = lda.fit_transform(X_train, Y_train)
    X_test_trans = lda.transform(X_test)
    return X_train_trans, X_test_trans

# 以隨機森林分類器來進行辨識，並取得預測的準確度
def rfc_model(dimension, X_train, X_test, Y_train, Y_test):
    model = RandomForestClassifier()
    model.fit(X_train, Y_train)
    pred = model.predict(X_test)
    return pred

# 將混淆矩陣以pyplot顯示出來
def show_matrix_in_plot(name, dimension, con_mat):
    plt.imshow(con_mat, interpolation='nearest', cmap=plt.cm.autumn)
    plt.title('{} Dimension {} Confusion matrix'.format(name, dimension))
    plt.colorbar()
    tick_marks = np.arange(4)
    plt.xticks(tick_marks, tick_marks)
    plt.yticks(tick_marks, tick_marks)
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.savefig(name+'_'+str(dimension)+'.png')
    plt.show()

def main(dimension):
    # 只做PCA的部分
    X_train, Y_train, X_test, Y_test = loadDataset()
    X_train_trans, X_test_trans = pca_process(X_train, Y_train, X_test, dimension)
    predict = rfc_model(dimension, X_train_trans, X_test_trans, Y_train, Y_test)
    print('PCA Dimension '+str(dimension)+': Accuracy: '+str((predict == np.array(Y_test)).mean() * 100))
    con_mat = confusion_matrix(predict, list(Y_test))
    show_matrix_in_plot('PCA', dimension, con_mat)

    # 做PCA+FLD的部分
    X_train_trans, X_test_trans = lda_process(X_train_trans, X_test_trans, Y_train)
    predict = rfc_model(dimension, X_train_trans, X_test_trans, Y_train, Y_test)
    print('LDA+PCA Dimension '+str(dimension)+': Accuracy: '+str((predict == np.array(Y_test)).mean() * 100))
    con_mat = confusion_matrix(predict, list(Y_test))
    show_matrix_in_plot('PCA+FLD(LDA)', dimension, con_mat)

main(10)
main(20)
main(30)
main(40)
main(50)


# 색종이(10163번)

Testcase = int(input())
set_list = []
for test in range(1, Testcase + 1):
    x, y, xr, yr = map(int, input().split())
    each_set = set()
    for i in range(x, x+xr):
        for j in range(y, y+yr):
            each_set.add((i,j))
    set_list.append(each_set)

for i in range(len(set_list)-1):
    dis_list = set_list[i+1:]
    A = set_list[i]
    for j in dis_list:
        A = A-j
    print(len(A))
print(len(set_list[-1]))


import random
import pandas

service_rolls = {'Navy': {'Enlist': 8, 'Survive': 5, 'Commission': 10, 'Promotion': 8, 'Reenlistment': 6}, 'Marines': {'Enlist': 9, 'Survive': 6, 'Commission': 9, 'Promotion': 9, 'Reenlistment': 6},'Army': {'Enlist': 5,'Survive': 5, 'Commission': 5, 'Promotion': 6, 'Reenlistment': 7}, 'Scouts': {'Enlist': 7, 'Survive': 7, 'Reenlistment': 3}, 'Merchants': {'Enlist': 7, 'Survive': 5, 'Commission': 4, 'Promotion': 10, 'Reenlistment': 4}, 'Others': {'Enlist': 3, 'Survive': 5, 'Reenlistment': 5}}

personal_development = {'Navy': {1 : 'strength', 2 : 'dexterity',3 : 'endurance', 4: 'social_standing', 5: 'intelligence', 6: 'education' }, 'Marines': {1 : 'strength', 2 : 'dexterity',3 : 'endurance', 4: 'gambling', 5: 'brawling', 6: 'blade'}, 'Army': {1 : 'strength', 2 : 'dexterity',3 : 'endurance', 4: 'gambling', 5: 'brawling', 6: 'education'} , 'Scouts': {1 : 'strength', 2 : 'dexterity',3 : 'endurance', 4: 'gun', 5: 'intelligence', 6: 'education'} , 'Merchants': {1 : 'strength', 2 : 'dexterity',3 : 'endurance', 4: 'strength', 5: 'blade', 6: 'bribery'}, 'Others': {1 : 'strength', 2 : 'dexterity',3 : 'endurance', 4: 'blade', 5: 'brawling', 6: 'social_standing'}}

service_skills = {'Navy': {1 : 'ships_boat', 2 : 'vacc_suit',3 : 'forward_observer', 4: 'blade', 5: 'gun', 6: 'gunnery' }, 'Marines': {1 : 'atv', 2 : 'vacc_suit',3 : 'blade', 4: 'blade', 5: 'gun', 6: 'gun'}, 'Army': {1 : 'atv', 2 : 'air_raft',3 : 'forward_observer', 4: 'blade', 5: 'gun', 6: 'gun'} , 'Scouts': {1 : 'air_raft', 2 : 'vacc_suit',3 : 'navigation', 4: 'mechanic', 5: 'electronic', 6: 'J_o_T'} , 'Merchants': {1 : 'steward', 2 : 'vacc_suit',3 : 'strength', 4: 'gun', 5: 'electronic', 6: 'J_o_T'}, 'Others': {1 : 'forgery', 2 : 'gambling',3 : 'brawling', 4: 'blade', 5: 'gun', 6: 'bribery'}}

advanced_education =  {'Navy': {1 : 'vacc_suit', 2 : 'mechanic',3 : 'electronic', 4: 'engineering', 5: 'gunnery', 6: 'J_o_T' }, 'Marines': {1 : 'atv', 2 : 'mechanic',3 : 'electronic', 4: 'tactics', 5: 'blade', 6: 'gun'}, 'Army': {1 : 'atv', 2 : 'mechanic',3 : 'electronic', 4: 'tactics', 5: 'blade', 6: 'gun'} , 'Scouts': {1 : 'air_raft', 2 : 'mechanic',3 : 'electronic', 4: 'J_o_T', 5: 'gunnery', 6: 'medical'} , 'Merchants': {1 : 'streetwise', 2 : 'mechanic',3 : 'electronic', 4: 'navigation', 5: 'gunnery', 6: 'medical'}, 'Others': {1 : 'streetwise', 2 : 'mechanic', 3 : 'electronic', 4: 'gambling', 5: 'brawling', 6: 'forgery'}}

advanced_higher_education =  {'Navy': {1 : 'medical', 2 : 'navigation',3 : 'engineering', 4: 'computer', 5: 'pilot', 6: 'admin' }, 'Marines': {1 : 'medical', 2 : 'tactics',3 : 'tactics', 4: 'computer', 5: 'leadership', 6: 'admin'}, 'Army': {1 : 'medical', 2 : 'tactics',3 : 'tactics', 4: 'computer', 5: 'leadership', 6: 'admin'} , 'Scouts': {1 : 'medical', 2 : 'navigation',3 : 'engineering', 4: 'computer', 5: 'pilot', 6: 'J_o_T'} , 'Merchants': {1 : 'medical', 2 : 'navigation',3 : 'engineering', 4: 'computer', 5: 'pilot', 6: 'admin'}, 'Others': {1 : 'medical', 2 : 'forgery', 3: 'electronic', 4:  'computer', 5: 'streetwise', 6: 'J_o_T'}}

skills_tables = [personal_development, service_skills, advanced_education, advanced_higher_education ]

mustering_out_benefits_table =  {'Navy': {1 : 'Low_Psg', 2 : 'Intelligence +1', 3 : 'Education +2 ', 4: 'Blade', 5: 'Travellers', 6: 'High_Psg', 7: 'Social_Standing +2'  }, 'Marines': {1 : 'Low_Psg', 2 : 'Intelligence +2',3 : 'Education +1', 4: 'Blade', 5: 'Travellers', 6: 'High_Psg', 7: 'Social_Standing +2' }, 'Army': {1 : 'Low_Psg', 2 : 'Intelligence +1',3 : 'Education +2', 4: 'Gun', 5: 'High_Psg', 6: 'Mid_Psg', 7: 'Social_Standing +1' } , 'Scouts': {1 : 'Low_Psg', 2 : 'Intelligence +2',3 : 'Education +2', 4: 'Blade', 5: 'Gun', 6: 'Scout'}, 'Merchants': {1 : 'Low_Psg', 2 : 'Intelligence + 1', 3 : 'Education +1', 4: 'Gun', 5: 'Blade', 6: 'Low_Psg', 7: 'Merchant'  }, 'Others': {1 : 'Low_Psg', 2 : 'Intelligence +1', 3: 'Education +2', 4:  'Gun', 5: 'High_Psg', 6: '--'}}

def two_d6():
    return random.randint(1, 6) + random.randint(1, 6)

def one_d6():
    return random.randint(1, 6)

dm_data = (('enlist', 'Navy', 'intelligence', 8, 1), ('enlist', 'Navy', 'education', 9, 2), ('enlist', 'Marines', 'intelligence', 8, 1), ('enlist', 'Marines', 'strength', 8, 2) , ('enlist', 'Army', 'dexterity', 6, 1), ('enlist', 'Army', 'endurance', 5, 2), ('enlist', 'Scouts', 'intelligence', 6, 1), ('enlist', 'Scouts', 'strength', 8, 2), ('enlist', 'Merchants', 'strength', 7, 1), ('enlist', 'Merchants', 'intelligence', 6, 2))

class Character:
    def __init__(self, number):
        self.number = number
        self.alive = True
        self.enlisted = False
        self.first_choice = None
        self.service = None
        self.initial_service = None
        self.commissioned = False
        self.career = None
        self.terms = 0
        self.age = 18
        self.rank = 0
        self.skills = 0
        self.notional_skills_cap = 0
        self.attribute_increase = 0
        self.initial_strength = two_d6()
        self.initial_endurance = two_d6()
        self.initial_dexterity = two_d6()
        self.initial_intelligence = two_d6()
        self.initial_education = two_d6()
        self.initial_social_standing = two_d6()
        self.strength = self.initial_strength
        self.endurance = self.initial_endurance
        self.dexterity = self.initial_dexterity
        self.intelligence = self.initial_intelligence
        self.education = self.initial_education
        self.social_standing = self.initial_social_standing
        self.brawling = 0
        self.gun = 0
        self.blade = 0
        self.mechanic = 0
        self.engineering = 0
        self.electronic = 0
        self.computer = 0
        self.admin = 0
        self.medical = 0
        self.steward = 0
        self.atv = 0
        self.air_raft = 0
        self.ships_boat = 0
        self.pilot = 0
        self.navigation = 0
        self.gunnery = 0
        self.vacc_suit = 0
        self.leadership = 0
        self.tactics = 0
        self.forward_observer = 0
        self.streetwise = 0
        self.gambling = 0
        self.bribery = 0
        self.forgery = 0
        self.J_o_T = 0
        self.end_of_service_reason = None
        self.material_benefits = []
        self.cash_benefits_count = 0
        self.reason_a = 0
        self.reason_b = 0
        self.reason_c = 0
        self.reason_d = 0
        self.retirement_request_reason = 'None'
        self.reenlist_choice = True
        self.character_attributes = [['strength',  self.strength], ['endurance', self.endurance], ['dexterity', self.dexterity], ['intelligence', self.intelligence], ['education', self.education], ['social_standing', self.social_standing]]
        self.enlistment_roll_mod = 0

    def dice_modifier(self, roll_for, char_service):
        modifier = 0
        for a in self.character_attributes:
            for index, tup in enumerate(dm_data):
                if tup[0] == roll_for and tup[1] == char_service:
                    if a[0] == tup[2] and a[1] >= tup[3]:
                        modifier += tup[4]
        return modifier

    def career_arc(self):
        self.choose_career()
        self.term()
        self.mustering_out()

#    def career_decision(self):
#        career_list = ['Navy', 'Marines', 'Army', 'Scouts', 'Merchants', 'Others']
#        [print(x) for x in career_list

    def choose_career(self):
        self.first_choice = random.choice(('Navy', 'Marines', 'Army', 'Scouts', 'Merchants', 'Others'))
#       print("You have applied to join the " + choice)
        enlistment_roll = two_d6()
        enlistment_roll += self.dice_modifier('enlist', self.first_choice) # self.character_attributes # )
#       self.enlistment_roll_mod += self.dice_modifier('enlist',  self.first_choice) # self.character_attributes # )
#       enlistment_roll += self.dice_modifier('enlist', choice, self.character_attributes)
#       checksum.append(self.dice_modifier('enlist', choice, self.character_attributes))
#       self.enlistment_roll_mod += self.dice_modifier('enlist', choice, self.character_attributes)
#       if (choice == 'Army' and self.dexterity >= 6): enlistment_roll += 1
#       if (choice == 'Scouts' and self.intelligence >= 6): enlistment_roll += 1
#       if (choice == 'Merchants' and self.strength>= 7): enlistment_roll += 1
#       if (choice == 'Navy' and self.education >= 9): enlistment_roll += 2
#       if (choice == 'Marines' and self.strength >= 8): enlistment_roll += 2
#       if (choice == 'Army' and self.endurance >= 5): enlistment_roll += 2
#       if (choice == 'Scouts' and self.strength >= 8): enlistment_roll += 2
#       if (choice == 'Merchants' and self.intelligence >= 6): enlistment_roll += 2
        if enlistment_roll >= service_rolls[self.first_choice]['Enlist']:
            self.career = self.first_choice
            self.initial_service = "contract"
            self.service = self.initial_service
#           print("You have successfully enlisted in the " + self.career)
        else:
            # draft
            self.career = random.choice(('Navy', 'Marines', 'Army', 'Scouts', 'Merchants', 'Others'))
            self.initial_service = "draft"
            self.service = self.initial_service
#           print("you have been drafted into the " + self.career)

    def set_attr(self, attr, buff):
            new_val = getattr(self, attr) + buff
            setattr(self, attr, new_val)
#       print(str(attr) + " has improved by " + str(buff))

    def resolve_skills(self):
        if self.education >= 8:
            skill_table = random.choice(skills_tables[0:3])
        else:
            skill_table = random.choice(skills_tables[0:2])
        skill_roll = one_d6()
        attr = skill_table[self.career][skill_roll]
        char_attributes = ['strength', 'endurance', 'dexterity', 'intelligence', 'education', 'social_standing']
        if (attr in char_attributes ):
            self.attribute_increase += 1
        self.set_attr(attr, 1)

    def new_term(self):
        # survival roll
        self.survival_check(self)
        # commissioning
        # promotion
        # skills
        # ageing

    def survival_check(self):
        survival_roll = two_d6()
        if (self.career == 'Navy' and self.intelligence >= 7): survival_roll += 2
        if (self.career == 'Marines' and self.endurance >= 8): survival_roll += 2
        if (self.career == 'Army' and self.education >= 6): survival_roll += 2
        if (self.career == 'Scouts' and self.endurance >= 9): survival_roll += 2
        if (self.career == 'Merchants' and self.intelligence >= 7): survival_roll += 2
        if (self.career == 'Others' and self.intelligence >= 9): survival_roll += 2
        if (survival_roll >= service_rolls[self.career]['Survive']):
            self.alive = True

    def term(self):
        skills = 0
        if self.service == 'contract':
            skills += self.commission()
            skills += self.promotion()
            skills += 1
            self.notional_skills_cap +=1
            if self.terms == 0:
                skills += 1
                self.notional_skills_cap += 1
            if self.career == 'Army':
                self.gun += 1
                self.notional_skills_cap += 1
            if self.career == 'Marines':
                self.blade += 1
                self.notional_skills_cap += 1
            if self.career == 'Scouts':
                self.pilot += 1
                self.notional_skills_cap += 1
            for s in range(skills):
                self.resolve_skills()
                skills -= 1
            self.terms += 1
            self.age = 18 + self.terms * 4
            self.ageing_process()
            self.reenlistment()
        else:
            self.alive = False
            self.end_of_service_reason = "Death in Service"
#           print("sadly you didn't make it")

    def filterA(self):
        # ageing becomeing a problem
        if 4 <= self.terms <= 11:
            early_ageing_attributes = [self.strength, self.endurance, self.dexterity]
            for ea in early_ageing_attributes:
                if ea < 3:
                    self.reenlist_choice = False
                    self.reason_a += 1
        elif self.terms > 12:
            late_ageing_attributes = [self.strength, self.endurance, self.dexterity, self.intelligence]
            for la in late_ageing_attributes:
                if la < 3:
                    self.reenlist_choice = False
                    self.reason_a += 1

    def filterB(self):
        # re-enlistment chances poor
        if (self.career == 'Navy' and self.intelligence < 7):
            self.reenlist_choice = False
            self.reason_b += 1
        if (self.career == 'Marines' and self.endurance < 8):
            self.reenlist_choice = False
            self.reason_b += 1
        if (self.career == 'Army' and self.education < 6):
            self.reenlist_choice = False
            self.reason_b += 1
        if (self.career == 'Scouts' and self.endurance < 9):
            self.reenlist_choice = False
            self.reason_b += 1
        if (self.career == 'Merchants' and self.intelligence < 7):
            self.reenlist_choice = False
            self.reason_b += 1
        if (self.career == 'Others' and self.intelligence < 9):
            self.reenlist_choice = False
            self.reason_b += 1

#    def filterC(self):
#        if (self.career == 'Scouts' or self.commissioned == False):
#            if (self.terms >= 6):
#                self.reenlist_choice = False
#                self.set_attr('reason_c', 1)
#            elif (self.terms >= 10):
#                self.reenlist_choice = False
#                self.set_attr('reason_c', 1)

    def filterD(self):
       # Maximum term covered by ageing rules
        if (self.terms == 14):
            self.reenlist_choice = False
            self.set_attr('reason_d', 1)

    def reenlistment_decision(self):
        self.reenlist_choice = True
        self.filterA()
#        self.filterB()
#        self.filterC()
        self.filterD()
        if self.reason_a > 0 and self.reason_b > 0:
            self.retirement_request_reason = 'Ageing & Survival Chances'
        elif self.reason_b > 0 and self.reason_c > 0:
            self.retirement_request_reason = 'Survival Chances and Time Served'
        elif self.reason_a > 0 and self.reason_c > 0:
            self.retirement_request_reason = 'Ageing & Time Served'
        elif self.reason_a > 0 and self.reason_b > 0 and self.reason_c > 0:
            self.retirement_request_reason = 'Ageing, Survival Chances & Time Served'
        elif self.reason_a > 0:
            self.retirement_request_reason = 'Ageing'
        elif self.reason_b > 0:
            self.retirement_request_reason = 'Survival chances'
        elif self.reason_c > 0:
            self.retirement_request_reason = 'Time Served'
        elif self.reason_d > 0:
            self.retirement_request_reason = 'Maximum age'
        else:
            self.retirement_request_reason = 'None'

    def reenlistment(self):
        if self.alive == False:
            return
#       reenlistment_choice = input("Do you want to reenlist? ")
#       for auto generated characters we assume the character wants to re-enlist
        self.reenlistment_decision()
        # level 0 filter a character will not re-enlist if doing so runs the risk of taking any attribute below 2
        reenlistment_roll = two_d6()
        if (reenlistment_roll == 12 and self.reenlist_choice == False):
#       print("You have been pressed back into service in time of need")
            self.service = 'contract'
            self.term()
        elif (reenlistment_roll >= service_rolls[self.career]['Reenlistment'] and self.reenlist_choice == True):
#           print("You have reenlisted for another term")
            self.service = 'contract'
            self.term()
        elif (reenlistment_roll < service_rolls[self.career]['Reenlistment'] and self.reenlist_choice == True):
#           print("The service no longer has need of your service, and you are offered retirement")
            self.end_of_service_reason = "Services no longer required"
        elif (reenlistment_roll < 12 and self.reenlist_choice == False):
            self.end_of_service_reason = "Granted Retirement"

    def commission(self):
        skills = 0
        if (self.commissioned == False and self.career != 'Others' and self.career != 'Scouts' and self.service != 'draft') :
            commission_roll = two_d6()
            if (self.career == 'Navy' and self.social_standing >= 9): commission_roll += 1
            if (self.career == 'Marines' and self.education >= 7): commission_roll += 1
            if (self.career == 'Army' and self.endurance >= 7): commission_roll += 1
            if (self.career == 'Merchants' and self.intelligence >= 6): commission_roll += 1
            if (commission_roll >= service_rolls[self.career]['Commission']):
                self.commissioned = True
                self.rank = 1
                skills += 1
                self.notional_skills_cap += 1
                if self.career == 'Army':
                    self.gun += 1
                    self.notional_skills_cap += 1
                if self.career == 'Marines':
                    self.gun += 1
                    self.notional_skills_cap += 1
        return skills

    def promotion(self):
        skills = 0
        if self.commissioned == True:
            if (self.career != 'Merchants' and self.rank < 6) or (self.career == 'Merchants' and self.rank < 5) :
                promotion_roll = two_d6()
                if (self.career == 'Navy' and self.education >= 8): promotion_roll += 1
                if (self.career == 'Marines' and self.social_standing >= 8): promotion_roll += 1
                if (self.career == 'Army' and self.education >= 7): promotion_roll += 1
                if (self.career == 'Merchants' and self.intelligence >= 9): promotion_roll += 1
                if (promotion_roll >= service_rolls[self.career]['Promotion']):
#                   print('you have been promoted')
                    self.rank += 1
                    skills += 1
                    self.notional_skills_cap +=1
                    if (self.career == 'Navy' and self.rank == 5): self.social_standing += 1
                    if (self.career == 'Navy' and self.rank == 6): self.social_standing += 1
                    if (self.career == 'Merchants' and self.rank == 4):
                        self.pilot += 1
                        self.notional_skills_cap +=1
        return skills

    def ageing_process(self):
        if (self.terms > 3 and self.terms < 8 ):
            if (two_d6() < 8): self.strength -= 1
            if (two_d6() < 7): self.dexterity -= 1
            if (two_d6() < 8): self.endurance -= 1
        elif (self.terms > 8 and self.terms < 11 ):
            if (two_d6() < 9): self.strength -= 1
            if (two_d6() < 8): self.dexterity -= 1
            if (two_d6() < 9): self.endurance -= 1
        elif ( self.terms > 11 and self.terms < 15):
            if (two_d6() < 9): self.strength -= 2
            if (two_d6() < 8): self.dexterity -= 2
            if (two_d6() < 9): self.endurance -= 2
            if (two_d6() < 9): self.intelligence -= 1
        ageing_attributes = [self.strength, self.endurance, self.dexterity, self.intelligence]
        for aa in ageing_attributes:
            if aa < 1:
                self.alive = False
                self.end_of_service_reason = "You died in service owing to the effects of old age"

    def mustering_out(self):
        if(self.alive):
            mustering_out_rolls = self.terms
            if (self.commissioned == True and self.rank <3 ): mustering_out_rolls += 1
            elif(self.rank >=3 ): mustering_out_rolls += 2
            split = random.randint(0,1)
            self.cash_benefits_count = min(mustering_out_rolls * split, 3)
            material_benefits_count = mustering_out_rolls - self.cash_benefits_count
            self.material_benefits = []
            for i in range(material_benefits_count):
                muster_roll = one_d6()
                if (self.rank >= 5): muster_roll += 1
                self.material_benefits.append(mustering_out_benefits_table[self.career][muster_roll])
            for i in self.material_benefits:
                if i == "Social_Standing +2":
                    self.social_standing += 2
                    self.attribute_increase += 2
                if i == "Social_Standing +1":
                    self.social_standing += 1
                    self.attribute_increase += 1
                if i == "Intelligence +2":
                    self.intelligence += 2
                    self.attribute_increase += 2
                if i == "Intelligence +1":
                    self.intelligence += 1
                    self.attribute_increase += 1
                if i == "Education +2":
                    self.education += 2
                    self.attribute_increase += 2
                if i == "Education +1":
                    self.education += 1
                    self.attribute_increase += 1

    def print_character(self):
        print(int(self.strength) , int(self.endurance) , int(self.dexterity) , int(self.intelligence) , int(self.education)  ,  int(self.social_standing) , end=" ")
        print(self.career)

        print("Terms " + str(self.terms))
        print("Rank " + str(self.rank))

    def total_stats(self):
        return self.strength + self.endurance + self.dexterity + self.intelligence + self.education + self.social_standing

    def total_skills(self):
        return self.brawling + self.gun + self.blade + self.mechanic + self.engineering + self.electronic + self.computer + self.admin + self.medical + self.steward + self.atv + self.air_raft + self.ships_boat + self.pilot + self.navigation + self.gunnery + self.vacc_suit + self.leadership + self.tactics + self.forward_observer + self.streetwise + self.gambling + self.bribery + self.forgery + self.J_o_T

    def to_dict(self):
        return {
            'number': self.number,
            'first_choice' : self.first_choice,
            'career': self.career,
            'initial term': self.initial_service,
            'service type': self.service,
            'commissioned': self.commissioned,
            'total stats': self.total_stats(),
            'total skills': self.total_skills(),
            'attribute increase': self.attribute_increase,
            'skill opportunities': self.total_skills() + self.attribute_increase,
            'init_strength': self.initial_strength,
            'init_endurance': self.initial_endurance,
            'init_dexterity': self.initial_dexterity,
            'init_intelligence': self.initial_intelligence,
            'init_education': self.initial_education,
            'init_social_standing': self.initial_social_standing,
            'strength': self.strength,
            'endurance': self.endurance,
            'dexterity': self.dexterity,
            'intelligence': self.intelligence,
            'education': self.education,
            'social_standing': self.social_standing,
            'rank': self.rank,
            'terms': self.terms,
            'age': self.age,
            'alive': self.alive,
            'retirement reason': self.retirement_request_reason,
            'end_of_service': self.end_of_service_reason,
            'brawling': self.brawling,
            'gun': self.gun,
            'blade': self.blade,
            'mechanic': self.mechanic,
            'engineering': self.engineering,
            'electronic': self.electronic,
            'computer': self.computer,
            'admin': self.admin,
            'medical': self.medical,
            'steward': self.steward,
            'atv': self.atv,
            'air_raft': self.air_raft,
            'ships_boat': self.ships_boat,
            'pilot': self.pilot,
            'navigation': self.navigation,
            'gunnery': self.gunnery,
            'vacc_suit': self.vacc_suit,
            'leadership': self.leadership,
            'tactics': self.tactics,
            'forward_observer': self.forward_observer,
            'streetwise': self.streetwise,
            'gambling': self.gambling,
            'bribery': self.bribery,
            'forgery': self.forgery,
            'J_o_T' : self.J_o_T,
            'material benefits': self.material_benefits,
            'count of cash benefits': self.cash_benefits_count,
            'skills_cap_check': self.notional_skills_cap,
            'reasonA': self.reason_a,
            'reasonB': self.reason_b,
            'reasonC': self.reason_c,
            'mod': self.enlistment_roll_mod
        }

characters = []

run_size = 200000

for i in range(run_size):
    characters.append(Character(i))

for i in range(run_size):
    characters[i].career_arc()

df = pandas.DataFrame.from_records([s.to_dict() for s in characters])

# print(df.describe(include = 'all'))

df_is_alive = df['alive'] == True

#print(df_is_alive.describe(include = "all"))

df.to_excel(r"C:\Users\Mike\Desktop\Traveller_New.xlsx", index = False, header=True)


# To add a new cell, type '#%%'
# To add a new markdown cell, type '#%% [markdown]'
#%%
from IPython import get_ipython

#%% [markdown]
# # 感知机
#%% [markdown]
# 输入: 训练数据集$T = \lbrace(x_1, y_1, (x_2,y_2), ... , (x_N, y_N)\rbrace$, 其中$x_1 \in X = R^n$,
# $y_i \in Y = \lbrace-1, +1\rbrace$, $i = 1, 2, ... , N$; 学习率$\eta(0 < \eta \leq 1)$
#%% [markdown]
# 输出: $w, b$; 感知机模型$f(x) = sign(w \cdot x + b)$
#
# (1) 选取初值$w_0, b_0$
#
# (2) 在训练集中选取数据$(x_i, y_i)$
#
# (3) 如果$y_i(w \cdot x_i + b) \leq 0$
#
# $$w \leftarrow w + \eta y_i x_i$$
#
# $$b \leftarrow b + \eta y_i$$
#
# (4) 转至(2), 直至训练集中没有误分类点
#%% [markdown]
# 数据集选取sklearn中iris, 并且以长度(sepal length)和宽度(sepal width)作为特征

#%%
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
# get_ipython().run_line_magic('matplotlib', 'inline')

#%%
iris = load_iris()
df = pd.DataFrame(iris.data, columns = iris.feature_names)
df['label'] = iris.target
# print(df.columns)
# print(df)

#%%
plt.scatter(df[0: 50]['sepal length (cm)'], df[0: 50]['sepal width (cm)'], color = 'blue', label = '0')
plt.scatter(df[50: 100]['sepal length (cm)'], df[50: 100]['sepal width (cm)'], color = 'orange', label = '1')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
plt.show()

#%%
data = np.array(df.iloc[:100, [0, 1, -1]])
X, y = data[:, :-1], data[:, -1]
y = np.array([1 if i == 1 else -1 for i in y])  # 将label转换为{-1, 1}

#%% [markdown]
# ## Perceptron

#%%
class Model:
    def __init__(self):
        self.w = np.ones(len(data[0]) - 1, dtype=np.float32)
        self.b = 0
        self.l_rate = 0.01

    def sign(self, x, w, b):
        y = np.dot(x, w) + b
        return y

    # 随机梯度下降法
    def fit(self, X_train, y_train):
        is_wrong = False
        while not is_wrong:
            wrong_count = 0
            for d in range(len(X_train)):
                X = X_train[d]
                y = y_train[d]
                if y * self.sign(X, self.w, self.b) <= 0:
                    self.w = self.w + self.l_rate * np.dot(y, X)
                    self.b = self.b + self.l_rate * y
                    # wrong_count += np.abs(y * self.sign(X, self.w, self.b))
                    wrong_count += 1
            # print(wrong_count)
            if wrong_count == 0:
                is_wrong = True
        return 'Finished!'

#%%
perceptron = Model()
perceptron.fit(X, y)

#%%
plt.figure(figsize=(10,5))

x_points = np.linspace(4, 7, 10)
y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1]
plt.plot(x_points, y_)

plt.plot(data[:50, 0], data[:50, 1], 'bo', color='blue', label='0')
plt.plot(data[50:100, 0], data[50:100, 1], 'bo', color='orange', label='1')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
plt.show()


# Add the igl library to the modules search path
import sys, os
sys.path.insert(0, os.getcwd() + "/../")

import igl

V = igl.eigen.MatrixXd()
F = igl.eigen.MatrixXi()

# Load a mesh in OFF format
igl.readOFF("../../tutorial/shared/bunny.off", V, F)

# Find the bounding box
m = V.colwiseMinCoeff()
M = V.colwiseMaxCoeff()

# Corners of the bounding box
V_box = igl.eigen.MatrixXd(
[
[m[0,0], m[0,1], m[0,2]],
[M[0,0], m[0,1], m[0,2]],
[M[0,0], M[0,1], m[0,2]],
[m[0,0], M[0,1], m[0,2]],
[m[0,0], m[0,1], M[0,2]],
[M[0,0], m[0,1], M[0,2]],
[M[0,0], M[0,1], M[0,2]],
[m[0,0], M[0,1], M[0,2]]
]
)

E_box = igl.eigen.MatrixXi(
[
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
[0, 4],
[1, 5],
[2, 6],
[7 ,3]
]
)

# Plot the mesh
viewer = igl.viewer.Viewer()
viewer.data.set_mesh(V, F)

# Plot the corners of the bounding box as points
viewer.data.add_points(V_box,igl.eigen.MatrixXd([[1,0,0]]))

# Plot the edges of the bounding box
for i in range(0,E_box.rows()):
    viewer.data.add_edges(
        V_box.row(E_box[i,0]),
        V_box.row(E_box[i,1]),
        igl.eigen.MatrixXd([[1,0,0]]))

# Plot labels with the coordinates of bounding box vertices
l1 = 'x: ' + str(m[0,0]) + ' y: ' + str(m[0,1]) + ' z: ' + str(m[0,2])
viewer.data.add_label(m.transpose(),l1)

l2 = 'x: ' + str(M[0,0]) + ' y: ' + str(M[0,1]) + ' z: ' + str(M[0,2])
viewer.data.add_label(M.transpose(),l2);

# Launch the viewer
viewer.launch();


from flask import Flask, render_template, redirect, url_for, request, session
import os
import cgi
import datetime
import time
import json

app = Flask(__name__)

# SETTINGS
app.config['DEBUG'] = True
app.config['PUSHER_CHAT_APP_ID'] = '207136'
app.config['PUSHER_CHAT_APP_KEY'] = 'aa578c9a158782bff5f5'
app.config['PUSHER_CHAT_APP_SECRET'] = '54c667c6a791f308640b'
app.config['SECRET_KEY'] = "\x81\xa8\xcb\x8fl\x15\x16\xbfJ\xc3\xeb\x90\xfe\x82e\xdaS\x07\x95N\xa7\xb4\x95"

import pusher

pusher_client = pusher.Pusher(
  app_id=app.config['PUSHER_CHAT_APP_ID'],
  key=app.config['PUSHER_CHAT_APP_KEY'],
  secret=app.config['PUSHER_CHAT_APP_SECRET'],
  ssl=True
)

@app.route("/")
def index():
    return render_template('index.html')

@app.route("/setname/", methods=["POST"])
def set_name():
    session['name'] = request.form['name']

    return "Successful"

@app.route("/pusher/auth/", methods=["POST"])
def pusher_authentication():
    auth = pusher_client.authenticate(
        channel = request.form['channel_name'],
        socket_id = request.form['socket_id'],
        custom_data = {
            'user_id': session['name'],
        }
    )

    return json.dumps(auth)

@app.route("/messages/", methods=["POST"])
def new_message():
    name = request.form['name']
    text = cgi.escape(request.form['text'])
    channel = request.form['channel']

    now = datetime.datetime.now()
    timestamp = time.mktime(now.timetuple()) * 1000
    pusher_client.trigger("presence-" + channel, 'new_message', {
        'text': text,
        'name': name,
        'time': timestamp
    })

    return "Successful"

if __name__ == "__main__":
    # Have to set host and port since using Cloud9; don't need if running locally or on a server
    host = os.getenv('IP','0.0.0.0')
    port = int(os.getenv('PORT', 5000))
    app.run(host=host, port=port)


from BluenetLib.lib.util.Conversion import Conversion

class ResultPacket:

    def __init__(self, data):
        self.type = 0
        self.opCode = 0
        self.length = 0
        self.payload = []
        self.valid = False

        if len(data) >= 4:
            self.valid = True
            self.type = data[0]
            self.opCode = data[1]
            self.length = Conversion.uint8_array_to_uint16([data[2], data[3]])
            totalSize = 4 + self.length
            if len(data) >= totalSize:
                self.payload = data[4:]
            else:
                self.valid = False
        else:
            self.valid = False

    def getUInt16Payload(self):
        if not self.valid:
            return 65535

        if self.length >= 2:
            return Conversion.uint8_array_to_uint16([self.payload[0], self.payload[1]])
        else:
            return 65535


from PIL import Image
import io
import os

import requests
from bottle import Bottle, static_file, redirect, response, request

base_dir = './static'
app = Bottle()

@app.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

@app.route('/', method='OPTIONS')
@app.route('/<path:path>', method='OPTIONS')
def options_handler():
    return

@app.route('/', method='GET')
def index():
    return redirect("/apps/clue/")

@app.route('/<path:path>', method='GET')
def serve_file(path: str):
    if request.query_string:
        path += "?" + request.query_string
    file_path = os.path.join(base_dir, path)
    if path.endswith('/'):
        file_path += "dir.html"
    _download_file_if_not_exists(path, file_path)
    return _serve_content(file_path)

def _serve_content(file_path: str):
    if file_path.endswith(".webp"):
        return _serve_webp_as_png(file_path)
    if file_path.endswith(".js"):
        return _update_urls_and_serve(file_path)
    return static_file(file_path, root=".")

def _update_urls_and_serve(file_path: str):
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    modified_content = content.replace("https://runeapps.org", "")
    response.content_type = 'text/javascript'
    return modified_content

def _serve_webp_as_png(webp_path: str):
    png_path = webp_path.replace(".webp", ".png")
    if not os.path.exists(png_path):
        with Image.open(webp_path) as img:
            img.save(png_path, 'PNG')
    return _serve_content(png_path)

def _download_file_if_not_exists(path: str, file_path: str):
    if not os.path.exists(file_path):
        print("Fetching", path)
        resp = requests.get(f'https://runeapps.org/{path}')
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        with open(file_path, 'wb') as f:
            f.write(resp.content)

if __name__ == '__main__':
    app.run(port=8811)


from csv_functions import *

PI = 3.1415926535897
C_SPEED = 299792458

def kkr_refr_integ(w, ww, abs):
    return ww * abs / (ww ** 2 - w ** 2)

def integ_rec_tr(x_0, x_1, y_0, y_1):
    if y_1 >= y_0:
        return (y_0 + (abs(y_0 - y_1) / 2)) * (x_1-x_0)
    else:
        return (y_1 + (abs(y_0 - y_1) / 2)) * (x_1-x_0)

def integr_lists(X_list, Y_list, method):
    result = 0
    if method == 'triangle':
        for i in range(len(X_list)-1):
            result += integ_rec_tr(X_list[i], X_list[i+1], Y_list[i], Y_list[i+1])
    return result

def find_refr_from_abs(input_file, output_file):

    antl_spec = f'data/{input_file}'
    abs_func = csv_to_dict(antl_spec)
    w_numbs = list(abs_func.keys())

    file = open(f"data/{output_file}.txt", 'w')
    ref_coeffs = []

    for n in range(len(w_numbs)):
        # обход особой точки (это и есть v.p. интеграл)
        w_left = w_numbs[:n]
        w_right = w_numbs[n + 1:]

        integr_f_left = []
        integr_f_right = []

        for w_i in w_left:
            integr_f_left.append(kkr_refr_integ(w_numbs[n], w_i, abs_func[w_i]))
        for w_i in w_right:
            integr_f_right.append(kkr_refr_integ(w_numbs[n], w_i, abs_func[w_i]))

        n_refr_coeff = 1 + 2 * ((integr_lists(w_left, integr_f_left, 'triangle') + integr_lists(w_right, integr_f_right, 'triangle')) / PI)

        ref_coeffs.append(n_refr_coeff)
        file.write(f"{w_numbs[n]}; {n_refr_coeff}\n")
        print(f"{int((n / len(w_numbs)) * 100)} %, w = {w_numbs[n]} cm-1")
    print(f"refractive index was obtained from {input_file[:-4]}")
    file.close()
    return ref_coeffs

def full_scat_int(n_0, n_1, w, const, output_filename):
    #const = 24*PI**3*I0*V**2, where I0 = 1,  V in m3
    scatt_coeffs = {}
    file = open(f'{output_filename}.txt', 'w')
    for i in range(len(n_0)):
        n_0_ = n_0[i] ** 2
        n_1_ = n_1[i] ** 2
        w_ = w[i] ** 4 / 100 #wave length in m
        scatt = const * w_ * ((n_1_ - n_0_) / (n_1_ + 2 * n_0_)) ** 2
        file.write(f"{w[i]}; {scatt}\n")
        scatt_coeffs[w[i]] = scatt
        print(f"{round(100 * i / len(n_0))}%. scattaring calculation")
    file.close()
    print('DONE')
    return scatt_coeffs

abs_antlerit_file = 'our_antrelit_24Jul2019_r4.CSV'
refr_antlerit_file = 'calc_refr_result_' + abs_antlerit_file[:-4]

n_antlerit = find_refr_from_abs(abs_antlerit_file, refr_antlerit_file)

abs_C6_file = 'C6_300C_77K_5Dec2018.CSV'
refr_C6_file = 'calc_refr_result_' + abs_C6_file[:-4]

n_C6 = find_refr_from_abs(abs_C6_file, refr_C6_file)

particle_d = 5 #diametr, um
V = (4 / 3) * ((particle_d * 10**(-6)) ** 3)  * PI
sc_const = 24 * PI**3 * V**2
w_numbs = list(csv_to_dict('data/C6_300C_77K_5Dec2018.CSV').keys())
scat_spec = full_scat_int(n_C6, n_antlerit, w_numbs, sc_const, 'abs(C6-antl)_prtcl_sz_5000nm')


import math
import numpy as np
import tensorflow as tf
import datetime

from tensorflow.python.ops import array_ops
from tensorflow.models.rnn import rnn_cell, rnn, seq2seq

class Tagger(object):
    """LSTM tagger model."""
    def __init__(self, vocab, tagset, alphabet, word_embedding_size,
                 char_embedding_size, num_chars, num_steps, optimizer_desc,
                 generate_lemmas, l2, dropout_prob_values, experiment_name,
                 supply_form_characters_to_lemma, threads=0, seed=None, write_summaries=True, use_attention=True, scheduled_sampling=None):
        """
        Builds the tagger computation graph and initializes it in a TensorFlow
        session.

        Arguments:

            vocab: Vocabulary of word forms.

            tagset: Vocabulary of possible tags.

            alphabet: Vocabulary of possible characters.

            word_embedding_size (int): Size of the form-based word embedding.

            char_embedding_size (int): Size of character embeddings, i.e. a
                half of the size of the character-based words embeddings.

            num_chars: Maximum length of a word.

            num_steps: Maximum lenght of a sentence.

            optimizer_desc: Description of the optimizer.

            generate_lemmas: Generate lemmas during tagging.

            seed: TensorFlow seed

            write_summaries: Write summaries using TensorFlow interface.
        """

        self.num_steps = num_steps
        self.num_chars = num_chars

        self.word_embedding_size = word_embedding_size
        self.char_embedding_size = char_embedding_size
        self.lstm_size = word_embedding_size + 2 * char_embedding_size ###

        self.vocab = vocab
        self.tagset = tagset
        self.alphabet = alphabet

        self.dropout_prob_values = dropout_prob_values

        self.forward_initial_state = tf.placeholder(tf.float32, [None, rnn_cell.BasicLSTMCell(self.lstm_size).state_size], name="forward_lstm_initial_state")
        self.backward_initial_state = tf.placeholder(tf.float32, [None, rnn_cell.BasicLSTMCell(self.lstm_size).state_size], name="backward_lstm_initial_state")
        self.sentence_lengths = tf.placeholder(tf.int64, [None], name="sentence_lengths")
        self.tags = tf.placeholder(tf.int32, [None, num_steps], name="ground_truth_tags")
        self.dropout_prob = tf.placeholder(tf.float32, [None], name="dropout_keep_p")
        self.generate_lemmas = generate_lemmas

        global_step = tf.Variable(0, trainable=False)

        input_list = []
        regularize = []

        # Word-level embeddings
        if word_embedding_size:
            self.words = tf.placeholder(tf.int32, [None, num_steps], name='words')
            word_embeddings = tf.Variable(tf.random_uniform([len(vocab), word_embedding_size], -1.0, 1.0))
            we_lookup = tf.nn.embedding_lookup(word_embeddings, self.words)

            input_list.append(we_lookup)

        # Character-level embeddings
        if char_embedding_size:
            self.chars = tf.placeholder(tf.int32, [None, num_steps, num_chars], name='chars')
            self.chars_lengths = tf.placeholder(tf.int64, [None, num_steps], name='chars_lengths')

            char_embeddings = \
                tf.Variable(tf.random_uniform([len(alphabet), char_embedding_size], -1.0, 1.0))
            ce_lookup = tf.nn.embedding_lookup(char_embeddings, self.chars)

            reshaped_ce_lookup = tf.reshape(ce_lookup, [-1, num_chars, char_embedding_size],
                                                             name="reshape-char_inputs")
            char_inputs = [tf.squeeze(input_, [1]) for input_ in
                           tf.split(1, num_chars, reshaped_ce_lookup)]

            char_inputs_lengths = tf.reshape(self.chars_lengths, [-1])

            with tf.variable_scope('char_forward'):
                char_lstm = rnn_cell.BasicLSTMCell(char_embedding_size)
                _, char_last_state = rnn.rnn(
                    cell=char_lstm,
                    inputs=char_inputs,
                    sequence_length=char_inputs_lengths,
                    dtype=tf.float32)
                tf.get_variable_scope().reuse_variables()
                regularize.append(tf.get_variable('RNN/BasicLSTMCell/Linear/Matrix'))

            with tf.variable_scope('char_backward'):
                char_lstm_rev = rnn_cell.BasicLSTMCell(char_embedding_size)
                _, char_last_state_rev = rnn.rnn(
                    cell=char_lstm_rev,
                    inputs=self._reverse_seq(char_inputs, char_inputs_lengths),
                    sequence_length=char_inputs_lengths,
                    dtype=tf.float32)
                tf.get_variable_scope().reuse_variables()
                regularize.append(tf.get_variable('RNN/BasicLSTMCell/Linear/Matrix'))

            last_char_lstm_state = tf.split(1, 2, char_last_state)[1]
            last_char_lstm_state_rev = tf.split(1, 2, char_last_state_rev)[1]

            last_char_states = \
                tf.reshape(last_char_lstm_state, [-1, num_steps, char_embedding_size],
                           name="reshape-charstates")
            last_char_states_rev = tf.reshape(last_char_lstm_state_rev, [-1, num_steps, char_embedding_size], name="reshape-charstates_rev")

            char_output = tf.concat(2, [last_char_states, last_char_states_rev])

            input_list.append(char_output)

        # All inputs correctly sliced
        input_list_dropped = [tf.nn.dropout(x, self.dropout_prob[0]) for x in input_list]
        inputs = [tf.squeeze(input_, [1]) for input_ in tf.split(1, num_steps, tf.concat(2, input_list_dropped))]

        with tf.variable_scope('forward'):
            lstm = rnn_cell.BasicLSTMCell(self.lstm_size)
            outputs, last_state = rnn.rnn(
                cell=lstm,
                inputs=inputs, dtype=tf.float32,
                initial_state=self.forward_initial_state,
                sequence_length=self.sentence_lengths)

            tf.get_variable_scope().reuse_variables()
            regularize.append(tf.get_variable('RNN/BasicLSTMCell/Linear/Matrix'))

        with tf.variable_scope('backward'):
            lstm_rev = rnn_cell.BasicLSTMCell(self.lstm_size)
            outputs_rev_rev, last_state_rev = rnn.rnn(
                cell=lstm_rev,
                inputs=self._reverse_seq(inputs, self.sentence_lengths), dtype=tf.float32,
                initial_state=self.backward_initial_state,
                sequence_length=self.sentence_lengths)

            outputs_rev=self._reverse_seq(outputs_rev_rev, self.sentence_lengths)

            tf.get_variable_scope().reuse_variables()
            regularize.append(tf.get_variable('RNN/BasicLSTMCell/Linear/Matrix'))

        #outputs_forward = tf.reshape(tf.concat(1, outputs), [-1, self.lstm_size],
        #                    name="reshape-outputs_forward")

        #outputs_backward = tf.reshape(tf.concat(1, outputs_rev), [-1, self.lstm_size],
        #                    name="reshape-outputs_backward")

        #forward_w = tf.get_variable("forward_w", [self.lstm_size, self.lstm_size])
        #backward_w = tf.get_variable("backward_w", [self.lstm_size, self.lstm_size])
        #non_linearity_bias = tf.get_variable("non_linearity_b", [self.lstm_size])

        outputs_bidi = [tf.concat(1, [o1, o2]) for o1, o2 in zip(outputs, reversed(outputs_rev))]

        #output = tf.tanh(tf.matmul(outputs_forward, forward_w) + tf.matmul(outputs_backward, backward_w) + non_linearity_bias)
        output = tf.reshape(tf.concat(1, outputs_bidi), [-1, 2 * self.lstm_size],
                            name="reshape-outputs_bidi")
        output_dropped = tf.nn.dropout(output, self.dropout_prob[1])

        # We are computing only the logits, not the actual softmax -- while
        # computing the loss, it is done by the sequence_loss_by_example and
        # during the runtime classification, the argmax over logits is enough.

        softmax_w = tf.get_variable("softmax_w", [2 * self.lstm_size, len(tagset)])
        logits_flatten = tf.nn.xw_plus_b(
            output_dropped,
            softmax_w,
            tf.get_variable("softmax_b", [len(tagset)]))
        #tf.get_variable_scope().reuse_variables()
        regularize.append(softmax_w)

        self.logits = tf.reshape(logits_flatten, [-1, num_steps, len(tagset)], name="reshape-logits")
        estimated_tags_flat = tf.to_int32(tf.argmax(logits_flatten, dimension=1))
        self.last_state = last_state

        # output maks: compute loss only if it insn't a padded word (i.e. zero index)
        output_mask = tf.reshape(tf.to_float(tf.not_equal(self.tags, 0)), [-1])

        gt_tags_flat = tf.reshape(self.tags, [-1])
        tagging_loss = seq2seq.sequence_loss_by_example(
            logits=[logits_flatten],
            targets=[gt_tags_flat],
            weights=[output_mask])

        tagging_accuracy = \
            tf.reduce_sum(tf.to_float(tf.equal(estimated_tags_flat, gt_tags_flat)) * output_mask) \
                / tf.reduce_sum(output_mask)
        tf.scalar_summary('train_accuracy', tagging_accuracy, collections=["train"])
        tf.scalar_summary('dev_accuracy', tagging_accuracy, collections=["dev"])

        self.cost = tf.reduce_mean(tagging_loss)

        tf.scalar_summary('train_tagging_loss', tf.reduce_mean(tagging_loss), collections=["train"])
        tf.scalar_summary('dev_tagging_loss', tf.reduce_mean(tagging_loss), collections=["dev"])

        if generate_lemmas:
            with tf.variable_scope('decoder'):
                self.lemma_chars = tf.placeholder(tf.int32, [None, num_steps, num_chars + 2],
                                                  name='lemma_chars')

                lemma_state_size = self.lstm_size

                lemma_w = tf.Variable(tf.random_uniform([lemma_state_size, len(alphabet)], 0.5),
                                           name="state_to_char_w")
                lemma_b = tf.Variable(tf.fill([len(alphabet)], - math.log(len(alphabet))),
                                           name="state_to_char_b")
                lemma_char_embeddings = tf.Variable(tf.random_uniform([len(alphabet), lemma_state_size / (2 if supply_form_characters_to_lemma else 1)], -0.5, 0.5),
                                                    name="char_embeddings")

                lemma_char_inputs = \
                    [tf.squeeze(input_, [1]) for input_ in
                        tf.split(1, num_chars + 2, tf.reshape(self.lemma_chars, [-1, num_chars + 2],
                                                              name="reshape-lemma_char_inputs"))]

                if supply_form_characters_to_lemma:
                    char_inputs_zeros = \
                        [tf.squeeze(chars, [1]) for chars in
                            tf.split(1, num_chars, tf.reshape(self.chars, [-1, num_chars],
                                                              name="reshape-char_inputs_zeros"))]
                    char_inputs_zeros.append(char_inputs_zeros[0] * 0)

                    def loop(prev_state, i):
                        # it takes the previous hidden state, finds the character and formats it
                        # as input for the next time step ... used in the decoder in the "real decoding scenario"
                        out_activation = tf.matmul(prev_state, lemma_w) + lemma_b
                        prev_char_index = tf.argmax(out_activation, 1)
                        return tf.concat(1, [tf.nn.embedding_lookup(lemma_char_embeddings, prev_char_index),
                                             tf.nn.embedding_lookup(lemma_char_embeddings, char_inputs_zeros[i])])

                    embedded_lemma_characters = []
                    for lemma_chars, form_chars in zip(lemma_char_inputs[:-1], char_inputs_zeros):
                        embedded_lemma_characters.append(
                            tf.concat(1, [tf.nn.embedding_lookup(lemma_char_embeddings, lemma_chars),
                                          tf.nn.embedding_lookup(lemma_char_embeddings, form_chars)])
                        )
                else:
                    def loop(prev_state, _):
                        # it takes the previous hidden state, finds the character and formats it
                        # as input for the next time step ... used in the decoder in the "real decoding scenario"
                        out_activation = tf.matmul(prev_state, lemma_w) + lemma_b
                        prev_char_index = tf.argmax(out_activation, 1)
                        return tf.nn.embedding_lookup(lemma_char_embeddings, prev_char_index)

                    embedded_lemma_characters = []
                    for lemma_chars in lemma_char_inputs[:-1]:
                        embedded_lemma_characters.append(tf.nn.embedding_lookup(lemma_char_embeddings, lemma_chars))

                def sampling_loop(prev_state, i):
                    threshold = scheduled_sampling / (scheduled_sampling + tf.exp(tf.to_float(global_step)))
                    condition = tf.less_equal(tf.random_uniform(tf.shape(embedded_lemma_characters[0])), threshold)
                    return tf.select(condition, embedded_lemma_characters[i], loop(prev_state,i))

                decoder_cell = rnn_cell.BasicLSTMCell(lemma_state_size)

                if scheduled_sampling:
                    lf = sampling_loop
                else:
                    lf = None

                if use_attention:
                    lemma_outputs_train, _ = seq2seq.attention_decoder(embedded_lemma_characters, output_dropped, reshaped_ce_lookup, decoder_cell, loop_function=lf)
                else:
                    lemma_outputs_train, _ = seq2seq.rnn_decoder(embedded_lemma_characters, output_dropped, decoder_cell, loop_function=lf)

                tf.get_variable_scope().reuse_variables()
                #regularize.append(tf.get_variable('attention_decoder/BasicLSTMCell/Linear/Matrix'))

                tf.get_variable_scope().reuse_variables()

                if use_attention:
                    lemma_outputs_runtime, _ = \
                        seq2seq.attention_decoder(embedded_lemma_characters, output_dropped, reshaped_ce_lookup, decoder_cell,
                            loop_function=loop)
                else:
                    lemma_outputs_runtime, _ = \
                        seq2seq.rnn_decoder(embedded_lemma_characters, output_dropped, decoder_cell,
                            loop_function=loop)

                lemma_char_logits_train = \
                    [tf.matmul(o, lemma_w) + lemma_b for o in lemma_outputs_train]

                lemma_char_logits_runtime = \
                    [tf.matmul(o, lemma_w) + lemma_b for o in lemma_outputs_runtime]

                self.lemmas_decoded = \
                    tf.reshape(tf.transpose(tf.argmax(tf.pack(lemma_char_logits_runtime), 2)), [-1, num_steps, num_chars + 1])

                lemma_char_weights = []
                for lemma_chars in lemma_char_inputs[1:]:
                    lemma_char_weights.append(tf.to_float(tf.not_equal(lemma_chars, 0)))

                lemmatizer_loss = seq2seq.sequence_loss(lemma_char_logits_train, lemma_char_inputs[1:],
                                                        lemma_char_weights)

                lemmatizer_loss_runtime = \
                        seq2seq.sequence_loss(lemma_char_logits_runtime, lemma_char_inputs[1:],
                                              lemma_char_weights)

                tf.scalar_summary('train_lemma_loss_with_gt_inputs',
                                  tf.reduce_mean(lemmatizer_loss), collections=["train"])
                tf.scalar_summary('dev_lemma_loss_with_gt_inputs',
                                  tf.reduce_mean(lemmatizer_loss), collections=["dev"])

                tf.scalar_summary('train_lemma_loss_with_decoded_inputs',
                                  tf.reduce_mean(lemmatizer_loss_runtime), collections=["train"])
                tf.scalar_summary('dev_lemma_loss_with_decoded_inputs',
                                  tf.reduce_mean(lemmatizer_loss_runtime), collections=["dev"])

                self.cost += tf.reduce_mean(lemmatizer_loss) + tf.reduce_mean(lemmatizer_loss_runtime)

        self.cost += l2 * sum([tf.nn.l2_loss(variable) for variable in regularize])

        tf.scalar_summary('train_optimization_cost', self.cost, collections=["train"])
        tf.scalar_summary('dev_optimization_cost', self.cost, collections=["dev"])

        def decay(learning_rate, exponent, iteration_steps):
            return tf.train.exponential_decay(learning_rate, global_step,
                                              iteration_steps, exponent, staircase=True)

        optimizer = eval('tf.train.' + optimizer_desc)
        self.train = optimizer.minimize(self.cost, global_step=global_step)

        if threads > 0:
            self.session = tf.Session(config=tf.ConfigProto(inter_op_parallelism_threads=threads,
                                                            intra_op_parallelism_threads=threads))
        else:
            self.session = tf.Session()
        self.session.run(tf.initialize_all_variables())

        if write_summaries:
            self.summary_train = tf.merge_summary(tf.get_collection("train"))
            self.summary_dev = tf.merge_summary(tf.get_collection("dev"))
            timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
            self.summary_writer = tf.train.SummaryWriter("logs/"+timestamp+"_"+experiment_name)

        self.steps = 0

    def learn(self, words, chars, tags, lengths, lemma_chars, chars_lengths):
        """Learn from the given minibatch."""

        initial_state = np.zeros([words.shape[0], 2 * self.lstm_size])
        self.steps += 1

        fd = {
            self.tags:tags,
            self.sentence_lengths: lengths,
            self.dropout_prob: self.dropout_prob_values,
            self.forward_initial_state: initial_state,
            self.backward_initial_state: initial_state
        }
        if self.word_embedding_size: fd[self.words] = words
        if self.char_embedding_size:
            fd[self.chars] = chars
            fd[self.chars_lengths] = chars_lengths
        if self.generate_lemmas: fd[self.lemma_chars] = lemma_chars

        _, cost, summary_str = \
                self.session.run([self.train, self.cost, self.summary_train], feed_dict=fd)
        if self.steps % 10 == 0:
            self.summary_writer.add_summary(summary_str, self.steps)

        return cost

    def predict_and_eval(self, words, chars, lengths, tags, lemma_chars, chars_lengths, out_summaries=True):
        """Predict tags for the given minibatch."""

        initial_state = np.zeros([words.shape[0], 2 * self.lstm_size])

        fd = {
            self.tags:tags,
            self.sentence_lengths: lengths,
            self.dropout_prob: np.array([1, 1]),
            self.forward_initial_state: initial_state,
            self.backward_initial_state: initial_state
        }
        if self.word_embedding_size: fd[self.words] = words
        if self.char_embedding_size:
            fd[self.chars] = chars
            fd[self.chars_lengths] = chars_lengths
        if self.generate_lemmas: fd[self.lemma_chars] = lemma_chars

        if self.generate_lemmas:
            logits, lemmas, summary_str = \
                    self.session.run([self.logits, self.lemmas_decoded, self.summary_dev], feed_dict=fd)
        else:
            logits, summary_str = \
                    self.session.run([self.logits, self.summary_dev], feed_dict=fd)
            lemmas = None
        if out_summaries:
            self.summary_writer.add_summary(summary_str, self.steps)

        return np.argmax(logits, axis=2), lemmas

    def tag_single_sentence(self, words, chars):
        """Tags a sentence of arbitrary length."""

        initial_state = np.zeros([1, 2 * self.lstm_size])
        backward_initial_state = np.zeros([1, 2 * self.lstm_size])

        tags = []
        for start in xrange(0, len(words), self.num_steps):
            w = np.zeros((1, self.num_steps), dtype='int32')
            for i, w_id in enumerate(words[start:start+self.num_steps]):
                w[0, i] = w_id
            c = np.zeros((1, self.num_steps, self.num_chars), dtype='int32')
            for i, chared_word in enumerate(chars[start:start+self.num_steps]):
                for j, c_id in enumerate(chared_word[:self.num_chars]):
                    c[0, i, j] = c_id

            fd = {
                self.sentence_lengths: [self.num_steps],
                self.dropout_prob: np.array([1, 1]),
                self.forward_initial_state: initial_state,
                self.backward_initial_state: backward_initial_state
            }
            if self.word_embedding_size: fd[self.words] = w
            if self.char_embedding_size: fd[self.chars] = c

            logits, state = self.session.run([self.logits, self.last_state], feed_dict=fd)

            initial_state = state
            tags.extend(np.argmax(logits[0], axis=1))

        return [int(x) for x in tags[:len(words)]]

    def _reverse_seq(self, input_seq, lengths):
      """Reverse a list of Tensors up to specified lengths.

      Args:
        input_seq: Sequence of seq_len tensors of dimension (batch_size, depth)
        lengths:   A tensor of dimension batch_size, containing lengths for each
                   sequence in the batch. If "None" is specified, simply reverses
                   the list.

      Returns:
        time-reversed sequence
      """
      if lengths is None:
        return list(reversed(input_seq))

      for input_ in input_seq:
        input_.set_shape(input_.get_shape().with_rank(2))

      # Join into (time, batch_size, depth)
      s_joined = array_ops.pack(input_seq)

      # Reverse along dimension 0
      s_reversed = array_ops.reverse_sequence(s_joined, lengths, 0, 1)
      # Split again into list
      result = array_ops.unpack(s_reversed)
      return result


import socket

HOST = '127.0.0.1'
PORT = 9010

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.SOL_TCP)
socket.connect((HOST, PORT))

def normalize(value, minValue, maxValue):
    if (maxValue - minValue) <= 0:
        return 0

    normalized = (value - minValue) / (maxValue - minValue)

    return normalized

def deNormalize(normalized, minValue, maxValue):
    deNormalized = ((normalized * (maxValue - minValue)) + minValue)

    return deNormalized;

cases = [
    [0, 0],
    [1, 1],
    [1, 0],
    [0, 1],
]

print('Sending data')

for (caseNr, case) in enumerate(cases):
    socket.sendall(
        str("{\"command\": \"compute\", \"input\": [" + str(case[0]) + ", " + str(
            case[1]) + "]}" + '\n').encode())

    print('Wait for return')
    incomingBuffer = ''
    running = True
    while running:

        # For now accepting max message size of 2048 (Individual message!)
        dataStringRaw = socket.recv(2048)
        dataString = dataStringRaw.decode()

        if not dataString:
            break

        incomingBuffer = incomingBuffer + dataString
        strings = incomingBuffer.split('\n')
        for message in strings[:-1]:
            print('Response for case' + str(case) + ': ')
            print(message)

            if '\0' in message:
                running = False

        incomingBuffer = strings[-1]

        # One response with a termination found.
        if '\0' in incomingBuffer:
            print(str(incomingBuffer))
            running = False

print('Shutting down')
# Graceful shutdown
socket.shutdown(1)
socket.close()

print('Exit')


# ZADACHA 1:
# POLUCHENIE CHISLA FAKTORIALA PRI POMOSHI REKURSIYI

def fact(x):
    if x == 1:
        return 1
    return fact(x - 1) * x

print(fact(8))

# 1 * 1 1
# 2 * 3 6
# 6 * 4 24
# 24 * 5 120
# 120 * 6 720
# 720 * 7 5040
# 5040 * 8 40320
# 40320 * 9 362880
# 362880 * 10 3628800

print("-------------------------------------")

# ZADACHA 2:
# POLUCHENIE CHISLA FIBONACHI OT VVEDENNOGO CHISLA PRI POMOSHI REKURSIYI

def fib(n):
    if n == 1:
        return 0
    if n == 2:
        return 1
    return fib(n-1) + fib(n-2)

print(fib(7))

print("-------------------------------------")

# ZADACHA 3:
# PROVERKA STROKI NA POLYNDROM PRI POMOSHI REKURSIYI

def palindrom(s):
    if len(s) <= 1:  # proverka dlinni stroki
        return True
    if s[0] != s[-1]:  # proverka na sravnenie 1 i poslednego simvola na ravenstvo
        return False
    return palindrom(s[1:-1])  # proverka vsey stroki pri pomoshi sreza s 1 po posledniy simvol

print(palindrom("к"))
print(palindrom("пп"))
print(palindrom("ка"))
print(palindrom("калук"))

print("-------------------------------------")

# ZADACHA 4:
# VVODITSYA STROKA NE NYLEVOY DLINI. IZVESTNO TAKZHE, CHTO DLINA NE PREVISHAET 1000 ZNAKOV.
# VIVESTI STROK, KOTORAYA POLUCHITSYA POSLE DOBAVLENIYA SKOBOK.
# PRIMER:
# STROKA = lItBeoFLcSGBOFQxMHoIUDDWcqcVgkcRoAeocXO
# RESULTAT = l(I(t(B(e(o(F(L(c(S(G(B(O(F(Q(x(M(H(o(I)U)D)D)W)c)q)c)V)g)k)c)R)o)A)e)o)c))X)O

def rec(sw):
    if len(sw) == 1 or len(sw) == 2:
        return sw
    return sw[0] + '(' + rec(sw[1:-1]) + ')' + sw[-1]

# sw = input()
# print(rec(sw))

print("-------------------------------------")

# ZADACHA 5:
# FUNKCIYA V KOTOROY CHISLO "X" VOZVODITSYA V STEPEN "N" PRI POMOSHI REKURSIYI

def power(x, n):
    if n == 0:
        return 1
    if n < 0:
        return 1/power(x, -n)  # vozvedenie v otricatelnuyu stepen
    if n % 2 == 0:
        return power(x, n // 2) * power(x, n // 2)
    else:
        return power(x, n - 1) * x

# x = int(input())
# n = int(input())
# print(power(x, n))

print("-------------------------------------")

# ZADACHA 6:
# EST SPISOK NADO OPREDELIT NA KAKOM UROVNE NAHODITSYA KAZHDIY IZ VLOZHENNIH SPISKOV

a = [1, [3, [4, [3, 4]], [2, 3, [4]]], 2, [2, 3, 4, [3, 4, [2, 3], 5]]]

def rec_num(spicok, level=1):
    pass
    print(*spicok, 'level=', level)  # * - chtobi vse elementy raspakovalis i vivelis cherez probel bez kvadrathih skobok
    for i in spicok:
        if type(i) == list:
            rec_num(i, level+1)

rec_num(a)

print("-------------------------------------")

# ZADACHA 7:
# OBHOD FAILOV V PAPKE PRI POMOSHI REKURSIYI

import os  # import module os

path = 'C:\\Users\\p6334\\OneDrive\\Desktop\\test_python'  # dobavlenie \ dlya korektnogo otobrazheniya puti

print(os.listdir(path))  # perechen soderzhimogo puti

def obxodFile(path, level=1):
    print('level=', level, 'Content:', os.listdir(path))
    for i in os.listdir(path):
        if os.path.isdir(path + '\\' + i):
            print('Спускаемся', path + '\\' + i)
            obxodFile(path + '\\' + i, level + 1)
            print('Вовращаемся в', path)

obxodFile(path)

# for i in os.listdir(path):  # perebor soderzhimogo puti
#       print(i, type(i), path + '\\' + i, os.path.isdir(path + '\\' + i))
# isdir - proverka na papky
# isfile - proverka na fayl
# proverka soderzhimogo na tip i proverka chto yavlyaetsya papkoy a chto faylom


class Solution:
    def numIslands(self, grid):
        count = 0
        if not grid:
            return count

        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if grid[i][j] == "1":
                    self._dfs(grid, i, j)
                    print(grid)
                    count += 1
        return count

    def _dfs(self, grid, i, j):
        if i<0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] != "1":
            return
        grid[i][j] = "#" # Mark it as visited in place
        self._dfs(grid, i-1, j)
        self._dfs(grid, i+1, j)
        self._dfs(grid, i, j-1)
        self._dfs(grid, i, j+1)

if __name__ == "__main__":
    test_cases = [
        [
            ["1","1","1","1","0"],
            ["1","1","0","1","0"],
            ["1","1","0","0","0"],
            ["0","0","0","0","0"]
        ],
        [
            ["1","1","0","0","0"],
            ["1","1","0","0","0"],
            ["0","0","1","0","0"],
            ["0","0","0","1","1"]
        ]
    ]

    solution = Solution()
    for grid in test_cases:
        print(solution.numIslands(grid))