import json

from odoo.http import request, route
from odoo.addons.website_sale.controllers.main import WebsiteSale

class WebsiteSaleProductComparison(WebsiteSale):

    @route('/shop/compare', type='http', auth='public', website=True, sitemap=False)
    def product_compare(self, **post):
        values = {}
        product_ids = [int(i) for i in post.get('products', '').split(',') if i.isdigit()]
        if not product_ids:
            return request.redirect("/shop")
        # use search to check read access on each record/ids
        products = request.env['product.product'].search([('id', 'in', product_ids)])
        values['products'] = products.with_context(display_default_code=False)
        return request.render("website_sale_comparison.product_compare", values)

    @route('/shop/get_product_data', type='json', auth='public', website=True)
    def get_product_data(self, product_ids, cookies=None):
        ret = {}

        website = request.env['website'].get_current_website()
        products = request.env['product.product'].search([('id', 'in', product_ids)])

        if cookies is not None:
            ret['cookies'] = json.dumps(request.env['product.product'].search([('id', 'in', list(set(product_ids + cookies)))]).ids)

        products = products.with_context(display_default_code=False)
        for product in products:
            ret[product.id] = {
                'render': request.env['ir.ui.view']._render_template(
                    "website_sale_comparison.product_product",
                    {'product': product, 'website': website}
                ),
                'product': dict(id=product.id, name=product.name, display_name=product.display_name),
            }
        return ret


import io
import pytest
import random
import string

from unittest import mock

import snarl.exc
import snarl.main

@pytest.fixture(scope='function')
def snarlobj():
    return snarl.main.Snarl()

def test_include_recursive(snarlobj):
    def doc():
        data = '\n'.join(('This is a test',
                          '',
                          '<!-- include recursive.snarl.md -->'
                          ))
        return io.StringIO(data)

    with mock.patch('snarl.main.open', create=True) as mock_open:
        mock_open.side_effect = lambda x, y: doc()
        with pytest.raises(snarl.exc.RecursiveIncludeError):
            snarlobj.parse(doc())

def test_include_simple(snarlobj):
    parent = '<!-- include simple.snarl.md -->\n'
    child = io.StringIO('included document')

    with mock.patch('snarl.main.open', create=True) as mock_open:
        mock_open.side_effect = lambda x, y: child
        snarlobj.fromstring(parent)
        assert 'included document' in '\n'.join(snarlobj.output)

def test_include_escape(snarlobj):
    parent = '<!-- include simple.snarl.md --escape-html -->\n'
    child = io.StringIO('<This is a test>')

    with mock.patch('snarl.main.open', create=True) as mock_open:
        mock_open.side_effect = lambda x, y: child
        snarlobj.fromstring(parent)
        assert '<This is a test>' in '\n'.join(snarlobj.output)

def test_include_verbatim(snarlobj):
    parent = '<!-- include simple.snarl.md --verbatim -->\n'
    child = io.StringIO('<!-- include testfile -->')

    with mock.patch('snarl.main.open', create=True) as mock_open:
        mock_open.side_effect = lambda x, y: child
        snarlobj.fromstring(parent)
        assert '<!-- include testfile -->' in '\n'.join(snarlobj.output)

def test_file(snarlobj):
    doc = '\n'.join(('```=block0',
                     f'This is block0.',
                     '```',
                     '```=output.txt --file',
                     '<<block0>>',
                     '```'))

    snarlobj.fromstring(doc)
    assert 'output.txt' in snarlobj.files()
    assert 'This is block0.' in ''.join(snarlobj.generate('output.txt'))

def test_lang_block(snarlobj):
    doc = '\n'.join(('```python:block0',
                     'print("This is a test")',
                     '```'))

    snarlobj.fromstring(doc)
    assert '```python' in '\n'.join(snarlobj.output)

def test_hide_block(snarlobj):
    doc = '\n'.join(('```=block0 --hide',
                     'This should not appear in weave output',
                     '```'))

    snarlobj.fromstring(doc)
    assert 'This should not appear in weave output' not in '\n'.join(snarlobj.output)

def test_block_escape(snarlobj):
    doc = '\n'.join(('```=block0 --escape-html',
                     '<This is a test>',
                     '```'))

    snarlobj.fromstring(doc)
    assert '<This is a test>' in '\n'.join(snarlobj.output)

def test_block_verbatim(snarlobj):
    doc = '\n'.join(('```=block0 --verbatim',
                     '<<This is a test>>',
                     '```'))

    snarlobj.fromstring(doc)
    assert '<<This is a test>>' in '\n'.join(snarlobj.output)

def test_block_unknown(snarlobj):
    doc = '\n'.join(('```=block0',
                     '<<This is a test>>',
                     '```'))

    snarlobj.fromstring(doc)
    with pytest.raises(KeyError):
        '\n'.join(snarlobj.generate('block0'))

def test_append_block(snarlobj):
    doc = '\n'.join(('```=block0',
                     'this is line1',
                     '```',
                     '```+=block0',
                     'this is line2',
                     '```'))
    snarlobj.fromstring(doc)
    assert 'this is line2' in '\n'.join(snarlobj.generate('block0'))

def test_replace(snarlobj):
    doc = '\n'.join(('```=block0 --replace gadgets gizmos',
                     'An article about gadgets.',
                     '```'))

    snarlobj.fromstring(doc)
    assert 'gizmos' in '\n'.join(snarlobj.generate('block0'))

def test_unknown_block_arg(snarlobj):
    doc = '\n'.join((
        '```=foo --unknown',
    ))

    with pytest.raises(snarl.exc.BlockArgumentError):
        snarlobj.fromstring(doc)

def test_tags(snarlobj):
    doc = '\n'.join(('```=block0 -t foo',
                     'This is block0',
                     '```',
                     '',
                     '```=block1 -t bar',
                     'This is block1',
                     '```'))

    snarlobj.fromstring(doc)
    assert 'block0' in snarlobj.blocks(tags=['foo'])
    assert 'block1' not in snarlobj.blocks(tags=['foo'])
    assert 'block1' in snarlobj.blocks(tags=['bar'])
    assert 'block0' not in snarlobj.blocks(tags=['bar'])

def test_unterminated_block(snarlobj):
    doc = '\n'.join((
        '```block0',
        'This block has no end marker.',
    ))

    with pytest.raises(snarl.exc.UnexpectedEOFError):
        snarlobj.fromstring(doc)


#!/usr/bin/env python3

import pickle
import numpy as np

from reinforcement_frog.settings import (
    rows, columns,
    gamma, alpha,
    epsilon, n_actions,
    actions, board_epsilon,
    ACTIONS
)

from reinforcement_frog.board import Agent, Board
import matplotlib.pyplot as plt

def save(obj, name):
    with open(name, mode='wb') as fp:
        fp.write(pickle.dumps(obj))

def load(name):
    with open(name, 'rb') as fp:
        return pickle.loads(fp.read())

if __name__ == '__main__':
    Q = np.zeros((rows * columns, n_actions))
    bestQ = None

    total_mean_score = []
    completed = 0
    explorations = 0
    max_reward = -30000
    max_gen = 3000
    last = 1
    for gen in range(1, max_gen + 1):
        state = 0
        a = Agent(epsilon, actions, max_gen // 2)
        b = Board(rows, columns, a, board_epsilon, True)

        scores = []
        for new_state in range(rows * columns):
            action, exploration = a.action(Q, b.board, state, gen-1)
            reward, dist, c = b.move(action)

            if exploration:
                explorations += 1

            if c:
                completed += 1
                break

            if reward > max_reward:
                max_reward = reward
                bestQ = Q.copy()

            scores.append(reward)
            ai = actions.index(action)
            qmax = np.max(Q[new_state, :])
            Q[state, ai] += alpha * (reward + gamma * qmax - Q[state, ai])

            s = f"""
            Generation\t{gen}
            Completed\t{completed}
            Explorations\t{explorations}
            Accuracy\t{completed / gen * 100}
            Moves\t{b.n_moves}
            Avg. Score\t{np.nanmean(total_mean_score)}
            Score\t{reward}
            Max. Reward\t{max_reward}
            Action:\t{ACTIONS.get(action)}
            Distance:\t{dist}
            """
            print(chr(27) + "[2J")
            print(s, end='\r')
            state = new_state

        total_mean_score.append(np.nanmean(scores))

        last = gen

    save(bestQ, 'best_qtable.t')
    save(Q, 'qtable.t')


import logging
from pathlib import Path

from farm.data_handler.processor import TextClassificationProcessor
from farm.modeling.tokenization import Tokenizer
from farm.utils import set_all_seeds
import torch

def test_processor_saving_loading(caplog):
    if caplog is not None:
        caplog.set_level(logging.CRITICAL)

    set_all_seeds(seed=42)
    lang_model = "bert-base-cased"

    tokenizer = Tokenizer.load(
        pretrained_model_name_or_path=lang_model, do_lower_case=False
    )

    processor = TextClassificationProcessor(tokenizer=tokenizer,
                                            max_seq_len=128,
                                            data_dir=Path("samples/doc_class"),
                                            train_filename="train-sample.tsv",
                                            dev_filename=None,
                                            test_filename=None,
                                            label_column_name="coarse_label",
                                            dev_split=0.1,
                                            label_list=["OTHER", "OFFENSE"],
                                            metric=["f1_macro"]
                                            )
    dicts = processor.file_to_dicts(file=Path("samples/doc_class/train-sample.tsv"))
    data, tensor_names, _ = processor.dataset_from_dicts(dicts)

    save_dir = Path("testsave/processor")
    processor.save(save_dir)

    processor = processor.load_from_dir(save_dir)
    dicts = processor.file_to_dicts(file=Path("samples/doc_class/train-sample.tsv"))
    data_loaded, tensor_names_loaded, _ = processor.dataset_from_dicts(dicts)

    assert tensor_names == tensor_names_loaded
    for i in range(len(data.tensors)):
        assert torch.all(torch.eq(data.tensors[i], data_loaded.tensors[i]))

if __name__ == "__main__":
    test_processor_saving_loading(None)


import json

python_dict = {
    "이름":"홍길동",
    "나이": 25,
    "거주지": "서울",
    "신체 정보": {
        "키" : 175.4,
        "몸무게" : 71.2
    },
    "취미": [
        "등산",
        "자전거 타기",
        "독서"
    ]

}
print(type(python_dict), python_dict)

json_data = json.dumps(python_dict) # json 형태로변환
print(type(json_data), json_data)

json_data = json.dumps(python_dict, sort_keys = True, indent = 4, ensure_ascii=False)
print(type(json_data), json_data)

python_dict2 = json.loads(json_data)
print(type(python_dict2), python_dict2)

student = [
    {
        'no': 1,
        'name': '김승영',
        'score': {'국어': 90, '영어': 90, '수학': 90}
    },
    {
        'no': 2,
        'name': '지재삼',
        'score': {'국어': 80, '영어': 79, '수학': 69}
    }
]

print(type(student))

#write
json_student = json.dumps(student) # json 형태로 변환
print(type(json_student))

with open('json_test.txt', 'w', encoding ='utf-8') as f:
    json.dump(json_student, f)  # json 파일 작성 한굴은 unicode형태로 저장

with open('json_test.txt', 'r', encoding ='utf-8') as f:
    x = json.load(f)    #json 형태의 파일 load
    print(type(x), x)

students = json.loads(x)
type(students)
for std in students:
    print("{}{} # {}{}{}"
            .format(type(std['no']),
                    type(std['name']),
                    type(std['score']['국어']),
                    type(std['score']['영어']),
                    type(std['score']['수학'])))
    print(std['no'], std['name'], end = ' ')
    total = sum([x for x in std['score'].values()])
    #total = std['score']['국어'] + std['score']['영어'] + std['score']['수학']
    [print(score, end=' ') for score in std['score'].values()]
    print(total, total /float(3))


# import only system from os
from os import system, name

# define our clear function
def clear():

    # for windows
    if name == 'nt':
        _ = system('cls')

    # for mac and linux(here, os.name is 'posix')
    else:
        _ = system('clear')

logo = '''
A u c t i o n   P r o g r a m
                         ___________
                         \         /
                          )_______(
                          |"""""""|_.-._,.---------.,_.-._
                          |       | | |               | | ''-.
                          |       |_| |_             _| |_..-'
                          |_______| '-' `'---------'` '-'
                          )"""""""(
                         /_________\\
                       .-------------.
                      /_______________\\
'''

clear()
end_of_program = False
bids_dict = {}
def personal_bid():
    global bids_dict
    print(logo)
    name = input("What's your name? ")
    bid = float(input("What's your bid? $"))
    bids_dict[name] = bid

def define_who_wins():
    global bids_dict
    clear()
    print(logo)
    max_bid = 0
    winner = ""
    for key in bids_dict:
        if bids_dict[key] > max_bid:
            winner = key
            max_bid = bids_dict[key]

    print(f"The highest bid was ${max_bid} and was done by {winner}")

while not end_of_program:
    personal_bid()
    again = input("Are There another bidders? (yes or no) ")
    if again == "no":
        define_who_wins()
        end_of_program = True
    elif again == "yes":
        clear()
    else:
        print("Ester egg !!!\n Program will be closed now!")
        break


import importlib
import pickle
from os import listdir
from os.path import join, exists
from typing import List

import numpy as np
from PIL import Image
from natsort import natsorted
from pyrep.objects import VisionSensor

from rlbench.backend.const import *
from rlbench.backend.utils import image_to_float_array, rgb_handles_to_mask
from rlbench.demo import Demo
from rlbench.observation_config import ObservationConfig

class InvalidTaskName(Exception):
    pass

def name_to_task_class(task_file: str):
    name = task_file.replace('.py', '')
    class_name = ''.join([w[0].upper() + w[1:] for w in name.split('_')])
    try:
        mod = importlib.import_module("rlbench.tasks.%s" % name)
        mod = importlib.reload(mod)
    except ModuleNotFoundError as e:
        raise InvalidTaskName(
            "The task file '%s' does not exist or cannot be compiled."
            % name) from e
    try:
        task_class = getattr(mod, class_name)
    except AttributeError as e:
        raise InvalidTaskName(
            "Cannot find the class name '%s' in the file '%s'."
            % (class_name, name)) from e
    return task_class

def get_stored_demos(amount: int, image_paths: bool, dataset_root: str,
                     variation_number: int, task_name: str,
                     obs_config: ObservationConfig,
                     random_selection: bool = True,
                     from_episode_number: int = 0) -> List[Demo]:

    task_root = join(dataset_root, task_name)
    if not exists(task_root):
        raise RuntimeError("Can't find the demos for %s at: %s" % (
            task_name, task_root))

    # Sample an amount of examples for the variation of this task
    examples_path = join(
        task_root, VARIATIONS_FOLDER % variation_number,
        EPISODES_FOLDER)
    examples = listdir(examples_path)
    if amount == -1:
        amount = len(examples)
    if amount > len(examples):
        raise RuntimeError(
            'You asked for %d examples, but only %d were available.' % (
                amount, len(examples)))
    if random_selection:
        selected_examples = np.random.choice(examples, amount, replace=False)
    else:
        selected_examples = natsorted(
            examples)[from_episode_number:from_episode_number+amount]

    # Process these examples (e.g. loading observations)
    demos = []
    for example in selected_examples:
        example_path = join(examples_path, example)
        with open(join(example_path, LOW_DIM_PICKLE), 'rb') as f:
            obs = pickle.load(f)

        l_sh_rgb_f = join(example_path, LEFT_SHOULDER_RGB_FOLDER)
        l_sh_depth_f = join(example_path, LEFT_SHOULDER_DEPTH_FOLDER)
        l_sh_mask_f = join(example_path, LEFT_SHOULDER_MASK_FOLDER)
        r_sh_rgb_f = join(example_path, RIGHT_SHOULDER_RGB_FOLDER)
        r_sh_depth_f = join(example_path, RIGHT_SHOULDER_DEPTH_FOLDER)
        r_sh_mask_f = join(example_path, RIGHT_SHOULDER_MASK_FOLDER)
        oh_rgb_f = join(example_path, OVERHEAD_RGB_FOLDER)
        oh_depth_f = join(example_path, OVERHEAD_DEPTH_FOLDER)
        oh_mask_f = join(example_path, OVERHEAD_MASK_FOLDER)
        wrist_rgb_f = join(example_path, WRIST_RGB_FOLDER)
        wrist_depth_f = join(example_path, WRIST_DEPTH_FOLDER)
        wrist_mask_f = join(example_path, WRIST_MASK_FOLDER)
        front_rgb_f = join(example_path, FRONT_RGB_FOLDER)
        front_depth_f = join(example_path, FRONT_DEPTH_FOLDER)
        front_mask_f = join(example_path, FRONT_MASK_FOLDER)

        num_steps = len(obs)

        if not (num_steps == len(listdir(l_sh_rgb_f)) == len(
                listdir(l_sh_depth_f)) == len(listdir(r_sh_rgb_f)) == len(
                listdir(r_sh_depth_f)) == len(listdir(oh_rgb_f)) == len(
                listdir(oh_depth_f)) == len(listdir(wrist_rgb_f)) == len(
                listdir(wrist_depth_f)) == len(listdir(front_rgb_f)) == len(
                listdir(front_depth_f))):
            raise RuntimeError('Broken dataset assumption')

        for i in range(num_steps):
            si = IMAGE_FORMAT % i
            if obs_config.left_shoulder_camera.rgb:
                obs[i].left_shoulder_rgb = join(l_sh_rgb_f, si)
            if obs_config.left_shoulder_camera.depth or obs_config.left_shoulder_camera.point_cloud:
                obs[i].left_shoulder_depth = join(l_sh_depth_f, si)
            if obs_config.left_shoulder_camera.mask:
                obs[i].left_shoulder_mask = join(l_sh_mask_f, si)
            if obs_config.right_shoulder_camera.rgb:
                obs[i].right_shoulder_rgb = join(r_sh_rgb_f, si)
            if obs_config.right_shoulder_camera.depth or obs_config.right_shoulder_camera.point_cloud:
                obs[i].right_shoulder_depth = join(r_sh_depth_f, si)
            if obs_config.right_shoulder_camera.mask:
                obs[i].right_shoulder_mask = join(r_sh_mask_f, si)
            if obs_config.overhead_camera.rgb:
                obs[i].overhead_rgb = join(oh_rgb_f, si)
            if obs_config.overhead_camera.depth or obs_config.overhead_camera.point_cloud:
                obs[i].overhead_depth = join(oh_depth_f, si)
            if obs_config.overhead_camera.mask:
                obs[i].overhead_mask = join(oh_mask_f, si)
            if obs_config.wrist_camera.rgb:
                obs[i].wrist_rgb = join(wrist_rgb_f, si)
            if obs_config.wrist_camera.depth or obs_config.wrist_camera.point_cloud:
                obs[i].wrist_depth = join(wrist_depth_f, si)
            if obs_config.wrist_camera.mask:
                obs[i].wrist_mask = join(wrist_mask_f, si)
            if obs_config.front_camera.rgb:
                obs[i].front_rgb = join(front_rgb_f, si)
            if obs_config.front_camera.depth or obs_config.front_camera.point_cloud:
                obs[i].front_depth = join(front_depth_f, si)
            if obs_config.front_camera.mask:
                obs[i].front_mask = join(front_mask_f, si)

            # Remove low dim info if necessary
            if not obs_config.joint_velocities:
                obs[i].joint_velocities = None
            if not obs_config.joint_positions:
                obs[i].joint_positions = None
            if not obs_config.joint_forces:
                obs[i].joint_forces = None
            if not obs_config.gripper_open:
                obs[i].gripper_open = None
            if not obs_config.gripper_pose:
                obs[i].gripper_pose = None
            if not obs_config.gripper_joint_positions:
                obs[i].gripper_joint_positions = None
            if not obs_config.gripper_touch_forces:
                obs[i].gripper_touch_forces = None
            if not obs_config.task_low_dim_state:
                obs[i].task_low_dim_state = None

        if not image_paths:
            for i in range(num_steps):
                if obs_config.left_shoulder_camera.rgb:
                    obs[i].left_shoulder_rgb = np.array(
                        _resize_if_needed(
                            Image.open(obs[i].left_shoulder_rgb),
                            obs_config.left_shoulder_camera.image_size))
                if obs_config.right_shoulder_camera.rgb:
                    obs[i].right_shoulder_rgb = np.array(
                        _resize_if_needed(Image.open(
                        obs[i].right_shoulder_rgb),
                            obs_config.right_shoulder_camera.image_size))
                if obs_config.overhead_camera.rgb:
                    obs[i].overhead_rgb = np.array(
                        _resize_if_needed(Image.open(
                        obs[i].overhead_rgb),
                            obs_config.overhead_camera.image_size))
                if obs_config.wrist_camera.rgb:
                    obs[i].wrist_rgb = np.array(
                        _resize_if_needed(
                            Image.open(obs[i].wrist_rgb),
                            obs_config.wrist_camera.image_size))
                if obs_config.front_camera.rgb:
                    obs[i].front_rgb = np.array(
                        _resize_if_needed(
                            Image.open(obs[i].front_rgb),
                            obs_config.front_camera.image_size))

                if obs_config.left_shoulder_camera.depth or obs_config.left_shoulder_camera.point_cloud:
                    l_sh_depth = image_to_float_array(
                        _resize_if_needed(
                            Image.open(obs[i].left_shoulder_depth),
                            obs_config.left_shoulder_camera.image_size),
                        DEPTH_SCALE)
                    near = obs[i].misc['left_shoulder_camera_near']
                    far = obs[i].misc['left_shoulder_camera_far']
                    l_sh_depth_m = near + l_sh_depth * (far - near)
                    if obs_config.left_shoulder_camera.depth:
                        d = l_sh_depth_m if obs_config.left_shoulder_camera.depth_in_meters else l_sh_depth
                        obs[i].left_shoulder_depth = obs_config.left_shoulder_camera.depth_noise.apply(d)
                    else:
                        obs[i].left_shoulder_depth = None

                if obs_config.right_shoulder_camera.depth or obs_config.right_shoulder_camera.point_cloud:
                    r_sh_depth = image_to_float_array(
                        _resize_if_needed(
                            Image.open(obs[i].right_shoulder_depth),
                            obs_config.right_shoulder_camera.image_size),
                        DEPTH_SCALE)
                    near = obs[i].misc['right_shoulder_camera_near']
                    far = obs[i].misc['right_shoulder_camera_far']
                    r_sh_depth_m = near + r_sh_depth * (far - near)
                    if obs_config.right_shoulder_camera.depth:
                        d = r_sh_depth_m if obs_config.right_shoulder_camera.depth_in_meters else r_sh_depth
                        obs[i].right_shoulder_depth = obs_config.right_shoulder_camera.depth_noise.apply(d)
                    else:
                        obs[i].right_shoulder_depth = None

                if obs_config.overhead_camera.depth or obs_config.overhead_camera.point_cloud:
                    oh_depth = image_to_float_array(
                        _resize_if_needed(
                            Image.open(obs[i].overhead_depth),
                            obs_config.overhead_camera.image_size),
                        DEPTH_SCALE)
                    near = obs[i].misc['overhead_camera_near']
                    far = obs[i].misc['overhead_camera_far']
                    oh_depth_m = near + oh_depth * (far - near)
                    if obs_config.overhead_camera.depth:
                        d = oh_depth_m if obs_config.overhead_camera.depth_in_meters else oh_depth
                        obs[i].overhead_depth = obs_config.overhead_camera.depth_noise.apply(d)
                    else:
                        obs[i].overhead_depth = None

                if obs_config.wrist_camera.depth or obs_config.wrist_camera.point_cloud:
                    wrist_depth = image_to_float_array(
                        _resize_if_needed(
                            Image.open(obs[i].wrist_depth),
                            obs_config.wrist_camera.image_size),
                        DEPTH_SCALE)
                    near = obs[i].misc['wrist_camera_near']
                    far = obs[i].misc['wrist_camera_far']
                    wrist_depth_m = near + wrist_depth * (far - near)
                    if obs_config.wrist_camera.depth:
                        d = wrist_depth_m if obs_config.wrist_camera.depth_in_meters else wrist_depth
                        obs[i].wrist_depth = obs_config.wrist_camera.depth_noise.apply(d)
                    else:
                        obs[i].wrist_depth = None

                if obs_config.front_camera.depth or obs_config.front_camera.point_cloud:
                    front_depth = image_to_float_array(
                        _resize_if_needed(
                            Image.open(obs[i].front_depth),
                            obs_config.front_camera.image_size),
                        DEPTH_SCALE)
                    near = obs[i].misc['front_camera_near']
                    far = obs[i].misc['front_camera_far']
                    front_depth_m = near + front_depth * (far - near)
                    if obs_config.front_camera.depth:
                        d = front_depth_m if obs_config.front_camera.depth_in_meters else front_depth
                        obs[i].front_depth = obs_config.front_camera.depth_noise.apply(d)
                    else:
                        obs[i].front_depth = None

                if obs_config.left_shoulder_camera.point_cloud:
                    obs[i].left_shoulder_point_cloud = VisionSensor.pointcloud_from_depth_and_camera_params(
                        l_sh_depth_m,
                        obs[i].misc['left_shoulder_camera_extrinsics'],
                        obs[i].misc['left_shoulder_camera_intrinsics'])
                if obs_config.right_shoulder_camera.point_cloud:
                    obs[i].right_shoulder_point_cloud = VisionSensor.pointcloud_from_depth_and_camera_params(
                        r_sh_depth_m,
                        obs[i].misc['right_shoulder_camera_extrinsics'],
                        obs[i].misc['right_shoulder_camera_intrinsics'])
                if obs_config.overhead_camera.point_cloud:
                    obs[i].overhead_point_cloud = VisionSensor.pointcloud_from_depth_and_camera_params(
                        oh_depth_m,
                        obs[i].misc['overhead_camera_extrinsics'],
                        obs[i].misc['overhead_camera_intrinsics'])
                if obs_config.wrist_camera.point_cloud:
                    obs[i].wrist_point_cloud = VisionSensor.pointcloud_from_depth_and_camera_params(
                        wrist_depth_m,
                        obs[i].misc['wrist_camera_extrinsics'],
                        obs[i].misc['wrist_camera_intrinsics'])
                if obs_config.front_camera.point_cloud:
                    obs[i].front_point_cloud = VisionSensor.pointcloud_from_depth_and_camera_params(
                        front_depth_m,
                        obs[i].misc['front_camera_extrinsics'],
                        obs[i].misc['front_camera_intrinsics'])

                # Masks are stored as coded RGB images.
                # Here we transform them into 1 channel handles.
                if obs_config.left_shoulder_camera.mask:
                    obs[i].left_shoulder_mask = rgb_handles_to_mask(
                        np.array(_resize_if_needed(Image.open(
                            obs[i].left_shoulder_mask),
                            obs_config.left_shoulder_camera.image_size)))
                if obs_config.right_shoulder_camera.mask:
                    obs[i].right_shoulder_mask = rgb_handles_to_mask(
                        np.array(_resize_if_needed(Image.open(
                            obs[i].right_shoulder_mask),
                            obs_config.right_shoulder_camera.image_size)))
                if obs_config.overhead_camera.mask:
                    obs[i].overhead_mask = rgb_handles_to_mask(
                        np.array(_resize_if_needed(Image.open(
                            obs[i].overhead_mask),
                            obs_config.overhead_camera.image_size)))
                if obs_config.wrist_camera.mask:
                    obs[i].wrist_mask = rgb_handles_to_mask(np.array(
                        _resize_if_needed(Image.open(
                            obs[i].wrist_mask),
                            obs_config.wrist_camera.image_size)))
                if obs_config.front_camera.mask:
                    obs[i].front_mask = rgb_handles_to_mask(np.array(
                        _resize_if_needed(Image.open(
                            obs[i].front_mask),
                            obs_config.front_camera.image_size)))

        demos.append(obs)
    return demos

def _resize_if_needed(image, size):
    if image.size[0] != size[0] or image.size[1] != size[1]:
        image = image.resize(size)
    return image


# -*- coding: utf-8 -*-
"""
Created on Thu Apr 28 18:23:34 2022

@author: Mauri
"""
import tkinter as tk
from tkinter import ttk, Toplevel
import csv

#

def calculation():

    values2 ={
        'borrow': borw.get(),
        'years': years.get(),

        }

    borrow = values2["borrow"]

   # print(borrow)

    #final calculations
    rate = 6.08 / 100

    interest = (rate / 12) * borrow

   # print(round(interest, 2))

    final_values = {
        'SSN': ssn.get(),
        'home_value' : value.get(),
        'mortgage' : mort.get(),
        'borrow': borw.get(),
        'equity': holder['equity'],
        'payment': round(interest, 2),
        'years': years.get()
        }
    #writes values to a csv for storage
    profile = [final_values["SSN"],final_values["home_value"],final_values["mortgage"],final_values["equity"],final_values["borrow"], final_values["payment"], final_values["years"] ]
    with open('Home_equity2.csv', 'w') as infile:
        writer = csv.writer(infile, lineterminator = '\n')
        writer.writerow(profile)

#This function gets the values of the variables inputed from the main window
def insert():

    #The values are then stored in dictionary for better management and to be used later
    global holder
    holder = {}
    values = {
        'SSN': ssn.get(),
        'home_value' : value.get(),
        'mortgage' : mort.get(),
        'income' : incm.get(),
        'expense' : exps.get()

    }

    #Check to see if the applicant makes enougth before moving forward
    checkpoint = incm.get()
    if(checkpoint < 1000):
        #display warning window
        tk.messagebox.showinfo("Not Approved", "Your income does not meet the requirments")

    else:

        expensses = values["expense"]
        income = values["income"]
        mortgage = values["mortgage"]
        home_value = values["home_value"]

        #Checks the debt to income ratio of the applicant (dti)
        dti = (int(expensses)/int(income)) * 100
        if(dti < 43):
            #creates a secondary window on top of the existing window to finallize the application
            branche = Toplevel(root)
            branche.title("Countinue")
            branche.geometry('325x250')

            max_borrow = int(home_value) * 0.80
            equity = max_borrow - int(mortgage)

            holder = {
                'equity': equity

            }

            #borw = tk.StringVar()
            #years = tk.StringVar()

            #labels
            side = tk.Label(branche, text="Your Equity is: ")
            side.grid(row = 0, column =0)

            #Displays the equity of the applicant to the window
            display = tk.Label(branche, text = equity)
            display.grid(row = 0, column=1)

            e = tk.Label(branche ,text = "Borrowing Amount")
            e.grid(row = 1,column = 0)
            g = tk.Label(branche ,text = "Financing Years")
            g.grid(row = 2,column = 0)

            #Ebtry boxes
            entry_6 = tk.Entry(branche, textvariable= borw)
            entry_6.grid(row=1, column=1)

            entry_7 = tk.Entry(branche, textvariable= years)
            entry_7.grid(row=2, column=1)

            btn3 = ttk.Button(branche, text="Submit", command = calculation)
            btn3.grid(row=3,column=0, sticky = "nsew")

            btn4 = ttk.Button(branche ,text="Cancel", command= branche.destroy)
            btn4.grid(row=3,column=1, sticky = "nsew")
        elif(dti >= 43):
            #displays warning message
            tk.messagebox.showinfo("Not Approved", "Sorry we are unable to approve your application at this time")

#the main GUI window
root = tk.Tk()
root.title("Home Equity Form")
root.geometry('325x250')

#Labels to identify entry values
security = tk.Label(root ,text = "SSN 4-Digits").grid(row = 0,column = 0)
a = tk.Label(root ,text = "Home Value").grid(row = 1,column = 0)
b = tk.Label(root ,text = "Mortgage Balance").grid(row = 2,column = 0)
c = tk.Label(root ,text = "Monthly Income").grid(row = 3,column = 0)
d = tk.Label(root ,text = "Monthly Expenses").grid(row = 4,column = 0)

#Initiallize variables use to get values from entry boxes
ssn = tk.IntVar()
value = tk.IntVar()
mort = tk.IntVar()
incm = tk.IntVar()
exps = tk.IntVar()
borw = tk.IntVar()
years = tk.IntVar()

#Entry boxes for all required values
entry_1 = tk.Entry(root, textvariable= ssn)
entry_1.grid(row = 0,column = 1)

entry_2 = tk.Entry(root, textvariable= value)
entry_2.grid(row = 1,column = 1)

entry_3 = tk.Entry(root, textvariable= mort)
entry_3.grid(row = 2,column = 1)

entry_4 = tk.Entry(root, textvariable= incm)
entry_4.grid(row = 3,column = 1)

entry_5 = tk.Entry(root, textvariable= exps)
entry_5.grid(row = 4,column = 1)

#When giving a command to a button, don't use ().
#   i.e. command = insert
#   if the function needs paramaters, call it in a lambda
#       i.e. command = lambda: insert(x,y,z)

#Submit buttons which creates a new window onclick

btn = ttk.Button(root, text="Submit", command = insert)
btn.grid(row=5,column=0, sticky = "nsew")
#Cancel button that destroy/close the window
btn2 = ttk.Button(root ,text="Cancel", command=root.destroy)
btn2.grid(row=5,column=1, sticky = "nsew")

#prnt = ttk.Button(root, text="Print to Console", )
#prnt.grid(row=5,column=2, sticky = "nsew")

root.mainloop()


import math

c1 = [20,20]
c1r = 10

c2 = [60,60]
c2r = 20

d = math.sqrt((abs(c1[0]-c2[0])**2)+abs(c1[1]-c2[1])**2)
aplha = math.acos(abs(c1r-c2r)/d)

print(d,aplha)

hpq = math.atan((abs(c1[1]-c2[1])/abs(c1[0]-c2[0])))

hpb = hpq + aplha
hpc = hpq - aplha
print(hpq,hpb)

x3 = c1[0] + c1r * math.cos(hpb)
y3 = c1[1] + c1r * math.sin(hpb)

x4 = c2[0] + c2r * math.cos(hpb)
y4 = c2[1] + c2r * math.sin(hpb)

print((x3,y3),(x4,y4))

x5 = c1[0] + c1r * math.cos(hpc)
y5 = c1[1] + c1r * math.sin(hpc)

x6 = c2[0] + c2r * math.cos(hpc)
y6 = c2[1] + c2r * math.sin(hpc)

print((x5,y5),(x6,y6))

img = np.ones([100, 100, 3], dtype=np.uint8) * 255
# c1
cv2.circle(img, (c1[0],c1[1]), c1r, color=(255, 0, 0),lineType=4)
cv2.circle(img, (c1[0],c1[1]), 0, color=(255, 0, 0))
# c2
cv2.circle(img, (c2[0],c2[1]), c2r, color=(0, 255, 0),lineType=4)
cv2.circle(img, (c2[0],c2[1]), 0, color=(0, 255, 0))
# 切线 1
cv2.line(img,(int(x3),int(y3)),(int(x4),int(y4)),color=(0, 0, 0))
cv2.line(img,(int(x5),int(y5)),(int(x6),int(y6)),color=(0, 0, 0))
plt.imshow(img)
plt.figure('image')
plt.show()


"""Takes fs-essentia-extractor_legacy embeddings, and to implements
the Gaia feature preprocessing with Python. Namely, select a subset
 of the features, normalizes each of them independently and applies
 dimensionality reduction with PCA."""

import os
import time
import glob
import yaml
import json
from pathlib import Path
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser

import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.decomposition import PCA

from lib.utils import get_fname
from lib.directories import AUDIO_DIR

# Use these statistics for each feature
PCA_DESCRIPTORS = [
    "mean",
    "dmean",
    "dmean2",
    "var",
    "dvar",
    "dvar2"
]

# Features that are multiple band
MBAND_FEATURES = [
    "barkbands",
    "erb_bands",
    "frequency_bands",
    "gfcc",
    "mfcc",
    "scvalleys",
    "spectral_contrast"
]

def load_yaml(path):
    return yaml.safe_load(Path(path).read_text())

def select_subset(output):
    """ Selects a determined subset from a large set of features"""

    # For multiband features, collect PCA_DESCRIPTORS statistics of each band separately
    mband_feats = {}
    for feat in MBAND_FEATURES:
        n_bands = len(output["lowlevel"][feat][PCA_DESCRIPTORS[0]]) # Get the Number of bands
        for i in range(n_bands): # Access each band
            mband_feats[f"{feat}_{i}"] = {}
            for stat in PCA_DESCRIPTORS:
                mband_feats[f"{feat}_{i}"][stat] = output["lowlevel"][feat][stat][i]
        del output["lowlevel"][feat]
    # Insert the collection to the rest of the lowlevel features
    for k,v in mband_feats.items():
        output["lowlevel"][k] = v
    # Select the subset of features
    embed = {}
    for feat,feat_dct in output["lowlevel"].items():
        if type(feat_dct) == dict:
            embed[feat] = []
            for stat in PCA_DESCRIPTORS:
                embed[feat].append(feat_dct[stat])
    return embed

# TODO: whiten PCA??
if __name__=="__main__":

    parser=ArgumentParser(description=__doc__,
                                   formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument('embed_dir',
                        type=str,
                        help='Directory containing fs-essentia-extractor_legacy embeddings.')
    parser.add_argument("-N",
                        type=int,
                        default=100,
                        help="Number of PCA components to keep.")
    parser.add_argument('--plot-scree',
                        action='store_true',
                        help="Plot variance contributions of PCA components.")
    parser.add_argument("--output-dir",
                        type=str,
                        default="",
                        help="Path to output directory. If not provided, "
                        "a directory will be created in the same directory "
                        "as the embed_dir.")
    args = parser.parse_args()

    # Read all the embeddins
    embed_paths = glob.glob(os.path.join(args.embed_dir, "*.yaml"))
    print(f"{len(embed_paths)} embeddings found.")

    # Create the initial embeddings from model outputs
    print("Creating the initial embeddings...")
    start_time = time.time()
    fnames,embeddings = [],[]
    for i,embed_path in enumerate(embed_paths):
        if (i+1)%1000==0:
            print(f"Processed {i} embeddings...")
        # Get the fname from the path
        fnames += [get_fname(embed_path).split("-")[0]]
        # Load the features and select the subset
        feat_dict = load_yaml(embed_path)
        embeddings += [select_subset(feat_dict)]
    total_time = time.time()-start_time
    print(f"Total time: {time.strftime('%M:%S', time.gmtime(total_time))}")

    # List of all included features
    SUBSET_KEYS = list(embeddings[0].keys())
    print(f"{len(SUBSET_KEYS)} features selected.")

    # Create and store a Scaler for each feature
    print("Fitting scalers for each feature...")
    start_time = time.time()
    scalers = []
    for feat in SUBSET_KEYS:
        # Create the Data Matrix
        data = np.array([embed[feat] for embed in embeddings])
        scaler = MinMaxScaler()
        scaler.fit(data)
        scalers.append((feat,scaler))
    total_time = time.time()-start_time
    print(f"Total time: {time.strftime('%M:%S', time.gmtime(total_time))}")

    # Normalize each feature independently
    print("Normalizing each feature independently...")
    start_time = time.time()
    for i in range(len(embeddings)):
        for key,scaler in scalers:
            d = np.array(embeddings[i][key]).reshape(1,-1)
            embeddings[i][key] = scaler.transform(d).reshape(-1)
    total_time = time.time()-start_time
    print(f"Total time: {time.strftime('%M:%S', time.gmtime(total_time))}")

    # Concat all normalized features, make sure same order is followed
    print("Concatanating all the features....")
    start_time = time.time()
    for i in range(len(embeddings)):
        embeddings[i] = np.array([embeddings[i][k] for k in SUBSET_KEYS]).reshape(-1)
    embeddings = np.array(embeddings)
    total_time = time.time()-start_time
    print(f"Total time: {time.strftime('%M:%S', time.gmtime(total_time))}")

    # Determine PCA components
    n_components = args.N if args.N!=-1 else embeddings.shape[1]

    # Create the output dir
    if args.output_dir == "":
        output_dir = f"{args.embed_dir}-PCA_{n_components}"
    else:
        output_dir = os.path.join(args.output_dir, os.path.basename(args.embed_dir))
    os.makedirs(output_dir, exist_ok=True)
    print(f"Exporting the embeddings to: {output_dir}")

    # Scree plot
    if args.plot_scree:
        print(f"Plotting the PCA Scree plot next to the embeddings...")
        import matplotlib.pyplot as plt
        model = os.path.basename(args.embed_dir)
        data = os.path.basename(os.path.dirname(args.embed_dir))
        title=f'FSD50K.{data} - {model} Embeddings PCA Scree Plot'
        pca = PCA(n_components=None, copy=True)
        pca.fit(embeddings)
        PC_values = np.arange(pca.n_components_) + 1
        cumsum_variance = 100*np.cumsum(pca.explained_variance_ratio_)
        fig,ax = plt.subplots(figsize=(15,8), constrained_layout=True)
        fig.suptitle(title, fontsize=20)
        ax.plot(PC_values, cumsum_variance, 'ro-', linewidth=2)
        ax.set_xlim([-5,len(PC_values)+5])
        ax.set_yticks(np.arange(0,105,5)) # 5% increase
        ax.set_xlabel('Number of Principal Components Selected', fontsize=15)
        ax.set_ylabel('% Cumulative Variance Explained', fontsize=15)
        ax.grid()
        figure_path = os.path.join(output_dir, f'FSD50K.{data}-{model}-scree_plot.jpeg')
        fig.savefig(figure_path)

    # Apply PCA if specified
    if args.N!=-1:
        print("Applying PCA to each embedding...")
        start_time = time.time()
        pca = PCA(n_components=n_components)
        embeddings = pca.fit_transform(embeddings)
        total_time = time.time()-start_time
        print(f"Total time: {time.strftime('%M:%S', time.gmtime(total_time))}")

    # Export the transformed embeddings
    print("Exporting the embeddings...")
    for fname,embed in zip(fnames,embeddings):
        embed = {"audio_path": os.path.join(AUDIO_DIR,f"{fname}.wav"),
                "embeddings": embed.tolist()}
        output_path = os.path.join(output_dir, f"{fname}.json")
        with open(output_path, "w") as outfile:
            json.dump(embed, outfile, indent=4)

    #############
    print("Done!")


"""Add img_url column to Project table

Revision ID: 1dcb912d6836
Revises: c50fa84f7100
Create Date: 2021-11-22 15:15:27.054109

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '1dcb912d6836'
down_revision = 'c50fa84f7100'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('project', sa.Column('img_url', sa.String(length=10000), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('project', 'img_url')
    # ### end Alembic commands ###


import pygame
import random
import time

red_color = (255, 0, 0)

class Character(object):
    def __init__(self, name, health, max_health, power, defense, special_desc, coins, x_y,  min_walk_x, max_walk_x, min_walk_y, max_walk_y, items={}, bounty=[]):
        self.name = name
        self.health = health
        self.max_health = max_health
        self.power = power
        self.defense = defense
        self.special_desc = special_desc
        self.coins = coins
        self.items = items
        self.x_y = [x, y]
        self.min_walk_x = min_walk_x
        self.min_walk_y = min_walk_y
        self.max_walk_x = max_walk_x
        self.max_walk_x = max_walk_x

    def attack(self, enemy, special_attack, screen):
        global damage
        if self.health >= 0 or self.name == "Zombie":
            if enemy.name == "Shadow":      # shadow special
                if special_attack == True:
                    damage = 1
                else:
                    damage = 0
                enemy.health -= damage
                print("\033[0;32;40m{} does \033[1;32;40m{}\033[0;32;40m damage to {}\033[0;37;40m.".format(self.name, damage, enemy.name))
            elif special_attack == True and self.name == "Hero":  # hero special
                damage = random.randint(0, self.power) * 2
                if damage > enemy.health and enemy.name != "Zombie":   # limits the damage to enemy health
                    damage = enemy.health
                elif damage >= enemy.health and enemy.name == "Zombie":
                    damage = enemy.health - 1
                enemy.health -= damage
                print("\033[5;37;42mSPECIAL ATTACK:\033[5;32;40m {} does {} damage to {}.\033[0;37;40m".format(self.name, damage, enemy.name))
            elif special_attack == True and self.name == "Medic":   # medic special
                damage = random.randint(0, self.power)
                if damage > enemy.health:
                    damage = enemy.health
                enemy.health -= damage
                self.health += damage
                self.special_attack_text = "{} does {} damage to hero and restores {} health".format(self.name, damage, damage)
            elif special_attack == True and self.name == "Wizard":
                damage = random.randint(0, self.power)
                if damage > enemy.health:
                    damage = enemy.health
                enemy.health -= damage
                self.special_attack_text = "{} does {} damage and freezes hero".format(self.name, damage)
            elif special_attack == True and self.name == "Ranger":
                damage = random.randint(0, self.power)
                damage2 = random.randint(0, self.power)
                if damage > enemy.health:
                    damage = enemy.health
                enemy.health -= damage
                if damage2 > enemy.health:
                    damage2 = enemy.health
                enemy.health -= damage2
                self.special_attack_text = "{} shoots two arrows doing {} and {} damage to hero".format(self.name, damage, damage2)
            elif special_attack == True and self.name == "Dragon":
                if enemy.items["Dragon_Fire_Shield"] == 0:
                    damage = enemy.health
                    self.special_attack_text = "{} breathes fire doing {} damage and kills hero".format(self.name, damage)
                else:
                    damage = 0
                    self.special_attack_text = "Dragon Fire Shield protects hero from {} fire".format(self.name)
                enemy.health -= damage
            else:
                damage = random.randint(0, self.power)
                defense_benefit = round(enemy.defense * .3)
                defense_times = round(enemy.defense / 2)
                count = 0

                print(damage, "-", count, "-", max(self.power - defense_benefit, 1), "Max damage in", defense_times, "tries")
                while damage > max((self.power - defense_benefit), 1) and count < defense_times:
                    damage = random.randint(0, self.power)
                    count += 1
                    print(damage, "-", count, "-", max(self.power - defense_benefit, 1), "Max damage in", defense_times, "tries")  # shows all numbers generated
                # If the enemy attacks within a certain number (number depends on defense level) of their max attack, another random number is generated. Number is generated half the enemies defense level times. This lowers the chance of high attacks on a higher defense oponent
                if damage > enemy.health and enemy.name != "Zombie":   # limits the damage to enemy health
                    damage = enemy.health
                elif damage >= enemy.health and enemy.name == "Zombie":
                    damage = enemy.health - 1
                enemy.health -= damage
                if self.name == "Hero":
                    print("\033[0;32;40m{} does \033[1;32;40m{}\033[0;32;40m damage to {}.\033[0;37;40m".format(self.name, damage, enemy.name))
                else:
                    print("\033[0;31;40m{} does \033[1;31;40m{}\033[0;31;40m damage to {}.\033[0;37;40m".format(self.name, damage, enemy.name))
            enemy.damage = damage
            time.sleep(1)

    def alive(self):
        if self.health > 0 or self.name == "Zombie":
            return True
        else:
            return False

    def print_status(self):
        align = 7 - len(self.name) - 1
        print(" " * align, "\033[1;34;40m{} - \033[1;32;40m\u2694\uFE0F P: {} \033[1;36;40m\U0001F6E1 D: {} \033[1;31;40m\u2764\uFE0F H: {}/{} \033[0;37;40m".format(self.name, self.power, self.defense, self.health, self.max_health))

    def walking(self, rand_numb, hero_char):
        rand_x = 0
        rand_y = 0
        if self.fight_status == False:
            if self.x_y[0] > self.max_walk_x:    # Moves right
                self.speed_x_y[0] *= -1
            if self.x_y[1] > self.max_walk_y:    # Moves Down
                self.speed_x_y[1] *= -1
            if self.x_y[0] < self.min_walk_x:         # Moves Left
                self.speed_x_y[0] *= -1
            if self.x_y[1] < self.min_walk_y:         # Moves up
                self.speed_x_y[1] *= -1

            if rand_numb == 0:      # Move right
                rand_x = self.speed_x_y[0]
                rand_y = 0
            elif rand_numb == 1:    # Move left
                rand_x -= self.speed_x_y[0]
                rand_y = 0
            elif rand_numb == 2:    # Move down
                rand_x = 0
                rand_y = self.speed_x_y[1]
            elif rand_numb == 3:    # Move up
                rand_x = 0
                rand_y -= self.speed_x_y[1]
            elif rand_numb == 4:    # South East
                rand_x = self.speed_x_y[0] / 2
                rand_y = self.speed_x_y[1] / 2
            elif rand_numb == 5:    # North East
                rand_x = self.speed_x_y[0] / 2
                rand_y -= self.speed_x_y[1] / 2
            elif rand_numb == 6:    # North West
                rand_x -= self.speed_x_y[0] / 2
                rand_y -= self.speed_x_y[1] / 2
            elif rand_numb == 7:    # South West
                rand_x -= self.speed_x_y[0] / 2
                rand_y = self.speed_x_y[1] / 2
            elif rand_numb ==8:
                rand_x = 0
                rand_y = 0

            self.x_y[0] += rand_x
            self.x_y[1] += rand_y

        #Makes enemy follow hero when attacking
        elif self.fight_status == True and self.x_y[0] > self.min_walk_x and self.x_y[0] < self.max_walk_x and self.x_y[1] > self.min_walk_y and self.x_y[1] < self.max_walk_y:
            if self.x_y[0] + 30 <= hero_char.x_y[0]:
                self.x_y[0] += abs(self.speed_x_y[0])
            elif self.x_y[0] - 30 >= hero_char.x_y[0]:
                self.x_y[0] -= abs(self.speed_x_y[0])
            if self.x_y[1] + 30 <= hero_char.x_y[1]:
                self.x_y[1] += abs(self.speed_x_y[1])
            elif self.x_y[1] - 30 >= hero_char.x_y[1]:
                self.x_y[1] -= abs(self.speed_x_y[1])

    def health_bar(self):
        health_perc = float(self.health / self.max_health)
        if health_perc < .05 and health_perc > 0:
            self.health_bar_numb = 1
        elif health_perc >=1:
            self.health_bar_numb = 20
        else:
            health_bar_numb = int((health_perc) / 5 * 100)
            self.health_bar_numb = health_bar_numb
            return health_bar_numb

    def remove_dead_char(self, enemy, hero, screen, background_image):
        x_y = [enemy.x_y[0] + 16, enemy.x_y[1] + 16]

        screen.blit(background_image, (x_y[0], x_y[1]), pygame.Rect(x_y[0], x_y[1], enemy.x_y[0] - 16, enemy.x_y[1] - 16))
        enemy.fight_status = False
        #enemy.x_y_when_clicked = [-300, -300]
        enemy.damage = ""
        hero.damage = ""
        hero.fight_status = False

    #def enemy_respawn(self):


import numpy as np
import h5py
from collections import defaultdict
from typing import List

from june.epidemiology.infection import (
    TransmissionGamma,
    Transmission,
    TransmissionConstant,
    TransmissionXNExp,
)
from june.hdf5_savers.utils import read_dataset, write_dataset

str_to_class = {
    "TransmissionXNExp": TransmissionXNExp,
    "TransmissionGamma": TransmissionGamma,
    "TransmissionConstant": TransmissionConstant,
}
attributes_to_save_dict = {
    "TransmissionXNExp": ["time_first_infectious", "norm_time", "n", "norm", "alpha"],
    "TransmissionGamma": ["shape", "shift", "scale", "norm"],
    "TransmissionConstant": ["probability"],
}

def save_transmissions_to_hdf5(
    hdf5_file_path: str, transmissions: List[Transmission], chunk_size: int = 50000
):
    """
    Saves transmissions data to hdf5. The transmission type is inferred from the first
    element of the list.

    Parameters
    ----------
    attributes_to_save
        attributes to save from each transmission
    hdf5_file_path
        hdf5 path to save transmissions
    transmissions
        list of transmission objects
    chunk_size
        number of hdf5 chunks to use while saving
    """
    with h5py.File(hdf5_file_path, "a") as f:
        if "infections" not in f:
            f.create_group("infections")
        f["infections"].create_group("transmissions")
        transmissions_group = f["infections"]["transmissions"]
        n_transsmissions = len(transmissions)
        transmissions_group.attrs["n_transsmissions"] = n_transsmissions
        transmission_type = transmissions[0].__class__.__name__
        transmissions_group.attrs["transmission_type"] = transmission_type
        n_chunks = int(np.ceil(n_transsmissions / chunk_size))
        attributes_to_save = attributes_to_save_dict[transmission_type]
        for chunk in range(n_chunks):
            idx1 = chunk * chunk_size
            idx2 = min((chunk + 1) * chunk_size, n_transsmissions)
            attribute_dict = defaultdict(list)
            for index in range(idx1, idx2):
                transmission = transmissions[index]
                for attribute_name in attributes_to_save:
                    attribute = getattr(transmission, attribute_name)
                    if attribute is None:
                        attribute_dict[attribute_name].append(np.nan)
                    else:
                        attribute_dict[attribute_name].append(attribute)
            for attribute_name in attributes_to_save:
                attribute_dict[attribute_name] = np.array(
                    attribute_dict[attribute_name], dtype=np.float64
                )
            for attribute_name in attributes_to_save:
                write_dataset(
                    group=transmissions_group,
                    dataset_name=attribute_name,
                    data=attribute_dict[attribute_name],
                    index1=idx1,
                    index2=idx2,
                )

def load_transmissions_from_hdf5(hdf5_file_path: str, chunk_size=50000):
    """
    Loads transmissions data from hdf5.

    Parameters
    ----------
    hdf5_file_path
        hdf5 path to load from
    chunk_size
        number of hdf5 chunks to use while loading
    """
    transmissions = []
    with h5py.File(hdf5_file_path, "r") as f:
        transmissions_group = f["infections"]["transmissions"]
        n_transsmissions = transmissions_group.attrs["n_transsmissions"]
        transmission_type = transmissions_group.attrs["transmission_type"]
        transmission_class = str_to_class[transmission_type]
        n_chunks = int(np.ceil(n_transsmissions / chunk_size))
        for chunk in range(n_chunks):
            idx1 = chunk * chunk_size
            idx2 = min((chunk + 1) * chunk_size, n_transsmissions)
            attribute_dict = {}
            for attribute_name in transmissions_group.keys():
                attribute_dict[attribute_name] = read_dataset(
                    transmissions_group[attribute_name], idx1, idx2
                )
            for index in range(idx2 - idx1):
                transmission = transmission_class()
                for attribute_name in attribute_dict:
                    attribute_value = attribute_dict[attribute_name][index]
                    if attribute_value == np.nan:
                        attribute_value = None
                    setattr(transmission, attribute_name, attribute_value)
                transmissions.append(transmission)
    return transmissions


import os

import yaml

ATTRIBUTES = [('nesbi_username', ''),
              ('nesbi_password', ''),
              ('nesbi_dry_run', False),
              ('nesbi_network_driver', ''),
              ('nsot_url', ''),
              ('nsot_email', ''),
              ('nsot_secret_key', ''),
              ('nsot_auth_header', 'X-NSoT-Email'),
              ('nsot_site_id', '1'),
              ('nsot_delete_objects', False),
              ('nesbi_snmp_version', '2c'),
              ('nesbi_snmp_community', ''),
              ('nesbi_scan_ports', [22]),
              ('nesbi_logging_level', 'info'),
              ('nesbi_logging_file', 'nesbi.log'),
              ('nesbi_logging_to_stdout', False),
              ('nesbi_thread_limit', 5)]

class Config:
    def __init__(self, config_file, **kwargs):
        with open(config_file, 'r') as f:
            data = yaml.safe_load(f.read()) or {}

        for k, v in data.items():
            setattr(self, k, v)

        for attr in ATTRIBUTES:
            self._set_self_attribute(attr[0], attr[1], **kwargs)

    def _set_self_attribute(self, attr, default, **kwargs):
        if kwargs.get(attr):
            setattr(self, attr, kwargs.get(attr))
        elif hasattr(self, attr):
            setattr(self, attr, getattr(self, attr))
        elif attr.upper() in os.environ:
            setattr(self, attr, os.environ.get(attr.upper()))
        else:
            setattr(self, attr, default)


"""
Checks to see if Makefile follows standards
"""
import os
import re

import pytest
from pytest_repo_health import health_metadata

from repo_health import get_file_content

module_dict_key = "makefile"
output_keys = {
    "upgrade": "target that upgrades our dependencies to newer released versions",
    "test": "target that runs tests",
    "quality": "target that runs code quality checks",
    "test-js": "target that runs javascript unit tests",
    "quality-js": "target that runs javascript code quality checks",
    "test-python": "target that runs python unit tests",
    "quality-python": "target that runs python code quality checks",
}

@pytest.fixture(name='makefile')
def fixture_makefile(repo_path):
    """Fixture containing the text content of Makefile"""
    full_path = os.path.join(repo_path, "Makefile")
    return get_file_content(full_path)

@health_metadata(
    [module_dict_key, "has_target"],
    output_keys
)
def check_has_make_target(makefile, all_results):
    """
    Checks make file has provided targets
    """
    for target, __ in output_keys.items():
        all_results[module_dict_key][target] = False
        regex_pattern = "".join(["^", target, ":"])
        match = re.search(regex_pattern, makefile, re.MULTILINE)
        if match:
            all_results[module_dict_key][target] = True

@health_metadata(
    [module_dict_key],
    {
        "pip-installed": "check if pip.txt was installed immediately after upgrade"
    }
)
def check_upgrade_script(makefile, all_results):
    """
    Checks if pip installed after upgrading pip.txt
    """
    upgrade_targets = re.finditer("^upgrade:", makefile, re.MULTILINE)

    for i in upgrade_targets:
        upgrade_script = makefile[i.end():]
        next_target = re.search("^[a-zA-Z_]+:", upgrade_script, re.MULTILINE)
        if next_target is not None:
            upgrade_script = upgrade_script[:next_target.start()]
        update_commands = (r"(\n\t(\$\(PIP_COMPILE\)|pip-compile)(.*?)((requirements/pip\.txt requirements/pip\.in)"
                           r"|(requirements/pip-tools\.txt requirements/pip-tools\.in))){2}")
        install_commands = r"(\n\t(pip install)(.*?)(requirements/pip.txt|requirements/pip-tools.txt)){2}"
        regex_pattern = "".join([update_commands, install_commands])
        match = re.search(regex_pattern, upgrade_script, re.MULTILINE)
        if match:
            all_results[module_dict_key]["pip-installed"] = True
            return

    all_results[module_dict_key]["pip-installed"] = False


#https://leetcode.com/problems/single-number/description/
#LeetCode 136. Single Number

#author:peihan
#date: 05/17/2018

#方法一：集合相减
#nums = [2,2,1]
nums = [4,1,2,1,2]

val = sorted(nums)
print(val)

pre_val = start_val = None
result=[]
i = 0

for number in val:
	cur_val = number
	if cur_val == pre_val:
		result.append(cur_val)
	pre_val = cur_val

nums = set(nums)
result = set(result)
nums = list(nums-result)
out = nums[0]

print (out)

# 方法2： 求和可得，这方法太厉害了
'''out = sum(list(set(nums)))*2 - sum(nums)
print (out)'''


from .combined_operations import CombinedOperation
from .operations import BackTranslate, UnitExpansion, SameSentence, Num2Words

class PositiveSamples(CombinedOperation):
    def __init__(self):
        self.operations = {
            "BackTranslate": BackTranslate(),
            "SameSentence": SameSentence(),
            "Num2Words": Num2Words(),
            "UnitExpansion": UnitExpansion()
        }

    def generate(self, text, ops=["BackTranslate", "SameSentence", "Num2Words", "UnitExpansion"]):
        positives = []
        for op in ops:
            if op not in self.operations: continue
            operator = self.operations[op]
            positives.append(operator.generate(text))
        return positives


from django.db import models
from voyage.models import Voyage
# Create your models here.
class Excursion(models.Model):
    nom=models.CharField(max_length=100,null=True)
    photoexcursion = models.ImageField(upload_to='pics',default=False)
    optionnelle=models.BooleanField(default=False)
    voyage = models.ManyToManyField(Voyage)
    date_creation=models.DateTimeField(auto_now_add=True,null=True)

    def __str__(self):
        return self.nom


import cv2
import numpy as np
import face_recognition
import os, csv
from datetime import datetime
from pathlib import Path

path = 'ImageDatabase'  # path of the folder where all sample images are present
images = []     # an empyt array
classNames = []
myList = os.listdir(path)   # it will fetch the name of the images ex - [Alba Test.jpg, Alba.jpg, Gal Gadot.jpg, Lulu.jpg]
print(myList)

# this loop will fetch image name from fath folder and append it to the array(classNames)

for cl in myList:
    curImg = cv2.imread(f'{path}/{cl}')
    images.append(curImg)
    classNames.append(os.path.splitext(cl)[0])
    # we dont want Name like - Alba.jpg,
    # we just want Alba so we use split function on the name an then reciving the first index
    # i.e. only "Alba" and removing .jpg
print(classNames)

# Meaning of Encoding
# Encoding is the process of converting data from one form to another.
# By encoding digital audio, video, and image files, they can be saved in a more efficient, compressed format.
# Encoded media files are typically similar in quality to their original uncompressed counterparts, but have much smaller file sizes

def findEncodings(images):
    encodeList = []
    for img in images:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        encode = face_recognition.face_encodings(img)[0]
        encodeList.append(encode)
    return encodeList

def check_dir():
    file_path = Path("./1.Entry")
    csv_file = 'EntryData_' + str(datetime.now().strftime('%d_%m_%Y')) + '.csv' # it will include the current date of the system in the file name
    csv_file_full = file_path / csv_file
    if csv_file_full.is_file():
        direxist = csv_file_full
        #print('file exist')
        return direxist
    else:
        with open(csv_file_full,'w', newline='') as cd:
            header = ['Name', 'Time']
            writer = csv.writer(cd,delimiter=',')
            writer.writerow(header)
            dircreated = csv_file_full
            #print('just created')
            return dircreated

 # this function will check for filename (csv_file) in the following dir (file_path)
 # if it will find the file it will return the full path of the file (cvs_file_full)
 # and if not it will creat one and then return the full path of the file

def Biometric_scan(name):
    filename = check_dir()
    with open(filename,'r+') as f:  # r+ == reading and writing the file at same time
        myDataList = f.readlines()
        nameList = []
        for line in myDataList:
            entry = line.split(',')
            nameList.append(entry[0])
        if name not in nameList:
            now = datetime.now()
            dtString = now.strftime('%H:%M:%S')
            f.writelines(f'\n{name},{dtString}')

encodeListKnown = findEncodings(images)
print('Encoding Complete')

cap = cv2.VideoCapture(0)

while True:
    success, img1 = cap.read()
    img = cv2.flip(img1,1)
    imgS = cv2.resize(img,(0,0),None,0.25,0.25) # reducing the size of the image by one forth
    imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)

    facesCurFrame = face_recognition.face_locations(imgS)  # facesCurFrame == faces in our current frame
    encodesCurFrame = face_recognition.face_encodings(imgS,facesCurFrame) # encodesCurFrame == encoding in our current frame

    for encodeFace,faceLoc in zip(encodesCurFrame,facesCurFrame):
        matches = face_recognition.compare_faces(encodeListKnown,encodeFace)
        faceDis = face_recognition.face_distance(encodeListKnown,encodeFace)
        #print(faceDis)
        matchIndex = np.argmin(faceDis)

        if matches[matchIndex]:
            name = classNames[matchIndex].upper()
            #print(name)
            Biometric_scan(name)
        if faceDis[matchIndex]< 0.60:
            Biometric_scan(name)
        else:
            name = 'Unknown'
            #print(name)
        if name == 'Unknown':
            y1,x2,y2,x1 = faceLoc
            y1, x2, y2, x1 = y1*4,x2*4,y2*4,x1*4
            # as we have resize our image in line 84, so if we want the rectangle around the face to be align properly,
            # we have to multiply the coordinates by 4
            cv2.rectangle(img,(x1,y1),(x2,y2),(0,0,255),2)
            cv2.rectangle(img,(x1,y2-35),(x2,y2),(0,0,255),cv2.FILLED)
            # it will create a rectangular box under the frace box which will show the name. y-35 - it is for decreasing the lenght of the box/rectangle
            cv2.putText(img,name,(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)
            # (x1+6,y2-6) - for aligning the text in to the small box which will show the name
        else:
            y1,x2,y2,x1 = faceLoc
            y1, x2, y2, x1 = y1*4,x2*4,y2*4,x1*4
            cv2.rectangle(img,(x1,y1),(x2,y2),(0,255,0),2)
            cv2.rectangle(img,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)
            cv2.putText(img,name,(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)

    cv2.imshow('Biometric_scan Cam',img)
    key = cv2.waitKey(1)
    if key == 27:
        break
cv2.destroyAllWindows()


import websockets
import asyncio
import base64

PORT = 5050

print(f"Server listening in Port {PORT}")
connected = set()

async def echo(webs, path):
    print('A client is connected')
    connected.add(webs)
    try:
        async for message in webs:
            for conn in connected:
                if conn != webs:
                    print('\n\nReceived msg from cliend: \n', message)
                    await conn.send(message)
    except websockets.exceptions.ConnectionClosed as e:
        print("A client just disconnected.")
    finally:
        connected.remove(webs)

start_server = websockets.serve(echo, "0.0.0.0", PORT)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()


# coding=utf-8

import threading

class SingletonThread(threading.Thread):
    _instance = None
    # Copy these variables into subclasses to avoid sharing:
    # (Would use __init_subclass__() but Python 2 doesn't support it and using
    # metaclasses to achieve the same is a lot of faff.)
    # _instance_lock = threading.Lock()
    # _stop_event = threading.Event()

    @classmethod
    def ensure_started(cls):
        instance = cls._instance
        if instance is not None and instance.is_alive():
            # No need to grab the lock
            return
        with cls._instance_lock:
            if cls._instance is None or not cls._instance.is_alive():
                cls._instance = cls()
                cls._instance.start()

    @classmethod
    def ensure_stopped(cls):
        if cls._instance is None:
            # No need to grab the lock
            return
        with cls._instance_lock:
            if cls._instance is None:
                # Nothing to stop
                return
            elif not cls._instance.is_alive():
                # Thread died
                cls._instance = None
                return

            # Signal stopping
            cls._stop_event.set()
            cls._on_stop()
            cls._instance.join()

            cls._instance = None
            cls._stop_event.clear()

    @classmethod
    def _on_stop(cls):
        """
        Hook to allow subclasses to add extra behaviour to stopping.
        """
        pass

    def __init__(self, *args, **kwargs):
        super(SingletonThread, self).__init__(*args, **kwargs)
        self.daemon = True


UNDIRECTED = 'undirected'
DIRECTED = 'directed'
OUT = 'out'
IN = 'in'

class graph(object):
    '''
    Python graph implementation (adjacency list)

    V = set of vertices
    E = set of edges
    n = number of vertices
    m = number of edges

    Objectives:
        Linear time for algorithms O(m + n)
        O(m + n) space

    Facts:
        m = 2Sum_{v \in V} deg(v)
        "density" -> m = Om(n^2)

    >>> ug = graph(kind='undirected')
    >>> ug.add_vertex('cat')
    >>> ug.add_vertex('dog')
    >>> ug.add_vertex('ape')
    >>> ug.add_edge('cat', 'dog')
    >>> ug.add_edge('cat', 'ape')
    >>> ug.vertices['cat']
    {'dog': 1, 'ape': 1}
    >>> ug.vertices['dog']
    {'cat': 1}
    >>> ug.remove_vertex('dog')
    >>> ug.vertices['cat']
    {'ape': 1}
    >>> dg = graph(kind='directed')
    >>> dg.add_vertex('cat')
    >>> dg.add_vertex('dog')
    >>> dg.add_edge('cat', 'dog', 3)
    >>> dg.vertices['cat']['out']
    {'dog': 3}
    >>> dg.vertices['cat']['in']
    {}
    >>> dg.vertices['dog']['out']
    {}
    >>> dg.vertices['dog']['in']
    {'cat': 3}
    >>> dg.remove_edge('cat', 'dog')
    >>> dg.vertices['cat']['out']
    {}
    >>> dg.vertices['dog']['in']
    {}
    '''
    def __init__(self, kind=UNDIRECTED):
        self.kind = kind
        self.vertices = {} # Will be a dictionary of dictionaries.

    def __repr__(self):
        return 'n = {}'.format(len(self.vertices))

    def add_vertex(self, v):
        if self.kind == UNDIRECTED:
            self.vertices[v] = {}
        else:
            self.vertices[v] = {OUT: {}, IN: {}}

    def add_edge(self, v1, v2, w=1):
        if self.kind == UNDIRECTED:
            self.vertices[v1][v2] = w
            self.vertices[v2][v1] = w
        else:
            self.vertices[v1][OUT][v2] = w
            self.vertices[v2][IN][v1] = w

    def remove_vertex(self, v):
        self.vertices.pop(v, None)
        for vertex in self.vertices:
            if self.kind == UNDIRECTED:
                self.vertices[vertex].pop(v, None)
            else:
                self.vertices[vertex][IN].pop(v, None)
                self.vertices[vertex][OUT].pop(v, None)

    def remove_edge(self, v1, v2):
        if self.kind == UNDIRECTED:
            self.vertices[v1].pop(v2, None)
            self.vertices[v2].pop(v1, None)
        else:
            self.vertices[v1][OUT].pop(v2, None)
            self.vertices[v2][IN].pop(v1, None)

    def find_sinks(self):
        pass

    def find_sources(self):
        pass

if __name__ == "__main__":
    import doctest
    doctest.testmod()


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

import tensorflow as tf
from tensorflow.python.ops import rnn, rnn_cell
import numpy as np
import preprocess
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_recall_fscore_support
max_seq_len = 75
k = 800
mapping = [-1,0,1]

class LSTMs():
    """
    LSTM for sentiment classification
    """

    def __init__(self,num_labels=3,lstm_hidden=(400,400),rnn_type='LSTM'):
        #Create input/output and weights
        self.input = tf.placeholder(tf.float32, [None, max_seq_len,k+2])
        self.output = tf.placeholder(tf.float32, [None, num_labels])
        self.keep_prob = tf.placeholder(tf.float32,[3])

        cells = []
        for num_hidden in lstm_hidden:
            if(rnn_type=='LSTM'):
                cell = rnn_cell.BasicLSTMCell(num_hidden,state_is_tuple=True)
            else:
                cell = rnn_cell.GRUCell(num_hidden)        #self.keep_prob
            celldropout = tf.nn.rnn_cell.DropoutWrapper(cell, input_keep_prob=self.keep_prob[0],output_keep_prob=self.keep_prob[1],state_keep_prob=self.keep_prob[2],seed=0)
            cells.append(celldropout)
        cell = rnn_cell.MultiRNNCell(cells , state_is_tuple=True)
        val, state = tf.nn.dynamic_rnn(cell, self.input, dtype=tf.float32)
        valT = tf.transpose(val,[1,0,2])

        last = tf.gather(valT,int(valT.get_shape()[0])-1)

        weight_out = tf.Variable(tf.truncated_normal([num_hidden, int(self.output.get_shape()[1])]))
        bias_out = tf.Variable(tf.constant(0.1, shape=[self.output.get_shape()[1]]))

        #Get prediction at last time setp
        prediction = tf.nn.softmax(tf.matmul(last,weight_out)+bias_out)
        self.prediction = prediction

        #Get prediction at every timestep
        allpredictions = tf.transpose(tf.map_fn(lambda x: tf.nn.softmax(tf.matmul(x,weight_out)+bias_out), valT, dtype=tf.float32),[1,0,2])
        self.all_predictions = allpredictions

        vars = tf.trainable_variables()
        lossL2 = tf.add_n([tf.nn.l2_loss(v) for v in vars if 'bias' not in v.name ]) * 0.001

        #loss = -tf.reduce_sum(self.output * tf.log(tf.clip_by_value(prediction,1e-10,1.0)))
        loss = tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(labels=self.output,logits=prediction)) #+ lossL2
        self.loss = loss

        predictClass = tf.argmax(prediction, 1)
        self.predictClass = predictClass

        #Calculate accuracy
        correct = tf.equal(tf.argmax(self.output, 1), tf.argmax(prediction, 1))
        acc = tf.reduce_mean(tf.cast(correct, tf.float32))
        self.accuracy = acc

        #Calculate confusion matrix
        confusion_matrix = tf.contrib.metrics.confusion_matrix(tf.argmax(self.output, 1),predictClass)
        self.confusion_matrix = confusion_matrix

    def load_model(self,model_name='LSTM_44_Test',step='350'):
        # with tf.Graph().as_default():

        """
        Usable model:
            -../model/checkpoint/yoyoyo/ch-2280 :[[263  14   7  11] , Validation accuracy: 0.74, default structure.  P,R,F1 = (0.72,0.74,0.72)
                                                 [ 25 258   8   9]  40 epochs
                                                 [ 16  39  35  41]  400,400
                                                 [ 30  24  17 117]]

            -../model/checkpoint/LSTM_Default
        """

        session_conf = tf.ConfigProto(
            allow_soft_placement=True,
            log_device_placement=False,
            device_count={'GPU': 0})
        sess = tf.Session(config=session_conf)
        global_step = tf.Variable(0, name="global_step", trainable=False)
        self.global_step = global_step
        saver = tf.train.Saver(tf.global_variables())
        saver.restore(sess, './sentiment_seg/model/checkpoint/' + model_name + '/ch-' + step)
        print("Model Restored")
        self.sess = sess

    #Create function that will predict and calculate accuracy, f1, precision,recall,confusion matrix
    def evaluate(self,X_comments,y,sample_size=10,y_mapping=[-32,-1,0,1]):
        X = preprocess.comments_to_matrix(X_comments)
        #TODO: Change from default model to model specify by user.
        try:
            self.sess
        except Exception:
            print("Model not initialized yet. Please load model first using load_model() function.")
            # sess.run(tf.global_variables_initializer())

        # Restoring Model
        #
        # saver = tf.train.Saver(tf.global_variables())
        # saver.restore(self.sess, '../model/checkpoint/-411')
        # print("Model Restored")
        print("Start evaluating...")
        current_step = tf.train.global_step(self.sess, self.global_step)
        print("Global step: %d"%current_step)
        feed_dict = {self.input: X, self.output: y,self.keep_prob:[1,1,1]}
        acc,l,pred = self.sess.run([self.accuracy,self.loss,self.predictClass], feed_dict=feed_dict)

        print("Accuracy: %.2f"%acc)
        print("Loss: {}".format(l))

        #Confusion matrix

        #y_labels = np.full([y.shape[0]],32)
        y_labels = np.full([y.shape[0]],-32)
        for i, m in enumerate(y_mapping):
            y_labels[y[:, i] == 1] = m
        pred = [y_mapping[i] for i in pred]

        cm = confusion_matrix(y_labels, pred)
        print(cm)

        #Calculate precision,recall per class
        precisions,recalls,fscores,supports = precision_recall_fscore_support(y_labels,pred)
        for i,sent in enumerate(["Negative","Neutral","Positive"]):
            print("Class: %s"%sent)
            print("Precision: %.2f"%precisions[i])
            print("Recall: %.2f"%recalls[i])
            print("F1 scores: %.2f"%fscores[i])
            print("================================")
        precision, recall, fscore, support = precision_recall_fscore_support(y_labels, pred,average='weighted')
        print("Weighted Score")
        print("Precision: %.2f" % precision)
        print("Recall: %.2f" % recall)
        print("F1 scores: %.2f" % fscore)

        print("Printing Sample Predicted comments")
        print("===========================")
        idx = np.random.choice(np.arange(X.shape[0]), sample_size, replace=False)
        sample_x = X[idx]
        comments = X_comments[idx]
        sample_y = y[idx]
        test_feed_dict = {self.input:sample_x,self.output:sample_y,self.keep_prob:[1,1,1]}
        test_pred,all_preds = self.sess.run([self.predictClass,self.all_predictions],test_feed_dict)

        correctPrediction = 0
        for i in range(len(test_pred)):
            pred = test_pred[i]
            current_pred_seq = all_preds[i][-len(comments[i]):]
            print(len(comments[i]))
            #Prin word with color by prediction
            for j,word in enumerate(comments[i]):
                word_pred = current_pred_seq[j]
                printSegmentColor(word,word_pred)
            predictionLabel = y_mapping[pred]
            realLabel = y_mapping[np.argmax(sample_y[i])]
            print(", %.2f Ans: %.2f"%(predictionLabel,realLabel),end=' ')
            if(predictionLabel==realLabel):
                print("O")
                correctPrediction+=1
            else:
                print("X")
        print("Samples accuracy: {}".format(round(correctPrediction/sample_size)))


# 0_Executing Program ============================================================================
import sys
import getopt
import re

args = sys.argv[1:]
opts, args = getopt.getopt(args, "i:b:h")

i_opt = './sample/sample_1.wav'
b_opt = "black"

for opt, arg in opts:
    if opt == "-i":
        i_opt = arg
        x = re.findall("\d", i_opt)
        o_opt = "output_" + x[0] + ".png"

    elif opt == "-b":
        if arg == "0":
            b_opt = "black"
        elif arg == "1":
            b_opt = "white"
        else:
            raise ValueError("")

    elif opt == "-h":
        print("-i : Input audio file path. Default path is './sample/sample_1.wav'")
        print("-b : Background color. 0 is black, 1 is white. Default value is 0(black)")

# 1_Importing Modules and Packages ================================================================

import librosa
import librosa.display
import numpy as np

from bokeh.plotting import figure
from bokeh.io import export_png

from bokeh.palettes import Blues8
from bokeh.palettes import Greens8
from bokeh.palettes import Inferno256

# 2_Loading Audio Files ===========================================================================

audio_data = i_opt   # Default path is './sample/sample_1.wav'
sig, sr = librosa.load(audio_data, sr = 44100)

# 3_Extacting Datas From Audio ====================================================================

# 3-1.Onset Envelope | 3-2.Beats | 3-3.Onsets -----------------------------------------------------
onset_frames = librosa.onset.onset_detect(sig, sr = sr)
onsets = librosa.frames_to_time(onset_frames, sr = sr)
onset_env = librosa.onset.onset_strength(sig, sr = sr, aggregate = np.median)
tempo = librosa.beat.tempo(onset_envelope = onset_env, sr = sr)
tempo, beats = librosa.beat.beat_track(onset_envelope = onset_env, sr = sr, units = 'time')

# 3-4.Frequency & Magnitude -----------------------------------------------------------------------
fft = np.fft.fft(sig)
magnitude = np.abs(fft)
magnitude_dB = librosa.amplitude_to_db(magnitude)
frequency = np.linspace(0, sr, len(magnitude_dB))

left_magnitude_dB = magnitude_dB[:len(magnitude_dB)/2]   # certain magnitude(dB)
left_frequency = frequency[:len(magnitude_dB)/2]         # certain frequency

# 4_Preprocessing Datas for Visualization =========================================================

# 4-1.Onset Envelope(propotional to audio length) -------------------------------------------------
E = len(onset_env)
x1 = np.random.rand(E) * E
y1 = np.random.rand(E) * E
n1 = 50
radii_1 = np.random.rand(E) * E / n1
colors_1 = ["#%02x%02x%02x" % (int(r), int(g), 180) for r, g in zip(x1, y1)]   # 255,100,37

# 4-2.Beats ---------------------------------------------------------------------------------------
B = len(beats)
x2 = [x1[i] for i in range(B)]
y2 = [y1[i] for i in range(B)]
n2 = 13
radii_2 = np.random.rand(B) * E / n2
colors_2 = Blues8[2]

# 4-3.Onsets --------------------------------------------------------------------------------------
O = len(onsets)
x3 = [x1[-(i+1)] for i in range(O)]
y3 = [y1[-(i+1)] for i in range(O)]
n3 = 8
size_3 = np.random.rand(O) * E / n3
colors_3 = Greens8[2]

# 4-4.Frequency & Magnitude -----------------------------------------------------------------------
left_magnitude_dB_max = max(left_magnitude_dB)
left_frequency_max = max(left_frequency)
x_ratio = left_magnitude_dB_max / (0.5 * E)    # for modifying max value = E
y_ratio = left_frequency_max / (0.5 * E)       # for modifying max value = E

F = len(left_frequency)
x_4 = left_magnitude_dB / x_ratio              # certain magnitude(dB)
y_4 = left_frequency / y_ratio                 # certain frequency
n4 = 100
colors_4 = Inferno256[-10]

x4_1 = [x_4[n4 * i] + 0.5 * E for i in range(F / n4)]
y4_1 = [y_4[n4 * i] for i in range(F / n4)]

x4_2 = [-x_4[n4 * i] + 0.5 * E for i in range(F / n4)]
y4_2 = [y_4[n4 * i] for i in range(F / n4)]

x4_3 = [x_4[n4 * i] + 0.5 * E for i in range(F / n4)]
y4_3 = [-y_4[n4 * i] + E for i in range(F / n4)]

x4_4 = [-x_4[n4 * i] + 0.5 * E for i in range(F / n4)]
y4_4 = [-y_4[n4 * i] + E for i in range(F / n4)]

# 4-5.Adjusting Values ----------------------------------------------------------------------------
np.set_printoptions(precision = 0)

# 5_Creating Plots ================================================================================

p = figure(x_range = (0, E), y_range = (0, E), plot_width = E, plot_height = E)

# 6_Adding Renderers ==============================================================================

# 6-1.Onset Envelope(propotional to audio length) -------------------------------------------------
p.circle(x1, y1, radius = radii_1, fill_color = colors_1, fill_alpha = 0.15, line_color = None)
p.circle(x1, y1, color = "white", size = 1, alpha = 0.15)
p.line(
       x1, y1, line_color = "white", line_width = 0.3, line_dash = "dashdot", line_alpha = 0.25)

# 6-2.Beats ---------------------------------------------------------------------------------------
p.circle(
         x2, y2, radius = radii_2, fill_color = colors_2, fill_alpha = 0.1,
         line_color = colors_2, line_width = 1, line_dash = "dotted", line_alpha = 0.8)
p.circle(
         x2, y2, radius = radii_2 / 2, fill_color = colors_2, fill_alpha = 0.1,
         line_color = colors_2, line_width = 1, line_dash = "dotted", line_alpha = 0.8)
p.circle(
         x2, y2, radius = radii_2 / 4, fill_color = colors_2, fill_alpha = 0.1,
         line_color = colors_2, line_width = 1, line_dash = "dotted", line_alpha = 0.8)
p.cross(x2, y2, color = colors_2, size = 10, alpha = 1)
p.line(
       x2, y2, line_color = colors_2, line_width = 1, line_dash = "dotted", line_alpha = 0.8)

# 6-3.Onsets --------------------------------------------------------------------------------------
p.square(
         x3, y3, size = size_3, angle = 45, fill_color = colors_3, fill_alpha = 0.1,
         line_color = colors_3, line_width = 1, line_dash = "4 4", line_alpha = 0.8)
p.square(
         x3, y3, size = size_3 / 2, angle = 45, fill_color = colors_3, fill_alpha = 0.1,
         line_color = colors_3, line_width = 1, line_dash = "4 4", line_alpha = 0.8)
p.square(
         x3, y3, size = size_3 / 4, angle = 45, fill_color = colors_3, fill_alpha = 0.1,
         line_color = colors_3, line_width = 1, line_dash = "4 4", line_alpha = 0.8)
p.cross(x3, y3, angle = 45, color = colors_3, size = 10, alpha = 1)
p.line(
       x3, y3, line_color = colors_3, line_width = 1, line_dash = "dashed", line_alpha = 0.8)

# 6-4.Frequency & Magnitude -----------------------------------------------------------------------
p.line(x4_1, y4_1, line_color = colors_4, line_dash = "dotted", line_width = 0.6, line_alpha = 0.4)
p.line(x4_2, y4_2, line_color = colors_4, line_dash = "dotted", line_width = 0.6, line_alpha = 0.4)
p.line(x4_3, y4_3, line_color = colors_4, line_dash = "dotted", line_width = 0.6, line_alpha = 0.4)
p.line(x4_4, y4_4, line_color = colors_4, line_dash = "dotted", line_width = 0.6, line_alpha = 0.4)
p.line(y4_1, x4_1, line_color = colors_4, line_dash = "dotted", line_width = 0.6, line_alpha = 0.4)
p.line(y4_2, x4_2, line_color = colors_4, line_dash = "dotted", line_width = 0.6, line_alpha = 0.4)
p.line(y4_3, x4_3, line_color = colors_4, line_dash = "dotted", line_width = 0.6, line_alpha = 0.4)
p.line(y4_4, x4_4, line_color = colors_4, line_dash = "dotted", line_width = 0.6, line_alpha = 0.4)

# 7_Setting Plot Properties =======================================================================

# Background Properties
p.background_fill_color = b_opt   # Default value is "black"
p.background_fill_alpha = 1

# Outline Properties
p.outline_line_width = 0
p.outline_line_alpha = 0
p.outline_line_color = "black"

# Border Properties
p.min_border_left = 0
p.min_border_right = 0
p.min_border_top = 0
p.min_border_bottom = 0

# Grid / Axes Properties
p.grid.visible = False
p.xaxis.visible = False
p.yaxis.visible = False

# Toolbar Properties
p.toolbar.logo = None
p.toolbar_location = None

# 8_Exporting Output Files =======================================================================

# Output to PNG file
export_png(p, filename = o_opt)   # ouput file name according to input file name


import turtle as t
import math
t.shape("turtle")
x = 0
while x < 7:
    t.forward(x/2*math.pi)
    t.left(2*math.pi)
    x += 0.01
t.exitonclick()


# -*- encoding: utf-8 -*-
'''
Created on 15/01/2011

@author: ErunamoJAZZ
@license: GPLv3
@summary: Muffin Translator, ayudante para la traducción de anime.
@web: http://code.google.com/p/muffin/
'''

#import wx.stc as stc
import wx, os
import threading, time
import codecs

class MuffinText(wx.TextCtrl):
    '''
    MuffinText: Clase encargada del area de texto.
    '''

    def __init__(self, parent):
        '''
        Constructor
        '''
        #Si solo se ha abierto y no se a guardado, permanece falso
        self.esta_guardado=False
        self.path=None
        self.__parent=parent

        texto_inicial=u"""#(Modelo para traducir)
Actor 1: Well do I understand your speech, yet few strangers do so.
         Why then do you not speak in the Common Tongue,
         as is the custom in the West, if you wish to be answered?
         # TL check: The above seems to be a quote from the lord of the rings, look it up later
Actor 2: What are you babbling about?

NOTA: Use la tecla 'ESC' para pausar y despausar el video.
      Puedes usar las teclas F1 y F2 para ir 5 segundos atras o adelante en el video.
      MuffinTranslator tiene un sistema de auto-guardado cada 30seg, después de guardar la primer vez.
      #NO OLVIDES REPORTAR LOS ERRORES EN: http://code.google.com/p/muffin/issues/list"""

        wx.TextCtrl.__init__(self, self.__parent, -1, texto_inicial, style=wx.TE_MULTILINE|wx.HSCROLL)

    def __abrir_texto(self,_path):
        '''
        Abre un texto intentando primero desde utf-8, y
        luego desde Latin-1 (ANSI). Este ultimo abrirá
        mal textos en otras codificaciones, como unicode.
        '''
        try:
            file= codecs.open(_path, 'rU', 'utf-8')#OJO
            #file=open(_path,"rU")
            texto = file.read()
            print (u'Texto abierto con codificación utf-8')
        except:
            file.close()
            file= codecs.open(_path, 'rU', 'Latin-1')
            texto = file.read()
            print (u'Texto abierto con codificación Latin-1 (ANSI)')

        file.close()

        self.SetValue(texto)
        if self.esta_guardado:
            self.hiloGuardado.kill()
            self.hiloGuardado, self.path=None,None
            self.esta_guardado=False

    def __guardar_texto(self,_doc_path=None):
        '''
        Guarda el texto en un archivo, y hace un backup del mismo.
        '''
        if not _doc_path is None:
            self.path=_doc_path
        if not self.path is None:
            self.SaveFile(self.path)#soluciona problema con unicode
            self.SaveFile(self.path+'~')#guarda también un backup
            print (u"»» Archivo guardado correctamente + backup")
            if not self.esta_guardado:
                self.esta_guardado=True
                self.hiloGuardado=AutoGuardado(self)
                self.hiloGuardado.start()

        else:#si no hay path...
            self.onSaveFileWhit(wx.Event)

    #Evento para abrir Archivos
    def onLoadFile(self, event):
            dlg = wx.FileDialog(None, message=u"Seleccione un archivo de texto",
                                defaultDir=os.path.expanduser('~'), defaultFile=".txt",
                                style=wx.OPEN | wx.CHANGE_DIR )
            if dlg.ShowModal() == wx.ID_OK:
                path = dlg.GetPath()
                self.__abrir_texto( unicode( path.replace('\\','/')  )  )
                dlg.Destroy()

    #Evento para "Guardar Archivo como..."
    def onSaveFileWhit(self, event):
            dlg = wx.FileDialog(None, message=u"Guarde como un archivo de texto",
                                defaultDir=os.path.expanduser('~'), defaultFile=".txt",
                                style=wx.SAVE | wx.CHANGE_DIR )
            if dlg.ShowModal() == wx.ID_OK:
                path = dlg.GetPath()
                self.__guardar_texto( unicode( path.replace('\\','/')  )  )
                dlg.Destroy()

    def onSaveFile(self, event):
        self.__guardar_texto()

###############################################
########   AUTO-GUARDADO, MULTIHILO   #########
class AutoGuardado(threading.Thread):
    '''
    AutoGuardado: Clase que hereda de Therad, y
    guarda cada cierto tiempo los datos.
    '''
    def __init__(self, _wxText):
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self.__wxText=_wxText
        self.seguir_guardando=self.__wxText.esta_guardado

    def run(self):
        '''
        Inicia Bucle de auto-guardado.
        '''
        while True : #si ya se ha guardado
            time.sleep(30)
            if self.seguir_guardando:
                self.__wxText.SaveFile(self.__wxText.path)
                print (u"» Guardado Automatico...(30seg) "+self.getName() )
            else:
                print (unicode( self.getName()+" is dead X.x") )
                break

    def kill(self):
        '''
        Hace que el bucle se termine en la proxima iteración.
        '''
        self.seguir_guardando=False
        print (unicode( self.getName()+" pronto... morirá u.u") )
        #self.join()

#stc.PreStyledTextCtrl()


from flask import Flask,render_template,request

app = Flask(__name__)

def calc_tax(v,rate):
    try:
        rs = str(int(float(v)*(1 + rate)))
    except:
        print('calc error')
        rs = "計算できませんでした。"
    return rs

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

@app.route("/health-check", methods=["GET"])
def health_check():
    return "ok"

@app.route("/std", methods=["POST"])
def stdtaxinc():
    print(request.get_data())
    return calc_tax(request.get_data(), 0.1)

@app.route("/red", methods=["POST"])
def reducedtaxinc():
    print(request.get_data())
    return calc_tax(request.get_data(), 0.08)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)


import cv2
import numpy
import PIL
import datetime

def count_Faces(frame):
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')  # Load the Haar Cascade Classifier for face detection
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # Convert the frame
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)  # Use the detectMultiScale method to capture faces
    # Get the number of detected faces
    num_faces = len(faces)
    cv2.putText(frame, f'Number of Faces: {num_faces}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)  # Display the face count
    return num_faces

def Face_Cascade(frame):
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') # Load the Haar Cascade Classifier for face detection
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Convert the frame
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5) # Use the detectMultiScale method to capture faces
    times = []
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) # Annotate the faces by drawing rectangles

        cv2.putText(frame, f'Face: ({x}, {y})', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) #text with coordinates on the detected face

        # extract the region of interest (ROI)
        roi_gray = gray[y:y + h, x:x + w]
        roi_color = frame[y:y + h, x:x + w]
    cv2.imshow('Annotated Frame', frame) # Display the frame
    return frame, faces

if __name__=='__main__':
    cap = cv2.VideoCapture(0)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter('StudentName+TestId.avi', fourcc, 20.0, (640, 480))
    print(cap.isOpened())
    while (cap.isOpened()):
        ret, frame = cap.read()
        if ret == True:
            Face_Cascade(frame)
            count_Faces(frame)
            out.write(frame)
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            cv2.imshow('frame', frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            pass
    cap.release()
    out.release()
    cv2.destroyAllWindows()


# -*- encoding: utf-8 -*-

import json
import random
import requests
import sched
import time

from django.shortcuts import render
from django.http import HttpResponse
from datetime import datetime

from .load_data import load_data, load_access_token
from .getCalenderInformation import get_schedule

REPLY_ENDPOINT = 'https://api.line.me/v2/bot/message/reply'
ACCESS_TOKEN = load_access_token
HEADER = {
    "Content-Type": "application/json",
    "Authorization": "Bearer " + ACCESS_TOKEN
}

def index(request):
    return HttpResponse("This is a bot api.")

def callback(request):
    reply = ""
    #  requestの情報をdic形式で取得
    request_json = json.loads(request.body.decode('utf-8'))
    for e in request_json['events']:
        # 返信先のトークンの取得
        reply_token = e['replyToken']
        # typeの取得
        message_type = e['message']['type']

        if message_type == 'text':
            # 受信メッセージの取得
            text = e['message']['text']
            # Lineにセリフを返す
            reply += reply_text(reply_token, text)

    return HttpResponse(reply)

def reply_text(reply_token, text):
    reply = ""
    #if text.find('追加') > -1 or text.find('ついか') > -1:
     #   m_data = 'd';
    #el
    if text.find('予定') > -1 or text.find('よてい') > -1:
        m_data = get_schedule()
        if not m_data:
            reply = '直近のイベントが見つかりませんでした。'
        else:
            for i in m_data:
                reply += '・{}\n{}'.format(i[0], i[1])
                if i != m_data[-1]: reply += '\n\n'
                else: reply += '\n\nがありますよ！\n頑張ってください！'
    elif text == '言語ガチャ':
        reply = random.choice(load_data)
    else:
        reply = 'まだ実装してないよ。'
    payload = {
        "replyToken": reply_token,
        "messages": [
            {
                "type": "text",
                "text": reply
            }
        ]
    }

    # Lineにデータを送信
    requests.post(REPLY_ENDPOINT, headers=HEADER, data=json.dumps(payload))
    return reply

def news():
    m_data = get_today_schedule()
    if not m_data:
        reply = '直近のイベントが見つかりませんでした。'
    else:
        for i in m_data:
            reply += '{}\n{}がありますよ！\n頑張ってください！'.format(i[0], i[1])
            if i != m_data[-1]: reply += '\n\n'

    requests.post(REPLY_ENDPOINT, headers=HEADER, data=json.dumps(payload))
    return reply