from pathlib import Path

import numpy as np
import pytest
from numpy.testing import assert_allclose, assert_array_equal

import mne
from mne import (
    get_volume_labels_from_aseg,
    head_to_mni,
    read_freesurfer_lut,
    read_talxfm,
    vertex_to_mni,
)
from mne._freesurfer import (
    _check_subject_dir,
    _estimate_talxfm_rigid,
    _get_mgz_header,
    read_lta,
)
from mne.datasets import testing
from mne.transforms import _angle_between_quats, _get_trans, apply_trans, rot_to_quat

data_path = testing.data_path(download=False)
subjects_dir = data_path / "subjects"
fname_mri = data_path / "subjects" / "sample" / "mri" / "T1.mgz"
aseg_fname = data_path / "subjects" / "sample" / "mri" / "aseg.mgz"
trans_fname = data_path / "MEG" / "sample" / "sample_audvis_trunc-trans.fif"
rng = np.random.RandomState(0)

@testing.requires_testing_data
def test_check_subject_dir():
    """Test checking for a Freesurfer recon-all subject directory."""
    _check_subject_dir("sample", subjects_dir)
    with pytest.raises(ValueError, match="subject folder is incorrect"):
        _check_subject_dir("foo", data_path)

@testing.requires_testing_data
def test_mgz_header():
    """Test MGZ header reading."""
    nib = pytest.importorskip("nibabel")
    header = _get_mgz_header(fname_mri)
    mri_hdr = nib.load(fname_mri).header
    assert_allclose(mri_hdr.get_data_shape(), header["dims"])
    assert_allclose(mri_hdr.get_vox2ras_tkr(), header["vox2ras_tkr"])
    assert_allclose(mri_hdr.get_ras2vox(), np.linalg.inv(header["vox2ras"]))

@testing.requires_testing_data
def test_vertex_to_mni():
    """Test conversion of vertices to MNI coordinates."""
    pytest.importorskip("nibabel")
    # obtained using "tksurfer (sample) (l/r)h white"
    vertices = [100960, 7620, 150549, 96761]
    coords = np.array(
        [
            [-60.86, -11.18, -3.19],
            [-36.46, -93.18, -2.36],
            [-38.00, 50.08, -10.61],
            [47.14, 8.01, 46.93],
        ]
    )
    hemis = [0, 0, 0, 1]
    coords_2 = vertex_to_mni(vertices, hemis, "sample", subjects_dir)
    # less than 1mm error
    assert_allclose(coords, coords_2, atol=1.0)

@testing.requires_testing_data
def test_head_to_mni():
    """Test conversion of aseg vertices to MNI coordinates."""
    # obtained using freeview
    coords = (
        np.array(
            [
                [22.52, 11.24, 17.72],
                [22.52, 5.46, 21.58],
                [16.10, 5.46, 22.23],
                [21.24, 8.36, 22.23],
            ]
        )
        / 1000.0
    )

    xfm = read_talxfm("sample", subjects_dir)
    coords_MNI = apply_trans(xfm["trans"], coords) * 1000.0

    mri_head_t, _ = _get_trans(trans_fname, "mri", "head", allow_none=False)

    # obtained from sample_audvis-meg-oct-6-mixed-fwd.fif
    coo_right_amygdala = np.array(
        [
            [0.01745682, 0.02665809, 0.03281873],
            [0.01014125, 0.02496262, 0.04233755],
            [0.01713642, 0.02505193, 0.04258181],
            [0.01720631, 0.03073877, 0.03850075],
        ]
    )
    coords_MNI_2 = head_to_mni(coo_right_amygdala, "sample", mri_head_t, subjects_dir)
    # less than 1mm error
    assert_allclose(coords_MNI, coords_MNI_2, atol=10.0)

@testing.requires_testing_data
def test_vertex_to_mni_fs_nibabel(monkeypatch):
    """Test equivalence of vert_to_mni for nibabel and freesurfer."""
    pytest.importorskip("nibabel")
    n_check = 1000
    subject = "sample"
    vertices = rng.randint(0, 100000, n_check)
    hemis = rng.randint(0, 1, n_check)
    coords = vertex_to_mni(vertices, hemis, subject, subjects_dir)
    read_mri = mne._freesurfer._read_mri_info
    monkeypatch.setattr(
        mne._freesurfer,
        "_read_mri_info",
        lambda *args, **kwargs: read_mri(*args, use_nibabel=True, **kwargs),
    )
    coords_2 = vertex_to_mni(vertices, hemis, subject, subjects_dir)
    # less than 0.1 mm error
    assert_allclose(coords, coords_2, atol=0.1)

def test_read_lta(tmp_path):
    """Test reading a Freesurfer linear transform array file."""
    with open(tmp_path / "test.lta", "w") as fid:
        fid.write(
            """type      = 0 # LINEAR_VOX_TO_VOX
                     nxforms   = 1
                     mean      = 0.0000 0.0000 0.0000
                     sigma     = 1.0000
                     1 4 4
                     0.99221027 -0.05494503  0.11180324 -3.84350586
                     0.05233596  0.99828744 0.02614108 -9.77523804
                     -0.11304809 -0.02008611 0.99338663 15.25457001
                     0 0 0 1
                     src volume info
                     valid = 1  # volume info valid
                     filename = tmp.mgz
                     volume = 256 256 256
                     voxelsize = 1 1 1
                     xras   = -1 0 0
                     yras   = 0 0 -1
                     zras   = 0 1 0
                     cras   = -1.19374 -3.31686 3.25835
                     dst volume info
                     valid = 1  # volume info valid
                     filename = tmp.mgz
                     volume = 256 256 256
                     voxelsize = 1 1 1
                     xras   = -1 0 0
                     yras   = 0 0 -1
                     zras   = 0 1 0
                     cras   = -1.19374 -3.31686 3.25835"""
        )
    assert_array_equal(
        read_lta(tmp_path / "test.lta"),
        np.array(
            [
                [0.99221027, -0.05494503, 0.11180324, -3.84350586],
                [0.05233596, 0.99828744, 0.02614108, -9.77523804],
                [-0.11304809, -0.02008611, 0.99338663, 15.25457001],
                [0.0, 0.0, 0.0, 1.0],
            ]
        ),
    )

    # test when dst volume != src_volume
    with open(tmp_path / "test2.lta", "w") as fid:
        fid.write(
            """type      = 0 # LINEAR_VOX_TO_VOX
                     nxforms   = 1
                     mean      = 0.0000 0.0000 0.0000
                     sigma     = 1.0000
                     1 4 4
                     0.41397345  -0.02919456  -0.00069703  26.37020874
                     -0.02894894 -0.40985453  -0.06119149 212.38204956
                     0.00361269   0.0611503   -0.41046342 203.33338928
                     0 0 0 1
                     src volume info
                     valid = 1  # volume info valid
                     filename = tmp2.mgz
                     volume = 512 385 512
                     voxelsize = 0.41499999 0.41541821 0.41499999
                     xras   = -1 0 0
                     yras   = 0 0 1
                     zras   = 0 -1 0
                     cras   = -106.23999786 105.82500458 -79.55259705
                     dst volume info
                     valid = 1  # volume info valid
                     filename = tmp.mgz
                     volume = 256 256 256
                     voxelsize = 1 1 1
                     xras   = -1 0 0
                     yras   = 0 0 -1
                     zras   = 0 1 0
                     cras   = -3.68961334 -0.12011719 3.4160614"""
        )
    assert_allclose(
        read_lta(tmp_path / "test2.lta"),
        np.array(
            [
                [0.99752641, -0.07034834, -0.00167959, -236.00043542],
                [0.06968626, 0.98660704, 0.14730093, 189.09766694],
                [-0.00870528, -0.14735012, 0.98906851, 329.7632126],
                [0.0, 0.0, 0.0, 1.0],
            ]
        ),
        atol=1e-8,
    )

@testing.requires_testing_data
@pytest.mark.parametrize(
    "fname",
    [
        None,
        Path(mne.__file__).parent / "data" / "FreeSurferColorLUT.txt",
    ],
)
def test_read_freesurfer_lut(fname, tmp_path):
    """Test reading volume label names."""
    pytest.importorskip("nibabel")
    atlas_ids, colors = read_freesurfer_lut(fname)
    assert list(atlas_ids).count("Brain-Stem") == 1
    assert len(colors) == len(atlas_ids) == 1266
    label_names, label_colors = get_volume_labels_from_aseg(
        aseg_fname, return_colors=True
    )
    assert isinstance(label_names, list)
    assert isinstance(label_colors, list)
    assert label_names.count("Brain-Stem") == 1
    for c in label_colors:
        assert isinstance(c, np.ndarray)
        assert c.shape == (4,)
    assert len(label_names) == len(label_colors) == 46
    with pytest.raises(ValueError, match="must be False"):
        get_volume_labels_from_aseg(aseg_fname, return_colors=True, atlas_ids=atlas_ids)
    label_names_2 = get_volume_labels_from_aseg(aseg_fname, atlas_ids=atlas_ids)
    assert label_names == label_names_2
    # long name (only test on one run)
    if fname is not None:
        return
    fname = tmp_path / "long.txt"
    names = [
        "Anterior_Cingulate_and_Medial_Prefrontal_Cortex-" + hemi
        for hemi in ("lh", "rh")
    ]
    ids = np.arange(1, len(names) + 1)
    colors = [(id_,) * 4 for id_ in ids]
    with open(fname, "w") as fid:
        for name, id_, color in zip(names, ids, colors):
            out_color = " ".join("%3d" % x for x in color)
            line = "%d    %s %s\n" % (id_, name, out_color)
            fid.write(line)
    lut, got_colors = read_freesurfer_lut(fname)
    assert len(lut) == len(got_colors) == len(names) == len(ids)
    for name, id_, color in zip(names, ids, colors):
        assert name in lut
        assert name in got_colors
        assert_array_equal(got_colors[name][:3], color[:3])
        assert lut[name] == id_
    with open(fname, "w") as fid:
        for name, id_, color in zip(names, ids, colors):
            out_color = " ".join("%3d" % x for x in color[:3])  # wrong length!
            line = "%d    %s %s\n" % (id_, name, out_color)
            fid.write(line)
    with pytest.raises(RuntimeError, match="formatted"):
        read_freesurfer_lut(fname)

@testing.requires_testing_data
def test_talxfm_rigid():
    """Test that talxfm_rigid gives reasonable results."""
    rigid = _estimate_talxfm_rigid("fsaverage", subjects_dir=subjects_dir)
    assert_allclose(rigid, np.eye(4), atol=1e-6)
    rigid = _estimate_talxfm_rigid("sample", subjects_dir=subjects_dir)
    assert_allclose(np.linalg.norm(rigid[:3, :3], axis=1), 1.0, atol=1e-6)
    move = 1000 * np.linalg.norm(rigid[:3, 3])
    assert 30 < move < 70
    ang = np.rad2deg(_angle_between_quats(rot_to_quat(rigid[:3, :3])))
    assert 20 < ang < 25


from lxml import etree

from utils_main import chrome_api

def get_personal_address(driver):
    """
    获取收货人，收货地区，收货详细地址，邮编，电话，是否为默认地址
    :param driver:
    :return: address_list
    """
    personal_address_href = chrome_api.get_element_href(driver, "#newDeliverAddress > a")
    driver.get(personal_address_href)
    address_list = []
    html_str = driver.page_source.encode("utf-8").decode()
    html = etree.HTML(html_str)
    add_list_ele = html.xpath("//tbody[@class='next-table-body']/tr")
    for addr_ele in add_list_ele:
        address_dict = {}
        receiver_name = addr_ele.xpath("./td[1]/div/text()")
        if len(receiver_name) > 0:
            address_dict["receiver_name"] = receiver_name[0]
        else:
            address_dict["receiver_name"] = ""
        area = addr_ele.xpath("./td[2]//span/text()")
        if len(area) > 0:
            address_dict["area"] = area[0]
        else:
            address_dict["area"] = ""
        address = addr_ele.xpath("./td[3]/div/text()")
        if len(address) > 0:
            address_dict["address"] = address[0]
        else:
            address_dict["address"] = ""
        zip_code = addr_ele.xpath("./td[4]/div/text()")
        if len(zip_code) > 0:
            address_dict["zip_code"] = zip_code[0]
        else:
            address_dict["zip_code"] = ""
        phone = addr_ele.xpath("./td[5]//span/text()")
        if len(phone) > 0:
            address_dict["phone"] = phone[0]
        else:
            address_dict["phone"] = ""
        is_addr_default = addr_ele.xpath("./td[7]//span/text()")
        if len(is_addr_default) > 0:
            is_addr_default = is_addr_default[0]
            if is_addr_default == "默认地址":
                address_dict["is_default_address"] = "是默认地址"
            else:
                address_dict["is_default_address"] = "不是默认地址"
        else:
            address_dict["is_default_address"] = ""
        address_list.append(address_dict)
    return address_list


#UVa: 1112 - Mice and Maze
from heapq import heappop,heappush
from sys import stdin

inf = float('inf')

def dijkstra():
	ans = inf
	visited = [False for _ in range(n)]
	dist = [inf for _ in range(n)]
	queue,dist[src] = [(0,src)],0

	while len(queue):
		d,u = heappop(queue)
		if visited[u]==False:
			visited[u] = True
			for v,w in G[u]:
				tmpd = d+w
				if visited[v]==False and dist[v]>tmpd:
					dist[v] = tmpd
					heappush(queue,(tmpd,v))

	return dist

def main():
	global G,n,src
	cases = int(stdin.readline())
	for i in range(cases):
		empty = stdin.readline()
		n = int(stdin.readline())
		G = [[] for _ in range(n)]
		src = int(stdin.readline())-1
		T = int(stdin.readline())
		M = int(stdin.readline())
		for _ in range(M):
			a,b,w = map(int,stdin.readline().split())
			if a!=b:
				G[b-1].append((a-1,w))

		mices = dijkstra()
		ans = 0
		for mice in mices:
			if mice<=T: ans += 1
		print(ans)
		#print(mices,T)
		if i<cases-1: print()

main()


def prime_list(n):
    # 에라토스테네스의 체 초기화: n개 요소에 True 설정(소수로 간주)
    sieve = [True] * n

    m = int(n ** 0.5)
    for i in range(2, m + 1):
        if sieve[i] == True:           # i가 소수인 경우
            for j in range(i+i, n, i): # i이후 i의 배수들을 False 판정
                sieve[j] = False

    # 소수 목록 산출
    return [i for i in range(2, n) if sieve[i] == True]


C = int(input())
for tc in range(1, C+1):
    info = list(map(int, input().split()))

    scores = sum(info[1:])
    average = scores // info[0]

    cnt = 0  # 평균 넘는 학생 수
    for i in range(1, len(info)):
        if info[i] > average:
            cnt += 1

    print('{:.3f}%'.format(cnt / info[0] * 100))

백준/Bronze/4344. 평균은 넘겠지/평균은 넘겠지.py


import cv2
import argparse

arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(arg_parser.parse_args())

# load the image and show it
img = cv2.imread(args["image"])
cv2.imshow("Original", img)
cv2.waitKey(0)

# flip the image horizontally
flipped = cv2.flip(img, 1)
cv2.imshow("Flipped horizontally", flipped)
cv2.waitKey(0)

# flip the image vertically
flipped = cv2.flip(img, 0)
cv2.imshow("Flipped vertically", flipped)
cv2.waitKey(0)


sue = float(input("Ingrese el sueldo mensual: "))

if sue <= 472:
    impuesto = 0
    cuota_fij = 0
elif sue <= 895.24:
    exceso = sue - 472
    impuesto = exceso * 0.1
    cuota_fij = 17.67
elif sue <= 2038.10:
    exceso = sue - 895.24
    impuesto = 42.53 + (exceso * 0.2)
    cuota_fij = 60
else:
    exceso = sue - 2038.10
    impuesto = 352.28 + (exceso * 0.3)
    cuota_fij = 288.57

iss = sue * 0.03
afp = sue * 0.0725
total_descuentos = iss + afp + impuesto + cuota_fij
suel_neto = sue - total_descuentos

print("Sueldo bruto: ${:.2f}".format(sue))
print("Impuesto sobre la renta: ${:.2f}".format(impuesto))
print("ISS: ${:.2f}".format(iss))
print("AFP: ${:.2f}".format(afp))
print("Cuota fija: ${:.2f}".format(cuota_fij))
print("Total descuentos: ${:.2f}".format(total_descuentos))
print("Sueldo neto: ${:.2f}".format(suel_neto))


# Operations on Tensors: Session 1
# 1. Arithmetic operations (explain broadcasting: row/column, and single-element tensors)
# torch.ops(t1, t2, t_out:optional), t1.ops(t2): element-wise/scalar/broadcasting
import torch

x = torch.tensor([[1, 2, 3],
                  [4, 5, 6]])
y = torch.tensor([[7, 8, 9],
                  [10, 11, 12]])

# torch.ops(t1, t2)
z = torch.add(x, y)
print(z)
z = torch.Tensor()

# torch.ops(t1, t2, out=t3)
torch.add(x, y, out=z)
print(z)

# t1.ops(t2)
z = x.add(y)
print(z)

# scalar
z = x.add(2)
print(z)

# row broadcasting
tensor = torch.tensor([1, 2, 3])
z = x.add(tensor)
print(z)

# column broadcasting
tensor = torch.tensor([[1],
                       [2]])
z = x.add(tensor)
print(z)

# Singleton out
m = torch.max(x)
print(m.item())

# 2. In-place operations
# t1.ops_(t2): element-wise/scalar/broadcasting
z = x.add_(y)
print(z)
print(x)
print(x == z)

# 3. Joining tensors
x = torch.tensor([[1, 2, 3],
                  [4, 5, 6]])
y = torch.tensor([[7, 8, 9],
                  [10, 11, 12]])
# In default dim=0
z = torch.cat([x, y])
print(z)
# In specified dim
z = torch.cat([x, y], dim=1)
print(z)


import os
from typing import Dict, Any

from common.consts import CONF_FILE_FOLDER_NAME

_conf_paths = (f'../{CONF_FILE_FOLDER_NAME}',
               f'/etc/{APP_NAME}',
               os.path.abspath(os.path.join(os.path.dirname(__file__), '../', __FOLDER_NAME__)),
               os.path.abspath(os.path.join(os.path.dirname(__file__), '../..', __FOLDER_NAME__)))

def _load():
    cnf: Dict[str, Any] = {k: v for k, v in os.environ.items()}

    for k, v in iter(os.environ.items()):
        cnf[k] = v
    env_dir = os.getenv('SDCC_HOME', os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))
    env_file = os.path.join(env_dir, '.env')
    if os.path.isfile(env_file):
        for k, v in dotenv_values(env_file).items():
            cnf[k] = v
    return cnf

_cnf = _load()


# -*- coding: utf-8 -*-
"""
Created on Thu Apr 11 11:25:26 2019

@author: YJH
"""

# -*- coding: utf-8 -*-
"""
Created on Thu Mar 21 10:46:34 2019
简单爬虫————request+beautifulsoup
@author: YJH
"""
import requests
from bs4 import BeautifulSoup
#获取指定url的超文本
def getHtml(url):
    '''
    url:需要爬数据的网络地址
    '''
    headers = {                            #加个请求头伪装浏览器
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
    }
    try:
        r = requests.get(url, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        print('success')
        return r.text
    except:
        print('false')
        return 'false'

#解析超文本，提取所需数据
def getInfo(html):
    '''
    html:待解析的
    '''
    unifo=[]#存放提取的数据，用于返回数据
    soup = BeautifulSoup(html, 'lxml')
    lis = soup.find_all('li', {"class":"gl-item"})
    print(len(lis))
    for i in range(len(lis)):
        try:
            # 获取商品信息 div 中的第一个 a 标签， 获取 title 属性值
            title = lis[i].a['title']
            # print(title)
            # 获取商品的价格信息
            price = lis[i].find('div', class_='p-price').i.string
            # print(price)
            unifo.append([title, price])
        except:
            print('')
    return unifo

# 显示数据
def displayHtmlGoods(goods_data):
    std = r'{0:^100}{1:^8}'
    print(std.format('商品名称', '价格'))
    with open('data.txt','w') as f:    #设置文件对象
        for i in range(len(goods_data)):
            f.write(std.format(goods_data[i][0], goods_data[i][1])+"\n")                 #将字符串写入文件中
            print(std.format(goods_data[i][0], goods_data[i][1]))

def main():

    url_basic = 'https://search.jd.com/Search?keyword='
    total_pages = 1 # 需要爬取的总页数
    keyword = '电脑' # 关键字

    for i in range(total_pages):
        page = 1 + i * 2
        url = url_basic + keyword + '&enc=utf-8&wq=' + keyword + '&page=' + str(page)
        print(url)
        html = getHtml(url)
        MyInfo=getInfo(html)

    displayHtmlGoods(MyInfo)

main()


def func (string,string2,lista):
    quico = 0
    while (quico < len(lista)):
        if lista[quico] == string:
            print(f"Encontrou '{lista[quico].upper()}' na posição {quico} da lista")

        elif lista[quico] == string2:
            print(f"Encontrou '{lista[quico].upper()}' na posição {quico} da lista")

        elif lista[quico] != string:
            print(f"Não encontrado na posição {quico} da lista")

        quico += 1

lista = ["oi","tchau","feliz","natal"]
string = input("Entre com a string")
string2 = input("Entre com a string")

func(string,string2,lista)


import duckdb
from pandas import DataFrame
import pytest

class TestInsertInto(object):
    def test_insert_into_schema(self, duckdb_cursor):
        # open connection
        con = duckdb.connect()
        con.execute('CREATE SCHEMA s')
        con.execute('CREATE TABLE s.t (id INTEGER PRIMARY KEY)')

        # make relation
        df = DataFrame([1], columns=['id'])
        rel = con.from_df(df)

        rel.insert_into('s.t')

        assert con.execute("select * from s.t").fetchall() == [(1,)]

        # This should fail since this will go to default schema
        with pytest.raises(duckdb.CatalogException):
            rel.insert_into('t')

        # If we add t in the default schema it should work.
        con.execute('CREATE TABLE t (id INTEGER PRIMARY KEY)')
        rel.insert_into('t')
        assert con.execute("select * from t").fetchall() == [(1,)]


# Menue
from __future__ import print_function, unicode_literals
import subprocess
from PyInquirer import style_from_dict, Token, prompt, Separator
from pprint import pprint
# end
import boto3
import argparse
import configparser
import os
import json
import botocore.exceptions
from datetime import datetime

style = style_from_dict({
    Token.Separator: '#cc5454',
    Token.QuestionMark: '#673ab7 bold',
    Token.Selected: '#cc5454',  # default
    Token.Pointer: '#673ab7 bold',
    Token.Instruction: '',  # default
    Token.Answer: '#f44336 bold',
    Token.Question: '',
})

config_file = 'config/config.json'

def readConfig():
    global local_config
    try:
        with open(config_file, 'r') as f:
            local_config = json.load(f)

    except Exception as ex:
        print('Error reading configuration file')
        exit()

def setConfigParameter(parameterInput, description):
    if parameterInput == None:
        return
    global local_config
    questions = [
        {
            'type': 'input',
            'name': parameterInput,
            'message': description,
        }
    ]

    answers = prompt(questions, style=style)
    local_config[parameterInput] = answers.get(
        parameterInput)

    with open(config_file, 'w') as f:
        json.dump(local_config, f)

def initialConfig():
    if local_config.get('budget_notification_mail', '') == ('' or None):

        print('No notification mail set.')
        setConfigParameter('budget_notification_mail',
                           'What is your notification mail address?')

    print('Mail adress set to: {}'.format(
        local_config.get('budget_notification_mail', '')))

version = "Gin"
client = boto3.client('securityhub')
costs = boto3.client('ce')
budget = boto3.client('budgets')
sts = boto3.client('sts')
# SecurityHub
awsbuddy_budget = "AWSBuddy_Default"
awsbuddy_budget_fc = "AWSBuddy_Forcast"
local_config = {}
try:
    account_id = sts.get_caller_identity()["Account"]
except Exception as ex:
    print('Error: Please set your credentials first.')
    exit()
# Check if budget exist
# yes
# do nothig
# no
# ask for budget
# display menu 100; 200; 500; 1000
# create budget
# check subscriber

def deployMonitoring():
    bashCommand = 'cd building_blocks/buckwatch/;npm run build;cdk deploy buckwatch-stack'
    process = subprocess.Popen(
        bashCommand, stdout=subprocess.PIPE, shell=True)
    output, error = process.communicate()

    print(output)
    print(error)

def destroyMonitoring():
    bashCommand = 'cd building_blocks/buckwatch/;npm run build;cdk destroy buckwatch-stack --force'
    process = subprocess.Popen(
        bashCommand, stdout=subprocess.PIPE, shell=True)
    output, error = process.communicate()

    print(output)
    print(error)

def checkBudget(budgetName):

    try:
        print("Checking budget ....")
        response = budget.describe_budget(
            AccountId=account_id,
            BudgetName=budgetName
        )
        print('{} Budget has been setup'.format(u'\u2713'))
        return True
    except budget.exceptions.NotFoundException:
        print("Budget not setup... ")
    return False

def getCosts(start, end):
    response = costs.get_cost_and_usage(
        TimePeriod={
            'Start': start,
            'End': end
        },
        Granularity='MONTHLY',
        Metrics=[
            "BlendedCost", "UnblendedCost", "UsageQuantity",
        ]
    )
    total = 0
    for month in response['ResultsByTime']:
        monthTotal = round(float(month['Total']['BlendedCost']['Amount']), 0)
        total += monthTotal

    return (total)

def DisplayCosts():
    _month = getCosts(
        '{}-01'.format(datetime.today().strftime("%Y-%m")),
        '{}'.format(datetime.today().strftime("%Y-%m-%d"))
    )
    _total = getCosts(
        '{}-01-01'.format(datetime.today().strftime("%Y")),
        '{}'.format(datetime.today().strftime("%Y-%m-%d"))
    )
    print('The ressources in {} for this month are {} USD and {} USD total this year.'.format(
        account_id, _month, _total))

def checkSecurityHub():
    try:
        response = client.describe_hub()
        secHubArn = (response["HubArn"])

        print("Security Hub is enabled! Yess")

    except client.exceptions.InvalidAccessException:
        print("Security Hub is not enabled... oO")

def enableSecuHub():
    enableSecHub()

def enableSecHub():
    try:
        print("Enabling SecurityHub ....")
        response = client.enable_security_hub(
            Tags={
                'AWSBuddy': version
            },
            EnableDefaultStandards=False
        )
    except client.exceptions.AccessDeniedException:
        print("Cannot enable SecurityHub - check your permissions... ")

Config = configparser.ConfigParser()
Config.read(os.path.expanduser('~/.aws/credentials'))

sections = Config.sections()
# for profile in sections:
# print(profile)

def get_budget_options(answers):
    options = ['50', '100', '200', '300']
    return options

def draw_budget():
    questions = [

        {
            'type': 'list',
            'name': 'Budget',
            'message': 'Budget Setup',
            'choices': get_budget_options,
            'validate': lambda answer: 'You must choose at least one Budget.'
            if len(answer) == 0 else True
        },
        {
            'type': 'list',
            'message': 'Select Notification Option',
            'name': 'Notification',
            'choices': [
                {
                    'name': 'yes'
                },
                {
                    'name': 'no'
                },

            ],
            'validate': lambda answer: 'You must choose at least one Budget.'
            if len(answer) == 0 else True
        },
    ]

    answers = prompt(questions, style=style)
    pprint(answers)

def get_menu_options(answers):
    options = ['Budget', 'Costs', 'Security',
               'Deploy', 'Destroy', 'CreateBudget', 'DeleteBudget', 'About', 'Settings', 'Exit']
    return options

def draw_intro():
    print('\n\n\nAWS Buddy 2020 Version: {}'.format(version))
    print('Copyright ZERODOTFIVE UG')
    print('Please contribute: {}\n'.format(
        'https://github.com/ZDF-UG/awsbuddy'))

def get_menu_settings(answers):
    options = ['Change notification mail']
    return options

def draw_settings():
    questions = [

        {
            'type': 'list',
            'name': 'Option',
            'message': 'Settings:',
            'choices': get_menu_settings,
            'validate': lambda answer: 'You must choose at least one Option.'
            if len(answer) == 0 else True
        },
    ]

    answers = prompt(questions, style=style)
    # pprint(answers)

    if answers['Option'] == 'Change notification mail':
        setConfigParameter('budget_notification_mail',
                           'What is your notification mail address?')
        draw_main()

def deleteBudget(budgetName):
    try:
        print("ECreating Budget {} ....".format(budgetName))
        response = budget.delete_budget(
            AccountId=account_id,
            BudgetName=budgetName
        )
    except budget.exceptions.NotFoundException:
        print("Budget {} not found.".format(budgetName))

def createBudget(budget_name, budget_amount, notification_type, mail, threshold_percent):
    try:
        response = budget.create_budget(
            AccountId=account_id,
            Budget={
                'BudgetName': budget_name,
                'BudgetLimit': {
                    'Amount': budget_amount,
                    'Unit': 'USD'
                },
                'CostTypes': {
                    'IncludeTax': True,
                    'IncludeSubscription': True,
                    'UseBlended': True,
                    'IncludeRefund': True,
                    'IncludeCredit': True,
                    'IncludeUpfront': True,
                    'IncludeRecurring': True,
                    'IncludeOtherSubscription': True,
                    'IncludeSupport': True,
                    'IncludeDiscount': False,
                    'UseAmortized': False
                },
                'TimeUnit': 'MONTHLY',
                'BudgetType': 'COST'
            },
            NotificationsWithSubscribers=[
                {
                    'Notification': {
                        'NotificationType': notification_type,
                        'ComparisonOperator': 'GREATER_THAN',
                        'Threshold': threshold_percent,
                        'ThresholdType': 'PERCENTAGE'
                    },
                    'Subscribers': [
                        {
                            'SubscriptionType': 'EMAIL',
                            'Address': mail
                        },
                    ]
                },
            ]
        )
    except budget.exceptions.DuplicateRecordException:
        print("Budget {} does already exist.".format(budget_name))

def draw_main():

    questions = [

        {
            'type': 'list',
            'name': 'Option',
            'message': 'This is the main menu. Please choose one of the following actions:',
            'choices': get_menu_options,
            'validate': lambda answer: 'You must choose at least one Option.'
            if len(answer) == 0 else True
        },
    ]

    answers = prompt(questions, style=style)
    # pprint(answers)

    if answers['Option'] == 'Budget':
        checkBudget(awsbuddy_budget)
        draw_budget()
    if answers['Option'] == 'Costs':
        DisplayCosts()
    if answers['Option'] == 'DeleteBudget':
        deleteBudget(awsbuddy_budget)
        deleteBudget(awsbuddy_budget_fc)

    if answers['Option'] == 'CreateBudget':
        createBudget(awsbuddy_budget_fc, "100",
                     'FORECASTED', 'ayoub@umoru.de', 80)
        createBudget(awsbuddy_budget, "100", 'ACTUAL', 'ayoub@umoru.de', 80)

    if answers['Option'] == 'Security':
        checkSecurityHub()
    if answers['Option'] == 'Exit':
        return 0
    if answers['Option'] == 'About':
        draw_intro()
    if answers['Option'] == 'Settings':
        draw_settings()
    if answers['Option'] == 'Deploy':
        deployMonitoring()
    if answers['Option'] == 'Destroy':
        destroyMonitoring()
    draw_main()

readConfig()
initialConfig()
draw_intro()
draw_main()


import matplotlib.pyplot as plt
import numpy as np
from sklearn.manifold import TSNE

def to_img(x, sep=False):
    """
    convert a n-by-T-by-F segment spectrograms to a 2d image
    Args:
        x(np.ndarray): n-by-T-by-F segment spectrograms
        sep(bool): add separators between segments if True
    """
    n = 1
    T, F = x.shape
    if sep:
        min_val = np.min(x)
        sep = np.ones((n, 1, F)) * min_val
        x = np.concatenate([x, sep], axis=1)
        T += 1
    return x.reshape((n * T, F)).transpose()

def plot(x_val, output_dir, img="result", epoch=1, n_segs=8, clim=(-2., 2.)):

    nrows = len(x_val)

    for i in range(n_segs):
        fig = plt.figure(figsize=(6, 6))
        x_2d = to_img(x_val[i], sep=False)
        im = plt.imshow(x_2d, interpolation="none", origin="lower")
        im.set_clim(*clim)
        #fig.subplots_adjust(hspace=0.2)
        plt.savefig(output_dir + "/" + img + "_Epoch_" + str(epoch) + "_seg_"+ str(i+1) +".png")
        plt.close(fig)
    #plt.show()

def plot_latent_space(latent, out_dir, epoch, name="Train"):
    N = latent.shape[1]
    labels = np.random.randint(N, size=latent.shape[0])
    latent_embedded = TSNE(n_components=2).fit_transform(latent)

    fig = plt.figure(figsize=(8, 6))
    plt.scatter( latent_embedded[:, 0], latent_embedded[:, 1],
                                                           c=labels, marker='o', edgecolor='none')
    plt.colorbar(ticks=range(N))
    plt.grid(True)
    plt.savefig(out_dir + "/latent_space_"+ name + "_" +str(epoch) +".png")
    plt.close(fig)
    #plt.show()


#!/usr/bin/python3

import jwt
import os
import sys
import requests
import json
import logging
import base64
import tempfile
import argparse
from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend

from configuration import Configuration
from db import Database
from ur import UsageRecord, parse_usage_record

def lookup_service_url(name):
    endpoints = json.load(open(config.get('services')))
    return endpoints[name]["endpoint"]

def lookup_service_pubkey(name):
    endpoints = json.load(open(config.get('services')))
    cert = endpoints[name]["cert"]
    cert_obj = load_pem_x509_certificate(cert.encode('ascii'), default_backend())
    return(cert_obj.public_key())

def extract_usage_records(token, service):
    signer = lookup_service_pubkey(service)
    msg = jwt.decode(token, signer, algorithms='RS256')

    if msg["status"] != "success":
        error = msg["error"] if "error" in msg else "Unknown error"
        logging.error("Server failed to return the record (%s)", error)
        raise Exception("Server failed to return the record (%s)", error)

    usage_records = list()
    for ur in msg["data"]:
        usage_records.append(parse_usage_record(ur))

    return usage_records

def get_usage_records(service):
    cert = config.get("cert")
    key = config.get("key")
    if cert is None or key is None:
        logging.error("The configuration doesn't specify authentication certificate or private key")
        raise Exception("Both cert and key must be specified")

    verify = config.get("cadir") if config.get("cadir") is not None else True

    url = lookup_service_url(service)

    requests_logger = logging.getLogger("urllib3")
    requests_logger.setLevel(logging.ERROR)
    response = requests.get(url, verify=verify, cert=(cert, key))

    if response.status_code != 200:
        logging.error("Failed to get response from %s: (%d: %s)" %
            (url, response.status_code, response.reason))
        raise Exception("Failed to get HTTP response")

    token = response.text.rstrip(os.linesep)
    return (extract_usage_records(token, service))

def store_usage_records(usage_records):
    db = Database()
    for ur in usage_records:
        db.store_ur(ur)

def parse_args():
    parser = argparse.ArgumentParser(
            description="Obtain a set of usage records from a service")
    parser.add_argument('service', help="The service to get usage records from")

    return parser.parse_args()

config = Configuration()

if __name__ == '__main__':
    args = parse_args()

    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    usage_records = get_usage_records(args.service)
    store_usage_records(usage_records)


import cx_Oracle
from typing import Optional

def insertCodeTag(appDbConnStr: str, codeTag: str) -> bool:
    """inserts a code tag into the app db
    Returns:
        bool: returns true if process is ok
    """
    dbConn = None
    dbCur = None
    isInsertSuccess = True
    try:
        # get connection with raw data table
        dbConn = cx_Oracle.connect(appDbConnStr)
        # column names of the table
        colNames = ["TAG_NAME"]
        # get cursor for code tags table
        dbCur = dbConn.cursor()

        sqlVals = [codeTag]

        # text for sql place holders
        sqlPlaceHldrsTxt = ','.join([':{0}'.format(x+1)
                                     for x in range(len(colNames))])

        # insert the code tag
        codeTagInsSql = 'insert into code_book.code_tags({0}) values ({1})'.format(
            ','.join(colNames), sqlPlaceHldrsTxt)

        dbCur.execute(codeTagInsSql, sqlVals)

        # commit the changes
        dbConn.commit()
    except Exception as err:
        isInsertSuccess = False
        print('Error while creation of code tag')
        print(err)
    finally:
        # closing database cursor and connection
        if dbCur is not None:
            dbCur.close()
        if dbConn is not None:
            dbConn.close()
    return isInsertSuccess


from django.contrib import admin
from django.urls import path,include
from . import views

urlpatterns = [
    path('',views.dash,name='authenticate'),
    path('login/',views.login,name='login'),
    path('msg/',views.msg,name='msg'),
    path('dash/',views.dash,name='dashboard'),
    path('logout/',views.logout,name="logout"),
    path('addpackage/',views.addpackage,name="addpackage"),
    path("predict/",views.predict,name="predict")
]


from keras import metrics
from PIL import Image

from keras.models import model_from_json
from keras.utils.np_utils import to_categorical

import keras.backend as K
import numpy as np
# import matplotlib.pyplot as plt
import seaborn
from show_images import show_images

import warnings

warnings.filterwarnings('ignore')

class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
               'dog', 'frog', 'horse', 'ship', 'truck']

def load_model(model_name='model.json', h5_name='model.h5'):
    # Load model from JSON
    json_file = open(model_name, 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    model = model_from_json(loaded_model_json)
    # Load weights into new model
    model.load_weights(h5_name)
    print("Loaded model from disk")
    return model

def process_pic(filename):
    original_pic = Image.open(filename).resize((32, 32))
    original_array = np.expand_dims(np.array(original_pic), 0)

    original_array = np.swapaxes(original_array, 2, 3)
    original_array = np.swapaxes(original_array, 1, 2)
    return original_array

def deprocess_array(array):
    array = np.swapaxes(array, 1, 2)
    array = np.swapaxes(array, 2, 3)
    # array = array.astype(np.uint8)

    return array

def generate_example(model, eps, original_array):
    target_idx = model.predict(original_array).argmax()
    target = to_categorical(target_idx, 10)
    target_variable = K.variable(target)

    loss = metrics.categorical_crossentropy(model.output, target_variable)

    gradients = K.gradients(loss, model.input)
    get_grad_values = K.function([model.input], gradients)
    grad_values = get_grad_values([original_array])[0]
    grad_signs = np.sign(grad_values)

    perturbation = grad_signs * eps
    print(perturbation[0])
    # perturbation = perturbation.astype(np.uint8)
    modified_array = original_array + perturbation
    # modified_array = modified_array.astype(np.uint8)
    return perturbation, modified_array

def make_pred(model, array_input):
    pred = model.predict(array_input)
    preds = [(class_names[i], pred[0][i]) for i in range(10)]
    return preds

def compare_visualize(model, original, perturbation, modified):
    original_pred = make_pred(model, original)
    perturbation_pred = make_pred(model, perturbation)
    modified_pred = make_pred(model, modified)

    original = deprocess_array(original)
    # plt.imshow(original[0])
    print('Predictions for original image:\n {}'.format(original_pred))

    perturbation = deprocess_array(perturbation)
    perturbation = np.clip(255 - perturbation, 0., 255.)
    # plt.imshow(perturbation[0])
    print('Predictions for perturbation:\n {}'.format(perturbation_pred))

    modified = deprocess_array(modified)
    modified = 255 - np.clip(modified, 0., 255.)

    # plt.imshow(modified[0])
    print('Predictions for modified image:\n {}'.format(modified_pred))

    show_images([original[0], perturbation[0], modified[0]], 3)

model = load_model()
original = process_pic('../images/plane.jpg')
perturbation, modified = generate_example(model, 0.5, original)
compare_visualize(model, original, perturbation, modified)


from PyQt5.QtCore import QSize
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QMainWindow, QMessageBox, QStackedWidget

from app.constants import Default
from app.controllers.game_controller import GameController
from app.domain.enums import GameState
from app.levels.tank_generator import TankFabric
from app.ui.widgets.choose_tank import ChooseTankWidget
from app.ui.widgets.entry import EntryWidget
from app.ui.widgets.game import GameWidget
from app.ui.widgets.menu import MenuWidget

class MainWindow(QMainWindow):
    """Main window for app"""

    username: str = None
    new_game_flag: bool = True
    game_controller: GameController = None
    player_fabric: TankFabric = None

    def __init__(self, size: QSize = QSize(612, 512), parent=None):
        super().__init__(parent)
        self.setWindowTitle("WORLD OF TANKS")
        self.setWindowIcon(QIcon(Default.PATH_TO_ICON))
        self.setFixedSize(size)

        self.entry = EntryWidget(self)
        self.menu = MenuWidget(self)
        self.game = GameWidget(self)
        self.choose = ChooseTankWidget(self)

        self.widgets = QStackedWidget(self)
        self.initWidgets(size)

        self.display(0)

    def initWidgets(self, size: QSize):
        """Initialize main widgets."""
        self.widgets.resize(size)
        self.widgets.addWidget(self.entry)
        self.widgets.addWidget(self.menu)
        self.widgets.addWidget(self.game)
        self.widgets.addWidget(self.choose)

    def display(self, idx: int):
        self.widgets.setCurrentIndex(idx)
        self.widgets.currentWidget().init()

    def closeEvent(self, e):
        if self.game_controller is None or self.game_controller.game is None:
            e.accept()
            return

        self.game_controller.pause.set()

        if self.game_controller.game.state != GameState.FINISHED:
            result = QMessageBox.question(
                self,
                "Closing confirmation WORLD OF TANKS",
                f"Maybe save, {self.username}?",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No,
            )

            if result == QMessageBox.Yes:
                self.game_controller.save()

        self.game.close()
        e.accept()
        QMainWindow.closeEvent(self, e)


#!/usr/bin/env python

import os
import argparse
import numpy as np
import cv2
import yaml
from lxml import etree as ET
from copy import copy
import sys
import json
import math

class WorldGenerator(object):

    kernel_size = 4 # for 2D map image preprocessing

    LOOKUP_TABLE = np.array([
    1.0,
    1.0,
    2.0,
    6.0,
    24.0,
    120.0,
    720.0,
    5040.0,
    40320.0,
    362880.0,
    3628800.0,
    39916800.0,
    479001600.0,
    6227020800.0,
    87178291200.0,
    1307674368000.0,
    20922789888000.0,
    355687428096000.0,
    6402373705728000.0,
    121645100408832000.0,
    2432902008176640000.0,
    51090942171709440000.0,
    1124000727777607680000.0,
    25852016738884976640000.0,
    620448401733239439360000.0,
    15511210043330985984000000.0,
    403291461126605635584000000.0,
    10888869450418352160768000000.0,
    304888344611713860501504000000.0,
    8841761993739701954543616000000.0,
    265252859812191058636308480000000.0,
    8222838654177922817725562880000000.0,
    263130836933693530167218012160000000.0
     ])

    def Ni(self, n, i):
        a1=self.LOOKUP_TABLE[n]
        a2=self.LOOKUP_TABLE[i]
        a3=self.LOOKUP_TABLE[n-i]
        ni=a1/(a2*a3)
        return ni

    def Bernstein(self,n, i, t):
        if t == 0.0 and i == 0:
            ti = 1.0
        else:
            ti = t**i

        if (n == i and t == 1.0):
            tni = 1.0
        else:
            tni = (1-t)**(n-i)

        basis = self.Ni(n, i)*ti*tni
        return basis

    def Bezier2D(self, trajectory, segment):
        cpts = segment['Parts']
        npts = len(trajectory)
        interpolatedPoints = [0]*cpts
        icount = 0
        t = 0.0
        step = 1.0/(cpts-1)

        for i in range(cpts):
            if (1.0-t) < 5e-6:
                t = 1.0

            jcount = 0
            interpolatedPoints[icount] = [0.0, 0.0]

            for j in range(npts):
                basis = self.Bernstein(npts - 1, j, t)
                interpolatedPoints[icount][0] += basis*trajectory[jcount][0]
                interpolatedPoints[icount][1] += basis*trajectory[jcount][1]
                jcount += 1

            icount += 1
            t += step
        return interpolatedPoints

    def __init__(self, yaml_path,layout_path):
        self.yaml_path = yaml_path
        self.pgm_path = os.path.join(os.path.dirname(yaml_path),
                                     os.path.splitext(os.path.basename(yaml_path))[0] + '.pgm')
        self.generated_world_path = os.path.join(os.path.dirname(os.path.dirname(yaml_path)),
                                                 'worlds',
                                                 'generated_' + os.path.splitext(os.path.basename(yaml_path))[0] + '.world')
        print(self.yaml_path)
        print(self.generated_world_path)
        self.layout_path=layout_path
        print(self.layout_path)

        ####################Prepare the image: ####################################
        ## Converts the image from cartographer to one from gmapping, doesnt really matter what are the values you set for the black white etc, because the map and the world will be
        ## perfectly syncronized
        img=cv2.imread(self.pgm_path)
        img= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        height, width= img.shape
        self.width=width
        self.height=height

        for x in range(0,width):
            for y in range(0,height):
                if(img[y,x]<=65):
                    img[y,x]=0
                if(img[y,x]>=196):
                    img[y,x]=254
                if(img[y,x]<196 and img[y,x]>65):
                    img[y,x]=205
        print('Preprocessing image finished...')
        cv2.imwrite('savedImage.pgm', img)
        #############################################################################

        self.map = cv2.imread('savedImage.pgm', -1).astype(np.float)

        self.map=self.map[::-1,:]

        self.map[self.map==0] = 255 # obstacle
        self.map[self.map==254] = 0 # empty
        self.map[self.map==205] = 0 # unknown

        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (self.kernel_size, self.kernel_size))
        self.map = cv2.morphologyEx(self.map, cv2.MORPH_CLOSE, kernel)

        with open(self.yaml_path, 'r') as f:
            yaml_data = yaml.safe_load(f)

        self.origin = np.array([yaml_data['origin'][0], yaml_data['origin'][1]])
        self.resolution = yaml_data['resolution']

    def write_basics(self):
        sdf = ET.Element("sdf",version="1.6")
        world = ET.SubElement(sdf, "world", name="default")
        # global light source
        include = ET.SubElement(world, 'include')
        uri = ET.SubElement(include, 'uri')
        uri.text = 'model://sun'
        # simple ground plane
        # include = ET.SubElement(world, 'include')
        # uri = ET.SubElement(include, 'uri')
        # uri.text = 'model://ground_plane'
        # ode
        physics = ET.SubElement(world, 'physics', type='ode')
        real_time_update_rate = ET.SubElement(physics, 'real_time_update_rate')
        real_time_update_rate.text = '1000.0'
        max_step_size = ET.SubElement(physics, 'max_step_size')
        max_step_size.text = '0.001'
        real_time_factor = ET.SubElement(physics, 'real_time_factor')
        real_time_factor.text = '1'
        ode = ET.SubElement(physics, 'ode')
        solver = ET.SubElement(ode, 'solver')
        type = ET.SubElement(solver, 'type')
        type.text = 'quick'
        iters = ET.SubElement(solver, 'iters')
        iters.text = '150'
        precon_iters = ET.SubElement(solver, 'precon_iters')
        precon_iters.text = '0'
        sor = ET.SubElement(solver, 'sor')
        sor.text = '1.400000'
        use_dynamic_moi_rescaling = ET.SubElement(solver, 'use_dynamic_moi_rescaling')
        use_dynamic_moi_rescaling.text = '1'
        constraints = ET.SubElement(ode, 'constraints')
        cfm = ET.SubElement(constraints, 'cfm')
        cfm.text = '0.00001'
        erp = ET.SubElement(constraints, 'erp')
        erp.text = '0.2'
        contact_max_correcting_vel = ET.SubElement(constraints, 'contact_max_correcting_vel')
        contact_max_correcting_vel.text = '2000.000000'
        contact_surface_layer = ET.SubElement(constraints, 'contact_surface_layer')
        contact_surface_layer.text = '0.01000'

        # scene
        scene = ET.SubElement(world, 'scene')
        ambient = ET.SubElement(scene, 'ambient')
        ambient.text = '0.4 0.4 0.4 1'
        background = ET.SubElement(scene, 'background')
        background.text = '0.7 0.7 0.7 1'
        shadows = ET.SubElement(scene, 'shadows')
        shadows.text = 'true'

        # gui
        gui = ET.SubElement(world, 'gui', fullscreen='0')
        camera = ET.SubElement(gui, 'camera', name='user_camera')
        pose = ET.SubElement(camera, 'pose')
        pose.text = '0.0 0.0 17.0 -1.5708 1.5708 0'
        view_controller = ET.SubElement(camera, 'view_controller')
        view_controller.text ='orbit'

        return sdf, world

    def generate_v_wall(self, parent, x, y, length, id):
        collision = ET.SubElement(parent, 'collision', name='obstacle_{}'.format(id))
        pose = ET.SubElement(collision, 'pose')
        pose.text = '{} {} 0 0 0 1.5708'.format(str(x), str(y))
        geometry = ET.SubElement(collision, 'geometry')
        box = ET.SubElement(geometry, 'box')
        size = ET.SubElement(box, 'size')
        size.text = '{} 0.15 1.0'.format(str(length))

        visual = ET.SubElement(parent, 'visual', name='obstacle_{}'.format(id))
        pose = ET.SubElement(visual, 'pose')
        pose.text = '{} {} 0 0 0 1.5708'.format(str(x), str(y))
        geometry = ET.SubElement(visual, 'geometry')
        box = ET.SubElement(geometry, 'box')
        size = ET.SubElement(box, 'size')
        size.text = '{} 0.15 1.0'.format(str(length))
        material = ET.SubElement(visual, 'material')
        script = ET.SubElement(material, 'script')
        uri = ET.SubElement(script, 'uri')
        uri.text = 'file://media/materials/scripts/gazebo.material'
        name = ET.SubElement(script, 'name')
        name.text = 'Gazebo/Grey'
        ambient = ET.SubElement(material, 'ambient')
        ambient.text = '1 1 1 1'

    def generate_h_wall(self, parent, x, y, length, id):
        collision = ET.SubElement(parent, 'collision', name='obstacle_{}'.format(id))
        pose = ET.SubElement(collision, 'pose')
        pose.text = '{} {} 0 0 0 0'.format(str(x), str(y))
        geometry = ET.SubElement(collision, 'geometry')
        box = ET.SubElement(geometry, 'box')
        size = ET.SubElement(box, 'size')
        size.text = '{} 0.15 1.0'.format(str(length))

        visual = ET.SubElement(parent, 'visual', name='obstacle_{}'.format(id))
        pose = ET.SubElement(visual, 'pose')
        pose.text = '{} {} 0 0 0 0'.format(str(x), str(y))
        geometry = ET.SubElement(visual, 'geometry')
        box = ET.SubElement(geometry, 'box')
        size = ET.SubElement(box, 'size')
        size.text = '{} 0.15 1.0'.format(str(length))
        # cylinder = ET.SubElement(geometry, 'cylinder')
        material = ET.SubElement(visual, 'material')
        script = ET.SubElement(material, 'script')
        uri = ET.SubElement(script, 'uri')
        uri.text = 'file://media/materials/scripts/gazebo.material'
        name = ET.SubElement(script, 'name')
        name.text = 'Gazebo/Grey'
        ambient = ET.SubElement(material, 'ambient')
        ambient.text = '1 1 1 1'

    def is_v_wall_type(self, r, c, gridmap):
        """
            Return True if it is belong to vertical wall ...

            This function helps to reduce the number of walls to generate
        """

        vl = 0 # expected vertical length
        rr = r
        cc = c
        while self.map[rr][cc] == 255:
            rr += 1
            vl += 1

        hl = 0 # expected horizontal length
        rr = r
        cc = c
        while self.map[rr][cc] == 255:
            cc += 1
            hl += 1
        return vl > hl

    def generate_layout(self,parent):
        try:
            with open(self.layout_path) as f:
                data=json.load(f)

            trajectory=[]
            stations=[]

            id_line=0
            for segment in data['Segments']:
                if segment['Vectors']:
                    pointStart=[segment['StartVector']['X']/1000.0, segment['StartVector']['Y']/1000.0]
                    pointEnd=[segment['EndVector']['X']/1000.0, segment['EndVector']['Y']/1000.0]
                    trajectory.append(pointStart)
                    for ptinvectors in segment['Vectors']:
                        trajectory.append([ptinvectors['X']/1000.0, ptinvectors['Y']/1000.0])
                    trajectory.append(pointEnd)
                    curve_points=self.Bezier2D(trajectory,segment)
                    trajectory.append(curve_points)
                    print(curve_points)
                    # marker_lines.points.extend(curve_points)

                    for point in curve_points:
                        # point=[station['Vector']['X']/1000.0, station['Vector']['Y']/1000.0]
                        collision = ET.SubElement(parent, 'collision', name='curve_{}'.format(id_line))
                        pose = ET.SubElement(collision, 'pose')
                        pose.text = '{} {} 0 0 0 {}'.format(str(point[0]),str(point[1]) , '0')
                        geometry = ET.SubElement(collision, 'geometry')
                        plane = ET.SubElement(geometry, 'plane')
                        # size = ET.SubElement(plane, 'size')
                        # size.text = '0.05 {}'.format(str(length))
                        surface=ET.SubElement(collision,'surface')
                        friction=ET.SubElement(surface,'friction')
                        ode=ET.SubElement(friction,'ode')
                        mu=ET.SubElement(ode,'mu')
                        mu.text='100'
                        mu2=ET.SubElement(ode,'mu2')
                        mu2.text='50'
                        torsional=ET.SubElement(friction,'torsional')
                        ode2=ET.SubElement(torsional,'ode')
                        contact=ET.SubElement(surface,'contact')
                        ode3=ET.SubElement(contact,'ode')
                        bounce=ET.SubElement(surface,'bounce')
                        max_contacts=ET.SubElement(collision,'max_contacts')
                        max_contacts.text='10'

                        visual = ET.SubElement(parent, 'visual', name='curve_{}'.format(id_line))
                        pose = ET.SubElement(visual, 'pose')
                        pose.text = '{} {} 0 0 0 {}'.format(str(point[0]),str(point[1]) , '0')
                        cast_shadows=ET.SubElement(visual,'cast_shadows')
                        geometry = ET.SubElement(visual, 'geometry')
                        cylinder = ET.SubElement(geometry, 'cylinder')
                        radius = ET.SubElement(cylinder, 'radius')
                        radius.text = '0.02'
                        length=ET.SubElement(cylinder,'length')
                        length.text='0'
                        # cylinder = ET.SubElement(geometry, 'cylinder')
                        material = ET.SubElement(visual, 'material')
                        script = ET.SubElement(material, 'script')
                        uri = ET.SubElement(script, 'uri')
                        uri.text = 'file://media/materials/scripts/gazebo.material'
                        name = ET.SubElement(script, 'name')
                        name.text = 'Gazebo/Red'
                        # ambient = ET.SubElement(material, 'ambient')
                        # ambient.text = '1 1 1 1'
                        id_line+=1
                    del trajectory[:]
                # List of layout points is not according to id
                # layout_list.append([segment['StartVector']['X']/1000, segment['StartVector']['Y']/1000])
                else:
                    pointStart=[segment['StartVector']['X']/1000.0, segment['StartVector']['Y']/1000.0]
                    pointEnd=[segment['EndVector']['X']/1000.0, segment['EndVector']['Y']/1000.0]
                    mean_point=[pointStart[0]+(pointEnd[0]-pointStart[0])/2, pointStart[1]+(pointEnd[1]-pointStart[1])/2]
                    length=math.sqrt((pointEnd[0]-pointStart[0])**2+(pointEnd[1]-pointStart[1])**2)
                    angle=math.atan((pointEnd[1]-pointStart[1])/(pointEnd[0]-pointStart[0]))+1.5708
                    # if segment['Vectors']:
                    collision = ET.SubElement(parent, 'collision', name='line_{}'.format(id_line))
                    pose = ET.SubElement(collision, 'pose')
                    pose.text = '{} {} 0 0 0 {}'.format(str(mean_point[0]),str(mean_point[1]) , str(angle))
                    geometry = ET.SubElement(collision, 'geometry')
                    plane = ET.SubElement(geometry, 'plane')
                    size = ET.SubElement(plane, 'size')
                    size.text = '0.05 {}'.format(str(length))
                    surface=ET.SubElement(collision,'surface')
                    friction=ET.SubElement(surface,'friction')
                    ode=ET.SubElement(friction,'ode')
                    mu=ET.SubElement(ode,'mu')
                    mu.text='100'
                    mu2=ET.SubElement(ode,'mu2')
                    mu2.text='50'
                    torsional=ET.SubElement(friction,'torsional')
                    ode2=ET.SubElement(torsional,'ode')
                    contact=ET.SubElement(surface,'contact')
                    ode3=ET.SubElement(contact,'ode')
                    bounce=ET.SubElement(surface,'bounce')
                    max_contacts=ET.SubElement(collision,'max_contacts')
                    max_contacts.text='10'

                    visual = ET.SubElement(parent, 'visual', name='line_{}'.format(id_line))
                    pose = ET.SubElement(visual, 'pose')
                    pose.text = '{} {} 0 0 0 {}'.format(str(mean_point[0]),str(mean_point[1]) , str(angle))
                    cast_shadows=ET.SubElement(visual,'cast_shadows')
                    geometry = ET.SubElement(visual, 'geometry')
                    plane = ET.SubElement(geometry, 'plane')
                    size = ET.SubElement(plane, 'size')
                    size.text = '0.05 {}'.format(str(length))
                    material = ET.SubElement(visual, 'material')
                    script = ET.SubElement(material, 'script')
                    uri = ET.SubElement(script, 'uri')
                    uri.text = 'file://media/materials/scripts/gazebo.material'
                    name = ET.SubElement(script, 'name')
                    name.text = 'Gazebo/Yellow'
                    # ambient = ET.SubElement(material, 'ambient')
                    # ambient.text = '1 1 1 1'
                    id_line+=1

            id=0
            for station in data['Stations']:
                stationPoint=[station['Vector']['X']/1000.0, station['Vector']['Y']/1000.0]
                collision = ET.SubElement(parent, 'collision', name='station_{}'.format(id))
                pose = ET.SubElement(collision, 'pose')
                pose.text = '{} {} 0 0 0 {}'.format(str(stationPoint[0]),str(stationPoint[1]) , '0')
                geometry = ET.SubElement(collision, 'geometry')
                plane = ET.SubElement(geometry, 'plane')
                # size = ET.SubElement(plane, 'size')
                # size.text = '0.05 {}'.format(str(length))
                surface=ET.SubElement(collision,'surface')
                friction=ET.SubElement(surface,'friction')
                ode=ET.SubElement(friction,'ode')
                mu=ET.SubElement(ode,'mu')
                mu.text='100'
                mu2=ET.SubElement(ode,'mu2')
                mu2.text='50'
                torsional=ET.SubElement(friction,'torsional')
                ode2=ET.SubElement(torsional,'ode')
                contact=ET.SubElement(surface,'contact')
                ode3=ET.SubElement(contact,'ode')
                bounce=ET.SubElement(surface,'bounce')
                max_contacts=ET.SubElement(collision,'max_contacts')
                max_contacts.text='10'

                visual = ET.SubElement(parent, 'visual', name='station_{}'.format(id))
                pose = ET.SubElement(visual, 'pose')
                pose.text = '{} {} 0 0 0 {}'.format(str(stationPoint[0]),str(stationPoint[1]) , '0')
                cast_shadows=ET.SubElement(visual,'cast_shadows')
                geometry = ET.SubElement(visual, 'geometry')
                cylinder = ET.SubElement(geometry, 'cylinder')
                radius = ET.SubElement(cylinder, 'radius')
                radius.text = '0.1'
                length=ET.SubElement(cylinder,'length')
                length.text='0'
                # cylinder = ET.SubElement(geometry, 'cylinder')
                material = ET.SubElement(visual, 'material')
                script = ET.SubElement(material, 'script')
                uri = ET.SubElement(script, 'uri')
                uri.text = 'file://media/materials/scripts/gazebo.material'
                name = ET.SubElement(script, 'name')
                name.text = 'Gazebo/Blue'
                # ambient = ET.SubElement(material, 'ambient')
                # ambient.text = '1 1 1 1'

                id+=1

            self_collide=ET.SubElement(parent, 'self_collide')
            self_collide.text='0'
            kinematic=ET.SubElement(parent, 'kinematic')
            kinematic.text='0'
            gravity=ET.SubElement(parent,'gravity')
            gravity.text='1'

        except Exception as e:
            print(e)

    def generate(self):
        sdf, world = self.write_basics()

        model = ET.SubElement(world, 'model', name='obstacle')
        static = ET.SubElement(model, 'static')
        static.text = '1'
        pose = ET.SubElement(model, 'pose', frame='')
        pose.text = '0 0 0 0 0 0'
        link = ET.SubElement(model, 'link', name='obstacle')

        parent = link

        flag = copy(self.map) # 255 -> need to build wall, 0 -> already ...

        wall_count = 0
        while True:
            idxs = np.argwhere(flag == 255)
            if len(idxs) == 0:
                break

            wall_count += 1

            start_r, start_c = idxs[0]
            # start_r=self.height-1-start_r

            h_wall = False
            v_wall = False
            end_r = start_r
            end_c = start_c
            # if self.map[end_r + 1][end_c] == 255 :
            if self.is_v_wall_type(start_r, start_c, self.map):
                v_wall = True
                while self.map[end_r][end_c] == 255:
                    flag[end_r][end_c] = 0
                    end_r += 1
                center_x = self.origin[0] + int((start_c + end_c) / 2) * self.resolution
                center_y = self.origin[1] + int((start_r + end_r) / 2) * self.resolution
                # center_y = self.origin[1] + int(self.height-1-(start_r + end_r) / 2) * self.resolution
                l = (end_r - start_r) * self.resolution
                self.generate_v_wall(link, center_x, center_y, l, wall_count)
            elif self.map[end_r][end_c + 1] == 255:
                h_wall = True
                while self.map[end_r][end_c] == 255:
                    flag[end_r][end_c] = 0
                    end_c += 1
                center_x = self.origin[0] + int((start_c + end_c) / 2) * self.resolution
                center_y = self.origin[1] + int((start_r + end_r) / 2) * self.resolution
                l = (end_c - start_c) * self.resolution
                self.generate_h_wall(link, center_x, center_y, l, wall_count)
            else:
                flag[end_r][end_c] = 0
                continue
            print('[{} idxs remained], wall_count={}, center_x={}, center_y={}, l={}'.format(len(idxs), wall_count, center_x, center_y, l))

        ##Draw the layout in world
        model_layout = ET.SubElement(world, 'model', name='yellow_lines')
        static_layout = ET.SubElement(model_layout, 'static')
        static_layout.text = '1'
        link_layout = ET.SubElement(model_layout, 'link', name='yellow_lines')

        self.generate_layout(link_layout)

        tree = ET.ElementTree(sdf)
        # print('oi' + self.generated_world_path)

        tree.write(self.generated_world_path, pretty_print=True)

parser = argparse.ArgumentParser(description="Run commands")
parser.add_argument('--yaml', type=str, help="yaml path")
parser.add_argument('--layout', type=str, help="layout path")
if len(sys.argv)==1:
    parser.print_help(sys.stderr)
    sys.exit(1)

args = parser.parse_args()

world_generator = WorldGenerator(args.yaml, args.layout)
world_generator.generate()


# encoding:utf-8
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from plug import plugs_get_all
from protocol_master_ui import Ui_MainWindow
import ui
import media
import protocol
import session
import datetime
from ESSetting import ESSetting
import logging

logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', level=logging.DEBUG)

class ESMainWindow(QMainWindow, Ui_MainWindow):
    """
       管理插件、信道、和协议。
    """
    def __init__(self):
        super(ESMainWindow, self).__init__()
        self.setupUi(self)
        self.setting = ESSetting.instance()
        self.medias_dict = media.Media.get_sub_class_instances()
        self.protocols_dict = protocol.Protocol.get_sub_class_instances()
        self.init_menu()
        layout = QHBoxLayout()
        self.plugIndexContainer = QStackedWidget()
        layout.addWidget(self.plugIndexContainer)
        self.upper.setLayout(layout)
        self.plugs = plugs_get_all()
        self.session = session.SessionSuit.create_binary_suit(self.get_current_media(), self.get_current_protocol())
        self.session.data_snd.connect(self.log_snd_frame)
        self.session.data_ready.connect(self.log_rcv_frame)
        self.session.data_clean.connect(self.log_rcv_frame)

        self.install_plugs()

        self.log_idx = 0
        self.tableWidgetFrame.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
        self.tableWidgetFrame.setColumnWidth(0, 95)
        self.tableWidgetFrame.setColumnWidth(1, 35)
        self.tableWidgetFrame.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tableWidgetFrame.customContextMenuRequested.connect(self.log_tablewidgit_menu)
        self.tableWidgetFrame.cellClicked.connect(self.log_history_clicked)
        self.status_bar_timer = QTimer(self)
        self.status_bar_timer.timeout.connect(self.update_status_bar)
        self.status_bar_timer.start(1000)
        self.sync_plug(-1)
        self.plugIndexContainer.setCurrentIndex(self.setting.get_plug_idx())
        self.sync_media(None)

    def sync_plug(self, idx):
        if idx >= 0:
            self.session.data_ready.disconnect()
            self.setting.set_plug_idx(idx)
        self.session.protocol = self.get_current_protocol()
        self.session.data_ready.connect(self.get_current_plug().handle_receive_data)

    def sync_media(self, key):
        if key is not None:
            self.get_current_media().error.disconnect()
            self.setting.set_media_key(key)
        self.session.media = self.get_current_media()
        self.session.media.error.connect(self.show_error)

    def update_status_bar(self):
        message = self.session.status_message()
        self.statusBar.showMessage(message)

    def log_history_clicked(self, row, col):
        txt = self.tableWidgetFrame.item(row, col).text()
        self.textBrowserFrameInfo.setText(txt)
        readable_text =  self.get_current_protocol().to_readable_str
        self.textBrowserFrameInfo.append(readable_text)

    def log_tablewidgit_menu(self,pos):
        menu = QMenu()
        clear = menu.addAction("清空")
        action = menu.exec_(self.tableWidgetFrame.mapToGlobal(pos))
        if action == clear:
            self.clear_log_info()
            return
        else:
            return

    def install_plugs(self):
        for plug in self.plugs:
            widget = QTreeWidgetItem(self.leftTreeWidget)
            widget.setText(0, plug.name)
            self.plugIndexContainer.addWidget(plug)
            plug.session = self.session
            protocols = plug.get_protocols()
            for pro in protocols:
                assert pro in self.protocols_dict

    def init_menu(self):
        action = QAction(u"通信参数", self)
        action.setShortcut("Ctrl+R")
        action.triggered.connect(self.show_media_config)
        self.menuSet.addAction(action)
        self.toolbar.addAction(action)
        action = QAction(u"协议", self)
        action.setShortcut("Ctrl+R")
        action.triggered.connect(self.show_protocol_config)
        self.menuSet.addAction(action)
        self.toolbar.addAction(action)

    def plug_index_clicked(self, index):
        idx = index
        if not isinstance(index, int):
            idx = index.row()
        if self.setting.get_plug_idx() != idx:
            self.plugIndexContainer.setCurrentIndex(idx)
            self.sync_plug(idx)

    def show_media_config(self):
        if len(self.medias_dict) > 0:
            self.session.media = self.get_current_media()
            def ok_func(media):
                if self.get_current_media() != media:
                    self.sync_media(media.name)
            ui.show_user_media_options(list(self.medias_dict.values()), ok_func)
        else:
            QMessageBox.information(None, "错误", u"没有可以用使用的信道")

    def show_protocol_config(self):
        if len(self.protocols_dict) > 0:
            def ok_func(protocol, options):
                pass
            options = list()
            for pros in self.protocols_dict:
                 options.append(pros.name)
            ui.show_user_options([media.MediaOptions(u"协议",options)],ok_func)
            self.update_session()
        else:
            QMessageBox.information(None, u"错误", u"没有可以用使用的协议")

    def show_error(self, msg):
        QMessageBox.information(None, u"错误", msg)
        self.get_current_plug().media_error_happen()

    def log_snd_frame(self, protocol):
        self._add_log_info("snd", str(protocol))

    def log_rcv_frame(self, protocol):
        self._add_log_info("rcv", str(protocol))

    def _add_log_info(self,tag, info):
        self.log_idx += 1
        self.tableWidgetFrame.setRowCount(self.log_idx)
        time_display = datetime.datetime.now().strftime('%m-%d %H:%M:%S.%f')
        widget = QTableWidgetItem(time_display)
        self.tableWidgetFrame.setItem(self.log_idx-1, 0, widget)
        widget = QTableWidgetItem(tag)
        self.tableWidgetFrame.setItem(self.log_idx-1, 1, widget)
        widget = QTableWidgetItem(info)
        self.tableWidgetFrame.setItem(self.log_idx-1, 2, widget)
        if self.log_idx > 50000:
            self.clear_log_info()

    def clear_log_info(self):
        self.tableWidgetFrame.setRowCount(0)
        self.log_idx = 0

    def get_current_media(self):
        key = list(self.medias_dict.keys())[0]
        return self.medias_dict[self.setting.get_media_key(key)]

    def get_current_protocol(self):
        keys = self.plugs[self.setting.get_plug_idx()].get_protocols()
        if len(keys) > 0:
            return self.protocols_dict[keys[0]]
        else:
            return list(self.protocols_dict.values())[0]

    def get_current_plug(self):
        return self.plugs[self.setting.get_plug_idx()]

    def resizeEvent(self, a0):
        #print("upper size",self.upper.size())
        #print("lower size",self.lower.size())
        super(ESMainWindow, self).resizeEvent(a0)

def protocol_master_run():
    app = QApplication(sys.argv)
    ex = ESMainWindow()
    ex.show_media_config()
    ex.move((QApplication.desktop().width() - ex.width())/2, (QApplication.desktop().height() - ex.height())/2);
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    protocol_master_run()


"""Vesting schedules"""
import datetime
from dataclasses import dataclass
from typing import List

@dataclass(frozen=True)
class VestingEvent:
    date: datetime.date
    value: float

@dataclass(frozen=True)
class Schedule:
    grant_date: datetime.date
    first_event_value: float
    first_event_date: datetime.date
    subsequent_events_value: float
    subsequent_events_spacing_weeks: int
    num_events: int

    def nth_event(self, n: int) -> VestingEvent:
        if n == 0:
            return VestingEvent(
                date=self.first_event_date, value=self.first_event_value
            )

        delta = datetime.timedelta(weeks=self.subsequent_events_spacing_weeks * n)
        event_date = self.first_event_date + delta
        return VestingEvent(date=event_date, value=self.subsequent_events_value)

    @property
    def vesting_events(self) -> List[VestingEvent]:
        return [self.nth_event(n) for n in range(self.num_events)]

def four_year_schedule_one_year_cliff(grant_date: datetime.date) -> Schedule:
    return Schedule(
        grant_date=grant_date,
        first_event_date=grant_date + datetime.timedelta(weeks=52),
        first_event_value=1 / 4,
        subsequent_events_value=1 / 16,
        subsequent_events_spacing_weeks=13,
        num_events=13,
    )

def one_year_schedule_no_cliff(grant_date: datetime.date) -> Schedule:
    return Schedule(
        grant_date=grant_date,
        first_event_date=grant_date + datetime.timedelta(weeks=13),
        first_event_value=1 / 4,
        subsequent_events_value=1 / 4,
        subsequent_events_spacing_weeks=13,
        num_events=4,
    )

def one_year_schedule_one_year_cliff(grant_date: datetime.date) -> Schedule:
    return Schedule(
        grant_date=grant_date,
        first_event_date=grant_date + datetime.timedelta(weeks=52),
        first_event_value=1,
        subsequent_events_value=0,
        subsequent_events_spacing_weeks=0,
        num_events=1,
    )

def four_year_schedule_no_cliff(grant_date: datetime.date) -> Schedule:
    return Schedule(
        grant_date=grant_date,
        first_event_date=grant_date + datetime.timedelta(weeks=13),
        first_event_value=1 / 16,
        subsequent_events_value=1 / 16,
        subsequent_events_spacing_weeks=13,
        num_events=16,
    )


from typing import Union
from utils.logger import logger
from utils.config import global_config
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkalidns.request.v20150109.AddDomainRecordRequest import AddDomainRecordRequest
from aliyunsdkalidns.request.v20150109.DeleteDomainRecordRequest import DeleteDomainRecordRequest

class AliyunDns(object):
    def __init__(self):
        self.appid = global_config.getRaw('aliyun', 'appid')
        self.appsecret = global_config.getRaw('aliyun', 'appsecret')
        self.__letsencryptSubDomain = '_acme-challenge'

    def add_dns_record(self,domain_name_re, domain_name, type, value):
        try:
            client = AcsClient(self.appid, self.appsecret, 'cn-hangzhou')
            request = AddDomainRecordRequest()
            request.set_accept_format('json')
            request.set_Value(value)
            request.set_Type(type)
            request.set_RR(domain_name_re)
            request.set_DomainName(domain_name)
            response = client.do_action_with_exception(request)
            # python2:  print(response)
            response = str(response, encoding='utf-8')
            logger.info(f'response=[{response}]')
            return response
        except Union[ClientException, ServerException] as result:
            logger.info(f'exception=[{result}]')

    def del_dns_record(self, record_id):
        try:
            client = AcsClient(self.appid, self.appsecret, 'cn-hangzhou')
            request = DeleteDomainRecordRequest()
            request.set_RecordId(record_id)
            response = client.do_action_with_exception(request)
            response = str(response, encoding='utf-8')
            logger.info(f'response=[{response}]')
            return response
        except Union[ClientException, ServerException] as result:
            logger.info(f'exception=[{result}]')


import io
import builtins
import codecs
import os
import threading

from contextlib import contextmanager

open_usage = {}

std_open = open
io_open = io.open
codecs_open = codecs.open
os_open = os.open

@contextmanager
def restore_open():
    try:
        mock_open = builtins.open
        mock_io_open = io.open
        mock_codecs_open = codecs.open
        mock_os_open = os.open
        builtins.open = std_open
        io.open = io_open
        codecs.open = codecs_open
        os.open = os_open
        try:
            mock_builtins = __builtins__["open"]
            __builtins__["open"] = std_open
        except:
            mock_builtins = __builtins__.open
            __builtins__.open = std_open
        yield
    finally:
        builtins.open = mock_open
        io.open = mock_io_open
        codecs.open = mock_codecs_open
        os.open = mock_os_open
        try:
            __builtins__["open"] = mock_builtins
        except:
            __builtins__.open = mock_builtins

def print_open():
    print(std_open)
    print(io_open)
    print(codecs_open.__code__.co_filename)
    print(os_open)

@contextmanager
def use_safe_open():
    try:
        ident = threading.current_thread().ident
        old = open_usage.get(ident, False)
        open_usage[ident] = True
        yield
    finally:
        open_usage[ident] = old

def should_use_safe_open():
    ident = threading.current_thread().ident
    return open_usage.get(ident, False)


from App.ProblemBuilder.Builder import CreateProblem
from App.THSolver.ThermalSolver import ThermalSolver
from App.THSolver.FlowChannel import FlowChannel
from Materials.TH_TEST1 import TH_TEST1
from Materials.Fluids.FluidHydrogen import FluidHydrogen
from App.OutputGenerator import OutputGenerator

problem = CreateProblem("\Cases\Case3\mesh.msh")

for cell in problem.GetRegion("solid").cells:
    cell.QGen = 1e4 * cell.volume

for cell in problem.cells:
    cell.T = 850

problem.SetMaterial("solid", TH_TEST1())
problem.SetMaterial("fluid", TH_TEST1())
print("materials assigned")

problem.SetConstantTempThermalBC("hot", 1000)
problem.SetConstantTempThermalBC("cold", 1000)
print("thermal bc's created")

flowChannel = FlowChannel(-0.5, 0.5, 20, FluidHydrogen(), 0.628318, 0.0314159)
flowChannel.SetInletConditions(300, 300000, 0.01)

problem.InsertFlowChannel("fluid", "interface", flowChannel)
print("flow channel created")

thermalSolver = ThermalSolver()

thermalSolver.Solve(problem, 10)

# for cell in problem.flowChannels[0].flowCells:
#     print(cell.T)
OutputGenerator(problem, "NewBuilderTest.csv")


import socket
import sys
import os

def main():
    server, connection_type, client_socket, client_address = initialize_server(sys.argv[1])
    while True:
        if connection_type == "close":
            client_socket, client_address = server.accept()
        # if the client doesn't send a new query in 1 second, close connection.
        client_socket.settimeout(1.0)
        try:
            query = client_socket.recv(2048)
            print(query.decode())
            # if client sent an empty packet, close the connection and handle the next one.
            if query.decode() == "":
                connection_type = "close"
                client_socket.close()
                continue
        except socket.timeout:
            client_socket.close()
            continue
        # separate the lines by new line char.
        lines = (query.decode()).split("\r\n")
        # extract file path from GET line.
        file_path = extract_file_path(lines)
        # if an empty file name was inserted, return index.html.
        if file_path == "/":
            file_path += "index.html"
        # if the client requests to redirect, return result.html.
        if file_path == "/redirect":
            handle_redirect(client_socket)
            continue
        # remove "/" from the beginning of the file name.
        file_path = file_path[1:]
        # navigate to the "files" folder.
        path = os.path.dirname(__file__)
        os.chdir(path + "/files")
        # if the requested file name wasn't found, return 404 not found error page.
        if not file_exists(file_path):
            handle_not_found(client_socket)
            continue
        # find the connection line, and extract to connection type from it.
        connection_type = extract_connection_type(lines)
        # use the relevant function to send the file.
        if extract_file_type(file_path) == "ico" or extract_file_type(file_path) == "jpg":
            send_jpg_ico(client_socket, file_path, connection_type)
        else:
            send_file(client_socket, file_path, connection_type)
        # if connection type is "close", close the socket to accept a new connection.
        if connection_type == "close":
            client_socket.close()

def initialize_server(port):
    # create a tcp socket.
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # accept all IP addresses, and use the command line arg as port number.
    server_ip = '0.0.0.0'
    server_port = int(port)
    server.bind((server_ip, server_port))
    # accept 1 client at a time.
    server.listen(1)
    # initialize client's parameters.
    connection_type = "close"
    client_socket = 0
    client_address = 0
    return server, connection_type, client_socket, client_address

def extract_file_path(lines):
    # skip irrelevant lines.
    i = 0
    while (lines[i].split(" "))[0] != "GET":
        i += 1
    # extract file name from GET line.
    file_path = (lines[i].split(" "))[1]
    return file_path

def extract_file_type(file_path):
    # file_path format is: "/.../file_name". split it and take the last part to extract file name.
    file_name = (file_path.split("/"))
    file_name = file_name[len(file_name) - 1]
    # extract file type from file name.
    file_type = file_name.split(".")[1]
    return file_type

def extract_connection_type(lines):
    connection_type = ""
    # find the connection line.
    for line in lines:
        line = line.split(" ")
        if line[0] == "Connection:":
            # extract the connection type.
            connection_type = line[1]
    return connection_type

def file_exists(file_path):
    # if file open (for reading) succeed, return true. else, return false.
    try:
        open(file_path, "r")
        return True
    except IOError:
        return False

def handle_redirect(client_socket):
    # if client requests to redirect, navigate to "result.html" as defined.
    message = "HTTP/1.1 301 Moved Permanently\r\n"
    message += "Connection: close\r\n"
    message += "Location: /result.html\r\n\r\n"
    client_socket.send(message.encode())
    client_socket.close()

def handle_not_found(client_socket):
    # if client requests a file which does not exist, return 404 page as defined.
    message = "HTTP/1.1 404 Not Found\r\n"
    message += "Connection: close\r\n\r\n"
    client_socket.send(message.encode())
    client_socket.close()

def send_file(client_socket, file_path, connection_type):
    # read the file to the buffer.
    buffer = ""
    f = open(file_path, 'r')
    temp = f.read(2048)
    while temp:
        buffer += temp
        temp = f.read(2048)
    f.close()
    # send the details of the file to the client.
    message = "HTTP/1.1 200 OK\r\n"
    message += ("Connection: " + connection_type + "\r\n")
    message += ("Content-Length: " + str(len(buffer)) + "\r\n")
    message += "\r\n"
    message += buffer
    message += "\r\n\r\n"
    client_socket.send(message.encode())

def send_jpg_ico(client_socket, file_path, connection_type):
    # get the file's size in bytes.
    file_size = os.path.getsize(file_path)
    # send the file's details to the client.
    message = "HTTP/1.1 200 OK\r\n"
    message += ("Connection: " + connection_type + "\r\n")
    message += ("Content-Length: " + str(file_size) + "\r\n")
    message += "\r\n"
    client_socket.send(message.encode())
    # read the file as bytes to var temp, and send the bytes straight to the client.
    f = open(file_path, 'rb')
    temp = f.read(2048)
    while temp:
        client_socket.send(temp)
        temp = f.read(2048)
    client_socket.send("\r\n\r\n".encode())
    f.close()

main()


import fasttext
import pickle
import numpy as np
max_len = 250
MAX_VOCAB_SIZE = 60702

from keras.preprocessing.sequence import pad_sequences
# file_train_name = 'cail_0518/data_train_seg.txt'
out_file_train_name = 'cail_0518/data_train_fasttext_num.txt'
# file_test_name = 'cail_0518/data_test_seg.txt'
out_file_test_name = 'cail_0518/data_test_fasttext_num.txt'

def write_file(x_list,y_list,out_file):
    for i in range(len(x_list)):
        out_str = ''
        for y in y_list[i]:
            out_str = out_str + '__label__' + y + ' '
        out_str += ' '.join([str(a) for a in x_list[i]])
        out_file.write(out_str + '\n')

with open(('aux_files/dataset_%d.pkl' %MAX_VOCAB_SIZE), 'rb') as f:
        dataset = pickle.load(f)
train_x = pad_sequences(dataset.train_seqs2, maxlen=max_len, padding='post')
train_y = np.array(dataset.train_y)
test_x = pad_sequences(dataset.test_seqs2, maxlen=max_len, padding='post')
test_y = np.array(dataset.test_y)

out_file_train = open(out_file_train_name,'w')
out_file_test = open(out_file_test_name,'w')
write_file(train_x,train_y,out_file_train)
write_file(test_x,test_y,out_file_test)

# f = open(file_name,'r')
# f_out = open(out_file_name,'w')
# for line in f:
#     out_str = ''
#     line_list = line.strip().split('\t')
#     sentence = line_list[0]
#     label_str = line_list[1]
#     label_list = label_str.split('&')
#     for label in label_list:
#         out_str = out_str + '__label__' + label + ' '
#     out_str += sentence
#     f_out.write(out_str + '\n')