Ejemplo n.º 1
0
    def __init__(self, parent):
        super(BruteForceView, self).__init__("bruteforce", parent)
        self.category = "bf"

        regex = QRegExp("\d{1,6}")
        self.__validator = QRegExpValidator(regex, self.lineEditPort)
        self.lineEditPort.setValidator(self.__validator)

        regex = QRegExp("\d{1,5}")

        self.__validator = QRegExpValidator(regex, self.lineEditPort)
        self.lineEditMaximum.setValidator(self.__validator)

        # Connect buttons
        self.pushButtonCancel.clicked.connect(self.pushButtonCancelClicked)
        self.pushButtonExploit.clicked.connect(self.pushButtonExploitClicked)
        self.toolButtonUsers.clicked.connect(self.toolButtonUsersClicked)
        self.toolButtonPasswords.clicked.connect(self.toolButtonPasswordsClicked)

        # Connect signal and thread
        self.__communicate = Communicate()
        self.__exploitThread = ExploitThread(self.__communicate)
        self.__communicate.finishExploit.connect(self.setResultExploit)

        # Button and progressbar
        self.setProgressBarState(0)
        self.pushButtonCancel.setEnabled(False)

        # Generator
        self.__generatorUsers = Generator()
        self.__generatorPasswords = Generator()
Ejemplo n.º 2
0
 def checkState(value, pattern):
     regexp = QRegExp(pattern)
     validator = QRegExpValidator(regexp)
     state = validator.validate(value, 0)[0]
     if state == QValidator.Acceptable:
         return True
     else:
         return False
Ejemplo n.º 3
0
    def __init__(self, parent):
        parent.setWindowTitle("Create a new directory")
        parent.resize(400, 250)

        parent.setAttribute(Qt.WA_DeleteOnClose)

        descriptionLabel = QLabel(parent)
        descriptionLabel.setText("Enter the name for the new directory " \
                                    + "and choose a parent directory for it")

        newDirectoryLabel = QLabel(parent)
        newDirectoryLabel.setText("Name of the new directory")

        directoryLabel = QLabel(parent)
        directoryLabel.setText("Parent directory for the new directory")

        parent.newDirectoryInput = QLineEdit(parent)
        validator = QRegExpValidator(parent.newDirectoryInput)
        # altho a valid unix filename can contain anything but / and \0 (null)
        # this should be enough for every sane person
        pattern = QRegExp("[a-zA-Z0-9-_.]+")
        validator.setRegExp(pattern)
        parent.newDirectoryInput.setValidator(validator)

        parent.directoryInput = QLineEdit(parent.startDirectory, parent)
        parent.directoryInput.setReadOnly(True)

        browseButton = QPushButton("&Browse", parent)
        browseButton.clicked.connect(parent.browseDirectory)

        okButton = QPushButton("&Done", parent)
        okButton.clicked.connect(parent.createNewDirectory)

        cancelButton = QPushButton("&Cancel", parent)
        cancelButton.clicked.connect(parent.close)

        frame = QFrame(parent)
        frame.setFrameStyle(QFrame.HLine)
        frame.setFrameShadow(QFrame.Sunken)

        space = QWidget(parent)
        space.resize(400, 50)

        grid = QGridLayout(parent)
        grid.addWidget(descriptionLabel, 0, 0, 1, 3)
        grid.addWidget(newDirectoryLabel, 1, 0, 1, 3)
        grid.addWidget(parent.newDirectoryInput, 2, 0, 1, 3)
        grid.addWidget(directoryLabel, 3, 0, 1, 3)
        grid.addWidget(parent.directoryInput, 4, 0, 1, 2)
        grid.addWidget(browseButton, 4, 2, 1, 1)
        grid.addWidget(space, 5, 0, 1, 3)
        grid.addWidget(frame, 6, 0, 1, 3)
        grid.addWidget(cancelButton, 7, 0, 1, 1)
        grid.addWidget(okButton, 7, 2, 1, 1)
Ejemplo n.º 4
0
    def __init__(self, parent=None, default_value=0):
        QSpinBox.__init__(self, parent)

        self.validator = QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,2}"), self)

        self.setRange(0, 255)
        self.setValue(default_value)
Ejemplo n.º 5
0
class RomanSpinBox(QSpinBox):

    def __init__(self, parent=None):
        super(RomanSpinBox, self).__init__(parent)
        regex = QRegExp(r"^M?M?M?(?:CM|CD|D?C?C?C?)"
                        r"(?:XC|XL|L?X?X?X?)(?:IX|IV|V?I?I?I?)$")
        regex.setCaseSensitivity(Qt.CaseInsensitive)
        self.validator = QRegExpValidator(regex, self)
        self.setRange(1, 3999)
        self.connect(self.lineEdit(), SIGNAL("textEdited(QString)"),
                     self.fixCase)


    def fixCase(self, text):
        self.lineEdit().setText(text.toUpper())


    def validate(self, text, pos):
        return self.validator.validate(text, pos)


    def valueFromText(self, text):
        return intFromRoman(unicode(text))


    def textFromValue(self, value):
        return romanFromInt(value)
Ejemplo n.º 6
0
class SpinBoxHex(QSpinBox):
    def __init__(self, parent=None, default_value=0):
        QSpinBox.__init__(self, parent)

        self.validator = QRegExpValidator(QRegExp('^([ ]*[0-9A-Fa-f][ ]*){1,8}$'), self)
        self.setValue(default_value)

    def validate(self, text, pos):
        return self.validator.validate(text, pos)

    def valueFromText(self, text):
        return min(int(text.replace(' ', ''), 16), (1 << 31) - 1)

    def textFromValue(self, value):
        s = ''

        for i, c in enumerate(reversed(hex(value).replace('0x', '').upper())):
            if i % 2 == 0:
                s = ' ' + s

            s = c + s

        s = s.strip()

        if len(s.replace(' ', '')) % 2 == 1:
            s = '0' + s

        return s
Ejemplo n.º 7
0
 def __init__(self, parent=None):
     super(RomanSpinBox, self).__init__(parent)
     regex = QRegExp(r"^M?M?M?(?:CM|CD|D?C?C?C?)"
                     r"(?:XC|XL|L?X?X?X?)(?:IX|IV|V?I?I?I?)$")
     regex.setCaseSensitivity(Qt.CaseInsensitive)
     self.validator = QRegExpValidator(regex, self)
     self.setRange(1, 3999)
     self.lineEdit().textEdited.connect(self.fixCase)
Ejemplo n.º 8
0
    def validate_text(self, text):
        """
        Validates and updates the entered text if necessary.
        Spaces are replaced by _ and capital letters are replaced by small.
        :param text: The text entered
        :type text: String
        """
        text_edit = self.sender()
        cursor_position = text_edit.cursorPosition()
        text_edit.setValidator(None)
        if len(text) == 0:
            return
        locale = QSettings().value("locale/userLocale")[0:2]

        if locale == 'en':
            name_regex = QRegExp('^(?=.{0,40}$)[ _a-zA-Z][a-zA-Z0-9_ ]*$')
            name_validator = QRegExpValidator(name_regex)
            text_edit.setValidator(name_validator)
            QApplication.processEvents()
            last_character = text[-1:]
            state = name_validator.validate(text, text.index(last_character))[0]
            if state != QValidator.Acceptable:
                msg = u'\'{0}\' is not allowed at this position.'.format(
                    last_character
                )
                self.show_notification(msg)
                text = text[:-1]

        # remove space and underscore at the beginning of the text
        if len(text) > 1:
            if text[0] == ' ' or text[0] == '_':
                text = text[1:]

        self.blockSignals(True)
        text_edit.setText(text)
        text_edit.setCursorPosition(cursor_position)
        self.blockSignals(False)
        text_edit.setValidator(None)
    def __init__(self, parent):
        super(ImageTab, self).__init__(parent)
        self.parent = parent
        self.name = 'Images'

        self.formats = config.image_formats
        self.extra_img = config.image_extra_formats

        validator = QRegExpValidator(QRegExp(r'^[1-9]\d*'), self)

        converttoQL = QLabel(self.tr('Convert to:'))
        self.extQCB = QComboBox()
        self.extQCB.addItems(self.formats)
        commandQL = QLabel(self.tr('Extra options:'))
        self.commandQLE = QLineEdit()

        hlayout2 = utils.add_to_layout('h', converttoQL, self.extQCB,
                                       commandQL, self.commandQLE)

        sizeQL = QLabel('<html><p align="center">' + self.tr('Image Size:') +
                        '</p></html>')
        self.widthQLE = utils.create_LineEdit((50, 16777215), validator, 4)
        self.heightQLE = utils.create_LineEdit((50, 16777215), validator, 4)
        label = QLabel('<html><p align="center">x</p></html>')
        label.setMaximumWidth(25)

        hlayout1 = utils.add_to_layout('h', self.widthQLE, label,
                                       self.heightQLE)
        sizelayout = utils.add_to_layout('v', sizeQL, hlayout1)

        self.imgaspectQChB = QCheckBox(self.tr("Maintain aspect ratio"))
        self.autocropQChB = QCheckBox(self.tr("Auto-crop"))

        vlayout = utils.add_to_layout('v', self.imgaspectQChB,
                                      self.autocropQChB)

        rotateQL = QLabel("<html><div align='center'>" + self.tr("Rotate") +
                          ":</div><br>(" + self.tr("degrees - clockwise") +
                          ")</html>")
        self.rotateQLE = utils.create_LineEdit((100, 16777215), validator, 3)
        self.vflipQChB = QCheckBox(self.tr('Vertical flip'))
        self.hflipQChB = QCheckBox(self.tr('Horizontal flip'))

        vlayout2 = utils.add_to_layout('v', self.vflipQChB, self.hflipQChB)
        hlayout3 = utils.add_to_layout('h', sizelayout, vlayout, rotateQL,
                                       self.rotateQLE, vlayout2, None)

        final_layout = utils.add_to_layout('v', hlayout2, hlayout3)
        self.setLayout(final_layout)
    def __init__(self, parent=None):
        super(GotocellDialog, self).__init__(parent)
        self.setupUi(self)
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)

        # 允许 一个大写或者小写的字母,后面跟着一个范围1~9的数字,
        # 后面再跟0个,1个或 2个0~9的数字(对于正则表达式的介绍,请查看文档中QRegExp类)
        regExp = QRegExp("[A-Za-z][1-9][0-9]{0,2}")

        self.lineEdit.setValidator(QRegExpValidator(regExp, self))

        self.connect(self.buttonBox, SIGNAL("accept()"), self,
                     SLOT("accept()"))
        self.connect(self.buttonBox, SIGNAL("reject()"), self,
                     SLOT("reject()"))
Ejemplo n.º 11
0
    def __init__(self, parent=None, preferences=None):

        super(DanbooruPage, self).__init__(parent)
        #FIXME: Doesn't work
        #loadUi(DANBOORU_UI, self)
        self.setupUi(self)

        self.kcfg_danbooruUrls.insertStringList(preferences.boards_list)
        # Allow only HTTP(S) URls in the lineedit
        regex = (
            r"(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?"
        )
        regex = QRegExp(regex)

        self._validator = QRegExpValidator(regex, self)
        self.kcfg_danbooruUrls.lineEdit().setValidator(self._validator)
Ejemplo n.º 12
0
 def createEditor(self, parent, option, index):
     """
     Reimplementation of generic list column
     QItemDelegate createEditor method
     """
     data_source = index.model().data_source()
     if DelegateRoutine().is_pdf(data_source, index):
         return
     self.items = data_source.delimiter_names()
     regex = QRegExp(r"^[\w\W]{1}$")
     validator = QRegExpValidator(regex, parent)
     combobox = QComboBox(parent)
     combobox.addItems(sorted(self.items.values()))
     combobox.setEditable(True)
     combobox.setValidator(validator)
     return combobox
Ejemplo n.º 13
0
 def setValidateRegExp(self, regexp):
     """Sets a regular expression the text must match.
     
     If the regular expression matches the full text, the OK button is
     enabled, otherwise disabled.
     
     If regexp is None, an earlier set regular expression is removed.
     
     """
     validator = function = None
     if regexp is not None:
         rx = QRegExp(regexp)
         validator = QRegExpValidator(rx, self.lineEdit())
         function = rx.exactMatch
     self.lineEdit().setValidator(validator)
     self.setValidateFunction(function)
Ejemplo n.º 14
0
    def __init__(self, github, name, parent=None):
        super(RepoRemoveDialog, self).__init__(parent,
                                               windowTitle="Remove Repo")

        self.github = github
        self.login = self.github.get_user().login
        self.name = name

        self.label = QLabel('''
        <p>Are you sure?</p>

        <p>This action <b>CANNOT</b> be undone.</p>
        <p>This will delete the <b>{}/{}</b> repository, wiki, issues, and
        comments permanently.</p>

        <p>Please type in the name of the repository to confirm.</p>
        '''.format(self.login, self.name))
        self.label.setTextFormat(Qt.RichText)

        validator = QRegExpValidator(
            QRegExp(r'{}/{}'.format(self.login, self.name)))
        self.nameEdit = QLineEdit(textChanged=self.textChanged)
        self.nameEdit.setValidator(validator)

        # Form

        self.form = QFormLayout()
        self.form.addRow(self.label)
        self.form.addRow(self.nameEdit)

        # ButtonBox

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel,
                                          accepted=self.accept,
                                          rejected=self.reject)

        # Layout

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.form)
        self.mainLayout.addWidget(self.buttonBox)
        self.setLayout(self.mainLayout)

        self.textChanged()
Ejemplo n.º 15
0
    def startUi(self):
        """This function checks if ui file exists and then show the view"""
        try:
            self.load("project")

            self.lineEditLocation.setText(expanduser("~"))
            regex = QRegExp("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
            self.__validator = QRegExpValidator(regex, self.lineEditIP)
            self.lineEditIP.setValidator(self.__validator)

            # Connect things
            self.buttonBox.rejected.connect(self.buttonBoxRejected)
            self.buttonBox.accepted.connect(self.buttonBoxAccepted)
            self.toolButton.clicked.connect(self.toolButtonClicked)
            return True
        except Exception as e:
            MessageBox.critical("Error", str(e))
            return False
Ejemplo n.º 16
0
    def __init__(self, parent):
        super(ImageTab, self).__init__(parent)
        self.parent = parent
        self.name = 'Images'
        self.formats = [
            'bmp', 'cgm', 'dpx', 'emf', 'eps', 'fpx', 'gif', 'jbig', 'jng',
            'jpeg', 'mrsid', 'p7', 'pdf', 'picon', 'png', 'ppm', 'psd', 'rad',
            'tga', 'tif', 'webp', 'xpm'
        ]

        self.extra_img = [
            'bmp2', 'bmp3', 'dib', 'epdf', 'epi', 'eps2', 'eps3', 'epsf',
            'epsi', 'icon', 'jpe', 'jpg', 'pgm', 'png24', 'png32', 'pnm', 'ps',
            'ps2', 'ps3', 'sid', 'tiff'
        ]

        pattern = QRegExp(r'^[1-9]\d*')
        validator = QRegExpValidator(pattern, self)

        converttoLabel = QLabel(self.tr('Convert to:'))
        self.extComboBox = QComboBox()
        self.extComboBox.addItems(self.formats)

        hlayout1 = pyqttools.add_to_layout(QHBoxLayout(), converttoLabel,
                                           self.extComboBox, None)

        sizeLabel = QLabel('<html><p align="center">' +
                           self.tr('Image Size:') + '</p></html>')
        self.widthLineEdit = pyqttools.create_LineEdit((50, 16777215),
                                                       validator, 4)
        self.heightLineEdit = pyqttools.create_LineEdit((50, 16777215),
                                                        validator, 4)
        label = QLabel('x')
        label.setMaximumWidth(25)
        self.aspectCheckBox = QCheckBox(self.tr("Maintain aspect ratio"))
        hlayout2 = pyqttools.add_to_layout(QHBoxLayout(), self.widthLineEdit,
                                           label, self.heightLineEdit)
        vlayout = pyqttools.add_to_layout(QVBoxLayout(), sizeLabel, hlayout2)
        hlayout3 = pyqttools.add_to_layout(QHBoxLayout(), vlayout,
                                           self.aspectCheckBox, None)
        final_layout = pyqttools.add_to_layout(QVBoxLayout(), hlayout1,
                                               hlayout3)
        self.setLayout(final_layout)
Ejemplo n.º 17
0
    def init_gui_controls(self):
        self.edtTable.setFocus()
        self.setTabOrder(self.edtTable, self.edtDesc)
        if self.entity:
            self.edtTable.setText(self.entity.short_name)
            self.edtDesc.setText(self.entity.description)

            self.cbSupportDoc.setCheckState( \
                    self.bool_to_check(self.entity.supports_documents))

            if self.entity.supports_documents and self.supporting_document_exists(
            ):
                self.cbSupportDoc.setEnabled(False)

        name_regex = QRegExp('[A-Za-z0-9_\s]*$')
        name_validator = QRegExpValidator(name_regex)
        self.edtTable.setValidator(name_validator)

        self.edtTable.setEnabled(not self.in_db)
Ejemplo n.º 18
0
    def __init__(self, parent=None, iface=None):
        """Constructor for import dialog.

        :param parent: Optional widget to use as parent
        :type parent: QWidget

        :param iface: An instance of QGisInterface
        :type iface: QGisInterface
        """
        QDialog.__init__(self, parent)
        self.parent = parent
        self.setupUi(self)

        self.setWindowTitle(self.tr('InaSAFE OpenStreetMap Downloader'))

        self.iface = iface
        self.buildings_url = "http://osm.linfiniti.com/buildings-shp"
        self.roads_url = "http://osm.linfiniti.com/roads-shp"

        self.help_context = 'openstreetmap_downloader'
        # creating progress dialog for download
        self.progress_dialog = QProgressDialog(self)
        self.progress_dialog.setAutoClose(False)
        title = self.tr("InaSAFE OpenStreetMap Downloader")
        self.progress_dialog.setWindowTitle(title)
        # Set up context help
        help_button = self.button_box.button(QtGui.QDialogButtonBox.Help)
        help_button.clicked.connect(self.show_help)

        self.show_info()

        # set up the validator for the file name prefix
        expression = QRegExp('^[A-Za-z0-9-_]*$')
        validator = QRegExpValidator(expression, self.filename_prefix)
        self.filename_prefix.setValidator(validator)

        # Set Proxy in webpage
        proxy = get_proxy()
        self.network_manager = QNetworkAccessManager(self)
        if proxy is not None:
            self.network_manager.setProxy(proxy)
        self.restore_state()
        self.update_extent()
Ejemplo n.º 19
0
class RomanSpinBox(QSpinBox):
    def __init__(self, parent=None):
        super(RomanSpinBox, self).__init__(parent)
        regex = QRegExp(r"^M?M?M?(?:CM|CD|D?C?C?C?)"
                        r"(?:XC|XL|L?X?X?X?)(?:IX|IV|V?I?I?I?)$")
        regex.setCaseSensitivity(Qt.CaseInsensitive)
        self.validator = QRegExpValidator(regex, self)
        self.setRange(1, 3999)
        self.lineEdit().textEdited.connect(self.fixCase)

    def fixCase(self, text):
        self.lineEdit().setText(text.toUpper())

    def validate(self, text, pos):
        return self.validator.validate(text, pos)

    def valueFromText(self, text):
        return intFromRoman(unicode(text))

    def textFromValue(self, value):
        return romanFromInt(value)
Ejemplo n.º 20
0
class SpinBoxHex(QSpinBox):
    def __init__(self, parent=None, default_value=0):
        QSpinBox.__init__(self, parent)

        self.validator = QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,2}"), self)

        self.setRange(0, 255)
        self.setValue(default_value)

    def validate(self, text, pos):
        return self.validator.validate(text, pos)

    def valueFromText(self, text):
        return int(text, 16)

    def textFromValue(self, value):
        s = hex(value).replace('0x', '').upper()

        if len(s) == 1:
            s = '0' + s

        return s
Ejemplo n.º 21
0
    def __init__(self, show_strength=True, parent=None):
        super(PinMatrixWidget, self).__init__(parent)

        self.password = QLineEdit()
        self.password.setValidator(QRegExpValidator(QRegExp('[1-9]+'), None))
        self.password.setEchoMode(QLineEdit.Password)

        if QT_VERSION_STR >= '5':
            self.password.textChanged.connect(self._password_changed)
        elif QT_VERSION_STR >= '4':
            QObject.connect(self.password, SIGNAL('textChanged(QString)'),
                            self._password_changed)
        else:
            raise RuntimeError('Unsupported Qt version')

        self.strength = QLabel()
        self.strength.setMinimumWidth(75)
        self.strength.setAlignment(Qt.AlignCenter)
        self._set_strength(0)

        grid = QGridLayout()
        grid.setSpacing(0)
        for y in range(3)[::-1]:
            for x in range(3):
                button = PinButton(self.password, x + y * 3 + 1)
                button.setSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)
                button.setFocusPolicy(Qt.NoFocus)
                grid.addWidget(button, 3 - y, x)

        hbox = QHBoxLayout()
        hbox.addWidget(self.password)
        if show_strength:
            hbox.addWidget(self.strength)

        vbox = QVBoxLayout()
        vbox.addLayout(grid)
        vbox.addLayout(hbox)
        self.setLayout(vbox)
Ejemplo n.º 22
0
class SpinBoxHex(QSpinBox):
    def __init__(self, parent=None, default_value=0):
        QSpinBox.__init__(self, parent)

        self.validator = QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,2}"), self)

        self.setRange(0, 255)
        self.setValue(default_value)

    def validate(self, text, pos):
        return self.validator.validate(text, pos)

    def valueFromText(self, text):
        return int(text, 16)

    def textFromValue(self, value):
        s = hex(value).replace('0x', '').upper()

        if len(s) == 1:
            s = '0' + s

        return s
Ejemplo n.º 23
0
    def __init__(self, parent=None, iface=None):
        """Constructor for import dialog.

        .. versionadded: 3.3

        :param parent: Optional widget to use as parent
        :type parent: QWidget

        :param iface: An instance of QGisInterface
        :type iface: QGisInterface
        """
        QDialog.__init__(self, parent)
        self.parent = parent
        self.setupUi(self)

        self.setWindowTitle(self.tr('PetaJakarta Downloader'))

        self.iface = iface

        # creating progress dialog for download
        self.progress_dialog = QProgressDialog(self)
        self.progress_dialog.setAutoClose(False)
        title = self.tr('PetaJakarta Downloader')
        self.progress_dialog.setWindowTitle(title)

        # Set up things for context help
        self.help_button = self.button_box.button(QtGui.QDialogButtonBox.Help)
        # Allow toggling the help button
        self.help_button.setCheckable(True)
        self.help_button.toggled.connect(self.help_toggled)
        self.main_stacked_widget.setCurrentIndex(1)

        # set up the validator for the file name prefix
        expression = QRegExp('^[A-Za-z0-9-_]*$')
        validator = QRegExpValidator(expression, self.filename_prefix)
        self.filename_prefix.setValidator(validator)
        self.time_stamp = None
        self.restore_state()
Ejemplo n.º 24
0
 def createWidgets(self, layout):
     self.label = QLabel(wordWrap=True)
     self.voicingLabel = QLabel()
     self.voicing = QComboBox(editable=True)
     self.voicingLabel.setBuddy(self.voicing)
     self.voicing.setCompleter(None)
     self.voicing.setValidator(QRegExpValidator(
         QRegExp("[SATB]+(-[SATB]+)*", Qt.CaseInsensitive), self.voicing))
     self.voicing.addItems((
         'SA-TB', 'S-A-T-B',
         'SA', 'S-A', 'SS-A', 'S-S-A',
         'TB', 'T-B', 'TT-B', 'T-T-B',
         'SS-A-T-B', 'S-A-TT-B', 'SS-A-TT-B',
         'S-S-A-T-T-B', 'S-S-A-A-T-T-B-B',
         ))
     self.lyricsLabel = QLabel()
     self.lyrics = QComboBox()
     self.lyricsLabel.setBuddy(self.lyrics)
     self.lyrics.setModel(listmodel.ListModel(lyricStyles, self.lyrics,
         display=listmodel.translate_index(0),
         tooltip=listmodel.translate_index(1)))
     self.lyrics.setCurrentIndex(0)
     self.pianoReduction = QCheckBox()
     self.rehearsalMidi = QCheckBox()
     
     layout.addWidget(self.label)
     box = QHBoxLayout()
     layout.addLayout(box)
     box.addWidget(self.voicingLabel)
     box.addWidget(self.voicing)
     self.createStanzaWidget(layout)
     box = QHBoxLayout()
     layout.addLayout(box)
     box.addWidget(self.lyricsLabel)
     box.addWidget(self.lyrics)
     self.createAmbitusWidget(layout)
     layout.addWidget(self.pianoReduction)
     layout.addWidget(self.rehearsalMidi)
Ejemplo n.º 25
0
    def __init__(self, title_prefix=''):
        ProgramPage.__init__(self)

        self.setupUi(self)

        self.edit_mode = False
        self.identifier_is_unique = False

        self.setTitle(title_prefix + 'General Information')
        self.setSubTitle(
            'Specify name, identifier, programming language and description for the program.'
        )

        self.edit_identifier.setValidator(
            QRegExpValidator(QRegExp('^[a-zA-Z0-9_][a-zA-Z0-9._-]{2,}$'),
                             self))
        self.combo_language.insertSeparator(Constants.LANGUAGE_SEPARATOR)

        self.registerField('name', self.edit_name)
        self.registerField('identifier', self.edit_identifier)
        self.registerField('language', self.combo_language)
        self.registerField('description', self.text_description, 'plainText',
                           self.text_description.textChanged)

        self.edit_name.textChanged.connect(self.auto_generate_identifier)
        self.check_auto_generate.stateChanged.connect(self.update_ui_state)
        self.edit_identifier.textChanged.connect(self.check_identifier)
        self.combo_language.currentIndexChanged.connect(self.update_ui_state)
        self.combo_language.currentIndexChanged.connect(self.check_language)

        self.edit_name_checker = MandatoryLineEditChecker(
            self, self.label_name, self.edit_name)
        self.edit_identifier_checker = MandatoryLineEditChecker(
            self, self.label_identifier, self.edit_identifier)

        self.check_language(self.combo_language.currentIndex())
Ejemplo n.º 26
0
    def __init__(self, parent=None):
        super(Github2FAWizardPage,
              self).__init__(parent,
                             title="Two-Factor Authentication",
                             subTitle="Enter required authentication code")

        # LineEdits

        self.codeEdit = QLineEdit()
        # codeEdit may only contain 1 or more digits
        self.codeEdit.setValidator(QRegExpValidator(QRegExp(r'[\d]+')))

        # Form

        self.form = QFormLayout()
        self.form.addRow("Code: ", self.codeEdit)

        # Layout

        self.setLayout(self.form)

        # Fields

        self.registerField('2fa_code*', self.codeEdit)
Ejemplo n.º 27
0
    def setValidador(cls, campos):
        """
        Setea el tipo de validación para cada campo recibido en el arreglo "campos".
        :param campos: arreglo con los campos a validar.
        :return:
        """
        regexp = None
        for campo in campos:
            c = campo.accessibleDescription()
            if c == "palabra":
                regexp = QRegExp("[a-zA-Zéáúóíñ]+")
            elif c == "texto":
                regexp = QRegExp("[a-zA-Zéáúóíñ]+[a-zA-Zéáúóíñ ]*")
            elif c == "numeros":
                regexp = QRegExp("[1-9]\d{1,4}")
            elif c == "textoNumeros":
                regexp = QRegExp("[a-zA-Zéáúóíñ0-9]+[a-zA-Zéáúóíñ0-9 ]*")
            elif c == "codigo":
                regexp = QRegExp("\d{9}")
            elif c == "importe":
                regexp = QRegExp("[1-9]\d*\.\d{2}")
            elif c == "codLote":
                regexp = QRegExp("[0-9A-Za-z]{2,10}")
            elif c == "cantidad":
                regexp = QRegExp("[1-9]\d{1,6}")
            elif c == "dni":
                regexp = QRegExp("\d{8}")
            elif c == "telefono":
                regexp = QRegExp("\d{0,20}")
            elif c == "direccion":
                regexp = QRegExp(".+\d{0,5}")
            elif c == "nya":
                regexp = QRegExp("[a-zA-Zéáúóíñ]{2,15}")

            validator = QRegExpValidator(regexp)
            campo.setValidator(validator)
Ejemplo n.º 28
0
class SpinBoxHex(QSpinBox):
    def __init__(self, parent=None):
        super(SpinBoxHex, self).__init__(parent)
        self.validator = QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,2}"), self)
        self.setRange(0, 255)


    def fixCase(self, text):
        self.lineEdit().setText(text.toUpper())


    def validate(self, text, pos):
        return self.validator.validate(text, pos)


    def valueFromText(self, text):
        return text.toInt(16)[0]

    def textFromValue(self, value):
        s = QString.number(value, base=16).toUpper()
        if len(s) == 1:
            s = '0' + s
            
        return s
Ejemplo n.º 29
0
    def __init__(self, parent):
        super(AudioVideoTab, self).__init__(parent)
        self.parent = parent
        self.name = 'AudioVideo'
        self.formats = [
            '3gp', 'aac', 'ac3', 'afc', 'aiff', 'amr', 'asf', 'au', 'avi',
            'dvd', 'flac', 'flv', 'mka', 'mkv', 'mmf', 'mov', 'mp3', 'mp4',
            'mpg', 'ogg', 'ogv', 'psp', 'rm', 'spx', 'vob', 'wav', 'webm',
            'wma', 'wmv'
        ]
        self.extra_formats = [
            'aifc', 'm2t', 'm4a', 'm4v', 'mp2', 'mpeg', 'ra', 'ts'
        ]

        nochange = self.tr('No Change')
        frequency_values = [nochange, '22050', '44100', '48000']
        bitrate_values = [
            nochange, '32', '96', '112', '128', '160', '192', '256', '320'
        ]
        pattern = QRegExp(r'^[1-9]\d*')
        validator = QRegExpValidator(pattern, self)

        converttoLabel = QLabel(self.tr('Convert to:'))
        self.extComboBox = QComboBox()
        self.extComboBox.addItems(self.formats + [self.tr('Other')])
        self.extComboBox.setMinimumWidth(130)
        self.extLineEdit = QLineEdit()
        self.extLineEdit.setMaximumWidth(85)
        self.extLineEdit.setEnabled(False)
        hlayout1 = pyqttools.add_to_layout(QHBoxLayout(), converttoLabel, None,
                                           self.extComboBox, self.extLineEdit)
        commandLabel = QLabel(self.tr('Command:'))
        self.commandLineEdit = QLineEdit()
        self.presetButton = QPushButton(self.tr('Preset'))
        self.defaultButton = QPushButton(self.tr('Default'))
        hlayout2 = pyqttools.add_to_layout(QHBoxLayout(), commandLabel,
                                           self.commandLineEdit,
                                           self.presetButton,
                                           self.defaultButton)

        sizeLabel = QLabel(self.tr('Video Size:'))
        aspectLabel = QLabel(self.tr('Aspect:'))
        frameLabel = QLabel(self.tr('Frame Rate (fps):'))
        bitrateLabel = QLabel(self.tr('Video Bitrate (kbps):'))

        self.widthLineEdit = pyqttools.create_LineEdit((50, 16777215),
                                                       validator, 4)
        self.heightLineEdit = pyqttools.create_LineEdit((50, 16777215),
                                                        validator, 4)
        label = QLabel('x')
        layout1 = pyqttools.add_to_layout(QHBoxLayout(), self.widthLineEdit,
                                          label, self.heightLineEdit)
        self.aspect1LineEdit = pyqttools.create_LineEdit((35, 16777215),
                                                         validator, 2)
        self.aspect2LineEdit = pyqttools.create_LineEdit((35, 16777215),
                                                         validator, 2)
        label = QLabel(':')
        layout2 = pyqttools.add_to_layout(QHBoxLayout(), self.aspect1LineEdit,
                                          label, self.aspect2LineEdit)
        self.frameLineEdit = pyqttools.create_LineEdit(None, validator, 4)
        self.bitrateLineEdit = pyqttools.create_LineEdit(None, validator, 6)

        labels = [sizeLabel, aspectLabel, frameLabel, bitrateLabel]
        widgets = [layout1, layout2, self.frameLineEdit, self.bitrateLineEdit]

        videosettings_layout = QHBoxLayout()
        for a, b in zip(labels, widgets):
            text = a.text()
            a.setText('<html><p align="center">{0}</p></html>'.format(text))
            layout = pyqttools.add_to_layout(QVBoxLayout(), a, b)
            videosettings_layout.addLayout(layout)

        freqLabel = QLabel(self.tr('Frequency (Hz):'))
        chanLabel = QLabel(self.tr('Channels:'))
        bitrateLabel = QLabel(self.tr('Audio Bitrate (kbps):'))

        self.freqComboBox = QComboBox()
        self.freqComboBox.addItems(frequency_values)
        self.chan1RadioButton = QRadioButton('1')
        self.chan1RadioButton.setMaximumSize(QSize(51, 16777215))
        self.chan2RadioButton = QRadioButton('2')
        self.chan2RadioButton.setMaximumSize(QSize(51, 16777215))
        self.group = QButtonGroup()
        self.group.addButton(self.chan1RadioButton)
        self.group.addButton(self.chan2RadioButton)
        spcr1 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum)
        spcr2 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum)
        chanlayout = pyqttools.add_to_layout(QHBoxLayout(), spcr1,
                                             self.chan1RadioButton,
                                             self.chan2RadioButton, spcr2)
        self.audio_bitrateComboBox = QComboBox()
        self.audio_bitrateComboBox.addItems(bitrate_values)

        labels = [freqLabel, chanLabel, bitrateLabel]
        widgets = [self.freqComboBox, chanlayout, self.audio_bitrateComboBox]

        audiosettings_layout = QHBoxLayout()
        for a, b in zip(labels, widgets):
            text = a.text()
            a.setText('<html><p align="center">{0}</p></html>'.format(text))
            layout = pyqttools.add_to_layout(QVBoxLayout(), a, b)
            audiosettings_layout.addLayout(layout)

        hidden_layout = pyqttools.add_to_layout(QVBoxLayout(),
                                                videosettings_layout,
                                                audiosettings_layout)

        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        self.moreButton = QPushButton(QApplication.translate('Tab', 'More'))
        self.moreButton.setSizePolicy(QSizePolicy(QSizePolicy.Fixed))
        self.moreButton.setCheckable(True)
        hlayout3 = pyqttools.add_to_layout(QHBoxLayout(), line,
                                           self.moreButton)

        self.frame = QFrame()
        self.frame.setLayout(hidden_layout)
        self.frame.hide()

        final_layout = pyqttools.add_to_layout(QVBoxLayout(), hlayout1,
                                               hlayout2, hlayout3, self.frame)
        self.setLayout(final_layout)

        self.presetButton.clicked.connect(self.choose_preset)
        self.defaultButton.clicked.connect(self.set_default_command)
        self.moreButton.toggled.connect(self.frame.setVisible)
        self.moreButton.toggled.connect(self.resize_parent)
        self.extComboBox.currentIndexChanged.connect(
            lambda: self.extLineEdit.setEnabled(self.extComboBox.currentIndex(
            ) == len(self.formats)))
        self.widthLineEdit.textChanged.connect(
            lambda: self.command_elements_change('size'))
        self.heightLineEdit.textChanged.connect(
            lambda: self.command_elements_change('size'))
        self.aspect1LineEdit.textChanged.connect(
            lambda: self.command_elements_change('aspect'))
        self.aspect2LineEdit.textChanged.connect(
            lambda: self.command_elements_change('aspect'))
        self.frameLineEdit.textChanged.connect(
            lambda: self.command_elements_change('frames'))
        self.bitrateLineEdit.textChanged.connect(
            lambda: self.command_elements_change('video_bitrate'))
        self.freqComboBox.currentIndexChanged.connect(
            lambda: self.command_elements_change('frequency'))
        self.audio_bitrateComboBox.currentIndexChanged.connect(
            lambda: self.command_elements_change('audio_bitrate'))
        self.chan1RadioButton.clicked.connect(
            lambda: self.command_elements_change('channels1'))
        self.chan2RadioButton.clicked.connect(
            lambda: self.command_elements_change('channels2'))
Ejemplo n.º 30
0
    def __init__(self, parent=None,key=None):
        super(LDSConfigPage, self).__init__(parent)
        
        self.parent = parent 
        self.key = key#'lds'
        
        try:
            (ldsurl,ldskey,ldssvc,ldsver,ldsfmt,ldscql) = self.parent.mfr.readLDSConfig()
        except:
            (ldsurl,ldskey,ldssvc,ldsver,ldsfmt,ldscql) = (None,)*6
        
        self.setTitle(self.parent.plist.get(self.key)[1]+' Configuration Options')
        self.setSubTitle('Here you can enter a name for your custom configuration file, your LDS API key and required output. Also select whether you want to configure a proxy or enable password encryption')

        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        fileLabel = QLabel('User Config File')
        keyLabel = QLabel('LDS API Key')
        destLabel = QLabel('Output Type')
        internalLabel = QLabel('Save Layer-Config in DB')
        self.warnLabel = QLabel('!!!')
        encryptionLabel = QLabel('Enable Password Protection')
        serviceLabel = QLabel('Service Type')
        versionLabel = QLabel('Service Version')
        
        
        infoLinkLabel = QLabel('<a href="http://www.linz.govt.nz/about-linz/linz-data-service/features/how-to-use-web-services">LDS API Information Page</a>')
        infoLinkLabel.setOpenExternalLinks(True);
        keyLinkLabel = QLabel('<a href="http://data.linz.govt.nz/my/api/">LDS API Key</a>')
        keyLinkLabel.setOpenExternalLinks(True);

        #edit boxes
        self.fileEdit = QLineEdit(self.parent.uchint)
        self.fileEdit.setToolTip('Name of user config file (without .conf suffix)')
        self.keyEdit = QLineEdit(ldskey)
        self.keyEdit.setToolTip('This is your LDS API key. If you have an account you can copy your key from here <a href="http://data.linz.govt.nz/my/api/">http://data.linz.govt.nz/my/api/</a>')
               
        #dropdown
        self.destSelect = QComboBox()
        self.destSelect.setToolTip('Choose from one of four possible output destinations')
        self.destSelect.addItem('')
        for itemkey in ('pg','ms','fg','sl'):
            itemindex = self.parent.plist.get(itemkey)[0]
            itemdata = self.parent.plist.get(itemkey)[1]
            self.destSelect.addItem(itemdata, itemindex)
            if itemdata == self.parent.sechint:
                self.destSelect.setCurrentIndex(itemindex)
                
        self.serviceSelect = QComboBox()
        self.serviceSelect.setToolTip('Choose from WFS (or one day, WMS)')
        for itemkey in ('','WFS','WMS','WMTS'):
            self.serviceSelect.addItem(itemkey)
            self.serviceSelect.setCurrentIndex(0)        
            
        self.versionSelect = QComboBox()
        self.versionSelect.setToolTip('Choose service Version')
        for itemkey in ('','1.0.0','1.1.0','2.0.0'):
            self.versionSelect.addItem(itemkey)
            self.versionSelect.setCurrentIndex(0)
        
        
        self.keyEdit.setValidator(QRegExpValidator(QRegExp("[a-fA-F0-9]{32}", re.IGNORECASE), self))
        
        #checkbox
        self.internalEnable = QCheckBox()
        self.internalEnable.setToolTip('Enable saving layer-config (per layer config and progress settings) internally')
        self.internalEnable.toggle()
        self.internalEnable.setChecked(True)
        self.internalEnable.stateChanged.connect(self.setWarn)
        
        self.encryptionEnable = QCheckBox()
        self.encryptionEnable.setToolTip('Encrypt any passwords saved to user config file')

        
        self.registerField(self.key+"file",self.fileEdit)
        self.registerField(self.key+"apikey",self.keyEdit)
        self.registerField(self.key+"dest",self.destSelect,"currentIndex")
        self.registerField(self.key+"internal",self.internalEnable)
        self.registerField(self.key+"encryption",self.encryptionEnable)

        #grid
        grid = QGridLayout()
        grid.setSpacing(10)
        
        grid.addWidget(fileLabel, 1, 0)
        grid.addWidget(self.fileEdit, 1, 2)
        #grid.addWidget(cfileButton, 1, 3)        
        
        grid.addWidget(keyLabel, 2, 0)
        grid.addWidget(self.keyEdit, 2, 2)
        
        grid.addWidget(destLabel, 3, 0)
        grid.addWidget(self.destSelect, 3, 2)
        
        grid.addWidget(internalLabel, 4, 0)
        grid.addWidget(self.internalEnable, 4, 2)
        #if self.internalEnable.checkState(): grid.addWidget(intwarnLabel, 4, 4)
        
        grid.addWidget(encryptionLabel, 5, 0)
        grid.addWidget(self.encryptionEnable, 5, 2)
        
        svgrid = QGridLayout()
        svgrid.addWidget(serviceLabel, 0, 0) 
        svgrid.addWidget(self.serviceSelect, 0, 2) 
        svgrid.addWidget(versionLabel, 1, 0) 
        svgrid.addWidget(self.versionSelect, 1, 2)
        
        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addLayout(svgrid)

        #layout       
        vbox = QVBoxLayout()
        vbox.addLayout(grid)
        #vbox.addLayout(hbox)
        vbox.addStretch(1)
        vbox.addWidget(self.warnLabel)
        vbox.addWidget(keyLinkLabel)
        vbox.addWidget(infoLinkLabel)
        
        self.setLayout(vbox)
class LM_DoubleSpinBox_with_calc(QDoubleSpinBox):
    '''
    This class is a special spinbox which allows the user to enter a math-expression. As soon as the edit is finished
    the expression will be evaluated and result will be entered in spinBox.
    To evaluate if the entered formula is valid, check "canBeCommitted" (bool). If true, you can read value.
    IMPORTANT: You can not use any "suffix" or "prefix" (which is ignoring the Regex...)
    '''
    def __init__(self, parent=None):
        super(LM_DoubleSpinBox_with_calc, self).__init__(parent)
        #setup a special validator (allowed are leading '=', 0-9 , . ( ) * / + - ... no caracters ... excel-like
        self.validator = QRegExpValidator(
            QRegExp("(^={1}\d*([-+*/(),.]*\d*)*)|([0-9,.])*"))
        self.expression = ""  # this is the variable which holds the expression
        self.setSpecialValueText(
            ""
        )  # this is only an action to avoid error messages if the field is empty
        self.setCorrectionMode(QAbstractSpinBox.CorrectToPreviousValue)
        self.canBeCommitted = True  #this variable holds the status, if the user has entered a valid formula or not

    def valueFromText(self, string):
        '''
        If the user has entered "anything" and hit enter or focus is lost, this function will be called, the
        call is overloaded with the entered string.
        :param string:Value entered in Widget as string
        :return: float (from string)
        '''
        string = string.replace(
            ",", ".")  #tanslate from "german" floating point value
        if string.startsWith("="):
            self.expression = string
            self.setFocusPolicy(Qt.StrongFocus)
            return float(self.value(
            ))  #dont forget about the value if user is entering a formula
        elif string.isEmpty():
            return float(self.value(
            ))  #dont forget about the value if user has cleared the lineEdit
        return float(string)

    def textFromValue(self, p_float):
        '''
        This function is called, when a value (float) should be "displayed", which have to be a string.
        :param p_float: float()
        :return: String from float
        '''
        if self.expression != "":
            expression = self.expression.replace("=", "").replace(
                ",", ".")  #forget about the "="
            try:
                result = float(eval(
                    str(expression)))  #calculate the expression
                self.expression = ""
                self.setValue(result)  #set the "value"
            except SyntaxError:  #this should not happen, because the formula is evaluated fist with "inValidCalculation"
                #print("There was a syntaxError, returning", self.expression)
                result = "=" + self.expression
            return "{0}".format(result).replace(
                ".",
                ",")  #return the display presentation of the value (string)
        return "{0}".format(p_float).replace(
            ".", ",")  #if the exression is empty, only return the string

    def validate(self, string, p_int):
        '''
        Function overrides builtin.
        Is more or less only a "switch" for bool "canBeCommited" which is true, if user has currently entered a valid
        math formula
        :param string: "content of current Spinbox"
        :param p_int: "count which should be validated"
        :return:
        '''
        if string.startsWith("="):
            if self.isValidCalculation(string):
                self.canBeCommitted = True
                return self.validator.validate(string, p_int)
            else:
                self.canBeCommitted = False
                return self.validator.validate(string, p_int)
        else:
            self.canBeCommitted = True
            return self.validator.validate(string, p_int)

    def isValidCalculation(self, string):
        '''
        Ducktyped: if the string is a valid formula which can be evaluated, this function returns True, otherwise
        False
        :param string: QString / String containing a math formula
        :return: True if valid, otherwise false.
        '''
        try:
            float(eval(str(string).replace("=", "").replace(
                ",", ".")))  #calculate the expression
            return True
        except:
            return False
Ejemplo n.º 32
0
    def __init__(self, nbprocessors):
        QDialog.__init__(self)
        self.layout = QVBoxLayout(self)
        self.taskset = None

        # Utilizations:
        vbox_utilizations = QVBoxLayout()
        group = QGroupBox("Task Utilizations:")

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel("Generator:", self))
        self.comboGenerator = QComboBox()
        self.comboGenerator.addItem("RandFixedSum")
        self.comboGenerator.addItem("UUniFast-Discard")
        self.comboGenerator.addItem("Kato's method")
        self.comboGenerator.currentIndexChanged.connect(self.generator_changed)
        hbox.addWidget(self.comboGenerator)
        vbox_utilizations.addLayout(hbox)

        # Load slider + spinner:
        hbox_load = QHBoxLayout()
        sld = _DoubleSlider(QtCore.Qt.Horizontal, self)
        sld.setMinimum(0)
        sld.setMaximum(32)
        self.spin_load = QDoubleSpinBox(self)
        self.spin_load.setMinimum(0)
        self.spin_load.setMaximum(32)
        self.spin_load.setSingleStep(0.1)
        hbox_load.addWidget(QLabel("Total utilization: ", self))
        hbox_load.addWidget(sld)
        hbox_load.addWidget(self.spin_load)
        sld.doubleValueChanged.connect(self.spin_load.setValue)
        self.spin_load.valueChanged.connect(sld.setValue)
        self.spin_load.setValue(nbprocessors / 2.)
        vbox_utilizations.addLayout(hbox_load)

        # Number of periodic tasks:
        self.hbox_tasks = QHBoxLayout()
        self.spin_tasks = QSpinBox(self)
        self.spin_tasks.setMinimum(0)
        self.spin_tasks.setMaximum(999)  # That's arbitrary.
        self.hbox_tasks.addWidget(QLabel("Number of periodic tasks: ", self))
        self.hbox_tasks.addStretch(1)
        self.hbox_tasks.addWidget(self.spin_tasks)
        vbox_utilizations.addLayout(self.hbox_tasks)

        # Number of sporadic tasks:
        self.hbox_sporadic_tasks = QHBoxLayout()
        self.spin_sporadic_tasks = QSpinBox(self)
        self.spin_sporadic_tasks.setMinimum(0)
        self.spin_sporadic_tasks.setMaximum(999)  # That's arbitrary.
        self.hbox_sporadic_tasks.addWidget(
            QLabel("Number of sporadic tasks: ", self))
        self.hbox_sporadic_tasks.addStretch(1)
        self.hbox_sporadic_tasks.addWidget(self.spin_sporadic_tasks)
        vbox_utilizations.addLayout(self.hbox_sporadic_tasks)

        # Min / Max utilizations
        self.hbox_utilizations = QHBoxLayout()
        self.hbox_utilizations.addWidget(QLabel("Min/Max utilizations: ",
                                                self))
        self.interval_utilization = IntervalSpinner(self,
                                                    min_=0,
                                                    max_=1,
                                                    step=.01,
                                                    round_option=False)
        self.hbox_utilizations.addWidget(self.interval_utilization)
        vbox_utilizations.addLayout(self.hbox_utilizations)

        group.setLayout(vbox_utilizations)
        self.layout.addWidget(group)

        # Periods:
        vbox_periods = QVBoxLayout()
        group = QGroupBox("Task Periods:")

        # Log uniform
        self.lunif = QRadioButton("log-uniform distribution between:")
        vbox_periods.addWidget(self.lunif)
        self.lunif.setChecked(True)

        self.lunif_interval = IntervalSpinner(self)
        self.lunif_interval.setEnabled(self.lunif.isChecked())
        self.lunif.toggled.connect(self.lunif_interval.setEnabled)
        vbox_periods.addWidget(self.lunif_interval)

        # Uniform
        self.unif = QRadioButton("uniform distribution between:")
        vbox_periods.addWidget(self.unif)

        self.unif_interval = IntervalSpinner(self)
        self.unif_interval.setEnabled(self.unif.isChecked())
        self.unif.toggled.connect(self.unif_interval.setEnabled)
        vbox_periods.addWidget(self.unif_interval)

        # Discrete
        discrete = QRadioButton("chosen among these (space separated) values:")
        vbox_periods.addWidget(discrete)

        self.periods = QLineEdit(self)
        self.periods.setValidator(
            QRegExpValidator(QRegExp("^\\d*(\.\\d*)?( \\d*(\.\\d*)?)*$")))

        vbox_periods.addWidget(self.periods)
        self.periods.setEnabled(discrete.isChecked())
        discrete.toggled.connect(self.periods.setEnabled)
        vbox_periods.addStretch(1)

        group.setLayout(vbox_periods)
        self.layout.addWidget(group)

        buttonBox = QDialogButtonBox()
        cancel = buttonBox.addButton(QDialogButtonBox.Cancel)
        generate = buttonBox.addButton("Generate", QDialogButtonBox.AcceptRole)
        cancel.clicked.connect(self.reject)
        generate.clicked.connect(self.generate)
        self.layout.addWidget(buttonBox)

        self.show_randfixedsum_options()
Ejemplo n.º 33
0
    def createDialog(self):
        """
        Create dialog
        """

        self.dockToolbar = QToolBar(self)
        self.dockToolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.setWindowTitle(WINDOW_TITLE)
        self.resize(500, 400)

        self.ipEdit = QLineEdit(self.defaultIp)
        ipRegExpVal = QRegExpValidator(self)
        ipRegExp = QRegExp("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
        ipRegExpVal.setRegExp(ipRegExp)
        self.ipEdit.setValidator(ipRegExpVal)

        self.portEdit = QLineEdit(self.defaultPort)
        self.portEdit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        validatorPort = QIntValidator(self)
        self.portEdit.setValidator(validatorPort)

        self.progressBar = QProgressBar(self)
        self.progressBar.setMaximum(100)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setAlignment(Qt.AlignCenter)
        self.progressBar.setObjectName("progressBar")

        self.guiSikuliGroupBox = QGroupBox("")
        self.guiSikuliGroupBox.setFlat(True)
        self.automaticAdp = QRadioButton("Automatic")
        self.automaticAdp.setChecked(True)
        self.defaultAdp = QRadioButton("Default")
        self.genericAdp = QRadioButton("Generic")
        vbox = QHBoxLayout()
        vbox.addWidget(self.automaticAdp)
        vbox.addWidget(self.defaultAdp)
        vbox.addWidget(self.genericAdp)
        vbox.addStretch(1)
        self.guiSikuliGroupBox.setLayout(vbox)

        layout = QVBoxLayout()
        layout.addWidget(self.dockToolbar)
        layout.addSpacing(12)
        paramLayout = QGridLayout()
        paramLayout.addWidget(QLabel("Destination IP:"), 0, 0, Qt.AlignRight)
        paramLayout.addWidget(self.ipEdit, 0, 1)
        paramLayout.addWidget(QLabel("Destination Port:"), 1, 0, Qt.AlignRight)
        paramLayout.addWidget(self.portEdit, 1, 1)
        paramLayout.addWidget(QLabel(self.tr("Gui adapter selector:")), 2, 0,
                              Qt.AlignRight)
        paramLayout.addWidget(self.guiSikuliGroupBox, 2, 1)
        layout.addLayout(paramLayout)

        self.logsEdit = QTextEdit()
        self.logsEdit.setReadOnly(True)
        self.logsEdit.setTextInteractionFlags(Qt.NoTextInteraction)

        layout.addSpacing(12)
        layout.addWidget(self.logsEdit)
        layout.addSpacing(12)
        layout.addWidget(self.progressBar)

        self.setLayout(layout)
Ejemplo n.º 34
0
    def __init__(self, parent=None,key=None):
        super(ProxyConfigPage, self).__init__(parent)
        
        self.parent = parent 
        self.key = key
        
        try:
            (pxytype,pxyhost,pxyport,pxyauth,pxyusr,pxypwd) = self.parent.mfr.readProxyConfig()
        except:
            (pxytype,pxyhost,pxyport,pxyauth,pxyusr,pxypwd) = (None,)*6
            
        #if we use enums for pxy types
        #pxytype = [a[0] for a in WFSDataStore.PROXY_TYPE.reverse.items() if a[1]==pxytype][0]

            
        self.setTitle(self.parent.plist.get(self.key)[1]+' Configuration Options')
        self.setSubTitle('Enter the hostname/ip-address, port number and authentication details of your HTTP proxy')

        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        directlabel = QLabel('Direct Connection')
        systemlabel = QLabel('Use System Proxy settings')
        proxylabel = QLabel('Configure Proxy')
        
        hostLabel = QLabel('Proxy Host')
        portLabel = QLabel('Proxy Port')
        authLabel = QLabel('Authentication')
        usrLabel = QLabel('Username')
        pwdLabel = QLabel('Password')
        
        
        #radio buttons
        self.directradio = QRadioButton()
        self.systemradio = QRadioButton()
        self.usrdefradio = QRadioButton()
        
        
        #edit boxes
        self.hostEdit = QLineEdit(pxyhost)
        self.hostEdit.setToolTip('Enter Proxy host (IP Address or hostname)')
        self.portEdit = QLineEdit(pxyport)
        self.portEdit.setToolTip('Enter Proxy port')
        
        #dropdown
        self.authSelect = QComboBox()
        self.authSelect.addItem('')
        self.authSelect.setToolTip('Select appropriate proxy authentication mechanism')
        self.authSelect.addItems(WFSDataStore.PROXY_AUTH)
        self.authSelect.setCurrentIndex(0 if LU.assessNone(pxyauth) is None else WFSDataStore.PROXY_AUTH.index(pxyauth))
        
        self.usrEdit = QLineEdit(pxyusr)
        self.usrEdit.setToolTip('Enter your proxy username (if required)')
        self.pwdEdit = QLineEdit('')#pxypwd
        self.usrEdit.setToolTip('Enter your proxy password (if required)')
        self.pwdEdit.setEchoMode(QLineEdit.Password)
        
        self.portEdit.setValidator(QRegExpValidator(QRegExp("\d{1,5}"), self))
        
        self.registerField(self.key+"host",self.hostEdit)
        self.registerField(self.key+"port",self.portEdit)
        self.registerField(self.key+"auth",self.authSelect,"currentIndex")
        self.registerField(self.key+"usr",self.usrEdit)
        self.registerField(self.key+"pwd",self.pwdEdit)
        
        self.registerField(self.key+WFSDataStore.PROXY_TYPE[0],self.directradio)
        self.registerField(self.key+WFSDataStore.PROXY_TYPE[1],self.systemradio)
        self.registerField(self.key+WFSDataStore.PROXY_TYPE[2],self.usrdefradio)

        #grid
        grid1 = QGridLayout()
        grid1.setSpacing(10)
        
        grid2 = QGridLayout()
        grid2.setSpacing(10)
        
        #layout
        hbox = QHBoxLayout()
        grid1.addWidget(self.directradio,1,0)
        grid1.addWidget(directlabel,1,1)
        grid1.addWidget(self.systemradio,2,0)
        grid1.addWidget(systemlabel,2,1)
        grid1.addWidget(self.usrdefradio,3,0)
        grid1.addWidget(proxylabel,3,1)
        hbox.addLayout(grid1)
        hbox.addStretch(1)
        
        
        self.gbox = QGroupBox('Proxy Configuration')

        #dsu
        subs = False
        if pxytype == WFSDataStore.PROXY_TYPE[1]:
            #system
            self.systemradio.setChecked(True)
        elif pxytype == WFSDataStore.PROXY_TYPE[2]:
            #user_defined
            self.usrdefradio.setChecked(True)
            subs = True
        else:
            #direct (default)
            self.directradio.setChecked(True)
            
        self.setUserDefined(subs)
        
        self.directradio.clicked.connect(self.disableUserDefined)
        self.systemradio.clicked.connect(self.disableUserDefined)
        self.usrdefradio.clicked.connect(self.enableUserDefined)
        
        grid2.addWidget(hostLabel, 1, 0)
        grid2.addWidget(self.hostEdit, 1, 2)
        
        grid2.addWidget(portLabel, 2, 0)
        grid2.addWidget(self.portEdit, 2, 2)
        
        grid2.addWidget(authLabel, 3, 0)
        grid2.addWidget(self.authSelect, 3, 2)
        
        grid2.addWidget(usrLabel, 4, 0)
        grid2.addWidget(self.usrEdit, 4, 2)
        
        grid2.addWidget(pwdLabel, 5, 0)
        grid2.addWidget(self.pwdEdit, 5, 2)
             
        self.gbox.setLayout(grid2)
        
        #layout    
        vbox = QVBoxLayout()
        vbox.addLayout(hbox)
        vbox.insertWidget(1,self.gbox)
        self.setLayout(vbox)  
Ejemplo n.º 35
0
 def __init__(self, parent, typeid):
     QRegExpValidator.__init__(self, parent)
     self.typeid = typeid
     self.init()
Ejemplo n.º 36
0
    def _setupGUI(self):
        self._class_buttons = {}
        self.label_menu = {}
        self.label_action = {}
        self._label_editor = None

        # Label class buttons
        self._parea = QGroupBox("Labels")
        self._classbox = QScrollArea()
        self._classbox_layout = FloatingLayout()
        self._parea.setLayout(self._classbox_layout)
        self._parea.setGeometry(0, 0, 200, 200)
        self._classbox.setWidget(self._parea)
        self._classbox.setGeometry(0, 0, 100, 100)
        # 添加txt模块
        self.combo_box = QComboBox()
        self._group_box_add_txt = QGroupBox('add_txt', self)
        self._group_box_add_txt_layout = QVBoxLayout()
        self._group_box_add_txt.setLayout(self._group_box_add_txt_layout)
        temp = cf.LABELS
        self.items = []
        # 获取所有的标签
        for i in temp:
            self.items.append(i['attributes']['class'])
        # 假如下拉框
        self.combo_box.addItems(self.items)
        self.add_txt_btn = QPushButton('add txt')
        self.add_txt_btn.clicked.connect(self.add_txt)
        # 加入下拉框和按钮
        self._group_box_add_txt_layout.addWidget(self.combo_box, 0)
        self._group_box_add_txt_layout.addWidget(self.add_txt_btn, 1)

        # 根据关键字搜索图片模块
        self._group_box_add_files = QGroupBox('add files', self)
        # 文件名包含的
        self._key_word = QLineEdit('')
        self._key_word.setPlaceholderText('Second')
        # 文件类型
        self._extension = QLineEdit('')
        self._extension.setPlaceholderText('bmp')
        self._search_btn = QPushButton('search files')
        self._group_box_add_files_layout = QVBoxLayout()
        # 加入控件
        self._group_box_add_files_layout.addWidget(self._key_word, 0)
        self._group_box_add_files_layout.addWidget(self._extension, 1)
        self._group_box_add_files_layout.addWidget(self._search_btn, 2)
        self._group_box_add_files.setLayout(self._group_box_add_files_layout)

        # 添加标签模块
        self._group_box_add_label = QGroupBox("添加标签", self)
        self._add_label_group_layout = QVBoxLayout()
        self._group_box_add_label.setLayout(self._add_label_group_layout)
        # 标签的class
        self.attributes_LineEdit = QLineEdit('')
        self.attributes_LineEdit.setPlaceholderText('attributes')
        # 标签画出来的类型
        self.attributes_type = QComboBox()
        self.attributes_type.addItems(self.get_attributes_type())
        # 快捷键,目前设置了只允许一个键
        self.hotkey = QLineEdit('')
        self.hotkey.setPlaceholderText('hotkey')
        self.regx = QRegExp("[a-z0-9]$")
        self.validator = QRegExpValidator(self.regx, self.hotkey)
        self.hotkey.setValidator(self.validator)
        # 标签显示
        self.text_LineEdit = QLineEdit('')
        self.text_LineEdit.setPlaceholderText('text')
        # 颜色
        color = QtGui.QColor(0, 0, 0)
        self.color_label = QtGui.QWidget()
        self.color_label.setStyleSheet("QWidget { background-color: %s }" %
                                       color.name())
        self.color_info = [0, 0, 0]
        self.color_layout = QtGui.QHBoxLayout()
        self.color_btn = QPushButton('选择颜色')
        self.color_btn.clicked.connect(self.color_dialog)
        self.color_layout.addWidget(self.color_label)
        self.color_layout.addWidget(self.color_btn)
        # 笔刷
        global brush2idx
        self.brush_combo_box = QComboBox()
        self.brush_combo_box.addItems(list(brush2idx.keys()))
        # 按钮
        self.attributes_add_btn = QPushButton('添加标签')
        self.attributes_add_btn.clicked.connect(self.add_attributes)
        # 加入控件
        self._add_label_group_layout.addWidget(self.attributes_LineEdit, 0)
        self._add_label_group_layout.addWidget(self.attributes_type, 1)
        self._add_label_group_layout.addWidget(self.hotkey, 2)
        self._add_label_group_layout.addWidget(self.text_LineEdit, 3)
        self._label_widget = QWidget()
        self._label_widget.setLayout(self.color_layout)
        self._add_label_group_layout.addWidget(self._label_widget, 4)
        self._add_label_group_layout.addWidget(self.brush_combo_box, 5)
        self._add_label_group_layout.addWidget(self.attributes_add_btn, 6)

        # 生成训练数据按钮
        self._file_button = QPushButton('生成训练数据')
        self._file_button.clicked.connect(self.generate)

        # Global widget
        self._layout = MyVBoxLayout()
        self.setLayout(self._layout)
        self._layout.addWidget(self._classbox, 1)
        self._layout.insertWidget(-1, self._group_box_add_label, 1)
        self._layout.insertWidget(-1, self._group_box_add_txt, 1)
        self._layout.insertWidget(-1, self._group_box_add_files, 1)
        self._layout.insertWidget(-1, self._file_button, 1)
Ejemplo n.º 37
0
    def __init__(self, parent=None, default_value=0):
        QSpinBox.__init__(self, parent)

        self.validator = QRegExpValidator(QRegExp('^([ ]*[0-9A-Fa-f][ ]*){1,8}$'), self)
        self.setValue(default_value)
Ejemplo n.º 38
0
def hostOrFqdnOrIpValidator(parent):
    validator = QRegExpValidator(IP_OR_HOSTNAME_OR_FQDN_REGEXP, parent)
    validator.setObjectName('hostOrFqdnOrIPValidator')
    return validator
Ejemplo n.º 39
0
 def __init__(self, parent=None):
     super(SpinBoxHex, self).__init__(parent)
     self.validator = QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,2}"), self)
     self.setRange(0, 255)
Ejemplo n.º 40
0
# QDate is not affected by QLocale.setDefault() in main 
#_MONTHS_ = [unicode(QDate.longMonthName(m)) for m in range(1, 13)]
locale = QLocale()
_MONTHS_ = [unicode(locale.monthName(m)) for m in range(1, 13)]

# default category names used to set up models at start 
_EXPCATEGORIES_ = ['Bars, Party', 'Groceries', 'Household', 'Restaurants', 
        'Travelling', 'Clothes', 'Miscellaneous' ]

_RECCATEGORIES_ = [ 'Work', 'Gifts', 'Scholarships' ]

_HEADERLABELS_ = ['Name', 'Value', 'Date']

# global validator to check user given dates 
_DATEVALIDATOR_ = QRegExpValidator(QRegExp('\d{1,2}\.'))

def loadUi(modpath, widget):
    """
    Uses the PyQt4.uic.loadUi method to lead the input ui file associated
    with the given module path and widget class information on the input widget.
    
    :param modpath | str
    :param widget  | QWidget
    """
    # generate the uifile path
    basepath = os.path.dirname(modpath)
    basename = widget.__class__.__name__.lower()
    uifile   = os.path.join(basepath, 'ui/%s.ui' % basename)
    uipath   = os.path.dirname(uifile)
Ejemplo n.º 41
0
def hostnameValidator(parent):
    validator = QRegExpValidator(HOSTNAME_REGEXP, parent)
    validator.setObjectName('hostnameValidator')
    return validator
Ejemplo n.º 42
0
def hostIP4Validator(parent):
    validator = QRegExpValidator(IPV4_REGEXP, parent)
    validator.setObjectName('hostIP4Validator')
    return validator
Ejemplo n.º 43
0
    def __init__(self, parent=None, iface=None):
        """Constructor for import dialog.

        :param parent: Optional widget to use as parent
        :type parent: QWidget

        :param iface: An instance of QGisInterface
        :type iface: QGisInterface
        """
        QDialog.__init__(self, parent)
        self.parent = parent
        self.setupUi(self)

        self.setWindowTitle(self.tr('InaSAFE OpenStreetMap Downloader'))

        self.iface = iface

        self.help_context = 'openstreetmap_downloader'
        # creating progress dialog for download
        self.progress_dialog = QProgressDialog(self)
        self.progress_dialog.setAutoClose(False)
        title = self.tr('InaSAFE OpenStreetMap Downloader')
        self.progress_dialog.setWindowTitle(title)

        # Set up things for context help
        self.help_button = self.button_box.button(QtGui.QDialogButtonBox.Help)
        # Allow toggling the help button
        self.help_button.setCheckable(True)
        self.help_button.toggled.connect(self.help_toggled)
        self.main_stacked_widget.setCurrentIndex(1)

        # Disable boundaries group box until boundary checkbox is ticked
        self.boundary_group.setEnabled(False)

        # set up the validator for the file name prefix
        expression = QRegExp('^[A-Za-z0-9-_]*$')
        validator = QRegExpValidator(expression, self.filename_prefix)
        self.filename_prefix.setValidator(validator)

        self.restore_state()

        # Setup the rectangle map tool
        self.canvas = iface.mapCanvas()
        self.rectangle_map_tool = \
            RectangleMapTool(self.canvas)
        self.rectangle_map_tool.rectangle_created.connect(
            self.update_extent_from_rectangle)
        self.capture_button.clicked.connect(self.drag_rectangle_on_map_canvas)

        # Setup pan tool
        self.pan_tool = QgsMapToolPan(self.canvas)
        self.canvas.setMapTool(self.pan_tool)

        # Setup helper for admin_level
        json_file_path = resources_path('osm', 'admin_level_per_country.json')
        if os.path.isfile(json_file_path):
            self.countries = json.load(open(json_file_path))
            self.bbox_countries = None
            self.populate_countries()
            # connect
            self.country_comboBox.currentIndexChanged.connect(
                self.update_helper_political_level)
            self.admin_level_comboBox.currentIndexChanged.connect(
                self.update_helper_political_level)

        self.update_extent_from_map_canvas()
Ejemplo n.º 44
0
def netNameValidator(parent):
    validator = QRegExpValidator(FQDN_REGEXP, parent)
    validator.setObjectName('netNameValidator')
    return validator
Ejemplo n.º 45
0
    def __init__(self,parent=None,key=None):
        super(PostgreSQLConfigPage, self).__init__(parent)
        
        self.parent = parent 
        self.key = key
        
        try:
            (pghost,pgport,pgdbname,pgschema,pgusr,pgpwd,pgover,pgconfig,pgepsg,pgcql) = self.parent.mfr.readPostgreSQLConfig()
        except:
            (pghost,pgport,pgdbname,pgschema,pgusr,pgpwd,pgover,pgconfig,pgepsg,pgcql) = (None,)*10
        
        self.setTitle('PostgreSQL/PostGIS Configuration Options')
        self.setSubTitle('Enter the hostname/ip-address, port number, name and schema of your PostgreSQL server instance.')
     
        QToolTip.setFont(QFont('SansSerif', 10))
              
        #labels
        hostLabel = QLabel('PostgreSQL Host')
        portLabel = QLabel('PostgreSQL Port')
        dbnameLabel = QLabel('PostgreSQL DB Name')
        schemaLabel = QLabel('PostgreSQL DB Schema')
        usrLabel = QLabel('Username')
        pwdLabel = QLabel('Password')
        
        #edit boxes
        self.hostEdit = QLineEdit(pghost)
        self.hostEdit.setToolTip('Enter the name of your PostgreSQL host/IP-address')
        self.portEdit = QLineEdit('5432' if LU.assessNone(pgport) is None else pgport)
        self.portEdit.setToolTip('Enter the PostgreSQL listen port')
        self.dbnameEdit = QLineEdit(pgdbname)
        self.dbnameEdit.setToolTip('Enter the name of the PostgreSQL DB to connect with')
        self.schemaEdit = QLineEdit(pgschema)
        self.schemaEdit.setToolTip('Set the database schema here')
        self.usrEdit = QLineEdit(pgusr)
        self.usrEdit.setToolTip('Name of PostgreSQL account/user')
        self.pwdEdit = QLineEdit('')#pgpwd
        self.pwdEdit.setToolTip('Enter PostgreSQL account password')
        self.pwdEdit.setEchoMode(QLineEdit.Password)
        
        self.portEdit.setValidator(QRegExpValidator(QRegExp("\d{1,5}"), self))
        
        
        self.registerField(self.key+"host",self.hostEdit)
        self.registerField(self.key+"port",self.portEdit)
        self.registerField(self.key+"dbname",self.dbnameEdit)
        self.registerField(self.key+"schema",self.schemaEdit)
        self.registerField(self.key+"usr",self.usrEdit)
        self.registerField(self.key+"pwd",self.pwdEdit)

        #grid
        grid = QGridLayout()
        grid.setSpacing(10)
        
        #layout
        grid.addWidget(hostLabel, 1, 0)
        grid.addWidget(self.hostEdit, 1, 2)
        
        grid.addWidget(portLabel, 2, 0)
        grid.addWidget(self.portEdit, 2, 2)
        
        grid.addWidget(dbnameLabel, 3, 0)
        grid.addWidget(self.dbnameEdit, 3, 2)
        
        grid.addWidget(schemaLabel, 4, 0)
        grid.addWidget(self.schemaEdit, 4, 2)
        
        grid.addWidget(usrLabel, 5, 0)
        grid.addWidget(self.usrEdit, 5, 2)
        
        grid.addWidget(pwdLabel, 6, 0)
        grid.addWidget(self.pwdEdit, 6, 2)
              
        #layout                
        self.setLayout(grid)  
Ejemplo n.º 46
0
def netValidator(parent):
    validator = QRegExpValidator(QRegExp(NET_ALL_REGEXP), parent)
    validator.setObjectName('netValidator')
    return validator
Ejemplo n.º 47
0
    def __init__(self, parent=None, **kwargs):
        self._delimiter_idx = 0
        self._delimiter_custom = "|"
        self._delimiter = ","
        self._quotechar = "'"
        self._escapechar = "\\"
        self._doublequote = True
        self._skipinitialspace = False

        super(QWidget, self).__init__(parent, **kwargs)

        # Dialect options
        form = QFormLayout()
        self.delimiter_cb = QComboBox()
        self.delimiter_cb.addItems(
            [name for name, _ in self._PresetDelimiters])
        self.delimiter_cb.insertSeparator(self.delimiter_cb.count())
        self.delimiter_cb.addItem("Other")

        self.delimiter_cb.setCurrentIndex(self._delimiter_idx)
        self.delimiter_cb.activated.connect(self._on_delimiter_idx_changed)

        validator = QRegExpValidator(QRegExp("."))
        self.delimiteredit = LineEdit(self._delimiter_custom,
                                      enabled=False,
                                      minimumContentsLength=2)
        self.delimiteredit.setValidator(validator)
        self.delimiteredit.editingFinished.connect(self._on_delimiter_changed)

        delimlayout = QHBoxLayout()
        delimlayout.setContentsMargins(0, 0, 0, 0)
        delimlayout.addWidget(self.delimiter_cb)
        delimlayout.addWidget(self.delimiteredit)

        self.quoteedit = LineEdit(self._quotechar, minimumContentsLength=2)
        self.quoteedit.setValidator(validator)
        self.quoteedit.editingFinished.connect(self._on_quotechar_changed)

        self.escapeedit = LineEdit(self._escapechar, minimumContentsLength=2)
        self.escapeedit.setValidator(validator)
        self.escapeedit.editingFinished.connect(self._on_escapechar_changed)

        #         self.skipinitialspace_cb = QCheckBox(
        #             checked=self._skipinitialspace
        #         )

        form.addRow("Cell delimiter", delimlayout)
        form.addRow("Quote character", self.quoteedit)
        form.addRow("Escape character", self.escapeedit)

        form.addRow(QFrame(self, frameShape=QFrame.HLine))

        # File format option
        self.missingedit = QLineEdit()
        self.missingedit.editingFinished.connect(self.format_changed)

        form.addRow("Missing values", self.missingedit)

        self.header_format_cb = QComboBox()
        self.header_format_cb.addItems([
            "No header", "Plain header", "Orange header",
            "Orange simplified header"
        ])
        self.header_format_cb.currentIndexChanged.connect(self.format_changed)
        form.addRow("Header", self.header_format_cb)

        self.setLayout(form)
        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
Ejemplo n.º 48
0
def proxyValidator(parent):
    # FIXME this regexp is buggy, it match 'https://:foo.be/'
    # it also match http://///
    validator = QRegExpValidator(QRegExp('^https?://(\S+(:\S+)?@)?(\S)+(:\d{1,5})?/?$'), parent)
    validator.setObjectName('proxyValidator')
    return validator
Ejemplo n.º 49
0
def mailValidator(parent):
    validator = QRegExpValidator(MAIL_REGEXP, parent)
    validator.setObjectName('mailValidator')
    return validator
Ejemplo n.º 50
0
class BruteForceView(Widget):

    def __init__(self, parent):
        super(BruteForceView, self).__init__("bruteforce", parent)
        self.category = "bf"

        regex = QRegExp("\d{1,6}")
        self.__validator = QRegExpValidator(regex, self.lineEditPort)
        self.lineEditPort.setValidator(self.__validator)

        regex = QRegExp("\d{1,5}")

        self.__validator = QRegExpValidator(regex, self.lineEditPort)
        self.lineEditMaximum.setValidator(self.__validator)

        # Connect buttons
        self.pushButtonCancel.clicked.connect(self.pushButtonCancelClicked)
        self.pushButtonExploit.clicked.connect(self.pushButtonExploitClicked)
        self.toolButtonUsers.clicked.connect(self.toolButtonUsersClicked)
        self.toolButtonPasswords.clicked.connect(self.toolButtonPasswordsClicked)

        # Connect signal and thread
        self.__communicate = Communicate()
        self.__exploitThread = ExploitThread(self.__communicate)
        self.__communicate.finishExploit.connect(self.setResultExploit)

        # Button and progressbar
        self.setProgressBarState(0)
        self.pushButtonCancel.setEnabled(False)

        # Generator
        self.__generatorUsers = Generator()
        self.__generatorPasswords = Generator()

    def check(self):
        if Network.ping(self.exploit.ip):
            if not self.isPort() or not str(self.lineEditUsers.text()) or not str(self.lineEditPasswords.text()) or not str(self.lineEditMaximum.text()):
                MessageBox.critical("Error", "You have to complete the information")
                return False
            else:
                users = str(self.lineEditUsers.text())
                lusers = str(self.lineEditLengthsUsers.text())
                passwords = str(self.lineEditPasswords.text())
                lpasswords = str(self.lineEditLengthsPasswords.text())
                maximum = str(self.lineEditMaximum.text())
                if not self.__generatorUsers.check(users, lusers, maximum) or not self.__generatorPasswords.check(passwords, lpasswords, maximum):
                    MessageBox.critical("Error", "Each range need a length")
                    return False
                else:
                    return True
        else:
            MessageBox.critical("Error", "Destination Host Unreachable")
            return False

    def isPort(self):
        if str(self.lineEditPort.text()):
            state = self.__validator.validate(self.lineEditPort.text(), 0)[0]
            return state == QValidator.Acceptable
        else:
            return False

    def pushButtonCancelClicked(self):
        self.__exploitThread.terminate()
        self.setProgressBarState(3)
        self.pushButtonCancel.setEnabled(False)
        self.pushButtonExploit.setEnabled(True)

    def pushButtonExploitClicked(self):
        if self.check():
            self.plainTextEditData.clear()
            try:
                self.setProgressBarState(2)
                self.pushButtonExploit.setEnabled(False)
                self.pushButtonCancel.setEnabled(True)

                if str(self.lineEditUsers.text()):
                    if exists(str(self.lineEditUsers.text())):
                        users = Parse.getContentFromFile(str(self.lineEditUsers.text()))
                    else:
                        users = self.__generatorUsers.create()
                else:
                    users = None

                if str(self.lineEditPasswords.text()):
                    if exists(str(self.lineEditPasswords.text())):
                        passwords = Parse.getContentFromFile(str(self.lineEditPasswords.text()))
                    else:
                        passwords = self.__generatorPasswords.create()
                else:
                    passwords = None

                if not users or not passwords:
                    MessageBox.critical("Error", "An error happened while items generation or read the dictionary.")
                    self.pushButtonCancelClicked()

                data = {"port": int(self.lineEditPort.text()), "users": users, "passwords": passwords}

                self.__exploitThread.setExploit(self.exploit, data)
                self.__exploitThread.start()
            except Exception as e:
                MessageBox.critical("Error", str(e.args))

    def setExploit(self, exploit):
        self.exploit = exploit
        self.plainTextEditData.appendPlainText("")
        default = self.exploit.default()
        if default:
            try:
                self.lineEditPort.setText(default["port"])
                self.lineEditUsers.setText(default["users"])
                self.lineEditPasswords.setText(default["passwords"])
            except KeyError:
                pass

    def setProgressBarState(self, state):
        if state == 0:
            self.progressBar.hide()
            self.progressBar.setRange(0, 1)
            self.progressBar.setValue(0)
        elif state == 1:
            self.progressBar.setFormat("Waiting")
            self.progressBar.setRange(0, 1)
            self.progressBar.setValue(0)
        elif state == 2:
            self.progressBar.setFormat("Exploiting")
            self.progressBar.setRange(0, 0)
            self.progressBar.show()
        elif state == 3:
            self.progressBar.setFormat("Completed")
            self.progressBar.setRange(0, 1)
            self.progressBar.setValue(1)
            self.progressBar.show()

    def setResultExploit(self, result):
        if "Success" in result:
            self.exploit.vulnerable = True
            self.vulnerable = True

        self.plainTextEditData.appendPlainText(result)
        self.setProgressBarState(3)
        self.pushButtonExploit.setEnabled(True)

    def toolButtonUsersClicked(self):
        self.lineEditUsers.setText(FileDialog.getOpenFileName("txt"))

    def toolButtonPasswordsClicked(self):
        self.lineEditPasswords.setText(FileDialog.getOpenFileName("txt"))