import json
import os
import sys

from src.GracefulKiller import GracefulKiller
from src.youtube.songEnricher import enrich_song

json_file = os.path.join(os.path.dirname(__file__), "../../data/data.json")
simplified_file = os.path.join(os.path.dirname(__file__), "../../data/simplified.json")
jsonToSimplify = {}
simplified = []
with open(json_file) as json_data:
    jsonToSimplify = json.load(json_data)

def main(songs_json):
    song_entries = songs_json['entries']
    for key in song_entries:
        for songIndex in range(0, len(song_entries[key])):
            entry = song_entries[key][songIndex]

            kind = "none"
            url = entry['url']
            title = "%s - %s" % (entry['artist'], entry['song'])
            if "youtube" in entry and "snippet" in entry['youtube']:
                title = entry["youtube"]["snippet"]["title"]
                kind = entry["youtube"]["id"]["kind"]

                if "videoId" in entry["youtube"]["id"]:
                    url = entry["youtube"]["id"]["videoId"]

                if "playlistId" in entry["youtube"]["id"]:
                    url = entry["youtube"]["id"]["playlistId"]

            simplified.append({
                "genre": entry["genre"],
                "id": entry["unique_id"],
                "title": title,
                "kind": kind,
                "url": url
            })
    with open(simplified_file, 'w') as outfile:
        json.dump(simplified, outfile, indent=4)

if __name__ == '__main__':
    main(jsonToSimplify)


ANSI_CODES = {
    'fg_colour_template': u'\u001b[38;5;{}m',
    'bg_colour_template': u'\u001b[48;5;{}m',
    'reset': u'\u001b[0m',
}

COLOURS = {
    'value': 44,
}

def colourise(text, fg_colour_id, bg_colour_id=None):
    """Style a string with ANSI colour IDs.

    Args:
        text (str): Message to apply the styling to
        fg_colour_id (int): A value 0 to 255 representing the ANSI colour
            to be used as the font colour
        bg_colour_id (int): A value 0 to 255 representing the ANSI colour
            to be used as the highlight colour

    Returns:
        str: The ``text`` argument wrapped in the desired ANSI codes
    """
    fg_colour = ANSI_CODES['fg_colour_template'].format(fg_colour_id)

    if bg_colour_id:
        bg_colour = ANSI_CODES['bg_colour_template'].format(bg_colour_id)
    else:
        bg_colour = ''

    return '{}{}{}{}'.format(bg_colour, fg_colour, text, ANSI_CODES['reset'])

def confirm(text):
    """Ask the user to confirm.

    A confirmation is valid when 'y' or 'yes' was given as raw input.

    Args:
        text (str): Message passed to ``raw_input`` asking user for input

    Returns:
        bool: Whether the user confirmed or not
    """
    response = raw_input(text)
    ok = False

    try:
        ok = response.lower() in ['y', 'yes']
    except Exception:
        pass

    return ok


import os, random
from util.data import Data

# Set the random seed.
SEED = 0
random.seed(SEED)
SAMPLE_SIZE = 80

fname = "wendy-virtual.csv"
test = "readers"
data_name = fname + ".pkl"
sub_data_name = test + "_" + data_name

print("Loading data..")
if not os.path.exists(sub_data_name):
    print("Loading original data..")
    if os.path.exists(data_name):
        d = Data.load(data_name)
    else:
        d = Data.load(fname, sep=",", verbose=True)
        d.save(data_name)
        # 12002 (repeated header line)
        # 97498 (repeated header line)
        #  ... (4 more occurrences of this line)
    print("Done.")
    print()
    print(d)
    # Reduce to the "readers" test type
    d = d[d["Test"] == "readers"]
    print(d)
    # Collect by unique configurations
    params = ["Frequency", "File Size", "Record Size", "Num Threads"]
    d = d[params].unique().collect(d)
    d = d[params + ["Throughput"]]
    # Reduce all throughput sets with more than 80 samples to 80 samples.
    d["Throughput"] = (random.sample(tvals, SAMPLE_SIZE) for tvals in d["Throughput"])
    # Sort the data (to make it reasonably ordered)
    d.sort()
    print(d)
    # Save the data to file.
    d.save(sub_data_name)
else:
    d = Data.load(sub_data_name)
print("Done.")
print()

# Create new data that mimics structure of old data.
nd = Data(
    names=["Machine","Store","Journal","Hyp","Hyp_Sched","VM_Sched","RCU","F_size","R_Size","Threads","Mode","Freq","Throughput"],
    types=[str,      str,    str,      str,  str,        str,       int,  int,     int,     int,      str,   int,   float]
)
for (freq, fs, rs, nt, thrpts) in d:
    # Cycle through each of the throughput values and add them to the new data.
    for thrpt in thrpts:
        nd.append(["new", "HDD", "yes", "xen", "CFQ", "NOOP", 128, fs, rs, nt, "Fread", freq, thrpt])

print(nd)
nd.save("MODIFIED-wendy-virtual.csv")


 #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#

import subprocess, threading, shlex
import os
import sys

def run_rele(rele_type, rele_path):
	if rele_type == "usb":
		subprocess.Popen(["/usr/bin/python3", "/lib/security/howdy/usb.py", rele_path])
	if rele_type == "wifi":
		subprocess.Popen(["/usr/bin/python3", "/lib/security/howdy/wifi.py", rele_path])

rele_types = sys.argv[1]
rele_paths = sys.argv[2]

arr_types = rele_types.split(':')
arr_paths = rele_paths.split(':')

idx = 0
if len(arr_types) > 0:
	for type in arr_types:
		rele_type = arr_types[idx]
		rele_path = arr_paths[idx]
		run_rele(rele_type, rele_path)
		idx = idx + 1
else:
	run_rele(rele_types, rele_paths)

sys.exit(0)


from functools import reduce

# 统计大小写字母个数
def statistics(string):
    upper_count = 0
    lower_count = 0
    for elem in string:
        if elem.isupper():
            upper_count += 1
        elif elem.islower():
            lower_count += 1
    return upper_count, lower_count

# list 去重 乱序
def repeat_rid(name):
    new = list(set(name))
    return new

# list 去重 还是以前顺序
def repeat_rid_order(name):
    new = list(set(name))
    new.sort(key=name.index)
    return new

# 斐波那契数列
def fibonacci(n):
    if n <= 2:
        return 1
    else:
        return fibonacci(n - 2) + fibonacci(n - 1)

# 汉诺塔
def hanoi(n, start, go, end):
    if n == 1:
        print('{} -> {}'.format(start, end))
    else:
        hanoi(n - 1, start, end, go)
        hanoi(1, start, go, end)
        hanoi(n - 1, go, start, end)

# 杨辉三角
def triangles(n):
    # 杨辉三角形的数
    def triangles_num(line, col):
        # 每行第一个和最后一个为1
        if col == 0 or line == col:
            return 1
        else:
            # 上边两个数相加
            return triangles_num(line - 1, col - 1) + triangles_num(line - 1, col)
    # 画图
    for i in range(0, n):
        # 画空格
        for x in range(1, n - i):
            print(end="\t")
        # 杨辉三角形数
        for j in range(0, i + 1):
            print(triangles_num(i, j), end="\t\t")
        print()

# 参数组合
def all_parameter(name, password, national='汉', *hobby, age, married=False, **kw):
    return name, password, national, hobby, age, married, kw

# map函数，两个参数，一个函数，一个序列，用来把函数用到每一个序列成员
nums = (4, 5, 8, -8, 9, -7)
print(tuple(map(abs, nums)))

# reduce函数 首先参数函数必须只有两个参数，把结果继续和序列的下个元素累积
# reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
def power(num, p=2):
    return num ** p

print(reduce(power, (2, 2, 2, 2)))

# filter函数 参数函数必须返回布尔，根据布尔值来决定元素去留
def positive(num):
    return num >= 0

print(list(filter(positive, nums)))

# sorted函数， key=可以指定排序的函数
print(sorted(nums))
# 下面的lambda表达式表示一个函数：输入一个值然后取其绝对值，根据绝对值来排序
print(sorted(nums, key=lambda x: abs(x)))

if __name__ == '__main__':
    print(statistics('TuTyn./'))
    print(repeat_rid([2, 8, 5, 9, 8, 9, 2]))
    print(repeat_rid_order([2, 8, 5, 9, 8, 9, 2]))
    print(fibonacci(10))
    hanoi(2, 'A', 'B', 'C')
    triangles(6)


#！/usr/bin/env python
# -*- coding:utf-8 -*-
# _time_='2021/10/27 15:13'
# _PROJECT_NAME_=' alien_invasion '
# _NAME_=' settings '
# _USER_=' ThinkPad E15 '

class Settings():
    """存储游戏中所有设置类"""

    def __init__(self):
        """初始化游戏的设置"""
        #屏幕设置
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color = (230,230,230)

        #飞船的设置
        self.ship_speed_factor = 1.5
        self.ship_limit = 3

        #子弹设置
        self.bullet_speed_factor = 3
        self.bullet_width = 300
        self.bullet_height =15
        self.bullet_color = 60,60,60
        self.bullets_allowed = 3

        # 外星人设置
        self.alien_speed_factor = 1
        self.fleet_drop_speed = 10
        #fleet_direction为1表示向右移。-1为向左移
        self.fleet_direction = 1


"""This Flask app exposes a REST API which reads animal information from a
Redis database."""

import datetime
import json
import os

import flask
from flask import request
from flask import jsonify
import redis

from midterm import generate_animals

app = flask.Flask(__name__)
rd = redis.StrictRedis(
    host="redis", port=6379, db=0, charset="utf-8", decode_responses=True
)

@app.route("/create_animals", methods=["GET"])
def create_animals():
    """Generate animals and populate a redis database. The function expects the
    user to pass `number=foo`"""
    num_animals = request.args.get("number", default=1, type=int)
    for _ in range(num_animals):
        animal = generate_animals.generate_animal()
        rd.set(animal["uuid"], json.dumps(animal))

    if request.args.get("verbose", default=False, type=bool):
        return jsonify({key: rd.get(key) for key in rd.keys("*")})
    else:
        return f"Created {num_animals} animals.\n"

@app.route("/get_date_range", methods=["GET"])
def get_date_range():
    """Specify a start and end date and get animals that fall within the
    range. YYYY-MM-DDTHH:HH:SS.MS """
    start_date = request.args.get("start", default=None, type=str)
    start_date = datetime.datetime.fromisoformat(start_date)
    end_date = request.args.get("end", default=None, type=str)
    end_date = datetime.datetime.fromisoformat(end_date)

    animals = []
    for key in rd.keys("*"):
        animal = json.loads(rd.get(key))
        if (
            start_date
            <= datetime.datetime.fromisoformat(animal["created-on"])
            <= end_date
        ):
            animals.append(animal)

    return jsonify(animals)

@app.route("/get_uuid", methods=["GET"])
def get_uuid():
    """Get animal based on uuid specifier."""
    animal_uuid = request.args.get("uuid", default=1, type=str)
    return jsonify(rd.get(animal_uuid))

@app.route("/update_animal", methods=["GET"])
def update_animal():
    """Edit an existing animal.

    Specify an animal to edit by uuid. Then pass any of the follow animal
    parameters with values to update: body, arms, legs, tails."""

    animal_uuid = request.args.get("uuid", default=None, type=str)
    animal = json.loads(rd.get(animal_uuid))

    new_animal_body = request.args.get("body", default=None, type=str)
    if new_animal_body is not None:
        animal["body"] = new_animal_body

    new_animal_arms = request.args.get("arms", default=None, type=int)
    if new_animal_body is not None:
        animal["arms"] = new_animal_arms

    new_animal_legs = request.args.get("legs", default=None, type=int)
    if new_animal_legs is not None:
        animal["legs"] = new_animal_legs

    new_animal_tails = request.args.get("tails", default=None, type=int)
    if new_animal_tails is not None:
        animal["tails"] = new_animal_tails

    rd.set(animal_uuid, json.dumps(animal))
    return animal

@app.route("/remove_by_date", methods=["GET"])
def remove_by_date():
    """Specify a start and end date and remove all animals that fall within the
    range. YYYY-MM-DDTHH:HH:SS.MS """
    start_date = request.args.get("start", default=None, type=str)
    start_date = datetime.datetime.fromisoformat(start_date)
    end_date = request.args.get("end", default=None, type=str)
    end_date = datetime.datetime.fromisoformat(end_date)

    removed = []
    for key in rd.keys("*"):
        animal = json.loads(rd.get(key))
        if (
            start_date
            <= datetime.datetime.fromisoformat(animal["created-on"])
            <= end_date
        ):
            removed.append(animal)

    for animal in removed:
        rd.delete(animal["uuid"])

    return jsonify(removed)

@app.route("/get_leg_average", methods=["GET"])
def get_leg_average():
    """Get the average number of legs across all the animals in
    the dataset."""
    animals = [json.loads(rd.get(key)) for key in rd.keys("*")]
    legs = [animal["legs"] for animal in animals]
    return jsonify(sum(legs) / len(legs))

@app.route("/get_num_animals", methods=["GET"])
def get_num_animals():
    """Get the total number of animals in the dataset."""
    return jsonify(len(list(rd.keys("*"))))

@app.route("/get_animals", methods=["GET"])
def get_animals():
    """Print out all the animals in the dataset."""
    return jsonify({key: rd.get(key) for key in rd.keys("*")})

if __name__ == "__main__":

    app.run(debug=True, host="0.0.0.0")


import os
import numpy as np
import tensorflow as tf

from utils.load_config import load_config
from utils.load_data import load_data
from utils.extraction_model import load_extraction_model
from utils.remove_transition_morph_space import remove_transition_frames
from utils.PatternFeatureReduction import PatternFeatureSelection
from utils.ref_feature_map_neurons import ref_feature_map_neuron
from utils.calculate_position import calculate_position
from plots_utils.plot_cnn_output import plot_cnn_output
from plots_utils.plot_ft_map_pos import plot_ft_map_pos
from plots_utils.plot_ft_map_pos import plot_ft_pos_on_sequence
from models.NormBase import NormBase

np.random.seed(0)
np.set_printoptions(precision=3, suppress=True, linewidth=150)

"""
test script to try an implementation of a holistic representation model by a RBF_patch_pattern function of the face

run: python -m tests.NormBase.t11g_holisitc_template
"""

# define configuration
config_path = 'NB_t11g_holistic_template_m0002.json'
plot_intermediate = True
compute_NB = False

train = True
human_full = False
test = False
plot = False

# declare parameters
best_eyebrow_IoU_ft = [68, 125]
best_lips_IoU_ft = [235, 203, 68, 125, 3, 181, 197, 2, 87, 240, 6, 95, 60, 157, 227, 111]

# load config
config = load_config(config_path, path='configs/norm_base_config')

# create directory if non existant
save_path = os.path.join("models/saved", config["config_name"])
if not os.path.exists(save_path):
    os.mkdir(save_path)

# load and define model
v4_model = load_extraction_model(config, input_shape=tuple(config["input_shape"]))
v4_model = tf.keras.Model(inputs=v4_model.input, outputs=v4_model.get_layer(config['v4_layer']).output)
size_ft = tuple(np.shape(v4_model.output)[1:3])
print("[LOAD] size_ft", size_ft)
print("[LOAD] Model loaded")
print()

nb_model = NormBase(config, tuple(config['input_shape']))

if train:
    # -------------------------------------------------------------------------------------------------------------------
    # train

    # load data
    data = load_data(config)

    # remove transition frames
    data = remove_transition_frames(data)

    # predict
    preds = v4_model.predict(data[0], verbose=1)
    print("[TRAIN] shape prediction", np.shape(preds))

    # get feature maps that mimic a semantic selection pipeline
    # keep only highest IoU semantic score
    eyebrow_preds = preds[..., best_eyebrow_IoU_ft]
    print("shape eyebrow semantic feature selection", np.shape(eyebrow_preds))
    lips_preds = preds[..., best_lips_IoU_ft]
    print("shape lips semantic feature selection", np.shape(lips_preds))
    preds = np.concatenate((eyebrow_preds, lips_preds), axis=3)
    print("[TRAIN] shape preds", np.shape(preds))

    # add holistic templates
    # left ext eyebrow, left int eyebrow, right int eyebrow, right ext eyebrow, left lips, up lip, right lip, down lip
    rbf_template = [[[16, 21], [16, 21]], [[15, 20], [21, 26]], [[16, 21], [30, 35]], [[16, 21], [37, 42]],
            [[35, 40], [21, 26]], [[34, 39], [27, 32]], [[36, 41], [33, 38]], [[38, 43], [27, 32]]]
    config['rbf_sigma'] = [2100, 2100, 2100, 2100, 2100, 3000, 2100, 2500]

    # left lip
    rbf_template = [[[36, 41], [33, 38]]]
    config['rbf_sigma'] = [2100]
    # up lip
    # rbf_template = [[[34, 39], [27, 32]]]  # good on c2 with 3000
    # config['rbf_sigma'] = [3000]
    template = [[[37, 38], [29, 30]]]
    # rbf_template = [[[37, 38], [29, 31]]]  # a bit jittery with 600
    config['rbf_sigma'] = [500]
    # config['rbf_sigma'] = [600]
    # down lip
    rbf_template = [[[38, 40], [29, 31]]]  # [1350] start to be jittery
    rbf_template = [[[38, 40], [28, 32]]]
    config['rbf_sigma'] = [2200]  # upper bound
    config['rbf_sigma'] = [2100]
    # config['rbf_sigma'] = [2000]  # lower bound
    patterns = PatternFeatureSelection(config, template=rbf_template)
    rbf_template = np.repeat(np.expand_dims(preds, axis=0), len(rbf_template), axis=0)
    print("[TRAIN] shape rbf_template", np.shape(rbf_template))
    template = patterns.fit(rbf_template)
    template[template < 0.1] = 0

    # # using eyebrow ft map only
    # eyebrow_mask = [[[15, 22], [14, 21]]]  # left eye ext
    # config['rbf_sigma'] = [980]
    # eyebrow_mask = [[[15, 22], [21, 28]]]  # left eye int
    # config['rbf_sigma'] = [950]
    # eyebrow_mask = [[[17, 24], [27, 34]]]  # right eye int
    # config['rbf_sigma'] = [950]
    # eyebrow_mask = [[[16, 23], [38, 45]]]  # right eye ext
    # eyebrow_mask = [[[19, 20], [38, 39]]]  # right eye ext  point where I want it to be
    # config['rbf_sigma'] = [850]  # works on c1
    # # 1
    # eyebrow_mask = [[[17, 22], [36, 43]]]  # right eye ext
    # # 2
    # config['rbf_sigma'] = [750]  # works on c2
    # # 3
    # config['rbf_sigma'] = [850]  # avoid jump on c1
    # # 4
    # eyebrow_mask = [[[16, 23], [35, 44]]]  # 7x7
    # config['rbf_sigma'] = [1500]  # catch front
    # config['rbf_sigma'] = [1400]
    # # config['rbf_sigma'] = [1300]  # jump
    # # good on c2
    # # eyebrow_mask = [[[15, 22], [14, 21]], [[15, 22], [21, 28]], [[17, 24], [27, 34]], [[15, 22], [36, 43]]]
    # # config['rbf_sigma'] = [980, 900, 950, 900]
    # # test on c1
    # # eyebrow_mask = [[[15, 22], [14, 21]], [[15, 22], [21, 28]], [[17, 24], [27, 34]], [[15, 22], [36, 43]]]
    # # config['rbf_sigma'] = [980, 950, 950, 920]
    # eyebrow_patterns = PatternFeatureSelection(config, mask=eyebrow_mask)  # 3x3  eyebrow
    # mask_eyebrow_template = np.repeat(np.expand_dims(eyebrow_preds, axis=0), len(eyebrow_mask), axis=0)
    # print("[TRAIN] shape mask_eyebrow_template", np.shape(mask_eyebrow_template))
    # eyebrow_template = eyebrow_patterns.fit(mask_eyebrow_template)
    # print("[TRAIN] shape eyebrow_template", np.shape(eyebrow_template))
    #
    # # using lips ft map only
    # lips_mask = [[[35, 40], [21, 26]]]  # left lips
    # config['rbf_sigma'] = [2100]
    # lips_mask = [[[34, 39], [27, 32]]]  # up lips
    # config['rbf_sigma'] = [3000]
    # lips_mask = [[[36, 41], [33, 38]]]  # right lips
    # config['rbf_sigma'] = [1800]
    # lips_mask = [[[38, 43], [27, 32]]]  # down lips
    # config['rbf_sigma'] = [2500]
    # lips_mask = [[[35, 40], [21, 26]], [[34, 39], [27, 32]], [[36, 41], [33, 38]], [[38, 43], [27, 32]]]
    # config['rbf_sigma'] = [2100, 3000, 1800, 2500]
    # lips_patterns = PatternFeatureSelection(config, mask=lips_mask)  # 3x3  eyebrow
    # mask_lips_template = np.repeat(np.expand_dims(lips_preds, axis=0), len(lips_mask), axis=0)
    # print("[TRAIN] shape mask_lips_template", np.shape(mask_lips_template))
    # lips_template = lips_patterns.fit(mask_lips_template)
    # print("[TRAIN] shape lips_template", np.shape(lips_template))
    #
    # template = np.concatenate((eyebrow_template, lips_template), axis=3)
    # template = eyebrow_template
    # print("[TRAIN] shape template", np.shape(template))
    # template[template < 0.1] = 0

    # compute positions
    pos = calculate_position(template, mode="weighted average", return_mode="xy float flat")
    print("[TRAIN] shape pos", np.shape(pos))

    if plot_intermediate:
        plot_cnn_output(template, os.path.join("models/saved", config["config_name"]),
                        "00_template.gif", verbose=True, video=True)

        test_pos_2d = np.reshape(pos, (len(pos), -1, 2))
        plot_ft_map_pos(test_pos_2d,
                        fig_name="00b_human_pos.png",
                        path=os.path.join("models/saved", config["config_name"]))

        # test_max_preds = np.expand_dims(np.amax(test_preds, axis=3), axis=3)
        test_max_preds = np.expand_dims(np.amax(eyebrow_preds, axis=3), axis=3)
        # test_max_preds = np.expand_dims(np.amax(lips_preds, axis=3), axis=3)
        preds_plot = test_max_preds / np.amax(test_max_preds) * 255
        print("shape preds_plot", np.shape(preds_plot))
        plot_ft_pos_on_sequence(pos, preds_plot, vid_name='00_ft_eyebrow_pos.mp4',
                                save_folder=os.path.join("models/saved", config["config_name"]),
                                pre_proc='raw', ft_size=(56, 56))

        plot_ft_pos_on_sequence(pos, data[0],
                                vid_name='00_ft_pos_human.mp4',
                                save_folder=os.path.join("models/saved", config["config_name"]),
                                lmk_size=1, ft_size=(56, 56))

    if compute_NB:
        nb_model.n_features = np.shape(pos)[-1]  # todo add this to init
        # train manually ref vector
        nb_model.r = np.zeros(nb_model.n_features)
        nb_model._fit_reference([pos, data[1]], config['batch_size'])
        print("[TRAIN] model.r", np.shape(nb_model.r))
        print(nb_model.r)
        ref_train = np.copy(nb_model.r)
        # train manually tuning vector
        nb_model.t = np.zeros((nb_model.n_category, nb_model.n_features))
        nb_model.t_mean = np.zeros((nb_model.n_category, nb_model.n_features))
        nb_model._fit_tuning([pos, data[1]], config['batch_size'])
        ref_tuning = np.copy(nb_model.t)
        print("[TRAIN] ref_tuning[1]")
        print(ref_tuning[1])
        # get it resp
        it_train = nb_model._get_it_resp(pos)
        print("[TRAIN] shape it_train", np.shape(it_train))

        # ds_train = nb_model._get_decisions_neurons(it_train, config['seq_length'])
        # print("[TRAIN] shape ds_train", np.shape(ds_train))
        # print()

if human_full:
    # -------------------------------------------------------------------------------------------------------------------
    # test Full human
    # load data
    data = load_data(config)
    # predict
    preds = v4_model.predict(data[0], verbose=1)
    print("[PRED] shape prediction", np.shape(preds))

    # get feature maps that mimic a semantic selection pipeline
    # keep only highest IoU semantic score
    eyebrow_preds = preds[..., best_eyebrow_IoU_ft]
    print("[PRED] shape eyebrow semantic feature selection", np.shape(eyebrow_preds))
    lips_preds = preds[..., best_lips_IoU_ft]
    print("[PRED] shape lips semantic feature selection", np.shape(lips_preds))
    preds = np.concatenate((eyebrow_preds, lips_preds), axis=3)
    print("[PRED] shape preds", np.shape(preds))

    # max activation
    max_eyebrow_preds = np.expand_dims(np.amax(eyebrow_preds, axis=-1), axis=3)
    max_lips_preds = np.expand_dims(np.amax(lips_preds, axis=-1), axis=3)
    print("[PRED] max_eyebrow_preds", np.shape(max_eyebrow_preds))
    print("[PRED] max_lips_preds", np.shape(max_lips_preds))

    # compute templates
    mask_template = np.repeat(np.expand_dims(preds, axis=0), len(mask), axis=0)
    template = patterns.transform(mask_template)
    print("[PRED] shape template", np.shape(template))
    template[template < 0.1] = 0

    # mask_eyebrow_template = np.repeat(np.expand_dims(eyebrow_preds, axis=0), len(eyebrow_mask), axis=0)
    # print("[TRAIN] shape mask_eyebrow_template", np.shape(mask_eyebrow_template))
    # eyebrow_template = eyebrow_patterns.transform(mask_eyebrow_template)
    # mask_lips_template = np.repeat(np.expand_dims(lips_preds, axis=0), len(lips_mask), axis=0)
    # print("[TRAIN] shape mask_lips_template", np.shape(mask_lips_template))
    # lips_template = lips_patterns.transform(mask_lips_template)
    #
    # template = np.concatenate((eyebrow_template, lips_template), axis=3)
    # print("[PRED] shape template", np.shape(template))
    # template[template < 0.1] = 0

    # compute positions
    pos = calculate_position(template, mode="weighted average", return_mode="xy float flat")
    print("[PRED] shape pos", np.shape(pos))

    if compute_NB:
        # get it resp for eyebrows
        it_train = nb_model._get_it_resp(pos)
        print("[PRED] shape it_train", np.shape(it_train))

        # ds_train = nb_model._get_decisions_neurons(it_train, config['seq_length'])
        # print("[PRED] shape ds_train", np.shape(ds_train))
        # print()

if test:
    # -------------------------------------------------------------------------------------------------------------------
    # test monkey

    # load data
    test_data = load_data(config, train=False)

    # predict
    test_preds = v4_model.predict(test_data[0], verbose=1)
    print("[TEST] shape test_preds", np.shape(test_preds))

    # get feature maps that mimic a semantic selection pipeline
    # keep only highest IoU semantic score
    test_eyebrow_preds = test_preds[..., best_eyebrow_IoU_ft]
    test_lips_preds = test_preds[..., best_lips_IoU_ft]
    print("[TEST] shape eyebrow semantic feature selection", np.shape(test_eyebrow_preds))
    print("[TEST] shape lips semantic feature selection", np.shape(test_lips_preds))
    test_preds = np.concatenate((test_eyebrow_preds, test_lips_preds), axis=3)
    print("[TEST] shape test_preds", np.shape(test_preds))

    # max activation
    test_max_eyebrow_preds = np.expand_dims(np.amax(test_eyebrow_preds, axis=-1), axis=3)
    print("[TEST] test_max_eyebrow_preds", np.shape(test_max_eyebrow_preds))
    test_max_lips_preds = np.expand_dims(np.amax(test_lips_preds, axis=-1), axis=3)
    print("[TEST] test_max_lips_preds", np.shape(test_max_lips_preds))

    # add holistic templates
    test_mask = [[[8, 15], [17, 24]], [[9, 16], [22, 29]], [[9, 16], [28, 35]], [[8, 15], [33, 40]],
                 [[33, 38], [19, 24]], [[32, 37], [26, 31]], [[33, 38], [32, 37]], [[34, 39], [26, 31]]]
    config['rbf_sigma'] = [3500, 3500, 3500, 3500, 2100, 3200, 2100, 3500]

    test_mask = [[[32, 37], [26, 31]]]
    config['rbf_sigma'] = [3200]
    test_patterns = PatternFeatureSelection(config, mask=test_mask)  # 3x3  eyebrow
    test_mask_template = np.repeat(np.expand_dims(test_preds, axis=0), len(test_mask), axis=0)
    test_template = test_patterns.fit(test_mask_template)
    test_template[test_template < 0.1] = 0

    #
    # # using eyebrow ft map only
    # test_eyebrow_maks = [[[9, 16], [17, 24]]]  # left eye ext
    # config['rbf_sigma'] = [800]
    # test_eyebrow_maks = [[[10, 17], [22, 29]]]  # left eye int
    # config['rbf_sigma'] = [800]
    # test_eyebrow_maks = [[[9, 16], [28, 35]]]  # right eye int
    # config['rbf_sigma'] = [800]
    # test_eyebrow_maks = [[[8, 15], [33, 40]]]  # right eye ext
    # config['rbf_sigma'] = [540]
    # test_eyebrow_maks = [[[9, 16], [17, 24]], [[10, 17], [22, 29]], [[9, 16], [28, 35]], [[8, 15], [33, 40]]]
    # config['rbf_sigma'] = [800, 800, 800, 540]
    # test_patterns = PatternFeatureSelection(config, mask=test_eyebrow_maks)  # 3x3  eyebrow
    # test_mask_eyebrow_template = np.repeat(np.expand_dims(test_eyebrow_preds, axis=0), len(test_eyebrow_maks), axis=0)
    # print("[TEST] shape test_mask_eyebrow_template", np.shape(test_mask_eyebrow_template))
    # test_eyebrow_template = test_patterns.fit(test_mask_eyebrow_template)
    # print("[TEST] shape test_eyebrow_template", np.shape(test_eyebrow_template))
    #
    # # using lips ft map only
    # test_lips_mask = [[[33, 38], [19, 24]]]  # left eye ext
    # config['rbf_sigma'] = [1800]
    # test_lips_mask = [[[32, 37], [26, 31]]]  # left eye int
    # config['rbf_sigma'] = [3000]
    # test_lips_mask = [[[33, 38], [32, 37]]]  # right eye int
    # config['rbf_sigma'] = [2100]
    # test_lips_mask = [[[35, 40], [26, 31]]]  # right eye ext
    # config['rbf_sigma'] = [3200]
    # test_lips_mask = [[[33, 38], [19, 24]], [[32, 37], [26, 31]], [[33, 38], [32, 37]], [[35, 40], [26, 31]]]
    # config['rbf_sigma'] = [1800, 3000, 2100, 3200]
    # test_patterns = PatternFeatureSelection(config, mask=test_lips_mask)  # 3x3  eyebrow
    # test_mask_lips_template = np.repeat(np.expand_dims(test_lips_preds, axis=0), len(test_lips_mask), axis=0)
    # print("[TEST] shape test_mask_lips_template", np.shape(test_mask_lips_template))
    # test_lips_template = test_patterns.fit(test_mask_lips_template)
    # print("[TEST] shape test_lips_template", np.shape(test_lips_template))
    #
    # test_template = np.concatenate((test_eyebrow_template, test_lips_template), axis=3)
    # print("[TEST] shape test_template", np.shape(test_template))
    # test_template[test_template < 0.1] = 0
    #
    # compute positions
    test_pos = calculate_position(test_template, mode="weighted average", return_mode="xy float flat")
    print("[TEST] shape test_pos", np.shape(test_pos))

    if plot_intermediate:
        plot_cnn_output(test_template, os.path.join("models/saved", config["config_name"]),
                        "00_test_template.gif", verbose=True, video=True)

        test_pos_2d = np.reshape(test_pos, (len(test_pos), -1, 2))
        plot_ft_map_pos(test_pos_2d,
                        fig_name="00b_monkey_test_pos.png",
                        path=os.path.join("models/saved", config["config_name"]))

        # test_max_preds = np.expand_dims(np.amax(test_preds, axis=3), axis=3)
        # test_max_preds = np.expand_dims(np.amax(test_eyebrow_preds, axis=3), axis=3)
        test_max_preds = np.expand_dims(np.amax(test_lips_preds, axis=3), axis=3)
        preds_plot = test_max_preds / np.amax(test_max_preds) * 255
        print("shape preds_plot", np.shape(preds_plot))
        plot_ft_pos_on_sequence(test_pos, preds_plot, vid_name='00_ft_eyebrow_pos.mp4',
                                save_folder=os.path.join("models/saved", config["config_name"]),
                                pre_proc='raw', ft_size=(56, 56))

        plot_ft_pos_on_sequence(test_pos, test_data[0],
                                vid_name='00_ft_pos_monkey.mp4',
                                save_folder=os.path.join("models/saved", config["config_name"]),
                                lmk_size=1, ft_size=(56, 56))

    if compute_NB:
        # get IT responses of the model
        it_test = nb_model._get_it_resp(test_pos)

        # test by training new ref
        nb_model._fit_reference([test_pos, test_data[1]], config['batch_size'])
        ref_test = np.copy(nb_model.r)
        it_ref_test = nb_model._get_it_resp(test_pos)
        #
        # # ds_test = nb_model._get_decisions_neurons(it_ref_test, config['seq_length'])
        # # print("[TEST] shape ds_test", np.shape(ds_test))

if plot:
    # --------------------------------------------------------------------------------------------------------------------
    # plots
    # ***********************       test 00 raw output      ******************
    #
    # # raw activity
    # plot_cnn_output(max_eyebrow_preds, os.path.join("models/saved", config["config_name"]),
    #                 "00_max_feature_maps_eyebrow_output.gif", verbose=True, video=True)
    # plot_cnn_output(max_lips_preds, os.path.join("models/saved", config["config_name"]),
    #                 "00_max_feature_maps_lips_output.gif", verbose=True, video=True)
    # plot_cnn_output(test_max_eyebrow_preds, os.path.join("models/saved", config["config_name"]),
    #                 "00_test_max_feature_maps_eyebrow_output.gif", verbose=True, video=True)
    # plot_cnn_output(test_max_lips_preds, os.path.join("models/saved", config["config_name"]),
    #                 "00_test_max_feature_maps_lips_output.gif", verbose=True, video=True)
    #
    # plot_cnn_output(preds, os.path.join("models/saved", config["config_name"]),
    #                 "00a_max_feature_maps_output.gif", verbose=True, video=True)
    # plot_cnn_output(test_preds, os.path.join("models/saved", config["config_name"]),
    #                 "00a_test_max_maps_output.gif", verbose=True, video=True)
    #
    # build arrows
    arrow_tail = np.repeat(np.expand_dims(np.reshape(ref_train, (-1, 2)), axis=0), config['n_category'], axis=0)
    arrow_head = np.reshape(ref_tuning, (len(ref_tuning), -1, 2))
    arrows = [arrow_tail, arrow_head]
    arrows_color = ['#0e3957', '#3b528b', '#21918c', '#5ec962', '#fde725']

    # put one color per label
    labels = data[1]
    color_seq = np.zeros(len(preds))
    color_seq[labels == 1] = 1
    color_seq[labels == 2] = 2
    color_seq[labels == 3] = 3
    color_seq[labels == 4] = 4

    print("[PLOT] shape preds", np.shape(preds))
    pos_2d = np.reshape(pos, (len(pos), -1, 2))
    print("[PLOT] shape pos_flat", np.shape(pos_2d))
    plot_ft_map_pos(pos_2d,
                    fig_name="00b_human_train_pos.png",
                    path=os.path.join("models/saved", config["config_name"]),
                    color_seq=color_seq,
                    arrows=arrows,
                    arrows_color=arrows_color)

    # build arrows
    arrow_tail = np.repeat(np.expand_dims(np.reshape(ref_test, (-1, 2)), axis=0), config['n_category'], axis=0)
    arrow_head = np.reshape(ref_tuning, (len(ref_tuning), -1, 2))
    arrows = [arrow_tail, arrow_head]
    arrows_color = ['#0e3957', '#3b528b', '#21918c', '#5ec962', '#fde725']

    # put one color per label
    test_labels = test_data[1]
    color_seq = np.zeros(len(test_labels))
    color_seq[test_labels == 1] = 1
    color_seq[test_labels == 2] = 2
    color_seq[test_labels == 3] = 3
    color_seq[test_labels == 4] = 4

    test_pos_2d = np.reshape(test_pos, (len(test_pos), -1, 2))
    plot_ft_map_pos(test_pos_2d,
                    fig_name="00b_monkey_test_pos.png",
                    path=os.path.join("models/saved", config["config_name"]),
                    color_seq=color_seq,
                    arrows=arrows,
                    arrows_color=arrows_color)

    # ***********************       test 01 model     ******************
    # plot it responses for eyebrow model
    nb_model.plot_it_neurons(it_train,
                             title="01_it_train",
                             save_folder=os.path.join("models/saved", config["config_name"]))
    # nb_model.plot_it_neurons(it_test,
    #                          title="01_it_test",
    #                          save_folder=os.path.join("models/saved", config["config_name"]))
    nb_model.plot_it_neurons(it_ref_test,
                             title="01_it_ref_test",
                             save_folder=os.path.join("models/saved", config["config_name"]))

    # ***********************       test 02 model     ******************
    # plot it responses for eyebrow model
    nb_model.plot_it_neurons_per_sequence(it_train,
                             title="02_it_train",
                             save_folder=os.path.join("models/saved", config["config_name"]))
    # nb_model.plot_it_neurons_per_sequence(it_test,
    #                          title="02_it_test",
    #                          save_folder=os.path.join("models/saved", config["config_name"]))
    nb_model.plot_it_neurons_per_sequence(it_ref_test,
                             title="02_it_ref_test",
                             save_folder=os.path.join("models/saved", config["config_name"]))

    print()
    # plot tracked vector on sequence
    plot_ft_pos_on_sequence(pos, data[0],
                            vid_name='03_ft_pos_human.mp4',
                            save_folder=os.path.join("models/saved", config["config_name"]),
                            lmk_size=1, ft_size=(56, 56))

    # plot tracked vector on sequence
    plot_ft_pos_on_sequence(test_pos, test_data[0],
                            vid_name='03_ft_pos_monkey.mp4',
                            save_folder=os.path.join("models/saved", config["config_name"]),
                            lmk_size=1, ft_size=(56, 56))
    print()

    # plot tracked vector on feature maps
    max_eyebrow_preds_plot = max_eyebrow_preds / np.amax(max_eyebrow_preds) * 255
    plot_ft_pos_on_sequence(pos[:, :8], max_eyebrow_preds_plot, vid_name='03_ft_pos_eyebrow_human.mp4',
                            save_folder=os.path.join("models/saved", config["config_name"]),
                            pre_proc='raw', ft_size=(56, 56))
    max_lips_preds_plot = max_lips_preds / np.amax(max_lips_preds) * 255
    plot_ft_pos_on_sequence(pos[:, 8:], max_lips_preds_plot, vid_name='03_ft_pos_lips_human.mp4',
                            save_folder=os.path.join("models/saved", config["config_name"]),
                            pre_proc='raw', ft_size=(56, 56))
    # monkey
    test_max_eyebrow_preds_plot = test_max_eyebrow_preds / np.amax(test_max_eyebrow_preds) * 255
    plot_ft_pos_on_sequence(test_pos[:, :8], test_max_eyebrow_preds_plot, vid_name='03_ft_pos_eyebrow_monkey.mp4',
                            save_folder=os.path.join("models/saved", config["config_name"]),
                            pre_proc='raw', ft_size=(56, 56))
    test_max_lips_preds_plot = test_max_lips_preds / np.amax(test_max_lips_preds) * 255
    plot_ft_pos_on_sequence(test_pos[:, 8:], test_max_lips_preds_plot, vid_name='03_ft_pos_lips_monkey.mp4',
                            save_folder=os.path.join("models/saved", config["config_name"]),
                            pre_proc='raw', ft_size=(56, 56))

    # ***********************       test 04 decision neuron     ******************
    # nb_model.plot_decision_neurons(ds_train,
    #                                title="04_ds_train",
    #                                save_folder=os.path.join("models/saved", config["config_name"]),
    #                                normalize=True)
    # nb_model.plot_decision_neurons(ds_test,
    #                                title="04_ds_test",
    #                                save_folder=os.path.join("models/saved", config["config_name"]),
    #                                normalize=True)


import os
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import smtplib
import random

engine= pyttsx3.init('sapi5')
voices= engine.getProperty('voices')
#print(voices)
engine.setProperty('voice',voices[1].id)

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

def wishMe():
    hour=int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning!!")
    elif hour>=12 and hour<18:
        speak("Good Afternoon !!")
    else:
        speak("Good Evening !!")
    speak("Hey I am Phoebe, How may I help you?")

def takecommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)

    try:
        print("Recognizing...")
        query= r.recognize_google(audio, language='en-in')
        print(f"User said: {query}\n")

    except Exception as e :
        print("say that again please ...")
        return "none"
    return query

def sendEmail(to,content) :
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('email@gmail.com','password')
    server.sendmail('email@gmail.com',to,content)
    server.close()

def show(query):

    if 'friends' in query:
        dr ="path"
        episode= os.listdir(dr)
        os.startfile(os.path.join(dr,(episode[0])))
    elif 'Harry potter' in query:
        dr ="path"
        episode= os.listdir(dr)
        os.startfile(os.path.join(dr,(episode[0])))

if __name__=="__main__":
    wishMe()
    while True:
     query = takecommand().lower()

     if 'wikipedia' in query:
        speak('Searching wikipedia.....')
        query = query.replace("wikipedia", "")
        results = wikipedia.summary(query,sentences=2)
        speak('According to wikipedia...')
        print(results)
        speak(results)

     elif 'open youtube' in query:
        webbrowser.open("youtube.com")

     elif 'open google' in query:
        webbrowser.open("google.com")

     elif 'open stackoverflow' in query:
         webbrowser.open("stackoverflow.com")

     elif 'play music' in query:
         music_dr ="C:\\Users\\soumy\\Music"
         songs= os.listdir(music_dr)
         print(songs)
         n=random.randint(0,len(songs))
         os.startfile(os.path.join(music_dr,(songs[n])))

     elif 'time' in query:
         strtime= datetime.datetime.now().strftime("%H:%M:%S")
         speak(f"Ma'am the time is {strtime}")

     elif 'open code' in query:
         codepath = "C:\\path"
         os.startfile(codepath)

     elif 'email' in query:
         try:
             speak("What should it say?")
             content = takecommand()
             to = "email@gmail.com"
             sendEmail(to,content)
             speak("Email has been sent")
         except Exception as e:
            print(e)
            speak("Sorry am  unable to do that")

     elif 'tell me a joke' in query:
         joke_list = ['I ate a clock yesterday, it was very time-consuming.','Have you played the updated kids game? I Spy With My Little Eye . . . Phone.','A perfectionist walked into a bar...apparently, the bar wasn’t set high enough','You know it is going to be a bad day when the letters in your alphabet soup spell D-I-S-A-S-T-E-R.','A fire hydrant has H-2-O on the inside and K-9-P on the outside','Did you hear about the crook who stole a calendar? He got twelve months.']
         n=random.randint(0,len(joke_list))
         speak(joke_list[n])

     elif 'good quote' in query:
         quote_list = ['Love For All, Hatred For None','Change the world by being yourself','Every moment is a fresh beginning','Never regret anything that made you smile','Die with memories, not dreams','Aspire to inspire before we expire.' ]
         n=random.randint(0,len(quote_list))
         speak(quote_list[n])

     elif 'show' in query:
         speak('Which one do you want me to open?')
         query=takecommand().lower()
         show(query)

     elif 'quit' in query:
        speak('Ok maam ,I am Quiting.....')
        exit()


from trading.stats.before.q_options import Options, main
from trading import util

class Options2(Options):
    Abbr = "options2"

    def answer(self, data, strategy):
        o, s = data
        #XXX factorize computing to a method in Options
        price = s.summary.get('Last Trade')
        puts_vol = sum(map(lambda x:x.volume, o.puts))
        calls_vol = sum(map(lambda x:x.volume, o.calls))
        puts_vol2 = sum(map(lambda x:x.volume*(price-x.strike), o.puts))
        calls_vol2 = sum(map(lambda x:x.volume*(x.strike-price), o.calls))
        puts_vol3 = sum(map(lambda x:x.open_int, o.puts))
        calls_vol3 = sum(map(lambda x:x.open_int, o.calls))
        c, p, c2, p2 = 0, 0, 0, 0
        for e in o.calls:
            if e.volume >= e.open_int:
                if price > e.strike:
                    c+=1
                else:
                    c2+=1
        for e in o.puts:
            if e.volume >= e.open_int:
                if price < e.strike:
                    p += 1
                else:
                    p2+=1
        r1 = puts_vol and calls_vol/float(puts_vol) or 0
        r2 = puts_vol2 and calls_vol2/float(puts_vol2) or 0
        r3 = puts_vol3 and calls_vol3/float(puts_vol3) or 0

        if strategy == 'gap_up':
            return r3 < r1 < r2 and not p2 and not c and not c2
            #return not not (r3 > r1 > r2  and p and c and c2)
        elif strategy == 'gap_down':
            return

if __name__ == '__main__':
    main(Options2)


# -*- coding: utf-8 -*-
"""
Created on Tue Jul 13 12:21:52 2021

@author: JackC
"""

from math import tan,pi,atan,sin,asin
from matplotlib import pyplot as plt

class len:
    def __init__(self,r,f,tc,te,nd):
        self.r=r
        self.f=f
        self.tc=tc
        self.te=te
        self.nd=nd
        self.rr=((tc/2 - te/2)**2 + r**2)/(tc - te)
    def getYDWithYD(self,y,d):
        if(d==0):
            d=0.0000001
        #输入为y，与透镜中心面交点离光轴距离，d，入射角度(绝对角度)
        #输出为y，与透镜中心面交点离光轴距离，d，出射角度(绝对角度)
        k=-tan(d/180*pi)
        b=y
        tc=self.tc
        r=self.rr

        #print("d:"+str(d))
        #print("b:"+str(b))
        #print("k:"+str(k))
        #print("tc:"+str(tc))
        #print("rr:"+str(r))

        x=-(b - (2*b - k*(- 4*b**2 - 8*b*k*r + 4*b*k*tc + 4*k**2*r*tc - k**2*tc**2 + 4*r**2)**(1/2) + 2*k*r - k*tc)/(2*(k**2 + 1)))/k
        #y=(2*b + k*(- 4*b**2 - 8*b*k*r + 4*b*k*tc + 4*k**2*r*tc - k**2*tc**2 + 4*r**2)**(1/2) + 2*k*r - k*tc)/(2*(k**2 + 1))
        y=-k*x+b
        #得到左侧入射交点

        theta=atan((r-tc/2-x)/y)
        theta+=pi/2
        phi=d/180*pi

        theta=(theta+2*pi)%pi
        if(theta>pi/2):
            theta-=pi
        phi=(phi+2*pi)%pi
        if(phi>pi/2):
            phi-=pi

        #print("inang:"+str(inang/pi*180))
        print("phi:"+str(phi/pi*180))
        print("theta:"+str(theta/pi*180))
        print("x:"+str(x))
        print("y:"+str(y))

        inang=abs(phi-theta)
        ouang=asin(sin(inang)/self.nd)
        print("ina:"+str(inang/pi*180))
        print("oua:"+str(ouang/pi*180))

        if(phi<theta):
            out=theta-ouang
        else:
            out=theta+ouang

        out=(out+2*pi)%pi
        if(out>pi/2):
            out-=pi
        outy=y-tan(out)*x

        outo=out/pi*180
        print("out:"+str(outo))

        k=tan(out)
        b=outy
        x2=-(b - (2*b + k*(- 4*b**2 + 8*b*k*r - 4*b*k*tc + 4*k**2*r*tc - k**2*tc**2 + 4*r**2)**(1/2) - 2*k*r + k*tc)/(2*(k**2 + 1)))/k
        y2=-k*x2+b

        theta2=atan((x2-r+tc/2)/y2)
        theta2+=pi/2
        theta2=(theta2+2*pi)%pi
        if(theta2>pi/2):
            theta2-=pi
        print("theta2:"+str(theta2/pi*180))
        inang2=abs(out-theta2)
        ouang2=asin(sin(inang2)*self.nd)
        print("ina2:"+str(inang2/pi*180))
        print("oua2:"+str(ouang2/pi*180))

        print("x2:"+str(x2))
        print("y2:"+str(y2))
        if(out<theta2):
            out2=theta2-ouang2
        else:
            out2=theta2+ouang2
        outy2=y2-tan(out2)*x2
        out2=out2/pi*180
        print("out2:"+str(out2))
        print("outy2:"+str(outy2))

        print("")

        return outy,outo,x,outy2,out2,x2,y,y2

la=len(3,7.65,2.2,1,1.5168)

def drawroute(la,cnt,dcnt,rang,bgp,edp,dot=1):
    inlights=[]
    oulights=[]
    for i in range(-cnt//2,cnt//2+1):
        if(dot):
            inlights.append([i/(cnt/rang),atan(i/(cnt/rang)/bgp)/pi*180])
        else:
            inlights.append([i/(cnt/rang),0])
        oulights.append(la.getYDWithYD(inlights[-1][0],inlights[-1][1]))

    plt.grid()
    for l in range(cnt+1):
        x=[-bgp+(bgp+oulights[l][2])/100*i for i in range(dcnt)]
        y=[inlights[l][0]+tan(inlights[l][1]/180*pi)*i for i in x]
        plt.plot(x,y,c='green')

    for l in range(cnt+1):
        x=[edp*i/dcnt+oulights[l][5] for i in range(dcnt)]
        y=[oulights[l][3]+tan(oulights[l][4]/180*pi)*i for i in x]
        plt.plot(x,y,c='red')

    for l in range(cnt+1):
        x=[oulights[l][2],oulights[l][5]]
        y=[oulights[l][6],oulights[l][7]]
        print("x:")
        print(x)
        print("y:")
        print(y)
        plt.plot(x,y,c="blue")

    plt.show()

drawroute(la,30,100,4,10,10,0)
drawroute(la,30,100,4,10,10,1)


for i in range(int(input())):
    n = int(input())

    rr = [int(r) for r in input()]
    bb = [int(b) for b in input()]

    if sum(rr) / len(rr) == sum(bb) / len(bb):
        print('EQUAL')
    else:
        print('RED' if sum(rr) / len(rr) > sum(bb) / len(bb) else 'BLUE')


# os.chdir(os.path.dirname(__file__))

def getEmails(path_to_file):
    emails = []
    # Format of CSV needs to be [business_name,email]
    with open(path_to_file, newline='') as csvfile:

        # Find index of email column
        emailIndex = None
        for row in csvfile:
            columns = row.lower().split(";")
            for column in columns:
                if "email" in column:
                    emailIndex = columns.index(column)
            break

        # Get email
        for row in csvfile:
            email = row.lower().split(";")[emailIndex].strip()
            emails.append(email)

    return emails


"""
Implementation of deep recurrent attentive writer (DRAW), based on

    https://github.com/ericjang/draw

Original paper:

    DRAW: A recurrent neural network for image generation.
    https://arxiv.org/abs/1502.04623

"""
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib.rnn import LSTMCell

# Load the data
data = input_data.read_data_sets('datasets/mnist', one_hot=True)
IMAGE_WIDTH  = 28
IMAGE_HEIGHT = 28
IMAGE_SIZE   = IMAGE_WIDTH * IMAGE_HEIGHT

# Hyperparameters
encoder_size  = 256
decoder_size  = 256
T             = 10
batch_size    = 100
learning_rate = 1e-3
num_epochs    = 20
latent_dim    = 10
eps           = 1e-8

# Attention parameters
attention = True
read_n    = 5
write_n   = 5

def linear(x, dim):
    W = tf.get_variable('W', [x.get_shape()[-1].value, dim])
    b = tf.get_variable('b', [dim], initializer=tf.constant_initializer(0.0))
    return tf.matmul(x, W) + b

# Seed the TF random number generator for reproducible initialization
tf.set_random_seed(0)

# For feeding in data
x = tf.placeholder(tf.float32, [None, IMAGE_SIZE])

# VAE
encoder = LSTMCell(encoder_size)
decoder = LSTMCell(decoder_size)

def filter_bank(gx, gy, var, delta, n):
    grid = tf.reshape(tf.cast(tf.range(n), dtype=tf.float32), [1, -1])
    mu_x = tf.reshape(gx + (grid - n/2 - 0.5) * delta, [-1, n, 1]) # Eq. 19
    mu_y = tf.reshape(gy + (grid - n/2 - 0.5) * delta, [-1, n, 1]) # Eq. 20
    a    = tf.reshape(tf.cast(tf.range(IMAGE_WIDTH),  tf.float32), [1, 1, -1])
    b    = tf.reshape(tf.cast(tf.range(IMAGE_HEIGHT), tf.float32), [1, 1, -1])
    var  = tf.reshape(var, [-1, 1, 1])

    # Eq. 25
    Fx    = tf.exp(-tf.square((a - mu_x) / (2*var)))
    norm  = tf.reduce_sum(Fx, 2, keep_dims=True)
    Fx   /= tf.maximum(norm, eps)

    # Eq. 26
    Fy    = tf.exp(-tf.square((b - mu_y) / (2*var)))
    norm  = tf.reduce_sum(Fy, 2, keep_dims=True)
    Fy   /= tf.maximum(norm, eps)

    return Fx, Fy

def attention_window(scope, reuse, decoder_output, n):
    with tf.variable_scope(scope, reuse=reuse):
        params = linear(decoder_output, 5) # Eq. 21
    gx, gy, log_var, log_delta, log_gamma = tf.split(params, 5, axis=1)
    var   = tf.exp(log_var)
    delta = tf.exp(log_delta)
    gamma = tf.exp(log_gamma)

    gx     = (gx + 1) * (IMAGE_WIDTH + 1)/2                       # Eq. 22
    gy     = (gy + 1) * (IMAGE_HEIGHT + 1)/2                      # Eq. 23
    delta  = (max(IMAGE_WIDTH, IMAGE_HEIGHT) - 1) / (n-1) * delta # Eq. 24
    Fx, Fy = filter_bank(gx, gy, var, delta, n)

    return Fx, Fy, gamma

# Eq. 27
def apply_filter(x, Fx, Fy, gamma, n):
    Fx_t = tf.transpose(Fx, perm=[0, 2, 1])
    x = tf.reshape(x, [-1, IMAGE_HEIGHT, IMAGE_WIDTH])
    x = tf.matmul(Fy, tf.matmul(x, Fx_t))
    return tf.reshape(gamma, [-1, 1]) * tf.reshape(x, [-1, n*n])

# Eq. 29
def apply_filter_rev(x, Fx, Fy, gamma, n):
    Fy_t = tf.transpose(Fy, perm=[0, 2, 1])
    x = tf.reshape(x, [-1, n, n])
    x = tf.matmul(Fy_t, tf.matmul(x, Fx))
    return tf.reshape(1/gamma, [-1, 1]) * tf.reshape(x, [-1, IMAGE_SIZE])

def read(x, x_error, decoder_output, reuse):
    if attention:
        Fx, Fy, gamma = attention_window('read', reuse, decoder_output, read_n)
        x       = apply_filter(x, Fx, Fy, gamma, read_n)
        x_error = apply_filter(x_error, Fx, Fy, gamma, read_n)
    return tf.concat([x, x_error], 1)

def write(decoder_output, reuse):
    if not attention:
        return linear(decoder_output, IMAGE_SIZE)

    with tf.variable_scope('patch', reuse=reuse):
        w = linear(decoder_output, write_n**2)
        w = tf.reshape(w, [batch_size, write_n, write_n])
    Fx, Fy, gamma = attention_window('write', reuse, decoder_output, write_n)
    return apply_filter_rev(w, Fx, Fy, gamma, write_n)

canvas          = tf.zeros_like(x)
reconstruction  = tf.zeros_like(x)
decoder_output  = tf.zeros((batch_size, decoder_size))
encoder_state   = encoder.zero_state(batch_size, tf.float32)
decoder_state   = decoder.zero_state(batch_size, tf.float32)
canvases        = []
reconstructions = []
z_means         = []
z_log_vars      = []
for t in range(T):
    if t == 0:
        reuse = None
    else:
        reuse = True

    # Encoding step
    with tf.variable_scope('encoder', reuse=reuse):
        # The encoder observes previous output
        x_error = x - reconstruction
        r = read(x, x_error, decoder_output, reuse)
        encoder_inputs = tf.concat([r, decoder_output], 1)

        encoder_output, encoder_state = encoder(encoder_inputs, encoder_state)
        with tf.variable_scope('mean'):
            z_mean = linear(encoder_output, latent_dim)
        with tf.variable_scope('var'):
            z_log_var = linear(encoder_output, latent_dim)
        z_means.append(z_mean)
        z_log_vars.append(z_log_var)

    # Latent embedding
    epsilon = tf.random_normal(tf.shape(z_log_var))
    z = z_mean + epsilon * tf.exp(0.5*z_log_var)

    # Decoding step
    with tf.variable_scope('decoder', reuse=reuse):
        decoder_output, decoder_state = decoder(z, decoder_state)
        with tf.variable_scope('reconstruction'):
            # Accumulate the modifications
            canvas = canvas + write(decoder_output, reuse=reuse)
    canvases.append(canvas)

    # Previous reconstruction
    reconstruction = tf.sigmoid(canvas)
    reconstructions.append(reconstruction)

# Reconstruction loss at final time step
CE = tf.nn.sigmoid_cross_entropy_with_logits(logits=canvases[-1], labels=x)
CE = tf.reduce_sum(CE, 1)

# Latent loss for each time step
KLs = []
for z_mean, z_log_var in zip(z_means, z_log_vars):
    KL = 1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var)
    KL = -0.5 * tf.reduce_sum(KL, 1)
    KLs.append(KL)
KL = tf.add_n(KLs)

# Total loss
loss = tf.reduce_mean(CE + KL)

# Optimizer
optimizer  = tf.train.AdamOptimizer(learning_rate, beta1=0.5)
grads_vars = optimizer.compute_gradients(loss)
grads_vars = [(tf.clip_by_norm(g, 5), v) for g, v in grads_vars]
train_op   = optimizer.apply_gradients(grads_vars)

# Seed the random number generator for reproducible batches
np.random.seed(0)

# Print list of variables
print("")
print("Variables")
print("---------")
variables  = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
num_params = 0
for v in variables:
    num_params += np.prod(v.get_shape().as_list())
    print(v.name, v.get_shape())
print("=> Total number of parameters =", num_params)

# TF session
sess = tf.Session()
sess.run(tf.global_variables_initializer())

# Minimize the loss function
num_batches_per_epoch = data.train.num_examples // batch_size
for epoch in range(num_epochs):
    current_loss = 0
    for _ in range(num_batches_per_epoch):
        batch_x, _ = data.train.next_batch(batch_size)
        _, loss_val = sess.run([train_op, loss], {x: batch_x})
        current_loss += loss_val

    print("After {} epochs, loss = {}"
          .format(epoch+1, current_loss/num_batches_per_epoch))

def reconstruct(x_):
    return sess.run(reconstructions, {x: x_})

#-------------------------------------------------------------------------------
# Example reconstructions
#-------------------------------------------------------------------------------

nx = ny = 10
images = data.test.images[:nx*ny]
reconstructed_images = reconstruct(images)

for t, reconstructed_image in enumerate(reconstructed_images):
    grid = np.zeros((28*ny, 28*nx))
    for i in range(ny):
        for j in range(nx):
            grid[28*(ny-i-1):28*(ny-i),28*j:28*(j+1)] = (
                reconstructed_image[i*ny+j].reshape((28, 28))
                )

    plt.figure()
    plt.imshow(grid, cmap='gray')
    plt.savefig('figs/draw/reconstruction_t{}.png'.format(t))
    plt.close()


file = open('dane/dane.txt', 'r').read().split('\n')[:-1]
file = [[i.split()[0]] + i.split() + [i.split()[-1]] for i in file]
file = [file[0]] + file + [file[-1]]

ans = 0
tab = [-1, 1]
for i in range(1, len(file) - 1):
    for j in range(1, len(file[i]) -1):
        temp = 0
        for k in tab:
            temp += int( abs(int(file[i+k][j])- int(file[i][j])) > 128 or abs(int(file[i][j+k]) - int(file[i][j])) > 128)
        ans += int(temp > 0)

print(ans)


import entities
import cards
# each room has a battle in it, what the battle is depends on how deep you go

# each room stems from a room class
class Room(object):

    # making multiple enemies in the future is a possibility. Would have to figure out *args for the enemy param
    # and would have to add a for loop for the enemy turns in battle()
    def __init__(self, enemy, next_room):
        self.enemy = enemy
        self.next_room = next_room

    # room class probably has a method which plays a battle. Takes param of enemy which is fought
    def battle(self, player):

        player.reset_piles()
        # battle loop, determines that the battle continues if player and enemy are both still alive
        while player.health > 0 and self.enemy.health > 0:

            # player makes their deccisions/attacks
            player.my_turn(self.enemy)
            # enemy makes their decisions/attacks
            # seems like this may be happening even after the enemy dies
            self.enemy.my_turn(player)

        # ends turn as a safety measure incase you defeated the enemy before your turn was over
        # also functions as a way to restore energy after the battle
        player.end_turn()
        if player.health <= 0:
            self.next_room = "death"
        else:
            print("You win!")

    # each room returns a string which should represent the next room

    # default, pre-battle interaction with room. By default, only describes the room
    def interact(self, player):
        print("default room")

    def get_next_room(self):
        return self.next_room

class Death(Room):

    # in this case, description simply describes that you died
    def __init__(self):
        pass

    def interact(self):
        print("You have fallen....")

class FirstRoom(Room):

    def interact(self, player):
        print("""
Your adventure is just beginning.
On the way through the town, somebody slips by you a little bit too closely
Upon further inspection, it seems like he took your wallet
You locate him, but it looks like he's not going down without a fight
        """)
        self.battle(player)
        return self.get_next_room()

class ThiefBand(Room):

    def interact(self, player):
        print("""
You proceed, your wallet now back in your hands, towards the dungeon.
You feel like you're being followed...
Soon before you enter the dungeon, it becomes apparent who you were followed by
It seems that pickpocket had friends. A band of thieves emerges
The leader presents himself, and initiates a fight!
        """)
        self.battle(player)
        return self.get_next_room()

class Dungeon(Room):

    def interact(self, player):
        print("""
Now that those bandits are taken care of, It's time to go into the dungeon!
Uh-oh. That sounds like a Dragon
Yup, it's a dragon. Time to fight.
        """)
        self.battle(player)
        return self.get_next_room()

class Map(object):

    def __init__(self, player):
        self.player = player
        self.rooms = {
            'start room': FirstRoom(entities.Enemy("Pickpocket", 14, 3), 'thief band'),
            'thief band': ThiefBand(entities.Enemy("Bandit Leader", 20, 4), 'dungeon'),
            'dungeon': Dungeon(entities.Enemy("Dragon", 30, 5), 'end'),
            'death': Death()
        }

    def run(self):

        # we should run the start room first
        next = self.rooms['start room'].interact(self.player)
        while next != 'end' and next != 'death':
            next = self.rooms[next].interact(self.player)
        if next == 'end':
            print("That's all for the game right now")
        else:
            # lets you interact with the death room
            self.rooms[next].interact()


from __future__ import unicode_literals

"""
MongoEngine fixtures
"""
import mongoengine as mongo

from field_values import get_random_value

def make_fixture(model_class, **kwargs):
    """
    Take the model_klass and generate a fixure for it

    Args:
        model_class (MongoEngine Document): model for which a fixture
            is needed
        kwargs (dict): any overrides instead of random values

    Returns:
        dict for now, other fixture types are not implemented yet
    """
    all_fields = get_fields(model_class)

    fields_for_random_generation = map(
        lambda x: getattr(model_class, x), all_fields
    )

    overrides = {}

    for kwarg, value in kwargs.items():
        if kwarg in all_fields:
            kwarg_field = getattr(model_class, kwarg)
            fields_for_random_generation.remove(kwarg_field)
            overrides.update({kwarg_field: value})

    random_values = get_random_values(fields_for_random_generation)

    values = dict(overrides, **random_values)

    assert len(all_fields) == len(values), (
        "Mismatch in values, {} != {}".format(
            len(all_fields), len(values)
        )
    )
    data = {k.name: v for k, v in values.items()}
    return model_class(**data)

def get_fields(model_class):
    """
    Pass in a mongo model class and extract all the attributes which
    are mongoengine fields

    Returns:
        list of strings of field attributes
    """
    return [
        attr for attr, value in model_class.__dict__.items()
        if issubclass(type(value), (mongo.base.BaseField, mongo.EmbeddedDocumentField))  # noqa
    ]

def get_random_values(fields):
    """
    Pass in a list of fields (as strings) to get a dict with the
    field name as a key and a randomly generated value as another
    """
    values = {}

    for field in fields:
        try:
            value = get_random_value(field)
        except AttributeError:
            # this can only really occur if the field is not implemented yet.
            # Silencing the exception during the prototype phase
            value = None

        values.update({field: value})

    return values


from wxpy import *
bot = Bot(cache_path=True)
friends_stat=bot.friends().stats()
friends_loc=[]
for province ,count in friends_stat["city"].items():
    if province !="":
        friends_loc.append([province,count])

#对每个省份的人数降序排列
friends_loc.sort(key=lambda x:x[1],reverse=True)

#打印前10
for item in friends_loc[:]:
    print(item[0],item[1])


import logging
import os

import vtk

import slicer
from slicer.ScriptedLoadableModule import *
from slicer.util import VTKObservationMixin

#
# SurfaceModelNodesSelector
#

class SurfaceModelNodesSelector(ScriptedLoadableModule):
    """Uses ScriptedLoadableModule base class, available at:
    https://github.com/Slicer/Slicer/blob/main/Base/Python/slicer/ScriptedLoadableModule.py
    """

    def __init__(self, parent):
        ScriptedLoadableModule.__init__(self, parent)
        self.parent.title = "SurfaceModelNodesSelector"  # TODO: make this more human readable by adding spaces
        self.parent.categories = ["PointSelector"]  # TODO: set categories (folders where the module shows up in the module selector)
        self.parent.dependencies = []  # TODO: add here list of module names that this module requires
        self.parent.contributors = ["Saima Safdar"]  # TODO: replace with "Firstname Lastname (Organization)"
        # TODO: update with short description of the module and a link to online module documentation
        self.parent.helpText = """
This module is used to select the indeces/nodes of the any 3D surface model module documentation.
"""
        # TODO: replace with organization, grant and thanks
        self.parent.acknowledgementText = """

"""

        # Additional initialization step after application startup is complete
        slicer.app.connect("startupCompleted()", registerSampleData)

#
# Register sample data sets in Sample Data module
#

def registerSampleData():
    """
    Add data sets to Sample Data module.
    """
    # It is always recommended to provide sample data for users to make it easy to try the module,
    # but if no sample data is available then this method (and associated startupCompeted signal connection) can be removed.

    import SampleData
    iconsPath = os.path.join(os.path.dirname(__file__), 'Resources/Icons')

    # To ensure that the source code repository remains small (can be downloaded and installed quickly)
    # it is recommended to store data sets that are larger than a few MB in a Github release.

    # SurfaceModelNodesSelector1
    SampleData.SampleDataLogic.registerCustomSampleDataSource(
        # Category and sample name displayed in Sample Data module
        category='SurfaceModelNodesSelector',
        sampleName='SurfaceModelNodesSelector1',
        # Thumbnail should have size of approximately 260x280 pixels and stored in Resources/Icons folder.
        # It can be created by Screen Capture module, "Capture all views" option enabled, "Number of images" set to "Single".
        thumbnailFileName=os.path.join(iconsPath, 'SurfaceModelNodesSelector1.png'),
        # Download URL and target file name
        uris="https://github.com/Slicer/SlicerTestingData/releases/download/SHA256/998cb522173839c78657f4bc0ea907cea09fd04e44601f17c82ea27927937b95",
        fileNames='SurfaceModelNodesSelector1.nrrd',
        # Checksum to ensure file integrity. Can be computed by this command:
        #  import hashlib; print(hashlib.sha256(open(filename, "rb").read()).hexdigest())
        checksums='SHA256:998cb522173839c78657f4bc0ea907cea09fd04e44601f17c82ea27927937b95',
        # This node name will be used when the data set is loaded
        nodeNames='SurfaceModelNodesSelector1'
    )

    # SurfaceModelNodesSelector2
    SampleData.SampleDataLogic.registerCustomSampleDataSource(
        # Category and sample name displayed in Sample Data module
        category='SurfaceModelNodesSelector',
        sampleName='SurfaceModelNodesSelector2',
        thumbnailFileName=os.path.join(iconsPath, 'SurfaceModelNodesSelector2.png'),
        # Download URL and target file name
        uris="https://github.com/Slicer/SlicerTestingData/releases/download/SHA256/1a64f3f422eb3d1c9b093d1a18da354b13bcf307907c66317e2463ee530b7a97",
        fileNames='SurfaceModelNodesSelector2.nrrd',
        checksums='SHA256:1a64f3f422eb3d1c9b093d1a18da354b13bcf307907c66317e2463ee530b7a97',
        # This node name will be used when the data set is loaded
        nodeNames='SurfaceModelNodesSelector2'
    )

#
# SurfaceModelNodesSelectorWidget
#

class SurfaceModelNodesSelectorWidget(ScriptedLoadableModuleWidget, VTKObservationMixin):
    """Uses ScriptedLoadableModuleWidget base class, available at:
    https://github.com/Slicer/Slicer/blob/main/Base/Python/slicer/ScriptedLoadableModule.py
    """

    def __init__(self, parent=None):
        """
        Called when the user opens the module the first time and the widget is initialized.
        """
        ScriptedLoadableModuleWidget.__init__(self, parent)
        VTKObservationMixin.__init__(self)  # needed for parameter node observation
        self.logic = None
        self._parameterNode = None
        self._updatingGUIFromParameterNode = False

    def setup(self):
        """
        Called when the user opens the module the first time and the widget is initialized.
        """
        ScriptedLoadableModuleWidget.setup(self)

        # Load widget from .ui file (created by Qt Designer).
        # Additional widgets can be instantiated manually and added to self.layout.
        uiWidget = slicer.util.loadUI(self.resourcePath('UI/SurfaceModelNodesSelector.ui'))
        self.layout.addWidget(uiWidget)
        self.ui = slicer.util.childWidgetVariables(uiWidget)

        # Set scene in MRML widgets. Make sure that in Qt designer the top-level qMRMLWidget's
        # "mrmlSceneChanged(vtkMRMLScene*)" signal in is connected to each MRML widget's.
        # "setMRMLScene(vtkMRMLScene*)" slot.
        uiWidget.setMRMLScene(slicer.mrmlScene)

        # Create logic class. Logic implements all computations that should be possible to run
        # in batch mode, without a graphical user interface.
        self.logic = SurfaceModelNodesSelectorLogic()

        # Connections

        # These connections ensure that we update parameter node when scene is closed
        self.addObserver(slicer.mrmlScene, slicer.mrmlScene.StartCloseEvent, self.onSceneStartClose)
        self.addObserver(slicer.mrmlScene, slicer.mrmlScene.EndCloseEvent, self.onSceneEndClose)

        # These connections ensure that whenever user changes some settings on the GUI, that is saved in the MRML scene
        # (in the selected parameter node).
        # self.ui.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI)
        # self.ui.inputFiducial.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI)
        # self.ui.outputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI)
        # self.ui.imageThresholdSliderWidget.connect("valueChanged(double)", self.updateParameterNodeFromGUI)
        # self.ui.invertOutputCheckBox.connect("toggled(bool)", self.updateParameterNodeFromGUI)
        # self.ui.invertedOutputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI)

        # Buttons
        self.ui.applyButton.connect('clicked(bool)', self.onApplyButton)

        # Make sure parameter node is initialized (needed for module reload)
        self.initializeParameterNode()

    def cleanup(self):
        """
        Called when the application closes and the module widget is destroyed.
        """
        self.removeObservers()

    def enter(self):
        """
        Called each time the user opens this module.
        """
        # Make sure parameter node exists and observed
        self.initializeParameterNode()

    def exit(self):
        """
        Called each time the user opens a different module.
        """
        # Do not react to parameter node changes (GUI wlil be updated when the user enters into the module)
        self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)

    def onSceneStartClose(self, caller, event):
        """
        Called just before the scene is closed.
        """
        # Parameter node will be reset, do not use it anymore
        self.setParameterNode(None)

    def onSceneEndClose(self, caller, event):
        """
        Called just after the scene is closed.
        """
        # If this module is shown while the scene is closed then recreate a new parameter node immediately
        if self.parent.isEntered:
            self.initializeParameterNode()

    def initializeParameterNode(self):
        """
        Ensure parameter node exists and observed.
        """
        # Parameter node stores all user choices in parameter values, node selections, etc.
        # so that when the scene is saved and reloaded, these settings are restored.

        self.setParameterNode(self.logic.getParameterNode())

        # Select default input nodes if nothing is selected yet to save a few clicks for the user
        if not self._parameterNode.GetNodeReference("InputVolume"):
            firstVolumeNode = slicer.mrmlScene.GetFirstNodeByClass("vtkMRMLScalarVolumeNode")
            if firstVolumeNode:
                self._parameterNode.SetNodeReferenceID("InputVolume", firstVolumeNode.GetID())

    def setParameterNode(self, inputParameterNode):
        """
        Set and observe parameter node.
        Observation is needed because when the parameter node is changed then the GUI must be updated immediately.
        """

        if inputParameterNode:
            self.logic.setDefaultParameters(inputParameterNode)

        # Unobserve previously selected parameter node and add an observer to the newly selected.
        # Changes of parameter node are observed so that whenever parameters are changed by a script or any other module
        # those are reflected immediately in the GUI.
        if self._parameterNode is not None and self.hasObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode):
            self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)
        self._parameterNode = inputParameterNode
        if self._parameterNode is not None:
            self.addObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)

        # Initial GUI update
        self.updateGUIFromParameterNode()

    def updateGUIFromParameterNode(self, caller=None, event=None):
        """
        This method is called whenever parameter node is changed.
        The module GUI is updated to show the current state of the parameter node.
        """

        if self._parameterNode is None or self._updatingGUIFromParameterNode:
            return

        # Make sure GUI changes do not call updateParameterNodeFromGUI (it could cause infinite loop)
        self._updatingGUIFromParameterNode = True

        # Update node selectors and sliders
        # self.ui.inputSelector.setCurrentNode(self._parameterNode.GetNodeReference("InputVolume"))
        # self.ui.inputFiducial.setCurrentNode(self._parameterNode.GetNodeReference("InputFiducial"))
        # self.ui.outputSelector.setCurrentNode(self._parameterNode.GetNodeReference("OutputVolume"))
        # self.ui.invertedOutputSelector.setCurrentNode(self._parameterNode.GetNodeReference("OutputVolumeInverse"))
        # self.ui.imageThresholdSliderWidget.value = float(self._parameterNode.GetParameter("Threshold"))
        # self.ui.invertOutputCheckBox.checked = (self._parameterNode.GetParameter("Invert") == "true")

        # Update buttons states and tooltips
        # if self._parameterNode.GetNodeReference("InputVolume") and self._parameterNode.GetNodeReference("OutputVolume"):
        #     self.ui.applyButton.toolTip = "Compute output volume"
        #     self.ui.applyButton.enabled = True
        # else:
        #     self.ui.applyButton.toolTip = "Select input and output volume nodes"
        #     self.ui.applyButton.enabled = False

        # All the GUI updates are done
        self._updatingGUIFromParameterNode = False

    def updateParameterNodeFromGUI(self, caller=None, event=None):
        """
        This method is called when the user makes any change in the GUI.
        The changes are saved into the parameter node (so that they are restored when the scene is saved and loaded).
        """

        if self._parameterNode is None or self._updatingGUIFromParameterNode:
            return

        wasModified = self._parameterNode.StartModify()  # Modify all properties in a single batch

        # self._parameterNode.SetNodeReferenceID("InputVolume", self.ui.inputSelector.currentNodeID)
        # self._parameterNode.SetNodeReferenceID("InputFiducial", self.ui.inputFiducial.currentNodeID)
        # self._parameterNode.SetNodeReferenceID("OutputVolume", self.ui.outputSelector.currentNodeID)
        # self._parameterNode.SetParameter("Threshold", str(self.ui.imageThresholdSliderWidget.value))
        # self._parameterNode.SetParameter("Invert", "true" if self.ui.invertOutputCheckBox.checked else "false")
        # self._parameterNode.SetNodeReferenceID("OutputVolumeInverse", self.ui.invertedOutputSelector.currentNodeID)

        self._parameterNode.EndModify(wasModified)

    def onApplyButton(self):
        """
        Run processing when user clicks "Apply" button.
        """
        with slicer.util.tryWithErrorDisplay("Failed to compute results.", waitCursor=True):

            # Compute output
            dataDirectoryPath = self.ui.dataDirectoryPath.directory
            self.logic.process(dataDirectoryPath)#, self.ui.inputSelector.currentNode(), self.ui.inputFiducial.currentNode(), self.ui.outputSelector.currentNode(),
                               #self.ui.imageThresholdSliderWidget.value, self.ui.invertOutputCheckBox.checked)

            # # Compute inverted output (if needed)
            # if self.ui.invertedOutputSelector.currentNode():
            #     # If additional output volume is selected then result with inverted threshold is written there
            #     self.logic.process(self.ui.inputSelector.currentNode(), self.ui.invertedOutputSelector.currentNode(),
            #                        self.ui.imageThresholdSliderWidget.value, not self.ui.invertOutputCheckBox.checked, showResult=False)

#
# SurfaceModelNodesSelectorLogic
#

class SurfaceModelNodesSelectorLogic(ScriptedLoadableModuleLogic):
    """This class should implement all the actual
    computation done by your module.  The interface
    should be such that other python code can import
    this class and make use of the functionality without
    requiring an instance of the Widget.
    Uses ScriptedLoadableModuleLogic base class, available at:
    https://github.com/Slicer/Slicer/blob/main/Base/Python/slicer/ScriptedLoadableModule.py
    """

    def __init__(self):
        """
        Called when the logic class is instantiated. Can be used for initializing member variables.
        """
        ScriptedLoadableModuleLogic.__init__(self)

    def setDefaultParameters(self, parameterNode):
        """
        Initialize parameter node with default settings.
        """
        if not parameterNode.GetParameter("Threshold"):
            parameterNode.SetParameter("Threshold", "100.0")
        if not parameterNode.GetParameter("Invert"):
            parameterNode.SetParameter("Invert", "false")

    def onMarkupEndInteraction(self, caller, event):
        markupsNode = caller
        markupsNodeindex = int(caller.GetAttribute('Markups.MovingMarkupIndex'))
        pos = [0,0,0]
        markupsNode.GetNthControlPointPosition(markupsNodeindex, pos)
        #sliceView = markupsNode.GetAttribute("Markups.MovingInSliceView")
        #movingMarkupIndex = markupsNode.GetDisplayNode().GetActiveControlPoint()
        print(markupsNodeindex)
        print(pos)
        #print(movingMarkupIndex)
        #logging.info("End interaction: point ID = {0}, slice view = {1}".format(movingMarkupIndex, sliceView))

    def process(self, dataDirectoryPath, showResult=True):
        """
        Run the processing algorithm.
        Can be used without GUI widget.
        :param dataDirectoryPath: path to the data directory containing .ply files

        """

        if not dataDirectoryPath:
            raise ValueError("no Data folder selected")

        import time
        startTime = time.time()
        logging.info('Processing started')
        logging.info('Search for .ply files')
        modelDir = dataDirectoryPath
        modelFileExt = "ply"
        modelFiles = list(f for f in os.listdir(modelDir) if f.endswith("."+modelFileExt))
        print(modelFiles)
        import pandas as pd

        #dataframe to store all the ply files name along with index
        df = pd.DataFrame(modelFiles, columns =['FileNames'])
        filepath = dataDirectoryPath+'/models_ids.csv'
        df.to_csv(filepath, index=True)

        idFile = 0
        for idFile in range(idFile,len(df)):
            print(df.iloc[idFile].FileNames)
            markupsNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLMarkupsFiducialNode")
            markupsNode.CreateDefaultDisplayNodes()

            modelFileName =  df.iloc[idFile].FileNames
            modelNode = slicer.util.loadModel(dataDirectoryPath+ "/" + modelFileName)
            size = len(modelFileName)
            modelFileName = modelFileName[:size - 4]
            print(modelFileName)
            markupsNode.SetName(modelFileName)
            print(df.index.get_loc(idFile))

            meshModel = modelNode.GetMesh()
            points = meshModel.GetPoints()
            nPoints = points.GetNumberOfPoints()
            for i in range(nPoints):
                p = points.GetPoint(i)
                markupsNode.AddControlPoint(p[0],p[1],p[2])
                markupsNode.SetNthControlPointLocked(i, True)

            d = markupsNode.GetDisplayNode()
            d.PointLabelsVisibilityOff()
            #saving the markup point and cleaning the scene
            slicer.util.saveNode(markupsNode, os.path.join(dataDirectoryPath, modelFileName+".mrk.json"))
            slicer.mrmlScene.Clear(0)

        stopTime = time.time()
        logging.info(f'Processing completed in {stopTime-startTime:.2f} seconds')

#
# SurfaceModelNodesSelectorTest
#

class SurfaceModelNodesSelectorTest(ScriptedLoadableModuleTest):
    """
    This is the test case for your scripted module.
    Uses ScriptedLoadableModuleTest base class, available at:
    https://github.com/Slicer/Slicer/blob/main/Base/Python/slicer/ScriptedLoadableModule.py
    """

    def setUp(self):
        """ Do whatever is needed to reset the state - typically a scene clear will be enough.
        """
        slicer.mrmlScene.Clear()

    def runTest(self):
        """Run as few or as many tests as needed here.
        """
        self.setUp()
        self.test_SurfaceModelNodesSelector1()

    def test_SurfaceModelNodesSelector1(self):
        """ Ideally you should have several levels of tests.  At the lowest level
        tests should exercise the functionality of the logic with different inputs
        (both valid and invalid).  At higher levels your tests should emulate the
        way the user would interact with your code and confirm that it still works
        the way you intended.
        One of the most important features of the tests is that it should alert other
        developers when their changes will have an impact on the behavior of your
        module.  For example, if a developer removes a feature that you depend on,
        your test should break so they know that the feature is needed.
        """

        self.delayDisplay("Starting the test")

        # Get/create input data

        import SampleData
        registerSampleData()
        inputVolume = SampleData.downloadSample('SurfaceModelNodesSelector1')
        self.delayDisplay('Loaded test data set')

        inputScalarRange = inputVolume.GetImageData().GetScalarRange()
        self.assertEqual(inputScalarRange[0], 0)
        self.assertEqual(inputScalarRange[1], 695)

        outputVolume = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLScalarVolumeNode")
        threshold = 100

        # Test the module logic

        logic = SurfaceModelNodesSelectorLogic()

        # Test algorithm with non-inverted threshold
        logic.process(inputVolume, outputVolume, threshold, True)
        outputScalarRange = outputVolume.GetImageData().GetScalarRange()
        self.assertEqual(outputScalarRange[0], inputScalarRange[0])
        self.assertEqual(outputScalarRange[1], threshold)

        # Test algorithm with inverted threshold
        logic.process(inputVolume, outputVolume, threshold, False)
        outputScalarRange = outputVolume.GetImageData().GetScalarRange()
        self.assertEqual(outputScalarRange[0], inputScalarRange[0])
        self.assertEqual(outputScalarRange[1], inputScalarRange[1])

        self.delayDisplay('Test passed')