# objects and their cost
prices = {'knight': 30,
          'king': 220,
          'wizard': 400,
          'dragon': 700,
          'level': 3000,
          'meteors': 1200}

# characters and their damage
damage = {'knight': 2.5,
          'king': 3.5,
          'wizard': 4.5,
          'dragon': 6,
          'meteors': 14,
          'arrow': 3}

# characters and their value
value = {'knight': 20,
          'king': 160,
          'wizard': 420,
          'dragon': 600}

# levels and their maximum healths
levels = {1: 3000,
          2: 6000,
          3: 10000}


# 3.- Mono Indexer

import pickle
import re
import sys
from SAR_p3_monkey_lib import Monkey

if __name__ == "__main__":

    if len(sys.argv) != 2 and (len(sys.argv) != 3 or sys.argv[-1] != "tri"):
        print("python %s textfile [tri]" % sys.argv[0])
        sys.exit(-1)

    txt_filename = sys.argv[1]
    use_tri = len(sys.argv) == 3 and sys.argv[-1] == "tri"
    i = txt_filename.rfind('.')
    index_filename = (txt_filename[:i] if i > 0 else txt_filename) + \
        ("_tri.index" if use_tri else ".index")

    m = Monkey()
    m.compute_index(txt_filename, use_tri)
    m.save_index(index_filename)


from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('register/', views.registerPage, name="register"),

    # path('', views.registerPage, name="register"),
    path('login/', views.loginPage, name="login"),
    path('logout/', views.logoutUser, name="logout"),

    # path('customer/<str:pk_test>/', views.customer, name="customer"),

    # path('create_store/<str:pk>/', views.createOrder, name="create_order"),
    path('update_store/<str:pk>/', views.updateStore, name="update_order"),
    path('delete_store/<str:pk>/', views.deleteStore, name="delete_order"),
    path('store/', views.stores, name='stores'),
    path('add_store/', views.addStore, name="add_store"),
    path('function_user/', views.functionUser, name="function_user")

]


import geopandas as gpd
import numpy as np
import pandas as pd
from sklearn.neighbors import KDTree

def configure(context):
    context.config("data_path")

REFERENCE_YEAR = 2018

SHAPEFILES = [
    (2018, "municipality_borders/gd-b-00.03-875-gg18/ggg_2018-LV95/shp/g1g18.shp", "GMDNR", "GMDNAME"),
    (2017, "municipality_borders/gd-b-00.03-875-gg17/ggg_2017/shp/LV95/g1g17.shp", "GMDNR", "GMDNAME"),
    (2016, "municipality_borders/gd-b-00.03-875-gg16/ggg_2016/shp/g1g16.shp", "GMDNR", "GMDNAME"),
    (2015, "municipality_borders/gd-b-00.03-876-gg15/GGG_15_V161025/shp/g1g15.shp", "GMDNR", "GMDNAME"),
    (2014, "municipality_borders/gd-b-00.03-877-gg14/ggg_2014/shp/g1g14.shp", "GMDNR", "GMDNAME"),
    (2013, "municipality_borders/gd-b-00.03-877-gg13_r1/ggg_2013/shp/g1g13.shp", "GMDNR", "GMDNAME"),
    (2012, "municipality_borders/gd-b-00.03-878-gg12/g1g12_shp_121130/G1G12.shp", "GMDE", "NAME"),
    (2011, "municipality_borders/gd-b-00.03-879-gg11/g1g11_shp_121130/G1G11.shp", "GMDE", "NAME"),
    (2010, "municipality_borders/gd-b-00.03-880-gg10/g1g10_shp_121130/G1G10.shp", "GMDE", "NAME"),
    (2009, "municipality_borders/gd-b-00.03-881-gg09g1/g1g09_shp_090626/G1G09.shp", "GMDE", "NAME")
]

def execute(context):
    data_path = context.config("data_path")

    df_all = []
    all_ids = set()

    # Load all the shape files, only add the municipalities that haven't been found before
    for year, shapefile, id_field, name_field in context.progress(SHAPEFILES, label="Reading municipality shape files"):
        df = gpd.read_file(
            "%s/%s" % (data_path, shapefile),
            encoding="latin1"
        ).to_crs("epsg:2056")

        df.crs = "epsg:2056"

        df.loc[:, "municipality_id"] = df[id_field]
        df.loc[:, "municipality_name"] = df[name_field]
        df.loc[:, "year"] = year

        df_ids = set(np.unique(df["municipality_id"]))
        df_new_ids = df_ids - all_ids

        df_all.append(
            df[df["municipality_id"].isin(df_new_ids)][["municipality_id", "municipality_name", "year", "geometry"]])
        all_ids |= df_new_ids

    df_all = pd.concat(df_all)

    df_reference = gpd.GeoDataFrame(df_all[df_all["year"] == REFERENCE_YEAR])
    df_reference.crs = df_all.crs

    df_deprecated = gpd.GeoDataFrame(df_all[df_all["year"] != REFERENCE_YEAR])
    df_deprecated["deprecated_municipality_id"] = df_deprecated["municipality_id"]
    del df_deprecated["municipality_id"]
    df_deprecated["geometry"] = df_deprecated.centroid
    df_deprecated.crs = df_all.crs

    # For each deprecated municipality find the covering reference municipality
    df_mapping = gpd.sjoin(
        df_reference, df_deprecated, op="contains"
    ).reset_index()[["municipality_id", "deprecated_municipality_id"]]

    # Now we are left over with some old municipalities whose centroids
    # are not covered by any new municipality (mainly at the border and
    # close to lakes). Therefore, we do another run and find the current
    # municipality with the closes distance (more expensive operation).

    missing_ids = set(
        np.unique(df_deprecated["deprecated_municipality_id"])
    ) - set(np.unique(df_mapping["deprecated_municipality_id"]))

    df_missing = df_deprecated[
        df_deprecated["deprecated_municipality_id"].isin(missing_ids)
    ][["deprecated_municipality_id", "geometry"]]

    coordinates = np.vstack([df_reference["geometry"].centroid.x, df_reference["geometry"].centroid.y]).T
    kd_tree = KDTree(coordinates)

    coordinates = np.vstack([df_missing["geometry"].x, df_missing["geometry"].y]).T
    indices = kd_tree.query(coordinates, return_distance=False).flatten()

    df_missing.loc[:, "municipality_id"] = df_reference.iloc[indices]["municipality_id"].values
    df_missing = df_missing[["municipality_id", "deprecated_municipality_id"]]

    df_existing = pd.DataFrame(df_reference[["municipality_id"]])
    df_existing["deprecated_municipality_id"] = df_existing["municipality_id"]

    df_mapping = pd.concat([df_existing, df_mapping, df_missing])
    df_reference = df_reference[["municipality_id", "municipality_name", "geometry"]]

    return df_reference, df_mapping

def update_municipality_ids(df, df_mapping, remove_unknown=False):
    assert ("municipality_id" in df.columns)

    df["deprecated_municipality_id"] = df["municipality_id"]
    del df["municipality_id"]

    df_join = pd.merge(
        df[["deprecated_municipality_id"]], df_mapping,
        on="deprecated_municipality_id", how="left"
    )

    df.loc[:, "municipality_id"] = df_join.loc[:, "municipality_id"].values

    if remove_unknown:
        return df[~np.isnan(df["municipality_id"])]
    else:
        return df


from replit import clear
#HINT: You can call clear() to clear the output in the console.
import art
print(art.logo)
print("Welcome to the Secret Auction Program")
users={}
condition= True
while condition==True:
    ask_user=str(input("What is your name? "))
    user_bid=int(input("What's your bid?: $"))
    users[ask_user]=user_bid
    to_continue=input("Are there any other bidders? Type 'yes' or 'no'. ")
    if to_continue =='no':
        condition=False
    elif to_continue =='yes':
        clear()

all_values=users.values()
max_value=max(all_values)
for key, value in users.items():
    if max_value==value:
        new_key= key
        print(f"The winner is {key} with a bid of ${value}.")

"""
###############The solution given by the Instructor#################

from replit import clear
from art import logo
print(logo)

bids = {}
bidding_finished = False

def find_highest_bidder(bidding_record):
  highest_bid = 0
  winner = ""
  # bidding_record = {"Angela": 123, "James": 321}
  for bidder in bidding_record:
    bid_amount = bidding_record[bidder]
    if bid_amount > highest_bid:
      highest_bid = bid_amount
      winner = bidder
  print(f"The winner is {winner} with a bid of ${highest_bid}")

while not bidding_finished:
  name = input("What is your name?: ")
  price = int(input("What is your bid?: $"))
  bids[name] = price
  should_continue = input("Are there any other bidders? Type 'yes or 'no'.\n")
  if should_continue == "no":
    bidding_finished = True
    find_highest_bidder(bids)
  elif should_continue == "yes":
    clear()

"""


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

# Create your views here.
def index(request):
    a = 5
    c = 10
    d = 15
    e =a+c+d
    return HttpResponse("
Hello my index total is: "+str(e)+"
")


import sys
import json
from transceiver import *

MY_HOST = '127.0.0.1'
MY_PORT = sys.argv[1]
MY_PORT = int(MY_PORT)

while True:
    cmd = int(input('cmd:'))
    if cmd == GET_TXS:
        get_txs=json.dumps({'msg_type':GET_TXS, 'sender':MY_PORT, 'content':''})
        send(MY_PORT, get_txs)
    elif cmd == NEW_TX:
        sender = input('sender:')
        receiver = int(input('receiver:'))
        value = int(input('value:'))
        tx = {'sender':sender, 'receiver':receiver, 'value':value}
        tx_msg=json.dumps({'msg_type':NEW_TX, 'sender':MY_PORT, 'content':tx})
        send(receiver, tx_msg)
    elif cmd == GET_CHAIN:
        get_chain = json.dumps({'msg_type':GET_CHAIN, 'sender':MY_PORT, 'content':''})
        send(MY_PORT, get_chain)
    elif cmd == NEW_BLOCK:
        new_block = json.dumps({'msg_type':NEW_BLOCK, 'sender':MY_PORT, 'content':''})
        send(MY_PORT, new_block)
    elif cmd == CHAIN_VALIDATION:
        is_valid = json.dumps({'msg_type':CHAIN_VALIDATION, 'sender':MY_PORT, 'content':''})
        send(MY_PORT, is_valid)
    elif cmd == SHUTDOWN:
        shutdown=json.dumps({'msg_type':SHUTDOWN, 'sender':MY_PORT, 'content':''})
        send(MY_PORT, shutdown)
        break


from fastpredict_noise_func import fast_pred_noise
import matplotlib.pyplot as plt
import numpy as np
import math
import time
from sklearn.cluster import KMeans
import pickle

"""
We choose the example in 'Large-scale Heteroscedastic Regression via
Gaussian Process' to test our model
"""

"""
Parameters in this example:
number of design points: 500
number of subsets: 5
f(x): sin(x) + epsilon(x), epsilon(x) ~ N(0, r(x))
r(x): 0.05 + 0.2(1 +sin(2x)) / (1 + exp(-0.2x))

Use k-means method to partition design points into 5 disjoint subsets
"""

"Construct function"

def r(x):
    y = 0.05 + 0.2*(1 + np.sin(2*x)) / (1 + np.exp(-0.2*x))
    y = y ** 2
    return y

"f(x) = sinc(x) = sin(pi*x) / (pi*x)"

def f(x):
    y = math.sin(math.pi * x) / (math.pi * x)
    return y

"""Initialization"""
n = 500
N = 5
q = 1000
d = 1

"We use random sample to get design and predict points"
data1 = pickle.load(open('C:/Users/Jorjin/Desktop/Research 1st/Nested Kriging/Code_Python/data.txt', 'rb'))
x = data1['x'].T
X = data1['X'].T
# np.random.seed(1)
# x = np.random.uniform(-10, 10, q)
# np.random.seed(2)
# X = np.random.uniform(-10, 10, n)

"Note that we want to predict f(x) without noise, so we only need variance on design points"
"since f(x) = sin(pi * x) / (pi * x), we need to avoid  x = 0"
y_x = np.zeros(q, dtype='float64')
y_X = np.zeros(n, dtype='float64')
for i in range(q):
    if x[i] != 0:
        y_x[i] = f(x[i])
    else:
        y_x[i] = 1

for i in range(n):
    if X[i] != 0:
        y_X[i] = f(X[i])
    else:
        y_X[i] = 1
"noise term"
"noise-free test"
y_noise_free = np.zeros(n, dtype='float64')
var_noise_free = np.zeros(n, dtype='float64')
y_noise = np.zeros(n, dtype='float64')
y_x_noise = np.zeros(q, dtype='float64')
var_noise = r(X)
# c1 = np.random.uniform(0, 0.15, n)
# c2 = np.random.uniform(0, 0.15, q)
# var_noise = c1
for i in range(n):
    np.random.seed(2*i)
    y_noise[i] = np.random.normal(0, r(X)[i])
    # y_noise[i] = np.random.normal(0, c1[i])
for i in range(q):
    np.random.seed(i)
    y_x_noise[i] = y_x[i] + np.random.normal(0, r(x)[i])
    # y_x_noise[i] = y_x[i] + np.random.normal(0, c2[i])

"Use k-means to get clusters, which includes the information of gp and gp_size"
"random_state is the random seed to control results"
"use reshape(-1, 1) to convert X to col vector"
cluster = KMeans(n_clusters=N).fit(X.reshape(-1, 1))
gp = cluster.labels_
"np.bincount() to count the size of each group (this is for non-negative int)"
gpsize = np.bincount(gp)

"kernel parameters"
var = 15
covtype = 'gauss'
param = np.array([1.5], dtype='float64')

"reshape x, X"
x = x.reshape(-1, 1)
X = X.reshape(-1, 1)

# "We replace cluster with unordered cluster to see what the group choice influence performance"
# gp1 = np.zeros(500, dtype='int32')
# for i in range(100):
#     for j in range(5):
#         gp1[5 * i + j] = j
# gpsize1 = np.array([100, 100, 100, 100, 100])

"""Apply algorithm"""
t1 = time.time()
Result = fast_pred_noise(X, y_X, n, d, gp, gpsize, N, x, q, var_noise,
                   y_noise, covtype, var, param, nuggetfactor=1.0001)
t2 = time.time()
print('run time: ', t2 - t1, 's')

"Error and 95% confidence interval"
m_A = Result['m_A']
v_A = np.sqrt(Result['v_A'])
UB = m_A + 1.96 * v_A
LB = m_A - 1.96 * v_A
mse = np.sum((y_x - m_A)**2) / q

"Figure"
"We need to rearrange array to let them be ordered such that we can use plot"
"We use argsort() to sort it with x-axis"

Data = np.array([x[:, 0], m_A, UB, LB, y_x])
Data = Data[:, Data[0].argsort()]

colors = np.array(['purple', 'green', 'blue', 'yellow', 'brown'])

fig, ax = plt.subplots(figsize=(12, 12))
ax.plot(Data[0], Data[1], color='red', linewidth=2, label='model')
ax.plot(Data[0], Data[2], color='black', linewidth=2, label='LB&UB')
ax.plot(Data[0], Data[3], color='black', linewidth=2)
ax.plot(Data[0], Data[4], color='purple', linewidth=2, label='real')
# ax.scatter(x, y_x_noise, c='blue', marker='+', s=50)
ax.scatter(X, y_X + y_noise, c=colors[gp], marker='+', s=50)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Result of noise-model')
ax.legend()
fig.show()


#!/usr/bin/python3
""" lists all State objects that contain the letter a """
from model_state import Base, State
from sys import argv
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

def main():
    """ lists all State objects that contain the letter a """
    engine = create_engine(
            'mysql://{}:{}@localhost/{}'.format(argv[1], argv[2], argv[3]))
    Session = sessionmaker(bind=engine)
    session = Session()
    result = session.query(State).filter(State.name.like('%a%'))

    for row in result:
        print(str(row.id) + ': ' + str(row.name))

if __name__ == "__main__":
    main()


import torch
from torch import nn, optim

from tqdm import tqdm

from ..evaluation.criterion import ECELoss

class ModelWithTemperature(nn.Module):
    """
    A thin decorator, which wraps a model with temperature scaling
    model (nn.Module):
        A classification neural network
        NB: Output of the neural network should be the classification logits,
            NOT the softmax (or log softmax)!
    """
    def __init__(self, model):
        super(ModelWithTemperature, self).__init__()
        self.model = model
        self.temperature = nn.Parameter(torch.ones(1) * 1.5)

    def set_logger(self, logger):
        self.logger = logger

    # def forward(self, input_ids, attention_mask):
    #     pred = self.model(input_ids=input_ids, attention_mask=attention_mask)
    #     logits = pred.logits
    #     return self.temperature_scale(logits)

    def forward(self, input):
        output = self.model(**input)
        if isinstance(output, torch.Tensor):
            logits = output
        else:
            logits = output.logits
        return self.temperature_scale(logits)

    # def forward(self, input):
    #     logits = self.model(input)
    #     return self.temperature_scale(logits)

    def temperature_scale(self, logits):
        """
        Perform temperature scaling on logits
        """
        # Expand temperature to match the size of logits
        temperature = self.temperature.unsqueeze(1).expand(logits.size(0), logits.size(1))
        return logits / temperature

    # This function probably should live outside of this class, but whatever
    def set_temperature(self, valid_loader):
        """
        Tune the tempearature of the model (using the validation set).
        We're going to set it to optimize NLL.
        valid_loader (DataLoader): validation set loader
        """
        # for input, label in tqdm(valid_loader, desc="Training"):
        #     input = input.cuda()
        #     # print(input, label)
        #     logits = self.model(input)
        #     print(logits.shape, np.count_nonzero(logits.cpu()), logits)
        #     break

        self.cuda()
        nll_criterion = nn.CrossEntropyLoss().cuda()
        ece_criterion = ECELoss().cuda()

        # First: collect all the logits and labels for the validation set
        logits_list = []
        labels_list = []
        with torch.no_grad():
            # num_batch = 0
            # for data_batch in tqdm(valid_loader, desc="Training"):
            #     input_ids = data_batch['input_ids'].cuda()
            #     attention_mask = data_batch['attention_mask'].cuda()
            #     label = data_batch['labels'].cuda()
            #     preds = self.model(input_ids=input_ids, attention_mask=attention_mask)
            #     logits = preds.logits

            # for input, label in tqdm(valid_loader, desc="Training"):
            #     input = input.cuda()
            #     # print(input, label)
            #     logits = self.model(input)
            #     # print(logits.shape, np.count_nonzero(logits.cpu()), logits)

            for input, label in tqdm(valid_loader, desc="Training"):
                # print(input['pixel_values'].shape)
                output = self.model(**input)
                if isinstance(output, torch.Tensor):
                    logits = output
                else:
                    logits = output.logits

                logits_list.append(logits)
                labels_list.append(label)

                # num_batch += 1
                # if num_batch > 10: break
            logits = torch.cat(logits_list).cuda()
            labels = torch.cat(labels_list).cuda()
        labels = torch.flatten(labels)
        # Calculate NLL and ECE before temperature scaling
        print(logits.shape, labels.shape)
        before_temperature_nll = nll_criterion(logits, labels).item()
        before_temperature_ece = ece_criterion(logits, labels).item()
        self.logger.info('Before temperature - NLL: %.3f, ECE: %.3f' % (before_temperature_nll, before_temperature_ece))

        # Next: optimize the temperature w.r.t. NLL
        optimizer = optim.LBFGS([self.temperature], lr=0.01, max_iter=500)

        def eval():
            optimizer.zero_grad()
            loss = nll_criterion(self.temperature_scale(logits), labels)
            loss.backward()
            return loss

        # for _ in tqdm(range(10)):
        optimizer.step(eval)

        # Calculate NLL and ECE after temperature scaling
        after_temperature_nll = nll_criterion(self.temperature_scale(logits), labels).item()
        after_temperature_ece = ece_criterion(self.temperature_scale(logits), labels).item()
        self.logger.info('Optimal temperature: %.3f' % self.temperature.item())
        self.logger.info('After temperature - NLL: %.3f, ECE: %.3f' % (after_temperature_nll, after_temperature_ece))

        return self


import numpy as np
import tempfile
from itertools import combinations

from pygromos.files.blocks.pertubation_blocks import pertubation_eds_state, atom_eds_pertubation_state
from pygromos.files.topology.ptp import Pertubation_topology as ptp
from pygromos.tests.test_files.general_file_functions import general_file_tests

from pygromos.tests.in_testfiles import in_test_file_path
from pygromos.tests.test_files import out_test_root_dir

in_path = in_test_file_path + "/ptp/eds.ptp"
in_path2 = in_test_file_path + "/ptp/lam_pert.ptp"

root_out = tempfile.mkdtemp(dir=out_test_root_dir, prefix="ptp_")
outpath = root_out + "/out_ptp.ptp"
outpath_less_state = root_out + "/out_ptp_lessStates.ptp"
outpath_less_atom = root_out + "/out_ptp_lessAtoms.ptp"
outpath_new_atom = root_out + "/out_ptp_newAtoms.ptp"
outpath_new_build = root_out + "/out_ptp_newBuild.ptp"
outpath_new_build_complex = root_out + "/out_ptp_newBuild_complex.ptp"

class test_ptp(general_file_tests):
    __test__ = True
    class_type = ptp
    in_file_path = in_path
    root_out = root_out

    def test_IO(self):
        ptp = self.class_type(in_path)
        print(ptp)
        ptp.write(outpath)

    def test_get_eds_states(self):
        ptp = self.class_type(in_path)
        states = ptp.MPERTATOM.states
        print(states)

    def test_add_eds_state(self):
        from pygromos.files.blocks.pertubation_blocks import atom_eds_pertubation_state, pertubation_eds_state

        ptp = self.class_type(in_path)

        on_state = pertubation_eds_state(IAC=16, CHARGE=-1.0)
        new_atoms_state = [
            atom_eds_pertubation_state(NR=x, NAME="H", STATES={7: on_state, 13: on_state})
            if x == 1
            else atom_eds_pertubation_state(NR=x, NAME="H", STATES={7: on_state})
            for x in range(1, 4)
        ]

        ptp.MPERTATOM.add_state_atoms(state_atoms=new_atoms_state)

        ptp.write(outpath_new_atom)

    def test_delete_eds_state(self):
        ptp = self.class_type(in_path)
        ptp.MPERTATOM.delete_state(stateIDs=6)
        ptp.MPERTATOM.delete_state(stateNames="state3")
        ptp.write(outpath_less_state)

    def test_remove_eds_atoms(self):
        ptp = self.class_type(in_path)
        ptp.MPERTATOM.delete_atom(atomNR=[3, 4, 5, 6])
        ptp.write(outpath_less_atom)

    def test_new_eds_ptp_from_scratch(self):
        from pygromos.files.blocks.pertubation_blocks import (
            atom_eds_pertubation_state,
            pertubation_eds_state,
            MPERTATOM,
        )

        ptp = self.class_type()
        on_state = pertubation_eds_state(IAC=16, CHARGE=-1.0)

        new_atoms_state = [atom_eds_pertubation_state(NR=x, NAME="H", STATES={x: on_state}) for x in range(1, 4)]

        mperatom_block = MPERTATOM(NJLA=len(new_atoms_state), NPTB=0)

        mperatom_block.add_state_atoms(state_atoms=new_atoms_state)
        ptp.MPERTATOM = mperatom_block
        print(ptp)
        ptp.write(outpath_new_build)

    def test_eds_gen_all_states_ptp(self):
        # INPUT:
        # the states to use:
        o_state = pertubation_eds_state(IAC=16, CHARGE=-1.0)
        h_state = pertubation_eds_state(IAC=33, CHARGE=-2.0)

        # Map for molecule ID with Atom IDS
        # First atom assumed to be O and last two Hs
        molecules_atoms = {1: [1, 2, 3], 2: [4, 5, 6], 3: [7, 8, 9], 4: [10, 11, 12]}

        # BUILD UP STATES
        # Generate active state mapping:
        max_active_mols_same_time = len(molecules_atoms)
        molecule_states = {}
        state_ID = 1
        for active_mols in range(1, max_active_mols_same_time + 1):
            combis = list(combinations(molecules_atoms, active_mols))
            molecule_states.update({state_ID + ind: x for ind, x in enumerate(combis)})
            state_ID = state_ID + len(combis)
        # gives the state number as key and all the active molecules in this state

        # build state atoms for ptp
        new_atoms_state_dict = {}
        for state, molecules in molecule_states.items():
            for molecule in molecules:
                if molecule in new_atoms_state_dict:
                    atoms = new_atoms_state_dict[molecule]
                    atoms[0].STATES.update({state: o_state})
                    atoms[1].STATES.update({state: h_state})
                    atoms[2].STATES.update({state: h_state})
                else:
                    atoms = [
                        atom_eds_pertubation_state(NR=molecules_atoms[molecule][0], NAME="O", STATES={state: o_state}),
                        atom_eds_pertubation_state(NR=molecules_atoms[molecule][1], NAME="H1", STATES={state: h_state}),
                        atom_eds_pertubation_state(NR=molecules_atoms[molecule][2], NAME="H2", STATES={state: h_state}),
                    ]
                    new_atoms_state_dict.update({molecule: atoms})

        # finally make a list for our ptp file (#ThanksGromos)
        new_atoms_state = np.concatenate(list(new_atoms_state_dict.values()))

        # BUILD PTP
        ptp = self.class_type(in_path)
        ptp.MPERTATOM.add_state_atoms(state_atoms=new_atoms_state)
        print(ptp)
        ptp.write(outpath_new_build_complex)

        # TADAAAAA - DONE


import matplotlib.pyplot as plt
import re
import numpy as np
import math

time = []
ax = []
ay = []
az = []

for i in range(0,18,1):
    if (i%10 == 0):
      print(str(round(i/.18,2)) + "% parsed")
    num = ""

    if (i > 9):
      num = "0" + str(i)
    else:
       num = "00" + str(i)

    imu_file = open("../../OREGON/rollover1/ORE_imu_0_"+num)
    file_lines = imu_file.readlines()

    for line in file_lines:
      values = line.split(',')
      time.append(float(values[0]))
      ax.append(float(values[5]))
      ay.append(float(values[6]))
      az.append(float(values[7].strip('\n')))

break_time = time[-1]

for i in range(0,45,1):
    if (i%10 == 0):
      print(str(round(i/.45,2)) + "% parsed")
    num = ""

    if (i > 9):
      num = "0" + str(i)
    else:
       num = "00" + str(i)

    imu_file = open("../../OREGON/ORE_imu_0_"+num)
    file_lines = imu_file.readlines()

    for line in file_lines:
      values = line.split(',')
      time.append(float(values[0])+break_time)
      ax.append(float(values[5]))
      ay.append(float(values[6]))
      az.append(float(values[7].strip('\n')))

fx = []
fy = []
fz = []
window_size = 2000
SAMPLING_RATE_HZ = 2048

for i in range(len(time)-window_size):
  if (i%(len(time)/20) == 0):
      print(str(round(100*i/len(time),2)) + "% processed")

  sp = np.abs(np.fft.rfft(ax[i:i + window_size], 4096))
  dom_freq = np.argmax(sp[1:])
  if abs(np.max(sp[1:])) > 400:
    fx.append(dom_freq)
  else:
    fx.append(0)

for i in range(len(time)-window_size):
  if (i%(len(time)/20) == 0):
      print(str(round(100*i/len(time),2)) + "% processed")

  sp = np.abs(np.fft.rfft(ay[i:i + window_size], 4096))
  dom_freq = np.argmax(sp[1:])
  if abs(np.max(sp[1:])) > 400:
    fy.append(dom_freq)
  else:
    fy.append(0)

for i in range(len(time)-window_size):
  if (i%(len(time)/20) == 0):
      print(str(round(100*i/len(time),2)) + "% processed")

  sp = np.abs(np.fft.rfft(az[i:i + window_size], 4096))
  dom_freq = np.argmax(sp[1:])
  if abs(np.max(sp[1:])) > 400:
    fz.append(dom_freq)
  else:
    fz.append(0)

f = open("vibes.txt", "w")
f.writelines(["time,frequency_x,frequency_y,frequency_z"])
for i in range(0, len(fx), 1):
  s = str(time[i+window_size]) + "," + str(fx[i]) + "," + str(fy[i]) + "," + str(fz[i]) + '\n'
  f.writelines([s])
f.close()

fig, axs = plt.subplots(4)
axs[0].set_title("ax")
axs[1].set_title("fx")
axs[2].set_title("fy")
axs[3].set_title("fz")

axs[0].scatter(time, ax, s=1)
axs[1].scatter(time[0:len(time)-window_size], fx, s=1)
axs[2].scatter(time[0:len(time)-window_size], fy, s=1)
axs[3].scatter(time[0:len(time)-window_size], fz, s=1)

plt.show()


from fastapi import FastAPI, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
import os
import poll_schema
from typing import List
from sqlalchemy.orm import Session

import crud
from database import SessionLocal, engine
from models import Base

Base.metadata.create_all(bind=engine)

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    # allow_origins=[os.environ.get("CORS_HOST", "http://localhost:3000")],
    allow_origins=[
        "http://localhost:3000",
        os.environ.get("CORS_HOST", "REACT_APP_POLLS_API_HOST"),
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Dependency
def get_db():
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

@app.post("/questions", response_model=poll_schema.QuestionInfo)
def create_question(
    question: poll_schema.QuestionCreate, db: Session = Depends(get_db)
):
    return crud.create_question(db=db, question=question)

@app.get("/questions", response_model=List[poll_schema.Question])
def get_questions(db: Session = Depends(get_db)):
    return crud.get_all_questions(db=db)

def get_question_obj(db, qid):
    obj = crud.get_question(db=db, qid=qid)
    if obj is None:
        raise HTTPException(status_code=404, detail="Question not found")
    return obj

@app.get("/questions/{qid}", response_model=poll_schema.QuestionInfo)
def get_question(qid: int, db: Session = Depends(get_db)):
    return get_question_obj(db=db, qid=qid)

@app.put("/questions/{qid}", response_model=poll_schema.QuestionInfo)
def edit_question(
    qid: int, question: poll_schema.QuestionEdit, db: Session = Depends(get_db)
):
    get_question_obj(db=db, qid=qid)
    obj = crud.edit_question(db=db, qid=qid, question=question)
    return obj

@app.delete("/questions/{qid}")
def delete_question(qid: int, db: Session = Depends(get_db)):
    get_question_obj(db=db, qid=qid)
    crud.delete_question(db=db, qid=qid)
    return {"detail": "Question deleted", "status_code": 204}

@app.post("/questions/{qid}/choice", response_model=poll_schema.ChoiceList)
def create_choice(
    qid: int, choice: poll_schema.ChoiceCreate, db: Session = Depends(get_db)
):
    get_question_obj(db=db, qid=qid)
    return crud.create_choice(db=db, qid=qid, choice=choice)

@app.put("/choices/{choice_id}/vote", response_model=poll_schema.ChoiceList)
def update_vote(choice_id: int, db: Session = Depends(get_db)):
    return crud.update_vote(choice_id=choice_id, db=db)

@app.get("/choices", response_model=List[poll_schema.ChoiceList])
def get_choices(db: Session = Depends(get_db)):
    return crud.get_choices(db=db)


import geopandas as gpd
import matplotlib.pyplot as plt
import pandas as pd
from mapclassify import classify
import seaborn as sns
from my_modules.brazil_colors import create_ordered_colormap

def mono_br_geoplot(ano: int, gdf: gpd.GeoDataFrame, df: pd.DataFrame, which_plot=0):

    # ano = 2017
    # gdf = estados_geo
    titles= [f'Unidades Federativas Agrupadas\nPor Quartis ({ano})', f'Unidades Federativas Agrupadas\nPor Intervalos Fixos ({ano})']

    bins=[60, 65, 70, 75, 80]
    schemes = ['quantiles', 'UserDefined']
    cmaps = ['coolwarm_r', "cividis"]
    column= str(ano) + '_cobertura_vacinal'

    data_to_plot = df.query("ano==@ano").groupby(by='uf', sort=False).mean().round(2).cobertura_vacinal

    if gdf.index.equals(data_to_plot.index):
        gdf[column] = data_to_plot
    else:
        print('Can\'t merge. Indexes are not the same')
        return
    # fig, axs = plt.subplots(1,2,figsize=(10,10), facecolor='0.5')
    fig, ax = plt.subplots(1,1, figsize=(10,10))

    if which_plot==0:
        gdf.plot(
            column=column,
            edgecolor='0.5',
    #         linewidth=.1
            cmap=cmaps[0],
            scheme = schemes[0],
            k=4,
            legend=True,
            legend_kwds=dict(loc='center right', bbox_to_anchor=(1,0.1), title="Cobertura Vacinal\n", title_fontsize= 'medium'),
            ax=ax)
    else:
        gdf.plot(
            column=column,
            edgecolor='0.5',
            cmap=cmaps[1],
            scheme = schemes[1],
        #     k=4,
            legend=True,
            legend_kwds=dict(loc='center right', bbox_to_anchor=(1,0.1),  title="Cobertura Vacinal\n", title_fontsize= 'medium'),
            ax=ax,
            classification_kwds = dict(bins=bins))

    ## formatting legend
#     for i in range(len(axs.flatten())):
#     iterable = []

#     for i in iterable:
#         if axs[i] is not None:
    i = 0
    axs = [ax]

    axs[i].set_title(titles[which_plot], fontsize = 20)
    axs[i].axis('off')

    custom_classifier = classify(y=data_to_plot, scheme=schemes[which_plot], bins=bins*which_plot, k=4+which_plot)

    legend_texts = axs[i].get_legend().texts

    for legend_number in range(len(legend_texts)):

        vmin,vmax = legend_texts[legend_number].get_text().split(", ")
        number_of_states_per_class = custom_classifier.counts[legend_number]

        text_to_write = '{:.2f} a {:.2f}%  ({} UFs)'.format(float(vmin), float(vmax), number_of_states_per_class)
        legend_texts[legend_number].set_text(text_to_write)

        if which_plot == 1 :

            text_to_write = f'≤ {bins[0]}%  ({number_of_states_per_class} UFs)' if f'a {bins[0]}.00%' in text_to_write else text_to_write
            text_to_write = f'> {bins[-1]}%  ({number_of_states_per_class} UFs)' if f'{bins[-1]}.00 a' in text_to_write else text_to_write
            text_to_write = text_to_write.replace('.00', '')
            legend_texts[legend_number].set_text(text_to_write)

def double_br_geoplot(ano: int, gdf: gpd.GeoDataFrame, df: pd.DataFrame, save=True):

    # ano = 2017
    # gdf = estados_geo
    titles= ['Unidades Federativas Agrupadas\nPor Quartis', 'Unidades Federativas Agrupadas\nPor Intervalos Fixos']

    bins=[60, 65, 70, 75, 80]
    schemes = ['quantiles', 'UserDefined']
    cmaps = ['coolwarm_r', "cividis"]
    column= str(ano) + '_cobertura_vacinal'

    data_to_plot = df.query("ano==@ano").groupby(by='uf', sort=False).mean().round(2).cobertura_vacinal

    if gdf.index.equals(data_to_plot.index):
        gdf[column] = data_to_plot
    else:
        print('Can\'t merge. Indexes are not the same')
        return
    # fig, axs = plt.subplots(1,2,figsize=(10,10), facecolor='0.5')
    fig, axs = plt.subplots(1,2, constrained_layout=False ,figsize=(20,10))

    gdf.plot(
        column=column,
        edgecolor='0.5',
#         linewidth=.1
        cmap=cmaps[0],
        scheme = schemes[0],
        k=4,
        legend=True,
        legend_kwds=dict(loc='center right', bbox_to_anchor=(1,0.1), title="Cobertura Vacinal\n", title_fontsize= 'medium'),
        ax=axs[0])

    gdf.plot(
        column=column,
        edgecolor='0.5',
        cmap=cmaps[1],
        scheme = schemes[1],
    #     k=4,
        legend=True,
        legend_kwds=dict(loc='center right', bbox_to_anchor=(1,0.1), title="Cobertura Vacinal\n", title_fontsize= 'medium'),
        ax=axs[1],
        classification_kwds = dict(bins=bins))

    ## formatting legend
#     for i in range(len(axs.flatten())):
    for i in range(len(axs.flatten())):

        axs[i].set_title(titles[i], fontsize=20)
        axs[i].axis('off')

        custom_classifier = classify(y=data_to_plot, scheme=schemes[i], bins=bins*i, k=4+i)

        legend_texts = axs[i].get_legend().texts
        for legend_number in range(len(legend_texts)):
            vmin,vmax = legend_texts[legend_number].get_text().split(", ")
            number_of_states_per_class = custom_classifier.counts[legend_number]

            text_to_write = '{:.2f} a {:.2f}%  ({} UFs)'.format(float(vmin), float(vmax), number_of_states_per_class)
            legend_texts[legend_number].set_text(text_to_write)

            if i ==1 :

                text_to_write = f'≤ {bins[0]}%  ({number_of_states_per_class} UFs)' if f'a {bins[0]}.00%' in text_to_write else text_to_write
                text_to_write = f'> {bins[-1]}%  ({number_of_states_per_class} UFs)' if f'{bins[-1]}.00 a' in text_to_write else text_to_write
                text_to_write = text_to_write.replace('.00', '')
                legend_texts[legend_number].set_text(text_to_write)

    fig.suptitle(f"{ano}", fontsize = 28)

    if save == True:
        fig.savefig("../reports/figures/cloropleths/geo" + str(ano) + "_to_gif.png", facecolor='w',transparent=None)
        plt.close()
    else:
        plt.show()

def podium_swarmplot(imunizacao_ufs, estados_geo):
    ####### Creating DataFrame to plot #############
    anos = range(2017,2021)

    ordered_states = list(imunizacao_ufs.uf.unique())
    state_counter = {key:[0,0,0,0] for key in ordered_states}

    for ano in anos:
    #     print(ano)

        data_to_plot = imunizacao_ufs.query("ano==@ano").groupby(by='uf', sort=False).mean().round(2).cobertura_vacinal
        custom_classifier = classify(y=data_to_plot, scheme='quantiles', k=4)#, bins=bins*which_plot, k=4+which_plot)

        counter = 0

        for each_class in custom_classifier.classes:
    #         print (each_class, counter)
            for state_position in each_class:
                state = ordered_states[state_position]
                state_counter[state][counter] += 1

            counter += 1

    # state_counter

    state_counter_df = pd.DataFrame.from_dict(state_counter, orient = 'index',
                           columns=[txt + '_25%' for txt in ('1os', '2os', '3os', '4os')])
    # state_counter_df

    ##############

    state_counter_df = pd.DataFrame.from_dict(state_counter, orient = 'index',
                           columns=[txt + '_25%' for txt in ('1os', '2os', '3os', '4os')])

    state_counter_df = state_counter_df.melt(ignore_index=False).reset_index()

    new_columns = dict(zip(state_counter_df.columns, ['uf', 'grupo', 'aparicoes']))
    state_counter_df.rename(columns= new_columns, inplace=True)

    lista = []
    for aparicoes, grupo in zip(state_counter_df.aparicoes, state_counter_df.grupo):
        lista.append((aparicoes * [grupo]))

    state_counter_df['aparicoes_por_grupo'] = lista
    state_counter_df = state_counter_df.explode(column='aparicoes_por_grupo').dropna()
    state_counter_df = state_counter_df.reset_index(drop=True)

    # state_counter_df

    ############# SWARMPLOTTING #############

    # with sns.axes_style('whitegrid'):
    plt.draw()
    order=state_counter_df.sort_values(by='aparicoes_por_grupo', kind='heapsort').uf.unique()
    palette=create_ordered_colormap(order, output_as_list=True, replace_state_color_by_region=True)

    plt.figure(figsize=(18,6))

    ax = sns.swarmplot(data=state_counter_df, x='uf', y='aparicoes_por_grupo',
                 size=7, orient='v', #hue='uf',
                 palette=palette, order=order, marker="o"
                 )

    uf_siglas_dict = (estados_geo.sigla).to_dict()
    siglas = [uf_siglas_dict[state.get_text()] for state in ax.get_xticklabels()]
    ax.set_xticklabels(siglas)
    ax.set_yticklabels(('', '', '', ''))

    ax.set(xlabel= "Unidade Federativa", ylabel= 'Menor <----- Cobertura Vacinal -----> Maior')
    plt.title("Nestes 4 anos, quais foram as UFs com maiores e menores coberturas vacinais em relação às outras?",
              fontsize=16)
    plt.suptitle('Pódio da Imunidade',fontsize=24, y=1)
    ax.yaxis.grid(False) # horizontal lines
    ax.xaxis.grid(True)
    plt.show()


"""
Dans_Diffraction Examples
Simulate the functionality of the CXRO website: https://henke.lbl.gov/optical_constants/
Use formulas from:
B.L. Henke, E.M. Gullikson, and J.C. Davis, X-ray interactions: photoabsorption, scattering, transmission,
and reflection at E=50-30000 eV, Z=1-92, Atomic Data and Nuclear Data Tables 54 no.2, 181-342 (July 1993).
"""

import sys, os
import numpy as np
import matplotlib.pyplot as plt
cf = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(cf, '..'))
import Dans_Diffraction as dif

formula = 'Ca2RuO4'
density = 4.583  # g/cm^3
energy_range = np.arange(0.03, 15, 0.01)  # keV
grazing_angle = 90  # Deg
slab_thickness = 0.2  # microns

# Attenuation length
dif.fp.plot_xray_attenuation_length(formula, density, energy_range, grazing_angle)

# Transmission
dif.fp.plot_xray_transmission(formula, density, energy_range, slab_thickness)

plt.show()


'''http://adventofcode.com/2017/day/5'''

def count_steps_to_exit(offsets: list):
    '''
    Return number of steps to reach the exit from list from file.
    Each element of list is offset for jumps through list.
    After each jump the offset of that jump decreases by 1, if the offset was three or more. Otherwise, increase by 1.
    '''
    jump, count_steps = 0, 0
    while jump < len(offsets):
        curr = jump
        jump += offsets[curr]
        if offsets[curr] >= 3:
            offsets[curr] -= 1
        else:
            offsets[curr] += 1
        count_steps += 1

    return count_steps

def test(func):
    '''Test function.'''
    print('#1: ', end='')
    answer = 10
    with open('sources/test.txt', 'r') as file:
        content = [int(line) for line in file]
        print('ok' if func(content) == answer else 'fail')

if __name__ == '__main__':
    # test(count_steps_to_exit)

    with open('sources/maze.txt', 'r') as file:
        content = [int(line) for line in file]
        print(count_steps_to_exit(content))


# 뉴욕 타임스 뉴스 기사 중 헤드라인을 읽어 텍스트 생성 연습

import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Embedding, Flatten, Dense, LSTM
from keras.preprocessing.text import Tokenizer
from keras.utils import pad_sequences, to_categorical

df = pd.read_csv("https://raw.githubusercontent.com/pykwon/python/master/testdata_utf8/articlesapril.csv")
# print(df.head(2))
# print(df.columns, len(df.columns))
print(df['headline'].head(2))
print(df.headline.values)  # headline만 필요하다.
print(df['headline'].isnull().values.any())  # False - null은 없다.

headline = []
headline.extend(list(df.headline.values))
print(headline[:10])
print(len(headline)) # 1324개

# 'Unknown'(noise) 자료 제거
headline = [n for n in headline if n != 'Unknown']

print(headline[:10])
print(len(headline)) # 1214개

# ascii코드 문자, 구두점 제거, 단어 소문자화
from string import punctuation

# print("He하이llo 가a나다.".encode("ascii", errors='ignore').decode())
# print(", python. ".strip(punctuation)) # . , 제거
# print(", python. ".strip(punctuation + ' ')) # . , 제거 + 공백 제거

def replace_func(s):
    s = s.encode('utf8').decode("ascii", errors='ignore') # ascii코드 문자
    return ''.join(c for c in s if c not in punctuation).lower() # 구두점 제거, 단어 소문자화

# sss = ['abc123,..굿굿good']
# print([replace_func(x) for x in sss])

text = [replace_func(x) for x in headline]
print(text[:5])
# 'Former N.F.L. Cheerleaders’ Settlement Offer'
# 'former nfl cheerleaders settlement offer'

# vocabulary
tok = Tokenizer()
tok.fit_on_texts(text)
vocab_size = len(tok.word_index) + 1
print('vocab_size : ', vocab_size)  # 3494

sequences = list()
for line in text:
    enc = tok.texts_to_sequences([line])[0] # 각 샘플에 대한 인덱싱 처리 (정수 인코딩)
    for i in range(1, len(enc)):
        se = enc[:i + 1]
        sequences.append(se)

print(sequences) # [[99, 269], [99, 269, 371], ...]

print(tok.word_index) # {'the': 1, 'a': 2, 'to': 3, 'of': 4, 'in': 5, ...
print(sequences[:11]) # [[99, 269], [99, 269, 371], [99, 269, 371, 1115], ...

print('dict items : ', tok.word_index.items()) # dict items :  dict_items([('the', 1), ('a', 2),   ==>  {1:'the', 2:'a' ..} 이렇게 만들기
index_to_word = {}
for key, value in tok.word_index.items():
    print('key : ', key)
    print('value : ', value)
    index_to_word[value] = key

print(index_to_word[1])

max_len = max(len(i) for i in sequences)
print('max_len : ', max_len) # 24

psequences = pad_sequences(sequences, maxlen=max_len, padding='pre')
print(psequences[:3])

psequences = np.array(psequences)
x = psequences[:, :-1]  # feature
y = psequences[:, -1]   # label
print(x[:3])
print(y[:3])

# y값 원핫처리
y = to_categorical(y, num_classes=vocab_size)
print(y[:1]) # [[0. 0. 0. ... 0. 0. 0.]]

# --------- 전처리 완료 --------------

# model

model = Sequential()
model.add(Embedding(vocab_size, 32, input_length=max_len -1))
model.add(LSTM(128, activation='tanh'))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(vocab_size, activation='softmax'))
print(model.summary())

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(x, y, epochs=200, verbose=2)
print('model evaluate : ', model.evaluate(x, y))

# 문자열 생성 함수
def seq_gen_text_func(model, t, current_word, n):
    init_word = current_word  # 처음 들어온 단어도 마지막 함께 출력할 계획
    sentence = ''
    for _ in range(n):
        encoded = t.texts_to_sequences([current_word])[0]
        encoded = pad_sequences([encoded], maxlen=max_len - 1, padding='pre')  # - 1 주는 이유 : 마지막에 label을 빼야해서
        result = np.argmax(model.predict(encoded, verbose=0), axis= -1)

        # 예측 단어 찾기
        for word, index in t.word_index.items():
            # print(word, ' : ', index)
            if index == result:  # 예측한 단어와 인덱스에 동일한 단어가 있다면 해당 단어는 예측 단어이므로 break
                break

        current_word = current_word + ' ' + word
        sentence = sentence + ' '+ word

    sentence = init_word + sentence
    return sentence

print(seq_gen_text_func(model, tok, 'who', 10))
print(seq_gen_text_func(model, tok, 'how', 10))
print(seq_gen_text_func(model, tok, 'with', 10))
print(seq_gen_text_func(model, tok, 'and', 10))


from PyQt6.QtCore import QDate, QSize
from PyQt6.QtWidgets import QApplication, QMainWindow, QDateEdit
import sys

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("Widget-Examples")
        widget = QDateEdit()
        widget.dateChanged.connect(self.handle_input)
        self.setCentralWidget(widget)
        self.setFixedSize(QSize(200, 40))
    def handle_input(self, value:QDate):
        print(f'{str(value.day())}.{str(value.month())}.{str(value.year())}')

app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()


class Length:
    __foot = 0
    __inch = 0

    def __init__(self, foot, inch):

        if foot > 0:
            self.__foot = foot
        else:
            self.__foot = abs(foot)

        if inch < 12 and inch >= 0:
            self.__inch = inch
        elif inch >= 12:
            self.__foot += inch // 12
            self.__inch = inch % 12
        elif inch < 0 and inch > -12:
            self.__inch = abs(inch)
        elif inch <= -12:
            self.__foot += abs(inch) // 12
            self.__inch = abs(inch) % 12
        else:
            print("something went wrong")

    def __str__(self):
        return (
            f"current length is: {self.__foot} foot/feet and {self.__inch} inch(es)")

    def __add__(self, x):
        sum = Length(self.__foot, self.__inch)
        sum.__foot += x.__foot
        if sum.__inch + x.__inch >= 12:
            sum.__foot += (sum.__inch + x.__inch) // 12
            sum.__inch = (sum.__inch + x.__inch) % 12
        elif sum.__inch + x.__inch < 12:
            sum.__inch += x.__inch
        else:
            print("something went wrong with add method")
        return sum

    def __sub__(self, x):
        dif = Length(self.__foot, self.__inch)
        dif.__foot -= x.__foot
        if dif.__inch - x.__inch < 0:
            dif.__foot -= 1
            dif.__inch = 12 - x.__inch
        elif dif.__inch - x.__inch >= 0:
            dif.__inch -= x.__inch
        else:
            print("something went wrong with sub method")
        return dif

def main():
    len1 = Length(4, 2)
    len2 = Length(0, 3)
    len3 = len1 - len2
    print(len3)

main()


import sys
import glob
import json
"""
Scrape logs from cctbx.xfel.merge to find images with a resolution cutoff below
a given value.

Arguments are the cctbx.xfel.merge output directory and the resolution cutoff.

Usage examples:
$ python ~/scrape_logs.py run_000451.JF07T32V01_master/002_rg003/scale 3.5
$ for d in $(find . -type d -name out -path *scale*); do if [[ $(ls $d/*.expt 2>/dev/null |wc -l) -gt 0 ]]; then echo $d >&2; python ~/scrape_logs.py $d/.. 3.5; fi; done > frame_res.txt
"""

RESULTS="/global/cscratch1/sd/dwpaley/swissfel/results"
SCALE_DIR = sys.argv[1]
D_MAX = float(sys.argv[2])

id_image = {}
#expt_names = glob.glob(SCALE_DIR + "/../out/*_integrated.expt")
expt_names = glob.glob('/global/cscratch1/sd/dwpaley/psi/reindex/run702/*_integrated.expt')
for expt_name in expt_names:
  expt_json = json.load(open(expt_name))
  for expt in expt_json['experiment']:
    ident = expt['identifier']
    i_imageset = expt['imageset']
    imageset = expt_json['imageset'][i_imageset]
    image_index = "{}:{}".format(
        imageset['images'][0],
        imageset['single_file_indices']
        )
    id_image[ident] = image_index

resolution_ident = []
#log_names = glob.glob(SCALE_DIR + "/out/*rank*.log")
log_names = glob.glob(SCALE_DIR + "/*rank*.log")
for log in log_names:
  with open(log) as f:
    log_lines = f.readlines()
  for l in log_lines:
    if 'resolution cutoff' not in l:
      continue
    try:
      res = float(l.split('resolution cutoff ')[1].split(',')[0])
      ident = l.split('experiment identifier ')[1].strip()
      resolution_ident.append((res, ident))
    except: pass

resolution_ident.sort(key=lambda l:l[0])

for r_i in resolution_ident:
  res, ident = r_i
  if res > D_MAX: break
  print("{:.3f}\t {}".format(
      res,
      id_image[ident]
      ))


import flask

from featuring.controllers.crud_user import (
    retrieve_user_by_username,
    delete_user_by_username,
    retrieve_all_users,
    create_one_user,
)

from featuring.controllers.crud_ticket import (
    create_one_ticket,
    retrieve_all_tickets,
    retrieve_ticket_by_ticket_id,
    update_ticket_by_ticket_id,
    delete_ticket_by_ticket_id,
)

from featuring.controllers.crud_client import retrieve_all_clients
from featuring.controllers.crud_product import retrieve_all_products
from featuring.controllers.authentication import create_session_token

from .responses import APIResponse

from .schemas import (
    SessionCreationInputSchema,
    SessionCreationOutputSchema,
    SessionRetrievalOutputSchema,
    SelfRegisterInputSchema,
    UserCreationInputSchema,
    UserRetrievalOutputSchema,
    TicketCreationInputSchema,
    TicketUpdateInputSchema,
    TicketRetrievalOutputSchema,
    ClientRetrievalOutputSchema,
    ProductRetrievalOutputSchema)

from .decorators import (
    endpoint,
    protected,
    handle_auth_error,
    handle_invalid_input,
    handle_unique_violation,
    handle_not_found
)

# --------------------------------------------------------------------------------------------------
# General Endpoints
# --------------------------------------------------------------------------------------------------

@endpoint
def ping():
    return APIResponse.empty(200)

@endpoint
@handle_auth_error
@handle_invalid_input
def create_session():
    input_data = SessionCreationInputSchema().load_strict(flask.request.json or {})
    created = create_session_token(**input_data.data)
    output = SessionCreationOutputSchema().dump({'token': created}).data
    return APIResponse.success(output)

@endpoint
@protected
@handle_invalid_input
@handle_not_found
def retrieve_session():
    output = SessionRetrievalOutputSchema().dump(flask.request.session).data
    return APIResponse.success(output)
    return APIResponse.empty(200)

# --------------------------------------------------------------------------------------------------
# User Endpoints
# --------------------------------------------------------------------------------------------------

@endpoint
@handle_unique_violation
@handle_invalid_input
def register_user():
    input_data = SelfRegisterInputSchema().load_strict(flask.request.json or {})
    created = create_one_user(**input_data.data)
    output = UserRetrievalOutputSchema().dump(created).data
    return APIResponse.success(output)

@endpoint
@protected
@handle_unique_violation
@handle_invalid_input
def create_user():
    input_data = UserCreationInputSchema().load_strict(flask.request.json or {})
    created = create_one_user(**input_data.data)
    output = UserRetrievalOutputSchema().dump(created).data
    return APIResponse.success(output)

@endpoint
@protected
def retrieve_user_list():
    output = [UserRetrievalOutputSchema().dump(obj).data for obj in retrieve_all_users()]
    return APIResponse.success(output)

@endpoint
@protected
@handle_invalid_input
@handle_not_found
def retrieve_user(username):
    obj = retrieve_user_by_username(username)
    output = UserRetrievalOutputSchema().dump(obj).data
    return APIResponse.success(output)

@endpoint
@protected
@handle_invalid_input
@handle_not_found
def delete_user(username):
    count = delete_user_by_username(username)
    return APIResponse.empty(204) if count else APIResponse.empty(404)

# --------------------------------------------------------------------------------------------------
# Ticket Endpoints
# --------------------------------------------------------------------------------------------------

@endpoint
@protected
@handle_unique_violation
@handle_invalid_input
def create_ticket():
    input_data = TicketCreationInputSchema().load_strict(flask.request.json or {})
    created = create_one_ticket(**input_data.data)
    output = TicketRetrievalOutputSchema().dump(created).data
    return APIResponse.success(output)

@endpoint
@protected
def retrieve_ticket_list():
    output = [TicketRetrievalOutputSchema().dump(obj).data for obj in retrieve_all_tickets()]
    return APIResponse.success(output)

@endpoint
@protected
@handle_invalid_input
@handle_not_found
def retrieve_ticket(ticket_id):
    obj = retrieve_ticket_by_ticket_id(ticket_id)
    output = TicketRetrievalOutputSchema().dump(obj).data
    return APIResponse.success(output)

@endpoint
@protected
@handle_invalid_input
@handle_not_found
def update_ticket(ticket_id):
    input_data = TicketUpdateInputSchema().load_strict(flask.request.json or {})
    obj = update_ticket_by_ticket_id(ticket_id, **input_data.data)
    output = TicketRetrievalOutputSchema().dump(obj).data
    return APIResponse.success(output)

@endpoint
@protected
@handle_invalid_input
@handle_not_found
def delete_ticket(ticket_id):
    count = delete_ticket_by_ticket_id(ticket_id)
    return APIResponse.empty(204) if count else APIResponse.empty(404)

# --------------------------------------------------------------------------------------------------
# Client Endpoints
# --------------------------------------------------------------------------------------------------

@endpoint
@protected
def retrieve_client_list():
    output = [ClientRetrievalOutputSchema().dump(obj).data for obj in retrieve_all_clients()]
    return APIResponse.success(output)

# --------------------------------------------------------------------------------------------------
# Product Endpoints
# --------------------------------------------------------------------------------------------------

@endpoint
@protected
def retrieve_product_list():
    output = [ProductRetrievalOutputSchema().dump(obj).data for obj in retrieve_all_products()]
    return APIResponse.success(output)


"""
==========================
Inclusion body experiments
==========================
"""

from vivarium.core.experiment import Experiment
from vivarium.core.control import Control
from vivarium.core.composition import (
    EXPERIMENT_OUT_DIR,
)

# composites
from vivarium_multibody.composites.lattice import (
    Lattice,
    make_lattice_config,
)
from inclusion.composites.inclusion_body_growth import InclusionBodyGrowth

# plots
from vivarium.plots.agents_multigen import plot_agents_multigen
from vivarium_multibody.plots.snapshots import (
    plot_snapshots, plot_tags, format_snapshot_data)

LATTICE_CONFIG = make_lattice_config(
    time_step=30,
    jitter_force=1e-4,
    bounds=[30, 30],
    n_bins=[10, 10])

def test_experiment(
        initial_biomass=1000,
        total_time=2000,
):
    agent_id = '1'
    parameters = {
        'agent_id': agent_id,
        'inclusion_process': {
            'damage_rate': 1e-4,  # rapid damage
        },
        'growth_rate': {
            'growth_rate': 0.001  # fast growth
        },
    }

    # make the agent
    agent_composer = InclusionBodyGrowth(parameters)
    agent_composite = agent_composer.generate()

    # make the environment
    composer = Lattice(LATTICE_CONFIG)
    composite = composer.generate()

    # merge in the agent
    composite.merge(
        composite=agent_composite,
        path=('agents', agent_id))

    # get initial state
    initial_state = composite.initial_state()
    initial_state['agents'][agent_id]['molecules'] = {'biomass': initial_biomass}

    # make the experiment
    inclusion_experiment = Experiment({
        'processes': composite['processes'],
        'topology': composite['topology'],
        'initial_state': initial_state
    })

    # run the experiment
    inclusion_experiment.update(total_time)

    # get the data
    data = inclusion_experiment.emitter.get_data()

    return data

def inclusion_plots_suite(data=None, out_dir=EXPERIMENT_OUT_DIR):
    n_snapshots = 5
    tagged_molecules = [
        ('inclusion_body',),
        ('front', 'aggregate',),
        ('back', 'aggregate',)]

    # multigen plot
    plot_settings = {}
    plot_agents_multigen(data, plot_settings, out_dir)

    # extract data for snapshots
    bounds = LATTICE_CONFIG['multibody']['bounds']
    agents, fields = format_snapshot_data(data)

    # snapshots plot
    plot_snapshots(
        bounds=bounds,
        agents=agents,
        fields=fields,
        n_snapshots=n_snapshots,
        out_dir=out_dir,
        filename='inclusion_snapshots'
    )

    # tags plot
    plot_tags(
        data=data,
        bounds=bounds,
        tagged_molecules=tagged_molecules,
        n_snapshots=n_snapshots,
        convert_to_concs=False,
        out_dir=out_dir,
    )

# libraries for control
experiments_library = {
    '1': {
        'name': 'inclusion_lattice',
        'experiment': test_experiment,
        'kwargs': {
            'total_time': 12000,
        }},
}
plots_library = {
    '1': inclusion_plots_suite
}
workflow_library = {
    '1': {
        'name': 'inclusion_body_experiment',
        'experiment': '1',
        'plots': ['1'],
    }
}

if __name__ == '__main__':
    c = Control(
        experiments=experiments_library,
        plots=plots_library,
        workflows=workflow_library,
        )
    c.run_workflow('1')


import sys

# 문제 분석
# lower case로 이루어진 N개의 단어가 들어오면
# 1. 길이가 짧은 것부터
# 2. 길이가 같으면 사전 순으로
# 정렬 (중복 시 하나만 남기고 제거)

# 입력
# 단어의 개수 N (1 <= N <= 20,000)
# len(string) 문자열의 길이 <= 50
# 한줄에 단어 하나씩

# 접근 방법
# 20,000개의 길이의 리스트 (중복 시 하나만 남겨야 함)
# data = [] 에서 len(i)로 정렬

lst = sys.stdin.readlines()[1:]
lst = list(set(lst))
lst.sort()
lst.sort(key=len)
# print(lst)
print(''.join(lst))

# array.sort()
# array.sort(key = lambda x: len(x))
# for i in array:
#         sys.stdout.write(str(i)+'\n')


from PyQt5.QtWidgets import QMainWindow, QMessageBox, QGraphicsDropShadowEffect
from PyQt5 import uic, QtGui
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtCore import Qt

from Query import Query
from model.Employee import Employee
from UI.NewEmployee import UI_New_Employee
from UI.EmployeeList import UI_Employee_List
from UI.Department import Department
from UI.Timekeeping import Timekeeping
from UI.TimekeepingRecord import Timekeeping_Record
from UI.Tranning import Tranning

class Home(QMainWindow):
    def __init__(self):
        super().__init__()
        uic.loadUi("./UI/Home.ui", self)

        self.current_form = "Home"
        self.current_UI = self

        self.WiDTH_WINDOWN = 1500
        self.HEIGHT_WINDOWN = 800

        self.setWindowFlag(Qt.FramelessWindowHint)

        self.UI_addEmployee = UI_New_Employee()
        self.UI_employeeList = UI_Employee_List()
        self.UI_department = Department()
        self.UI_Timekeeping = Timekeeping()
        self.UI_TKRecord = Timekeeping_Record()
        self.UI_Tranning = Tranning()

        self.lbl_background.setPixmap(
            QPixmap("./public/img/BackgroungHome.jpg"))
        # QPixmap("./public/img/employee-background.jfif"))

        self.pushButton_8.clicked.connect(
            lambda: self.event_change_form("newEmployee"))
        self.pushButton_11.clicked.connect(
            lambda: self.event_change_form("employee"))
        self.pushButton_14.clicked.connect(
            lambda: self.event_change_form("department"))
        self.pushButton_17.clicked.connect(
            lambda: self.event_change_form("timekeeping"))
        self.pushButton_3.clicked.connect(
            lambda: self.event_change_form("timekeeping-record"))
        self.pushButton_20.clicked.connect(
            lambda: self.event_change_form("tranning"))

        # event back to home page
        self.UI_employeeList.btn_Back.mousePressEvent = self.event_back_to_home
        self.UI_addEmployee.btn_Back.mousePressEvent = self.event_back_to_home
        self.UI_Timekeeping.btn_Back.mousePressEvent = self.event_back_to_home
        self.UI_department.btn_Back.mousePressEvent = self.event_back_to_home
        self.UI_TKRecord.btn_Back.mousePressEvent = self.event_back_to_home
        self.UI_Tranning.btn_Back.mousePressEvent = self.event_back_to_home

        # event close app
        self.UI_employeeList.lbl_Close.mousePressEvent = self.event_close_app
        self.UI_addEmployee.lbl_Close.mousePressEvent = self.event_close_app
        self.UI_Timekeeping.lbl_Close.mousePressEvent = self.event_close_app
        self.UI_department.lbl_Close.mousePressEvent = self.event_close_app
        self.UI_TKRecord.lbl_Close.mousePressEvent = self.event_close_app
        self.UI_Tranning.lbl_Close.mousePressEvent = self.event_close_app
        self.lbl_Close.mousePressEvent = self.event_close_app

        # event minimize app
        self.lbl_Minimize.mousePressEvent = self.event_minimize_app

        # css header form
        self.shadow = QGraphicsDropShadowEffect()

        # setting blur radius
        self.shadow.setBlurRadius(15)
        self.shadow.setColor(QtGui.QColor(0, 153, 153).lighter())
        self.shadow.setOffset(5)

    def event_change_form(self, form):
        self.current_form = form

        if (form == "newEmployee"):
            self.current_UI = self.UI_addEmployee
        elif (form == "employee"):
            self.current_UI = self.UI_employeeList
        elif (form == "department"):
            self.current_UI = self.UI_department
        elif (form == "timekeeping"):
            self.current_UI = self.UI_Timekeeping
        elif (form == "timekeeping-record"):
            self.current_UI = self.UI_TKRecord
        elif (form == "tranning"):
            self.current_UI = self.UI_Tranning

        self.current_UI.setFixedHeight(self.HEIGHT_WINDOWN)
        self.current_UI.setFixedWidth(self.WiDTH_WINDOWN)
        self.current_UI.setWindowFlag(Qt.FramelessWindowHint)
        self.current_UI.show()
        self.current_UI.init_form()
        self.hide()

    def event_back_to_home(self, *arg, **kwargs):

        if (self.current_form == "timekeeping"):
            self.UI_Timekeeping.event_stop_all_thread()
            self.UI_Timekeeping.hide()
        elif (self.current_form == "tranning"):
            self.UI_Tranning.hide()
            self.UI_Tranning.event_stop_all_thread()
        elif (self.current_form == "newEmployee"):
            self.UI_addEmployee.hide()
            self.UI_addEmployee.event_stop_all_thread()
        elif (self.current_form == "employee"):
            self.UI_employeeList.hide()
            self.UI_employeeList.event_stop_all_thread()
        elif (self.current_form == "timekeeping-record"):
            self.UI_TKRecord.hide()
            self.current_UI.event_stop_all_thread()

        self.UI_department.hide()

        self.current_UI = self
        self.current_form = "Home"
        self.show()

    def event_close_app(self, *arg, **kwargs):
        mess = QMessageBox()
        mess.setWindowTitle("Warning")
        mess.setText("Are you sure want to close application ?")

        mess.setIcon(QMessageBox.Warning)
        mess.setWindowIcon(QtGui.QIcon("./public/img/back.png"))
        mess.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        if mess.exec_() == QMessageBox.Yes:
            self.current_UI.close()

    def event_minimize_app(self, *arg, **kwargs):
        self.current_UI.showMinimized()


from classes.classes import Cliente

cliente1 = Cliente('Paulo', 21)
cliente1.insere_endereco('Belo Horizonte', 'MG')

print(cliente1.nome)
cliente1.lista_enderecos()
print('############## AGORA VOU DELETAR O CLIENTE1 E POR ISSO VAI DELETAR O ENDEREÇOS ASSOCIADOS A ELE ##############')
del cliente1
print()

cliente2 = Cliente('João', 30)
cliente2.insere_endereco('São Paulo', 'SP')
cliente2.insere_endereco('Rio de Janeiro', 'RJ')

print(cliente2.nome)
cliente2.lista_enderecos()
print()

cliente3 = Cliente('Carla', 15)
cliente3.insere_endereco('Salvador', 'BA')
print(cliente3.nome)
cliente3.lista_enderecos()
print()

print('############## AGORA O COLETOR DE LIXO VAI DELETAR O CLIENTE ######################')


"""remove explosiveness remnants

Revision ID: 77395783fce5
Revises: e5a31e87d305
Create Date: 2017-08-28 13:58:03.355534

"""
from alembic import op
from sqlalchemy import Column
from sqlalchemy.dialects.postgresql import INTEGER, NUMERIC, DATE

# revision identifiers, used by Alembic.
revision = '77395783fce5'
down_revision = 'e5a31e87d305'

def upgrade():
    op.execute('DROP TABLE IF EXISTS explosiveness')

def downgrade():
    """
        CREATE TABLE explosiveness (
            product_version_id integer NOT NULL,
            signature_id integer NOT NULL,
            last_date date NOT NULL,
            oneday numeric,
            threeday numeric,
            day0 numeric,
            day1 numeric,
            day2 numeric,
            day3 numeric,
            day4 numeric,
            day5 numeric,
            day6 numeric,
            day7 numeric,
            day8 numeric,
            day9 numeric
        )
    """
    op.create_table(
        'explosiveness',
        Column(u'day0', NUMERIC()),
        Column(u'day1', NUMERIC()),
        Column(u'day2', NUMERIC()),
        Column(u'day3', NUMERIC()),
        Column(u'day4', NUMERIC()),
        Column(u'day5', NUMERIC()),
        Column(u'day6', NUMERIC()),
        Column(u'day7', NUMERIC()),
        Column(u'day8', NUMERIC()),
        Column(u'day9', NUMERIC()),
        Column(
            u'last_date',
            DATE(),
            primary_key=True,
            nullable=False
        ),
        Column(u'oneday', NUMERIC()),
        Column(
            u'product_version_id',
            INTEGER(),
            primary_key=True,
            nullable=False,
            autoincrement=False,
            index=True
        ),
        Column(
            u'signature_id',
            INTEGER(),
            primary_key=True,
            nullable=False,
            index=True
        ),
        Column(u'threeday', NUMERIC())
    )


import time
import pickle
from .utils.utils import clean_data

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

class Model:
    vectorizer = pickle.load(open("./models/tfidfVectorizer.pickle", "rb"))
    model = pickle.load(open("./models/lrModel.pickle", "rb"))

def get_review_sentiment(review, vectorizer, model):
    review = clean_data(review)
    review = vectorizer.transform([review])
    sentiment = model.predict(review)
    probability = model.predict_proba(review)

    return {
        "sentiment" : "Positive" if sentiment==1 else "Negative",
        "positive prediction" : probability[0][1],
        "negative prediction" : probability[0][0]
        }

app = FastAPI(title="Deploying a ML Model with FastAPI")

@app.get("/")
def home():
    return {"message": "The API is working ..."}

@app.get("/predict/")
async def prediction(review:str):
    try:
        start = time.time()
        result = get_review_sentiment(review, Model.vectorizer, Model.model)
        duration = time.time() - start
        result["time"] = duration

        return {
            "success": True,
            "result": result
        }

    except Exception as error:
        return {
            "success": False,
            "errors": [str(error)]
        }


import tkinter as tk
import pygame

# Variables
# Colors

WHITE = 255, 255, 255
BLACK = 0,0,0
RED = 255, 0, 0
GREEN = 0, 255, 0
BLUE = 0, 0, 255

# Screen
# TKinter Width and Height
root = tk.Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
root.destroy()  # Close the temporary tkinter window

# Pygame Screen
WIDTH, HEIGHT = screen_width, screen_height
WIN = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)

# Title
pygame.display.set_caption("Ocean Guardian")


# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

from multiprocessing import Process, Queue
#from Queue import Full
import pyaudio
import wave
import numpy as N
from cf_dsp import dsp

class wave_reader:
    def __init__(self, infile, frames_per_buffer=4410):
        print("Opening '%s' file..." % infile,)
        self.f = wave.open(infile, 'rb')
        rate = self.f.getframerate()
        sampwidth = self.f.getsampwidth()
        channels = self.f.getnchannels()
        print("fmt %d, %d Hz stream of %d size (%d channel)" % (
                sampwidth, rate, frames_per_buffer, channels))
        if channels > 1:
            raise RuntimeError("Only mono input wave file")
        self.eq = eq(rate, sampwidth, frames_per_buffer)
        self.frames_per_buffer = frames_per_buffer
        self.params = []

    def recv(self):
        if len(self.params) > 0:
            return self.params.pop()
        data = self.f.readframes(self.frames_per_buffer)
        if data == '':
            return None
        for param in self.eq.gen(data):
            self.params.insert(0, param)
        return self.params.pop()

class wave_file:
    def __init__(self, wf):
        self.wf = wave.open(wf, 'rb')
        self.rate = self.wf.getframerate()
        self.channels = self.wf.getnchannels()
        self.format = self.wf.getsampwidth()

    def read(self, frames_per_buffer):
        data = self.wf.readframes(frames_per_buffer)
        if data == '':
            raise KeyboardInterrupt
        return data

    def close(self):
        self.wf.close()

class fake_audio_process:
    def __init__(self, *arg):
        self.cpt = 0

    def recv(self, mode=None):
        #  time.sleep(0.5)
        if self.cpt & 1:
            return (0.9, 0.9, 0.9, 0.9, N.random.random(886)/10.0)
        self.cpt += 1
        return (0.0, 0.0, 0.0, 0.0, N.random.random(886)/10.0)

class audio_process:
    def __init__(self, fps=25, input_fd=None, output_device_index=None):
        self.q = Queue(4096 * 4096)
        self.rate = 44100     # hardcoded 44100 Hz sample rate
        if self.rate / fps != self.rate / fps:
            raise RuntimeError("Frame per second must be a multiple of %d" %
                               self.rate)
        self.frames_per_buffer = self.rate // fps
        self.output_device_index = output_device_index
        self.input_fd = input_fd
        p = Process(target=self.run, args=())
        p.start()

    def process(self):
        while True:
            data = self.input_stream.read(self.frames_per_buffer)
            self.q.put_nowait(self.dsp.gen(data))
            if self.output_stream:
                self.output_stream.write(data)

    def get_device_name(self, idx):
        if not idx:
            return "default"
        return self.p.get_device_info_by_index(int(idx))['name']

    def check_input_stream(self):
        if self.input_stream.rate != self.rate:
            raise RuntimeError("Bad input sample rate %d, only %d supported" %
                               (self.input_stream.rate, self.rate))
        if self.input_stream.channels != 1:
            raise RuntimeError("Only mono input supported")
        if self.input_stream.format != 2:
            raise RuntimeError("Only paInt16 sample format supported")

    def open_stream(self, input=False, output=False):
        return self.p.open(
                format=pyaudio.paInt16,
                channels=2,
                rate=self.rate,
                output=output,
                input=input,
                output_device_index=self.output_device_index,
                input_device_index=int(self.input_fd),
                frames_per_buffer=self.frames_per_buffer)

    def run(self):
        import os
        try:
            os.nice(-5)
        except OSError:
            print("Could not set high priority on audio processing, "
                  "beware of input overflow")
        self.dsp = dsp()
        self.p = pyaudio.PyAudio()

        if os.path.isfile(self.input_fd):
            self.input_stream = wave_file(self.input_fd)
            self.check_input_stream()
            print("Input stream: '%s' format %d bytes, rate %d Hz, "
                  "%d channels" % (
                          self.input_fd,
                          self.input_stream.format,
                          self.input_stream.rate,
                          self.input_stream.channels))

            print("Opening Output stream: '%s'" %
                  self.get_device_name(self.output_device_index))
            self.output_stream = self.open_stream(output=True)
        #     self.output_stream = None
        else:
            print("Opening Input stream: '%s' paInt16 %d Hz stream of "
                  "%d size" % (
                    self.get_device_name(self.input_fd),
                    self.rate, self.frames_per_buffer))
            self.input_stream = self.open_stream(input=True)
            self.output_stream = None

        while True:
            try:
                self.process()
            except IOError as e:
                print("IOError:", e)
#            except Full as e:
#                print("The queue is full!")
            except KeyboardInterrupt:
                break
        print("Closing streams")
        self.input_stream.close()
        if self.output_stream:
            self.output_stream.close()
        self.p.terminate()

    def recv(self, render_video=None):
        if not render_video and self.q.qsize() > 3:
            print("Processing too slow - %d frames late, flushing..." %
                  self.q.qsize())
            try:
                while True:
                    self.q.get(False)
            except:
                pass
        return self.q.get()


lista = []
while True:
    a, b = map(str, input().split(' '))
    if a == '0' and b == '0':
        break
    for numero in b:
        if numero != a:
            lista.append(numero)
    try:
        while lista[0] == '0':
            del(lista[0])
    except IndexError:
        lista.append('0')
    for i in lista:
        print(i, end='')
    print()
    lista.clear()


from gamelib import *

game = Game(800,600,"Exploring List", 60)
bk = Animation("images\\field_5.png",5,game,1000,1000)
game.setBackground(bk)

asteroids = []

for num in range(150):
    asteroids.append(  Animation("images\\asteroid1t.gif",41,game,2173/41, 52, 2 )   )

for asteroid in asteroids:
    x = game.width + randint(100 ,10500)
    y = randint(5 ,550)
    s = randint(4,8)
    asteroid.moveTo(x,y)
    asteroid.setSpeed(s,90)

while not game.over:
    game.processInput()
    game.drawBackground()

    for asteroid in asteroids:
        asteroid.move()

    game.update(30)

game.quit()


from django.conf.urls import patterns, include, url
from django.contrib import admin

from eAlarmWebapp import settings
from myapp.views import Home, DeviceProperties, AddDeviceProperties, EditDeviceProperties, Area, AddArea, DeviceInfor, EditArea\
, Device, User, Error, Group, ListDevice, AddDevice, EditDevice, Report, Railway, \
    RailwayList, RailwayProperty, Log, Route, RailwayAssign, Language, Manage, \
    DeviceType, DeviceTypeProperties

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^home$', Home.home),
    #Vinh
    #manage
    url(r'^manage/railway/balance/$', Manage.balance,name='assign-railway'),
    url(r'^manage/assign-railway/$', Manage.assign_railway,name='assign-railway'),
    url(r'^manage/railway/order/$', Manage.railway_order,name='manage-railway-order'),
    url(r'^manage/railway/statistics/$', Manage.railway_statistics,name='manage-railway-statistics'),
    url(r'^ajax-get-device-by-route$', Manage.getDeviceByRoute,name='ajax-get-device-by-route'),
    url(r'^ajax-down-order-route$', Manage.downOrderRoute,name='ajax-down-order-route'),
    url(r'^ajax-up-order-route$', Manage.upOrderRoute,name='ajax-up-order-route'),
    url(r'^ajax-down-order-device$', Manage.downOrderDevice,name='ajax-down-order-device'),
    url(r'^ajax-up-order-device$', Manage.upOrderDevice,name='ajax-up-order-device'),
    url(r'^ajax-get-user-device$', Manage.getAssignDeviceByUser,name='ajax-get-user-device'),
    url(r'^ajax-assign-device-to-user$', Manage.assignDeviceToUser,name='ajax-assign-device-to-user'),
    url(r'^ajax-unsign-device-from-user$', Manage.unsignDeviceFromUser,name='ajax-unsign-device-from-user'),
    #railway
    url(r'^railway/monitor/$', Railway.monitor,name='railway-monitor'),
    url(r'^railway/monitor/V2/$', Railway.monitorV2,name='railway-monitor'),
    url(r'^railway/manager/$', Railway.railway_manager,name='railway-manager'),
    url(r'^ajax-get-railway-history$', Railway.getRailwayHistory,name='ajax-get-railway-history'),
    url(r'^ajax-delete-railway-history$', Railway.deleteRailwayHistory,name='ajax-delete-railway-history'),
    url(r'^ajax-edit-railway-history$', Railway.editRailwayHistory,name='ajax-edit-railway-history'),
    url(r'^ajax-edit-railway-history-detail$', Railway.editRailwayHistoryDetail,name='ajax-edit-railway-history-detail'),
    url(r'^railway/maps/$', Railway.maps,name='railway-maps'),
    url(r'^railway/list/$', RailwayList.index,name='railway-list'),
    url(r'^railway/property/$', RailwayProperty.index,name='railway-property'),
    url(r'^railway/route/$', Route.index,name='railway-route'),
    #device type
    url(r'^device/type/$', DeviceType.index,name='device-type'),
    url(r'^device/type/add/$', DeviceType.add_device_type,name='add-device-type'),
    url(r'^device/type/edit/$', DeviceType.edit_device_type,name='edit-device-type'),
    url(r'^device/type/properties/$', DeviceTypeProperties.index,name='device-type-properties'),
    url(r'^device/type/properties/list/$', DeviceTypeProperties.property_list,name='device-type-properties-list'),
    url(r'^device/type/properties/add/$', DeviceTypeProperties.add,name='device-type-properties-add'),
    url(r'^device/type/properties/edit/$', DeviceTypeProperties.edit,name='device-type-properties-edit'),
    url(r'^device/type/properties/delete/$', DeviceTypeProperties.delete,name='device-type-properties-delete'),
    #assign railway
    url(r'^railway/assign/$', RailwayAssign.index,name='railway-assign'),
    #add,edit,delete railway
    url(r'^railway/list/add/$', RailwayList.add_railway,name='railway-list-add'),
    url(r'^railway/list/edit/(?P<railway_id>\w+)/$', RailwayList.edit_railway,name='railway-list-edit'),
    url(r'^railway/list/delete/(?P<railway_id>\w+)/$', RailwayList.delete_railway,name='railway-list-delete'),
     #add,edit,delete property
    url(r'^railway/property/add/$', RailwayProperty.add_property,name='railway-property-add'),
    url(r'^railway/property/edit/(?P<property_id>\w+)/$', RailwayProperty.edit_property,name='railway-property-edit'),
    url(r'^railway/property/delete/(?P<property_id>\w+)/$', RailwayProperty.delete_property,name='railway-property-delete'),
    #add,edit,delete route
    url(r'^railway/route/add/$', Route.add_route,name='railway-route-add'),
    url(r'^railway/route/edit/(?P<route_id>\w+)/$', Route.edit_route,name='railway-route-edit'),
    url(r'^railway/route/delete/(?P<route_id>\w+)/$', Route.delete_route,name='railway-route-delete'),
    #get_property
    url(r'^get-property/(?P<p_id>\w+)/(?P<p_code>\w+)/$', RailwayProperty.get_property, name='get-property'),
    #get_route
    url(r'^get-route/(?P<r_id>\w+)/(?P<r_code>\w+)/$', Route.get_route, name='get-route'),
    #view log
    url(r'^log/view/$', Log.index,name='log-view'),
    #machine room
    url(r'^device-infor$', DeviceInfor.index),
    url(r'^$', Home.index),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^password/change/$', 'django.contrib.auth.views.password_change', {'template_name': 'change-password.html'}, name='password_change'),
    url(r'^password/change/done/$',
                    'django.contrib.auth.views.password_change_done', {'template_name': 'change-password-done.html'},
                    name='password_change_done'),
    url(r'^login$', 'django.contrib.auth.views.login', {'template_name': 'signin.html'}, name='login'),
    url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': 'login'}),
    url(r'^device-property$', DeviceProperties.index),
    url(r'^add-device-property$', AddDeviceProperties.index,name='add-device-property'),
    url(r'^edit-device-property$', EditDeviceProperties.index,name='add-device-property'),
	url(r'^area$', Area.index),
    url(r'^add-area$', AddArea.index),
    url(r'^add-area$', AddArea.index,name='add-area'),
    url(r'^edit-area$', EditArea.index),
    url(r'^device$', Device.index),
    url(r'^device-list$', ListDevice.index),
    url(r'^add-device', AddDevice.index),
    url(r'^add-device', AddDevice.index,name='add-device'),
    url(r'^edit-device', EditDevice.index),
    url(r'^edit-device', EditDevice.index,name='edit-device'),

    # User
    url(r'^user$', User.view_user,name='user'),
    url(r'^user/add/$', User.add_user,name='delete-user'),
    url(r'^user/delete/(?P<user_id>\w+)/$', User.delete_user,name='add-user'),
    url(r'^user/(?P<user_id>\w+)/$', User.change_user,name='change-user'),
    # Group
    url(r'^group$', Group.view_group,name='user'),
    url(r'^group/add/$', Group.add_group,name='add-group'),
    url(r'^group/delete/(?P<group_id>\w+)/$', Group.delete_group,name='delete-group'),
    url(r'^group/(?P<group_id>\w+)/$', Group.change_group,name='change-group'),
    # Device Report
    url(r'^device-report$', Report.view_device_report,name='device-report'),
    url(r'^device-detail-report$', Report.view_device_detail_report,name='device-detail-report'),
    url(r'^device-error-report$', Report.view_device_error_report,name='device-error-report'),
    url(r'^sensor-mirror-report/$', Report.view_sensor_mirror_report,name='sensor-mirror-report'),
    # Device Detail Report
    url(r'^group$', Group.view_group,name='user'),
    url(r'^permission-error$', Error.permission_error,name='permission-error'),
    url(r'^notfound-error$', Error.notfound_error,name='notfound-error'),
    # Ajax
    url(r'^ajax-railway-history$', DeviceInfor.getRaiwayHistory,name='ajax-railway-history'),
    url(r'^ajax-railway-detail-history$', DeviceInfor.getRaiwayDetailHistory,name='ajax-railway-detail-history'),
    url(r'^ajax-device-history$', DeviceInfor.getDeviceHistory,name='ajax-device-history'),
    url(r'^language/(?P<language_code>\w+)/$', Language.switch_language, name='switch-language'),
    # System
    url(regex=r'^report/(?P<path>.*)$', view='django.views.static.serve', kwargs={'document_root': settings.REPORT_ROOT, 'show_indexes' : True, }),
    url(regex=r'^(?P<path>.*)$', view='django.views.static.serve', kwargs={'document_root': settings.STATIC_ROOT, 'show_indexes' : True, }),
)


#!/usr/bin/env python3

import os
import sys
import torch
import logging
import speechbrain as sb
from hyperpyyaml import load_hyperpyyaml
from speechbrain.utils.distributed import run_on_main
import webdataset as wds
from glob import glob
import io
import torchaudio

sys.path.append("local/")
sys.path.append("local/chain")
import pathlib

from make_shards import wavscp_to_output, segments_to_output, text_to_output, sync_streams, make_data_point

logger = logging.getLogger(__name__)

class KaldiData(torch.utils.data.IterableDataset):
    def __init__(self, path, tokenizer, bos_index, eos_index):
        self.testdir = pathlib.Path(path)
        self.tokenizer = tokenizer
        self.bos_index = bos_index
        self.eos_index = eos_index
        self._iterable = None

    @staticmethod
    def count_scp_lines(scpfile):
        lines = 0
        with open(scpfile) as fin:
            for _ in fin:
                lines += 1
        return lines

    def rename(self, sample):
        sample["trn"] = sample["transcript.txt"]
        sample["wav"] = sample["audio.pth"]
        del sample["transcript.txt"]
        del sample["audio.pth"]
        return sample

    def tokenize(self, sample):
        text = sample["trn"]
        # quick hack for one sample in text of test2021:
        text = text.replace(" <NOISE>", "")
        fulltokens = torch.LongTensor(
                [self.bos_index] + self.tokenizer.encode(text) + [self.eos_index]
        )
        sample["tokens"] = fulltokens[1:-1]
        sample["tokens_bos"] = fulltokens[:-1]
        sample["tokens_eos"] = fulltokens[1:]
        return sample

    def __len__(self):
        if (self.testdir / "segments").exists():
            return self.count_scp_lines(self.testdir / "segments")
        else:
            return self.count_scp_lines(self.testdir / "wav.scp")

    def __iter__(self):
        self._iterable = self._get_iterable()
        return self

    def __next__(self):
        outputs = next(self._iterable)
        datapoint = make_data_point(outputs)
        datapoint = self.rename(datapoint)
        datapoint = self.tokenize(datapoint)
        return datapoint

    def _get_iterable(self):
        if (self.testdir / "segments").exists():
            audio_iter = segments_to_output(self.testdir / "segments", self.testdir / "wav.scp")
        else:
            audio_iter = wavscp_to_output(self.testdir / "wav.scp")
        text_iter = text_to_output(self.testdir / "text")
        return sync_streams([audio_iter, text_iter], maxskip=0)

# Brain class for speech recognition training
class ShallowFusion(sb.Brain):
    def compute_forward(self, batch, stage):
        # We first move the batch to the appropriate device.
        batch = batch.to(self.device)
        feats = self.hparams.compute_features(batch.wav.data)
        feats = self.modules.normalize(feats, batch.wav.lengths)

        # Running the encoder (prevent propagation to feature extraction)
        encoded_signal = self.modules.encoder(feats.detach())

        predictions, _ = self.hparams.test_search(
            encoded_signal, batch.wav.lengths
        )

        return predictions

    def compute_objectives(self, predictions, batch, stage):
        specials = [self.hparams.bos_index, self.hparams.eos_index, self.hparams.unk_index]
        predictions = [
                [token for token in pred if token not in specials]
                for pred in predictions
        ]
        predicted_words = [
            self.hparams.tokenizer.decode_ids(prediction).split(" ")
            for prediction in predictions
        ]
        target_words = [words.split(" ") for words in batch.trn]

        # Monitor word error rate and character error rated at
        # valid and test time.
        self.wer_metric.append(batch.__key__, predicted_words, target_words)
        self.cer_metric.append(batch.__key__, predicted_words, target_words)

        return torch.tensor([0.])

    def on_stage_start(self, stage, epoch):
        self.cer_metric = self.hparams.cer_computer()
        self.wer_metric = self.hparams.error_rate_computer()

    def on_stage_end(self, stage, stage_loss, epoch):
        """Gets called at the end of an epoch.

        Arguments
        ---------
        stage : sb.Stage
            One of sb.Stage.TRAIN, sb.Stage.VALID, sb.Stage.TEST
        stage_loss : float
            The average loss for all of the data processed in this stage.
        epoch : int
            The currently-starting epoch. This is passed
            `None` during the test stage.
        """

        # Store the train loss until the validation stage.
        stage_stats = {}
        stage_stats["CER"] = self.cer_metric.summarize("error_rate")
        stage_stats["WER"] = self.wer_metric.summarize("error_rate")
        with open(self.hparams.wer_file, "w") as w:
            self.wer_metric.write_stats(w)
        with open(self.hparams.decode_text_file, "w") as fo:
            for utt_details in self.wer_metric.scores:
                print(utt_details["key"], " ".join(utt_details["hyp_tokens"]), file=fo)

    def on_evaluate_start(self, max_key=None, min_key=None):
        lm_ckpt = self.hparams.lm_ckpt_finder.find_checkpoint(min_key="loss")
        self.hparams.lm_pretrainer.collect_files(lm_ckpt.path)
        self.hparams.lm_pretrainer.load_collected(self.device)
        asr_ckpt = self.hparams.asr_ckpt_finder.find_checkpoint(min_key="WER")
        self.hparams.asr_pretrainer.collect_files(asr_ckpt.path)
        self.hparams.asr_pretrainer.load_collected(self.device)

if __name__ == "__main__":

    # Reading command line arguments
    hparams_file, run_opts, overrides = sb.parse_arguments(sys.argv[1:])

    # Load hyperparameters file with command-line overrides
    with open(hparams_file) as fin:
        hparams = load_hyperpyyaml(fin, overrides)

    # Create experiment directory
    sb.create_experiment_directory(
        experiment_directory=hparams["output_folder"],
        hyperparams_to_save=hparams_file,
        overrides=overrides,
    )

    # Trainer initialization
    asr_brain = ShallowFusion(
        modules=hparams["modules"],
        hparams=hparams,
        run_opts=run_opts,
    )

    print("Decoding", hparams["test_data_id"])
    test_data = KaldiData(hparams["test_data_dir"],
            tokenizer = hparams["tokenizer"],
            bos_index = hparams["bos_index"],
            eos_index = hparams["eos_index"])
    test_loader_kwargs = hparams.get("test_loader_kwargs", {})
    test_loader_kwargs.setdefault("batch_size", hparams.get("test_batch_size", 1))
    if "collate_fn" not in test_loader_kwargs:
        test_loader_kwargs["collate_fn"] = sb.dataio.batch.PaddedBatch

    test_stats = asr_brain.evaluate(
        test_set=test_data,
        min_key="WER",
        test_loader_kwargs = test_loader_kwargs
    )


from django.contrib.auth import get_user_model
from django.contrib.postgres.indexes import GinIndex
from django.db import models

User = get_user_model()

class Notification(models.Model):
    created_on = models.DateTimeField(
        auto_now_add=True,
        help_text="The date and time when the notification was created.",
    )
    type = models.CharField(max_length=64, help_text="The type of notification.")
    broadcast = models.BooleanField(
        default=False,
        help_text=(
            "If True, then the notification will be sent to all users. "
            "A broadcast notification will not immediately create all the "
            "NotificationRecipient objects, but will do so when the "
            "notification is read or cleared by a user."
        ),
    )
    workspace = models.ForeignKey(
        "core.Workspace",
        null=True,
        on_delete=models.CASCADE,
        related_name="notifications",
        help_text=(
            "The workspace where the notification lives."
            "If the notification is a broadcast notification, then the "
            "workspace will be None."
            "Workspace can be null also if the notification is not "
            "associated with a specific workspace or if the user does not "
            "have access to the workspace yet, like for a workspace invitation."
        ),
    )
    sender = models.ForeignKey(
        User,
        null=True,
        on_delete=models.SET_NULL,
        related_name="sent_notifications",
        help_text="The user that will receive the notification.",
    )
    recipients = models.ManyToManyField(
        User,
        through="NotificationRecipient",
        related_name="notifications",
        help_text=(
            "The users that will receive the notification. For broadcast "
            "notifications, the recipients will be created when the "
            "notification is read or cleared by the user."
            "For direct notifications, the recipients will be created "
            "immediately when the notification is created."
        ),
    )
    data = models.JSONField(default=dict, help_text="The data of the notification.")

    class Meta:
        ordering = ["-created_on"]
        indexes = [
            models.Index(fields=["-created_on"]),
            GinIndex(name="notification_data", fields=["data"]),
        ]

class NotificationRecipient(models.Model):
    notification = models.ForeignKey(
        Notification,
        on_delete=models.CASCADE,
        help_text="The notification that will be sent to the recipient.",
    )
    recipient = models.ForeignKey(
        User,
        null=True,
        on_delete=models.CASCADE,
        help_text="The user that will receive the notification.",
    )
    read = models.BooleanField(
        default=False,
        help_text=("If True, then the notification has been read by the user. "),
    )
    cleared = models.BooleanField(
        default=False,
        help_text=(
            "If True, then the notification has been cleared by the user. "
            "Cleared notifications will not be visible by the user anymore."
        ),
    )
    queued = models.BooleanField(
        default=False,
        help_text=(
            "If True, then the notification has been queued for sending. "
            "Queued notifications cannot be seen by the user yet. "
            "Once the notification has been sent, this field will be "
            "set to False and the user will be able to fetch it via API."
        ),
    )
    email_scheduled = models.BooleanField(
        default=False,
        help_text=(
            "If True, then the notification has been scheduled to be sent by email "
            "to the recipient email."
        ),
    )
    # The following fields are copies of the notification fields needed to
    # speed up queries.
    created_on = models.DateTimeField(
        help_text="A copy of the notification created_on field needed to speed up queries.",
    )
    broadcast = models.BooleanField(
        default=False,
        help_text=(
            "A copy of the notification broadcast field needed to speed up queries."
        ),
    )
    workspace_id = models.BigIntegerField(
        null=True,
        help_text=(
            "A copy of the notification workspace_id field needed to speed up queries."
        ),
    )

    class Meta:
        ordering = ["-created_on"]
        unique_together = ("notification", "recipient")
        indexes = [
            models.Index(fields=["-created_on"]),
            models.Index(
                fields=[
                    "broadcast",
                    "cleared",
                    "read",
                    "queued",
                    "recipient_id",
                    "workspace_id",
                ],
                name="unread_notif_count_idx",
                condition=models.Q(cleared=False, read=False),
                include=["notification_id"],
            ),
        ]


from DynamicSQLite import database
from DynamicSQLite.database import DModel
class Customer(DModel):
    TABLE = 'Customers'
    def __init__(self, name, address):
        self.name = name
        self.address = address
        super(Customer, self).__init__(self.TABLE, self.__dict__.copy())

new_customer = Customer('Jesse', '201 Fredrick Avenue')
database.add_models(new_customer)

customers = database.load_table_limit(Customer.TABLE, 2)
print(customers)


stacks, actions = open("5.in", "r").read().split("\n\n")

elements = []
for stack in stacks.split("\n")[:-1]:
    elements.append([stack[i+1] for i in range(0, len(stack), 4)])

# Stack is correctly orriented after this step
stacks = [list(filter(lambda x: x != " ", e)) for e in zip(*elements)]

def part1_reorder(x,y,z):
    for _ in range(int(x)):
        val = stacks[int(y)-1].pop(0)
        stacks[int(z)-1] = [val] + stacks[int(z)-1]

def part2_reorder(x,y,z):
    elements = [stacks[int(y)-1].pop(0) for _ in range(int(x))]
    stacks[int(z)-1] = elements + stacks[int(z)-1]

for action in actions.split("\n"):
    # move x from y to z
    _,x,_,y,_,z = action.split(" ")
    # part1_reorder(x,y,z)
    part2_reorder(x,y,z)
print("".join([s[0] for s in stacks]))


from flask_restful import Resource, reqparse
import sys
sys.path.append('../')
from Data.EmployeeData import EmployeeData

employee_put_args =  reqparse.RequestParser()
employee_put_args.add_argument("id",type = int, help="id of the employee", required = True, location='form')
employee_put_args.add_argument("name", help="name of the employee", required = True,location='form')
employee_put_args.add_argument("age",type = int, help="age of the employee", required = True, location='form')
employee_put_args.add_argument("yearsOfExperience",type = int, help="years of experience of the employee", location='form')

employees_collection_name = "Employees"
librarians_collection_name = "Librarians"

class employee(Resource):
    employee_data = EmployeeData()

    def get(self, employee_id):
        self.employee_data.abort_if_id_isnt_valid(employee_id, employees_collection_name, True)
        return self.employee_data.get_employee(employee_id)

    def delete(self, employee_id):
        self.employee_data.abort_if_id_isnt_valid(employee_id, employees_collection_name, True)
        return self.employee_data.delete_employee(employee_id), 202

class employees(Resource):
    employee_data = EmployeeData()

    def get(self):
        return self.employee_data.get_employees()

    def post(self, is_super = False, args = None):
            if is_super is False:
                args = employee_put_args.parse_args()

            self.employee_data.abort_if_id_isnt_valid(args.id, employees_collection_name, False) # Data layer

            args.isFired = False
            del args['yearsOfExperience']
            self.employee_data.post_employees(args) # Data layer

            del args['_id']
            return args, 201

class librarians(Resource):
    employee_data = EmployeeData()
    employees = employees()

    def post(self):

        args = employee_put_args.parse_args()

        new_args = {'id': args.id, 'yearsOfExperience': args.yearsOfExperience}

        self.employees.post(True, args)

        self.employee_data.post_librarian(new_args)
        del new_args['_id']

        return new_args, 201


from andromeda_chain.prompt import AndromedaPrompt

CHOICE_PROMPT =  AndromedaPrompt(
    name="choice_prompt",
    prompt_template = """{{history}}
You must now choose an option out of the {{valid_choices}}.
Remember that it must be coherent with your last thought.
{{select 'choice' logprobs='logprobs' options=valid_choices}}: """,
    input_vars=["history", "valid_choices"],
    output_vars=["choice"],
)