"""
This is the minimal gui for the pyX2Cscope library, which is an example of how the library could be possibly used.
"""

import logging
import os
import sys
import time
from collections import deque
from datetime import datetime

import matplotlib.pyplot as plt
import numpy as np
import serial.tools.list_ports
from matplotlib.animation import FuncAnimation
from mchplnet.interfaces.factory import InterfaceFactory
from mchplnet.interfaces.factory import InterfaceType as IType
from mchplnet.lnet import LNet
from PyQt5.QtCore import QFileInfo, QMutex, QRegExp, QSettings, Qt, QTimer, pyqtSlot
from PyQt5.QtGui import *
from PyQt5.QtWidgets import (
    QApplication,
    QCheckBox,
    QComboBox,
    QFileDialog,
    QGridLayout,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QMainWindow,
    QMessageBox,
    QPushButton,
    QSlider,
    QWidget,
)

from pyx2cscope.gui import img as img_src
from pyx2cscope.variable.variable_factory import VariableFactory

logging.basicConfig(level=logging.DEBUG)  # Configure the logging module

class X2Cscope_GUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.VariableList = []
        self.old_Variablelist = []
        self.var_factory = None
        self.ser = None
        self.timerValue = 500
        self.port_combo = QComboBox()
        self.layout = None
        self.slider_var1 = QSlider(Qt.Horizontal)
        self.Scaling_var5 = QLineEdit(self)
        self.Unit_var5 = QComboBox(self)
        self.Scaling_var4 = QLineEdit(self)
        self.Value_var5 = QLineEdit(self)
        self.ScaledValue_var5 = QLineEdit(self)
        self.combo_box5 = QComboBox()
        self.Live_var5 = QCheckBox(self)
        self.ScaledValue_var4 = QLineEdit(self)
        self.Unit_var4 = QComboBox(self)
        self.Value_var4 = QLineEdit(self)
        self.combo_box4 = QComboBox()
        self.Value_var3 = QLineEdit(self)
        self.Live_var3 = QCheckBox(self)
        self.Live_var4 = QCheckBox(self)
        self.Unit_var3 = QComboBox(self)
        self.ScaledValue_var3 = QLineEdit(self)
        self.Scaling_var3 = QLineEdit(self)
        self.combo_box3 = QComboBox()
        self.plot_button = QPushButton("Plot")
        self.combo_box2 = QComboBox()
        self.ScaledValue_var2 = QLineEdit(self)
        self.Unit_var2 = QComboBox(self)
        self.Scaling_var2 = QLineEdit(self)
        self.Value_var2 = QLineEdit(self)
        self.Live_var2 = QCheckBox(self)
        self.plot_var5_checkbox = QCheckBox()
        self.plot_var2_checkbox = QCheckBox()
        self.plot_var4_checkbox = QCheckBox()
        self.plot_var3_checkbox = QCheckBox()
        self.plot_var1_checkbox = QCheckBox()
        self.ScaledValue_var1 = QLineEdit(self)
        self.Scaling_var1 = QLineEdit(self)
        self.Unit_var1 = QComboBox(self)
        self.Value_var1 = QLineEdit(self)
        self.combo_box1 = QComboBox()
        self.Live_var1 = QCheckBox(self)
        self.mutex = QMutex()
        self.grid_layout = QGridLayout()
        self.box_layout = QHBoxLayout()
        self.timer5 = QTimer()
        self.timer4 = QTimer()
        self.timer3 = QTimer()
        self.timer2 = QTimer()
        self.timer1 = QTimer()
        self.sampletime = QLineEdit()
        self.Connect_button = QPushButton("Connect")
        self.baud_combo = QComboBox()
        self.select_file_button = QPushButton("Select elf file")
        self.error_shown = False
        self.shown_errors = set()
        self.plot_window_open = False
        self.settings = QSettings("MyCompany", "MyApp")
        self.file_path: str = self.settings.value("file_path", "", type=str)
        self.selected_var_indices = [
            0,
            0,
            0,
            0,
            0,
        ]  # List to store selected variable indices
        self.selected_variables = []  # List to store selected variables
        decimal_regex = QRegExp("[0-9]+(\\.[0-9]+)?")
        self.decimal_validator = QRegExpValidator(decimal_regex)

        self.plot_data = deque(maxlen=250)  # Store plot data for all variable.
        self.fig, self.ax = None, None
        self.ani = None
        self.init_ui()

    # noinspection PyUnresolvedReferences
    def init_ui(self):
        # Create a central widget and layout
        central_widget = QWidget(self)
        self.layout = QGridLayout(central_widget)

        port_layout = QGridLayout()
        port_label = QLabel("Select Port:")

        # Refresh button initialization
        refresh_button = QPushButton()
        refresh_button.setFixedHeight(10)
        refresh_button.setFixedSize(25, 25)
        refresh_button.clicked.connect(self.refresh_ports)
        refresh_img = os.path.join(os.path.dirname(img_src.__file__), "refresh.png")
        refresh_button.setIcon(QIcon(refresh_img))

        self.select_file_button.setEnabled(True)
        # Elf file loader button
        self.select_file_button.clicked.connect(self.select_elf_file)

        port_layout.addWidget(port_label, 0, 0)
        port_layout.addWidget(self.port_combo, 0, 1)
        port_layout.addWidget(refresh_button, 0, 2)

        baud_layout = QGridLayout()
        baud_label = QLabel("Select Baud Rate:")
        baud_layout.addWidget(baud_label, 0, 0)
        baud_layout.addWidget(self.baud_combo, 0, 1)

        # Add common baud rates to the combo box
        self.baud_combo.addItems(["38400", "115200", "230400", "460800", "921600"])
        default_baud_rate = "115200"
        index = self.baud_combo.findText(default_baud_rate, Qt.MatchFixedString)
        if index >= 0:
            self.baud_combo.setCurrentIndex(index)

        self.Connect_button.clicked.connect(self.toggle_connection)
        self.Connect_button.setFixedSize(100, 30)

        self.sampletime.setText("500")
        self.sampletime.setValidator(self.decimal_validator)
        self.sampletime.editingFinished.connect(self.sampletime_edit)
        self.sampletime.setFixedSize(30, 20)

        self.box_layout.addWidget(QLabel("Sampletime"), alignment=Qt.AlignLeft)
        self.box_layout.addWidget(self.sampletime, alignment=Qt.AlignLeft)
        self.box_layout.addWidget(QLabel("ms"), alignment=Qt.AlignLeft)

        self.box_layout.addStretch(1)
        self.box_layout.addWidget(self.Connect_button, alignment=Qt.AlignRight)

        self.timer_list = [
            self.timer1,
            self.timer2,
            self.timer3,
            self.timer4,
            self.timer5,
        ]
        # Add self.labels on top
        self.labels = [
            "Live",
            "Variable",
            "Value",
            "Scaling",
            "Scaled Value",
            "Unit",
            "Plot",
        ]
        for col, label in enumerate(self.labels):
            self.grid_layout.addWidget(QLabel(label), 0, col)

        self.live_checkboxes = [
            self.Live_var1,
            self.Live_var2,
            self.Live_var3,
            self.Live_var4,
            self.Live_var5,
        ]
        self.combo_boxes = [
            self.combo_box1,
            self.combo_box2,
            self.combo_box3,
            self.combo_box4,
            self.combo_box5,
        ]
        self.value_boxes = [
            self.Value_var1,
            self.Value_var2,
            self.Value_var3,
            self.Value_var4,
            self.Value_var5,
        ]
        self.scaling_boxes = [
            self.Scaling_var1,
            self.Scaling_var2,
            self.Scaling_var3,
            self.Scaling_var4,
            self.Scaling_var5,
        ]
        self.scaled_value_boxes = [
            self.ScaledValue_var1,
            self.ScaledValue_var2,
            self.ScaledValue_var3,
            self.ScaledValue_var4,
            self.ScaledValue_var5,
        ]
        unit_boxes = [
            self.Unit_var1,
            self.Unit_var2,
            self.Unit_var3,
            self.Unit_var4,
            self.Unit_var5,
        ]
        self.plot_checkboxes = [
            self.plot_var1_checkbox,
            self.plot_var2_checkbox,
            self.plot_var3_checkbox,
            self.plot_var4_checkbox,
            self.plot_var5_checkbox,
        ]

        for row, (
            live_var,
            combo_box,
            value_var,
            scaling_var,
            scaled_value_var,
            unit_var,
            plot_checkbox,
        ) in enumerate(
            zip(
                self.live_checkboxes,
                self.combo_boxes,
                self.value_boxes,
                self.scaling_boxes,
                self.scaled_value_boxes,
                unit_boxes,
                self.plot_checkboxes,
            ),
            1,
        ):
            live_var.setEnabled(False)
            combo_box.addItems(["None"])
            combo_box.setEnabled(False)
            combo_box.setFixedWidth(350)
            value_var.setText("0")
            value_var.setValidator(self.decimal_validator)
            scaling_var.setText("1")
            scaled_value_var.setText("0")
            scaled_value_var.setValidator(self.decimal_validator)
            unit_var.addItems([" ", "V", "RPM", "Watt", "Ampere"])
            if row > 1:
                row += 1
            self.grid_layout.addWidget(live_var, row, 0)
            self.grid_layout.addWidget(combo_box, row, 1)
            if row == 1:
                self.grid_layout.addWidget(self.slider_var1, row + 1, 0, 1, 7)

            self.grid_layout.addWidget(value_var, row, 2)
            self.grid_layout.addWidget(scaling_var, row, 3)
            self.grid_layout.addWidget(scaled_value_var, row, 4)
            self.grid_layout.addWidget(unit_var, row, 5)
            self.grid_layout.addWidget(plot_checkbox, row, 6)

        self.plot_button.clicked.connect(self.plot_data_plot)

        # adding everything to the main layout
        self.layout.addLayout(port_layout, 1, 0)
        self.layout.addLayout(baud_layout, 2, 0)
        self.layout.addWidget(self.select_file_button, 3, 0)
        self.layout.addLayout(self.box_layout, 4, 0)
        self.layout.addLayout(self.grid_layout, 5, 0)
        self.layout.addWidget(self.plot_button, 6, 0)
        # self.grid_layout.addWidget(self.slider_var2, 8, 0, 1, 6)
        self.timer1.timeout.connect(
            lambda: self.handle_var_update(
                self.combo_box1.currentText(), self.Value_var1
            )
        )

        self.timer2.timeout.connect(
            lambda: self.handle_var_update(
                self.combo_box2.currentText(), self.Value_var2
            )
        )

        self.timer3.timeout.connect(
            lambda: self.handle_var_update(
                self.combo_box3.currentText(), self.Value_var3
            )
        )

        self.timer4.timeout.connect(
            lambda: self.handle_var_update(
                self.combo_box4.currentText(), self.Value_var4
            )
        )

        self.timer5.timeout.connect(
            lambda: self.handle_var_update(
                self.combo_box5.currentText(), self.Value_var5
            )
        )

        self.combo_box1.currentIndexChanged.connect(
            lambda: self.handle_variable_getram(
                self.combo_box1.currentText(), self.Value_var1
            )
        )
        self.combo_box2.currentIndexChanged.connect(
            lambda: self.handle_variable_getram(
                self.combo_box2.currentText(), self.Value_var2
            )
        )
        self.combo_box3.currentIndexChanged.connect(
            lambda: self.handle_variable_getram(
                self.combo_box3.currentText(), self.Value_var3
            )
        )
        self.combo_box4.currentIndexChanged.connect(
            lambda: self.handle_variable_getram(
                self.combo_box4.currentText(), self.Value_var4
            )
        )
        self.combo_box5.currentIndexChanged.connect(
            lambda: self.handle_variable_getram(
                self.combo_box5.currentText(), self.Value_var5
            )
        )
        self.Value_var1.editingFinished.connect(
            lambda: self.handle_variable_putram(
                self.combo_box1.currentText(), self.Value_var1
            )
        )
        self.Value_var2.editingFinished.connect(
            lambda: self.handle_variable_putram(
                self.combo_box2.currentText(), self.Value_var2
            )
        )
        self.Value_var3.editingFinished.connect(
            lambda: self.handle_variable_putram(
                self.combo_box3.currentText(), self.Value_var3
            )
        )
        self.Value_var4.editingFinished.connect(
            lambda: self.handle_variable_putram(
                self.combo_box4.currentText(), self.Value_var4
            )
        )
        self.Value_var5.editingFinished.connect(
            lambda: self.handle_variable_putram(
                self.combo_box5.currentText(), self.Value_var5
            )
        )

        self.Value_var1.textChanged.connect(
            lambda: self.update_scaled_value(
                self.Scaling_var1, self.Value_var1, self.ScaledValue_var1
            )
        )
        self.Scaling_var1.textChanged.connect(
            lambda: self.update_scaled_value(
                self.Scaling_var1, self.Value_var1, self.ScaledValue_var1
            )
        )

        self.Value_var2.textChanged.connect(
            lambda: self.update_scaled_value(
                self.Scaling_var2, self.Value_var2, self.ScaledValue_var2
            )
        )
        self.Scaling_var2.textChanged.connect(
            lambda: self.update_scaled_value(
                self.Scaling_var2, self.Value_var2, self.ScaledValue_var2
            )
        )

        self.Value_var3.textChanged.connect(
            lambda: self.update_scaled_value(
                self.Scaling_var3, self.Value_var3, self.ScaledValue_var3
            )
        )
        self.Scaling_var3.textChanged.connect(
            lambda: self.update_scaled_value(
                self.Scaling_var3, self.Value_var3, self.ScaledValue_var3
            )
        )

        self.Value_var4.textChanged.connect(
            lambda: self.update_scaled_value(
                self.Scaling_var4, self.Value_var4, self.ScaledValue_var4
            )
        )
        self.Scaling_var4.textChanged.connect(
            lambda: self.update_scaled_value(
                self.Scaling_var4, self.Value_var4, self.ScaledValue_var4
            )
        )

        self.Value_var5.textChanged.connect(
            lambda: self.update_scaled_value(
                self.Scaling_var5, self.Value_var5, self.ScaledValue_var5
            )
        )
        self.Scaling_var5.textChanged.connect(
            lambda: self.update_scaled_value(
                self.Scaling_var5, self.Value_var5, self.ScaledValue_var5
            )
        )

        self.Live_var1.stateChanged.connect(
            lambda: self.var_live(self.Live_var1, self.timer1)
        )
        self.Live_var2.stateChanged.connect(
            lambda: self.var_live(self.Live_var2, self.timer2)
        )
        self.Live_var3.stateChanged.connect(
            lambda: self.var_live(self.Live_var3, self.timer3)
        )
        self.Live_var4.stateChanged.connect(
            lambda: self.var_live(self.Live_var4, self.timer4)
        )
        self.Live_var5.stateChanged.connect(
            lambda: self.var_live(self.Live_var5, self.timer5)
        )

        # Add slider for Variable 2
        self.slider_var1.setMinimum(0)
        self.slider_var1.setMaximum(10000)
        self.slider_var1.setEnabled(False)

        self.slider_var1.valueChanged.connect(self.slider_var1_changed)

        # Set the central widget and example window properties
        self.setCentralWidget(central_widget)
        self.setWindowTitle("pyX2Cscope")
        mchp_img = os.path.join(os.path.dirname(img_src.__file__), "pyx2cscope.jpg")
        self.setWindowIcon(QIcon(mchp_img))

        # Populate the available ports combo box
        self.refresh_ports()

    @pyqtSlot()
    def var_live(self, live_var, timer):
        try:
            if live_var.isChecked():
                if not timer.isActive():
                    timer.start(self.timerValue)
            else:
                if timer.isActive():
                    timer.stop()
        except Exception as e:
            error_message = f"Error: {e}"
            logging.error(error_message)
            self.handle_error(error_message)

    @pyqtSlot()
    def update_scaled_value(self, scaling_var, value_var, scaled_value_var):
        scaling_text = scaling_var.text()
        value_text = value_var.text()

        if scaling_text and value_text:
            try:
                scaling = float(scaling_text)
                value = float(value_text)
                scaled_value = scaling * value
                scaled_value_var.setText("{:.2f}".format(scaled_value))
            except Exception as e:
                error_message = f"Error: {e}"
                logging.error(error_message)
                self.handle_error(error_message)
        else:
            scaled_value_var.setText("")

    def plot_data_update(self):
        try:
            timestamp = datetime.now()
            if len(self.plot_data) > 0:
                last_timestamp = self.plot_data[-1][0]
                time_diff = (
                    timestamp - last_timestamp
                ).total_seconds() * 1000  # to convert time in ms.
            else:
                time_diff = 0
            self.plot_data.append(
                (
                    timestamp,
                    time_diff,
                    float(self.Value_var1.text()),
                    float(self.Value_var2.text()),
                    float(self.Value_var3.text()),
                    float(self.Value_var4.text()),
                    float(self.Value_var5.text()),
                )
            )
        except Exception as e:
            print(e)

    def update_plot(self, frame):
        try:
            if not self.plot_data:
                return

            data = np.array(self.plot_data).T
            time_diffs = data[1]
            values = data[2:7]
            self.ax.clear()
            start = time.time()

            for value, combo_box, plot_var in zip(
                values, self.combo_boxes, self.plot_checkboxes
            ):
                if plot_var.isChecked() and combo_box.currentIndex() != 0:
                    self.ax.plot(
                        np.cumsum(time_diffs), value, label=combo_box.currentText()
                    )

            self.ax.set_xlabel("Time (ms)")
            self.ax.set_ylabel("Value")
            self.ax.set_title("Live Plot")
            self.ax.legend(loc="upper right")
            end = time.time()
            print(end - start)
            self.fig.canvas.draw()
            self.fig.canvas.flush_events()
        except Exception as e:
            print(e)

    def plot_data_plot(self):
        try:
            if not self.plot_data:
                return

            def initialize_plot():
                self.fig, self.ax = plt.subplots()
                self.ani = FuncAnimation(self.fig, self.update_plot, interval=1)
                plt.xticks(rotation=45)
                self.ax.axhline(
                    0, color="black", linewidth=0.5
                )  # Reference line at y=0
                self.ax.axvline(
                    0, color="black", linewidth=0.5
                )  # Reference line at x=0
                plt.subplots_adjust(
                    bottom=0.15, left=0.15
                )  # Adjust plot window position
                plt.show(
                    block=False
                )  # Use block=False to prevent the GUI from freezing

            if self.plot_window_open:
                if self.fig is not None and plt.fignum_exists(self.fig.number):
                    # If the plot window is still open, update the plot and restart the animation with the new interval
                    self.update_plot(0)
                    self.ani.event_source.stop()
                    self.ani.event_source.start(self.timerValue)
                else:
                    # The plot window was closed manually, recreate it
                    initialize_plot()
            else:
                # Create a new plot window
                initialize_plot()
                self.plot_window_open = True
        except Exception as e:
            print(e)

    # noinspection PyUnresolvedReferences
    def handle_error(self, error_message: str):
        if error_message not in self.shown_errors:
            msg_box = QMessageBox(self)
            msg_box.setWindowTitle("Error")
            msg_box.setText(error_message)
            msg_box.setStandardButtons(QMessageBox.Ok)
            msg_box.buttonClicked.connect(self.error_box_closed)
            msg_box.exec_()
            self.shown_errors.add(error_message)

    def error_box_closed(self):
        # Handle closing of the error pop-up box if needed
        pass

    def sampletime_edit(self):
        try:
            new_sample_time = int(self.sampletime.text())
            if new_sample_time != self.timerValue:
                self.timerValue = new_sample_time
                for timer in self.timer_list:
                    if timer.isActive():
                        timer.start(self.timerValue)
        except Exception as e:
            error_message = f"Error: {e}"
            logging.error(error_message)
            self.handle_error(error_message)
            print(e)

    @pyqtSlot()
    def handle_var_update(self, counter, value_var):
        try:
            if counter is not None:
                counter = self.var_factory.get_variable_elf(counter)
                value = counter.get_value()
                value_var.setText(str(value))
                if (
                    value_var == self.Value_var1
                ):  # Check if it's Variable 1 being updated
                    self.slider_var1.setValue(
                        int(value)
                    )  # Set slider to the updated value
                self.plot_data_update()
        except Exception as e:
            error_message = f"Error: {e}"
            logging.error(error_message)
            self.handle_error(error_message)

    def slider_var1_changed(self, value):
        if self.combo_box1.currentIndex() == 0:
            self.handle_error("Select Variable")
        else:
            self.Value_var1.setText(str(value))
            self.update_scaled_value(
                self.Scaling_var1, self.Value_var1, self.ScaledValue_var1
            )
            self.handle_variable_putram(self.combo_box1.currentText(), self.Value_var1)

    @pyqtSlot()
    def handle_variable_getram(self, variable, Value_var):
        try:
            current_variable = variable

            for index, combo_box in enumerate(self.combo_boxes):
                if combo_box.currentText() == current_variable:
                    self.selected_var_indices[index] = combo_box.currentIndex()

            if current_variable and current_variable != "None":
                counter = self.var_factory.get_variable_elf(current_variable)
                value = counter.get_value()
                Value_var.setText(str(value))
                if Value_var == self.Value_var1:
                    self.slider_var1.setValue(int(value))

                # Check if the variable is already in the selected_variables list before adding it
                if current_variable not in self.selected_variables:
                    self.selected_variables.append(current_variable)

        except Exception as e:
            error_message = f"Error: {e}"
            logging.error(error_message)
            self.handle_error(error_message)

    @pyqtSlot()
    def handle_variable_putram(self, variable, Value_var):
        try:
            current_variable = variable
            value = float(Value_var.text())

            if current_variable and current_variable != "None":
                counter = self.var_factory.get_variable_elf(current_variable)
                counter.set_value(value)

        except Exception as e:
            error_message = f"Error: {e}"
            logging.error(error_message)
            self.handle_error(error_message)

    @pyqtSlot()
    def select_elf_file(self):
        file_dialog = QFileDialog()
        file_dialog.setNameFilter("ELF Files (*.elf)")
        file_dialog.setFileMode(QFileDialog.ExistingFile)
        fileinfo = QFileInfo(self.file_path)
        self.select_file_button.setText(fileinfo.fileName())

        if self.file_path:
            file_dialog.setDirectory(self.file_path)
        if file_dialog.exec_():
            selected_files = file_dialog.selectedFiles()
            if selected_files:
                self.file_path = selected_files[0]
                self.settings.setValue("file_path", self.file_path)
                self.select_file_button.setText(QFileInfo(self.file_path).fileName())
        # self.refresh_combo_box()

    def refresh_combo_box(self):
        if self.VariableList is not None:
            for index, combo_box in enumerate(self.combo_boxes):
                selected_index = self.selected_var_indices[index]
                current_selected_text = combo_box.currentText()

                combo_box.clear()
                combo_box.addItems(self.VariableList)

                if current_selected_text in self.VariableList:
                    combo_box.setCurrentIndex(combo_box.findText(current_selected_text))
                else:
                    combo_box.setCurrentIndex(selected_index)
        else:
            logging.warning("VariableList is None. Unable to refresh combo boxes.")

    def refresh_ports(self):
        # Clear and repopulate the available ports combo box
        available_ports = [port.device for port in serial.tools.list_ports.comports()]
        self.port_combo.clear()
        self.port_combo.addItems(available_ports)

    @pyqtSlot()
    def toggle_connection(self):
        if self.file_path == "":
            QMessageBox.warning(self, "Error", "Please select an ELF file.")
            self.select_elf_file()
            return

        if self.ser is None or not self.ser.is_open:
            for timer in self.timer_list:
                if timer.isActive():
                    timer.stop()
            self.plot_data.clear()  # Clear plot data when disconnected
            self.connect_serial()
        else:
            self.disconnect_serial()

    def disconnect_serial(self):
        try:
            if self.ser is not None and self.ser.is_open:
                self.ser.stop()
                self.ser = None  # Reset the serial connection object

            # Reset UI elements and timers
            self.Connect_button.setText("Connect")
            self.Connect_button.setEnabled(True)
            self.select_file_button.setEnabled(True)
            widget_list = [self.port_combo, self.baud_combo]

            for widget in widget_list:
                widget.setEnabled(True)

            for combo_box in self.combo_boxes:
                combo_box.setEnabled(False)

            for live_var in self.live_checkboxes:
                live_var.setEnabled(False)

            self.slider_var1.setEnabled(False)
            for timer in self.timer_list:
                if timer.isActive():
                    timer.stop()

        except Exception as e:
            error_message = f"Error while disconnecting: {e}"
            logging.error(error_message)
            self.handle_error(error_message)

    def connect_serial(self):
        try:
            # Disconnect first if already connected
            if self.ser is not None and self.ser.is_open:
                self.disconnect_serial()

            port = self.port_combo.currentText()
            baud_rate = int(self.baud_combo.currentText())

            self.ser = InterfaceFactory.get_interface(
                IType.SERIAL, port=port, baudrate=baud_rate
            )
            l_net = LNet(self.ser)
            self.var_factory = VariableFactory(l_net, self.file_path)
            self.VariableList = self.var_factory.get_var_list_elf()
            self.VariableList.insert(0, "None")
            self.refresh_combo_box()
            logging.info("Serial Port Configuration:")
            logging.info(f"Port: {port}")
            logging.info(f"Baud Rate: {baud_rate}")

            self.Connect_button.setText("Disconnect")
            self.Connect_button.setEnabled(True)

            widget_list = [self.port_combo, self.baud_combo, self.select_file_button]

            for widget in widget_list:
                widget.setEnabled(False)

            for combo_box in self.combo_boxes:
                combo_box.setEnabled(True)
            self.slider_var1.setEnabled(True)

            for live_var in self.live_checkboxes:
                live_var.setEnabled(True)

            timer_list = []
            for i in range(len(self.live_checkboxes)):
                timer_list.append((self.live_checkboxes[i], self.timer_list[i]))

            for live_var, timer in timer_list:
                if live_var.isChecked():
                    timer.start(self.timerValue)

        except Exception as e:
            error_message = f"Error while connecting: {e}"
            logging.error(error_message)
            self.handle_error(error_message)

        # ... (existing code)

    def closeEvent(self, event):
        # Close the serial connection and clean up when the application is closed
        if self.ser:
            self.disconnect_serial()
        event.accept()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = X2Cscope_GUI()
    ex.show()
    sys.exit(app.exec_())


import tensorflow as tf
from Data_Loader import DataLoader
import os
import numpy as np
from scipy import misc
import matplotlib.pyplot as plt
import scipy
import os.path as path
from PIL import Image
from skimage import img_as_ubyte

# add a line for pull test
class BaseModel(object):

    def __init__(self, sess, conf):
        self.sess = sess
        self.conf = conf
        self.is_training = True
        self.input_shape = [None, None, None, self.conf.in_channel]
        self.output_shape = [None, None, None, self.conf.out_channel]
        self.output_shape = [None, None, None, self.conf.out_channel]
        self.create_placeholders()

    def create_placeholders(self):
        with tf.name_scope('Input'):
            self.x = tf.placeholder(tf.float32, self.input_shape, name='input')
            self.y = tf.placeholder(tf.float32, self.output_shape, name='annotation')
            self.keep_prob = tf.placeholder(tf.float32)

    def loss_func(self):
        with tf.name_scope('Loss'):
            if self.conf.loss_type == 'MSE':
                with tf.name_scope('MSE'):
                    #norm_factor = tf.shape(self.y)[1] * tf.shape(self.y)[2]
                    #self.loss = tf.norm(self.y - self.y_pred)
                    self.loss=tf.losses.mean_squared_error(self.y , self.y_pred)#
            if self.conf.use_reg:
                with tf.name_scope('L2_loss'):
                    l2_loss = tf.reduce_sum(
                        self.conf.lmbda * tf.stack([tf.nn.l2_loss(v) for v in tf.get_collection('reg_weights')]))
                    self.loss += l2_loss
            self.mean_loss, self.mean_loss_op = tf.metrics.mean(self.loss)

    def configure_network(self):
        self.y_pred = tf.sigmoid(self.logits)
        self.loss_func()
        global_step = tf.get_variable('global_step', [], initializer=tf.constant_initializer(0), trainable=False)
        learning_rate = tf.train.exponential_decay(self.conf.init_lr,
                                                   global_step,
                                                   decay_steps=500,
                                                   decay_rate=0.97,
                                                   staircase=True)
        self.learning_rate = tf.maximum(learning_rate, self.conf.lr_min)
        with tf.name_scope('Optimizer'):
            optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)
            self.train_op = optimizer.minimize(self.loss, global_step=global_step)
        self.sess.run(tf.global_variables_initializer())
        trainable_vars = tf.trainable_variables()
        self.saver = tf.train.Saver(var_list=trainable_vars, max_to_keep=1000)
        self.train_writer = tf.summary.FileWriter(self.conf.logdir + self.conf.run_name + '/train/', self.sess.graph)
        self.valid_writer = tf.summary.FileWriter(self.conf.logdir + self.conf.run_name + '/valid/')
        self.configure_summary()
        print('*' * 50)
        print('Total number of trainable parameters: {}'.
              format(np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])))
        print('*' * 50)

    def configure_summary(self):
        summary_list = [tf.summary.scalar('learning_rate', self.learning_rate),
                        tf.summary.scalar('loss', self.mean_loss),
                        tf.summary.image('prediction_mask', self.y_pred, max_outputs=3),
                        tf.summary.image('original_mask', self.y, max_outputs=3)]
        self.merged_summary = tf.summary.merge(summary_list)

    def save_summary(self, summary, step):
        if self.is_training:
            self.train_writer.add_summary(summary, step)
        else:
            self.valid_writer.add_summary(summary, step)
        self.sess.run(tf.local_variables_initializer())

    def train(self):
        self.sess.run(tf.local_variables_initializer())
        if self.conf.reload_step > 0:
            self.reload(self.conf.reload_step)
            print('----> Continue Training from step #{}'.format(self.conf.reload_step))
        else:
            print('----> Start Training')
        self.best_validation_loss = 10000
        self.data_reader = DataLoader(self.conf)

        if self.idxs is not None:                   # if we have a mask for training, idxs is the list of pixels used for training. 1 in the mask
            self.data_reader.idxs= self.idxs

        # self.data_reader.load_crop_data(mode='valid')
        self.data_reader.get_data(mode='valid')
        self.num_val_batch = max (int(self.data_reader.y_valid.shape[0] / self.conf.batch_size),1)
        for train_step in range(1, self.conf.max_step + 1):
            self.is_training = True
            if train_step % self.conf.SUMMARY_FREQ == 0:
                x_batch, y_batch = self.data_reader.next_batch(mode='train')
                feed_dict = {self.x: x_batch, self.y: y_batch, self.keep_prob: self.conf.drop_out_rate}
                _, _, summary = self.sess.run([self.train_op,
                                               self.mean_loss_op,
                                               self.merged_summary],
                                              feed_dict=feed_dict)
                loss = self.sess.run(self.mean_loss)
                print('step: {0:<6}, train_loss= {1:.4f}'.format(train_step, loss))
                self.save_summary(summary, train_step + self.conf.reload_step)
            else:
                x_batch, y_batch = self.data_reader.next_batch(mode='train')
                feed_dict = {self.x: x_batch, self.y: y_batch, self.keep_prob: self.conf.drop_out_rate}
                self.sess.run([self.train_op, self.mean_loss_op], feed_dict=feed_dict)
            if train_step % self.conf.VAL_FREQ == 0:
                self.evaluate(train_step)

    def evaluate(self, train_step):
        self.is_training = False
        self.sess.run(tf.local_variables_initializer())
        # pred_mask = np.zeros_like(self.data_reader.y_valid)
        # for step in range(self.num_val_batch):
        #     start = step * self.conf.batch_size
        #     end = (step + 1) * self.conf.batch_size
        #     x_val, y_val = self.data_reader.next_batch(start, end, mode='valid')
        feed_dict = {self.x: self.data_reader.x_valid, self.y: self.data_reader.y_valid, self.keep_prob: 1}
        pred_mask,  _ = self.sess.run([self.y_pred, self.mean_loss_op], feed_dict=feed_dict)
        summary_valid = self.sess.run(self.merged_summary, feed_dict=feed_dict)
        valid_loss = self.sess.run(self.mean_loss)
        self.save_summary(summary_valid, train_step + self.conf.reload_step)
        self.save_fig(train_step,
                      pred_mask.reshape(-1, self.data_reader.val_img_size[0], self.data_reader.val_img_size[1], self.conf.out_channel),
                      self.data_reader.y_valid.reshape(-1, self.data_reader.val_img_size[0], self.data_reader.val_img_size[1], self.conf.out_channel),
                      valid_loss, mode='valid')
        if valid_loss < self.best_validation_loss:
            self.best_validation_loss = valid_loss
            improved_str = '(improved)'
            self.save(train_step + self.conf.reload_step)
        else:
            improved_str = ''
        print('-' * 25 + 'Validation' + '-' * 25)
        print('After {0} training step: val_loss= {1:.4f} {2}'
              .format(train_step, valid_loss, improved_str))
        print('-' * 60)

    def test(self, step_num):
        self.sess.run(tf.local_variables_initializer())
        self.reload(step_num)
        self.data_reader = DataLoader(self.conf)
        self.data_reader.get_data(mode='test')
        self.num_test_batch = max (int(self.data_reader.y_test.shape[0] / self.conf.batch_size) , 1)
        pred_mask = np.zeros_like(self.data_reader.y_test)
        self.is_training = False
        self.sess.run(tf.local_variables_initializer())
        for step in range(self.num_test_batch):
            start = step * self.conf.batch_size
            end = (step + 1) * self.conf.batch_size
            x_test, y_test = self.data_reader.next_batch(start, end, mode='test')
            feed_dict = {self.x: x_test, self.y: y_test, self.keep_prob: 1}
            pred_mask[start:end], _ = self.sess.run([self.y_pred, self.mean_loss_op], feed_dict=feed_dict)
        test_loss = self.sess.run(self.mean_loss)
        self.save_fig(step_num, pred_mask, self.data_reader.y_test, test_loss)
        print('-' * 18 + 'Test Completed' + '-' * 18)
        print('test_loss= {0:.4f}'.format(test_loss))
        print('-' * 50)

    def save(self, step):
        print('----> Saving the model at step #{0}'.format(step))
        checkpoint_path = os.path.join(self.conf.modeldir+self.conf.run_name, self.conf.model_name)
        self.saver.save(self.sess, checkpoint_path, global_step=step)

    def reload(self, step):
        checkpoint_path = os.path.join(self.conf.modeldir+self.conf.run_name, self.conf.model_name)
        model_path = checkpoint_path + '-' + str(step)
        if not os.path.exists(model_path + '.meta'):
            print('----> No such checkpoint found', model_path)
            return
        print('----> Restoring the model at step# {}'.format(step))
        self.saver.restore(self.sess, model_path)
        print('----> Model successfully restored')

    def save_fig(self, step, pred, y, loss, mode='test'):
        num_images = pred.shape[0]
        fig, axs = plt.subplots(nrows=num_images, ncols=3)
        axs = axs.reshape(-1, 3)
        for ii in range(num_images):
            pred_mask = pred[ii]
            true_mask = y[ii]
            ax = axs[ii, 0]
            ax.imshow(true_mask)
            ax.set_xticks([])
            ax.set_yticks([])
            ax.set_title('Groung Truth')
            ax = axs[ii, 1]
            ax.imshow(pred_mask)
            ax.set_xticks([])
            ax.set_yticks([])
            ax.set_title('Prediction')
            ax = axs[ii, 2]
            ax.imshow(np.abs(true_mask-pred_mask))
            ax.set_xticks([])
            ax.set_yticks([])
            ax.set_title('Difference)')
            ax.set_xlabel('loss='+str(loss))
            fig.set_size_inches(6, 2*num_images)
            fig.savefig(self.conf.modeldir+self.conf.run_name+'/'+mode+'_step_{0}_image{1}.png'.format(step, ii))
            misc.imsave(self.conf.modeldir+self.conf.run_name+'/'+mode+'_step_{0}_image{1}.bmp'.format(step, ii),pred_mask)
        plt.close('all')

    def load_mask(self):
        # get file names in masks directory sorted in alphabetical order
        mask_path = self.conf.data_dir +'mask/'
        file_list =[]
        mask_files=[]
        for f in os.listdir(mask_path):
            file_list.append(f)
        file_list.sort()
        #check if they are really file :)
        for f in file_list:
            if not f.startswith('.'):
                file_name = path.join(mask_path, f)
                if path.isfile(file_name) and not (file_name in mask_files):
                    mask_files.append(file_name)

        if len(mask_files) < 1:
            raise ValueError('Missing masks files in folder %s!' % mask_path)

        num_mask = len(mask_files)
        idx =[]
        for i in range(num_mask):
            mask = scipy.misc.imread(mask_files[i])
            idx_temp = np.transpose(np.nonzero(mask[:, :, 1])) # non_zero indices for each mask
            max_bottom_left_front_corner = (np.max(idx_temp[:, 0]) - self.conf.height - 1, np.max(idx_temp[:, 1]) - self.conf.width - 1)
            for j in idx_temp:                #check the nonzero points of masks and exclude border points
                if j[0] < max_bottom_left_front_corner[0] and j[1] < max_bottom_left_front_corner[1]:
                    idx.append(j)

        #mask_path = self.conf.data_dir + 'tr_mask.bmp'
        #mask = scipy.misc.imread(mask_path)
        #idx = np.transpose(np.nonzero(mask[:, :, 1]))
        #idxs = []  # indices close to borders which cannot be bottom_left corner are excluded from idx
        #max_bottom_left_front_corner = (np.max(idx[:,0]) - self.conf.height - 1, np.max(idx[:,1]) - self.conf.width - 1)
        #max_bottom_left_front_corner = (self.conf.img_size[0] - self.conf.height - 1, self.conf.img_size[1] - self.conf.width - 1)
        #for i in idx:
        #    if i[0] < max_bottom_left_front_corner[0] and i[1] < max_bottom_left_front_corner[1]:
        #         idxs.append(i)

        self.idxs = np.asarray(idx)


from random import randint

from OpenGL.GL import *

from PyQt5.QtCore import QObject
from PyQt5.QtMultimedia import QSound

from Objeto import Objeto
from Trajetoria import *

class Asteroide(Objeto):
    """
    Representa um Asteroide.
    """

    def __init__(self, jogo, largura, altura, x, y, trajetoria: Trajetoria):
        QObject.__init__(self, jogo)
        self.jogo = jogo
        self.largura = largura
        self.altura = altura
        self.x = x
        self.y = y
        self.trajetoria = trajetoria

        self.visivel = True

        self.hp = 100
        self.velocidade = 20
        self.textura = self.jogo.texturaAsteroid

    def move(self):
        self.x, self.y = self.trajetoria.anterior(self.velocidade)

    def desenha(self):
        self.move()

        glEnable(GL_TEXTURE_2D)
        glBindTexture(GL_TEXTURE_2D, self.textura)
        glBegin(GL_QUADS)
        glTexCoord2f(0.0, 1.0)
        glVertex2f(self.x + self.largura / 2, self.y + self.altura / 2)  # superior direito
        glTexCoord2f(0.0, 0.0)
        glVertex2f(self.x - self.largura / 2, self.y + self.altura / 2)  # superior esquerdo
        glTexCoord2f(1.0, 0.0)
        glVertex2f(self.x - self.largura / 2, self.y - self.altura / 2)  # inferior esquerdo
        glTexCoord2f(1.0, 1.0)
        glVertex2f(self.x + self.largura / 2, self.y - self.altura / 2)  # inferior direito
        glEnd()
        glDisable(GL_TEXTURE_2D)

        if self.x - self.largura / 2 > self.jogo.jogoLargura \
                or self.x + self.largura / 2 < -self.jogo.jogoLargura \
                or self.y - self.largura / 2 > self.jogo.jogoAltura \
                or self.y + self.largura / 2 < -self.jogo.jogoAltura:
            self.visivel = False


"""lokaleplan URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin

from lokaleplan.views import (
    SessionList, SessionDelete, Home, PerlView, AddUser,
    ParticipantDetail, ParticipantPlans, ParticipantMessageUpdate,
    EventTable, EventList, EventDelete, LocationList,
    EventUpdate, EventUpdateExternal, EventCreate, EventCreateExternal,
    SessionEdit, SessionCreate,
)

sessions = [
    url(r'^$', Home.as_view(), name='home'),
    url(r'^delete/$', SessionDelete.as_view(), name='session_delete'),
    url(r'^import/$', PerlView.as_view(), name='import'),
    url(r'^edit/$', SessionEdit.as_view(), name='edit-csv'),
    url(r'^adduser/$', AddUser.as_view(), name='add_user'),
    url(r'^hold/(?P<pk>[0-9]+)/$', ParticipantDetail.as_view(), name='participant_detail'),
    url(r'^hold/(?P<pk>[0-9]+)/message/$', ParticipantMessageUpdate.as_view(), name='participant_message'),
    url(r'^lokaleplan-(?P<pk>[0-9]+)\.tex$', ParticipantPlans.as_view(),
        name='participant-tex', kwargs=dict(mode='source')),
    url(r'^lokaleplan-(?P<pk>[0-9]+)\.pdf$', ParticipantPlans.as_view(),
        name='participant-pdf', kwargs=dict(mode='pdf')),
    url(r'^locations/$', LocationList.as_view(), name='location_list'),
    url(r'^events/$', EventList.as_view(), name='events'),
    url(r'^events/locations/$', EventTable.as_view(),
        name='locations', kwargs=dict(mode='locations')),
    url(r'^events/participants/$', EventTable.as_view(),
        name='participants', kwargs=dict(mode='participants')),
    url(r'^event/(?P<pk>\d+)/$', EventUpdate.as_view(), name='event_update'),
    url(r'^event/(?P<pk>\d+)/delete/$', EventDelete.as_view(), name='event_delete'),
    url(r'^event/external/new/$', EventCreateExternal.as_view(),
        name='event_create_external'),
    url(r'^event/external/(?P<pk>\d+)/$', EventUpdateExternal.as_view(),
        name='event_update_external'),
    url(r'^event/new/$', EventCreate.as_view(), name='event_create'),
    url(r'^lokaleplan\.tex$', ParticipantPlans.as_view(),
        name='participants-tex', kwargs=dict(mode='source')),
    url(r'^lokaleplan\.pdf$', ParticipantPlans.as_view(),
        name='participants-pdf', kwargs=dict(mode='pdf')),
]

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url('^', include('django.contrib.auth.urls')),
    url(r'^$', SessionList.as_view(), name='session_list'),
    url(r'^new/$', SessionCreate.as_view(), name='session_create'),
    url(r'^session/(?P<session>\d+)/', include(sessions)),
]


class Solution:
    def findDuplicate(self, paths: List[str]) -> List[List[str]]:
        m = defaultdict(lambda: [])

        for i in range(len(paths)):
            p = paths[i]
            splits = p.split(' ')

            for j in range(1, len(splits)):
                s = splits[j].index('(')
                m[splits[j][s:]].append(splits[0] + '/' + splits[j][:s])

        return [m[i] for i in m if len(m[i]) > 1]


from django.http import HttpResponse
import datetime
from django.template import Template, Context
from django.template.loader import get_template

class Persona(object):
    def __init__(self, nombre, apellido) -> None:
        self.nombre = nombre
        self.apellido = apellido

def saludo(request):  # primera vista
    p1 = Persona("Profesor Juan", "Díaz")
    temasDelCurso = ["Tema 1", "Tema 2", "Tema 3", "Tema 4", "Tema 5"]
    """ nombre = "Juan" """
    """ apellido = "García" """
    ahora = datetime.datetime.now()
    # doc_externo = open(
    #    "C:/Users/ruben/Documents/estudios/django/Proyecto1/Proyecto1/templates/index.html")
    #plantilla = Template(doc_externo.read())
    # doc_externo.close()

    doc_externo = get_template('index.html')

    # contexto = Context(
    #    {"nombre": p1.nombre, "apellido": p1.apellido, "momento_actual": ahora, "temas": temasDelCurso})
    documento = doc_externo.render(
        {"nombre": p1.nombre, "apellido": p1.apellido, "momento_actual": ahora, "temas": temasDelCurso})
    return HttpResponse(documento)

def despedida(request):  # segunda vista
    return HttpResponse("¡Hasta luego mundo!")

def dame_Fecha(request):
    fecha_actual = datetime.datetime.now()

    documento = """

Fecha y hora actuales %s

    """ % fecha_actual

    return HttpResponse(documento)

def calcular_Edad(request, edad, year):
    periodo = year - 2021
    edadFutura = edad + periodo

    documento = """

En el año %s tendrás %s años

    """ % (year, edadFutura)

    return HttpResponse(documento)


import base64
from logging import critical
from typing import List, Tuple
from critical_connections import CriticalConnections
from draw_graph import draw_graph

from fastapi import FastAPI, Response
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    "http://localhost:3000",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class Graph(BaseModel):
    nodes_number: int
    edges: List[Tuple[int, int]]

def normilize_edges(edges):
    aux_edges = edges.copy()

    for i in range(len(aux_edges)):
        edges[i] = tuple(sorted(aux_edges[i]))

    return edges

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.post("/get-graph")
def plot_graph(graph: Graph):

    graph.edges = normilize_edges(graph.edges)

    critical_connections = CriticalConnections().get_critical_connections(graph.nodes_number, graph.edges)

    img_bytes = draw_graph(graph, critical_connections)

    encoded_image_string = base64.b64encode(img_bytes.read())

    return {"image_string": encoded_image_string}


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import csv
import matplotlib.pyplot as plt
import numpy as np
from sympy import *

plot_color=1
font_size = 26
font_weight = 550
legend_font_size = 22
axes_font_size = 16
marker_size = 15

num_data_points = 25
channel_rate = 2
IS = 12
W=channel_rate*1000000
P_s = 1500*8
image_size = IS*8*1000
perc_cov_values = np.linspace(0.1,1,num_data_points)
perc_cov_requ = []

#ss_requ = csvread('SumSimRequirements_PSU_Data_Set.csv')
with open('Cluster_Perc_Sets_Covered.csv', 'r') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
#        print(row)
        perc_cov_requ.append(float(row[0]))

num_images = [0 for i in range(len(perc_cov_values))]
for p in range(len(perc_cov_values)):
    for i in range(len(perc_cov_requ)):
        if perc_cov_requ[i] >= perc_cov_values[p]:
            num_images[p] = i
            break

#
#B = num_images*image_size;
#
T = np.zeros(num_data_points)
for i in range(num_data_points):
    B = num_images[i]*image_size
    T[i] = (B*4*2.15 + P_s*2*4)/(W)

fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(perc_cov_values, T, 'bx-', markersize=10, label="NSFNET Topology")
#plt.plot(perc_cov_values, num_images)
ax.set_xlabel('Prob. All Sets Covered', fontsize=axes_font_size, family='Arial', weight=font_weight) #, fontweight='bold'
ax.set_ylabel('Minimum Satisfiable Timeliness ', fontsize=axes_font_size, family='Arial', weight=font_weight) #, fontweight='bold'
#ax.spines['top'].set_visible(False)
#ax.spines['right'].set_visible(False)
plt.legend(loc='best', fontsize=12)
plt.savefig('prob_sets_cov_vs_tness.pdf');
#plt.savefig('./figures/use_cases_examples/nsf_net/prob_sets_cov_vs_tness.pdf');

#hold on;
#if plot_color == 1
#    plot( T, N_grid, '-*', 'color', [0 0.5 0], 'MarkerSize', marker_size-2 );
#    plot( T, N_line, '-ob', 'MarkerSize', marker_size );
#    plot( T, N_clique, '-sr', 'MarkerSize', marker_size );
#else
#    plot( T, N_grid, '-*k', 'MarkerSize', marker_size-2 );
#    plot( T, N_line, '-ok', 'MarkerSize', marker_size );
#    plot( T, N_clique, '-sk', 'MarkerSize', marker_size );
#end
#
#leg = legend('Grid','Line','Clique', 'Location', 'North');
#set(leg, 'FontSize', legend_font_size);
#xlabel('Timeliness', 'FontSize', font_size);
#ylabel('Maximum Network Size', 'FontSize', font_size);
#set(gca, 'FontSize', axes_font_size);
#
#output_directory = sprintf('./use_case_examples/num_nodes_vs_tness/');
#if ~exist(output_directory, 'dir')
#  mkdir(output_directory);
#end
#if plot_color == 1
#    saveas(gcf, sprintf('%snum_nodes_vs_tness_%i_SS_%i_IS_%i_W_color.pdf', output_directory, SS, IS, channel_rate));
#else
#    saveas(gcf, sprintf('%snum_nodes_vs_tness_%i_SS_%i_IS_%i_W.pdf', output_directory, SS, IS, channel_rate));
#end


from django.urls import path
from. import views

urlpatterns = [
    path('', views.blog, name='blog'),
    path('<int:id>/', views.post, name='post'),
    path('login/', views.login_request, name='login'),
    path('signup/', views.signup_request, name='signup'),
    path('logout/', views.logout_request, name='logout'),
    path('post', views.form, name='form'),
]


from tkinter import *
import tkinter

# def hide_me(event):
#     event.widget.pack_forget()

# def show_err():
#     message.set('button pressed.')

# root = Tk()
# message = tkinter.StringVar()
# message.set('Not pressed.')
# print(message.__dict__)

# btn=Button(root, text="Click")
# btn.bind('<Button-1>', hide_me)
# btn.pack()
# Instruction = Label(root, text=message, font='size, 20')
# Instruction.pack()
# btn2=Button(root, text="Click too",command=show_err())
# #btn2.bind('<Button-1>', show_err(btn))
# btn2.pack()
# root.mainloop()
root=Tk()
Imacounter=0

def my_function():
	label1.config(text="intialized")

label1=Label(root,text="")
button1=Button(root,text="increase",command=my_function)
label1.pack()
button1.pack()

root.mainloop()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 27 15:43:28 2019

@author: rawabe
"""

import matplotlib.pyplot as plt
X = range(1, 50)
Y = [value * 3 for value in X]
plt.plot(X, Y)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('Draw a line.')
plt.show()


import setuptools

with open('README.md', 'r') as fh:
    long_description = fh.read()

setuptools.setup(
    name = 'pubg-toolbox',
    version = '0.0.5',
    author = 'Junhan Zhu',
    author_email = 'junhanoct@gmail.com',
    description = 'Simple queries and handles for PUBG data analysis',
    long_description = long_description,
    long_description_content_type = 'text/markdown',
    url = 'https://github.com/junhan-z/pubg-toolbox',
    packages = setuptools.find_packages(),
    classifiers = [
        'Programming Language :: Python :: 3',
        'License :: OSI Approved :: MIT License',
        'Topic :: Utilities',
    ],
    python_requires = '>=3',
)


arr = [7, 5, 9, 0, 3, 1, 6, 2, 9, 1, 4, 8, 0, 5, 2]

cnt = [0] * (max(arr) + 1)  # 모든 범위 포함하는 리스트 선언

# O(N)
for i in range(len(arr)):   # 각 데이터에 해당하는 인덱스 값 증가
    cnt[arr[i]] += 1

# O(N+K)
for i in range(len(cnt)):   # 리스트에 기록된 정렬 정보 확인
    for j in range(cnt[i]):
        print(i, end=' ')   # 띄어쓰기 구분으로 카운트된 횟수만큼 인덱스 출력

이코테_이것이 코딩 테스트다/정렬/계수 정렬(소스코드 예제).py

계수 정렬(소스코드 예제).py


from django.shortcuts import render,redirect
from post.models import Post
from math import ceil

def create(request):
	if request.method == 'POST':
		title = request.POST.get('title')
		content = request.POST.get('content')
		post = Post.objects.create(title=title, content=content)
		return redirect('/post/read/?post_id=%d'%post.id)
	else:
		return render(request,'create.html')

def edit(request):
	if request.method == 'POST':
		# 取出原文章
		post_id = request.POST.get('post_id')
		post = Post.objects.get(id=post_id)
		# 修改文章
		post.title = title
		post.content = content
		post.save()
		return redirect('/post/read/?post_id=%d' % post.id)
	else:
		# get不修改
		post_id = request.GET.get('post_id')
		post = Post.objects.get(id=post_id)
		return render(request,'edit.html',{'post': post})

def read(request):
	post_id = int(request.GET.get('post_id'))
	try:
		post = Post.objects.get(id=post_id)
		return render(request,'read.html',{'post': post})
	except Post.DoesNotExist:
		return redirect('/')

def list(request):
	page = int(request.GET.get('page',1)) # 当前页码，默认为-1
	p = 5
	# 计算页数
	total = Post.objects.count()
	pages = ceil(total / p)

	# 取出本页需要实现的文章
	start = (page - 1) * p
	end = start + 5
	posts = Post.objects.all()[start: end]
	return render(request,'post_list.html', { "posts": posts, 'pages': range(pages) })

def search(request):
	keyword = request.POST.get('keyword')
	posts = Post.objects.filter(content__contains=keyword)
	return render(request,'search.html',{'posts': posts})


#!/usr/bin/python3

# ## {R2D2919B742E} ##
# ###########################################################################
# What if magic existed?
# What if a place existed where your every thought and dream come to life.
# There is only one catch: it has to be written down.
# Such a place exists, it is called programming.
#    - Scott Taylor Reph, RightThumb.com
# ###########################################################################
# ## {C3P0D40fAe8B} ##

import numpy
import os
import sys
# import simplejson as json
# import shutil

import _rightThumb._base1 as _
import _rightThumb._vars as _v
import _rightThumb._string as _str

_.switches.register('File1', '-f1','file1.txt')
_.switches.register('File2', '-f2','file2.txt')

_.appInfo=    {
	'file': 'lists.py',
	'description': 'Changes the world',
	'prerequisite': [],
	'examples': [],
	'columns': [],
	}

_.appInfo['examples'].append('p lists -f1 file1.txt -f2 file2.txt')

# _.appInfo['columns'].append({'name': 'name', 'abbreviation': 'n'})

_.switches.process()

# pipeData = ''

# if not sys.stdin.isatty():
#     pipeData = sys.stdin.readlines()
#     try:
#         if pipeData[0][0].isalnum() == False:
#             pipeData[0] = pipeData[0][1:]
#     except Exception as e:
#         pass

########################################################################################
def action():
	file1Raw = []

	file1 = []
	file2 = []
	files = []
	files2 = []
	good = []
	bad = []
	f1 = _.switches.value('File1')
	f2 = _.switches.value('File2')
	threshold = 90
	chars = '0123456789abcdefghijklmnopqrstuvwxyz'
	def diff(a,b):
		try:
			if a > b:
				result = (b/a)*100
			elif a == b:
				result = 100
			else:
				result = (a/b)*100
		except Exception as e:
			result = 0
		return result
	if os.path.isfile(f1) == True:
		with open(f1,  'r', encoding='latin-1') as f:
			for line in f:
				data = {}
				line = line.replace('\n','')
				file1Raw.append(line)
				data = {'line': line}
				i=0
				for c in chars:
					cnt = line.lower().count(c)
					i+=cnt
					data[c] = cnt
				if i > 2:
					file1.append(data)
					files.append(line)
					files2.append(line)
			f.close()
	if os.path.isfile(f2) == True:
		with open(f2,  'r', encoding='latin-1') as f:
			for line in f:
				data = {}
				line = line.replace('\n','')
				data = {'line': line}
				i=0
				for c in chars:
					cnt = line.lower().count(c)
					# print(cnt)
					i+=cnt
					data[c] = cnt
				if i > 2:
					file2.append(data)
					files.append(line)
			f.close()
	if len(file1) < len(file2):
		tmp2 = file2
		tmp1 = file1
		file1 = tmp2
		file2 = tmp1
		del tmp1
		del tmp2
	# print(file1)
	# print(file2)
	def mostProbable(row):
		t = []
		for d in file2:

			a = []
			for c in chars:
				calcDiff = diff(d[c],row[c])
				# if calcDiff > -1:
				a.append(calcDiff)
			t.append({'line': d['line'], 'rank': numpy.mean(a)})
		ttt = sorted(t, key=lambda k: k['rank'])
		# for tt in ttt:
		#     print(tt['rank'],tt['line'])
		# sys.exit()
		return ttt[len(ttt)-1]

	for ff in file1:
		probableMatch = mostProbable(ff)
		# print(probableMatch)
		is_100 = []
		if probableMatch['rank'] > threshold:
			if not probableMatch['line'] in is_100 and not ff['line'] in is_100:
				if int(round(probableMatch['rank'])) == 100:
					# print( probableMatch['line'] )
					is_100.append( probableMatch['line'] )
				good.append({'list1':ff['line'],'list2':probableMatch['line'],'rank':int(round(probableMatch['rank']))})
		else:
			bad.append({'list1':ff['line'],'list2':probableMatch['line'],'rank':int(round(probableMatch['rank']))})
	_.tables.register('good',good)
	_.tables.register('bad',bad)
	_.tables.fieldProfileSet('bad','_header_','alignment','center')
	_.tables.fieldProfileSet('good','_header_','alignment','center')
	_.switches.fieldSet('Long','active',True)
	_.switches.fieldSet('Sort','active',True)
	_.switches.fieldSet('Sort','value','d;.rank')
	print()
	print('GOOD:',len(good))
	_.tables.print('good','list1,list2,rank')
	print()
	print()
	print('BAD:',len(bad))
	_.tables.print('bad','list1,list2,rank')
	print()
	print()
	print('Not 100%')
	print()
	the100 = []
	for item in good:
		if item['rank'] == 100:
			the100.append( item['list1'] )

	for item in file1Raw:
		if not item in the100:
			print( item )

	# missing = []
	# for bad in files:
	#     if not bad in files2:
	#         missing.append(bad)
	# print('Missing:',len(missing))
	# for m in missing:
	#     print(m)
	# totalDif = 0
	# if len(file1) > len(file2):
	#     totalDif = len(file1) - len(file2)
	# else:
	#     totalDif = len(file2) - len(file1)
	# print()
	# print(len(file1),len(file2), totalDif)
########################################################################################
if __name__ == '__main__':
	action()


import math #používání balíčku math, obsahuje mocniny a odmocniny

cislo1 = 0 #první číslo do vzorečku
cislo2 = 0 #druhé číslo do vzorečku
funkce = "" #sčítání, odčítání, násobení, dělení, mocnina, odmocnina
n = 0 #Hodnota pro n-tou odmocninu či mocninu

while True: #Program se opakuje vždy dokola bez ukončení

    #neni udelana kontrola, zda-li je hodnota cislo1, cislo2 a n realne cislo

    cislo1 = float(input("Zadej první číslo do výpočtu: ")) #stanovení prvního čísla do vzorečku, pomoci funkce float() se text změní na !DESETINNÉ! číslo
    funkce = input("Zadej funkci \n Možnosti | [+] [-] [*] [/] [mocnina] [odmocnina]: ") #výběr funkce, \n napíše text na další řádek, pouze grafické

    if funkce == "+":
        cislo2 = float(input("Zadej druhé číslo do výpočtu: "))
        print(cislo1 + cislo2) #dělení

    elif funkce == "-":
        cislo2 = float(input("Zadej druhé číslo do výpočtu: "))
        print(cislo1 - cislo2) #odečítání

    elif funkce == "*":
        cislo2 = float(input("Zadej druhé číslo do výpočtu: "))
        print(cislo1 * cislo2) #násobení

    elif funkce == "/":
        cislo2 = float(input("Zadej druhé číslo do výpočtu: "))
        if cislo2 == 0: #kontrola
            print("Nulou nelze dělit!!")
        else:
            print(cislo1 / cislo2) #dělení

    elif funkce == "mocnina":
        n = int(input("Kolikátou mocninu čísla?: "))
        print(math.pow(cislo1, n)) #použití funkce math.pow pro mocniny, cislo1 je první zadaná hodnota, n je n-tá mocnina

    elif funkce == "odmocnina":
        if cislo1 < 0: #kontrola
            print("Odmocnina záporného čísla neexistuje...")
        else:
            n = int(input("Kolikátou odmocninu čísla?: "))
            print(math.pow(cislo1, 1/n))  #použití funce math.pow() pro odmocninu, např. 3 odmocnina je vlastně mocnina 1/3, proto tento výpočet
                                          #pro jednoduchou druhou odmocninu lze použít funkce math.sqrt()


# Variable Table

# Input - abcabcd
# Output - abcd

# c_letter - a,b,c,a,b
# i -> 0,0,0,1
# j -> 0,1,2,1
# char_set -> (a, b, c), () ....
# max_length -> 3

def lengthOfLongestSubstring(self, s):
    """Working solution to problem, pretty slow though could be faster"""

    if len(s) == 1:
        return 1

    max_length = 0
    char_set = set()
    i = 0
    j = 0

    while j < len(s):
        if s[j] in char_set:
            if len(char_set) > max_length:
                max_length = len(char_set)
                j = i + 1
                i += 1
            else:
                j = i + 1
                i += 1

            char_set = set()
        else:
            char_set.add(s[j])
            j += 1

    max_length = max(len(char_set), max_length)

    return max_length


import sys
sys.setrecursionlimit(10**6)

# python の 再帰 では間に合わない

def main():
    N = int(input())
    E = [list(map(lambda x: int(x) - 1, input().split()))
         for _ in range(N - 1)]
    Q = int(input())
    Qs = [list(map(int, input().split())) for _ in range(Q)]

    c = [0] * N
    seen = [False] * N
    depth = [0] * N
    G = [[] for _ in range(N)]

    for a, b in E:
        G[a].append(b)
        G[b].append(a)

    def dfs(v, p, d):
        depth[v] = d
        for next_v in G[v]:
            if next_v == p:
                continue
            dfs(next_v, v, d + 1)

    def dfs_c(v, p, x):
        c[v] += x
        for next_v in G[v]:
            if next_v == p:
                continue
            dfs_c(next_v, v, c[v])
    # dfs(0, -1, 0)
    todo = [0]
    d = 0
    while todo:
        v = todo.pop()
        seen[v] = True
        for nv in G[v]:
            if seen[nv]:
                continue
            depth[nv] = depth[v] + 1
            todo.append(nv)

    for t, e, x in Qs:
        t -= 1
        e -= 1
        tg = E[e][t]
        op = E[e][1 - t]
        if depth[tg] > depth[op]:
            c[tg] += x
        else:
            c[0] += x
            c[op] -= x

    # dfs_c(0, -1, 0)

    todo = [0]
    while todo:
        v = todo.pop()
        for nv in G[v]:
            if depth[nv] < depth[v]:
                continue
            c[nv] += c[v]
            todo.append(nv)
        d += 1

    print(*c, sep="\n")

if __name__ == '__main__':
    main()


import numpy as np
import matplotlib.pyplot as plt

from funbo.utils import *
from .utils import *
from .trials import plot_trials

try:
    import plotly.offline as ply
    import plotly.graph_objs as go

    if in_jupyter():
        print('plotly setup')
        ply.init_notebook_mode(connected=False)
except ImportError:
    ply = None

def plot_trial_area(optimiser, trial, true_best, quiet=False, ax=None):
    """
    """
    xmin, xmax = optimiser.domain_bounds[0]
    if not quiet:
        print('area between: {}'.format(multidimensional_integrate(lambda x: abs(true_best(x)-trial.f(x)), optimiser.domain_bounds)))
        print('R_g = {}'.format(trial.R_g))
        print('R_ls = {}'.format(format_list([r for x, r in trial.R_ls], 3)))
        print('f = {}'.format(trial.f))
    if ax is None:
        fig, ax = plt.subplots(figsize=(12, 6))
    xs = np.linspace(xmin, xmax, num=200)
    fs = [trial.f(x) for x in xs]

    ax.plot(xs, fs, color='salmon', label='f')
    ax.scatter(trial.f.control_xs, trial.f.control_ys, color='salmon', s=10, label='f control points')

    fits = [true_best(x) for x in xs]
    ax.plot(xs, fits, linestyle='--', color='k', label='to fit')
    ax.fill_between(xs, [min(a, b) for a,b in zip(fits, fs)], [max(a,b) for a,b in zip(fits, fs)], alpha=0.2)

    # sampled locations where local rewards were given
    if trial.R_ls:
        s_xs, s_rs = unzip(trial.R_ls)
        s_ys = [trial.f(x) for x in s_xs]
        ax.scatter(s_xs, s_ys, c='black', s=10, zorder=10, label='local rewards')

    ax.legend()

def plot_surrogate_with_trials(optimiser, trial_num, true_best=None, ylim=None, midpoint_fraction=None):
    if trial_num < 0:
        trial_num = len(optimiser.trials) + trial_num
    t = optimiser.trials[trial_num]
    fig = plot_surrogate(optimiser, t.surrogate, ylim, midpoint_fraction)
    plot_trials(optimiser, optimiser.trials[:trial_num+1], true_best, color_by_reward=False, ax=fig.axes[0])
    return fig

def plot_surrogate(optimiser, surrogate, ylim=None, midpoint_fraction=None, fig_ax=None):
    assert surrogate is not None, 'no surrogate'
    if fig_ax is None:
        fig, ax = plt.subplots(figsize=(20, 10))
    else:
        fig, ax = fig_ax
    # undo seaborn styling
    ax.grid(False)
    ax.set_facecolor((1, 1, 1))

    x_name = optimiser.domain_names[0]
    xmin, xmax = optimiser.domain_bounds[0]
    xs = np.linspace(xmin, xmax, num=100)

    if ylim is not None:
        ymin, ymax = ylim
        y_margin = 0
    else:
        ymin, ymax = optimiser.range_bounds
        y_margin = (ymax-ymin)*0.1

    ys = np.linspace(ymin-y_margin, ymax+y_margin, num=100)
    ax.margins(0, 0)

    grid = np.meshgrid(xs, ys)
    mus_points, var_points = surrogate.predict(grid_to_points(grid))
    mus_grid = vals_to_grid(mus_points, grid[0].shape)

    cmap = 'viridis' if optimiser.is_maximising() else 'viridis_r'
    if midpoint_fraction is None:
        norm = None
    else:
        norm = utils.MidpointNorm(np.min(mus_points), np.max(mus_points), midpoint=None, midpoint_fraction=midpoint_fraction)
    im = ax.pcolormesh(grid[0], grid[1], mus_grid, cmap=cmap, norm=norm)
    c = fig.colorbar(im, ax=ax)
    c.set_label(r'$R_l({},f({}))$'.format(x_name, x_name))

    ax.set_xlabel('${}$'.format(x_name))
    ax.set_ylabel(r'$f({})$'.format(x_name))

    return fig

def plot_surrogate_3D(optimiser, surrogate, show_var=True, flip_z=False):
    assert ply is not None, 'plotly not imported'
    assert surrogate is not None, 'no surrogate'

    x_name = optimiser.domain_names[0]
    xmin, xmax = optimiser.domain_bounds[0]
    xs = np.linspace(xmin, xmax, num=100)

    ymin, ymax = optimiser.range_bounds
    y_margin = (ymax-ymin)*0.1
    ys = np.linspace(ymin-y_margin, ymax+y_margin, num=100)

    grid = np.meshgrid(xs, ys)
    grid_shape = grid[0].shape
    mus_points, var_points = surrogate.predict(grid_to_points(grid))
    mus_grid = vals_to_grid(mus_points, grid_shape)
    if flip_z:
        mus_grid = -mus_grid

    data = [
        go.Surface(x=grid[0], y=grid[1], z=mus_grid, colorscale='Viridis', reversescale=optimiser.is_minimising() != flip_z),
    ]
    if show_var:
        sig_grid = vals_to_grid(np.sqrt(np.clip(var_points, 0, np.inf)), grid_shape)
        n_sig = 2
        color_row = ['#0000ff'] * grid[0].shape[1]
        colors = [color_row] * grid[0].shape[0]
        data.extend([
            go.Surface(x=grid[0], y=grid[1], z=mus_grid + n_sig*sig_grid, surfacecolor=colors, opacity=0.3, showscale=False),
            #go.Surface(x=grid[0], y=grid[1], z=mus_grid - n_sig*sig_grid, surfacecolor=colors, opacity=0.3, showscale=False),
        ])

    layout = go.Layout(
        title='3D surface',
        autosize=False,
        width=1000,
        height=750,
        margin=dict(l=0, r=0, b=0, t=0),
        scene=dict(
            xaxis=dict(title=x_name),
            yaxis=dict(title='f({})'.format(x_name)),
            zaxis=dict(title='{}R_l({},f({}))'.format('-' if flip_z else '', x_name, x_name)),
            aspectratio=dict(x=1, y=1, z=1)
        )
    )
    fig = go.Figure(data=data, layout=layout)
    ply.iplot(fig, show_link=False)

def surface_3D(x, y, z, tooltips=None, axes_names=('x','y','z')):
    '''plot a 3D surface using plotly

    Parameters should be of the form:
    ```
    X = np.arange(...)
    Y = np.arange(...)
    X, Y = np.meshgrid(X, Y)
    Z = f(X,Y)
    ```

    Args:
        tooltips: an array with the same length as the number of points,
            containing a string to display beside them
    '''
    data = [go.Surface(
        x=x, y=y, z=z,
        text=tooltips, colorscale='Viridis', opacity=1
    )]
    layout = go.Layout(
        title='3D surface',
        autosize=False,
        width=900,
        height=600,
        margin=dict(l=0, r=0, b=0, t=0),
        scene=dict(
            xaxis=dict(title=axes_names[0]),
            yaxis=dict(title=axes_names[1]),
            zaxis=dict(title=axes_names[2])
        )
    )
    fig = go.Figure(data=data, layout=layout)
    # show_link is a link to export to the 'plotly cloud'
    ply.iplot(fig, show_link=False)


import pytest

#### writing tests for the main function ####

DATA = 'data'
def test_load_data(tmp_path):
    """Test for the game to be loading a file from temp directory"""
    d = tmp_path / "dict"
    d.mkdir()
    p = d / "test data"
    p.write_text(DATA)
    assert p.read_text() == DATA
    assert len(list(tmp_path.iterdir())) == 1

def test_load_data_missing_file():
    """Test for when the loading fails on the game"""
    file_name = "art_database/game_data_clean.json"
    if file_name == FileNotFoundError:
        with pytest.raises(FileNotFoundError):
            file_name = "art_database/game_data.json"  # replace with another file


from django.conf import settings
from django.apps import apps

REFERRAL_MODEL = getattr(settings, "REFERRAL_CODE_MODEL", "referrals.ReferralCode")
REFERRAL_PARAM_KEY = getattr(settings, "REFERRAL_PARAM_KEY", "ref_code")
REFERRAL_COOKIE_KEY = getattr(settings, "REFERRAL_COOKIE_KEY", "ref_code")
REFERRAL_COOKIE_AGE = getattr(settings, "REFERRAL_COOKIE_AGE", 60 * 60 * 24)

class ReferralLinkMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        ReferralCode = apps.get_model(REFERRAL_MODEL, require_ready=True)
        cookie_age = REFERRAL_COOKIE_AGE

        # Get user referrer from cookie referral code
        cookie_referral_code = request.COOKIES.get(REFERRAL_COOKIE_KEY, None)
        cookie_referrer = ReferralCode.get_user_from_code(cookie_referral_code)
        param_referrer = None
        request.referrer = cookie_referrer
        if cookie_referrer is None:
            # try get referral code from query parameter
            param_referral_code = request.GET.get(REFERRAL_PARAM_KEY, None)
            param_referrer = ReferralCode.get_user_from_code(param_referral_code)
            request.referrer = param_referrer
        response = self.get_response(request)
        if param_referrer is not None:
            response.set_cookie(
                REFERRAL_PARAM_KEY,
                str(param_referral_code),
                max_age=cookie_age,
            )
        return response


from tkinter import *
from tkinter import messagebox
from PIL import ImageTk, Image
import random
import sqlite3
import maindesk
import questionImport

class QuestionSupply:
    def __init__(self, master, user_name, is_admin):
        # 用户相关信息
        self.user_name = user_name
        self.is_admin = is_admin

        # 设置主窗口属性
        self.master = master
        self.master.title('主程序')

        # 设置子窗口
        self.question_supply = Frame(self.master, width=1000, height=750)
        self.question_supply.pack()

        # 添加其他部件
        self.set_tips()
        self.set_button()

    def set_tips(self):
        word_set = ("宋体", 30)

        # 标签
        self.label_tips = Label(self.question_supply, text='请选择题目类型', height=2, font=word_set)
        self.label_tips.place(relx=0.387, rely=0.2)

    def set_button(self):
        word_set = ("宋体", 20)

        # 选择
        self.button_choice = Button(self.question_supply, text='选择题', command=self.cmd_choice, font=word_set)
        self.button_choice.place(relx=0.24, rely=0.43, width=140, height=80)

        # 判断
        self.button_judgement = Button(self.question_supply, text='判断题', command=self.cmd_judgement, font=word_set)
        self.button_judgement.place(relx=0.62, rely=0.43, width=140, height=80)

        # 简答
        self.button_short_answer \
            = Button(self.question_supply, text='简答题', command=self.cmd_short_answer, font=word_set)
        self.button_short_answer.place(relx=0.24, rely=0.62, width=140, height=80)

        # 简答
        self.button_cancel = Button(self.question_supply, text='取消', command=self.cmd_cancel, font=word_set)
        self.button_cancel.place(relx=0.62, rely=0.62, width=140, height=80)

    def cmd_choice(self):
        self.question_supply.destroy()
        questionImport.QuestionImport(self.master, self.user_name, True, 'choice')

    def cmd_judgement(self):
        self.question_supply.destroy()
        questionImport.QuestionImport(self.master, self.user_name, True, 'judgement')

    def cmd_short_answer(self):
        self.question_supply.destroy()
        questionImport.QuestionImport(self.master, self.user_name, True, 'short')

    def cmd_cancel(self):
        self.question_supply.destroy()
        maindesk.MainDesk(self.master, self.user_name, True)

if __name__ == '__main__':
    root = Tk()
    QuestionSupply(root, 'user_test', True)
    root.mainloop()


N, K = map(int, input().split())
arr = []
for i in range(N):
    x = int(input())
    if x <= K:
        arr.append(x)
con = K
cnt = 0
i = len(arr)-1
while con > 0:
    if arr[i] <= con:
        a = con // arr[i]
        con -= arr[i] * a
        cnt += a
    elif arr[i] > con:
        i -= 1
print(cnt)


from sms import app
from ini_conf import MyIni

if __name__ == '__main__':
    my_ini = MyIni()
    mysql_ini = my_ini.get_mysql()
    sys_ini = my_ini.get_sys()

    app.config['SECRET_KEY'] = sys_ini['secret_key']
    app.config['WHITE_LIST_OPEN'] = sys_ini['while_list_open']
    app.config['WHITE_LIST'] = sys_ini['while_list'].split(',')
    app.config['SQLALCHEMY_DATABASE_URI']= 'mysql://%s:%s@%s:%s/%s' % (
        mysql_ini['user'], mysql_ini['pwd'], mysql_ini['host'],
        mysql_ini['port'], mysql_ini['db'])
    app.config['SMS_WSDL_PARAMS'] = my_ini.get_webservice()
    del my_ini
    app.run(host=sys_ini['host'], port=sys_ini['port'], threaded=True)


from gromorg import GromOrg
from pyqchem import Structure
from pyqchem.tools import get_geometry_from_pubchem

# Main molecule
structure = Structure(coordinates=[[ 0.6695, 0.0000, 0.0000],
                                   [-0.6695, 0.0000, 0.0000],
                                   [ 1.2321, 0.9289, 0.0000],
                                   [ 1.2321,-0.9289, 0.0000],
                                   [-1.2321, 0.9289, 0.0000],
                                   [-1.2321,-0.9289, 0.0000]],
                      symbols=['C', 'C', 'H', 'H', 'H', 'H'],
                      charge=0,
                      multiplicity=1)

# Solvent molecule
solvent = Structure(coordinates=[[0.000000,  0.000000,  0.000000],
                                 [0.758602,  0.000000,  0.504284],
                                 [0.758602,  0.000000,  -0.504284]
                                 ],
                      symbols=['O', 'H', 'H'])

# GROMACS parameters
params = {# Run paramters
          'integrator': 'md-vv',     # Verlet integrator
          'nsteps': 5000,            # 0.001 * 5000 = 50 ps
          'dt': 0.001,               # ps
          # Temperature coupling is on
          'tcoupl': 'nose-hoover',    # Nose-Hoover thermostat
          'tau_t': 0.3,               # time constant, in ps
          'ref_t': 100,               # reference temperature, one for each group, in K
          # Bond parameters
          'gen_vel': 'yes',           # assign velocities from Maxwell distributio
          'gen_temp': 100,            # temperature for Maxwell distribution
          'gen_seed': -1,             # generate a random seed
          }

# define simulation
calc = GromOrg(structure,
               params=params,        # main molecule in pyqchem Structure format
               box=[15, 15, 15],     # a, b, c cell distances
               supercell=[3, 3, 3],  # supercell
               solvent=solvent,      # solvent in pyqchem Structure format
               solvent_scale=0.57,   # solvent scale parameter
               )

# run MD simulation
trajectory, energy = calc.run_md(whole=True)

# store trajectory in gro file
trajectory.save('trajectory.gro')


import random

random_int = random.randint(0,10)
print(random_int) # This will print a random integer between 0 and 10

random_float = random.random()
print(random_float) # This will print a random float between 0 and 1

random_float = random.uniform(0,10)
print(random_float) # This will print a random float between 0 and 10

cars = ["Ford", "Volvo", "BMW"]
random_choice = random.choice(cars) # This will print a random element from the list

# Lists
fruits = ["apple", "banana", "cherry"]
print(fruits) # Prints the whole list
print(fruits[1]) # Prints the second element of the list
fruits[1] = "kiwi" # Change the value of the second element
fruits.append("orange") # Add to the end of the list
fruits.insert(1, "pear") # Inserts at index 1
fruits.remove("banana") # Removes the first instance of the item
fruits.pop() # removes last item
fruits.pop(1) # Remove the item at index 1
fruits.clear() # removes all elements from the list
fruits.sort() # alphabetical
fruits.reverse() # reverse the order of the list
fruits.index("apple") # Returns the index of the first instance of the value
fruits.count("apple") # Counts how many times the item appears in the list
fruits.extend(["orange", "pear"]) # Add list to list


import numpy as np
import timeit
import csv
import matplotlib.pyplot as plt
from model import SolarUAV
from data import SolarModel, WDataGen
start = timeit.default_timer()

print('Defining flight parameters')
# Define flight parameters
t_start = 7.
dur = 100
dt = 0.01
launch_vel = [0, 15, 0]
cr_alt = 500
pts = np.array((
    [0, 0],
    [300, 450],
    [0, 650],
    [-300, 450],
    [0, 0]
)) * 1000

# Define simulation parameters
tot_sim = 10  # total number of simulations for each month
months = np.arange(1, 13)  # months Jan to Dec
CANtot_succ = 0  # number of successful simulations in Canada

print('Start of MC simulations')
# Run simulations
with open(r"C:\Users\justi\Documents\Final year project\Modelling\app\MCResults\MCSim1CAN.csv", 'w') as file:
    writer = csv.writer(file)
    writer.writerow(['Month', 'Success rate (CAN)'])
    for month in months:
        for i in range(1, tot_sim+1):

            # Skip simulations if quarter-way through the MC sim there is no successful flight
            if i > 10 and CANtot_succ == 0:
                continue

            # Generate weather data
            wdata = WDataGen.wdata_sampling(t_start, 5, 0, 0, 0)

            # Generate flight model
            flight_modelCAN = SolarUAV.FlightModel(t_start, dur, dt)
            flight_modelCAN.vel_ini = launch_vel  # set initial velocity
            flight_modelCAN.wdata = wdata  # load weather data
            flight_modelCAN.mission_p2p(
                pts, cr_alt, dsc_rate=0.6, asc_rate=1.6)  # define flight mission
            SolarModel.repslr_irr(
                55, -100, 'America/Winnipeg', month)  # Canada
            print(f'Simulating flight in CAN, month: {month} ........ {i}')

            flight_modelCAN.sim_flight()  # simulate flight

            if flight_modelCAN.flight_succ:
                CANtot_succ += 1

            del flight_modelCAN

        CANrate_succ = CANtot_succ * 100 / tot_sim  # success rate in Canada
        writer.writerow([month, CANrate_succ])  # write result to file
        CANtot_succ = 0

stop = timeit.default_timer()
print('Time: ', stop - start)
print('End of simulations.')


batches = []
loss_epoch = []
train_acc_epoch = []
valid_acc_epoch = []
validation_accuracy = 0.0
EPOCHS = 2
BATCH_SIZE = 150

# batch_count = int(len(train['features']) / BATCH_SIZE)
batch_count = 5
# Add ops to save and restore all the variables.

# Start training
with tf.Session() as sess_re:
    new_saver = tf.train.import_meta_graph(os.path.join('model', 'mynet_A', 'valid_0.13.ckpt-100.meta'))
    new_saver.restore(sess_re, tf.train.latest_checkpoint(os.path.join('model'
                                                                       , 'mynet_A')))
    # Initialize the variables (i.e. assign their default value)
    init = tf.global_variables_initializer()

    # Run the initializer
    sess_re.run(init)
    # Restoring model and retraining with your own data
    re_g = tf.get_default_graph()

    # op to write logs to Tensorboard
    train_writer = tf.summary.FileWriter(logdir="logs", graph=re_g, filename_suffix="mynet_A_re")

#     print ("scope","name", "shape","type")
#     for i in (tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)):
#         print (i)

    for epoch in range(EPOCHS): # EPOCHS = 2
        batches_pbar = tqdm(range(batch_count), desc='Epoch {:>2}/{}'.format(epoch + 1, EPOCHS), unit='batches')

        for batch_i in batches_pbar:
            batch_start = batch_i * BATCH_SIZE
            batch_features = train['features'][batch_start:batch_start + BATCH_SIZE]
            batch_labels = train['labels'][batch_start:batch_start + BATCH_SIZE]

            _, l, summary = sess_re.run(
                [optimizer, loss, merged_summary_op],
                feed_dict={x: batch_features, y: batch_labels})
            # print (epoch * batch_count + batch_i)
            train_writer.add_summary(summary, epoch * BATCH_SIZE + batch_i)

        training_accuracy = sess_re.run(
            accuracy,
            feed_dict={x: batch_features, y: batch_labels}
        )

        idx = np.random.randint(len(valid['features']), size=int(BATCH_SIZE * .2))

        validation_accuracy = sess_re.run(
            accuracy,
            feed_dict={x: valid['features'][idx,:], y: valid['labels'][idx,:]}
        )

        print('Epoch {:>2}/{}'.format(epoch + 1, EPOCHS))
        print("loss is {}".format(l))
        print("training set accuracy is {}".format(training_accuracy))
        print("validation set accuracy is {}".format(validation_accuracy))

        batches.append(len(batches))
        loss_epoch.append(l)
        train_acc_epoch.append(training_accuracy)
        valid_acc_epoch.append(validation_accuracy)

    # Save model weights to disk
    # global_step refer to the number of batches seen by the graph.
    model_path = "model//{0}//valid_{1:.2f}.ckpt".format("mynet_A", validation_accuracy)
    save_path = saver.save(sess_re, model_path, global_step=100)
    print("Model saved in file: %s" % save_path)


from __future__ import annotations  # for python 3.8

from datetime import datetime
from operator import attrgetter

import requests

from agstoolbox.core.gh.release import Release
from agstoolbox.core.version.version import Version
from agstoolbox.core.version.version_utils import tag_to_version

def is_asset_archive(release_name: str, asset_name: str) -> bool:
    version = release_name.replace(" ", "").replace("v.", "")
    is_patch = asset_name.startswith("AGS-" + version + "-P")
    if is_patch:
        patch = asset_name.split(version + "-P")[1].split(".")[0]
        version += "-P" + patch

    archive_name = "AGS-" + version + ".zip"
    return asset_name == archive_name

def parse_releases(response_json) -> list[Release]:
    releases = [None] * len(response_json)
    count = 0

    for rel in response_json:
        rls = None
        found_asset = False

        # This can raise a TypeError in some weird condition I don't know what it is
        for asset in rel['assets']:
            # check for either predictable or patch release archives
            if is_asset_archive(rel['name'], asset['name']):
                rls = Release()
                rls.archive_id = str(asset['id'])
                rls.archive_name = asset['name']
                rls.archive_url = asset['browser_download_url']
                rls.archive_size = int(asset['size'])
                found_asset = True
                break

        if not found_asset:
            for asset in rel['assets']:
                # check for either predictable or patch release archives
                if is_asset_archive(rel['tag_name'], asset['name']):
                    rls = Release()
                    rls.archive_id = str(asset['id'])
                    rls.archive_name = asset['name']
                    rls.archive_url = asset['browser_download_url']
                    rls.archive_size = asset['size']
                    found_asset = True
                    break

        if not found_asset:
            continue

        rls.text_details = rel['body']
        rls.name = rel['name']
        rls.id = str(rel['id'])
        rls.url = rel['url']
        rls.html_url = rel['html_url']

        tag = rel['tag_name']
        rls.tag = tag
        rls.version = tag_to_version(tag)

        rls.is_pre_release = rel['prerelease']
        rls.published_at = rel['published_at']
        tstamp = datetime.strptime(rel['published_at'], "%Y-%m-%dT%H:%M:%SZ")
        rls.published_at_timestamp = tstamp.timestamp()
        releases[count] = rls
        count += 1

    releases = list(filter(None, releases))

    releases.sort(key=attrgetter("published_at_timestamp"), reverse=True)

    return releases

def list_releases() -> list[Release]:
    response = requests.get(
        "https://api.github.com/repos/adventuregamestudio/ags/releases?per_page=100")
    response_json = response.json()
    return parse_releases(response_json)

def get_latest_release_family(releases: list[Release], family: str) -> Release | None:
    filtered_releases = [r for r in releases if r.version.family == family]
    filtered_releases.sort(key=attrgetter("version.as_int"), reverse=True)
    if len(filtered_releases) >= 1:
        return filtered_releases[0]
    else:
        return None

def get_release_version(releases: list[Release], version: Version) -> Release | None:
    filtered_releases = [r for r in releases if r.version.as_int == version.as_int]
    if len(filtered_releases) == 1:
        return filtered_releases[0]
    else:
        return None


from django.urls import path

from . views import  drivers, create_driver, single_driver,rate

urlpatterns = [
    # path('drivers_dash/', drivers_dash, name='drivers_dash'),
    path("create_driver", create_driver, name="create_driver"),
    path('drivers/', drivers, name='drivers'),
    path('drivers/<str:name>', single_driver, name='single_driver'),
    path("rate/<int:id>", rate, name='rate'),

]


import json
import boto3
s3 = boto3.client('s3')

def lambda_handler(event, context):
    start = event['start']
    end = event['end']

    start = int(start)
    end = int(end)
    blocks = []
    for b in range(start, end+1):
        blocks.append(str(b))
    blocks = tuple(blocks)

    query = "select blockNumber, hash, transactionIndex, 'from', 'to', isMainChain FROM S3Object where blockNumber in " + str(blocks)  + " limit 30"
    print(query)

    response = s3.select_object_content(
        Bucket='blockchain-api-challenge',
        Key='blockchain_data/tx.csv',
        Expression=query,
        ExpressionType='SQL',
        InputSerialization={
            'CompressionType': 'NONE',
            'CSV': {
                'FileHeaderInfo': 'USE',
                'FieldDelimiter': ',',
                'RecordDelimiter': '\n'
            }
        },
        OutputSerialization={
            'JSON': {
                'RecordDelimiter': '\n'
            }
        }
    )

    records = ''
    for events in response['Payload']:
        if 'Records' in events:
            records = events['Records']['Payload'].decode('utf-8')
            print(records)

        elif 'Stats' in events:
            statsDetails = events['Stats']['Details']
            print("Bytes scanned: ")
            print(statsDetails['BytesScanned'])
            print("Bytes processed: ")
            print(statsDetails['BytesProcessed'])

    if records == '':
        return {
            'statusCode': 200,
            'body': 'page does not exist'
        }

    return {
        'statusCode': 200,
        'body': records
    }


import logging
import boto3
from botocore.exceptions import ClientError

s3 = boto3.client('s3')
bucket_name = 'uploadingimageandgettingurl'
#for bucket in s3.buckets.all():
 #   print(bucket.name)

# with open('batmanRises.png', 'wb') as img:
#     s3.download_fileobj('uploadingimageandgettingurl', 'batmanRises.png' , img)

def upload_file(file_name,bucket,object_name=None):
    if object_name is None:
        object_name=file_name

    s3_client = boto3.client('s3')
    try:
        response = s3_client.upload_file(file_name,bucket,object_name)
    except ClientError as e:
        logging.error(e)
        return False
    return True

#with open('putatoe.jpg', 'rb') as img:
#     s3.upload_fileobj(img ,'uploadingimageandgettingurl', "putatoe_image")

s3.upload_file('batmanRises.png',bucket_name, 'batman_img' ,ExtraArgs = {'ACL':'public-read'})

key = "putatoe_image"
location = s3.get_bucket_location(Bucket = bucket_name)['LocationConstraint']
url = "https://s3-%s.amazonaws.com/%s/%s" % (location, bucket_name, key)
print(url)


from django.shortcuts import redirect, render
from .forms import userForm
from .models import userdata

# Create your views here.
def index(request):
    if request.method=='POST':
        user=userForm(request.POST)
        if user.is_valid(): #true
            user.save()
            print("Your data has been saved!")
        else:
            print(user.errors)
    return render(request,'index.html')

def showdata(request):
    data=userdata.objects.all()
    return render(request,'showdata.html',{'data':data})

def deletedata(request,stid):
   id=userdata.objects.get(id=stid)
   userdata.delete(id)
   return redirect('showdata')

def updatedata(request,stid):
    id=userdata.objects.get(id=stid)
    if request.method=='POST':
        updateuser=userForm(request.POST)
        if updateuser.is_valid():
            updateuser=userForm(request.POST,instance=id)
            updateuser.save()
            print("Your records has been updated!")
            return redirect('showdata')
        else:
            print(updateuser.errors)
    return render(request,'updatedata.html',{'stdata':userdata.objects.get(id=stid)})


from collections import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dict={} #Empty dictionary to hold index and value in a K,V manner
        result=[]
        for i, j in enumerate(nums):
            result= target - j # result is subtraction of target - value J at index i

            #If the result is in the dict return the value of the key result in the dict and the index i
            if result in dict:
                return [dict[result], i]

            dict[j]= i # element j will be key and index i will be value for the dict


from xml.etree.ElementTree import Element, SubElement, ElementTree

class CharacterElement:
    def __init__ (self, player_name, image_path,x,y):
        self.player_name       = player_name
        self.image_path        = image_path
        self.x                 = x
        self.y                 = y

    # def __init__ (self):
    #     self.player_name    = 'player'
    #     self.image_path     = 'testCharacter_1_image'

    def make_character_snippet (self):
        e_character_root = Element("character")
        e_character_root.set('location.name','table')
        e_character_root.set('location.x',self.x)
        e_character_root.set('location.y',self.y)
        e_character_root.set('posZ','0')
        e_character_root.set('rotate','0')
        e_character_root.set('roll','0')
        e_character_root.append(self._make_character_element())
        e_character_root.append(self._make_chat_palette())
        return e_character_root

    def _make_character_element (self):
        e_character = Element("data")
        e_character.set('name','character')

        e_image = SubElement(e_character, "data")
        e_image.set('name','image')
        e_image_path = SubElement(e_image,'data')
        e_image_path.set('type','image')
        e_image_path.set('name','imageIdentifier')
        e_image_path.text = self.image_path

        e_common = SubElement(e_character, "data")
        e_common.set('name','common')
        e_player_name = SubElement(e_common, "data")
        e_player_name.set('name','name')
        e_player_name.text = self.player_name
        e_size = SubElement(e_common, "data")
        e_size.set('name','size')
        e_size.text = '1'

        e_detail = SubElement(e_character, "data")
        e_detail.set('name','detail')
        e_resource = SubElement(e_detail, "data")
        e_resource.set('name','resource')
        e_wealth = SubElement(e_resource, "data")
        e_wealth.set('type','numberResource')
        e_wealth.set('currentValue','0')
        e_wealth.set('name','wealth')
        e_wealth.text = '16'

        e_authority = SubElement(e_resource, "data")
        e_authority.set('type','numberResource')
        e_authority.set('currentValue','0')
        e_authority.set('name','authority')
        e_authority.text = '16'

        e_information = SubElement(e_detail, "data")
        e_information.set('name','information')
        e_explanation = SubElement(e_information, "data")
        e_explanation.set('type','note')
        e_explanation.set('name','explanation')

        e_memo = SubElement(e_information, "data")
        e_memo.set('type','note')
        e_memo.set('name','memo')

        return e_character

    def _make_chat_palette (self):
        e_chat_palette = Element("chat-palette")
        e_chat_palette.set('dicebot','')
        return e_chat_palette


import datetime

class Bankrekening:
    def _current_time():
        now = datetime.datetime.now()
        return f"{now:%Y-%m-%d %H:%M:%S}"

    def __init__(self, naam, saldo):
        self._name = naam
        self.__saldo = saldo
        self._transactie_overzicht = []
        print("Bankrekening aangemaakt voor " + self._name)

    def storten(self, bedrag):
        if bedrag > 0:
            self.__saldo += bedrag
            self.toon_saldo()
            self._transactie_overzicht.append((Bankrekening._current_time(), bedrag))
        self.toon_saldo()

    def opnemen(self, bedrag):
        if 0 < bedrag <= self.__saldo:
            self.__saldo -= bedrag
            self._transactie_overzicht.append(((Bankrekening._current_time(), -bedrag)))
        else:
            print(
                "Het bedrag dient groter dan nul (0) en maximaal gelijk aan het saldo te zijn"
            )
        self.toon_saldo()

    def toon_saldo(self):
        print(f"Saldo bedraagt {self.__saldo}")

    def toon_transacties(self):
        for date, bedrag in self._transactie_overzicht:
            if bedrag > 0:
                trans_type = "gestort"
            else:
                trans_type = "opgenomen"
                bedrag *= -1
            print(f"{bedrag} {trans_type} op {Bankrekening._current_time()}")


from django.urls import path

from . import views
from . import apiviews

app_name = 'polls'
urlpatterns = [
        path('', views.IndexView.as_view(), name='index'),
        path('<int:pk>/', views.DetailView.as_view(), name='detail'),
        path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
        path('<int:question_id>/vote/', views.vote, name='vote'),
        path('api/questions/', apiviews.QuestionList.as_view(), name='question_list'),
        path('api/questions/<int:pk>/', apiviews.QuestionDetail.as_view(), name='question_detail'),
        path('api/choices/', apiviews.ChoiceList.as_view(), name='choice_list'),
        path('api/choices/<int:pk>/', apiviews.ChoiceDetail.as_view(), name='choice_detail'),

]