import kivy
from kivy.properties import ObjectProperty
from kivy.clock import Clock
from kivy.uix.screenmanager import ScreenManager, Screen
import points

class Type5Window(Screen):

    video = ObjectProperty(None)
    answer = ""
    ppp = 0
    start = 0

    def update(self, btn):

        self.start = self.start + 1
        if self.start == 3:
            self.start = 0

        if self.start == 0:
            self.ids.video.source = "bubble_sort.gif"
        elif self.start == 1:
            self.ids.video.source = "scalanie.gif"
        elif self.start == 2:
            self.ids.video.source = "wstawianie.gif"

        if self.ids.video.source == "scalanie.gif" and self.answer == "B":
            self.ppp = self.ppp + 1
            points.globalPoint += 1
            # self.ids.points.text = "POINTS: {}".format(self.ppp)
        elif self.ids.video.source == "wstawianie.gif" and self.answer == "C":
            self.ppp = self.ppp + 1
            points.globalPoint += 1
            # self.ids.points.text = "POINTS: {}".format(self.ppp)
        elif self.ids.video.source == "bubble_sort.gif" and self.answer == "A":
            self.ppp = self.ppp + 1
            points.globalPoint += 1
            # self.ids.points.text = "POINTS: {}".format(self.ppp)

        self.ids.answerA.active = False
        self.ids.answerB.active = False
        self.ids.answerC.active = False

    AMOUNT = 30
    seconds = AMOUNT
    widget = None

    def start1(self):
        Clock.schedule_interval(self.Callback_Clock, 1)

    def Callback_Clock(self, dt):
        self.seconds = self.seconds - 1
        self.time.text = "00:{}".format(self.seconds)
        if self.seconds == 0:
            self.time.text = "FINISH"
            self.seconds = self.AMOUNT
            self.confirm.trigger_action(duration=0.1)
        if self.confirm.state == "down":
            self.seconds = self.AMOUNT


from dotenv import load_dotenv
import os
import openai
import subprocess
import json
import argparse

class Styles:
    bold = "\u001b[1m"
    underline = "\u001b[4m"
    inverted = "\u001b[7m"
    reset = "\u001b[0m"
    green = "\u001b[38;5;121m"
    blue = "\u001b[38;5;117m"
    red = "\u001b[38;5;198m"
    yellow = "\u001b[38;5;228m"
    white = "\u001b[38;5;255m"
    black = "\u001b[38;5;234m"
    bg_green = "\u001b[48;5;121m"
    bg_blue = "\u001b[48;5;117m"
    bg_red = "\u001b[48;5;198m"
    bg_yellow = "\u001b[48;5;228m"
    bg_white = "\u001b[48;5;255m"
    bg_black = "\u001b[48;5;234m"

def styled(txt: str, style: str = ""):
    return style + txt + Styles.reset

if __name__ == "__main__":
    max_history = 300

    load_dotenv()

    file_path = os.path.realpath(__file__)
    folder_path = file_path.replace("main.py", "")

    parser = argparse.ArgumentParser()

    parser.add_argument("terminal_command_request")

    parser.add_argument(
        "-e",
        "--execute",
        help="DANGER! This will execute the command immediately. ",
        action="store_true",
    )
    parser.add_argument(
        "-x",
        "--hide_code",
        help="Hides the code/command that is shown to execute when executing code.",
        action="store_true",
    )
    parser.add_argument(
        "-s",
        "--set_key",
        help="Reset API key",
        type=str,
        required=False,
    )
    parser.add_argument(
        "-c", "--no_colour", help="No colour output", action="store_true"
    )

    args = parser.parse_args()

    api_key = os.getenv("OPENAI_API_KEY")

    if not api_key or args.set_key:
        print(
            styled(
                "Go to https://openai.com/api/ to generate your own API key.",
                Styles.blue,
            )
        )
        print(
            styled(
                "...also save this alias to your .zshrc or .bashrc file with:\n",
                Styles.blue,
            )
        )
        print(styled('alias gpt="python3 ~' + file_path, Styles.green))

        if args.set_key is not None:
            api_key = args.set_key
        else:
            api_key = input("Input your API key to be saved to '.env':")
        with open(folder_path + ".env", "w") as f:
            f.write(f'OPENAI_API_KEY = "{api_key}"')

    openai.api_key = api_key

    # Get the first command line argument
    terminal_command_request = args.terminal_command_request

    try:
        with open(folder_path + "request_history.json", mode="r") as f:
            history = json.loads(f.read())
    except FileNotFoundError:
        history: dict = {}

    if terminal_command_request in history.keys():
        answer = history[terminal_command_request]
    else:
        response = openai.Completion.create(
            model="text-davinci-003",
            prompt="Write a short bash script to "
                   + terminal_command_request
                   + "\n```bash\n#!/bin/bash",
            temperature=0,
            max_tokens=100,
            top_p=1,
            frequency_penalty=0,
            presence_penalty=0,
            stop=["```"],
        )

        answer = response["choices"][0]["text"].strip()

        # update cache
        history.update({terminal_command_request: answer})
        if len(history.keys()) > max_history:
            history = {
                i: history[i]
                for i in history
                if list(history.keys()).index(i) < max_history
            }

        with open(folder_path + "request_history.json", mode="w") as f:
            f.write(json.dumps(history))

    if args.execute:
        if not args.hide_code:
            print("⎽⎽⎽")
            if not args.no_colour:
                print(styled(" ▶ \n", Styles.green) + styled(answer, Styles.blue))
            else:
                print(" ▶ \n" + answer)
            print("‾‾‾")

        # shell_output = os.system(answer)
        shell_output = subprocess.run(answer, stdout=subprocess.PIPE, shell=True)

        print(shell_output.stdout.decode("utf-8"))
    else:
        if not args.no_colour:
            print(styled(answer, Styles.blue))
        else:
            print(answer)


# Numpy merupakan singkatan Numerical Python yang digunakan dalam memproses array... misi ngedit dikit
# Matplotlib digunakan untuk menggambarkan titik koordinat menjadi sebuah garis... misi mau coba ngedit lagi
import numpy as np
import matplotlib.pyplot as graphic

x1 = int(input('Masukan Nilai X1  : '))
y1 = int(input('Masukan Nilai Y1  : '))
x2 = int(input('Masukan Nilai X2  : '))
y2 = int(input('Masukan Nilai Y2  : '))
print('------------------------------------------------')
# koordinar awal x dan y
x = x1
y = y1
# membuat pengkondisian dengan beberapa syarat seperti :

# ---> Jika nilai x1 = x2 (garis vertikal), maka :
#       a. y = y + 1 dan x tetap
#       b. gambar titik kordinat (x,y)
#       c. tampilkan garis dari titik-titik koordinat yang terbentuk (selesai)

if x1 == x2:
    koor_x = []
    koor_y = []
    for i in range (0,y2,1):
        print('Garis yang di lewati yaitu', x, ',', y+i)
        koor_x.append(x)
        koor_y.append(y+i)
    graphic.plot(koor_x,koor_y)
    graphic.show()

# ---> Jika nilai y1 = y2 (garis horizontal), maka :
#       a. x = x + 1 dan y tetap
#       b. gambar titik kordinat (x,y)
#       c. tampilkan garis dari titik-titik koordinat yang terbentuk (selesai)

elif y1 == y2:
    koor_x = []
    koor_y = []
    for i in range (0,x2,1):
        print('Garis yang di lewati yaitu', x+i, ',', y)
        koor_x.append(x+i)
        koor_y.append(y)
    graphic.plot(koor_x,koor_y)
    graphic.show()
# ---> Jika ke-2 syarat di atas tidak memenuhi,  maka proses penentuan titik koordinat berlanjut ke:
#       1. hitung kemiringan garis dengan m = (y2 - y1) / (x2 - x1)
#       2. iterasi diulang sebanyak N kali
#       3. menentukan nilai i dengan persamaan y = m ( x - x1 ) + y1
#       4. lakukan pembulatan pada  nilai y
#       5. gambar titik (x, y(pembulatan))
#       6. nilai x didapatkan dari persamaan x = x + 1

else:
    koor_x = []
    koor_y = []
    gradient = (y2 - y1) / (x2 - x1)
    # N adalah banyaknya iterasi yang didapatkan dari persamaan dibawah ini apabila  x1 != x2 atau y1 != y2
    N = x2 - x1 + 1
    for i in range (0,N,1):
        bulat_y = gradient * (x - x1) + y1
        koord_Y = round(bulat_y)
        print('Garis yang di lewati oleh titik A da titik B yaitu ', x,',', koord_Y)
        koor_x.append(x)
        koor_y.append(koord_Y)
        x+=1
# syntaks apppend digunakan untuk menambah item ke dalam array atau list
# plt.plot digunakan agar mathplotlib dapat membuat titik pertemuan di masing-masing koordinat x,y
# plt.show digunakan agar mathplotlib dapat menampilkan garis dari titik titik kordinat yang telah di dapat

    graphic.plot(koor_x,koor_y)
    graphic.show()


#!/bin/python3

import time
import sys
import os
from PIL import Image

on = os.system('ps -aux | grep "wall.py" | wc -l')

if on > 0:
    os.system('killall wall.py')

file = sys.argv[1]

if file == "":
    print("Dame un parametro plox, un gif")

if not file.endswith(".gif"):
    print("Introduce un gif")

if os.path.isdir('/tmp/wall'):
    os.system('rm -r /tmp/wall && mkdir /tmp/wall')
else:
    os.system('mkdir /tmp/wall')

num_key_frames = int(os.popen("identify "+file+"| wc -l").read())

with Image.open(file) as im:
    for i in range(num_key_frames):
        im.seek(im.n_frames // num_key_frames * i)
        im.save('/tmp/wall/{}.png'.format(i))

times = os.popen("identify "+file+" | cut -d ':' -f 2").read().split("s")
timing = [s.replace("\n", "") for s in times]
while("" in timing) :
    timing.remove("")

while True:

    for pic in zip(range(num_key_frames), timing):
        print(pic)
        os.system('feh --bg-fill /tmp/wall/'+str(pic[0])+'.png')
        time.sleep(float(pic[1])*10)
    pic=[]


import tables
import numpy as np
import logging
logger = logging.getLogger('root')

class EnterExitPrint(object):
    """docstring for EnterExitPrint"""
    def __init__(self, enter, exit):
        super(EnterExitPrint, self).__init__()
        self.enter = enter
        self.exit = exit

    def __enter__(self):
        logger.info(self.enter)

    def __exit__(self ,type, value, traceback):
        logger.info(self.exit)

def count_events(files):
    n_events = 0
    for file in files:
        f = tables.open_file(file, 'r')
        n_events += f.root.label.shape[0]
        f.close()
    return n_events

def chunks(files, chunksize, max_q_size=4, shuffle=True, max_count=None):
    """Yield successive n-sized chunks from a and b."""
    i_chunk = 0
    for file in files:
        f = tables.open_file(file, 'r')
        nrows = f.root.label.nrows
        for istart in range(0,nrows,max_q_size*chunksize):
            i_chunk += 1
            if max_count and i_chunk > max_count:
                break
            a = np.array(f.root.img_pt[istart:istart+max_q_size*chunksize]) # Images
            b = np.array(f.root.label[istart:istart+max_q_size*chunksize]) # Labels
            if shuffle:
                c = np.c_[a.reshape(len(a), -1), b.reshape(len(b), -1)] # shuffle within queue size
                np.random.shuffle(c)
                test_images = c[:, :a.size//len(a)].reshape(a.shape)
                test_labels = c[:, a.size//len(a):].reshape(b.shape)
            else:
                test_images = a
                test_labels = b
            for jstart in range(0,len(test_labels),chunksize):
                yield normalize_and_rgb(test_images[jstart:jstart+chunksize].copy()),test_labels[jstart:jstart+chunksize].copy(), len(test_labels[jstart:jstart+chunksize].copy())
        f.close()

def normalize_and_rgb(images):
    #normalize image to 0-255 per image.
    image_sum = 1/np.sum(np.sum(images,axis=1),axis=-1)
    given_axis = 0
    # Create an array which would be used to reshape 1D array, b to have
    # singleton dimensions except for the given axis where we would put -1
    # signifying to use the entire length of elements along that axis
    dim_array = np.ones((1,images.ndim),int).ravel()
    dim_array[given_axis] = -1
    # Reshape b with dim_array and perform elementwise multiplication with
    # broadcasting along the singleton dimensions for the final output
    image_sum_reshaped = image_sum.reshape(dim_array)
    images = images*image_sum_reshaped*255

    # make it rgb by duplicating 3 channels.
    images = np.stack([images, images, images],axis=-1)
    return images

# def eval_performance(truths, predictions, times):


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Validator script for CS 2204 Homework submissions"""
import sys
import os
import traceback
from contextlib import redirect_stdout, redirect_stderr
from importlib.util import spec_from_file_location, module_from_spec
from io import StringIO
from math import isclose

import pycodestyle

#########################################################################
# Test infrastructure

def points(val):
    """
    Simple decorator to add a __points__ property to a function.

    Usage: @points(10)
    """

    def decorator(func):
        func.__points__ = val
        return func

    return decorator

def abort(func):
    """Simple decorator to add a __abort__ property to a function"""
    func.__abort__ = True
    return func

def import_file(filename, module_name=None):
    """Import a file with a given module name. Returns the module object"""
    if module_name is None:
        module_name, _ = os.path.splitext(os.path.basename(filename))
    spec = spec_from_file_location(module_name, filename)
    module = module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

def run_file(filename):
    """Runs the file at the top-level. Returns standard output, error tuple"""
    with StringIO() as stdout, StringIO() as stderr:
        with redirect_stdout(stdout), redirect_stderr(stderr):
            import_file(filename, "__main__")
            out = stdout.getvalue()
            err = stderr.getvalue()

    return out, err

def check_pep8_style(filename):
    """Checking PEP8 style for filename. Returns n_errors, messages tuple"""

    with StringIO() as out, redirect_stdout(out), redirect_stderr(sys.stdout):

        pep8_checker = pycodestyle.Checker(filename, show_source=True)
        pep8_errors = pep8_checker.check_all()
        pep8_msgs = out.getvalue()

    return pep8_errors, pep8_msgs

def validate(*tests):
    """Validation function"""
    total_score = 0
    divider = "-" * 45

    for test in tests:
        max_points = getattr(test, "__points__", 0)
        abort = False

        print(divider)
        prefix = f"{test.__doc__}:"
        print(f"{prefix:<{len(divider) - 10}}", end="")
        try:
            with StringIO() as out, redirect_stdout(out), redirect_stderr(
                sys.stdout
            ):

                partial = test()
                msg = out.getvalue()

        except:  # noqa
            with StringIO() as tb_out:
                traceback.print_exc(limit=-1, file=tb_out)
                msg = tb_out.getvalue()

            points = min(max_points, 0)
            abort = getattr(test, "__abort__", False)

        else:
            if partial is not None:
                points = partial
                if partial == 0:
                    abort = getattr(test, "__abort__", False)
            else:
                points = max(max_points, 0)

        suffix = "ok"
        if max_points <= 0:
            if points != 0:
                suffix = f"{points:+d} pts"
        else:
            suffix = f"{points}/{max_points} pts"
        print(f"{suffix:>10}")

        if msg:
            print(f"\n\n{msg}")

        total_score += points

        if abort:
            print("Aborting future tests. Fix this one, first!")
            break

    total_score = max(total_score, 0)
    print("=" * len(divider))
    print(f"Final score (estimated): {total_score:.0f} pts")

#########################################################################
# Assignment-specific tests

# Notes:
# You can set the max positive points for each test with @points()
# You can also set a negative value with @points, it is interpreted as penalty.
# If the test returns with
#  - None: max positive points are added, no penalties are applied
#  - Number: a given points are added, if negative, given penalties are applied
#  - Exception: no positive points are added, max penalties applied

@points(15)
def test_load_transactions():
    """Testing load_transactions"""
    module = import_file("fraud.py")
    transactions = module.load_transactions("transactions.txt")
    assert len(transactions) == 1000
    first_transaction = transactions[0]
    assert isinstance(first_transaction, module.Transaction)
    assert isinstance(first_transaction.amount, float)

@points(10)
def test_foreign_transactions():
    """Testing foreign_transactions"""
    module = import_file("fraud.py")
    transactions = module.load_transactions("transactions.txt")
    Transaction = module.Transaction

    expected = [
        Transaction(
            time="2019-07-13 17:02:56",
            amount=12.39,
            company="Fazekas Márton Kht.",
            phone="+36 24 197-2587",
        ),
        Transaction(
            time="2019-11-15 01:58:00",
            amount=2.53,
            company="Balog és Sándor Bt.",
            phone="+36 94 543-2730",
        ),
        Transaction(
            time="2019-12-31 07:55:39",
            amount=27.84,
            company="Kiss Kiss Nyrt.",
            phone="+36 49 013-1271",
        ),
        Transaction(
            time="2020-01-10 21:53:44",
            amount=27.62,
            company="Fazekas Márton Kht.",
            phone="+36 24 197-2587",
        ),
        Transaction(
            time="2020-09-25 05:31:19",
            amount=21.27,
            company="Farkas és Tóth Kft.",
            phone="+36 18 451-6142",
        ),
        Transaction(
            time="2020-11-25 07:01:18",
            amount=40.36,
            company="Farkas és Tóth Kft.",
            phone="+36 18 451-6142",
        ),
        Transaction(
            time="2021-03-22 03:26:15",
            amount=40.97,
            company="Kiss Kiss Nyrt.",
            phone="+36 49 013-1271",
        ),
        Transaction(
            time="2021-03-24 04:52:59",
            amount=32.43,
            company="Németh és Pataki Kkt.",
            phone="+36 40 980-1149",
        ),
        Transaction(
            time="2021-08-30 02:30:08",
            amount=150.32,
            company="Kiss Kiss Nyrt.",
            phone="+36 49 013-1271",
        ),
        Transaction(
            time="2021-12-24 16:17:35",
            amount=15.51,
            company="Farkas és társa Kft.",
            phone="+36 51 179-5649",
        ),
        Transaction(
            time="2022-01-10 14:36:17",
            amount=28.25,
            company="Horváth Kft.",
            phone="+36 59 701-8645",
        ),
    ]

    returned = module.foreign_transactions(transactions)
    assert set(expected) == set(returned)

@points(15)
def test_late_night_transactions():
    """Testing late_night_transactions"""
    module = import_file("fraud.py")
    transactions = module.load_transactions("transactions.txt")
    returned = module.late_night_transactions(transactions)
    Transaction = module.Transaction

    expected_subset = [
        Transaction(
            time="2019-10-08 01:54:52",
            amount=11.39,
            company="Boone-Perkins",
            phone="+1-608-511-7806x40298",
        ),
        Transaction(
            time="2020-07-14 02:57:21",
            amount=36.12,
            company="Blake-Mendez",
            phone="+1-719-444-6668",
        ),
        Transaction(
            time="2019-11-03 00:35:49",
            amount=36.19,
            company="Thomas Group",
            phone="+1-186-760-3400x01721",
        ),
        Transaction(
            time="2021-01-15 03:44:59",
            amount=27.45,
            company="Hayden PLC",
            phone="+1-549-237-6645x5206",
        ),
        Transaction(
            time="2020-07-09 04:01:25",
            amount=22.66,
            company="Taylor and Sons",
            phone="+1-828-897-7935x713",
        ),
    ]

    assert len(returned) == 239
    assert set(returned) > set(expected_subset)

@points(15)
def test_highest_transactions():
    """Testing highest_transactions"""
    module = import_file("fraud.py")
    transactions = module.load_transactions("transactions.txt")
    Transaction = module.Transaction

    expected_top_five = [
        Transaction(
            time="2019-11-09 19:35:55",
            amount=181.75,
            company="White-Carr",
            phone="+1-683-988-9471x923",
        ),
        Transaction(
            time="2021-08-30 02:30:08",
            amount=150.32,
            company="Kiss Kiss Nyrt.",
            phone="+36 49 013-1271",
        ),
        Transaction(
            time="2020-10-17 23:26:23",
            amount=78.2,
            company="Patel-Weeks",
            phone="+1-381-739-3537x971",
        ),
        Transaction(
            time="2019-08-21 16:19:46",
            amount=76.8,
            company="Clark, Kelley and Friedman",
            phone="+1-602-680-3985x7997",
        ),
        Transaction(
            time="2021-04-21 09:19:58",
            amount=76.73,
            company="Christensen LLC",
            phone="+1-171-332-0562",
        ),
    ]

    returned_top_five = module.highest_transactions(transactions, 5)
    assert set(returned_top_five) == set(expected_top_five)
    assert len(module.highest_transactions(transactions, 10)) == 10
    assert len(module.highest_transactions(transactions, 25)) == 25

@points(15)
def test_median_expense():
    """Testing median_expense"""
    module = import_file("fraud.py")
    transactions = module.load_transactions("transactions.txt")
    assert isclose(module.median_expense(transactions), 21.925)

@points(15)
def test_significant_transactions():
    """Testing significant_transactions"""
    module = import_file("fraud.py")
    transactions = module.load_transactions("transactions.txt")
    returned = module.late_night_transactions(transactions)
    Transaction = module.Transaction

    expected = [
        Transaction(
            time="2019-11-09 19:35:55",
            amount=181.75,
            company="White-Carr",
            phone="+1-683-988-9471x923",
        ),
        Transaction(
            time="2020-06-29 04:31:39",
            amount=47.73,
            company="Moore-Oliver",
            phone="+1-956-998-4999x4202",
        ),
        Transaction(
            time="2021-08-30 02:30:08",
            amount=150.32,
            company="Kiss Kiss Nyrt.",
            phone="+36 49 013-1271",
        ),
    ]

    returned = module.significant_transactions(transactions, 20)
    assert set(expected) == set(returned)
    assert len(module.significant_transactions(transactions, 5)) == 34
    assert len(module.significant_transactions(transactions, 10)) == 10
    assert len(module.significant_transactions(transactions, 15)) == 9

@points(15)
def test_fraudulent_transactions():
    """Testing fraudulent_transactions"""
    module = import_file("fraud.py")
    transactions = module.load_transactions("transactions.txt")
    Transaction = module.Transaction

    expected_fraudulent = [
        Transaction(
            time="2021-08-30 02:30:08",
            amount=150.32,
            company="Kiss Kiss Nyrt.",
            phone="+36 49 013-1271",
        )
    ]

    returned_fraudulent = module.fraudulent_transactions(transactions)
    assert set(expected_fraudulent) == set(returned_fraudulent)

@points(-10)
def test_author():
    """Checking author information"""
    module = import_file("fraud.py")
    author = getattr(module, "__author__", None)
    assert (
        isinstance(author, str) and author
    ), "__author__ variable is not set properly"

def test_pep8():
    """Checking PEP8 style"""

    n_errors, msgs = check_pep8_style("fraud.py")
    if n_errors:
        print(msgs)
        return -n_errors

if __name__ == "__main__":
    validate(
        test_load_transactions,
        test_foreign_transactions,
        test_late_night_transactions,
        test_highest_transactions,
        test_median_expense,
        test_significant_transactions,
        test_fraudulent_transactions,
        test_author,
        test_pep8,
    )


# -*- coding: utf-8 -*-
"""
Created on Mon Apr  8 12:29:39 2019

@author: grin
"""

import logging
import sys

class StreamToLogger(object):
    """
    Fake file-like stream object that redirects writes to a logger instance.
    """
    def __init__(self, logger, log_level=logging.INFO):
        self.logger = logger
        self.log_level = log_level
        self.linebuf = ''

    def close(self):
        logging.shutdown()

    def flush(self):
        pass

    def write(self, buf):
        for line in buf.rstrip().splitlines():
            self.logger.log(self.log_level, line.rstrip())

if (not '--verbose' in sys.argv) and (not '-v' in sys.argv):
    fh = logging.FileHandler('./log/out.log', 'a', 'utf-8')
    logging.basicConfig(
        level=logging.INFO,
        datefmt = '%Y-%m-%d;%H:%M:%S',
        format='%(asctime)s;%(levelname)s;%(name)s;%(message)s',
        #filename="out.log",
        handlers = [fh]
    )

# logging.getLogger('bokeh.server').setLevel(logging.WARNING)
logging.getLogger('tornado.access').disabled = True

def write_to_log(mes, mesType = 'info'):
    if (not '--verbose' in sys.argv) and (not '-v' in sys.argv):
        stdout_logger = logging.getLogger('STDOUT')
        sl1 = StreamToLogger(stdout_logger, logging.INFO)
        sys.stdout = sl1
        stderr_logger = logging.getLogger('STDERR')
        sl2 = StreamToLogger(stderr_logger, logging.ERROR)
        sys.stderr = sl2
        print(mes)
        for i in (sl1, sl2): i.close()
    else:
        print(mes)


import numpy as np
import matplotlib.pyplot as plt

# Given Parameters

N_fatalities = np.linspace(1,1000,1000)  # fatalities

P_df = 0.1; beta = 0.1

alpha = 2
k = 3
N_A = 100

r= 0.025
I = 5*10**6
B = 0.33

# Individual Risk

Pf_ind_risk = (beta*(10**-4))/P_df  # per year

# print('Acceptable Failure Probability: ', Pf_ind_risk)

# Societal Risk

C = ((beta*100)/(k*np.sqrt(N_A)))**2  # binomial distribution

Pf_SR = (C/(N_fatalities**alpha))

# Economic Risk

D_damage = (5*10**7)*N_fatalities

Pf_ER = (I*B*r)/(D_damage)

# Visualize

my_linewidth = 4

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

plt.yscale('log')
plt.xscale('log')
plt.plot(N_fatalities, Pf_SR, linewidth=my_linewidth, label='Societal Risk')
plt.plot(N_fatalities,Pf_ER, linewidth=my_linewidth, color='r', label='Economic Risk')
plt.axhline(Pf_ind_risk, linewidth=my_linewidth, color='g', label='Individual Risk')

plt.ylabel('Probability of Exceedance, $1-F_N(n)$')
plt.xlabel('Fatalities, N')
plt.ylim(10**(-7),1)

plt.legend(loc='upper right')

plt.savefig('risk_types_py.svg')


from ray import air, tune

def tune_hyper_param(algo, config, log_dir, iterations,
                     name,max_concurrent_trials=1):
    """
    Wrapper for the ray.tune.Tuner.fit function used for tuning the hyper-parameters
    :param algo: The algorithm to use for training
    :param config: The algorithm configs
    :param log_dir: Where to save logs and the checkpoints
    :param iterations: Number of iterations to tune for
    :param name: name of the training to group the logs
    :param max_concurrent_trials: maximum number of trial tuned in parallel
    :return: the results of the hyper-parameter tuning
    """
    tuner = tune.Tuner(
        algo,
        param_space=config,
        tune_config=tune.TuneConfig(
            metric="episode_reward_mean",
            mode="max",
            max_concurrent_trials=max_concurrent_trials
        ),
        run_config=air.RunConfig(
            name=name,
            local_dir=log_dir,

            stop={"training_iteration": iterations},
        ),

    )

    results = tuner.fit()
    return results


import datetime
import os
import numpy as np

# classifiers
from model import ToMatrix
from neural_network import NeuralNetwork
from twinsvm.TVSVM import TwinSVMClassifier
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB, GaussianNB
from sklearn.pipeline import Pipeline
from sklearn.preprocessing.data import MinMaxScaler
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.tree import DecisionTreeClassifier
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis, LinearDiscriminantAnalysis
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import RandomForestClassifier

# features
from features.word_based.word_counts import WordCounts
from features.character_based.number_of_characters import NumberOfCharacters
from features.character_based.alpha_ratio import AlphaRatio
from features.character_based.digit_ratio import DigitRatio
from features.character_based.whitespace_ratio import WhitespaceRatio
from features.character_based.special_chars_ratio import SpecialCharsRatio
from features.word_based.number_of_words import NumberOfWords
from features.word_based.short_words_ratio import ShortWordsRatio
from features.word_based.average_word_len import AverageWordLen
from features.word_based.unique_words_ratio import UniqueWordsRatio
from features.word_based.spam_words import SpamWords
from features.flesh_reading_score import FleschReadingEase
from sklearn.neural_network import MLPClassifier

dataset_dir = "enron-dataset"

def get_dataset():
    emails_dirs = [os.path.join(dataset_dir, f) for f in os.listdir(dataset_dir)]

    instances = []
    for emails_dir in emails_dirs:
        if not os.path.isdir(emails_dir): continue
        dirs = [os.path.join(emails_dir, f) for f in os.listdir(emails_dir)]

        for d in dirs:
            if not os.path.isdir(d): continue
            emails = [os.path.join(d, f) for f in os.listdir(d)]
            for mail in emails:
                if '.DS_Store' in mail: continue

                with open(mail, "rb") as mailDescriptor:
                    instances.append({
                        "content": mailDescriptor.read(),
                        "is_spam": int(mail.split(".")[-2] == 'spam'),
                        "features": {}
                    })

    # return instances[3000:4000]
    return instances

def get_features(train):
    features = [
        # ('word_counts', WordCounts(train)),
        ('number_of_characters', NumberOfCharacters()),
        ('alpha_ratio', AlphaRatio()),
        ('digit_ratio', DigitRatio()),
        ('whitespace_ratio', WhitespaceRatio()),
        ('special_chars_ratio', SpecialCharsRatio()),
        ('number_of_words', NumberOfWords()),
        ('short_words_ratio', ShortWordsRatio()),
        ('average_word_len', AverageWordLen()),
        ('unique_words_ratio', UniqueWordsRatio()),
        ('spam_words', SpamWords()),
        ('flesch_reading_score', FleschReadingEase()),
    ]
    return features

def get_pipeline(features):
    feature_names = []
    for feature in features:
        feature_names += feature[1].FEATS
    print(feature_names)
    return Pipeline(features + [
        ('transform', ToMatrix(features=feature_names)),
        ('norm', MinMaxScaler())
    ])

def run_classifiers(test, train):
    nnClassifier = NeuralNetwork(activation='sigmoid')

    params3 = {'Epsilon1': 0.1, 'Epsilon2': 0.1, 'C1': 1, 'C2': 1, 'kernel_type': 0, 'kernel_param': 1, 'fuzzy': 0}
    params6 = {'Epsilon1': 0.1, 'Epsilon2': 0.1, 'C1': 1, 'C2': 1,'kernel_type':1,'kernel_param': 1,'fuzzy' :1}

    classifiers = [
        # SVC(kernel="linear", C=0.025),
        # SVC(gamma=2, C=1),
        # TwinSVMClassifier(**params3),
        # TwinSVMClassifier(**params6),
        # MultinomialNB(),
        # KNeighborsClassifier(1),
        nnClassifier,
        # DecisionTreeClassifier(max_depth=5),
        # RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),
        # MLPClassifier(alpha=1),
        # AdaBoostClassifier(),
        # GaussianNB(),
        # LinearDiscriminantAnalysis(),
        # QuadraticDiscriminantAnalysis(),
    ]

    print("Transforming data to features...")
    #  get pipeline of features and generate them
    pipeline = get_pipeline(get_features(train))

    # X_train = np.load('enron_word_cnt_train_features_matrix.npy')
    # trainLabels = np.load('enron_word_cnt_train_labels.npy')
    X_train = pipeline.fit_transform(train)
    trainLabels = [instance['is_spam'] for instance in train]
    # np.save('enron_train_features_matrix.npy', X_train)
    # np.save('enron_train_labels.npy', trainLabels)

    # X_test = np.load('enron_word_cnt_test_features_matrix.npy')
    # testLabels = np.load('enron_word_cnt_test_labels.npy')
    X_test = pipeline.fit_transform(test)
    testLabels = [instance["is_spam"] for instance in test]
    # np.save('enron_test_features_matrix.npy', X_test)
    # np.save('enron_test_labels.npy', testLabels)

    nnClassifier.X_test = np.array(X_test)
    nnClassifier.Y_test = np.array(testLabels)

    print("Finished transforming data to features...")

    for classifier in classifiers:
        print("\n==================== {0} ====================".format(str(classifier.__class__.__name__)))

        print("Start training...")
        startTime = datetime.datetime.now()
        classifier.fit(X_train, trainLabels)
        endTime = datetime.datetime.now()
        print("Finished training for", endTime-startTime)

        print("Starting prediction...")
        startTime = datetime.datetime.now()
        predictedLabels = classifier.predict(X_test)
        endTime = datetime.datetime.now()
        print("Finished prediction for", endTime-startTime)

        confusionMatrix = confusion_matrix(testLabels, predictedLabels)
        precision = confusionMatrix[1, 1] / (confusionMatrix[1, 1] + confusionMatrix[0, 1])
        recall = confusionMatrix[1,1] / (confusionMatrix[1,1] + confusionMatrix[1,0])
        f1 = 2 * (precision * recall) / (precision + recall)
        accuracy = ((confusionMatrix[0, 0] + confusionMatrix[1, 1]) / len(predictedLabels)) * 100

        print("\nConfusion matrix:\n{0}\n".format(confusionMatrix))
        print("Precision: {0}".format(round(precision, 2)))
        print("Recall: {0}".format(round(recall, 2)))
        print("F1: {0}".format(round(f1, 2)))
        print("Accuracy: {0}".format(round(accuracy, 2)))

if __name__ == "__main__":
    train, test = train_test_split(get_dataset(), test_size=0.40)
    predictedLabels = run_classifiers(test, train)


from .client import PORT

from helper.IPC import Server, FuncCall, Connection, Response, Packet
from helper.main_handler import main_handler
from helper.report_exceptions import report_exception

from .nearcrowd_account import NearCrowdAccount
from helper.provider_config import provider
from .accounts_db import Accounts
import helper.db_config as db_config
from .locks import get_lock
from .functions import *
import asyncio
from typing import Any
import sd_notify

server = Server(PORT, Connection, report_exception)
TIMEOUT = 30

async def get_account(account_id: str) -> NearCrowdAccount | None:
	try:
		private_key = await Accounts.get_key(account_id)
		return NearCrowdAccount(account_id, private_key)
	except Exception:
		return None

async def apply_accountless(call: FuncCall):
	return await call.apply(globals()[call.name])

async def apply_for_accounts(accounts: NearCrowdAccount | list[NearCrowdAccount], call: FuncCall):
	return await asyncio.gather(*[call.apply(globals()[call.name], i) for i in accounts])

async def get_accounts_list() -> list[NearCrowdAccount]:
	return [NearCrowdAccount(account_id, private_key) for account_id, private_key in await Accounts.get_accounts_credentials()]

async def lock_account(account: NearCrowdAccount):
	await get_lock(account.account_id).acquire()
	return account

async def lock_accounts(accounts: list[NearCrowdAccount]) -> list[NearCrowdAccount]:
	if len(accounts) == 0:
		return []

	tasks = [asyncio.create_task(lock_account(i)) for i in accounts]
	done, pending = await asyncio.wait(tasks)
	for i in pending:
		i.cancel()
	return [i.result() for i in done]

def unlock(accounts: list[NearCrowdAccount]):
	for i in accounts:
		get_lock(i.account_id).release()

async def get_locked_accounts(account_ids: list[str] | None) -> list[NearCrowdAccount]:
	assert isinstance(account_ids, list | None), type(account_ids)

	if account_ids is None:
		accounts = await get_accounts_list()
	else:
		accounts = await asyncio.gather(*[get_account(i) for i in account_ids])

	accounts = list(filter(lambda x: x is not None, accounts))
	return await lock_accounts(accounts)

def get_ids(accounts: list[NearCrowdAccount]) -> list[str]:
	return [i.account_id for i in accounts]

class ConnectionHandler:
	def __init__(self, conn: Connection) -> None:
		self.conn = conn
		self.accounts = []

	async def proceed_client(self):
		tasks = []
		while self.conn.is_active():
			try:
				packet: Packet = await self.conn.read(timeout=TIMEOUT)
				assert isinstance(packet, Packet), type(packet)
				tasks.append(asyncio.create_task(self._proceed_call(Response(self.conn, packet))))
			except TimeoutError:
				if all([task.done() for task in tasks]):
					print('Probably forgot to close connection', self.accounts)
					break
				else:
					continue
			except Exception:
				break

		for task in tasks:
			task.cancel()
		unlock(self.accounts)
		await self.conn.close()

	async def _proceed_call(self, resp: Response):
		await resp.respond(await self.execute_call(resp.data))

	async def execute_call(self, call: FuncCall) -> Any:
		assert isinstance(call, FuncCall), type(call)

		if call.name in ('set_accounts'):
			unlock(self.accounts)
			self.accounts = await call.apply(get_locked_accounts)
			return get_ids(self.accounts)

		if call.name in ('create_account', 'is_connected', 'get_coef', 'get_access_keys', 'verify_keys'):
			return await apply_accountless(call)

		assert call.name in ('query'), call.name
		result = await apply_for_accounts(self.accounts, call)
		return {k.account_id: v for k, v in zip(self.accounts, result)}

@server.on_connect
async def on_client_connect(conn: Connection):
	c = ConnectionHandler(conn)
	await c.proceed_client()

async def start():
	provider.start()
	await db_config.start()
	await server.start()
	sd_notify.Notifier().ready()

	await server.run()

async def stop():
	await provider.close()
	await server.stop()

if __name__ == '__main__':
	main_handler(start, report_exception, server.close)


#Code referenced from TA Alek Bedard
from flask import Flask, jsonify, request
import sys

app = Flask(__name__)

@app.route('/')
def light():
    if len(sys.argv) < 2:
         return "Dude! You are not curling from a server!!"

    num = 10
    counter = 30
    while(counter < 30):
        num = num*num*num
        counter = counter - 1
    return "from" + sys.argv[1] + "\n"

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)


from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view

from product.models import Product
from online_system.api.serializers import ProductSerializer

@api_view(['GET',])
def api_detail_product_view(request, id):

    try:
        products = Product.objects.get(id=id)
    except Product.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    serializer = ProductSerializer(products)
    return Response(serializer.data)

@api_view(['PUT',])
def api_update_product_view(request, id):

    try:
        product = Product.objects.get(id=id)
    except Product.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    serializer = ProductSerializer(product, data=request.data)
    data = {}
    if serializer.is_valid():
        serializer.save()
        data['success'] = "update successfull"
        return Response(data=data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['DELETE',])
def api_delete_product_view(request, id):

    try:
        products = Product.objects.get(id=id)
        print(products)
    except Product.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    operations = product.delete()
    data = {}
    if operations:
        data['success'] = 'deleted successfull'
    else:
        data['falilure'] = 'deleted unsuccessfull'
    return Response(data=data)


from PyQt5 import QtCore, QtGui, QtWidgets

from Start.DB_Configuration import exe_query

class Ui_Admin_Remove_Employee_window(object):

    def __init__(self):
        self.res = []
        self.staff_id = -1

    def setupUi(self, Admin_Remove_Employee_window):
        Admin_Remove_Employee_window.setObjectName("Admin_Remove_Employee_window")
        Admin_Remove_Employee_window.resize(1303, 783)
        Admin_Remove_Employee_window.setCursor(QtGui.QCursor(QtCore.Qt.ClosedHandCursor))
        Admin_Remove_Employee_window.setStyleSheet("background-color: rgb(255, 238, 249);")
        self.Remove_Employee_header_L = QtWidgets.QLabel(Admin_Remove_Employee_window)
        self.Remove_Employee_header_L.setGeometry(QtCore.QRect(470, 30, 401, 51))
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.Remove_Employee_header_L.setFont(font)
        self.Remove_Employee_header_L.setCursor(QtGui.QCursor(QtCore.Qt.ClosedHandCursor))
        self.Remove_Employee_header_L.setStyleSheet("background-color: rgb(255, 97, 100);")
        self.Remove_Employee_header_L.setAlignment(QtCore.Qt.AlignCenter)
        self.Remove_Employee_header_L.setObjectName("Remove_Employee_header_L")
        self.Remove_Employee_TableWidget = QtWidgets.QTableWidget(Admin_Remove_Employee_window)
        self.Remove_Employee_TableWidget.setGeometry(QtCore.QRect(30, 120, 1231, 461))
        self.Remove_Employee_TableWidget.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.Remove_Employee_TableWidget.setObjectName("Remove_Employee_TableWidget")
        self.Remove_Employee_TableWidget.setColumnCount(8)
        self.Remove_Employee_TableWidget.setRowCount(0)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        item.setFont(font)
        self.Remove_Employee_TableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        item.setFont(font)
        item.setBackground(QtGui.QColor(120, 105, 110))
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        item.setForeground(brush)
        self.Remove_Employee_TableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        item.setFont(font)
        self.Remove_Employee_TableWidget.setHorizontalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        item.setFont(font)
        self.Remove_Employee_TableWidget.setHorizontalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        item.setFont(font)
        self.Remove_Employee_TableWidget.setHorizontalHeaderItem(4, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        item.setFont(font)
        self.Remove_Employee_TableWidget.setHorizontalHeaderItem(5, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        item.setFont(font)
        self.Remove_Employee_TableWidget.setHorizontalHeaderItem(6, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        item.setFont(font)
        self.Remove_Employee_TableWidget.setHorizontalHeaderItem(7, item)
        self.Remove_Employee_TableWidget.horizontalHeader().setDefaultSectionSize(150)
        self.Remove_Employee_remove_PB = QtWidgets.QPushButton(Admin_Remove_Employee_window)
        self.Remove_Employee_remove_PB.setGeometry(QtCore.QRect(960, 630, 251, 71))
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.Remove_Employee_remove_PB.setFont(font)
        self.Remove_Employee_remove_PB.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.Remove_Employee_remove_PB.setAcceptDrops(False)
        self.Remove_Employee_remove_PB.setAutoFillBackground(False)
        self.Remove_Employee_remove_PB.setStyleSheet("background-color: rgb(138, 201, 255);")
        self.Remove_Employee_remove_PB.setObjectName("Remove_Employee_remove_PB")
        self.Remove_Employee_Staff_id_LE = QtWidgets.QLineEdit(Admin_Remove_Employee_window)
        self.Remove_Employee_Staff_id_LE.setGeometry(QtCore.QRect(340, 640, 321, 51))
        self.Remove_Employee_Staff_id_LE.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.Remove_Employee_Staff_id_LE.setObjectName("Remove_Employee_Staff_id_LE")
        self.Remove_Employee_Staff_id_L = QtWidgets.QLabel(Admin_Remove_Employee_window)
        self.Remove_Employee_Staff_id_L.setGeometry(QtCore.QRect(130, 640, 181, 41))
        font = QtGui.QFont()
        font.setFamily("Comic Sans MS")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.Remove_Employee_Staff_id_L.setFont(font)
        self.Remove_Employee_Staff_id_L.setCursor(QtGui.QCursor(QtCore.Qt.ClosedHandCursor))
        self.Remove_Employee_Staff_id_L.setStyleSheet("background-color: rgb(255, 201, 5);")
        self.Remove_Employee_Staff_id_L.setAlignment(QtCore.Qt.AlignCenter)
        self.Remove_Employee_Staff_id_L.setObjectName("Remove_Employee_Staff_id_L")

        self.retranslateUi(Admin_Remove_Employee_window)
        QtCore.QMetaObject.connectSlotsByName(Admin_Remove_Employee_window)

        # TODO:SHOW_LIST_ALL_EMPLOYEE_CLICKED
        self.show_all_of_employee()

        # TODO:REMOVE_EMPLOYEE_CLICKED
        self.Remove_Employee_remove_PB.clicked.connect(self.remove_staff)

    def retranslateUi(self, Admin_Remove_Employee_window):
        _translate = QtCore.QCoreApplication.translate
        Admin_Remove_Employee_window.setWindowTitle(_translate("Admin_Remove_Employee_window", "Remove A Employee"))
        self.Remove_Employee_header_L.setText(_translate("Admin_Remove_Employee_window", "List of Employee"))
        item = self.Remove_Employee_TableWidget.horizontalHeaderItem(0)
        item.setText(_translate("Admin_Remove_Employee_window", "Staff No. #"))
        item = self.Remove_Employee_TableWidget.horizontalHeaderItem(1)
        item.setText(_translate("Admin_Remove_Employee_window", "First name"))
        item = self.Remove_Employee_TableWidget.horizontalHeaderItem(2)
        item.setText(_translate("Admin_Remove_Employee_window", "Last name"))
        item = self.Remove_Employee_TableWidget.horizontalHeaderItem(3)
        item.setText(_translate("Admin_Remove_Employee_window", "Email"))
        item = self.Remove_Employee_TableWidget.horizontalHeaderItem(4)
        item.setText(_translate("Admin_Remove_Employee_window", "National id"))
        item = self.Remove_Employee_TableWidget.horizontalHeaderItem(5)
        item.setText(_translate("Admin_Remove_Employee_window", "Password"))
        item = self.Remove_Employee_TableWidget.horizontalHeaderItem(6)
        item.setText(_translate("Admin_Remove_Employee_window", "Salary"))
        item = self.Remove_Employee_TableWidget.horizontalHeaderItem(7)
        item.setText(_translate("Admin_Remove_Employee_window", "Start date"))
        self.Remove_Employee_remove_PB.setText(_translate("Admin_Remove_Employee_window", "Remove"))
        self.Remove_Employee_Staff_id_L.setText(_translate("Admin_Remove_Employee_window", "Staff No.#"))

    def show_all_of_employee(self):
        self.res = exe_query(f"""
                                SELECT Staff_ID,Staff_Firstname,Staff_Lastname,Staff_Password,Staff_Email,
                                 Staff_National_ID,Staff_Salary,Staff_StartDate,Staff_Role_Recep_Cleaning
                                 FROM staff_information WHERE Staff_ID <> -1;
                            """)

        row = 0
        self.Remove_Employee_TableWidget.setRowCount(len(self.res))
        for data in self.res:
            self.Remove_Employee_TableWidget.setItem(row, 0, QtWidgets.QTableWidgetItem(str(data[0])))
            self.Remove_Employee_TableWidget.setItem(row, 1, QtWidgets.QTableWidgetItem(str(data[1])))
            self.Remove_Employee_TableWidget.setItem(row, 2, QtWidgets.QTableWidgetItem(str(data[2])))
            self.Remove_Employee_TableWidget.setItem(row, 3, QtWidgets.QTableWidgetItem(str(data[3])))
            self.Remove_Employee_TableWidget.setItem(row, 4, QtWidgets.QTableWidgetItem(str(data[4])))
            self.Remove_Employee_TableWidget.setItem(row, 5, QtWidgets.QTableWidgetItem(str(data[5])))
            self.Remove_Employee_TableWidget.setItem(row, 6, QtWidgets.QTableWidgetItem(str(data[6])))
            self.Remove_Employee_TableWidget.setItem(row, 7, QtWidgets.QTableWidgetItem(str(data[7])))

            row += 1

    def remove_staff(self):

        if self.Remove_Employee_Staff_id_LE.text() != '':
            self.staff_id = int(self.Remove_Employee_Staff_id_LE.text())
            exe_query(f"""
                        UPDATE cleaning_service SET Staff_ID = -1 WHERE Staff_ID = '{self.staff_id}';
                     """)
            exe_query(f"""
                        UPDATE reservation SET Staff_ID = -1 WHERE Staff_ID = '{self.staff_id}';
                     """)
            exe_query(f"""
                        DELETE FROM staff_information WHERE Staff_ID = '{self.staff_id}';
                     """)


#coding=utf-8
from functools import partial
from OCC.Core.Quantity import Quantity_Color, Quantity_TOC_RGB
from OCC.Core.TopoDS import TopoDS_Compound
from OCC.Extend.DataExchange import read_step_file_with_names_colors
from OCC.Extend.TopologyUtils import TopologyExplorer
from PyQt5.QtWidgets import QApplication, QComboBox, QTableView
from PyQt5 import QtWidgets,QtGui,QtCore
from PyQt5.QtGui import QFont, QBrush, QPixmap, QMovie
from graphics import GraphicsView, GraphicsPixmapItem
from module.CreateParameter import *
from module.CreateParameter import Create_Speed_reducer_kbr_series_1to1
import copy,time,sys
from ui import Process_message
#from module import source
from multiprocessing import  Queue,Manager
from module import FuctionModule,assemble
import  threading
from module import SolidworksModule

def test(func):
    def inner():
        print('running')
    return inner

class Process_message(QtWidgets.QMainWindow, Process_message.Ui_Form):  # 零件加载过程界面
    def __init__(self, parent=None):
        super(Process_message, self).__init__(parent)
        self.setupUi(self)
        # self.pushButton=QtWidgets.QPushButton()
        # self.pushButton.setGeometry(0,0,10,10)

    def process_message_show(self):
        pass
        self.label.setObjectName("label")
        self.gif = QMovie(':/picture/icons/loading.gif')
        self.label.setMovie(self.gif)
        self.gif.start()
        self.show()
def Create_ProcessBar(self, ButtonId=None):  # 过程处理函数 获取数据生成所需的界面                步骤1
        try:
            # -----------------清空3D显示界面
            self.statusbar.showMessage("状态：软件运行正常")
            self.canva._display.EraseAll()
            self.canva._display.hide_triedron()
            self.canva._display.display_triedron()
            self.canva._display.Repaint()
            # ------------------------------
            self.message = Process_message()  #
            self.tableWidget_2.clear()  # 清空原来的数据
            self.tableWidget_2.clearSpans()

            self.tableWidget_2.setHorizontalHeaderLabels(['选项', '列表值', '备注'])
            textFont = QFont()
            textFont.setFamily("微软雅黑")
            textFont.setPointSize(11)
            self.tableWidget_2.setEditTriggers(QTableView.NoEditTriggers)  # 不可编辑  # 表格不可编辑
            # 选型
            headItem = self.tableWidget_2.horizontalHeaderItem(0)  # 获得水平方向表头的Item对象
            headItem.setFont(textFont)  # 设置字体
            brush = QtGui.QBrush(QtGui.QColor(85, 85, 255))
            headItem.setForeground(brush)  # 设置文字颜色
            # 列表值
            headItem = self.tableWidget_2.horizontalHeaderItem(1)  # 获得水平方向表头的Item对象
            headItem.setFont(textFont)  # 设置字体
            brush = QtGui.QBrush(QtGui.QColor(255, 170, 0))
            headItem.setForeground(brush)  # 设置文字颜色
            # 备注
            headItem = self.tableWidget_2.horizontalHeaderItem(2)  # 获得水平方向表头的Item对象
            headItem.setFont(textFont)  # 设置字体
            brush = QtGui.QBrush(QtGui.QColor(255, 0, 127))
            headItem.setForeground(brush)  # 设置文字颜色
            if ButtonId in ["KS系列(孔输出)","KS系列(孔输出法兰)","KS系列(轴输出)","KS系列(轴输出法兰)"] :
                self.ButtonId = ButtonId
                self.Ceate_combox_table(ButtonId)#建立
                # 将所有的combox 选项和型号槽绑定 只要选项更新就会选项产品参数
                for i in self.combox_list:
                    if self.combox_list.index(i)==7:
                        i.currentTextChanged.connect(self.Ceate_show_3d)#刷新
                        continue
                    if self.combox_list.index(i)==1:
                        i.currentTextChanged.connect(self.show_technical_information)#根据combox内容刷新技术资料
                    i.currentTextChanged.connect(self.Ceate_product_parameter_table_and_show_3d)#刷新
            elif ButtonId in ["KBR系列(1-1)","KBR系列(1-2)","KB系列"] :
                self.ButtonId = ButtonId
                self.Ceate_combox_table(ButtonId)#建立
                # 将所有的combox 选项和型号槽绑定 只要选项更新就会选项产品参数
                for i in self.combox_list:
                    if self.combox_list.index(i)==7:
                        i.currentTextChanged.connect(self.Ceate_show_3d)#刷新
                        continue
                    if self.combox_list.index(i)==2:
                        i.currentTextChanged.connect(self.combox_refresh_function)#根据combox内容刷新combox刷新
                        continue
                    if self.combox_list.index(i)==1:
                        i.currentTextChanged.connect(self.show_technical_information)#根据combox内容刷新技术资料
                    i.currentTextChanged.connect(self.Ceate_product_parameter_table_and_show_3d)#刷新
            elif ButtonId in ["EDA系列"] :
                self.ButtonId = ButtonId
                self.Ceate_combox_table(ButtonId)#建立
                # 将所有的combox 选项和型号槽绑定 只要选项更新就会选项产品参数
                for i in self.combox_list:
                    if self.combox_list.index(i)==10:
                        i.currentTextChanged.connect(self.Ceate_show_3d)#刷新
                        continue
                    if self.combox_list.index(i)==1:
                        i.currentTextChanged.connect(self.combox_refresh_function)#刷新
                        i.currentTextChanged.connect(self.show_technical_information)  # 根据combox内容刷新技术资料
                        continue
                    i.currentTextChanged.connect(self.Ceate_product_parameter_table_and_show_3d)#刷新
            elif ButtonId in ["ECA系列"] :
                self.ButtonId = ButtonId
                self.Ceate_combox_table(ButtonId)#建立
                # 将所有的combox 选项和型号槽绑定 只要选项更新就会选项产品参数
                for i in self.combox_list:
                    if self.combox_list.index(i)==10:
                        i.currentTextChanged.connect(self.Ceate_show_3d)#刷新
                        continue
                    if self.combox_list.index(i)==1:
                        i.currentTextChanged.connect(self.combox_refresh_function)#刷新
                        i.currentTextChanged.connect(self.show_technical_information)  # 根据combox内容刷新技术资料
                        continue
                    i.currentTextChanged.connect(self.Ceate_product_parameter_table_and_show_3d)#刷新
                    pass
            self.sinal = 1
            self.message.process_message_show()
        except Exception as e:
            print(e)

        if True:
            if self.sinal == 1:
                try:
                    pass
                except:
                    pass
                self.show_parameter()
                self.sinal = 0
                self.message.close()
                # break
def Ceate_combox_table(self, ButtonId=None):  # 生成选项卡表格   步骤二
        '''
        1.建立选型列表名称
        2.获取各个选项的值
        3.
        '''
        try:

            # ------------------------------------------------------------KS系列
            if ButtonId in ["KS系列(孔输出)"]:
                self.boll_SCcrew = Create_Speed_reducer_ks_hole_output()#建立类
            elif ButtonId in["KS系列(轴输出)"]:
                self.boll_SCcrew = Create_Speed_reducer_ks_axle_output()  # 建立类
            elif ButtonId in["KS系列(孔输出法兰)"]:
                self.boll_SCcrew = Create_Speed_reducer_ks_hole_flank_output()  # 建立类
            elif ButtonId in["KS系列(轴输出法兰)"]:
                self.boll_SCcrew = Create_Speed_reducer_ks_axle_flank_output()  # 建立类

            #---------------------------------------------------------------KBR系列
            if ButtonId in ["KBR系列(1-1)"]:
                self.boll_SCcrew = Create_Speed_reducer_kbr_series_1to1()#建立类
            elif ButtonId in["KBR系列(1-2)"]:
                self.boll_SCcrew = Create_Speed_reducer_kbr_series_1to2()#建立类

            #----------------------------------------------------------------KB系列
            if ButtonId in ["KB系列"]:
                self.boll_SCcrew = Create_Speed_reducer_kb_series()#建立类

            #----------------------------------------------------------------EDA系列
            if ButtonId in ["EDA系列"]:
                self.boll_SCcrew = Create_transformer_EDA_series()#建立类
            # ----------------------------------------------------------------ECA系列
            if ButtonId in ["ECA系列"]:
                self.boll_SCcrew = Create_transformer_ECA_series()# 建立类

            all_combox_list = self.boll_SCcrew.Create_combox_list()
            self.order_code_position = len(all_combox_list) - 1  # 订购码的位置
            self.tableWidget_2.setRowCount(len(all_combox_list))  # 参数表格设置.
            self.combox_list = []
            blank_size=self.tableWidget_2.geometry().width()/3
            self.tableWidget_2.setColumnWidth(1, blank_size)  # 手动设置列宽
            self.tableWidget_2.setColumnWidth(0, blank_size)  # 手动设置列宽
            self.tableWidget_2.setColumnWidth(2, blank_size)  # 手动设置列宽
            # ------------------------------------------------先生成combox选项卡
            for i in all_combox_list:  # 遍历生成所有的选项
                comBox = QComboBox()
                comBox.setFont(QFont("微软雅黑", 9, QFont.Black))
                comBox.setStyleSheet("QComboBox{color:rgb(0,0,0)}")
                self.combox_list.append(comBox)
                # comBox.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
                if type(i).__name__ == "dict":  # 如果室字典类型则生成combox
                    for key, value in i.items():
                        newItem = QtWidgets.QTableWidgetItem(str(key))
                        newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
                        newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
                        newItem.setFont(QFont("微软雅黑", 9, QFont.Black))  # 设置字体
                        newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))
                        self.tableWidget_2.setItem(all_combox_list.index(i), 0, newItem)  # 代码
                        for k in value:
                            self.combox_list[all_combox_list.index(i)].addItem(k)
                    self.tableWidget_2.setCellWidget(all_combox_list.index(i), 1,
                                                     self.combox_list[all_combox_list.index(i)])
                    comBox.destroy()
                else:  # f否则生成普通单元格
                    pass
                    newItem = QtWidgets.QTableWidgetItem(str(i[0]))
                    newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
                    newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
                    newItem.setFont(QFont("微软雅黑", 9, QFont.Black))
                    newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))
                    self.tableWidget_2.setItem(all_combox_list.index(i), 0, newItem)  # 代码
                    # ------------------------------------------------------------------------
                    newItem = QtWidgets.QTableWidgetItem(str(i[1]))
                    newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
                    newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
                    newItem.setFont(QFont("微软雅黑", 9, QFont.Black))
                    newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))
                    self.tableWidget_2.setItem(all_combox_list.index(i), 1, newItem)  # 代码
                # 设置备注单元格的颜色
                newItem = QtWidgets.QTableWidgetItem(str(""))
                newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
                newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
                # newItem.setFont(QFont("song", 9,QFont.Black))
                self.tableWidget_2.setItem(all_combox_list.index(i), 2, newItem)  # 代码

            # ----------------------------------------------------生成产品参数的tablewidget

        except:
            pass

def Create_product_parameter_table_and_show_3d(self, QClor=1, dict={}, start=0):  # 生成/更新产品参数表格    #步骤3
    '''
    根据combox选项生成产品参数列表
    '''
    try:
        QApplication.processEvents()
        self.aCompound = TopoDS_Compound()

    except:
        pass
    start = len(self.combox_list)  # 确定起始位置
    self.combox_current_text_list = []
    for i in self.combox_list:
        if i.currentText() == "":
            continue
        self.combox_current_text_list.append(i.currentText())  # 装有combox的列表
    try:
        if self.ButtonId in ["KS系列(孔输出)","KS系列(孔输出法兰)","KS系列(轴输出)","KS系列(轴输出法兰)"]:
            self.combox_list[7].clear()  # 清楚原来的combobox选项
            series ="KS"+self.combox_current_text_list[0]  # 机座号
            additems = self.boll_SCcrew.path_dict["FX" + str(series)]  # 对应机座号的可选模型的
            self.filename_dict = {}
            additem_list = []
            for i in range(len(additems)):
                additem = additems[i].split("\\")[-1].replace(".step", "")
                self.filename_dict[additem] = copy.deepcopy(additems[i])
                additem_list.append(additem)
            self.combox_list[7].addItems(additem_list)  # 根据选项变换combox里的内容
            series_1 = self.combox_current_text_list[1]  # 减速比
            dict = self.boll_SCcrew.series[str(series)]  # 机座号选型列表
            dict["额定承载扭矩T2N(Nm)"] = self.boll_SCcrew.T2N[str(series_1)][series]
            dict["最大承载扭矩T2B(Nm)"] = str(float(self.boll_SCcrew.T2N[str(series_1)][series]) * 1.5)
            dict["背隙"] = self.boll_SCcrew.arcmin[str(series_1)]
            dict["输出轴许可径向力"] = self.boll_SCcrew.output_radial_force[str(series_1)][series]
            dict["制锁"] = self.boll_SCcrew.self_lock[str(series_1)]

        elif self.ButtonId in ["KBR系列(1-1)","KBR系列(1-2)"]:
            self.combox_list[7].clear()  # 清楚原来的combobox选项
            series = "KBR"+self.combox_current_text_list[0]  # 机座号
            additems = self.boll_SCcrew.path_dict["FX"+str(series)]  # 对应机座号的可选模型的
            self.filename_dict = {}
            additem_list = []
            for i in range(len(additems)):
                additem = additems[i].split("\\")[-1].replace(".step", "")
                self.filename_dict[additem] = copy.deepcopy(additems[i])
                additem_list.append(additem)
            self.combox_list[7].addItems(additem_list)  # 根据选项变换combox里的内容

            series_1 = self.combox_current_text_list[1]  # 段数
            series_2=self.combox_current_text_list[2] #减速比
            #series_3 = self.boll_SCcrew.series[str(series)]  # 机座号选型列表
            dict["额定输出扭矩T2N(Nm)"] = self.boll_SCcrew.T2N[series_1][series_2][series]
            dict["最大输出扭矩(Nm)"] = str(float(self.boll_SCcrew.T2N[series_1][series_2][series])*2)
            dict["额定输入转速(rpm)"] = self.boll_SCcrew.n1N[str(series)]
            dict["最大输入转速(rpm)"] = self.boll_SCcrew.n1B[str(series)]
            dict["背隙"] = self.boll_SCcrew.arcmin[self.combox_current_text_list[4]][series_1][series_2]
            dict["容许径向力(N)"] = self.boll_SCcrew.F1[str(series)]
            dict["容许轴向力(N)"] = self.boll_SCcrew.F2[str(series)]
            dict["效率(%)"] = self.boll_SCcrew.power[str(series_1)][series_2]
            dict["噪音(DB)"] = self.boll_SCcrew.dB[str(series)]
            dict["重量(Kg)"] = self.boll_SCcrew.weight[series_1][series]
            dict["减速机转动惯量(kg.cm2)"] = self.boll_SCcrew.Moment_inertia[series_1][series_2][series]

        elif self.ButtonId in ["KB系列"]:
            self.combox_list[7].clear()  # 清楚原来的combobox选项
            series = "KB"+self.combox_current_text_list[0]  # 机座号
            additems = self.boll_SCcrew.path_dict["FX"+str(series)]  # 对应机座号的可选模型的
            self.filename_dict = {}
            additem_list = []
            for i in range(len(additems)):
                additem = additems[i].split("\\")[-1].replace(".step", "")
                self.filename_dict[additem] = copy.deepcopy(additems[i])
                additem_list.append(additem)
            self.combox_list[7].addItems(additem_list)  # 根据选项变换combox里的内容

            series_1 = self.combox_current_text_list[1]  # 段数
            series_2=self.combox_current_text_list[2] #减速比

            #series_3 = self.boll_SCcrew.series[str(series)]  # 机座号选型列表
            dict["额定输出扭矩T2N(Nm)"] = self.boll_SCcrew.T2N[series_1][series_2][series]
            dict["最大输出扭矩(Nm)"] = str(float(self.boll_SCcrew.T2N[series_1][series_2][series])*2)
            dict["额定输入转速(rpm)"] = self.boll_SCcrew.n1N[str(series)]
            dict["最大输入转速(rpm)"] = self.boll_SCcrew.n1B[str(series)]
            dict["背隙"] = self.boll_SCcrew.arcmin[self.combox_current_text_list[4]][series_1][series]
            dict["容许径向力(N)"] = self.boll_SCcrew.F1[str(series)]
            dict["容许轴向力(N)"] = self.boll_SCcrew.F2[str(series)]
            dict["效率(%)"] = self.boll_SCcrew.power[str(series_1)][series]
            dict["噪音(DB)"] = self.boll_SCcrew.dB[str(series)]
            dict["重量(Kg)"] = self.boll_SCcrew.weight[series_1][series]
            dict["减速机转动惯量(kg.cm2)"] = self.boll_SCcrew.Moment_inertia[series_1][series_2][series]

        elif self.ButtonId in ["EDA系列"]:
            self.combox_list[10].clear()  # 清除原来的combobox选项
            series = "EDA"+self.combox_current_text_list[0]  # 机座号
            Motor_position=self.combox_current_text_list[1]
            Fixed_mode=self.combox_current_text_list[2]
            lead="B"+self.combox_current_text_list[3]
            move_distance="C"+self.combox_current_text_list[4]
            Reduction_ratio="D"+self.combox_current_text_list[5]
            power="K"+self.combox_current_text_list[6]
            #rotate_speed=self.combox_current_text_list[7]
            #sensor_num=self.combox_current_text_list[8]
            dict = self.boll_SCcrew.series[str(series)]
            dict["减速比"]=self.combox_current_text_list[5]
            series=series+"-"+Motor_position[0]+Fixed_mode[0:2]+"-"+lead+"-"+move_distance+"-"+Reduction_ratio+"-"+power
            additem_list = ["-",series]
            self.combox_list[10].addItems(additem_list)  # 根据选项变换combox里的内容
            #机座号选型列表
        elif self.ButtonId in ["ECA系列"]:
            print("enter")
            self.combox_list[9].clear()  # 清除原来的combobox选项
            series = self.combox_current_text_list[0]  # 机座号
            dict = self.boll_SCcrew.series[str(series)]
            dict["减速比"]=self.combox_current_text_list[5]
            additem_list = ["-",series]
            self.combox_list[10].addItems(additem_list)  # 根据选项变换combox里的内容
            #机座号选型列表

        dict_list = []
        self.tableWidget_2.setRowCount(len(dict) + len(self.combox_list))  # 参数表格设置.

        for key in dict.keys():
            ls_list = []
            ls_list.append(key)
            ls_list.append(dict[key])
            dict_list.append(ls_list)
        RowCount = len(dict)
        for i in range(RowCount):
            # 第一列
            newItem = QtWidgets.QTableWidgetItem(dict_list[i][0])
            self.tableWidget_2.setItem(i + len(self.combox_list), 0, newItem)  # 代码
            newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
            newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)  # 文字居中
            newItem.setFont(QFont("微软雅黑", 9, QFont.Black))
            newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))

            # 第二列
            if type(dict_list[i][1]) == list:
                pass
                comBox = QComboBox()  # 选项列表
                for ls_item in dict_list[i][1]:
                    pass
                    comBox.addItem(ls_item)
                self.tableWidget_2.setCellWidget(i + len(self.combox_list), 1, comBox)

            else:
                newItem = QtWidgets.QTableWidgetItem(str(dict_list[i][1]))
                self.tableWidget_2.setItem(i + len(self.combox_list), 1, newItem)  # 代码
                newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
                newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)  # 文字居中
                newItem.setFont(QFont("微软雅黑", 9, QFont.Black))
                newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))
            # 第三列
            newItem = QtWidgets.QTableWidgetItem("")
            self.tableWidget_2.setItem(i + len(self.combox_list), 2, newItem)  # 代码
            newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
            newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)  # 文字居中
            newItem.setFont(QFont("微软雅黑", 9, QFont.Black))
            newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))

    except Exception as e:
        print(e)
        pass
    # 获取combox现在设定的参数
    try:
        # ----------------------------------------------清除原有的模型--------------------------
        try:
            for i in self.show:
                self.canva._display.Context.Remove(i, True)
                self.canva._display.Context.erase()
            self.aCompound.Free()
        except:
            pass

        # -----------------设置订购码/导出solidworks按钮----------------------------------------------------------------
        if self.ButtonId in ["KS系列(孔输出)", "KS系列(孔输出法兰)", "KS系列(轴输出)", "KS系列(轴输出法兰)"]:  # 设置订购码
            try:
                series ="KS"+self.combox_list[1].currentText() + "-"  # 系列号和机座代号
                Deceleration_ratio = self.combox_list[3].currentText() + "-"  # 减速比
                Deceleration_ratio = self.combox_list[2].currentText() + "-"  # 减速比
                Rotating_shaft = self.combox_list[3].currentText()[0:2] + "-"  # 附件轴类型
                Out_Flanges = self.combox_list[4].currentText()[0] + "-"  # 输出安装法兰类型
                Fixt_mode = self.combox_list[5].currentText() + "/"  # 安装方式
                Motor_type = self.combox_list[6].currentText()[0:1]  # 电机类型
                series = series + Deceleration_ratio + Rotating_shaft + Out_Flanges + Fixt_mode + Motor_type
            except Exception as e:
                pass
                print(e)
            newItem = QtWidgets.QTableWidgetItem(series)
            newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
            newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
            newItem.setFont(QFont("微软雅黑", 8, QFont.Black))
            newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))
            #self.tableWidget_2.setSpan(self.order_code_position, 1, 1, 2)#合并单元格
            #-----------------------------------------------------------------导入solidworks按钮
            self.out_put_solidworks_buttom = QtWidgets.QPushButton("导出至Solidworks")
            self.out_put_solidworks_buttom.clicked.connect(partial(Out_put_solidworks,self.solidworks_import_fiiepath,self))
            self.tableWidget_2.setCellWidget(self.order_code_position-1, 2, self.out_put_solidworks_buttom)
            self.tableWidget_2.setItem(self.order_code_position-1, 1, newItem)  # 设置导出按钮
            #-----------------------------------------------------------------------------------
            self.copy_buttom = QtWidgets.QPushButton("复制订购码")
            self.copy_buttom.clicked.connect(partial(order_code_copy, series,self))
            self.tableWidget_2.setCellWidget(self.order_code_position, 2, self.copy_buttom)
            self.tableWidget_2.setItem(self.order_code_position, 1, newItem)  # 设置订购码

        if self.ButtonId in ["KBR系列(1-1)", "KBR系列(1-2)","KB系列"]:  # 设置订购码
            try:
                if self.ButtonId=="KB系列":
                    series = "KB" + self.combox_list[1].currentText() + "-"  # 系列号和机座代号
                else:
                    series = "KBR" + self.combox_list[1].currentText() + "-"  # 系列号和机座代号
                Deceleration_ratio = self.combox_list[3].currentText() + "-"  # 减速比
                Deceleration_ratio = self.combox_list[2].currentText() + "-"  # 段数
                Rotating_shaft = self.combox_list[3].currentText()[0:2] + "-"  # 减速比
                Out_Flanges = self.combox_list[4].currentText()[0:2] + "-"  # 轴型
                Fixt_mode = self.combox_list[5].currentText()[0:2] + "/"  # 背隙
                Motor_type = self.combox_list[6].currentText()[0:1]  # 电机类型
                series = series + Deceleration_ratio + Rotating_shaft + Out_Flanges + Fixt_mode + Motor_type
            except Exception as e:
                pass
                print(e)
            newItem = QtWidgets.QTableWidgetItem(series)
            newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
            newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
            newItem.setFont(QFont("微软雅黑", 8, QFont.Black))
            newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))
            #self.tableWidget_2.setSpan(self.order_code_position, 1, 1, 2)#合并单元格
            # -----------------------------------------------------------------导入solidworks按钮
            self.out_put_solidworks_buttom = QtWidgets.QPushButton("导出至Solidworks")
            self.out_put_solidworks_buttom.clicked.connect(partial(Out_put_solidworks,self.solidworks_import_fiiepath,self))
            self.tableWidget_2.setCellWidget(self.order_code_position - 1, 2, self.out_put_solidworks_buttom)
            self.tableWidget_2.setItem(self.order_code_position - 1, 1, newItem)  # 设置导出按钮
            #--------------------------------------------------------------------------------------------------
            self.copy_buttom=QtWidgets.QPushButton("复制订购码")
            self.copy_buttom.clicked.connect(partial(order_code_copy, series,self))
            self.tableWidget_2.setCellWidget(self.order_code_position,2,self.copy_buttom)
            self.tableWidget_2.setItem(self.order_code_position, 1, newItem)  # 设置订购码

        if self.ButtonId in ["EDA系列"]:  # 设置订购码
            try:
                series = "EDA" + self.combox_current_text_list[0]  # 机座号
                Motor_position = self.combox_current_text_list[1]
                Fixed_mode = self.combox_current_text_list[2]
                lead = "B" + self.combox_current_text_list[3]
                move_distance = "C" + self.combox_current_text_list[4]
                Reduction_ratio = "D" + self.combox_current_text_list[5]
                power = "K" + self.combox_current_text_list[6]
                # rotate_speed=self.combox_current_text_list[7]
                # sensor_num=self.combox_current_text_list[8]
                series = series + "-" + Motor_position[0] + Fixed_mode[0:2] + "-" + lead + "-" + \
                         move_distance + "-" + Reduction_ratio + "-" + power
            except Exception as e:
                pass
                print(e)
            newItem = QtWidgets.QTableWidgetItem(series)
            newItem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
            newItem.setBackground(QtGui.QBrush(QtGui.QColor(240, 255, 191)))  # 设置背景颜色
            newItem.setFont(QFont("微软雅黑", 8, QFont.Black))
            newItem.setForeground(QBrush(QtGui.QColor(0, 0, 0)))
            #self.tableWidget_2.setSpan(self.order_code_position, 1, 1, 2)#合并单元格
            # -----------------------------------------------------------------导入solidworks按钮
            self.out_put_solidworks_buttom = QtWidgets.QPushButton("导出至Solidworks")
            self.out_put_solidworks_buttom.clicked.connect(partial(Out_put_solidworks,self))
            self.tableWidget_2.setCellWidget(self.order_code_position - 1, 2, self.out_put_solidworks_buttom)
            self.tableWidget_2.setItem(self.order_code_position - 1, 1, newItem)  # 设置导出按钮
            #-----------------------------------------------------------------------------------------
            self.copy_buttom=QtWidgets.QPushButton("复制订购码")
            self.copy_buttom.clicked.connect(partial(order_code_copy, series,self))
            self.tableWidget_2.setCellWidget(self.order_code_position,2,self.copy_buttom)
            self.tableWidget_2.setItem(self.order_code_position, 1, newItem)  # 设置订购码
            # ----------显示3D-------------------------------------------------------------------
            '''
            self.tab_7.repaint()
            try:
                filenam = self.filename_dict[self.combox_list[2].currentText()]
                filenam = filenam.repalce(".step", "")
                self.aCompound = self.boll_SCcrew.Create_shape(filename=filenam)
                self.Show3D(mode=1, aCompound=self.aCompound)
                self.statusbar.showMessage("数据生成成功")
                pass
            except:
                self.statusbar.showMessage("此零件官方未提供3D，生成失败")
            '''
    except Exception as e:
        pass

def Ceate_show_3d(self, QClor=1, dict={}, start=0, ):#仅更新3D
        #根据combox选项生成产品参数列表
        if self.combox_list[7].currentText() != "-":
            #self.statusbar.showMessage("数据生成中.....")
            pass
        if self.ButtonId in ["EDA系列"]:
            if self.combox_list[10].currentText() != "-" and self.combox_list[10].currentText()+".STEP" in self.file_list :
                #self.statusbar.showMessage("数据生成中.....")
                #判断模型是否在resources中
                self.statusbar.showMessage("")
                pass
            else:
                self.statusbar.showMessage("没有与选项符合的模型")

        try:
            # ----------------------------------------------清除原有的模型--------------------------
            try:
                for i in self.show:
                    self.canva._display.Context.Remove(i, True)
                    self.canva._display.Context.erase()
                self.aCompound.Free()
            except:
                pass
            # ----------显示3D-------------------------------------------------------------------
            self.tab_7.repaint()
            try:
                if not self.ButtonId in ["EDA系列"]:
                    if self.combox_list[7].currentText() != "-":  # 一般情况
                        filenam = self.filename_dict[self.combox_list[7].currentText()]
                        filenam = filenam.replace(".\\", "")
                        self.output_filename = filenam
                        Show3D(self=self, mode=0, file=filenam)
                        self.canva._display.Repaint()
                        self.filename = filenam
                        self.statusbar.showMessage("数据生成成功")

                if self.ButtonId in ["EDA系列"]:
                    if self.combox_list[10].currentText() != "-" and self.combox_list[10].currentText()+".STEP" in self.file_list:
                        series = "EDA" + self.combox_current_text_list[0]  # 机座号
                        filenam = "./resource/EDA/"+series+"/3D/"+self.combox_list[10].currentText()+".STEP"
                        filenam = filenam.replace("/", "\\")
                        self.output_filename = filenam
                        # 判断模型是否在resources中
                        if not os.path.exists(self.output_filename):
                            QApplication.processEvents()
                            down_load_path=os.getcwd()+"/resource/EDA/"+series+"/3D/"+self.combox_list[10].currentText()+".STEP"
                            down_load_path.replace("\\","/")
                            down_load_file_name="resource/EDA/"+series+"/3D/"+self.combox_list[10].currentText()+".STEP"
                            #self.ftp_serve.Down_load_part_file(down_load_path,down_load_file_name)
                            file_size=self.ftp_serve.Get_file_size(down_load_file_name)
                            t=threading.Thread(target=self.ftp_serve.Down_load_part_file,args=(down_load_path,down_load_file_name,))
                            t.start()
                            self.statusbar.showMessage("数据下载中......")
                            self.progressBar.label.setText("下载中")
                            self.progressBar.Show()
                            while True:
                                QApplication.processEvents()
                                now_file_size=os.lstat(self.output_filename).st_size
                                self.progressBar.Down_load_part_progressBar(file_size,now_file_size)
                                if file_size==str(os.lstat(self.output_filename).st_size):
                                    break
                            self.progressBar.Hide()
                            self.statusbar.showMessage("数据下载完成")

                        #显示3D
                        Show3D(self=self, mode=0, file=filenam)
                        #self.canva._display.Repaint()
                        self.filename = filenam
                        self.statusbar.showMessage("数据生成成功")
            except:
                self.statusbar.showMessage("此零件官方未提供3D，生成失败")

        except:
            pass

def Show3D(self, mode=0, file=None, aCompound=None):  # 生成3D mode控制显示模式
        try:

            self.canva._display.EraseAll()
            self.canva._display.hide_triedron()
            self.canva._display.display_triedron()
            self.canva._display.Repaint()
            self.new_build = TopoDS_Builder()  # 建立一个TopoDS_Builder()
            self.New_Compound = TopoDS_Compound()  # 定义一个复合体
            self.new_build.MakeCompound(self.New_Compound)  # 生成一个复合体DopoDS_shape
            self.QApplication=QApplication
            if mode == 0:
                #file=os.path.join(os.getcwd(),file)
                shapes_labels_colors_list=[]
                self.statusbar.showMessage("数据生成中请梢后......")
                t1=threading.Thread(target=assemble.read_step_file_with_names_colors,args=(self,file,shapes_labels_colors_list,))
                t1.start()
                self.progressBar.label.setText("正在生成")
                while True:
                    QApplication.processEvents()
                    if len(shapes_labels_colors_list)!=0:
                        break
                shapes_labels_colors=shapes_labels_colors_list[0]

                self.statusbar.showMessage("数据生成中请梢后......")
                self.aCompound=shapes_labels_colors
                shape_num=len(shapes_labels_colors.keys())
                self.progressBar.Show()
                for shpt_lbl_color in shapes_labels_colors:
                    label, c = shapes_labels_colors[shpt_lbl_color]
                    self.progressBar.Load_part_progressBar(shape_num)
                    QApplication.processEvents()
                    #for e in TopologyExplorer(shpt_lbl_color).solids():
                        #self.new_build.Add(self.New_Compound, e)
                    self.canva._display.DisplayColoredShape(shpt_lbl_color, color=Quantity_Color(c.Red(),
                                                                                c.Green(),
                                                                                c.Blue(),
                                                                                Quantity_TOC_RGB))
                    #self.aCompound=self.New_Compound
                print(self.solidworks_import_fiiepath)
                self.solidworks_import_fiiepath=file
                print(888888,self.solidworks_import_fiiepath)
                self.progressBar.Value_clear()
                self.progressBar.Hide()

            elif mode == 1:
                self.show = self.canva._display.DisplayColoredShape(aCompound, color="WHITE", update=True)
            self.canva._display.FitAll()

        except Exception as e:
            pass
            print(e)
            self.statusbar.showMessage("没有此零件")

def combox_refresh_function(self):#根据comcox改变combox
    if self.ButtonId in ["KBR系列(1-1)", "KBR系列(1-2)","KB系列"]:
        Reduction_ratio = self.boll_SCcrew.lever[self.combox_list[2].currentText()]
        self.combox_list[3].clear()
        self.combox_list[3].addItems(Reduction_ratio)  # 根据选项变换combox里的内容
    if self.ButtonId in ["EDA系列"]:
        try:
            series = self.combox_list[1].currentText()
            path = "EDA" + "/EDA" + series + "/3D"
            self.model_3d_file_list = self.ftp_serve.Get_file_list(path)
            lead_list, move_distance_list, Reduction_ratio_list, power_list,self.file_list = self.boll_SCcrew.Get_resourcr_list(
                self.model_3d_file_list)
            self.combox_list[4].clear()
            self.combox_list[4].addItems(lead_list)
            self.combox_list[5].clear()
            self.combox_list[5].addItems(move_distance_list)
            self.combox_list[6].clear()
            self.combox_list[6].addItems(Reduction_ratio_list)
            self.combox_list[7].clear()
            self.combox_list[7].addItems(power_list)
        except:
            pass

        #self.combox_list[3].addItems(Reduction_ratio)  # 根据选项变换combox里的内容

def show_technical_information(self):
    ButtonId=self.ButtonId
    if ButtonId in ["KS系列(孔输出)", "KS系列(孔输出法兰)", "KS系列(轴输出)", "KS系列(轴输出法兰)"]:
        pix_name_1 = "KS_1"
        pix_name_2 = "KS_2"
    elif ButtonId in ["KBR系列(1-1)","KBR系列(1-2)"]:
        series = "KBR" + self.combox_list[1].currentText()  # 机座号
        if series in ["KBR60","KBR90"]:
            pix_name_1 = "KBR-1"
            pix_name_2 = "KBR-1"
        elif series in ["KBR115","KBR142"]:
            pix_name_1 = "KBR-2"
            pix_name_2 = "KBR-2"
        elif series in ["KBR180","KBR220"]:
            pix_name_1 = "KBR-3"
            pix_name_2 = "KBR-3"
        elif series in ["KBR280","KBR340"]:
            pix_name_1 = "KBR-4"
            pix_name_2 = "KBR-4"
    elif ButtonId in ["KB系列"]:
        series = "KB" + self.combox_list[1].currentText()  # 机座号
        if series in ["KB60","KB90"]:
            pix_name_1 = "KB-1"
            pix_name_2 = "KB-1"
        elif series in ["KB115","KB142"]:
            pix_name_1 = "KB-2"
            pix_name_2 = "KB-2"
        elif series in ["KB180","KB220"]:
            pix_name_1 = "KB-3"
            pix_name_2 = "KB-3"
        elif series in ["KB280","KB340"]:
            pix_name_1 = "KB-4"
            pix_name_2 = "KB-4"
    elif ButtonId in ["EDA系列"]:
        series = "EDA" + self.combox_list[1].currentText()  # 机座号
        if series in ["EDA40"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA50"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA60"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA75"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA80"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA95"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA110"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA135"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA180"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
        elif series in ["EDA220"]:
            pix_name_1 = "EDA-1"
            pix_name_2 = "EDA-1"
    # ----------2D显示图片操作 技术资料（1）----------------
    try:
        pix_name = ButtonId  # 2D
        #self.pix = QPixmap('Pic\\' + pix_name + ".PNG")
        self.graphicsView = GraphicsView(self.pix_dict[series], self.tab_8)
        self.graphicsView.setGeometry(QtCore.QRect(0, 0, 461 * self.width_scal, 581 * self.height_scal))
        self.graphicsView.setObjectName("graphicsView")
        self.graphicsView.scale(0.4, 0.4)  # 显示比例
        self.graphicsView.repaint()
        self.graphicsView.update()
        self.graphicsView.show()
        self.item = GraphicsPixmapItem(self.pix)  # 创建像素图元
        self.scene = QtWidgets.QGraphicsScene()  # 创建场景显示比例
        self.scene.addItem(self.item)

    except Exception as e:
        print(e)
        pass

    # ----------2D显示图片操作 技术资料（2）----------------
    try:
        self.graphicsView = GraphicsView(self.pix_dict[pix_name_1], self.tab_3)
        self.graphicsView.setGeometry(QtCore.QRect(0, 0, 461 * self.width_scal, 581 * self.height_scal))
        self.graphicsView.setObjectName("graphicsView")
        self.graphicsView.scale(0.4, 0.4)  # 显示比例
        self.item = GraphicsPixmapItem(self.pix)  # 创建像素图元
        self.scene = QtWidgets.QGraphicsScene()  # 创建场景显示比例
        self.scene.addItem(self.item)
        self.graphicsView.repaint()
        self.graphicsView.update()
        self.graphicsView.show()
    except:
        pass
        # ----------2D显示图片操作 技术资料（3）----------------
    try:
        self.graphicsView = GraphicsView(self.pix_dict[pix_name_2], self.tab_4)
        self.graphicsView.setGeometry(QtCore.QRect(0, 0, 461 * self.width_scal, 581 * self.height_scal))
        self.graphicsView.setObjectName("graphicsView")
        self.graphicsView.scale(0.4, 0.4)  # 显示比例
        self.item = GraphicsPixmapItem(self.pix)  # 创建像素图元
        self.scene = QtWidgets.QGraphicsScene()  # 创建场景显示比例
        self.scene.addItem(self.item)
        self.graphicsView.repaint()
        self.graphicsView.update()
        self.graphicsView.show()
    except:
        pass

def Create_pix_naime_dict_fun(pix_name,return_queue):
    app = QtWidgets.QApplication(sys.argv)
    #widget = QtWidgets.QWidget()
    pix_dict = {}
    for i in pix_name:
        try:
            pix_dict[i] = QPixmap("./"+'Pic/' + i + ".png")
        except Exception as e:
            print(e)
    #return_queue.put(pix_dict)
    print(return_queue)

def Create_pix_name_dict(self,path=".\\Pic"):#--------------------------------------------------- 资料图片加载
    def threading_load_pic(pix_name=""):
        #start_time=time.time()
        self.pix_dict[pix_name]=QPixmap("./"+'Pic/' + pix_name + ".png")
        #end_time=time.time()
        #print(pix_name,start_time,end_time)
    try:
        self.pix_dict = {}
        index=0
        pix_list=[]
        start_time = time.time()
        t={}#线程字典
        for root, dirs, files in os.walk(".\\Pic", topdown=False):
            if root == ".\\Pic":
                all_number=len(files)
                for i in files:
                    if i.lower().endswith("jpg"):
                        continue
                    pix_name = i.replace(".png", "")
                    pix_list.append(pix_name)
                    #self.pix_dict[pix_name] = QPixmap("./"+'Pic/' + pix_name + ".png")
                    t[i]=threading.Thread(target=threading_load_pic,args=(pix_name,))
                    t[i].start()
                    index+=1
                    compplete_percent=str(int(index/all_number*100))+"%"
                    self.splash.showMessage("资源加载中:"+compplete_percent+"  "+i)
                break

        '''
        尝试多进程失败
        queue=Queue()
        return_queue=Queue()
        queue.put(pix_list)
        manager=Manager()
        pix_dict=manager.list()
        new_speed=FuctionModule.speed_processing()
        new_speed.Create_multi_process(Create_pix_naime_dict_fun,queue,return_queue)
        '''
        end_time = time.time()
        print(end_time - start_time)
        self.splash.showMessage("资源加载中:" + "100%"+" 完成")
    except Exception as e:
        print(e)
        pass

def canvan_click(self):
        pass

def order_code_copy(series,self):
    clipboard = QApplication.clipboard()
    clipboard.setText(series)
    self.statusbar.showMessage("复制成功")
def Out_put_solidworks(self):
    try:
        print("enter", self.solidworks_import_fiiepath)
        solidworks_api=SolidworksModule.Solidworks_API()
        self.statusbar.showMessage("Solidworks链接成功")
        print("enter",self.solidworks_import_fiiepath)
        solidworks_api.Import_part(filepath=self.solidworks_import_fiiepath)
    except:
        self.statusbar.showMessage("导出失败")
    self.statusbar.showMessage("导出成功")