"""
财务数据 ,限售股解禁,基金持股
Created on 2018/05/14
@author: yudong chou
@contact: 33836858@qq.com
"""
import crawl_service as crawl
import db_mysql_cons as cn

def update_stock_report(report, nd, jd):
    """
    获取业绩报告（主表)
    :return:
    """
    if report == 'report':
        stocks = crawl.get_stock_report(nd, jd)
        sql1 = cn.DEL_T_CHN_STOCK_REPORT
        sql2 = cn.ISR_T_CHN_STOCK_REPORT
    elif report == 'profit':
        stocks = crawl.get_stock_profit(nd, jd)
        sql1 = cn.DEL_T_CHN_STOCK_PROFIT
        sql2 = cn.ISR_T_CHN_STOCK_PROFIT
    elif report == 'operation':
        stocks = crawl.get_stock_operation(nd, jd)
        sql1 = cn.DEL_T_CHN_STOCK_OPERATION
        sql2 = cn.ISR_T_CHN_STOCK_OPERATION
    elif report == 'growth':
        stocks = crawl.get_stock_growth(nd, jd)
        sql1 = cn.DEL_T_CHN_STOCK_GROWTH
        sql2 = cn.ISR_T_CHN_STOCK_GROWTH
    elif report == 'debtpaying':
        stocks = crawl.get_stock_debtpaying(nd, jd)
        sql1 = cn.DEL_T_CHN_STOCK_DEBTPAYING
        sql2 = cn.ISR_T_CHN_STOCK_DEBTPAYING
    else:
        stocks = crawl.get_stock_cashflow(nd, jd)
        sql1 = cn.DEL_T_CHN_STOCK_CASHFLOW
        sql2 = cn.ISR_T_CHN_STOCK_CASHFLOW
    if stocks is None:
        return -1
    params_list2 = []
    param_list1 = (nd,) + (jd,)
    for i in stocks.index:
        data = (nd,) + (jd,) + tuple(stocks.iloc[i].values.astype(str),)
        params_list2.append(data)
    try:
        con = cn.connection()
        cur = con.cursor()
        cur.execute(sql1, param_list1)
        cur.executemany(sql2, params_list2)
        res = cur.rowcount
        con.commit()
        return res
    except Exception as e:
        con.rollback()
        print('更新', report, '事务处理失败', e)
        return -1
    finally:
        cur.close()
        con.close()
        print('更新', report, '连接关闭')

def update_stock_forecast(nd, jd):
    """
    获取业绩预告
    :return:
    """
    stocks = crawl.get_stock_forecast(nd, jd)
    print(stocks)
    if stocks is None:
        return -1
    params_list2 = []
    param_list1 = (nd,) + (jd,)
    for i in stocks.index:
        data = (nd,) + (jd,) + tuple(stocks.iloc[i].values.astype(str),)
        params_list2.append(data)
    try:
        con = cn.connection()
        cur = con.cursor()
        cur.execute(cn.DEL_T_CHN_STOCK_FORECAST, param_list1)
        cur.executemany(cn.ISR_T_CHN_STOCK_FORECAST, params_list2)
        res = cur.rowcount
        con.commit()
        return res
    except Exception as e:
        con.rollback()
        print('更新业绩预告事务处理失败', e)
        return -1
    finally:
        cur.close()
        con.close()
        print('更新业绩预告连接关闭')

def update_stock_xsgjj(nd, yf):
    """
    获取限售股解禁
    :return:
    """
    stocks = crawl.get_stock_xsgjj(nd, yf)
    if stocks is None:
        return -1
    params_list2 = []
    param_list1 = (nd,) + (yf,)
    for i in stocks.index:
        data = (nd,) + (yf,) + tuple(stocks.iloc[i].values.astype(str),)
        params_list2.append(data)
    try:
        con = cn.connection()
        cur = con.cursor()
        cur.execute(cn.DEL_T_CHN_STOCK_XSGJJ, param_list1)
        cur.executemany(cn.ISR_T_CHN_STOCK_XSGJJ, params_list2)
        res = cur.rowcount
        con.commit()
        return res
    except Exception as e:
        con.rollback()
        print('更新业限售股解禁事务处理失败', e)
        return -1
    finally:
        cur.close()
        con.close()
        print('更新限售股解禁连接关闭')

def update_stock_jjcg(nd, jd):
    """
    获取基金持股
    :return:
    """
    stocks = crawl.get_stock_jjcg(nd, jd)
    if stocks is None:
        return -1
    params_list2 = []
    param_list1 = (nd,) + (jd,)
    for i in stocks.index:
        data = (nd,) + (jd,) + tuple(stocks.iloc[i].values.astype(str),)
        params_list2.append(data)
    try:
        con = cn.connection()
        cur = con.cursor()
        cur.execute(cn.DEL_T_CHN_STOCK_JJCG, param_list1)
        cur.executemany(cn.ISR_T_CHN_STOCK_JJCG, params_list2)
        res = cur.rowcount
        con.commit()
        return res
    except Exception as e:
        con.rollback()
        print('更新基金持股事务处理失败', e)
        return -1
    finally:
        cur.close()
        con.close()
        print('更新基金持股连接关闭')


from robot.parsing import get_model

from Capitalize_Keyword.keyword_extract import GetFiles
from Capitalize_Keyword.keyword_extract import AllKeywordsFromFile
from Capitalize_Keyword.keyword_extract import KeywordNameVisitor
from Capitalize_Keyword.keyword_extract import KeywordCallVisitor

from Capitalize_Keyword.Change_keywords import KeywordTestCaseUpper

class StartCapitilizer:
    def __init__(self, robot_file, keyword_dir="DEFAULT"):
        self.files_list = []
        self.all_keywords = []
        self.model = get_model(robot_file)
        self.robot_file = robot_file
        self.keyword_dir = keyword_dir
        self.files = GetFiles()
        self.name_visitor = KeywordNameVisitor()
        self.call_visitor = KeywordCallVisitor()
        self.get_keywords_from_resourceFile()
        self.get_keywords_from_test_file()
        self.change_keywords()

    def get_keywords_from_resourceFile(self):
        if self.keyword_dir != "DEFAULT":
            self.files_list = self.files.get_dir(self.keyword_dir)
            extractor = AllKeywordsFromFile(self.files_list, self.keyword_dir)
            extractor.add_all_keywords_to_list()
            for keyword in extractor.get_all_keywords_list():
                self.all_keywords.append(keyword)

    def get_keywords_from_test_file(self):
        self.name_visitor.visit(self.model)
        keyword_names = self.name_visitor.return_name_list()
        for keyword_name in keyword_names:
            self.all_keywords.append(keyword_name)

    def change_keywords(self):
        self.changer = KeywordTestCaseUpper(self.all_keywords)
        print("Updating All Keywords With Uppercase")
        self.changer.visit(self.model)
        print("**DONE**")
        self.model.save(output=self.robot_file)

    def get_changed_KC(self):
        return self.changer.return_changed_call()

    def get_changed_KN(self):
        return self.changer.return_changed_name()


from bisect import bisect, bisect_right, bisect_left, insort_left

class Solution:
    def containsNearbyAlmostDuplicate(self, nums, indexDiff, valueDiff):
        sliding_window = []
        for i in range(len(nums)):
            if i > indexDiff: sliding_window.remove(nums[i-indexDiff-1])

            floor_index = self.find_rightmost_le(sliding_window, nums[i])
            ceil_index = self.find_leftmost_ge(sliding_window, nums[i])
            if floor_index is not None:
                if abs(nums[i] - sliding_window[floor_index]) <= valueDiff:
                    return True
            if ceil_index is not None:
                if abs(nums[i] - sliding_window[ceil_index]) <= valueDiff:
                    return True
            insort_left(sliding_window, nums[i])

        return False

    def find_rightmost_le(self, a, x):
        i = bisect_right(a, x)
        if i:
            return i-1
        return None

    def find_leftmost_ge(self, a, x):
        i = bisect_left(a, x)
        if i != len(a):
            return i
        return None


import tensorflow as tf
import tensorflow_datasets as tfds
import pandas as pd
import numpy as np

train_ds = pd.read_csv('labeledTrainData.csv')
train_x = train_ds['review']
train_y = train_ds['sentiment']
test_ds = pd.read_csv('testData.csv')
test_x = test_ds.pop('review')
test_id = test_ds.pop('id').tolist()

VOCAB_SIZE = 3000
encoder = tf.keras.layers.TextVectorization(
    max_tokens=VOCAB_SIZE)
encoder.adapt(train_ds['review'])
print(test_ds.isna().any())
print(train_x.shape)
print(test_x.head())

model_multi_lstm = tf.keras.Sequential([
    tf.keras.Input(shape=(1,), dtype=tf.string),
    encoder,
    tf.keras.layers.Embedding(len(encoder.get_vocabulary()), 64, mask_zero=True),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64,  return_sequences=True)),
    tf.keras.layers.Dropout(0.25),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(32, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

model_multi_lstm.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              optimizer=tf.keras.optimizers.Adam(1e-4),
              metrics=['accuracy'])

history = model_multi_lstm.fit(train_x, train_y, epochs=10)

predictions = model_multi_lstm.predict(test_x)
for i, prediction in enumerate(predictions):
    predictions[i] = int(round(prediction[0]))

predictions = predictions.reshape(-1).astype(int)
print(predictions)
predictions = pd.DataFrame({'id': test_id,
                           'sentiment': predictions})

predictions.to_csv('predictions.csv', index=False)


def calc(symb, a, b):
    if symb == '+':
        return a + b
    elif symb == "-":
        return a - b
    elif symb == '*':
        return a * b
    else:
        return a / b

n = int(input())
ans_list = []
for i in range(0, n):
    arithmetic = input()
    mylist = list(map(str, input().split(maxsplit=4)))
    x = calc(arithmetic, int(mylist[1]), int(mylist[3]))
    s = "{} {} {} = {}".format(mylist[0], arithmetic, mylist[2], str(x))
    ans_list.append(s)

for i in ans_list:
    print(i)


#Melhore o jogo do DESAFIO 28 onde o computador vai “pensar” em um número entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer.
from random import randint
numpc = randint(0, 10)
cont = 0
print('Sou seu computador...')
print('Acabei de pensar em um número entre 0 e 10.')
print('Será que vc consegue adivinhar qual foi?')
palpite = int(input('Qual é seu palpite? '))
cont += 1
while palpite != numpc:
    if palpite > numpc:
        print('menos, tente outra vez...')
        palpite = int(input('Qual seu palpite? '))
        cont += 1
    elif palpite < numpc:
        print('mais, tente outra vez')
        palpite = int(input('qual seu palpite? '))
        cont += 1
print('vc acertou com {} tentativas. parabens'.format(cont))
if cont == 1:
    print('De primeira, vc é o brabo!')
elif cont == 2:
    print('Muito bom, vc é fera nisso!')
elif cont == 3:
    print('é.. parabens')
elif cont == 4:
    print('vc pode fazer melhor...')
else:
    print('mas vc é muito ruim na adivinhação...')


# Генераторы последовательностей

# Запись общей конструкции, которой подчиняются все генераторы последовательностей

# [x for x in range(0, n+1) if x%2==0]

# Логика следующая:
# х пробегает все значения по какому-то списку, но в список добавляются только те элементы последовательности,
# которые удовлетворяют условию.
# То есть, перед нами генератор списка, который создаст последовательность из тех элементов списка,
# которые удовлетворяют условию
# Все то же самое касается и словарей и множеств. Общая конструкция не меняется, а добавляется только специфика
# каждого типа данных.

# В Питоне есть отдельное название для этого способа генерации Списков, Словарей, Множество.
# И это называется Генераторы

# Давайте убедимся на примере, что данный способ записи гараздо более экономичный.

# Но перед этим разберем понятие 'Тернарный оператор'
# Это способ записи выражения присваивания в одну строку.

# Создадим ф-ю проверки возраста, которая будет проверять возраст на совершеннолетие.

def check_adult(age_person):
    check = 0
    if age_person >= 18:
        check = 1
    else:
        check = 0
    return check

age = 18

print(check_adult(age))  # 1

# Эту же ф-ю запишем через Лямбда-функция + тернарный оператор

check_adult_1 = lambda x: 1 if age >= 18 else 0
print(check_adult_1(age))

# Теперь это выражение перепишем с помощью тернарного оператора

check = 1 if age >= 18 else 0
print(check)

# Далее Генераторы последовательностей

# -------------------- для Списка ----------------------

# Рассмотрим два сопсоба

# Сгенерируем список из квадратов чисел
# Для начала создаем пустой список
list_sq_1 = []
N = 10  # параметр N задает количество необходимых квадратов

for i in range(1 , N+1):
    list_sq_1.append(i**2)  # каждый элемент списка возводим в квадрат
print(list_sq_1)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# Чтобы иметь последние цифры чисел генерируемой последовательности
list_sq_2 = []

for i in range(1 , N+1):
    list_sq_2.append((i**2)%10)  # каждый элемент списка возводим в квадрат и делим на 10 - получаем последнее число
print(list_sq_2)
# [1, 4, 9, 6, 5, 6, 9, 4, 1, 0]

# Теперь то же самое сделаем с помощью генераторов списков

list_sq_g = [(i**2)%10 for i in range(1 , N+1)]
print(list_sq_g)
# [1, 4, 9, 6, 5, 6, 9, 4, 1, 0]

# Но, в этом варианте записи громозкость кода возникает если еще добавляются условия if
list_sq_3 = []
for i in range(1 , N+1):
    if (i**2)%2 == 0:  # если значение четное
     list_sq_3.append(i**2)  # добавляем в список
print(list_sq_3)
# [4, 16, 36, 64, 100]  # получаем только четные значения

# То же выражение в Генераторе списков
list_sq_g = [i**2 for i in range(1 , N+1) if (i**2)%2 == 0]
print(list_sq_g)
# [4, 16, 36, 64, 100]

# Это Питоновсий стиль, что делает вычисление гораздо быстрее и выглядит намного лучше.

# -------------------- для Словаря ----------------------

# Единственное отличие от Списков - здесь используется Ключ-Значение
dict_g = {i: i**2 for i in range(1 , N+1)}  # Ключ-Значение i: i^2
print(dict_g)
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

# -------------------- для Множества ----------------------

# Записывается также, как и Словарь, но только без ключей
set_g = {i**2 for i in range(1 , N+1)}
print(set_g)  # {64, 1, 4, 36, 100, 9, 16, 49, 81, 25}  # квадраты чисел последовательности

set_g_d = {(i**2)%10 for i in range(1 , N+1)}  # здесь выводим остатки от деления
print(set_g_d)  # {0, 1, 4, 5, 6, 9}

# Рещим задачу
# У нас есть список имен. Мы должны получить список из первых букв, но в верхнем регистре

list_names = ['Dima', 'kate', 'oleg', 'Nastya']

# Далее создаем новый спсок с помощью генератора списка из первых букв в верхнем регистре
# Здесь мы используем тернарный оператор и генератор списка

list_char = [x[0] if x[0].isupper() else x[0].title() for x in list_names]
# Расшифровка выражения
# х - имя
# Если первая буква х[0] текущего имени большая .isupper(), добавляем ее в список
# Иначе возводим ее в верхний регистр  x[0].title()
# в цикле для каждого имени переданного списка
print(list_char)
# ['D', 'K', 'O', 'N']  # получаем первые буквы имен в верхнем регистре


class Solution:
    def evaluate(self, expr):
        """
        :type expr: str
        :rtype: int
        """

        def match_paren(s: str):
            d = 1
            r = 0
            while d:
                r += 1
                if s[r] == ')':
                    d -= 1
                elif s[r] == '(':
                    d += 1
            return r

        def split(expr: str):
            expr = expr[1:-1]
            parts = []
            while expr:
                if expr[0] == '(':
                    rb = match_paren(expr)
                    first = expr[:rb + 1]
                    expr = expr[rb + 2:]
                else:
                    first, _, expr = expr.partition(' ')
                parts.append(first)
            return parts

        def eval(expr, local: dict = None):
            try:
                return int(expr)
            except ValueError:
                pass
            try:
                return local[expr]
            except (KeyError, TypeError):
                pass
            parts = split(expr)
            if parts[0] == 'add':
                return eval(parts[1], local) + eval(parts[2], local)
            elif parts[0] == 'mult':
                return eval(parts[1], local) * eval(parts[2], local)
            elif parts[0] == 'let':
                if local is None:
                    local = dict()
                local_update = local.copy()
                for v, e in zip(parts[1::2], parts[2::2]):
                    local_update[v] = eval(e, local_update)
                return eval(parts[-1], local_update)

        return eval(expr)

fn = Solution().evaluate

for expr in [
        "1",
        "12",
        "-1",
        "(add 12 32)",
        "(mult 22 44)",
        "(mult 22 (add 3 5))",
        "(mult 22 (add 3 (mult 3 5)))",
        "(let x 2 (add 3 x))",
        "(let x 2 x 3 (mult 3 x))",
        "(let x 1 y 2 x (add x y) (add x y))",
        "(let x 2 (add (let x 3 (let x 4 x)) x))",
        "(let a1 3 b2 (add a1 1) b2)",
        "(let x -2 y x y)",
]:
    print(expr, '->', fn(expr))


from urllib.request import urlopen
from json import load

def search_images(date, camera):
    """
    Applies given date and camera type to the URL and retrieves data from it.

    :param date: str
    :param camera: str
    :return: set/None
    """
    if date:
        date = '&earth_date=' + date
    if camera:
        camera = '&camera=' + camera
    URL = 'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?api_key=DEMO_KEY{0}{1}'.format(date, camera)
    json_file = load(urlopen(URL))
    photo_links = set()
    if json_file['photos'] != list():
        for i in range(len(json_file['photos'])):
            photo_links.add(json_file['photos'][i]['img_src'])
        return photo_links
    else:
        return None


import time
import numpy as np
import matplotlib

# adapt as needed for your system
# from sys import platform
# if platform =="darwin":
#   matplotlib.use("Qt5Agg")
# else:
#   matplotlib.use('TkAgg')

from matplotlib import pyplot as plt

from env.hopf_network import HopfNetwork
from env.quadruped_gym_env import QuadrupedGymEnv

#best results obtained with cartesian only!!
PD_CARTESIAN_ONLY = True #if this is true the next one has to be true as well
ADD_CARTESIAN_PD = True #change both of these variables to have PD only in the joint space
BASIC_TRACKING_PLOT = False
CPG_STATES_PLOT = False
EXT_TRACKING_PLOT = True
TIME_STEP = 0.001
foot_y = 0.0838 # this is the hip length
sideSign = np.array([-1, 1, -1, 1]) # get correct hip sign (body right is negative)

env = QuadrupedGymEnv(render=True,              # visualize
                    on_rack=False,              # useful for debugging!
                    isRLGymInterface=False,     # not using RL
                    time_step=TIME_STEP,
                    action_repeat=1,
                    motor_control_mode="TORQUE",
                    add_noise=False,    # start in ideal conditions
                    record_video=False #didnt work for me, you have to install ffmpeg
                    )

# initialize Hopf Network, supply gait
cpg = HopfNetwork(time_step=TIME_STEP)

TEST_STEPS = int(10 / (TIME_STEP))
t = np.arange(TEST_STEPS)*TIME_STEP

# [TODO] initialize data structures to save CPG and robot states

xs_cpg = np.zeros((TEST_STEPS,4))
ys_cpg = np.zeros((TEST_STEPS,4))
zs_cpg = np.zeros((TEST_STEPS,4))
xs_robot = np.zeros((TEST_STEPS,4))
ys_robot = np.zeros(TEST_STEPS)
zs_robot = np.zeros((TEST_STEPS,4))
distance_run = np.zeros(3)
robot_v = np.zeros((TEST_STEPS,3))
robot_p = np.zeros(TEST_STEPS)

# First task, data structure initialization
r_list = np.zeros([TEST_STEPS,4])
theta_list = np.zeros([TEST_STEPS,4])
dr_list = np.zeros([TEST_STEPS,4])
dtheta_list = np.zeros([TEST_STEPS,4])

# Second task, data structure initialization
pos_leg_0 = np.zeros([TEST_STEPS,3])
des_pos_leg_0 = np.zeros([TEST_STEPS,3])
joint_leg_3 = np.zeros([TEST_STEPS,3])
des_joint_leg_3 = np.zeros([TEST_STEPS,3])

############## Sample Gains
# joint PD gains
kp=1*np.array([100,100,100])
kd=0.5*np.array([2,2,2])
if not PD_CARTESIAN_ONLY and not ADD_CARTESIAN_PD : #same as if "PD_JOINT_ONLY"
  kp = 10*np.array([100,100,100])
  kd = 5 * np.array([2, 2, 2])
# Cartesian PD gains
kpCartesian = 5* np.diag([500]*3)
kdCartesian = 1* np.diag([20]*3)
if PD_CARTESIAN_ONLY:
  kpCartesian = 5 * np.diag([500] * 3)
  kdCartesian = 2 * np.diag([20] * 3)

for j in range(TEST_STEPS):
  # initialize torque array to send to motors
  action = np.zeros(12)
  # get desired foot positions from CPG
  xs,zs = cpg.update()

  q = env.robot.GetMotorAngles()
  dq = env.robot.GetMotorVelocities()
  robot_v[j,:] = env.robot.GetBaseLinearVelocity()

  # loop through desired foot positions and calculate torques
  for i in range(4):
    # initialize torques for legi
    tau = np.zeros(3)
    # get desired foot i pos (xi, yi, zi) in leg frame
    leg_xyz = np.array([xs[i],sideSign[i] * foot_y,zs[i]])
    # call inverse kinematics to get corresponding joint angles (see ComputeInverseKinematics() in quadruped.py)
    leg_q = env.robot.ComputeInverseKinematics(i, leg_xyz)
    # Add joint PD contribution to tau for leg i
    q_i = q[3*i:3*(i+1)]
    dq_i = dq[3*i:3*(i+1)]
    tau += kp*(leg_q-q_i) + kd*(-dq_i)
    if PD_CARTESIAN_ONLY:
      tau = np.zeros(3)

    # add Cartesian PD contribution
    if ADD_CARTESIAN_PD:
      # Get current Jacobian and foot position in leg frame (see ComputeJacobianAndPosition() in quadruped.py)
      J,pos = env.robot.ComputeJacobianAndPosition(i)
      # Get current foot velocity in leg frame (Equation 2)
      v = np.matmul(J,dq_i)
      # Calculate torque contribution from Cartesian PD (Equation 5) [Make sure you are using matrix multiplications]
      tau += np.matmul(np.transpose(J),(np.matmul(kpCartesian,(leg_xyz-pos))+np.matmul(kdCartesian,-v)))

    # Set tau for legi in action vector
    action[3*i:3*i+3] = tau

  # send torques to robot and simulate TIME_STEP seconds
  env.step(action)
  #we take the value for the joints for the last leg, i = 3 out of the loop
  joint_leg_3[j,:] = q_i
  des_joint_leg_3[j,:] = leg_q

  raw_power = np.multiply(env.robot.GetMotorVelocities(), env.robot.GetMotorTorques())
  robot_p[j] =np.sum(np.maximum(raw_power, np.zeros(12))) #we also assume here that the robot cannot use regenerative braking

  xs_cpg[j,:] = xs
  zs_cpg[j,:] = zs
  if not ADD_CARTESIAN_PD:
    J, pos = env.robot.ComputeJacobianAndPosition(i)
  xs_robot[j,:] = pos[0]
  zs_robot[j,:] = pos[2]
  ys_cpg[j,:] = pos[1]
  ys_robot[j] = leg_xyz[1]
  # [TODO] save any CPG or robot states
  r_list[j,:] = cpg.get_r()
  theta_list[j,:] = cpg.get_theta()
  dr_list[j,:] = cpg.get_dr()
  dtheta_list[j,:] = cpg.get_dtheta()

distance_run = np.array(env.robot.GetBasePosition())-np.array(env.robot._GetDefaultInitPosition())
print(distance_run)

#####################################################
# PLOTS
#####################################################

short_t = int(np.ceil(TEST_STEPS/25))
#print(short_t)

if CPG_STATES_PLOT:
  fig, axis = plt.subplots(4,4)
  axis[0,0].plot(range(short_t),r_list[:short_t,0])
  axis[0,0].set_title("r0")
  axis[0,1].plot(range(short_t),r_list[:short_t,1])
  axis[0,1].set_title("r1")
  axis[0,2].plot(range(short_t),r_list[:short_t,2])
  axis[0,2].set_title("r2")
  axis[0,3].plot(range(short_t),r_list[:short_t,3])
  axis[0,3].set_title("r3")

  axis[1,0].plot(range(short_t),dr_list[:short_t,0])
  axis[1,0].set_title("dr0")
  axis[1,1].plot(range(short_t),dr_list[:short_t,1])
  axis[1,1].set_title("dr1")
  axis[1,2].plot(range(short_t),dr_list[:short_t,2])
  axis[1,2].set_title("dr2")
  axis[1,3].plot(range(short_t),dr_list[:short_t,3])
  axis[1,3].set_title("dr3")

  axis[2,0].plot(range(short_t),theta_list[:short_t,0])
  axis[2,0].set_title("theta0")
  axis[2,1].plot(range(short_t),theta_list[:short_t,1])
  axis[2,1].set_title("theta1")
  axis[2,2].plot(range(short_t),theta_list[:short_t,2])
  axis[2,2].set_title("theta2")
  axis[2,3].plot(range(short_t),theta_list[:short_t,3])
  axis[2,3].set_title("theta3")

  axis[3,0].plot(range(short_t),dtheta_list[:short_t,0])
  axis[3,0].set_title("dtheta0")
  axis[3,1].plot(range(short_t),dtheta_list[:short_t,1])
  axis[3,1].set_title("dtheta1")
  axis[3,2].plot(range(short_t),dtheta_list[:short_t,2])
  axis[3,2].set_title("dtheta2")
  axis[3,3].plot(range(short_t),dtheta_list[:short_t,3])
  axis[3,3].set_title("dtheta3")
  fig.tight_layout(pad=2.0)
  plt.show()

if EXT_TRACKING_PLOT:
  #print(np.size(xs_cpg))
  fig, axis = plt.subplots(1,3)
  axis[0].plot(range(short_t*3),xs_cpg[:short_t*3,3],c="red")
  axis[0].plot(range(short_t*3), xs_robot[:short_t*3, 1], c="blue")
  axis[0].set_title("x")
  axis[1].plot(range(short_t * 3), ys_cpg[:short_t * 3,3], c="red")
  axis[1].plot(range(short_t * 3), ys_robot[:short_t * 3], c="blue")
  axis[1].set_ylim([-0.25,0.25])
  axis[1].set_title("y")
  axis[2].plot(range(short_t*3), zs_cpg[:short_t*3,3], c="red")
  axis[2].plot(range(short_t*3), zs_robot[:short_t*3, 1], c="blue")
  axis[2].set_title("z")
  #if not PD_CARTESIAN_ONLY and not ADD_CARTESIAN_PD:#same as if "PD_JOINT_ONLY"
  #  plt.title("tracking cartesian command for leg 4, joint PD only")
  #if PD_CARTESIAN_ONLY:
  #  plt.title("tracking cartesian command for leg 4, cartesian PD only")
  plt.show()

  fig, axis = plt.subplots(1,3)
  axis[0].plot(range(short_t*3), des_joint_leg_3[:short_t*3, 0], c="red")
  axis[0].plot(range(short_t*3), joint_leg_3[:short_t*3, 0], c="blue")
  axis[0].set_ylim([-1.5,1.5])
  axis[0].set_title("hip angle")
  axis[1].plot(range(short_t*3), des_joint_leg_3[:short_t*3, 1], c="red")
  axis[1].plot(range(short_t*3), joint_leg_3[:short_t*3, 1], c="blue")
  axis[1].set_title("thigh angle")
  axis[2].plot(range(short_t*3), des_joint_leg_3[:short_t*3, 2], c="red")
  axis[2].plot(range(short_t*3), joint_leg_3[:short_t*3, 2], c="blue")
  axis[2].set_title("calf angle")
  #if not PD_CARTESIAN_ONLY and not ADD_CARTESIAN_PD:
  #  plt.title("tracking joint command for leg 4, joint PD only")
  #if PD_CARTESIAN_ONLY:
  #  plt.title("tracking joint command for leg 4, cartesian PD only")
  plt.show()

# plot the speed
fig1 = plt.figure()
plt.plot(range(TEST_STEPS),np.sqrt(robot_v[:,0]**2+robot_v[:,1]**2))
plt.show()
average_speed = np.sum(np.sqrt(robot_v[:,0]**2+robot_v[:,1]**2))/TEST_STEPS
average_power = np.sum(robot_p)/TEST_STEPS
print("average speed: ")
print(average_speed)
print("average power: ")
print(average_power)
mass = np.sum(env.robot.GetTotalMassFromURDF())
CoT = average_power/(mass*9.81*average_speed)
print("CoT: ")
print(CoT)

if BASIC_TRACKING_PLOT:
  #print(np.size(xs_cpg))
  fig2 = plt.figure()
  plt.plot(range(short_t*3),xs_cpg[:short_t*3,3],c="red")
  plt.plot(range(short_t*3),xs_robot[:short_t*3,1],c="blue")
  plt.title("tracking x cartesian command for leg 4")
  plt.show()

  fig3 = plt.figure()
  plt.plot(range(short_t*3),zs_cpg[:short_t*3],c="red")
  plt.plot(range(short_t*3),zs_robot[:short_t*3,1],c="blue")
  plt.title("tracking z cartesian command for leg 4")
  plt.show()


import copy

import d20
import draconic

from cogs5e.models.sheet.resistance import Resistances, do_resistances
from utils.enums import CritDamageType
from . import Effect
from .roll import RollEffectMetaVar
from .. import utils
from ..errors import TargetException
from ..results import DamageResult

class Damage(Effect):
    def __init__(
        self,
        damage: str,
        overheal: bool = False,
        higher: dict = None,
        cantripScale: bool = None,
        fixedValue: bool = None,
        **kwargs,
    ):
        super().__init__("damage", **kwargs)
        self.damage = damage
        self.overheal = overheal
        # common
        self.higher = higher
        self.cantripScale = cantripScale
        self.fixedValue = fixedValue

    def to_dict(self):
        out = super().to_dict()
        out.update({"damage": self.damage, "overheal": self.overheal})
        if self.higher is not None:
            out["higher"] = self.higher
        if self.cantripScale is not None:
            out["cantripScale"] = self.cantripScale
        if self.fixedValue is not None:
            out["fixedValue"] = self.fixedValue
        return out

    def run(self, autoctx):
        super().run(autoctx)
        if autoctx.target is None:
            raise TargetException(
                "Tried to do damage without a target! Make sure all Damage effects are inside of a Target effect."
            )
        # general arguments
        args = autoctx.args
        damage = self.damage
        resistances = Resistances()
        c_args = args.get("c", [], ephem=True)
        crit_arg = args.last("crit", None, bool, ephem=True)
        nocrit = args.last("nocrit", default=False, type_=bool, ephem=True)
        max_arg = args.last("max", None, bool, ephem=True)
        magic_arg = args.last("magical", None, bool, ephem=True)
        silvered_arg = args.last("silvered", None, bool, ephem=True)
        mi_arg = args.last("mi", None, int)
        dtype_args = args.get("dtype", [], ephem=True)
        critdice = sum(args.get("critdice", type_=int))
        savage = args.last("savage", None, bool, ephem=True)
        hide = args.last("h", type_=bool)

        crit_damage_type = autoctx.crit_type

        # character-specific arguments
        if autoctx.character and args.last("critdice") is None:
            critdice = autoctx.character.options.extra_crit_dice

        # combat-specific arguments
        if not autoctx.target.is_simple:
            resistances = autoctx.target.get_resists().copy()
        resistances.update(Resistances.from_args(args, ephem=True))

        # check if we actually need to run this damage roll (not in combat and roll is redundant)
        if autoctx.target.is_simple and self.is_meta(autoctx):
            return

        d_args = []
        # check if we actually need to care about the -d tag
        if not (self.contains_roll_meta(autoctx) or self.fixedValue):
            d_args = args.get("d", [], ephem=True)
            # add on combatant damage effects (#224)
            d_args.extend(autoctx.caster_active_effects(mapper=lambda effect: effect.effects.damage_bonus, default=[]))

        # set up damage AST
        damage = autoctx.parse_annostr(damage)
        dice_ast = copy.copy(d20.parse(damage))
        dice_ast = utils.upcast_scaled_dice(self, autoctx, dice_ast)

        if savage:
            dice_ast.roll = d20.ast.OperatedSet(
                d20.ast.NumberSet([dice_ast.roll, dice_ast.roll]), d20.SetOperator("k", [d20.SetSelector("h", 1)])
            )

        # -mi # (#527)
        if mi_arg:
            dice_ast = d20.utils.tree_map(utils.mi_mapper(mi_arg), dice_ast)

        # -d #
        for d_arg in d_args:
            d_ast = d20.parse(d_arg)
            dice_ast.roll = d20.ast.BinOp(dice_ast.roll, "+", d_ast.roll)

        # crit
        # nocrit (#1216)
        # Disable critical damage in saves (#1556)
        in_crit = (autoctx.in_crit or crit_arg) and not (nocrit or autoctx.in_save)
        if in_crit:
            if crit_damage_type == CritDamageType.MAX_ADD:
                dice_ast = utils.tree_map_prefix(utils.max_add_crit_mapper, dice_ast)
            elif crit_damage_type == CritDamageType.DOUBLE_ALL:
                dice_ast.roll = d20.ast.BinOp(d20.ast.Parenthetical(dice_ast.roll), "*", d20.ast.Literal(2))
            elif crit_damage_type == CritDamageType.DOUBLE_DICE:
                dice_ast = utils.tree_map_prefix(utils.double_dice_crit_mapper, dice_ast)
            else:
                dice_ast = d20.utils.tree_map(utils.crit_mapper, dice_ast)
            if critdice and not autoctx.is_spell:
                if crit_damage_type in (CritDamageType.DOUBLE_ALL, CritDamageType.DOUBLE_DICE):
                    crit_ast = utils.crit_dice_gen(dice_ast, critdice)
                    if crit_ast:
                        dice_ast.roll = d20.ast.BinOp(dice_ast.roll, "+", crit_ast)
                else:
                    utils.critdice_tree_update(dice_ast, int(critdice))

        # -c #
        if in_crit:
            for c_arg in c_args:
                c_ast = d20.parse(c_arg)
                dice_ast.roll = d20.ast.BinOp(dice_ast.roll, "+", c_ast.roll)

        # max
        if max_arg:
            dice_ast = d20.utils.tree_map(utils.max_mapper, dice_ast)

        # evaluate damage
        dmgroll = d20.roll(dice_ast)

        # magic arg (#853), magical effect (#1063)
        # silvered arg (#1544)
        always = set()
        magical_effect = autoctx.caster_active_effects(mapper=lambda effect: effect.effects.magical_damage, reducer=any)
        if magical_effect or autoctx.is_spell or magic_arg:
            always.add("magical")
        silvered_effect = autoctx.caster_active_effects(
            mapper=lambda effect: effect.effects.silvered_damage, reducer=any
        )
        if silvered_effect or silvered_arg:
            always.add("silvered")
        # dtype transforms/overrides (#876)
        transforms = {}
        for dtype in dtype_args:
            if ">" in dtype:
                *froms, to = dtype.split(">")
                for frm in froms:
                    transforms[frm.strip().lower()] = to.strip().lower()
            else:
                transforms[None] = dtype
        # display damage transforms (#1103)
        if None in transforms:
            autoctx.meta_queue(f"**Damage Type**: {transforms[None]}")
        elif transforms:
            for frm in transforms:
                autoctx.meta_queue(f"**Damage Change**: {frm} > {transforms[frm]}")

        # evaluate resistances
        do_resistances(dmgroll.expr, resistances, always, transforms)

        # determine healing/damage, stringify expr
        result = d20.MarkdownStringifier().stringify(dmgroll.expr)
        if dmgroll.total < 0:
            roll_for = "Healing"
        else:
            roll_for = "Damage"

        # output
        roll_for = roll_for if not in_crit else f"{roll_for} (CRIT!)"
        if not hide:
            autoctx.queue(f"**{roll_for}**: {result}")
        else:
            d20.utils.simplify_expr(dmgroll.expr)
            autoctx.queue(f"**{roll_for}**: {d20.MarkdownStringifier().stringify(dmgroll.expr)}")
            autoctx.add_pm(str(autoctx.ctx.author.id), f"**{roll_for}**: {result}")

        autoctx.target.damage(autoctx, dmgroll.total, allow_overheal=self.overheal)

        # #1335
        autoctx.metavars["lastDamage"] = dmgroll.total
        return DamageResult(damage=dmgroll.total, damage_roll=dmgroll, in_crit=in_crit)

    def is_meta(self, autoctx):
        """Check if the damage string is completely a metavar sub."""
        return any(f"{{{v}}}" == self.damage for v in autoctx.metavars)

    def contains_roll_meta(self, autoctx):
        """Check if the damage string contains the result of a Roll effect."""
        return any(f"{{{k}}}" in self.damage for k, v in autoctx.metavars.items() if isinstance(v, RollEffectMetaVar))

    def build_str(self, caster, evaluator):
        super().build_str(caster, evaluator)
        try:
            damage = evaluator.transformed_str(self.damage)
            evaluator.builtins["lastDamage"] = damage
        except draconic.DraconicException:
            damage = self.damage
            evaluator.builtins["lastDamage"] = 0

        # damage/healing
        if damage.startswith("-"):
            return f"{damage[1:].strip()} healing"
        return f"{damage} damage"


from talon import actions, cron, scope, app, Module
from .poller import Poller
from ..configuration import hud_get_configuration
import os

languages = {}

class ProgrammingLanguagePoller(Poller):
    enabled = False
    content = None
    job = None
    current_language = None
    can_toggle = False

    def enable(self):
        if not self.enabled:
            self.job = cron.interval("200ms", self.language_check)
            self.enabled = True

    def disable(self):
        if self.enabled:
            self.enabled = False
            cron.cancel(self.job)
            self.job = None
            self.content.publish_event("status_icons", "programming_toggle", "remove")

    def language_check(self):
        global languages
        can_toggle = actions.user.hud_can_toggle_programming_language()
        language = actions.user.hud_get_programming_language()

        if self.current_language != language or can_toggle != self.can_toggle:
            self.current_language = language
            self.can_toggle = can_toggle
            if language != "":
                icon = ""
                text = ""
                if language in languages:
                    icon = languages[language]["icon"]
                    text = languages[language]["extension"]

                callback = False
                if can_toggle:
                    callback = lambda _, _2: actions.user.hud_toggle_programming_language()
                status_icon = self.content.create_status_icon("programming_toggle", icon, text, language + " detected", callback)
                self.content.publish_event("status_icons", status_icon.topic, "replace", status_icon)
            else:
                status_icon = self.content.create_status_icon("programming_toggle", "", "", "No programming language detected", False)
                self.content.publish_event("status_icons", status_icon.topic, "replace", status_icon)

def add_statusbar_programming_icon(_ = None):
    actions.user.hud_activate_poller("programming_toggle")

def remove_statusbar_programming_icon(_ = None):
    actions.user.hud_deactivate_poller("programming_toggle")
    actions.user.hud_remove_status_icon("programming_toggle")

def register_language_poller():
    actions.user.hud_add_poller("programming_toggle", ProgrammingLanguagePoller())
    default_option = actions.user.hud_create_button("Add code language", add_statusbar_programming_icon, "text_navigation")
    activated_option = actions.user.hud_create_button("Remove code language", remove_statusbar_programming_icon, "text_navigation")
    status_option = actions.user.hud_create_status_option("programming_toggle", default_option, activated_option)
    actions.user.hud_publish_status_option("programming_option", status_option)

app.register("ready", register_language_poller)

def load_languages(languages_file):
    languages = {}
    languages_header = "Language,Extension,Icon"
    if not os.path.exists(languages_file):
        language_defaults = [
            "bash,.sh,programming_bash",
            "c,,programming_c",
            "cplusplus,.cpp,programming_cplusplus",
            "csharp,.cs,programming_cplusplus",
            "objectivec,,programming_objectivec",
            "haskel,.hs,programming_haskel",
            "swift,,programming_swift",
            "rust,.rs,programming_rust",
            "r,.r,programming_r",
            "php,.php,programming_php",
            "ruby,.rb,programming_ruby",
            "python,.py,programming_python",
            "lua,.lua,programming_lua",
            "html,.html,programming_html",
            "javascript,.js,programming_javascript",
            "typescript,.ts,programming_typescript",
            "perl,.pl,programming_perl",
            "json,.json,programming_json",
            "markdown,.md,programming_markdown",
            "yaml,.yml,"
        ]
        file_contents = "" + languages_header + "\n"
        file_contents += "\n".join(language_defaults)
        with open(languages_file, "w") as f:
            f.write(file_contents)

    with open(languages_file, "r") as file:
        for line in file.readlines():
            if line == languages_header:
                continue
            split_vars = line.strip().split(",")
            if len(split_vars) > 1:
                language = {}
                language["extension"] = split_vars[1]
                if len(split_vars) > 2:
                    language["icon"] = split_vars[2]
                else:
                    language["icon"] = ""
                languages[split_vars[0]] = language
    return languages

languages_file = os.path.join(hud_get_configuration("content_preferences_folder"), "programming_languages.csv")
languages = load_languages(languages_file)

mod = Module()
@mod.action_class
class Actions:

    def hud_get_available_languages():
        """Get the available programming languages inside of the HUD"""
        global languages
        return languages

    def hud_can_toggle_programming_language() -> bool:
        """Check if we should be able to toggle the programming language from the status bar"""
        active_modes = scope.get("mode")
        if (active_modes is not None):
            for index, active_mode in enumerate(active_modes):
                if (active_mode.replace("user.", "") in languages.keys()):
                    return True
        return False

    def hud_toggle_programming_language():
        """Toggle the programming language manually in the status bar"""
        actions.user.code_clear_language_mode()

    def hud_get_programming_language() -> str:
        """Get the programming language to be displayed in the status bar - By default tries to mimic knausj"""
        active_modes = scope.get("mode")
        if (active_modes is not None):
            for index, active_mode in enumerate(active_modes):
                if (active_mode.replace("user.", "") in languages.keys()):
                    return active_mode.replace("user.", "")

        active_tags = scope.get("tag")
        if "user.auto_lang" in active_tags:
            lang = actions.code.language()
            if lang:
                return lang
        if (active_tags is not None):
            for index, active_tag in enumerate(active_tags):
                if (active_tag.replace("user.", "") in languages.keys()):
                    return active_tag.replace("user.", "")

        lang = actions.code.language()
        if not lang:
            return ""
        else:
            return lang if lang else ""


"""
The heartbeat class implements the logic for sending heartbeats every
configured interval.

"""
import logging
import threading

LOGGER = logging.getLogger(__name__)

class Heartbeat(object):
    """Send a heartbeat frame every interval if no data has been written.

    :param rabbitpy.io.IO io: Used to get the # of bytes written each interval
    :param rabbitpy.channel0.Channel channel0: The channel that the heartbeat
        is sent over.

    """

    def __init__(self, io, channel0, interval):
        self._channel0 = channel0
        self._interval = float(interval) / 2.0
        self._io = io
        self._last_written = self._io.bytes_written
        self._lock = threading.Lock()
        self._timer = None

    def start(self):
        """Start the heartbeat checker"""
        if not self._interval:
            LOGGER.debug('Heartbeats are disabled, not starting')
            return
        self._start_timer()
        LOGGER.debug('Heartbeat started, ensuring data is written at least '
                     'every %.2f seconds', self._interval)

    def stop(self):
        """Stop the heartbeat checker"""
        if self._timer:
            self._timer.cancel()
            self._timer = None

    def _start_timer(self):
        """Create a new thread timer, destroying the last if it existed."""
        if self._timer:
            del self._timer
        self._timer = threading.Timer(self._interval, self._maybe_send)
        self._timer.daemon = True
        self._timer.start()

    def _maybe_send(self):
        """Fired by threading.Timer every ``self._interval`` seconds to
        maybe send a heartbeat to the remote connection, if no other frames
        have been written.

        """
        if not self._io.bytes_written - self._last_written:
            self._channel0.send_heartbeat()
        self._lock.acquire(True)
        self._last_written = self._io.bytes_written
        self._lock.release()
        self._start_timer()


s = input()
vowels='AEIOU'
kevin_score = 0
stuart_score = 0

# there is (len(s) - i) substrings
# starting from index i in s
for index in range(len(s)):
    if s[index] in vowels:
        kevin_score += len(s) - index
    else:
        stuart_score += len(s) - index

if kevin_score > stuart_score:
    print('Kevin {}'.format(kevin_score))
elif kevin_score < stuart_score:
    print('Stuart {}'.format(stuart_score))
else:
    print('Draw')


'''
Problem #6: Rounding
'''

def round_division():
    '''Returns a string of divisions rounded to the nearest integer.'''
    number_cases = int(input())
    result_list = []

    for _ in range(number_cases):
        int_a, int_b = [int(x) for x in input().split()]
        result = round(int_a / int_b)
        result_list.append(result)

    result_string = ' '.join(str(result) for result in result_list)
    return result_string

if __name__ == '__main__':
    print(round_division())


##    1. (5 баллов) Скачать отсюда архив страниц интернет-сайта с тайско-английским словарём. Извлечь с каждой страницы
##    пары "тайское слово -- английское слово" и поместить их в питоновскую структуру данных типа "словарь",
##    где ключом будет тайское слово, а значением - английское.
##
##    2. (8 балла) Использовать структуру данных из предыдущего задания, записать её в файл формата json на диск,
##    а также создать ещё одну структуру данных, где будет наоборот: английское слово ключ, а массив тайских слов - значение.
##    Её тоже записать на диск в формате json.
##
##    3. (10 баллов) Создать на фласке веб-приложение "Англо-тайский словарь", где можно было бы в текстовом поле ввести английское слово
##    и получить в качестве результата запроса - его перевод на тайский.

from bs4 import BeautifulSoup
import json
import os
import re

def get_dict(html):
    d = {}
    soup = BeautifulSoup(html, 'html.parser')
    text = soup.get_text()
    tr_items = soup.find_all('tr')
    for it in tr_items:
        trs = it.find_all('td')
        if trs:
            w = trs[0].find('a')
            if w:
                w = w.get_text()
                d[w] = trs[-1].get_text()
    return d

def crawl():
    d = {}
    lst = os.listdir('thai_pages')
    for fl in lst:
        with open('thai_pages/'+fl, 'r', encoding='utf-8') as f:
            html = f.read()
            d.update(get_dict(html))
    return d #5

def jsonify(d):
    text = json.dumps(d)
    with open('thai-eng.json', 'w', encoding='utf-8') as f:
        f.write(text)
    inv_d = {}
    for key in d:
        if ';' in d[key]:
            keys = d[key].split(';')
            for k in keys:
                inv_d[k.strip()] = key
        else:
            inv_d[d[key]] = key
    text_i = json.dumps(inv_d)
    with open('eng-thai.json', 'w', encoding='utf-8') as f:
        f.write(text_i) #8

def main():
    d = crawl()
    jsonify(d)

if __name__ == '__main__':
    main()


import argparse
from config import *
from game import Game
from network import Network
import pygame
from random import randint
import signal
import sys

parser = argparse.ArgumentParser(description="Float Fight, made with pygame")
parser.add_argument('--number', required=True, help="A game number from 0-1000")
args = parser.parse_args()

game_number = int(args.number)
our_team_id = randint(0, 1000)

if game_number < 0 or game_number > 1000:
    print("\nERROR: The game number must be between 0 and 1000.\n")
    sys.exit(1)

pygame.init()
pygame.display.set_caption(f"Float Fight - Game #{game_number}")
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()

def handle_sigint(sig, frame) -> None:
    """
    If the user presses CTRL+C or closes the game window, this function will get called. It sets a variable
    called shutdown_signal to be True. The game's event loop keeps going and going. That is, unless it sees
    this variable change, in which case the program will exit.
    """
    global shutdown_signal
    if sig == signal.SIGINT:
        print('Received Ctrl+C. Shutting down...')
        shutdown_signal = True

shutdown_signal = False
# handle_sigint is the function that is defined a few lines up. We're telling Python that, if the window gets
# closed, handle_sigint is the function that should get called so that we can do something in response.
signal.signal(signal.SIGINT, handle_sigint)

network = Network(game_number, our_team_id)
networking_thread = network.start()

game = Game(screen, network.get_messages_to_send(), our_team_id)
pygame.display.update()

# This is the game's event loop, which keeps going and going, handling any events
# that pygame tells it about.
while not shutdown_signal:
    clock.tick(10) # limits frames per second to 10

    for event in pygame.event.get():
        # All events come through here. All events have a type, and if the type is USEREVENT, we know that
        # it's one that our own code created, to announce to the rest of the code that something has happened.
        # For example, maybe a message arrived from our opponent, or maybe one of the cells on the board needs
        # to announce that it was clicked and a move was made.

        try:
            if event.type == pygame.QUIT:
                shutdown_signal = True
            elif event.type == pygame.USEREVENT and event.action == ACTION_GAME_STATE_CHANGED:
                # While the game is in a preparing state, the network code knows to keep announcing "I'm here!
                # I'm here!" so our opponent can find us. Once the game state changes, the network code knows
                # not to do that anymore. That's why we tell it about game state changes, too.
                network.update_game_state(event.state)

            # Redrawing the whole screen too often can be a lot of work for pygame, so we only do it when we need
            # to. The game module's handle_event does all sorts of things. It was written to always return either
            # True or False when it's done. True means that something changed that should make the screen look
            # different and we should redraw it. False means that everything can keep looking the same.
            if game.handle_event(event) is True:
                game.draw_game()
                pygame.display.update()

        except Exception as ex:
            print(f"ERROR:    {ex}")

network.shutdown()
networking_thread.join()

pygame.quit()
sys.exit(0)


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

from typing import Union, cast

import pytest

from jsonbourne import JsonObj

pytestmark = [pytest.mark.pydantic, pytest.mark.optdeps]

try:
    from pydantic import BaseModel, ConfigDict

    _extra = "allow" if "pytest" in sys.modules else "ignore"
    _model_config = cast(ConfigDict, {"extra": _extra})

    class PydanticJsonObj(BaseModel, JsonObj[Union[str, int]]):  # type: ignore[misc]
        a: int
        b: int
        c: str

        @property
        def a_property(self) -> str:
            return "prop_value"

        model_config = _model_config

    class PydanticJsonObjPropertySetter(BaseModel, JsonObj):  # type: ignore[misc]
        a: int
        b: int
        c: str

        #
        @property
        def aprop(self) -> int:
            return self.a

        @aprop.setter
        def aprop(self, value: int) -> None:
            self.a = value

        model_config = _model_config

except Exception:
    pass

def test_jsonobj_property_pydantic() -> None:
    thing_w_prop = PydanticJsonObj(**{"a": 1, "b": 2, "c": "herm"})
    assert thing_w_prop.c == thing_w_prop["c"]
    assert thing_w_prop.a_property == "prop_value"
    assert thing_w_prop["a_property"] == "prop_value"

def test_jsonobj_property_pydantic_setattr_hasattr() -> None:
    thing_w_prop = PydanticJsonObj(**{"a": 1, "b": 2, "c": "herm"})
    assert thing_w_prop.c == thing_w_prop["c"]
    assert thing_w_prop.a_property == "prop_value"
    assert thing_w_prop["a_property"] == "prop_value"

def test_jsonobj_property_with_setter_pydantic() -> None:
    thing_w_prop = PydanticJsonObjPropertySetter(**{"a": 1, "b": 2, "c": "herm"})
    assert thing_w_prop.a == 1
    thing_w_prop.a = 123
    assert thing_w_prop.a == 123
    assert thing_w_prop.c == thing_w_prop["c"]
    assert thing_w_prop.aprop == 123


num = int(input('Enter a number greater than 5 : '))
try:
    assert num>=5, 'The number entered by you is not greater than 5'
    print('The number greater than 5 entered by you is :', num)
except AssertionError:
    print('The Entered number by you is not greater than 5. Please re-enter the number.')

# Code for finding highest Even number in a given list

def highest_even(li):
    Highest = 0
    for item in li:
        if item % 2 == 0:
            if item > Highest:
                Highest = item
    return Highest

print (highest_even ([21, 22, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]))

# Programme to find the highest number input by the user.
num = int (input ('Enter a number greater than 5 : '))
try:
    assert num >= 5, 'The number entered by you is not greater than 5'
    print ('The number greater than 5 entered by you is :', num)
except AssertionError:
    print ('The Entered number by you is not greater than 5. Please re-enter the number.')

#
num = [-5,4,3,2,1,0,-1,-2,-3,-4,-5]
for i in num:
    if(i<0):
        print(i)
    else :
        continue

# Classes
class PlayerCharacter:
    membership = True # Class Attribute which are static
    def __init__(self, name, age):
        if (age > 18):
            self.name = name #Declared Attribute which are dynamic
            self.age = age #Declared Attribute which are dynamic

    def run(self):#Method in a class
        print ('run')#Method in the class but the return is not defined and hence it will print run and then none because the return is none.

player1 = PlayerCharacter ('Ajay', 24) #Instantiate the class / Creating an object with the details mentioned.
player2 = PlayerCharacter ('Shital', 45) #Instantiate the class / Creating an object with the details mentioned.
player2.attack = '50' #adding of an attribute to the object
player1.membership = False #Changing the Class Attribute values

print (player2.name, player2.age)
print (f'My Name is {player1.name} and I am {player1.age} years old.')
print (player1.name, player1.age)
print(player2.attack)
print(player1.membership)
print(player1.name,player1.run())
print(player2.name,player2.run())


import numpy as np
import pandas as pd
import igraph as ig
import pyreadr
from genetic_algorithm.coverage_evaluation import coverage_sum

class EvaluationFunction(object):
	_instance = None

	def __new__(
			cls,
			smiles_distance_path,
			moa_distance_path,
			graph_distance_path,
			ppi_path,
			graph_rank_path,
			drug_targets_path
		):
		# Singleton design pattern
		if cls._instance is None:
			cls._instance = super(EvaluationFunction, cls).__new__(cls)
			cls._instance.smiles_distances = pyreadr.read_r(smiles_distance_path)[None]
			cls._instance.moa_distances = pyreadr.read_r(moa_distance_path)[None]
			cls._instance.paths_distances = pyreadr.read_r(graph_distance_path)[None]
			cls._instance.ppi_network = ig.read(ppi_path)
			cls._instance.graph_rank = pyreadr.read_r(graph_rank_path)[None]
			cls._instance.L1000_drug_targets = pd.read_csv(drug_targets_path, sep="\t")
			cls._instance.drug_names = cls._instance.smiles_distances.index.to_list()
		return cls._instance

	def __call__(self, individual):
		if np.sum(individual) <= 1:
			return (0, 0, 0, 1, len(self.drug_names))
		candidate_drugs = [self.drug_names[i] for i, bit in enumerate(individual) if bit == 1]
		smiles_submat = self.smiles_distances.loc[candidate_drugs, candidate_drugs]
		moa_submat = self.moa_distances.loc[candidate_drugs, candidate_drugs]
		paths_submat = self.paths_distances.loc[candidate_drugs, candidate_drugs]
		_, coverage_pval = coverage_sum(
			candidate_drugs,
			self.L1000_drug_targets,
			self.ppi_network,
			self.graph_rank
		)
		n_drugs = np.sum(individual)
		#if (n_drugs > 100) or (n_drugs <= 0):
		#	n_drugs = 316
		linear_index = np.triu_indices(n_drugs, k=1)
		return (
			np.mean(smiles_submat.values[linear_index]),
			np.mean(moa_submat.values[linear_index]),
			np.mean(paths_submat.values[linear_index]),
			coverage_pval,
			n_drugs
		)


import socket
import tqdm
import os
import CGL_test_server as cgl_server
from multiprocessing import Process, Queue
import time

# device's IP address
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 5001
# receive 4096 bytes each time
BUFFER_SIZE = 4096
SEPARATOR = "<SEPARATOR>"

# create the server socket
# TCP socket
s = socket.socket()

# bind the socket to our local address
s.bind((SERVER_HOST, SERVER_PORT))

CGL_q = Queue()
a = Process(target=cgl_server.initialize, args=(CGL_q,))
a.start()

while True:
    s.listen(5)
    print("[*] Listening as {}:{}".format(SERVER_HOST, SERVER_PORT))

    client_socket, address = s.accept()
    print("[+] {} is connected.".format(address))

    received = client_socket.recv(BUFFER_SIZE).decode()

    filename, filesize, folder_name = received.split(SEPARATOR)
    filename = os.path.basename(filename)
    filesize = int(filesize)

    if not os.path.isdir("server/" + folder_name):
        os.mkdir("server/" + folder_name)

    progress = tqdm.tqdm(range(filesize), "Receiving {}".format(filename), unit="B", unit_scale=True, unit_divisor=1024)

    with open("server/" + folder_name + "/" + filename, "wb") as f:
        while True:
            bytes_read = client_socket.recv(BUFFER_SIZE)
            if not bytes_read:
                break
            f.write(bytes_read)
            progress.update(len(bytes_read))

    client_socket.close()
    CGL_q.put(folder_name + "/" + filename)

    while not os.path.exists("server_output/" + folder_name + "/" + filename):
        pass

    client_socket, address = s.accept()
    print("[+] {} is connected.".format(address))

    filename = "server_output/" + folder_name + "/" + filename

    filesize = os.path.getsize(filename)

    client_socket.send("{}{}{}".format(filename, SEPARATOR, filesize).encode())
    time.sleep(1)
    progress = tqdm.tqdm(range(filesize), "Sending {}".format(filename), unit="B", unit_scale=True, unit_divisor=1024)
    with open(filename, "rb") as f:
        while True:
            # read the bytes from the file
            bytes_read = f.read(BUFFER_SIZE)
            print("sending output")
            if not bytes_read:
                # file transmitting is done
                break
            client_socket.sendall(bytes_read)
            progress.update(len(bytes_read))

    client_socket.close()

    time.sleep(1)

s.close()


import unittest

from eva.Eva import Eva

class EvaTest(unittest.TestCase):
    """
    (if <condition>
        <consequent>
        <alternate>
    )
    """

    def test1(self):
        eva = Eva()
        self.assertEqual(eva.eval(
            ['begin',
             ['var', 'x', 10],
             ['var', 'y', 0],
             ['if', ['>', 'x', 10],
              ['set', 'y', 20],
              ['set', 'y', 30],
              ],
             'y'
             ],
        ), 30)


def make_positive(number):
    if number < 0:
        positive = number * -1  # or positive = abs(number)
        return positive
    else:
        return number

question = int(input("What is you number: "))
print(make_positive(question))


import logging

from django import forms
from django.db.models.functions import ExtractYear
from django.utils import six
from django.utils.encoding import force_text
from django.utils.html import conditional_escape

from .models import Deer, Hunter, Location, Log, LogSheet, Site

from library.forms import MultipleSelectWithAdd, SelectWithAdd

logger = logging.getLogger(__name__)

DEER_PREFIX = 'deer'
HUNTER_PREFIX = 'hunter'

def _get_year_field():
    year_choices = [
        (year, year) for year in
        LogSheet.objects.dates('date', 'year')
        .annotate(year=ExtractYear('date'))
        .order_by('year')
        .values_list('year', flat=True)
    ]

    return forms.MultipleChoiceField(choices=year_choices, label='', widget=forms.SelectMultiple(attrs={'size': 20}))

class DeerForm(forms.ModelForm):
    hunter_formset_number = forms.IntegerField(widget=forms.HiddenInput())

    class Meta:
        # Sets the order the fields will be displayed
        fields = ['count', 'gender', 'points', 'tracking', 'log', 'hunter_formset_number']
        model = Deer
        widgets = {'log': forms.HiddenInput}

    def __init__(self, *args, **kwargs):
        log_required = kwargs.pop('log_required', False)
        super().__init__(*args, **kwargs)
        if not log_required:
            self.fields['log'].required = False

    def clean(self):
        cleaned_data = super().clean()
        count = cleaned_data['count']
        gender = cleaned_data['gender']
        points = cleaned_data['points']
        tracking = cleaned_data['tracking']

        if count:
            log = cleaned_data['log']

            if log.hunter is None:
                raise forms.ValidationError(
                    'Hunter needs to be specified when any deer are shot or killed. If not specified, '
                    'list first name as <unknown>.'
                )

            if gender is None:
                self.add_error('gender', 'Need to specify the deer gender when any are shot or killed')

            if gender == Deer.GENDER_MALE and points is None:
                self.add_error('points', 'Male deer need the number of points specified')

            if tracking is None:
                self.add_error(
                    'tracking', 'Need to specify if tracking was required when any deer are shot or killed'
                )
        else:
            if gender is not None:
                self.add_error('gender', 'Gender is set but the count equals 0')

            if points is not None:
                if gender == Deer.GENDER_MALE:
                    self.add_error('points', 'Points is set but the count equals 0')
                else:
                    self.add_error('points', 'Points is set but the count equals 0 and the gender is Female')

        return cleaned_data

DeerFormSet = forms.formset_factory(DeerForm, extra=0)

class HunterAnalysisForm(forms.Form):
    years = _get_year_field()

    hunter_choices = [(hunter.id, str(hunter)) for hunter in Hunter.objects.exclude(first_name='<unknown>')]

    hunters = forms.MultipleChoiceField(
        choices=hunter_choices, label='', widget=forms.SelectMultiple(attrs={'size': 20})
    )

class HunterForm(forms.ModelForm):
    hunter_formset_number = forms.IntegerField(widget=forms.HiddenInput())
    location_id = forms.IntegerField(widget=forms.HiddenInput())    # Store only the ID, so we can avoid the large list
    log_sheet_id = forms.IntegerField(widget=forms.HiddenInput())   # Store only the ID, so we can avoid the large list
    pk = forms.IntegerField(required=False, widget=forms.HiddenInput())  # Need this to add instance to form later

    class Meta:
        exclude = ['location', 'log_sheet']
        model = Log
        widgets = {
            'hunter': SelectWithAdd(),
            'incorrect_warnings': forms.CheckboxSelectMultiple,
            'missing_warnings': forms.CheckboxSelectMultiple
        }

    def as_table(self):
        return self._as_table('hunter') + \
               '
Deer
' + \
               self._as_table('comment')

    def _as_table(self, field_name):
        bf = self[field_name]
        bf_errors = self.error_class([conditional_escape(error) for error in bf.errors])

        if bf.label:
            label = conditional_escape(force_text(bf.label))
            label = bf.label_tag(label) or ''
        else:
            label = ''

        if self.fields[field_name].help_text:
            help_text = f'{force_text(self.fields[f"{field_name}"].help_text)}'
        else:
            help_text = ''

        error_row = f'
{force_text(bf_errors)}
' if bf_errors else ''

        if field_name == 'hunter':
            return f"""
                {error_row}

                    {label}

                        {six.text_type(self['pk'])}
                        {six.text_type(self['log_sheet_id'])}
                        {six.text_type(self['location_id'])}
                        {six.text_type(self['hunter_formset_number'])}
                        {six.text_type(bf)}{help_text}

                        {six.text_type(self['missing_warnings'])}
                        {six.text_type(self['incorrect_warnings'])}

            """
        else:
            return f"""
                {error_row}

                    {label}
                    {six.text_type(bf)}{help_text}

            """

HunterFormSet = forms.formset_factory(HunterForm, extra=0)

class LocationAnalysisForm(forms.Form):
    years = _get_year_field()

    location_choices = [
        (location, location)
        for location in Location.objects.distinct().values_list('label', flat=True).order_by('label')
    ]

    locations = forms.MultipleChoiceField(
        choices=location_choices, label='', widget=forms.SelectMultiple(attrs={'size': 20})
    )

class LocationForm(forms.Form):
    location = forms.ModelMultipleChoiceField(
        Location.objects.none(), label='', widget=MultipleSelectWithAdd(attrs={'size': 20})
    )

    def __init__(self, **kwargs):
        self.year = kwargs.pop('year')
        super().__init__()
        self.fields['location'].queryset = Location.objects.filter(year=self.year)
        self.initial['location'] = kwargs.get('initial', {'location': []})['location']

    def as_p(self):
        html = super().as_p()
        return html.replace('
', '
').replace(f'[{self.year}] ', '')

class LogSheetForm(forms.Form):
    log_sheet = forms.ModelChoiceField(LogSheet.objects.all(), widget=SelectWithAdd())

class SiteAnalysisForm(forms.Form):
    site_choices = [(site, site) for site in Site.objects.exclude(street='')]

    sites = forms.MultipleChoiceField(
        choices=site_choices, label='', widget=forms.SelectMultiple(attrs={'size': 20})
    )


"""Find all matching values in a k-ary tree."""
from ..queue.queue import Queue

def find_matches(tree, value=None):
    """
    Find all matching values in a tree.

    Input: k-ary tree with non-unique values and a target value
    Output: collection of all the nodes from within the tree that match the provided value
    """
    if tree is None or tree.root is None:
        raise ValueError('Must provide tree')

    if value is None:
        raise ValueError('Must provide value')

    result = []
    queue = Queue()
    queue.enqueue(tree.root)

    while queue:
        current = queue.dequeue()
        if current.val == value:
            result.append(current)
        for child in current.children:
            queue.enqueue(child)

    return result


class Solution(object):
    def numDecodings(self, s):
        """
        :type s: str
        :rtype: int
        """
        # The mapping below isn't necessary since we are returnning the number of encodings.
        # In this case, we would use a decision tree, which is a brute force approach. O(2^n)
        # for each decision having a max of two next decisions.
        # letterToNum = {
        #    '1' : 'A',
        #    '2' : 'B',
        #    '3' : 'C',
        #    '4' : 'D',
        #    '5' : 'E',
        #    '6' : 'F',
        #    '7' : 'G',
        #    '8' : 'H',
        #    '9' : 'I',
        #    '10' : 'J',
        #    '11' : 'K',
        #    '12' : 'L',
        #    '13' : 'M',
        #    '14' : 'N',
        #    '15' : 'O',
        #    '16' : 'P',
        #    '17' : 'Q',
        #    '18' : 'R',
        #    '19' : 'S',
        #    '20' : 'T',
        #    '21' : 'U',
        #    '22' : 'V',
        #    '23' : 'W',
        #    '24' : 'X',
        #    '25' : 'Y',
        #    '26' : 'Z'
        #}

        # This is a recursive dynamic programming solution.

        dp = {len(s) : 1}
        def dfs(i):
            if i in dp:
                return dp[i]
            if s[i] == '0':
                return 0
            result = 0
            result += dfs(i + 1) # Taking i as a single digit.
            if (i + 1 < len(s)) and (s[i] == '1' or (s[i] == '2' and int(s[i+1]) <= 6)):
                result += dfs(i + 2)
            dp[i] = result
            return result
        return dfs(0)

        # This is a bottom-up iterative DP solution.
        """
        if not s:
            return 0
        dp = [0 for i in range(len(s) + 1)]
        dp[0] = 1
        dp[1] = 0 if s[0] == '0' else 1
        for i in range(2, len(s) + 1):
            # One digit jump
            if 0 < int(s[i-1]) <= 9:
                dp[i] += dp[i - 1]
            # Two digit jump
            if 10 <= int(s[i-2 : i]) <= 26:
                dp[i] += dp[i-2]
        return dp[len(s)]
        """


#Author: Eduardo Santos Carlos de Souza

#Usage:
#argv[1] = number of folds
#argv[2] = filename of images array
#argv[3] = filename of labels array
#argv[4] = folder to save the folds

import numpy as np
import sys
import os.path

#Carregar imagens, labels e modelos
images = np.load(sys.argv[2])
labels = np.load(sys.argv[3])
n_images = images.shape[0]
shuff = np.random.permutation(n_images)
images, labels = images[shuff], labels[shuff]

images_name = str(os.path.split(sys.argv[2])[-1])
labels_name = str(os.path.split(sys.argv[3])[-1])
out_path = sys.argv[4]

folds = int(sys.argv[1])
fold_size = int(n_images/folds)
for i in range(folds):
	train_images = np.concatenate((images[0:i*fold_size], images[(i+1)*fold_size:n_images]))
	train_labels = np.concatenate((labels[0:i*fold_size], labels[(i+1)*fold_size:n_images]))
	test_images = images[i*fold_size:(i+1)*fold_size]
	test_labels = labels[i*fold_size:(i+1)*fold_size]

	train_path = "fold_" + str(i) + "_train_"
	test_path = "fold_" + str(i) + "_test_"
	np.save(os.path.join(out_path, train_path + images_name), train_images)
	np.save(os.path.join(out_path, train_path + labels_name), train_labels)
	np.save(os.path.join(out_path, test_path + images_name), test_images)
	np.save(os.path.join(out_path, test_path + labels_name), test_labels)

	print("Fold " + str(i))
	print("Train: [0, " + str(i*fold_size) + ") U [" + str((i+1)*fold_size) + ", " + str(n_images) + "); Images Shape: " + str(train_images.shape))
	print("Test: [" + str(i*fold_size) + ", " + str((i+1)*fold_size) + "); Images Size: " + str(test_images.shape))


import tensorflow as tf
from keras import layers, models

class FashionNet():

    def __init__(self, X_train, X_test, Y_train_category, Y_test_category, Y_train_color, Y_test_color, epochs):
        self.X_train = X_train
        self.X_test  = X_test
        self.Y_train_category = Y_train_category
        self.Y_test_category  = Y_test_category
        self.Y_train_color = Y_train_color
        self.Y_test_color  = Y_test_color
        self.epochs = epochs
    def build(self):
        input_layer = layers.Input(shape = (64, 64, 3))
        x = layers.Conv2D(64, (3,3), activation = "relu")(input_layer)
       # x = layers.Conv2D(64, (3,3), activation = "relu")(x)
        x = layers.MaxPool2D()(x)
        x = layers.Conv2D(128, (3,3), activation = "relu")(x)
       # x = layers.Conv2D(128, (3,3), activation = "relu")(x)
        x = layers.MaxPool2D()(x)
        x = layers.Conv2D(256, (3,3), activation = "relu")(x)
       # x = layers.Conv2D(256, (3,3), activation = "relu")(x)
       # x = layers.Conv2D(256, (3,3), activation = "relu")(x)
        x = layers.MaxPool2D()(x)
        x = layers.Conv2D(512, (3,3), activation = "relu")(x)
       # x = layers.Conv2D(512, (3,3), activation = "relu")(x)
       # x = layers.Conv2D(512, (3,3), activation = "relu")(x)
        x = layers.MaxPool2D()(x)
        x = layers.Conv2D(512, (3,3), strides = (2,2), activation = "relu")(x)
       # x = layers.Conv2D(512, (3,3), strides = (2,2),activation = "relu")(x)
       # x = layers.Conv2D(512, (3,3), strides = (2,2),activation = "relu")(x)
        x = layers.MaxPool2D()(x)
        x = layers.Flatten()(x)
        category_output = layers.Dense(4, activation = "softmax")(x)
        color_output = layers.Dense(3, activation = "softmax")(x)

        net = models.Model(inputs = input_layer,
                            outputs = [category_output, color_output],
                            name = "FashionNet")

        losses = { "category_output": "categorical_crossentropy",
                    "color_output"  : "categorical_crossentropy" }
        loss_weights = { "category_output": 1.0,
                          "color_output"  : 1.0 }
        net.compile(optimizer = "adam",
                    loss = losses,
                    loss_weights = loss_weights,
                    metrics = ['accuracy'])
        H = net.fit(x = self.X_train,
                    y = {"category_output": self.Y_train_category,
                    "color_output"  : self.Y_train_color},
                    validation_data = (self.X_test,
                    {"category_output": self.Y_test_category,
                    "color_output"  : self.Y_test_color}),
                    epochs = self.epochs,
                    verbose = 1)


# -*- coding: cp1252 -*-
"""
Created on Sun Jan 25 18:32:50 2015

@author: ggrbill
"""
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import TerzaghisProblemAnalytical as analytical

t = open("Terzaghi_6_Dt_0_1_EBFVM//topDisplacement_602.csv")
b = open("Terzaghi_6_Dt_0_1_EBFVM//BottomPressure_602.csv")

t1 = open("Terzaghi_2Regions_0_Rk_10_EBFVM//topDisplacement_602.csv")
b1 = open("Terzaghi_2Regions_0_Rk_10_EBFVM//BottomPressure_602.csv")

t2 = open("Terzaghi_2Regions_3_Dif_Mec_EBFVM//topDisplacement_602.csv")
b2 = open("Terzaghi_2Regions_3_Dif_Mec_EBFVM//BottomPressure_602.csv")

nDiv = 1;

tList = ( t ).readlines();
bList = ( b ).readlines();

tList1 = ( t1 ).readlines();
bList1 = ( b1 ).readlines();

tList2 = ( t2 ).readlines();
bList2 = ( b2 ).readlines();

numberOfLines = len( tList1 ) - 3;
numberOfPoints = int(numberOfLines/nDiv);

currentTime = []
topDisplacement = []
bottomPressure = []
topDisplacement1 = []
bottomPressure1 = []
topDisplacement2 = []
bottomPressure2 = []

TopStress = 1.0e+6 # Pa
for i in range(numberOfPoints):
    pointIndex = i*nDiv;
    currentTime.append( float( tList[pointIndex+3].split(',')[0] ) )
    topDisplacement.append( float( tList[pointIndex+3].split(',')[1] )*1000 )
    bottomPressure.append( float( bList[pointIndex+3].split(',')[1] ) /1000 )
    topDisplacement1.append( float( tList1[pointIndex+3].split(',')[1] )*1000 )
    bottomPressure1.append( float( bList1[pointIndex+3].split(',')[1] ) /1000 )
    topDisplacement2.append( float( tList2[pointIndex+3].split(',')[1] )*1000 )
    bottomPressure2.append( float( bList2[pointIndex+3].split(',')[1] ) /1000 )

t.close()
b.close()
t1.close()
b1.close()
t2.close()
b2.close()

currentTime = np.array(currentTime)
topDisplacement = np.array(topDisplacement)
bottomPressure = np.array(bottomPressure)
topDisplacement1 = np.array(topDisplacement1)
bottomPressure1 = np.array(bottomPressure1)
topDisplacement2 = np.array(topDisplacement2)
bottomPressure2 = np.array(bottomPressure2)

## Lista de Cores
color_list = [  '#4F81BD', '#9BBB59', '#F79646' ]
lineWidth = 1.2

## Mudando configurações padrões da borda do gráfico e das linhas de marcadores dos eixos (ticks markers)
matplotlib.rc('axes' ,edgecolor='#4F4F4F', linewidth = 1.5)
matplotlib.rcParams['xtick.major.size'] = 0
matplotlib.rcParams['xtick.minor.size'] = 0
matplotlib.rcParams['ytick.major.size'] = 0
matplotlib.rcParams['ytick.minor.size'] = 0

## Usando fontes do Latex
matplotlib.rc('font',**{'family':'serif','serif':['charter']})
matplotlib.rc('text', usetex=True)

## Criando o gráfico
fig = plt.figure( num = 1, figsize = (10,6) )
axis = plt.subplot(111)

## Plotando dados (função loglog) e linhas de grade (função grid)
plt.grid( True, which='both', axis='both', linestyle = '-', color = '#B5B5B5' )
plt.plot( currentTime, topDisplacement , '-', color = color_list[0], linewidth = lineWidth, label = 'Single Column')
plt.plot( currentTime, topDisplacement1, '-', color = color_list[1], linewidth = lineWidth, label = 'Double Column - Two Permeabilities')
plt.plot( currentTime, topDisplacement2, '-', color = color_list[2], linewidth = lineWidth, label = 'Double Column - Two Materials')

## Mudando a posição e tamanho da área de plotagem
#box = axis.get_position()
#axis.set_position([box.x0-0.03, box.y0+0.03, box.width*0.7, box.height])

## linhas de grade posicionadas atrás das curvas plotadas
axis.set_axisbelow( True )
## Invertendo direção do Eixo Y
axis.invert_yaxis()

## Tamanho da fonte dos "labels" dos marcadores (ticks)
plt.tick_params( axis='both', which='major', labelsize=12)

## Configurando a legenda e os "labels" dos eixos - - -  bbox_to_anchor = (1.05, 0.5)
plt.legend(loc = "center right", numpoints = 1, fontsize = 12, frameon=True, title=r"\bf{Vertical displacement}" )
plt.ylabel( r" Displacement(mm)", size = 16)
plt.xlabel( r" Time(s) ", size = 16)

##plt.savefig('C:\\Users\\ggrbill\\Desktop\\figure2.pdf')
plt.show()

## Criando o gráfico
fig = plt.figure( num = 2, figsize = (10,6) )
axis = plt.subplot(111)

## Plotando dados (função loglog) e linhas de grade (função grid)
plt.grid( True, which='both', axis='both', linestyle = '-', color = '#B5B5B5' )
plt.plot( currentTime, bottomPressure , '-', color = color_list[0], linewidth = lineWidth, label = 'Single Column')
plt.plot( currentTime, bottomPressure1, '-', color = color_list[1], linewidth = lineWidth, label = 'Double Column - Two Permeabilities')
plt.plot( currentTime, bottomPressure2, '-', color = color_list[2], linewidth = lineWidth, label = 'Double Column - Two Materials')

## Mudando a posição e tamanho da área de plotagem
#box = axis.get_position()
#axis.set_position([box.x0-0.03, box.y0+0.03, box.width*0.7, box.height])

## linhas de grade posicionadas atrás das curvas plotadas
axis.set_axisbelow( True )

## Tamanho da fonte dos "labels" dos marcadores (ticks)
plt.tick_params( axis='both', which='major', labelsize=12)

## Configurando a legenda e os "labels" dos eixos
plt.legend(loc = "upper right", numpoints = 1, fontsize = 12, frameon=True, title=r"\bf{Pressure}" )
plt.ylabel( r" Pressure(kPa)", size = 16)
plt.xlabel( r" Time(s) ", size = 16)

##plt.savefig('C:\\Users\\ggrbill\\Desktop\\figure2.pdf')
plt.show()


# -*- coding: utf-8 -*-
"""
Created on Sun Jul  5 16:23:59 2020

@author: CODER_RITVIK
"""

import json                             #importing the required packages
from difflib import get_close_matches

data = json.load(open("data.json"))     #loadind the required JSON file

def translate(w):
    w = w.lower()                   #returns the lowercase of the string
    if w in data:
        return data[w]

    elif w.title() in data:         #it looks for the words like Delhi
        return data[w.title()]

    elif w.upper() in data:         #in case user enters words like USA
        return data[w.upper()]

    elif len(get_close_matches(w, data.keys())) > 0:         #if the required is not present in the dictionary
        yn = input("Did you mean %s instead? Enter Y if yes, or N if no: " % get_close_matches(w, data.keys())[0])

        if yn == "Y":
            return data[get_close_matches(w, data.keys())[0]]

        elif yn == "N":
            return "The word doesn't exist. Please double check it."

        else:
            return "We didn't understand your entry."

    else:
        return "The word doesn't exist. Please double check it."

word = input("Enter word: ")         #inputting the required word
output = translate(word)

if type(output) == list:           #if the output is  a list
    for item in output:
        print(item)

else:
    print(output)                  #if the output is a string


import numpy as np
import matplotlib.pyplot as plt
import math
from numpy.polynomial import Polynomial as poly

def baseLsqm(x, y, bflag = True):
	if(np.size(x) != np.size(y)):
		raise ValueError('size of axes not identical')
	x2 = x**2
	y2 = y**2
	xy = np.array([x[i] * y[i] for i in range(np.size(x))])
	xavg = np.average(x)
	yavg = np.average(y)
	x2avg = np.average(x2)
	y2avg = np.average(y2)
	xyavg = np.average(xy)
	k = (xyavg - xavg * yavg) / (x2avg - xavg ** 2) if bflag else xyavg / x2avg
	b = yavg - k * xavg if bflag else 0
	dk = math.sqrt(((y2avg - yavg ** 2) / (x2avg - xavg**2) - k**2) / np.size(x)) if bflag else math.sqrt(((y2avg - k**2 * xavg ** 2) / (x2avg - xavg**2) - k**2) / np.size(x))
	db = dk * math.sqrt(x2avg - xavg**2) if bflag else 0
	return [k, b, dk, db]

def lsqm(x, y, dx = np.empty(0), dy = np.empty(0), bflag = True):
	if(dx.size == 0 and dy.size == 0):
		return baseLsqm(x, y)
	if(dx.size == 0):
		dx = np.zeros(np.size(x))
	if(dy.size == 0):
		dy = np.zeros(np.size(y))
	k, b, dk, db = baseLsqm(x, y, bflag)
	# Dk = math.sqrt(dk**2 + (dy[-1] / x[-1])**2 + ((y[-1] - b) * dx[-1] / x[-1]**2)**2)
	Dk = math.sqrt(dk**2 + (np.average(dy) / (np.average(x) - np.min(x)))**2 + (np.average(y) * np.average(dx) / (np.average(x) - np.min(x))**2)**2)
	# Db = math.sqrt(db**2 + dy[-1]**2 + (k * dx[-1])**2)
	# Dk = math.sqrt(dk**2 + (np.average(np.array([dy[i] / (x[i+1] - dx[i+1] - x[i] - dx[i]) for i in range(len(x) - 1)])))**2)
	Db = math.sqrt(db**2 + np.average(dy)**2 + (k * np.average(dx))**2) if bflag else 0
	return [k, b, Dk, Db]

def plot(x, y, dx = None, dy = None, filename = None, plotFmt = '.', title = None, xlabel = None, ylabel = None):
	fig, ax = plt.subplots()
	plt.minorticks_on()
	plt.grid(True, "major", "both", color = "#888888")
	plt.grid(True, "minor", "both", linestyle = '--')
	plt.title(title)
	plt.xlabel(xlabel)
	plt.ylabel(ylabel)
	ax.errorbar(x, y, dy, dx, fmt = plotFmt)
	if(filename != None):
		plt.savefig(filename)
	plt.show()

def plotLsqm(x, y, dx = np.empty(0), dy = np.empty(0), filename = None, plotFmt = '.', lsqmFmt = 'r', title = None, xlabel = None, ylabel = None, stretch = 0.1, bflag = True):
	if(dx.size == 0):
		dx = np.zeros(np.size(x))
	if(dy.size == 0):
		dy = np.zeros(np.size(y))
	k, b, dk, db = lsqm(x, y, dx, dy, bflag)
	fig, ax = plt.subplots()
	plt.minorticks_on()
	plt.grid(True, "major", "both", color = "#888888")
	plt.grid(True, "minor", "both", linestyle = '--')
	plt.title(title)
	plt.xlabel(xlabel)
	plt.ylabel(ylabel)
	xdist = np.max(x) - np.min(x)
	ax.plot([np.min(x) - stretch * xdist, np.max(x) + stretch * xdist], [k * (np.min(x) - stretch * xdist) + b, k * (np.max(x) + stretch * xdist) + b], lsqmFmt)
	ax.errorbar(x, y, dy, dx, fmt = plotFmt)
	if(filename != None):
		plt.savefig(filename)
	plt.show()
	return [k, b, dk, db]

def plotlsqm(x, y, dx = np.empty(0), dy = np.empty(0), filename = None, plotFmt = '.', lsqmFmt = 'r', title = None, xlabel = None, ylabel = None, stretch = 0.1, bflag = True):
	return plotLsqm(x, y, dx, dy, filename, plotFmt, lsqmFmt, title, xlabel, ylabel, stretch, bflag)

def plotPoly(n, x, y, dx = None, dy = None, filename = None, plotFmt = '.', polyFmt = 'r', title = None, xlabel = None, ylabel = None):
	fig, ax = plt.subplots()
	plt.minorticks_on()
	plt.grid(True, "major", "both", color = "#888888")
	plt.grid(True, "minor", "both", linestyle = '--')
	plt.title(title)
	plt.xlabel(xlabel)
	plt.ylabel(ylabel)
	approx = poly.fit(x, y, n)
	t = np.linspace(x[0], x[-1], num = 1000)
	ax.plot(t, approx(t), polyFmt)
	ax.errorbar(x, y, dy, dx, fmt = plotFmt)
	if(filename != None):
		plt.savefig(filename)
	plt.show()
	return approx

def basePlot():
	fig, ax = plt.subplots()
	plt.minorticks_on()
	plt.grid(True, 'major', 'both', color = '#888888')
	plt.grid(True, 'minor', 'both', linestyle = '--')
	return fig, ax


import sys
sys.stdin = open("그래프 경로_input.txt")

def reach(S):

    global V, E, line, matrix, G, visited   # 전역변수화

    visited[S] = 1   # 출발 노드 및 인접 노드는 무조건 방문했다고 표시

    for i in range(V+1):   # 인접행렬의 행 개수만큼 반복
        if matrix[S][i] == 1 and visited[i] == 0:   # 인접행렬의 출발 노드와 연결된 노드 + 아직 방문하지 않은 경우
            reach(i)   # i번 노드로 이동해서 위를 반복함 ex) 1 -> 4이면 4로 이동하고 4 -> 6으로 순환

    if visited[G] == 1:   # 도착 노드에 방문했다고 표시되면 1 반환
        return 1
    else:
        return 0   # 도착 노드에 방문하지 못했다고 표시되면 0 반환

T = int(input())

for tc in range(T):

    V, E = map(int, input().split())   # V = 노드 개수, E = 간선 개수
    line = []   # 노드 연결 정보(어떤 노드가 연결되었는지 보여주는 정보)

    for i in range(E):
        line += list(map(int, input().split()))

    S, G = map(int, input().split())   # S = 출발 노드, G = 도착 노드

    matrix = [[0 for _ in range(V+1)] for _ in range(V+1)]   # 인접행렬 생성
    visited = [0] * (V+1)  # 방문한 노드 표시하는 스택

    for j in range(0, len(line), 2):   # 인접행렬에 노드 연결정보 채우기
        matrix[line[j]][line[j+1]] = 1   # 방향성 있는 정보 채우기(x=진입, y=진출)

    # for k in range(len(matrix)):
    #     print(f'{k} {matrix[k]}')

    print(f'#{tc+1} {reach(S)}')


from funcionario import Funcionario
from typing import List
import datetime

class Medico(Funcionario):
  def __init__(self, data: dict):
    f = open("logs.txt", "a")
    try:
      self.__emAtendimento = data["emAtendimento"]
      self.__especialidade = data["especialidade"]
      super().__init__(data["nome"], data["idade"], data["sexo"], data["id"])
    except ValueError as e:
      print(e)
      f.write("{}: Dados incorretos de Médico, favor preencher corretamente a ficha de inscrição\n".format(datetime.datetime.now()))
    else:
      f.write("{}: Dados cadastrados com sucesso!\n".format(datetime.datetime.now()))
    f.close()

  def getEmAtendimento(self) -> bool:
    return self.__emAtendimento
  def getEspecialidade(self) -> str:
    return self.__especialidade

  def setEmAtendimento(self, atendendo: bool):
    self.__emAtendimento = atendendo
  def setEspecialidade(self, especialidade):
    self.__especialidade = especialidade

class Interno(Medico):
  def __init__(self, data: dict):
    try:
      if data["tempoDeInternato"] >= datetime.datetime.now():
        self.__tempoDeInternato = data["tempoDeInternato"] - datetime.datetime.now()
      else:
        raise Exception("Favor fornecer uma data válida")
      self.__supervisor = data["supervisor"]
      self.__rotacao = data["rotacao"]
      super().__init__(data)
    except :
      print("Dados incorretos de Interno, favor preencher corretamente a ficha de inscrição")
    else:
      f = open("logs.txt", "a")
      f.write("{}: Dados cadastrados com sucesso!\n".format(datetime.datetime.now()))
      f.close()

  def getTempoDeInternato(self) -> datetime:
    return self.__tempoDeInternato
  def getSupervisor(self):
    return self.__supervisor
  def getRotacao(self):
    return self.__rotacao

  def setTempoDeInternato(self, tempoInternato):
    if tempoInternato >= datetime.datetime.now():
      self.__tempoDeInternato = tempoInternato - datetime.datetime.now()
    else:
      raise Exception("Favor fornecer uma data válida")

class Titular(Medico):
  def __init__(self, data: dict):
    try:
      f = open("logs.txt", "a")
      super().__init__(data)
      if (type(data["crm"]) and type(data["areaAtuacao"])) is str:
        self.__crm = data["crm"]
        self.__areaAtuacao = data["areaAtuacao"]

      else:
        raise Exception("dados enviados estão com tipos incorretos")
    except:
      f.write("{}: Dados incorretos de Médico Titular, favor preencher corretamente a ficha de inscrição\n".format(datetime.datetime.now()))
    else:
      f.write("{}: Dados cadastrados com sucesso!\n".format(datetime.datetime.now()))

    f.close()

  def getCrm(self) -> str:
    return self.__crm
  def getAreaAtuacao(self) -> str:
    return self.__areaAtuacao

  def reCadastroTitular(self, data: dict):
    self.__crm = data["crm"]
    self.__areaAtuacao = data["areaAtuacao"]

  def setAreaAtuacao(self, areaAtuacao):
    self.__areaAtuacao = areaAtuacao

class Residente(Titular):
  def __init__(self, data: dict):
    try:
      f = open("logs.txt", "a")
      super().__init__(data)
      self.__supervisor = data["supervisor"]
    except:
      f.write("{}: Dados incorretos de Residente, favor preencher corretamente a ficha de inscrição\n".format(datetime.datetime.now()))
    else:
      f.write("{}: Dados cadastrados com sucesso!\n".format(datetime.datetime.now()))

    f.close()

  def getSupervisor(self) -> Titular:
    return self.__supervisor

  def reCadastroTitular(self, data: dict):
    f = open("logs.txt", "a")
    try:
      # utiliza o método da superclasse para cadastrar dados gerais, para depois cadastrar dados especificos
      self.__supervisor = data["supervisor"]
      super().reCadastroTitular(data)
    except:
      f.write("{}: Recadastro de Residente incompletos, favor preenchê-los integralmente\n".format(datetime.datetime.now()))
    else:
      f.write("{}: Dados cadastrados com sucesso!\n".format(datetime.datetime.now()))
    f.close()

class Cirurgiao(Titular):
  def __init__(self, data: dict):
    try:
      f = open("logs.txt", "a")
      self.__inicioDeCarreira = data["inicioDeCarreira"] #data de início do profissional na área de atuação
      self.__equipeCirurgica = data["equipeCirurgica"]
      super().__init__(data)
    except:
      f.write("{}: Dados incorretos de Residente, favor preencher corretamente a ficha de inscrição\n".format(datetime.datetime.now()))
    else:
      f.write("{}: Dados cadastrados com sucesso!\n".format(datetime.datetime.now()))

    f.close()

  def getInicioDeCarreira(self) -> datetime:
    return self.__inicioDeCarreira
  def getEquipeCirurgica(self) -> List[Titular]:
    try:
      return self.__equipeCirurgica
    except:
      raise Exception("Dados não são listas de Médicos titulares, favor preencher corretamente")

  def addMembroEquipe(self, membro: Titular):
    try:
      f = open("logs.txt", "a")
      self.__equipeCirurgica.append(membro)
    except:
      f.write("{}: Favor inserir dados corretamente\n".format(datetime.datetime.now()))
    else:
      f.write("{}: Membro cadastrado com sucesso!\n".format(datetime.datetime.now()))

    f.close()

  def removeMembroEquipe(self, membro: Titular):
    try:
      f = open("logs.txt", "a")
      self.__equipeCirurgica.remove(membro)
    except:
      f.write("{}: Médico não encontrado, favor colocar cadastro válido\n".format(datetime.datetime.now()))
    else:
      f.write("{}: Membro removido com sucesso.\n".format(datetime.datetime.now()))
    f.close()

  def reCadastroTitular(self, data: dict):
    try:
      # utiliza o método da superclasse para cadastrar dados gerais, para depois cadastrar dados especificos
      f = open("logs.txt", "a")
      self.__inicioDeCarreira = data["inicioDeCarreira"]
      self.__equipeCirurgica = data["equipeCirurgica"]
      super().reCadastroTitular(data)
    except:
      f.write("{}: Recadastro de Cirurgião incompletos, favor preenchê-los integralmente".format(datetime.datetime.now()))
    else:
      f.write("{}: Dados cadastrados com sucesso!\n".format(datetime.datetime.now()))

    f.close()

class MedicoClinico(Titular):
  def __init__(self, data: dict):
    f = open("logs.txt", "a")
    try:
      super().__init__(data)
      self.__endereco = data["enderecoClinica"]
    except:
      f.write("{}: Dados incorretos de Médico Geral, favor preencher corretamente a ficha de inscrição\n".format(datetime.datetime.now()))
    else:
      f.write("{}: Dados cadastrados com sucesso!\n".format(datetime.datetime.now()))
    f.close()

  def getEndereco(self):
    return self.__endereco
  def reCadastroTitular(self, data: dict):
    f = open("logs.txt", "a")
    try:
      # utiliza o método da superclasse para cadastrar dados gerais, para depois cadastrar dados especificos

      super().reCadastroTitular(data)
      self.__endereco = data["enderecoClinica"]

    except:
      f.write("{}: Recadastro de Médico Geral incompletos, favor preenchê-los integralmente\n".format(datetime.datetime.now()))
    else:
      f.write("{}: Dados cadastrados com sucesso!\n".format(datetime.datetime.now()))
    f.close()


from flask import Flask, jsonify
from flask_cors import CORS

from access_redis import read_redis
from process_message import seperate_sentence

DEBUG = True

app = Flask(__name__)
app.config.from_object(__name__)

CORS(app, resources={r'/*': {'origins': '*'}})

@app.route('/summarization', methods=['GET'])
def summarization():
    message_list = read_redis()
    wordcloud_data = seperate_sentence(message_list)
    return jsonify(wordcloud_data)

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


class Dish():
     cook_book = {}
     def __init__(self):
         with  open("recipes.txt",encoding="utf8") as dish_file:
             for text in dish_file:
                 if not text.strip():
                     break
                 else:
                     dish_name = text.strip().lower()
                     self.cook_book[dish_name] = []
                     ingr_count = int(dish_file.readline().strip())
                     while ingr_count:
                         ingr_info = dish_file.readline().strip().split('|')
                         self.cook_book[dish_name].append({"ingradient_name": ingr_info[0], "quantity" : float(ingr_info[1]), "measure" : ingr_info[2]})
                         ingr_count -= 1
                     dish_file.readline()

     def get_shop_list_by_dishes(self, dishes, person_count = 0):
             list_dishes = {}
             dishes = [x.lower() for x in dishes]
             if not person_count:
                 person_count = int(input("Введите количестко персон "))
             if dishes:
                      for user_dish in dishes:
                         if self.cook_book.get(user_dish.lower()):
                             for dish_name in self.cook_book[user_dish]:
                                     if dish_name["ingradient_name"] in list_dishes:
                                         list_dishes[dish_name["ingradient_name"]]["quantity"] += dish_name["quantity"] * person_count
                                     else:
                                         list_dishes[dish_name["ingradient_name"]] = {"measure": dish_name["measure"], "quantity":dish_name["quantity"] * person_count}
                         else:
                             print(f"нет такого блюда {user_dish}")

             return self.show_dict(list_dishes)

     def show_dict(self,some_dict = {}):
                for key,item in some_dict.items():
                     print(f"{key}   {str(item)}")

Dish().get_shop_list_by_dishes(["омлет","Утка по-пекински"], 3)

#print(Dish().get_shop_list_by_dishes([ "Запеченный картофь",'Омлет'], 0))


# 카드에서 원하는 조합이 나올 확률 구하기

numN = int(input('총 종이의 장 수 : '))
numR = int(input('뽑을 종이의 장 수 : '))
numNone = int(input('꽝의 장 수 : '))
print('선물 종이의 개수는 {} 장'.format(numN-numNone))
numPre = numN-numNone
numNoneCatch = int(input('꽝은 몇 장 뽑고 싶음?'))
print('뽑을 선물 종이의 개수는 {} 장'.format(numR - numNoneCatch))

numPreCatch = numR - numNoneCatch

if numR > numN:
    print('뽑는 종이의 총 개수를 잘못 입력했습니다')

if numNoneCatch > numNone:
    print('뽑는 꽝의 개수를 잘못 입력했습니다')

if numPreCatch > numPre:
    print('뽑는 선물의 개수를 잘못 입력했습니다')

def proFun(n,r):

    resultP = 1
    resultR = 1

    for i in range(n, (n - r), -1):
        resultP *= i

    for i in range(1, (r + 1)):
        resultR *= i

    return resultP//resultR

print( '{} %'.format(100*int(proFun(numNone,numNoneCatch))*int(proFun(numPre,numPreCatch))/(int(proFun(numN,numR)))))


# antlr4 -Dlanguage=Python3 GoLexer.g4
# antlr4 -no-listener -Dlanguage=Python3 GoParser.g4
# python main.py -compile input.txt
import sys
import os
from antlr4 import *
from GoLexer import GoLexer
from GoParser import GoParser
from TypeChecker import typeChecking
from ErrorHandler import MyErrorListener
from CodeGenerator import codeGen

def parse(file):
    err_listener = MyErrorListener()

    input_stream = FileStream(file)
    lexer = GoLexer(input_stream)

    lexer.removeErrorListeners()
    lexer.addErrorListener(err_listener)

    stream = CommonTokenStream(lexer)
    parser = GoParser(stream)
    parser.removeErrorListeners()
    parser.addErrorListener(err_listener)
    tree = parser.program()
    if tree.ast is None or len(err_listener.errors) != 0:
        sys.exit("LEXING/PARSING/AST-GENERATING FAILED")
    print("LEXING & PARSING & AST-GENERATING SUCCESSFUL")
    typeChecking(tree)
    print("TYPECHECKING SUCCESSFUL")
    print(tree.global_scope)
    return tree

if __name__ == '__main__':
    filename = "./test/valid_codesnipsets/assign_int_to_float64.go"
    tree = parse(filename)
    filename = filename.removesuffix(".go")
    code = codeGen(tree, filename)
    # with open(filename+".j", 'w') as file:
    #    file.write(code)


# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#              Predicting the future
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from numpy import newaxis
# We sorted descending
curr_frame = X_test[len(X_test)-1]
future = []

# Quick plot of the frame we're predicting from
plt.plot(curr_frame)

points_to_predict = 10
for i in range(points_to_predict):
      # append the prediction to our empty future list
     future.append(model.predict(curr_frame[newaxis,:,:])[0,0])
      # insert our predicted point to our current frame
     curr_frame = np.insert(curr_frame, len(X_test[0]), future[-1], axis=0)
      # push the frame up one to make it progress into the future
     curr_frame = curr_frame[1:]

plt.plot(future)


"""
Find the lowest hydraulic potential node for smooth KW geometry
to use as the domain outlet
"""

import numpy as np
from scipy import interpolate
from matplotlib import pyplot as plt

# Read in datasets
bed = np.loadtxt('bed_DEM.dat')
sfc = np.loadtxt('sfc_DEM.dat')
contour = np.loadtxt('KW_outline_simplified.txt', delimiter=',')

# Generate phi for different assumed floatation fraction
ffs = np.arange(0.5, 1.1, 0.1)

bed_elev = bed[:, -1].reshape(-1, 1)
sfc_elev = sfc[:, -1].reshape(-1, 1)
bed_xy = bed[:, :2]

rhow = 1000
rhoi = 910
g = 9.81

phi_bed = bed_elev*rhow*g
p_ice = (sfc_elev - bed_elev)*rhoi*g
phi = phi_bed + ffs*p_ice

fig, ax = plt.subplots()
# Interpolate
for i in range(len(ffs)):
    phi_interpolant = interpolate.NearestNDInterpolator(bed_xy, phi[:, i])
    phi_contour = phi_interpolant(contour)
    ax.plot(np.arange(0, len(phi_contour)), phi_contour)

    index_phi_min = np.argmin(phi_contour)
    print('Phi min index:', index_phi_min)

plt.show()


from django.contrib import admin
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction

from .models import DescribeExampleSet

class DescribeAdmin(admin.ModelAdmin):
    actions = ["use_examples"]
    list_display = (
        "name",
        "site",
        "example_image_file",
        "example_file",
    )
    fieldsets = (
        (None, {"fields": ("name", "site", "example_image_file", "example_file",)},),
    )
    # inlines = [JoinedInLine]

    @transaction.atomic()
    def use_examples(self, request, queryset):
        # get selected example set
        selected = queryset[0]
        # get current site
        current_site = get_current_site(request)

        # remove existing example set (if any)
        try:
            existing_examples = DescribeExampleSet.objects.get(site=current_site)
            if existing_examples.pk == selected.pk:
                # nothing to do!  already set
                self.message_user(request, f"{current_site.name} updated examples")
                return
            # de-select existing example set
            existing_examples.site = None
            existing_examples.save()
        except ObjectDoesNotExist:
            # default -- no example set was selected
            pass

        # update site
        DescribeExampleSet.objects.update_or_create(
            pk=selected.pk, defaults={"site": current_site}
        )
        self.message_user(request, f"{current_site.name} updated examples")

admin.site.register(DescribeExampleSet, DescribeAdmin)