from gurobipy import *

from parametros import *

import numpy as np

# GENERACIÓN DE COLUMNAS

contador_de_columnas = 1

C = [k for k in range(1, contador_de_columnas + 1)] # Número de columnas

###################################
# VARIABLES INICIALES ARBITRARIAS #
###################################

# Variables de estado (parámetros obtenidos del pricing)

# Variable de estado W-p,s,t
# Cantidad de pacientes con protocolo p que tienen agendada su sesión s en el día t

w_pst_dada = {} #cantididad de pacientes con protocolo p que tiene su sesión s el día t

for p in P:
# Para cada protocolo

    for s in S[p]:
    #Para cada sesión

        for t in T:
        #Para cada día

            w_pst_dada[p,s,t] = 0
            # Variable de estado
            # Cantidad de protocolos p en sesión s en día t

# Variable de estado R-p
# Cantidad de pacientes con protocolo p que llegaron en el último periodo

r_p_dada = {}

for p in P:

    r_p_dada[p] = 0

# Valores Iniciales

r_p_dada[1] = 5

r_p_dada[2] = 3

r_p_dada[3] = 4

# Variables de estado acción (parámetros obtenidos del pricing)

# Variable de estado Z-p
# Cantidad de protocolos p derivados a sistema privado

z_p_dada = {}

for p in P:

    z_p_dada[p] = 0

# Valores Iniciales

z_p_dada[1] = 5

z_p_dada[2] = 3

z_p_dada[3] = 4

# Variable de estado X-p,t
# Cantidad de pacientes con protocolo p con sesión agendada en día t
# Permite realizar calendarización interdía

x_pt_dada = {}

for p in P:

    for t in T:

        x_pt_dada[p,t] = 0

# Variable de estado Y-p,t,s,m
# Cantidad de pacientes protocolo p, sesión s, día t, módulo m
# Variable a cargo de caldarización intradía

y_pstm_dada = {}

for p in P:

    for s in S[p]:

        for t in T:

            for m in M:

                y_pstm_dada[p,s,t,m] = 0

# Variable de estado U-p,t,s,m
# Cantidad de pacientes con protocolo p que en el día t terminan
# su sesión s en el módulo m

u_pstm_dada = {}

for p in P:

    for s in S[p]:

        for t in T:

            for m in M:

                u_pstm_dada[p,s,t,m] = 0

###########
# Maestro #
###########

maestro = Model("Asignacion")

# Variable generación de columnas

pi = {}

pi = maestro.addVars(C, lb=0.0, ub=GRB.INFINITY, obj=0.0, vtype=GRB.CONTINUOUS, name="Columna ingresada")

################
# DEFINICIONES #
################

#################
# FUNCIÓN COSTO #
#################
# En informe (9)

k_c = {}

for c in C:

    if c == contador_de_columnas:

        k_c[c] = quicksum(z_p_dada[p]*CD[p] for p in P) + quicksum(hora_extra * u_pstm_dada[p,s,t,m] * CM for hora_extra in BE2 for p in P for s in S[p] for t in T for m in range(BR2 + hora_extra, 41))

#el hora extra estaría multiplicando como 1*u+2*u+3*u???

# OMEGA

omega_cpst = {}

for c in C:

    if c == contador_de_columnas:

        for p in P:

            for s in S[p]:

                for t in T:

                    if (int(t) + 6 - K_ps[p][s]) > 0 and (int(t) + 6) < 13:

                        omega_cpst[c,p,s,t] = w_pst_dada[p,s,t] - γ * (w_pst_dada[p,s,(t + 6)] + x_pt_dada[p,(t + 6 - K_ps[p][s])])

                    else:

                        omega_cpst[c,p,s,t] = w_pst_dada[p,s,t]

# RHO

rho_cp = {}

for c in C:

    if c == contador_de_columnas:

        for p in P:

            rho_cp[c,p] = r_p_dada[p] - γ * lambdas[p-1]

# Esperanza de W

E_alpha_w = {}

for p in P:

    for s in S[p]:

        for t in T:

            E_alpha_w[p,s,t] = w_pst_dada[p,s,t]

# Esperanza de R

E_alpha_r = {}

for p in P:

    E_alpha_r[p] = lambdas[p-1]

#################
# RESTRICCIONES #
#################

# Restricción 1

maestro.addConstr((1 - γ) * sum(pi[c] for c in C) == 1)

# Restricción 2

for p in P:

    for s in S[p]:

        for t in T:

            maestro.addConstr(sum((omega_cpst[c,p,s,t] * pi[c]) for c in C) >= E_alpha_w[p,s,t])

# Restricción 3

for p in P:

    maestro.addConstr(sum((rho_cp[c,p] * pi[c]) for c in C) >= E_alpha_r[p])

# Restricción 4

for c in C:

    maestro.addConstr(pi[c] >= 0)

####################
# FUNCIÓN OBJETIVO #
####################

maestro.setObjective(sum((k_c[c] * pi[c]) for c in C), GRB.MINIMIZE)

#Probar funcionamiento del modelo

maestro.optimize()

#maestro.computeIIS()

#maestro.write("output_maestro.ilp")

maestro.printAttr("X")


'''
CIS 117 Python Programing: Lab 12
David Skrenta
'''

import sqlite3

DB_NAME = 'skrenta.db'

con = sqlite3.connect(DB_NAME)
cur = con.cursor()

cur.execute('CREATE TABLE PopByRegion (region, population)')

cur.execute('INSERT INTO PopByRegion VALUES ("Central Africa", "330,993")')
cur.execute('INSERT INTO PopByRegion VALUES ("Southeastern Africa", "743,112")')
cur.execute('INSERT INTO PopByRegion VALUES ("Japan", "100,562")')

cur.execute('SELECT Region, Population FROM PopByRegion')
print(cur.fetchall())
cur.execute('SELECT Region, Population FROM PopByRegion ORDER by Region')
print(cur.fetchall())
cur.execute('SELECT Region FROM PopByRegion')
print(cur.fetchall())
cur.execute ('SELECT Region FROM PopbyRegion WHERE Population > 400000')
print(cur.fetchall())
cur.execute('SELECT * FROM PopByRegion WHERE Region = "Japan"')
print(cur.fetchone())
cur.execute('''UPDATE PopByRegion SET Population = 100600 WHERE Region = "Japan"''')
cur.execute('SELECT * FROM PopByRegion WHERE Region = "Japan"')
print(cur.fetchone())
cur.execute('DELETE FROM PopByRegion WHERE Region < "S"')
cur.execute('SELECT * FROM PopByRegion')
print(cur.fetchall())

con.close()

'''
[('Central Africa', '330,993'), ('Southeastern Africa', '743,112'), ('Japan', '100,562')]
[('Central Africa', '330,993'), ('Japan', '100,562'), ('Southeastern Africa', '743,112')]
[('Central Africa',), ('Southeastern Africa',), ('Japan',)]
[('Central Africa',), ('Southeastern Africa',), ('Japan',)]
('Japan', '100,562')
('Japan', 100600)
[('Southeastern Africa', '743,112')]

'''


from django.shortcuts import render
from .models import TinTuc
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

# Create your views here.
def home(request):
    # Lấy dữ liệu từ database
    tintuc = TinTuc.objects.get_queryset().order_by('-id')

    # Phân trang
    page = request.GET.get('page', 1)
    paginator = Paginator(tintuc, 6)
    try:
        TinTucs = paginator.page(page)
    except PageNotAnInteger:
        TinTucs = paginator.page(1)
    except EmptyPage:
        TinTucs = paginator.page(paginator.num_pages)

    Data = {"TinTucs": TinTucs,
            }
    return render(request, 'simso/news.html', Data)

def tintuc(request, id):
    # Lấy dữ liệu từ database
    tintuc = TinTuc.objects.get(id=id)

    Data = {'TinTuc': tintuc,
            "TinTucKhacs": TinTuc.objects.all().order_by('-id').exclude(id=id)[:10],
            }
    return render(request, 'simso/tintuc.html', Data)


#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import sys
# import time
import numpy
from scipy.io import loadmat
from scipy.signal import hilbert
from scipy.fftpack import fft
import collections
import json
import shutil
import itertools

import tensorflow as tf
from sklearn import metrics

from CNN_model import CNN
from Config import Config

class Model(object):
    def __init__(self):
        #os.environ['CUDA_VISIBLE_DEVICES'] = Config.env   # 确定使用哪块GPU
        #os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'   # 程序本身相关信息打印程度

        self.save_dir = 'checkpoints'
        self.save_path = os.path.join(self.save_dir, 'best_validation')  # 最佳验证结果保存路径
        self.save_result = 'results'
        #self.gpu_config = tf.ConfigProto(log_device_placement=False, allow_soft_placement=True)
        #self.gpu_config.gpu_options.allow_growth = True

    # sys.setrecursionlimit(900000)

    # 获取频谱
    def fft_trans(self,array):
        N = len(array)
        return abs(numpy.fft.fft(array))[:, : int(N/2)] / N

    # 获取包络谱
    def enelop_trans(self,array):
        array_h = numpy.imag(hilbert(array))
        array_ene = abs(fft((array ** 2 + array_h ** 2) ** 0.5)) / len(array[0])
        array_ene[:, 0] = 0
        return array_ene[:, :int(len(array[0]) / 2)]

    # 打乱顺序
    def shuffle(self,data, label):
        '''
        打乱下标，打乱数据
        '''
        indices = numpy.random.permutation(numpy.arange(len(label)))
        return data[indices], label[indices]

    # deed dict generator
    def feed_test_data(self, x_batch, dropout_keep_prob_fc, is_training):
        '''
        generate the feed data dict object
        '''
        feed_dict = {self.model.input_x: x_batch,
                    self.model.dropout_keep_prob_fc:dropout_keep_prob_fc,
                    self.model.is_training: is_training }
        return feed_dict

    def run_test(self, x_test):
        #self.json_config = os.path.join(self.save_result, 'config.json')
        print("Predicting data...")
        x_test = numpy.array(x_test).reshape(-1,2048)
        x_test = self.enelop_trans(x_test)
        print('X_test shape is: ', x_test.shape)
        self.config = Config()
        self.model = CNN(self.config)
        with tf.Session() as sess_test:
            tf.global_variables_initializer().run()
            saver = tf.train.Saver()
            saver.restore(sess=sess_test, save_path=self.save_path)  # 读取保存的模型
            feed_dict = self.feed_test_data(x_test, 1.0, False)   # EVAL: keep_prob=1.0, valuation & testing are not during training.
            y_test_pred = sess_test.run(self.model.y_pred, feed_dict=feed_dict)
            print('y_test_pred',y_test_pred)

if __name__ == "__main__":
    data = numpy.array(range(2048)).reshape(1,2048)
    model = Model()
    model.run_test(data)


#!/usr/bin/env python
# coding: utf-8

def client_send_data(host,port,data):

    import socket
    hote = host
    ports =port

    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.connect((hote, port))
    print("Connection on {}".format(port))

    socket.send(data.encode())

    socket.close()


#!/usr/bin/env python
import pika
import psutil

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

while  (1):
	cpu_usage = psutil.cpu_percent(4)
	ram_usage = psutil.virtual_memory()[2]
	channel.queue_declare(queue='cpuusage')
	channel.queue_declare(queue='ramusage')
	channel.basic_publish(exchange='', routing_key='cpuusage', body= str(cpu_usage))
	channel.basic_publish(exchange='', routing_key='ramusage', body= str(ram_usage))
	print(" [x] Statistics Sent")
connection.close()


#rest api functions which returns individual responses of each api's
#api's consumed:
#1. drchrono.com/api/appointments
#2. drchrono.com/api/appointments/appointment_id
#3  drchrono.com/api/patients/
#4. drchrono.com/api/patients/patient_id
import datetime

import requests

from .settings import API_BASE_ADDRESS

def get_todays_appointments(access_token):
    """returns api response for ''../api/appointments/'(appointments scheduled for today)"""
    response = requests.get(
        API_BASE_ADDRESS + "appointments",
        headers={"Authorization": "Bearer {}".format(access_token)},
        params={"date": str(datetime.date.today())},
    )
    if 200 <= response.status_code < 400:
        return response.json()
    else:
        print(response)
        raise Exception("API returned an error response")

def get_appointment(access_token, appointment_id):
    """returns api response for ''../api/appointments/app_id/''(query the appointment endpoint
     for an appointment_id)"""
    response = requests.get(
        API_BASE_ADDRESS + "appointments/{}".format(appointment_id),
        headers={"Authorization": "Bearer {}".format(access_token)},
    )
    if 200 <= response.status_code < 400:
        return response.json()
    else:
        return None

def get_patient(access_token, patient_id):
    """returns response for particular api '../api/patients/' (list patient_details of patient_id)"""
    response = requests.get(
        API_BASE_ADDRESS + "patients/{}".format(patient_id),
        headers={"Authorization": "Bearer {}".format(access_token)},
    )
    if 200 <= response.status_code < 400:
        return response.json()
    else:
        return None

def put_appointment(access_token, appointment_id, data):
    """put data for particular appointment_id ''../api/appointments/app_id/'' (Updates appointment details)"""
    response = requests.put(
        API_BASE_ADDRESS + "appointments/{}".format(appointment_id),
        headers={"Authorization": "Bearer {}".format(access_token)},
        data=data,
    )
    return response

def put_patient(access_token, patient_id, data):
    """puts data for particular patient_id ''../api/patients/patient_id''(Updates patient details)"""
    return requests.put(
        API_BASE_ADDRESS + "patients/{}".format(patient_id),
        headers={"Authorization": "Bearer {}".format(access_token)},
        data=data,
    )


import matplotlib.pyplot as plt
import networkx as nx
from board_constants import *
from itertools import combinations
from read_txt import get_puzzles

GAME_SIZE = 9

class Cell:
	def __init__(self, cell_id):
		game_size = 9
		self.cell_id = cell_id
		self.domain = set(range(1,GAME_SIZE+1))

class Game:
	def __init__(self):
		self.game_board = []		#flat list of all cells, row by row
		self.constraint_graph = nx.Graph()

	def populate_board(self):
		for i in range(GAME_SIZE ** 2):
			self.game_board.append(Cell(i))

		self.constraint_graph.add_nodes_from(range(81))

		for i in range(GAME_SIZE):
			edges = combinations(ROW_LIST[i], 2)
			self.constraint_graph.add_edges_from(edges)
			edges = combinations(COL_LIST[i], 2)
			self.constraint_graph.add_edges_from(edges)
			edges = combinations(BOX_LIST[i], 2)
			self.constraint_graph.add_edges_from(edges)

	def enforce_unary_constraints(self, constraints_dict):
		for cell_id, val in constraints_dict.items():
			self.game_board[cell_id].domain = set([val])
			for n in self.constraint_graph[cell_id]:
				self.game_board[n].domain.discard(val)

	def pprint(self):
		i = 0
		for _ in range(GAME_SIZE):
			row = ""
			for _ in range(GAME_SIZE):
				domain = self.game_board[i].domain
				if len(domain) == 1:
					elem = domain.pop()
					domain.add(elem)
					row += str(elem)
				else:
					row += "_"
				i += 1
			print(row)

	def select_unassigned_variable(self, assignment):
		for i in range(GAME_SIZE ** 2):
			if not assignment.get(i, False):
				return i

	def is_consistent(self, variable, value, assignment):
		neighbors = self.constraint_graph[variable]
		for n in neighbors:
			if value == assignment.get(n, 0):
				return False
		return True

def backtracking_search(game):
	return recursive_backtracking({}, game)

def recursive_backtracking(assignment, game):
	if len(assignment) == GAME_SIZE ** 2:
		return assignment

	var = game.select_unassigned_variable(assignment)
	for value in game.game_board[var].domain:
		# if value is consistent with assignment given csp constraints:
		if game.is_consistent(var, value, assignment):
			assignment[var] = value
			result = recursive_backtracking(assignment, game)
			if result != -1:
				return result
			assignment.pop(var)
	return -1

def read_euler_puzzle(puzzle):
	i = 0
	d = {}
	for ch in puzzle:
		if ch != "0":
			d[i] = int(ch)
		i += 1
	return d

def print_assignment(assignment):
	if assignment == -1:
		print("Failure")
		return

	i = 0
	for _ in range(GAME_SIZE):
		row = ""
		for _ in range(GAME_SIZE):
			row += str(assignment[i])
			i += 1
		print(row)

solution_counter = 0
for name, puzzle in get_puzzles():
	game = Game()
	game.populate_board()
	grid = read_euler_puzzle(puzzle)
	game.enforce_unary_constraints(grid)
	assignment = backtracking_search(game)

	euler_solution = int(str(assignment[0]) + str(assignment[1]) + str(assignment[2]))
	solution_counter += euler_solution

	print(name)
	print_assignment(assignment)

print(solution_counter)


from typing import List, no_type_check, Any

from fugue.collections.partition import PartitionCursor
from fugue.dataframe import (
    ArrayDataFrame,
    DataFrame,
    DataFrames,
    LocalDataFrame,
    to_local_bounded_df,
)
from fugue.exceptions import FugueWorkflowError
from fugue.execution import SQLEngine
from fugue.execution.execution_engine import _generate_comap_empty_dfs
from fugue.extensions.processor import Processor
from fugue.extensions.transformer import CoTransformer, Transformer, _to_transformer
from triad.collections import ParamDict
from triad.collections.schema import Schema
from triad.utils.assertion import assert_or_throw
from triad.utils.convert import to_instance, to_type

class RunTransformer(Processor):
    @no_type_check
    def process(self, dfs: DataFrames) -> DataFrame:
        df = dfs[0]
        tf = _to_transformer(
            self.params.get_or_none("transformer", object),
            self.params.get_or_none("schema", object),
        )
        tf._workflow_conf = self.execution_engine.conf
        tf._params = self.params.get("params", ParamDict())  # type: ignore
        tf._partition_spec = self.partition_spec  # type: ignore
        ie = self.params.get("ignore_errors", [])
        self._ignore_errors = [to_type(x, Exception) for x in ie]

        if isinstance(tf, Transformer):
            return self.transform(df, tf)
        else:
            return self.cotransform(df, tf)

    def transform(self, df: DataFrame, tf: Transformer) -> DataFrame:
        tf._key_schema = self.partition_spec.get_key_schema(df.schema)  # type: ignore
        tf._output_schema = Schema(tf.get_output_schema(df))  # type: ignore
        tr = _TransformerRunner(df, tf, self._ignore_errors)  # type: ignore
        return self.execution_engine.map(
            df=df,
            map_func=tr.run,
            output_schema=tf.output_schema,  # type: ignore
            partition_spec=tf.partition_spec,
            on_init=tr.on_init,
        )

    @no_type_check
    def cotransform(self, df: DataFrame, tf: CoTransformer) -> DataFrame:
        assert_or_throw(
            df.metadata.get("serialized", False), "must use serialized dataframe"
        )
        tf._key_schema = df.schema - list(df.metadata["serialized_cols"].values())
        # TODO: currently, get_output_schema only gets empty dataframes
        empty_dfs = _generate_comap_empty_dfs(
            df.metadata["schemas"], df.metadata.get("serialized_has_name", False)
        )
        tf._output_schema = Schema(tf.get_output_schema(empty_dfs))
        tr = _CoTransformerRunner(df, tf, self._ignore_errors)
        return self.execution_engine.comap(
            df=df,
            map_func=tr.run,
            output_schema=tf.output_schema,
            partition_spec=tf.partition_spec,
            on_init=tr.on_init,
        )

class RunJoin(Processor):
    def process(self, dfs: DataFrames) -> DataFrame:
        if len(dfs) == 1:
            return dfs[0]
        how = self.params.get_or_throw("how", str)
        on = self.params.get("on", [])
        df = dfs[0]
        for i in range(1, len(dfs)):
            df = self.execution_engine.join(df, dfs[i], how=how, on=on)
        return df

class RunSetOperation(Processor):
    def process(self, dfs: DataFrames) -> DataFrame:
        if len(dfs) == 1:
            return dfs[0]
        how = self.params.get_or_throw("how", str)
        func: Any = {
            "union": self.execution_engine.union,
            "subtract": self.execution_engine.subtract,
            "intersect": self.execution_engine.intersect,
        }[how]
        distinct = self.params.get("distinct", True)
        df = dfs[0]
        for i in range(1, len(dfs)):
            df = func(df, dfs[i], distinct=distinct)
        return df

class Distinct(Processor):
    def process(self, dfs: DataFrames) -> DataFrame:
        assert_or_throw(len(dfs) == 1, FugueWorkflowError("not single input"))
        return self.execution_engine.distinct(dfs[0])

class RunSQLSelect(Processor):
    def process(self, dfs: DataFrames) -> DataFrame:
        statement = self.params.get_or_throw("statement", str)
        engine = self.params.get_or_none("sql_engine", object)
        if engine is None:
            engine = self.execution_engine.default_sql_engine
        elif not isinstance(engine, SQLEngine):
            engine = to_instance(engine, SQLEngine, args=[self.execution_engine])
        return engine.select(dfs, statement)

class Zip(Processor):
    def process(self, dfs: DataFrames) -> DataFrame:
        how = self.params.get("how", "inner")
        partition_spec = self.partition_spec
        # TODO: this should also search on workflow conf
        temp_path = self.params.get_or_none("temp_path", str)
        to_file_threshold = self.params.get_or_none("to_file_threshold", object)
        return self.execution_engine.zip_all(
            dfs,
            how=how,
            partition_spec=partition_spec,
            temp_path=temp_path,
            to_file_threshold=to_file_threshold,
        )

class Rename(Processor):
    def process(self, dfs: DataFrames) -> DataFrame:
        assert_or_throw(len(dfs) == 1, FugueWorkflowError("not single input"))
        columns = self.params.get_or_throw("columns", dict)
        return dfs[0].rename(columns)

class DropColumns(Processor):
    def process(self, dfs: DataFrames) -> DataFrame:
        assert_or_throw(len(dfs) == 1, FugueWorkflowError("not single input"))
        if_exists = self.params.get("if_exists", False)
        columns = self.params.get_or_throw("columns", list)
        if if_exists:
            columns = set(columns).intersection(dfs[0].schema.keys())
        return dfs[0].drop(list(columns))

class SelectColumns(Processor):
    def process(self, dfs: DataFrames) -> DataFrame:
        assert_or_throw(len(dfs) == 1, FugueWorkflowError("not single input"))
        columns = self.params.get_or_throw("columns", list)
        return dfs[0][columns]

class _TransformerRunner(object):
    def __init__(
        self, df: DataFrame, transformer: Transformer, ignore_errors: List[type]
    ):
        self.schema = df.schema
        self.metadata = df.metadata
        self.transformer = transformer
        self.ignore_errors = tuple(ignore_errors)

    def run(self, cursor: PartitionCursor, df: LocalDataFrame) -> LocalDataFrame:
        self.transformer._cursor = cursor  # type: ignore
        df._metadata = self.metadata
        if len(self.ignore_errors) == 0:
            return self.transformer.transform(df)
        else:
            try:
                return to_local_bounded_df(self.transformer.transform(df))
            except self.ignore_errors:  # type: ignore
                return ArrayDataFrame([], self.transformer.output_schema)

    def on_init(self, partition_no: int, df: DataFrame) -> None:
        s = self.transformer.partition_spec
        self.transformer._cursor = s.get_cursor(  # type: ignore
            self.schema, partition_no
        )
        df._metadata = self.metadata
        self.transformer.on_init(df)

class _CoTransformerRunner(object):
    def __init__(
        self, df: DataFrame, transformer: CoTransformer, ignore_errors: List[type]
    ):
        self.schema = df.schema
        self.metadata = df.metadata
        self.transformer = transformer
        self.ignore_errors = tuple(ignore_errors)

    def run(self, cursor: PartitionCursor, dfs: DataFrames) -> LocalDataFrame:
        self.transformer._cursor = cursor  # type: ignore
        if len(self.ignore_errors) == 0:
            return self.transformer.transform(dfs)

        else:
            try:
                return to_local_bounded_df(self.transformer.transform(dfs))
            except self.ignore_errors:  # type: ignore
                return ArrayDataFrame([], self.transformer.output_schema)

    def on_init(self, partition_no: int, dfs: DataFrames) -> None:
        s = self.transformer.partition_spec
        self.transformer._cursor = s.get_cursor(  # type: ignore
            self.schema, partition_no
        )
        self.transformer.on_init(dfs)


import numpy as np
from multiagent.core import World, Agent, Landmark
from multiagent.scenario import BaseScenario

class Scenario(BaseScenario):
    def make_world(self):
        world = World()
        # set any world properties first
        world.dim_c = 2
        num_agents = 2
        num_adversaries = 1
        num_landmarks = 5
        # add agents
        world.agents = [Agent() for i in range(num_agents)]
        for i, agent in enumerate(world.agents):
            agent.name = 'agent %d' % i
            agent.collide = True
            agent.silent = True
            if i < num_adversaries:
                agent.adversary = True
                agent.color = np.array([0.75, 0.25, 0.25])
            else:
                agent.adversary = False
                agent.color = np.array([0.25, 0.25, 0.75])
        # add landmarks for goal posts and puck
        goal_posts = [[-0.25, -1.0],
                      [-0.25, 1.0],
                      [0.25, -1.0],
                      [0.25, 1.0]]
        world.landmarks = [Landmark() for i in range(num_landmarks)]
        for i, landmark in enumerate(world.landmarks):
            landmark.name = 'landmark %d' % i
            if i > 0:
                landmark.collide = True
                landmark.movable = False
                landmark.state.p_pos = np.array(goal_posts[i-1])
                landmark.state.p_vel = np.zeros(world.dim_p)
            else:
                landmark.collide = True
                landmark.movable = True
        # add landmarks for rink boundary
        #world.landmarks += self.set_boundaries(world)
        # make initial conditions
        self.reset_world(world)
        return world

    def set_boundaries(self, world):
        boundary_list = []
        landmark_size = 1
        edge = 1 + landmark_size
        num_landmarks = int(edge * 2 / landmark_size)
        for x_pos in [-edge, edge]:
            for i in range(num_landmarks):
                l = Landmark()
                l.state.p_pos = np.array([x_pos, -1 + i * landmark_size])
                boundary_list.append(l)

        for y_pos in [-edge, edge]:
            for i in range(num_landmarks):
                l = Landmark()
                l.state.p_pos = np.array([-1 + i * landmark_size, y_pos])
                boundary_list.append(l)

        for i, l in enumerate(boundary_list):
            l.name = 'boundary %d' % i
            l.collide = True
            l.movable = False
            l.boundary = True
            l.color = np.array([0.75, 0.75, 0.75])
            l.size = landmark_size
            l.state.p_vel = np.zeros(world.dim_p)

        return boundary_list

    def reset_world(self, world):
        # random properties for landmarks
        for i, landmark in enumerate(world.landmarks):
            if i > 0:
                landmark.color = np.array([0.7, 0.7, 0.7])
            else:
                landmark.color = np.array([0.1, 0.1, 0.1])
            landmark.index = i
        # set random initial states
        for agent in world.agents:
            agent.state.p_pos = np.random.uniform(-1, +1, world.dim_p)
            agent.state.p_vel = np.zeros(world.dim_p)
            agent.state.c = np.zeros(world.dim_c)
        world.landmarks[0].state.p_pos = np.random.uniform(-1, +1, world.dim_p)
        world.landmarks[0].state.p_vel = np.zeros(world.dim_p)

    # return all agents of the blue team
    def blue_agents(self, world):
        return [agent for agent in world.agents if not agent.adversary]

    # return all agents of the red team
    def red_agents(self, world):
        return [agent for agent in world.agents if agent.adversary]

    def reward(self, agent, world):
        # Agents are rewarded based on team they belong to
        return self.adversary_reward(agent, world) if agent.adversary else self.agent_reward(agent, world)

    def agent_reward(self, agent, world):
        # reward for blue team agent
        return 0.0

    def adversary_reward(self, agent, world):
        # reward for red team agent
        return 0.0

    def observation(self, agent, world):
        # get positions/vel of all entities in this agent's reference frame
        entity_pos = []
        entity_vel = []
        for entity in world.landmarks:  # world.entities:
            entity_pos.append(entity.state.p_pos - agent.state.p_pos)
            if entity.movable:
                entity_vel.append(entity.state.p_vel)
        # get positions/vel of all other agents in this agent's reference frame
        other_pos = []
        other_vel = []
        for other in world.agents:
            if other is agent: continue
            other_pos.append(other.state.p_pos - agent.state.p_pos)
            other_vel.append(other.state.p_vel)
        return np.concatenate([agent.state.p_vel] + entity_pos + entity_vel + other_pos + other_vel)


def isPalindrome(string):
    return string.lower() == string[::-1].lower()

while True:
    print()
    s = input('Enter a string(enter exit to exit): ')
    if s == 'exit':
        break
    if(isPalindrome(s)):
        print('Is a palindrome')
    else:
        print('Is not a palindrome')


import numpy as np
from .motion import RigidMotion

__all__ = ['Body', 'TransformedBody', 'Pitching', 'Heaving',
           'cylinder', 'flat_plate', 'naca_airfoil', 'joukowski_foil',
           'van_de_vooren_foil', 'karman_trefftz_foil']

class Body(object):
    """Base class for representing bodies
    """
    def __init__(self, points):
        """Create a body with nodes at the given points

        Parameters
        ----------
        points : 2d array, shape (n,2)
            Array of points defining the boundary of the body
            For a closed body, the boundary curve should be positively oriented
            (counter-clockwise around outside of body), starting from trailing
            edge
        """
        self._time = 0
        self._points = np.array(points, dtype="float64")

    @property
    def time(self):
        """The time used to specify the body's motion"""
        return self._time

    @time.setter
    def time(self, value):
        self._time = value

    def get_points(self, body_frame=False):
        return self._points

    def get_body(self):
        """Return the Body object in the body-fixed frame"""
        return self

    def get_motion(self):
        """Return the transformation from the body-fixed to inertial frame"""
        return None

def cylinder(radius, num_points):
    """Return a circular Body with the given radius and number of points"""
    th = np.linspace(0, 2 * np.pi, num_points)
    points = radius * np.array([np.cos(th), np.sin(th)]).T
    return Body(points)

def flat_plate(num_points):
    """Return a flat plate Body with the given number of points.

    In body coordinates the plate runs from (0,0) to (1,0)."""
    x = np.linspace(1, 0, num_points) # from 1 to 0 so trailing edge at index 0
    y = np.zeros_like(x)
    return Body(np.array([x, y]).T)

def joukowski_foil(xcenter=-.1, ycenter=.1, a=1, num_points=32):
    """Return a Joukowski foil Body.

    The foil has its trailing edge at (2a,0).  The foil has a total of
    num_points along the boundary.  Refer to chapter 4 of [1]_ for details.

    Parameters
    ----------
    xcenter, ycenter : float
        (xcenter,ycenter) is the center of the Joukowski preimage circle.
        xcenter should be negative and small; its magnitude determines
        the bluffness of the foil.  ycenter should be small; it
        determines the magnitude of the camber (positive gives upward
        camber, and negative gives downward camber).

    a : float
        radius of the Joukowski preimage circle

    num_points : int
        number of points along the boundary

    References
    ----------
    .. [1] Acheson, D. J., "Elementary Fluid Dynamics", Oxford, 1990.
    """

    t = np.linspace(0,2*np.pi,num_points)
    r = np.sqrt((a-xcenter)**2+ycenter**2)
    chi = xcenter + r*np.cos(t)
    eta = ycenter + r*np.sin(t)
    mag2 = chi*chi + eta*eta
    x = chi*(1+a**2/mag2)
    y = eta*(1-a**2/mag2)
    return Body(np.array([x,y]).T)

def karman_trefftz_foil(xcenter=-.1, ycenter=0, a=.1, angle_deg=10, num_points=32):
    """Return a Karman-Trefftz foil Body.

    The Karman-Trefftz foil is a modified version of the Joukowski
    foil but with a nonzero interior angle --- rather than a cusp ---  at the
    trailing edge.  Refer to [1]_ for details.

    Parameters
    ----------
    xcenter, ycenter, a : float.
        The same as in joukowski_foil().

    angle_deg : float
        The interior angle, in degrees, at the trailing edge.

    num_points : int
        Number of points along the boundary

    See Also
    --------
    joukowski_foil()

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Joukowsky_transform
    """

    angle_rad = angle_deg*np.pi/180
    n = 2-angle_rad/np.pi
    t = np.linspace(0,2*np.pi,num_points)
    ctr = xcenter + 1j*ycenter
    r = np.linalg.norm(ctr-a)
    zeta = ctr+r*np.exp(1j*t)
    mag2 = np.linalg.norm(zeta)
    z = n*((1+1/zeta)**n+(1-1/zeta)**n)/((1+1/zeta)**n-(1-1/zeta)**n)
    x = [w.real for w in z]
    y = [w.imag for w in z]
    return Body(np.array([x,y]).T)

def van_de_vooren_foil(semichord=1.0, thickness=0.15, angle_deg=5,
num_points=32):
    """Return a van de Vooren foil Body.

    Refer to section 6.6 of [1]_

    Parameters
    ----------
    semichord : float
        half the chord c, so c=2*semichord

    thickness : float
        vertical thickness as a fraction (0 < thickness < 1) of the semichord

    angle_deg : float
        interior angle, in degrees, at the trailing edge

    num_points : int
        number of points along the boundary

    References
    ----------
    .. [1] Katz, Joseph and Plotkin, Allen, "Low-Speed Aerodynamics", 2nd Ed.,
       Cambridge University Press, 2001.
    """

    k = 2-(angle_deg*np.pi/180)
    a = 2*semichord*((1+thickness)**(k-1))*2**(-k)
    t = np.linspace(0,2*np.pi,num_points)
    num = (a*(np.cos(t)-1)+1j*a*np.sin(t))**k
    den = (a*(np.cos(t)-thickness)+1j*a*np.sin(t))**(k-1)
    z = (num/den)+semichord
    x = [w.real for w in z]
    y = [w.imag for w in z]
    return Body(np.array([x,y]).T)

def naca_airfoil(code, num_points=20, te_clamp=False, uniform=False, chord=1):
    """Returns a NACA 4-digit series foil.

    Refer to [1]_ for a detailed description and formulas.

    Parameters:
    -----------
    code_str : string
        The 4-digit NACA code describing the foil.  If the first digit is M,
        the second digit is P, and the last two digits are TH, then:
        M = maximum camber, as a percentage of the chord
        P = distance of max camber from leading edge in tens of percent of chord
        TH = thickenss of the airfoil as a percentage of chord

        For example, 2315 means a cambered airfoil whose max camber is 2% of the
        chord, located 30% chordwise from the leading edge, and whose thickness
        is 15% of the chord.

    num_points : int
        The number of points along each surface of the foil. There will be
        2*num_points-1 points returned, with num_points along the edge and
        num_points-1 along the bottom edge.

    te_clamp : boolean
        Trailing edge clamp.  When false, the trailing edge has a slight
        nonzero thickness.  When true, the foil adjusted so that the trailing
        edge has exactly zero thickness.

    uniform : boolean
        Distribution of points along chord.  When false, points are uniformly
        distributd along the chord.  When true, points are distributed more
        densly near leading edge (where the curvature is large).

    chord : double
        Length of chord

    Returns:
    --------
    A two-column matrix q, whose first column encodes the x coordinates and
    whose second column encodes the y coordinates of the points on the foil.
    The rows are ordered so that the points traverse the foil in the
    counterclockwise fashion from the trailing edge to the leading edge and
    back again.

    References:
    -----------
    .. [1] https://en.wikipedia.org/wiki/NACA_airfoil

    Example:
    --------
    q = naca_foil('2315',50)
 """
    code_str = "%04d" % int(code)
    if len(code_str) != 4:
        raise ValueError("NACA designation is more than 4 digits")
    m = .01*int(code_str[0])
    p = .1*int(code_str[1])
    thick = .01*int(code_str[2:4])
    if (uniform is True):
        x = np.linspace(0,chord,num_points)
    else:
        t = np.linspace(0,0.5*np.pi,num_points)
        x = chord*(1-np.cos(t))

    # Construct the thickness line, yt
    xc = x/chord
    coefs = [-.1015, .2843, -.3516, -.1260, 0]
    sqrt_coef = .2969
    if (te_clamp is True):
        coefs[0] = -.1036
    yt = 5*thick*chord*(sqrt_coef*np.sqrt(xc)+np.polyval(coefs,xc))

    # Avoid unnecessary work (and avoid divide-by-zero) when no camber
    if p:
        # Construct the camber line, yc
        front = np.where(x <= p*chord)
        back = np.where(x > p*chord)
        yc = np.zeros_like(x)
        yc[front] = (m/p**2)*x[front]*(2*p-xc[front])
        yc[back] = (m/(1-p)**2)*(chord-x[back])*(1+xc[back]-2*p)

        # Combine thickness and camber line to produce the NACA airfoil.
        # The usual formulas for the camber adjustment involve sin(arctan(.))
        # and cos(arctan(.)), but to avoid branch cuts in the arctangent
        # function, I use instead the equivalent Cartesian formulations:
        # sin(arctan(x)) = x/sqrt(1+x^2)
        # cos(arctan(x)) = 1/sqrt(1+x^2)
        dycdx = np.zeros_like(x)
        dycdx[front] = (2*m/p**2)*(p-xc[front])
        dycdx[back] = (2*m/(1-p)**2)*(p-xc[back])
        z = np.sqrt(1+dycdx**2)
        xU = x - yt*dycdx/z # X coordinates along upper surface
        xL = x + yt*dycdx/z # X coordinates along lower surface
        yU = yc + yt/z      # Y coordinates along upper surface
        yL = yc - yt/z      # Y coordinates along lower surface
        x = np.hstack([xU[-1:0:-1],xL])
        y = np.hstack([yU[-1:0:-1],yL])
    else:
        x = np.hstack([x[-1:0:-1],x])
        y = np.hstack([yt[-1:0:-1],-yt])
    # Note: The [-1:0:-1] indexing above accomplishes two things: (1) it
    # reorders the vectors so the foil is described counterclockwise from the
    # trailing edge to the leading edge and back again, and (2) it omits the
    # repeated entry at the leading edge that would otherwise be present from
    # concatenating two copies of x.  It is important not to have two identical
    # successive entries, or else the matrix of influence coefficients in the
    # panel (boundary element) method becomes ill conditioned.

    return Body(np.array([x,y]).T)

class TransformedBody(object):
    """Base class for rigid (Euclidean) transformations of existing bodies
    """
    def __init__(self, body, angle=0, displacement=(0,0)):
        """angles are clockwise, in degrees"""
        self._parent = body
        self._body = body.get_body()
        self._motion = RigidMotion(-angle * np.pi / 180, displacement)

    def get_body(self):
        return self._body

    def get_motion(self):
        self._update()
        return self._motion.compose(self._parent.get_motion())

    def set_motion(self, value):
        self._motion = value

    @property
    def time(self):
        return self._body.time

    @time.setter
    def time(self, value):
        self._body.time = value

    def _update(self):
        # update body motion: subclasses override this
        pass

    def get_points(self, body_frame=False):
        q = self._body.get_points()
        if body_frame:
            return q
        return self.get_motion().map_position(q)

class Pitching(TransformedBody):
    """Sinusoidal pitching for an existing body
    """
    def __init__(self, body, amplitude, frequency, phase=0.):
        """amplitude and phase given in degrees"""
        super(Pitching, self).__init__(body)
        self._amplitude = amplitude * np.pi / 180
        self._frequency = frequency
        self._phase = phase * np.pi / 180

    def _update(self):
        theta = self._frequency * self.time + self._phase
        alpha = self._amplitude * np.sin(theta)
        alphadot = self._amplitude * self._frequency * np.cos(theta)
        self.set_motion(RigidMotion(-alpha, (0,0), -alphadot, (0,0)))

class Heaving(TransformedBody):
    """Sinusoidal heaving for an existing body
    """
    def __init__(self, body, displacement, frequency, phase=0.):
        super(Heaving, self).__init__(body)
        self._displacement = np.array(displacement, dtype="float64")
        self._frequency = frequency
        self._phase = phase * np.pi / 180

    def _update(self):
        theta = self._frequency * self.time + self._phase
        x = self._displacement * np.sin(theta)
        xdot = self._displacement * self._frequency * np.cos(theta)
        self.set_motion(RigidMotion(0, x, 0, xdot))


# -*- coding: utf-8 -*-
# PACKAGE TOOL

MIN_LEN_PT4FRAME = 6

# 四通道组帧
def pt4_makeframe(frame, channel=0):
    chanstr = str(channel)
    chanstr = chanstr.zfill(2)

    frame = "6833" + chanstr + frame + "16"
    return frame

# 四通道解帧
def pt4_dealframe(frame):
    l = [False]
    if len(frame) < MIN_LEN_PT4FRAME:
        return l
    frame = frame.upper()

    if frame[0:4] == '6833':
        l[0] = True
        l += [frame[2:4]]  # ctrl
        l += [frame[4:-2]]  # data 去除 16
        return l

    for i in range(0, len(frame), 2):
        if frame[i:i + 2] == '68':
            dataLen = int(frame[i + 4:i + 6], 16) * 2
            if (frame[(i + dataLen + 8):(i + dataLen + 8) + 2] == '16'):
                l[0] = True
                l += [frame[i + 2:i + 4]]  # ctrl
                l += [dataLen]  # len
                l += [frame[(i + 8):-2]]  # data
                return l
    return l

def pt4_dealsenddataframe(frame):
    dataList = []

    dataList += [frame[0:2]]  # 通道号
    dataList += [frame[2:]]  # 无线报文（不包含物理层）
    return dataList

def pt4_dealrecvdataframe(frame):
    dataList = []

    dataList += [frame[0:2]]  # 通道号
    dataList += [frame[2:4]]  # 信道索引
    dataList += [frame[4:6]]  # 接收信号强度
    dataList += [frame[6:]]  # 无线报文（包含物理层）
    return dataList

def pt4_dealframemain(frame):
    frame = frame.replace(' ', '')
    l = pt4_dealframe(frame)
    if l[0]:
        if l[1] == '20':  # 数据接收帧
            l = l[:-2] + pt4_dealrecvdataframe(l[-1]) # 取list最后一个元组
        elif l[1] == '33':
            l = l[:-2] + pt4_dealsenddataframe(l[-1]) #
    return l

if __name__ == '__main__':
    frame = "11 22 33 44 55 66"
    frame = frame.replace(' ', '')

    frame = pt4_makeframe(frame, 3)
    print(frame)

    frame = '68 33 00 01 0C 0A FF FF 01 00 04 03 02 01 AA AA AA AA AA AA 00 0C 01 00 04 03 02 01 AA AA AA AA AA AA ' \
            'F1 01 09 04 16 '

    '''
    frame = "68 20 39 00 00 00 17 33 00 33 01 0C 25 FF FF 09 00 00 55 07 00 01 00 04 03 02 01 01 0C 09 00 00 55 07 " \
            "00 01 00 04 03 02 01 21 11 10 02 09 00 00 55 07 00 32 58 29 08 70 41 20 59 65 B7 16"
    '''
    '''
    frame = frame.replace(' ', '')
    l = pt4_dealframe(frame)
    print(l)
    if l[0] == '20': # 数据接收帧
        f = pt4_dealdataframe(l[2])
        print(f)
    '''
    l = pt4_dealframemain(frame)
    print(l)
    print(l[-1])


#!/usr/bin/env python

from numbers import Number

def receive_polynomial(func):
    def wrapper(*args):
        if not isinstance(args[1], Polynomial) and not isinstance(args[1], Number):
            raise TypeError("Addition can only be perform on Polynomial object and real number")
        if isinstance(args[1], Number):
            if isinstance(args[1], complex):
                raise TypeError("Can not add complex number to polynomial")
            return func(args[0], Polynomial(args[1]))
        return func(*args)
    return wrapper

class Polynomial:
    def __init__(self, *coeffs):
        for c in coeffs:
            if not isinstance(c, Number):
                raise TypeError("One of the coefficient is not a number")
            if isinstance(c, complex):
                raise TypeError("One of the coefficient is a complex number")
        if len(coeffs) == 0:
            raise TypeError("There must be at least one coefficient")
        if coeffs[0] == 0 and len(coeffs) > 1:
            raise ValueError("The first coefficient can not be 0")
        self.coeffs = list(coeffs)

    def degree(self):
        return len(self.coeffs)-1 if self.coeffs[0] != 0 or len(self.coeffs) > 1 else None

    def __str__(self):
        if self.degree() is None:
            return '0'
        string = ""
        for i in xrange(0, len(self.coeffs)):
            c = self.coeffs[i]
            d = self.degree() - i
            if c != 0:
                string += ' + ' if c > 0 else ' - '
                if (c != 1 and c != -1) or d == 0:
                    string += str(c) if c > 0 else str(-c)
                if d > 0:
                    string += 'x'
                    if d > 1:
                        string += '^' + str(d)
        if string.index(" + ") == 0:
            string = string[3:]
        return string

    def evaluate(self, x):
        if not isinstance(x, Number):
            raise TypeError("x must be an number")
        if isinstance(x, complex):
            raise TypeError("x must not be a complex number")
        if self.degree() is None:
            return 0
        s = 0
        d = self.degree()
        for i in xrange(0, d + 1):
            s += self.coeffs[i] * (x ** (d - i))
        return s

    @receive_polynomial
    def __eq__(self, other):
        if self.degree() != other.degree():
            return False
        if self.degree() is None:
            return True
        for i in xrange(0, self.degree() + 1):
            if self.coeffs[i] != other.coeffs[i]:
                return False
        return True

    @receive_polynomial
    def __add__(self, other):
        sd = self.degree()
        od = other.degree()
        coeffs = []
        if sd < od:
            return other.__add__(self)
        if od is None:
            return Polynomial(*self.coeffs)
        for i in xrange(0, sd - od):
            coeffs.append(self.coeffs[i])
        for i in xrange(0, od + 1):
            coeffs.append(other.coeffs[i] + self.coeffs[i + sd - od])
        return Polynomial(*coeffs)

    @receive_polynomial
    def __mul__(self, other):
        sd = self.degree()
        od = other.degree()
        if sd < od:
            return other.__mul__(self)
        if od is None:
            return Polynomial(0)
        if od == 0:
            c = other.coeffs[0]
            coeffs = [c*x for x in self.coeffs]
            return Polynomial(*coeffs)
        p = Polynomial(0)
        for i in xrange(0, od+1):
            tmp = self.__mul__(other.coeffs[i])
            for j in xrange(0, od - i):
                tmp.coeffs.append(0)
            p += tmp
        return p

    @receive_polynomial
    def __sub__(self, other):
        return self.__add__(other.__mul__(-1))

p = Polynomial(1, -5, 6)
q = Polynomial(1, 1)


import pandas as pd
import pdb
import numpy as np
import random
import math
import argparse
import tensorflow as tf
import matplotlib.pyplot as plt
from keras import losses
from keras import models
from keras import regularizers
from keras.layers.core import Dense
from keras.layers.core import Dropout
from keras.layers.core import Flatten
from keras.layers.recurrent import LSTM
from keras.layers.recurrent import GRU
from keras.layers.convolutional import Conv1D
from keras.callbacks import TensorBoard
from keras.optimizers import adam
from keras.layers.advanced_activations import LeakyReLU
from shutil import copyfile

INPUT_COUNT = 40

def loadModel(model):
    try:
        model.load_weights("model.h5")
        print("model loaded")
    except OSError:
        print("can't find model file to load")

def saveModel(model):
    print("Saving model")
    try:
        copyfile('model.h5', 'model.h5.saved')
    except FileNotFoundError:
        print("didn't find model files to save")

    model.save_weights("model.h5", overwrite=True)

# generate a sequence of data, using x = sin(a*i). Passing in a and count
def getSineData(a, count):
    return np.array([math.sin(a * i) for i in range(0, count)])

# Given the time series data and data size, return the x,y data suitable for training
# x - time lagged by INPUT_COUNT, so for each time step we have INPUT_COUNT number of data points
# y - for each data point x, the data at the next time step
def getXY(data, total):
    x = data[0: total - INPUT_COUNT].reshape((total - INPUT_COUNT, 1))
    for i in range(1, INPUT_COUNT):
        x = np.concatenate((x, data[i: total - INPUT_COUNT + i].reshape((total - INPUT_COUNT, 1))), axis=1)

    y = data[INPUT_COUNT : total]
    return x,y

# Generate the training and evaluating data sets for data series sin(a*x)
def getSeries(a, trainCount, testCount=0):
    data = getSineData(a, trainCount+testCount)
    x,y = getXY(data, trainCount)
    if testCount > INPUT_COUNT:
        evalX, evalY = getXY(data[trainCount:], testCount)
    else:
        evalX, evalY = None, None
    return x, y, evalX, evalY

def getCNNSeries(a, trainCount, testCount):
    x, y, evalX, evalY = getSeries(a, trainCount, testCount)
    if testCount <= INPUT_COUNT:
        return x.reshape(x.shape[0], x.shape[1], 1), y, None, None
    return x.reshape(x.shape[0], x.shape[1], 1), y, evalX.reshape(evalX.shape[0], evalX.shape[1], 1), evalY

def buildFCModel():
    model = models.Sequential()
    model.add(Dense(100, input_shape=(INPUT_COUNT,)))
    model.add(LeakyReLU(alpha=0.03))
    model.add(Dense(100))
    model.add(LeakyReLU(alpha=0.03))
    model.add(Dense(1))

    model.compile(loss='mse', optimizer=adam(lr=0.0001))

    board = TensorBoard(log_dir='model', histogram_freq=1, write_graph=True, write_images=False)
    board.set_model(model)
    return model, board

def buildCNNModel():
    model = models.Sequential()
    model.add(Conv1D(100, 3, strides=1, input_shape=(INPUT_COUNT, 1)))
    model.add(LeakyReLU(alpha=0.03))
    model.add(Conv1D(100, 3, strides=1))
    model.add(LeakyReLU(alpha=0.03))
    model.add(Flatten())
    model.add(Dense(100))
    model.add(LeakyReLU(alpha=0.03))
    model.add(Dense(1))

    model.compile(loss='mse', optimizer=adam(lr=0.0001))

    board = TensorBoard(log_dir='model', histogram_freq=1, write_graph=True, write_images=False)
    board.set_model(model)
    return model, board

def buildLSTMModel():
    model = models.Sequential()
    model.add(LSTM(100, batch_input_shape=(1, 1, 1), return_sequences=True, stateful=True))
    model.add(LSTM(100, return_sequences=False, stateful=True))
    model.add(Dense(1))
    model.compile(loss='mse', optimizer=adam(lr=0.0001))

    board = TensorBoard(log_dir='model', histogram_freq=1, write_graph=True, write_images=False)
    board.set_model(model)
    return model, board

def testFC():
    model, board = buildFCModel()

    allX, allY, allEX, allEY = getSeries(0.06, 3000, 300)

    for i in range(1, 10):
        x, y, evalX, evalY = getSeries(0.06 + i * 0.006, 3000, 300)
        allX = np.concatenate((allX, x))
        allY = np.concatenate((allY, y))
        allEX = np.concatenate((allEX, evalX))
        allEY = np.concatenate((allEY, evalY))

    history = model.fit(x=allX, y=allY, validation_data=(allEX, allEY), batch_size=100, epochs=10, callbacks=[board])

    plotGenerated(model, 0.06)
    plotGenerated(model, 0.083)
    plotGenerated(model, 0.163)
    plotGenerated(model, 0.033)
    return

def testCNN():
    model, board = buildCNNModel()

    allX, allY, allEX, allEY = getCNNSeries(0.06, 3000, 300)

    for i in range(1, 10):
        x, y, evalX, evalY = getCNNSeries(0.06 + i * 0.006, 3000, 300)
        allX = np.concatenate((allX, x))
        allY = np.concatenate((allY, y))
        allEX = np.concatenate((allEX, evalX))
        allEY = np.concatenate((allEY, evalY))

    history = model.fit(x=allX, y=allY, validation_data=(allEX, allEY), batch_size=100, epochs=10, callbacks=[board])

    plotGeneratedCNN(model, 0.06)
    plotGeneratedCNN(model, 0.083)
    plotGeneratedCNN(model, 0.163)
    plotGeneratedCNN(model, 0.033)
    return

def testLSTM():
    model, board = buildLSTMModel()

    total = 3300
    trainSize = 3000

    loadModel(model)

    for epoch in range(0, 10):
        for i in range(0, 10):
            data = getSineData(0.06 + i * 0.006, total)
            x = data[0:trainSize].reshape((trainSize, 1, 1))
            y = data[1:trainSize+1]
            evalX = data[trainSize:total-1].reshape((total-1-trainSize, 1, 1))
            evalY = data[trainSize+1:total]
            model.fit(x=x, y=y, validation_data=(evalX, evalY), batch_size=1, epochs=1, shuffle=False)
            model.reset_states()

    saveModel(model)

    plotGeneratedLSTM(model, 0.06)
    plotGeneratedLSTM(model, 0.083)
    plotGeneratedLSTM(model, 0.163)
    plotGeneratedLSTM(model, 0.033)
    return

def render(y, predicted, a, count):
    plt.grid()
    plt.plot(y[0:count])
    plt.plot(predicted[0:count], 'go')
    plt.title("y=sin({}*x)".format(a))
    plt.savefig("plt-{}.png".format(a))
    plt.show()

# Create a series of data points using parameter a (as in sin(a*i)). Predict y using the real
# values of x for each data point. Plot out y against predicted data points.
def plotPredicted(model, a):
    model.reset_states()
    x, y, eX, eY = getSeries(a, 300)
    predicted = model.predict(x=x)
    render(y, predicted, a, 100)

# Start a series of data using parameter a (as in sin(a*i)). Using the data as starting point,
# predict the next data in the time series. Then predict more using the generated data points
# form earlier predictions.
def plotGenerated(model, a):
    x, y, eX, eY = getSeries(a, 300)
    predicted = np.zeros((100,))
    gx = x[0].copy()
    for i in range(0, 100):
        predicted[i] = model.predict(x=np.array([gx]))
        gx = np.append(gx[1:], predicted[i])

    render(y, predicted, a, 100)

def plotGeneratedCNN(model, a):
    x, y, eX, eY = getCNNSeries(a, 300, 0)
    predicted = np.zeros((100,))
    gx = x[0].copy()
    for i in range(0, 100):
        predicted[i] = model.predict(x=np.array([gx]))
        gx = np.append(gx[1:], np.array([[predicted[i]]]), axis=0)

    render(y, predicted, a, 100)

def plotGeneratedLSTM(model, a):
    model.reset_states()
    data = getSineData(a, 300)
    x = data[0:100]
    # Build up LSTM state
    model.predict(x=x.reshape((100, 1, 1)), batch_size=1)

    y = data[101:201]
    predicted = np.zeros((100,))
    gx = data[0]
    for i in range(100, 200):
        predicted[i-100] = model.predict(x=gx.reshape(1, 1, 1))
        gx = predicted[i-100]

    render(y, predicted, a, 100)

def main():
    parser = argparse.ArgumentParser(description='Trying to model unseen sine function')
    parser.add_argument("-m", "--model", help="fc/cnn/lstm")

    args = parser.parse_args()
    if args.model == 'fc':
        testFC()
    elif args.model == 'cnn':
        testCNN()
    elif args.model == 'lstm':
        testLSTM()
    else:
        print('unknown model')
    return

if __name__ == '__main__':
    main()


#  Raymond Kirk (Tunstill) Copyright (c) 2020
#  Email: ray.tunstill@gmail.com

# Provides the container for easily handling topic_store data. Exposed by topic_store.__init__

from __future__ import absolute_import, division, print_function

import bson
from datetime import datetime

import genpy
import roslib.message
import rospy
from genpy import Message as ROSMessage

try:
    from collections import Mapping as MappingType
except ImportError:
    from collections.abc import Mapping as MappingType

__all__ = ["TopicStore", "MongoDBParser", "DefaultTypeParser", "GenericPyROSMessage", "MongoDBReverseParser"]

_session_id = bson.ObjectId()

def time_as_ms(timestamp=None):
    if timestamp is None:
        timestamp = datetime.now()
    return (timestamp - datetime.fromtimestamp(0)).total_seconds()

def ros_time_as_ms(timestamp=None):
    if timestamp is None:
        timestamp = rospy.Time.now()
    return timestamp.to_sec()

def idx_of_instance(obj, instance_checks):
    if isinstance(instance_checks, tuple):
        instance_checks = (instance_checks,)
    for idx, _type in enumerate(instance_checks):
        if isinstance(obj, _type):
            return idx
    return -1

class DefaultTypeParser:
    """Type coercion utility class.

        Examples:
        >>> parser = DefaultTypeParser()
        >>> print(parser([1, 1, 1])) # Output: [1, 1, 1]
        >>> parser.add_converters({int: float}) # Parser will now parse all ints as floats
        >>> print(parser([1, 1, 1])) # Output: [1.0, 1.0, 1.0]
    """

    def __init__(self):
        # Lookup of type conversions (overriding classes should update the dict)
        self._core_types = [dict, list, tuple, set]
        self._type_converters = {t: self.__parse_dict if t is dict else self.__parse_list for t in self._core_types}
        self._instance_converters = ()
        self.add_converters({ROSMessage: GenericPyROSMessage.as_dict, genpy.Time: GenericPyROSMessage.as_dict,
                             genpy.Duration: GenericPyROSMessage.as_dict}, instance=True)

    def add_converters(self, type_to_converter_map, instance=False, replace_existing=True):
        """Adds more conversion functions. Must pass a dict of type: converter function pairs.

        Inheriting classes can use this method to support other type conversions by default.

        Args:
            type_to_converter_map (dict): Dict of type to callable returning a new type
            instance (bool): If true the converter will check these types with isinstance(data, type) if direct type
                doesn't have a conversion
            replace_existing: If false will raise a ValueError if a mapping already exists
        """
        for t in type_to_converter_map.keys():
            if t in self._core_types:
                raise ValueError("'{}' is a core type, cannot override the basic iterables".format(t))
        if not replace_existing and any(i in self._type_converters for i in type_to_converter_map.keys()):
            for key in type_to_converter_map.keys():
                if key in self._type_converters:
                    raise ValueError("Mapping from '{}' already exists by '{}'".format(key, self._type_converters[key]))
        self._type_converters.update(type_to_converter_map)
        if instance:
            self._instance_converters = self._instance_converters + tuple(type_to_converter_map.keys())

    def __call__(self, data):
        return self.parse_type(data)

    def parse_type(self, data):
        # Explicit conversion
        if type(data) in self._type_converters:
            return self._type_converters[type(data)](data)

        # If no explicit type, look for instance of
        instance_idx = idx_of_instance(data, self._instance_converters)
        if instance_idx != -1:
            return self._type_converters[self._instance_converters[instance_idx]](data)

        # No conversion just return the original data
        return data

    def __parse_dict(self, data):
        return {str(k): self.parse_type(v) for k, v in data.items()}

    def __parse_list(self, data):
        return [self.parse_type(i) for i in data]

class MongoDBParser(DefaultTypeParser):
    """Parser to ensure data types are supported in a database environment"""

    def __init__(self):
        DefaultTypeParser.__init__(self)
        # Conversion functions for bytes arrays (represented as string in python <3) and times
        self.add_converters({
            str: MongoDBParser.bytes_to_bson_if_not_unicode
        })

    @staticmethod
    def bytes_to_bson_if_not_unicode(s):
        # If it's a utf-8 string then keep as string, otherwise convert to BSON
        # In python 2.7 bytes and str are equivalent so this is needed for np.arrays and ros arrays
        try:
            s.decode('utf-8')
        except UnicodeError:
            s = bson.binary.Binary(s)
        return s

class MongoDBReverseParser(DefaultTypeParser):
    """Parser to ensure data types are supported in a database environment"""

    def __init__(self):
        DefaultTypeParser.__init__(self)
        # Conversion functions for bytes arrays (represented as string in python <3) and times
        self.add_converters({
            unicode: str,  # Python2.7 is weird with strings and unicode (just replace)
            # bson.binary.Binary: self.bson_to_bytes,
        })

    # @staticmethod
    # def bson_to_bytes(s):
    #     return str(s)

class GenericPyROSMessage:
    """Generic container for ROSMessage/Python data elements (converts genpy.Message to python types)"""

    def __init__(self, data):
        self._data = data

    @staticmethod
    def as_dict(ros_msg):
        return GenericPyROSMessage(ros_msg).data

    @property
    def data(self):
        """If data is a genpy.Message return a python dict representation of it, else return the data"""
        # If data is not a ROSMessage then return (it must be a python type)
        data = self._data

        if not issubclass(type(data), (ROSMessage, genpy.Time, genpy.Duration)):
            return data

        # If data is a ROS message then it has to be serialised to python
        slot_names = [k for k in data.__slots__]

        # Preserve connection header for ROSBag conversion support
        if hasattr(data, "_connection_header"):
            slot_names.append("_connection_header")

        # Copy the message information to a dict representation
        slots = {k: getattr(data, k) for k in slot_names}

        # If the message recursively call GenericROSPyMessage to convert all sub-ROS msgs
        msg_dict = {k: GenericPyROSMessage.as_dict(v) for k, v in slots.items()}

        msg_type = getattr(data, "_type", None)
        if msg_type is None:
            if issubclass(type(data), genpy.Time):
                msg_type = "genpy.Time"
            elif issubclass(type(data), genpy.Duration):
                msg_type = "genpy.Duration"

        # Update the dict with some meta information
        msg_dict.update({"_ros_meta": {
            'time': ros_time_as_ms(),
            'type': msg_type,
        }})

        return msg_dict

    @data.setter
    def data(self, value):
        self._data = value

    @data.deleter
    def data(self):
        del self._data

    def save(self, data):
        """Updates the internal data. Function equivalent of the data property field."""
        self._data = data

class TopicStore:
    """Storage container for message data .dict or [] returns python objects, .msgs or () returns ROS messages"""

    def __init__(self, data_tree):
        if not isinstance(data_tree, dict):
            raise ValueError("Data tree must be a dict to construct a TopicStore")
        # Ensure passed data tree does not contain ROS msgs
        self.__data_tree = DefaultTypeParser()(data_tree)
        if "_id" not in self.__data_tree:
            self.__data_tree["_id"] = bson.ObjectId()
        if "_ts_meta" not in self.__data_tree:
            self.__data_tree["_ts_meta"] = dict(session=_session_id, sys_time=time_as_ms(), ros_time=ros_time_as_ms())
        # Cache for dict to ROS message parsing
        self.__msgs = None

    @property
    def dict(self):
        return self.__data_tree

    @property
    def msgs(self):
        if self.__msgs is None:
            self.__msgs = TopicStore.__dict_to_ros_msg_dict(self.dict)
        return self.__msgs

    # Expose document ID and meta fields
    @property
    def id(self):
        return self["_id"]

    @property
    def session(self):
        return self["_ts_meta"]["session"]

    @property
    def sys_time(self):
        return self["_ts_meta"]["sys_time"]

    @property
    def ros_time(self):
        return self["_ts_meta"]["ros_time"]

    # TopicStore()[item] returns python type
    def __getitem__(self, item):
        return self.dict[item]

    # TopicStore()(item) returns ros type
    def __call__(self, item):
        return self.msgs[item]

    @staticmethod
    def __get_size(obj, recurse=True, human_readable=True):
        """Sum size of object & members. Utility function for printing document size, used in __repr__."""
        from types import ModuleType, FunctionType
        from gc import get_referents
        import sys
        blacklisted_types = (type, ModuleType, FunctionType)

        if isinstance(obj, blacklisted_types):
            raise TypeError('getsize() does not take argument of type: ' + str(type(obj)))
        size = 0

        if recurse:
            seen_ids = set()
            objects = [obj]
            while objects:
                need_referents = []
                for obj in objects:
                    if not isinstance(obj, blacklisted_types) and id(obj) not in seen_ids:
                        seen_ids.add(id(obj))
                        size += sys.getsizeof(obj)
                        need_referents.append(obj)
                objects = get_referents(*need_referents)
        else:
            size = sys.getsizeof(obj)

        if not human_readable:
            return size

        for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
            if size < 1024.0:
                break
            size /= 1024.0
        return "{:.2f}{}B".format(size, unit)

    def __recurse_types(self, d=None, depth=1, tabs=1, sep='\n', print_size=False):
        """Used by __repr__ to recurse dict and print types and sizes"""
        s = ""
        if depth == 1:
            s += "TopicStore Object {}: {}".format(
                datetime.fromtimestamp(self.dict["_ts_meta"]["sys_time"]).strftime('%d-%m-%Y %H:%M:%S'), "{"
            )
        if d is None:
            d = self.msgs
        for k, v in d.items():
            s += "{}{}{}{}: ".format(sep, "\t" * depth, k, ("(" + self.__get_size(v) + ")") if print_size else "")
            if isinstance(v, dict):
                s += "{" + self.__recurse_types(v, depth + tabs, tabs, sep, print_size) + sep + "\t" * depth + "}"
            else:
                s += "{}".format(type(v))

        if depth == 1:
            s += sep + "}"
        return s

    def __repr__(self, print_size=False):
        return self.__recurse_types(self.msgs, print_size=print_size)

    @staticmethod
    def __convert_dict_to_msg(d):
        """Internal function for python dict->ros message conversion, basic support for lists and partial ROS types."""
        if isinstance(d, dict) and "_ros_meta" in d:
            msg_type = d["_ros_meta"]["type"]
            if msg_type in ["genpy.Time", "genpy.Duration"] and all(s in d for s in ["secs", "nsecs"]):
                cls = rospy.rostime.Time if "Time" in msg_type else rospy.rostime.Duration
                del d["_ros_meta"]
                cls = cls(**d)
            else:
                msg_class = roslib.message.get_message_class(msg_type)
                if not msg_class:
                    # TODO: Should this rospy.logwarn and just return python dict? Otherwise projection needed so it
                    #  doesn't error
                    raise rospy.ROSException("Cannot load message class for [{}].  Please ensure the relevant package "
                                             "is installed on your system.".format(msg_type))
                cls = msg_class()
                slot_names = list(msg_class.__slots__)
                # Support copying connection header for ROSBag support
                if hasattr(msg_class, "_connection_header") and "_connection_header" in d:
                    slot_names.append("_connection_header")
                for s in slot_names:  # or cls = msg_class(**v) after removing ros meta etc
                    try:
                        setattr(cls, s, d[s])
                    except KeyError as e:
                        # Here we accept that if the message type has changed that we cannot necessarily fill all slots
                        rospy.logwarn("Could not set slot '{}' for class '{}' maybe the message definitions are "
                                      "incompatible".format(s, cls))

            return cls
        elif isinstance(d, dict):
            for k, v in d.items():
                d[k] = TopicStore.__convert_dict_to_msg(v)
        elif isinstance(d, list):
            d = [TopicStore.__convert_dict_to_msg(i) for i in d]
        elif isinstance(d, (genpy.Time, genpy.Duration, ROSMessage)):
            for i in d.__slots__:
                setattr(d, i, TopicStore.__convert_dict_to_msg(getattr(d, i)))
        return d

    @staticmethod
    def __extract_nested_dict_keys(d, parents=None):
        """This function iterates over one dict and returns a list of tuples: (key, parent_keys).
        Useful for looping through a multidimensional dictionary.
        """
        r = []
        if parents is None:
            parents = []

        if isinstance(d, dict):
            for k, v in d.iteritems():
                if isinstance(v, dict):
                    r.extend(TopicStore.__extract_nested_dict_keys(v, parents + [k]))
                elif isinstance(v, list):
                    for i in range(len(v)):
                        r.extend(TopicStore.__extract_nested_dict_keys(v[i], parents + [k]))
                else:
                    r.append((k, parents))

        return r

    # TODO: This should be a depth first search because if a message has nested types, they may never be converted
    @staticmethod
    def __dict_to_ros_msg_dict(data_dict, ):
        """Internal function to convert key, value pairs in a dict to ROS message types if they contain meta."""

        def nested_set(dic, keys, fn):
            # Reduce dic to the last key and apply function to value
            for key_index, next_key in enumerate(keys[:-1]):
                # If the dic value becomes a list at any point then iterate over and finish the keys
                if isinstance(dic, (list, set)):
                    for d in dic:
                        nested_set(d, keys[key_index:], fn)
                else:  # Must be a dict if not a list (constraint of python<->ros types due to bson)
                    dic = dic.setdefault(next_key, {})
            # Only attempt to set if dic is a dict and key is in the key set
            if isinstance(dic, MappingType) and keys[-1] in dic:
                dic[keys[-1]] = fn(dic[keys[-1]])

        # Do a depth first based parsing by sorting the unpacked multi-dim keys by length
        keys = TopicStore.__extract_nested_dict_keys(data_dict)
        sorted_keys = sorted(keys, key=lambda sx: -len(sx[-1]))
        to_convert = [x for x in sorted_keys if "_ros_meta" in x[-1]]

        # Apply the function (python dict -> ROS message to all keys that contain ros_meta)
        for key, parent_keys in to_convert:
            nested_set(data_dict, parent_keys[:-1], TopicStore.__convert_dict_to_msg)

        # data_dict = TopicStore.__convert_dict_to_msg(data_dict)  # this was an old-hack

        return data_dict

    @staticmethod
    def __ros_msg_dict_to_list(ros_msg_dict, return_keys=False, parent=""):
        """Useful for getting all ROS messages as flat list/dict. Only messages with _connection_header are returned."""
        if not isinstance(ros_msg_dict, dict):
            return
        for key, value in ros_msg_dict.items():
            if isinstance(value, ROSMessage):
                if return_keys:
                    yield (parent + "." + key), value
                else:
                    yield value
            for ret in TopicStore.__ros_msg_dict_to_list(value, return_keys, key if not parent else parent + "." + key):
                yield ret

    def to_ros_msg_list(self):
        # TODO: Cache this operation until self.__data_tree updated
        return list(TopicStore.__ros_msg_dict_to_list(self.msgs))

    def flatten_ros_msg_dict(self):
        # TODO: Cache this operation until self.__data_tree updated
        return {k: v for k, v in TopicStore.__ros_msg_dict_to_list(self.msgs, return_keys=True)}


# uncompyle6 version 3.7.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: /Users/chschw/Workspace/django/lab/django-cms/site/statify/utils.py
# Compiled at: 2013-04-24 04:02:44
import requests

def url_is_valid(url):
    valid_codes = [
     200, 301, 302]
    request = requests.get(url)
    if request.status_code in valid_codes:
        return True
    else:
        return False


from config import *
from lib import *
from data.newsgroups20 import Newsgroup
from torch.utils.data import DataLoader
from models.CNNText_Inception import CNNText_inception
from tensorboardX import SummaryWriter
from torch import optim
import torch.nn.parallel
import tqdm
import torch
from dixitool.pytorch.module import functional as F
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
#
seed_everything(1995)
# tensorboardX
writer = SummaryWriter()

#gpu
output_device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

print(output_device)
#dataset train,val
#only train now
print("Start loading data")
#variable args comes from config.py
train_ds = Newsgroup(args.data.train_dir,train=True)
test_ds = Newsgroup(args.data.test_dir, train=False)
#dataloader
train_dl = DataLoader(train_ds,batch_size=args.data.dataloader.batch_size,shuffle=True,drop_last=True)
test_dl = DataLoader(test_ds,batch_size=args.data.dataloader.batch_size,shuffle=False)

print("Finish loading data")
net = CNNText_inception(args.model)
net.to(output_device)
net = nn.DataParallel(net, list(range(2)))
criterion = nn.CrossEntropyLoss()

    #optimizer

#loss function CrossEntropyLoss
optimizer = optim.SGD(net.parameters(), lr=args.train.lr , weight_decay=args.train.weight_decay, momentum=args.train.momentum, nesterov=True)

best_acc = 0.0
global_step = 0
for epoch in range(args.train.epochs):
    print("Epoch:{}/{}".format(epoch,args.train.epochs))
    #train
    net.train()
    for idx, data in tqdm.tqdm(enumerate(train_dl)):
        inputs, labels = data
        inputs = inputs.to(output_device)
        labels = labels.to(output_device)
        optimizer.zero_grad()

        outputs = net(inputs)

        loss = criterion(outputs,labels)
        loss.backward()

        optimizer.step()

        writer.add_scalar('train/train_loss',loss.item(),global_step)

        global_step += 1

    #val
    net.eval()
    corrects = 0
    for idx, data in enumerate(test_dl):
        inputs, labels = data
        inputs = inputs.to(output_device)
        labels = labels.to(output_device)
        with torch.no_grad():
            outputs = net(inputs)
            _, preds = torch.max(outputs,dim=1)
            corrects += torch.sum(preds == labels).cpu().item()

    #准确率
    total_acc = float(corrects) / len(test_ds)
    #tensorboardX可视化
    writer.add_scalar('data/val_acc',total_acc,epoch)

    #保存模型参数
    if total_acc>best_acc:
        best_acc = total_acc
        F.save_model('checkpoints', '%.2f' % total_acc, net)
        #保存模型

writer.export_scalars_to_json("./all_scalars.json")
writer.close()


from beamngpy import BeamNGpy, Scenario, Road, Vehicle, setup_logging

def main():
    beamng = BeamNGpy('localhost', 64256, home='F:\Softwares\BeamNG_Research_SVN')

    scenario = Scenario('GridMap', 'road_test')
    road_a = Road('custom_track_center', looped=False)
    nodes = [
        (0, 0, 0, 8),
        (125, 0, 0, 8),
        (250, -10, 0, 12)
    ]
    road_a.nodes.extend(nodes)
    scenario.add_road(road_a)

    road_b = Road('custom_track_center', looped=False)
    nodes = [
        (125, 0, 0,12 ),
        (250, -10, 0, 12)
    ]
    road_b.nodes.extend(nodes)
    scenario.add_road(road_b)

    road_c = Road('custom_track_center', looped=False)
    nodes = [
        (125, 125, 0, 8),
        (125, 0, 0, 8),
    ]
    road_c.nodes.extend(nodes)
    scenario.add_road(road_c)

    vehicle = Vehicle('ego', model='etk800', licence='PYTHON', colour='Black')
    scenario.add_vehicle(vehicle, pos=(0, 0, 0.163609), rot=(0, 0, 180))  # 0.163609 ,

    scenario.make(beamng)
    bng = beamng.open(launch=True)
    try:
        bng.load_scenario(scenario)
        bng.start_scenario()

        input('Press enter when done...')
    finally:
        bng.close()

if __name__ == '__main__':
    main()


# Jain, Kritika
# 1002-093-381
# 2017-10-25
# Assignment_04_03

import numpy
import math
import copy
import Jain_04_04

class cl_world:
    def __init__(self, objects=[], canvases=[]):
        self.objects = objects
        self.canvases = canvases
        # variables are initialized
        self.vertexes = []
        self.faces = []
        self.current_camera_array = [self.Camera()] # this hold data about all cameras, the first cam is created as default
        self.read_camera_file()
        self.current_camera = self.current_camera_array[0]  # this hold data about the current cam
        self.viewport = self.current_camera.camera_viewport
        self.window = [-1,-1,1,1]

    class Camera: # camera class with the default values
        camera_name = ""
        camera_type = "parallel"
        VRP = [0, 0, 0]
        VPN = [0, 0, 1]
        VUP = [0, 1, 0]
        PRP = [0, 0, 1]
        VRC = [-1, 1, -1, 1, -1, 1]
        camera_viewport = [0.1, 0.1, 0.4, 0.4]

    def add_canvas(self, canvas):
        self.canvases.append(canvas)
        canvas.world = self

    def map_to_viewport(self,point,viewport,window):
        if point != []:
            for i in range(0,2):
                point[i] = (point[i]*(viewport[i+2] - viewport[i])/(window[i+2]-window[i])+ (viewport[i+2]+viewport[i])/2)
        return point

    def map_to_volume(self, vertexes, volume):
        vertexes = copy.deepcopy(vertexes)
        for point in vertexes:
            for i in range(0, 3):
                point[i] = (point[i] / (volume[i + 1] - volume[i])) # + ( volume[i + 1] + volume[i]) / 2)
        return vertexes

    def map_XY(self, point):
        result =[]
        if point!= []:
            result=[point[0],point[1]] # projecting to xy
        else:
            result.append(None)

        return result

    def map_to_window(self, point, window, canvas):
        if point != []:
            point[0] = int(int(canvas.cget("width"))*((point[0]*(window[2]-window[0]) +(window[2]+window[0])/2)/(window[2]-window[0])))
            point[1] = int(int(canvas.cget("height")) * (((point[1])*(window[3]-window[1])+(window[3]+window[1])/2)/(window[3]-window[1]))) ##cget("height"))-
        return point

    def project_parralel(self,vertexes):
        # vertexes = copy.deepcopy(vertexes)
        o = numpy.asarray(self.current_camera.VRP)
        n = numpy.asarray(self.current_camera.VPN)
        u = numpy.asarray(self.current_camera.VUP)
        new_vertexes = []
        p = numpy.asarray(self.current_camera.PRP)
        matrix = [-numpy.cross(u, n), u, n] / numpy.sqrt(
            numpy.dot(numpy.cross(u, n), numpy.cross(u, n)))
        matrix1 = [numpy.cross(u, -(p - o)) / numpy.sqrt(
            numpy.dot(numpy.cross(u, p - o),
                      numpy.cross(u, p - o))), u,
                   -(p - o)]
        matrix2 = [[-2, 0, 0], [0, 2, 0], [0, 0, 0]]
        for point in vertexes:
            if point != []:
                numpy.asarray(point)
                point = numpy.dot(numpy.dot(numpy.dot(point - o, matrix), matrix1), matrix2) + o
                new_vertexes.append(point)
        return new_vertexes

    def prepare_port_view(self, polynom , canvas, window):
        polynom1 = [0,0,0,0]
        polynom1[0] = int(int(canvas.cget("width"))* polynom[0] )
        polynom1[1] = int(int(canvas.cget("height"))*polynom[1] )
        polynom1[2] = int(int(canvas.cget("width")) * polynom[2] )
        polynom1[3] = int(int(canvas.cget("height")) * polynom[3] )
        result = [polynom1[0],polynom1[1],polynom1[2],polynom1[1],polynom1[2],polynom1[3],polynom1[0],polynom1[3]]
        return result

    def create_graphic_objects(self, canvas):
        vertexes = copy.deepcopy(self.vertexes)
        vertexes = self.project_parralel(vertexes)  # data is projected and mapped to volume
        vertexes = self.map_to_volume(vertexes,self.current_camera.VRC)
        viewport_frame = self.prepare_port_view(self.viewport, canvas,self.window)
        self.objects = []
        self.objects.append(canvas.create_polygon(viewport_frame, fill="white", outline='black'))
        canvas.itemconfigure(self.objects[0], state='normal')
        if True:
            for face in self.faces:
                # all the polys are constructed
                self.objects.append(canvas.create_polygon([vertexes[face[0] - 1][0],vertexes[face[0] - 1][1],
                                                           vertexes[face[1] - 1][0],vertexes[face[1] - 1][1],
                                                           vertexes[face[2] - 1][0],vertexes[face[2] - 1][1]],
                                                           fill="red", outline='black'))

                # if at least 2 point of the poly is in the volume then the poly is drawn
                k = 0
                if Jain_04_04.clip_line_parallel(vertexes[face[0] - 1], vertexes[face[1] - 1]) != [] :
                    k=k+1
                if Jain_04_04.clip_line_parallel(vertexes[face[1] - 1],vertexes[face[2] - 1]) != [] :
                    k = k+1
                if Jain_04_04.clip_line_parallel(vertexes[face[2] - 1],vertexes[face[0] - 1]) != []:
                    k = k+1
                if k> 1:
                    if Jain_04_04.clip_line_parallel(vertexes[face[0] - 1], vertexes[face[1] - 1]) != []:
                        point1, point2 = Jain_04_04.clip_line_parallel(vertexes[face[0] - 1], vertexes[face[1] - 1])
                    if Jain_04_04.clip_line_parallel(vertexes[face[1] - 1],vertexes[face[2] - 1]) != []:
                        point2, point3 = Jain_04_04.clip_line_parallel(vertexes[face[1] - 1], vertexes[face[2] - 1])
                    if Jain_04_04.clip_line_parallel(vertexes[face[2] - 1],
                                                                      vertexes[face[0] - 1]) != []:
                        point3, point1 = Jain_04_04.clip_line_parallel(vertexes[face[2] - 1], vertexes[face[0] - 1])
                    # print(point1)
                    point1 = self.map_to_viewport(point1, self.viewport, self.window)
                    point3 = self.map_to_viewport(point3, self.viewport, self.window)
                    point2 = self.map_to_viewport(point2, self.viewport, self.window)
                    point1 = self.map_to_window(point1,self.window, canvas)
                    point3 = self.map_to_window(point3,self.window, canvas)
                    point2 = self.map_to_window(point2,self.window, canvas)
                    point1 = self.map_XY(point1)
                    point3 = self.map_XY(point3)
                    point2 = self.map_XY(point2)
                    new_coords = [point1[0], point1[1],
                                  point3[0], point3[1],
                                  point2[0], point2[1]]

                    canvas.coords(self.objects[self.faces.index(face)+1], new_coords)
                    canvas.itemconfigure(self.objects[self.faces.index(face)+1],  state='normal')
                else:
                    canvas.itemconfigure(self.objects[self.faces.index(face)+1], state='hidden')

    def redisplay(self, canvas, ):
            if self.objects !=[]:
                viewport_frame = self.prepare_port_view(self.viewport, canvas, self.window)
                canvas.coords(self.objects[0], viewport_frame )
            vertexes = copy.deepcopy(self.vertexes)
            vertexes = self.project_parralel(vertexes)
            vertexes = self.map_to_volume(vertexes, self.current_camera.VRC)
            for face in self.faces:
                # if the points are in the volume space (cliping)
                # if atleast 2 point of the poly is in the volume then the poly is drawn
                k = 0
                if Jain_04_04.clip_line_parallel(vertexes[face[0] - 1], vertexes[face[1] - 1]) != []:
                    k = k + 1
                if Jain_04_04.clip_line_parallel(vertexes[face[1] - 1], vertexes[face[2] - 1]) != []:
                    k = k + 1
                if Jain_04_04.clip_line_parallel(vertexes[face[2] - 1], vertexes[face[0] - 1]) != []:
                    k = k + 1
                if k > 1:
                    if Jain_04_04.clip_line_parallel(vertexes[face[0] - 1], vertexes[face[1] - 1]) != []:
                        point1, point2 = Jain_04_04.clip_line_parallel(vertexes[face[0] - 1],
                                                                               vertexes[face[1] - 1])
                    if Jain_04_04.clip_line_parallel(vertexes[face[1] - 1], vertexes[face[2] - 1]) != []:
                        point2, point3 = Jain_04_04.clip_line_parallel(vertexes[face[1] - 1],
                                                                               vertexes[face[2] - 1])
                    if Jain_04_04.clip_line_parallel(vertexes[face[2] - 1],
                                                             vertexes[face[0] - 1]) != []:
                        point3, point1 = Jain_04_04.clip_line_parallel(vertexes[face[2] - 1],
                                                                               vertexes[face[0] - 1])
                    point1 = self.map_to_viewport(point1, self.viewport, self.window)  # if the poly should be drawn it
                    point3 = self.map_to_viewport(point3, self.viewport, self.window)  # is projected to the viewport
                    point2 = self.map_to_viewport(point2, self.viewport, self.window)  # and then projected to XY
                    point1 = self.map_to_window(point1, self.window, canvas)
                    point3 = self.map_to_window(point3, self.window, canvas)
                    point2 = self.map_to_window(point2, self.window, canvas)
                    point1 = self.map_XY(point1)
                    point3 = self.map_XY(point3)
                    point2 = self.map_XY(point2)
                    new_coords = [point1[0], point1[1],
                                  point3[0], point3[1],
                                  point2[0], point2[1]]

                    canvas.coords(self.objects[self.faces.index(face) + 1], new_coords)
                    canvas.itemconfigure(self.objects[self.faces.index(face) + 1], state='normal')
                else:  # else it is hidden
                    canvas.itemconfigure(self.objects[self.faces.index(face) + 1], state='hidden')

    def rotate(self, angle, start_point, end_point, vertexes_original):

        def rotation_matrix(vector, theta):  # rotation matrix constructed here
            vector = numpy.asarray(vector)
            vector = vector / math.sqrt(numpy.dot(vector, vector))
            a = math.cos(theta / 2.0)
            b, c, d = -vector * math.sin(theta / 2.0)
            aa, bb, cc, dd = a * a, b * b, c * c, d * d
            bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d
            return numpy.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)],
                                 [2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)],
                                 [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]])

        vertexes = copy.deepcopy(vertexes_original[:])
        vector = [0, 0, 0]
        for i in range(3):
            vector[i] = float(end_point[i]) - float(start_point[i]) # vector for rotation constructed
        vectro_length = (vector[0] ** 2 + vector[1] ** 2 + vector[2] ** 2) ** (0.5) # vector length
        for i in range(3):  # vector normalized
            vector[i] = vector[i] / (vectro_length)
        vertexes1 =[]
        angle = angle * math.pi/180
        for vertex in vertexes:  # rotation is made as multiplication of matrices
            vertex1 = numpy.dot(rotation_matrix(vector, angle),vertex)
            vertexes1.append(vertex1)
        return vertexes1

    def translate_vector(self, translate, vertexes_original :list):
        vertexes = copy.deepcopy(vertexes_original[:])
        for vertex in vertexes:
            for i in range(3):  # translation
                vertex[i] = vertex[i] + translate[i]
        return vertexes

    def scale(self, vector, scale, vertexes_original):
        vertexes = copy.deepcopy(vertexes_original[:])
        for vertex in vertexes:  # and shift
            for i in range(3):  # first we subtract the point
                vertex[i] = vertex[i] - vector[i]
        scale_matrix = [[scale[0], 0, 0], [0, scale[1], 0], [0, 0, scale[2]]]  # scaling matrix
        vertexes1 = []
        for vertex in vertexes:
            vertex1 = numpy.dot(scale_matrix, vertex)
            vertexes1.append(vertex1)
        for vertex in vertexes1:
            for i in range(3):  # and then we add it (after scale)
                vertex[i] = vertex[i] + vector[i]
        return vertexes1

    def read_camera_file(self): # reads camera file on start
        number_of_cameras = -1
        with open("cameras.txt") as f:
            file_lines = f.readlines()
        file_lines = [x.strip() for x in file_lines]
        for line in file_lines:
            if line[0] == "c":
                number_of_cameras += 1
                self.current_camera_array[number_of_cameras] = self.Camera()
            if line[0] == "i":
                self.current_camera_array[number_of_cameras].camera_name = prepare_data(line, type="str")
            if line[0] == "t":
                self.current_camera_array[number_of_cameras].camera_type = prepare_data(line,type="str")
            if line[0] == "r":
                self.current_camera_array[number_of_cameras].VRP = prepare_data(line,type="float")
            if line[0] == "n":
                self.current_camera_array[number_of_cameras].VPN = prepare_data(line,type="float")
            if line[0] == "u":
                self.current_camera_array[number_of_cameras].VUP = prepare_data(line,type="float")
            if line[0] == "p":
                self.current_camera_array[number_of_cameras].PRP = prepare_data(line,type="float")
            if line[0] == "s":

                self.current_camera_array[number_of_cameras].camera_viewport = prepare_data(line,type="float")

            if line[0] == "w":
                self.current_camera_array[number_of_cameras].VRC = prepare_data(line, type="float")

        # viewport_frame = self.prepare_port_view(self.viewport, self.canvas, self.window)

        # self.objects = []
        # self.objects.append(self.canvas.create_polygon(viewport_frame, fill="white", outline='black'))
        # self.canvas.itemconfigure(self.objects[0], state='normal')

def prepare_data(str, type="int"):  #unnecessary parts of string are removed
    a_list = str.split()
    a_list.pop(0)
    for i in a_list:
        if type == "int":
            a_list[a_list.index(i)] = int(a_list[a_list.index(i)])
        if type == "float":
            a_list[a_list.index(i)] = float(a_list[a_list.index(i)])
        if type =="str":
            pass
    return a_list

# Referred to this video (https://www.youtube.com/watch?v=I8o4kK9QRL4) for rotational matrix and parallel projection


# -*- coding: utf-8 -*-
import textwrap

class ConfigError(Exception):
    """Raised when configuration is bad
    """

def conflict_keyfunc(action):
    codeinfo = action.codeinfo()
    if codeinfo is None:
        return 0
    filename, lineno, function, sourceline = codeinfo
    return (filename, lineno)

class ConflictError(ConfigError):
    """Raised when there is a conflict in configuration.
    """
    def __init__(self, actions):
        actions.sort(key=conflict_keyfunc)
        self.actions = actions
        result = [
            'Conflict between:']
        for action in actions:
            codeinfo = action.codeinfo()
            if codeinfo is None:
                continue
            filename, lineno, function, sourceline = codeinfo
            result.append('  File "%s", line %s' % (filename, lineno))
            result.append('    %s' % sourceline)
        msg = '\n'.join(result)
        super(ConflictError, self).__init__(msg)

class AutoImportError(ConfigError):
    """Raised when Morepath fails to import a module during
    autoconfig/autosetup.
    """

    def __init__(self, module_name):

        msg = """\
            Morepath wanted to import '{}' during auto-configuration, but
            no such module could be imported.

            Make sure your module name matches the setup.py name, or use
            manual configuration:

                import yourmodule
                import morepath

                config = morepath.setup()
                config.scan(yourmodule)
                config.commit()

            For more information have a look at the 'morepath.autoconfig' docs.
        """

        msg = textwrap.dedent(msg).format(module_name)
        super(AutoImportError, self).__init__(msg)

class DirectiveReportError(ConfigError):
    """Raised when there's a problem with a directive.
    """
    def __init__(self, message, action):
        codeinfo = action.codeinfo()
        result = [message]
        if codeinfo is not None:
            filename, lineno, function, sourceline = codeinfo
            result.append('  File "%s", line %s' % (filename, lineno))
            result.append('    %s' % sourceline)
        msg = '\n'.join(result)
        super(DirectiveReportError, self).__init__(msg)

class DirectiveError(ConfigError):
    pass

class ResolveError(Exception):
    """Raised when path cannot be resolved
    """

class ViewError(ResolveError):
    """Raised when a view cannot be resolved
    """

class TrajectError(Exception):
    """Raised when path supplied to traject is not allowed.
    """

class LinkError(Exception):
    """Raised when a link cannot be made.
    """

class TopologicalSortError(Exception):
    pass


"""
Author: Nina del Rosario
Date: 7/18/2020
Script for exporting station ts with xarray

Need to do:
ERA5, SMPL3E, ASCAT H115

UPDATE_DESCRIPTION

"""
import os
import sm_tools as tools
import sm_config as config
import xarray as xr

output_root = r"..\test_output_data\station_csv"
log_file = os.path.join(output_root, "log_file.csv")

icos_readers = tools.get_icos_readers(config.icos_input_dir)
ismn_readers = tools.get_ismn_readers(config.ismn_input_dir)
# use this as a parameter below if you want to analyze both ICOS and ISMN
station_list = icos_readers + ismn_readers

product = "ERA5_0-1"
# product = "ERA5_0-25"
output_dir = os.path.join(output_root, product)
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

f = r"..\input_data\ERA5-Land\0-1_ERA5-Land_hourly.nc"
# f = r"..\input_data\ERA5-Land\0-25_ERA5-Land_hourly.nc"
ds = xr.open_dataset(f)

for station in station_list:
    station_name = station.station
    print(station_name)
    ts = ds['swvl1'].sel(latitude=station.latitude, longitude=station.longitude, method='nearest')
    ts_filename = tools.get_station_ts_filename(station)
    ts_file = os.path.join(output_dir, ts_filename)
    ts_pandas = ts.to_pandas()
    ts_pandas.rename('swvl1', inplace=True)
    ts_pandas.to_csv(ts_file)


from dataclasses import dataclass
from typing import List

@dataclass
class Point:
    x: int
    y: int

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

    def __str__(self):
        return f"({self.x}, {self.y})"

@dataclass
class Maze:
    inside_maze: list
    is_free: list

class PathFinder:
    @staticmethod
    def generate_random_world():
        max_x, max_y = 4, 4
        maze_points = [Point(x, y) for x in range(max_x) for y in range(max_y)]
        return maze_points, maze_points

    def get_path_to_target(self, maze: Maze, start: Point, target: Point):
        prev = {}
        source = start
        while source:
            if not prev.get(str(source)):
                prev[str(source)] = self.get_next_step_to_target(maze, source, target)
            if prev[str(source)]:
                yield prev[str(source)]
            source = prev[str(source)]

    def get_next_step_to_target(self, maze: Maze, source: Point, target: Point):
        queue = [target, ]
        used = [target, ]
        while len(queue) > 0:
            point = queue.pop(0)
            for neighbour in self.get_neighbours(point, maze):
                if neighbour in used:
                    continue
                if neighbour == source:
                    return point
                queue.append(neighbour)
                used.append(neighbour)

        return None

    @staticmethod
    def get_neighbours(point: Point, maze: Maze) -> List[Point]:
        offsets = [Point(0, 1), Point(1, 0), Point(-1, 0), Point(0, -1)]
        points = [point + offset for offset in offsets]
        return [
            point
            for point in points
            if point in maze.inside_maze and point in maze.is_free
        ]


from flask import Flask
from flask import request
from flask import render_template

import calculation as Distance

app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template("basic-view.html")

@app.route('/', methods=['POST'])
def my_form_post():
    point_A_text = request.form['point-A']
    point_B_text = request.form['point-B']

    point_A_lat, point_A_lon = float(point_A_text.split(',')[0]), float(point_A_text.split(',')[1])
    point_B_lat, point_B_lon = float(point_B_text.split(',')[0]), float(point_B_text.split(',')[1])

    euclid_distance = Distance.euclidean_distance(point_A_lat, point_A_lon, point_B_lat, point_B_lon)
    greatcircle_distance = Distance.great_circle_distance(point_A_lat, point_A_lon, point_B_lat, point_B_lon)
    vincenty_distance = Distance.vincenty_distance(point_A_lat, point_A_lon, point_B_lat, point_B_lon)

    print (euclid_distance)
    print (greatcircle_distance)
    print (vincenty_distance)

    euclid_error, greatcircle_error  = Distance.compute_percentage_error(euclid_distance, greatcircle_distance, vincenty_distance)
    return render_template('results.html', euclid_distance = euclid_distance, euclid_error = euclid_error, greatcircle_distance = greatcircle_distance, greatcircle_error = greatcircle_error, vincenty_distance = vincenty_distance)

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