Esempio n. 1
1
 def provideAuthentication(self, reply, auth):
     username = QInputDialog.getText(None, "Authentication", "Enter your username:"******"Authentication", "Enter your password:", QLineEdit.Password)
         if password[1]:
             auth.setPassword(password[0])
Esempio n. 2
0
    def connect(self):
        if self.connected:
            self.revert()
            self.client.disconnect()
            return

        try:
            login, login_ok = QInputDialog.getText(self, 'Логин', 'Введите логин:')
            if login_ok:
                passwd, password_ok = QInputDialog.getText(self, 'Пароль', 'Введите пароль:', 2)
                if password_ok:
                    server_item = self.serverList.currentItem()
                    try:
                        address = server_item.text().split(":")
                    except:
                        # server_item = self.serverList.findItems('', 0)[0]
                        self.serverList.setCurrentRow(0)
                        server_item = self.serverList.currentItem()
                        address = server_item.text().split(":")
                    if self.client.connect_to_server(address, login, passwd):
                        self.connectButton.setText("Отключиться")
                        self.connected = True
                    else:
                        self.critical("Неверный логин или пароль!", log=False)
                        # mb = QMessageBox.critical(self, "Ошибка", "Неверный логин или пароль!")

        except TimeoutError:
            self.critical("Сервер перестал отвечать")
Esempio n. 3
0
 def loguj(self):
     login, ok = QInputDialog.getText(self, "Logowanie", "Podaj login:"******"Logowanie", "Podaj haslo:")
         if ok:
             if not login or not haslo:
                 QMessageBox.warning(self, "Błąd", "Pusty login lub hasło!", QMessageBox.Ok)
                 return
             QMessageBox.information(self, "Dane logowania", "Podano: " + login + " " + haslo, QMessageBox.Ok)
Esempio n. 4
0
 def pull_split_queue(self):
     mb = QMessageBox()
     ind = QInputDialog()
     
     mb.information(self, "Breeze Software", "Please make sure that you have your Kornit Software open and running.", mb.Ok)
     
     queueNumber, ok = ind.getText(self, "Queue Number", "Please enter queue number.")
     if ok and queueNumber:
         queueNumber = queueNumber.lstrip("0")
         
         firstOrder, ok = ind.getText(self, "Starting Order", "Optional - please enter the beginning order number.")
         if not firstOrder: firstOrder = 1
         
         machineNumber, ok = ind.getInt(self, "Machine Number", "Please enter machine number", 1, 1, 9, 1)
             
         clearHF = mb.question(self, "Hot Folder", "Do you want to clear all the items in the hot folder?", mb.Yes | mb.No, mb.Yes)
     
         if clearHF == mb.Yes:
             dirPath = "C:/HotFolder"
             fileList = os.listdir(dirPath)
             for filename in fileList:
                 item = os.path.join(dirPath,filename)
                 if os.path.isfile(item): 
                     os.remove(item)         
         
         QMessageBox.information(self, 'Pulling Down', 'Your queue should show up in QuickP shortly.')            
         
         front = len(str(machineNumber)) + len(str(queueNumber))+2
         back = len(str(firstOrder)) + front
         
         dir_lst = os.listdir("//qserver/Breeze Artwork Storage/SplitQueues")
         counts = Counter(dir_lst)
                     
         for file in dir_lst:
             if file[:len(str(machineNumber)+"_"+queueNumber)] == str(machineNumber)+"_"+queueNumber and file[front:-(len(file) - back)] >= str(firstOrder):
                 type = file.split("_")
             
                 queue = type[1]
                 order = type[2]
                 skuName = type[3]
                 db = type[4]
                 sizeGarment = type[5]
                 skuType = type[6]
                 printType = type[7]
                 qty = type[8]
                 pos1 = type[9]
                 ext = type[10]
                 
                 fileName = skuType+"_"+printType+"_"+queue+"."+order+"."+skuName+"."+db+"."+sizeGarment+"."+qty+"_"+qty+"_"+pos1+"_"+ext                    
                 shutil.copy(os.path.join("//qserver/Breeze Artwork Storage/SplitQueues", file), os.path.join("c:\HotFolder", fileName))
                 #shutil.copy(os.path.join("//qserver/Breeze Artwork Storage/Test", file), os.path.join("//qserver/BreezeSplitQueues", file))                                        
     elif ok and not queueNumber:
         mb.critical(self, "No Queue Number", "Must enter queue number to continue.")
         if ok == True:
             self.pull_split_queue()
Esempio n. 5
0
 def addSearch(self):
     if "%s" in self.expEntry.text():
         name = QInputDialog.getText(self, tr('Query'), tr('Enter a name here:'))
         if name[1] and name[0] != "":
             name = name[0]
             keyword = QInputDialog.getText(self, tr('Query'), tr('Enter a keyword here:'))[0]
             self.searchManager.add(name, self.expEntry.text(), keyword)
             self.expEntry.clear()
         self.reload_()
     else:
         QMessageBox.warning(self, tr('Error'), tr('Search expression must contain a <b>%s</b> to indicate the search terms.'))
Esempio n. 6
0
 def LogIn(self):
     self.user = Auth(self.login.displayText(), self.password.displayText())
     if self.user.getError() is "UserNotFound":
         text, ok = QInputDialog.getText(self, 'ERROR', 'Enter your name:')
         if ok:
             self.login.setText(str(text))
     elif Auth(self.login.displayText(), self.password.displayText()).getError() is "IncorrectPassword":
         pass
         text, ok = QInputDialog.getText(self, 'ERROR', 'Enter your password:')
         if ok:
             self.password.setText(str(text))
     else:
         return self.user and self.close()
Esempio n. 7
0
 def addWebsite(self):
     # get the site name that the user wants
     website, ok = QInputDialog.getText(self, 'Enter Website', 'Enter the NEW website:')
     # show the site
     self.textEdit.setText(website)
     # get the password
     unencryptedPassword, ok = QInputDialog.getText(self, 'Enter Password', 'Enter the site password:')
     # encrypt the new password
     encryptedPassword = passwordEncrypt(unencryptedPassword, encryptionKey)
     self.textEdit.append("PASSWORD ACCEPTED")
     # create a size 2 list
     tempList = [website, encryptedPassword]
     # append the tempList to the password list
     passwords.append(tempList)
Esempio n. 8
0
 def DeletePass(self):
     # get the website
     userWebsite, ok = QInputDialog.getText(self, 'Enter Website', 'Enter the website to DELETE:')
     # update the user with info
     self.textEdit.setText("Thank you we have the website")
     self.textEdit.append(userWebsite)
     # get the password for the website from the user
     userPassword, ok = QInputDialog.getText(self, 'Enter Password', 'Enter the website Password:')
     # flip through the password list again (probably should have saved this meh, we got ram)
     for x, y in enumerate(passwords): # could have used (for i in passwords) again trying out enumerate
         if y[0] == userWebsite:
             if y[1] == passwordEncrypt(userPassword, encryptionKey):
                 # Delete the website and password from our list
                 passwords.remove([userWebsite, passwordEncrypt(userPassword, encryptionKey)])
                 self.textEdit.setText("We found and deleted the site and password")
Esempio n. 9
0
    def openTorrentFromURL(self):
        URL, ok = QInputDialog.getText(self, "Enter torrent URL",
                                       "URL of .torrent file:",)

        if ok and URL:
            torrentInfo = InfoGetter.get_bytes_from_URL(URL)
            self.configureTorrent(torrentInfo)
Esempio n. 10
0
    def create_dir(self, *args):
        """
        Create a new directory as a sibling (if the clicked item was a
        file) or child (if it was a folder) of the target of the last
         context-menu event, and open its name-editor.
        :param args:
        """

        # self.LOGGER << "create_dir()"
        fsmod = self.modfsmodel

        if fsmod._isdir(self.rclicked_inode):
            parent = fsmod.inode2path(self.rclicked_inode)
        else:
            parent = fsmod.inode2path(self.rclicked_inode).parent

        startname = "New Folder"

        # make sure it's unique
        parent_ls = parent.ls(conv=str.lower)
        suffix = 0
        while startname.lower() in parent_ls:
            suffix += 1
            startname = "New Folder %d" % suffix

        # noinspection PyArgumentList,PyTypeChecker
        new_name = QInputDialog.getText(self, "New Folder", "Create new folder in:\n{}".format(parent), text=startname)[
            0
        ]

        if new_name:
            fsmod.create_new_dir(parent, new_name)
Esempio n. 11
0
 def word_dialog(self, msg):
     response = QInputDialog.getText(self.top_level_window(), "Ledger Wallet Authentication", msg, QLineEdit.Password)
     if not response[1]:
         self.word = None
     else:
         self.word = str(response[0])
     self.done.set()
Esempio n. 12
0
    def showDialog(self):

        text, ok = QInputDialog.getText(self, 'input dialog',
            'enter your name:')

        if ok:
            self.le.setText(str(text))
Esempio n. 13
0
 def on_renameButton_clicked(self):
     """
     Private slot to rename the selected identity.
     """
     currentIdentity = self.identitiesCombo.currentText()
     name, ok = QInputDialog.getText(
         self,
         self.tr("Rename Identity"),
         self.tr("Identity Name:"),
         QLineEdit.Normal,
         currentIdentity)
     
     if ok and name != currentIdentity:
         if name:
             if name in self.__identities:
                 E5MessageBox.critical(
                     self,
                     self.tr("Rename Identity"),
                     self.tr(
                         """An identity named <b>{0}</b> already exists."""
                         """ You must provide a different name.""").format(
                         name))
                 self.on_renameButton_clicked()
             else:
                 del self.__identities[currentIdentity]
                 self.__currentIdentity.setName(name)
                 self.__identities[name] = self.__currentIdentity
                 self.identitiesCombo.setItemText(
                     self.identitiesCombo.currentIndex(), name)
         else:
             E5MessageBox.critical(
                 self,
                 self.tr("Copy Identity"),
                 self.tr("""The identity has to have a name."""))
             self.on_renameButton_clicked()
Esempio n. 14
0
    def finishQueue(self):
        queueNumber, ok = QInputDialog.getText(self, 'Enter Queue', 'Please scan or enter queue:')

        if ok:
            ImportExportDB.insertQueuePrinted(self, queueNumber)
            QMessageBox.information(self, 'Queue finished', 'You\'re queue as been marked complete.',
                                        QMessageBox.Close)        
Esempio n. 15
0
 def open_game_file(self, game_file):
     """Open a Game file."""
     if not os.path.isfile(game_file):
         game_file = str(QFileDialog.getOpenFileName(
             self, __doc__ + "- Open Blender Game", os.path.expanduser("~"),
             "Blender Game Engine file (*.blend)")[0]).strip()
         if game_file and os.path.isfile(game_file):
             return game_file
         else:
             return
     elif game_file.lower().endswith(".blend"):
         return game_file
     elif game_file.lower().endswith(".zip"):
         if not len(PASSWORD):
             pwd = QInputDialog.getText(self, __doc__, "Game SerialKey")[0]
         else:
             pwd = codecs.decode(PASSWORD, "rot13")
         try:
             with ZipFile(game_file, "r") as zipy:
                 zipy.setpassword(str(pwd))
                 # zipy.setpassword(PASSWORD)
                 if zipy.testzip():
                     zipy.extractall()
                     zipy.close()
                     return game_file.replace(".zip", ".blend")
         except Exception as e:
             log.warning(e)
Esempio n. 16
0
    def _onRename(self):
        """Handler for File->File System->Rename"""
        document = core.workspace().currentDocument()
        if document.qutepart.document().isModified() or \
           document.isExternallyModified() or \
           document.isExternallyRemoved() or \
           document.isNeverSaved():
            QMessageBox.warning(core.mainWindow(), 'Rename file', 'Save the file before renaming')
            return

        newPath, ok = QInputDialog.getText(core.mainWindow(), 'Rename file', 'New file name', text=document.filePath())
        if not ok:
            return

        if newPath == document.filePath():
            return

        if newPath == '/dev/null':
            try:
                os.remove(document.filePath())
            except (OSError, IOError) as ex:
                QMessageBox.critical(core.mainWindow(), 'Not this time', 'The OS thinks it needs the file')
            else:
                core.workspace().closeDocument(document)
        else:
            try:
                os.rename(document.filePath(), newPath)
            except (OSError, IOError) as ex:
                QMessageBox.critical(core.mainWindow(), 'Failed to rename file', str(ex))
            else:
                document.setFilePath(newPath)
                document.saveFile()
Esempio n. 17
0
 def on_addButton_clicked(self):
     """
     Private slot to add a new idntity.
     """
     name, ok = QInputDialog.getText(
         self,
         self.tr("Add Identity"),
         self.tr("Identity Name:"),
         QLineEdit.Normal)
     
     if ok:
         if name:
             if name in self.__identities:
                 E5MessageBox.critical(
                     self,
                     self.tr("Add Identity"),
                     self.tr(
                         """An identity named <b>{0}</b> already exists."""
                         """ You must provide a different name.""").format(
                         name))
                 self.on_addButton_clicked()
             else:
                 identity = IrcIdentity(name)
                 identity.setIdent(Utilities.getUserName())
                 identity.setRealName(Utilities.getRealName())
                 self.__identities[name] = identity
                 self.identitiesCombo.addItem(name)
                 self.identitiesCombo.setCurrentIndex(
                     self.identitiesCombo.count() - 1)
         else:
             E5MessageBox.critical(
                 self,
                 self.tr("Add Identity"),
                 self.tr("""The identity has to have a name."""))
             self.on_addButton_clicked()
Esempio n. 18
0
    def onResetMACTriggered(self):
        resetFlag = False
        mac,okPressed = QInputDialog.getText(self,"MAC状态重置","请输入MAC号:",QLineEdit.Normal, " ")
        if okPressed and mac.strip():
            print('mac:' + mac)
            logging.info('mac:' + mac)
            logging.info("\r\n")

            mysql = MySQLCommand(host=self.sysXMLDict['mysqlhost'],port=int(self.sysXMLDict['mysqlport']),user=self.sysXMLDict['mysqluser'],\
                             passwd=self.sysXMLDict['mysqlpassword'],db=self.sysXMLDict['mysqldatabase'],table=self.sysXMLDict['mysqltable'])
            mysqlConFlag = mysql.connectMysql()
            if not mysqlConFlag:
                self.mysqlConnectErrSignal.emit(MYSQL_CONNECT_ERROR)
                return

            self.lock.acquire()
            resetFlag = mysql.resetMysqlMACStatusAndSN(mac=mac,stbType=self.sysXMLDict['mysqlstbtype'],poNumber=self.poNumber)
            if resetFlag:
                QMessageBox.information(self,SUCCESSTITLE,RESET_MAC_SUCCESS)
            else:
                QMessageBox.critical(self,ERRORTITLE,RESET_MAC_FAILED)

            self.lock.release()
            mysql.closeMysql()

        else:
            QMessageBox.critical(self,ERRORTITLE,RESET_MAC_INFO)
Esempio n. 19
0
 def addRule(self, filter=""):
     """
     Public slot to add a new rule.
     
     @param filter filter to be added (string)
     """
     if not self.__subscription.canEditRules():
         return
     
     if not filter:
         filter = QInputDialog.getText(
             self,
             self.tr("Add Custom Rule"),
             self.tr("Write your rule here:"),
             QLineEdit.Normal)
         if filter == "":
             return
     
     from .AdBlockRule import AdBlockRule
     rule = AdBlockRule(filter, self.__subscription)
     offset = self.__subscription.addRule(rule)
     
     item = QTreeWidgetItem()
     item.setText(0, filter)
     item.setData(0, Qt.UserRole, offset)
     item.setFlags(item.flags() | Qt.ItemIsEditable)
     
     self.__itemChangingBlock = True
     self.__topItem.addChild(item)
     self.__itemChangingBlock = False
     
     self.__adjustItemFeatures(item, rule)
Esempio n. 20
0
 def on_newButton_clicked(self):
     """
     Private slot to create a new toolbar.
     """
     name, ok = QInputDialog.getText(
         self,
         self.tr("New Toolbar"),
         self.tr("Toolbar Name:"),
         QLineEdit.Normal)
     if ok and name:
         if self.toolbarComboBox.findText(name) != -1:
             # toolbar with this name already exists
             E5MessageBox.critical(
                 self,
                 self.tr("New Toolbar"),
                 self.tr(
                     """A toolbar with the name <b>{0}</b> already"""
                     """ exists.""")
                 .format(name))
             return
         
         tbItem = E5ToolBarItem(None, [], False)
         tbItem.title = name
         tbItem.isChanged = True
         self.__toolbarItems[id(tbItem)] = tbItem
         self.__toolBarItemToWidgetActionID[id(tbItem)] = []
         self.toolbarComboBox.addItem(name, int(id(tbItem)))
         self.toolbarComboBox.model().sort(0)
         self.toolbarComboBox.setCurrentIndex(
             self.toolbarComboBox.findText(name))
Esempio n. 21
0
 def on_renameButton_clicked(self):
     """
     Private slot to rename a custom toolbar.
     """
     oldName = self.toolbarComboBox.currentText()
     newName, ok = QInputDialog.getText(
         self,
         self.tr("Rename Toolbar"),
         self.tr("New Toolbar Name:"),
         QLineEdit.Normal,
         oldName)
     if ok and newName:
         if oldName == newName:
             return
         if self.toolbarComboBox.findText(newName) != -1:
             # toolbar with this name already exists
             E5MessageBox.critical(
                 self,
                 self.tr("Rename Toolbar"),
                 self.tr(
                     """A toolbar with the name <b>{0}</b> already"""
                     """ exists.""")
                 .format(newName))
             return
         index = self.toolbarComboBox.currentIndex()
         self.toolbarComboBox.setItemText(index, newName)
         tbItem = \
             self.__toolbarItems[self.toolbarComboBox.itemData(index)]
         tbItem.title = newName
         tbItem.isChanged = True
    def _rename_file(self):
        item = self.currentItem()
        if item.parent() is None:
            pathForFile = item.path
        else:
            pathForFile = os.path.join(item.path, item.text(0))
        result = QInputDialog.getText(self, _translate("TreeProjectsWidget", "Rename File"),
                          _translate("TreeProjectsWidget", "Enter New File Name:"), text=item.text(0))
        fileName = result[0]

        if result[1] and fileName.strip() != '':
            fileName = os.path.join(
                file_manager.get_folder(pathForFile), fileName)
            if pathForFile == fileName:
                return
            try:
                fileName = file_manager.rename_file(pathForFile, fileName)
                name = file_manager.get_basename(fileName)
                mainContainer = main_container.MainContainer()
                if mainContainer.is_open(pathForFile):
                    mainContainer.change_open_tab_name(pathForFile, fileName)
                subitem = ProjectItem(item.parent(), name,
                                      file_manager.get_folder(fileName))
                subitem.setToolTip(0, name)
                subitem.setIcon(0, self._get_file_icon(name))
                index = item.parent().indexOfChild(item)
                subitem.parent().takeChild(index)
            except file_manager.NinjaFileExistsException as ex:
                QMessageBox.information(self, _translate("TreeProjectsWidget", "File Already Exists"),
                    (_translate("TreeProjectsWidget", "Invalid Path: the file '%s' already exists.") %
                     ex.filename))
 def _copy_file(self):
     #get the selected QTreeWidgetItem
     item = self.currentItem()
     if item.parent() is None:
         pathForFile = item.path
     else:
         pathForFile = os.path.join(item.path, item.text(0))
     pathProjects = [p.path for p in self.get_open_projects()]
     addToProject = ui_tools.AddToProject(pathProjects, self)
     addToProject.setWindowTitle(_translate("TreeProjectsWidget", "Copy File to"))
     addToProject.exec_()
     if not addToProject.pathSelected:
         return
     name = QInputDialog.getText(self, _translate("TreeProjectsWidget", "Copy File"),
                                 _translate("TreeProjectsWidget", "File Name:"), text=item.text(0))[0]
     if not name:
         QMessageBox.information(self, _translate("TreeProjectsWidget", "Invalid Name"),
                     _translate("TreeProjectsWidget", "The file name is empty, please enter a name"))
         return
     path = file_manager.create_path(addToProject.pathSelected, name)
     try:
         content = file_manager.read_file_content(pathForFile)
         path = file_manager.store_file_content(path, content, newFile=True)
         self.add_existing_file(path)
     except file_manager.NinjaFileExistsException as ex:
             QMessageBox.information(self, _translate("TreeProjectsWidget", "File Already Exists"),
                 (_translate("TreeProjectsWidget", "Invalid Path: the file '%s' already exists.") %
                  ex.filename))
Esempio n. 24
0
    def openUrl(self):
        url, ok = QInputDialog.getText(self, "Enter a URL", "URL:",
                QLineEdit.Normal, "http://")

        if ok and url:
            url = QUrl(url)
            self.centralWidget.webView.setUrl(url)
    def _add_new_file(self):
        item = self.currentItem()
        if item.parent() is None:
            pathForFile = item.path
        else:
            pathForFile = os.path.join(item.path, item.text(0))
        result = QInputDialog.getText(self, _translate("TreeProjectsWidget", "New File"),
                                      _translate("TreeProjectsWidget", "Enter the File Name:"))
        fileName = result[0]

        if result[1] and fileName.strip() != '':
            try:
                fileName = os.path.join(pathForFile, fileName)
                fileName = file_manager.store_file_content(
                    fileName, '', newFile=True)
                name = file_manager.get_basename(fileName)
                subitem = ProjectItem(item, name, pathForFile)
                subitem.setToolTip(0, name)
                subitem.setIcon(0, self._get_file_icon(name))
                mainContainer = main_container.MainContainer()
                mainContainer.open_file(fileName)
            except file_manager.NinjaFileExistsException as ex:
                QMessageBox.information(self, _translate("TreeProjectsWidget", "File Already Exists"),
                    (_translate("TreeProjectsWidget", "Invalid Path: the file '%s' already exists.") %
                     ex.filename))
Esempio n. 26
0
File: qt.py Progetto: P4ncake/weboob
 def __call__(self):
     password, ok = QInputDialog.getText(None,
         '%s request' % self.value.label,
         'Please enter %s for %s' % (self.value.label,
                                     self.backend_name),
                                         QLineEdit.Password)
     return password
Esempio n. 27
0
    def RenameToolBar(self):
        flags = Qt.Window | Qt.WindowCloseButtonHint
        text, ok = QInputDialog.getText(self, 'ToolBar Name', 'Enter new Toolbar name.', flags=flags)
        if ok:
            if text == "":
                self.iface.messageBar().pushMessage("Error: ", "Enter Toolbar name.", level=QGis.Critical, duration=3)
                return 

            item = self.MyToolsBars.currentItem()
            text_old = item.text(self.MyToolsBars.currentColumn())

            # Rename the toolbar in the iface
            toolbars = self.iface.mainWindow().findChildren(QToolBar)
            for toolbar in toolbars:
                if toolbar.windowTitle() == text_old:
                    toolbar.setWindowTitle(text)

            item.setText(self.MyToolsBars.currentColumn(), text)
            self.hasChanged = True

            for key, value in self.restore.items():
                if text_old == value:
                    self.restore[key] = text
                    return

            self.restore[text_old] = text

        return
Esempio n. 28
0
    def onBackupDBTriggered(self):

        self.checkMysqldumpTool()

        backupFlag = True
        fileName,okPressed = QInputDialog.getText(self,"数据库备份","请输入文件名:",QLineEdit.Normal, "dbback.sql")
        if okPressed and fileName.strip():
            print('DBBackupFile:' + fileName)
            logging.info('DBBackupFile:' + fileName)

            logging.info("\r\n")

            command = 'mysqldump -u' + self.sysXMLDict['mysqluser'] + ' -h ' + self.sysXMLDict['mysqlhost'] + ' -p' + self.sysXMLDict['mysqlpassword'] \
                        + ' ' + self.sysXMLDict['mysqldatabase'] + ' ' + self.sysXMLDict['mysqltable'] + '>' + fileName
            print(command)
            logging.info("Backup DB command: " + command)

            process = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
            for line in process.stdout.readlines():
                if str(line).count('error'):
                    backupFlag = False
                    break

            process.wait()

            if backupFlag:
                QMessageBox.information(self,SUCCESSTITLE,MYSQL_BACKUP_SUCCESS)
            else:
                QMessageBox.critical(self,ERRORTITLE,MYSQL_BACKUP_FAILED)

        else:
            QMessageBox.critical(self,ERRORTITLE,MYSQL_INFO_BACKUP)
Esempio n. 29
0
    def playerComboCall(self, idx):
        if idx == self.ui.playerCombo.count()-1:
            newName, ok = QInputDialog.getText(self,'Add New Player','Enter a new player name')
            if newName == '' or not ok:
                return
            if newName in self.playerData.keys():
                QMessageBox.information(self, 'Player exists', 'The player %s already exists' % (newName))

            newCfg = mathConfig.mathConfig()
            newCfg['lastPlayer'] = True
            for k in self.playerData.keys():
                self.playerData[k]['lastPlayer'] = False
            self.playerData[newName] = newCfg
            self.populatePlayerCombo()
            self.setupPlayer(newName)
        else:
            newName = self.ui.playerCombo.itemText(idx)
            if newName == self.currentPlayer:
                return
            for k in self.playerData.keys():
                if newName == k:
                    self.playerData[newName]['lastPlayer'] = True
                else:
                    self.playerData[newName]['lastPlayer'] = False

            self.setupPlayer(newName)
        self.saveSettings()
Esempio n. 30
0
 def add_item(self):
     text, ok = QInputDialog.getText(self, 'Add Component Reference', 'Enter Component Reference Pattern')
     if ok:
         self.addItem(text)
         print(self.count())
         
     print(self.data_list())
    def cut(self):
        fl = False
        # Получение значения для левого верхнего угла
        while True:
            val, ok_btn_pressed = QInputDialog.getText(
                self, 'Обрезать', 'Введите координаты левого верхнего угла'
                ' в формате: x;y')
            if ok_btn_pressed:
                if ';' not in val:
                    QMessageBox.question(
                        self, 'Предупреждение', 'x и y, указанные в '
                        'диалоговом окне, должны быть '
                        'разделены этим символом: ";"', QMessageBox.Ok,
                        QMessageBox.Ok)
                elif len(val.split(';')) > 2:
                    QMessageBox.question(
                        self, 'Предупреждение',
                        'Должно быть введено ТОЛЬКО два '
                        'аргумента. Разве это так сложно?', QMessageBox.Ok,
                        QMessageBox.Ok)
                else:
                    try:
                        val = [int(item) for item in val.split(';')]
                        x_min, y_min = val
                        fl = True
                        break
                    except Exception as e:
                        QMessageBox.question(self, 'Предупреждение', str(e),
                                             QMessageBox.Ok, QMessageBox.Ok)
            else:
                break

        # Получение значения для правого нижнего и последующая обрезка
        # изображения
        if fl:
            while True:
                val, ok_btn_pressed = QInputDialog.getText(
                    self, 'Обрезать',
                    'Введите координаты правого нижнего угла '
                    'в формате: x;y')
                if ok_btn_pressed:
                    if ';' not in val:
                        QMessageBox.question(
                            self, 'Предупреждение', 'x и y, указанные в '
                            'диалоговом окне, должны быть '
                            'разделены этим символом: ";"', QMessageBox.Ok,
                            QMessageBox.Ok)
                    elif len(val.split(';')) > 2:
                        QMessageBox.question(
                            self, 'Предупреждение', 'Должно быть введено'
                            ''
                            'ТОЛЬКО два аргумента. '
                            'Разве это так сложно?', QMessageBox.Ok,
                            QMessageBox.Ok)
                    else:
                        try:
                            val = [int(item) for item in val.split(';')]
                            x_max, y_max = val
                            self.load_image = self.load_image.crop(
                                (x_min, y_min, x_max, y_max))
                            self.temp_image()
                            break
                        except Exception as e:
                            QMessageBox.question(self, 'Предупреждение',
                                                 str(e), QMessageBox.Ok,
                                                 QMessageBox.Ok)
                else:
                    break
Esempio n. 32
0
    def afterPushButtonPressed(self, button):

        self.after_pushButton.setEnabled(False)

        # For Linux and Mac OSX and FreeBSD and OpenBSD
        if os_type != OS.WINDOWS:

            # get root password
            passwd, ok = QInputDialog.getText(self, 'PassWord',
                                              'Please enter root password:'******'sudo', '-S', 'echo', 'hello'],
                                        stdout=subprocess.DEVNULL,
                                        stdin=subprocess.PIPE,
                                        stderr=subprocess.DEVNULL,
                                        shell=False)

                pipe.communicate(passwd.encode())

                answer = pipe.wait()

                # Wrong password
                while answer != 0:

                    passwd, ok = QInputDialog.getText(
                        self, 'PassWord', 'Wrong Password!\nPlease try again.',
                        QLineEdit.Password)

                    if ok:

                        pipe = subprocess.Popen(
                            ['sudo', '-S', 'echo', 'hello'],
                            stdout=subprocess.DEVNULL,
                            stdin=subprocess.PIPE,
                            stderr=subprocess.DEVNULL,
                            shell=False)

                        pipe.communicate(passwd.encode())

                        answer = pipe.wait()

                    else:
                        ok = False
                        break

                if ok != False:

                    # if user selects shutdown option after download progress,
                    # value of 'shutdown' will changed in temp_db for this progress
                    # and "wait" word will be written for this value.
                    # (see ShutDownThread and shutdown.py for more information)
                    # shutDown method will check that value in a loop .
                    # when "wait" changes to "shutdown" then shutdown.py script
                    # will shut down the system.

                    shutdown_enable = ShutDownThread(
                        self.parent, self.video_finder_plus_gid, passwd)
                    self.parent.threadPool.append(shutdown_enable)
                    self.parent.threadPool[len(self.parent.threadPool) -
                                           1].start()

                else:
                    self.after_checkBox.setChecked(False)
            else:
                self.after_checkBox.setChecked(False)

        else:
            # for Windows
            for gid in self.gid_list:
                shutdown_enable = ShutDownThread(self.parent,
                                                 self.video_finder_plus_gid)
                self.parent.threadPool.append(shutdown_enable)
                self.parent.threadPool[len(self.parent.threadPool) - 1].start()
Esempio n. 33
0
 def create_room(self):
     text, ok = QInputDialog.getText(self, NEW_ROOM, NEW_ROOM_ENTER_NAME)
     if ok:
         body = {MESSAGE_ACTION_NEW_ROOM_ROOM_NAME: text}
         self.client.create_room(body=body)
Esempio n. 34
0
 def getText(self):
     text, okPressed = QInputDialog.getText(self, "Give file_name",
                                            "File Name:", QLineEdit.Normal,
                                            "s5t1c1.txt")
     if okPressed and text != '':
         return text
Esempio n. 35
0
 def new_project(self):
     name, okPressed = QInputDialog.getText(self, "New Project", "Prject Name:", QLineEdit.Normal, "")
     if okPressed and name != '':
         subprocess.call(f'composer create-project --prefer-dist laravel/laravel=5.8 {name}',
                         cwd=re.escape(self.path), shell=True)
         self.selected.emit(f'{self.path}/{name}')
Esempio n. 36
0
 def _newLayout(self):
     title = tr("New Layout")
     msg = tr("Choose a name for your new layout:")
     name, ok = QInputDialog.getText(self, title, msg)
     if ok and name:
         self.model.new_layout(name)
Esempio n. 37
0
 def show_dialog(self):
     text, ok = QInputDialog.getText(self, '输入的对话框', 'Enter your name:')
     if ok:
         self.le.setText(str(text))
    def on_btnSshReadRpcConfig_clicked(self):
        """Read the configuration of a remote RPC node from the node's polis.conf file."""
        if self.current_network_cfg:
            host = self.current_network_cfg.ssh_conn_cfg.host
            port = self.current_network_cfg.ssh_conn_cfg.port
            username = self.current_network_cfg.ssh_conn_cfg.username
            if not host:
                self.errorMsg('Host address is required')
                self.ssh_tunnel_widget.edtSshHost.setFocus()
            if not port:
                self.errorMsg('Host TCP port number is required')
                self.ssh_tunnel_widget.edtSshHost.setFocus()

            ok = True
            if not username:
                username, ok = QInputDialog.getText(
                    self, 'Username Dialog',
                    'Enter username for SSH connection:')
            if not ok or not username:
                return
            from polisd_intf import PolisdSSH
            ssh = PolisdSSH(host, int(port), username)
            try:
                ssh.connect()
                polisd_conf = ssh.find_polisd_config()
                self.disable_cfg_update = True
                if isinstance(polisd_conf, tuple) and len(polisd_conf) >= 3:
                    if not polisd_conf[0]:
                        self.infoMsg(
                            'Remore Polis daemon seems to be shut down')
                    elif not polisd_conf[1]:
                        self.infoMsg('Could not find remote polisd.conf file')
                    else:
                        file = polisd_conf[2]
                        rpcuser = file.get('rpcuser', '')
                        rpcpassword = file.get('rpcpassword', '')
                        rpcport = file.get('rpcport', '9998')
                        modified = False
                        if rpcuser:
                            modified = modified or (
                                self.current_network_cfg.username != rpcuser)
                            self.current_network_cfg.username = rpcuser
                        if rpcpassword:
                            modified = modified or (
                                self.current_network_cfg.password !=
                                rpcpassword)
                            self.current_network_cfg.password = rpcpassword
                        if rpcport:
                            modified = modified or (
                                self.current_network_cfg.port != rpcport)
                            self.current_network_cfg.port = rpcport
                        rpcbind = file.get('rpcbind', '')
                        if not rpcbind:  # listen on all interfaces if not set
                            rpcbind = '127.0.0.1'
                        modified = modified or (self.current_network_cfg.host
                                                != rpcbind)
                        self.current_network_cfg.host = rpcbind
                        if modified:
                            self.is_modified = modified

                        if file.get('server', '1') == '0':
                            self.warnMsg(
                                "Remote polis.conf parameter 'server' is set to '0', so RPC interface will "
                                "not work.")
                        if not rpcuser:
                            self.warnMsg(
                                "Remote polis.conf parameter 'rpcuser' is not set, so RPC interface will  "
                                "not work.")
                        if not rpcpassword:
                            self.warnMsg(
                                "Remote polis.conf parameter 'rpcpassword' is not set, so RPC interface will  "
                                "not work.")
                    self.update_connection_details_ui()
                elif isinstance(polisd_conf, str):
                    self.warnMsg(
                        "Couldn't read remote polisd configuration file due the following error: "
                        + polisd_conf)
                ssh.disconnect()
            except Exception as e:
                self.errorMsg(str(e))
                return
            finally:
                self.disable_cfg_update = False
Esempio n. 39
0
    def connect_to_server(self):

        print('Connecting to ' + self.server_type,
              ' server: tcp://' + self.server_ip + ':' + self.server_port)

        sm.ODS = client_type_evaluator(self.server_type)
        print('Original data source', sm.ODS.name)
        if self.server_ip:
            sm.ODS.client.ip = self.server_ip
        if self.server_port:
            sm.ODS.client.port = self.server_port

        sm.ODS.connect()

        # TODO: On successful connection store the input

        # Bring up the directory tree
        dt = sm.ODS.get_directory_tree()

        dir_tree_dialog = DirTreeDialog()
        dir_tree_dialog.dir_tree_widget.add_elemtens(dt.d)
        if dir_tree_dialog.exec():
            self.server_path = dir_tree_dialog.return_tree_widget_path()

        # TODO: check iit is a proper session item

        passwd, ok = QInputDialog.getText(self, "MEF password",
                                          "Please type MEF password")
        if ok:
            if not sm.ODS.set_file_handler(self.server_path, passwd):
                QMessageBox.warning(self, "Password incorrect",
                                    "The password is incorrect")
                return
        else:
            return

        # ----- Delete previous data -----

        # Delete any previous buffers
        if isinstance(sm.PDS, MemoryBuffer):
            sm.PDS.terminate_buffer()
            sm.PDS.terminate_monitor_thread()
            sm.PDS.purge_data()

        # Delete data from plugins to be able to open new data source
        for plugin in self.plugin_list:
            plugin.delete_plugin_data()

        # Delete data from signal_display
        self.signal_display.initialize_data_map()
        self.signal_display.update_signals()
        self.signal_display.data_array = None

        # -----

        self.statusBar().showMessage('Loading metadata')
        sm.ODS.load_metadata()
        self.statusBar().showMessage('Loading annotatios')
        # Try to get annotations
        if getattr(self, "annotations", None) is not None:
            if getattr(sm.ODS, "get_annotations", None) is not None:

                ann_groups = sm.ODS.get_annotations()

                for ann_group in ann_groups.items():
                    self.annotations.add_annotation_set(
                        ann_group[1], ann_group[0])

        # Fork for buffer usage

        if CONF.get('data_management', 'use_memory_buffer'):
            sm.PDS = MemoryBuffer(self)
        else:
            sm.PDS = sm.ODS

        self.source_opened = True
        self.add_path_to_title()
        self.sig_file_opened.emit()  # TODO change this to source opened
Esempio n. 40
0
    def createDataSensor(self):
        #Pilih IP
        list_host = []
        with open("list-host.txt") as f:
            for line in f:
                line = line.strip()
                list_host.append(line)

        self.host = QtWidgets.QLineEdit(self.layoutWidget2)
        self.host.move(130, 22)

        host, ok = QInputDialog.getItem(self.layoutWidget2,
                                        "Select Available IP", "List of IP",
                                        list_host, 0, False)

        if ok and host:
            self.host.setText(str(host))

        # Input IP kedalam variable hosts
        host = self.host.text()

        # Buat Inventory File untuk Hosts
        hosts_file = open("./ansible/hosts.ini", "w+")
        hosts_file.write(host)
        hosts_file.close()
        os.chdir("/home/taufiq/Documents/DATA/docker-management")

        protectedSubnet = self.protectedSubnetlineEdit.text()
        externalSubnet = self.externalSubnetlineEdit.text()
        mqttTopic = self.mqttTopiclineEdit.text()
        mqttIP = self.mqttBrokerIPlineEdit.text()
        mqttPort = self.mqttBrokerPortlineEdit.text()
        deviceID = self.deviceIDlineEdit.text()
        deviceName = self.deviceNamelineEdit.text()
        networkInterface = self.networkInterfacelineEdit.text()
        company = self.companylineEdit.text()
        communityChoice = str(self.communityradioButton.isChecked())
        registeredChoice = str(self.reisteredradioButton.isChecked())

        #Konfigurasi Pilihan User
        communityChoice = str(self.communityradioButton.isChecked())
        registeredChoice = str(self.reisteredradioButton.isChecked())
        if communityChoice == "True":
            ruleChoice = "1"

        if registeredChoice == "True":
            ruleChoice = "2"
            self.oinkcode = QtWidgets.QLineEdit(self.layoutWidget2)
            self.oinkcode.move(130, 22)

            text, ok = QInputDialog.getText(self.layoutWidget2,
                                            'Input oinkcode',
                                            'Enter your oinkcode :')
            if ok:
                self.oinkcode.setText(str(text))

            oinkcode = self.oinkcode.text()

        #Tambahkan data ke dalam database
        db = db_conn.cursor()
        db.execute(
            "INSERT INTO tb_sensor_env (protectedSubnet, externalSubnet, mqttTopic, mqttIP, mqttPort, deviceID, deviceName, networkInterface, company) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
            (protectedSubnet, externalSubnet, mqttTopic, mqttIP, mqttPort,
             deviceID, deviceName, networkInterface, company))

        db_conn.commit()

        #Tambah file .env ke /var/tmp/sensor_environment untuk di copy ke remote host
        path_env_checking = os.path.isdir("/var/tmp/sensor_environment")
        output_env_path = str(path_env_checking)
        if output_env_path == "False":
            os.makedirs("/var/tmp/sensor_environment")
        else:
            print("/var/tmp/sensor_environment folder exists")

        env_sensor_file = open("/var/tmp/sensor_environment/sensor.env", "w+")
        env_sensor_file.write(
            'PROTECTED_SUBNET={0}\nEXTERNAL_SUBNET={1}\nALERT_MQTT_TOPIC={2}\nALERT_MQTT_SERVER={3}\nALERT_MQTT_PORT={4}\nDEVICE_ID={5}\nNETINT={6}\nCOMPANY={7}\n'
            .format(protectedSubnet, externalSubnet, mqttTopic, mqttIP,
                    mqttPort, deviceID, networkInterface, company))
        env_sensor_file.close()

        if ruleChoice == "1":
            Ui_MainWindow.installCommunitySensor()
        else:
            print("Belum ada :p")
Esempio n. 41
0
 def _renameLayout(self):
     title = tr("Rename Layout")
     msg = tr("Choose a name for your layout:")
     name, ok = QInputDialog.getText(self, title, msg)
     if ok and name:
         self.model.rename_selected_layout(name)
Esempio n. 42
0
 def getText(self):
     text, okPressed = QInputDialog.getText(self, "Get text", "Your name:",
                                            QLineEdit.Normal, "")
     if okPressed and text != '':
         print(text)
Esempio n. 43
0
 def add(self):
     name = self.newWindow.name.text()
     number = self.newWindow.number.text()
     genre = self.newWindow.genre.currentText()
     author = self.newWindow.author.currentText()
     year = self.newWindow.year.currentText()
     status = self.newWindow.status.currentText()
     if not name or not number or not genre or not author or \
             not year or not status:
         self.newWindow.statusBar().showMessage('Заполните ' 'все поля!')
     else:
         if status == 'Да':
             self.status = 1
             opinion, ok_pressed = QInputDialog.getText(
                 self, "Ваше "
                 "впечат"
                 "ление", "Напишите "
                 "свое "
                 "мнение о "
                 "книге")
             if ok_pressed:
                 self.opinions = opinion
             else:
                 self.opinions = ''
         else:
             self.opinions = ''
             self.status = 0
         ID = self.connection.cursor().execute(
             "SELECT id FROM "
             "authors "
             "WHERE author=?", (author, )).fetchall()
         if not ID:
             self.connection.cursor().execute(
                 f"""INSERT INTO authors(author) VALUES(
                  ?)""", (author, ))
             self.connection.commit()
             author = self.connection.cursor().execute(
                 "SELECT id FROM authors WHERE author=?",
                 (author, )).fetchall()
         else:
             author = ID
         ID2 = self.connection.cursor().execute(
             "SELECT id FROM "
             "genres "
             "WHERE genre=?", (genre, )).fetchall()
         if not ID2:
             self.connection.cursor().execute(
                 f'INSERT INTO genres(genre) VALUES({genre})')
             self.connection.commit()
             genre = self.connection.cursor().execute(
                 "SELECT id FROM genres WHERE genre=?",
                 (genre, )).fetchall()
         else:
             genre = ID2
         ID3 = self.connection.cursor().execute(
             "SELECT id FROM "
             "years "
             "WHERE year=?", (year, )).fetchall()
         if not ID3:
             self.connection.cursor().execute(
                 f'INSERT INTO years(year) VALUES({year})')
             self.connection.commit()
             year = self.connection.cursor().execute(
                 "SELECT id FROM years WHERE year=?", (year, )).fetchall()
         else:
             year = ID3
         self.connection.cursor().execute(
             f"INSERT INTO Read("
             f"name, author, "
             f"number_of_pages, "
             f"genre, year, "
             f"impression, status) "
             f" VALUES (?, ?, ?, ?,"
             f" ?, ?, ?)",
             (name, int(author[0][0]), int(number), int(
                 genre[0][0]), int(year[0][0]), self.opinions, self.status))
         self.connection.commit()
         books = self.connection.cursor().execute("SELECT * FROM "
                                                  "Read").fetchall()
         self.tableWidget.setColumnCount(8)
         self.tableWidget.setRowCount(0)
         for i, row in enumerate(books):
             self.tableWidget.setRowCount(self.tableWidget.rowCount() + 1)
             for j, elem in enumerate(row):
                 self.tableWidget.setItem(i, j, QTableWidgetItem(str(elem)))
         self.FromNumToName()
         self.newWindow.hide()
Esempio n. 44
0
def show_input_dialog(context, title, message):
    text, ok = QInputDialog.getText(context, title, message)
    return text, ok
Esempio n. 45
0
    def finish_add(self):
        with open('new_levels_info/level.txt', 'r',
                  encoding='utf8') as input_file:
            level = input_file.readline()
        with open('new_levels_info/chall_num.txt', 'r',
                  encoding='utf8') as input_file:
            chall_num = input_file.readline()
        output_file = open(f'{level}/inventory.txt', 'w', encoding='utf8')
        output_file.close()

        output_file = open(f'{level}/file.txt', 'w', encoding='utf8')
        output_file.close()

        output_file = open(f'{level}/inventory.txt', 'w', encoding='utf8')
        output_file.close()

        output_file = open(f'{level}/completed_tasks.txt',
                           'w',
                           encoding='utf8')
        output_file.close()

        output_file = open(f'{level}/sequence_text.txt', 'w', encoding='utf8')
        output_file.close()

        output_file = open(f'{level}/rooms_history_used.txt',
                           'w',
                           encoding='utf8')
        output_file.close()

        answer_d = {
            '0': 0,
            '1': 0,
            '2': 0,
            '3': 0,
            '4': 0,
            '5': 0,
            '6': 0,
            '7': 0,
            '8': 0,
            '9': 0
        }

        with open(f'{level}/challenge.txt', 'a',
                  encoding='utf8') as output_file:
            for _ in range(int(chall_num) - 1):
                text, ok_pressed = QInputDialog.getText(
                    self, "Введите строку",
                    "Какую часть пароля тут найдет пользователь?")
                if ok_pressed:
                    output_file.write(text + '\n')
                    for sym in text:
                        answer_d[sym] += 1

        ans = 0
        for key in answer_d:
            ans = max(ans, answer_d[key])
        key_ans = ''
        for key in answer_d:
            if answer_d[key] == ans:
                key_ans = key

        with open(f'{level}/answer.txt', 'w', encoding='utf8') as output_file:
            output_file.write(key_ans)

        with open('unlock_levels.txt', 'a', encoding='utf8') as output_file:
            output_file.write('\n' + level)
        self.exit()
Esempio n. 46
0
 def __init__(self, parent, ask=True, path="", salvar_caminho=True):
     super(CodeEditor, self).__init__(parent)
     # Contador de linhas
     self.highlight = None
     self.contador_de_linhas = ContadorDeLinhas(self)
     self.largura_contador = 38
     self.blockCountChanged.connect(self.atualizar_largura_contador)
     self.updateRequest.connect(self.atualizar_area_contador)
     self.cursorPositionChanged.connect(self.marcar_linha_atual)
     self.contador_de_linhas.setGeometry(
         QRect(0, 0, self.largura_contador, self.height()))
     self.setViewportMargins(self.largura_contador, 0, 0, 0)
     self.marcar_linha_atual()
     self.achar = Achar(self)
     self.caminho = ""
     self.textChanged.connect(functools.partial(self.set_salvo, False))
     # Dialogo para novo arquivo
     if ask:
         valido = False
         while not valido:
             self.nome, ok = QInputDialog.getText(None, "Novo arquivo",
                                                  "Nome do rascunho:")
             if ok:
                 if CodeEditor.validar(self.nome):
                     self.caminho = os.path.join(Main.get_caminho_padrao(),
                                                 self.nome,
                                                 self.nome + ".brpp")
                     if os.path.exists(self.caminho):
                         arq_existe = QMessageBox().warning(
                             None, 'Arquivo existe',
                             "Ao abrir esse arquivo, você apagará um arquivo existente. Gostaria de continuar?",
                             QMessageBox.Ok | QMessageBox.No)
                         if arq_existe == QMessageBox.Ok:
                             with open(
                                     os.path.join(
                                         'recursos', 'exemplos',
                                         'CodigoMinimo.brpp')) as arquivo:
                                 self.set_texto(arquivo.read())
                             valido = True
                         else:
                             valido = False
                     else:
                         with open(
                                 os.path.join(
                                     'recursos', 'exemplos',
                                     'CodigoMinimo.brpp')) as arquivo:
                             self.set_texto(arquivo.read())
                         valido = True
                 else:
                     QMessageBox().warning(None, 'Erro', "Nome inválido!",
                                           QMessageBox.Ok)
                     valido = False
             else:
                 return
     else:
         self.nome = "Novo"
     if path:
         if salvar_caminho:
             self.caminho = path
             diretorio, nome = ntpath.split(path)
             self.nome = ntpath.basename(diretorio)
         with open(path) as arquivo:
             self.set_texto(arquivo.read())
     self.salvo = True
Esempio n. 47
0
from qgis.core import QgsProject
import matplotlib.pyplot as plt
from osgeo import gdal_array
from PyQt5 import QtGui
from time import time
import pandas as pd
import numpy as np
import processing
import gdal
import os

# Se determina el momento en que inicia la ejcución del programa
start_time = time()

# Ruta general de la ubicación de los archivos
data_path, ok = QInputDialog.getText(None, 'RUTA',
                                     'Introduzca la ruta general: ')
if ok == False:
    raise Exception('Cancelar')
data_path = data_path.replace("\\", "/")

# Se imprime una recomendación
QMessageBox.information(
    iface.mainWindow(), "!Tenga en cuenta!",
    'Se recomienda que si ya se ha ejecutado el programa con anterioridad sean borrados los archivos '
    'que este genera para evitar conflictos al reemplazar los archivos pre-existentes en especial los .shp'
)

# Dimensiones del pixel
cellsize, ok = QInputDialog.getDouble(None, 'Tamaño del pixel',
                                      'Introduzca el tamaño del pixel: ')
if ok == False:
Esempio n. 48
0
    def showDialog(self):
        text, ok = QInputDialog.getText(self, 'Input Dialog',
                                        'Enter your password:')

        if ok:
            print((text))
    def click(self):

        inputurl = self.urlInput.text()
        url = ""

        if re.match("(.*)facebook.com/(.*)/photos", inputurl):
            url = inputurl
        elif re.match("(.*)facebook.com/(.*)", inputurl):
            url = "%s/photos" % inputurl
        else:
            self.err = QMessageBox()
            self.err.setText("invalid facebook URL")
            return

        # get login creds
        myUserName, good = QInputDialog.getText(self, "Username",
                                                "Input Username")

        if not good:
            self.err = QMessageBox()
            self.err.setText("ERROR: no username entered")
            self.err.show()
            return

        myPassword, good = QInputDialog.getText(self, "Password",
                                                "Input Password",
                                                QLineEdit.Password)

        if not good:
            self.err = QMessageBox()
            self.err.setText("ERROR: no password entered")
            self.err.show()
            return

        # other get login creds
        # self.LW = LoginWindow()
        # self.LW.show()

        ops = Options()
        ops.add_argument("--disable-notifications")
        self.driver = webdriver.Chrome(self.driver, options=ops)

        def scrollToBottom(secs):
            # print('3')
            while (secs > 0):
                secs -= 1
                try:
                    self.driver.execute_script(
                        "window.scrollTo(0, document.body.scrollHeight);", "")
                except Exception as e:
                    print(e)
                # print('4')
                time.sleep(2)

        loginUrl = "https://www.facebook.com"
        self.driver.get(loginUrl)

        usr = self.driver.find_element_by_name("email")
        pwd = self.driver.find_element_by_name("pass")
        usr.send_keys(myUserName)
        pwd.send_keys(myPassword)
        pwd.send_keys(keys.Keys.ENTER)
        time.sleep(3)
        self.driver.get(url)

        # get other photos link
        otherPhotosLink = ""
        dummyLink = self.driver.find_elements_by_class_name("_3c_")
        for l in dummyLink:
            link = l.get_attribute("href")
            # print(link)
            if re.match("(.*)/photos_all(.*)", link):
                otherPhotosLink = link

        # scroll down
        scrollToBottom(20)

        # get all pic page links
        listOfLinks = []
        dummyLink = self.driver.find_elements_by_class_name("uiMediaThumb")
        for link in dummyLink:
            picLink = link.get_attribute("href")
            listOfLinks.append(picLink)

        for l in listOfLinks:
            # print(l)
            self.driver.get(l)
            time.sleep(2)
            pics = self.driver.find_elements_by_class_name("spotlight")
            for pic in pics:
                plink = pic.get_attribute("src")
                self.list.append(plink)  # would save here but....testing

        print("------going to other photos page -------")
        self.driver.get(otherPhotosLink)
        listOfLinks.clear()

        # scroll down again
        scrollToBottom(30)

        # get these photos
        dummyLink = self.driver.find_elements_by_class_name("uiMediaThumb")
        for link in dummyLink:
            picLink = link.get_attribute("href")
            listOfLinks.append(picLink)

        for l in listOfLinks:
            # print(l)
            self.driver.get(l)
            time.sleep(2)
            pics = self.driver.find_elements_by_class_name("spotlight")

            for pic in pics:
                try:
                    plink = pic.get_attribute("src")
                    self.list.append(plink)
                except Exception as e:
                    print(e)

        self.addSig.emit(self.list)
        self.driver.close()
        self.close()
Esempio n. 50
0
 def addStudent(self):
     currentIndex = self.ui.listItems.currentRow()
     text, ok = QInputDialog.getText(self, "New Student", "Student Name")
     if ok and text is not None:
         self.ui.listItems.insertItem(currentIndex, text)
Esempio n. 51
0
 def addBookmark(self, va, parent=None):
     if parent is None:
         parent = self
     bname, ok = QInputDialog.getText(parent, 'Enter...', 'Bookmark Name')
     if ok:
         self.vw.setVaSetRow('Bookmarks', (va, str(bname)))
Esempio n. 52
0
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.show()

        #add message box with link to github documentation
        msgBox = QMessageBox()
        msgBox.setWindowTitle("For detailed input info click link below")
        msgBox.setTextFormat(QtCore.Qt.RichText)
        msgBox.setText(
            '<a href = "https://github.com/cbirdferrer/collatrix#whale-body-condition-function">CLICK HERE</a> for detailed input instructions, \n then click on OK button to continue'
        )
        x = msgBox.exec_()

        #ask for input csv
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        input_csv, _ = QFileDialog.getOpenFileName(
            self,
            "Input 1. CollatriX output file",
            "",
            "All Files (*);;csv files (*.csv)",
            options=options)
        if input_csv:
            print("collatrix output file = {0}".format(input_csv))

        #import csv
        df_all = pd.read_csv(input_csv, sep=",")
        df_all = df_all.dropna(how="all", axis='rows').reset_index()
        df_all.columns = df_all.columns.str.replace(".00%", ".0%")

        #set up empty message list
        message = []
        #ask if they want body Volume
        items = ('yes', 'no')
        volchoice, okPressed = QInputDialog.getItem(
            self, 'Input 2.',
            'Do you want body volume to be calculated? (width measurements required)',
            items, 0, False)
        if okPressed and volchoice:
            print("{0} body volume calculated".format(volchoice))

        if volchoice == 'yes':
            n, okPressed = QInputDialog.getText(
                self, "Input 2.1",
                "What did you name the total length measurement? \n Total Length Name:",
                QLineEdit.Normal, "")
            if okPressed and n != '':
                tl_name = str(n)
            l, okPressed = QInputDialog.getText(self, "Input 2.2",
                                                "Lower Bound:",
                                                QLineEdit.Normal, "")
            if okPressed and l != '':
                lower = int(l)
            u, okPressed = QInputDialog.getText(self, "Input 2.3",
                                                "Upper Bound:",
                                                QLineEdit.Normal, "")
            if okPressed and u != '':
                upper = int(u)
            i, okPressed = QInputDialog.getText(self, "Input 2.4", "Interval:",
                                                QLineEdit.Normal, "")
            if okPressed and i != '':
                interval = int(i)
            print(
                "for body volume: length name = {0}, lower bound = {1}, upper bound = {2}, interval = {3}"
                .format(tl_name, lower, upper, interval))
            volmess = "for body volume: length name = {0}, lower bound = {1}, upper bound = {2}, interval = {3}".format(
                tl_name, lower, upper, interval)
        elif volchoice == 'no':
            volmess = "no body volume calculated"
            pass

        #ask if they want BAI
        items = ('yes', 'no')
        baichoice, okPressed = QInputDialog.getItem(
            self, 'Input 3',
            "Do you want BAI to be calculated? (you have to have measured Total_Length widths)",
            items, 0, False)
        if okPressed and baichoice:
            print("{0} BAI calculated".format(baichoice))
        if baichoice == 'yes':
            #ask if they want trapezoid method, parabola method, or both methods
            items = ('parabola', 'trapezoid', 'both')
            bai_method, okPressed = QInputDialog.getItem(
                self, 'Input 3.1',
                "Do you want BAI to be to measured using parabolas, trapezoids, or both?",
                items, 0, False)
            if okPressed and bai_method:
                print("BAI calculated using {0} method(s)".format(bai_method))
            #get intervals
            n, okPressed = QInputDialog.getText(
                self, "Input 3.2",
                "What did you name the total length measurement?",
                QLineEdit.Normal, "")
            if okPressed and n != '':
                tl_name = str(n)
            l, okPressed = QInputDialog.getText(self, "Input 3.3",
                                                "Lower Bound:",
                                                QLineEdit.Normal, "")
            if okPressed and l != '':
                b_lower = int(l)
            u, okPressed = QInputDialog.getText(self, "Input 3.4",
                                                "Upper Bound:",
                                                QLineEdit.Normal, "")
            if okPressed and u != '':
                b_upper = int(u)
            i, okPressed = QInputDialog.getText(self, "Input 3.5", "Interval:",
                                                QLineEdit.Normal, "")
            if okPressed and i != '':
                b_interval = int(i)
            print(
                "for BAI: length name = {0}, lower bound = {1}, upper bound = {2}, interval = {3}"
                .format(tl_name, b_lower, b_upper, b_interval))
            baimess = "for BAI: length name = {0}, lower bound = {1}, upper bound = {2}, interval = {3}".format(
                tl_name, b_lower, b_upper, b_interval)
        elif baichoice == 'no':
            baimess = 'no BAI calculated'
            pass

        #ask for name of output
        outname, okPressed = QInputDialog.getText(self, "Input 4",
                                                  'Output Name:',
                                                  QLineEdit.Normal, "")

        #where should output be saved?
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        saveFold = QFileDialog.getExistingDirectory(
            None,
            "Input 5: folder where output should be saved",
            options=options)
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog

        #set up output with inputs
        message = "Whale Body Condition Processing Inputs: {0}, {1}".format(
            volmess, baimess)
        mess = pd.DataFrame(data={'Processing Notes': message}, index=[1])
        mess_out = os.path.join(saveFold,
                                "{0}_processing_notes.txt".format(outname))
        mess.to_csv(mess_out)

        #process the data
        if volchoice == 'yes':
            df_allx = body_vol(df_all, tl_name, interval, lower, upper)
        elif volchoice == 'no':
            df_allx = df_all

        if baichoice == 'yes':
            if bai_method == 'parabola':
                df_bai = bai_parabola(df_all, tl_name, b_interval, b_lower,
                                      b_upper)
            elif bai_method == 'trapezoid':
                df_bai = bai_trapezoid(df_all, tl_name, b_interval, b_lower,
                                       b_upper)
            elif bai_method == 'both':
                df_par = bai_parabola(df_all, tl_name, b_interval, b_lower,
                                      b_upper)
                df_trap = bai_trapezoid(df_all, tl_name, b_interval, b_lower,
                                        b_upper)
                df_bai = pd.merge(df_par, df_trap, on=['Animal_ID', 'Image'])
            df_all1 = pd.merge(df_allx, df_bai, on=['Animal_ID', 'Image'])
        elif baichoice == 'no':
            df_all1 = df_allx

        if 'index' in df_all1.columns:
            df_all1 = df_all1.drop(['index'], axis=1)
        else:
            df_all1 = df_all1

        outcsv = os.path.join(saveFold,
                              "{0}_bodycondition.csv".format(outname))
        df_all1.to_csv(outcsv, sep=',', index_label='IX')

        print(df_all1)

        print("done, close GUI window to end script")
Esempio n. 53
0
 def saveGraph(self):
     image_name, ok = QInputDialog.getText(self, 'Save', 'Input Image Name               ')
     if ok:
         self.mplwidget.save(image_name + '.png')
         QMessageBox.information(self, '', 'Save Successfully!')
Esempio n. 54
0
 def GetStr(self):
     name, ok = QInputDialog.getText(self, '文本输入框', '请输入姓名')
     if name and ok:
         self.label2.setText(str(name))
Esempio n. 55
0
 def createInputDialog(self):
     text, ok = QInputDialog.getText(self, "Input Dialog", "Enter Name")
     if ok:
         self.label.setText(str(text))
Esempio n. 56
0
    def sravnenie(self):
        if self.lineEdit_2.text() == '' or self.lineEdit_4.text() == '' or not str(self.lineEdit_4.text(

        )).isdigit() or \
                self.lineEdit_5.text() \
                == '' or not str(self.lineEdit_5.text(

        )).isdigit() or self.lineEdit_6.text() == '' or not str(self.lineEdit_6.text(

        )).isdigit() or \
                self.lineEdit_7.text() == '' or not str(self.lineEdit_7.text(

        )).isdigit() or self.lineEdit_8.text() == '' or \
                not str(self.lineEdit_8.text(

                )).isdigit() or self.lineEdit_9.text() == '' or not str(self.lineEdit_9.text()) \
                or self.lineEdit_11.text() == '' \
                or not str(self.lineEdit_11.text(

        )).isdigit() or self.lineEdit_13.text() == '' or self.lineEdit_12.text() == '' or str(
            self.lineEdit_12.text()).isdigit() or \
                not str(self.lineEdit_13.text(

                )).isdigit() or \
                self.lineEdit_17.text() == '' or \
                self.lineEdit_17.text().isalpha() or self.lineEdit_6.text().isalpha():
            i, okBtnPressed = QInputDialog.getText(
                self, "Ошибка",
                "Некоторые поля не заполнены или заполнены не правильно")
        else:
            if int(self.lineEdit_17.text()) < 10000:
                i, okBtnPressed = QInputDialog.getText(
                    self, "Враньё", "Стоимость не может быть меньше 100000")
            else:  ## Мы обработали все ошибки и начали выяснеть стоимость
                if 2019 - int(self.comboBox_4.currentText()) < 10:
                    global cena
                    if self.comboBox.currentText() == 'Citroen':
                        cen = int(self.lineEdit_17.text())  ## изначальная цена
                        goda = 2019 - int(self.comboBox_4.currentText())
                        cena_for_goda = 10000 * goda
                        probeg = 2000 * (int(self.lineEdit_6.text()) // 1000)
                        if self.comboBox_3.currentText() == "Да":
                            if self.comboBox_5.currentText() == 'идеальное':
                                cen = cen - cena_for_goda - probeg - 50000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                            elif self.comboBox_5.currentText() == 'нормальное':
                                cen = cen - cena_for_goda - probeg - 50000 - 10000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                            elif self.comboBox_5.currentText() == 'ужасное':
                                cen = cen - cena_for_goda - probeg - 50000 - 30000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                        else:
                            if self.comboBox_5.currentText() == 'идеальное':
                                cen = cen - cena_for_goda - probeg
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                            elif self.comboBox_5.currentText() == 'нормальное':
                                cen = cen - cena_for_goda - probeg - 10000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                            elif self.comboBox_5.currentText() == 'ужасное':
                                cen = cen - cena_for_goda - probeg - 30000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                    elif self.comboBox.currentText() == 'Opel':
                        cen = int(self.lineEdit_17.text())  ## изначальная цена
                        goda = 2019 - int(self.comboBox_4.currentText())
                        cena_for_goda = 15000 * goda
                        probeg = 4000 * (int(self.lineEdit_6.text()) // 1000)
                        if self.comboBox_3.currentText() == "Да":
                            if self.comboBox_5.currentText() == 'идеальное':
                                cen = cen - cena_for_goda - probeg - 50000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(cen)
                                self.z.show()
                            elif self.comboBox_5.currentText() == 'нормальное':
                                cen = cen - cena_for_goda - probeg - 50000 - 15000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                            elif self.comboBox_5.currentText() == 'ужасное':
                                cen = cen - cena_for_goda - probeg - 50000 - 35000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                        else:
                            if self.comboBox_5.currentText() == 'идеальное':
                                cen = cen - cena_for_goda - probeg
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                            elif self.comboBox_5.currentText() == 'нормальное':
                                cen = cen - cena_for_goda - probeg - 15000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                            elif self.comboBox_5.currentText() == 'ужасное':
                                cen = cen - cena_for_goda - probeg - 35000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                    elif self.comboBox.currentText() == 'Volkswagen':
                        cen = int(self.lineEdit_17.text())  ## изначальная цена
                        goda = 2019 - int(self.comboBox_4.currentText())
                        cena_for_goda = 2000 * goda
                        probeg = 1000 * (int(self.lineEdit_6.text()) // 1000)
                        if self.comboBox_3.currentText() == "Да":
                            if self.comboBox_5.currentText() == 'идеальное':
                                cen = cen - cena_for_goda - probeg - 50000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                            elif self.comboBox_5.currentText() == 'нормальное':
                                cen = cen - cena_for_goda - probeg - 50000 - 5000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                            elif self.comboBox_5.currentText() == 'ужасное':
                                cen = cen - cena_for_goda - probeg - 50000 - 15000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                        else:
                            if self.comboBox_5.currentText() == 'идеальное':
                                cen = cen - cena_for_goda - probeg
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                            elif self.comboBox_5.currentText() == 'нормальное':
                                cen = cen - cena_for_goda - probeg - 5000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()
                            elif self.comboBox_5.currentText() == 'ужасное':
                                cen = cen - cena_for_goda - probeg - 15000
                                q = str(abs(cen))
                                self.z = Pokaz_trdea(q)
                                self.z.show()

                else:
                    i, okBtnPressed = QInputDialog.getText(
                        self, "Ошибка",
                        "Мы не принимаем машины возростом старше 10 лет")
Esempio n. 57
0
 def setText(self):
     text, ok = QInputDialog.getText(self, "Change To",
                                     "{0} name:".format(self.section),
                                     QLineEdit.Normal, self.item.text())
     if ok and text != "":
         self.item.setText(text)
Esempio n. 58
0
 def setFuncArgName(self, fva, idx, atype, aname):
     newname, ok = QInputDialog.getText(self, 'Enter...', 'Argument Name')
     if ok:
         self.vw.setFunctionArg(fva, idx, atype, str(newname))
Esempio n. 59
0
    def open_data_source(self, path):

        sm.ODS, ext = extension_evaluator(path)

        if not sm.ODS:
            QMessageBox.warning(self, "Unrecognized file")
            return

        # Assign session or file path if not already set
        if ext == '.mefd':

            # Open a pop-up window to enter password
            passwd, ok = QInputDialog.getText(self, "MEF password",
                                              "Please type MEF password")
            if ok:
                if not sm.ODS.password_check(passwd):
                    QMessageBox.warning(self, "Password incorrect",
                                        "The password is incorrect")
                    return
                else:
                    sm.ODS.password = passwd
                    self.session_path = path
            else:
                return

        elif not self.file_path:
            self.file_path = path

        # ----- Delete previous data -----

        # Delete any previous buffers
        if isinstance(sm.PDS, MemoryBuffer):
            sm.PDS.terminate_buffer()
            sm.PDS.terminate_monitor_thread()
            sm.PDS.purge_data()

        # Delete data from plugins to be able to open new data source
        for plugin in self.plugin_list:
            plugin.delete_plugin_data()

        # Delete data from signal_display
        self.signal_display.initialize_data_map()
        self.signal_display.update_signals()
        self.signal_display.data_array = None

        # -----

        self.statusBar().showMessage('Loading metadata')
        sm.ODS.load_metadata()
        self.statusBar().showMessage('Loading annotatios')
        # Try to get annotations
        if getattr(self, "annotations", None) is not None:
            if getattr(sm.ODS, "get_annotations", None) is not None:

                ann_groups = sm.ODS.get_annotations()

                if ann_groups is not None:
                    for ann_group in ann_groups.items():
                        self.annotations.add_annotation_set(
                            ann_group[1], ann_group[0])

        # Fork for buffer usage
        if CONF.get('data_management', 'use_memory_buffer'):
            sm.PDS = MemoryBuffer(self)
        else:
            sm.PDS = sm.ODS

        self.statusBar().showMessage('')

        self.source_opened = True
        self.add_path_to_title()
        self.sig_file_opened.emit()
Esempio n. 60
0
 def showDialog(self):
     text, ok = QInputDialog.getText(self, 'Input Dialog',
                                     'Enter your name:')
     if ok is True:
         self.le.setText(str(text))