text:
#!/usr/bin/env/python3

import tkinter as tk
from tkinter import ttk
from tkinter import*

from ttkthemes import themed_tk as tkt
from tkinter import Canvas
from tkinter.constants import *
from PIL import Image, ImageDraw, ImageTk

import math
from math import *
import cmath

import matplotlib.pyplot as plt

import numpy as np
from numpy.linalg import inv

import subprocess
import os
import sys

g=9.806652 # Gravitaional acceleration
RadToDeg = 180.0/3.14159
DegToRad = 3.14159/180.0
theta=45

#Theme chooser
global P
bg1="purple"
bg2="dimgrey"
bg3="black"
fg3="snow"
fg4="dimgrey"

themel=["arc","black","blue","aquativo","kroc","radiance","keramik","clearlooks","classic","winxpblue","plastik"]
bg1l=["#dcdcdc","#808080","#87ceeb","#8313a6","#ffa500","#110000","#dcdcdc","#faf0e6","#696969","#ffa500","#c0c0c0"]
bg2l=["#c0c0c0","#696969","#191970","#3056b3","#8b4513","#d00001","#dcdcdc","#faf0e6","#dcdcdc","#ffa500","#c0c0c0"]
fg3l=["#696969","#696969","#191970","#0976b3","#8b4513","#d00001","#696969","#a52a2a", "#808080","#a52a2a","#000000"]
Pl=["arc","black","blue","aquativo","kroc","radiance","keramik","clearlooks","plastik","kroc","plastik"]

theme="blue"
_dir_path = os.path.dirname(os.path.realpath(__file__))
p=str(os.path.join(root_dir_path, "Templates"))

Px=p+"/hw"
P=str(os.path.join(root_dir_path, 'hwplastik.png'))

root1=tkt.ThemedTk()
root1.get_themes()
root1.set_theme("aquativo")

basestring = str

def hex2rgb(str_rgb):
    try:
        rgb = str_rgb[1:]

        if len(rgb) == 6:
            r, g, b = rgb[0:2], rgb[2:4], rgb[4:6]
        elif len(rgb) == 3:
            r, g, b = rgb[0] * 2, rgb[1] * 2, rgb[2] * 2
        else:
            raise ValueError()
    except:
        raise ValueError("Invalid value %r provided for rgb color."% str_rgb)

    return tuple(int(v, 16) for v in (r, g, b))

class GradientFrame(Canvas):

    def __init__(self, master, from_color, to_color, width=None, height=None, orient=HORIZONTAL, steps=None, fill=None, **kwargs):
        Canvas.__init__(self, master,**kwargs)
        if steps is None:
            if orient == HORIZONTAL:
                steps = height
            else:
                steps = width

        if isinstance(from_color, basestring):
            from_color = hex2rgb(from_color)

        if isinstance(to_color, basestring):
            to_color = hex2rgb(to_color)

        r,g,b = from_color
        dr = float(to_color[0] - r)/steps
        dg = float(to_color[1] - g)/steps
        db = float(to_color[2] - b)/steps

        if orient == HORIZONTAL:
            if height is None:
                raise ValueError("height can not be None")

            self.configure(height=height, bd=0, highlightthickness=0, relief='ridge')

            if width is not None:
                self.configure(width=width)

            img_height = height
            img_width = self.winfo_screenwidth()

            image = Image.new("RGB", (img_width, img_height), "#FFFFFF")
            draw = ImageDraw.Draw(image)

            for i in range(steps):
                r,g,b = r+dr, g+dg, b+db
                y0 = int(float(img_height * i)/steps)
                y1 = int(float(img_height * (i+1))/steps)

                draw.rectangle((0, y0, img_width, y1), fill=(int(r),int(g),int(b)))
        else:
            if width is None:
                raise ValueError("width can not be None")
            self.configure(width=width)

            if height is not None:
                self.configure(height=height)

            img_height = self.winfo_screenheight()
            img_width = width

            image = Image.new("RGB", (img_width, img_height), "#FFFFFF")
            draw = ImageDraw.Draw(image)

            for i in range(steps):
                r,g,b = r+dr, g+dg, b+db
                x0 = int(float(img_width * i)/steps)
                x1 = int(float(img_width * (i+1))/steps)

                draw.rectangle((x0, 0, x1, img_height), fill=(int(r),int(g),int(b)))

        self._gradient_photoimage = ImageTk.PhotoImage(image)

        self.create_image(0, 0, anchor=NW, image=self._gradient_photoimage)

def g(z):
	root1.set_theme("black")
	global theme
	global bg1
	global bg2
	global bg3
	global fg3
	global fg4
	global P
	theme=themel[z]
	bg1=bg1l[z]
	bg2=bg2l[z]
	bg3="snow"
	fg3="dimgrey"
	fg4=fg3l[z]
	print ("fg4",fg4)
	P=Px+Pl[z]+".png"
	root1.set_theme(theme)
	root1.config(bg=bg3)
	l1.config(fg=fg3,bg=bg3)
	print(theme)

l1=Label(root1,text="""Click on any of the following to choose a Theme. Then, quit the window.
		Please wait a little after clicking submit""")
l1.grid()

b1=ttk.Button(root1,text="       black      ", command=lambda: g(1))
b1.grid()
b1=ttk.Button(root1,text="        arc          ", command=lambda: g(0))
b1.grid()
b1=ttk.Button(text="   aquativo  ", command=lambda: g(3))
b1.grid()
b1=ttk.Button(text="        blue       ", command=lambda: g(2))
b1.grid()
b1=ttk.Button(text="         kroc      ", command=lambda: g(4))
b1.grid()
b1=ttk.Button(text=" clearlooks  ", command=lambda: g(7))
b1.grid()
b1=ttk.Button(text="   radiance   ", command=lambda: g(5))
b1.grid()
b1=ttk.Button(text="    keramik   ", command=lambda: g(6))
b1.grid()
b1=ttk.Button(text="     classic      ", command=lambda: g(8))
b1.grid()
b1=ttk.Button(text="  winxpblue ", command=lambda: g(9))
b1.grid()
b1=ttk.Button(text="      plastik     ", command=lambda: g(10))
b1.grid()
bp=Button(root1, text="Submit",command=lambda: root1.destroy())
bp.grid()

print(theme)

root1.mainloop()

global constant1
constant1=0

class Main(tkt.ThemedTk,tk.Tk):
    def __init__(self,*args,**kwargs):
        tk.Tk.__init__(self,*args,**kwargs)
        tkt.ThemedTk.__init__(self)   ##
        self.get_themes()             ##
        self.set_theme(theme)      ##
        photo=PhotoImage(file=P)

        self.f=Frame(width=500,height=30, bd=0, highlightthickness=0, relief='ridge')
        self.f.place(height=50, width=0, x=0, y=0)
        self.f.pack(side="bottom",fill="both",expand=True)
        self.f.grid_rowconfigure(1)
        self.f.grid_columnconfigure(1)
        self.f.config(bg=bg1)

        self.f1=Frame(width=500,height=30, bd=0, highlightthickness=0, relief='ridge')
        self.f1.place(height=50, width=0, x=0, y=0)
        self.f1.pack(side="bottom",fill="both",expand=True)
        self.f1.grid_rowconfigure(1)
        self.f1.grid_columnconfigure(1)
        self.f1.config(bg=bg2)

        self.f2=Frame(width=500,height=30, bd=0, highlightthickness=0, relief='ridge')
        self.f2.place(height=50, width=0, x=0, y=0)
        self.f2.pack(side="bottom",fill="both",expand=True)

        self.f2.grid_rowconfigure(1)
        self.f2.grid_columnconfigure(1)
        self.f2.config(bg=bg2)

        self.x=GradientFrame(self.f, from_color=bg2, to_color=bg1, height=35,fill="both")
        self.x.pack(fill="both")

        self.y=GradientFrame(self.f2, from_color="#FFFFFF", to_color=bg2, height=35,fill="both")
        self.y.pack(fill="both")

        # y=GradientFrame(F1, from_color="#FCFCFC", to_color="#000000", height=30).grid()
        q=ttk.Button(self.f1,text="Quit",command=lambda:sys.exit())
        q.pack()

        self.menu=Menu(self,background=fg4,foreground=bg3)
        self.config(menu=self.menu)
        self.submenu=Menu(self.menu,foreground=bg3,background=fg4,activebackground="snow",activeforeground=fg3)

        def g(z,f,f1,f2):
	        f.pack_forget()
	        f1.pack_forget()
	        f2.pack_forget()
	        global theme
	        global bg1
	        global bg2
	        global bg3
	        global fg3
	        global P
	        theme=themel[z]
	        bg1=bg1l[z]
	        bg2=bg2l[z]
	        fg4=fg3l[z]
	        bg3="snow"
	        fg3="dimgrey"
	        P=Px+Pl[z]+".png"

	        f=Frame(width=500,height=30, bd=0, highlightthickness=0, relief='ridge')
	        f.place(height=50, width=0, x=0, y=0)
	        f.pack(side="bottom",fill="both",expand=True)
	        f.grid_rowconfigure(1)
	        f.grid_columnconfigure(1)
	        f.config(bg=bg1)

	        f1=Frame(width=500,height=30, bd=0, highlightthickness=0, relief='ridge')
	        f1.place(height=50, width=0, x=0, y=0)
	        f1.pack(side="bottom",fill="both",expand=True)
	        f1.grid_rowconfigure(1)
	        f1.grid_columnconfigure(1)
	        f1.config(bg=bg2)
	        f2=Frame(width=500,height=30, bd=0, highlightthickness=0, relief='ridge')
	        f2.place(height=50, width=0, x=0, y=0)
	        f2.pack(side="bottom",fill="both",expand=True)
	        f2.grid_rowconfigure(1)
	        f2.grid_columnconfigure(1)
	        f2.config(bg=bg2)

	        q=ttk.Button(f1,text="Quit",command=lambda:sys.exit())
	        q.pack()

	        print(theme)
	        self.set_theme(theme)
	        f.config(bg=bg1)
	        f1.config(bg=bg2)
	        self.menu.config(background=fg4,foreground="white")
	        global constant1
	        constant1=1
	        print (constant1)
	        self.submenu.config(foreground=bg3,background=fg4,activebackground="snow",activeforeground=fg3)
	        self.submenu2.config(foreground=bg3,background=fg4,activebackground="snow",activeforeground=fg3)
	        print("pack")

	        self.x=GradientFrame(f, from_color=bg2, to_color=bg1, height=35,fill="both").pack(fill="both")
	        self.y=GradientFrame(f2, from_color="#FFFfff", to_color=bg2, height=35,fill="both").pack(fill="both")
	        self.f=f
	        self.f1=f1
	        self.f2=f2

        #Menu
        self.menu=Menu(self,background=fg4,foreground=bg3)
        self.config(menu=self.menu)

            ##
        self.submenu=Menu(self.menu,foreground=bg3,background=fg4,activebackground="snow",activeforeground=fg3)
        self.menu.add_cascade(label="file",menu=self.submenu)

        a=self.submenu.add_command(label="developer info",command=lambda:self.show_frame(P01))
        b=self.submenu.add_command(label="contact us",command=lambda:self.show_frame(P02))

            ##
        self.submenu2=Menu(self.menu,foreground=bg3,background=fg4,activebackground="snow",activeforeground=fg3)
        self.menu.add_cascade(label="Choose Theme",menu=self.submenu2)

        b1=self.submenu2.add_command(label="     black     ", command=lambda: g(1,self.f,self.f1,self.f2))
        b1=self.submenu2.add_command(label="       arc     ", command=lambda: g(0,self.f,self.f1,self.f2))
        b1=self.submenu2.add_command(label="   aquativo  ", command=lambda: g(3,self.f,self.f1,self.f2))
        b1=self.submenu2.add_command(label="      blue     ", command=lambda: g(2,self.f,self.f1,self.f2))
        b1=self.submenu2.add_command(label="      kroc     ", command=lambda: g(4,self.f,self.f1,self.f2))
        b1=self.submenu2.add_command(label=" clearlooks  ", command=lambda: g(7,self.f,self.f1,self.f2))
        b1=self.submenu2.add_command(label="   radiance ", command=lambda: g(5,self.f,self.f1,self.f2))
        b1=self.submenu2.add_command(label="   keramik  ", command=lambda: g(6,self.f,self.f1,self.f2))
        b1=self.submenu2.add_command(label="     classic    ", command=lambda: g(8,self.f,self.f1,self.f2))
        b1=self.submenu2.add_command(label=" winxpblue ", command=lambda: g(9,self.f,self.f1,self.f2))
        b1=self.submenu2.add_command(label="    plastik    ", command=lambda: g(10,self.f,self.f1,self.f2))

        F1=tk.Frame(self)
        F1=tk.Frame(self,width=400,height=450)
        F1.place(height=7000, width=4000, x=100, y=100)
        F1.config()
        F1.pack(fill="both",expand=True)

        F1.grid_rowconfigure(0,weight=1)
        F1.grid_columnconfigure(0,weight=1)
        F1.config()

        self.frames={}

        for F in (start1,start,P1,P2):
            frame=F(F1,self)
            self.frames[F]=frame
            frame.config(bg=bg3)
            frame.grid(row=0,column=0,sticky="nsew")

        for F in (start1,start,P1,P3):
            frame=F(F1,self)
            self.frames[F]=frame
            frame.config(bg=bg3)
            frame.grid(row=0,column=0,sticky="nsew")

        for F in (start1,start,P1,P4):
            frame=F(F1,self)
            self.frames[F]=frame
            frame.config(bg=bg3)
            frame.grid(row=0,column=0,sticky="nsew")

        for F in (start1,start,P1,P5,P6):
            frame=F(F1,self)
            self.frames[F]=frame
            frame.config(bg=bg3)
            frame.grid(row=0,column=0,sticky="nsew")

        for F in (start1,start,P1,P5,P7):
            frame=F(F1,self)
            self.frames[F]=frame
            frame.config(bg=bg3)
            frame.grid(row=0,column=0,sticky="nsew")

        for F in (start1,start,P1,P5,P8):
            frame=F(F1,self)
            self.frames[F]=frame
            frame.config(bg=bg3)
            frame.grid(row=0,column=0,sticky="nsew")

        for F in (start1,start,P1,P5,P9):
            frame=F(F1,self)
            self.frames[F]=frame
            frame.config(bg=bg3)
            frame.grid(row=0,column=0,sticky="nsew")

        for F in (start1,start,P1,P11,P13):
            frame=F(F1,self)
            self.frames[F]=frame
            frame.config(bg=bg3)
            frame.grid(row=0,column=0,sticky="nsew")

        for F in (start1,start,P1,P11,P12):
            frame=F(F1,self)
            self.frames[F]=frame
            frame.config(bg=bg3)
            frame.grid(row=0,column=0,sticky="nsew")

        for F in (start1,start,P1,P14,P16):
            frame=F(F1,self)
            self.frames[F]=frame
            frame.config(bg=bg3)
            frame.grid(row=0,column=0,sticky="nsew")

        for F in (start1,start,P1,P14,P15):
            frame=F(F1,self)
            self.frames[F]=frame
            frame.config(bg=bg3)
            frame.grid(row=0,column=0,sticky="nsew")

        for F in (start1,start,P17,P18,P19):
            frame=F(F1,self)
            self.frames[F]=frame
            frame.config(bg=bg3)
            frame.grid(row=0,column=0,sticky="nsew")

        for F in (start1,start,P17,P18,P20):
            frame=F(F1,self)
            self.frames[F]=frame
            frame.config(bg=bg3)
            frame.grid(row=0,column=0,sticky="nsew")

        for F in (P01,P02,start1,start):
            frame=F(F1,self)
            self.frames[F]=frame
            frame.config(bg=bg3)
            frame.grid(row=0,column=0,sticky="nsew")

        self.show_frame(start1)

    def enter_show_frame(self,cont,event=None):
        frame=self.frames[cont]
        frame.tkraise()

    def show_frame(self,cont):

        frame=self.frames[cont]
        frame.config(bg=bg3)
        frame.tkraise()

print(constant1)

class P01(tk.Frame):                     # Home Page

    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        x="""Developer Information"""
        label = Label(self,text=x,font="cmmi10 50",fg=fg3,bg=bg3)
        label.pack()

        y="""Developer: Eshita Shukla
Date of creation: September 24, 2017
Last modified: March 24, 2018

"""
        label = Label(self,text=y,font="cmmi 20",fg=fg3,bg=bg3)
        label.pack()

        b=ttk.Button(self,text="Let's begin!!!",command=lambda:controller.show_frame(P1))
        b.pack()

class P02(tk.Frame):                     # Home Page

    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        x="""Contact Us"""
        label = Label(self,text=x,font="cmmi10 50",fg=fg3,bg=bg3)
        label.pack()

        y="""email: abcd@gmail.com
contact: @#$%^&*!^$

"""
        label = Label(self,text=y,font="cmmi 20",fg=fg3,bg=bg3)
        label.pack()

        b=ttk.Button(self,text="Let's begin!!!",command=lambda:controller.show_frame(P1))
        b.pack()

#Home Page

class start1(tk.Frame):                     # Home Page

    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        photo=PhotoImage(file=P)
        label = Label(self,image =photo)
        label.image = photo # keep a reference!
        label.grid(row=0,column=0,columnspan=11,rowspan=11)

        print(constant1, " jj")

        b=ttk.Button(self,text="Start",command=lambda:controller.show_frame(start))
        b.grid(row=8,column=5)

class start(tk.Frame):                     # Home Page

    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        x="""Mathematics"""
        label = Label(self,text=x,font="cmmi10 50",fg=fg3,bg=bg3)
        label.pack()

        y="""Mathematics is a powerful calculation tool

It is more than just a claculator.

Plot graphs and trajectories.
Perform complex calculations.
perform matrix operations.
Calculate the sum of a sequence or its nth term.
Solve equations.

"""
        label = Label(self,text=y,font="cmmi 20",fg=fg3,bg=bg3)
        label.pack()

        b=ttk.Button(self,text="Let's begin!!!",command=lambda:controller.show_frame(P1))
        b.pack()

class P1(tk.Frame):                     # Home Page

    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        label=tk.Label(self,text="How can i help you?",font="forte 25",fg=fg3,bg=bg3)
        label.pack(pady=10,padx=100)

        l0=tk.Label(self,text="",font="forte 25",fg=fg3,bg=bg3)
        l0.pack()

        s = ttk.Style()
        s.configure('my.TButton', font=('Helvetica', 12))

        trajectory=ttk.Button(self,text="Find Trajectory",command=lambda:controller.show_frame(P3))
        trajectory.pack()

        calculator=ttk.Button(self,text="     Calculator     ",command=lambda:controller.show_frame(P2))
        calculator.pack()

        plotting=ttk.Button(self,text="     Plot graph     ",command=lambda:controller.show_frame(P4))
        plotting.pack()

        sequence=ttk.Button(self,text="     Sequence      ",command=lambda:controller.show_frame(P5))
        sequence.pack()

        matrix=ttk.Button(self,text="         Matrix        ",command=lambda:controller.show_frame(P11))
        matrix.pack()

        Rect_Pol =ttk.Button(self,text="      Complex       ",command=lambda:controller.show_frame(P16))
        Rect_Pol.pack()

        Solve_Eqn=ttk.Button(self,text="Solve Equation",command=lambda:controller.show_frame(P17))
        Solve_Eqn.pack()

        s=ttk.Button(self,text="       read info      ",command=lambda:controller.show_frame(start1))
        s.pack()

#Trajectory

class P3(tk.Frame,Main):                              #stationary

    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        L=Label(self,text="Trajectory",font="forte 25",fg=fg3,bg=bg3)
        L.grid(row=0,column=1, columnspan=3)

        velocity=StringVar()
        distance=StringVar()
        l=Label(self,text="                        ",font="forte",bg=bg3)
        l.grid(row=2,column=0)

        L2=Label(self,text="Weapon's Muzzle Velocity",font="forte",fg=fg3,bg=bg3)
        L2.grid(row=2,column=1)

        L3=Label(self,text="Distance",font="forte",fg=fg3,bg=bg3)
        L3.grid(row=3,column=1)

        v_weapon= Entry(self,bd=10,textvariable=velocity)
        v_weapon.grid(row=2,column=2)

        distance_weapon= Entry(self,bd=10,textvariable=distance)
        distance_weapon.grid(row=3,column=2)

        def calculation():
            v_text=velocity.get()
            d_text=distance.get()
            try:
                vtext=int(v_text)
                dtext=int(d_text)

                velocity_stat(vtext,dtext)
            except:
                pass

        def velocity_stat(v,d):

            RadToDeg = 180.0/3.14159
            DegToRad = 3.14159/180.0
            theta=45
            R=(v**2)/g

            if R<d:
                l1=tk.Label(self,text="Max range of the weapon is less that the given distance.",font="forte",fg="white",bg=bg3)
                l2=tk.Label(self,text="Change the input or go to home page",font="forte",fg=fg3,bg=bg3)

                l1.grid(columnspan=3)
                l2.grid(columnspan=3)

            else:
                x11=(g*d)/(v**2)
                theta = (math.asin(x11)/2)
                l3=Label(self,text="angle [in degrees]",font="forte",fg=fg3,bg=bg3)
                l4=Label(self,text=str(theta*RadToDeg),font="forte",fg=fg3,bg=bg3)
                #angle=str(CalTheta(thi, u, v, d, step).pack()
                #l5=Label(self,text=str(theta*RadToDeg),font="forte",fg="white",bg="black")
                l3.grid(column=0,columnspan=2)
                l4.grid(column=0,columnspan=2)
                #l5.grid()

        def CalTheta(thi, u, v, d, step):                  #f2
            ffi = f(thi, u, v, d)
            if(ffi ==0):
                return thi*RadToDeg
            if(ffi>0):
                th=thi
                while(th<=45*DegToRad):
                    ff = f(th, u, v, d)
                    if(ff <0) :
                        return th*RadToDeg
                    th=th-step
            if(ffi<0):
                th=thi
                while(th<=45*DegToRad):
                    ff = f(th, u, v, d)
                    if(ff >0) :
                        return th*RadToDeg
                    th=th-step
            return thi*RadToDeg

        submit3=ttk.Button(self,text="submit",command=calculation)
        submit3.grid(column=1)

        home=ttk.Button(self,text="home",command=lambda:controller.show_frame(P1))
        home.grid(column=1)

#Calculator

class P2(tk.Frame):                              #calculator#

    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        Expression=StringVar()

        L=Label(self,text="Calculator",font="forte 25",fg=fg3,bg=bg3)
        L.grid(row=0, column=1, columnspan=5)

        L2=Label(self,text="""To use complex no.s represent the imaginary term i with a 'j'""",font="forte",fg=fg3,bg=bg3)
        L2.grid(row=1,column=1,columnspan=10)
        L3=Label(self,text="""For trignometric calculations, use sin(),cos(),tan()
 constants: pi,e """,font="forte",fg=fg3,bg=bg3)
        L3.grid(row=2, column=1, columnspan=5)

        l2=Label(self, text="",bg=bg3)
        l2.grid()

        Exp=Entry(self,bd=10,textvariable=Expression,font="Ubuntu 15")
        Exp.grid(row=4,column=3)

        global A
        A=0
        self.xyz=8

        def Evaluating(A):
            P=3.14159
            e=2.71828
            print(A)
            def sin(a):
                return np.sin(radians(a))
            def cos(a):
                return np.cos(radians(a))
            def tan(a):
                return np.sin(radians(a))/np.cos(radians(a))
            Val=Expression.get()
            value=eval(Val)
            A=value
            Exp.delete(0,END)
            Exp.insert(END,str(value))
            l1=Label(self,text="value of the given expression is:",font="forte",fg=fg3,bg=bg3)
            l2=Label(self,text="               "+str(value)+"             ",font="forte",fg=fg3,bg=bg3)
            if self.xyz<=14:
                l1.grid(row=self.xyz)
                l2.grid(row=self.xyz+1)
                self.xyz=self.xyz+2
            else:
                l1.grid(row=self.xyz)
                l2.grid(row=self.xyz+1)
                self.xyz=self.xyz%14+6

        l1=Label(self,text="Enter the expression directly: ",font="forte",fg=fg3,bg=bg3)
        l1.grid(row=1,column=0)
        l2=Label(self, text="",bg=bg3)
        l2.grid()

        submit3=ttk.Button(self,text="submit",command=lambda:Evaluating(A))
        submit3.grid()

        home=ttk.Button(self,text="  home ",command=lambda:controller.show_frame(P1))
        home.grid()

#Plot Graph

class P4(tk.Frame):                              #plotting graph

    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        xlist=[]
        ylist=[]

        Expression=StringVar()
        x_1=IntVar()
        x_2=StringVar()
        st=StringVar()
        co=StringVar()

        l0=Label(self,text="Plot a Graph",font="forte 25",fg=fg3,bg=bg3)
        l0.grid()

        l1=Label(self,text="Enter the expression (in terms of x only):",font="forte",fg=fg3,bg=bg3)
        l1.grid(row=1,column=0)

        Exp= Entry(self,bd=10,textvariable=Expression)
        Exp.grid(row=1,column=1)

        l2=Label(self,text="Enter the starting value:",font="forte",fg=fg3,bg=bg3)
        l2.grid(row=3,column=0)

        first=Entry(self,bd=10,textvariable=x_1)
        first.grid(row=3,column=1)

        l3=Label(self,text="Enter the ending value:",font="forte",fg=fg3,bg=bg3)
        l3.grid(row=4,column=0)

        second=Entry(self,bd=10,textvariable=x_2)
        second.grid(row=4,column=1)

        l0=Label(self,text="",font="forte",fg=fg3,bg=bg3)
        l0.grid(row=5,column=0)

        l3=Label(self,text="color(r/g/s):",font="forte",fg=fg3,bg=bg3)
        l3.grid(row=6,column=0)

        colo=Entry(self,bd=10,textvariable=co)
        colo.grid(row=6,column=1)

        l0=Label(self,text="",font="forte",fg=fg3,bg=bg3)
        l0.grid(row=7,column=0)

        l3=Label(self,text='''Graph Type:
("^"=Triangular)
("s"=square)
("o"=circle)
("--"=dottted)  ''',font="forte",fg=fg3,bg=bg3)
        l3.grid(row=8,column=0)

        sty=Entry(self,bd=10,textvariable=st)
        sty.grid(row=8,column=1)

        def making_lists():
            x1i=x_1.get()
            x2i=x_2.get()

            x1=int(x1i)
            x2=int(x2i)
            e=2.303

            d=(x1-x2)/20
            try:
                for i in range(x1*20,x2*20,1):
                    x=i
                    Val=Expression.get()
                    Val2=""
                    for i in range(len(Val)):
                        if Val[i]=="x":
                            Val2=Val2+"(x/20)"
                        else:
                            Val2=Val2+Val[i]
                    value=eval(Val2)
                    y=value
                    xlist.append(x/20)
                    ylist.append(y)

                return xlist
                return ylist
                return Val
            except:
                l3=Label(self,text="wrong input",font="forte",fg=fg3,bg=bg3)
                l3.grid(row=7,column=0)

        def plotting1():
            making_lists()
            c=colo.get()
            s=sty.get()
            M=c+s
            if len(xlist)!=0:
                plt.style.use("ggplot")
                plt.plot(xlist, ylist,M)
                plt.show()

        def plotting2():
            making_lists()
            c=colo.get()
            s=sty.get()
            M=c+s
            if len(xlist)!=0:
                plt.style.use('seaborn-deep')
                plt.plot(xlist, ylist,M)
                plt.show()

        l0=Label(self,text="",font="forte",fg=fg3,bg=bg3)
        l0.grid(row=7,column=0)

        submit1=ttk.Button(self,text="Plot: seaborn-deep",command=plotting2)
        submit1.grid()

        #submit2=ttk.Button(self,text="plot without marker",command=plotting("dark_background"))
        #submit2.grid()

        #submit3=ttk.Button(self,text="plot without marker",command=plotting("seaborn-notebook"))
        #submit3.grid()

        submit4=ttk.Button(self,text="       Plot: ggplot       ",command=plotting1)
        submit4.grid()

        home=ttk.Button(self,text="home",command=lambda:controller.show_frame(P1))
        home.grid()

#Sequence

class P5(tk.Frame):

    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        rr=Label(self,text="Calculate the Sum or nth Term",font="forte 25",fg=fg3,bg=bg3)
        rr.pack()

        l=Label(self,text="What type of sequence is it?",font="forte 20",fg=fg3,bg=bg3)
        l.pack()

        lx=Label(self,text="",font="forte 25",fg=fg3,bg=bg3)
        lx.pack()

        AP=ttk.Button(self,text="       Arithmetic Progression       ",command=lambda:controller.show_frame(P6))
        AP.pack()

        GP=ttk.Button(self,text="        Geometric Progression       ",command=lambda:controller.show_frame(P7))
        GP.pack()

        IGP=ttk.Button(self,text="Infinite Geometric Progression",command=lambda:controller.show_frame(P9))
        IGP.pack()

        oth=ttk.Button(self,text="                  other (custom)                 ",command=lambda:controller.show_frame(P8))
        oth.pack()

        lx=Label(self,text="",font="forte 25",fg=fg3,bg=bg3)
        lx.pack()

        home=ttk.Button(self,text="Home",command=lambda:controller.show_frame(P1))
        home.pack()

class P6(tk.Frame):                              #Arithmetic Progression

    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        a_1=StringVar()
        n_1=StringVar()
        d_1=StringVar()

        l0=Label(self,text="Arithmetic Progression",font="forte 25",fg=fg3,bg=bg3)
        l0.grid(columnspan=2)

        l1=Label(self,text="first term",font="forte",fg=fg3,bg=bg3)
        l1.grid(row=1,column=0)

        a1=Entry(self,bd=10,textvariable=a_1)
        a1.grid(row=1,column=1)

        l2=Label(self,text="no. of terms",font="forte",fg=fg3,bg=bg3)
        l2.grid(row=2,column=0)

        n1=Entry(self,bd=10,textvariable=n_1)
        n1.grid(row=2,column=1)

        l3=Label(self,text="common difference",font="forte",fg=fg3,bg=bg3)
        l3.grid(row=3,column=0)

        d1=Entry(self,bd=10,textvariable=d_1)
        d1.grid(row=3,column=1)

        def calculation():
            ai=a1.get()
            ni=n1.get()
            di=d1.get()

            a=int(ai)
            n=int(ni)
            d=int(di)

            Sum=0
            L=[]
            for i in range(1,n+1):
                term=a+(i-1)*d
                L.append(term)
                Sum=Sum+term

            l4=Label(self,text="The series is:\n"+str(L),font="forte",fg=fg3,bg=bg3)
            l4.grid()
            l5=Label(self,text="The sum is:\n"+str(Sum),font="forte",fg=fg3,bg=bg3)
            l5.grid()

            return Sum

        submit4=ttk.Button(self,text="submit",command=calculation)
        submit4.grid(row=7,column=1)

        home=ttk.Button(self,text="home",command=lambda:controller.show_frame(P1))
        home.grid(row=8,column=1)

class P7(tk.Frame):                #geometric progression
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        a_1=StringVar()
        n_1=StringVar()
        r_1=StringVar()

        l0=Label(self,text="Geometric Progression",font="forte 25",fg=fg3,bg=bg3)
        l0.grid(columnspan=2)

        l1=Label(self,text="first term",font="forte",fg=fg3,bg=bg3)
        l1.grid(row=1,column=0)

        a1=Entry(self,bd=10,textvariable=a_1)
        a1.grid(row=1,column=1)

        l2=Label(self,text="no. of terms",font="forte",fg=fg3,bg=bg3)
        l2.grid(row=2,column=0)

        n1=Entry(self,bd=10,textvariable=n_1)
        n1.grid(row=2,column=1)

        l3=Label(self,text="common difference",font="forte",fg=fg3,bg=bg3)
        l3.grid(row=3,column=0)

        r1=Entry(self,bd=10,textvariable=r_1)
        r1.grid(row=3,column=1)

        def calculation():
            ai=a1.get()
            ni=n1.get()
            ri=r1.get()

            a=int(ai)
            n=int(ni)
            r=int(ri)

            Sum=0
            L=[]
            for i in range(0,n):
                term=a*(r**i)
                L.append(term)
                Sum=Sum+term

            l4=Label(self,text="The series is:\n"+str(L),font="forte",fg=fg3,bg=bg3)
            l4.grid(row=6,column=1)
            l5=Label(self,text="The sum is:\n"+str(Sum),font="forte",fg=fg3,bg=bg3)
            l5.grid(row=7,column=1)

            return Sum

        submit4=ttk.Button(self,text="submit",command=calculation)
        submit4.grid(column=1)

        home=ttk.Button(self,text="home",command=lambda:controller.show_frame(P1))
        home.grid(column=1)

class P8(tk.Frame):                       #other
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        n_1=StringVar()
        N_1=StringVar()

        l0=Label(self,text="Custom",font="forte 25",fg=fg3,bg=bg3)
        l0.grid()

        l2=Label(self,text="no. of terms",font="forte",fg=fg3,bg=bg3)
        l2.grid(row=2,column=0)

        n1=Entry(self,bd=10,textvariable=n_1)
        n1.grid(row=2,column=1)

        l3=Label(self,text="enter nth terms of the series(in terms of n)",font="forte",fg=fg3,bg=bg3)
        l3.grid(row=3,column=0)

        N1=Entry(self,bd=10,textvariable=N_1)
        N1.grid(row=3,column=1)

        def calculation():

            ni=n1.get()
            Ni=N1.get()

            nl=int(ni)

            Sum=0
            L=[]

            for i in range (1,nl+1):
                n=i
                term=eval(Ni)

                L.append(term)
                Sum=Sum+term

            l4=Label(self,text="The series is:\n"+str(L),font="forte",fg=fg3,bg=bg3)
            l4.grid(row=6,column=1)
            l5=Label(self,text="The sum is:\n"+str(Sum),font="forte",fg=fg3,bg=bg3)
            l5.grid(row=7,column=1)

            return Sum

        submit4=ttk.Button(self,text="Submit",command=calculation)
        submit4.grid(column=1)

        home=ttk.Button(self,text="Home",command=lambda:controller.show_frame(P1))
        home.grid(column=1)

class P9(tk.Frame):                # infinite geometric progression
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        a_1=StringVar()
        r_1=StringVar()

        l1=Label(self,text="first term",font="forte",fg=fg3,bg=bg3)
        l1.grid(row=1,column=0)

        a1=Entry(self,bd=10,textvariable=a_1)
        a1.grid(row=1,column=1)

        l3=Label(self,text="common ratio",font="forte",fg=fg3,bg=bg3)
        l3.grid(row=3,column=0)

        r1=Entry(self,bd=10,textvariable=r_1)
        r1.grid(row=3,column=1)

        def calculation():
            ai=a1.get()
            ri=r1.get()

            a=int(ai)
            r=float(ri)

            if r<1 and r>(-1):
                Sum=a/(1-r)
                l5=Label(self,text="The sum is:\n"+str(Sum),font="forte",fg=fg3,bg=bg3)
                l5.grid(row=7,column=1)
                return Sum

            else:
                l3=Label(self,text='''common ratio is more than infinity.
Thus,    Sum= INFINITY''',font="forte",fg=fg3,bg=bg3)
                l3.grid(row=4,column=0)
            home.__del__()

        submit4=ttk.Button(self,text="submit",command=calculation)
        submit4.grid(column=1)

        home=ttk.Button(self,text="home",command=lambda:controller.show_frame(P1))
        home.grid(column=1)

#Matrix

class P11(tk.Frame):
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        l1=Label(self,text="Matrix",font="forte 25",fg=fg3,bg=bg3)
        l1.pack()

        l0=Label(self,text="",font="forte 25",fg=fg3,bg=bg3)
        l0.pack()

        Multiply=ttk.Button(self,text="Multiply",command=lambda:controller.show_frame(P12))
        Multiply.pack()

        Inverse=ttk.Button(self,text="Inverse",command=lambda:controller.show_frame(P13))
        Inverse.pack()

        home=ttk.Button(self,text="Home",command=lambda:controller.show_frame(P1))
        home.pack()

class P12(tk.Frame):                       #Multiplication
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        self.x=10
        mat_1=StringVar()
        mat_2=StringVar()

        l1=Label(self,text="Matrix Multiplication (vector)",font="forte 1",fg=fg3,bg=bg3)
        l1.grid(row=1,column=2)

        l2=Label(self,text='''Seperate each row by a "  ;  " .
Seperate each element by a "  ,  " .

Esnclose everything in "  [  ]  "  . ''',font="forte",fg=fg3,bg=bg3)
        l2.grid(row=2,columnspan=3)

        l3=Label(self,text="Input 1st matrix",font="forte",fg=fg3,bg=bg3)
        l3.grid(row=3,column=0)

        mat1=Entry(self,bd=10,textvariable=mat_1,font="forte 30")
        mat1.grid(row=3,column=1,columnspan=2)

        l4=Label(self,text="Input 2nd matrix",font="forte",fg=fg3,bg=bg3)
        l4.grid(row=4,column=0)

        mat2=Entry(self,bd=10,textvariable=mat_2,font="forte 30")
        mat2.grid(row=4,column=1,columnspan=2)

        def Multiply():
            mati1=mat1.get()
            mati2=mat2.get()

            mat_x1=np.matrix(mati1)
            mat_x2=np.matrix(mati2)
            matx1=np.array(mat_x1)
            matx2=np.array(mat_x2)

            mat_multiply=np.matmul(matx1,matx2)

            l1=Label(self,text="Matrix:\n"+mati1,font="forte",fg=fg3,bg=bg3)
            l1.grid(row=self.x,column=0)

            l3=Label(self,text="Matrix:\n"+mati2,font="forte",fg=fg3,bg=bg3)
            l3.grid(row=self.x,column=1)

            l2=Label(self,text="Multiplication:\n"+str(mat_multiply),font="forte",fg=fg3,bg=bg3)
            l2.grid(row=self.x,column=2)

            self.x=self.x+1

        submit=ttk.Button(self,text="Submit",command=Multiply)
        submit.grid(column=1)

        lx=Label(self,text="",font="forte",fg=fg3,bg=bg3)
        lx.grid(column=1)

        back=ttk.Button(self,text="Back",command=lambda:controller.show_frame(P11))
        back.grid(column=1)

        home=ttk.Button(self,text="Home",command=lambda:controller.show_frame(P1))
        home.grid(column=1)

class P13(tk.Frame):                       #Inverse
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        self.x=6
        mat_1=StringVar()

        l1=Label(self,text="Matrix inverse",font="forte 1",fg=fg3,bg=bg3)
        l1.grid(row=1,column=2)

        l2=Label(self,text='''Seperate each row by a "  ;  " .
Seperate each element by a "  ,  " .

Esnclose everything in "  [  ]  "  . ''',font="forte",fg=fg3,bg=bg3)
        l2.grid(row=2,columnspan=3)

        l3=Label(self,text="Input matrix",font="forte",fg=fg3,bg=bg3)
        l3.grid(row=3,column=0)

        mat1=Entry(self,bd=10,textvariable=mat_1,font="forte 30")
        mat1.grid(row=3,column=1,columnspan=2)

        def Inverse():
            mati=mat1.get()

            mat_x=np.matrix(mati)
            mat=np.array(mat_x)

            mat_inverse=inv(mat)

            l1=Label(self,text="Matrix:       "+mati,font="forte",fg=fg3,bg=bg3)
            l1.grid(row=self.x,column=0)

            l3=Label(self,text="      ",font="forte",fg=fg3,bg=bg3)
            #l3.grid()

            l2=Label(self,text="Inverse:\n"+str(mat_inverse),font="forte",fg=fg3,bg=bg3)
            l2.grid(row=self.x,column=1)

            self.x=self.x+1

        submit=ttk.Button(self,text="Submit",command=Inverse)
        submit.grid(column=1)

        home=ttk.Button(self,text="Home",command=lambda:controller.show_frame(P1))
        home.grid(column=1)

#Complex

class P14(tk.Frame):
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        Rect_Pol =ttk.Button(self,text="Rectangular to Polar ",command=lambda:controller.show_frame(P16))
        Rect_Pol.pack()

        Pol_Rect =ttk.Button(self,text="Polar to Rectangular",command=lambda:controller.show_frame(P15))
        Pol_Rect.pack()

        Calc =ttk.Button(self,text="           Calculator            ",command=lambda:controller.show_frame(P2))
        Calc.pack()

        home=ttk.Button(self,text="Home",command=lambda:controller.show_frame(P1))
        home.pack()

class P15(tk.Frame):           # Polar to Rectangular
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        cosine=StringVar()
        sine=StringVar()

        l1=Label(self,text="Polar to Rectangular",font="forte 25",fg=fg3,bg=bg3)
        l1.grid(row=0,column=0)

        l1=Label(self,text="Input r",font="forte",fg=fg3,bg=bg3)
        l1.grid(row=1,column=0)

        r1=Entry(self,bd=10,textvariable=cosine)
        r1.grid(row=1,column=1,columnspan=2)

        l2=Label(self,text="Input theta(angle)",font="forte",fg=fg3,bg=bg3)
        l2.grid(row=2,column=0)

        th1=Entry(self,bd=10,textvariable=sine)
        th1.grid(row=2,column=1,columnspan=2)

        def pol_rect():
            ri=r1.get()
            thi=th1.get()

            r=eval(ri)
            th=eval(thi)

            c=complex(r,th)

           # Rect=cmath.rect(c)	#x=Rect[0]	#y=Rect[1]

            x=r*np.cos(radians(th))
            y=r*np.sin(radians(th))

            l1=Label(self,text="For complex(pol)= "+ri+"  ,  "+thi,font="forte",fg=fg3,bg=bg3)
            l1.grid()

            l2=Label(self,text="Polar form is:  x(cosine)="+str(x)+"  y(cosine)="+str(y),font="forte",fg=fg3,bg=bg3)
            l2.grid()

        submit=ttk.Button(self,text="Submit",command=pol_rect)
        submit.grid(column=1)

        back=ttk.Button(self,text="Back",command=lambda:controller.show_frame(P16))
        back.grid(column=1)

        home=ttk.Button(self,text="Home",command=lambda:controller.show_frame(P1))
        home.grid(column=1)

class P16(tk.Frame):               #Rectangular to polar
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        cosine=StringVar()
        sine=StringVar()

        l1=Label(self,text="Rectangular to Polar",font="forte 25",fg=fg3,bg=bg3)
        l1.grid(row=0,column=0)

        l1=Label(self,text="Input x(cosine)",font="forte",fg=fg3,bg=bg3)
        l1.grid(row=1,column=0)

        x1=Entry(self,bd=10,textvariable=cosine)
        x1.grid(row=1,column=1,columnspan=2)

        l2=Label(self,text="Input y(sine)",font="forte",fg=fg3,bg=bg3)
        l2.grid(row=2,column=0)

        y1=Entry(self,bd=10,textvariable=sine)
        y1.grid(row=2,column=1,columnspan=2)

        def rect_pol():

            xi=x1.get()
            yi=y1.get()

            x=eval(xi)
            y=eval(yi)

            c=complex(x,y)

            Pol=(cmath.polar(c))

            r=Pol[0]
            theta=Pol[1]

            l1=Label(self,text="For complex(rect)= "+xi+"+j"+yi,font="forte",fg=fg3,bg=bg3)
            l1.grid()

            l2=Label(self,text="Polar form is:  r="+str(r)+"  angle="+str(theta),font="forte",fg=fg3,bg=bg3)
            l2.grid()

        submit=ttk.Button(self,text="Submit",command=rect_pol)
        submit.grid(column=1)

        back=ttk.Button(self,text="Back",command=lambda:controller.show_frame(P14))
        back.grid(column=1)

        home=ttk.Button(self,text="Home",command=lambda:controller.show_frame(P1))
        home.grid(column=1)

#Solve Equations

class P17(tk.Frame):         #solve equations
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        rr=Label(self,text="Solve equation/s",font="forte 25",fg=fg3,bg=bg3)
        rr.pack()

        l=Label(self,text="How many variables does the equation have?",font="forte",fg=fg3,bg=bg3)
        l.pack()

        var_1=ttk.Button(self,text="1 variable (x)",command=lambda:controller.show_frame(P18))
        var_1.pack()

        home=ttk.Button(self,text="Home",command=lambda:controller.show_frame(P1))
        home.pack()

        '''var_2=ttk.Button(self,text="2 variables (x,y)",command=lambda:controller.show_frame(P7))
        var_2.pack()'''

class P18(tk.Frame):          #1 variable
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        rr=Label(self,text="1 variable",font="forte 25",fg=fg3,bg=bg3)
        rr.pack()

        Deg_2=ttk.Button(self,text="2 degree",command=lambda:controller.show_frame(P19))
        Deg_2.pack()

        Deg_3=ttk.Button(self,text="3 degree",command=lambda:controller.show_frame(P20))
        Deg_3.pack()

        rr=Label(self,text="",font="forte",fg=fg3,bg=bg3)
        rr.pack()

        back=ttk.Button(self,text="  Back ",command=lambda:controller.show_frame(P17))
        back.pack()

        home=ttk.Button(self,text=" Home ",command=lambda:controller.show_frame(P1))
        home.pack()

class P19(tk.Frame):          # 1 variable 2 degree
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        rr=Label(self,text="2 degree equation with 1 variable (x)",font="forte 25",fg=fg3,bg=bg3)
        rr.grid(row=0,column=0)

        a_1=StringVar()
        b_1=StringVar()
        c_1=StringVar()

        l1=Label(self,text="Coeff of x**2",font="forte",fg=fg3,bg=bg3)
        l1.grid(row=1,column=0)

        a1=Entry(self,bd=10,textvariable=a_1)
        a1.grid(row=1,column=1,columnspan=2)

        l2=Label(self,text="Coeff of x",font="forte",fg=fg3,bg=bg3)
        l2.grid(row=2,column=0)

        b1=Entry(self,bd=10,textvariable=b_1)
        b1.grid(row=2,column=1,columnspan=2)

        l3=Label(self,text="constant",font="forte",fg=fg3,bg=bg3)
        l3.grid(row=3,column=0)

        c1=Entry(self,bd=10,textvariable=c_1)
        c1.grid(row=3,column=1,columnspan=2)

        def roots():
            ai=a1.get()
            bi=b1.get()
            ci=c1.get()

            a=eval(ai)
            b=eval(bi)
            c=eval(ci)

            d = b**2-4*a*c # discriminant

            if d < 0:
                l4=Label(self,text="No solution",font="forte",fg=fg3,bg=bg3)
                l4.grid(row=6,column=0)

            elif d == 0:
                x = (-b+math.sqrt(b**2-4*a*c))/2*a
                l4=Label(self,text="One solution: "+str(x),font="forte",fg=fg3,bg=bg3)
                l4.grid(row=6,column=0)

            else:
                x1 = (-b+math.sqrt(b**2-4*a*c))/2*a
                x2 = (-b-math.sqrt(b**2-4*a*c))/2*a
                l4=Label(self,text="Two solutions:  x1= "+str(x1)+"x2= "+str(x2),font="forte",fg=fg3,bg=bg3)
                l4.grid(row=6,column=0)

        submit=ttk.Button(self,text="Submit",command=roots)
        submit.grid(column=1)

        back=ttk.Button(self,text="  Back  ",command=lambda:controller.show_frame(P16))
        back.grid(column=1)

        home=ttk.Button(self,text="Home",command=lambda:controller.show_frame(P1))
        home.grid(column=1)

'''     l2=Label(self,text="Input r",font="forte",fg="white",bg="black")
        l2.grid(row=0,column=0)

        r2=Entry(self,bd=10,textvariable=cosine)
        r2.grid(row=0,column=1,columnspan=2)                 '''

class P20(tk.Frame):          # 1 variable 3 degree
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

        rr=Label(self,text="3 degree equation with 1 variable (x)",font="forte 25",fg=fg3,bg=bg3)
        rr.grid(row=0,column=0)

        a_1=IntVar()
        b_1=IntVar()
        c_1=IntVar()
        d_1=IntVar()

        l2=Label(self,text="a: ",font="forte",fg=fg3,bg=bg3)
        l2.grid(row=2,column=0)

        a1=Entry(self,bd=10,textvariable=a_1)
        a1.grid(row=2,column=1,columnspan=2)

        l3=Label(self,text="b: ",font="forte",fg=fg3,bg=bg3)
        l3.grid(row=3,column=0)

        b1=Entry(self,bd=10,textvariable=b_1)
        b1.grid(row=3,column=1,columnspan=2)

        l1=Label(self,text="c: ",font="forte",fg=fg3,bg=bg3)
        l1.grid(row=4,column=0)

        c1=Entry(self,bd=10,textvariable=c_1)
        c1.grid(row=4,column=1,columnspan=2)

        l4=Label(self,text="d: ",font="forte",fg=fg3,bg=bg3)
        l4.grid(row=5,column=0)

        d1=Entry(self,bd=10,textvariable=d_1)
        d1.grid(row=5,column=1,columnspan=2)

        def roots():
            ai=a1.get()
            bi=b1.get()
            ci=c1.get()
            di=d1.get()

            a=eval(ai)
            b=eval(bi)
            c=eval(ci)
            d=eval(di)

            '''p = -b/(3*a)
            q = p**3 + (b*c-3*a*d)/(6*a**2)
            r = c/(3*a)'''

            yi=18*a*b*c*d - 4*(b**3)*d + (b**2)*(c**2) - 4*a*(c**3) -27*(a**2)*(d**2)

            #x   = (q +   (q**2+ (r-p**2)**3 )**(1/2)  )**(1/3) + (q -  (q**2 + (r-p**2)**3 )**(1/2))**(1/3) + p

            y0= b**2-3*a*c
            y1=2*b**3-9*a*b*c+27*(a**2)*d

            if yi<0:
                yi=yi*(-1)

            x=((y1+yi**0.5)/2)**(1/3)
            l=Label(self,text=str(x))
            l.grid()

        submit=ttk.Button(self,text="Submit",command=roots)
        submit.grid(column=1)

        home=ttk.Button(self,text="Home",command=lambda:controller.show_frame(P1))
        home.grid(column=1)

# Create object
print(theme)
root=Main()
root.title("Mathematics")
colour=theme
def exit_function():
    # Put any cleanup here.
    sys.exit()
    root.destroy()

root.protocol('WM_DELETE_WINDOW', exit_function)

root.mainloop()

max_stars_repo_name: EshitaShukla/Mathematics

max_issues_repo_name: EshitaShukla/Mathematics

max_forks_repo_name: EshitaShukla/Mathematics

reason: import numpy,from numpy


text:
import torch
import numpy as np
from torch.utils.data import DataLoader
from mot.utils import Registry, build_from_config

DATASETS = Registry('datasets')
COLLATES = Registry('collates')

def build_dataset(config):
    return build_from_config(DATASETS, config)

def build_collate(config):
    return build_from_config(COLLATES, config)

def build_dataloader(dataset, config):
    collate_class = build_collate(config.DATALOADER.COLLATE)
    args, kwargs = [], {}
    # if collate_class.multiscale:
    init_size = np.array([config.MODEL.ARGS.INPUT.HEIGHT,
        config.MODEL.ARGS.INPUT.WIDTH], dtype=np.int32)
    shared_size = torch.from_numpy(init_size).share_memory_()
    kwargs['shared_size'] = shared_size
    collate_fn = collate_class(*args, **kwargs)
    dataloader = DataLoader(dataset,
        batch_size=config.SOLVER.BATCH_SIZE,
        shuffle=config.DATALOADER.SHUFFLE,
        num_workers=config.SYSTEM.NUM_WORKERS,
        collate_fn=collate_fn, pin_memory=True, drop_last=True)
    return dataloader

ext: py

max_stars_repo_name: CnybTseng/JDE

max_issues_repo_name: CnybTseng/JDE

max_forks_repo_name: CnybTseng/JDE

reason: import numpy


text:
"""
https://github.com/teticio/kivy-tensorflow-helloworld/blob/main/buildozer.spec
"""
import numpy as np
from kivy.utils import platform

if platform == "android":
    from jnius import autoclass

    File = autoclass("java.io.File")
    Interpreter = autoclass("org.tensorflow.lite.Interpreter")
    InterpreterOptions = autoclass("org.tensorflow.lite.Interpreter$Options")
    Tensor = autoclass("org.tensorflow.lite.Tensor")
    DataType = autoclass("org.tensorflow.lite.DataType")
    TensorBuffer = autoclass("org.tensorflow.lite.support.tensorbuffer.TensorBuffer")
    ByteBuffer = autoclass("java.nio.ByteBuffer")

    class TensorFlowModel:
        def load(self, model_filename, num_threads=1, nnapi = False):
            model = File(model_filename)
            options = InterpreterOptions()
            #if num_threads is not None:
            options.setNumThreads(num_threads)
            options.setUseNNAPI(nnapi)

            self.interpreter = Interpreter(model, options)
            self.allocate_tensors()

        def allocate_tensors(self):
            print(self.interpreter, type(self.interpreter))
            self.interpreter.allocateTensors()
            self.input_shape = self.interpreter.getInputTensor(0).shape()
            self.output_shape = self.interpreter.getOutputTensor(0).shape()
            self.output_type = self.interpreter.getOutputTensor(0).dataType()

        def get_input_shape(self):
            return self.input_shape

        def resize_input(self, shape):
            if self.input_shape != shape:
                self.interpreter.resizeInput(0, shape)
                self.allocate_tensors()

        def pred(self, x):
            # assumes one input and one output for now
            input = ByteBuffer.wrap(x.tobytes())
            output = TensorBuffer.createFixedSize(self.output_shape, self.output_type)
            self.interpreter.run(input, output.getBuffer().rewind())
            return np.reshape(np.array(output.getFloatArray()), self.output_shape)

# elif platform == 'ios':
#     from pyobjus import autoclass, objc_arr
#     from ctypes import c_float, cast, POINTER
#
#     NSString = autoclass('NSString')
#     NSError = autoclass('NSError')
#     Interpreter = autoclass('TFLInterpreter')
#     InterpreterOptions = autoclass('TFLInterpreterOptions')
#     NSData = autoclass('NSData')
#     NSMutableArray = autoclass("NSMutableArray")
#
#     class TensorFlowModel:
#         def load(self, model_filename, num_threads=None):
#             self.error = NSError.alloc()
#             model = NSString.stringWithUTF8String_(model_filename)
#             options = InterpreterOptions.alloc().init()
#             if num_threads is not None:
#                 options.numberOfThreads = num_threads
#             self.interpreter = Interpreter.alloc(
#             ).initWithModelPath_options_error_(model, options, self.error)
#             self.allocate_tensors()
#
#         def allocate_tensors(self):
#             self.interpreter.allocateTensorsWithError_(self.error)
#             self.input_shape = self.interpreter.inputTensorAtIndex_error_(
#                 0, self.error).shapeWithError_(self.error)
#             self.input_shape = [
#                 self.input_shape.objectAtIndex_(_).intValue()
#                 for _ in range(self.input_shape.count())
#             ]
#             self.output_shape = self.interpreter.outputTensorAtIndex_error_(
#                 0, self.error).shapeWithError_(self.error)
#             self.output_shape = [
#                 self.output_shape.objectAtIndex_(_).intValue()
#                 for _ in range(self.output_shape.count())
#             ]
#             self.output_type = self.interpreter.outputTensorAtIndex_error_(
#                 0, self.error).dataType
#
#         def get_input_shape(self):
#             return self.input_shape
#
#         def resize_input(self, shape):
#             if self.input_shape != shape:
#                 # workaround as objc_arr doesn't work as expected on iPhone
#                 array = NSMutableArray.new()
#                 for x in shape:
#                     array.addObject_(x)
#                 self.interpreter.resizeInputTensorAtIndex_toShape_error_(
#                     0, array, self.error)
#                 self.allocate_tensors()
#
#         def pred(self, x):
#             # assumes one input and one output for now
#             bytestr = x.tobytes()
#             # must cast to ctype._SimpleCData so that pyobjus passes pointer
#             floatbuf = cast(bytestr, POINTER(c_float)).contents
#             data = NSData.dataWithBytes_length_(floatbuf, len(bytestr))
#             self.interpreter.copyData_toInputTensorAtIndex_error_(
#                 data, 0, self.error)
#             self.interpreter.invokeWithError_(self.error)
#             output = self.interpreter.outputTensorAtIndex_error_(
#                 0, self.error).dataWithError_(self.error).bytes()
#             # have to do this to avoid memory leaks...
#             while data.retainCount() > 1:
#                 data.release()
#             return np.reshape(
#                 np.frombuffer(
#                     (c_float * np.prod(self.output_shape)).from_address(
#                         output.arg_ref), c_float), self.output_shape)

else:
    import tensorflow as tf

    class TensorFlowModel:
        def load(self, model_filename, num_threads=None):
            self.interpreter = tf.lite.Interpreter(
                model_filename, num_threads=num_threads
            )
            self.interpreter.allocate_tensors()

        def resize_input(self, shape):
            if list(self.get_input_shape()) != shape:
                self.interpreter.resize_tensor_input(0, shape)
                self.interpreter.allocate_tensors()

        def get_input_shape(self):
            return self.interpreter.get_input_details()[0]["shape"]

        def pred(self, x):
            # assumes one input and one output for now
            self.interpreter.set_tensor(
                self.interpreter.get_input_details()[0]["index"], x
            )
            self.interpreter.invoke()
            return self.interpreter.get_tensor(
                self.interpreter.get_output_details()[0]["index"]
            )

max_stars_repo_name: kmkolasinski/kivy-tflite-helloworld

max_issues_repo_name: kmkolasinski/kivy-tflite-helloworld

max_forks_repo_name: kmkolasinski/kivy-tflite-helloworld


text:
from skimage.metrics import structural_similarity as ssim
from imutils import paths
from imutils.video import FPS
from helpers.abilitybar import AbilityBar
from helpers.abilitybar import LongAbilityBar
from helpers.abilitybar import LaAbilityBar
import subprocess as sp
import cv2
import numpy as np
import argparse
import datetime

ap = argparse.ArgumentParser()
ap.add_argument("-p", "--profile",
    help='Choose your profile. Available: TankDK, MagPlar, MagDen, StamBlade, StamCro, BowCro')
ap.add_argument('--nographics', action='store_true',
    help='Toggle the ability bars off. Just display the raw input image.')
ap.add_argument('--fullscreen', action='store_true',
    help='Launch in full screen. Your monitor should have Full HD display resolution for this to function correctly.')
ap.add_argument('--fps', action='store_true',
    help='Turn FPS calculations ON.')
args = vars(ap.parse_args())

if args["profile"] == "TankDK":
    SKILLS_BEING_TRACKED = {'images/cropped/BlockadeOfStorms.png': 14.0,
                            'images/cropped/Balance.png': 25.0,
                            'images/cropped/BlockadeOfFrost.png': 14.0}

    LONG_SKILLS = ['images/cropped/Balance.png']

elif args["profile"] == "MagPlar":
    SKILLS_BEING_TRACKED = {'images/cropped/UnstableWallOfElements.png': 10.0,
                            'images/cropped/BarbedTrap.png': 18.0}

    LONG_SKILLS = ['images/cropped/BarbedTrap.png']

elif args["profile"] == "MagDen":
    SKILLS_BEING_TRACKED = {'images/cropped/GrippingShards.png': 12.0,
                            'images/cropped/BlueBetty.png': 25.0}

    LONG_SKILLS = ['images/cropped/BlueBetty.png']

elif args["profile"] == "StamBlade":
    SKILLS_BEING_TRACKED = {'images/cropped/LeechingStrikes.png': 10.0,
                            'images/cropped/RaceAgainstTheTime.png': 12.0}

    LONG_SKILLS = ['images/cropped/RaceAgainstTheTime.png']

elif args["profile"] == "StamCro":
    SKILLS_BEING_TRACKED = {'images/cropped/EndlessHail.png': 14.0,
                            'images/cropped/BarbedTrap.png': 18.0}

    LONG_SKILLS = ['images/cropped/BarbedTrap.png']

elif args["profile"] == "BowCro":
    SKILLS_BEING_TRACKED = {'images/cropped/EndlessHail.png': 14.0,
                            'images/cropped/SkeletalArcher.png': 16.0}

    LONG_SKILLS = ['images/cropped/SkeletalArcher.png']

else:
    print("[WARNING] You are not using ANY profile.")
    SKILLS_BEING_TRACKED = None
    LONG_SKILLS = None

def skill_locations():
    # Set values from ESO UI. Offset is 64x64 box's width plus the 10px margin.
    OFFSET = 64 + 10
    CROPSIZE = 60

    # Reserve a dictionary for skill xy coords
    skills = {}

    # Calculate xy-coordinates of the skill icons
    for i in range(0,5):
        yStart, yEnd = 986, 986 + CROPSIZE
        xStart = 790 + (i * OFFSET)
        xEnd = xStart + CROPSIZE
        skills[i+1] = (yStart, yEnd, xStart, xEnd)

    return skills

def strip_locations():
    # Set values from ESO UI. Offset is 64x64 box's width plus the 10px margin.
    OFFSET = 64 + 10
    CROPSIZE = 67

    # Reserve a dictionary for skill xy coords
    skills = {}

    # Calculate xy-coordinates of the skill icons
    for i in range(0,5):
        yStart, yEnd = 982, 984
        xStart = 786 + (i * OFFSET)
        xEnd = xStart + CROPSIZE
        skills[i+1] = (yStart, yEnd, xStart, xEnd)

    return skills

def blackmagic_image():
    # Capture data from pipe
    raw_image = pipe.stdout.read(1920*1080*3)

    # transform the raw data into a numpy array
    image =  np.fromstring(raw_image, dtype='uint8')

    # Reshape to Full HD
    image = image.reshape((1080,1920,3))

    return image

def crop_ability_icons(skill_coords, image, bgr=False):
    bm_crops = []

    for i in skill_coords.keys():
        (yStart, yEnd, xStart, xEnd) = skill_coords[i]
        crop = image[yStart:yEnd, xStart:xEnd]

        # BGR channels not wanted, keep only R.
        if not bgr:
            _,_,crop = cv2.split(crop)

        bm_crops.append(crop)

    return bm_crops

def compare_icons(bm_icons, query_icon):
    for i, icon in enumerate(bm_icons, 1):
        ss = ssim(icon, query_icon)
        if ss > 0.80:
            return i
    return None

def analyse_icon(bm_icon_tops, threshold=15, verbose=False):
    # Similar to compare icons, but finds out if a skill
    # has been activated without caring what the actual skill
    # is. Reasoning: if a skill has been activated, we must
    # be interested in global cooldown metronome.
    LA_FOUND = False

    for i, icon in enumerate(bm_icon_tops, start=1):
        feature = cv2.mean(icon)

        hsv = cv2.cvtColor(icon, cv2.COLOR_BGR2HSV)
        feature = np.array(cv2.mean(hsv)[:3]).astype(int)

        # Let's half the saturation and value to reduce their weight on euclidean distance.
        feature[1] = feature[1] // 2
        feature[2] = feature[2] // 4

        # These HSV values correspond to the yellow glow around
        # an activated skill icon
        ICON = [24, 80, 35]
        dist = np.linalg.norm(feature - ICON).astype(int)

        if verbose and dist < threshold:
            print(f"[INFO] Slot {i}, feature: {feature}, dist: {dist}")

        if dist < threshold:
            LA_FOUND = True

    return LA_FOUND

def load_query_icons(only_two_skills=None):
    # Reserve lists for query images and their paths
    query_icons = []
    query_paths = []

    # Either go through all skills in SKILLS_BEING_TRACKED
    # Or use the ones already set in both Ability bars.
    # This is useful e.g. if using both lightning and ice staves
    # on a tank in different content.
    if only_two_skills is None:
        paths = SKILLS_BEING_TRACKED.keys()
    else:
        paths = only_two_skills

    # Load all images from images/cropped/ and store them in lists
    for path in paths:

        # Load image and keep only Red channel
        query_icon = cv2.imread(path)
        _,_,query_icon = cv2.split(query_icon)

        # Append to lists
        query_icons.append(query_icon)
        query_paths.append(path)

    return query_icons, query_paths

if __name__ == "__main__":

    # Launch FFMPEG with Blackmagic settings
    FFMPEG_BIN = "ffmpeg"
    command = [ FFMPEG_BIN,
        '-hide_banner',
        '-loglevel','warning',
        '-raw_format','bgra',
        '-format_code','Hp59',
        '-f','decklink',
        '-i', 'Intensity Pro 4K',
        '-pix_fmt', 'bgr24',
        '-vcodec', 'rawvideo',
        '-an','-sn',
        '-f', 'image2pipe', '-']

    # Get data from ffmpeg pipe
    pipe = sp.Popen(command, stdout = sp.PIPE, bufsize=-1)

    # Instansiate classes and important variables
    if not args['nographics']:
        # Dictionary for skills[i] = (yStart, yEnd, xStart, xEnd)
        skill_coords = skill_locations()
        skill_tops_coords = strip_locations()

        # Instanciate ability bars.
        upperbar = AbilityBar()
        lowerbar = LongAbilityBar()
        lightatt_bar = LaAbilityBar()

    # Load the initial query icons and paths. ALL of these
    # will be compared to slots 1-5 before the set_timer()
    # has been run on 1 long and 1 short skill
    if not args['nographics']:
        query_icons, query_paths = load_query_icons()
        selected = None

    if args['fullscreen']:
        cv2.namedWindow('ElderSCrollsOnline', cv2.WINDOW_FREERATIO)
        cv2.setWindowProperty('ElderSCrollsOnline', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)

    if args['fps']:
        fps = FPS().start()

    # Main loop
    while True:

        if not args['nographics']:
            # Get time for deltaTime calculations
            start = datetime.datetime.now()

        # Get a single ElderSCrollsOnline from capture card
        bm_capture = blackmagic_image()

        # Empty pipe read
        pipe.stdout.flush()

        # Crop icons from the BlackMagic source
        if not args['nographics']:
            bm_icons = crop_ability_icons(skill_coords, bm_capture)

            # Try to select only two abilities to boost performance
            # in a situation where len(SKILLS_BEING_TRACKED) > 2
            if  selected == None:
                if None not in [upperbar.skillPath, lowerbar.skillPath]:
                    # Load query icons and paths again.
                    # If e.g. lightning and ice staff abilities are both in
                    # SKILLS_BEING_TRACKED, one is now dropped out.
                    selected = [upperbar.skillPath, lowerbar.skillPath]
                    query_icons, query_paths = load_query_icons(only_two_skills=selected)

            # Loop queries and compare those to the icons in the image stream.
            for query_icon, query_path in zip(query_icons, query_paths):

                # Fetch the id [1-5] of a slotted skill that has ss < threshold.
                matched_idx = compare_icons(bm_icons, query_icon)

                if matched_idx is not None:
                    if query_path in LONG_SKILLS:
                        lowerbar.set_timer(query_path, matched_idx, SKILLS_BEING_TRACKED[query_path])
                    else:
                        upperbar.set_timer(query_path, matched_idx, SKILLS_BEING_TRACKED[query_path])

        # Crop strips and compare their HSV values to the values set in analyse_icon()
        if not args['nographics']:
            bm_icon_tops = crop_ability_icons(skill_tops_coords, bm_capture, bgr=True)

            ANY_SKILL_PRESSED = analyse_icon(bm_icon_tops, verbose=False)

            if ANY_SKILL_PRESSED:
                lightatt_bar.set_la_timer()

        """
        DISPLAY IMAGES
        """

        if bm_capture is not None:
            # Update graphics bars
            if not args['nographics']:
                if upperbar.active():
                    bm_capture = upperbar.draw_bar(bm_capture)

                if lowerbar.active():
                    bm_capture = lowerbar.draw_bar(bm_capture, flicker=True)

                if lightatt_bar.active():
                    bm_capture = lightatt_bar.draw_bar(bm_capture)

            # Draw image on screen
            cv2.imshow('ElderSCrollsOnline', bm_capture)

        # Exit if Q has been pressed
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        """
        UPDATE TIMERS
        """

        if not args['nographics']:
            # Check how many seconds did the processing take
            deltaTime = (datetime.datetime.now() - start).total_seconds()

            # Reduce the deltaTime from any active ability timers
            if upperbar.active():
                upperbar.reduce_time(deltaTime)

            if lowerbar.active():
                lowerbar.reduce_time(deltaTime)

            if lightatt_bar.active():
                lightatt_bar.reduce_time(deltaTime)

        if args['fps']:
            fps.update()

    """
    PERFORM CLEANUP
    """

    if args['fps']:
        fps.stop()
        print("[INFO] elasped time: {:.2f}".format(fps.elapsed()))
        print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))

    # Empty pipe read
    pipe.stdout.flush()
    cv2.destroyAllWindows()

max_stars_repo_name: sourander/eso-ability-timer

max_issues_repo_name: sourander/eso-ability-timer

max_forks_repo_name: sourander/eso-ability-timer


text:
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2019 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
#   contributors may be used to endorse or promote products derived from
#   this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Unit tests for the feels_like_temperature.WindChill plugin."""

import unittest

import numpy as np
from iris.tests import IrisTest

from improver.feels_like_temperature import calculate_wind_chill
from improver.tests.set_up_test_cubes import set_up_variable_cube

class Test_calculate_wind_chill(IrisTest):
    """Test the wind chill function."""

    def setUp(self):
        """Creates cubes to input"""

        temperature = np.array([[226.15, 237.4, 248.65]], dtype=np.float32)
        self.temperature_cube = set_up_variable_cube(temperature)

        wind_speed = np.array([[0., 7.5, 15.]], dtype=np.float32)
        self.wind_speed_cube = set_up_variable_cube(
            wind_speed, name="wind_speed", units="m s-1")

    def test_wind_chill_values(self):
        """Test output values when from the wind chill equation."""

        # use a temperature less than 10 degrees C.
        self.temperature_cube.data = np.full((1, 3), 274.85)
        self.wind_speed_cube.data = np.full((1, 3), 3)
        expected_result = np.full((1, 3), 271.674652, dtype=np.float32)
        result = calculate_wind_chill(
            self.temperature_cube, self.wind_speed_cube)
        self.assertArrayAlmostEqual(result.data, expected_result)

    def test_name_and_units(self):
        """Test correct outputs for name and units."""
        expected_name = "wind_chill"
        expected_units = 'K'
        result = calculate_wind_chill(
            self.temperature_cube, self.wind_speed_cube)
        self.assertEqual(result.name(), expected_name)
        self.assertEqual(result.units, expected_units)

    def test_different_units(self):
        """Test that values are correct from input cubes with
        different units"""

        self.temperature_cube.convert_units('fahrenheit')
        self.wind_speed_cube.convert_units('knots')

        data = np.array(
            [[257.05949633, 220.76791229, 231.12778024]])
        # convert to fahrenheit
        expected_result = (data * (9.0/5.0) - 459.67).astype(np.float32)
        result = calculate_wind_chill(
            self.temperature_cube, self.wind_speed_cube)
        self.assertArrayAlmostEqual(result.data, expected_result)

    def test_unit_conversion(self):
        """Tests that input cubes have the same units at the end of the
        function as they do at input"""

        self.temperature_cube.convert_units('fahrenheit')
        self.wind_speed_cube.convert_units('knots')

        calculate_wind_chill(
            self.temperature_cube, self.wind_speed_cube)

        temp_units = self.temperature_cube.units
        wind_speed_units = self.wind_speed_cube.units

        self.assertEqual(temp_units, 'fahrenheit')
        self.assertEqual(wind_speed_units, 'knots')

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

max_stars_repo_name: TomekTrzeciak/improver

max_issues_repo_name: TomekTrzeciak/improver

max_forks_repo_name: TomekTrzeciak/improver


text:
"""
        telemetry format:
                struct frame_header {
                        uint16_t        start_marker;   // 0x78 0x78
                        uint16_t        frame_counter;
                        uint8_t         frame_type;
                        uint32_t        onboard_time;   // 20 bits onboard_time,
                                                        // 12 bits data_length
                        uint8_t         data_length;    // 12+8 = 20 bits data_length
                        uint16_t        crc;
                };
                and payload:
                        data_length = 5315 byte for telemetry mode 1
                        data_length = 5415 byte for telemetry mode 2
                        sizes may change in future

"""
import socket
import numpy as np
from traitlets import Int, TCPAddress, Float
from skywinder.utils.configuration import GlobalConfiguration
import logging
from skywinder.communication.packet_classes import LidarTelemetryPacket, PacketInsufficientLengthError, \
    PacketChecksumError

logger = logging.getLogger(__name__)

slow_telemetry_request = """0,A,T
0 COLOSSUS:SLOWTEL
END 48630
"""

lidar_ping_request = """0,A,T
0 COLOSSUS:PING
END 2432
"""

class LidarTelemetry(GlobalConfiguration):
    telemetry_address = TCPAddress(default_value=('lidar', 7007)).tag(config=True)
    slow_telemetry_port = Int(7008, min=1024, max=65535).tag(config=True)
    telemetry_socket_connection_timeout = Float(default_value=1.0,min=0).tag(config=True)
    telemetry_socket_data_timeout = Float(default_value=0.01,min=0).tag(config=True)

    def __init__(self, **kwargs):
        super(LidarTelemetry, self).__init__(**kwargs)
        self.telemetry_socket = None
        self.slow_telemetry_socket = None
        self.data_in_progress = b''
        self.latest_lidar_packet = None

    def connect(self):
        try:
            self.telemetry_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.telemetry_socket.settimeout(self.telemetry_socket_connection_timeout)
            self.telemetry_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.telemetry_socket.connect(self.telemetry_address)
            self.telemetry_socket.settimeout(self.telemetry_socket_data_timeout)
            self.slow_telemetry_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.slow_telemetry_socket.settimeout(self.telemetry_socket_connection_timeout)
            self.slow_telemetry_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.slow_telemetry_socket.connect((self.telemetry_address[0],self.slow_telemetry_port))
            self.slow_telemetry_socket.settimeout(self.telemetry_socket_data_timeout)
        except socket.error:
            logger.exception("Couldn't open sockets for telemetry address %r and slow telemetry port %d" %
                             (self.telemetry_address, self.slow_telemetry_port))
            self.close()

    def close(self):
        if self.telemetry_socket:
            try:
                self.telemetry_socket.close()
            except Exception as e:  # pragma: no cover
                logger.exception("Failure while closing telemetry socket")  # pragma: no cover
            self.telemetry_socket = None
        if self.slow_telemetry_socket:
            try:
                self.slow_telemetry_socket.close()
            except Exception as e:  # pragma: no cover
                logger.exception("Failure while closing slow telemetry socket")  # pragma: no cover
            self.slow_telemetry_socket = None

    def send_lidar_command(self, command):
        if self.telemetry_socket is None:
            logger.info("Lidar telemetry socket not connected, trying to connect first")
            self.connect()
            if self.telemetry_socket is None:
                raise RuntimeError("Unable to connect to LIDAR telemetry socket")
        try:
            self.telemetry_socket.sendall(command)
        except socket.error:
            logger.exception("Failed to send LIDAR command %r" % command)
            self.close()
        logger.info("Sent lidar command\n%r" % command)

    def get_telemetry_data(self):
        if self.telemetry_socket is None:
            logger.info("Lidar telemetry socket not connected, trying to connect first")
            self.connect()
            if self.telemetry_socket is None:
                raise RuntimeError("Unable to connect to LIDAR telemetry socket")
        try:
            data = self.telemetry_socket.recv(2 ** 20)
        except socket.timeout:
            data = b''
        except socket.error as e:
            logger.exception("Error while trying to receive telemetry")
            data = b''

        print(self.data_in_progress)
        if not self.data_in_progress + data:
            return None
        lidar_packet, remainder = find_next_lidar_packet(self.data_in_progress + data)
        self.data_in_progress = remainder
        if lidar_packet is not None:
            logger.info("got valid packet from single TCP packet %d, %d" %
                        (lidar_packet.frame_counter, lidar_packet.payload_length))
            self.latest_lidar_packet = lidar_packet
        return lidar_packet

    def _get_slow_telemetry_data(self):
        try:
            packet = self.slow_telemetry_socket.recv(8192)
        except socket.error as e:
            print("no slow data", e)
            return None
        return packet

    def request_and_get_slow_telemetry(self):
        if self.telemetry_socket is None:
            logger.info("Lidar telemetry socket not connected, trying to connect first")
            self.connect()
            if self.telemetry_socket is None:
                raise RuntimeError("Unable to connect to LIDAR telemetry socket")
        self.send_lidar_command(slow_telemetry_request)
        return self._get_slow_telemetry_data()

    def ping(self):
        if self.telemetry_socket is None:
            logger.info("Lidar telemetry socket not connected, trying to connect first")
            self.connect()
            if self.telemetry_socket is None:
                raise RuntimeError("Unable to connect to LIDAR telemetry socket")
        self.send_lidar_command(lidar_ping_request)
        result = self._get_slow_telemetry_data()
        logger.info("Ping lidar returned %r" % result)
        return result

    def run(self): # Only used for initial test, not used elsewhere, so no need for coverage.
        if self.telemetry_socket is None:  # pragma: no cover
            self.connect()  # pragma: no cover
        while True:  # pragma: no cover
            print(self.request_and_get_slow_telemetry())  # pragma: no cover

def find_next_lidar_packet(data, start_pattern=b'xx'):
    if len(data) < LidarTelemetryPacket.header_length:
        logger.debug("Data length %d is too short to contain header of length %d" % (len(data), LidarTelemetryPacket.header_length))
        return None,data
    remainder = data
    while True:
        start_index = remainder.find(start_pattern)
        if start_index < 0:
            logger.debug("No start pattern found")
            return None, remainder
        if start_index > 0:
            logger.warning("dropping %d bytes preceeding first valid start pattern" % start_index)
            remainder = remainder[start_index:]
        try:
            header_length = LidarTelemetryPacket.header_length
            header = LidarTelemetryPacket.decode_header(remainder[:header_length])
            packet_length = header_length + header['data_length']
            packet = LidarTelemetryPacket(buffer=remainder[:packet_length])
            logger.info("Found lidar telemetry packet starting at index %d" % start_index)
            return packet, remainder[packet_length:]
        except PacketInsufficientLengthError:
            logger.debug("Data too short to include a packet, expected length is %d"%packet_length)
            if len(remainder[1:]) > LidarTelemetryPacket.header_length:
                logger.debug("Recursively searching for packet starting at index %d of %d" % (1,len(remainder)))
                trial_packet,trial_remainder = find_next_lidar_packet(remainder[1:],start_pattern=start_pattern)
                if trial_packet:
                    logger.debug("Found packet using recursion")
                    return trial_packet,trial_remainder
            return None, remainder
        except PacketChecksumError:
            logger.exception("Encountered bad data (failed checksum), advancing 1 byte")
            remainder = remainder[1:]
        except Exception:
            logger.exception("Failed to decode candidate packet at index %d, advancing 1 byte" % start_index)
            remainder = remainder[1:]

if __name__ == "__main__":
    lt = LidarTelemetry()
    lt.run()

max_stars_repo_name: PolarMesosphericClouds/SkyWinder

max_issues_repo_name: PolarMesosphericClouds/SkyWinder

max_forks_repo_name: PolarMesosphericClouds/SkyWinder