import unittest
import numpy as np

from mtrack.cores import CoreBuilder

class CoreBaseTest(unittest.TestCase):
    def setUp(self):
        self.volume_size = np.array([200, 100, 60])
        self.core_size = np.array([10, 10, 10])
        self.offset = np.array([0, 0, 0])
        self.context_size = np.array([20, 20, 20])
        self.n_cores = np.array([16, 6, 2])

class GenerateCoresTestCase(CoreBaseTest):
    def runTest(self):
        builder = CoreBuilder(volume_size=self.volume_size,
                              core_size=self.core_size,
                              offset=self.offset,
                              context_size=self.context_size)

        cores = builder.generate_cores(gen_nbs=True)
        # Check that we have the correct number of cores
        self.assertTrue(len(cores) == reduce(lambda x,y: x*y, self.n_cores))

        for core in cores:
            # Check correct core size
            self.assertTrue(core.x_lim_core["max"] - core.x_lim_core["min"] == self.core_size[0])
            self.assertTrue(core.y_lim_core["max"] - core.y_lim_core["min"] == self.core_size[1])
            self.assertTrue(core.z_lim_core["max"] - core.z_lim_core["min"] == self.core_size[2])

            # Check correct context size
            self.assertTrue(core.x_lim_context["max"] -\
                            core.x_lim_context["min"] == 2*self.context_size[0] + self.core_size[0])
            self.assertTrue(core.y_lim_context["max"] -\
                            core.y_lim_context["min"] == 2*self.context_size[1] + self.core_size[1])
            self.assertTrue(core.z_lim_context["max"] -\
                            core.z_lim_context["min"] == 2*self.context_size[2] + self.core_size[2])

            # Check that each block is contained in volume
            self.assertTrue(core.x_lim_context["min"] >= self.offset[0])
            self.assertTrue(core.y_lim_context["min"] >= self.offset[1])
            self.assertTrue(core.z_lim_context["min"] >= self.offset[2])

            self.assertTrue(core.x_lim_context["max"] <= self.offset[0] + self.volume_size[0])
            self.assertTrue(core.y_lim_context["max"] <= self.offset[1] + self.volume_size[1])
            self.assertTrue(core.z_lim_context["max"] <= self.offset[2] + self.volume_size[2])

            self.assertTrue(core.x_lim_core["min"] >= self.offset[0])
            self.assertTrue(core.y_lim_core["min"] >= self.offset[1])
            self.assertTrue(core.z_lim_core["min"] >= self.offset[2])

            self.assertTrue(core.x_lim_core["max"] <= self.offset[0] + self.volume_size[0])
            self.assertTrue(core.y_lim_core["max"] <= self.offset[1] + self.volume_size[1])
            self.assertTrue(core.z_lim_core["max"] <= self.offset[2] + self.volume_size[2])

class NeighbourTestCase(CoreBaseTest):
    def runTest(self):
        i = 0
        max_nbs = [0, 26, 124]
        min_nbs = [0, 7, 26]

        # Overwrite volume size s.t. max number of neighbours is realized
        self.volume_size = np.array([200, 160, 120])

        for context_size in [np.array([0,0,0]),
                             np.array([5,5,5]),
                             np.array([10,10,10])]:

            builder = CoreBuilder(volume_size=self.volume_size,
                                  core_size=self.core_size,
                                  offset=self.offset,
                                  context_size=context_size)

            cores = builder.generate_cores(gen_nbs=True)

            len_nbs = [len(x.nbs) for x in cores]
            self.assertTrue(max(len_nbs) == max_nbs[i])
            self.assertTrue(min(len_nbs) == min_nbs[i])
            i += 1

if __name__ == "__main__":
    unittest.main()


#  Curtis Owens
#  CS 210: Programming Languages
#  Professor Ksendemir
#  December 11, 2022

'''
Project 3 summary:
The Corner Grocer needs a program that analyzes the text records they generate throughout the day. These records list
items purchased in chronological order from the time the store opens to the time it closes. They are interested in
rearranging their produce section and need to know how often items are purchased so they can create the most effective
layout for their customers. The program that the Corner Grocer is asking you to create should address the following
three requirements for a given text-based input file that contains a list of purchased items for a single day:

Produce a list of all items purchased in a given day along with the number of times each item was purchased.
Produce a number representing how many times a specific item was purchased in a given day.
Produce a text-based histogram listing all items purchased in a given day, along with a representation of the
number of times each item was purchased.

'''

import re # For regular expression operations.
import string # For common string operations.

#  Python functtion opening and reading from a file:
grocery_items = dict()
input_file = open("cornerGrocer.txt", "r")
for line in input_file:
    line = line.strip()
    words = line.split(" ")
    for word in words:
        if word in grocery_items:
            grocery_items[word] = grocery_items[word] + 1
        else:
            grocery_items[word] = 1
input_file.close()

#  Python functtion that prints each item purchased along with its quantity:
def printItemCount():
    print("\nQUANTITY OF EACH ITEM PURCHASED TODAY\n")
    for item in list(grocery_items.keys()):
        print(item, end = "")
        print(":", grocery_items[item])
    print()

#  Python functtion that prints a user specified item:
def printCount(userItem):
    userItem = userItem.capitalize()
    for item in list(grocery_items.keys()):
        if (userItem == item):
            return grocery_items[item]
    return 0

#  Python functtion creates a file and writes the items and quanitities to it:
def createFile(fileName):
    input_file = open(fileName, "w")
    for item in list(grocery_items.keys()):
        input_file.write("\n" + item + " " + str(grocery_items[item]))
    input_file.close()
    return 0


import distutils.util
import os
import subprocess
if subprocess.run('nvidia-smi').returncode:
  raise RuntimeError(
      'Cannot communicate with GPU. '
      'Make sure you are using a GPU Colab runtime. '
      'Go to the Runtime menu and select Choose runtime type.')

import mujoco

import time
import itertools
import numpy as np
from typing import Callable, NamedTuple, Optional, Union, List

import mediapy as media
import matplotlib.pyplot as plt

# More legible printing from numpy.
np.set_printoptions(precision=3, suppress=True, linewidth=100)

def write_frames(frames, frate=60):
    try:
        shape = (240, 320)
        type = 'gif'
        if type == 'mp4':
            #for guide, https://google.github.io/mediapy/mediapy.html#write_video
            with media.VideoWriter('./tmp/moving_body.mp4', shape, fps=frate) as writer:
                for frame_i in frames:
                    writer.add_image(frame_i)
        elif type == 'gif':
            with media.VideoWriter('./tmp/moving_body.gif', shape, fps=frate, codec='gif') as writer:
                for frame_i in frames:
                    writer.add_image(frame_i)

        print("writing success!")

    except:
        print("writing failed!")
        return False

    return True

def case1():
    xml = """
    <mujoco>
      <worldbody>
        <light name="top" pos="0 0 1"/>
        <body name="box_and_sphere" euler="0 0 -30">
          <joint name="swing" type="hinge" axis="1 -1 0" pos="-.2 -.2 -.2"/>
          <geom name="red_box" type="box" size=".2 .2 .2" rgba=".3 .5 .3 1"/>
          <geom name="green_sphere" pos=".2 .2 .2" size=".1" rgba="0 1 0 1"/>
        </body>
      </worldbody>
    </mujoco>
    """
    model = mujoco.MjModel.from_xml_string(xml)
    data = mujoco.MjData(model)
    renderer = mujoco.Renderer(model)

    # enable joint visualization option:
    scene_option = mujoco.MjvOption()
    scene_option.flags[mujoco.mjtVisFlag.mjVIS_JOINT] = True

    duration = 3.8  # (seconds)
    framerate = 60  # (Hz)

    frames = []
    mujoco.mj_resetData(model, data)
    while data.time < duration:
        mujoco.mj_step(model, data)
        if len(frames) < data.time * framerate:
            renderer.update_scene(data, scene_option=scene_option)
            pixels = renderer.render()
            # print(np.sum(pixels))

            frames.append(pixels)

    # Simulate and display video.
    # media.show_video(frames, fps=framerate)
    return write_frames(frames, 30)

def case2():
    tippe_top = """
        <mujoco model="tippe top">
          <option integrator="RK4"/>

          <asset>
            <texture name="grid" type="2d" builtin="checker" rgb1=".1 .2 .3"
             rgb2=".2 .3 .4" width="300" height="300"/>
            <material name="grid" texture="grid" texrepeat="8 8" reflectance=".2"/>
          </asset>

          <worldbody>
            <geom size=".2 .2 .01" type="plane" material="grid"/>
            <light pos="0 0 .6"/>
            <camera name="closeup" pos="0 -.1 .07" xyaxes="1 0 0 0 1 2"/>
            <body name="top" pos="0 0 .02">
              <freejoint/>
              <geom name="ball" type="sphere" size=".02" />
              <geom name="stem" type="cylinder" pos="0 0 .02" size="0.004 .008"/>
              <geom name="ballast" type="box" size=".023 .023 0.005"  pos="0 0 -.015"
               contype="0" conaffinity="0" group="3"/>
            </body>
          </worldbody>

          <keyframe>
            <key name="spinning" qpos="0 0 0.02 1 0 0 0" qvel="0 0 0 0 1 200" />
          </keyframe>
        </mujoco>
        """
    model = mujoco.MjModel.from_xml_string(tippe_top)
    renderer = mujoco.Renderer(model)
    data = mujoco.MjData(model)
    mujoco.mj_forward(model, data)
    renderer.update_scene(data, camera="closeup")
    media.show_image(renderer.render())

    duration = 7    # (seconds)
    framerate = 60  # (Hz)

    # Simulate and display video.
    frames = []
    mujoco.mj_resetDataKeyframe(model, data, 0)  # Reset the state to keyframe 0
    while data.time < duration:
      mujoco.mj_step(model, data)
      if len(frames) < data.time * framerate:
        renderer.update_scene(data, "closeup")
        pixels = renderer.render()
        frames.append(pixels)

    return write_frames(frames, framerate)

def myFirstOwn():
    myfirstown = """
    <mujoco>
      <worldbody>
        <light name="top" pos="0 0 1"/>
        <body name="box_and_sphere" euler="0 0 -30">
          <joint name="swing" type="hinge" axis="1 -1 0" pos="-.2 -.2 -.2"/>
          <geom name="red_box" type="box" size=".2 .2 .2" rgba=".3 .5 .3 1"/>
          <geom name="green_sphere" pos=".2 .2 .2" size=".1" rgba="0 1 0 1"/>
        </body>
      </worldbody>
    </mujoco>
    """
model = mujoco.MjModel.from_xml_string(chaotic_pendulum)
renderer = mujoco.Renderer(model, 480, 640)
data = mujoco.MjData(model)
mujoco.mj_forward(model, data)
renderer.update_scene(data, camera="fixed")
media.show_image(renderer.render())

def renderMain():
    writelist = [case2()]
    print(writelist)

if __name__ =='__main__':
    renderMain()


from fastapi import APIRouter

from src.recommend.service import getMovieByNameService, getMoviesByActorsService

router = APIRouter()

@router.get("/")
async def root():
    return {"message": "Get all recommendations"}

@router.get("/byMovie/")
async def getMovieByName(name: str):
    try:
        result = await getMovieByNameService(name)
        return {"message": name, "result": result}
    except:
        return {"message": "An unhandled exception occurred"}

@router.get("/byActor/")
async def getMoviesByActors(name: str):
    try:
        result = await getMoviesByActorsService(name)
        return {"message": name, "result": result}
    except:
        return {"message": "An unhandled exception occurred"}


import sys
import torch
import torch.nn as nn
import torch.optim as optim

import util

from util import stderr_print
from confusion_matrix import ConfusionMatrix
from timer import Timer, timestamp

class CustomDropout(nn.Module):
    def __init__(self, unk_value=2, p=0.5):
        super(CustomDropout, self).__init__()
        self.unk_value = unk_value
        self.p = p

    def forward(self, X):
        Y = X.bernoulli(p=self.p) * self.unk_value
        Y[Y == 0] = X[Y == 0]
        return Y

class Net(nn.Module):
    def __init__(self, vocab_size, tagset_size, pad_value, unk_value, **kwargs):
        super(Net, self).__init__()
        self.unk_value = unk_value
        self.pad_value = pad_value
        self.vocab_size = vocab_size
        self.tagset_size = tagset_size
        self.embedding_dim = 20
        self.rnn_layer_size = 80
        self.rnn_layer_number = 3
        self.bidirectional = True
        #self.cell_type = "RNN_TANH"
        self.cell_type = "LSTM"
        self.dropout_rate = 0.2
        self.tagset_size = tagset_size

        self.rnn_out_size = self.rnn_layer_size * (self.bidirectional + 1)

        self.__build_model()

    def __build_model(self):
        self.unk_layer = CustomDropout(unk_value=self.unk_value,
                                       p=0.002)
        self.emb_layer = nn.Embedding(num_embeddings=self.vocab_size,
                                      embedding_dim=self.embedding_dim,
                                      padding_idx=self.pad_value)
        self.rnn_layer = nn.RNNBase(mode=self.cell_type,
                                    input_size=self.embedding_dim,
                                    hidden_size=self.rnn_layer_size,
                                    num_layers=self.rnn_layer_number,
                                    bidirectional=self.bidirectional,
                                    dropout=self.dropout_rate,
                                    batch_first=True)
        self.hidden_layer = None
        self.dropout_layer = nn.Dropout(p=self.dropout_rate)
        self.dense_layer = nn.Linear(self.rnn_out_size, self.tagset_size)
        self.activation_layer = nn.LogSoftmax(dim=1)

    def init_hidden(self, batch_size):
        rnn_layer_number = self.rnn_layer_number * (self.bidirectional + 1)
        if self.cell_type == "LSTM":
            hidden = torch.randn(rnn_layer_number, batch_size, self.rnn_layer_size)
            self.hidden_layer = hidden, hidden
        else:
            hidden = torch.randn(rnn_layer_number, batch_size, self.rnn_layer_size)
            self.hidden_layer = hidden

    def forward(self, X, L):
        seq_length = X.shape[1]
        if self.training:
            X = self.unk_layer(X)
        X = self.emb_layer(X)
        X = torch.nn.utils.rnn.pack_padded_sequence(X, L, batch_first=True)
        X, self.hidden_layer = self.rnn_layer(X, self.hidden_layer)
        X, _ = torch.nn.utils.rnn.pad_packed_sequence(X, batch_first=True)
        X = X.contiguous().view(-1, X.shape[2])
        X = self.dropout_layer(X)
        X = self.dense_layer(X)
        X = self.activation_layer(X)
        X = X.view(-1, seq_length, self.tagset_size)
        Yh = X
        return Yh

    def save(self, filename):
        torch.save(self, filename)
        stderr_print(f"Model saved to {filename}")

    def save_embeddings(self, i2char, filename):
        with open(filename, "w") as fout:
            for i, c in i2char.items():
                vector = [c]
                for n in self.emb_layer.weight[i]:
                    vector.append(f"{n:.8f}")
                print("\t".join(vector), file=fout)
        stderr_print(f"Embeddings saved to {filename}")

def predict(model, dataloader, loss_function, conf_matrix, n_batches=None):
    n_batches = n_batches or len(dataloader)
    epoch_loss = 0

    for batch_n, (X, Y, L) in enumerate(dataloader):
        if batch_n == n_batches:
            break
        stderr_print("Evaluating |{}|".format(util.loadbar(batch_n / (n_batches - 1))), end="\r")

        model.zero_grad()
        model.hidden = model.init_hidden(batch_size=len(L))

        Yh = model(X, L)

        Yh_tags = Yh.max(dim=2)[1]
        conf_matrix.add(Yh_tags, Y)

        with torch.no_grad():
            loss = loss_function(Yh.view(-1, Yh.shape[2]), Y.view(-1))
        epoch_loss += loss

    return epoch_loss

def train_epoch(model, dataloader, loss_function, optimizer, conf_matrix):
    n_batches = len(dataloader)
    epoch_loss = 0
    timer = Timer(total_ticks=n_batches)
    timer.start()

    for batch_n, (X, Y, L) in enumerate(dataloader):
        stderr_print("Training |{}| {}".format(util.loadbar(batch_n / (n_batches - 1)), timer.remaining()), end="\r")
        model.zero_grad()
        model.hidden = model.init_hidden(batch_size=len(L))

        Yh = model(X, L)

        Yh_tags = Yh.max(dim=2)[1]
        # conf_matrix.add(Yh_tags, Y)
        # print(Yh.shape, Y.shape)

        loss = loss_function(Yh.view(-1, Yh.shape[2]), Y.view(-1))
        loss.backward()
        optimizer.step()
        epoch_loss += loss

        timer.tick()

    return epoch_loss

def train(model, train_loader, dev_loader, n_epochs, confmat, out_dir, eval_batches=None):
    optimizer = optim.Adam(model.parameters())
    loss_function = nn.CrossEntropyLoss(ignore_index=0)
    eval_batches = min(eval_batches or len(train_loader), len(train_loader), len(dev_loader))
    train_confmat = confmat
    dev_confmat = train_confmat.copy()
    log = [{}]
    best_dev_loss = (None, 0)

    for e in range(1, n_epochs + 1):
        log.append({})
        model = model.train()
        train_loss = train_epoch(model, train_loader,
                                 loss_function=loss_function,
                                 optimizer=optimizer,
                                 conf_matrix=train_confmat)

        model = model.eval()
        train_confmat.reset()
        train_loss = predict(model, dev_loader,
                             loss_function=loss_function,
                             conf_matrix=train_confmat,
                             n_batches=eval_batches)

        log[e]["train_loss"] = train_loss / eval_batches
        log[e]["train_acc"] = train_confmat.accuracy()
        log[e]["train_f1"] = train_confmat.f_score(mean=True)
        print(f"[{timestamp()}] Epoch {e}: T "
              f"loss {log[e]['train_loss']:.6f}, "
              f"accuracy {log[e]['train_acc']:.4f}, "
              f"f1 {log[e]['train_f1']:.4f}")

        dev_confmat.reset()
        dev_loss = predict(model, dev_loader,
                           loss_function=loss_function,
                           conf_matrix=dev_confmat,
                           n_batches=eval_batches)

        log[e]["dev_loss"] = dev_loss / eval_batches
        log[e]["dev_acc"] = dev_confmat.accuracy()
        log[e]["dev_f1"] = dev_confmat.f_score(mean=True)
        print(f"[{timestamp()}] Epoch {e}: E "
              f"loss {log[e]['dev_loss']:.6f}, "
              f"accuracy {log[e]['dev_acc']:.4f}, "
              f"f1 {log[e]['dev_f1']:.4f}")

        if best_dev_loss[0] is None or log[e]["dev_loss"] < best_dev_loss[0]:
            best_dev_loss = log[e]["dev_loss"], e
            model.save(out_dir + "-check.model")

    if log[-1]["dev_loss"] > best_dev_loss[0]:
        print(f"Loading best model (epoch {best_dev_loss[1]})...")
        model = torch.load(out_dir + "-check.model")

    return model

def main():
    print(f"[{timestamp('%Y-%m-%d %H:%M:%S')}] train.py")
    remove_characters = "aeiouy"

    # data_dir = "data"
    data_dir = "/home/m17/hruska/nobackup/cs/deacc"

    train_file = data_dir + "/train-mini.txt"
    #train_file = data_dir + "/train.txt"
    dev_file = data_dir + "/dev.txt"
    test_file = data_dir + "/test.txt"

    #out_dir = "/home/m17/hruska/nobackup/out"
    if len(sys.argv) > 1:
        out_prefix = sys.argv[1]
    else:
        out_prefix = "/home/m17/hruska/nobackup/out/xxx"

    batch_size = 128

    stderr_print("Preparing data...")
    inchar2i, i2inchar, outchar2i, i2outchar = util.make_index_dicts(train_file, remove_characters)
    train_loader, dev_loader, test_loader = util.prepare_dataloaders(train_file, dev_file, test_file,
                                                                     inchar2i, outchar2i, batch_size)

    stderr_print("Setting up model...")
    model = Net(vocab_size=len(inchar2i),
                tagset_size=len(outchar2i),
                pad_value=0,
                unk_value=inchar2i["<UNK>"])
    print("Number of trainable parameters:", sum(p.numel() for p in model.parameters() if p.requires_grad))

    confmat = ConfusionMatrix(len(outchar2i),
                              ignore_index=outchar2i["<PAD>"],
                              class_dict=i2outchar)

    stderr_print("Training...")
    model = train(model, train_loader, dev_loader,
                  n_epochs=20,
                  confmat=confmat,
                  out_dir=out_prefix)

    stderr_print("Saving model...")
    torch.save(model, out_prefix + "-model.model")
    stderr_print("Saving embeddings...")
    model.save_embeddings(i2inchar, out_prefix + "-embs.txt")

if __name__ == "__main__":
    main()


with open("day05input.txt") as file:
    binPositions = [(line[:7].replace("F", "0").replace("B", "1"), line[7:].replace("L", "0").replace("R", "1")) for line in file]
    intPositions = [(int(rBin, 2), int(cBin, 2)) for rBin, cBin in binPositions]
    seatIds = {(rInt * 8) + cInt for rInt, cInt in intPositions}

    print(max(seatIds))

    for id in range(min(seatIds) + 1, max(seatIds) - 1):
        if id not in seatIds:
            print(id)


from tkinter import*
from tkinter import ttk, messagebox
import random
import tkinter.messagebox
from datetime import datetime

class BillingApp:
    def __init__(self, root):
        self.window=root

        self.window.geometry("1260x750+0+0")
        self.window.title("Billing App")
        bgcolor="#d97227"
        title=Label(self.window, text="Billing App", bd=12, relief=GROOVE, fg="white",bg=bgcolor,font=("times new roman",20), pady=2 ).pack(fill=X)

        #..........variables
        options = [
            "Product 1",
            "Product 2",
            "Product 3",
        ]

        # datatype of menu text
        self.name=StringVar()
        self.address=StringVar()
        self.ph=StringVar()
        self.bill_number=StringVar()
        x=random.randint(1000,9999)
        self.bill_number.set(str(x))

        self.select_box1 = StringVar()
        self.select_box2 = StringVar()
        self.select_box3 = StringVar()
        self.year1=StringVar()
        self.amount1 = StringVar()
        self.year2 = StringVar()
        self.amount2 = StringVar()
        self.year3 = StringVar()
        self.amount3 = StringVar()
        # initial menu text
        self.select_box1.set("Select here")
        self.select_box2.set("Select here")
        self.select_box3.set("Select here")
        self.discount = IntVar()
        self.total = IntVar()
        self.ftotal = IntVar()
        F1=LabelFrame(self.window, bd=10, relief=GROOVE,text="Customer Details", font=("times new roman", 15,"bold"),fg="gold",bg=bgcolor)
        F1.place(x=0,y=60,relwidth=1, height =140)

        namelabel=Label(F1, text="Customer Name", fg="white", bg=bgcolor,font=("times new roman", 13, "bold")).grid(row=0,column=0, padx=20, pady=25)
        nametext=Entry(F1, width=20, textvariable=self.name,font=("times new roman",12), bd=7, relief=SUNKEN).grid(row=0,column=1, padx=5, pady=10)
        addresslabel = Label(F1, text="Address", fg="white", bg=bgcolor, font=("times new roman", 13, "bold")).grid(
            row=0, column=2, padx=20, pady=25)
        addresstext = Entry(F1, width=20, textvariable=self.address,font=("times new roman", 12), bd=7, relief=SUNKEN).grid(row=0, column=3, padx=5, pady=10)

        phlabel = Label(F1, text="Phone No.", fg="white", bg=bgcolor, font=("times new roman", 13, "bold")).grid(
            row=0, column=4, padx=20, pady=25)
        phtext = Entry(F1, width=20,textvariable=self.ph, font=("times new roman", 12), bd=7, relief=SUNKEN).grid(row=0, column=5, padx=5, pady=10)

        F2 = LabelFrame(self.window, bd=10, relief=GROOVE, text="Purchase details",
                        font=("times new roman", 15, "bold"), fg="gold", bg=bgcolor)
        F2.place(x=0, y=170, width=500 , height=300)
        drop_down1 = OptionMenu(F2, self.select_box1, *options).grid(row=0, column=0, padx=5,
                                                                    pady=10)
        year_text1 = Entry(F2, width=20, textvariable=self.year1, font=("times new roman", 12), bd=7,
                          relief=SUNKEN)
        year_text1.insert(0, 'Type Year')

        year_text1.grid(row=0, column=1, padx=5,
                       pady=10)
        amount_text1 = Entry(F2, width=20, textvariable=self.amount1, font=("times new roman", 12), bd=7,
                            relief=SUNKEN)
        amount_text1.insert(0, 'Type Amount')
        amount_text1.grid(row=0, column=2, padx=5,
                         pady=10)
        drop_down2 = OptionMenu(F2, self.select_box2, *options).grid(row=1, column=0, padx=5,
                                                                    pady=10)
        year_text2 = Entry(F2, width=20, textvariable=self.year2, font=("times new roman", 12), bd=7,
                          relief=SUNKEN)
        year_text2.insert(0, 'Type Year')

        year_text2.grid(row=1, column=1, padx=5,
                       pady=10)
        amount_text2 = Entry(F2, width=20, textvariable=self.amount2, font=("times new roman", 12), bd=7,
                            relief=SUNKEN)
        amount_text2.insert(0, 'Type Amount')
        amount_text2.grid(row=1, column=2, padx=5,
                         pady=10)

        drop_down3 = OptionMenu(F2, self.select_box3, *options).grid(row=2, column=0, padx=5,
                                                                    pady=10)
        year_text3 = Entry(F2, width=20, textvariable=self.year3, font=("times new roman", 12), bd=7,
                          relief=SUNKEN)
        year_text3.insert(0, 'Type Year')

        year_text3.grid(row=2, column=1, padx=5,
                       pady=10)
        amount_text3 = Entry(F2, width=20, textvariable=self.amount3, font=("times new roman", 12), bd=7,
                            relief=SUNKEN)
        amount_text3.insert(0, 'Type Amount')
        amount_text3.grid(row=2, column=2, padx=5,
                         pady=10)

        #billing Area
        F3=Frame(self.window, bd=10, relief=GROOVE)
        F3.place(x=500, y=180, width=760, height=1300)
        bill_title=Label(F3, text="Bill Area", font=("Times new roman", 15), bd=7, relief=GROOVE).pack(fill=X)
        scrol_y=Scrollbar(F3, orient=VERTICAL)
        self.textarea=Text(F3, yscrollcommand=scrol_y.set)
        scrol_y.pack(side=RIGHT, fill=Y)
        scrol_y.config(command=self.textarea.yview)
        self.textarea.pack(fill=BOTH, expand=1)
        # Button Frame
        F4=LabelFrame(self.window, bd=10, relief=GROOVE, text="Purchase details",
                        font=("times new roman", 15, "bold"), fg="gold", bg=bgcolor)
        F4.place(x=0, y=460, relwidth=1 , height=400)

        total_label = Label(F4, text="Total", fg="white", bg=bgcolor, font=("times new roman", 13, "bold")).grid(
            row=0, column=4, padx=20, pady=25)
        total_text = Entry(F4, width=20, textvariable=self.total,font=("times new roman", 12), bd=7, relief=SUNKEN).grid(row=0, column=5, padx=5,

                                                                                pady=10)
        dis_label = Label(F4, text="Discount", fg="white", bg=bgcolor, font=("times new roman", 13, "bold")).grid(
            row=0, column=6, padx=20, pady=25)
        dis_text = Entry(F4, width=20, textvariable=self.discount, font=("times new roman", 12), bd=7, relief=SUNKEN).grid(
            row=0, column=7, padx=5,
            pady=10)

        ftotal_label = Label(F4, text="Final Total", fg="white", bg=bgcolor, font=("times new roman", 13, "bold")).grid(
            row=1, column=4, padx=20, pady=25)
        ftotal_text = Entry(F4, width=20, textvariable=self.ftotal, font=("times new roman", 12), bd=7, relief=SUNKEN).grid(
            row=1, column=5, padx=5,
            pady=10)

        btn_f = Frame(F4, bd=6, relief=GROOVE)
        btn_f.place(x=600,width=600,height=105)
        total_button=Button(btn_f, command=self.find_Total, text="Total", bg="cadetblue", fg="white", pady=15,width=11, font=("times new roman", 12)).grid(row=0, column=0,padx=5, pady=10)
        ftotal_button = Button(btn_f, command=self.find_Total, text="Final Total", bg="cadetblue", fg="white", pady=15,
                              width=11, font=("times new roman", 12)).grid(row=0, column=1, padx=5, pady=10)
        Gb_button = Button(btn_f, text="Generate Bill",command=self.Generate_bill, bg="cadetblue", fg="white", pady=15, width=11,
                              font=("times new roman", 12)).grid(row=0, column=2, padx=5, pady=10)
        Save_button = Button(btn_f, text="Save data", command=self.save_bill, bg="cadetblue", fg="white", pady=15, width=11,
                              font=("times new roman", 12)).grid(row=0, column=3, padx=5, pady=10)

    def find_Total(self):
          self.total_amount=(int(self.amount1.get())*int(self.year1.get())+
                             int(self.amount2.get())*int(self.year2.get())+
                             int(self.amount3.get())*int(self.year3.get()))

          self.total.set("Rs "+str(self.total_amount))
          if(self.discount.get()!=0):
              self.ftotal.set("Rs " + str(self.total_amount - self.discount.get()))

    def Generate_bill(self):
        self.textarea.delete('1.0',END)
        self.textarea.insert(END, "\tWELCOME TO THE BILLING SYSTEM...\n")
        self.textarea.insert(END, f"\n Bill number:{self.bill_number.get()}")
        self.textarea.insert(END, f"\n Customer Name:{self.name.get()}")
        self.textarea.insert(END, f"\n Customer Address:{self.address.get()}")
        self.textarea.insert(END,"\n....................................\n")

        self.textarea.insert(END, "\n Billing Details...\n")
        self.textarea.insert(END, f"\n Product:{self.select_box1.get()}")
        self.textarea.insert(END, f"\n Year:{self.year1.get()}")
        self.textarea.insert(END, f"\n Amount:{self.amount1.get()}")
        self.textarea.insert(END, "\n....................................\n")
        self.textarea.insert(END, f"\n Product :{self.select_box2.get()}")
        self.textarea.insert(END, f"\n Year:{self.year2.get()}")
        self.textarea.insert(END, f"\n Amount:{self.amount2.get()}")

        self.textarea.insert(END, "\n....................................\n")
        self.textarea.insert(END, f"\n Product :{self.select_box3.get()}")
        self.textarea.insert(END, f"\n Year:{self.year3.get()}")
        self.textarea.insert(END, f"\n Amount:{self.amount3.get()}")
        self.textarea.insert(END, "\n....................................\n")
        self.textarea.insert(END, f"\n Total:Rs {self.total.get()}")
        self.textarea.insert(END, f"\n Discount:Rs {self.discount.get()}")
        self.textarea.insert(END, f"\n Final Total:Rs {self.ftotal.get()}")
        self.textarea.insert(END, "\n....................................\n")
        self.textarea.insert(END, "\n Thank you............\n")
        self.textarea.insert(END, "\n....................................\n")

    def save_bill(self):
        self.data=self.textarea.get('1.0',END)
        file=open("Bills/"+str(self.name.get())+".txt","w")
        file.write(self.data)
        file.close()
        messagebox.showinfo("Successfully saved")

if __name__=='__main__':
    root=Tk()
    application=BillingApp(root )
    root.mainloop()


# QuinticPolynomial.py
#
# Author: Omar Gabr
# This file solves for an approximation to a quintic polynomial

# store constant terms in list
c_list = []
# store constant terms of derivative in different list
dc_list = []

for c in range(6):
    # ask user for coefficients of quintic polynomial and add to c_list
    c_i = int(input(f"Enter x^{c} coefficients: "))
    c_list.append(c_i)
    # calculate new constants after derivative and add to dc_list
    dc_i = c_i * c
    dc_list.append(dc_i)

# ask user for guess answer
x_0 = float(input("Enter guess: "))

# create a function that computes the polynomial
# input parameters are (1) list + (2) x-value
def poly(list, x):
    # the sum of the polynomial and i_th exponent are initialized
    sum = 0
    i = 0
    # for each element: (1) multiply with its corresponding x-term (2) then increment exponent
    for element in list:
        sum += element * (x ** i)
        i += 1
    # return sum of the polynomial
    return sum

# create list of  approximations
x_list = []
# calculate x_i terms
for i in range(60):
    # only when i is first value in range
    if (i == 0):
        # initialize x_i value as x_0 guess term
        x_i = x_0
    try:
        # initialize f(x) and f'(x) using poly function and pass x_i as input
        fx_i = poly(c_list, x_i)
        fdx_i  = poly(dc_list, x_i)
        # compute following x approximation using previous x_value
        x_i = x_i - (fx_i / fdx_i)
        # append each approximation into list
        x_list.append(x_i)
    except ZeroDivisionError:
        print("Division By Zero")
        break
print(f"An approximate solution to the quintic polynomial is: {x_list[-1]:.9f}")


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created 7 Feb 2018

@author: elonbrange
"""

#Linear Discriminative Analysis (LDA, Fisher's discriminant analysis)
# Binary class discriminant

#Importing packages
import numpy as np
import matplotlib.pyplot as plt
from numpy import linalg

#Importing dataset
data0 = np.genfromtxt("0.txt", delimiter = ",")
data1 = np.genfromtxt("1.txt", delimiter = ",")

def disp_img(data, n):
    y = np.empty((28, 28))
    for i in range(1, 27):
        low = 28*(i-1)
        up = 28*i -1
        for j in range(0, 27):
            y[i,j] = data[n, low:up][j]
    y = np.transpose(y)
    plt.matshow(y)
    plt.show
    return y

#Visualization:
#zeroes
#a0 = disp_img(data0, 0)
#a1 = disp_img(data0, 1)

#ones
#b0 = disp_img(data1, 0)
#b1 = disp_img(data1, 1)

#Number of classes & features
nclass = 2
features = 784

#Mean vectors Class0 and Class1
m0 = np.mean(data0, 0)
m1 = np.mean(data1, 0)

mv = []
mv.append(m0)
mv.append(m1)

#Within-class scatter matrix
#Calculating within-scatter for each class separately
#Class0
Sw0 = np.zeros((784, 784))
for i in range(1, len(data0)):
    row = data0[i,:].reshape(784,1)
    mvec = m0.reshape(784, 1)
    Sw0 += (row - mvec).dot((row - mvec).T)

#Class1
Sw1 = np.zeros((784, 784))
for i in range(1, len(data1)):
    row = data1[i,:].reshape(784,1)
    mvec = m1.reshape(784, 1)
    Sw1 += (row - mvec).dot((row - mvec).T)

#Within-scatter matrix
Sw = Sw0 + Sw1

#Alternative way, calculating covariance
cov0 = np.cov(data0,rowvar = False)
cov1 = np.cov(data1, rowvar = False)
S0 = 234*cov0
S1 = 277*cov1

covSw = S0 + S1

#Cross-checking methods
if covSw.all() == Sw.all():
    print("Within-class scatter OK")

#Between-class scatter matrix
#Calculating overall mean for each feature
data = np.concatenate((data0, data1), axis = 0)
mOverall = np.mean(data, 0)

#mOverall = np.mean(mv)
mOverall = mOverall.reshape(784, 1)

#B/w-scatter matrix class0
mv0 = m0.reshape(784, 1)
Sb0 = (mv0 - mOverall).dot((mv0 - mOverall).T)

#B/w-scatter matrix class0
mv1 = m1.reshape(784,1)
Sb1 = (mv1 - mOverall).dot((mv1 - mOverall).T)

#Between-scatter matrix
Sb = 234*Sb0 + 277*Sb1

#Sb = (mv1 - mv0).dot((mv1 - mv0).T)

#Solving eigenvalue problem
#Calculating (Moore-Penrose) pseudo inverse since Sw is singluar ->
SwInv = linalg.pinv(Sw)

#Eig to sove
eigVal, eigVec = linalg.eig(SwInv.dot(Sb))

#Eigenvalues and Eigenvectors tuples/pairs
eigPair = [(np.abs(eigVal[i]), eigVec[:,i]) for i in range(len(eigVal))]

#Sorting Eigenvalues in descending order
eigPair = sorted(eigPair, key=lambda k: k[0], reverse = True)

#Explanation of variance
varExpl = []
eigSum = sum(eigVal)
for i,j in enumerate(eigPair):
    varExpl.append('eigenvalue {0:}: {1:.2%}'.format(i+1, (j[0]/eigSum).real))

#Choosing eigenvectors with largest eigenvalues
W = np.hstack((eigPair[0][1].reshape(784,1)))

#Transforming data samples to new sub-space
lda0 = data0.dot(W)
lda1 = data1.dot(W)

#Decision boundary
bl = 0.5*(np.mean(lda1) - np.mean(lda0))

#Plotting histogram of classes
plt.hist(lda0, color = "blue")
plt.hist(lda1, color = "orange")
plt.title("Histogram of classes")
plt.show()

#Plotting the samples against gaussian noise
noise0 = np.random.normal(0, 1, 234)
noise1 = np.random.normal(0, 1, 277)

plt.scatter(lda0, noise0, marker = "x", color = "blue")
plt.scatter(lda1, noise1, marker = "x", color = "orange")
plt.legend([0,1], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.xlabel('LDA, W transform')
plt.ylabel('Gaussian noise')
plt.show()

#Alternative plot
plt.scatter(lda0, noise0, color = "white")
plt.scatter(lda1, noise1, color = "white")
for x, y in zip(lda0, noise0):
    plt.text(x, y, str(0), color="blue", fontsize=10)

for x, y in zip(lda1, noise1):
    plt.text(x, y, str(1), color="orange", fontsize=10)

#Decision boundary,
bl = 0.5*(np.mean(lda1) - np.mean(lda0))
tbl = np.mean(np.concatenate((lda0, lda1),axis = 0))
#Alternative calculation (orojecting the means)
#bl = 0.5*(m1.dot(W) - m0.dot(W))

x = [tbl, tbl]
y = [min((min(noise0), min(noise1))), max((max(noise0), max(noise1)))]
plt.plot(x, y)

#plt.legend([0,1], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.xlabel('LDA, W transform')
plt.ylabel('Gaussian noise')
plt.show()


# for each leaf make the least precedence operator the root of the subtree

class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def inorder_recu(root):
    if root:
        inorder_recu(root.left)
        print(root.val)
        inorder_recu(root.right)

def postorder_recursive(root):
    if root:
        postorder_recursive(root.left)
        postorder_recursive(root.right)
        print(root.val)

def preorder_recursive(root):
    if root:
        print(root.val)
        preorder_recursive(root.left)
        preorder_recursive(root.right)

priority = {'^': 3, '*': 2, '/': 2, '+': 1, '-': 1}

def infix_to_binary_expression(expression):
    if len(expression) == 1:
        return Node(expression[0])
    elif len(expression) == 0:
        return
    min_priority = 4
    min_priority_index = -1
    for i, token in enumerate(expression):
        if token in priority and priority[token] <= min_priority:
            min_priority = priority[token]
            min_priority_index = i
    root = Node(expression[min_priority_index])
    if min_priority_index > 0:
        root.left = infix_to_binary_expression(expression[:min_priority_index])
    if min_priority_index < len(expression)-1:
        root.right = infix_to_binary_expression(expression[min_priority_index+1:])
    return root

ans = infix_to_binary_expression(['a', '*', 'b', '/', 'c', '+', 'e', '/', 'f', '*', 'g', '+', 'k', '-', 'x', '*', 'y'])
print('Inorder(also infix) of the tree is ')
inorder_recu(ans)
print('Postorder(also postfix) of the binary tree is ')
postorder_recursive(ans)
print('Preorder(also prefix) of the binary tree is ')
preorder_recursive(ans)

def postfix_to_binary_expression(expression):
    stack = []
    for token in expression:
        if token in priority:
            right = stack.pop()
            left = stack.pop()
            head = Node(token)
            head.left = left
            head.right = right
            stack.append(head)
        else:
            stack.append(Node(token))
    assert len(stack) == 1
    return stack[0]

ans = postfix_to_binary_expression(['a', 'b', '*', 'c', '/', 'e', 'f', '/', 'g', '*', '+', 'k', '+', 'x', 'y', '*', '-'])
print('Inorder(also infix) of the tree is ')
inorder_recu(ans)
print('Postorder(also postfix) of the binary tree is ')
postorder_recursive(ans)
print('Preorder(also prefix) of the binary tree is ')
preorder_recursive(ans)


# -*- coding: utf-8 -*-
"""
Created on Mon Mar 21 14:43:04 2022
"""
import numpy as np
import matplotlib.pyplot as plt
import plot_config
from scipy.optimize import curve_fit
import os

datadir = os.path.join(plot_config.data_root_dir, 'cavity_cooling')

SAVE_FIGURE = False

colors = plt.get_cmap('tab10')

# cooling from GKP state
fig, ax = plt.subplots(1, 1, dpi=600, figsize=(5, 2.8))
ax.set_ylabel(r'Prob. of $|0\rangle$ (unnormalized)')
ax.set_xlabel(r'Time (cycles)')
ax.set_xscale('log')
ax.set_ylim(0.25,0.95)

for fname in [os.path.join(datadir, 'dissipative_cooling_1.npz'),
              os.path.join(datadir, 'dissipative_cooling_2.npz')]:
    data = dict(np.load(fname))
    rounds = data.pop('rounds')
    m00 = float(data.pop('m00'))
    m01 = float(data.pop('m01'))

    for i, eps in enumerate(np.sort(list(data))):
        label = eps if '2' in fname else None
        ax.plot(rounds, data[eps], marker='.', linestyle='-',
                label=label, color=colors(i))

rounds = [0,1200]
ax.plot(rounds, np.ones_like(rounds)*m00, linestyle='--', color=colors(0))
ax.plot(rounds, np.ones_like(rounds)*m01, linestyle='--', color='black')

plt.tight_layout()
savename = os.path.join(plot_config.save_root_dir,
                        r'cavity_cooling\gkp_ecdc_cooling.pdf')
if SAVE_FIGURE: fig.savefig(savename)


# Data preprocessing
# - Filter by lab time: 2021-04-12 from 9:14 to 9:55
# - Exclude record with rpm value of 0
# - Label data into normal (label code = 0) and faulty (label code = 1)

import os
import pandas as pd

dir_path = os.path.dirname(os.path.realpath(__file__))
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

# return data with label
def preprocess(path):
    raw = pd.read_json(path, orient='columns')
    raw = raw.drop(['_id', 'updatedAt', '__v'], axis=1)
    raw['createdAt'] = pd.to_datetime(raw['createdAt'], infer_datetime_format=True)
    raw.rename(columns={'createdAt': 'time'}, inplace=True)

    # Filter by DateTime: 2021 - 04 - 12 (both normal and faulty) & rpm != 0
    year2021 = raw[raw['time'].dt.year == 2021]
    year2021 = year2021[year2021['rpm'] != 0]
    normal = year2021[(year2021['time'] > '2021-04-12T09:14:00') & (year2021['time'] < '2021-04-12T09:31:00')]
    faulty = year2021[(year2021['time'] > '2021-04-12T09:31:00') & (year2021['time'] < '2021-04-12T09:55:00')]
    normal.insert(3, 'label', 0)
    faulty.insert(3, 'label', 1)
    df = pd.concat([normal, faulty])

    # Uncomment the code below to drop 'time' column
    # df = df.drop(['time'], axis=1).reset_index(drop=True)

    df.to_csv('cleaned_propeller.csv', index=False)
    return df

if __name__ == '__main__':
    df = preprocess(dir_path + '/propeller.json')
    df.info()
    print(df.head())


automatic_fire_right_ckick = (
    0.1, 0, 0,
   [   ],
   [
    (get_player_agent_no, ":attacker_agent"),
    (set_fixed_point_multiplier, 1),
      (agent_get_wielded_item, ":agent_cur_weapon", ":attacker_agent", 0),
      (gt,":agent_cur_weapon", 0),
      (item_get_type, ":cur_weapon_type", ":agent_cur_weapon"),

      (this_or_next|eq,":cur_weapon_type",itp_type_pistol),
      (this_or_next|eq,":cur_weapon_type",itp_type_crossbow),
      (eq,":cur_weapon_type",itp_type_musket),

      (agent_get_attack_action, ":attack_action", ":attacker_agent"),
      (try_begin),
        (neg|game_key_is_down, gk_attack),
        (game_key_is_down, gk_defend),
        #(eq, ":attack_action", 1),
        #ticker trigger
        (agent_get_slot,":ticker_time",":attacker_agent",slot_agent_shoot_time_ticker),
        (try_begin),
          (le,":ticker_time",0),

          #ticker trigger
          (item_get_speed_rating, ":ticker_time", ":agent_cur_weapon"),
          (val_max,":ticker_time",1),
          (store_div,":ticker_time",200,":ticker_time"),
          (agent_set_slot,":attacker_agent",slot_agent_shoot_time_ticker,":ticker_time"),

          (assign,":cur_weapon_slot",-1),
          (assign,":item_slot_num",4),
          (try_for_range,":cur_item_slot",0,":item_slot_num"),
            (eq,":cur_weapon_slot",-1),
            (agent_get_item_slot, ":item_no", ":attacker_agent", ":cur_item_slot"),
            (eq,":item_no",":agent_cur_weapon"),
            (assign,":cur_weapon_slot",":cur_item_slot"),
            (assign,":item_slot_num", 0),
          (try_end),

          (agent_get_item_cur_ammo, ":cur_ammo", ":attacker_agent",":cur_weapon_slot"),
          (gt,":cur_ammo",0),
          (val_sub,":cur_ammo",1),
          (try_begin),
            (this_or_next|eq,":agent_cur_weapon","itm_power_musket_8barrel"),
            (eq,":agent_cur_weapon","itm_zlmg"),
            (val_add,":cur_ammo",1),
          (try_end),
          (agent_set_ammo,":attacker_agent",":agent_cur_weapon",":cur_ammo"),

          (try_begin),
            (this_or_next|eq,":cur_weapon_type",itp_type_pistol),
            (eq,":cur_weapon_type",itp_type_musket),
            (assign,":cur_ammo_type",itp_type_bullets),
            (assign,":cur_ammo_id","itm_cartridges"),#as default
          (else_try),
            (assign,":cur_ammo_type",itp_type_bolts),
            (assign,":cur_ammo_id","itm_bolts"),#as default
          (try_end),
          #match the right ammmo type
          (assign,":item_slot_num",4),
          (try_for_range,":cur_item_slot",0,":item_slot_num"),
            (agent_get_item_slot, ":item_no", ":attacker_agent", ":cur_item_slot"),
            (gt,":item_no",-1),
            (item_get_type, ":item_type_2", ":item_no"),
            (eq,":item_type_2",":cur_ammo_type"),
            (agent_get_item_cur_ammo, ":cur_ammo", ":attacker_agent", ":cur_item_slot"),
            (gt,":cur_ammo",0),
            (assign,":cur_ammo_id",":item_no"),
            (assign,":item_slot_num",0),#break
          (try_end),

          #reduce ammo
          (assign,":killed",1),
          (try_begin),
            (eq,":agent_cur_weapon","itm_van_helsing_crossbow"),
            (assign,":killed",3),
          (else_try),
            (eq,":agent_cur_weapon","itm_van_helsing_crossbow_auto"),
            (assign,":killed",2),
          (else_try),
            (eq,":agent_cur_weapon","itm_rat_musket_8barrel"),
            (assign,":killed",2),
          (else_try),
            (eq,":agent_cur_weapon","itm_power_musket_8barrel"),
            (assign,":killed",4),
          (else_try),
            (neq,":cur_ammo_id","itm_cartridges_burst"),
            (eq,":agent_cur_weapon","itm_drawf_musket_8barrel2"),
            (assign,":killed",3),
          (else_try),
            (eq,":cur_ammo_id","itm_cartridges_burst"),
            (eq,":agent_cur_weapon","itm_drawf_musket_8barrel2"),
            (assign,":killed",4),
          (else_try),
            (eq,":cur_ammo_id","itm_cartridges_burst"),
            (eq,":agent_cur_weapon","itm_drawf_musket_8barrel1"),
            (assign,":killed",2),
          (else_try),
            (eq,":cur_ammo_id","itm_cartridges_burst"),
            (eq,":agent_cur_weapon","itm_zlmg"),
            (assign,":killed",2),
          (else_try),
            (eq,":cur_ammo_id","itm_cartridges_burst"),
            (eq,":agent_cur_weapon","itm_sissofbattle_A295"),
            (assign,":killed",4),
          (try_end),

          #get original position of weapon
          (agent_get_look_position,pos23,":attacker_agent"),

          (agent_get_bone_position, pos24, ":attacker_agent", 9, 1),
          (position_move_z, pos24, 30, 1),
          (position_copy_rotation,pos24,pos23),

          #(position_move_y, pos24,130),
          #(agent_get_horse,":attacker_agent_horse",":attacker_agent"),
          #(agent_get_animation, ":attacker_animation", ":attacker_agent", 0),
          #(try_begin),
          #    (this_or_next|eq,":attacker_animation","anim_walk_forward_crouch"),
          #    (eq,":attacker_animation","anim_stand_to_crouch"),
          #    (position_move_z,pos24,115,1),
          #(else_try),
          #  (lt,":attacker_agent_horse",0),
          #  (position_move_z,pos24,170,1),
          #(else_try),
          #  (position_move_z,pos24,270,1),
          #(try_end),

          ##get weapon position after calculating accuracy
          (set_fixed_point_multiplier, 1),
          (item_get_missile_speed, ":bullet_speed", ":agent_cur_weapon"),
             (try_begin),
               (le,":bullet_speed",0),
               (assign,":bullet_speed",150),
             (try_end),
          (try_begin),
              (eq,":flame_ammo",0),
             (eq,":cur_weapon_type",itp_type_musket),
             (play_sound_at_position, "snd_release_musket", pos24),
             (copy_position,pos5,pos24),
             (position_move_x,pos5,0),
             (position_move_y,pos5,130),
             (particle_system_burst_no_sync,"psys_musket_smoke",pos5,2),
             (particle_system_burst_no_sync,"psys_musket_ogon",pos5,3),
             (particle_system_burst_no_sync,"psys_musket_svet",pos5,3),

             (position_move_x, pos5, -4),
             (position_move_y, pos5,-120),
             (position_move_z, pos5,3),
             (particle_system_burst_no_sync, "psys_musket_powder_a", pos5, 2),
             (particle_system_burst_no_sync, "psys_pistol_powder_b", pos5, 3),
             (agent_set_animation, ":attacker_agent", "anim_release_musket", 1),
             (try_begin),
               (le,":bullet_speed",0),
               (assign,":bullet_speed",150),
             (try_end),
          (else_try),
              (eq,":flame_ammo",0),
             (eq,":cur_weapon_type",itp_type_pistol),
             (play_sound_at_position, "snd_release_musket", pos24),
             (copy_position,pos5,pos24),

             (position_move_x,pos5,27),
             (position_move_y,pos5,36),
             (particle_system_burst_no_sync,"psys_pistol_smoke",pos5,1),
             (particle_system_burst_no_sync,"psys_pistol_ogon",pos5,4),
             (particle_system_burst_no_sync,"psys_pistol_svet",pos5,4),

             (position_move_x, pos5,-30),
             (position_move_y, pos5,-30),
             (position_move_z, pos5,3),
             (particle_system_burst_no_sync, "psys_musket_powder_a", pos5, 1),
             (particle_system_burst_no_sync, "psys_pistol_powder_b", pos5, 2),
             (agent_set_animation, ":attacker_agent", "anim_release_pistol", 1),
          (else_try),
              (eq,":flame_ammo",0),
             (play_sound_at_position, "snd_release_crossbow", pos24),
             (agent_set_animation, ":attacker_agent", "anim_release_crossbow", 1),
          (try_end),
          (item_get_accuracy, ":accuracy", ":agent_cur_weapon"),
          (try_for_range, ":unused", 0, ":killed"),
            (copy_position,pos25,pos24),
            (val_add,":bullet_speed",-3),
            (val_max,":accuracy",1),
            (store_div,":randomize_value",300,":accuracy"),
            (store_random_in_range,":z",0,":randomize_value"),
            (store_random_in_range,":x",0,":randomize_value"),
            (position_rotate_z,pos25,":z"),
            (position_rotate_x,pos25,":x"),
            (add_missile, ":attacker_agent", pos25, ":bullet_speed", ":agent_cur_weapon", 0, ":cur_ammo_id",0),
          (try_end),
        (else_try),
          (val_sub,":ticker_time",1),
          (agent_set_slot,":attacker_agent",slot_agent_shoot_time_ticker,":ticker_time"),
        (try_end),
      (else_try),
        (agent_get_defend_action, ":defend_action_state", ":attacker_agent"),
        (this_or_next|gt,":defend_action_state",0),
        (gt,":attack_action",1),

        (game_key_is_down, gk_attack),
        (neg|game_key_is_down, gk_defend),

        (item_get_speed_rating, ":ticker_time", ":agent_cur_weapon"),
        (val_max,":ticker_time",1),
        (store_div,":ticker_time",800,":ticker_time"),
        (agent_set_slot,":attacker_agent",slot_agent_shoot_time_ticker,":ticker_time"),
      (try_end),
    (try_end),
   ]
)

复件 (3) 新建文本文档2.py

复件 (3) 新建文本文档2.py


import copy

cache = {}
hit = 0
miss = 0

def score(game, minmax, depth):
    '''
    :param depth:
    :param alpha:
    :param beta:
    :param game: current state of the game
    :param minmax: str can have following values 'min' or 'max'
    :return:
    '''
    global cache
    global hit, miss

    if game in cache:
        hit += 1
        return cache[game]
    else:
        miss += 1

    if game.winner() == "O":
        return -10
    if game.winner() == "X":
        return 10
    if game.winner() == "Tie":
        return 0
    if depth <= 0:
        return 0

    scores = []
    for i in range(1, 4):
        for j in range(1, 4):
            game_copy = copy.deepcopy(game)
            if game_copy.possible_move((i, j)):

                if minmax == 'max':
                    game_copy.make_turn((i, j), "X")
                    s = score(game_copy, "min", depth - 1)
                    scores.append(s)

                else:
                    game_copy.make_turn((i, j), "O")
                    s = score(game_copy, "max", depth - 1)
                    scores.append(s)

    if minmax == 'max':
        answer = max(scores)
    else:
        answer = min(scores)

    cache[game] = answer
    return answer

def next_turn(game):
    scores = {}

    for i in range(1, 4):
        for j in range(1, 4):
            game_copy = copy.deepcopy(game)
            if game_copy.possible_move((i, j)):
                game_copy.make_turn((i, j), "X")
                scores[(i, j)] = score(game_copy, "min", 4)

    return max(scores, key=scores.get)


from django.contrib import admin

from .models import Course, CourseTranslation

class CourseTranslationInline(admin.TabularInline):
    model = CourseTranslation
    fields = ('locale', 'title', 'description')
    ordering = ('locale',)
    min_num = 2
    extra = 0

@admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
    list_display = ('slug', 'order', 'track', 'topic')
    list_filter = ('track', 'topic')
    ordering = ('track__order', 'order')
    fields = ('track', 'topic', 'order', 'slug')
    inlines = [
        CourseTranslationInline,
    ]


import distro, math, numpy
from scipy.optimize import fsolve
from scipy.stats import tukeylambda

def _solver(stats):
    (lo, hi, q1, q3, sig2) = distro.extractStats(stats, [distro.Stat.Min,distro.Stat.Max, Distro.Stat.Q1, Distro.Stat.Q3, distro.Stat.Sig2])
    if abs((q3-q1)/(hi-lo)-0.5)<.05:
        #lamb>=1
        equation = lambda lamb : sig2/hi**2 - lamb**2*tukeylambda.stats(lamb,scale=1,moments='v')
        lamb = utils.solve_monotonic_increasing(equation,0,1.,100.)
        s = hi*lamb
        return (lamb,s)
    else:
        #guess that s=1
        equation = lambda lamb : sig2-tukeylambda.stats(lamb,scale=1,moments='v')
        lamb = utils.solve_monotonic_increasing(equation,0,-0.4999,1)
        return (lamb,1)

distro.register(
    name        = 'Tukey_Lambda', #
    domain      = distro.Domain.Continuous,
    params      = ('lamb','s'),   #added scale param s
    paramSolver = _solver,
    cdf         = lambda x, lamb, s : tukeylambda.cdf(x,lamb, scale = s),
    sample      = lambda lamb, s : tukeylambda.rvs(lamb,scale=s),
    fittingFns  = {
        distro.Stat.Mu: lambda lamb, s : 0,
        distro.Stat.Skew: lambda lamb, s : 0,
        distro.Stat.Kurt : lambda lamb, s : float(tukeylambda.stats(lamb,scale=s,moments='k'))+3
    }
)


#!/usr/bin/python3 -u
# -*- coding: utf-8 -*-
__author__ = "Blurgy";

import os
import numpy as np
import data
import nn_utils as nn
import time
import plot
import click

import warnings
warnings.filterwarnings('ignore', r'.*output shape of zoom.*')
warnings.filterwarnings('error', r'.*divide by zero.*')

@click.command()
@click.option("--epoch", type = int, default = 30,
              help = "Specify number of epoches, 20 by default")
@click.option("--rate", type = float, default = 1e-3,
              help = "Specify value of initial learning rate, 1e-3 by default")
@click.option("--decay", type = click.Choice(["exponential", "constant", "staircase"]),
              default = "staircase",
              help = "Specify decay schedule of learning rate, `staircase` by default")
@click.option("--continue-at", type = click.Path(exists=True), default = None,
              help = "Continue training at specified file, initializes a new model if not specified")
@click.option("--batch-size", type = int, default = 32,
              help = "Specify batch size, 32 by default")
@click.option("--channels", type = (int, int, int, int), default = (32, 32, 64, 64),
              help = "Specify conv layer sizes, <32, 32, 64, 64> by default")
def main(epoch, rate, decay, continue_at, batch_size, channels):
    base_learning_rate = rate;
    decay_schedule = nn.decay_schedule(epoch, decay);
    learning_rate = base_learning_rate * decay_schedule;
    if(continue_at != None and os.path.exists(continue_at)):
        model = data.load_model(continue_at);
    else:
        model = nn.init_model(*channels);

    acc_curve = plot.plot();
    loss_curve = plot.plot();
    global_stime = time.perf_counter();
    for ep in range(epoch):
        lr = learning_rate[ep];
        train = data.preprocess_training_set();
        print("training set(%d instances) loaded and shuffled" % (len(train)));
        X, Y = data.sample_batches_train(train, batch_size);
        del train;
        print("epoch %d/%d, batch size %d, learning rate %g" % (ep+1, epoch, batch_size, lr));

        model['epoch'] += 1;
        yes, cnt, epoch_loss = 0, 0, 0;
        stime = time.perf_counter();
        for i in range(len(X)):
            x, y = X[i], Y[i];
            nn.forward(model, x, is_test_time = False);
            dz, loss = nn.grad(model, y);
            epoch_loss += loss;
            nn.backward(model, dz);

            prediction = np.argmax(model['output'], axis=1);
            score = prediction.reshape(-1,1) == y.reshape(-1,1);
            yes += np.sum(score);
            cnt += len(y);
            acc = yes/cnt*100;
            print(" %d/%d, acc %.2f%%, batch loss %.2f   " % (yes, cnt, acc, loss), end = '\r');
            acc_curve.append(acc);
            nn.adam_update(model, lr);
            # nn.momentum_update(model, lr);
            # nn.sgd_update(model, lr);
        etime = time.perf_counter();
        print();
        print("epoch %d/%d, overall loss %.2f, time elapsed %.2f second(s)" % (ep+1, epoch, epoch_loss, etime-stime));
        data.save_model(model);
        loss_curve.append(epoch_loss);
        acc_curve.save("acc.png");
        loss_curve.save("loss.png");
        print("model saved");
        print();
    global_etime = time.perf_counter();
    print(" time elapsed %.2f second(s)" % (global_etime - global_stime));

if(__name__ == "__main__"):
    main();