Пример #1
0
    def highlightBlock(self, text):
        """Apply syntax highlighting to the given block of text."""
        for expression, nth, format in self.rules:
            index = expression.indexIn(text, 0)

            while index >= 0:
                # We actually want the index of the nth match
                index = expression.pos(nth)
                length = expression.cap(nth).length()
                self.setFormat(index, length, format)
                index = expression.indexIn(text, index + length)

        self.setCurrentBlockState(0)
        if not self.multi_start:
            # Do multi-line strings
            in_multiline = self.match_multiline(text, *self.tri_single)
            if not in_multiline:
                in_multiline = self.match_multiline(text, *self.tri_double)
        else:
            # Do multi-line comment
            self.comment_multiline(text, self.multi_end[0], *self.multi_start)

        #Spaces
        expression = QRegExp('\s+')
        index = expression.indexIn(text, 0)
        while index >= 0:
            index = expression.pos(0)
            length = expression.cap(0).length()
            self.setFormat(index, length, STYLES['spaces'])
            index = expression.indexIn(text, index + length)
Пример #2
0
    def run(self):
        self.msleep(300)
        block = self._highlighter.document().begin()
        while block.blockNumber() != -1:
            text = block.text()
            formats = []

            for expression, nth, char_format in self._highlighter.rules:
                index = expression.indexIn(text, 0)

                while index >= 0:
                    # We actually want the index of the nth match
                    index = expression.pos(nth)
                    length = expression.cap(nth).length()

                    formats.append((index, length, char_format))
                    index = expression.indexIn(text, index + length)

            # Spaces
            expression = QRegExp("\s+")
            index = expression.indexIn(text, 0)
            while index >= 0:
                index = expression.pos(0)
                length = expression.cap(0).length()
                formats.append((index, length, STYLES["spaces"]))
                index = expression.indexIn(text, index + length)

            self.styles[block.blockNumber()] = formats
            block = block.next()
    def event(self, event):
        if event.type() == QEvent.KeyPress:

            if event.key() in (Qt.Key_Shift, Qt.Key_Control, Qt.Key_AltGr, Qt.Key_Alt):
                return True

            regex = QRegExp(self.keyWordREGEX, Qt.CaseInsensitive, QRegExp.RegExp)
            if regex.exactMatch(self.text()) and not (event.key() == Qt.Key_Backspace): # 16777219 is the backspace
            #if event.key() != Qt.Key_Backspace and event.key() != Qt.Key_Space:
                QLineEdit.event(self, event)
                self.getWords()
                if not len(self.completions):
                    return True
                if self.text() == "":
                    return True

                if len(self.partials) >= 1:
                    autocomplete = self.partials[0]
                    self.applyCompletion(autocomplete)
                    signalAttach = QString(autocomplete)
                    self.AutoComplete.emit(signalAttach)    #if autocomplete got a "@" in it, only the part, starting with "@..." will be sent
                    return True
                else:
                    signalAttach = QString('NONE')
                    self.AutoComplete.emit(signalAttach)
                    return True


            else:
                return QLineEdit.event(self, event)

        else:
            return QLineEdit.event(self, event)
Пример #4
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()
Пример #5
0
 def get_cdrom_drives():
     drives = list(DEFAULT_DRIVES)
     cdinfo = QFile(LINUX_CDROM_INFO)
     if cdinfo.open(QIODevice.ReadOnly | QIODevice.Text):
         drive_names = []
         drive_audio_caps = []
         line = cdinfo.readLine()
         while not line.isEmpty():
             if line.indexOf(':') != -1:
                 key, values = line.split(':')
                 if key == 'drive name':
                     drive_names = QString(values).trimmed().split(QRegExp("\\s+"), QString.SkipEmptyParts)
                 elif key == 'Can play audio':
                     drive_audio_caps = [v == '1' for v in
                                         QString(values).trimmed().split(QRegExp("\\s+"), QString.SkipEmptyParts)]
             line = cdinfo.readLine()
         # Show only drives that are capable of playing audio
         for drive in drive_names:
             if drive_audio_caps[drive_names.indexOf(drive)]:
                 device = u'/dev/%s' % drive
                 symlink_target = QFile.symLinkTarget(device)
                 if symlink_target != '':
                     device = symlink_target
                 drives.append(device)
     return sorted(uniqify(drives))
Пример #6
0
 def __init__(self):
     self.regexp_str = "Wait(?: at most " + Regexfloat + " secs)? for measurements completion"
     self.label = "Wait(at most X secs) for measurements completion"
     self.regexp_str = "^ *" + self.regexp_str + " *$"  #so that the same string with heading and trailing whitespaces also matches
     self.regexp = QRegExp(self.regexp_str)
     self.waiting = False
     self.waiting_start = 0
class RegexHighlighter(QSyntaxHighlighter):
    def __init__(self, widget):
        QSyntaxHighlighter.__init__(self, widget)
        self.regex = None
        # create format type
        self.odd_format = QTextCharFormat()
        self.odd_format.setFontWeight(QFont.Bold)
        self.odd_format.setForeground(Qt.darkBlue)
        self.even_format = QTextCharFormat()
        self.even_format.setFontWeight(QFont.Bold)
        self.even_format.setForeground(Qt.darkMagenta)

    def set_regex(self, exp):
        self.regex = QRegExp(exp)

    def highlightBlock(self, text):
        if not self.regex:
            return
        matches = 0
        pos = self.regex.indexIn(text, 0)
        while (pos >= 0):
            length = self.regex.matchedLength()
            matches += 1
            if matches % 2 == 0:
                self.setFormat(pos, length, self.even_format)
            else:
                self.setFormat(pos, length, self.odd_format)
            # handle wildcard (*)
            if length == 0:
                pos += 1
            pos = self.regex.indexIn(text, pos + length)
Пример #8
0
def pg_tables(schema="public"):
    """
    Returns all the tables in the given schema minus the default PostGIS tables.
    Views are also excluded. See separate function for retrieving views.
    """
    t = text("SELECT table_name FROM information_schema.tables WHERE table_schema = :tschema and table_type = :tbtype " \
             "ORDER BY table_name ASC")
    result = _execute(t, tschema=schema, tbtype="BASE TABLE")

    pgTables = []

    for r in result:
        tableName = r["table_name"]

        #Remove default PostGIS tables
        tableIndex = getIndex(_postGISTables, tableName)
        if tableIndex == -1:

            #Validate if table is a lookup table and if it is, then omit
            rx = QRegExp("check_*")
            rx.setPatternSyntax(QRegExp.Wildcard)
            if not rx.exactMatch(tableName):
                pgTables.append(tableName)

    return pgTables
Пример #9
0
    def popup(self, pos=None, searchText=""):
        """
        Popup the menu at `pos` (in screen coordinates). 'Search' text field
        is initialized with `searchText` if provided.

        """
        if pos is None:
            pos = QPoint()

        self.__clearCurrentItems()

        self.__search.setText(searchText)
        patt = QRegExp("(^|\W)" + searchText)
        patt.setCaseSensitivity(False)
        self.__suggestPage.setFilterRegExp(patt)

        self.ensurePolished()

        if self.testAttribute(Qt.WA_Resized) and self.sizeGripEnabled():
            size = self.size()
        else:
            size = self.sizeHint()

        desktop = QApplication.desktop()
        screen_geom = desktop.availableGeometry(pos)

        # Adjust the size to fit inside the screen.
        if size.height() > screen_geom.height():
            size.setHeight(screen_geom.height())
        if size.width() > screen_geom.width():
            size.setWidth(screen_geom.width())

        geom = QRect(pos, size)

        if geom.top() < screen_geom.top():
            geom.setTop(screen_geom.top())

        if geom.left() < screen_geom.left():
            geom.setLeft(screen_geom.left())

        bottom_margin = screen_geom.bottom() - geom.bottom()
        right_margin = screen_geom.right() - geom.right()
        if bottom_margin < 0:
            # Falls over the bottom of the screen, move it up.
            geom.translate(0, bottom_margin)

        # TODO: right to left locale
        if right_margin < 0:
            # Falls over the right screen edge, move the menu to the
            # other side of pos.
            geom.translate(-size.width(), 0)

        self.setGeometry(geom)

        self.show()

        if searchText:
            self.setFocusProxy(self.__search)
        else:
            self.setFocusProxy(None)
Пример #10
0
class HoogleRunner(plasmascript.Runner):
    def init(self):
        """
        Initialize and register with Plasma.
        """
        self.myIcon = QIcon(self.package().filePath("images", "lambda.svg"))
        self.regExp = QRegExp("^hoogle (.*)$")
        syntax = Plasma.RunnerSyntax("hoogle :q:", "Query hoogle for :q:")
        self.addSyntax(syntax)
 
    def match(self, context):
        """
        Add a match to the given `context` iff the query starts with 'hoogle'.
        """
        if context.isValid() and self.regExp.exactMatch(context.query()):
            term = self.regExp.cap(1)
            m = Plasma.QueryMatch(self.runner)
            m.setText("Query Hoogle for '%s'" % term)
            m.setType(Plasma.QueryMatch.ExactMatch)
            m.setIcon(self.myIcon)
            m.setData(term)
            context.addMatch(term, m)
 
    def run(self, context, match):
        """
        Have KDE open the query in the browser.
        """
        urlString = QString("http://www.haskell.org/hoogle/?hoogle=")
        # Apparently Hoogle doesn't like percent encoded URLs.
        # urlString.append(QUrl.toPercentEncoding(match.data().toString()))
        urlString.append(match.data().toString())
        QDesktopServices().openUrl(QUrl(urlString))
Пример #11
0
    def set_selected_word(self, word, partial=True):
        """Set the word to highlight."""
        # partial = True for new highlighter compatibility
        hl_worthy = len(word) > 2
        if hl_worthy:
            self.selected_word_pattern = QRegExp(r'\b%s\b' %
                                                 self.sanitize(word))
        else:
            self.selected_word_pattern = None

        suffix = "(?![A-Za-z_\d])"
        prefix = "(?<![A-Za-z_\d])"
        word = re.escape(word)
        if not partial:
            word = "%s%s%s" % (prefix, word, suffix)
        lines = []
        pat_find = re.compile(word)
        document = self.document()
        for lineno, text in enumerate(document.toPlainText().splitlines()):
            if hl_worthy and pat_find.search(text):
                lines.append(lineno)
            elif self._old_search and self._old_search.search(text):
                lines.append(lineno)
        # Ask perrito if i don't know what the next line does:
        self._old_search = hl_worthy and pat_find
        self.rehighlight_lines(lines)
Пример #12
0
    def highlightBlock(self, text):
        for pattern, format in self.rules:
            exp = QRegExp(pattern)
            index = exp.indexIn(text)
            while index >= 0:
                length = exp.matchedLength()
                if exp.numCaptures() > 0:
                    self.setFormat(exp.pos(1), len(str(exp.cap(1))), format)
                else:
                    self.setFormat(exp.pos(0), len(str(exp.cap(0))), format)
                index = exp.indexIn(text, index + length)

        # Multi line strings
        start = self.multilineStart
        end = self.multilineEnd

        self.setCurrentBlockState(0)
        startIndex, skip = 0, 0
        if self.previousBlockState() != 1:
            startIndex, skip = start.indexIn(text), 3
        while startIndex >= 0:
            endIndex = end.indexIn(text, startIndex + skip)
            if endIndex == -1:
                self.setCurrentBlockState(1)
                commentLen = len(text) - startIndex
            else:
                commentLen = endIndex - startIndex + 3
            self.setFormat(startIndex, commentLen, self.stringFormat)
            startIndex, skip = (start.indexIn(text,
                                              startIndex + commentLen + 3), 3)
Пример #13
0
    def __init__(self, parent=None):
        super(PythonHighlighter, self).__init__(parent)

        self.initializeFormats()

        PythonHighlighter.Rules.append((QRegExp(
                "|".join([r"\b%s\b" % keyword for keyword in KEYWORDS])),
                "keyword"))
        PythonHighlighter.Rules.append((QRegExp(
                "|".join([r"\b%s\b" % builtin for builtin in BUILTINS])),
                "builtin"))
        PythonHighlighter.Rules.append((QRegExp(
                "|".join([r"\b%s\b" % constant
                for constant in CONSTANTS])), "constant"))
        PythonHighlighter.Rules.append((QRegExp(
                r"\b[+-]?[0-9]+[lL]?\b"
                r"|\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b"
                r"|\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"),
                "number"))
        PythonHighlighter.Rules.append((QRegExp(
                r"\bPyQt4\b|\bQt?[A-Z][a-z]\w+\b"), "pyqt"))
        PythonHighlighter.Rules.append((QRegExp(r"\b@\w+\b"),
                "decorator"))
        stringRe = QRegExp(r"""(?:'[^']*'|"[^"]*")""")
        stringRe.setMinimal(True)
        PythonHighlighter.Rules.append((stringRe, "string"))
        self.stringRe = QRegExp(r"""(:?"["]".*"["]"|'''.*''')""")
        self.stringRe.setMinimal(True)
        PythonHighlighter.Rules.append((self.stringRe, "string"))
        self.tripleSingleRe = QRegExp(r"""'''(?!")""")
        self.tripleDoubleRe = QRegExp(r'''"""(?!')''')
Пример #14
0
 def data(self, arg, value, *args, **kwargs):
     ip_reg = QRegExp(IP_REG)
     if (isinstance(value, list) or isinstance(value, tuple) or isinstance(value, str) or isinstance(value, int)) \
             and not ip_reg.exactMatch(str(value)):
         return ArgDataUserID(arg, value, *args, **kwargs)
     else:
         return ArgDataIP(arg, value, *args, **kwargs)
Пример #15
0
def pg_tables(schema="public", exclude_lookups=False):
    """
    Returns all the tables in the given schema minus the default PostGIS tables.
    Views are also excluded. See separate function for retrieving views.
    """
    t = text("SELECT table_name FROM information_schema.tables WHERE table_schema = :tschema and table_type = :tbtype " \
             "ORDER BY table_name ASC")
    result = _execute(t,tschema = schema,tbtype = "BASE TABLE")
        
    pgTables = []
        
    for r in result:
        tableName = r["table_name"]
        
        #Remove default PostGIS tables
        tableIndex = getIndex(_postGISTables, tableName)
        if tableIndex == -1:
            if exclude_lookups:
                #Validate if table is a lookup table and if it is, then omit
                rx = QRegExp("check_*")
                rx.setPatternSyntax(QRegExp.Wildcard)
                
                if not rx.exactMatch(tableName):
                    pgTables.append(tableName)
                    
            else:
                pgTables.append(tableName)
            
    return pgTables
Пример #16
0
    def _find_in_files(self):
        """Trigger the search on the files."""
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join([word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
                                        by_phrase)
Пример #17
0
    def run(self):
        styles = {}
        self.msleep(300)
        block = self._highlighter.document().begin()
        while block.blockNumber() != -1:
            text = block.text()
            formats = []

            for expression, nth, char_format in self._highlighter.rules:
                index = expression.indexIn(text, 0)

                while index >= 0:
                    # We actually want the index of the nth match
                    index = expression.pos(nth)
                    length = expression.cap(nth).length()

                    formats.append((index, length, char_format))
                    index = expression.indexIn(text, index + length)

            #Spaces
            expression = QRegExp('\s+')
            index = expression.indexIn(text, 0)
            while index >= 0:
                index = expression.pos(0)
                length = expression.cap(0).length()
                formats.append((index, length, STYLES['spaces']))
                index = expression.indexIn(text, index + length)

            styles[block.blockNumber()] = formats
            block = block.next()
        self.emit(SIGNAL("highlightingDetected(PyQt_PyObject)"), styles)
Пример #18
0
    def popup(self, pos=None, searchText=""):
        """
        Popup the menu at `pos` (in screen coordinates). 'Search' text field
        is initialized with `searchText` if provided.

        """
        if pos is None:
            pos = QPoint()

        self.__clearCurrentItems()

        self.__search.setText(searchText)
        patt = QRegExp("(^|\W)"+searchText)
        patt.setCaseSensitivity(False)
        self.__suggestPage.setFilterRegExp(patt)

        self.ensurePolished()

        if self.testAttribute(Qt.WA_Resized) and self.sizeGripEnabled():
            size = self.size()
        else:
            size = self.sizeHint()

        desktop = QApplication.desktop()
        screen_geom = desktop.availableGeometry(pos)

        # Adjust the size to fit inside the screen.
        if size.height() > screen_geom.height():
            size.setHeight(screen_geom.height())
        if size.width() > screen_geom.width():
            size.setWidth(screen_geom.width())

        geom = QRect(pos, size)

        if geom.top() < screen_geom.top():
            geom.setTop(screen_geom.top())

        if geom.left() < screen_geom.left():
            geom.setLeft(screen_geom.left())

        bottom_margin = screen_geom.bottom() - geom.bottom()
        right_margin = screen_geom.right() - geom.right()
        if bottom_margin < 0:
            # Falls over the bottom of the screen, move it up.
            geom.translate(0, bottom_margin)

        # TODO: right to left locale
        if right_margin < 0:
            # Falls over the right screen edge, move the menu to the
            # other side of pos.
            geom.translate(-size.width(), 0)

        self.setGeometry(geom)

        self.show()

        if searchText:
            self.setFocusProxy(self.__search)
        else:
            self.setFocusProxy(None)
Пример #19
0
 def __init__(self):
     self.regexp_str = "Set PPMS Field to " + Regexfloat + " Oe @ " + Regexfloat + " Oe/s (Linear|NoOvershoot|Oscillate)? (Persistent|Driven)?"
     self.label = "Set PPMS Field to X Oe @ X Oe/s (Linear|NoOvershoot|Oscillate) (Persistent|Driven)"
     self.regexp_str = "^ *" + self.regexp_str + " *$"  #so that the same string with heading and trailing whitespaces also matches
     self.regexp = QRegExp(self.regexp_str)
     self.waiting = False
     self.waiting_start = 0
Пример #20
0
 def __init__(self):
     self.regexp_str = "Wait(?: at most " + Regexfloat + " secs)? for PPMS Field to reach " + Regexfloat + " Oe"
     self.label = "Wait(at most X secs) for PPMS Field to reach X Oe"
     self.regexp_str = "^ *" + self.regexp_str + " *$"  #so that the same string with heading and trailing whitespaces also matches
     self.regexp = QRegExp(self.regexp_str)
     self.waiting = False
     self.waiting_start = 0
Пример #21
0
 def __init__(self, main):
     #        print "|".join(dir(main.ui))
     self.regexp_str = "Set UI (" + "|".join(dir(
         main.ui)) + ") to " + Regexfloat
     self.label = "Set UI PROPERTY to FLOAT"
     self.regexp_str = "^ *" + self.regexp_str + " *$"  #so that the same string with heading and trailing whitespaces also matches
     self.regexp = QRegExp(self.regexp_str)
Пример #22
0
    def __init__(self, document):
        QSyntaxHighlighter.__init__(self, document)

        # Multi-line strings (expression, flag, style)
        # FIXME: The triple-quotes in these two lines will mess up the
        # syntax highlighting from this point onward
        self.tri_single = (QRegExp("'''"), 1, STYLES['string2'])
        self.tri_double = (QRegExp('"""'), 2, STYLES['string2'])

        rules = []

        # Keyword, operator, and brace rules

        rules += [(r'%s' % o, 0, STYLES['operator']) for o in self.operators]
        rules += [(r'%s' % b, 0, STYLES['brace']) for b in self.braces]
        rules += [(r'\b%s\b' % w, 0, STYLES['keyword']) for w in self.keywords]

        # All other rules
        rules += [

            # From '#' until a newline
            (r':[^(\n|;|\})]*', 0, STYLES['value']),
            (r'\/\*(.*)\*\/*', 0, STYLES['comment']),

            # Double-quoted string, possibly containing escape sequences
            (r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']),
            # Single-quoted string, possibly containing escape sequences
            (r"'[^'\\]*(\\.[^'\\]*)*'", 0, STYLES['string']),
        ]

        # Build a QRegExp for each pattern
        self.rules = [(QRegExp(pat), index, fmt)
                      for (pat, index, fmt) in rules]
Пример #23
0
    def __init__(self, parent=None):
        super(SWHighlighter, self).__init__(parent)
        self.initializeFormats()

        KEYWORDS = [
            "var", "let", "func", "if", "else", "for", "in", "while", "repeat",
            "read", "print", "call", "return", "break", "continue"
        ]

        BUILDINS = ["int", "char", "bool", "true", "false"]

        OPERATORS = [
            "\+", "-", "\*", "/", "%", "&", "\|", "~", "\^", "\!", "<", ">",
            "=", "\."
        ]

        SWHighlighter.Rules.append(
            (QRegExp("|".join([r"\b%s\b" % keyword
                               for keyword in KEYWORDS])), "keyword"))
        SWHighlighter.Rules.append(
            (QRegExp("|".join([r"\b%s\b" % buildin
                               for buildin in BUILDINS])), "buildin"))
        SWHighlighter.Rules.append(
            (QRegExp("|".join([r"%s" % operator
                               for operator in OPERATORS])), "operator"))
        SWHighlighter.Rules.append((QRegExp(r"\b[0-9]+\b"), "number"))
        SWHighlighter.Rules.append((QRegExp(r"/\*.*\*/"), "comment"))
Пример #24
0
    def __init__(self, parent=None):
        super(GithubCredentialsWizardPage,
              self).__init__(parent,
                             title="Credentials",
                             subTitle="Enter your username/password or token")

        # Radio Buttons

        self.userPassRadioButton = QRadioButton()
        self.userPassRadioButton.toggled.connect(self.changeMode)
        self.userPassRadioButton.toggled.connect(self.completeChanged.emit)

        self.tokenRadioButton = QRadioButton()
        self.tokenRadioButton.toggled.connect(self.changeMode)
        self.tokenRadioButton.toggled.connect(self.completeChanged.emit)

        #  LineEdits

        # usernameEdit
        self.usernameEdit = QLineEdit(textChanged=self.completeChanged.emit)
        # Username may only contain alphanumeric characters or dash
        # and cannot begin with a dash
        self.usernameEdit.setValidator(
            QRegExpValidator(QRegExp('[A-Za-z\d]+[A-Za-z\d-]+')))

        # passwordEdit
        self.passwordEdit = QLineEdit(textChanged=self.completeChanged.emit)
        self.passwordEdit.setValidator(QRegExpValidator(QRegExp('.+')))
        self.passwordEdit.setEchoMode(QLineEdit.Password)

        # tokenEdit
        self.tokenEdit = QLineEdit(textChanged=self.completeChanged.emit)
        # token may only contain alphanumeric characters
        self.tokenEdit.setValidator(QRegExpValidator(QRegExp('[A-Za-z\d]+')))
        self.tokenEdit.setEchoMode(QLineEdit.Password)

        # Form

        form = QFormLayout()
        form.addRow("<b>username/password</b>", self.userPassRadioButton)
        form.addRow("username: "******"password: "******"<b>token</b>", self.tokenRadioButton)
        form.addRow("token: ", self.tokenEdit)

        # Layout

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

        # Fields

        self.registerField("username", self.usernameEdit)
        self.registerField("password", self.passwordEdit)
        self.registerField("token", self.tokenEdit)

        self.userPassRadioButton.toggle()

        self.require_2fa = False
    def fillInAvailableTools(self):

        # Operations on the selected item
        choices = {}

        # Classification for the selected item
        classification = ""

        if self.model.isDir(self.currentIndex):
            regex = QRegExp("\\d{4}") # match directory names with four digits
            name = self.model.fileName(self.currentIndex)
            parentname = self.model.fileName(self.model.parent(self.currentIndex))
            isdir = self.model.isDir(self.currentIndex)
            parentisdir = self.model.isDir(self.model.parent(self.currentIndex))
            # print "%s %s %s %s" % (name, parentname,isdir,parentisdir)
            if isdir and regex.exactMatch(name):
                # We have a database dir
                # print "Database Dir"
                classification = "database"
            elif parentisdir and regex.exactMatch(parentname):
                # We have a dataset
                # print "Dataset Dir"
                classification = "dataset"
        else:
            regex = QRegExp("\\d{4}")
            model = self.model
            parentIndex = model.parent(self.currentIndex)
            parentparentIndex = model.parent(parentIndex)
            parentparentname = model.fileName(parentparentIndex)
            parentparentisdir = model.isDir(parentparentIndex)
            if parentparentisdir and regex.exactMatch(parentparentname):
                # We have a file with a parentparent which is a database classification
                classification = "array"

        # Build up a list of available operations based on the classification

        tool_set_nodes = [tool_set_node for tool_set_node in self.tool_library_node
                          if tool_set_node.tag == 'tool_group']
        tool_file_nodes = []
        for tool_set_node in tool_set_nodes:
            tool_file_nodes.extend([node for node in tool_set_node
                           if node.tag == 'tool'])

        # Find all tool_nodes that acts on the resolved classification
        # (by looking at the XML node 'acts_on')
        for tool_node in tool_file_nodes:
            acts_on_node = tool_node.find('acts_on')
            exports_to_node = tool_node.find('exports_to')

            if acts_on_node is None or exports_to_node is None:
                # This tool doesn't export anything
                continue

            tool_classifications = acts_on_node.text.split(',')
            exports_to_value = exports_to_node.text
            if classification in tool_classifications:
                choices[exports_to_value] = tool_node

        self.classification = classification
        return choices
Пример #26
0
 def set_selected_word(self, word):
     """Set the word to highlight."""
     if len(word) > 2:
         self.selected_word_pattern = QRegExp(
             r'\b%s\b' % self.sanitize(word))
     else:
         self.selected_word_pattern = None
Пример #27
0
 def __init__(self):
     self.regexp_str = "Wait(?: at most " + Regexfloat + " secs)? for magnet (X|Y|Z) to finish ramping"
     self.label = "Wait (at most X secs) for magnet (X|Y|Z) to finish ramping"
     self.regexp_str = "^ *" + self.regexp_str + " *$"  #so that the same string with heading and trailing whitespaces also matches
     self.regexp = QRegExp(self.regexp_str)
     self.waiting = False
     self.waiting_start = 0
Пример #28
0
    def __init__(self, document):
        QSyntaxHighlighter.__init__(self, document)

        # Multi-line strings (expression, flag, style)
        # FIXME: The triple-quotes in these two lines will mess up the
        # syntax highlighting from this point onward
        self.tri_single = (QRegExp("'''"), 1, STYLES['string2'])
        self.tri_double = (QRegExp('"""'), 2, STYLES['string2'])

        rules = []
        rules += [(r'\b%s\b' % w, 0, STYLES['keyword'])
            for w in Python.keywords]
        rules += [(r'%s' % o, 0, STYLES['operator'])
            for o in Python.operators]
        rules += [(r'%s' % b, 0, STYLES['brace'])
            for b in Python.braces]
        rules += [
            # Double-quoted string, possibly containing escape sequences
            (r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']),
            # Single-quoted string, possibly containing escape sequences
            (r"'[^'\\]*(\\.[^'\\]*)*'", 0, STYLES['string']),
            # 'def' followed by an identifier
            (r'\bdef\b\s*(\w+)', 1, STYLES['defclass']),
            # 'class' followed by an identifier
            (r'\bclass\b\s*(\w+)', 1, STYLES['defclass']),
            # From '#' until a newline
            (r'#[^\n]*', 0, STYLES['comment']),
        ]

        # Build a QRegExp for each pattern
        self.rules = [(QRegExp(pat), index, fmt)
            for (pat, index, fmt) in rules]
Пример #29
0
 def __init__(self):
     self.regexp_str = "Set VTI Loop (\d+) to " + Regexfloat + " K(?: @ " + Regexfloat + " K/min)?"
     self.label = "Set VTI Loop X to X K (@ X K/min)"
     self.regexp_str = "^ *" + self.regexp_str + " *$"  #so that the same string with heading and trailing whitespaces also matches
     self.regexp = QRegExp(self.regexp_str)
     self.waiting = False
     self.waiting_start = 0
Пример #30
0
    def __init__(self, parent=None):
        QSyntaxHighlighter.__init__(self, parent)
        self.parent = parent
        sqlKeyword = QTextCharFormat()
        sqlOperator = QTextCharFormat()

        self.highlightingRules = []

        #Keywords
        sqlKeyword.setFontWeight(QFont.Bold)
        sqlKeyword.setForeground(Qt.blue)

        sqlKeywords = ["AND", "OR", "LIKE"]
        for word in sqlKeywords:
            regExp = QRegExp("\\b" + word + "\\b", Qt.CaseInsensitive)
            rule = HighlightingRule(regExp, sqlKeyword)
            self.highlightingRules.append(rule)

        #Comparison Operators
        sqlOperator.setForeground(Qt.magenta)
        sqlOperators = ["<", ">", "="]
        for operator in sqlOperators:
            regExp = QRegExp("\\W" + operator + "\\W", Qt.CaseInsensitive)
            rule = HighlightingRule(regExp, sqlOperator)
            self.highlightingRules.append(rule)
Пример #31
0
 def __init__(self):
     self.regexp_str = "Wait(?: at most " + Regexfloat + " secs)? for channel (\w) to reach " + Regexfloat + " \+/\- " + Regexfloat + " K"
     self.label = "Wait(at most X secs) for channel X to reach X +/- X K"
     self.regexp_str = "^ *" + self.regexp_str + " *$"  #so that the same string with heading and trailing whitespaces also matches
     self.regexp = QRegExp(self.regexp_str)
     self.waiting = False
     self.waiting_start = 0
Пример #32
0
 def __init__(self):
     self.regexp_str = "Set PPMS Temperature to " + Regexfloat + " K @ " + Regexfloat + " K/min (FastSettle|NoOvershoot)?"
     self.label = "Set PPMS Temperature to X K @ X K/min (FastSettle/NoOvershoot)"
     self.regexp_str = "^ *" + self.regexp_str + " *$"  #so that the same string with heading and trailing whitespaces also matches
     self.regexp = QRegExp(self.regexp_str)
     self.waiting = False
     self.waiting_start = 0
Пример #33
0
    def run(self):
        """Execute this rules in another thread to avoid blocking the ui."""
        styles = {}
        self.msleep(300)
        block = self._highlighter.document().begin()
        while block.blockNumber() != -1:
            text = block.text()
            formats = []

            for expression, nth, char_format in self._highlighter.rules:
                index = expression.indexIn(text, 0)

                while index >= 0:
                    # We actually want the index of the nth match
                    index = expression.pos(nth)
                    length = len(expression.cap(nth))

                    formats.append((index, length, char_format))
                    index = expression.indexIn(text, index + length)

            # Spaces
            expression = QRegExp("\s+")
            index = expression.indexIn(text, 0)
            while index >= 0:
                index = expression.pos(0)
                length = len(expression.cap(0))
                formats.append((index, length, STYLES["spaces"]))
                index = expression.indexIn(text, index + length)

            styles[block.blockNumber()] = formats
            block = block.next()
        self.emit(SIGNAL("highlightingDetected(PyQt_PyObject)"), styles)
Пример #34
0
    def highlightBlock(self, text):
        #for every pattern
        for pattern, format in self.highlightingRules:
            #Create a regular expression from the retrieved pattern
            expression = QRegExp(pattern)
            #Check what index that expression occurs at with the ENTIRE text
            index = expression.indexIn(text)
            #While the index is greater than 0
            while index >= 0:
                #Get the length of how long the expression is true, set the format from the start to the length with the text format
                length = expression.matchedLength()
                self.setFormat(index, length, format)
                #Set index to where the expression ends in the text
                index = expression.indexIn(text, index + length)

        #HANDLE QUOTATION MARKS NOW.. WE WANT TO START WITH " AND END WITH ".. A THIRD " SHOULD NOT CAUSE THE WORDS INBETWEEN SECOND AND THIRD TO BE COLORED
        self.setCurrentBlockState(0)
        startIndex = 0
        if self.previousBlockState() != 1:
            startIndex = self.valueStartExpression.indexIn(text)
        while startIndex >= 0:
            endIndex = self.valueEndExpression.indexIn(text, startIndex)
            if endIndex == -1:
                self.setCurrentBlockState(1)
                commentLength = len(text) - startIndex
            else:
                commentLength = endIndex - startIndex + self.valueEndExpression.matchedLength(
                )
            self.setFormat(startIndex, commentLength, self.valueFormat)
            startIndex = self.valueStartExpression.indexIn(
                text, startIndex + commentLength)
Пример #35
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)
Пример #36
0
 def findcontrol(self, name):
     regex = QRegExp("^{}$".format(name))
     regex.setCaseSensitivity(Qt.CaseInsensitive)
     try:
         widget = self.findChildren(QWidget, regex)[0]
     except IndexError:
         widget = None
     return widget
Пример #37
0
    def getIndent(self,text):
		spaces= QRegExp("^(\\s*).*$")
		#~ indentation=""
		#~ if len(text) > 0 and text[-1] in [':', '{', '(', '[']:
				#~ indentation="	"
		if spaces.indexIn(text) == -1:
			return ""
		return spaces.cap(1)
Пример #38
0
 def findcontrol(self, name):
     regex = QRegExp("^{}$".format(QRegExp.escape(name)))
     regex.setCaseSensitivity(Qt.CaseInsensitive)
     try:
         widget = self.findChildren(QWidget, regex)[0]
     except IndexError:
         widget = None
     return widget
Пример #39
0
def listToRegExp(lst):
    if (len(lst) < 1):
        return QRegExp()
    exp = str(lst[0])
    if (len(lst) > 1):
        for element in lst[1:]:
            exp = exp + '|' + str(element)
    return QRegExp('\\b(' + exp + ')\\b')
Пример #40
0
 def end_multilines(self):
     strdef = (QRegExp(self.__start_pattern), QRegExp(self.__end_pattern),
               0, self.get_style(self.__style))
     self._comments.append(strdef)
     del self.__style
     del self.__escape
     del self.__start_pattern
     del self.__end_pattern
Пример #41
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)
Пример #42
0
 def enable_fields(self, index):
     hours_reg = QRegExp(r"0*[0-9]{1,3}")
     sec_reg = QRegExp(r"(0*[0-9])|(0*[0-5][0-9])")
     for counter, line_edit in enumerate(self.lineEdits_list[index - 1]):
         line_edit.setEnabled(self.valve_list[index - 1].isChecked())
         if counter % 3 == 0:
             line_edit.setValidator(QRegExpValidator(hours_reg, self))
         else:
             line_edit.setValidator(QRegExpValidator(sec_reg, self))
Пример #43
0
 def getData(self, error):
     if error:
         self.html = self.http.errorString()
     else:
         self.html = self.http.readAll()
     # the following is a hack to handle redirects...
     regexp = QRegExp(r'Redirect\sto\s\<a\shref=\"(.*)\">')
     if regexp.indexIn(QString(self.html)) > -1:
         self.setSource(QUrl(regexp.capturedTexts()[1]))
Пример #44
0
 def find(self, name):
     location = QString(robjects.r.help(unicode(name))[0])
     regexp = QRegExp(r"(library.*)")
     start = regexp.indexIn(location)
     end = location.lastIndexOf("/")
     name = location[end+1:]
     location = location[start-1:]+".html"
     location.replace("help", "html")
     self.help_open(location, name, location)
Пример #45
0
    def __setup_ui(self):
        self.setMaximumSize(300, 300)
        self.setMinimumSize(300, 300)
        vlayout = QVBoxLayout()

        host_layout = QHBoxLayout()
        port_layout = QHBoxLayout()
        slotid_layout = QHBoxLayout()
        intfid_layout = QHBoxLayout()
        onuid_layout = QHBoxLayout()
        btn_layout = QHBoxLayout()

        host_layout.addWidget(QLabel('Host'), 3)
        self.__host_edit = QLineEdit('192.168.184.128')
        #self.__host_edit = QLineEdit()
        self.__host_edit.setValidator(QRegExpValidator(self.__host_reg))
        host_layout.addWidget(self.__host_edit, 7)

        port_layout.addWidget(QLabel('Port'), 3)
        self.__port_edit = QLineEdit('6641')
        #self.__port_edit = QLineEdit()
        self.__port_edit.setValidator(QRegExpValidator(self.__port_reg))
        port_layout.addWidget(self.__port_edit, 7)

        slotid_layout.addWidget(QLabel('Slot id'), 3)
        # self.__port_edit = QLineEdit('6641')
        self.__slotid_edit = QLineEdit('1')
        self.__slotid_edit.setValidator(QRegExpValidator(QRegExp("[0-9]")))
        slotid_layout.addWidget(self.__slotid_edit, 7)

        intfid_layout.addWidget(QLabel('Intf id'), 3)
        self.__intfid_edit = QLineEdit('0')
        self.__intfid_edit.setValidator(QRegExpValidator(
            QRegExp("[0-9][0-9]")))
        intfid_layout.addWidget(self.__intfid_edit, 7)

        onuid_layout.addWidget(QLabel('Intf id'), 3)
        # self.__port_edit = QLineEdit('6641')
        self.__onuid_edit = QLineEdit('1')
        self.__onuid_edit.setValidator(QRegExpValidator(QRegExp("[0-9][0-9]")))
        onuid_layout.addWidget(self.__onuid_edit, 7)

        self.ok_btn = QPushButton('ok')
        #self.ok_btn.setFlat(True)
        #self.ok_btn.setEnabled(False)
        self.cancel_btn = QPushButton('cancel')
        btn_layout.addWidget(self.ok_btn, 5)
        btn_layout.addWidget(self.cancel_btn, 5)

        vlayout.addLayout(host_layout)
        vlayout.addLayout(port_layout)
        vlayout.addLayout(slotid_layout)
        vlayout.addLayout(intfid_layout)
        vlayout.addLayout(onuid_layout)
        vlayout.addLayout(btn_layout)

        self.setLayout(vlayout)
Пример #46
0
	def highlightEntity(self,text,entity):
		if entity.style == self.Default:
			return
		expression=QRegExp(entity.pattern)
		index=expression.indexIn(text)
		while index>=0:
			length =expression.matchedLength()
			self.setFormat(index,length,self.style(entity.style))
			index=expression.indexIn(text,index+length)
Пример #47
0
    def __init__(self, document):
        super(Highlighter, self).__init__(document)
        STYLES = {
        'preprocessor': self.format('darkMagenta'),
        'keyword': self.format('darkOrange'),
        'special': self.format('darkMagenta'),
        'operator': self.format('darkMagenta'),
        'brace': self.format('darkGray'),
        'defclass': self.format('blue'),
        'string': self.format('green'),
        'string2': self.format('green'),
        'comment': self.format('grey'),
        'framework': self.format('blue'),
        }

        #Init error format
        self.err_format = self.format('red', ('bold', 'underline'))
        self.errors = self.parent().parent().parent().errors

        # Multi-line strings (expression, flag, style)
        # FIXME: The triple-quotes in these two lines will mess up the
        # syntax highlighting from this point onward
        self.tri_double = ( QRegExp(r'''"""(?!')'''), 2, STYLES['string2'])
        self.tri_single = ( QRegExp(r"""'''(?!")"""), 1, STYLES['string2'])

        #Brace rule
        self.braces = QRegExp('(\{|\}|\(|\)|\[|\])')

        rules = []
        rules += [(r'\b%s\b' % w, 0, STYLES['keyword']) for w in Highlighter.keywords]
        rules += [(r'\b%s\b' % w, 0, STYLES['preprocessor']) for w in Highlighter.preprocessors]
        rules += [(r'\b%s\b' % w, 0, STYLES['special']) for w in Highlighter.specials]
        rules += [(r'%s' % o, 0, STYLES['operator']) for o in Highlighter.operators]
        rules += [(r'%s' % b, 0, STYLES['brace']) for b in Highlighter.braces]

        rules += [
                # Framework PyQt
                (r'\bPyQt4\b|\bPySide\b|\bQt?[A-Z][a-z]\w+\b',0,STYLES['framework']),
                # 'def' followed by an identifier
                (r'\bdef\b\s*(\w+)', 1, STYLES['defclass']),
                # 'class' followed by an identifier
                (r'\bclass\b\s*(\w+)', 1, STYLES['defclass']),
                # Double-quoted string, possibly containing escape sequences
                #(r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']),
                (r"""(:?"["]".*"["]"|'''.*''')""", 0, STYLES['string']),
                # Single-quoted string, possibly containing escape sequences
                #(r"'[^'\\]*(\\.[^'\\]*)*'", 0, STYLES['string']),
                (r"""(?:'[^']*'|"[^"]*")""", 0, STYLES['string']),
                # From '#' until a newline
                (r'#[^\n]*', 0, STYLES['comment']),
        ]

        # Build a QRegExp for each pattern
        self.rules = [( QRegExp(pat), index, fmt) for (pat, index, fmt) in rules]
        self.rules[-2][0].setMinimal(True)
        self.rules[-3][0].setMinimal(True)
Пример #48
0
 def __init__(self):
     #Text that will appear in the list of commands on the right side of the Macro editor
     self.label = "Set start|stop|step angle to FLOAT"
     #Regular expression which may or may not catch parameters
     self.regexp_str = "Set (start|stop|step) angle to " + Regexfloat
     #Add this to the beginning and end of the regular expression
     #so that whitespaces before and after will not prevent the regex from matching
     self.regexp_str = "^ *" + self.regexp_str + " *$"
     #instantiate regex
     self.regexp = QRegExp(self.regexp_str)
Пример #49
0
 def end_pattern(self):
     regexp = QRegExp(self.__pattern)
     if 'I' in self.__flags:
         regexp.setCaseSensitivity(Qt.CaseInsensitive)
     rule = (regexp, 0, self.get_style(self.__style), )
     self._grammar.append(rule)
     del self.__pattern
     del self.__group
     del self.__flags
     del self.__style
 def __init__(self, editor, parent = None):
     """
     Constructor
     
     @param editor reference to the editor object (QScintilla.Editor)
     @param parent reference to the parent object (QObject)
     """
     CompleterBase.__init__(self, editor, parent)
     
     self.__defRX = QRegExp(r"""^[ \t]*def \w+\(""")
     self.__defSelfRX = QRegExp(r"""^[ \t]*def \w+\([ \t]*self[ \t]*[,)]""")
     self.__defClsRX = QRegExp(r"""^[ \t]*def \w+\([ \t]*cls[ \t]*[,)]""")
     self.__classRX = QRegExp(r"""^[ \t]*class \w+\(""")
     self.__importRX = QRegExp(r"""^[ \t]*from [\w.]+ """)
     self.__classmethodRX = QRegExp(r"""^[ \t]*@classmethod""")
     
     self.__defOnlyRX = QRegExp(r"""^[ \t]*def """)
     
     self.__ifRX = QRegExp(r"""^[ \t]*if """)
     self.__elifRX = QRegExp(r"""^[ \t]*elif """)
     self.__elseRX = QRegExp(r"""^[ \t]*else:""")
     
     self.__tryRX = QRegExp(r"""^[ \t]*try:""")
     self.__finallyRX = QRegExp(r"""^[ \t]*finally:""")
     self.__exceptRX = QRegExp(r"""^[ \t]*except """)
     self.__exceptcRX = QRegExp(r"""^[ \t]*except:""")
     
     self.__whileRX = QRegExp(r"""^[ \t]*while """)
     self.__forRX = QRegExp(r"""^[ \t]*for """)
     
     self.readSettings()
Пример #51
0
 def handle_stdout(self):
     """
     Private slot to handle the readyReadStdout
     signal of the pylint process.
     """
     result_list = []
     #regex = QRegExp('(\w)\S*:\S*(\d*):.*: (.*)')
     regex = QRegExp('(\w)\s*:\s*(\d*):(.*)')
     regex_score = \
         QRegExp('.*at.(\d.\d*)/10.*')
     while self.pylint_pross and self.pylint_pross.canReadLine():
         result = unicode(self.pylint_pross.readLine())
         if result != None:
             pos = 0
             while True:
                 pos = regex.indexIn(result, pos)
                 if pos < 0:
                     if regex_score.indexIn(result, 0) >= 0:
                         self.win.setWindowTitle( \
                             "PyLint Results :" \
                             + str(regex_score.cap(1)) \
                             + ':'                                
                             + os.path.basename(str(self.parent.editor.filename)))
                     break
                 result_list.append((regex.cap(1), regex.cap(2), regex.cap(3)))
                 #print 'Append : ',(regex.cap(1), regex.cap(2), regex.cap(3))
                 pos = pos + regex.matchedLength()
                 
     if len(result_list)>0:
         self.win.append_results(result_list)
Пример #52
0
 def parse(self, text):
     """
     Parse some text, assuming it is in the form of:
         word 1414 {grammar} word 1414 {grammar} etc.
     and returns a list of tupples '(word, strong, grammar)'.
     """
     result = []
     r = QRegExp(r'([αβχδεφγηιϕκλμνοπθρστυςωξψζ]*)' +
                  '\s*' +
                  '([\d ]+)' +
                  '\s*' +
                  '\{(.*)\}\s*')
     r.setMinimal(True)
     pos = r.indexIn(text)
     while pos >= 0:
         # Some verbs have two strong numbers, we keep only the first,
         # the second one being grammar
         strong = r.cap(2).strip()
         if " " in strong:
             strong = strong.split(" ")[0]
         result.append((r.cap(1).strip(),
                        strong,
                        r.cap(3).strip()))
         pos = r.indexIn(text, pos + len(r.cap(0)))
     return result
Пример #53
0
    def highlightBlock(self, text):
        for pattern, format in self.rules:
            exp = QRegExp(pattern)
            index = exp.indexIn(text)
            while index >= 0:
                length = exp.matchedLength()
                if exp.numCaptures() > 0:
                    self.setFormat(exp.pos(1), len(str(exp.cap(1))), format)
                else:
                    self.setFormat(exp.pos(0), len(str(exp.cap(0))), format)
                index = exp.indexIn(text, index + length)

        # Multi line strings
        start = self.multilineStart
        end = self.multilineEnd

        self.setCurrentBlockState(0)
        startIndex, skip = 0, 0
        if self.previousBlockState() != 1:
            startIndex, skip = start.indexIn(text), 3
        while startIndex >= 0:
            endIndex = end.indexIn(text, startIndex + skip)
            if endIndex == -1:
                self.setCurrentBlockState(1)
                commentLen = len(text) - startIndex
            else:
                commentLen = endIndex - startIndex + 3
            self.setFormat(startIndex, commentLen, self.stringFormat)
            startIndex, skip = (start.indexIn(text,
                                              startIndex + commentLen + 3),
                                3)
Пример #54
0
 def get_pagelinks(self, field, arg_data):
     if isinstance(arg_data.value, int) and not arg_data.compatibility.user_id:
         value = arg_data.label
     else:
         value = arg_data.value
     ip_reg = QRegExp(IP_REG)
     if (isinstance(value, list) or isinstance(value, tuple) or isinstance(value, str) or isinstance(value, int)) \
             and not ip_reg.exactMatch(str(value)):
         return arg_types['username'].get_pagelinks(field, arg_data)
     else:
         return arg_types['ip_saddr_str'].get_pagelinks(field, arg_data)
Пример #55
0
    def highlightBlock(self, text):
        for rule in self.highlightingRules:
            expression = QRegExp(rule.pattern)
            index = expression.indexIn(text)

            while index >= 0:
                length = expression.matchedLength()
                self.setFormat(index, length, rule.format)
                index = expression.indexIn(text, index + length)

        self.setCurrentBlockState(0)
Пример #56
0
    def validate(self, _input, _pos):
        re_valid  = QRegExp('^([0-9A-Fa-f]{2})*$')
        re_interm = QRegExp('^([0-9A-Fa-f]{2})*([0-9A-Fa-f]{1})$')

        _input=_input.upper()

        if re_valid.exactMatch(_input):
            return (QValidator.Acceptable, _input, _pos)
        elif re_interm.exactMatch(_input):
            return (QValidator.Intermediate, _input, _pos)

        return (QValidator.Invalid, _input, _pos)
Пример #57
0
def hasEnvironmentEntry(key):
    """
    Module function to check, if the environment contains an entry.
    
    @param key key of the requested environment entry (string)
    @return flag indicating the presence of the requested entry (boolean)
    """
    filter = QRegExp("^%s[ \t]*=" % key)
    if isWindowsPlatform():
        filter.setCaseSensitivity(Qt.CaseInsensitive)
    
    entries = QProcess.systemEnvironment().filter(filter)
    return entries.count() > 0
Пример #58
0
 def _textAndFindFlags(self, backward=False):
     text = self.findComboBox.currentText()
     flags = QTextDocument.FindFlags()
     if backward:
         flags |= QTextDocument.FindBackward
     if not self.ignoreCaseCheckBox.isChecked():
         flags |= QTextDocument.FindCaseSensitively
     if self.flagsComboBox.currentIndex() == self.FULL_WORD:
         flags |= QTextDocument.FindWholeWords
     elif self.flagsComboBox.currentIndex() == self.STARTS_WITH:
         text = QRegExp("\\b%s" % text)
         caseSensitive = not self.ignoreCaseCheckBox.isChecked() and Qt.CaseSensitive or Qt.CaseInsensitive
         text.setCaseSensitivity(caseSensitive)
     return text, flags
Пример #59
0
    def slotCursorPositionChanged(self):
        """Called whenever the cursor position changes.
        
        Highlights matching characters if the cursor is at one of them.
        
        """
        cursor = self.edit().textCursor()
        block = cursor.block()
        text = block.text()

        # try both characters at the cursor
        col = cursor.position() - block.position()
        end = col + 1
        col = max(0, col - 1)
        for c in text[col:end]:
            if c in self.matchPairs:
                break
            col += 1
        else:
            self.clear()
            return

        # the cursor is at a character from matchPairs
        i = self.matchPairs.index(c)
        cursor.setPosition(block.position() + col)

        # find the matching character
        new = QTextCursor(cursor)
        if i & 1:
            # look backward
            match = self.matchPairs[i - 1]
            flags = QTextDocument.FindBackward
        else:
            # look forward
            match = self.matchPairs[i + 1]
            flags = QTextDocument.FindFlags()
            new.movePosition(QTextCursor.Right)

        # search, also nesting
        rx = QRegExp(QRegExp.escape(c) + "|" + QRegExp.escape(match))
        nest = 0
        while nest >= 0:
            new = cursor.document().find(rx, new, flags)
            if new.isNull():
                self.clear()
                return
            nest += 1 if new.selectedText() == c else -1
        cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor)
        self.highlight([cursor, new])
Пример #60
0
def function_arguments(fun):
    try:
        args = robjects.r('do.call(argsAnywhere, list("%s"))' % fun)
        args = QString(str(args))
        if args.contains("function"):
            regexp = QRegExp(r"function\s\(")
            start = regexp.lastIndexIn(args)
            regexp = QRegExp(r"\)")
            end = regexp.lastIndexIn(args)
            args = args[start:end+1].replace("function ", "") # removed fun
        else:
            args = args.replace("\n\n", "").remove("NULL")
    except Exception: # if something goes wrong, ignore it!
        args = QString()
    return args