import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject, Gio
from gui_functions import Function, Cal_Date
import shutil
from datetime import date, datetime, timedelta
from SQL import Queries, Store
#from GUI_Admin import Main

class Widget:
    def __init__(self, store_func, parent, queries, **setup):
        self.builder = Gtk.Builder()
        self.builder.add_from_file(setup["glade_file"])
        self.builder.connect_signals(self)
        self.widget = self.builder.get_object(setup["widget_id"])
        self.scroll = self.builder.get_object(setup["widget_scroll_id"])
        if setup["widget_calander_id"] != None:
            self.calander = self.builder.get_object(setup["widget_calander_id"])
        else:
            self.calander = None
        self.parent = parent
        self.queries = queries

        self.current_items = None
        self.current_filter = None
        self.file = None
        if setup["file_chooser"] != None:
            self.file_chooser = self.builder.get_object(setup["file_chooser"])
        else:
            self.file_chooser = None
        self.query = setup["timer_query"]

        self.store = setup["store_setup"] #Gtk.ListStore(str)
        self.columns = setup["column_numbers"]
        self.column_headings = setup["column_headings"]
        self.entries = setup["entries"]

        self.filter = self.store.filter_new()
        self.filter.set_visible_func(self.filter_func)
        self.filter_view = Gtk.TreeModel.sort_new_with_model(self.filter)
        self.treeview = Gtk.TreeView.new_with_model(self.filter_view)
        self.tree_selection = self.treeview.get_selection()
        self.tree_selection.connect("changed", self.onSelectionChanged)
        self.scroll.add(self.treeview)

        for i, column_title in enumerate(self.column_headings):
            renderer = Gtk.CellRendererText()
            self.column = Gtk.TreeViewColumn(column_title, renderer, text=i)
            self.column.set_sort_column_id(i)
            self.treeview.append_column(self.column)

        self.widget.show_all()
        self.store_func = store_func
        self.timer()

    def timer(self):
        GObject.timeout_add(1000, self.timer_func)

    def timer_func(self):
        s = self.store
        new_items = self.store_func.get(self.query)
        comparison = self.store_func.compare(self.current_items, new_items)
        if comparison == False:
            x = self.store_func.build(s, new_items)
        self.current_items = new_items

        return True

    def filter_func(self, model, iter, data):
        if self.current_filter is None or self.current_filter == "":
            return True
        elif self.current_filter in model[iter][self.current_filter_column]:
            return model[iter][self.current_filter_column]

    def onSelectionChanged(self, tree_selection):
        (model, pathlist) = tree_selection.get_selected_rows()
        for path in pathlist :
            tree_iter = model.get_iter(path)
            c = self.columns
            self.row = []
            for i in c:
                value = model.get_value(tree_iter,c[i])
                self.row.append(str(value))
            print(self.row)
            Function.set_entries(self, self.entries, self.row)

            if self.calander != None:
                for j in range(len(self.column_headings)):
                    if self.column_headings[j].endswith("Expiry") == True:
                        date_to_set = self.row[j]
                        Cal_Date.set_date(self,  calander_object=self.calander, date=date_to_set)
                    elif self.column_headings[j].endswith("Date") == True:
                        date_to_set = self.row[j]
                        Cal_Date.set_date(self,  calander_object=self.calander, date=date_to_set)

            if self.file_chooser != None:
                for k in range(len(self.column_headings)):
                    if self.column_headings[k].endswith("Certificate") == True:
                        f = Gio.File.new_for_path(self.row[k])
                        self.file_chooser.set_file(f)

                    elif self.column_headings[k].endswith("File") == True:
                        f = Gio.File.new_for_path(self.row[k])
                        self.file_chooser.set_file(f)

    def confirm_init(self):
        self.builder.add_from_file("Glade/confirm.glade")
        self.builder.connect_signals(self)
        self.confirm = self.builder.get_object("confirm")
        self.log = False
        self.msg_label = self.builder.get_object("title")
        self.confirm.set_transient_for(self.parent)
        self.f_labels = ["f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11"]
        self.v_labels = ["v11", "v10", "v9", "v8", "v7", "v6", "v5", "v4", "v3", "v2", "v1"]

    def insert(self, query, values, log_query, log_values):
        self.confirm_init()
        self.q = query
        self.v = values
        self.lq = log_query
        self.lv = log_values
        table = "equipment"
        self.msg = ("You are about to add the following {} to the database".format(table))
        self.heading_labels = self.column_headings
        self.label_values = list(values)[1:]
        self.show_message()

    def log_insert(self, log_query, log_values):
        self.confirm_init()
        self.lq = log_query
        self.lv = log_values
        table = "logbook"
        self.msg = ("You are about to add the following {} to the database".format(table))
        self.heading_labels = self.column_headings
        self.label_values = list(log_values)[1:]
        self.log = True
        self.show_message()

    def update(self, query, values, log_query, log_values):
        self.confirm_init()
        columns = list(self.column_headings)[1:]
        current_values = self.row[1:]
        new_values = list(values)[1:-1]
        self.q = query
        self.v = values
        self.lq = log_query
        self.lv = log_values
        self.heading_labels = []
        self.label_values = []
        self.msg = ("You are about to update the following fields with: ")
        for i in range(len(new_values)):
            if new_values[i] != current_values[i]:
                self.heading_labels.append(columns[i])
                self.label_values.append(new_values[i])

        self.show_message()

    def show_message(self):
        self.msg_label.set_label(self.msg)
        for i in range(len(self.heading_labels)):
            field_label = self.builder.get_object(self.f_labels[i])
            value_label = self.builder.get_object(self.v_labels[i])
            field_label.set_label(self.heading_labels[i])
            value_label.set_label(str(self.label_values[i]))
        self.confirm.show()

    def on_confirm_button_clicked(self, confirm_button):
        if self.log == False:
            self.queries.query(self.q, self.v)
            self.queries.log_query(self.lq, self.lv)
            self.confirm.destroy()
        elif self.log == True:
            self.queries.log_query(self.lq, self.lv)
            self.confirm.destroy()

    def on_confirm_cancel_button_clicked(self, confirm_cancel_button):
        self.confirm.destroy()

    def on_confirm_delete_event(self, *args):
        self.confirm.destroy()

#Do Remove/Update and Completions
class EquipAdd(Widget):
    def __init__(self, queries, store_func, parent):
        self.entries = {"equipment_add_entry_eal" : 0, "equipment_add_entry_type" : 1, "equipment_add_entry_manufacturer" : 2, "equipment_add_entry_model" : 3, "equipment_add_entry_pressure" : 4, "equipment_add_entry_serial" : 5}
        self.queries = queries

        setup = {"glade_file" : "Glade/equipment_add.glade",
                 "widget_id" :  "equipment_add_page",
                 "widget_scroll_id" : "equipment_add_scroll_window",
                 "widget_calander_id" : None,
                 "timer_query" : queries.equipment["select"],
                 "store_setup" : Gtk.ListStore(str, str, str, str, int, str),
                 "column_numbers" : (0, 1, 2, 3, 4, 5),
                 "column_headings" : ["EAL Number", "Equipment Type", "Manufacturer", "Model", "Pressure", "Serial Number"],
                 "entries" : self.entries,
                 "file_chooser" : None}

        Widget.__init__(self, store_func, parent, queries, **setup)

        Function.entry_completion(self, self.store, "equipment_add_entry_eal", 0)
        Function.entry_completion(self, self.store, "equipment_add_entry_type", 1)
        Function.entry_completion(self, self.store, "equipment_add_entry_manufacturer", 2)
        Function.entry_completion(self, self.store, "equipment_add_entry_model", 3)
        #Function.entry_completion(self, self.store, "equipment_add_entry_pressure", 4)
        #Function.entry_completion(self, self.store, "equipment_add_entry_serial", 5)

    def on_equipment_add_button_add_clicked(self, equipment_add_button_add):
        entries = ["equipment_add_entry_eal", "equipment_add_entry_type", "equipment_add_entry_manufacturer", "equipment_add_entry_model", "equipment_add_entry_pressure", "equipment_add_entry_serial"]
        text = Function.get_entries(self, entries)
        now = datetime.now()
        for item in self.current_items:
            row = list(item)
            if row[0] == text[0]:
                match = True
                break
            else:
                match = False

        if match == True:
            query = self.queries.equipment["update"]
            utext = text[1:]
            utext.append(text[0])
            values = (now, utext[0], utext[1], utext[2], utext[3], utext[4], utext[5])
            location = 'Westcott'
            procedure = 'N/A'
            message = text[0] + ' updated field'
            log_query = self.queries.logbook["insert"]
            log_values = (now, text[0], now, location, procedure, message)
            self.update(query, values, log_query, log_values)
        elif match == False:
            values = (now, text[0], text[1], text[2], text[3], text[4], text[5])
            location = 'Westcott'
            procedure = 'N/A'
            message = text[0] + ' added to equipment store'
            log_query = self.queries.logbook["insert"]
            log_values = (now, text[0], now, location, procedure, message)
            query = self.queries.equipment["insert"]
            self.insert(query, values, log_query, log_values)

        Function.clear_entries(self, entries)

    def on_equipment_add_button_clear_clicked(self, equipment_add_button_clear):
        self.tree_selection.unselect_all()
        entries = self.entries
        Function.clear_entries(self, entries)
        self.current_filter = None

    def on_equipment_add_entry_eal_changed(self, entry):
        self.tree_selection.unselect_all()
        search = entry.get_text()
        self.current_filter = search.upper()
        self.current_filter_column = 0
        self.filter.refilter()

    def on_equipment_add_entry_type_changed(self, entry):
        self.tree_selection.unselect_all()
        search = entry.get_text()
        self.current_filter = search
        self.current_filter_column = 1
        self.filter.refilter()

    def on_equipment_add_entry_manufacturer_changed(self, entry):
        self.tree_selection.unselect_all()
        search = entry.get_text()

    def on_equipment_add_entry_model_changed(self, entry):
        self.tree_selection.unselect_all()
        search = entry.get_text()

    def on_equipment_add_page_delete_event(self, *args):
        Gtk.main_quit(*args)

class EquipCal(Widget):
    def __init__(self, queries, store_func, parent, com_store):

        self.queries = queries
        self.type = "External"
        self.entries = {"equipment_calibration_entry_eal" : 0, "equipment_calibration_entry_company" : 1}

        setup = {"glade_file" : "Glade/equipment_calibration.glade",
                 "widget_id" :  "equipment_calibration_page",
                 "widget_scroll_id" : "equipment_calibration_scroll_window",
                 "widget_calander_id" : "equipment_calibration_calendar_date",
                 "timer_query" : queries.calibration["select"],
                 "store_setup" : Gtk.ListStore(str, str, str, str, str, str, str),
                 "column_numbers" : (0,1,2,3,4,5,6),
                 "column_headings" : ["EAL Number", "Calibration Company", "Calibration Type", "Calibration Date", "Calibration Recall", "Calibration Expiry", "Calibration Certificate"],
                 "entries" : self.entries,
                 "file_chooser" : "equipment_calibration_file_certificate"}

        Widget.__init__(self, store_func, parent, queries, **setup)

        Function.entry_completion(self, com_store, "equipment_calibration_entry_eal", 0)

    def on_equipment_calibration_radio_external_toggled(self, equipment_calibration_radio_external):
        self.type = "External"

    def on_equipment_calibration_radio_internal_toggled(self, equipment_calibration_radio_internal):
        self.type = "Internal"

    def on_equipment_calibration_button_enter_clicked(self, equipment_calibration_button_enter):
        entries = ["equipment_calibration_entry_eal", "equipment_calibration_entry_company"]
        text = Function.get_entries(self, entries)
        print(text)
        calibration_type = self.type
        if (calibration_type == "External"):
            length = 12
        elif (calibration_type == "Internal"):
            length = 6
        else:
            length = 12

        calibration_date = Cal_Date.date(self, "equipment_calibration_calendar_date")
        calibration_expiry = Cal_Date.expiry(self, calibration_date, length)
        calibration_recall = Cal_Date.recall(self, calibration_expiry)
        calibration_certificate = ''

        if self.file != None:
            file_name = 'Calibration_Certificate_' + str(calibration_date)
            file_settings = {"dep":"Equipment", "sub":"Calibration", "eal_ref":text[0]}
            calibration_certificate = Function.file_path2(self, self.file, file_name, file_settings)
            shutil.copy(self.file, calibration_certificate)
            self.file_chooser.unselect_all()
        else:
            calibration_certificate = "Not Uploaded"

        now = datetime.now()
        location = Function.get_entry(self, "equipment_calibration_entry_location")

        for item in self.current_items:
            row = list(item)
            if row[0] == text[0]:
                match = True
                break
            else:
                match = False

        if match == True:
            query = self.queries.calibration["update"]
            utext = text[1:]
            utext.append(text[0])
            values = (now, utext[0], calibration_type, calibration_date, calibration_recall, calibration_expiry, calibration_certificate, utext[1])
            procedure = 'N/A'
            message = text[0] + ' updated field'
            log_query = self.queries.logbook["insert"]
            log_values = (now, text[0], now, location, procedure, message)
            self.update(query, values, log_query, log_values)

        elif match == False:
            message = "Calibration certificate added."
            procedure = "N/A"
            values = (now, text[0], text[1], calibration_type, calibration_date, calibration_recall, calibration_expiry, calibration_certificate)
            log_values = (now, text[0], now, location, procedure, message)
            query = self.queries.calibration["insert"]
            log_query = self.queries.logbook["insert"]
            self.insert(query, values, log_query, log_values)

        Function.clear_entries(self, entries)

    def on_equipment_calibration_button_clear_clicked(self, equipment_calibration_button_clear):
        self.tree_selection.unselect_all()
        self.file_chooser.unselect_all()
        entries = self.entries
        Function.clear_entries(self, entries)
        self.current_filter = None
        print ("Clear")

    def on_equipment_calibration_file_certificate_file_set(self, equipment_calibration_file_certificate):
        self.file_chooser = equipment_calibration_file_certificate
        self.file = self.file_chooser.get_filename()

    def on_equipment_calibration_entry_eal_changed(self, equipment_calibration_entry_eal):
        search = equipment_calibration_entry_eal.get_text()
        self.current_filter = search.upper()
        self.current_filter_column = 0
        self.filter.refilter()

    def on_equipment_calibration_page_delete_event(self, *args):
        Gtk.main_quit(*args)

class EquipProof(Widget):
    def __init__(self, queries, store_func, parent, com_store, proc_store):
        self.queries = queries
        self.entries = {"equipment_proof_entry_eal" : 0, "equipment_proof_entry_bar" : 1, "equipment_proof_entry_duration" : 2, "equipment_proof_entry_pt" : 3, "equipment_proof_entry_procedure" : 4, "equipment_proof_entry_location" : 8}
        self.result = "Pass"

        setup = {"glade_file" : "Glade/equipment_proof.glade",
                 "widget_id" :  "equipment_proof_page",
                 "widget_scroll_id" : "equipment_proof_scroll_window",
                 "widget_calander_id" : "equipment_proof_calendar_date",
                 "timer_query" : queries.proof["select"],
                 "store_setup" : Gtk.ListStore(str, int, int, str, str, str, str, str, str, str, str),
                 "column_numbers" : (0,1,2,3,4,5,6,7,8,9,10),
                 "column_headings" : ["EAL Number", "Test Pressure", "Test Duration", "Transducer Number", "Procedure", "Proof Date", "Proof Recall", "Proof Expiry", "Test Location", "Result", "Proof Certificate"],
                 "entries" : self.entries,
                 "file_chooser" : "equipment_proof_file_certificate"}

        Widget.__init__(self, store_func, parent, queries, **setup)

        Function.entry_completion(self, com_store, "equipment_proof_entry_eal", 0)
        Function.entry_completion(self, com_store, "equipment_proof_entry_pt", 0)
        Function.entry_completion(self, proc_store, "equipment_proof_entry_procedure", 2)

    def on_equipment_proof_radio_pass_toggled(self, equipment_proof_radio_pass):
        self.result = "Pass"

    def on_equipment_proof_radio_fail_toggled(self, equipment_proof_radio_fail):
        self.result = "Fail"

    def on_equipment_proof_button_enter_clicked(self, equipment_proof_button_enter):
        entries = ["equipment_proof_entry_eal", "equipment_proof_entry_bar", "equipment_proof_entry_duration", "equipment_proof_entry_pt", "equipment_proof_entry_procedure", "equipment_proof_entry_location"]
        text = Function.get_entries(self, entries)
        proof_date = Cal_Date.date(self, "equipment_proof_calendar_date")
        proof_expiry = Cal_Date.expiry(self, proof_date, 12)
        proof_recall = Cal_Date.recall(self, proof_expiry)

        proof_certificate = ''
        if self.file != None:
            file_name = 'Proof_Certificate_' + str(proof_date)
            file_settings = {"dep":"Equipment", "sub":"Proof", "eal_ref":text[0]}
            proof_certificate = Function.file_path2(self, self.file, file_name, file_settings)
            shutil.copy(self.file, proof_certificate)
            self.file_chooser.unselect_all()
        else:
            proof_certificate = "Not Uploaded"

        now = datetime.now()

        for item in self.current_items:
            row = list(item)
            if row[0] == text[0]:
                match = True
                break
            else:
                match = False

        if match == True:
            query = self.queries.proof["update"]
            utext = text[1:]
            utext.append(text[0])
            values = (now, utext[0], utext[1], utext[2], utext[3], proof_date, proof_recall, proof_expiry, utext[4], self.result, proof_certificate, utext[5])
            procedure = 'N/A'
            message = text[0] + ' updated field'
            log_query = self.queries.logbook["insert"]
            log_values = (now, text[0], now, text[5], text[4], message)
            self.update(query, values, log_query, log_values)

        elif match == False:
            proof_message = "Proof certificate added."
            values = (now, text[0], text[1], text[2], text[3], text[4], proof_date, proof_recall, proof_expiry, text[5], self.result, proof_certificate)
            log_values = (now, text[0], now, text[5], text[4], proof_message)

            query = self.queries.proof["insert"]
            log_query = self.queries.logbook["insert"]
            self.insert(query, values, log_query, log_values)

        Function.clear_entries(self, entries)
        print ("Add")

    def on_equipment_proof_button_clear_clicked(self, equipment_proof_button_clear):
        self.tree_selection.unselect_all()
        self.file_chooser.unselect_all()
        entries = self.entries
        Function.clear_entries(self, entries)
        self.current_filter = None

    def on_equipment_proof_file_certificate_file_set(self, equipment_proof_file_certificate):
        self.file_chooser = equipment_proof_file_certificate
        self.file = self.file_chooser.get_filename()

    def on_equipment_proof_entry_eal_changed(self, equipment_proof_entry_eal):
        search = equipment_proof_entry_eal.get_text()
        self.current_filter = search.upper()
        self.current_filter_column = 0
        self.filter.refilter()

    def on_equipment_proof_page_delete_event(self, *args):
        Gtk.main_quit(*args)

class EquipClean(Widget):
    def __init__(self, queries, store_func, parent, com_store, proc_store):
        self.queries = queries
        self.entries = {"equipment_cleanliness_entry_eal" : 0, "equipment_cleanliness_entry_pco" : 1, "equipment_cleanliness_entry_dew" : 2, "equipment_cleanliness_entry_procedure" : 3, "equipment_cleanliness_entry_location" : 7}
        self.result = "Pass"

        setup = {"glade_file" : "Glade/equipment_cleanliness.glade",
                 "widget_id" :  "equipment_cleanliness_page",
                 "widget_scroll_id" : "equipment_cleanliness_scroll_window",
                 "widget_calander_id" : "equipment_cleanliness_calendar_date",
                 "timer_query" : queries.cleanliness["select"],
                 "store_setup" : Gtk.ListStore(str, str, str, str, str, str, str, str, str, str),
                 "column_numbers" : (0,1,2,3,4,5,6,7,8,9),
                 "column_headings" : ["EAL Number", "Particle Counter Number", "Dew Point Meter", "Procedure", "Cleanliness & Dryness Date", "Cleanliness & Dryness Recall", "Cleanliness & Dryness Expiry", "Test Location", "Result", "Proof Certificate"],
                 "entries" : self.entries,
                 "file_chooser" : "equipment_cleanliness_file_certificate"}

        Widget.__init__(self, store_func, parent, queries, **setup)

        Function.entry_completion(self, com_store, "equipment_cleanliness_entry_eal", 0)
        Function.entry_completion(self, com_store, "equipment_cleanliness_entry_pco", 0)
        Function.entry_completion(self, com_store, "equipment_cleanliness_entry_dew", 0)
        Function.entry_completion(self, proc_store, "equipment_cleanliness_entry_procedure", 2)

    def on_equipment_cleanliness_radio_pass_toggled(self, equipment_cleanliness_radio_pass):
        self.result = "Pass"

    def on_equipment_cleanliness_radio_fail_toggled(self, equipment_cleanliness_radio_fail):
        self.result = "Fail"

    def on_equipment_cleanliness_button_enter_clicked(self, equipment_cleanliness_button_enter):
        entries = ["equipment_cleanliness_entry_eal", "equipment_cleanliness_entry_pco", "equipment_cleanliness_entry_dew", "equipment_cleanliness_entry_procedure", "equipment_cleanliness_entry_location"]
        text = Function.get_entries(self, entries)
        clean_date = Cal_Date.date(self, "equipment_cleanliness_calendar_date")
        clean_expiry = Cal_Date.expiry(self, clean_date, 12)
        clean_recall = Cal_Date.recall(self, clean_expiry)

        clean_certificate = ''
        if self.file != None:
            file_name = 'Cleanliness_&_Dryness_Certificate_' + str(clean_date)
            file_settings = {"dep":"Equipment", "sub":"Cleanliness_&_Dryness", "eal_ref":text[0]}
            clean_certificate = Function.file_path2(self, self.file, file_name, file_settings)
            shutil.copy(self.file, clean_certificate)
            self.file_chooser.unselect_all()
        else:
            clean_certificate = "Not Uploaded"

        now = datetime.now()
        for item in self.current_items:
            row = list(item)
            if row[0] == text[0]:
                match = True
                break
            else:
                match = False

        if match == True:
            query = self.queries.cleanliness["update"]
            utext = text[1:]
            utext.append(text[0])
            values = (now, utext[0], utext[1], utext[2], clean_date, clean_recall, clean_expiry, utext[3], self.result, clean_certificate, utext[4])
            procedure = 'N/A'
            message = text[0] + ' updated field'
            log_query = self.queries.logbook["insert"]
            log_values = (now, text[0], now, text[4], text[3], message)
            self.update(query, values, log_query, log_values)

        elif match == False:
            message = "Cleanliness & Dryness certificate added."

            values = (now, text[0], text[1], text[2], text[3], clean_date, clean_recall, clean_expiry, text[4], self.result, clean_certificate)

            log_values = (now, text[0], now, text[4], text[3], message)
            query = self.queries.cleanliness["insert"]

            log_query = self.queries.logbook["insert"]
            self.insert(query, values, log_query, log_values)

        Function.clear_entries(self, entries)

    def on_equipment_cleanliness_button_clear_clicked(self, equipment_cleanliness_button_clear):
        self.tree_selection.unselect_all()
        self.file_chooser.unselect_all()
        entries = self.entries
        Function.clear_entries(self, entries)
        self.current_filter = None
        print ("Clear")

    def on_equipment_cleanliness_file_certificate_file_set(self, equipment_cleanliness_file_certificate):
        self.file_chooser = equipment_cleanliness_file_certificate
        self.file = self.file_chooser.get_filename()

    def on_equipment_cleanliness_entry_eal_changed(self, equipment_cleanliness_entry_eal):
        search = equipment_cleanliness_entry_eal.get_text()
        self.current_filter = search.upper()
        self.current_filter_column = 0
        self.filter.refilter()

    def on_equipment_cleanliness_page_delete_event(self, *args):
        Gtk.main_quit(*args)

class EquipSearch(Widget):
    def __init__(self, queries, store_func, parent):
        self.queries = queries
        self.entries = {"equipment_search_entry_search" : 0}

        setup = {"glade_file" : "Glade/equipment_search.glade",
                 "widget_id" :  "equipment_search_page",
                 "widget_scroll_id" : "equipment_search_scroll_window",
                 "widget_calander_id" : None,
                 "timer_query" : queries.overview["select"],
                 "store_setup" : Gtk.ListStore(str, str, str, str, str, str, str),
                 "column_numbers" : (0,1,2,3,4,5,6),
                 "column_headings" : ["EAL Number", "Equipment Type", "Serial Number", "Calibration Expiry", "Proof Expiry", "Cleanliness Expiry", "Current Location"],
                 "entries" : self.entries,
                 "file_chooser" : None}

        Widget.__init__(self, store_func, parent, queries, **setup)

    def on_equipment_search_entry_search_changed(self, equipment_search_entry_search):
        search = equipment_search_entry_search.get_text()
        self.current_filter = search.upper()
        self.current_filter_column = 0
        self.filter.refilter()

    def on_equipment_search_button_export_clicked(self, equipment_search_button_export):
        with open('overview.csv', 'w', newline='') as f:
            writer = csv.writer(f)
            rows = self.current_items
            for row in rows:
                writer.writerow(row)

    def on_equipment_search_page_delete_event(self, *args):
        Gtk.main_quit(*args)

class Log(Widget):
    def __init__(self, queries, store_func, parent, com_store, proc_store):
        self.queries = queries
        self.entries = {"equipment_log_entry_eal" : 0, "equipment_log_entry_from" : 2, "equipment_log_entry_procedure" : 3, "equipment_log_entry_message" : 4}

        setup = {"glade_file" : "Glade/equipment_log.glade",
                 "widget_id" :  "equipment_log_page",
                 "widget_scroll_id" : "equipment_log_scroll_window",
                 "widget_calander_id" : "equipment_log_calendar_date",
                 "timer_query" : queries.logbook["select"],
                 "store_setup" : Gtk.ListStore(str, str, str, str, str),
                 "column_numbers" : (0,1,2,3,4),
                 "column_headings" : ["EAL Number", "Log Date", "Location", "Documents", "Message"],
                 "entries" : self.entries,
                 "file_chooser" : None}

        Widget.__init__(self, store_func, parent, queries, **setup)

        Function.entry_completion(self, com_store, "equipment_log_entry_eal", 0)
        Function.entry_completion(self, proc_store, "equipment_log_entry_procedure", 2)

    def on_equipment_log_button_enter_clicked(self, equipment_log_button_enter):
        entries = ["equipment_log_entry_eal", "equipment_log_entry_from", "equipment_log_entry_procedure", "equipment_log_entry_message"]
        text = Function.get_entries(self, entries)
        log_date = Cal_Date.date(self, "equipment_log_calendar_date")
        now = datetime.now()
        log_values = (now, text[0], log_date, text[1], text[2], text[3])
        log_query = self.queries.logbook["insert"]
        self.log_insert(log_query, log_values)

        Function.clear_entries(self, entries)

    def on_equipment_log_button_clear_clicked(self, equipment_log_button_clear):
        self.tree_selection.unselect_all()
        entries = self.entries
        Function.clear_entries(self, entries)
        self.current_filter = None

    def on_equipment_log_entry_eal_changed(self, entry):
        search = entry.get_text()
        self.current_filter = search.upper()
        self.current_filter_column = 0
        self.filter.refilter()

    def on_equipment_log_page_delete_event(self, *args):
        Gtk.main_quit(*args)

class DocAdd(Widget):
    def __init__(self, queries, store_func, parent):
        self.queries = queries
        self.entries = {"documents_add_entry_for" : 0, "documents_add_entry_ref" : 1, "documents_add_entry_name" : 2, "documents_add_entry_issue" : 3, "documents_add_entry_reason" : 4}

        setup = {"glade_file" : "Glade/documents.glade",
                 "widget_id" :  "documents_add_page",
                 "widget_scroll_id" : "documents_add_scroll_window",
                 "widget_calander_id" : "documents_add_calendar_date",
                 "timer_query" : queries.documents["select"],
                 "store_setup" : Gtk.ListStore(str, str, str, int, str, str, str),
                 "column_numbers" : (0,1,2,3,4,5,6),
                 "column_headings" : ["Client", "Reference", "Name", "Issue", "Reason for Issue", "Date", "File"],
                 "entries" : self.entries,
                 "file_chooser" : "documents_add_file_path"}

        Widget.__init__(self, store_func, parent, queries, **setup)

        Function.entry_completion(self, self.store, "documents_add_entry_for", 0)
        Function.entry_completion(self, self.store, "documents_add_entry_ref", 1)
        Function.entry_completion(self, self.store, "documents_add_entry_name", 2)

    def on_documents_add_button_enter_clicked(self, documents_add_button_enter):
        entries = ["documents_add_entry_for", "documents_add_entry_ref", "documents_add_entry_name", "documents_add_entry_issue", "documents_add_entry_reason"]
        text = Function.get_entries(self, entries)
        date = Cal_Date.date(self, "documents_add_calendar_date")

        doc = ''
        if self.file != None:
            file_name = text[2]
            file_settings = {"dep":"Procedures", "sub":text[0], "eal_ref":None}
            doc = Function.file_path2(self, self.file, file_name, file_settings)
            shutil.copy(self.file, doc)
            self.file_chooser.unselect_all()
        else:
            doc = "Not Uploaded"

        now = datetime.now()
        for item in self.current_items:
            row = list(item)
            if row[1] == text[1]:
                match = True
                break
            else:
                match = False

        if match == True:
            query = self.queries.documents["update"]
            values = (now, text[0], text[2], text[3], text[4], date, doc, text[1])
            procedure = 'N/A'
            message = text[1] + ' updated field'
            log_query = self.queries.logbook["insert"]
            log_values = (now, text[0], now, text[4], text[3], message)
            self.update(query, values, log_query, log_values)

        elif match == False:
            query = self.queries.documents["insert"]
            values = (now, text[0], text[1], text[2], text[3], text[4], date, doc)
            log_query = self.queries.logbook["insert"]
            log_values = (now, text[1], date, "N/A", text[2], text[4])
            self.insert(query, values, log_query, log_values)
        Function.clear_entries(self, entries)

    def on_documents_add_button_clear_clicked(self, documents_add_button_clear):
        self.tree_selection.unselect_all()
        self.file_chooser.unselect_all()
        entries = self.entries
        Function.clear_entries(self, entries)
        self.current_filter = None

    def on_documents_add_file_path_file_set(self, documents_add_file_path):
        self.file_chooser = documents_add_file_path
        self.file = self.file_chooser.get_filename()

    def on_documents_add_entry_ref_changed(self, entry):
        search = entry.get_text()
        self.current_filter = search.upper()
        self.current_filter_column = 1
        self.filter.refilter()

    def on_documents_add_entry_for_changed(self, entry):
        search = entry.get_text()
        self.current_filter = search.upper()
        self.current_filter_column = 0
        self.filter.refilter()

    def on_documents_add_entry_name_changed(self, entry):
        search = entry.get_text()
        self.current_filter = search.upper()
        self.current_filter_column = 2
        self.filter.refilter()

        on_documents_add_entry_name_changed

    def on_documents_add_page_delete_event(self, *args):
        Gtk.main_quit(*args)


def remove_duplicates(arr:list):

    new_set=set(arr)

    return list(new_set)

print(remove_duplicates([1, 1, 2, 2, 3, 4, 5]))

# best approach for this will be off as below

def remove_dup_element(arr:list):

    unique_list=[]

    seen:set=set()

    for item in arr:

        if item not in seen:

            unique_list.append(item)
            seen.add(item)

    return unique_list

print(remove_dup_element([1, 1, 2, 2, 3, 4, 5]))


"""empty message

Revision ID: 4e0eba9ad9e9
Revises: 6ed46ab14773
Create Date: 2021-04-24 23:33:37.698316

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '4e0eba9ad9e9'
down_revision = '6ed46ab14773'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('Artist', 'seeking_venue',
               existing_type=sa.BOOLEAN(),
               nullable=True)
    op.alter_column('Venue', 'seeking_talent',
               existing_type=sa.BOOLEAN(),
               nullable=True)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('Venue', 'seeking_talent',
               existing_type=sa.BOOLEAN(),
               nullable=False)
    op.alter_column('Artist', 'seeking_venue',
               existing_type=sa.BOOLEAN(),
               nullable=False)
    # ### end Alembic commands ###


import random

import cv2
import mujoco_py
import numpy as np
import warnings
from PIL import Image
from gym.spaces import Box, Dict

from multiworld.core.multitask_env import MultitaskEnv
from multiworld.core.wrapper_env import ProxyEnv
from multiworld.envs.env_util import concatenate_box_spaces
from multiworld.envs.env_util import get_stat_in_paths, create_stats_ordered_dict

from gym.spaces import Box, Dict

class GymToMultiEnv(ProxyEnv): # MultitaskEnv):
    def __init__(
            self,
            wrapped_env,
    ):
        """Minimal env to convert a gym env to one with dict observations"""
        self.quick_init(locals())
        super().__init__(wrapped_env)

        obs_box = wrapped_env.observation_space
        self.observation_space = Dict([
            ('observation', obs_box),
            ('state_observation', obs_box),
        ])

    def step(self, action):
        obs, reward, done, info = self.wrapped_env.step(action)
        new_obs = dict(
            observation=obs,
            state_observation=obs,
        )
        return new_obs, reward, done, info

    def reset(self):
        obs = self.wrapped_env.reset()
        new_obs = dict(
            observation=obs,
            state_observation=obs,
        )
        return new_obs

    def _get_obs(self):
        raise NotImplementedError()

class MujocoGymToMultiEnv(GymToMultiEnv):
    def set_state(self, qpos, qvel):
        assert qpos.shape == (self.model.nq,) and qvel.shape == (self.model.nv,)
        old_state = self.sim.get_state()
        new_state = mujoco_py.MjSimState(old_state.time, qpos, qvel,
                                         old_state.act, old_state.udd_state)
        self.sim.set_state(new_state)
        self.sim.forward()

    @property
    def dt(self):
        return self.model.opt.timestep * self.frame_skip

    def do_simulation(self, ctrl, n_frames=None):
        if n_frames is None:
            n_frames = self.frame_skip
        if self.sim.data.ctrl is not None and ctrl is not None:
            self.sim.data.ctrl[:] = ctrl
        for _ in range(n_frames):
            self.sim.step()

    def render(self, mode='human'):
        if mode == 'rgb_array':
            self._get_viewer().render()
            # window size used for old mujoco-py:
            width, height = 500, 500
            width, height = 4000, 4000
            data = self._get_viewer().read_pixels(width, height, depth=False)
            # original image is upside-down, so flip it
            return data[::-1, :, :]
        elif mode == 'human':
            self._get_viewer().render()

    def close(self):
        if self.viewer is not None:
            self.viewer.finish()
            self.viewer = None

    def _get_viewer(self):
        if self.viewer is None:
            self.viewer = mujoco_py.MjViewer(self.sim)
            self.viewer_setup()
        return self.viewer

    def get_body_com(self, body_name):
        return self.data.get_body_xpos(body_name)

    def state_vector(self):
        return np.concatenate([
            self.sim.data.qpos.flat,
            self.sim.data.qvel.flat
        ])

    def get_image(self, width=84, height=84, camera_name=None):
        return self.sim.render(
            width=width,
            height=height,
            camera_name=camera_name,
        )

    def initialize_camera(self, init_fctn):
        sim = self.sim
        viewer = mujoco_py.MjRenderContextOffscreen(sim, device_id=self.device_id)
        init_fctn(viewer.cam)
        sim.add_render_context(viewer)

    def get_diagnostics(self, paths, **kwargs):
        return {}


# Importando librerías
import pandas as  pd
import numpy as np
from statsmodels.formula.api import ols

# Definiendo ruta de trabajo
path='C:/Users/CTIC - UNI/Documents/clase2/'
# Importando data
ventas=pd.read_csv(path+'ventas.csv',sep=',')

# Cambiando nombres de las columnas
ventas.columns=['ventas','precio','public','calid','miss']
# Eliminando columnas
ventas.drop(['miss'],axis=1,inplace=True)

# Analizando correlación entre variables
correlaciones=pd.DataFrame(np.corrcoef(ventas,rowvar=False))
correlaciones.columns=ventas.columns
correlaciones.index=ventas.columns

# Regresión Lineal: MCO
#######################
# Definiendo objeto
modelo=ols(formula='ventas~precio+public+calid',data=ventas)
# Entrenando el modelo
modelo=modelo.fit()
# Summary
modelo.summary()

#Extrayendo objetos
modelo.params # coeficientes
modelo.bse # std(coeficientes)

# prueba de hipotesis
# Ho = bcalidad=0

# Definiento parametros
alpha=0.05 #nivel de significancia
k=0 # valor a testear

# Estadistico calculado
tcalc=(modelo.params[3]-k)/modelo.bse[3]

# Estadistico de tablas
from scipy import stats
ttab = stats.t.ppf(alpha/2,len(ventas)-len(modelo.params))

# Regla de desicion
if abs(tcalc)>abs(ttab):
    print('Se rechaza Ho')
else:
    print('No se Rechaza Ho')

# Intervalo de confianza
ls_calid=modelo.params[3]+stats.t.ppf(1-alpha/2,len(ventas)-len(modelo.params))*modelo.bse[3]
ls_calid=modelo.params[3]+stats.t.ppf(alpha/2,len(ventas)-len(modelo.params))*modelo.bse[3]


import sys
sys.stdin=open("input.txt")

def perm(k,before,s):
    global result
    if k==n:
        s+=arr[before][0]
        if result>s:
            result=s
        return
    elif result<=s:
        return
    else:
        for i in range(1,n):
            if not visited[i]:
                visited[i]=1
                perm(k+1,i,s+arr[before][i])
                visited[i]=0
    return

for t in range(int(input())):
    n=int(input())
    arr=[[int(x)for x in input().split()] for _ in range(n)]
    visited=[0]*n
    result=10000

    perm(1,0,0)
    print("#{} {}".format(t+1,result))

Python/SW Expert Academy/Programming Advanced/Brute Force/5189. 전자카트.py


from __future__ import print_function

__all__ = [
    "makeAgentService",
]

import cStringIO
from plistlib import readPlistFromString, writePlistToString
import socket

from twext.python.launchd import launchActivateSocket
from twext.python.log import Logger
from twext.who.checker import HTTPDigestCredentialChecker
from twext.who.opendirectory import (
    DirectoryService as OpenDirectoryDirectoryService,
    NoQOPDigestCredentialFactory
)
from twisted.application.internet import StreamServerEndpointService
from twisted.cred.portal import IRealm, Portal
from twisted.internet.defer import inlineCallbacks, returnValue
from twisted.internet.endpoints import AdoptedStreamServerEndpoint
from twisted.internet.protocol import Factory
from twisted.protocols import amp
from twisted.web.guard import HTTPAuthSessionWrapper
from twisted.web.resource import IResource, Resource, ForbiddenResource
from twisted.web.server import Site, NOT_DONE_YET
from zope.interface import implements

log = Logger()

class AgentRealm(object):
    """
    Only allow a specified list of avatar IDs to access the site
    """
    implements(IRealm)

    def __init__(self, root, allowedAvatarIds):
        """
        @param root: The root resource of the site
        @param allowedAvatarIds: The list of IDs to allow access to
        """
        self.root = root
        self.allowedAvatarIds = allowedAvatarIds

    def requestAvatar(self, avatarId, mind, *interfaces):
        if IResource in interfaces:
            if avatarId.shortNames[0] in self.allowedAvatarIds:
                return (IResource, self.root, lambda: None)
            else:
                return (IResource, ForbiddenResource(), lambda: None)

        raise NotImplementedError()

class AgentGatewayResource(Resource):
    """
    The gateway resource which forwards incoming requests through
    gateway.Runner.
    """
    isLeaf = True

    def __init__(self, store, directory, inactivityDetector):
        """
        @param store: an already opened store
        @param directory: a directory service
        @param inactivityDetector: the InactivityDetector to tell when requests
            come in
        """
        Resource.__init__(self)
        self.store = store
        self.directory = directory
        self.inactivityDetector = inactivityDetector

    def render_POST(self, request):
        """
        Take the body of the POST request and feed it to gateway.Runner();
        return the result as the response body.
        """

        self.inactivityDetector.activity()

        def onSuccess(result, output):
            txt = output.getvalue()
            output.close()
            request.write(txt)
            request.finish()

        def onError(failure):
            message = failure.getErrorMessage()
            tbStringIO = cStringIO.StringIO()
            failure.printTraceback(file=tbStringIO)
            tbString = tbStringIO.getvalue()
            tbStringIO.close()
            error = {
                "Error": message,
                "Traceback": tbString,
            }
            log.error("command failed {error}", error=failure)
            request.write(writePlistToString(error))
            request.finish()

        from calendarserver.tools.gateway import Runner
        body = request.content.read()
        command = readPlistFromString(body)
        output = cStringIO.StringIO()
        runner = Runner(self.store, [command], output=output)
        d = runner.run()
        d.addCallback(onSuccess, output)
        d.addErrback(onError)
        return NOT_DONE_YET

def makeAgentService(store):
    """
    Returns a service which will process GatewayAMPCommands, using a socket
    file descripter acquired by launchd

    @param store: an already opened store
    @returns: service
    """
    from twisted.internet import reactor

    sockets = launchActivateSocket("AgentSocket")
    fd = sockets[0]

    family = socket.AF_INET
    endpoint = AdoptedStreamServerEndpoint(reactor, fd, family)

    directory = store.directoryService()

    def becameInactive():
        log.warn("Agent inactive; shutting down")
        reactor.stop()

    from twistedcaldav.config import config
    inactivityDetector = InactivityDetector(
        reactor, config.AgentInactivityTimeoutSeconds, becameInactive
    )
    root = Resource()
    root.putChild(
        "gateway",
        AgentGatewayResource(
            store, directory, inactivityDetector
        )
    )

    # We need this service to be able to return com.apple.calendarserver,
    # so tell it not to suppress system accounts.
    directory = OpenDirectoryDirectoryService(
        "/Local/Default", suppressSystemRecords=False
    )

    portal = Portal(
        AgentRealm(root, [u"com.apple.calendarserver"]),
        [HTTPDigestCredentialChecker(directory)]
    )
    credentialFactory = NoQOPDigestCredentialFactory(
        "md5", "/Local/Default"
    )
    wrapper = HTTPAuthSessionWrapper(portal, [credentialFactory])

    site = Site(wrapper)

    return StreamServerEndpointService(endpoint, site)

class InactivityDetector(object):
    """
    If no 'activity' takes place for a specified amount of time, a method
    will get called.  Activity causes the inactivity time threshold to be
    reset.
    """

    def __init__(self, reactor, timeoutSeconds, becameInactive):
        """
        @param reactor: the reactor
        @timeoutSeconds: the number of seconds considered to mean inactive
        @becameInactive: the method to call (with no arguments) when
            inactivity is reached
        """
        self._reactor = reactor
        self._timeoutSeconds = timeoutSeconds
        self._becameInactive = becameInactive

        if self._timeoutSeconds > 0:
            self._delayedCall = self._reactor.callLater(
                self._timeoutSeconds,
                self._inactivityThresholdReached
            )

    def _inactivityThresholdReached(self):
        """
        The delayed call has fired.  We're inactive.  Call the becameInactive
            method.
        """
        self._becameInactive()

    def activity(self):
        """
        Call this to let the InactivityMonitor that there has been activity.
        It will reset the timeout.
        """
        if self._timeoutSeconds > 0:
            if self._delayedCall.active():
                self._delayedCall.reset(self._timeoutSeconds)
            else:
                self._delayedCall = self._reactor.callLater(
                    self._timeoutSeconds,
                    self._inactivityThresholdReached
                )

    def stop(self):
        """
        Cancels the delayed call
        """
        if self._timeoutSeconds > 0:
            if self._delayedCall.active():
                self._delayedCall.cancel()

#
# Alternate implementation using AMP instead of HTTP
#

class GatewayAMPCommand(amp.Command):
    """
    A command to be executed by gateway.Runner
    """
    arguments = [('command', amp.String())]
    response = [('result', amp.String())]

class GatewayAMPProtocol(amp.AMP):
    """
    Passes commands to gateway.Runner and returns the results
    """

    def __init__(self, store, directory):
        """
        @param store: an already opened store
            operations
        @param directory: a directory service
        """
        amp.AMP.__init__(self)
        self.store = store
        self.directory = directory

    @GatewayAMPCommand.responder
    @inlineCallbacks
    def gatewayCommandReceived(self, command):
        """
        Process a command via gateway.Runner

        @param command: GatewayAMPCommand
        @returns: a deferred returning a dict
        """
        command = readPlistFromString(command)
        output = cStringIO.StringIO()
        from calendarserver.tools.gateway import Runner
        runner = Runner(
            self.store,
            [command], output=output
        )

        try:
            yield runner.run()
            result = output.getvalue()
            output.close()
        except Exception as e:
            error = {"Error": str(e)}
            result = writePlistToString(error)

        output.close()
        returnValue(dict(result=result))

class GatewayAMPFactory(Factory):
    """
    Builds GatewayAMPProtocols
    """
    protocol = GatewayAMPProtocol

    def __init__(self, store):
        """
        @param store: an already opened store
        """
        self.store = store
        self.directory = self.store.directoryService()

    def buildProtocol(self, addr):
        return GatewayAMPProtocol(
            self.store, self.davRootResource, self.directory
        )

#
# A test AMP client
#

command = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
 "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>command</key>
        <string>getLocationAndResourceList</string>
</dict>
</plist>"""

def getList():
    # For the sample client, below:
    from twisted.internet import reactor
    from twisted.internet.protocol import ClientCreator

    creator = ClientCreator(reactor, amp.AMP)
    host = '127.0.0.1'
    import sys
    if len(sys.argv) > 1:
        host = sys.argv[1]
    d = creator.connectTCP(host, 62308)

    def connected(ampProto):
        return ampProto.callRemote(GatewayAMPCommand, command=command)
    d.addCallback(connected)

    def resulted(result):
        return result['result']
    d.addCallback(resulted)

    def done(result):
        print('Done: %s' % (result,))
        reactor.stop()
    d.addCallback(done)
    reactor.run()

if __name__ == '__main__':
    getList()


#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from __future__ import print_function

import os
import sys

from pyspark.sql import SparkSession
from pyspark.sql.functions import explode, split
from pyspark.sql.types import (ArrayType, StringType)
import timeit
import spark_jython

def legacy_word_count(rdd):
    wc = rdd.flatMap(lambda x: x.split(" ")).map(lambda w: (w, 1)).reduceByKey(lambda x, y: x + y)
    return wc.count()

def dataframe_udf_word_count(tokenizeUDF, df):
    wc = df.select(tokenizeUDF(df['value']).alias("w")).select(explode("w").alias("words")) \
        .groupBy("words").count()
    return wc.count()

def dataframe_scala_udf_word_count(df):
    wc = df.select(split(df['value'], " ").alias("w")).select(explode("w").alias("words")) \
        .groupBy("words").count()
    return wc.count()

def benchmark(textInputPath, repeat, number):
    """
    Benchmark wordcount on a provided text input path with a given number
    of repeats each executed number times.

    :param textInputPath: The input path to perform wordcount on.
    :param repeat: Number of times to repeat the test
    :param number: Number of iterations to perform the wordcount per test
    """
    def benchmark_func(func):
        return timeit.repeat(func, repeat=repeat, number=number)

    print("Benchmarking wordcount:")
    tokenize = lambda x: x.split(" ")
    returnUDFType = ArrayType(StringType())
    # session.catalog.registerFunction does not return under spark 2.0
    from pyspark.sql.functions import UserDefinedFunction
    tokenizeUDF = UserDefinedFunction(tokenize, returnUDFType, 'split')
    session.catalog.registerFunction("split", tokenize, returnUDFType)

    tokenizeJythonUDF = session.catalog.registerJythonFunction("split", tokenize, returnUDFType)
    rdd = sc.textFile(textInputPath)
    rdd.cache()
    rdd.count()
    print("RDD:")
    print(timeit.repeat(lambda: legacy_word_count(rdd), repeat=repeat, number=number))
    rdd.unpersist()
    df = session.read.text(textInputPath)
    df.cache()
    df.count()
    print("DataFrame Python UDF:")
    python_udf_test_lambda = lambda: dataframe_udf_word_count(tokenizeUDF, df)
    python_udf_times = timeit.repeat(python_udf_test_lambda, repeat=repeat, number=number)
    print(python_udf_times)
    print("DataFrame Jython UDF:")
    jython_udf_test_lambda = lambda: dataframe_udf_word_count(tokenizeJythonUDF, df)
    jython_udf_times = timeit.repeat(jython_udf_test_lambda, repeat=repeat, number=number)
    print(jython_udf_times)
    print("DataFrame Scala UDF:")
    scala_udf_test_lambda = lambda: dataframe_scala_udf_word_count(df)
    scala_udf_times = timeit.repeat(scala_udf_test_lambda, repeat=repeat, number=number)
    print(scala_udf_times)

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("Usage: sql_udf_perf <inputPath> <repeat> <number>", file=sys.stderr)
        sys.exit(-1)

    session = SparkSession \
        .builder \
        .appName("PythonSQL Per") \
        .getOrCreate()
    sc = session._sc
    spark = session
    textInputPath = sys.argv[1]
    repeat = int(sys.argv[2])
    number = int(sys.argv[3])
    benchmark(textInputPath, repeat, number)


def main():
    from sys import stdin
    input = stdin.readline

    # 入力を受け取る
    N = input().rstrip()

    # Nの桁数を求める
    len_N = len(N)
    N = int(N)

    cnt = 0
    # N-1桁目までの各桁について、数をカウント
    for i in range(1, len_N):
        n = 9 * (10**(i-1))
        cnt += int(n*(n+1)//2) % 998244353

    # N桁目について、数をカウント
    n = N - (10**(len_N-1) -1)
    cnt += int(n*(n+1)//2) % 998244353

    print(cnt % 998244353)

if __name__ == '__main__':
    main()


__author__ = 'Simone Biffi'

from datetime import datetime
import numpy as np
from helper import image
import cv2
contatore  = 0

def horizontal_run_length_smoothing(x, limit) :
    horizontal = np.copy(x)
    start = 0
    count = 0
    now = 0
    for i in np.nditer(horizontal):
        if i == 0:
            if count == 0:
                start = now
            count += 1
        if i == 1:
            if count <= limit:
                horizontal[start: now] = 1
                count = 0
        now += 1
    return horizontal

def vertical_run_length_smoothing(x, limit):
    vertical = np.copy(x)
    start = 0
    count = 0
    now = 0
    for i in np.nditer(vertical):
        if i == 0:
            if count == 0:
                start = now
            count += 1
        if i == 1:
            if count <= limit:
                vertical[start: now] = 1
                count = 0
        now += 1
    return vertical

timer = datetime.now()

# loads the image and convert to grayscale
img, gray = image.load_and_gray('../../samples/bolletta3.jpg')

binary = image.binarize(gray)

binary[binary == 0] = 1 # black pixel
binary[binary == 255] = 0 # white pixel

#vertical
vertical = np.apply_along_axis(vertical_run_length_smoothing, axis=0, arr=binary, limit = 280)

#horizontal
horizontal = np.apply_along_axis(horizontal_run_length_smoothing, axis=1, arr=binary, limit = 300)

tmp = np.bitwise_and(horizontal, vertical)

result = np.apply_along_axis(horizontal_run_length_smoothing, axis=1, arr=tmp, limit = 30)

result[result == 0] = 255
result[result == 1] = 0
cv2.imwrite('../../samples/rlsa.png', result)

print((datetime.now()-timer))


import primegen
import re
from primroot import primroot

def convert_chars_to_int(msg):
    """
    Функция перевода символов в числа
    """
    return [ord(ch) for ch in msg]

def convert_int_to_chars(num_to_decode):
    """
    Функция перевода чисел в символы
    """
    return "".join([chr(num) for num in num_to_decode])

def dh_encode(msg_to_encode):

    # переводим символы в числа
    numbers_list = convert_chars_to_int(msg_to_encode)

    print(numbers_list)

    # генерируем простые числа
    a_priv = primegen.prime_gen(40)
    b_priv = primegen.prime_gen(40)

    p = primegen.prime_gen(50)
    q = primroot(p)

    print(f"prime = {p}\n")

    print(f"primitive root = {q}\n")

    A_pub = pow(q, a_priv, p)
    B_pub = pow(q, b_priv, p)

    print(f"A_pub = {A_pub}, A_priv = {a_priv}\n")

    print(f"B_pub = {B_pub}, A_priv = {b_priv}\n")

    K_a = pow(B_pub, a_priv, p)
    K_b = pow(A_pub, b_priv, p)

    print(f"secret key = {K_a}\n")

    print("Use cesar for encoding with sec. key\n")
    encoded_num = [(num + K_a) % 255 for num in numbers_list]
    print(encoded_num)

    return convert_int_to_chars(encoded_num), K_a

def dh_decode(msg_to_decode, key):
    return convert_int_to_chars([(ord(ch) - key) % 255 for ch in msg_to_decode])

def main():

    isLatinNumString = False

    while isLatinNumString != True:

        # получаем входную строку
        message = input("Введите сообщение для отправки: ")

        if re.fullmatch("^[A-Za-z0-9]+$", message):
            isLatinNumString = True
        else:
            print("only Latin symbols and numbers")

    encoded_message, sec_key = dh_encode(message)

    print("Закодированное сообщение: " + encoded_message)

    decoded_message = dh_decode(encoded_message, sec_key)

    print("Декодированное сообщение: " + decoded_message)

if __name__ == '__main__':
    main()


import numpy as np
import pandas as pd

def eventprofile(data, events, lookback=1, lookforward=1, accum=False):
    '''Event Profiler for a pandas.DataFrame of symbols indexed
    events are picked from the events dataframe by the symbol name and index.
    Output data is normalized agains the event value'''

    index = range(-lookback,lookforward+1)
    periods = pd.DataFrame([], index=index)

    i = 0
    for symbol in events.columns:
        for index in events[events[symbol] != False].index.tolist():
            loc = data.index.get_loc(index)
            period = data.iloc[loc-lookback:loc+lookforward+1][symbol]
            if period.size == lookback + lookforward + 1:
                if accum:
                    period = period.cumsum()
                period = period - period.iloc[lookback]
                periods[i] = period.values
                i += 1

    # Study Params
    mean = np.mean(periods, axis=1)
    mean.name = 'mean'
    std = np.std(periods, axis=1)
    std.name = 'std'
    count = periods.count(axis=1)
    count.name = 'count'

    return pd.concat([mean, std, count], axis=1)


"""
Authors: Spotlight Pathology Ltd
License: Apache License V.2
"""

from torch.utils.data import DataLoader, Dataset, Subset
import torch
from skimage.io import imread
from skimage import img_as_float32, img_as_ubyte
import json
import os
from shutil import rmtree
import h5py as h5
import uuid
from train.preprocessing.transforms import (
    detection_resize_tiling,
    get_box_to_fit,
    convert_bbox,
    augment_detections
)

class SimpleDataset(Dataset):
    def __init__(self, tensor_list):
        self.tensor_list = tensor_list

    def __len__(self):
        return len(self.tensor_list)

    def __getitem__(self, idx):
        return self.tensor_list[idx]

class DetectionsDataset(Dataset):
    def __init__(
            self,
            image_paths,
            labels_json,
            size: int,
            stride: int,
            tempdir: str,
            augment: bool,
            augment_p: float = None,
            resize_by_tiling: bool = True,
            include_empty: bool = False,
            balance_empty: bool = False,
            balance_empty_weight: float = 0.1,
    ):
        with open(labels_json) as f:
            json_dict = json.load(f)
            self.labels = json_dict['annotations']
            all_images = json_dict['images']

        # map images to the correct filepaths
        self.images = []
        for image in all_images:
            old_path = os.path.basename(image['file_name'])
            new_path = [p for p in image_paths if old_path in p]
            if len(new_path) == 1:
                image['file_name'] = new_path[0]
                self.images.append(image)
        assert len(self.images) == len(image_paths)

        # create targets per image
        self.num_has_targets = 0
        self.num_empty = 0
        self.include_empty = include_empty
        self.resize_by_tiling = resize_by_tiling
        self.balance_empty = balance_empty
        self.augment = augment
        self.augment_p = augment_p
        self.data = []
        self.create_targets()
        self.size = size
        self.stride = stride
        self.tempdir = tempdir
        self.tile_data = []

        if self.resize_by_tiling:
            for datapoint in self.data:
                image = imread(datapoint[0])

                tiles, tile_targets = detection_resize_tiling(
                    image,
                    target=datapoint[1],
                    size=self.size,
                    stride=self.stride,
                    include_empty=self.include_empty
                )
                self.save_tiles(tiles, tile_targets, datapoint[0])

        else:
            for datapoint in self.data:
                image = imread(datapoint[0])
                self.save_tiles([image], [datapoint[1]], datapoint[0])

        if self.balance_empty:
            self.weights = self.make_weights_for_balanced_density(
                balance_empty_weight
            )

        # count how many dataset items have lymphocytes
        for tdata in self.tile_data:
            targets = tdata[1]
            has_targets = torch.max(targets["labels"]).item() > 0
            if has_targets:
                self.num_has_targets += 1
            else:
                self.num_empty += 1

    def save_tiles(self, tiles, tile_targets, im_name):
        """Save tiles temporarily as h5 to avoid memory overload."""
        for i, tile in enumerate(tiles):
            tileh5 = os.path.join(
                self.tempdir,
                os.path.basename(im_name) + str(uuid.uuid4()) + '.h5'
            )
            self.tile_data.append([tileh5, tile_targets[i]])

            with h5.File(tileh5, 'w') as f:
                f.create_dataset(
                    'tile', data=tile,
                    compression='gzip',
                )

    def create_targets(self):
        """
        Create targets per image by combining all bboxes for each image.
        """
        for image in self.images:

            image_id = image['id']
            image_labels = [
                bbox for bbox in self.labels
                if bbox['image_id'] == image_id
            ]

            img_path = image['file_name']
            img_shape = imread(img_path).shape
            img_dims = (img_shape[1], img_shape[0])

            # add to dataset only if there are some detections in image
            if len(image_labels) > 0:
                target = {}
                # boxes converted to x0, y0, x1, y1 and reshaped to fit in img
                target['boxes'] = torch.FloatTensor(
                    [
                        get_box_to_fit(convert_bbox(bbox['bbox']), img_dims)
                        for bbox in image_labels
                    ]
                )
                target['labels'] = torch.IntTensor([1 for _ in image_labels])
                target['labels'] = target['labels'].to(torch.int64)
                target['image_id'] = torch.tensor(image_id)
                target['area'] = torch.tensor(
                    [bbox['area'] for bbox in image_labels]
                )
                target['iscrowd'] = torch.IntTensor(
                    [bbox['iscrowd'] for bbox in image_labels]
                )
                self.data.append([img_path, target])
                self.num_has_targets += 1
            else:
                if self.include_empty:
                    # if no targets are found in image, add a dummy "0" type
                    # object
                    target = {}
                    target['boxes'] = torch.FloatTensor([[1, 2, 3, 4]])
                    target['labels'] = torch.IntTensor([0])
                    target['labels'] = target['labels'].to(torch.int64)
                    target['image_id'] = torch.tensor(image_id)
                    target['area'] = torch.tensor([4])
                    target['iscrowd'] = torch.IntTensor([0])

                    self.data.append([img_path, target])
                    self.num_empty += 1
                pass

    def make_weights_for_balanced_density(self, weight_empty=0.1):
        weight_has_targets = 1 - weight_empty
        weights = []

        data = self.tile_data

        for idx, (_, target) in enumerate(data):
            has_targets = torch.max(target["labels"]).item() > 0
            if has_targets:
                weights.append(weight_has_targets)
            else:
                weights.append(weight_empty)
        weights = torch.DoubleTensor(weights)
        return weights

    def __getitem__(self, idx):
        im_path, target = self.tile_data[idx]
        with h5.File(im_path, 'r') as f:
            img = f.get('tile')[:]

        img = img_as_ubyte(img)
        if self.augment:  # img must be uint8
            img, target = augment_detections(img, target, self.augment_p)

        img = img_as_float32(img)
        img = torch.tensor(img).permute(2, 0, 1)
        return img, target, im_path

    def __len__(self):
        return len(self.tile_data)

    def clean_up(self):
        rmtree(self.tempdir)

def create_detection_loader(
        image_paths,
        labels_json: str,
        batch_size: int,
        reshuffle: bool,
        num_workers: int,
        size: int = None,
        stride: int = None,
        tempdir: str = None,
        subset: int = None,
        augment: bool = False,
        augment_p: float = None,
        resize_by_tiling: bool = True,
        include_empty: bool = False,
        balance_empty: bool = False,
        balance_empty_weight: float = 0.1,
):
    """
    Create a dataloader for cell detection.
    """
    dataset = DetectionsDataset(
        image_paths=image_paths,
        labels_json=labels_json,
        size=size,
        stride=stride,
        tempdir=tempdir,
        augment=augment,
        augment_p=augment_p,
        resize_by_tiling=resize_by_tiling,
        include_empty=include_empty,
        balance_empty=balance_empty,
        balance_empty_weight=balance_empty_weight,
    )

    if (subset is not None) & (not balance_empty):
        indices = torch.randperm(subset)
        dataset = Subset(dataset, indices=indices)

    if balance_empty:
        # will create a dataset of same length by weighted
        # random sampling WITH replacement
        sampler = torch.utils.data.sampler.WeightedRandomSampler(
            dataset.weights,
            len(dataset) if subset is None else subset
        )
        loader = DataLoader(
            dataset,
            batch_size=batch_size,
            num_workers=num_workers,
            pin_memory=True,  # required for multiprocessing with cuda
            prefetch_factor=2,
            collate_fn=collate_fn,
            sampler=sampler
        )
    else:
        loader = DataLoader(
            dataset,
            batch_size=batch_size,
            shuffle=reshuffle,  # this determines if we will reshuffle
            num_workers=num_workers,
            pin_memory=True,  # required for multiprocessing with cuda
            prefetch_factor=2,
            collate_fn=collate_fn
        )
    return loader

def collate_fn(batch):
    return tuple(zip(*batch))


#4
n = int(input("Podaj liczbę nie większą niż 8: "))
if n >= 8:
    print('Liczba powinna być większa niż 8')
else:
    s = 1
    for i in range(n + 1):
        if i == 0:
            print('0 ! = 1')
        else:
            s *= i
            print(i,"! =", s)

#2
items = ["woda", "herbata", "cytryna", "miód"]
print("Zagotuj wodę")
for step in items:
    print(step)
print("Podawaj w szklance")

#3
x=0
for i in range(1,11):
    x += i
    print(x)

my_list = ["ada", "ala"]
for step in my_list:
    print(step)

for step in range(5):
    print(step)

for step in range(2,10,2):
    print(step)

list=["Ada", "Julia", "Rob"]
for step in range(3):
    print(step, ':', list[step])

txt='aasjdhlafh'
for letter in txt:
    print("-", letter)


import os
from setuptools import Extension, setup

try:
    from Cython.Build import cythonize
except ImportError:
    cythonize = None

extensions = [
    Extension(
        name="nixstrings",
        sources=[
            "nixstrings.pyx",
        ],
    )
]
if cythonize:
    extensions = cythonize(extensions, compiler_directives={'language_level' : "3"},)

setup(ext_modules=extensions)


class ShortNameException(Exception):
    '''This is user defined Exception class which must be sub class of Exception'''
    def __init__(self, lenght, atleast):
        Exception.__init__(self)
        self.length = lenght
        self.atleast = atleast

class InvalidAgeException(Exception):
    def __init__(self, age,minage):
        Exception.__init__(self)
        self.age = age
        self.minage = minage

try:
    name = input('Enter name:')
    if len(name) < 3:
        raise ShortNameException(len(name),3)
    age = int(input('Enter age:'))
    if age < 18:
        raise InvalidAgeException(age, 18)
except EOFError:
    print('Why did you enter End Of File?')
except ShortNameException as ex:
    print(f'{name} should be at least {ex.atleast} chars but it has {ex.length}?')
except InvalidAgeException as ex:
    print(f'Given age {ex.age} should be at least {ex.minage}?')


from interpreter.instruction import Instruction
from interpreter.operator import Operator
from interpreter.quadruple import Quadruple, OperatorQuadruple
from interpreter.st import Symbol, SymbolTable

class Assignment(Instruction):
    def __init__(self, exp1, assignment_type, exp2, row):
        self.exp1 = exp1
        self.assignment_type = assignment_type
        self.exp2 = exp2
        self.row = row

    def firstRun(self, localE):
        exp2Name = self.exp2.firstRun(localE)
        exp2Name = exp2Name[1].temp if exp2Name[0] == "symbol" else exp2Name[1]
        exp1Name = self.exp1.firstRun(localE)
        exp1Name = exp1Name[1].temp if exp1Name[0] == "symbol" else exp1Name[1]
        if Operator.ASSIGN == self.assignment_type:
            q0 = Quadruple(OperatorQuadruple.ASSIGNMENT,exp2Name,None,exp1Name)
            Quadruple.QDict.append(q0)
            return ("tempname", q0.r)
        elif Operator.TIMESA == self.assignment_type:
            q0 = Quadruple(OperatorQuadruple.TIMES, exp1Name, exp2Name, exp1Name)
            Quadruple.QDict.append(q0)
            return ("tempname", q0.r)
        elif Operator.QUOTA == self.assignment_type:
            q0 = Quadruple(OperatorQuadruple.QUOTIENT, exp1Name, exp2Name, exp1Name)
            Quadruple.QDict.append(q0)
            return ("tempname", q0.r)
        elif Operator.REMA == self.assignment_type:
            q0 = Quadruple(OperatorQuadruple.REMAINDER, exp1Name, exp2Name, exp1Name)
            Quadruple.QDict.append(q0)
            return ("tempname", q0.r)
        elif Operator.PLUSA == self.assignment_type:
            q0 = Quadruple(OperatorQuadruple.PLUS, exp1Name, exp2Name, exp1Name)
            Quadruple.QDict.append(q0)
            return ("tempname", q0.r)
        elif Operator.MINUSA == self.assignment_type:
            q0 = Quadruple(OperatorQuadruple.MINUS, exp1Name, exp2Name, exp1Name)
            Quadruple.QDict.append(q0)
            return ("tempname", q0.r)
        elif Operator.SHRA == self.assignment_type:
            q0 = Quadruple(OperatorQuadruple.SHR, exp1Name, exp2Name, exp1Name)
            Quadruple.QDict.append(q0)
            return ("tempname", q0.r)
        elif Operator.SHLA == self.assignment_type:
            q0 = Quadruple(OperatorQuadruple.SHL, exp1Name, exp2Name, exp1Name)
            Quadruple.QDict.append(q0)
            return ("tempname", q0.r)
        elif Operator.ANDBWA == self.assignment_type:
            q0 = Quadruple(OperatorQuadruple.ANDBW, exp1Name, exp2Name, exp1Name)
            Quadruple.QDict.append(q0)
            return ("tempname", q0.r)
        elif Operator.XORBWA == self.assignment_type:
            q0 = Quadruple(OperatorQuadruple.XORBW, exp1Name, exp2Name, exp1Name)
            Quadruple.QDict.append(q0)
            return ("tempname", q0.r)
        elif Operator.ORBWA == self.assignment_type:
            q0 = Quadruple(OperatorQuadruple.ORBW, exp1Name, exp2Name, exp1Name)
            Quadruple.QDict.append(q0)
            return ("tempname", q0.r)


from queue import PriorityQueue
queue = PriorityQueue()
input_num = int(input())

for i in range(input_num):
    queue.put(int(input()))

result=0
count=0
while True:
    if queue.qsize()==1:
        print(result)
        break
    count=queue.get() + queue.get()
    queue.put(count)
    result+=count


import serial

class SerialConfig:
    '''Class holding the data neccessary for the serial configuration'''
    def __init__(self, port, baud, bytesize, parity, stopbits) -> None:
        '''Constructor'''
        self.port = port
        self.baud = baud
        self.bytesize = bytesize
        self.parity = parity
        self.stopbits = stopbits

serial_config = SerialConfig('COM5', 115200, 8, 'N', 1)
try:
    with serial.Serial(serial_config.port, serial_config.baud) as ser:
        # start char
        print('writing')
        ser.write(b'a')
        if ser.read() != b'a':
            print('no connection')
        else:
            print('serial connection available')
except Exception as e:
    print("no connection")


#!/usr/bin/env python3
import csv
import sys
import os
import pandas as pd
from difflib import SequenceMatcher
from test import *

def get_columns(file):
    colums = {}
    with open(file, "r") as f:
        for lines in f:
            splitted_line = lines.split(";")
            if (splitted_line[0][0] == "#" or splitted_line[0][0] == "\n"):
                continue
            if (splitted_line[-1][-1] == "\n" or splitted_line[-1][-1] == ";"):
                splitted_line[-1] = splitted_line[-1][:-1]
            colums[splitted_line[0]] = tuple(splitted_line[1:])
    return colums

def name_is_same(s1, s2):
    s1 = s1.upper()
    s2 = s2.upper()
    ratio = SequenceMatcher(None, s1, s2).ratio()
    if (ratio > 0.75):
        return True
    return False

def check_key(columns, column_name, new_row, df, source):
    new_file = []
    for index, row in df.iterrows():
        for key in columns["key"]:
             if (new_row[column_name.index(key)] == row[key]
             and len(new_row[column_name.index(key)])) or (len(columns["key"]) > 1 and key != columns["key"][0]and len(new_row[column_name.index(key)]) and name_is_same(new_row[column_name.index(key)], row[key])):
                for i in range(len(row) - 1):
                    if (len(row[i]) == 0 and len(new_row[i]) > 0):
                        row[i] = new_row[i]
                        row[i + 1] = cut_path(source)
                return False
    return True

def iterate_csv(column_name, columns, df):
    for i in range(len(sys.argv)):
        if (i > 1):
            with open("final_" + cut_path(sys.argv[i]), "r", encoding="utf-8") as f_2:
                reader = csv.DictReader(f_2, delimiter=";")
                for row in reader:
                    new_row = []
                    for c_name in column_name:
                        appended = False
                        if c_name in row:
                            new_row.append(row[c_name])
                            if (len(row[c_name])):
                                new_row.append(sys.argv[i])
                            else:
                                new_row.append("")
                            appended = True
                        elif "_source" not in c_name:
                            for c_sy in columns[c_name]:
                                if c_sy in row:
                                    new_row.append(row[c_sy])
                                    new_row.append(cut_path(sys.argv[i]))
                                    appended = True
                                    break
                        if appended == False and "_source" not in c_name:
                            new_row.append("")
                            new_row.append("")
                    if check_key(columns, column_name, new_row, df, sys.argv[i]):
                        df.loc[len(df)] = new_row

def cut_path(path):
    splitted_path = path.split("/")
    return splitted_path[-1]

def file_to_utf(argv):
    i = 2
    while (i < len(argv)):
        with open(argv[i], 'r', encoding='utf-8', errors='ignore') as f, open("final_" + cut_path(argv[i]), "w") as outfile:
            inputs = csv.reader(f)
            output = csv.writer(outfile)
            for index, row in enumerate(inputs):
                output.writerow(row)
        i += 1

def consolidate():
    colums = get_columns(sys.argv[1])
    columns_name = [key for key in colums.keys() if key != "key"]
    j = 1
    for i in range(len(columns_name)):
        columns_name.insert(i + j, columns_name[i + j - 1] + "_source")
        j += 1
    df = pd.DataFrame(columns = columns_name)
    iterate_csv(columns_name, colums, df)
    df.to_csv("output.csv", sep=";", index=False)

def main():
    if (len(sys.argv) == 2 and sys.argv[1] == '-h'):
        print("\nHELP\n\n1. You need to provide at least 2 files.\n2. The priority of the file over the others are defined by it's position as an argument (first argument has the highest priority)\n3. The model of the outputed csv file must be defined in the model.txt file following the format specifeid in the model.txt file\n")
    elif (len(sys.argv) < 4):
        print("error: you need to provide at least one model file and two csv")
    else:
        priority = []
        for i in range(len(sys.argv)):
            if i != 0 and (i + 1) % 2 == 0 and os.path.isfile(sys.argv[i]) == False:
                print("error: argument {} is not a valid file".format(i))
                return
        file_to_utf(sys.argv)
        consolidate()
        for i in range(len(sys.argv)):
            if (i > 1):
                os.remove("final_" + cut_path(sys.argv[i]))

if __name__ == "__main__":
    main()


import sys
input = sys.stdin.readline

# T만큼 반복하여 테스트 데이터를 입력 받음
for _ in range(int(input().rstrip())):
    case = input().rstrip()
    cnt_left, cnt_right, check = 0, 0, 0
    for i in case:
        if i == '(':
            cnt_left += 1
        else:
            cnt_right += 1
            if cnt_right > cnt_left:
                check = 1
    if cnt_left == cnt_right:
        if check: print('NO')
        else: print('YES')
    else: print('NO')


import contextlib
import numpy as np
from adafruit_macropad import MacroPad
# from adafruit_hid.keycode import Keycode
import logging
macropad = MacroPad()
# we need the number of arrays we want to split it in
# so we need the number of outputs from the terminal
logging.basicConfig(level=logging.DEBUG)
my_lines=[]
input_list=[]
num_of_output=0 # a internal counter
output_file_path="E:\output"
file_path="C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Laser Quantum Ltd\LQ Terminal.lnk"

while True:
    key_event = macropad.keys.events.get()
    with open(file_path, "a") as text_file:
        with contextlib.redirect_stdout(text_file):
            for my_line in text_file:
               # print out output at that specific position
                num_of_output +=1
                if key_event.key_number==1 and key_event.pressed and macropad.encoder_switch==True: # prints out the output at that specific moment
                    one_output=macropad.display_text(my_lines[num_of_output])
                    one_output.show()
                else:
                    if key_event and key_event.pressed and key_event.key_number==2 and macropad.encoder_switch==True:
                        continue
                # display each output in turn onto the macropad screen for a specific amount of time
                my_lines.append(my_line)
            logging.debug("The output is added to a list in the file")
            # splits=np.split(my_lines, num_of_output)
    # we need a way to assign the specific commands with the numbers
    # length of the array is the num_of_output

            for element in range(0, num_of_output):
                while True:
                    key_event and key_event.pressed
                    if key_event != '' and key_event != 'ENTER':
                        input_list.append(key_event)
                    if key_event.pressed and key_event !='':    # they could press an equals button/or nothing
                        continue
                    if key_event.key_number == 11 and key_event.pressed:
                        continue
                    #apppend the initial commands into a list
    # we compare the lists to each other using the same position
            for i, j, k in list(zip(my_lines, input_list)):
                output_file_path="E:\output"
                x=list(zip(input_list,my_lines))  # use zip function to format lists in a specific way
                tuple(x)
                tuple_no_space=str(tuple(x)).replace(', ', '')

    # displays all of the commands and outputs stored in the list onto the macropad screen
    text_lines= macropad.display_text(title="Commands & Output")
    if key_event.key_number==3 and key_event.pressed and macropad.encoder_switch==True:
        for i in range(len(tuple_no_space)):
            text_lines[i].text=macropad.display_text(tuple_no_space[i])
            text_lines.show()

 #for loop to iterate through items in the list and print line by line


import http.client, json, os, sys, urllib.parse, uuid
from os.path import join
from socket import gaierror
from spreadsheetWrangler import SpreadsheetWrangler

thismodule = sys.modules[__name__]
thismodule.scriptdir = os.path.dirname(os.path.realpath(__file__))
thismodule.parentdir = join(thismodule.scriptdir, "..")

class WordTranslator():
    def __init__(self):
        subscriptionKeysFolder = join(thismodule.parentdir, "subscriptionKeys")
        subscriptionKeyPath = join(subscriptionKeysFolder, "translatorSubscriptionKey.txt")
        self.subscriptionKey = open(subscriptionKeyPath).read()
        self.host = 'api.cognitive.microsofttranslator.com'
        self.path = '/translate?api-version=3.0'

    def translate_words_and_create_spreadsheet(self, inputWords, outputspreadsheet, outputLangCodes, outputLangNames):
        print("I'll print each word when I finish translating it")

        translationsDict = self.generate_translations_dict(inputWords, outputLangCodes)
        SpreadsheetWrangler.write_dict_to_spreadsheet(translationsDict, outputspreadsheet, outputLangCodes)

        print ("I'm finished translating words")

    # returns a dict like {fish: [鱼, Pescado, Cá], kidney beans: [芸豆, Frijoles, Đậu thận]}
    def generate_translations_dict(self, inputWords, outputLangs):
        translations = {}

        for word in inputWords:
            word = word.lstrip().rstrip().capitalize()

            # Empty words get an empty response
            if word is None or word is "":
                translatedWords = []
                for _ in outputLangs:
                    translatedWords.append("")
            else:
                translatedWords = self.get_translated_words(word, outputLangs)

            translations[word] = translatedWords
            print(word)

        return translations

    def get_translated_words(self, inputWord, outputLangs):
        result = self.__get_translations_from_server(inputWord, outputLangs)
        return self.__get_words_from_result(result)

    # gets server translation json for a given word to the given output langs
    def __get_translations_from_server(self, word, outputLangs):
        params = ""
        for lang in outputLangs:
            params += "&to=" + lang.lstrip().rstrip()

        requestBody = [{
            'Text' : word,
        }]

        headers = {
            'Ocp-Apim-Subscription-Key': self.subscriptionKey,
            'Content-type': 'application/json',
            'X-ClientTraceId': str(uuid.uuid4())
        }

        content = json.dumps(requestBody, ensure_ascii=False).encode('utf-8')
        try:
            conn = http.client.HTTPSConnection(self.host)
            conn.request ("POST", self.path + params, content, headers)
            response = conn.getresponse()
            return response.read()
        except gaierror:
            return None

    @staticmethod
    # converts output json into a list of the translated words
    def __get_words_from_result(result):
        if result == None:
            return []

        jsonData = json.loads(result)
        words = []

        for language in jsonData[0]["translations"]:
            words.append(language["text"])

        return words

if __name__ == '__main__':
    inputFolder = join(thismodule.parentdir, "input")
    outputFolder = join(thismodule.parentdir, "output")
    WordTranslator().translate_words_and_create_spreadsheet(
        list(open(join(inputFolder, "words.txt"))),
        join(outputFolder,"translatedWords.xlsx"),
        list(open(join(inputFolder, "toLanguages.txt")))[1:],
        ["Simplified Chinese", "Spanish", "Vietnamese"]) # Yeah it's a bit of a hardcoded cheat, I know


#---------------#
#Summative Unit 4 - Dictionaries Program
#keeping track of expenses program
#By Marb Pano
#April 14, 2023
#---------------#

import random
import time

#----dictionaries---#

employee_salary = {
    }#name of employee and thier salary

operating_cost = {'Rent': 0,
                  'Accounting and Legal Fees': 0,
                  'Bank Charges': 0,
                  'Sales Fees': 0,
                  'Marketing Fees': 0,
                  'Officce Supplies': 0,
                  'Repairs': 0,
                  'Utilities': 0,

    }
#other expenses like banking fees,accouting fees, marketing, office supplies.etc

product_cost = {
    }#how much did it cost to buy the product(s)

#---list---#
inspirational_words = ['If your going through a rough patch, just know everything will be alright we all been there!',
                       'People love you and you know it.',
                       'You can do this!',
                       'You are important',
                       'NEVER GIVE UP!',
                       'Your Business is doing good',
                       'Sales up, share prices down, life is good',
                       'A Rescession is bad... but not for investors',
                       'Invest Wisely!',
                       'Invest in my Crypto Pump and Dump(totes not a scam)',
                       'If you were told to invest in a Crypto Pump and Dump, dont do it!',

]#when working on your business it is important we have inspirational words to help you through the day
#------inspiration-------#
def random_inspirational_words():
    x = random.choice(inspirational_words)
    print(f'    {x}')
#classess
class Employee_salary:

    def __init__(self, employee_salary):
        self.employee_salary = employee_salary

    def print_things(self):
        print('')

        for item, cost in list(self.employee_salary.items()):
            print(f"{item}: ${cost}")

    def adding_things(self):
        print(" ")

        while True:#the only problem with this is that if you have two employees with the same name, the more recent input employee
            #will overwrite the previous ones value
            try:
                item = input("Emplyee Name(type 'done' if you finish): ")#the key in dictionary

                if item == 'done':
                    break

                else:
                    cost = float(input("Salary: "))#value of the dictionary
                    self.employee_salary[item] = cost

                print("")
                print("Contains:")
                self.print_things()

            except:
                print("ONLY USE NUMBERS(RESTART)")

    def remove_things(self):
        print("")

        while True:
            self.print_things()

            employee = input('What Employee/Salary do you want removed?(Type "done" to exit) ')

            if employee == 'done':
                break

            else:
                if employee in self.employee_salary:
                    del self.employee_salary[employee]#deletes the key along with value
                    self.print_things()

                else:
                    print(f"{employee} is not in the Employee List")

class Operating_cost:

    def __init__(self, operating_cost):
        self.operating_cost = operating_cost

    def print_things(self):
        print("")

        for item, cost in list(self.operating_cost.items()):#for every item and cost in shopping_list print the {item} or key, {cost} or value. in dict
            print(f"{item}: ${cost}")

    def adding_things(self):
        print("")

        while True:

            try:
                for item, cost in list(self.operating_cost.items()):

                    x = float(input(f"Overall cost of {item} "))
                    self.operating_cost[item] = x#i just wanted the value to change and not the set key

                print("")
                print("Contains")
                self.print_things()
                break# this is to exit out of the loop

            except:
                print("ONLY USE NUMBERS")

    def remove_things(self):
        print("")#i WANTED only the value to be "removed" and not the key

        while True:

            self.print_things()

            expense = str(input('What Expense do you want removed?(Type "done" to exit) '))

            if expense == "done":#prety self explanatory
                break

            else:
                if expense in self.operating_cost:
                    self.operating_cost[expense] = 0#essentially not removing the value and making it "None" but change value to 0
                    #this allows for math to be done, important for calc the net income

                else:
                    print(f"{expense} is not in the Operating Cost") #fool proof

            print("")

            self.print_things()#print often to show what is in list and what happen
            print("")

class Product_cost:

    def __init__(self, product_cost):
        self.product_cost = product_cost

    def print_things(self):
        print("")

        for item, cost in list(self.product_cost.items()):
            print(f"{item}: ${cost}")

    def adding_things(self):
        print(" ")

        while True:
            try:
                item = input("Product Name(type 'done' if you finish): ")#the key in dictionary

                if item == 'done':
                    break

                else:
                    cost = float(input("Cost of Product: "))#value of the dictionary
                    self.product_cost[item] = cost

                print("")
                print("Contains:")
                self.print_things()

            except:
                print("ONLY USE NUMBERS")

    def remove_things(self):
        print("")

        while True:
            self.print_things()

            product = input('What Product do you want removed?(Type "done" to exit) ')#asking for specific key in dic

            if product == 'done':#i used your model so that whenever done is typed, it goes out of the loop
                break

            else:
                if product in product_cost:
                    del product_cost[product]#dont wanna make it too hard, so its better to just remove the key
                    self.print_things()#i like to print the dict often to show user whats there and what was removed

                else:
                    print(f"{product} is not in the Product Cost")

#Important Variables
ES = Employee_salary(employee_salary)
OC = Operating_cost(operating_cost)
PC = Product_cost(product_cost)

def adding_cost():#to add up all the expenses so that we can calculate net income

    x = sum(value for key, value in operating_cost.items())#didnt know u can do this to this day
    y = sum(value for key, value in employee_salary.items())#to add the values in each list
    z = sum(value for key, value in product_cost.items())

    a = x + y + z

    print(f"Overall Cost of Expenses: ${a}")

    return a

while 1:
    print("")
    random_inspirational_words()

#asking a question #I used "str" to solve constant error for when you put random things in the input
    question = str(input("""
Options:
1. Print Current List's
2. Add Items to lists's
3. Remove Items from List's
4. Pre-Tax Net Income
5. Exit
"""))

    if question == "1":#simply printing

        print("Operating Cost")
        OC.print_things()
        print("")

        print("Employee's Salaries")
        ES.print_things()
        print("")

        print("Product Cost's")
        PC.print_things()
        print("")

        e = adding_cost()

    elif question == "2":#adding items from lists

        while True:
            add_question = str(input("""
What list do you want to Add To?

1. Operating Cost
2. Employee's Salaries
3. Product Cost's
4. Exit
"""))#since we are working with many lists

            if add_question == "1":
                OC.adding_things()

            elif add_question == "2":
                ES.adding_things()

            elif add_question == "3":
                PC.adding_things()

            elif add_question == "4":
                break

            else:
                print("ONLY USE NUMBERS ABOVE")#This is for when the anwser is given a integer but not 1,2,3,4

    elif question == "3":#removing items from lists

        while True:
            remove_question = str(input("""
What list do you want to Remove From?

1. Operating Cost
2. Employee's Salaries
3. Product Cost's
4. Exit
"""))#since we are working with many lists

            if remove_question == "1":
                OC.remove_things()

            elif remove_question == "2":
                ES.remove_things()

            elif remove_question == "3":
                PC.remove_things()

            elif remove_question == "4":
                break

            else:
                print("ONLY USE NUMBERS ABOVE")#This is for when the anwser is given a integer but not 1,2,3,4

    elif question == "4":#net income

        while True:

            try:

                d = float(input("What was the business Total Revenue?(Only numbers) "))#gets the revenue
                e = adding_cost()

                net_income = d - e

                print(f"Net Income is ${net_income}")#after subtracting it prints
                break

            except:
                print("ONLY NUMBERS")#fool proof so float numbers are inputed
                continue

    elif question == "5":
        time.sleep(3)
        break

    else:
        print("ONLY USE NUMBERS: 1,2,3,4,5")
        continue

#the questions relating the OOP summative will be handed through google docs, because
#I did it here through comments, but did not save.

OOP Summative/OOP summative - List's in OOP.py


import cv2

# 1.创建窗口
cv2.namedWindow('new', cv2.WINDOW_NORMAL)
cv2.resizeWindow('new', 640, 480)

# 2. 显示窗口
cv2.imshow('new', 0)

# 接收键盘和鼠标事件。为了是让窗口显示，不至于一闪而过. 参数是 ms，如果想一直显示则传 0
key = cv2.waitKey(0)

# 输入 q 退出
if(key == 'q'):
    exit()

# 3. 销毁
cv2.destroyAllWindows()


class Solution:
    def titleToNumber(self, s: str) -> int:
        ans = 0
        # A character can be converted into a number by getting its ascii code
        # the string is then a number with base 26
        # we can convert this number to decimal
        for i,ch in enumerate(s[::-1]):
            ans += 26**i * (ord(ch) - 64)

        return ans