Beispiel #1
0
    def printFullBuffer(self, buff):
        del self.buffer
        pos = str(len(buff)) + 'B'
        self.buffer = struct.unpack(pos, buff)
        count = 0
        fullBuff = QString()
        for byte in self.buffer:
            fullBuff.append("%.2x" % byte)
            if count < 15:
                fullBuff.append(" ")
                count += 1
            else:
                fullBuff.append("\n")
                count = 0

        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText(fullBuff)
        cursor.movePosition(QTextCursor.Start)
    def __init__(self, visualization, parent_widget=None):
        QWidget.__init__(self, parent_widget)
        self.inGui = False
        self.visualization = visualization

        size = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.widgetLayout = QGridLayout(self)
        self.setSizePolicy(size)

        self.scroll = QScrollArea()
        file_path = self.visualization.get_file_path()

        self.lbl_image = QImage(QString(file_path))
        self.label = QLabel()
        self.label.setPixmap(QPixmap.fromImage(self.lbl_image))
        self.scroll.setWidget(self.label)
        self.widgetLayout.addWidget(self.scroll)

        self.tabIcon = QIcon(":/Images/Images/map.png")
        self.tabLabel = visualization.table_name
 def toSimpleHtml(self):
     html = QString()
     black = QColor(Qt.black)
     block = self.document().begin()
     while block.isValid():
         iterator = block.begin()
         while iterator != block.end():
             fragment = iterator.fragment()
             if fragment.isValid():
                 format = fragment.charFormat()
                 family = format.fontFamily()
                 color = format.foreground().color()
                 text = Qt.escape(fragment.text())
                 if (format.verticalAlignment() ==
                         QTextCharFormat.AlignSubScript):
                     text = QString("<sub>%1</sub>").arg(text)
                 elif (format.verticalAlignment() ==
                       QTextCharFormat.AlignSuperScript):
                     text = QString("<sup>%1</sup>").arg(text)
                 if format.fontUnderline():
                     text = QString("<u>%1</u>").arg(text)
                 if format.fontItalic():
                     text = QString("<i>%1</i>").arg(text)
                 if format.fontWeight() > QFont.Normal:
                     text = QString("<b>%1</b>").arg(text)
                 if format.fontStrikeOut():
                     text = QString("<s>%1</s>").arg(text)
                 if color != black or not family.isEmpty():
                     attribs = ""
                     if color != black:
                         attribs += ' color="{0}"'.format(color.name())
                     if not family.isEmpty():
                         attribs += ' face="{0}"'.format(family)
                     text = (QString("<font%1>%2</font>").arg(attribs).arg(
                         text))
                 html += text
             iterator += 1
         block = block.next()
     return html
Beispiel #4
0
    def startElement(self, namespaceURI, localName, qName, attributes):
        """
        Begin of an XML element

        :param qName: the name of the XML element
        :type qName: PyQt4.QtCore.QString
        :param attributes: attributes  associated to qName (if any)
        """
        if qName == "WELL":
            self.ct = fltFromQStr(attributes.value("CT"))
            self.ctmean = fltFromQStr(attributes.value("CTMEAN"))
            self.ctdev = fltFromQStr(attributes.value("CTDEV"))
            self.amount = fltFromQStr(attributes.value("AMOUNT"))
            self.enabled = logicalFromQStr(attributes.value("ENABLED"))
            self.NRQ = fltFromQStr(attributes.value("NRQ"))
            self.NRQerror = fltFromQStr(attributes.value("NRQERROR"))
        elif qName == "TARGET":
            self.eff = fltFromQStr(attributes.value("EFF"))
            self.pm = fltFromQStr(attributes.value("PM"))
            self.targetColor = attributes.value("COLOR")
            self.targetEnabled = logicalFromQStr(attributes.value("ENABLED"))
            self.text = QString()
        elif qName == "NAME":
            self.text = QString()
        elif qName == "SAMPLE":
            self.sampleColor = attributes.value("COLOR")
            self.sampleEnabled = logicalFromQStr(attributes.value("ENABLED"))
            self.text = QString()
        elif qName == "PLATE":
            self.pl = Plaque()
            self.platetitle = attributes.value("NAME")
            self.plateType = attributes.value("TYPE")
        elif qName == "REFSAMPLE":
            self.refSample = attributes.value("NAME")
        elif qName == "REFTARGET":
            self.refTarget = attributes.value("NAME")
        elif qName == "TYPE":
            self.text = QString()
        elif qName == "TARGETSORDER":
            self.targetsOrder = []
        elif qName == "TG":
            self.tg = attributes.value("NAME")
            self.text = QString()
        elif qName == "SAMPLESORDER":
            self.samplesOrder = []
        elif qName == "SP":
            self.sp = attributes.value("NAME")
            self.text = QString()
        return True
Beispiel #5
0
    def pnlFileEvent_1(self):

        inputFilePath = QFileDialog.getOpenFileName(
            self, "Open Xml File", QCoreApplication.applicationDirPath(),
            "Xml Files (*.xml)")
        if inputFilePath == "":
            return
        fileInfo = QFileInfo(inputFilePath)
        self.pnlFile.Value = fileInfo.fileName()
        contents = None
        with open(inputFilePath, 'rb', 0) as tempFile:
            contents = tempFile.read()
            tempFile.close()
        bytes = FasDataBlockFile.CRC_Calculation(contents)

        string_0 = QString(inputFilePath)

        crcFileDir = string_0.left(string_0.length() - 3) + "crc"
        fileInfo = QFileInfo(crcFileDir)
        if self.rwFlag == "r":
            if not fileInfo.exists():
                QMessageBox.warning(self, "Warning",
                                    "CRC file is not existing.")
                return
            crcFileContents = None
            with open(crcFileDir, 'rb', 0) as tempFileCrc:
                crcFileContents = tempFileCrc.read()
                tempFileCrc.close()
            if bytes != crcFileContents:
                self.pnlCalculatedCrcValue.textBox.setStyleSheet(
                    "color: rgb(255, 0, 0);")
            else:
                self.pnlCalculatedCrcValue.textBox.setStyleSheet(
                    "color: rgb(0, 0, 0);")
            self.pnlSuppliedCrcValue.Value = crcFileContents
            self.pnlCalculatedCrcValue.Value = bytes
        else:
            fileStream = open(crcFileDir, 'wb')
            fileStream.write(bytes)
            fileStream.close()
            self.pnlCalculatedCrcValue.Value = bytes
Beispiel #6
0
    def drawStats(self, qp):
        defaultCol = QColor(0,255,0, 200)

        #qp = QtGui.QPainter()
        qp.resetTransform()
        w = self.width()
        h = self.height()

        top = 50
        bottom = h-50
        width, height = w*0.2, 22
        dist = 10
        space = height+dist
        pos = width/4


        # DRAW PROGRESS BAGS (left)
        if self.bat>-1:
            self.drawBar(qp, QRectF(pos, top+space*0, width,height), defaultCol, 'BAT %4.2fV'%(self.bat/1000.), self.bat, 3000, 4150)
        if self.link>-1:
            self.drawBar(qp, QRectF(pos, top+space*1, width,height), defaultCol, 'SIG %03d%%'%self.link, self.link)
        if self.cpu>-1:
            self.drawBar(qp, QRectF(pos, top+space*2, width,height), defaultCol, 'CPU %03d%%'%self.cpu, self.cpu)



        # DRAW RAW STATS( right)
        pos = w-width/4-width/2
        space = height+2

        if self.pktsOut>-1:
            qp.drawText(QRectF(pos, top+space*0, width,height), Qt.AlignLeft, '%04d kb/s'%self.pktsOut)
        if self.pktsIn>-1:
            qp.drawText(QRectF(pos, top+space*1, width,height), Qt.AlignLeft, '%04d kb/s'%self.pktsIn)

        if self.pressure>-1:
            qp.drawText(QRectF(pos, top+space*3, width,height), Qt.AlignLeft, '%06.2f hPa'%self.pressure)
        if self.temp>-1:
            qp.drawText(QRectF(pos, top+space*4, width,height), Qt.AlignLeft, QString('%05.2f'%self.temp)+QChar(0260)+QString("C"))
        if self.aslLong>-1:
            qp.drawText(QRectF(pos, top+space*5, width,height), Qt.AlignLeft, '%4.2f m'%self.aslLong)
Beispiel #7
0
 def data(self, index, role=Qt.DisplayRole):
     if (not index.isValid() or
         not (0 <= index.row() < len(self.ships))):
         return QVariant()
     ship = self.ships[index.row()]
     column = index.column()
     if role == Qt.DisplayRole:
         if column == NAME:
             return QVariant(ship.name)
         elif column == OWNER:
             return QVariant(ship.owner)
         elif column == COUNTRY:
             return QVariant(ship.country)
         elif column == DESCRIPTION:
             return QVariant(ship.description)
         elif column == TEU:
             return QVariant(QString("%L1").arg(ship.teu))
     elif role == Qt.TextAlignmentRole:
         if column == TEU:
             return QVariant(int(Qt.AlignRight|Qt.AlignVCenter))
         return QVariant(int(Qt.AlignLeft|Qt.AlignVCenter))
     elif role == Qt.TextColorRole and column == TEU:
         if ship.teu < 80000:
             return QVariant(QColor(Qt.black))
         elif ship.teu < 100000:
             return QVariant(QColor(Qt.darkBlue))
         elif ship.teu < 120000:
             return QVariant(QColor(Qt.blue))
         else:
             return QVariant(QColor(Qt.red))
     elif role == Qt.BackgroundColorRole:
         if ship.country in ("Bahamas", "Cyprus", "Denmark",
                 "France", "Germany", "Greece"):
             return QVariant(QColor(250, 230, 250))
         elif ship.country in ("Hong Kong", "Japan", "Taiwan"):
             return QVariant(QColor(250, 250, 230))
         elif ship.country in ("Marshall Islands",):
             return QVariant(QColor(230, 250, 250))
         else:
             return QVariant(QColor(210, 230, 230))
     return QVariant()
Beispiel #8
0
    def __addComponent(self, name, xml, action):
        cp = LabeledObject(name, None)
        cpEdit = Component(self.receiver.componentList)
        cpEdit.id = cp.id
        cpEdit.directory = self.receiver.componentList.directory
        cpEdit.createGUI()

        cpEdit.name = name
        cpEdit.set(QString(xml), True)
        cpEdit.savedXML = None
        cp.name = cpEdit.name
        cp.instance = cpEdit
        self.receiver.componentList.addElement(cp, False)
        if hasattr(cpEdit, "connectExternalActions"):
            cpEdit.connectExternalActions(**self.receiver.externalCPActions)
        cpEdit.dialog.setWindowTitle("%s [Component]" % cp.name)

        if action == "STORE":
            self.receiver.configServer.storeComponent(name, xml)
            cpEdit.savedXML = cp.instance.get()
            cp.savedName = cp.name
        elif action == "SAVE":
            cp.instance.merge(False)
            if cp.instance.save():
                cp.savedName = cp.name
                cpEdit.savedXML = cp.instance.get()

        if hasattr(self.receiver.ui, 'mdi'):
            subwindow = self.receiver.subWindow(
                cp.instance, self.receiver.ui.mdi.subWindowList())
            if subwindow:
                self.receiver.setActiveSubWindow(subwindow)
                cp.instance.dialog.setSaveFocus()
            else:
                subwindow = self.receiver.ui.mdi.addSubWindow(cpEdit.dialog)
                subwindow.resize(680, 560)
                cpEdit.dialog.setSaveFocus()
                cpEdit.dialog.show()
                cp.instance = cpEdit
            cpEdit.dialog.show()
        return cp.id
Beispiel #9
0
 def __init__(self, parent=None, fontsize=12):
     super(PPTextEditor, self).__init__(parent)
     # Do not allow line-wrap; horizontal scrollbar appears when required.
     self.setLineWrapMode(QPlainTextEdit.NoWrap)
     # make sure when we jump to a line, it goes to the window center
     self.setCenterOnScroll(True)
     # Get a monospaced font as selected by the user with View>Font
     self.setFont(pqMsgs.getMonoFont(fontsize, True))
     # instantiate our "syntax" highlighter object, but link it to an empty
     # QTextDocument. We will redirect it to our actual document only after
     # loading a document, as it relies on metadata, and then only when/if
     # the IMC.*HiliteSwitch es are on.
     self.nulDoc = QTextDocument()  # make a null document
     self.hiliter = wordHighLighter(self.nulDoc)
     # all the metadata lists will be initialized when self.clear() is
     # called from pqMain, shortly.
     # save a regex for quickly finding if a selection is a single word
     self.oneWordRE = QRegExp(u'^\W*(\w{2,})\W*$')
     self.menuWord = QString()
     # Create and initialize an SHA-1 hash machine
     self.cuisineart = QCryptographicHash(QCryptographicHash.Sha1)
Beispiel #10
0
    def readSettings(self):
        """ Read settings
        """
        setting = QSettings("Davide Setti", "Lector")
        pos = setting.value("pos", QVariant(QPoint(50, 50))).toPoint()
        size = setting.value("size", QVariant(QSize(800, 500))).toSize()
        self.curDir = setting.value("file_dialog_dir",
                                    QVariant('~/')).toString()
        self.resize(size)
        self.move(pos)
        self.restoreGeometry(setting.value("mainWindowGeometry").toByteArray())
        self.restoreState(setting.value("mainWindowState").toByteArray())

        ## load saved language
        lang = str(setting.value("rbtn/lang", QVariant(QString())).toString())
        try:
            currentIndex = self.ui.rbtn_lang_select.findData(lang)
            self.ui.rbtn_lang_select.setCurrentIndex(currentIndex)
            self.ocrWidget.language = lang
        except KeyError:
            pass
Beispiel #11
0
    def keyPressEvent(self, evt):
        #modifier can not be used as shortcut
        if evt.key() in self.keyword_modifiers:
            return

        #save the key
        if evt.key() == Qt.Key_Backtab and evt.modifiers() & Qt.ShiftModifier:
            self.keys = Qt.Key_Tab
        else:
            self.keys = evt.key()

        if evt.modifiers() & Qt.ShiftModifier:
            self.keys += Qt.SHIFT
        if evt.modifiers() & Qt.ControlModifier:
            self.keys += Qt.CTRL
        if evt.modifiers() & Qt.AltModifier:
            self.keys += Qt.ALT
        if evt.modifiers() & Qt.MetaModifier:
            self.keys += Qt.META
        #set the keys
        self.set_shortcut(QString(QKeySequence(self.keys)))
Beispiel #12
0
 def __init__(self, parent):
     QDialog.__init__(self, parent)
     self.ui = Ui_GoOnlineDialog()
     self.ui.setupUi(self)
     self.profiles = listProfiles()
     for userName, keyId, entry in self.profiles:
         text = userName
         if keyId:
             text += ' (KeyID: %s)' % keyId
         self.ui.keys.addItem(QString(text))
     entries = [entry for userName, keyId, entry in self.profiles]
     st = localSettings()
     if st.getInt('Settings/RememberKey', 0):
         self.ui.rememberKey.setChecked(True)
         entry = st.getString('Settings/SavedProfile')
         password = st.getString('Settings/SavedPassword')
         if entry and password and (entry in entries):
             self.ui.keys.setCurrentIndex(entries.index(entry))
             self.ui.password.setText(password)
     else:
         self.ui.rememberKey.setChecked(False)
Beispiel #13
0
    def __init__(self, nom, eff=100., pm=0., isRef=Qt.Unchecked):
        """
        Constructor of Gene object

        :param nom: the name of the target
        :type nom: PyQt4.QtCore.QString
        :param eff: the efficiency of the target
        :type eff: float
        :param pm: the standard error on the efficiency
        :type eff: float
        :param isRef: a boolean to indicate if the gene is a reference one
        :type isRef: PyQt4.QtCore.CheckState
        """
        self.name = QString(nom)
        self.eff = eff
        self.pm = pm
        # Pour dire si le gene est un gene de reference
        self.isRef = isRef
        self.ctref = nan
        # Pour dire si on veut tracer un gene
        self.enabled = True
Beispiel #14
0
        def getResourceConfigGroup(account):
            """Get Resource Config Groups for account type"""

            accountGroups = []
            if account["type"] == "SMTP":
                config = KConfig("mailtransports")
                generalGroup = config.group("General")
                defaultAccount = generalGroup.readEntry("default-transport")
                if defaultAccount:
                    groupname = QString("Transport ").append(defaultAccount)
                    transportGroup = config.group(groupname)
                    accountGroups.append(transportGroup)
                    return accountGroups[0]
            else:
                config = KConfig("kmailrc")
                for each in list(config.groupList()):
                    if each.contains(
                            "Account") and not each.endsWith("Wizard"):
                        account = config.group(each)
                        accountGroups.append(account)
            return accountGroups
Beispiel #15
0
    def closeEvent(self, event):
        if self.okToContinue():

            #delete temp db file (/tmp/output.sqlite)
            if path.isfile('tmp/output.sqlite'):
                remove('tmp/output.sqlite')

            # self.settings = QSettings()
            filename = (QVariant(QString(self.filename))
                        if self.filename is not None else QVariant())
            self.settings.setValue("LastFile", filename)
            recentFiles = (QVariant(self.recentFiles)
                           if self.recentFiles else QVariant())
            self.settings.setValue("RecentFiles", recentFiles)
            self.settings.setValue("MainWindow/Geometry", QVariant(
                self.saveGeometry()))
            self.settings.setValue("MainWindow/State", QVariant(
                self.saveState()))
            del self.settings
        else:
            event.ignore()
Beispiel #16
0
    def sn_getenckey(dummy=None):
        txt, ok = QInputDialog.getText(
            None, 'Enter key',
            'Enter key.\nData lost if key is lost.\nSee docs. for key upgrade notes.'
        )
        if not ok:
            return

        if str(txt).startswith('v0:'):
            txt = QString(txt[3:])
        else:
            txt = unicode(txt)

        # arbitrary kludge to convert string to 256 bits - don't change
        sha = SHA.new()
        md5 = MD5.new()
        sha.update(txt)
        md5.update(txt)
        __ENCKEY[0] = sha.digest()[:16] + md5.digest()[:16]
        if len(__ENCKEY[0]) != 32:
            raise Exception("sn_getenckey failed to build key")
Beispiel #17
0
 def updateFileMenu(self):
     self.fileMenu.clear()
     self.addActions(self.fileMenu, self.fileMenuActions[:-1])
     current = (QString(self.filename)
                if self.filename is not None else None)
     recentFiles = []
     for fname in self.recentFiles:
         if fname != current and QFile.exists(fname):
             recentFiles.append(fname)
     if recentFiles:
         self.fileMenu.addSeparator()
         for i, fname in enumerate(recentFiles):
             action = QAction(
                 QIcon(":/icon.png"),
                 "&{0} {1}".format(i + 1,
                                   QFileInfo(fname).fileName()), self)
             action.setData(QVariant(fname))
             action.triggered.connect(self.loadFile)
             self.fileMenu.addAction(action)
     self.fileMenu.addSeparator()
     self.fileMenu.addAction(self.fileMenuActions[-1])
Beispiel #18
0
 def data(self, index, role):
     """ return data to be displayed in a cell """
     row, col = index.row(), index.column()
     value = self.values[row][col]
     if role == Qt.DisplayRole:
         if value is not None:
             return QString(self.formats[col] % value)
         else:
             return QVariant("")
     elif role == Qt.ToolTipRole:
         # construct data for display in tooltip
         if (index.column() == 0):
             if value is not None:
                 return build_attribute_tooltip(self.valid_codes,
                                                self.parser.parse(value))
         else:
             return QVariant("")
     elif role == Qt.UserRole:
         return index.internalPointer()
     else:
         return QVariant()
Beispiel #19
0
 def toLowerCase(self):
     global reWord  # the regex \b\w+\b
     tc = QTextCursor(self.textCursor())
     if not tc.hasSelection():
         return  # no selection, nothing to do
     startpos = tc.selectionStart()
     endpos = tc.selectionEnd()
     qs = QString(tc.selectedText())  # copy of selected text
     i = reWord.indexIn(qs, 0)  # index of first word if any
     if i < 0: return  # no words in selection, exit
     while i >= 0:
         w = reWord.cap(0)  # found word as QString
         n = w.size()  # its length
         qs.replace(i, n, w.toLower())  # replace it with UC version
         i = reWord.indexIn(qs, i + n)  # find next word if any
     # we have changed at least one word, replace selection with altered text
     tc.insertText(qs)
     # that wiped the selection, so restore it by "dragging" left to right
     tc.setPosition(startpos, QTextCursor.MoveAnchor)  # click
     tc.setPosition(endpos, QTextCursor.KeepAnchor)  # drag
     self.setTextCursor(tc)
Beispiel #20
0
    def setupDiagnosticIndicatorTab(self):
        years = range(self.config["years"][0], self.config["years"][1] + 1)
        # yearItems is a list of [int, boolean] pairs, where the integer is a year
        #  and the boolean is true if the year has already been added to the drop
        self.yearItems = []
        for year in years:
            #the second value in the list determines if it is already added to the drop down
            self.yearItems.append([year, False])

        datasets = get_available_dataset_names(self.project)

        for dataset in datasets:
            self.diagnostic_dataset_name.addItem(QString(dataset))

        self.setup_diagnostic_indicators()
        self.indicatorResultsTab.removeTab(0)
        QObject.connect(self.diagnostic_go_button, SIGNAL("released()"),
                        self.on_indicatorBox)
        QObject.connect(self.diagnostic_dataset_name,
                        SIGNAL("currentIndexChanged(QString)"),
                        self.on_diagnostic_dataset_name_currentIndexChanged)
    def drawAxes(self):
        self.painter.save()
        self.painter.setPen(self.axiscolor)

        # draw axes line
        self.painter.drawLine(self.axesscale / 2,
                              self.height() - self.axesscale / 2,
                              self.axesscale / 2, 0)
        self.painter.drawLine(self.axesscale / 2,
                              self.height() - self.axesscale / 2, self.width(),
                              self.height() - self.axesscale / 2)
        #draw y axis num
        self.yheight = self.height() - self.axesscale / 2
        step = self.yheight / 5
        for i in xrange(5):
            lineheight = self.yheight - (i * step)
            self.painter.drawLine(self.axesscale / 2, lineheight,
                                  self.axesscale / 2 + 5, lineheight)
            numstr = QString("%1 kb/s").arg(i * 250)
            self.painter.drawText(0, lineheight, numstr)
        self.painter.restore()
 def acceptDlg(self):
     if self.pnlDetail.Point3d != None and isinstance(
             self.pnlDetail.Point3d, Point3D):
         xyPoint = QgisHelper.CrsTransformPoint(
             self.pnlDetail.Point3d.get_X(), self.pnlDetail.Point3d.get_Y(),
             define._latLonCrs, define._xyCrs,
             self.pnlDetail.Point3d.get_Z())
         self.x = QString(str(xyPoint.get_X()))
         self.y = QString(str(xyPoint.get_Y()))
         self.latitude = QString(str(self.pnlDetail.Point3d.get_Y()))
         self.longitude = QString(str(self.pnlDetail.Point3d.get_X()))
         self.altitude = QString(str(self.pnlDetail.Altitude().Metres))
     if self.pnlCenter.Point3d != None and isinstance(
             self.pnlCenter.Point3d, Point3D):
         self.cenLatitude = QString(str(self.pnlCenter.Point3d.get_Y()))
         self.cenLongitude = QString(str(self.pnlCenter.Point3d.get_X()))
     self.magVariation = self.pnlMagVariation.Value
     self.type = self.pnlType.SelectedItem
     self.accept()
Beispiel #23
0
 def setupHistoryList(self):
     self.table.clear()
     conn = sqlite3.connect('youdao-anki.db')
     cursor = conn.cursor()
     cursor.execute(
         "select * from history where deckname='%s' order by id desc" %
         self.deckList.currentText())
     values = cursor.fetchall()
     cursor.close()
     conn.close()
     # values[number of raw][0->id,1->terms,2->time]
     self.table.setColumnCount(2)
     self.table.setRowCount(len(values))
     self.table.setHorizontalHeaderLabels(QString("Mark;Time;").split(";"))
     for index, day in enumerate(values):
         self.table.setItem(index, 1, QTableWidgetItem(str(day[2])))
         mark = day[3]
         if mark is None:
             mark = 'N'
         self.table.setItem(index, 0, QTableWidgetItem(mark))
     self.debug.appendPlainText('187: get sync history')
 def predictTags(self):
     self.T = []
     words = str(self.lineEdit.text()) + ' ' + str(
         self.plainTextEdit.toPlainText())
     words = re.sub('\n', ' ', words)
     words = re.sub('[!@%^&*()$:"?<>=~,;`{}|]', ' ', words)
     words = re.sub(
         r'''(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?]))''',
         ' ', words)
     words = re.sub('_', '-', words)
     words = words.replace('[', ' ')
     words = words.replace(']', ' ')
     words = words.replace('/', ' ')
     words = words.replace('\\', ' ')
     words = re.sub(r'(\s)\-+(\s)', r'\1', words)
     words = re.sub(r'\.+(\s)', r'\1', words)
     words = re.sub(r'\.+\.(\w)', r'\1', words)
     words = re.sub(r'(\s)\.+(\s)', r'\1', words)
     words = re.sub("'", '', words)
     words = re.sub(
         r'\s\d+[\.\-\+]+\d+|\s[\.\-\+]+\d+|\s+\d+\s+|\s\d+[\+\-]+', ' ',
         words)
     words = re.sub("^\d+\s|\s\d+\s|\s\d+$", " ", words)
     words = re.sub(r'\s\#+\s|\s\++\s', ' ', words)
     stemmed_words = [stemmer.stem(word) for word in words.split()]
     clean_text = filter(lambda w: not w in s, stemmed_words)
     words = ''
     for word in clean_text:
         words += word + ' '
     self.T.append(words)
     results = classifier.predict(self.T)
     results = multibin.inverse_transform(results)
     print '\n', results, '\n'
     buff = ''
     self.tagarr = []
     for result in results[0]:
         buff = buff + QString(result) + ' ; '
         self.tagarr.append(result)
     self.lineEdit_2.setText(buff[:len(buff) - 3])
     self.recommend()
Beispiel #25
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        uic.loadUi("mainwindow.ui", self)

        model = QStandardItemModel(7, 4, self)
        for row in range(7):
            for column in range(4):
                item = QStandardItem(QString("%1").arg(row * 4 + column))
                model.setItem(row, column, item)

        self.tableView = QTableView()
        self.tableView.setModel(model)
        self.setCentralWidget(self.tableView)

        # 获取视图的项目选择模型
        selectionModel = self.tableView.selectionModel()

        # 定义左上角和右下角的索引,然后使用这两个索引创建选择
        topLeft = model.index(1, 1, QModelIndex())
        bottomRight = model.index(5, 2, QModelIndex())
        selection = QItemSelection(topLeft, bottomRight)

        # 使用指定的选择模式来选择项目
        selectionModel.select(selection, QItemSelectionModel.Select)

        self.mainToolBar.addAction(_fromUtf8("当前项目"), self.getCurrentItemData)
        self.mainToolBar.addAction(_fromUtf8("切换选择"), self.toggleSelection)

        self.connect(selectionModel,SIGNAL("selectionChanged(QItemSelection,QItemSelection)"),
                     self.updateSelection)
        self.connect(selectionModel, SIGNAL("currentChanged(QModelIndex,QModelIndex)"),
                self.changeCurrent)

        # 多个视图共享选择
        self.tableView2 = QTableView()
        self.tableView2.setWindowTitle("tableView2")
        self.tableView2.resize(400, 300)
        self.tableView2.setModel(model)
        self.tableView2.setSelectionModel(selectionModel)
        self.tableView2.show()
Beispiel #26
0
    def drawScaleNum(self):
        self.painter.save()
        self.painter.setPen(self.foreground)
        startRad = (360 - self.startAngle - 90) * (3.14 / 180)
        deltaRad = (360 - self.startAngle -
                    self.endAngle) * (3.14 / 180) / self.scaleMajor
        fm = QtGui.QFontMetricsF(self.font())

        for i in xrange(self.scaleMajor + 1):
            sina = sin(startRad - i * deltaRad)
            cosa = cos(startRad - i * deltaRad)

            tmpVal = 1.0 * i * ((self.maxValue - self.minValue) /
                                self.scaleMajor) + self.minValue

            numstr = QString("%1").arg(tmpVal)
            w = fm.size(Qt.TextSingleLine, numstr).width()
            h = fm.size(Qt.TextSingleLine, numstr).height()
            x = 82 * cosa - w / 2
            y = -82 * sina + h / 4
            self.painter.drawText(x, y, numstr)
        self.painter.restore()
Beispiel #27
0
    def _initFileOptionsWidget(self):
        # List all image formats supported by QImageWriter
        exts = [
            str(QString(ext))
            for ext in list(QImageWriter.supportedImageFormats())
        ]

        # insert them into file format combo box
        for ext in exts:
            self.fileFormatCombo.addItem(ext + ' sequence')

        # connect handles
        self.fileFormatCombo.currentIndexChanged.connect(
            self._handleFormatChange)
        self.filePatternEdit.textEdited.connect(self._handlePatternChange)
        self.directoryEdit.textChanged.connect(self._validateFilePath)
        self.selectDirectoryButton.clicked.connect(self._browseForPath)

        # set default file format to png
        self.fileFormatCombo.setCurrentIndex(exts.index('png'))
        self._updateFilePattern()
        self._validateFilePath()
    def updateTaskTableWidget(self):
        rowCount = len(self.tasks)
        self.ui.tWTasks.setRowCount(rowCount)
        rowCount = 0
        for _, task in self.tasks.items():
            item = QtGui.QTableWidgetItem()
            item.setText(QString(task.taskName))
            self.ui.tWTasks.setItem(rowCount, 0, item)

            item = QtGui.QTableWidgetItem()
            # debug.debug(unicode(task.storeName))
            item.setText(unicode(task.storeName))
            self.ui.tWTasks.setItem(rowCount, 1, item)

            item = QtGui.QTableWidgetItem()
            item.setText(task.reservType)
            self.ui.tWTasks.setItem(rowCount, 2, item)

            item = QtGui.QTableWidgetItem()
            item.setText('%s' % task.proxyServer)
            self.ui.tWTasks.setItem(rowCount, 3, item)
            rowCount += 1
Beispiel #29
0
    def filterAcceptsRow(self, source_row, source_parent):
        '''
        Re-implementation of QSortFilterProxyModel's' filterAcceptsRow( self, source_row, source_parent ) function.
        It uses not only 'name' of the item, but also tags of item/modul.
        '''
        result = False

        useIndex = self.sourceModel().index(source_row, 0, source_parent)
        name = self.sourceModel().data(useIndex, Qt.DisplayRole).toString()

        if (name.contains(self.filterRegExp())):
            result = True
        else:
            # searching in tags
            mod = self.sourceModel().data(useIndex,
                                          Qt.UserRole + 1).toPyObject()
            for tag in mod.tags():
                tag = QString(tag)
                if (tag.contains(self.filterRegExp())):
                    result = True
                    break
        return result
Beispiel #30
0
    def setFromNode(self, node=None):
        if node:
            ## defined in NodeDlg
            self.node = node
        if not self.node:
            return
        attributeMap = self.node.attributes()

        self.name = unicode(
            attributeMap.namedItem("name").nodeValue()
            if attributeMap.contains("name") else "")
        self.target = unicode(
            attributeMap.namedItem("target").nodeValue()
            if attributeMap.contains("target") else "")

        text = unicode(DomTools.getText(self.node)).strip()
        if text and text.startswith("$datasources."):
            self.target = text

        doc = self.node.firstChildElement(QString("doc"))
        text = DomTools.getText(doc)
        self.doc = unicode(text).strip() if text else ""