class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.root.setText("")
        self.onlyInt = QIntValidator()
        self.ui.a.setValidator(self.onlyInt)
        self.ui.b.setValidator(self.onlyInt)
        self.ui.c.setValidator(self.onlyInt)
        self.ui.pushButton.clicked.connect(self.roots)

    def roots(self):
        a = self.ui.a.text()
        b = self.ui.b.text()
        c = self.ui.c.text()
        a = int(a)
        b = int(b)
        c = int(c)

        disk = b**2 - 4 * a * c
        if disk < 0:
            string = "Немає дійсних коренів."
        elif disk == 0:
            x = -b / 2 / a
            x = round(x, 2)
            string = "x=" + str(x)
        else:
            x1 = (-b - sqrt(disk)) / 2 / a
            x2 = (-b + sqrt(disk)) / 2 / a
            x1 = round(x1, 2)
            x2 = round(x2, 2)
            string = "x1=" + str(x1) + "\nx2=" + str(x2)
        self.ui.root.setText(string)
Beispiel #2
0
    def __init__(self):

        super(mywindow, self).__init__()

        # Init Main GUI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Load BOT Settings
        self.loadSettings()

        # Set Start Button OnClick Event Function
        self.ui.btStart.clicked.connect(self.onStart)

        # Set Stop Button OnClick Event Function
        self.ui.btStop.clicked.connect(self.onStop)

        # Set Start Menu OnClick Event Function
        self.ui.menuStart.triggered.connect(self.onStart)

        # Set Stop Menu OnClick Event Function
        self.ui.menuStop.triggered.connect(self.onStop)

        # Set Save Settings Menu OnClick Event Function
        self.ui.menuSaveSettings.triggered.connect(self.saveSettings)

        # Set EXIT Menu OnClick Event Function
        self.ui.menuEXIT.triggered.connect(self.onEXIT)
Beispiel #3
0
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # self.setFixedSize(1280, 720)
        self.setWindowTitle('Учет выполнения нарядов')
        self.ui.pushButton.clicked.connect(self.log_in)
        self.ui.pushButton.setAutoDefault(True)  # click on <Enter>
        self.ui.lineEdit_2.returnPressed.connect(self.ui.pushButton.click)  # click on <Enter>

        self.ui.comboBox_2_Naryad.currentIndexChanged.connect(self.Nar2)
        self.ui.vihod_Button.clicked.connect(self.Vihod)

        self.ui.pushButton_2_nachat.clicked.connect(self.Nachat_nar)
        self.ui.pushButton_4_pauza.clicked.connect(self.Pauza_nar)
        self.ui.pushButton_3_zaconch.clicked.connect(self.Zakonch_nar)
        self.ui.pushButton_x_otkr_kd.clicked.connect(self.Otkr_chert)
        self.ui.pushButton_obnov_sp_nar.clicked.connect(self.but_obnov_spis_naryadov)
        self.ui.lineEdit_3_nParol.setVisible(False)
        self.ui.lineEdit_3_nParol_2.setVisible(False)
        self.ui.listWidget_3_Temp.setVisible(False)

        self.ui.label_7.installEventFilter(self)
        self.ui.label_6.installEventFilter(self)

        self.action = self.findChild(QtWidgets.QAction, "action")
        self.action.triggered.connect(self.Smena_Parol)
        self.action_2_new_user = self.findChild(QtWidgets.QAction, "action_2_new_user")
        self.action_2_new_user.triggered.connect(self.Reg_new_user)
        # =====================================================проверка файлов
        for item in proverka_list_puti:
            if FNC.proverka_nalichie_puti(item) == False:
                self.showDialog("Не найден " + item)
                sys.exit(app.exec())
        for item in proverka_list_znach:
            if FNC.proverka_nalichie_znach(item) == False:
                self.showDialog("Не найден " + item)
                sys.exit(app.exec())
        # =====================================================

        with open(cfg['employee'] + '\\employee.txt', 'r', encoding='utf-8') as f:
            Stroki = f.readlines()
        with open(cfg['FiltrEmp'] + '\\FiltrEmp.txt', 'r') as f:
            Stroki_emp = f.readlines()
        Stroki_temp2 = Stroki.copy()
        with open(cfg['FiltrEmpDel'] + '\\FiltrEmpDel.txt', 'r') as f:
            Stroki_FiltrEmpDel = f.readlines()
        for item in Stroki_temp2:
            for iskl in Stroki_FiltrEmpDel:
                if iskl.strip() in item:
                    Stroki.remove(item)
                    break
        Stroki_temp2.clear()
        for line in Stroki:
            line = line.replace(',', '  ')
            line = line.replace('\n', '')
            if FNC.etap_po_fio(line, Stroki_emp) != "":
                line = line.encode('cp1251', errors='ignore').decode('cp1251')
                self.ui.comboBox.addItem(line)
    def __init__(self):
        #launch the UI
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #gain access to spreadsheet
        googleAuth.googleAuth()

        #initialize/reset values
        self.resetVariables()

        #set images to be scaled
        self.ui.sftImage.setScaledContents(True)
        self.ui.aftImage.setScaledContents(True)
        self.ui.shinyImage.setScaledContents(True)
        self.ui.battleImage.setScaledContents(True)

        #connect buttons to their utility methods
        self.ui.pokemonLineEdit.returnPressed.connect(self.getPokemon)
        self.ui.sftSubmitPushButton.clicked.connect(self.submitSft)
        self.ui.aftSubmitPushButton.clicked.connect(self.submitAft)
        self.ui.shinySubmitPushButton.clicked.connect(self.submitShiny)
        self.ui.battleSubmitPushButton.clicked.connect(self.submitBattler)
        self.ui.updateRowsButton.clicked.connect(self.updateRowCounters)

        #Update the current empty rows
        self.updateRowCounters()
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.label.setGeometry(QtCore.QRect(100, 25, 700, 150))
        if response.status_code != 200:
            self.ui.label.setGeometry(QtCore.QRect(250, 25, 700, 150))
        self.ui.label.setText(title)

        self.ui.resplabel.setGeometry(QtCore.QRect(300, 10, 700, 150))
        self.ui.resplabel.setText(response_status)

        if response.status_code == 200:
            self.ui.tableWidget.setColumnCount(2)
            self.ui.tableWidget.setRowCount(len(jsn['series']))
            self.ui.tableWidget.setHorizontalHeaderLabels(
                ('Region', 'Net change'))
            row = 0
            for tup in data:
                col = 0
                for item in tup:
                    cellinfo = QTableWidgetItem(item)
                    self.ui.tableWidget.setItem(row, col, cellinfo)
                    cellinfo.setFlags(QtCore.Qt.ItemIsSelectable
                                      | QtCore.Qt.ItemIsEnabled)
                    col += 1

                row += 1
Beispiel #6
0
class main_window(QtWidgets.QMainWindow):

    def __init__(self):
        super(QtWidgets.QMainWindow, self).__init__()  # read on how to use super and use it well here to initialize only the QtWidgets.QMainWindow class
        self.setWindowIcon(QtGui.QIcon("todo_icon.ico")) # this sets the icon of the user interface
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.save_PushButton.setStyleSheet("background-color: rgb(0,128,0); color: white;")
        self.ui.delete_PushButton.setStyleSheet("background-color: rgb(255,0,0); color: white;")
        self.edit_PushButton_default()
        # self.groups_comboBox_default()
        self.enable_or_disable_save_PushButton()
        """ this disables the save button until the user clicks to type a new task 
            and disables the save button anytime the text input is blank"""
        self.ui.new_task_TextEdit.textChanged.connect(self.enable_or_disable_save_PushButton)
        self.ui.edit_PushButton.clicked.connect(self.change_editButton_text)
        self.ui.save_PushButton.clicked.connect(self.add_task_to_db)

    # this function makes the edit button blue by default
    def edit_PushButton_default(self):
        self.ui.edit_PushButton.setText("Edit")
        self.ui.edit_PushButton.setStyleSheet("background-color: #0066CC; color: white;")

    def change_editButton_text(self):
        if self.ui.edit_PushButton.text() == "Edit":
            self.ui.edit_PushButton.setText("Update")
            self.ui.edit_PushButton.setStyleSheet("background-color: rgb(255,69,0); color: white;")   
        else:
            self.edit_PushButton_default()

    """ this function checks whether the textEdit for new tasks is empty
        returns true if empty and false otherwise."""

    def isEmpty_new_task_TextEdit(self):
        self.content = self.ui.new_task_TextEdit.toPlainText()
        if self.content == "":
            return True
        else:
            return False

    def enable_or_disable_save_PushButton(self):
        if self.isEmpty_new_task_TextEdit():
            self.ui.save_PushButton.setEnabled(False)
        else:
            self.ui.save_PushButton.setEnabled(True)


    def add_task_to_db(self):
        self.start_date = self.ui.start_dateEdit.date().toPyDate()
        self.start_time = self.ui.start_timeEdit.time().toPyTime()
        self.end_date = self.ui.end_dateEdit.date().toPyDate()
        self.end_time = self.ui.end_timeEdit.time().toPyTime()
        self.task_description = self.ui.new_task_TextEdit.toPlainText()
        self.group = str(self.ui.groups_comboBox.currentText())
        #inserts a new task into the task database
        self.new_task = task(self.start_date, self.start_time, self.end_date, self.end_time, self.task_description, self.group) 
        # clears the text input after the user clicks the save button
        self.ui.new_task_TextEdit.clear()
        self.ui.allTasks_listWidget.addItem(self.task_description)
 def __init__(self):
     super(mywindow, self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.pushButton_3.clicked.connect(self.btnClickedShowAll)
     self.ui.pushButton.clicked.connect(self.btnClickedAdd)
     self.ui.pushButton_2.clicked.connect(self.btnClickedRemoveTest)
     self.ui.pushButton_4.clicked.connect(self.btnClickedShowStatistics)
 def __init__(self):
     super(mywindow, self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.root.setText("")
     self.onlyInt = QIntValidator()
     self.ui.a.setValidator(self.onlyInt)
     self.ui.b.setValidator(self.onlyInt)
     self.ui.c.setValidator(self.onlyInt)
     self.ui.pushButton.clicked.connect(self.roots)
Beispiel #9
0
 def __init__(self):
     super(mywindow, self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.b_lexico.clicked.connect(self.ev_lexico)
     self.ui.b_sintactico.clicked.connect(self.ev_sintactico)
     self.ui.b_cargar.clicked.connect(self.ev_cargar)
     self.ui.b_limpiar.clicked.connect(self.ev_limpiar)
     self.ui.b_limpiar_sintactico.clicked.connect(
         self.ev_limpiar_sintactico)
     self.ui.b_limpiar_lexico.clicked.connect(self.ev_limpiar_lexico)
Beispiel #10
0
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton.clicked.connect(self.pushButton_handler)

        self.ui.pushButton_2.clicked.connect(self.pushButton_2_handler)

        self.ui.pushButton_3.clicked.connect(self.pushButton_3_handler)
        self.path = None
Beispiel #11
0
    def __init__(self):

        super(mywindow, self).__init__()

        self.ui = Ui_MainWindow()

        self.ui.setupUi(self)

        self.ui.label.setFont(QtGui.QFont('SansSerif', 30))

        self.ui.label.setGeometry(QtCore.QRect(10, 10, 200, 200))

        self.ui.label.setText("LikeGeeks")  #change label text
Beispiel #12
0
 def __init__(self, parent=None):
     super(mywindow, self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ip = None
     self.port = None
     self.p_number = None
     self.e_number = None
     self.ui.btn_send.setEnabled(False)
     self.ui.send_Text.setEnabled(False)
     self.ui.btn_clear.setEnabled(False)
     # Обработчики кнопок
     self.ui.btn_connect.clicked.connect(self.connect_server)
     self.ui.btn_send.clicked.connect(self.send_message)
     self.ui.btn_clear.clicked.connect(self.clear_panel)
Beispiel #13
0
 def __init__(self):
     super(QtWidgets.QMainWindow, self).__init__()  # read on how to use super and use it well here to initialize only the QtWidgets.QMainWindow class
     self.setWindowIcon(QtGui.QIcon("todo_icon.ico")) # this sets the icon of the user interface
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.save_PushButton.setStyleSheet("background-color: rgb(0,128,0); color: white;")
     self.ui.delete_PushButton.setStyleSheet("background-color: rgb(255,0,0); color: white;")
     self.edit_PushButton_default()
     # self.groups_comboBox_default()
     self.enable_or_disable_save_PushButton()
     """ this disables the save button until the user clicks to type a new task 
         and disables the save button anytime the text input is blank"""
     self.ui.new_task_TextEdit.textChanged.connect(self.enable_or_disable_save_PushButton)
     self.ui.edit_PushButton.clicked.connect(self.change_editButton_text)
     self.ui.save_PushButton.clicked.connect(self.add_task_to_db)
Beispiel #14
0
	def __init__(self):
		super(mywindow, self).__init__()
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)

		self.ui.comboBox.addItem("Метан <CH₄> - Methane")
		self.ui.comboBox.addItem("Метиловый спирт <CH₃OH> - Methanol")
		self.ui.comboBox.addItem("Пентан <C₅H₁₂> - Pentan")
		self.ui.comboBox.addItem("Пропан <C₃H₈> - Propan")
		self.ui.comboBox.addItem("Пропилен <C₃H₆> - Propylene")
		self.ui.comboBox.addItem("Сероводород <H₂S> - Hydrogen sulphide")
		self.ui.comboBox.addItem("Бутадиен <C₄H₆> - Butadiene")
		self.ui.comboBox.addItem("Бутан <C₄H₁₀> - Butane")
		self.ui.comboBox.addItem("Винилхлорид <C₂H₃Cl> - Vinylchloride")
		self.ui.comboBox.activated[str].connect(self.onActivated)
		self.ui.comboBox_2.addItem(Class_zagromo[0])
		self.ui.comboBox_2.addItem(Class_zagromo[1])
		self.ui.comboBox_2.addItem(Class_zagromo[2])
		self.ui.comboBox_2.addItem(Class_zagromo[3])
		self.ui.pushButton.clicked.connect(self.on_click)
Beispiel #15
0
    def __init__(self):

        super(mywindow, self).__init__()

        self.ui = Ui_MainWindow()

        self.ui.setupUi(self)
        self.ui.btnDownload.clicked.connect(self.btnClicked)
        self.ui.txtDir.setText('/home/dinhnv/Desktop/test')
        self.ui.txtUrl.setText(
            'https://www.youtube.com/watch?v=VD3swXisXSM&list=PLKU4arUIngTxmHYvkKUA3HylwU8oiSC5y'
        )
        self.ui.btnFile.clicked.connect(self.browseSlot)
        self.ui.tableWidget.setColumnWidth(0, 199)

        self.rowItems = []
        self.url_list = []
        self.complete_url_list = {}
        self.convert_list = []
        self.thread_pool = {}
        self.rowcount = 0
Beispiel #16
0
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        for i in [
                'spot_price', 'strike_price', 'risk_rate', 'exp_time', 'sigma'
        ]:
            self.__dict__[i] = ''

        self.dividends = []

        self.ui.calculateButton.clicked.connect(self.calculateButtonClicked)
        self.ui.divAddButton.clicked.connect(self.divAddButtonClicked)
        self.ui.divBox.activated[str].connect(self.divOnActivated)
        self.ui.divDeleteButton.clicked.connect(self.divDeleteButtonClicked)
        self.ui.divAllDeleteButton.clicked.connect(
            self.divAllDeleteButtonClicked)
        self.ui.undTypeBox.activated[str].connect(self.undActivated)

        self.ui.divYieldLabel.setDisabled(True)
        self.ui.divYield.setDisabled(True)
Beispiel #17
0
 def __init__(self):
     super(mywindow, self).__init__()
     self.tasks = []
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.graphWidget = pg.PlotWidget()
     self.ui.layoutGraph.addWidget(self.graphWidget)
     self.graphWidget.setBackground('w')
     self.graphWidget.setLabel('left',
                               'Температура (К)',
                               color='red',
                               size=30)
     self.graphWidget.setLabel('bottom',
                               'Радиус (см)',
                               color='red',
                               size=30)
     self.ui.label_current_time.setText("Индекс времени k = ")
     self.ui.sliderImage.valueChanged.connect(self.plotNextGraph)
     self.ui.buttonCaluclate.clicked.connect(self.calculate)
     self.ui.buttonClear.clicked.connect(self.clear)
     self.l = pg.LegendItem((160, 60), offset=(430, 10))
     self.l.setParentItem(self.graphWidget.graphicsItem())
 def __init__(self):
     super(mywindow, self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.RegionChoose()
     self.ui.region.currentIndexChanged.connect(self.RegionChoose)
     self.ui.final_2.clicked.connect(self.Calculate)
     self.ui.cores_in.selectionModel().selectionChanged.connect(
         self.SearchPlayerIn)
     self.ui.cores_out.selectionModel().selectionChanged.connect(
         self.SearchPlayerOut)
     self.ui.sups_in.selectionModel().selectionChanged.connect(
         self.SearchPlayerIn)
     self.ui.sups_out.selectionModel().selectionChanged.connect(
         self.SearchPlayerOut)
     self.ui.clear_sel_sups_in.clicked.connect(
         self.ui.sups_in.clearSelection)
     self.ui.clear_sel_cores_in.clicked.connect(
         self.ui.cores_in.clearSelection)
     self.ui.clear_sel_sups_out.clicked.connect(
         self.ui.sups_out.clearSelection)
     self.ui.clear_sel_cores_out.clicked.connect(
         self.ui.cores_out.clearSelection)
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.RegionChoose()
        self.ui.region.currentIndexChanged.connect(self.RegionChoose)
        self.ui.final_2.clicked.connect(self.Calculate)
        self.ui.cores_in.selectionModel().selectionChanged.connect(
            self.SearchPlayerIn)
        self.ui.cores_out.selectionModel().selectionChanged.connect(
            self.SearchPlayerOut)
        self.ui.sups_in.selectionModel().selectionChanged.connect(
            self.SearchPlayerIn)
        self.ui.sups_out.selectionModel().selectionChanged.connect(
            self.SearchPlayerOut)
        self.ui.clear_sel_sups_in.clicked.connect(
            self.ui.sups_in.clearSelection)
        self.ui.clear_sel_cores_in.clicked.connect(
            self.ui.cores_in.clearSelection)
        self.ui.clear_sel_sups_out.clicked.connect(
            self.ui.sups_out.clearSelection)
        self.ui.clear_sel_cores_out.clicked.connect(
            self.ui.cores_out.clearSelection)

    def RegionChoose(self):
        Region = int(self.ui.region.currentIndex() + 1)
        self.ui.score_matrix.clear()
        winlist_orig = sheet.get_worksheet(Region * 2 + 1).get_all_records()
        loselist_orig = sheet.get_worksheet(Region * 2 + 2).get_all_records()
        players_list_win = []
        players_list_lose = []
        deleting(winlist_orig, players_list_win)
        deleting(loselist_orig, players_list_lose)

        self.ui.cores_in.clear()
        self.ui.cores_out.clear()
        self.ui.sups_in.clear()
        self.ui.sups_out.clear()

        for team in teams:
            temp = {}
            for player in players_list_win:
                if player[0] == team:
                    temp[str(player[1])] = player[2]
            globals()[str(team + '_win')] = temp
            for nick in temp.keys():
                if temp.get(nick)[0] == 'C':
                    self.ui.cores_in.addItem(nick)
                    self.ui.cores_out.addItem(nick)
                elif temp.get(nick)[0] == 'S':
                    self.ui.sups_in.addItem(nick)
                    self.ui.sups_out.addItem(nick)

        for team in teams:
            temp = {}
            for player in players_list_lose:
                if player[0] == team:
                    temp[str(player[1])] = player[2]
            globals()[str(team + '_lose')] = temp

        self.ui.score_matrix.setColumnCount(len(teams))
        self.ui.score_matrix.setRowCount(len(teams))
        self.ui.score_matrix.setHorizontalHeaderLabels(teams)
        self.ui.score_matrix.setVerticalHeaderLabels(teams)
        self.ui.score_matrix.horizontalHeader().setFixedHeight(25)
        self.ui.score_matrix.verticalHeader().setFixedWidth(75)
        for it in range(len(teams)):
            self.ui.score_matrix.setColumnWidth(it, 75)
            self.ui.score_matrix.setRowHeight(it, 35)
        #self.ui.score_matrix.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
        for row in range(len(teams)):
            for col in range(len(teams)):
                self.ui.score_matrix.setItem(row, col, QTableWidgetItem())
                item = self.ui.score_matrix.item(row, col)
                item.setTextAlignment(Qt.AlignCenter)
                item.setFont(QtGui.QFont('Segoe UI', 12))
        for row in range(len(teams)):
            for col in range(row + 1):
                item = self.ui.score_matrix.item(row, col)
                item.setBackground(QtGui.QColor(150, 150, 150))
                item.setFlags(item.flags() & ~Qt.ItemIsEnabled)

    def SearchPlayerIn(self):
        global player_in
        global player_out
        player_in = []
        for player1 in self.ui.cores_in.selectedItems():
            player_in.append(player1)
        for player1 in self.ui.sups_in.selectedItems():
            player_in.append(player1)
        for index in range(self.ui.cores_out.count()):
            row = self.ui.cores_out.item(index)
            row.setFlags(row.flags() | Qt.ItemIsEnabled)
        for index in range(self.ui.sups_out.count()):
            row = self.ui.sups_out.item(index)
            row.setFlags(row.flags() | Qt.ItemIsEnabled)
        for index in self.ui.cores_in.selectedIndexes():
            row = index.row()
            item = self.ui.cores_out.item(row)
            item.setFlags(item.flags() & ~Qt.ItemIsEnabled)
        for index in self.ui.sups_in.selectedIndexes():
            row = index.row()
            item = self.ui.sups_out.item(row)
            item.setFlags(item.flags() & ~Qt.ItemIsEnabled)
        column = range(3, 8)
        flag_in = 0
        flag_out = 0
        for row in range(self.ui.output_table.rowCount()):
            for col in column:
                for one in player_in:
                    if one.text() in self.ui.output_table.item(row,
                                                               col).text():
                        flag_in += 1
                for two in player_out:
                    if two.text() in self.ui.output_table.item(row,
                                                               col).text():
                        flag_out += 1
            if flag_in == len(player_in) and flag_out == 0:
                self.ui.output_table.showRow(row)
                flag_in = 0
            else:
                self.ui.output_table.hideRow(row)
                flag_in = 0
                flag_out = 0

    def SearchPlayerOut(self):
        global player_in
        global player_out
        player_out = []
        for player1 in self.ui.cores_out.selectedItems():
            player_out.append(player1)
        for player1 in self.ui.sups_out.selectedItems():
            player_out.append(player1)
        for index in range(self.ui.cores_in.count()):
            row = self.ui.cores_in.item(index)
            row.setFlags(row.flags() | Qt.ItemIsEnabled)
        for index in range(self.ui.sups_in.count()):
            row = self.ui.sups_in.item(index)
            row.setFlags(row.flags() | Qt.ItemIsEnabled)
        for index in self.ui.cores_out.selectedIndexes():
            row = index.row()
            item = self.ui.cores_in.item(row)
            item.setFlags(item.flags() & ~Qt.ItemIsEnabled)
        for index in self.ui.sups_out.selectedIndexes():
            row = index.row()
            item = self.ui.sups_in.item(row)
            item.setFlags(item.flags() & ~Qt.ItemIsEnabled)
        column = range(3, 8)
        flag_in = 0
        flag_out = 0
        for row in range(self.ui.output_table.rowCount()):
            for col in column:
                for two in player_out:
                    if two.text() in self.ui.output_table.item(row,
                                                               col).text():
                        flag_out += 1
                for one in player_in:
                    if one.text() in self.ui.output_table.item(row,
                                                               col).text():
                        flag_in += 1
            if flag_out > 0 or flag_in != len(player_in):
                self.ui.output_table.hideRow(row)
                flag_out = 0
                flag_in = 0
            else:
                self.ui.output_table.showRow(row)
                flag_out = 0
                flag_in = 0

    def Calculate(self):
        global player_in
        global player_out
        player_in = []
        player_out = []
        self.ui.sups_in.clearSelection()
        self.ui.cores_in.clearSelection()
        self.ui.sups_out.clearSelection()
        self.ui.cores_out.clearSelection()
        self.ui.output_table.clear()
        self.ui.output_table.setColumnCount(0)
        self.ui.output_table.setRowCount(0)

        global playing
        playing = []
        global teams_with_score
        teams_with_score = []

        for team in teams:
            teams_with_score.append([team, 0, 0])
        num_rows, num_cols = self.ui.score_matrix.rowCount(
        ), self.ui.score_matrix.columnCount()
        for i in range(0, num_rows):
            for j in range(i + 1, num_cols):
                scorex = self.ui.score_matrix.item(i, j)
                #self.ui.label_10.setText(scorex)
                if (scorex and scorex.text()):
                    team1 = self.ui.score_matrix.horizontalHeaderItem(i).text()
                    team2 = self.ui.score_matrix.verticalHeaderItem(j).text()
                    if team1 not in playing:
                        playing.append(team1)
                    if team2 not in playing:
                        playing.append(team2)
                    scorex = scorex.text()
                    scorex = scorex.split('-')
                    for teamz in teams_with_score:
                        if teamz[0] == team1:
                            teamz[1] += int(scorex[0])
                            teamz[2] += 2 - int(scorex[0])
                        elif teamz[0] == team2:
                            teamz[1] += int(scorex[1])
                            teamz[2] += 2 - int(scorex[1])

        team_multis = {teamx[0]: teamx[1:] for teamx in teams_with_score}
        for team in playing:
            temporary = globals()[str(team + '_win')]
            globals()[str(team)] = temporary.copy()
        sup_nicks = []
        sup_price = []
        sup_pts = []
        core_nicks = []
        core_price = []
        core_pts = []
        setup = []
        setup1 = []
        setup_all = []
        setup_all1 = []

        for team in playing:
            nicks = eval(team).keys()
            for nick in nicks:
                if eval(team).get(nick)[0] == 'C':
                    core_nicks.append(nick)
                    core_pts.append(
                        round(
                            float(eval(str(team + '_win')).get(nick)[1]) *
                            team_multis.get(team)[0] +
                            float(eval(str(team + '_lose')).get(nick)[1]) *
                            team_multis.get(team)[1],
                            2))  # пофиксить на умножение
                    core_price.append(eval(team).get(nick)[2])
                elif eval(team).get(nick)[0] == 'S':
                    sup_nicks.append(nick)
                    sup_pts.append(
                        round(
                            float(eval(str(team + '_win')).get(nick)[1]) *
                            team_multis.get(team)[0] +
                            float(eval(str(team + '_lose')).get(nick)[1]) *
                            team_multis.get(team)[1], 2))
                    sup_price.append(eval(team).get(nick)[2])

        for i in range(len(sup_nicks)):
            for j in range(i + 1, len(sup_nicks)):
                for k in range(len(core_nicks)):
                    for l in range(k + 1, len(core_nicks)):
                        for m in range(l + 1, len(core_nicks)):
                            score = round(
                                sup_pts[i] + sup_pts[j] + core_pts[k] +
                                core_pts[l] + core_pts[m], 2)
                            price = sup_price[i] + sup_price[j] + core_price[
                                k] + core_price[l] + core_price[m]
                            if price <= 50:
                                setup1.append([
                                    score, price, sup_nicks[i] + ' (' +
                                    str(sup_pts[i]) + ')', sup_nicks[j] +
                                    ' (' + str(sup_pts[j]) + ')',
                                    core_nicks[k] + ' (' + str(core_pts[k]) +
                                    ')', core_nicks[l] + ' (' +
                                    str(core_pts[l]) + ')', core_nicks[m] +
                                    ' (' + str(core_pts[m]) + ')'
                                ])
                                if (
                                        checking_cores(core_nicks[k],
                                                       core_nicks[l],
                                                       core_nicks[m]) and
                                    (checking_sups(sup_nicks[i], sup_nicks[j]))
                                ):  # and (core_nicks[l] or core_nicks[m]) in check_cores
                                    if (ex_sups(sup_nicks[i], sup_nicks[j])
                                            and ex_cores(
                                                core_nicks[k], core_nicks[l],
                                                core_nicks[m])):  #
                                        setup.append([
                                            score, price, sup_nicks[i] + ' (' +
                                            str(sup_pts[i]) + ')',
                                            sup_nicks[j] + ' (' +
                                            str(sup_pts[j]) + ')',
                                            core_nicks[k] + ' (' +
                                            str(core_pts[k]) + ')',
                                            core_nicks[l] + ' (' +
                                            str(core_pts[l]) + ')',
                                            core_nicks[m] + ' (' +
                                            str(core_pts[m]) + ')'
                                        ])

        setup_all1.sort(key=lambda i: i[0], reverse=True)
        setup.sort(key=lambda i: i[0], reverse=True)
        setup1.sort(key=lambda i: i[0], reverse=True)
        top_score = setup[0][0]
        setup = setup[0:10000]
        for i in range(len(setup)):
            setup[i].insert(1, round(setup[i][0] - top_score, 2))

        columns = [
            'Score', 'Diff', 'Price', 'Sup1', 'Sup2', 'Core1', 'Core2', 'Core3'
        ]
        self.ui.output_table.setColumnCount(len(columns))
        self.ui.output_table.setHorizontalHeaderLabels(columns)
        for record in range(len(setup)):
            self.ui.output_table.insertRow(record)
            for cell in range(len(setup[record])):
                self.ui.output_table.setItem(
                    record, cell, QTableWidgetItem(str(setup[record][cell])))
        #self.ui.output_table.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
        for col in range(0, 3):
            self.ui.output_table.resizeColumnToContents(col)
        for col in range(3, 8):
            self.ui.output_table.setColumnWidth(col, 130)
Beispiel #20
0
class mywindow(QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton.clicked.connect(self.pushButton_handler)

        self.ui.pushButton_2.clicked.connect(self.pushButton_2_handler)

        self.ui.pushButton_3.clicked.connect(self.pushButton_3_handler)
        self.path = None

    def pushButton_handler(self):
        filename = QFileDialog.getOpenFileName()
        path = filename[0]

        with open(path) as graph:
            lines = [line.strip() for line in graph]  # Беру строки из файла

        self.n, self.m = map(
            int, lines[0].split())  # Беру с файла количество вершин и рёбер

        self.g = [0] * self.n  # Список смежности вершин
        for i in range(self.n):
            self.g[i] = []

        self.G = nx.Graph()
        if self.m == 0:
            for i in range(1, self.n + 1):
                self.G.add_node(i)
        for i in range(1, self.m + 1):
            u, v = map(int, lines[i].split())
            self.G.add_edge(u, v)
            u -= 1  # потому что в питоне нумерация с 0, а у нас с 1
            v -= 1
            self.g[u].append(v)  # добавляем в список смежности
            self.g[v].append(u)

        self.l = QVBoxLayout(self.ui.widget)
        sc = PlotCanvas(self.ui.widget, self.G, 'black', 'black')
        self.l.addWidget(sc)

    def pushButton_2_handler(self):
        filename = QFileDialog.getOpenFileName()
        self.path = filename[0]

    def pushButton_3_handler(self):
        def check(lst, sub):  #срез списка
            for i in range(len(lst)):
                if lst[i:i + len(sub)] == sub:
                    return True
            return False

        def hamilton(u):
            turn.append(u)
            if len(turn) == self.n:  # если уже вершины прошли
                if turn[-1] in self.g[0]:  # и если это цикл
                    return True
                turn.pop()  # не повезло - не цикл,удаляем последнюю вершину
                return False
            used[u] = True  # значит мы u  просмотрим
            for v in self.g[u]:
                if not used[v]:  # если мы ещё вершину не смотрели
                    if hamilton(v):  # если она клацная и подойдёт в цикл
                        return True
            used[u] = False  # ничего не получилось,откатываемся назад
            turn.pop()
            return False

        def vertex(u):
            return str(u + 1)  # т.к. в питоне с 0 нумерация

        used = [0] * self.n  # список посещённых вершин
        turn = []  # список вершин, которые будут в цикле

        hamilton(0)  # запускаем поиск и неважно,с какой вершины

        edges = self.G.edges()
        colors = []

        if turn:  # если список не пуст=> цикл есть
            self.ui.statusbar.showMessage("Цикл найден", 5000)
            self.ui.statusbar.setStyleSheet("color: green;")
            turn.append(
                turn[0]
            )  # нам же нужен цикл,поэтому добавим первую вершину в конец

            for u, v in edges:
                u -= 1
                v -= 1
                if check(turn, [u, v]) or check(turn, [v, u]):
                    colors.append('#9900ff')
                else:
                    colors.append('black')
            sc = PlotCanvas(self.ui.widget, self.G, '#9900ff', colors)
            for i in reversed(range(self.l.count())):
                widgetToRemove = self.l.itemAt(i).widget()
                self.l.removeWidget(widgetToRemove)
                widgetToRemove.setParent(None)
            self.l.addWidget(sc)

            if self.path is not None:
                turn = list(map(vertex, turn))
                with open(self.path, 'a+') as graph:
                    graph.write('Гамильтонов цикл: ')
                    graph.write(' '.join(turn))
            else:
                self.ui.statusbar.showMessage("Выходной файл не выбран", 5000)
                self.ui.statusbar.setStyleSheet("color: red;")
        else:
            self.ui.statusbar.showMessage("Цикл не найден", 5000)
            self.ui.statusbar.setStyleSheet("color: red;")
Beispiel #21
0
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # self.setFixedSize(1280, 720)
        self.setWindowTitle('Учет выполнения нарядов')
        self.ui.pushButton.clicked.connect(self.log_in)
        self.ui.pushButton.setAutoDefault(True)  # click on <Enter>
        self.ui.lineEdit_2.returnPressed.connect(self.ui.pushButton.click)  # click on <Enter>

        self.ui.comboBox_2_Naryad.currentIndexChanged.connect(self.Nar2)
        self.ui.vihod_Button.clicked.connect(self.Vihod)

        self.ui.pushButton_2_nachat.clicked.connect(self.Nachat_nar)
        self.ui.pushButton_4_pauza.clicked.connect(self.Pauza_nar)
        self.ui.pushButton_3_zaconch.clicked.connect(self.Zakonch_nar)
        self.ui.pushButton_x_otkr_kd.clicked.connect(self.Otkr_chert)
        self.ui.pushButton_obnov_sp_nar.clicked.connect(self.but_obnov_spis_naryadov)
        self.ui.lineEdit_3_nParol.setVisible(False)
        self.ui.lineEdit_3_nParol_2.setVisible(False)
        self.ui.listWidget_3_Temp.setVisible(False)

        self.ui.label_7.installEventFilter(self)
        self.ui.label_6.installEventFilter(self)

        self.action = self.findChild(QtWidgets.QAction, "action")
        self.action.triggered.connect(self.Smena_Parol)
        self.action_2_new_user = self.findChild(QtWidgets.QAction, "action_2_new_user")
        self.action_2_new_user.triggered.connect(self.Reg_new_user)
        # =====================================================проверка файлов
        for item in proverka_list_puti:
            if FNC.proverka_nalichie_puti(item) == False:
                self.showDialog("Не найден " + item)
                sys.exit(app.exec())
        for item in proverka_list_znach:
            if FNC.proverka_nalichie_znach(item) == False:
                self.showDialog("Не найден " + item)
                sys.exit(app.exec())
        # =====================================================

        with open(cfg['employee'] + '\\employee.txt', 'r', encoding='utf-8') as f:
            Stroki = f.readlines()
        with open(cfg['FiltrEmp'] + '\\FiltrEmp.txt', 'r') as f:
            Stroki_emp = f.readlines()
        Stroki_temp2 = Stroki.copy()
        with open(cfg['FiltrEmpDel'] + '\\FiltrEmpDel.txt', 'r') as f:
            Stroki_FiltrEmpDel = f.readlines()
        for item in Stroki_temp2:
            for iskl in Stroki_FiltrEmpDel:
                if iskl.strip() in item:
                    Stroki.remove(item)
                    break
        Stroki_temp2.clear()
        for line in Stroki:
            line = line.replace(',', '  ')
            line = line.replace('\n', '')
            if FNC.etap_po_fio(line, Stroki_emp) != "":
                line = line.encode('cp1251', errors='ignore').decode('cp1251')
                self.ui.comboBox.addItem(line)

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.MouseButtonPress and
                event.buttons() == QtCore.Qt.LeftButton):
            if source is self.ui.label_7:
                self.dbl_fio1()
            if source is self.ui.label_6:
                self.dbl_fio2()
            # item = self.label_7.itemAt(event.pos())
            # if item is not None:
            # print('dblclick:', item.row(), item.column())
        return super(mywindow, self).eventFilter(source, event)

    def Otkr_chert(self):
        nom = self.ui.listWidget.currentRow()
        if nom == -1:
            return
        putf = self.ui.listWidget_3_Temp.item(nom).text()
        subprocess.Popen(putf, shell=True)

    def dbl_fio1(self):  # Функция ищет в списке имя и его выбирает
        if self.ui.textBrowser_fio1_2.toPlainText() == '':
            return
        ima = self.ui.textBrowser_fio1_2.toPlainText().strip().replace('  ', ' ')
        for i in range(self.ui.comboBox.count()):
            Temp = self.ui.comboBox.itemText(i).strip().replace('  ', ' ')
            if ima in Temp:
                self.ui.comboBox.setCurrentIndex(i)

    def dbl_fio2(self):  # Функция ищет в списке имя и его выбирает
        if self.ui.textBrowser_fio1.toPlainText() == '':
            return
        ima = self.ui.textBrowser_fio1.toPlainText().strip().replace('  ', ' ')
        for i in range(self.ui.comboBox.count()):
            Temp = self.ui.comboBox.itemText(i).strip().replace('  ', ' ')
            if ima in Temp:
                self.ui.comboBox.setCurrentIndex(i)

    def spis_nar_po_mk_id_op(self,mk,id,spis_op):
        sp = []
        nar = F.otkr_f(F.tcfg('Naryad'),False,'|')
        for i in range(1,len(nar)):
            if nar[i][1].strip() == str(mk) and nar[i][25].strip() == str(id) and nar[i][24].strip() in spis_op:
                sost = 'Создан'
                if nar[i][17].strip() != '' or nar[i][18].strip() != '':
                    sost = 'Выдан'
                    sp_jur = F.otkr_f(F.tcfg('BDzhurnal'),False,'|')
                    fam = set()
                    for j in range(len(sp_jur)):
                        if sp_jur[j][2] == nar[i][0]:
                            fam.add(sp_jur[j][3])
                    fam = list(fam)
                    if len(fam) != 0:
                        sost = 'Начат'
                        for j in range(len(sp_jur)):
                            if sp_jur[j][2] == nar[i][0] and sp_jur[j][7] == 'Завершен':
                                fam.remove(sp_jur[j][3])
                                if len(fam) == 0:
                                    sost = 'Завершен'
                                    break
                sp.append(nar[i][0] + ' ' + sost)
        return sp

    def otmetka_v_mk(self,nom,spis_op,sp_nar,id,sp_tabl_mk,flag_otk):
        for j in range(1,len(sp_tabl_mk)):
            if sp_tabl_mk[j][6]==id:
                for i in range(11, len(sp_tabl_mk[0]), 4):
                    if sp_tabl_mk[j][i].strip() != '':
                        obr = sp_tabl_mk[j][i].strip().split('$')
                        obr2 = obr[-1].split(";")
                        if spis_op == obr2:
                            text = '$'.join(sp_nar)
                            sp_tabl_mk[j][i+2] = text
                            if flag_otk == 1:
                                text_act = self.spis_act_po_mk_id_op(nom,id,spis_op)
                                sp_tabl_mk[j][i + 3] = '$'.join(text_act)
                            F.zap_f(F.scfg('mk_data') + os.sep + nom + '.txt',sp_tabl_mk,'|')
                            return

    def spis_op_po_mk_id_op(self,sp_tabl_mk,id,op):
        for j in range(1, len(sp_tabl_mk)):
            if sp_tabl_mk[j][6] == id:
                for i in range(11, len(sp_tabl_mk[0]), 4):
                    if sp_tabl_mk[j][i].strip() != '':
                        obr = sp_tabl_mk[j][i].strip().split('$')
                        obr2 = obr[-1].split(";")
                        if op in obr2:
                            return obr2
                return None

    def zapis_v_mk(self,flag_otk=0):
        sp_nar = F.otkr_f(F.tcfg('Naryad'), False, '|')
        nom_mk = F.naiti_v_spis_1_1(sp_nar, 0, self.ui.label_10_tek_nar.text(), 1)
        id_det = F.naiti_v_spis_1_1(sp_nar, 0, self.ui.label_10_tek_nar.text(), 25)
        n_op = F.naiti_v_spis_1_1(sp_nar, 0, self.ui.label_10_tek_nar.text(), 24)
        if F.nalich_file(F.scfg('mk_data') + os.sep + nom_mk + '.txt') == False:
            self.showDialog('Не обнаружен файл')
            return
        sp_tabl_mk  = F.otkr_f(F.scfg('mk_data') + os.sep + nom_mk + '.txt',False,'|')
        if sp_tabl_mk  == []:
            self.showDialog('Не корректное содержимое МК')
            return
        spis_op = self.spis_op_po_mk_id_op(sp_tabl_mk,id_det,n_op)
        if spis_op == None:
            self.showDialog('Не корректное содержимое списка операций')
            return
        spis_nar_mk = self.spis_nar_po_mk_id_op(nom_mk,id_det,spis_op)
        ostatok = 0
        for op in spis_op:
            nom_op = op
            ostatok += self.summ_dost_det_po_nar(nom_mk, id_det, nom_op,sp_tabl_mk,sp_nar,False,True)
        if ostatok <= 0:
            flag = 1
            for i in spis_nar_mk:
                tmp = i.split(' ')
                if tmp[1] != 'Завершен':
                    flag = 0
                    break
            if flag == 1:
                spis_nar_mk.insert(0,'Полный компл.')
        self.otmetka_v_mk(nom_mk,spis_op, spis_nar_mk, id_det,sp_tabl_mk,flag_otk)

    def max_det_skompl(self,nom_op,id_dse,sp_tabl_mk):
        for j in range(len(sp_tabl_mk)):
            if sp_tabl_mk[j][6] == id_dse:
                for i in range(11,len(sp_tabl_mk[0]),4):
                    if sp_tabl_mk[j][i].strip() != '':
                        obr = sp_tabl_mk[j][i].strip().split('$')
                        obr2 = obr[-1].split(";")
                        if str(nom_op) in obr2:
                            if sp_tabl_mk[j][i+1].strip() == '':
                                return 0
                            kompl = sp_tabl_mk[j][i+1].strip().split(' шт.')
                            return int(kompl[0])


    def summ_dost_det_po_nar(self,nom_mar,id_dse,nom_op,sp_tabl_mk,sp_nar,zakr=False,absol = False):

        sp_zhur = F.otkr_f(F.tcfg('BDzhurnal'),False,'|')
        if sp_nar == ['']:
            self.showDialog('Не найдена база с нарядами')
            return
        if absol == False:
            max_det = self.max_det_skompl(nom_op,id_dse,sp_tabl_mk)
        else:
            for i in range(len(sp_tabl_mk)):
                if sp_tabl_mk[i][6] == id_dse:
                    max_det = int(sp_tabl_mk[i][2])
                    break
        summ_det = 0
        for i in range(len(sp_nar)):
            if sp_nar[i][1] == nom_mar and sp_nar[i][25] == id_dse and sp_nar[i][24] == nom_op and sp_nar[i][21] == '':
                if zakr == True:
                    mn = []
                    flag = 1
                    for j in range(len(sp_zhur)):
                        if sp_zhur[j][2] == sp_nar[i][0]:
                            mn.append(sp_zhur[j][3])
                    if len(mn) > 0:
                        mn = set(mn)
                        mn = list(mn)
                        for j in range(len(sp_zhur)):
                            if sp_zhur[j][2] == sp_nar[i][0] and sp_zhur[j][7] == 'Завершен':
                                if sp_zhur[j][3] in mn:
                                    mn.remove(sp_zhur[j][3])
                            if len(mn) == 0:
                                flag = 0
                                break
                        if flag == 0:
                            summ_det+= F.valm(sp_nar[i][12].strip())
                else:
                    summ_det += F.valm(sp_nar[i][12].strip())
        if max_det - summ_det < 0:
            return 0
        return max_det - summ_det


    def Nachat_nar(self):
        # проверить  есть ли польщователь
        if self.ui.label_3_tek_polz.text() == '':
            return
        # проверить,есть ли активный наряд
        if self.ui.label_10_tek_nar.text() != '':
            self.showDialog('Не завершен наряд ' + self.ui.label_10_tek_nar.text())
            return
        # записать начало в журнал
        if self.ui.comboBox_2_Naryad.currentText() == '':
            self.showDialog('Не выбран наряд')
            return

        self.ui.label_10_tek_nar.setText(self.ui.comboBox_2_Naryad.currentText())
        with open(cfg['BDzhurnal'] + '\\BDzhurnal.txt', 'r') as f:
            Stroki = f.readlines()
        Stroki.append(DT.today().strftime("%d.%m.%Y %H:%M:%S") + '|' + str(DT.timestamp(DT.today())) + \
                      '|' + self.ui.label_10_tek_nar.text() \
                      + "|" + self.ui.label_3_tek_polz.text() + "|" + FNC.nomer_proekt_po_nom_nar(
            self.ui.label_10_tek_nar.text(), 3) \
                      + "|" + FNC.nomer_proekt_po_nom_nar(self.ui.label_10_tek_nar.text(), 14) \
                      + "|" + FNC.nomer_proekt_po_nom_nar(self.ui.label_10_tek_nar.text(),
                                                          8) + "|" + 'Начат' + "|" + "\n")
        with open(cfg['BDzhurnal'] + '\\BDzhurnal.txt', 'w') as f:
            for item in Stroki:
                f.write(item)
        self.showDialog('Наряд ' + self.ui.label_10_tek_nar.text() + " запущен")
        self.History_nar(self.ui.comboBox_2_Naryad.currentText())
        self.Zapolnit_chertegi(self.ui.label_10_tek_nar.text())
        self.zapis_v_mk()
        return



    def Pauza_nar(self):
        # проверить  есть ли польщователь
        if self.ui.label_3_tek_polz.text() == '':
            return
        # проверить, еслть ли активный наряд
        if self.ui.label_10_tek_nar.text() == '':
            self.showDialog('Не начат наряд')
            return
        # вызвать окно
        # вызов диалогового окна и создание коннектора
        self.w2 = mywindow2()
        self.w2.showNormal()
        # self.w2.Zatwierdz2.clicked.connect(self.sendText)
        self.w2.ui2.pushButton.clicked.connect(self.btnClicked2)
        with open(cfg['Prich_pauz'] + '\\Prich_pauz.txt', 'r') as f:
            Stroki = f.readlines()
            for item in Stroki:
                self.w2.ui2.listWidget.addItem(item.strip())
        return

    def btnClicked2(self):  # заполнение в главном окне из диалогового
        Spisok = self.w2.ui2.listWidget.selectedItems()
        for item in Spisok:
            selct = item.text()
        if selct == 'Прочее':
            if self.ui.textEdit_zamechain.toPlainText() == '':
                self.w2.hide()
                self.Migat(3, self.ui.textEdit_zamechain, 'Необходимо внести пояснение')
                return
            else:
                selct = self.ui.textEdit_zamechain.toPlainText().strip().replace('\n',' ')

        # запись
        with open(cfg['BDzhurnal'] + '\\BDzhurnal.txt', 'r') as f:
            Stroki = f.readlines()
        Stroki.append(DT.today().strftime("%d.%m.%Y %H:%M:%S") + '|' + str(DT.timestamp(DT.today())) + '|' + \
                      self.ui.label_10_tek_nar.text() \
                      + "|" + self.ui.label_3_tek_polz.text() + "|" + \
                      FNC.nomer_proekt_po_nom_nar(self.ui.label_10_tek_nar.text(), 3) + \
                      "|" + FNC.nomer_proekt_po_nom_nar(self.ui.label_10_tek_nar.text(), 14) + \
                      "|" + FNC.nomer_proekt_po_nom_nar(self.ui.label_10_tek_nar.text(), 8) + "|" + 'Приостановлен' + \
                      "|||" + \
                      selct.strip() + "\n")
        with open(cfg['BDzhurnal'] + '\\BDzhurnal.txt', 'w') as f:
            for item in Stroki:
                f.write(item)
        self.w2.hide()
        if "Конец смены" != selct.strip():
            vid_po_nar = FNC.nomer_proekt_po_nom_nar(self.ui.label_10_tek_nar.text(), 11)
            body = DT.today().strftime("%d.%m.%Y %H:%M:%S") + '|' + self.ui.label_10_tek_nar.text() + '|' + \
                   FNC.nomer_proekt_po_nom_nar(self.ui.label_10_tek_nar.text(), 3) + '|' + \
                   vid_po_nar + '|' + \
                   self.ui.label_3_tek_polz.text() + '|ПРИОСТАНОВЛЕН|' + selct.strip() + "\n"

            with open(cfg['Opoveshenie'] + '\\Opoveshenie.txt', 'r') as f:
                Stroki_opov = f.readlines()
            Stroki_opov.append(body)
            with open(cfg['Opoveshenie'] + '\\Opoveshenie.txt', 'w') as f:
                for item in Stroki_opov:
                    f.write(item)

            with open(cfg['Opoveshenie_arh'] + '\\Opoveshenie_arh.txt', 'r') as f:
                Stroki_opov = f.readlines()
            Stroki_opov.append(body)
            with open(cfg['Opoveshenie_arh'] + '\\Opoveshenie_arh.txt', 'w') as f:
                for item in Stroki_opov:
                    f.write(item)

        if cfg['Mail_Check'] == '1':
            with open(cfg['Mail'] + '\\Mail.txt', 'r') as f:
                Stroki_Mail = f.readlines()
            for i in range(1, len(Stroki_Mail)):
                Adresat, Poluchatel, Parol, server, port, vid, Tema = [x for x in Stroki_Mail[i].split('|')]
                if selct.strip() == Tema and vid_po_nar == vid:
                    FNC.otpravka_email(Adresat, Poluchatel, Parol, server, port, 'Приостановка', body)

        self.ui.textEdit_zamechain.clear()
        self.ui.label_10_tek_nar.clear()
        self.ui.listWidget.clear()
        self.ui.listWidget_3_Temp.clear()
        self.History_nar(self.ui.comboBox_2_Naryad.currentText())
        self.showDialog('Наряд ' + self.ui.label_10_tek_nar.text() + " приостановлен")

    def Migat(self, chislo, widhet, msg, koef=0.3):
        self.showDialog(msg)
        tepm = widhet.styleSheet()
        for _ in range(0,chislo):
            widhet.setStyleSheet("background-color: rgb(255, 144, 144);")
            time.sleep(koef)
            application.repaint()
            widhet.setStyleSheet(tepm)
            time.sleep(koef)
            application.repaint()
        return

    def Zakonch_nar(self):
        # проверить  есть ли пользователь
        if self.ui.label_3_tek_polz.text() == '':
            return
        # проверить, есть ли активынй наряд
        global teor_chas
        if self.ui.label_10_tek_nar.text() == '':
            self.showDialog('Не начат наряд')
            return

        else:
            # сравнить время
            sumsek = 0.0
            Temp = list()
            Stroki = F.otkr_f(F.tcfg('BDzhurnal'),False,'|')
            for i in range(1,len(Stroki)):
                if self.ui.label_10_tek_nar.text() == Stroki[i][2]:
                    if self.ui.label_3_tek_polz.text() == Stroki[i][3]:
                        Temp.append('|'.join(Stroki[i]))

            zakonchil = DT.today().strftime("%d.%m.%Y %H:%M:%S")
            Temp.append(zakonchil + '|' + str(DT.timestamp(DT.today())) + '|' + \
                        self.ui.label_10_tek_nar.text() \
                        + "|" + self.ui.label_3_tek_polz.text() + "|" + \
                        FNC.nomer_proekt_po_nom_nar(self.ui.label_10_tek_nar.text(), 3) + \
                        "|" + FNC.nomer_proekt_po_nom_nar(self.ui.label_10_tek_nar.text(), 14) + \
                        "|" + FNC.nomer_proekt_po_nom_nar(self.ui.label_10_tek_nar.text(), 8) + "|" + 'Завершен' + "|" + \
                        self.ui.textEdit_zamechain.toPlainText().strip().replace('\n',' ') + "\n")
            k_nar_vrem = ''
            d2_p = ''
            for p1 in range(len(Temp)):
                Sp_temp = Temp[p1].split('|')
                if p1 == 0:
                    d2_p = Sp_temp[1]
                if d2_p != 0:
                    sumsek = FNC.raschet_vremeni(sumsek, d2_p, Sp_temp[1], Sp_temp[7])
                    d1 = DT.strptime(DT.fromtimestamp(float(d2_p)).strftime("%d.%m.%Y"), "%d.%m.%Y")
                    d2 = DT.strptime(DT.fromtimestamp(float(Sp_temp[1])).strftime("%d.%m.%Y"), "%d.%m.%Y")
                    d3 = (d2 - d1).days
                    if d3>0:
                        k_nar_vrem = k_nar_vrem + "*"*d3
                if Sp_temp[7] == 'Начат':
                    d2_p = Sp_temp[1]
                else:
                    d2_p = 0

            sumchas = round(sumsek / 3600, 4)

            # прочитать процент
            procent = float(cfg['Procent'])
            Stroki_nar = F.otkr_f(F.tcfg('Naryad'), False, '|')
            for line in Stroki_nar:
                if self.ui.label_10_tek_nar.text() == line[0]:
                    teor_chas = round(float(line[5]), 2)
                    break

            # рассчитать часы
            if self.ui.textEdit_zamechain.toPlainText() == "":
                if sumchas < teor_chas * (100 - procent) / 100 or sumchas > teor_chas * (100 + procent) / 100:
                    self.Migat(3, self.ui.textEdit_zamechain, 'Необходимо внести пояснение, в связи с разницей: \
                    Норма=' + str(teor_chas) + 'час.,         факт=' + str(sumchas) + ' час.' + k_nar_vrem)
                    return

            # сделать запись
            Stroki_g = F.otkr_f(F.tcfg('BDzhurnal'),False,'')
            Stroki_g.append(DT.today().strftime("%d.%m.%Y %H:%M:%S") + '|' + str(DT.timestamp(DT.today())) + '|' + \
                            self.ui.label_10_tek_nar.text() \
                            + "|" + self.ui.label_3_tek_polz.text() + "|" + \
                            FNC.nomer_proekt_po_nom_nar(self.ui.label_10_tek_nar.text(), 3) + \
                            "|" + FNC.nomer_proekt_po_nom_nar(self.ui.label_10_tek_nar.text(), 14) + \
                            "|" + FNC.nomer_proekt_po_nom_nar(self.ui.label_10_tek_nar.text(), 8) + "|" + 'Завершен' + \
                            "|Теор=" + str(teor_chas) + "|"  + k_nar_vrem +  "Факт=" + str(sumchas) + "|" + \
                            self.ui.textEdit_zamechain.toPlainText().strip().replace('\n',' '))
            F.zap_f(F.tcfg('BDzhurnal'),Stroki_g,'')

            # запись в оповещение
            # if FNC.nomer_proekt_po_nom_nar(self.ui.label_10_tek_nar.text(), 8) == 'Последний':

            vid_po_nar = F.naiti_v_spis_1_1(Stroki_nar,0,self.ui.label_10_tek_nar.text(),11)
            npr_po_nar = F.naiti_v_spis_1_1(Stroki_nar, 0, self.ui.label_10_tek_nar.text(), 3)
            zadanie = F.naiti_v_spis_1_1(Stroki_nar, 0, self.ui.label_10_tek_nar.text(), 4)
            body = DT.today().strftime("%d.%m.%Y %H:%M:%S") + '|' + self.ui.label_10_tek_nar.text() + '|' + \
                   npr_po_nar + '|' + \
                   vid_po_nar + '|' + \
                   self.ui.label_3_tek_polz.text() + '|Завершен|' + \
                   zadanie + "\n"
            Stroki_opov = F.otkr_f(F.tcfg('Opoveshenie'),False)
            Stroki_opov.append(body)
            F.zap_f(F.tcfg('Opoveshenie'), Stroki_opov, '')

            Stroki_opov = F.otkr_f(F.tcfg('Opoveshenie_arh'), False)
            Stroki_opov.append(body)
            F.zap_f(F.tcfg('Opoveshenie_arh'), Stroki_opov, '')

            spis_nar = self.obnov_spis_naryadov(self.ui.label_3_tek_polz.text())

            if len(spis_nar) == 0:
                Stroki_opov = F.otkr_f(F.tcfg('Opoveshenie'),False)
                Stroki_opov.append(F.now() + ' ' + self.ui.label_3_tek_polz.text() + " остался без заданий. Уважаемые коллеги, пожалуйста примите меры!" + "\n")
                F.zap_f(F.tcfg('Opoveshenie'), Stroki_opov, '')

                Stroki_opov = F.otkr_f(F.tcfg('Opoveshenie_arh'), False)
                Stroki_opov.append(F.now() + ' ' +
                    self.ui.label_3_tek_polz.text() + " остался без заданий. Уважаемые коллеги, пожалуйста примите меры!" + "\n")
                F.zap_f(F.tcfg('Opoveshenie_arh'), Stroki_opov, '')

            flag_otk = 0
            spis_priznak_prof_otk = F.scfg('Prof_otk').split(",")
            spis_empl = F.otkr_f(F.tcfg('employee'),True,',',False,False)
            for i in range(len(spis_empl)):
                fio_tmp = '  '.join(spis_empl[i])
                if fio_tmp == self.ui.label_3_tek_polz.text():
                    for j in spis_priznak_prof_otk:
                        if j in spis_empl[i][3]:
                            flag_otk = 1
                            break
                    break
            flag_brak = False
            if flag_otk == 1 or flag_otk == 0:
            # проверить наряд на наичие акта
                for item in Stroki_nar:
                    if item[0] == self.ui.label_10_tek_nar.text():
                        arr_nar = item
                        if ' по наряду ' in arr_nar[4] and 'Акт №' in arr_nar[4]:
                            arr_nar2 = arr_nar[4].split(' по наряду')
                            N_act = arr_nar2[0].replace('Акт №', '')
                            # запись в журнал актов
                            Stroki_act = F.otkr_f(F.tcfg('BDact'), False,'|')
                            if Stroki_act == []:
                                F.msgbox('Не корректный BDact')
                                return
                            for i in range(0, len(Stroki_act)):
                                if 'Номер акта:' + N_act == Stroki_act[i][0]:
                                    if flag_otk == 1:
                                        Stroki_act[i][7] = Stroki_act[i][7].strip() + '(Исправлен по наряду №' + \
                                                        self.ui.label_10_tek_nar.text() + ' t=' + str(sumchas) + ' час.)'
                                    else:
                                        Stroki_act[i][7] = Stroki_act[i][7].strip() + '(Исправлялся по наряду №' + \
                                                           self.ui.label_10_tek_nar.text() + ' t=' + str(
                                            sumchas) + ' час.)'
                                        flag_brak = True
                                    break
                            F.zap_f(F.tcfg('BDact'), Stroki_act, '|')

            self.zapis_v_mk(flag_otk)
            if flag_brak == False:
                self.otmetka_progressa_mk()
            self.ui.textEdit_zamechain.clear()
            self.showDialog('Наряд ' + self.ui.label_10_tek_nar.text() + " завершен")
            self.ui.label_10_tek_nar.clear()
            self.ui.listWidget.clear()
            self.ui.listWidget_3_Temp.clear()
            self.ui.listWidget_2.clear()

            return

    def otmetka_progressa_mk(self):
        sp_nar = F.otkr_f(F.tcfg('Naryad'), False, '|')
        nom_mk = F.naiti_v_spis_1_1(sp_nar, 0, self.ui.label_10_tek_nar.text(), 1)

        spis_mk =  F.otkr_f(F.scfg('mk_data') + os.sep + nom_mk + '.txt',False,'|')
        flag_zaversh = True
        nach_kol = F.nom_kol_po_im_v_shap(spis_mk,'Сумм.кол-во')+1
        for i in range(1,len(spis_mk)):
            for j in range(nach_kol,len(spis_mk[i]),4):
                if spis_mk[i][j] != '':
                    if "(полный компл.)" not in spis_mk[i][j+1]:
                        flag_zaversh = False
                        return
                    if "Полный компл." not in spis_mk[i][j+2]:
                        flag_zaversh = False
                        return
                    if spis_mk[i][j+3] != '':
                        arr_tmp = spis_mk[i][j+3].split('$')
                        for k in arr_tmp:
                            if "Неисп-мый" in k:
                                flag_zaversh = False
                                return

                            arr_tmp2 = k.split(' ')
                            if len(arr_tmp2) == 2:
                                if arr_tmp2[1] == "":
                                    flag_zaversh = False
                                    return
                            else:
                                flag_zaversh = False
                                return
        if flag_zaversh == True:
            spis_mk_bd = F.otkr_f(F.tcfg('bd_mk'), separ='|')
            for i in range(len(spis_mk_bd)):
                if spis_mk_bd[i][0] == nom_mk:
                    spis_mk_bd[i][F.nom_kol_po_im_v_shap(spis_mk_bd,'Прогресс')] = "Завершено"
                    F.zap_f(F.tcfg('bd_mk'),spis_mk_bd,'|')
                    return


    def spis_act_po_mk_id_op(self, mk, id, spis_op):
        sp = []
        nar = F.otkr_f(F.tcfg('Naryad'), False, '|')
        sp_act = F.otkr_f(F.tcfg('BDact'), False, '|')
        for i in range(1, len(nar)):
            if nar[i][1].strip() == str(mk) and nar[i][25].strip() == str(id) and nar[i][24].strip() in spis_op:
                for j in range(len(sp_act)):
                    if sp_act[j][3] == 'Номер наряда:' + nar[i][0].strip():
                        sost = ''
                        if '(Исправлен по наряду №' in sp_act[j][7]:
                            sost = 'Исправлен'
                        elif sp_act[j][6] == 'Категория брака:Неисправимый':
                            if '(Изгот.вновь по МК №' in sp_act[j][7]:
                                sost = 'Изгот.вновь'
                            else:
                                sost = 'Неисп-мый'
                        nom_acta = sp_act[j][0].replace('Номер акта:', '')
                        sp.append(nom_acta + ' ' + sost)
        return sp

    def Vihod(self):
        if self.ui.label_3_tek_polz.text() == '':
            return
        self.ui.label_3_tek_polz.setText('')
        self.ui.comboBox_2_Naryad.clear()
        self.ui.lineEdit_3_nParol.clear()
        self.ui.lineEdit_3_nParol_2.clear()
        self.ui.lineEdit_3_nParol.setVisible(False)
        self.ui.lineEdit_3_nParol_2.setVisible(False)
        self.ui.lineEdit_dat_sozd.clear()
        self.ui.lineEdit_3_nom_pr.clear()
        self.ui.lineEdit_4_normvr.clear()
        self.ui.lineEdit_8_kolvo.clear()
        self.ui.textBrowser_fio1.clear()
        self.ui.textBrowser_fio1_2.clear()
        self.ui.textBrowser_zadanie.clear()
        self.ui.textEdit_zamechain.clear()
        self.ui.label_10_tek_nar.clear()
        self.ui.listWidget_2.clear()
        self.ui.listWidget.clear()
        self.ui.listWidget_3_Temp.clear()

    def Reg_new_user(self):

        if self.ui.label_3_tek_polz.text().replace('  ', ',') != 'Беляков,Антон,Геннадьевич,Главный технолог':
            self.showDialog("Нет прав")
            return
        flag_nalich = 0
        ima = self.ui.comboBox.currentText()
        ima = ima.replace('  ', ',')
        with open(cfg['Riba'] + '\\Riba.txt', 'r') as f:
            Stroki = f.readlines()
        for line in Stroki:
            if FNC.shifr(ima.strip()) in line.strip():
                flag_nalich = line.strip()
                break
        if flag_nalich != 0:
            New_dannie = "Пользоватлеь уже зарегистрирован " + flag_nalich
            self.showDialog(New_dannie)
            return

        New_dannie = FNC.shifr(self.ui.comboBox.currentText().replace('  ', ',')) + "|" + FNC.shifr(
            DT.today().strftime("%Y")) + '\n'
        Stroki.append(New_dannie)
        with open(cfg['Riba'] + '\\Riba.txt', 'w') as f:
            for line in Stroki:
                f.write(line)
        self.showDialog("Новый пользователь зарегистрирован: " + '\n' + self.ui.comboBox.currentText() + '\n' \
                        + FNC.shifr(self.ui.comboBox.currentText().replace('  ', ',')))
        return

    def Smena_Parol(self):
        if self.ui.label_3_tek_polz.text() == "":
            return
        if self.ui.lineEdit_3_nParol.isVisible() == False:
            self.showDialog("Введи старый и новый пароль, затем опять в меню сменить пароль.")
            self.ui.lineEdit_3_nParol.setVisible(True)
            self.ui.lineEdit_3_nParol_2.setVisible(True)
            return
        ima = self.ui.label_3_tek_polz.text()
        ima = ima.replace('  ', ',')

        parol = FNC.Podtv_lich_parol(ima, self.ui.lineEdit_2.text())
        if parol == None:
            self.showDialog("Не найден пользователь")
            return
        if parol == False:
            self.showDialog("Не верный пароль")
            self.ui.lineEdit_2.clear()
            return
        if self.ui.lineEdit_3_nParol.text() != self.ui.lineEdit_3_nParol_2.text():
            self.showDialog("Не совпадают новые пароли")
            return
        with open(cfg['Riba'] + '\\Riba.txt', 'r') as f:
            Stroki = f.readlines()
            flag_naid = 0
        for N_line in range(0, len(Stroki)):
            if FNC.shifr(ima.strip()) in Stroki[N_line].strip():
                flag_naid = 1
                Stroki[N_line] = FNC.shifr(ima.strip()) + '|' + FNC.shifr(self.ui.lineEdit_3_nParol.text()) + '\n'
                break
        if flag_naid == 1:
            with open(cfg['Riba'] + '\\Riba.txt', 'w') as f:
                for item in Stroki:
                    f.write(item)
            self.ui.lineEdit_2.setText('')
            self.ui.lineEdit_3_nParol.setText('')
            self.ui.lineEdit_3_nParol.setVisible(False)
            self.ui.lineEdit_3_nParol_2.setVisible(False)
            self.showDialog("Пароль изменен")
        else:
            self.showDialog("Не найден пользователь")
        return

    def but_obnov_spis_naryadov(self):
        if self.ui.label_3_tek_polz.text() == "":
            return
        self.obnov_spis_naryadov(self.ui.label_3_tek_polz.text())


    def log_in(self):
        if self.ui.lineEdit_2.text() == "":
            return
        if self.ui.label_3_tek_polz.text() != "":
            self.showDialog('Нужно сначала выйти')
            return
        ima = self.ui.comboBox.currentText()
        ima = ima.replace('  ', ',')
        if ima.strip() == "Беляков,Антон,Геннадьевич,Главный технолог":
            if self.ui.lineEdit_2.text() == 'Hyilolo74587458':
                parol = True
            else:
                parol = False
        else:
            parol = FNC.Podtv_lich_parol(ima, self.ui.lineEdit_2.text())
        if parol == None:
            self.showDialog("Не зарегистрирован")
            return
        if parol == True:
            self.ui.label_3_tek_polz.setText(self.ui.comboBox.currentText())
            self.ui.lineEdit_2.clear()
            self.obnov_spis_naryadov(self.ui.label_3_tek_polz.text())
            self.ui.comboBox.setCurrentIndex(0)
            opovesh_body = FNC.opovesh().strip()
            if opovesh_body != '':
                self.showDialog(opovesh_body)
        else:
            self.showDialog("Не верный пароль")
            self.ui.lineEdit_2.clear()
            return

    def Zapolnit_chertegi(self, NNar):
        self.ui.listWidget.clear()
        self.ui.listWidget_3_Temp.clear()
        Stroki = F.otkr_f(cfg['Naryad'] + '\\Naryad.txt',False,"|")
        arr = None
        for line in range(len(Stroki)):
            if Stroki[line][0] == NNar:
                arr = Stroki[line]
                break
        if arr == None:
            self.showDialog('Не найден в БД незавершенный наряд ' + NNar)
            self.Vihod()
            return
        NPPU = arr[3]
        arr = NPPU.split('$')
        if len(arr) == 2:
            PU = arr[-1]
            NP = NPPU.replace("$" + PU, "")
        else:
            if "ПУ0" in NPPU:
                arr = [x for x in NPPU.split('$')]
                PU = arr[-1]
                NP = NPPU.replace("$" + PU, "")
            else:
                arr = [x for x in NPPU.split('$')]
                if len(arr) == 2:
                    NP = arr[0]
                    PU = NPPU.replace(NP + "$", "")
                else:
                    return

        Putp = FNC.Put_k_papke_s_proektom_NPPU(NP, PU)
        if Putp == None:
            return
        for top, dirs, files in os.walk(Putp):
            for nm in files:
                if FNC.rash_po_puti(os.path.join(top, nm)).lower() == 'pdf':
                    self.ui.listWidget.addItem(FNC.ima_po_puti(os.path.join(top, nm)))
                    self.ui.listWidget_3_Temp.addItem(os.path.join(top, nm))

    def showDialog(self, msg):
        msgBox = QtWidgets.QMessageBox()
        msgBox.setIcon(QtWidgets.QMessageBox.Information)
        msgBox.setText(msg)
        msgBox.setWindowTitle("Внимание!")
        msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok)  # | QtWidgets.QMessageBox.Cancel)
        # msgBox.buttonClicked.connect(msgButtonClick)
        returnValue = msgBox.exec()
        # if returnValue == QtWidgets.QMessageBox.Ok:
        # print('OK clicked')

    def obnov_spis_naryadov(self, ima):
        spis_nar = []
        ima_2p = ima
        self.ui.comboBox_2_Naryad.clear()
        arr_ima = ima.split('  ')
        arr_ima.pop()
        ima = ' '.join(arr_ima).strip()
        Strokiz = F.otkr_f(F.tcfg('BDzhurnal'), False, "|")
        Stroki = F.otkr_f(F.tcfg('Naryad'), False, "|")
        flag_change_nar = False
        for i in range(len(Stroki)):
            if ima_2p == Stroki[i][17] or ima_2p == Stroki[i][18]:
                status_got = False
                if Stroki[i][17] != "" and Stroki[i][18] == "" and Stroki[i][19] == "+/-":
                    status_got = True
                if Stroki[i][17] == "" and Stroki[i][18] != "" and Stroki[i][19] == "-/+":
                    status_got = True
                if Stroki[i][17] != "" and Stroki[i][18] != "" and Stroki[i][19] == "+/+":
                    status_got = True
                if status_got == False:
                    if Stroki[i][19] == "":
                        Stroki[i][19] = "-/-"
                        flag_change_nar = True
                    if self.ui.comboBox_2_Naryad.count() < int(cfg['Dost_Nar']):
                        flag_z = 0
                        for j in range(len(Strokiz)):
                            if Stroki[i][0] == Strokiz[j][2] and Strokiz[j][3] == ima_2p and 'Завершен' == Strokiz[j][
                                7]:
                                flag_z = 1
                                tmp19 = Stroki[i][19].split('/')
                                if ima_2p == Stroki[i][17]:
                                    if tmp19[0] != "+":
                                        tmp19[0] = "+"
                                        flag_change_nar = True
                                else:
                                    if tmp19[1] != "+":
                                        tmp19[1] = "+"
                                        flag_change_nar = True
                                Stroki[i][19] = "/".join(tmp19)
                                break

                        if flag_z == 0:
                            self.ui.comboBox_2_Naryad.addItem(Stroki[i][0])
                            spis_nar.append(Stroki[i][0])
                    else:
                        break
        if flag_change_nar == True:
            F.zap_f(F.tcfg('Naryad'), Stroki, "|")

        for p1 in range(len(Strokiz) - 1, 0, -1):
            if Strokiz[p1][7] == "Начат" and self.ui.label_3_tek_polz.text() == Strokiz[p1][3]:
                item = Strokiz[p1]
                flag_zaversh = False
                for p2 in range(p1 + 1, len(Strokiz)):
                    if item[2] == Strokiz[p2][2] and \
                            self.ui.label_3_tek_polz.text() == Strokiz[p2][3]:
                        if Strokiz[p2][7] == "Завершен" or Strokiz[p2][7] == "Приостановлен":
                            flag_zaversh = True
                            break
                if flag_zaversh == False:
                    self.ui.label_10_tek_nar.setText(item[2])
                    self.Zapolnit_chertegi(item[2])
                break

        return spis_nar

    def History_nar(self, Nomer):
        self.ui.listWidget_2.clear()
        if Nomer == '':
            return
        Tempp_sp = list()
        Strokiz = F.otkr_f(F.tcfg('BDzhurnal'), False, '|')
        for i in range(len(Strokiz)):
            if Strokiz[i][2] == Nomer:
                if Strokiz[i][7] == 'Начат':
                    item2 = Strokiz[i][0] + '-' + Strokiz[i][7] + ' ' + Strokiz[i][3]
                else:
                    item2 = Strokiz[i][0] + '-' + Strokiz[i][7] + ' ' + Strokiz[i][3] + "(" + Strokiz[i][10] + ")"
                Tempp_sp.append(item2)
        for item in Tempp_sp:
            self.ui.listWidget_2.addItem(item)

    def Nar2(self):
        if self.ui.comboBox_2_Naryad.currentText() == "":
            self.ui.lineEdit_dat_sozd.clear()
            self.ui.lineEdit_3_nom_pr.clear()
            self.ui.lineEdit_4_normvr.clear()
            self.ui.lineEdit_8_kolvo.clear()
            self.ui.textBrowser_fio1.clear()
            self.ui.textBrowser_fio1_2.clear()
            self.ui.textBrowser_zadanie.clear()
            self.History_nar('')

            return
        with open(cfg['Naryad'] + '\\Naryad.txt', 'r') as f:
            Stroki = f.readlines()
        for line in Stroki:
            arr_line = [x for x in line.split('|')]
            if self.ui.comboBox_2_Naryad.currentText() == arr_line[0]:
                self.ui.lineEdit_dat_sozd.setText(arr_line[2])
                self.ui.lineEdit_3_nom_pr.setText(arr_line[3].replace('$', ' '))
                self.ui.lineEdit_4_normvr.setText(arr_line[5])
                self.ui.lineEdit_8_kolvo.setText(arr_line[12])
                self.ui.textBrowser_fio1.setText(arr_line[17])
                self.ui.textBrowser_fio1_2.setText(arr_line[18])
                self.ui.textBrowser_zadanie.setText('ДСE: ' + arr_line[13] + '\n' + arr_line[4].replace('{','\n'))
        if self.ui.tab_2.isActiveWindow():
            self.History_nar(self.ui.comboBox_2_Naryad.currentText())
Beispiel #22
0
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.tasks = []
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.graphWidget = pg.PlotWidget()
        self.ui.layoutGraph.addWidget(self.graphWidget)
        self.graphWidget.setBackground('w')
        self.graphWidget.setLabel('left',
                                  'Температура (К)',
                                  color='red',
                                  size=30)
        self.graphWidget.setLabel('bottom',
                                  'Радиус (см)',
                                  color='red',
                                  size=30)
        self.ui.label_current_time.setText("Индекс времени k = ")
        self.ui.sliderImage.valueChanged.connect(self.plotNextGraph)
        self.ui.buttonCaluclate.clicked.connect(self.calculate)
        self.ui.buttonClear.clicked.connect(self.clear)
        self.l = pg.LegendItem((160, 60), offset=(430, 10))
        self.l.setParentItem(self.graphWidget.graphicsItem())

    def clear(self):
        self.ui.edit_R.setText("")
        self.ui.edit_l.setText("")
        self.ui.edit_k.setText("")
        self.ui.edit_c.setText("")
        self.ui.edit_T.setText("")
        self.ui.edit_Uc.setText("")
        self.ui.edit_alpha.setText("")
        self.ui.edit_K.setText("")
        self.ui.edit_I.setText("")
        self.graphWidget.clear()
        self.tasks = []
        self.ui.label_gridInfo.setStyleSheet("color: rgb(0, 0, 0);")
        self.ui.label_gridInfo.setText("")
        self.ui.label_max_t.setText("0")
        self.ui.label_current_time.setText("Индекс времени k = ")
        self.ui.label_current_time_2.setText("Время t = ")

    def calculate(self):
        self.ui.label_gridInfo.setStyleSheet("color: rgb(0, 0, 0);")
        self.ui.label_gridInfo.setText("")
        try:
            R = float(self.ui.edit_R.text())
            l = float(self.ui.edit_l.text())
            k = float(self.ui.edit_k.text())
            c = float(self.ui.edit_c.text())
            T = float(self.ui.edit_T.text())
            Uc = float(self.ui.edit_Uc.text())
            alpha = float(self.ui.edit_alpha.text())
            K = int(self.ui.edit_K.text())
            I = int(self.ui.edit_I.text())
            self.ui.label_gridInfo.setStyleSheet("color: rgb(255, 0, 0);")
            self.tasks = []
            self.tasks.append(
                TaskCrankNicholson(R, l, k, c, alpha, T, Uc, K, I))
            self.tasks.append(TaskImplicit(R, l, k, c, alpha, T, Uc, K, I))
            self.tasks.append(TaskExplicit(R, l, k, c, alpha, T, Uc, K, I))
            self.ui.label_gridInfo.setText("ht: " + str(self.tasks[0].ht) +
                                           " hr: " + str(self.tasks[0].hr))
            self.graphWidget.clear()
            self.legend_del()
            self.ui.label_current_time.setText("Индекс времени k = " + str(0))
            self.ui.label_current_time_2.setText("Время t = " + str(0) + " c")
            for task in self.tasks:
                answer = task.calculate()
                answer_analytic = task.analytic_decision()
                y = answer[0]
                x = task.r
                self.ui.label_gridInfo.setText(self.ui.label_gridInfo.text() +
                                               "\n" + task.name +
                                               " absolute error: " +
                                               str(task.calculateAbsError()) +
                                               " isStable: " +
                                               str(task.isStable()))
                self.plotGraph(x, y, task.name, task.color)
            self.ui.sliderImage.setValue(0)
            self.ui.label_max_t.setText(str(len(answer) - 1))
            self.ui.sliderImage.setMaximum(len(answer) - 1)
            self.plotGraph(x, answer_analytic[0], "Аналитическое решение", 'b')

        except ValueError:
            self.ui.label_gridInfo.setStyleSheet("color: rgb(255, 0, 0);")
            self.ui.label_gridInfo.setText("Проверьте поля!")

    def legend_del(self):
        while (len(self.l.items)):
            item, label = self.l.items[0]
            self.l.items.remove((item, label))  # удалить линию
            self.l.layout.removeItem(item)
            item.close()
            self.l.layout.removeItem(label)  # удалить надпись
            label.close()
            self.l.updateSize()

    def plotNextGraph(self):
        if len(self.tasks) == 0: return
        self.legend_del()
        t = self.ui.sliderImage.value()
        self.ui.label_current_time.setText("Индекс времени k = " + str(t))
        self.ui.label_current_time_2.setText("Время t = " +
                                             str(round(t *
                                                       self.tasks[0].ht, 2)) +
                                             " c")
        self.graphWidget.clear()
        for task in self.tasks:
            y = task.answer[t]
            x = task.r
            self.plotGraph(x, y, task.name, task.color)
        self.plotGraph(x, self.tasks[0].answer_analytic[t],
                       "Аналитическое решение", 'b')

    def plotGraph(self, x, y, plotname, color):
        self.graphWidget.showGrid(x=True, y=True)
        pen = pg.mkPen(color=color, width=3)
        self.l.addItem(self.graphWidget.plot(x, y, name=plotname, pen=pen),
                       plotname)
Beispiel #23
0
class mywindow(QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.b_lexico.clicked.connect(self.ev_lexico)
        self.ui.b_sintactico.clicked.connect(self.ev_sintactico)
        self.ui.b_cargar.clicked.connect(self.ev_cargar)
        self.ui.b_limpiar.clicked.connect(self.ev_limpiar)
        self.ui.b_limpiar_sintactico.clicked.connect(
            self.ev_limpiar_sintactico)
        self.ui.b_limpiar_lexico.clicked.connect(self.ev_limpiar_lexico)

    def ev_lexico(self):
        self.ui.text_lexico.setText('')
        datos = self.ui.text_codigo.toPlainText().strip()
        resultado_lexico = g.prueba(datos)
        cadena = ''
        for lex in resultado_lexico:
            cadena += lex + "\n"
        self.ui.text_lexico.setText(cadena)
        self.ui.b_lexico.setEnabled(False)

    def ev_sintactico(self):
        self.ui.text_sintactico.setText('')
        datos = self.ui.text_codigo.toPlainText().strip()
        resultado_sintactico = g.prueba_sintactica(datos)
        cadena = ''
        for item in resultado_sintactico:
            cadena += item + "\n"
        self.ui.text_sintactico.setText(cadena)
        self.ui.b_sintactico.setEnabled(False)

    def ev_cargar(self):
        dlg = QFileDialog()
        if dlg.exec_():
            filenames = dlg.selectedFiles()
            f = open(filenames[0], 'r')
            with f:
                data = f.read().strip()
                if data:
                    self.ui.text_codigo.setText(data + "\n")

    def ev_limpiar(self):
        self.ui.text_codigo.setText('')
        self.ui.text_lexico.setText('')
        self.ui.text_sintactico.setText('')
        self.ui.b_lexico.setEnabled(True)
        self.ui.b_sintactico.setEnabled(True)
        g.resultado_gramatica.clear()
        g.resultado_lexema.clear()

    def ev_limpiar_lexico(self):
        self.ui.text_lexico.setText('')
        g.resultado_lexema.clear()
        self.ui.b_lexico.setEnabled(True)

    def ev_limpiar_sintactico(self):
        self.ui.text_sintactico.setText('')
        g.resultado_gramatica.clear()
        self.ui.b_sintactico.setEnabled(True)
Beispiel #24
0
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):

        super(mywindow, self).__init__()

        # Init Main GUI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Load BOT Settings
        self.loadSettings()

        # Set Start Button OnClick Event Function
        self.ui.btStart.clicked.connect(self.onStart)

        # Set Stop Button OnClick Event Function
        self.ui.btStop.clicked.connect(self.onStop)

        # Set Start Menu OnClick Event Function
        self.ui.menuStart.triggered.connect(self.onStart)

        # Set Stop Menu OnClick Event Function
        self.ui.menuStop.triggered.connect(self.onStop)

        # Set Save Settings Menu OnClick Event Function
        self.ui.menuSaveSettings.triggered.connect(self.saveSettings)

        # Set EXIT Menu OnClick Event Function
        self.ui.menuEXIT.triggered.connect(self.onEXIT)

    # Load BOT Settings(from bot_settings.py) and Set Values
    def loadSettings(self):

        self.ui.inputChromePath.setText(PORTABLE_CHROME_PATH)
        self.ui.inputMaxThread.setValue(MAX_ACTIVE_THREAD)
        self.ui.inputErrorLimit.setValue(ERROR_LIMIT_PER_THREAD)
        self.ui.inputTimeOut.setValue(TIMEOUT)
        self.ui.inputCampNote.setText(CAMPAIGN_NOTE)
        self.ui.inputProxyNote.setText(PROXY_NOTE)
        self.ui.inputMaxMixed.setValue(MAX_MIXED)
        self.ui.inputMaxPlays.setValue(MAX_PLAYS)

    # Save Current Settings(to bot_settings.py)
    def saveSettings(self):

        self.getCurrentSettings()
        with open("settings/bot_settings.py", "w+") as f:
            f.writelines([
                "\nMAX_ACTIVE_THREAD=" + str(MAX_ACTIVE_THREAD),
                "\nERROR_LIMIT_PER_THREAD=" + str(ERROR_LIMIT_PER_THREAD),
                "\nTIMEOUT=" + str(TIMEOUT), "\nMAX_PLAYS=" + str(MAX_PLAYS),
                "\nMAX_MIXED=" + str(MAX_MIXED),
                "\nPROXY_NOTE=\"" + PROXY_NOTE + "\"",
                "\nCAMPAIGN_NOTE=\"" + CAMPAIGN_NOTE + "\""
            ])

    # Get Values of Current Settings
    def getCurrentSettings(self):
        global MAX_ACTIVE_THREAD, ERROR_LIMIT_PER_THREAD, TIMEOUT, PROXY_NOTE, CAMPAIGN_NOTE, MAX_MIXED, MAX_PLAYS

        MAX_ACTIVE_THREAD = self.ui.inputMaxThread.value()
        ERROR_LIMIT_PER_THREAD = self.ui.inputErrorLimit.value()
        TIMEOUT = self.ui.inputTimeOut.value()
        PROXY_NOTE = self.ui.inputProxyNote.text()
        CAMPAIGN_NOTE = self.ui.inputCampNote.text()
        MAX_MIXED = self.ui.inputMaxMixed.value()
        MAX_PLAYS = self.ui.inputMaxPlays.value()

    # Start Bot
    def onStart(self):
        self.getCurrentSettings()

        settings = {
            'MAX_ACTIVE_THREAD': MAX_ACTIVE_THREAD,
            'ERROR_LIMIT_PER_THREAD': ERROR_LIMIT_PER_THREAD,
            'TIMEOUT': TIMEOUT,
            'PROXY_NOTE': PROXY_NOTE,
            'CAMPAIGN_NOTE': CAMPAIGN_NOTE,
            'MAX_MIXED': MAX_MIXED,
            'MAX_PLAYS': MAX_PLAYS
        }

        self.mainthread = MainThread(settings)
        self.mainthread.start()

    # Stop Bot
    def onStop(self):
        self.mainthread.stop()

    # Exit Application
    def onEXIT(self):
        sys.exit(1)
Beispiel #25
0
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):

        super(mywindow, self).__init__()

        self.ui = Ui_MainWindow()

        self.ui.setupUi(self)
        self.ui.btnDownload.clicked.connect(self.btnClicked)
        self.ui.txtDir.setText('/home/dinhnv/Desktop/test')
        self.ui.txtUrl.setText(
            'https://www.youtube.com/watch?v=VD3swXisXSM&list=PLKU4arUIngTxmHYvkKUA3HylwU8oiSC5y'
        )
        self.ui.btnFile.clicked.connect(self.browseSlot)
        self.ui.tableWidget.setColumnWidth(0, 199)

        self.rowItems = []
        self.url_list = []
        self.complete_url_list = {}
        self.convert_list = []
        self.thread_pool = {}
        self.rowcount = 0

    def browseSlot(self):
        QFileDialog = QtWidgets.QFileDialog
        directory = QFileDialog.getExistingDirectory(
            self, "Select Folder", "/home", QFileDialog.ShowDirsOnly
            | QFileDialog.DontResolveSymlinks)
        if directory:
            self.ui.txtDir.setText(directory)

    def msgbox(self, message):
        QMessageBox.warning(self, "Message", message)

    def btnClicked(self):
        ui = self.ui
        url = ui.txtUrl.toPlainText()
        directory = ui.txtDir.text()
        if url.strip() == "":
            self.msgbox("URL can not bank!")
            return
        if directory.strip() == "":
            self.msgbox("Folder can not bank!")
            return

        can_download, rowcount = self.can_download(url)
        if can_download:
            self.download_url(url, rowcount)
        else:
            self.msgbox("This url is already being downloaded")
            if len(self.url_list) is not 0:
                if len(self.url_list) < 2:
                    self.ui.statusbar.showMessage(
                        'Downloading {0} file'.format(len(self.url_list)))
                else:
                    self.ui.statusbar.showMessage(
                        'Downloading {0} files'.format(len(self.url_list)))
            else:
                self.ui.statusbar.showMessage("done")

    def get_format(self):
        format = self.ui.formatVideo.currentText()
        formats_support = self.formats_convert_support()
        return formats_support[format]

    def formats_convert_support(self):
        return {
            "mp3": {
                'format': "bestaudio",
                "postprocessors": {
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': 'mp3',
                    'preferredquality': '192',
                }
            },
            "mp4": {
                'format': "bestvideo[ext=mp4]+bestaudio[ext=m4a]/",
            },
            "flv": {
                'format': "bestvideo[ext=flv]+bestaudio[ext=m4a]/",
            },
            "3gp": {
                'format': "bestvideo[ext=3gp]+bestaudio[ext=m4a]/",
            },
        }

    def download_url(self, url, row=None):
        if row >= 0:
            row = row
        elif row is None:
            row = self.rowcount

        directory = str(self.ui.txtDir.text())
        format_select = self.get_format()
        options = {
            'url': url,
            'directory': directory,
            'rowcount': row,
            'proxy': '',
            'format': format_select,
            'parent': self,
        }

        self.thread_pool = Download(options)
        self.thread_pool.status_bar_signal.connect(
            self.ui.statusbar.showMessage)
        self.thread_pool.remove_url_signal.connect(self.remove_url)
        self.thread_pool.add_update_list_signal.connect(self.add_to_table)
        self.thread_pool.remove_row_signal.connect(self.decrease_rowcount)
        self.thread_pool.start()

    def can_download(self, url):
        if url not in self.url_list:
            for row, _url in self.complete_url_list.items():
                if url == _url:
                    return True, row
            return True, self.rowcount
        else:
            return False, self.rowcount

    def remove_url(self, url):
        try:
            self.url_list.remove(url)
        except:
            print(url)
            print(self.url_list)
            return

    def add_to_table(self, values):
        ui = self.ui
        rowItems = self.rowItems
        filename = values['filename']
        tableWidget = ui.tableWidget
        rowCount = tableWidget.rowCount()

        tableWidget.setRowCount(rowCount)
        col = 0
        if filename not in rowItems:
            rowItems.append(filename)

        new_row_count = len(rowItems)

        if rowCount != new_row_count:
            tableWidget.insertRow(tableWidget.rowCount())
        new_row = new_row_count - 1
        for value in values:
            if value == 'row':
                continue
            tableWidget.setItem(new_row, col,
                                QtWidgets.QTableWidgetItem(values[value]))
            tableWidget.item(new_row, col).setToolTip(values[value])
            col += 1

    def decrease_rowcount(self):
        self.rowcount -= 1
Beispiel #26
0
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        for i in [
                'spot_price', 'strike_price', 'risk_rate', 'exp_time', 'sigma'
        ]:
            self.__dict__[i] = ''

        self.dividends = []

        self.ui.calculateButton.clicked.connect(self.calculateButtonClicked)
        self.ui.divAddButton.clicked.connect(self.divAddButtonClicked)
        self.ui.divBox.activated[str].connect(self.divOnActivated)
        self.ui.divDeleteButton.clicked.connect(self.divDeleteButtonClicked)
        self.ui.divAllDeleteButton.clicked.connect(
            self.divAllDeleteButtonClicked)
        self.ui.undTypeBox.activated[str].connect(self.undActivated)

        self.ui.divYieldLabel.setDisabled(True)
        self.ui.divYield.setDisabled(True)

    def calculateButtonClicked(self):
        self.info_text = ''

        self.underlying_type = self.ui.undTypeBox.currentText()
        self.info_text += f"Underlying Type: {self.underlying_type}\n"

        self.spot_price, self.info_text = valid_input(self.ui.spotLabel,
                                                      self.ui.spotPrice,
                                                      self.info_text)

        self.strike_price, self.info_text = valid_input(
            self.ui.strikeLabel, self.ui.strikePrice, self.info_text)

        # try:
        #     self.strike_price = float(eval
        #                               (self.ui.strikePrice.text().replace(',', '.')))
        #     self.info_text += f"Strike Price: {self.strike_price}\n"
        # except:
        #     self.info_text += "Enter the strike price...\n"

        self.risk_free_rate, self.info_text = valid_input(
            self.ui.riskFreeRateLabel, self.ui.riskFreeRate, self.info_text)

        if self.underlying_type in ['Currency', 'Index']:
            self.dividend_yield, self.info_text = valid_input(
                self.ui.divYieldLabel, self.ui.divYield, self.info_text)

        self.volatility, self.info_text = valid_input(self.ui.volatilityLabel,
                                                      self.ui.volatility,
                                                      self.info_text)

        if days_to_date(self.ui.startDate.text(), self.ui.expDate.text()) > 0:
            self.exp_time = days_to_date(self.ui.startDate.text(),
                                         self.ui.expDate.text())
            self.info_text += f"Start Date : {self.ui.startDate.text()}\nExpiration Date: {self.ui.expDate.text()}\nExpires in {self.exp_time} days\n"

        else:
            self.info_text += "Check the expiration date. It must be later than start date\n"

        if self.dividends:
            self.info_text += "Including dividents payments"

        self.ui.infoText.setText(self.info_text)
        if 'CHECK' in self.info_text:
            return

        if self.underlying_type == 'Equity':
            bs = BS(self.spot_price,
                    self.strike_price,
                    self.risk_free_rate,
                    self.exp_time,
                    self.volatility,
                    dividends=self.dividends)

        elif self.underlying_type in ['Currency', 'Index']:
            bs = BS(self.spot_price,
                    self.strike_price,
                    self.risk_free_rate,
                    self.exp_time,
                    self.volatility,
                    div_yield=self.dividend_yield)

        else:
            bs = BS(self.spot_price,
                    self.strike_price,
                    self.risk_free_rate,
                    self.exp_time,
                    self.volatility,
                    is_fut=True)

        self.ui.callPrice.setText(str(round(bs.call_price, 6)))
        self.ui.putPrice.setText(str(round(bs.put_price, 6)))

        self.ui.callDelta.setText(str(round(bs.call_delta, 6)))
        self.ui.putDelta.setText(str(round(bs.put_delta, 6)))

        self.ui.gamma.setText(str(round(bs.gamma, 6)))
        self.ui.vega.setText(str(round(bs.vega, 6)))

        self.ui.callRho.setText(str(round(bs.call_rho, 6)))
        self.ui.putRho.setText(str(round(bs.put_rho, 6)))

        self.ui.callTheta.setText(str(round(bs.call_theta, 6)))
        self.ui.putTheta.setText(str(round(bs.put_theta, 6)))

        self.ui.d1.setText(str(round(bs.d1, 6)))
        self.ui.d2.setText(str(round(bs.d2, 6)))

    def divAddButtonClicked(self):
        div_pay, div_time = '', ''
        self.info_text = ''
        try:
            div_pay = float(eval(self.ui.divPayment.text().replace(',', '.')))
        except:
            self.info_text += "Check divident payments\n"

        if days_to_date(self.ui.startDate.text(), self.ui.divDate.text()) > 0:
            div_time = days_to_date(self.ui.startDate.text(),
                                    self.ui.divDate.text())
        else:
            self.info_text += "Check divident payments. The divident payment date must be later than start date\n"

        if [div_pay, div_time] not in self.dividends and div_pay and div_time:
            self.dividends.insert(0, [div_pay, div_time])
            self.ui.divBox.insertItem(
                0,
                f"{div_pay} at {self.ui.divDate.text()} (in {div_time} days)")
            self.ui.divBox.setCurrentIndex(0)

        self.ui.infoText.setText(self.info_text)

    def divOnActivated(self, text):
        words = text.split(' ')
        self.ui.divPayment.setText(words[0])
        self.ui.divDate.setDate(
            datetime.datetime.strptime(words[2], '%d.%m.%Y').date())

    def undActivated(self, text):
        if text != 'Equity':
            self.ui.divHead.setDisabled(True)
            self.ui.divBox.setDisabled(True)
            self.ui.label_2.setDisabled(True)
            self.ui.label_4.setDisabled(True)
            self.ui.divPayment.setDisabled(True)
            self.ui.divDate.setDisabled(True)
            self.ui.divAddButton.setDisabled(True)
            self.ui.divDeleteButton.setDisabled(True)
            self.ui.divAllDeleteButton.setDisabled(True)

            self.dividends = []
            self.ui.divBox.clear()
            self.ui.infoText.setText(
                "All dividend payments has been removed with changing of underlying type"
            )
        else:
            self.ui.divHead.setEnabled(True)
            self.ui.divBox.setEnabled(True)
            self.ui.label_2.setEnabled(True)
            self.ui.label_4.setEnabled(True)
            self.ui.divPayment.setEnabled(True)
            self.ui.divDate.setEnabled(True)
            self.ui.divAddButton.setEnabled(True)
            self.ui.divDeleteButton.setEnabled(True)
            self.ui.divAllDeleteButton.setEnabled(True)

        if text == 'Equity':
            self.ui.spotLabel.setText('Spot Price, S')
            self.ui.divYieldLabel.setText('Dividend Yield, q')

            self.ui.divYieldLabel.setDisabled(True)
            self.ui.divYield.setDisabled(True)

        elif text == 'Currency':
            self.ui.spotLabel.setText('Exchange Rate, S')
            self.ui.divYieldLabel.setText('Foreign Risk-free Rate, r_f')

            self.ui.divYieldLabel.setEnabled(True)
            self.ui.divYield.setEnabled(True)

        elif text == 'Index':
            self.ui.spotLabel.setText('Index Level, S')
            self.ui.divYieldLabel.setText('Dividend Yield, q')

            self.ui.divYieldLabel.setEnabled(True)
            self.ui.divYield.setEnabled(True)

        elif text == 'Future':
            self.ui.spotLabel.setText('Future Price, F')
            self.ui.divYieldLabel.setText('Dividend Yield, q')

            self.ui.divYieldLabel.setDisabled(True)
            self.ui.divYield.setDisabled(True)

    def divDeleteButtonClicked(self):
        div_pay = float(eval(self.ui.divPayment.text().replace(',', '.')))
        div_time = days_to_date(self.ui.startDate.text(),
                                self.ui.divDate.text())

        itd = None
        for i, elem in enumerate(self.dividends):
            if elem == [div_pay, div_time]:
                itd = i

        try:
            self.dividends.remove([div_pay, div_time])
            self.ui.divBox.removeItem(itd)

        except:
            self.ui.infoText("This dividend payment is not found")

    def divAllDeleteButtonClicked(self):
        self.dividends = []
        self.ui.divBox.clear()
        self.ui.infoText.setText("All dividend payments has been removed")
Beispiel #27
0
class mywindow(QtWidgets.QMainWindow):
	def __init__(self):
		super(mywindow, self).__init__()
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)

		self.ui.comboBox.addItem("Метан <CH₄> - Methane")
		self.ui.comboBox.addItem("Метиловый спирт <CH₃OH> - Methanol")
		self.ui.comboBox.addItem("Пентан <C₅H₁₂> - Pentan")
		self.ui.comboBox.addItem("Пропан <C₃H₈> - Propan")
		self.ui.comboBox.addItem("Пропилен <C₃H₆> - Propylene")
		self.ui.comboBox.addItem("Сероводород <H₂S> - Hydrogen sulphide")
		self.ui.comboBox.addItem("Бутадиен <C₄H₆> - Butadiene")
		self.ui.comboBox.addItem("Бутан <C₄H₁₀> - Butane")
		self.ui.comboBox.addItem("Винилхлорид <C₂H₃Cl> - Vinylchloride")
		self.ui.comboBox.activated[str].connect(self.onActivated)
		self.ui.comboBox_2.addItem(Class_zagromo[0])
		self.ui.comboBox_2.addItem(Class_zagromo[1])
		self.ui.comboBox_2.addItem(Class_zagromo[2])
		self.ui.comboBox_2.addItem(Class_zagromo[3])
		self.ui.pushButton.clicked.connect(self.on_click)

	def E(Cg, Cct):
		if Cg <= Cct:
			return self.ui.lineEdit_12.text()
		else:

	@pyqtSlot()
	def on_click(self):
		text = str(self.ui.comboBox_2.currentText())
		massa = 0
		try:
			massa = int(self.ui.lineEdit.text())
			self.ui.label_4.setStyleSheet('color: black')
		except Exception:
			self.ui.label_4.setStyleSheet('color: red')
		#print(combustion_mode[Classification_number][class_zagro[text]])
		self.ui.lineEdit_13.setText(class_trebu(combustion_mode[Classification_number][class_zagro[text]] + 1,massa))

	def onActivated(self, text):
		if text=="Метан <CH₄> - Methane":
			Classification_number = 3
			self.ui.lineEdit_32.setText(Classification[Classification_number])
			self.ui.lineEdit_33.setText("(размер детонационной ячейки больше 40 см)")
			self.ui.lineEdit_12.setText("50160")
			self.ui.lineEdit_6.setText("0,656")
			self.ui.lineEdit_34.setText("ГГ")
			self.ui.lineEdit_12.setText(str(44*1.44))
		elif text=="Метиловый спирт <CH₃OH> - Methanol":
			Classification_number = 2
			self.ui.lineEdit_32.setText(Classification[Classification_number])
			self.ui.lineEdit_33.setText("(размер детонационной ячейки лежит в пределах от 10 до 40 см)")
			self.ui.lineEdit_12.setText("23839")
			self.ui.lineEdit_6.setText("792")
			self.ui.lineEdit_34.setText("ЛВЖ")
			self.ui.lineEdit_12.setText(str(44*0.45))

		elif text=="Пентан <C₅H₁₂> - Pentan":
			Classification_number = 3
			self.ui.lineEdit_32.setText(Classification[Classification_number])
			self.ui.lineEdit_33.setText("(размер детонационной ячейки больше 40 см)")
			self.ui.lineEdit_12.setText("45462")
			self.ui.lineEdit_6.setText("626")
			self.ui.lineEdit_34.setText("ГГ")
			self.ui.lineEdit_12.setText(str(44))

		elif text=="Пропан <C₃H₈> - Propan":
			Classification_number = 1
			self.ui.lineEdit_32.setText(Classification[Classification_number])
			self.ui.lineEdit_33.setText("(размер детонационной ячейки лежит в пределах от 2 до 10 см)")
			self.ui.lineEdit_12.setText("46300")
			self.ui.lineEdit_6.setText("493")
			self.ui.lineEdit_34.setText("ГГ")
			self.ui.lineEdit_12.setText(str(44*1))

		elif text=="Пропилен <C₃H₆> - Propylene":
			Classification_number = 1
			self.ui.lineEdit_32.setText(Classification[Classification_number])
			self.ui.lineEdit_33.setText("(размер детонационной ячейки лежит в пределах от 2 до 10 см)")
			self.ui.lineEdit_12.setText("45694")
			self.ui.lineEdit_6.setText("1,81")
			self.ui.lineEdit_34.setText("ГГ")
			self.ui.lineEdit_12.setText(str(44*1))

		elif text=="Сероводород <H₂S> - Hydrogen sulphide":
			Classification_number = 2
			self.ui.lineEdit_32.setText(Classification[Classification_number])
			self.ui.lineEdit_33.setText("(размер детонационной ячейки лежит в пределах от 10 до 40 см)")
			self.ui.lineEdit_12.setText("16989")
			self.ui.lineEdit_6.setText("1,36")
			self.ui.lineEdit_34.setText("ГГ"),
			self.ui.lineEdit_12.setText(str(44*0.34))

		elif text=="Бутадиен <C₄H₆> - Butadiene":
			Classification_number = 1
			self.ui.lineEdit_32.setText(Classification[Classification_number])
			self.ui.lineEdit_33.setText("(размер детонационной ячейки лежит в пределах от 2 до 10 см)")
			self.ui.lineEdit_12.setText("44574")
			self.ui.lineEdit_6.setText("615")
			self.ui.lineEdit_34.setText("ЛВЖ")
			self.ui.lineEdit_12.setText(str(44*1))

		elif text=="Бутан <C₄H₁₀> - Butane":
			Classification_number = 1
			self.ui.lineEdit_32.setText(Classification[Classification_number])
			self.ui.lineEdit_33.setText("(размер детонационной ячейки лежит в пределах от 2 до 10 см)")
			self.ui.lineEdit_12.setText("45800")
			self.ui.lineEdit_6.setText("2,48")
			self.ui.lineEdit_34.setText("ГГ")
			self.ui.lineEdit_12.setText(str(44*1))

		elif text=="Винилхлорид <C₂H₃Cl> - Vinylchloride":
			Classification_number = 3
			self.ui.lineEdit_32.setText(Classification[Classification_number])
			self.ui.lineEdit_33.setText("(размер детонационной ячейки лежит в пределах от 10 до 40 см)")
			self.ui.lineEdit_12.setText("18307")
			self.ui.lineEdit_6.setText("911")
			self.ui.lineEdit_34.setText("ГГ")
			self.ui.lineEdit_12.setText(str(44*0.42))
Beispiel #28
0
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.refreshButton.clicked.connect(self.btnClicked)

    # def btnClicked(self):
    #     self.ui.label.setText("Вы нажали на кнопку!")
    #     # Если не использовать, то часть текста исчезнет.
    #     self.ui.label.adjustSize()

    def btnClicked(self):
        try:
            self.ui.sqlRelationalTable.setSort(
                7, Qt.AscendingOrder
            )  # Qt.DescendingOrder сортировка в обратном порядке
            self.max_ = 'max'
            self.min_ = 'min'

            self.criterion_dict = {}
            self.final_rating = {}

            self.query = QSqlQuery()
            self.query.exec("""SELECT seller.`id` from seller""")
            while self.query.next():
                self.criterion_dict[(self.query.value(0))] = {}

            self.min_rating('price_rub', self.ui.priceSpinBox)
            self.max_rating('yearsOnTheMarket', self.ui.yearsSpinBox)
            self.max_rating('rating', self.ui.reviewSpinBox)
            self.min_rating('delivery_days', self.ui.deliveryTimeSpinBox)
            # print(self.criterion_dict)
            for key, item in self.criterion_dict.items():
                i = 0
                for k, _ in item.items():
                    print(k, _)
                    i += _
                self.final_rating[key] = round(i, 2)
            print(self.final_rating)

            self.query = QSqlQuery()
            # self.query.exec("""CREATE TEMPORARY TABLE rating_table(`id` INT NOT NULL,`rating` float,PRIMARY KEY (`id`))""")
            print(
                self.query.exec(
                    """CREATE TEMPORARY TABLE if not exists final_table as (Select * from seller)"""
                ))
            print(
                self.query.exec(
                    """ALTER TABLE `final_table` ADD COLUMN `final_rating` FLOAT(11)"""
                ))
            for key, item in self.final_rating.items():
                # self.query.exec("""insert into rating_table(`id`,`rating`) value({0},{1})""".format(key,item))\
                print(item / 4, key)
                print(
                    self.query.exec(
                        """update final_table set final_rating={0} where id = {1}"""
                        .format(item / 4, key)))
            self.ui.sqlRelationalTable.submitAll()
            self.ui.sqlRelationalTable.setTable('final_table')
            self.ui.setNameColumn()
            self.ui.sqlRelationalTable.setHeaderData(8, Qt.Horizontal,
                                                     "Рейтинг")

            self.ui.sqlRelationalTable.select()
        except Exception as e:
            print(e)

    def maxmin(self, value, column):
        self.query = QSqlQuery()
        self.query.exec("""SELECT seller.`id`,{0}({1}) from seller""".format(
            value, column))
        while self.query.next():
            return float(self.query.value(1))

    def min_rating(self, criterion, spinBox):
        self.min_criterion = self.maxmin(self.min_,
                                         'seller.`{0}`'.format(criterion))
        self.criterion_rating_per_one = self.min_criterion * float(
            spinBox.text().replace(',', '.'))
        self.query.exec(
            """SELECT seller.`id`,seller.`{}` from seller""".format(criterion))
        while self.query.next():
            try:
                self.criterion_rating = round(
                    self.criterion_rating_per_one / int(self.query.value(1)) *
                    100, 2)
            except:
                self.criterion_rating = 0
            self.criterion_dict[self.query.value(
                0)][criterion] = self.criterion_rating
        return self.criterion_dict

    def max_rating(self, criterion, spinBox):
        self.max_criterion = self.maxmin(self.max_,
                                         'seller.`{0}`'.format(criterion))
        self.criterion_rating_per_one = self.max_criterion / 100 * float(
            spinBox.text().replace(',', '.'))
        self.query.exec(
            """SELECT seller.`id`,seller.`{}` from seller""".format(criterion))
        while self.query.next():
            try:
                self.criterion_rating = round(
                    int(self.query.value(1)) / self.criterion_rating_per_one,
                    2)
            except:
                self.criterion_rating = 0
            self.criterion_dict[self.query.value(
                0)][criterion] = self.criterion_rating

        return self.criterion_dict
Beispiel #29
0
 def __init__(self):
     super(mywindow, self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.refreshButton.clicked.connect(self.btnClicked)
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton_3.clicked.connect(self.btnClickedShowAll)
        self.ui.pushButton.clicked.connect(self.btnClickedAdd)
        self.ui.pushButton_2.clicked.connect(self.btnClickedRemoveTest)
        self.ui.pushButton_4.clicked.connect(self.btnClickedShowStatistics)

    def btnClickedShowStatistics(self):
        operator = self.ui.lineEdit_2.text()
        error = ""
        if operator == '':
            error = "Enter the name of operator"
        else:
            main_connect = connect_db('tests.db')
            main_cursor = main_connect.cursor()
            all_select_sql = '''SELECT Device_type, COUNT(*) as All_tests FROM tests_results WHERE Operator = \'''' + operator + '''\' GROUP BY Device_type'''
            success_select_sql = '''SELECT Device_type, COUNT(*) as Success_tests FROM tests_results WHERE Operator = \'''' + operator + '''\' AND Success = 1 GROUP BY Device_type'''
            unsuccess_select_sql = '''SELECT Device_type, COUNT(*) as Unsuccess_tests FROM tests_results WHERE Operator = \'''' + operator + '''\' AND Success = 0 GROUP BY Device_type'''
            statistics_list = main_cursor.execute(all_select_sql).fetchall()

            dev_type_list = []
            all_tests_list = []
            success_tests_list = []
            unsuccess_tests_list = []
            for item in statistics_list:
                dev_type_list.append(item[0])
                all_tests_list.append(item[1])
            success_list = main_cursor.execute(success_select_sql).fetchall()
            for item in success_list:
                success_tests_list.append(item[1])
            unsuccess_list = main_cursor.execute(
                unsuccess_select_sql).fetchall()
            for item in unsuccess_list:
                unsuccess_tests_list.append(item[1])
            result_list = []
            for i in range(0, len(statistics_list) - 1):
                result_list.append(
                    (dev_type_list[i], all_tests_list[i],
                     success_tests_list[i], unsuccess_tests_list[i]))
            main_cursor.close()
            main_connect.close()
            self.ui.label_6.setText(operator)

            row = 0
            for line in result_list:
                col = 0
                for cell_data in line:
                    col += 1
                row += 1
            self.ui.tableWidget.setRowCount(row)
            self.ui.tableWidget.setColumnCount(col)
            header_list = [
                'Device type', 'All tests', 'Success tests', 'Unsuccess tests'
            ]
            self.ui.tableWidget.setHorizontalHeaderLabels(header_list)

            row = 0
            for line in result_list:
                col = 0
                for cell_data in line:
                    cellinfo = QTableWidgetItem(str(cell_data))
                    cellinfo.setFlags(QtCore.Qt.ItemIsSelectable
                                      | QtCore.Qt.ItemIsEnabled)
                    self.ui.tableWidget.setItem(row, col, cellinfo)
                    col += 1
                row += 1

        self.ui.lineEdit_2.setText('')
        if error:
            self.ui.label_7.setText(error)
            self.ui.label_7.setStyleSheet('color: red')
        else:
            self.ui.label_7.setText('')

    def btnClickedRemoveTest(self):
        error = ""
        delete_id = self.ui.lineEdit_3.text()
        if delete_id:
            main_connect = connect_db('tests.db')
            main_cursor = main_connect.cursor()
            delete_sql = '''DELETE FROM tests_results WHERE id=''' + delete_id
            main_cursor.execute(delete_sql)
            main_connect.commit()
            main_cursor.close()
            main_connect.close()
            self.btnClickedShowAll()
            self.ui.lineEdit_3.setText('')
        else:
            error = "Enter ID of the test to remove"
        if error:
            self.ui.label_7.setText(error)
            self.ui.label_7.setStyleSheet('color: red')
        else:
            self.ui.label_7.setText('Test ID # ' + delete_id + ' has removed')
            self.ui.label_7.setStyleSheet('color: green')

    def btnClickedAdd(self):
        error = ""
        main_connect = connect_db('tests.db')
        main_cursor = main_connect.cursor()

        insert_list = []
        if (self.ui.lineEdit.text() == '' or self.ui.lineEdit_2.text() == ''):
            error = "Cant add blank fields"
        else:
            insert_list.append(self.ui.lineEdit.text())
            insert_list.append(self.ui.lineEdit_2.text())
            datetime_now = datetime.datetime.now().strftime(
                "%Y-%m-%d %H:%M:%S")
            insert_list.append(datetime_now)
            insert_list.append(self.ui.spinBox.text())

            insert_sql = '''INSERT INTO tests_results (Device_type, Operator, Time, Success) VALUES(?, ?, ?, ?);'''
            main_cursor.execute(insert_sql, insert_list)
            main_connect.commit()
            main_cursor.close()
            main_connect.close()
        self.ui.lineEdit_2.setText('')
        self.ui.lineEdit.setText('')
        self.ui.spinBox.setValue(0)
        self.btnClickedShowAll()
        if error:
            self.ui.label_7.setText(error)
            self.ui.label_7.setStyleSheet('color: red')
        else:
            self.ui.label_7.setText('Test has been added')
            self.ui.label_7.setStyleSheet('color: green')

    def btnClickedShowAll(self):
        show_list = show_all_tests()
        row = 0
        for line in show_list:
            col = 0
            for cell_data in line:
                col += 1
            row += 1
        self.ui.tableWidget_2.setRowCount(row)
        self.ui.tableWidget_2.setColumnCount(col)
        header = ['ID', 'Device type', 'Operator', 'Time', 'Success']
        self.ui.tableWidget_2.setHorizontalHeaderLabels(header)

        row = 0
        for line in show_list:
            col = 0
            for cell_data in line:
                cellinfo = QTableWidgetItem(str(cell_data))
                cellinfo.setFlags(QtCore.Qt.ItemIsSelectable
                                  | QtCore.Qt.ItemIsEnabled)
                self.ui.tableWidget_2.setItem(row, col, cellinfo)
                col += 1
            row += 1