示例#1
0
    def highlightBlock(self, text):
        for h in self.singleline:
            expression = QRegExp(h.expression)
            index = expression.indexIn(text)
            while index >= 0:
                length = expression.matchedLength()
                self.setFormat(index, length, h.get_format())
                index = expression.indexIn(text, index + length)

        for h in self.multiline:
            startIndex = 0
            self.setCurrentBlockState(0)
            expression = QRegExp(h.expression)
            expression_end = QRegExp(h.expression_end)

            if (self.previousBlockState() != 1):
                startIndex = expression.indexIn(text)

            while startIndex >= 0:
                endIndex = expression_end.indexIn(text, startIndex + 1)
                if endIndex == -1:
                    self.setCurrentBlockState(1)
                    commentLength = len(text) - startIndex
                else:
                    commentLength = endIndex - startIndex + \
                        expression_end.matchedLength()
                self.setFormat(startIndex, commentLength, h.get_format())
                startIndex = expression.indexIn(text,
                                                startIndex + commentLength)
 def handleHtmlPage(self, htmlPage):
         tup = ()
         self._gridList = []
         wina7rx = QRegExp("\{\"pool_id\":700(\\d+).*\"pool_end\":(\\d+).*\"guaranteed_amount\":(\\d+).*\}")
         posi = wina7rx.indexIn(str(htmlPage))
         ngrille = wina7rx.cap(1)
         print "ngrille=%s" % ngrille
         #self.gridList.append(wina7rx.cap(1))
         date = wina7rx.cap(2)
         print "date=%s" % date
         jackpot = wina7rx.cap(3)
         print "jackpot=%s" % jackpot
         tup = (ngrille, date, jackpot)
         self._gridList.append(tup)
         while posi != -1 :
                 posi = wina7rx.indexIn(str(htmlPage), posi+1)
                 ngrille = wina7rx.cap(1)
                 print "ngrille=%s" % ngrille
                 date = wina7rx.cap(2)
                 print "date=%s" % date
                 jackpot = wina7rx.cap(3)
                 print "jackpot=%s" % jackpot
                 tup = (ngrille, date, jackpot)
                 self._gridList.append(tup)
         print self._gridList
示例#3
0
  def highlightBlock(self, text):
    """@reimp @protected"""
    for pattern, format in self.highlightingRules:
      expression = QRegExp(pattern)
      index = expression.indexIn(text)
      while index >= 0:
        length = expression.matchedLength()
        self.setFormat(index, length, format)
        index = expression.indexIn(text, index + length)

    self.setCurrentBlockState(0)

    startIndex = 0
    if self.previousBlockState() != 1:
      startIndex = self.commentStartExpression.indexIn(text)

    while startIndex >= 0:
      endIndex = self.commentEndExpression.indexIn(text, startIndex +1)

      if endIndex == -1:
        self.setCurrentBlockState(1)
        commentLength = len(text) - startIndex
      else:
        commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength()

      self.setFormat(startIndex, commentLength,
          self.multiLineCommentFormat)
      startIndex = self.commentStartExpression.indexIn(text,
          startIndex + commentLength);
示例#4
0
 def highlightBlock(self, text):
     for rule in self.highlighting_rules:
         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)
示例#5
0
 def handleDistribHtmlPage(self, htmlPage):
         euro7startRx = QRegExp("data-grid-id=\"(\\d*)\"")
         indexGrille = ""
         posi = 0
         while posi != -1 and indexGrille != self._gridList[self._indexGrille][0]:
             print "posi = %d" % posi
             print "indexGrille = %s" % indexGrille
             print "self._indexGrille = %s" % self._gridList[self._indexGrille][0]
             posi= euro7startRx.indexIn(htmlPage, posi+1)
             indexGrille = euro7startRx.cap(1)
         euro7TeamRx = QRegExp("<label for=\"[^\"]*\">([^<]*)<\/label>")
         self._grid = Grille()
         self._grid.setReturnRate(0.75)
         self._grid.setFirstRankRate(0.55)
         self._grid.setScndRankRate(0.45)
         jackpot = int(self._gridList[self._index][2])
         self._grid.setJackpot(jackpot)
         self._grid.setNbPlayers(jackpot)
         index_l = 0
         total = 0
         #size_l = 5
         i=0
         #try:
         if True:
             posi= euro7TeamRx.indexIn(htmlPage, posi)
             print "posi = %d" % posi
             while posi != -1 and i < self._gridSize:
                 i += 1
                 team1 = euro7TeamRx.cap(1)
                 print "team1 = %s" % team1
                 posi= euro7TeamRx.indexIn(htmlPage, posi+1)
                 posi= euro7TeamRx.indexIn(htmlPage, posi+1)
                 team2 = euro7TeamRx.cap(1)
                 print "indice %i" % i
                 print "team2 = %s" % team2
                 match = Match(team1 + " vs " + team2)
                 match.setTeam1(team1)
                 match.setTeam2(team2)
                 p1 = 0.33
                 pN = 0.33
                 p2 = 0.33
                 total = p1 + pN +p2
                 r1 = p1/total*100
                 r2 = p2/total*100
                 rN = pN/total*100
                 match.setRepartition(p1/total, pN/total, p2/total)
                 self._grid.addGame(match)
                 print "game added : %d" % i
                 posi= euro7TeamRx.indexIn(htmlPage, posi+1)
         #except:
                 #msg = QMessageBox()
                 #msg.setText("Loading page error")
                 #msg.exec_()
         #self.__workbook1.save(self.__outPutFileName)
         return
示例#6
0
 def handleHtmlPage(self, htmlPage):
         tup = ()
         self._gridList = []
         htmlAscii = filter(onlyascii, str(htmlPage))
         #print "html = %s" % htmlAscii
         mini5NumGrillerx = QRegExp("<div class=\"grid grid-3\" data-grid-id=\"(\\d+)\" data-grid-type=\"3\">")
         mini5DateRx = QRegExp("<span\\s*class=\"date\">[\\s\\n\\r]*(\\w+)\\s*(\\d+)\\s*(\\w+)\\s*(\\d+)\\s*.{0,6}\\s*(\\d+):(\\d+)\\s*</span>")
         #mini5DateRx = QRegExp("<span\\s*class=\"date\">[\\s\\n\\r]*(\\w+)\\s*(\\d+)\\s*(\\w+)\\s*(\\d+)\\s*.+\\s*(\\d+):(\\d+)\\s*</span>")
         mini5JackpotRx = QRegExp("<p class=\"montant-jackpot\">Jackpot\\s*garanti\\s*<span>\\s*(\\d+)")
         posi = mini5NumGrillerx.indexIn(str(htmlAscii))
         ngrille = mini5NumGrillerx.cap(1)
         print "ngrille=%s" % ngrille
         posi = mini5DateRx.indexIn(str(htmlAscii), posi+1)
         jour = mini5DateRx.cap(1)
         numJour = mini5DateRx.cap(2)
         mois = mini5DateRx.cap(3)
         annee = mini5DateRx.cap(4)
         heure = mini5DateRx.cap(5)
         minute = mini5DateRx.cap(6)
         mois = filter(onlyascii, mois)
         print "jour=%s" % jour
         print "mois=%s" % mois
         print "annee=%s" % annee
         date = CombinoCalendar(int(numJour), mois, int(annee), int(heure), int(minute))
         epochDate = date.epochDate()/1000
         print "date=%s" % (jour + str(numJour) + mois + str(annee))
         print "epochDate=%d" % epochDate
         #self.gridList.append(mini5rx.cap(1))
         posi = mini5JackpotRx.indexIn(str(htmlAscii), posi+1)
         jackpot = mini5JackpotRx.cap(1)
         print "jackpot=%s" % jackpot
         tup = (ngrille, epochDate, jackpot)
         self._gridList.append(tup)
         posi = mini5NumGrillerx.indexIn(str(htmlAscii), posi+1)
         while posi != -1 :
                 ngrille = mini5NumGrillerx.cap(1)
                 print "ngrille=%s" % ngrille
                 posi = mini5DateRx.indexIn(str(htmlAscii), posi+1)
                 jour = mini5DateRx.cap(1)
                 numJour = mini5DateRx.cap(2)
                 mois = mini5DateRx.cap(3)
                 annee = mini5DateRx.cap(4)
                 mois = filter(onlyascii, mois)
                 heure = mini5DateRx.cap(5)
                 minute = mini5DateRx.cap(6)
                 print "date=%s" % (jour + str(numJour) + mois + str(annee))
                 date = CombinoCalendar(int(numJour), mois, int(annee), int(heure), int(minute))
                 epochDate = date.epochDate()/1000
                 print "epochDate=%d" % epochDate
                 posi = mini5JackpotRx.indexIn(str(htmlAscii), posi+1)
                 jackpot = mini5JackpotRx.cap(1)
                 print "jackpot=%s" % jackpot
                 tup = (ngrille, epochDate, jackpot)
                 self._gridList.append(tup)
                 posi = mini5NumGrillerx.indexIn(str(htmlAscii), posi+1)
         print self._gridList
示例#7
0
    def variationFromString(self, string, caseSense=True):
        rx = QRegExp(self.variationRegExpPattern)
        rx.setMinimal(False)
        rx.setCaseSensitivity(Qt.CaseInsensitive)
        if caseSense: rx.setCaseSensitivity(Qt.CaseSensitive)

        index = rx.indexIn(string)
        length = rx.matchedLength()

        match = string[index:index + length]

        return match
 def highlightBlock(self, text):
     # Derived from Qt function, used to apply color-syntaxing to text
     # :param text: text input
     
     rules = [(QColor(100, 165, 225), r"^(//|#).+$"),         #blue 100, 165, 225
              (QColor(205, 200, 120), r"^(//|#) Warning.+$"), #yellow 205, 200, 120
              (QColor(165,  75,  75), r"^(//|#).+Error.+$"),  #red 165, 75, 75
              (QColor(115, 215, 150), r"^(//|#).+Result.+$")] #green 115, 215, 150
     # loop through rules
     for color, pattern in rules:
         keyword = QTextCharFormat()
         keyword.setForeground(color)
         # get regexp pattern
         expression = QRegExp(pattern)
         index = expression.indexIn(text)
         # loop until all matches are done
         while index >= 0:
             length = expression.matchedLength()
             # format text with current formatting
             self.setFormat(index, length, keyword)
             index = expression.indexIn(text, index + length)
     self.setCurrentBlockState(0)
示例#9
0
 def handleHtmlPage(self, htmlPage):
         tup = ()
         self._gridList = []
         loto15rx = QRegExp("<option selected=\"selected\" value=\"(\\d+)\">")
         loto15DateRx = QRegExp("\\d*\\s*du\\s*(\\d*\/\\d*\/\\d*)<\/option>")
         posi_encours = loto15rx.indexIn(str(htmlPage))
         ngrille = loto15rx.cap(1)
         print "ngrille=%s" % ngrille
         posi = loto15DateRx.indexIn(str(htmlPage), posi_encours)
         date = loto15DateRx.cap(1)
         print "Date=%s" % date
         dmy = string.split(date, "/")
         print "dmy :%s" % str(dmy)
         qdatetime = QDateTime()
         qdatetime.setDate(QDate(int("20"+dmy[2]), int(dmy[1]), int(dmy[0])))
         qdatetime = qdatetime.addDays(1).addSecs(-1) # next day
         epochDate = qdatetime.toMSecsSinceEpoch()/1000
         print "epochDate=%d" % epochDate
         tup = (ngrille, epochDate, 0)
         self._gridList.append(tup)
         loto15rx = QRegExp("<option value=\"(\\d+)\">")
         posi = 0
         posi = loto15rx.indexIn(str(htmlPage), posi+1)
         while posi != -1 :#and posi < posi_encours:
                 ngrille = loto15rx.cap(1)
                 print "ngrille=%s" % ngrille
                 posi = loto15DateRx.indexIn(str(htmlPage), posi)
                 date = loto15DateRx.cap(1)
                 print "Date=%s" % date
                 dmy = string.split(date, "/")
                 qdatetime = QDateTime()
                 qdatetime.setDate(QDate(int("20"+dmy[2]), int(dmy[1]), int(dmy[0])))
                 qdatetime = qdatetime.addDays(1).addSecs(-1) # next day
                 epochDate = qdatetime.toMSecsSinceEpoch()/1000
                 print "epochDate=%d" % epochDate
                 tup = (ngrille, epochDate, 0)
                 self._gridList.append(tup)
                 posi = loto15rx.indexIn(str(htmlPage), posi+1)
示例#10
0
文件: sh.py 项目: hofoen/pcef-core
    def highlightBlock(self, text):
        """ Highlight a block of text """
        if self.enabled is False:
            return
        text = unicode(text)
        original_text = text
        prev_data = self.currentBlock().previous().userData()

        if prev_data is not None:
            self._lexer._saved_state_stack = prev_data.syntax_stack
        elif hasattr(self._lexer, '_saved_state_stack'):
            del self._lexer._saved_state_stack

        # Lex the text using Pygments
        index = 0
        for token, text in self._lexer.get_tokens(text):
            length = len(text)
            self.setFormat(index, length, self._get_format(token))
            index += length

        if hasattr(self._lexer, '_saved_state_stack'):
            data = PygmentsBlockUserData(
                syntax_stack=self._lexer._saved_state_stack)
            self.currentBlock().setUserData(data)
            # Clean up for the next go-round.
            del self._lexer._saved_state_stack

        #Spaces
        expression = QRegExp('\s+')
        index = expression.indexIn(original_text, 0)
        while index >= 0:
            index = expression.pos(0)
            length = len(expression.cap(0))
            self.setFormat(index, length, self._get_format(Whitespace))
            index = expression.indexIn(original_text, index + length)

        self.hilighlightingBlock.emit(original_text, self)
示例#11
0
 def handleDistribHtmlPage(self, htmlPage):
         print "handleDistribHtmlPage"
         jackpot = int(self._gridList[self._index][2]) / 0.70
         self._grid.setJackpot(jackpot)
         self._grid.setNbPlayers(jackpot)
         htmlStrPage = filter(onlyascii, str(htmlPage))
         teamString = "<td class=\"center matchs_av\">((\\(?\\)?\\d*\\w*\\.?'?-?\\s*)*)<\/td>"
         enfOfGridString = "<div class=\"repart_legende\">"
         loto15Teamrx = QRegExp(teamString)
         endOfGridRx = QRegExp(enfOfGridString)
         posiEndOfGrid= endOfGridRx.indexIn(htmlStrPage, 0)
         repString = ">(\\d*,*\\d*)\\s*\%<"
         loto15Reprx = QRegExp(repString)
         index_l = 0
         total = 0
         posi = 0
         i = 0
         #try:
         if True :
                 posi= loto15Teamrx.indexIn(htmlStrPage, posi+1)
                 print "posi = %d" % posi
                 while posi != -1:
                         i+=1
                         print "indice %i" % i
                         team1 = loto15Teamrx.cap(1)
                         posi= loto15Teamrx.indexIn(htmlStrPage, posi+1)
                         print "posi2 = %d" % posi
                         print "posi2 = %d" % posi
                         print "team1 = %s" % team1
                         team2 = loto15Teamrx.cap(1)
                         posiMax= loto15Teamrx.indexIn(htmlStrPage, posi+1)
                         if posiMax < 0:
                                 posiMax = posiEndOfGrid
                         print "posi3 = %d" % posi
                         print "team2 = %s" % team2
                         match = Match(team1 + " vs " + team2)
                         match.setTeam1(team1)
                         match.setTeam2(team2)
                         posiInter= loto15Reprx.indexIn(htmlStrPage, posi+1)
                         print "posiInter = %d" % posiInter
                         print "posiMax = %d" % posiMax
                         if (posiInter > 0) and (posiInter <= posiMax) :
                                 posi = posiInter
                                 print "posi4 = %d" % posi
                                 p1 = float(loto15Reprx.cap(1).replace(",","."))
                                 posi= loto15Reprx.indexIn(htmlStrPage, posi+1)
                                 print "posi5 = %d" % posi
                                 pN = float(loto15Reprx.cap(1).replace(",","."))
                                 posi= loto15Reprx.indexIn(htmlStrPage, posi+1)
                                 print "posi6 = %d" % posi
                                 p2 = float(loto15Reprx.cap(1).replace(",","."))
                                 total = float(p1+pN+p2)
                                 r1 = p1/total*100
                                 r2 = p2/total*100
                                 rN = pN/total*100
                                 match.setRepartition(p1/total, pN/total, p2/total)
                         self._grid.addGame(match)
                         print "game added : %d" % i
                         posi= loto15Teamrx.indexIn(htmlStrPage, posi+1)
                         print "posi1 = %d" % posi
                 print "%d grilles" % i
                 self._gridSize = i
         #except:
                 #msg = QMessageBox()
                 #msg.setText("Loading page error")
                 #msg.exec_()
         #self.__workbook1.save(self.__outPutFileName)
         return
示例#12
0
class StringParser(object):

    def __init__(self):
        super(StringParser, self).__init__()

        self._string = ""
        self._regExp = QRegExp("LOD[0-9]*[0-9]", Qt.CaseSensitive)
        self._regExpLOD = QRegExp("LOD[0-9]*[0-9]", Qt.CaseSensitive)
        self._regExpVariation = QRegExp("VAR[0-9]*[0-9]", Qt.CaseSensitive)
        self._resolutionsMap = {
            "1K": 1024, "2K": 2048,
            "3K": 3072, "4K": 4096,
            "5K": 5120, "6K": 6144,
            "7K": 7168, "8K": 8196
        }



    @property
    def string(self):
        return self._string


    @property
    def regExpLOD(self):
        return self._regExpLOD


    @property
    def regExpVariation(self):
        return self._regExpVariation


    @property
    def regExp(self):
        return self._regExpVariation


    @string.setter
    def string(self, string):
        if not isinstance(string, str):
            raise TypeError("Expected < str >")

        self._string = string


    def clear(self):
        self._string = ""


    def resolutionFromString(self):
        for resolution in self._resolutionsMap:
            if self._string.find(resolution) != -1:
                res = self._resolutionsMap[resolution]
                return res, res


    def variation(self):
        index = self._regExpVariation.indexIn(self._string)
        length = self._regExpVariation.matchedLength()
        match = self._string[index:index + length]

        return match


    def LOD(self):
        index = self._regExpLOD.indexIn(self._string)
        length = self._regExpLOD.matchedLength()
        match = self._string[index:index + length]

        return match


    def find(self):
        """
        Find by pattern and return first
        """

        index = self._regExp.indexIn(self._string)
        length = self._regExp.matchedLength()
        match = self._string[index:index + length]

        return match


    def findAll(self):
        """
        Find by pattern and return all
        """

        index = 0
        matches = []

        while index >= 0:
            index = self._regExp.indexIn(self._string, index)
            length = self._regExp.matchedLength()
            print length
            match = self._string[index:index + length]
            index += length

            if match: matches.append(match)

        return matches
示例#13
0
    def keyPressEvent(self, event):
        self.dirty = True
        customKey = False
        #AutoTab
        if (event.key() == Qt.Key_Enter or event.key() == 16777220):
            customKey = True
            numTab = 0
            #new line
            newBlock = self.textCursor().block()
            currLine = newBlock.text()
            tabRE = QRegExp("^[\t]*")
            tabRE.indexIn(currLine)
            numTab = tabRE.matchedLength()
            if (currLine != "" and currLine.strip()[-1] == "{"):
                numTab += 1
            QPlainTextEdit.keyPressEvent(self, event)
            if (numTab > 0):
                tCursor = self.textCursor()
                for _ in range(0, numTab):
                    tCursor.insertText("\t")

                #automatic close brace
                if currLine != "" and currLine.strip()[-1] == "{":
                    tCursor.insertText("\n")
                    for _ in range(0, numTab - 1):
                        tCursor.insertText("\t")
                    tCursor.insertText("}")
                    tCursor.movePosition(QTextCursor.PreviousBlock)
                    tCursor.movePosition(QTextCursor.EndOfLine)
                    self.setTextCursor(tCursor)

        if event.key() == Qt.Key_Tab and self.textCursor().hasSelection():
            customKey = True
            selStart = self.textCursor().selectionStart()
            selEnd = self.textCursor().selectionEnd()
            cur = self.textCursor()
            endBlock = self.document().findBlock(selEnd)
            currBlock = self.document().findBlock(selStart)
            while currBlock.position() <= endBlock.position():
                cur.setPosition(currBlock.position())
                cur.insertText("\t")
                currBlock = currBlock.next()

        if event.key() == Qt.Key_Backtab and self.textCursor().hasSelection():
            customKey = True
            selStart = self.textCursor().selectionStart()
            selEnd = self.textCursor().selectionEnd()
            cur = self.textCursor()
            endBlock = self.document().findBlock(selEnd)
            currBlock = self.document().findBlock(selStart)
            while currBlock.position() <= endBlock.position():
                cur.setPosition(currBlock.position())
                if currBlock.text().left(1) == "\t":
                    cur.deleteChar()
                currBlock = currBlock.next()

        # Allow commenting and uncommenting of blocks of code
        if event.key() == Qt.Key_Slash and event.modifiers(
        ) == Qt.ControlModifier:
            customKey = True
            selStart = self.textCursor().selectionStart()
            selEnd = self.textCursor().selectionEnd()
            cur = self.textCursor()
            endBlock = self.document().findBlock(selEnd)
            currBlock = self.document().findBlock(selStart)

            while currBlock.position() <= endBlock.position():
                cur.setPosition(currBlock.position())

                if currBlock.text()[0] == "#":
                    cur.deleteChar()

                    # Make sure we remove extra spaces
                    while currBlock.text()[0] == " ":
                        cur.deleteChar()
                else:
                    cur.insertText("# ")

                currBlock = currBlock.next()

        # Open the text finder
        if event.key() == Qt.Key_F and event.modifiers() == Qt.ControlModifier:
            customKey = True
            print("Opening finder...")

        if not customKey:
            QPlainTextEdit.keyPressEvent(self, event)
示例#14
0
class PyHighlighter(QSyntaxHighlighter):

  KEYWORD_PATTERNS = (
    r"\bbreak\b",
    r"\bclass\b",
    r"\bcontinue\b",
    r"\bdef\b",
    r"\bdo\b",
    r"\belif\b",
    r"\belse\b",
    r"\bfor\b",
    r"\bfunction\b",
    r"\bid\b",
    r"\bif\b",
    r"\bimport\b",
    r"\bin\b",
    r"\bprint\b",
    r"\breturn\b",
    r"\btype\b",
    r"\bwhile\b",
  )

  TYPE_PATTERNS = (
    r"\bbool\b",
    r"\bdouble\b",
    r"\bint\b",
    r"\blong\b",
    r"\bprint\b",
    r"\bstr\b",
    r"\bunicode\b",
  )

  CONSTANT_PATTERNS = (
    r"\bTrue\b",
    r"\bFalse\b",
  )

  def __init__(self, parent=None):
    """
    @param  parent  QObject or QTextDocument or QTextEdit or None
    """
    super(PyHighlighter, self).__init__(parent)

    keywordFormat = QTextCharFormat()
    keywordFormat.setForeground(HLS_KEYWORD_COLOR)
    keywordFormat.setFontWeight(QFont.Bold)
    self.highlightingRules = [(QRegExp(pattern), keywordFormat)
        for pattern in self.KEYWORD_PATTERNS]

    typeFormat = QTextCharFormat()
    typeFormat.setForeground(HLS_TYPE_COLOR)
    typeFormat.setFontWeight(QFont.Bold)
    self.highlightingRules.extend([(QRegExp(pattern), typeFormat)
        for pattern in self.TYPE_PATTERNS])

    constantFormat = QTextCharFormat()
    constantFormat.setForeground(HLS_LITERAL_COLOR)
    self.highlightingRules.extend([(QRegExp(pattern), constantFormat)
        for pattern in self.CONSTANT_PATTERNS])

    classFormat = QTextCharFormat()
    classFormat.setFontWeight(QFont.Bold)
    classFormat.setForeground(HLS_CLASS_COLOR)
    self.highlightingRules.append((QRegExp(r"\bQ[A-Za-z]+\b"),
        classFormat))

    functionFormat = QTextCharFormat()
    functionFormat.setFontItalic(True)
    functionFormat.setForeground(HLS_FUNCTION_COLOR)
    self.highlightingRules.append((QRegExp(r"\b[A-Za-z0-9_]+(?=\()"),
        functionFormat))

    quotationFormat = QTextCharFormat()
    quotationFormat.setForeground(HLS_LITERAL_COLOR)
    self.highlightingRules.append((QRegExp(r'"[^"]*"'), quotationFormat))
    self.highlightingRules.append((QRegExp(r'u"[^"]*"'), quotationFormat))
    self.highlightingRules.append((QRegExp(r"'[^']*'"), quotationFormat))
    self.highlightingRules.append((QRegExp(r"u'[^']*'"), quotationFormat))

    singleLineCommentFormat = QTextCharFormat()
    singleLineCommentFormat.setForeground(HLS_COMMENT_COLOR)
    self.highlightingRules.append((QRegExp("#[^\n]*"), singleLineCommentFormat))

    self.multiLineCommentFormat = QTextCharFormat()
    self.multiLineCommentFormat.setForeground(HLS_COMMENT_COLOR)

    self.commentStartExpression = QRegExp(r'"""')
    self.commentEndExpression = QRegExp(r'"""')

    todoFormat = QTextCharFormat()
    todoFormat.setBackground(HLS_TODO_COLOR)
    self.postHighlightingRules = [(QRegExp(pattern), todoFormat)
        for pattern in HLS_TODO_PATTERNS]

    doxyFormat = QTextCharFormat()
    doxyFormat.setForeground(HLS_COMMENT_COLOR)
    doxyFormat.setFontWeight(QFont.Bold)
    self.postHighlightingRules.extend([(QRegExp(pattern), doxyFormat)
        for pattern in HLS_DOXY_PATTERNS])

  def highlightBlock(self, text):
    """@reimp @protected"""
    for pattern, format in self.highlightingRules:
      expression = QRegExp(pattern)
      index = expression.indexIn(text)
      while index >= 0:
        length = expression.matchedLength()
        self.setFormat(index, length, format)
        index = expression.indexIn(text, index + length)

    self.setCurrentBlockState(0)

    startIndex = 0
    if self.previousBlockState() != 1:
      startIndex = self.commentStartExpression.indexIn(text)

    while startIndex >= 0:
      endIndex = self.commentEndExpression.indexIn(text, startIndex +1)

      if endIndex == -1:
        self.setCurrentBlockState(1)
        commentLength = len(text) - startIndex
      else:
        commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength()

      self.setFormat(startIndex, commentLength,
          self.multiLineCommentFormat)
      startIndex = self.commentStartExpression.indexIn(text,
          startIndex + commentLength);

    for pattern, format in self.postHighlightingRules:
      expression = QRegExp(pattern)
      index = expression.indexIn(text)
      while index >= 0:
        length = expression.matchedLength()
        self.setFormat(index, length, format)
        index = expression.indexIn(text, index + length)
示例#15
0
class CppHighlighter(QSyntaxHighlighter):

  KEYWORD_PATTERNS = (
    r"\bcase\b",
    r"\bclass\b",
    r"\bdefault\b",
    r"\benum\b",
    r"\bexplicit\b",
    r"\bfriend\b",
    r"\bfor\b",
    r"\belse\b",
    r"\bif\b",
    r"\binline\b",
    r"\bnamespace\b",
    r"\boperator\b",
    r"\bprivate\b",
    r"\bprotected\b",
    r"\bpublic\b",
    r"\breturn\b",
    r"\bswitch\b",
    r"\bstruct\b",
    r"\btemplate\b",
    r"\btypedef\b",
    r"\btypename\b",
    r"\bunion\b",
    r"\bvirtual\b",
    r"\bvolatile\b",
  )

  TYPE_PATTERNS = (
    r"\bchar\b",
    r"\bconst\b",
    r"\bdouble\b",
    r"\bexplicit\b",
    r"\bint\b",
    r"\blong\b",
    r"\bshort\b",
    r"\bfloat\b",
    r"\bdouble\b",
    r"\bsignals\b",
    r"\bsigned\b",
    r"\bslots\b",
    r"\bstatic\b",
    r"\bstruct\b",
    r"\bunsigned\b",
  )

  CONSTANT_PATTERNS = (
    r"\btrue\b",
    r"\bfalse\b",
  )

  def __init__(self, parent=None):
    """
    @param  parent  QObject or QTextDocument or QTextEdit or None
    """
    super(CppHighlighter, self).__init__(parent)

    keywordFormat = QTextCharFormat()
    keywordFormat.setForeground(HLS_KEYWORD_COLOR)
    keywordFormat.setFontWeight(QFont.Bold)
    self.highlightingRules = [(QRegExp(pattern), keywordFormat)
        for pattern in self.KEYWORD_PATTERNS]

    typeFormat = QTextCharFormat()
    typeFormat.setForeground(HLS_TYPE_COLOR)
    typeFormat.setFontWeight(QFont.Bold)
    self.highlightingRules.extend([(QRegExp(pattern), typeFormat)
        for pattern in self.TYPE_PATTERNS])

    constantFormat = QTextCharFormat()
    constantFormat.setForeground(HLS_LITERAL_COLOR)
    self.highlightingRules.extend([(QRegExp(pattern), constantFormat)
        for pattern in self.CONSTANT_PATTERNS])

    classFormat = QTextCharFormat()
    classFormat.setFontWeight(QFont.Bold)
    classFormat.setForeground(HLS_CLASS_COLOR)
    self.highlightingRules.append((QRegExp(r"\bQ[A-Za-z]+\b"),
        classFormat))

    functionFormat = QTextCharFormat()
    functionFormat.setFontItalic(True)
    functionFormat.setForeground(HLS_FUNCTION_COLOR)
    self.highlightingRules.append((QRegExp(r"\b[A-Za-z0-9_]+(?=\()"),
        functionFormat))

    quotationFormat = QTextCharFormat()
    quotationFormat.setForeground(HLS_LITERAL_COLOR)
    self.highlightingRules.append((QRegExp(r'"[^"]*"'), quotationFormat))

    # This must comes before the line comments since they conficts
    pragmaFormat = QTextCharFormat()
    pragmaFormat.setForeground(HLS_PRAGMA_COLOR)
    self.highlightingRules.append((QRegExp(r"#[^\n]*"),
        pragmaFormat))

    self.multiLineCommentFormat = QTextCharFormat()
    self.multiLineCommentFormat.setForeground(HLS_COMMENT_COLOR)

    singleLineCommentFormat = QTextCharFormat()
    singleLineCommentFormat.setForeground(HLS_COMMENT_COLOR)
    self.highlightingRules.append((QRegExp("//[^\n]*"),
        singleLineCommentFormat))

    self.commentStartExpression = QRegExp(r"/\*")
    self.commentEndExpression = QRegExp(r"\*/")

  def highlightBlock(self, text):
    """@reimp @protected"""
    for pattern, format in self.highlightingRules:
      expression = QRegExp(pattern)
      index = expression.indexIn(text)
      while index >= 0:
        length = expression.matchedLength()
        self.setFormat(index, length, format)
        index = expression.indexIn(text, index + length)

    self.setCurrentBlockState(0)

    startIndex = 0
    if self.previousBlockState() != 1:
      startIndex = self.commentStartExpression.indexIn(text)

    while startIndex >= 0:
      endIndex = self.commentEndExpression.indexIn(text, startIndex +1)

      if endIndex == -1:
        self.setCurrentBlockState(1)
        commentLength = len(text) - startIndex
      else:
        commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength()

      self.setFormat(startIndex, commentLength,
          self.multiLineCommentFormat)
      startIndex = self.commentStartExpression.indexIn(text,
          startIndex + commentLength);
示例#16
0
    def handleOddsHtmlPage(self, htmlPage, source=BETEXPLORER_SOURCE):
        print "handleOddsHtmlPage source = %d" % source
        epochDate = self._gridList[self._index][1]
        date = QDateTime()
        date.setMSecsSinceEpoch(int(epochDate) * 1000)
        deprecated = QDateTime.currentDateTime() > date.addDays(+1)

        strHtml = str(htmlPage)
        if source == BETEXPLORER_SOURCE:
            oddsRx = QRegExp(
                "<a href=.*data-odd-max=\"(\\d*\.\\d*)\".*data-odd-max=\"(\\d*\.\\d*)\".*data-odd-max=\"(\\d*\.\\d*)\".*>")
        elif source == ZULUBET_SOURCE:
            oddsRx = QRegExp(
                "<td\\s*class=\"aver_odds_full\"\\s*align=\"center\">(\\d*\.\\d*)</td><td\\s*class=\"aver_odds_full\"\\s*align=\"center\">(\\d*\.\\d*)</td><td\\s*class=\"aver_odds_full\"\\s*align=\"center\">(\\d*\.\\d*)</td>")

        for match in self._grid.matches():
            if not match.cotesDisponibles():
                if source == BETEXPLORER_SOURCE and not deprecated:
                    team1Rx = QRegExp(
                        "><span>(\\w*[\\'\\.-]?\\s*)*(%s)(\\w*[\\'\\.-]?\\s*)*</span>\\s*-\\s*<span>\\s*((\\w*[\\'\\.-]?\\s*)*)</span><" % match.team1())
                    team1Rx.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
                    team2Rx = QRegExp(
                        "><span>\\s*(\\w*[\\'\\.-]?\\s*)*</span>\\s*-\\s*<span>(\\w*[\\'\\.-]?\\s*)*(%s)(\\w*[\\'\\.-]?\\s*)*</span><" % match.team2())
                    team2Rx.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
                elif source == ZULUBET_SOURCE:
                    team1Rx = QRegExp(
                        #"<img\\s*src=\"http://www\.zulubet\.com/flags/flag-\\w*\.png\"\\s*class=\"flags\\s*flag-\\w*\"\\s*title=\"(\\w*\\'?\\s*-?)*,(\\w*\\'?\\s*-?)*\"\\s*width=\"\\d*\"\\s*height=\"\\d*\">\\s*(%s)\\s*-\\s*(\\w*\\'?\\s*-?)*<\img>" % match.team1())
                        "width=\"\\d*\"\\s*height=\"\\d*\">\\s*(%s)\\s*-\\s*(\\w*[\\'\\.-]?\\s*)*</td>" % match.team1())
                    team1Rx.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
                    team2Rx = QRegExp(
                        "width=\"\\d*\"\\s*height=\"\\d*\">(\\w*[\\'\\.-]?\\s*)*-\\s*(%s)\\s*</td>" % match.team2())
                    team2Rx.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
                else:
                    team1Rx = QRegExp("---deprecated---")
                    team2Rx = QRegExp("---deprecated---")

                # team2Rx = QRegExp(match.team2())
                teamXRx = team1Rx
                posi = teamXRx.indexIn(strHtml)
                posi2 = team2Rx.indexIn(strHtml)
                #if posi < 0:
                    #print "-1-%s- not found" % match.team1()
                    #teamXRx = team2Rx
                    #posi = teamXRx.indexIn(strHtml)
                #if (posi >= 0) and (posi2 >= 0):
                if (posi >= 0) and (posi2 == posi):
                    print "-%s- found" % ''.join((match.team1(), " vs " + match.team2()))
                else:  # try in an other way
                    print "-%s- not found, try another way" % ''.join((match.team1(), " vs " + match.team2()))
                    # split team names
                    team1list = match.team1().split(" ")
                    team2list = match.team2().split(" ")
                    # find the longest
                    maxLen = 0
                    miniTeam1 = ""
                    for elt1 in team1list:
                        if len(elt1) > maxLen:
                            maxLen = len(elt1)
                            miniTeam1 = filter(onlyascii, elt1)
                    maxLen = 0
                    miniTeam2 = ""
                    for elt2 in team2list:
                        if len(elt2) > maxLen:
                            maxLen = len(elt2)
                            miniTeam2 = filter(onlyascii, elt2)
                    print "Try with {0} vs {1}".format(miniTeam1, miniTeam2)
                    if source == BETEXPLORER_SOURCE and not deprecated:
                        teamRx = QRegExp(
                            "><span>\\s*(\\w*\\'?\\s*-?)*{0}(\\w*\\'?\\s*-?)*</span>\\s*-\\s*<span>(\\w*\\'?\\s*-?)*{1}(\\w*\\'?\\s*-?)*</span><".format(
                                miniTeam1, miniTeam2))
                    elif source == ZULUBET_SOURCE:
                        #teamRx = QRegExp(
                            #"<img\\s*src=\"http://www\.zulubet\.com/flags/flag-\\w*\.png\"\\s*class=\"flags\\s*flag-\\w*\"\\s*title=\"(\\w*\\'?\\s*-?)*,(\\w*\\'?\\s*-?)*\"\\s*width=\"\\d*\"\\s*height=\"\\d*\">(\\w*\\'?\\s*-?)*{0}(\\w*\\'?\\s*-?)*-(\\w*\\'?\\s*-?)*{1}(\\w*\\'?\\s*-?)*<\img>".format(
                                #miniTeam1, miniTeam2))
                        teamRx = QRegExp("\">(\\w*\\'?\\s*-?)*{0}(\\w*\\'?\\s*-?)*-(\\w*\\'?\\s*-?)*{1}(\\w*\\'?\\s*-?)*</td>".format(miniTeam1, miniTeam2))
                    else:
                        teamRx = QRegExp("---deprecated---")
                        print "---GRID DEPRECATED---"

                    teamRx.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
                    posi = teamRx.indexIn(strHtml)
                    if posi >= 0:
                        print "found : {0} vs {1}".format(miniTeam1, miniTeam2)
                    else:
                        print "still not found :'("
                        # print "Odds handling KO %s not found" % str(match)
                if posi >= 0:
                    print "posi = %d" % posi
                    posi = oddsRx.indexIn(strHtml, posi)
                    oddStr1 = oddsRx.cap(1)
                    oddStr2 = oddsRx.cap(2)
                    oddStr3 = oddsRx.cap(3)
                    print "read odds1 = %s" % oddStr1
                    try:
                        match.setCotes(float(oddsRx.cap(1)), float(oddsRx.cap(2)), float(oddsRx.cap(3)))
                        team1 = filter(onlyascii, match.team1())
                        team2 = filter(onlyascii, match.team2())
                        print "Odds handling OK : %s" % team1 + " vs " + team2
                        print "Odds handling OK : "
                        match.setCotesDisponibles(True)
                    except:
                        team1 = filter(onlyascii, match.team1())
                        team2 = filter(onlyascii, match.team2())
                        print "Odds handling OK : cant read odds for %s" % team1 + " vs " + team2
        return