def set_round_order(self, players):
        """
        Determines the order in which players will take their turns during the game
        Input: list of player_token objects that are playing the game
        Output: list of player_tokens objects that are sorted based on highest dice roll
        """
        if len(players) == 1:
            return players
        else:
            first_rolls = {}
            for player in players:
                QMessageBox.information(self, 'Who Goes First?', player.name + ' roll the die!', QMessageBox.Ok, QMessageBox.Ok)
                first_rolls[player] = self.die.roll()

            #Covers the case where players rolled the same number on their initial roll
            #Only allows 1 roll off. If the players roll the same number again, turn order is sorted by name
            second_rolls = {}
            for player in players:
                temp_dict = first_rolls.copy()
                temp_dict.pop(player)
                if first_rolls[player] in temp_dict.values():
                    QMessageBox.information(self, 'Who Goes First?', "Roll Off!\n" + player.name + ' reroll the die!',
                                            QMessageBox.Ok, QMessageBox.Ok)
                    second_rolls[player] = self.die.roll()
                else:
                    second_rolls[player] = 0

            for player in players:
                first_rolls[player] = first_rolls[player] + (0.1 * second_rolls[player])

            dict_sort = sorted(first_rolls.items(), key=lambda x: x[1], reverse=True)
            sorted_players = [x[0] for x in dict_sort]

            return sorted_players
 def newFile(self):
     """
     Слот для создания нового каталога
     :return: None
     """
     dialog = QFileDialog.getSaveFileName(
         caption="Создать каталог",
         dir=str(os.path.abspath("main.py")),
         filter=f"Data base(*.db);;{self.filter[1]}",
         selectedFilter=f"Data base(*.db)")
     if len(str(dialog[0])) == 0:
         QMessageBox.information(None,
                                 "Предупреждение",
                                 "Введите название файла",
                                 buttons=QMessageBox.Ok,
                                 defaultButton=QMessageBox.Ok)
     else:
         conn = sqlite3.connect(str(dialog[0]))
         cursor = conn.cursor()
         cursor.execute(
             """CREATE TABLE books (Название_книги text, Автор  text, Год_выпуска text, Жанр text, Статус text)"""
         )
         conn.commit()
         conn.close()
         self.filename = str(dialog[0])
         self.sql = SQLite(self.filename)
         widget = self.sql.on()
         self.setCentralWidget(widget)
         self.resize(widget.width(), widget.height())
         self.actionwidgetsOn()
    def do_unlock_result(self, result_str: str) -> None:
        """
        To understand the return value of the lock instruction
        :param result_str: Unlock the message sent by the thread
        :return:
        """
        if 'END' in result_str:
            # self.ui.pushButton.setDisabled(False)
            return

        result_list = result_str.split('\n')
        print('The return value is received:', result_list)

        if result_list[1] == '0':
            # Perform an
            self.control_server_Thread.ota_state_Thread.connect(
                self.updata_ota)
            self.control_server_Thread.start()
            return

        # Send unlocking failure (prompt for network connection)(close the
        # server)
        QMessageBox.information(
            self, 'Send unlock failed',
            'Please check your network connection and retry.!',
            QMessageBox.Yes, QMessageBox.Yes)
Exemple #4
0
 def mess(self):
     """
     消息弹窗提示
     :return:
     """
     QMessageBox.information(self, "提示信息", "Hello World!!",
                             QMessageBox.Ok | QMessageBox.Cancel)
def act():
    text = QInputDialog.getMultiLineText(QtCreator.Core.ICore.dialogParent(),
        "Input Text", "Input your text, including some macros",
        "3 + 3 = %{Python:3+3}"
    )
    text = QtCreator.Utils.MacroExpander().expand(text[0])
    QMessageBox.information(QtCreator.Core.ICore.dialogParent(), "Result", text)
 def on_clickMe_clicked(self, is_checked):
     if is_checked:
         message = self.trUtf8(b'I am checked now.')
     else:
         message = self.trUtf8(b'I am unchecked now.')
     QMessageBox.information(self, self.trUtf8(b'You clicked me'),
                             message)
Exemple #7
0
 def saveAlpha(self):
     # self.imageList.saveAlpha(self.final)
     # self.final:alpha, self.foreground:trimap
     self.imageList.saveBoth(self.final, self.foreground)
     self.save()
     self.saveStatus = 1
     QMessageBox.information(self, "", "sucess", QMessageBox.Yes)
    def fetch_markers(data, ddf):  # Fetch data into table view markersTable
        if MarkersTabController.ui is None:
            QMessageBox.information(MarkersTabController.ui, "Warning", "Something went wrong with the .txt file.")
        else:
            linkageGroupsDict = defaultdict(list)
            markers = list()
            # ~~~~~~~~~~~~~~ Read the markers from the file (Panda DataFrame) ~~~~~~~~~~~~~~#
            for index, row in data.iterrows():
                marker = Marker(row['id'], row['marker_name'],
                                (list(ddf.loc[ddf['marker_name'] == row['marker_name'], 'properties'])),
                                row['linkage_id'], row['chr'], "-", row['genetic_coord'])
                markers.append(marker)
                linkageGroupsDict[marker.linkage_group].append(marker)

            LinkageGroup.create_linkages(linkageGroupsDict)  # Create all linkage groups
            Marker.markers = markers
            MarkersTabController.markers = markers
            MarkersTabController.ui.markersTable.verticalHeader().hide()
            # ~~~~~~~~~~~~~~ Display the markers in the table in gui ~~~~~~~~~~~~~~#
            for row, marker in enumerate(markers):
                MarkersTabController.ui.markersTable.insertRow(row)
                for column, variable in enumerate(vars(marker).items()):
                    item = QTableWidgetItem(str(variable[1])) if str(
                        variable[0]) != 'alleles' else QTableWidgetItem('N/A') if len(
                        variable[1]) == 0 else QTableWidgetItem(str(variable[1])[2:-2])
                    item.setFlags(QtCore.Qt.ItemIsEnabled)
                    MarkersTabController.ui.markersTable.setItem(row, column, item)

            NetworkTabController.initialize_combobox(LinkageGroup.LinkageGroups)


            # Display statistics
            StatisticsController.display_stat(markers, LinkageGroup.LinkageGroups)
            GraphicalGenotypeController.draw_graphical_genotype_map()
Exemple #9
0
    def create(self):
        equivalent_loads = self.get_equivalent_loads()
        rho_x = float(self.form.rhox_combobox.currentText())
        rho_y = float(self.form.rhoy_combobox.currentText())
        prefix = self.form.prefix.text()
        suffix = self.form.suffix.text()
        data = self.etabs.load_combinations.generate_concrete_load_combinations(
            equivalent_loads=equivalent_loads,
            prefix=prefix,
            suffix=suffix,
            rho_x=rho_x,
            rho_y=rho_y,
        )
        progressbar = FreeCAD.Base.ProgressIndicator()
        n = int(len(data) / 4)
        progressbar.start("Creating Load Combinations...", n)
        for i in range(0, len(data), 4):
            comb = data[i:i + 4]
            row = ' | '.join([str(s) for s in comb])
            self.form.load_combinations_list.addItem(row)
            self.etabs.SapModel.RespCombo.add(comb[0], 0)
            self.etabs.SapModel.RespCombo.SetCaseList(
                comb[0],
                0,  # loadcase=0, loadcombo=1
                comb[2],  # cname
                comb[3],  # sf
            )
            progressbar.next(True)
        progressbar.stop()

        QMessageBox.information(None, 'Successfull',
                                'Successfully written to etabs file.')
 def openFile(self):
     """
     Слот для подключения каталога
     :return: None
     """
     dialog = QFileDialog.getOpenFileName(
         caption="Открыть каталог",
         dir=str(os.path.abspath("main.py")),
         filter=f"{self.filter[0]};;{self.filter[1]}",
         selectedFilter=f"{self.filter[0]}")
     if len(str(dialog[0])) != 0:
         if str(dialog[0]).split(".")[1] not in ('db', 'sdb', 'sqlite',
                                                 'db3', 's3db', 'sqlite3',
                                                 'sl3', 'db2', 's2db',
                                                 'sqlite2', 'sl2'):
             QMessageBox.information(None,
                                     "Предупреждение",
                                     "Данный тип файлов не поддерживается",
                                     buttons=QMessageBox.Ok,
                                     defaultButton=QMessageBox.Ok)
         else:
             self.filename = str(dialog[0])
             self.sql = SQLite(self.filename)
             widget = self.sql.on()
             self.setCentralWidget(widget)
             self.resize(widget.width(), widget.height())
             self.actionwidgetsOn()
    def ask_question(self, player, tile_type, isCake):
        """
        Interfaces with board, player, and QA manager to get question,
        get player input, verify input, and update accordingly
        Input: Player token who is answering question, the question type, and tile type to determine cake or not
        Output: True/False to determine subsequent action if answer is right
        Using just stdin/stdout for now to show functionality
        """
        question = self.qa_manager.get_question(tile_type)
        answer, valid_input = QInputDialog.getText(self, tile_type + ' Question', question)

        if valid_input:
            correct, answer_string = self.qa_manager.check_answer(question, answer)
            if correct:
                QMessageBox.information(self, 'Your answer was...', 'Correct!', QMessageBox.Ok, QMessageBox.Ok)
                print("Correct")
                if isCake:
                    player.award_cake_piece(tile_type)
                return True
            else:
                QMessageBox.information(self, 'Your answer was...', 'Incorrect! Correct answer was: ' + answer_string,
                                        QMessageBox.Ok, QMessageBox.Ok)
                print("Wrong")
                return False
        else:
            print("-----------------------")
            print("--- Input cancelled ---")
            print("-----------------------")
 def spider_csdn(self):
     # 目标文章的链接
     title_url = self.text.toPlainText()
     MessageBox = QMessageBox(self.windows)
     if not title_url:
         MessageBox.critical(self.windows, "错误", "请输入网址")
         return
     head = {
         "User-Agent":
         "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36 Edg/84.0.522.52"
     }
     html = requests.get(url=title_url, headers=head).text
     page = parsel.Selector(html)
     #创建解释器
     title = page.css(".title-article::text").get()
     res = re.compile("[^\u4e00-\u9fa5^a-z^A-Z^0-9]")
     restr = ''
     res.sub(restr, title)
     content = page.css("article").get()
     content = re.sub("<a.*?a>", "", content)
     content = re.sub("<br>", "", content)
     texts = tomd.Tomd(content).markdown
     #转换为markdown 文件
     with open(title + ".md", mode="w", encoding="utf-8") as f:
         f.write("#" + title)
         f.write(texts)
         MessageBox.information(self.windows, "正确", "获取文章完成")
Exemple #13
0
 def _search_results_ready(self, results):
     if results:
         browser = ObjectsBrowserWindow(self._main_window, title=_("Search results"), unsorted_objects=results, person=self._person, progress_indicator=self._search_progress)
         self._browser_window = browser
     else:
         self._search_progress.hide()
         QMessageBox.information(self._main_window, _("Information"), _("No object matches the given search criteria."))
Exemple #14
0
    def get_device_info(self):
        # Enable the sendpin button if it's a trezor and it needs it
        if self.device_info['needs_pin_sent']:
            self.ui.sendpin_button.setEnabled(True)
            self.clear_info()
            return
        else:
            self.ui.sendpin_button.setEnabled(False)

        # If it isn't initialized, show an error but don't do anything
        if 'code' in self.device_info and self.device_info[
                'code'] == DEVICE_NOT_INITIALIZED:
            self.clear_info()
            QMessageBox.information(None, "Not initialized yet",
                                    'Device is not initalized yet')
            return

        # do getkeypool and getdescriptors
        keypool = do_command(
            commands.getkeypool, self.client,
            None if self.getkeypool_opts['account_used'] else
            self.getkeypool_opts['path'], self.getkeypool_opts['start'],
            self.getkeypool_opts['end'], self.getkeypool_opts['internal'],
            self.getkeypool_opts['keypool'], self.getkeypool_opts['account'],
            self.getkeypool_opts['addrtype'])
        descriptors = do_command(commands.getdescriptors, self.client,
                                 self.getkeypool_opts['account'])

        self.ui.keypool_textedit.setPlainText(json.dumps(keypool, indent=2))
        self.ui.desc_textedit.setPlainText(json.dumps(descriptors, indent=2))
Exemple #15
0
    def restore_finish(self, paths, snapshot_id):
        self.status_label.clear()
        self.setEnabled(True)
        if len(paths) is 0:
            return
        restore_dir = QFileDialog.getExistingDirectory()
        if len(restore_dir) is 0:
            return

        self.restore_dir = restore_dir
        self.paths = paths
        self.snapshot_id = snapshot_id

        reply = QMessageBox.information(
            self.window, "Start Restore?",
            f"You are about to restore to {restore_dir}. Continue?",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply is QMessageBox.No:
            return

        if len(os.listdir(restore_dir)) is not 0:
            reply = QMessageBox.information(
                self.window, "Potential Overwrite?",
                f"You are restoring to a non-empty folder! BlobBackup will OVERWRITE any conflicting paths. Continue?",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply is QMessageBox.No:
                return

        self.accept()
Exemple #16
0
    def __init__(self, parent=None):
        """
        Constructor

        @param parent reference to the parent widget
        @type QWidget
        """
        # self.items = {}
        self.is_double_clicked = False
        self.sel_name = 'HE410N8115'  # 默认选择阴凉库1
        bgbruse = ''  # 保存单元格的默认笔刷
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        # 显示画图
        # static_canvas = FigureCanvas(Figure(figsize=(5, 3)))
        # self.addToolBar(NavigationToolbar(static_canvas, self))
        # self.horizontalLayout.addWidget(static_canvas)


        # self._static_ax = static_canvas.figure.subplots()





        self.set_date()
        QMessageBox.information(self,
                                "消息框标题",
                                "请将系统的短日期格式设置为yyyy/M/d \n"
                                "长时间格式设置为h:mm:ss",
                                )
Exemple #17
0
    def on_up_tb_clicked(self):
        # 按年份,月份修改
        tb = 'LOGS_' + self.sel_name
        start_date,end_date = self.get_date()
        query = self.conn.show_errdata(self.sel_name, start_date, end_date,self.one_high,self.one_low,self.two_high,self.two_low)
        while query.next():
            # 获取当前的实际温度
            one = query.value(1)
            two = query.value(2)
            # print(one,two)
            if (one > self.one_high or one < self.one_low) and (two < self.two_high or two > self.two_low):
                # print('修改温度')
                if abs(self.one_low - one) < abs(self.one_high - one):
                    high = random.uniform(self.one_low - 1, self.one_low + 1)
                else:
                    high = random.uniform(self.one_high - 1, self.one_high + 1)
                self.conn.up_data(tb, high, query.value(0).toString('yyyy/M/d h:mm:ss'), 'one')
            elif (one < self.one_high or one > self.one_low) and (two > self.two_high or two < self.two_low):
                # print('修改湿度')
                if abs(self.two_low - two) < abs(self.two_high - two):
                    high = random.uniform(self.two_low - 1, self.two_low + 1)
                else:
                    high = random.uniform(self.two_high - 1, self.two_high + 1)
                self.conn.up_data(tb, high, query.value(0).toString('yyyy/M/d h:mm:ss'), 'two')

        QMessageBox.information(self,
                                "消息框标题",
                                "修改完毕!",
                                )
    def clickLogin(self):
        """
        Quando o usuário acionar o botão de login, verifica se
        o usuário e o login conferem. Os registros estão no
        arquivo usuarios.txt.
        Se existe, apresenta uma mensagem e fecha o app
        Se não, mostra uma mensagem de erro
        """

        usuarios = {} 

        try:
            with open("usuarios.txt", 'r') as f:
                for line in f:
                    campos = line.split(" ")
                    username = campos[0]
                    senha = campos[1].strip('\n')
                    usuarios[username] = senha                
        except FileNotFoundError:
            print("O arquivo de usuários (usuarios.txt) não foi encontrado.")
            f = open("usuarios.txt", 'w')

        username = self.nome_edit.text()
        senha = self.pwd_edit.text()
        if (username, senha) in usuarios.items():
            QMessageBox.information(self, "Registro Ok", "Login realizado com sicesso", 
                                        QMessageBox.Ok, QMessageBox.Ok)
            self.close()
        else: 
            QMessageBox.warning(self, "Problemas!", "Senha o nome do usuário incorecto", 
                                    QMessageBox.Close, QMessageBox.Close)
 def start_root(self) -> None:
     # Check if conditions are met
     if not self.file_flg:
         QMessageBox.information(self, 'Insufficient conditions',
                                 'Missing firmware file!', QMessageBox.Yes,
                                 QMessageBox.Yes)
         return
     if not self.dev_flg:
         QMessageBox.information(self, 'Insufficient conditions',
                                 'No device selected yet!', QMessageBox.Yes,
                                 QMessageBox.Yes)
         return
     # Create a QT thread to transfer firmware to the device
     my_port = self.check_port()
     my_addr = self.get_dev_ip_for_lan()
     print('Server initialization complete')
     self.control_server_Thread = SeverThreadForQT(server_port=my_port,
                                                   server_ip=my_addr)
     # Lock button
     self.pB_get_device.setDisabled(True)
     self.pB_import_firmware.setDisabled(True)
     self.pB_OK.setDisabled(True)
     self.pB_Cencel.setDisabled(True)
     # Send an unlocked device upgrade
     self.send_unlock(self.sub_id, self.img_sha256, my_addr, my_port)
Exemple #20
0
    def run_and_check_result(self, command):
        """
        运行程序并且检测返回结果

        :param command: 需要运行的命令
        :return: None
        """
        stdout_data, stderr_data = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            stdin=subprocess.PIPE,  # GUI程序中记得设置标准输入
            shell=True).communicate()
        stdout_data = stdout_data.decode('gbk')
        stderr_data = stderr_data.decode('gbk')
        if stdout_data == '请求的操作需要提升(作为管理员运行)。\n\r\n':
            QMessageBox.warning(self, '提示', '请使用管理员权限运行程序!', QMessageBox.Ok,
                                QMessageBox.Ok)
        elif stdout_data == '\r\n' and stderr_data == '':
            QMessageBox.information(self, '提示', 'OK!', QMessageBox.Ok,
                                    QMessageBox.Ok)
        else:
            QMessageBox.information(self, '提示',
                                    f'{stdout_data}\r\n{stderr_data}',
                                    QMessageBox.Ok, QMessageBox.Ok)
Exemple #21
0
 def save_captured_to_pcap(self):
     """
     将抓到的数据包保存为pcap格式的文件
     """
     if self.packet_id == 1:
         QMessageBox.warning(None, "警告", "没有可保存的数据包!")
         return
     # 选择保存名称
     filename, _ = QFileDialog.getSaveFileName(
         parent=None,
         caption="保存文件",
         directory=getcwd(),
         filter="Pcap Files (*.pcap);;All Files (*)",
     )
     if filename == "":
         QMessageBox.warning(None, "警告", "保存失败!")
         return
     # 如果没有设置后缀名(保险起见,默认是有后缀的)
     if filename.find(".pcap") == -1:
         # 默认文件格式为 pcap
         filename = filename + ".pcap"
     copy(self.temp_file, filename)
     chmod(filename, 0o0400 | 0o0200 | 0o0040 | 0o0004)
     QMessageBox.information(None, "提示", "保存成功!")
     self.save_flag = True
Exemple #22
0
    def user_commit_register(self):
        """ 用户提交注册 """
        if self.register_password_1.text() != self.register_password_2.text():
            QMessageBox.information(self, "错误", "两次输入密码不一致!")
            return
        self.register_button.clicked.disconnect()  # 关闭注册点击链接
        self.text_animation_timer.start(500)  # 按钮文字显示状态
        md5_hash = md5()
        md5_hash.update(self.register_password_1.text().encode("utf-8"))
        register_dict = {
            "phone": self.register_phone.text(),
            "nickname": self.register_nickname.text(),
            "password": md5_hash.hexdigest(),
            "input_code": self.register_code.text(),
            "code_uuid": self._code_uuid
        }

        print(register_dict)
        multi_data = generate_multipart_data(register_dict)
        app = QApplication.instance()
        network_manager = getattr(app, "_network")

        url = SERVER + "register/"
        request = QNetworkRequest(url=QUrl(url))
        # request.setHeader(QNetworkRequest.ContentTypeHeader, "multipart/form-data; boundary=%s" % multi_data.boundary())  # 设置后服务器无法找到边界报400
        reply = network_manager.post(request, multi_data)
        reply.finished.connect(self.user_register_back)
        multi_data.setParent(reply)
Exemple #23
0
    def assign_value_for_filter(self, filter_id, show=True):
        """
        preper list with value from main filter, send it to make_filter_list.
        Replace column for filter_id with column with assigned data
        :param filter_id:
        :return:
        """
        session = Session()
        filter_ = session.query(FilterF).get(filter_id)
        rows = []
        for row in range(self.sti.rowCount()):
            row_value = [
                self.sti.item(row, col).text() for col in filter_.columns
            ]
            rows.append(row_value)

        read_rows = self.make_filter_list(filter_id, rows)
        col_nr = filter_.column_nr
        self.sti.takeColumn(col_nr)
        self.sti.insertColumn(col_nr, read_rows)
        self.sti.setHorizontalHeaderLabels(self.headers)
        session.close()
        self.set_color_on_header()

        if show:
            QMessageBox.information(self, "Informacja", "Operacja zakończona.")
Exemple #24
0
    def view_fit_grains_results(self):
        if self.fit_grains_results is None:
            QMessageBox.information(
                self.parent, "No Grains Fond", "No grains were found")
            return

        for result in self.fit_grains_results:
            print(result)

        # Build grains table
        num_grains = len(self.fit_grains_results)
        shape = (num_grains, 21)
        grains_table = np.empty(shape)
        gw = instrument.GrainDataWriter(array=grains_table)
        for result in self.fit_grains_results:
            gw.dump_grain(*result)
        gw.close()

        # Use the material to compute stress from strain
        material = HexrdConfig().active_material

        # Display results dialog
        dialog = FitGrainsResultsDialog(grains_table, material, self.parent)
        dialog.ui.resize(1200, 800)
        self.fit_grains_results_dialog = dialog
        dialog.show()
Exemple #25
0
def allowed_to_continue(
    filename,
    gist_url,
    dir_name,
    n=2,
):
    import check_legal
    check = check_legal.CheckLegalUse(
        filename,
        gist_url,
        dir_name,
        n=n,
    )
    allow, text = check.allowed_to_continue()
    if allow and not text:
        return True, check
    else:
        if text in ('INTERNET', 'SERIAL'):
            ui = SerialForm()
            ui.form.serial.setText(check.serial)
            Gui.Control.showDialog(ui)
            # if ui.setupUi():
            #     Gui.Control.closeDialog(ui)
            return False, check
        elif text == 'REGISTERED':
            msg = "Congrajulation! You are now registered, enjoy using this features!"
            QMessageBox.information(None, 'Registered', str(msg))
            return True, check
    return False, check
Exemple #26
0
    def delete_user(self) -> None:
        login = self.ui.combo_users.currentText()

        answer = QMessageBox.question(
            self,
            "Potwierdź usunięcie użytkownika",
            f"Czy na pewno chcesz usunąć użytkownika {login}?",
        )

        if answer == QMessageBox.No:
            return

        c = ctx.db.cursor()
        c.execute("delete from users where login=?", (login, ))

        if c.rowcount == 1:
            ctx.db.commit()

            QMessageBox.information(self, "Sukces",
                                    f"Pomyślnie usunięto użytkownika {login}")

            if ctx.login == login:
                ctx.main.main_window.logout(False)

            self.finished.emit()
        else:
            QMessageBox.critical(self, "Błąd",
                                 f"Nie udało się usunąć użytkownika {login}")
 def new_main_program_file(self):
     """Creates a new blank main program file. Let's user decide the file name and path.
      Alternative version using only one getSaveFileName dialog.
      """
     # noinspection PyCallByClass
     answer = QFileDialog.getSaveFileName(self, "Create new main program", APPLICATION_PATH)
     file_path = answer[0]
     if not file_path:  # Cancel button clicked
         return
     # Remove file if it exists. getSaveFileName has asked confirmation for us.
     try:
         os.remove(file_path)
     except OSError:
         pass
     try:
         with open(file_path, "w"):
             pass
     except OSError:
         msg = "Please check directory permissions."
         # noinspection PyTypeChecker, PyArgumentList, PyCallByClass
         QMessageBox.information(self, "Creating file failed", msg)
         return
     main_dir = os.path.dirname(file_path)
     self.program_path = os.path.abspath(main_dir)
     # Update UI
     self.ui.lineEdit_main_program.setText(file_path)
     self.ui.label_mainpath.setText(self.program_path)
Exemple #28
0
    def run_filters(self):
        """
        make filters
        :return:
        """
        session = Session()
        # filters_ = session.query(FilterF).filter_by(type='words').all()
        filters_ = session.query(FilterF).all()
        for fil in filters_:

            if fil.type == 'words':
                rows = self.get_data_from_columns(fil.columns)
                assignded_column = self.make_words_list(fil.id, rows)
                self.replace_column(fil.column_nr, assignded_column)

            elif fil.type == 'cut':
                if fil.name == 'model':
                    rows = self.get_data_from_columns(fil.columns)
                    assignded_column = self.filter_cut_model(rows)
                    self.replace_column(fil.column_nr, assignded_column)

                elif fil.name == 'subbrand_brand_model':
                    rows = self.get_data_from_columns(fil.columns)
                    assignded_column = self.join_columns(rows)
                    self.replace_column(fil.column_nr, assignded_column)

        session.close()
        QMessageBox.information(self, "Informacja", "Operacja zakończona.")
Exemple #29
0
    def on_check_for_update(self):
        self.setCursor(Qt.WaitCursor)

        current_version = get_current_version_name()

        try:
            latest_version = get_latest_version_name()
        except ValueError as ve:
            QMessageBox.critical(self, "Error while checking for updates",
                                 f"Error: {ve}")
            return

        if current_version != latest_version:
            latest_release_url = f"{releases_link}/tag/{latest_version}"

            go_to_github_button = QPushButton(icon("external-link.svg"),
                                              "Go to latest release")
            go_to_github_button.clicked.connect(
                lambda: open_url(latest_release_url))

            info_box = QMessageBox(
                QMessageBox.Information, "New release available",
                f"New Version {latest_version} is available.")

            info_box.addButton(QMessageBox.Cancel)
            info_box.addButton(go_to_github_button, QMessageBox.AcceptRole)

            info_box.exec_()
        else:
            QMessageBox.information(
                self, "No newer release",
                f"Version {current_version} is up to date.")

        self.setCursor(Qt.ArrowCursor)
Exemple #30
0
 def show_db_map_entity_metadata(self, db_map_ids):
     metadata = {
         db_map.codename: self._metadata_per_entity(db_map, entity_ids)
         for db_map, entity_ids in db_map_ids.items()
     }
     QMessageBox.information(self, "Entity metadata",
                             self._parse_db_map_metadata(metadata))
    def writeToFile(self, filename):
        """ Save all contacts in the model to a file. """
        try:
            f = open(filename, "wb")
            pickle.dump(self.tableModel.addresses, f)

        except IOError:
            QMessageBox.information(self, "Unable to open file: %s" % filename)
        finally:
            f.close()
Exemple #32
0
 def score(self):
     score = self.mineSweeper.score()
     if score is not None:
         self.mineSweeper.reveal()
         if score == +1:
             QMessageBox.information(self, self.tr("Victory!"), self.tr("You won :)"), QMessageBox.Ok)
         if score == -1:
             QMessageBox.critical(self, self.tr("Defeat!"), self.tr("You lost :("), QMessageBox.Ok)
         for tile in self.mineSweeper:
             tile.delegate.marked = False
         self.mineSweeper.reset()
Exemple #33
0
 def round(self, tile: TicTacToe.Tile):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     self.player.tile = tile
     score = self.ticTacToe.round(True)
     QApplication.restoreOverrideCursor()
     if score is not None:
         if score == +1:
             QMessageBox.information(self, self.tr("Victory!"), self.tr("You won :)"), QMessageBox.Ok)
         if score == 0:
             QMessageBox.warning(self, self.tr("Tie!"), self.tr("You tied :|"), QMessageBox.Ok)
         if score == -1:
             QMessageBox.critical(self, self.tr("Defeat!"), self.tr("You lost :("), QMessageBox.Ok)
         self.ticTacToe.reset(True)
Exemple #34
0
 def round(self, disc: FourPlay.Disc):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     self.player.disc = disc
     score = self.fourPlay.round(True)
     QApplication.restoreOverrideCursor()
     if score is not None:
         if score == +1:
             QMessageBox.information(self, self.tr("Victory!"), self.tr("You won :)"), QMessageBox.Ok)
         if score == 0:
             QMessageBox.warning(self, self.tr("Tie!"), self.tr("You tied :|"), QMessageBox.Ok)
         if score == -1:
             QMessageBox.critical(self, self.tr("Defeat!"), self.tr("You lost :("), QMessageBox.Ok)
         self.fourPlay.reset(True)
    def readFromFile(self, filename):
        """ Read contacts in from a file. """
        try:
            f = open(filename, "rb")
            addresses = pickle.load(f)
        except IOError:
            QMessageBox.information(self, "Unable to open file: %s" % filename)
        finally:
            f.close()

        if len(addresses) == 0:
            QMessageBox.information(self, "No contacts in file: %s" % filename)
        else:
            for address in addresses:
                self.addEntry(address["name"], address["address"])
    def addEntry(self, name=None, address=None):
        """ Add an entry to the addressbook. """
        if name is None and address is None:
            addDialog = AddDialogWidget()

            if addDialog.exec_():
                name = addDialog.name
                address = addDialog.address

        address = {"name": name, "address": address}
        addresses = self.tableModel.addresses[:]

        # The QT docs for this example state that what we're doing here
        # is checking if the entered name already exists. What they
        # (and we here) are actually doing is checking if the whole
        # name/address pair exists already - ok for the purposes of this
        # example, but obviously not how a real addressbook application
        # should behave.
        try:
            addresses.remove(address)
            QMessageBox.information(self, "Duplicate Name",
                                    "The name \"%s\" already exists." % name)
        except ValueError:
            # The address didn't already exist, so let's add it to the model.

            # Step 1: create the  row
            self.tableModel.insertRows(0)

            # Step 2: get the index of the newly created row and use it.
            # to set the name
            ix = self.tableModel.index(0, 0, QModelIndex())
            self.tableModel.setData(ix, address["name"], Qt.EditRole)

            # Step 3: lather, rinse, repeat for the address.
            ix = self.tableModel.index(0, 1, QModelIndex())
            self.tableModel.setData(ix, address["address"], Qt.EditRole)

            # Remove the newAddressTab, as we now have at least one
            # address in the model.
            self.removeTab(self.indexOf(self.newAddressTab))

            # The screenshot for the QT example shows nicely formatted
            # multiline cells, but the actual application doesn't behave
            # quite so nicely, at least on Ubuntu. Here we resize the newly
            # created row so that multiline addresses look reasonable.
            tableView = self.currentWidget()
            tableView.resizeRowToContents(ix.row())
Exemple #37
0
    def openPort(self):
        if self.serialport.isOpen():
            return

        _port = self.GetPort()
        if '' == _port:
            QMessageBox.information(self, "Invalid parameters", "Port is empty.")
            return

        _baudrate = self.cmbBaudRate.currentText()
        if '' == _baudrate:
            QMessageBox.information(self, "Invalid parameters", "Baudrate is empty.")
            return

        self.serialport.port     = _port
        self.serialport.baudrate = _baudrate
        self.serialport.bytesize = self.GetDataBits()
        self.serialport.stopbits = self.GetStopBits()
        self.serialport.parity   = self.GetParity()
        self.serialport.rtscts   = self.chkRTSCTS.isChecked()
        self.serialport.xonxoff  = self.chkXonXoff.isChecked()
        # self.serialport.timeout  = THREAD_TIMEOUT
        # self.serialport.writeTimeout = SERIAL_WRITE_TIMEOUT
        try:
            self.serialport.open()
        except serial.SerialException as e:
            QMessageBox.critical(self, "Could not open serial port", str(e),
                QMessageBox.Close)
        else:
            self._start_reader()
            self.setWindowTitle("%s on %s [%s, %s%s%s%s%s]" % (
                appInfo.title,
                self.serialport.portstr,
                self.serialport.baudrate,
                self.serialport.bytesize,
                self.serialport.parity,
                self.serialport.stopbits,
                self.serialport.rtscts and ' RTS/CTS' or '',
                self.serialport.xonxoff and ' Xon/Xoff' or '',
                )
            )
            pal = self.btnOpen.palette()
            pal.setColor(QtGui.QPalette.Button, QtGui.QColor(0,0xff,0x7f))
            self.btnOpen.setAutoFillBackground(True)
            self.btnOpen.setPalette(pal)
            self.btnOpen.setText('Close')
            self.btnOpen.update()
Exemple #38
0
    def mousePressEvent(self, mouseEvent: QMouseEvent):
        closestNode = self.playerNode.closest(mouseEvent.pos() - self.paintOffset)
        direction = closestNode.row - self.playerNode.row, closestNode.column - self.playerNode.column
        crawlNode = self.playerNode.crawl(direction)

        self.animation = QPropertyAnimation(self, b"player", self)
        if len(crawlNode.links) > 2:
            self.animation.setEasingCurve(QEasingCurve.OutBack);
        else:
            self.animation.setEasingCurve(QEasingCurve.OutBounce);
        self.animation.setStartValue(self.player)
        self.animation.setEndValue(crawlNode.point)
        self.animation.setDuration(400)
        self.animation.start()

        self.playerNode = crawlNode
        if self.playerNode == self.finishNode:
            QMessageBox.information(self, self.tr("Victory!"), self.tr("You won :)"), QMessageBox.Ok)
            self.initMaze()
    def displayError(self, socketError, message):
        if socketError == QAbstractSocket.HostNotFoundError:
            QMessageBox.information(self, "Blocking Fortune Client",
                    "The host was not found. Please check the host and port "
                    "settings.")
        elif socketError == QAbstractSocket.ConnectionRefusedError:
            QMessageBox.information(self, "Blocking Fortune Client",
                    "The connection was refused by the peer. Make sure the "
                    "fortune server is running, and check that the host name "
                    "and port settings are correct.")
        else:
            QMessageBox.information(self, "Blocking Fortune Client",
                    "The following error occurred: %s." % message)

        self.getFortuneButton.setEnabled(True)
Exemple #40
0
def main():
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    QMessageBox.information(None, "Info", "Just drag and drop the items.")
    sys.exit(app.exec_())
 def show_help(self):
     QMessageBox.information(self, "Dynamic Layouts Help",
                         "This example shows how to change layouts "
                         "dynamically.")