Example #1
0
def get_series_number_qt(dcmreader,
                         counts,
                         bins,
                         qt_app=None):  # pragma: no cover

    if qt_app is None:
        # @TODO  there is problem with type of qappliaction
        # mport PyQt4
        # rom PyQt4.QtGui import QApplication
        # t_app = QApplication(sys.argv)
        # t_app = PyQt4.QtGui.QWidget(sys.argv)
        print(qt_app)

    series_info = dcmreader.dicomdirectory.get_stats_of_series_in_dir()
    study_info_msg = dcmreader.dicomdirectory.get_study_info_msg(
        series_info=series_info)
    print(dcmreader.print_series_info(series_info))
    from PyQt4.QtGui import QInputDialog
    # bins = ', '.join([str(ii) for ii in bins])
    sbins = [str(ii) for ii in bins]
    sbinsd = {}
    for serie_number in series_info.keys():
        strl = get_one_serie_info(series_info, serie_number)
        sbinsd[strl] = serie_number
        # sbins.append(str(ii) + "  " + serie_number)
    sbins = list(sbinsd)
    snstring, ok = \
        QInputDialog.getItem(qt_app,
                             'Serie Selection',
                             study_info_msg +
                             ' Select serie:',
                             sbins,
                             editable=False)
    sn = sbinsd[str(snstring)]
    return sn
Example #2
0
 def useLayerExtent(self):
     CANVAS_KEY = 'Use canvas extent'
     extentsDict = {}
     extentsDict[CANVAS_KEY] = {
         "extent": iface.mapCanvas().extent(),
         "authid":
         iface.mapCanvas().mapRenderer().destinationCrs().authid()
     }
     extents = [CANVAS_KEY]
     layers = dataobjects.getAllLayers()
     for layer in layers:
         authid = layer.crs().authid()
         if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF) \
                 and authid is not None:
             layerName = u'{} [{}]'.format(layer.name(), authid)
         else:
             layerName = layer.name()
         extents.append(layerName)
         extentsDict[layerName] = {
             "extent": layer.extent(),
             "authid": authid
         }
     (item, ok) = QInputDialog.getItem(self, self.tr('Select extent'),
                                       self.tr('Use extent from'), extents,
                                       False)
     if ok:
         self.setValueFromRect(extentsDict[item]["extent"])
         if extentsDict[item]["authid"] != iface.mapCanvas().mapRenderer(
         ).destinationCrs().authid():
             iface.messageBar().pushMessage(
                 self.tr("Warning"),
                 self.
                 tr("The projection of the chosen layer is not the same as canvas projection! The selected extent might not be what was intended."
                    ), QgsMessageBar.WARNING, 8)
Example #3
0
    def add_display(self):
        analog_ports = self.home_module.client_core.get_analog_ports()

        (name, ok) = QInputDialog.getText(
            self,
            QCA.translate("AdminHomeMap", "Agregar Display"),
            QCA.translate("AdminHomeMap", "Ingresar el nombre del display:"),
        )

        if ok:
            if len(name) > 32 or len(name) < 3:
                QMessageBox.critical(
                    self,
                    QCA.translate("AdminHomeHeating", "Agregar Display"),
                    QCA.translate("AdminHomeHeating", "El nombre del display debe tener entre 3 y 32 caracteres"),
                )
            else:
                (port, ok) = QInputDialog.getItem(
                    self,
                    QCA.translate("AdminHomeHeating", "Seleccionar puerto"),
                    QCA.translate("AdminHomeHeating", "Seleccionar el puerto del display"),
                    analog_ports.keys(),
                    0,
                    False,
                )

                self.abort_operation_mode()
                self.start_operation_mode("add_display", {"position": None, "name": name, "port": port})
Example #4
0
 def edit_parameters(self):
     allaxes = self.canvas.figure.get_axes()
     if len(allaxes) == 1:
         axes = allaxes[0]
     elif len(allaxes) > 1:
         titles = []
         for axes in allaxes:
             title = axes.get_title()
             ylabel = axes.get_ylabel()
             if title:
                 text = title
                 if ylabel:
                     text += ": "+ylabel
                 text += " (%s)"
             elif ylabel:
                 text = ylabel+" (%s)"
             else:
                 text = "%s"
             titles.append(text % repr(axes))
         item, ok = QInputDialog.getItem(self, 'Customize',
                                         'Select axes:', titles,
                                         0, False)
         if ok:
             axes = allaxes[titles.index(unicode(item))]
         else:
             return
     else:
         return
     figure_edit(axes, self)
Example #5
0
 def showPeakTable(self):
     """
     TODO: write little function to check if sample is None or good
     or write exception with good code
     
     """
     if not self.view.sampleTableView.selectedIndexes(
     ):  #not self.acTree.selectedIndexes():
         s, b = QInputDialog.getItem(
             self.view, "Select one sample", "Select one sample :",
             [spl.shortName() for spl in self.model])
         if not b:
             return
         sample = self.model.sample(str(s), fullNameEntry=False)
     else:
         idx = self.view.sampleTableView.selectedIndexes()[0]
         sample = self.model.sample(idx.data().toString(),
                                    fullNameEntry=False)
     if sample is None:
         print("sample not found...")
         return
     if not sample.rawPeaks:
         self.view.showErrorMessage(
             "No peaks found",
             "This sample does not have peaks, please do peak picking before"
         )
     view = QTableView()
     view.horizontalHeader().setStretchLastSection(True)
     view.setSortingEnabled(True)
     model = MSDialogController.getSampleModel(sample, flags='peak')
     view.setModel(model)
     self.view.addMdiSubWindow(
         view, " ".join(["PeakList of",
                         str(sample.shortName())]))
Example #6
0
 def show(self):
     (seType, ok) = QInputDialog.getItem(self.parent, u'创建模板',
                                         u'需要创建的Excel文件模板', SelecType)
     if ok and (seType != None and seType.strip() != ''):
         if seType == SelecType[0]:
             mtype = ExcelType.SITEANDCELL
         elif seType == SelecType[1]:
             mtype = ExcelType.SERVINGCELL
         # elif seType == SelecType[2]:
         #     mtype = ExcelType.ANALYSITE
         # elif seType == SelecType[3]:
         #     mtype = ExcelType.PUSHSITE
         # elif seType == SelecType[4]:
         #     mtype = ExcelType.MERGESITE
         else:
             QMessageBox.critical(self.parent, u"错误", u"请重新选择要生成的模板!")
             return
         fileName = QFileDialog.getSaveFileName(
             self.parent, SelecType[mtype], SelecType[mtype] + u"数据.xls",
             'Excel File (*.xls)')
         if fileName != None and fileName.strip() != '':
             if createModelFile(mtype, fileName):
                 QMessageBox.information(self.parent, u"生成模板文件",
                                         u"生成模板文件成功!")
             else:
                 QMessageBox.critical(self.parent, u"生成模板文件", u"生成模板文件失败!")
Example #7
0
 def showClusterTable(self):
     if not self.view.sampleTableView.selectedIndexes(
     ):  #not self.acTree.selectedIndexes():
         s, b = QInputDialog.getItem(
             self.view, "Select one sample", "Select one sample :",
             [spl.shortName() for spl in self.model])
         if not b:
             return
         sample = self.model.sample(str(s), fullNameEntry=False)
     else:
         idx = self.view.sampleTableView.selectedIndexes()[0]
         sample = self.model.sample(idx.data().toString(),
                                    fullNameEntry=False)
     if sample is None:
         print("sample not found...")
         return
     if not sample.mappedPeaks:
         self.view.showErrorMessage(
             "No peaks found",
             "This sample does not have peaks, please do peak picking before"
         )
     view = QTableView()
     view.setSortingEnabled(True)
     view.horizontalHeader().setStretchLastSection(True)
     view.setModel(
         MSDialogController.getSampleModel(sample, flags='cluster'))
     self.view.addMdiSubWindow(view,
                               "ClusterList of%s" % str(sample.shortName()))
Example #8
0
    def set_color(self):
        # couleur = QtGui.QColorDialog.getColor(QtCore.Qt.white)

        testqt, ok = QInputDialog.getItem(None, "Couleur",
                                          "Selection d'une couleur",
                                          LETTERSTOQCOLOR.keys(), False)
        if ok:
            # couleur = self.nameColorsToLetters[testqt]
            couleur = LETTERSTOQCOLOR[testqt]
            logger.debug(couleur)
            self.color = FRENCHTOLETTER[testqt]
        else:
            couleur = LETTERSTOQCOLOR['noir']
            self.color = 'b'

        # self.color = str(couleur.name())
        # logger.debug( couleur.name())

        # self.color = self.lettersToNameColor[testqt]

        pixmap = QPixmap(self.pushButton_color.size())
        # pixmap.fill(QColor(self.color))
        pixmap.fill(couleur)
        icon = QIcon(pixmap)
        self.pushButton_color.setIcon(icon)
        # logger.debug(  QColor(self.color) )

        # self.pushButton_color.setStyleSheet("background-color: " + self.color )

        # palette = QtGui.QPalette()
        # palette.setColor(QtGui.QPalette.ButtonText, self.lettersToQColor[testqt])
        # palette.setColor(10, couleur)
        # self.pushButton_color.setPalette(palette)
        self.emit(SIGNAL("redraw()"))
Example #9
0
 def make_jss(self, html):
     ' make js '
     indnt = ' ' * int(QInputDialog.getInteger(None, __doc__,
                       " JS Indentation Spaces: ", 4, 0, 8, 2)[0])
     scrpt = QInputDialog.getItem(None, __doc__, "Enclosing script Tags ?",
                     ['Use script html tags', 'No script tags'], 0, False)[0]
     p = True if 'Use script html tags' in scrpt else False
     self.soup = self.get_soup(html)
     jss = '<script>{}'.format(linesep) if p is True else ''
     jss += '//{} by {}{}'.format(datetime.now().isoformat().split('.')[0],
                                    getuser(), linesep)
     jss += '$(document).ready(function(){' + linesep
     previously_styled = []
     previously_styled.append(tag_2_ignore)
     jss += '{}//{}{}'.format(linesep, '-' * 76, linesep)
     for part in self.get_ids():
         if part not in previously_styled:
             jss += '{}//{}{}'.format(indnt, '#'.join(part).lower(), linesep)
             jss += js_template.format(indnt, 'var ',
                    re.sub('[^a-z]', '', part[1].lower() if len(part[1]) < 11 else re.sub('[aeiou]', '', part[1].lower())),
                    ' = ', '$("#{}").lenght'.format(part[1]), ';', linesep,
                    linesep, '')
             previously_styled.append(part)
     jss += '//{}{}'.format('-' * 76, linesep)
     for part in self.get_classes():
         if part not in previously_styled:
             jss += '{}//{}{}'.format(indnt, '.'.join(part).lower(), linesep)
             jss += js_template.format(indnt, 'var ',
                    re.sub('[^a-z]', '', part[1].lower() if len(part[1]) < 11 else re.sub('[aeiou]', '', part[1].lower())),
                    ' = ', '$(".{}").lenght'.format(part[1]), ';', linesep,
                    linesep, '')
             previously_styled.append(part)
     jss += '});'
     jss += '{}</script>'.format(linesep) if p is True else ''
     return jss.strip()
Example #10
0
    def doGeocoding(self, address):
        address = unicodedata.normalize('NFKD', unicode(address)).encode('ASCII', 'ignore')
        url = "http://api-adresse.data.gouv.fr/search/?q="+address.replace(" ", "%20")
        
        result = self.request(url)

        try:
            data = json.loads(result)
            features = data["features"]
            if len(features) > 0:
                feature_list = []
                for feature in features:
                    feature_list.append(feature["properties"]["label"]+" - "+str(round(feature["properties"]["score"]*100))+"%")
                feature, ok = QInputDialog.getItem(self.iface.mainWindow(), self.tr("Result"), "", feature_list)
                if ok:
                    index = feature_list.index(feature)
                    x = features[index]["geometry"]["coordinates"][0]
                    y = features[index]["geometry"]["coordinates"][1]
                    point_4326 = QgsPoint(x, y)
                    transform = QgsCoordinateTransform(QgsCoordinateReferenceSystem(4326), 
                                                        self.canvas.mapSettings().destinationCrs())
                    point_2154 = transform.transform(point_4326)
                    self.rb.addPoint(point_2154)
                    self.iface.mapCanvas().setCenter(point_2154)
                    self.iface.mapCanvas().refresh()
            else:
                QMessageBox.information(self.iface.mainWindow(), self.tr("Result"), self.tr("No result."))
        except ValueError:
            QMessageBox.critical(self.iface.mainWindow(), self.tr("Error"), self.tr("An error occured. Check your network settings (proxy)."))
Example #11
0
        def edit_parameters(self):
            allaxes = self.canvas.figure.get_axes()
            if len(allaxes) == 1:
                axes = allaxes[0]
            else:
                titles = []
                for axes in allaxes:
                    title = axes.get_title()
                    ylabel = axes.get_ylabel()
                    label = axes.get_label()
                    if title:
                        fmt = "%(title)s"
                        if ylabel:
                            fmt += ": %(ylabel)s"
                        fmt += " (%(axes_repr)s)"
                    elif ylabel:
                        fmt = "%(axes_repr)s (%(ylabel)s)"
                    elif label:
                        fmt = "%(axes_repr)s (%(label)s)"
                    else:
                        fmt = "%(axes_repr)s"
                    titles.append(fmt % dict(title=title,
                                         ylabel=ylabel, label=label,
                                         axes_repr=repr(axes)))
                item, ok = QInputDialog.getItem(
                    self.parent, 'Customize', 'Select axes:', titles, 0, False)
                if ok:
                    axes = allaxes[titles.index(six.text_type(item))]
                else:
                    return

            figureoptions.figure_edit(axes, self)
Example #12
0
        def edit_parameters(self):
            allaxes = self.canvas.figure.get_axes()
            if len(allaxes) == 1:
                axes = allaxes[0]
            else:
                titles = []
                for axes in allaxes:
                    title = axes.get_title()
                    ylabel = axes.get_ylabel()
                    label = axes.get_label()
                    if title:
                        fmt = "%(title)s"
                        if ylabel:
                            fmt += ": %(ylabel)s"
                        fmt += " (%(axes_repr)s)"
                    elif ylabel:
                        fmt = "%(axes_repr)s (%(ylabel)s)"
                    elif label:
                        fmt = "%(axes_repr)s (%(label)s)"
                    else:
                        fmt = "%(axes_repr)s"
                    titles.append(fmt % dict(title=title,
                                             ylabel=ylabel,
                                             label=label,
                                             axes_repr=repr(axes)))
                item, ok = QInputDialog.getItem(self.parent, 'Customize',
                                                'Select axes:', titles, 0,
                                                False)
                if ok:
                    axes = allaxes[titles.index(six.text_type(item))]
                else:
                    return

            figureoptions.figure_edit(axes, self)
Example #13
0
 def on_actionGotoPoint_triggered(self):
     data = self._data
     points = [str(pid) for pid in data.cell_points]
     selected, ok = QInputDialog.getItem(self, "Goto point",
                                         "Select the point to go to",
                                         points, 0)
     if ok:
         pid = int(selected)
         self.ui.action_Move_point.setChecked(True)
         if pid not in data.cell_points:
             return
         prev_pos = self._previousScene.current_data._current_index
         cur_pos = self._currentScene.current_data._current_index
         prev_data = self._previousScene.current_data
         if not pid in prev_data:
             closest = -1
             best_dist = len(data) + 1
             for img_data in data:
                 if pid in img_data:
                     dist = abs(img_data._current_index - prev_pos)
                     if dist < best_dist:
                         best_dist = dist
                         closest = img_data._current_index
             new_prev_pos = closest
         else:
             new_prev_pos = prev_pos
         new_cur_pos = min(max(cur_pos + new_prev_pos - prev_pos, 0),
                           len(data))
         self.ui.previousState.setCurrentIndex(new_prev_pos)
         self.ui.currentState.setCurrentIndex(new_cur_pos)
         self._previousScene.setSelectedIds([pid])
         self._currentScene.setSelectedIds([pid])
         self.ui.previousData.centerOn(
             self._previousScene.current_data[pid])
Example #14
0
    def showTempPasswordDialog(self):
        """ Sets overridePassword for a server.
        Using this one doesn't actually have to enter the password
        in the ServerDialog (and by extension save to disk).
        """
        serverList = ServerList()

        # Create a stringlist to be used by the qinputdialog
        stringList = []
        for server in serverList.getTable():
            stringList.append(server.name)

        # Display list of servers
        (serverString, ok) = QInputDialog.getItem(
            self,
            QApplication.translate("MainWindow", "Select server"),
            QApplication.translate("MainWindow", "Server:"),
            stringList,
            editable=False
        )
        if ok:
            server = serverList.getServerObjectByName(serverString)
            if server != None:
                # Ask for password
                (value, ok) = QInputDialog.getText(
                    self,
                    QApplication.translate("MainWindow", "Temporary password"),
                    QApplication.translate("MainWindow", "Enter password:"),
                    QLineEdit.Password
                )
                if ok:
                    # Use value as the overridePassword for the server.
                    LumaConnection(server).overridePassword(value)
Example #15
0
 def edit_parameters(self):
     if edit_parameters is None:
         allaxes = self.canvas.figure.get_axes()
         if len(allaxes) == 1:
             axes = allaxes[0]
         elif len(allaxes) > 1:
             titles = []
             for axes in allaxes:
                 title = axes.get_title()
                 ylabel = axes.get_ylabel()
                 if title:
                     text = title
                     if ylabel:
                         text += ": "+ylabel
                     text += " (%s)"
                 elif ylabel:
                     text = "%s (%s)" % ylabel
                 else:
                     text = "%s"
                 titles.append(text % repr(axes))
             item, ok = QInputDialog.getItem(self, 'Customize',
                                             'Select axes:', titles,
                                             0, False)
             if ok:
                 axes = allaxes[titles.index(unicode(item))]
             else:
                 return
         else:
             return
         figure_edit(axes, self)
     else:
         super(NavigationToolbar2QT, self).edit_parameters()
Example #16
0
def get_series_number_qt(dcmreader, counts, bins, qt_app=None):  # pragma: no cover

    if qt_app is None:
        # @TODO  there is problem with type of qappliaction
        # mport PyQt4
        # rom PyQt4.QtGui import QApplication
        # t_app = QApplication(sys.argv)
        # t_app = PyQt4.QtGui.QWidget(sys.argv)
        print(qt_app)

    series_info = dcmreader.dicomdirectory.get_stats_of_series_in_dir()
    study_info_msg = dcmreader.dicomdirectory.get_study_info_msg(series_info=series_info)
    print(dcmreader.print_series_info(series_info))
    from PyQt4.QtGui import QInputDialog
    # bins = ', '.join([str(ii) for ii in bins])
    sbins = [str(ii) for ii in bins]
    sbinsd = {}
    for serie_number in series_info.keys():
        strl = get_one_serie_info(series_info, serie_number)
        sbinsd[strl] = serie_number
        # sbins.append(str(ii) + "  " + serie_number)
    sbins = list(sbinsd)
    snstring, ok = \
        QInputDialog.getItem(qt_app,
                             'Serie Selection',
                             study_info_msg +
                             ' Select serie:',
                             sbins,
                             editable=False)
    sn = sbinsd[str(snstring)]
    return sn
 def on_actionGotoPoint_triggered(self):
     data = self._data
     points = [str(pid) for pid in data.cell_points]
     selected, ok = QInputDialog.getItem(self, "Goto point", "Select the point to go to", points, 0)
     if ok:
         pid = int(selected)
         self.ui.action_Move_point.setChecked(True)
         if pid not in data.cell_points:
             return
         prev_pos = self._previousScene.current_data._current_index
         cur_pos = self._currentScene.current_data._current_index
         prev_data = self._previousScene.current_data
         if not pid in prev_data:
             closest = -1
             best_dist = len(data)+1
             for img_data in data:
                 if pid in img_data:
                     dist = abs(img_data._current_index - prev_pos)
                     if dist < best_dist:
                         best_dist = dist
                         closest = img_data._current_index
             new_prev_pos = closest
         else:
             new_prev_pos = prev_pos
         new_cur_pos = min(max(cur_pos + new_prev_pos - prev_pos, 0), len(data))
         self.ui.previousState.setCurrentIndex(new_prev_pos)
         self.ui.currentState.setCurrentIndex(new_cur_pos)
         self._previousScene.setSelectedIds([pid])
         self._currentScene.setSelectedIds([pid])
         self.ui.previousData.centerOn(self._previousScene.current_data[pid])
Example #18
0
    def showTempPasswordDialog(self):
        """ Sets overridePassword for a server.
        Using this one doesn't actually have to enter the password
        in the ServerDialog (and by extension save to disk).
        """
        serverList = ServerList()

        # Create a stringlist to be used by the qinputdialog
        stringList = []
        for server in serverList.getTable():
            stringList.append(server.name)

        # Display list of servers
        (serverString, ok) = QInputDialog.getItem(
            self,
            QApplication.translate("MainWindow", "Select server"),
            QApplication.translate("MainWindow", "Server:"),
            stringList,
            editable=False)
        if ok:
            server = serverList.getServerObjectByName(serverString)
            if server != None:
                # Ask for password
                (value, ok) = QInputDialog.getText(
                    self,
                    QApplication.translate("MainWindow", "Temporary password"),
                    QApplication.translate("MainWindow", "Enter password:"),
                    QLineEdit.Password)
                if ok:
                    # Use value as the overridePassword for the server.
                    LumaConnection(server).overridePassword(value)
Example #19
0
 def useLayerExtent(self):
     CANVAS_KEY = "Use canvas extent"
     extentsDict = {}
     extentsDict[CANVAS_KEY] = {
         "extent": iface.mapCanvas().extent(),
         "authid": iface.mapCanvas().mapRenderer().destinationCrs().authid(),
     }
     extents = [CANVAS_KEY]
     layers = dataobjects.getAllLayers()
     for layer in layers:
         authid = layer.crs().authid()
         if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF) and authid is not None:
             layerName = u"{} [{}]".format(layer.name(), authid)
         else:
             layerName = layer.name()
         extents.append(layerName)
         extentsDict[layerName] = {"extent": layer.extent(), "authid": authid}
     (item, ok) = QInputDialog.getItem(self, self.tr("Select extent"), self.tr("Use extent from"), extents, False)
     if ok:
         self.setValueFromRect(extentsDict[item]["extent"])
         if extentsDict[item]["authid"] != iface.mapCanvas().mapRenderer().destinationCrs().authid():
             iface.messageBar().pushMessage(
                 self.tr("Warning"),
                 self.tr(
                     "The projection of the chosen layer is not the same as canvas projection! The selected extent might not be what was intended."
                 ),
                 QgsMessageBar.WARNING,
                 8,
             )
Example #20
0
 def keyPressEvent(self, event):
     key = event.key()
     mod = event.modifiers()
     if key == Qt.Key_Up and self.history:
         self.history_i = min(self.history_i+1, len(self.history)-1)
         self.lineInput.setText(self.history[self.history_i])
     elif key == Qt.Key_Down and self.history:
         self.history_i = max(self.history_i-1, -1)
         if self.history_i >= 0:
             self.lineInput.setText(self.history[self.history_i])
         else:
             self.lineInput.setText('')
     elif key == Qt.Key_Enter or key == Qt.Key_Return:
         if mod & Qt.ShiftModifier:
             self.complete()
         else:
             self.run()
     elif key == Qt.Key_Escape:
         txt, r = QInputDialog.getItem(self, QCoreApplication.translate("QPyShell", "Command line history"),
             QCoreApplication.translate("QPyShell", "Please select a history item:"),
             self.history, 0, False)
         if r and txt:
             self.lineInput.setText(txt)
     elif self.standalone and key == Qt.Key_Print:
         self.printContents()
     elif self.standalone and key == Qt.Key_Q and (mod & Qt.ControlModifier):
         self.close()
     else:
         QWidget.keyPressEvent(self, event)
Example #21
0
def choose(parent, options, title, description):
    strings = ["%d. %r" % (i, item) for i, item in enumerate(options, 1)]
    selected, ok = QInputDialog.getItem(parent, title, description, strings, editable=False)
    if ok:
        return options[strings.index(selected)]
    else:
        raise RuntimeError("getItem failed")
Example #22
0
    def callback_MocapRowEntry(self):
        # https://stackoverflow.com/questions/7907928/openpyxl-check-for-empty-
        global item
        global description
        global SuffixCount
        global rowCountIndex

        sheet = wb.get_sheet_by_name('Project 1')

        sheet['A'+str(rowCountIndex)].value = str(SuffixCount)
        sheet['B'+str(rowCountIndex)].value = 'MVN_Take_'+ str(SuffixCount)
        sheet['C'+str(rowCountIndex)].value = 'FBX_'+str(SuffixCount)+'.fbx'

        # for selecting which level the mocap was captured on #
        items = ('No-Level', 'Single-Level', 'Multi-Level')
        item, ok = QInputDialog.getItem(self, "Select Which Level", "Capture-Type", items, 0, False)
        if ok and item:
            sheet['D'+str(rowCountIndex)].value = str(item)

        # for entering the description for the mocap take #
        description, ok = QInputDialog.getText(self, "Take Description", "Enter a Description for this Take:")
        if ok and description:
            sheet['E'+str(rowCountIndex)].value = str(description)
            self.le_outputfield.setText('Entry '+ str(SuffixCount)+' Entered!')
        print('|| Entry: ' + str(SuffixCount) + ' | Level-Type: ' + str(item) + ' | Description: ' + str(description) + ' ||')

        SaveFile('template.xlsx')
        SuffixCount += 1
        rowCountIndex += 1
Example #23
0
 def showPeakTable(self):
     """
     TODO: write little function to check if sample is None or good
     or write exception with good code
     
     """
     if not self.view.sampleTableView.selectedIndexes():#not self.acTree.selectedIndexes():
         s, b = QInputDialog.getItem(self.view, "Select one sample", "Select one sample :", 
                                  [spl.shortName() for spl in self.model])
         if not b:
             return
         sample = self.model.sample(str(s), fullNameEntry=False)
     else:
         idx = self.view.sampleTableView.selectedIndexes()[0]
         sample = self.model.sample(idx.data().toString(), fullNameEntry=False)
     if sample is None:
         print ("sample not found...")
         return
     if not sample.rawPeaks:
         self.view.showErrorMessage("No peaks found", 
                                    "This sample does not have peaks, please do peak picking before")
     view=QTableView()
     view.horizontalHeader().setStretchLastSection(True)
     view.setSortingEnabled(True)
     model=MSDialogController.getSampleModel(sample, flags='peak')
     view.setModel(model)           
     self.view.addMdiSubWindow(view, " ".join(["PeakList of", str(sample.shortName())]))
    def set_color(self):
        # couleur = QtGui.QColorDialog.getColor(QtCore.Qt.white)

        testqt, ok = QInputDialog.getItem(None, "Couleur", "Selection d'une couleur", self.lettersToQColor.keys(), False)
        if ok:
            # couleur = self.nameColorsToLetters[testqt]
            couleur = self.lettersToQColor[testqt]
            logger.debug(couleur)
            self.color = self.frenchToLetter[testqt]
        else:
            couleur = self.lettersToQColor['noir']
            self.color = 'b'

        # self.color = str(couleur.name())
        # logger.debug( couleur.name())

        # self.color = self.lettersToNameColor[testqt]

        pixmap = QPixmap(self.pushButton_color.size())
        # pixmap.fill(QColor(self.color))
        pixmap.fill(couleur)
        icon = QIcon(pixmap)
        self.pushButton_color.setIcon(icon)
        # logger.debug(  QColor(self.color) )

        # self.pushButton_color.setStyleSheet("background-color: " + self.color )

        # palette = QtGui.QPalette()
        # palette.setColor(QtGui.QPalette.ButtonText, self.lettersToQColor[testqt])
        # palette.setColor(10, couleur)
        # self.pushButton_color.setPalette(palette)
        self.emit(SIGNAL("colorChanged"))
Example #25
0
def select_db():
    """
     This database allows you to select interactively which database you want to use.
     Its implementation is really minimal for the moment, but it may act as memo
     when you search of the name of databasse.
    """
    try:
        from pycvf.lib.ui import qt
        from PyQt4.QtGui import QInputDialog

        dbl = dblist()
        r = QInputDialog.getItem(None, "Select a database to use", "Select a database to use", dbl)
        if r[1]:
            r = str(r[0])
        else:
            raise KeyboardInterrupt
    except KeyboardInterrupt:
        raise
    except:
        dbl = dblist()
        sl = map(lambda x, y: (x, y), range(1, 1 + len(dbl)), dbl)
        for l in sl:
            print l
        r = int(sys.stdin.readline())
        r = dbl[r - 1]
    return builders.load_force(r)
    def add_var(self, source = 'input'):
        '''
        Adds a variable to the margins

        Parameters
        ----------
        source : str, default to 'free'
                 Can be 'free' (default), 'input' or 'output' according to the variable
        '''

#        TODO: fix this lists      = {'input': self.input_vars_list, 'output': self.output_vars_list, 'free': self.free_vars_list}

        lists      = {'input': self.input_vars_list}

        variables_list = lists[source]
        varnames = self.get_name_label_dict(variables_list) # {varname: varlabel}

        varlabel, ok = QInputDialog.getItem(self.parent(), "Ajouter une variable", "Nom de la variable",
                                           sorted(varnames.keys()))

        insertion = ok and (varlabel in sorted(varnames.keys()))
        if insertion:
            varname = varnames[varlabel]
            datatable_name = self.get_var_datatable(varname)
            target = None
            if source=='input' and self.input_margins_df:
                index = self.input_margins_df.index
                indices = [ (var, mod)  for (var, mod) in index if var==varname ]
                target_df = (self.input_margins_df['target'][indices]).reset_index()
                target = dict(zip(target_df['mod'] ,target_df['target']))
            else:
                if datatable_name =='output_table':
                    varcol = self.output_table.column_by_name.get(varname)
                elif datatable_name =='inputs':
                    varcol = self.inputs.column_by_name.get(varname)

                if varcol.__class__ not in MODCOLS:
                        val, ok = QInputDialog.getDouble(self.parent(), "Valeur de la  marge", unicode(varlabel) + "  (millions d'euros)")
                        if ok:
                            target = {str(varname): val*1e6}
                else:
                    if datatable_name =='output_table':
                        unique_values = unique(self.output_table.get_value(varname, self.entity))
                    elif datatable_name =='inputs':
                        unique_values = unique(self.inputs.get_value(varname, self.entity))
                    target = {}

                    for mod in unique_values:
                        val, ok = QInputDialog.getDouble(self.parent(), "Valeur de la  marge", unicode(varlabel) + u" pour la modalité " + str(mod) )
                        if ok:
                            target[mod] = val
                        else:
                            return

            if target:
                self.calibration.add_var2(varname, target = target, source=source)
                self.param_or_margins_changed()
Example #27
0
    def add_var(self, source = 'input'):
        '''
        Adds a variable to the margins

        Parameters
        ----------
        source : str, default to 'free'
                 Can be 'free' (default), 'input' or 'output' according to the variable
        '''

#        TODO: fix this lists      = {'input': self.input_vars_list, 'output': self.output_vars_list, 'free': self.free_vars_list}

        lists      = {'input': self.input_vars_list}

        variables_list = lists[source]
        varnames = self.get_name_label_dict(variables_list) # {varname: varlabel}

        varlabel, ok = QInputDialog.getItem(self.parent(), "Ajouter une variable", "Nom de la variable",
                                           sorted(varnames.keys()))

        insertion = ok and (varlabel in sorted(varnames.keys()))
        if insertion:
            varname = varnames[varlabel]
            datatable_name = self.get_var_datatable(varname)
            target = None
            if source=='input' and self.input_margins_df:
                index = self.input_margins_df.index
                indices = [ (var, mod)  for (var, mod) in index if var==varname ]
                target_df = (self.input_margins_df['target'][indices]).reset_index()
                target = dict(zip(target_df['mod'] ,target_df['target']))
            else:
                if datatable_name =='output_table':
                    varcol = self.output_table.column_by_name.get(varname)
                elif datatable_name =='inputs':
                    varcol = self.inputs.column_by_name.get(varname)

                if varcol.__class__ not in MODCOLS:
                        val, ok = QInputDialog.getDouble(self.parent(), "Valeur de la  marge", unicode(varlabel) + "  (millions d'euros)")
                        if ok:
                            target = {str(varname): val*1e6}
                else:
                    if datatable_name =='output_table':
                        unique_values = unique(self.output_table.get_value(varname, self.entity))
                    elif datatable_name =='inputs':
                        unique_values = unique(self.inputs.get_value(varname, self.entity))
                    target = {}

                    for mod in unique_values:
                        val, ok = QInputDialog.getDouble(self.parent(), "Valeur de la  marge", unicode(varlabel) + u" pour la modalité " + str(mod) )
                        if ok:
                            target[mod] = val
                        else:
                            return

            if target:
                self.calibration.add_var2(varname, target = target, source=source)
                self.param_or_margins_changed()
 def set_language(self):
     lang = QInputDialog.getItem(None, "Select Language", "Language",
                                 self.ui_languages)
     self.ui_language = lang[0]
     if self.ui_language == "French":
         self.ui_mTranslator.load(":/french.qm")
         self.ui_gTranslator.load(':/qt_fr.qm')
     elif self.ui_language == "Chinese":
         self.ui_mTranslator.load(":/chinese.qm")
         self.ui_gTranslator.load(':/qt_zh_CN.qm')
Example #29
0
def get_format(name):
	if name in format_dict:
		return format_dict[name]
	form = QInputDialog.getItem(None, "Format for %s" % name, 'Pick a format', format_options)
	for line in fileinput.input():
		if line.endswith('# end'):
			print('\n\n} # end')
		else:
			print(line)
	return form
Example #30
0
def choose(parent, options, title, description):
    strings = ["%d. %r" % (i, item) for i, item in enumerate(options, 1)]
    selected, ok = QInputDialog.getItem(parent,
                                        title,
                                        description,
                                        strings,
                                        editable=False)
    if ok:
        return options[strings.index(selected)]
    else:
        raise RuntimeError("getItem failed")
Example #31
0
 def loadPeakList(self):
     """
     TODO:rewrite this cause it is fake
     use csv module for that ?
     """        
     string, boolean = QInputDialog.getItem(self.view, "Choose a kind of MS", "Kind of MS experiment :",
                                            ("HighResolution" , "Multiple Reaction Monitoring"), editable=False)
     if string and boolean:
         f = str(QFileDialog.getOpenFileName(self.view, "Select peaklist to open", filter="*.pkl"))
         if not f:
             return
Example #32
0
 def _saveCurrent(self):
     '''Save the current playlist'''
     playlistModel = self.modelManager.playlists
     (name, ok) = QInputDialog.getItem(self,
             'Save Playlist',
             'Enter or select the playlist name',
             [name for name in playlistModel],
             0,
             True)
     if ok == True:
         playlistModel.saveCurrent(name)
Example #33
0
    def __init__(self,
                 dirpath=None,
                 initdir='.',
                 qt_app=None,
                 gui=True,
                 series_number=None):
        self.valid = False
        self.dirpath = dirpath
        self.dcmdir = self.get_dir()
        self.series_number = series_number
        self.overlay = {}
        self.dcmlist = []

        if len(self.dcmdir) > 0:
            self.valid = True
            counts, bins = self.status_dir()

            if len(bins) > 1:
                if self.series_number is None:  # pragma: no cover
                    if (qt_app is not None) or gui:
                        if qt_app is None:

                            # @TODO  there is problem with type of qappliaction
                            # mport PyQt4
                            # rom PyQt4.QtGui import QApplication
                            # t_app = QApplication(sys.argv)
                            # t_app = PyQt4.QtGui.QWidget(sys.argv)
                            print qt_app

                        from PyQt4.QtGui import QInputDialog
                        # bins = ', '.join([str(ii) for ii in bins])
                        sbins = [str(ii) for ii in bins]
                        snstring, ok = \
                            QInputDialog.getItem(qt_app,
                                                 'Serie Selection',
                                                 'Select serie:',
                                                 sbins,
                                                 editable=False)
                    else:
                        print 'series'
                        series_info = self.dcmdirstats()
                        print self.print_series_info(series_info)
                        snstring = raw_input('Select Serie: ')

                    sn = int(snstring)
                else:
                    sn = self.series_number

            else:
                sn = bins[0]

            self.series_number = sn

            self.dcmlist = self.get_sortedlist(SeriesNumber=sn)
Example #34
0
	def _comenzar(self):
		ok = 0
		eleccion, ok1 = QInputDialog.getItem(self, "Algoritmos", "Seleccione un algoritmo", self.algoritmos.keys())
		if ok1:
			self.contenedor = self.algoritmos[str(eleccion)]()
			self.cant, ok = QInputDialog.getInt(self, "Duracion", "Indique la duracion de la simulacion", min=0, max=60)
		if ok and ok1:
			self.setWindowTitle(self.windowTitle() + " --" +str(eleccion))
			self.temporizador.start(1000)
			self.iniciar.setEnabled(False)
			self.bloquear.setEnabled(True)
		self._inicializarDatos()
 def useLayerExtent(self):
     CANVAS_KEY = "Use canvas extent"
     extentsDict = {}
     extentsDict[CANVAS_KEY] = iface.mapCanvas().extent()
     extents = [CANVAS_KEY]
     layers = dataobjects.getAllLayers()
     for layer in layers:
         extents.append(layer.name())
         extentsDict[layer.name()] = layer.extent()
     (item, ok) = QInputDialog.getItem(self, self.tr("Select extent"), self.tr("Use extent from"), extents, False)
     if ok:
         self.setValueFromRect(extentsDict[item])
Example #36
0
 def run(self, option):
     ' run backend process '
     if option is 0:
         cmd = 'wdb.server.py'
     else:
         cmd = '{}wdb.server.py --theme={}'.format('chrt -i 0 ' if str(QInputDialog.getItem(None, __doc__, "Debugger Process CPU Priority:", ['LOW CPU Priority', 'High CPU Priority'], 0, False)[0]) in 'LOW CPU Priority' else '', str(QInputDialog.getItem(None, __doc__, "Web GUI Theme Skin:", ['dark', 'light'], 0, False)[0]))
     self.process.start(cmd)
     if not self.process.waitForStarted():
         QMessageBox.information(None, __doc__ + '- ERROR!',
         str(self.process.readAllStandardOutput()) +
         str(self.process.readAllStandardError()))
     else:
         open_new_tab('http://localhost:1984')
Example #37
0
File: qtutil.py Project: eteq/glue
def edit_layer_symbol(layer):
    """ Interactively edit a layer's symbol """
    dialog = QInputDialog()
    options = ['o', '^', '*', 's']
    try:
        initial = options.index(layer.style.marker)
    except IndexError:
        initial = 0
    symb, isok = dialog.getItem(None, 'Pick a Symbol',
                                'Pick a Symbol',
                                options, current=initial)
    if isok and symb != layer.style.marker:
        layer.style.marker = symb
 def useLayerExtent(self):
     CANVAS_KEY = 'Use canvas extent'
     extentsDict = {}
     extentsDict[CANVAS_KEY] = iface.mapCanvas().extent()
     extents = [CANVAS_KEY]
     layers = dataobjects.getAllLayers()
     for layer in layers:
         extents.append(layer.name())
         extentsDict[layer.name()] = layer.extent()
     (item, ok) = QInputDialog.getItem(self, self.tr('Select extent'),
             self.tr('Use extent from'), extents, False)
     if ok:
         self.setValueFromRect(extentsDict[item])
    def __saveCurrent(self):
        '''Save the current playlist'''
        lsinfo = self.mpdclient.lsinfo()
        playlists = []
        for somedict in lsinfo:
            if somedict.get('playlist',None) != None:
                playlists.append(somedict['playlist'])

        (name,ok) = QInputDialog.getItem(self,'Save Playlist','Enter or select the playlist name',playlists,0,True)
        if ok == True:
            if name in playlists:
                self.mpdclient.send('rm', (name,))
            self.mpdclient.send('save', (name,))
Example #40
0
    def ask(self, remove=False):
        if not remove:
            label = "Ajouter une variable"
            choices = self.vars - self.selected_vars
        else:
            choices = self.selected_vars
            label = "Retirer une variable"

        var, ok = QInputDialog.getItem(self, label, "Choisir la variable", sorted(list(choices)))
        if ok and var in list(choices):
            return str(var)
        else:
            return None
Example #41
0
    def switchDepartments(self, dept=''):
        """
                Switches the departments for the selected clips to the inputed department.
                If no department is supplied, then the user will be prompted to select one
                from a list.
                
                :param      dept:
                :type       <str>:
                
                :return     <bool>: success
        """
        # prompt the user to select a department if necessary
        if (not dept):
            dept, accepted = QInputDialog.getItem(
                self, 'Select Department', 'Select Department',
                settings.enabledDepartments())
            if (not accepted):
                return False

        # make sure we have a department
        if (not dept):
            return False

        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.blockUi(True)
        total = self.uiPlaylistTREE.topLevelItemCount()
        count = 0

        core.updateProgress(0)
        for i in range(total):
            item = self.uiPlaylistTREE.topLevelItem(i)

            # make sure the item is selected
            if (not item.isSelected()):
                core.updateProgress(int(100 * (i / float(total))))
                continue

            # set the item's department
            item.setDepartment(dept)
            count += 1
            core.updateProgress(int(100 * (i / float(total))))

        core.updateProgress(100)
        self.blockUi(False)

        QApplication.restoreOverrideCursor()

        self.emitPlaylistChanged()
        core.info('Switched %s clip departments.' % count)

        return True
Example #42
0
    def __init__(self, dirpath=None, initdir='.',
                 qt_app=None, gui=True, series_number=None):
        self.valid = False
        self.dirpath = dirpath
        self.dcmdir = self.get_dir()
        self.series_number = series_number
        self.overlay = {}
        self.dcmlist = []

        if len(self.dcmdir) > 0:
            self.valid = True
            counts, bins = self.status_dir()

            if len(bins) > 1:
                if self.series_number is None:
                    if (qt_app is not None) or gui:
                        if qt_app is None:

                            # @TODO  there is problem with type of qappliaction
                            # mport PyQt4
                            # rom PyQt4.QtGui import QApplication
                            # t_app = QApplication(sys.argv)
                            # t_app = PyQt4.QtGui.QWidget(sys.argv)
                            print qt_app

                        from PyQt4.QtGui import QInputDialog
                        # bins = ', '.join([str(ii) for ii in bins])
                        sbins = [str(ii) for ii in bins]
                        snstring, ok = \
                            QInputDialog.getItem(qt_app,
                                                 'Serie Selection',
                                                 'Select serie:',
                                                 sbins,
                                                 editable=False)
                    else:
                        print 'series'
                        series_info = self.dcmdirstats()
                        print self.print_series_info(series_info)
                        snstring = raw_input('Select Serie: ')

                    sn = int(snstring)
                else:
                    sn = self.series_number

            else:
                sn = bins[0]

            self.series_number = sn

            self.dcmlist = self.get_sortedlist(SeriesNumber=sn)
    def ask(self, remove=False):
        if not remove:
            label = "Ajouter une variable"
            choices = self.vars - self.selected_vars
        else:
            choices = self.selected_vars
            label = "Retirer une variable"

        var, ok = QInputDialog.getItem(self, label, "Choisir la variable",
                                       sorted(list(choices)))
        if ok and var in list(choices):
            return str(var)
        else:
            return None
 def switchDepartments( self, dept = '' ):
     """
             Switches the departments for the selected clips to the inputed department.
             If no department is supplied, then the user will be prompted to select one
             from a list.
             
             :param      dept:
             :type       <str>:
             
             :return     <bool>: success
     """
     # prompt the user to select a department if necessary
     if ( not dept ):
         dept, accepted = QInputDialog.getItem( self, 'Select Department', 'Select Department', settings.enabledDepartments() )
         if ( not accepted ):
             return False
     
     # make sure we have a department
     if ( not dept ):
         return False
     
     QApplication.setOverrideCursor( Qt.WaitCursor )
     self.blockUi(True)
     total = self.uiPlaylistTREE.topLevelItemCount()
     count = 0
     
     core.updateProgress(0)
     for i in range(total):
         item = self.uiPlaylistTREE.topLevelItem(i)
         
         # make sure the item is selected
         if ( not item.isSelected() ):
             core.updateProgress( int(100 * (i/float(total))) )
             continue
         
         # set the item's department
         item.setDepartment(dept)
         count += 1
         core.updateProgress( int(100 * (i/float(total))) )
     
     core.updateProgress(100)
     self.blockUi(False)
     
     QApplication.restoreOverrideCursor()
     
     self.emitPlaylistChanged()
     core.info('Switched %s clip departments.' % count)
     
     return True
Example #45
0
 def rmv_var(self):
     '''
     Removes variable from the margins
     '''
     vars_in_table = self.calibration.frame['var'].unique()
     varnames = self.get_name_label_dict(vars_in_table)
     varlabel, ok = QInputDialog.getItem(self.parent(), "Ajouter une variable", "Nom de la variable",
                                        sorted(varnames.keys()))
     varname = varnames[varlabel]
     deletion = ok and (varlabel)
     if deletion:
         df =  self.calibration.frame.reset_index(drop=True)
         cleaned = df[df['var'] != varname]
         self.calibration.frame = cleaned
     self.param_or_margins_changed()
 def rmv_var(self):
     '''
     Removes variable from the margins
     '''
     vars_in_table = self.calibration.frame['var'].unique()
     varnames = self.get_name_label_dict(vars_in_table)
     varlabel, ok = QInputDialog.getItem(self.parent(), "Ajouter une variable", "Nom de la variable",
                                        sorted(varnames.keys()))
     varname = varnames[varlabel]
     deletion = ok and (varlabel)
     if deletion:
         df =  self.calibration.frame.reset_index(drop=True)
         cleaned = df[df['var'] != varname]
         self.calibration.frame = cleaned
     self.param_or_margins_changed()
Example #47
0
File: qtutil.py Project: eteq/glue
def pick_item(items, labels, title="Pick an item", label="Pick an item",
              default=0):
    """ Prompt the user to choose an item

    :param items: List of items to choose
    :param labels: List of strings to label items
    :param title: Optional widget title
    :param label: Optional prompt

    Returns the selected item, or None
    """
    choice, isok = QInputDialog.getItem(None, title, label,
                                        labels, current=default)
    if isok:
        return dict(zip(labels, items))[str(choice)]
   def showTableNames(self):
      tables_names = self.sqliteConnector.getTableNames()
      if len(tables_names) > 0:
         tempTablesDialog, output = QInputDialog.getItem(self,
               "Tables available in " + self.currFilename,
               "",
               tables_names,
               current = 0,
               editable = False) 

         if output:
            self.openTable(tempTablesDialog)

      else:
         QMessageBox.critical(self, "Error", u'There are no tables registered in ' + self.currFilename)
Example #49
0
 def run(self, option):
     ' run backend process '
     if option is 0:
         QMessageBox.information(None, __doc__,
         '''pip-dump dumps the exact versions of installed packages in your
         active environment to your requirements.txt file.
         If you have more than one file matching *requirements.txt pattern
         (example dev-requirements.txt), it will update each one smartly.''')
         cmd = '{}pip-dump {} "{}"'.format('chrt -i 0 '
             if str(QInputDialog.getItem(None, __doc__,
             "PIP-Tools Process CPU Priority:", ['LOW CPU Priority',
             'High CPU Priority'], 0, False)[0]) in 'LOW CPU Priority'
             else '',
             '--verbose'
             if str(QInputDialog.getItem(None, __doc__, "PIP-Tools Options:",
             ['verbose', 'none'], 0, False)[0]) in 'verbose'
             else '',
             QFileDialog.getOpenFileName(None,
             "{} - Open requirements.txt".format(__doc__),
             path.expanduser("~"), 'requirements.txt(requirements.txt)'))
     else:
         QMessageBox.information(None, __doc__,
         '''pip-review checks PyPI and reports available updates.
         It uses the list of currently installed packages to check updates.
         Dont overwrite packages, just reports them.''')
         cmd = '{}pip-review --{}'.format('chrt -i 0 '
             if str(QInputDialog.getItem(None, __doc__,
             "PIP-Tools Process CPU Priority:", ['LOW CPU Priority',
             'High CPU Priority'], 0, False)[0]) in 'LOW CPU Priority'
             else '',
             str(QInputDialog.getItem(None, __doc__, "PIP-Tools Options:",
             ['verbose', 'local', 'raw'], 0, False)[0]))
     self.process.start(cmd)
     if not self.process.waitForStarted():
         QMessageBox.information(None, __doc__ + '- ERROR!',
         str(self.process.readAllStandardError()))
Example #50
0
    def show(self):
        allLayerNames = getAllLayerName(self.iface)
        (layerName, ok) = QInputDialog.getItem(self.parent, u'导出数据',
                            u'选择要导出的数据图层', allLayerNames)

        if ok and (layerName != None and layerName != ''):
            layer = getLayerByName(layerName, self.iface)
            saveFileName = QFileDialog.getSaveFileName(self.parent, u"导出数据",
                                '/', 'Excel File (*.xls)')
            if saveFileName.strip() != "":
                exportData = ExportData(self.iface, self.parent)
                if exportData.exportDataToExcel(layer, saveFileName):
                    QMessageBox.information(self.parent, u"导出数据", u"导出数据成功!")
                else:
                    QMessageBox.critical(self.parent, u"导出数据", u"导出数据失败!")
    def __saveCurrent(self):
        '''Save the current playlist'''
        lsinfo = self.mpdclient.lsinfo()
        playlists = []
        for somedict in lsinfo:
            if somedict.get('playlist', None) != None:
                playlists.append(somedict['playlist'])

        (name, ok) = QInputDialog.getItem(self, 'Save Playlist',
                                          'Enter or select the playlist name',
                                          playlists, 0, True)
        if ok == True:
            if name in playlists:
                self.mpdclient.send('rm', (name, ))
            self.mpdclient.send('save', (name, ))
Example #52
0
    def openDevice(self):
        
        if self.ad16 != None:
            QtGui.QMessageBox.information(self, 'Error', 'Device already open. Close first!')
        
        # create open device dialog
        dlg = QFileDialog(self)
        dlg.setAcceptMode(QFileDialog.AcceptOpen)
        dlg.setWindowTitle('Open DMAP file')
        dlg.setViewMode( QtGui.QFileDialog.Detail )
        dlg.setNameFilters( ['DMAP Files (*.dmap)', 'All Files (*)'] )
        dlg.setDefaultSuffix('dmap')
        
        # show dialog, open only if user did not cancel
        if dlg.exec_() :
            # file name must be converted into standard python string
            name = str(dlg.selectedFiles()[0])
            
            # open file and extract entries
            devNames = QStringList()
            f = open(name,'r')
            for line in f:
                x = line.split(' ',1)
                devNames.append(x[0])
            
            # create dialog to choose the right device
            devName = QInputDialog.getItem(self, 'Open device in DMAP file', 'Device:', devNames,0,False)

            # open AD16 device
            if(devName[1]) :
                myad16 = libad16.ad16()
                mtca4u.set_dmap_location(name)
                print 'DMAP file location is set to: '+mtca4u.get_dmap_location()
                try:
                    myad16.open(str(devName[0]))
                except libad16.ad16Exception as e:
                    QtGui.QMessageBox.information(self, 'Error', e.what)
                    return
                except Exception as e:
                    QtGui.QMessageBox.information(self, 'Error', 'Device cannot be opened: '+str(e))
                    return
                myad16.setTriggerMode(libad16.trigger.PERIODIC,1)
                self.ad16 = myad16
        
            # update start button
            self.startStopButton.setText("Start")
            self.startStopButton.setEnabled(True)
    def chooseLayerForRemoval(self, iface, mdl):
        if mdl.rowCount() < 2:
            if mdl.rowCount() == 1:
                return 0
            return None

        list1 = []
        for i in range(0, mdl.rowCount()):
            list1.append(str(i + 1) + " : " + mdl.item(i, 2).data(Qt.EditRole))
        testqt, ok = QInputDialog.getItem(iface.mainWindow(), "Layer selector",
                                          "Choose the Layer", list1, False)
        if ok:
            for i in range(0, mdl.rowCount()):
                if testqt == (str(i + 1) + " : " +
                              mdl.item(i, 2).data(Qt.EditRole)):
                    return i
        return None
Example #54
0
 def on_actionGotoCell_triggered(self):
     cells = [str(cid) for cid in self._data.cells]
     selected, ok = QInputDialog.getItem(self, "Goto cell",
                                         "Select the cell to go to", cells,
                                         0)
     if ok:
         cid = int(selected)
         self.ui.actionAdd_cell.setChecked(True)
         data = self._data
         if cid not in data.cells:
             return
         ls = data.cells_lifespan[cid]
         prev_pos = self._previousScene.current_data._current_index
         cur_pos = self._currentScene.current_data._current_index
         full_poly = data.cells[cid]
         poly = [pid for pid in full_poly if pid in data[prev_pos]]
         #log_debug("Cell %d on time %d: %s" % (cid, prev_pos, poly))
         if prev_pos < ls.start or prev_pos >= ls.end or not poly:
             for i in range(*ls.slice().indices(len(data))):
                 poly = [pid for pid in full_poly if pid in data[i]]
                 if poly:
                     log_debug("Found cell %d on image %d with polygon %s" %
                               (cid, i, poly))
                     new_prev_pos = i
                     break
             else:
                 log_debug("Cell %d found nowhere in range %s!!!" %
                           (cid, ls.slice()))
         else:
             new_prev_pos = prev_pos
         new_cur_pos = min(max(cur_pos + new_prev_pos - prev_pos, 0),
                           len(data))
         self.ui.previousState.setCurrentIndex(new_prev_pos)
         self.ui.currentState.setCurrentIndex(new_cur_pos)
         self._previousScene.current_cell = cid
         self._currentScene.current_cell = cid
         prev_data = self._previousScene.current_data
         poly = data.cells[cid]
         prev_poly = QPolygonF(
             [prev_data[ptid] for ptid in poly if ptid in prev_data])
         prev_bbox = prev_poly.boundingRect()
         log_debug("Previous bounding box = %dx%d+%d+%d" %
                   (prev_bbox.width(), prev_bbox.height(), prev_bbox.left(),
                    prev_bbox.top()))
         self.ui.previousData.ensureVisible(prev_bbox)
 def on_operation_commands_add_clicked(self):
     tx_packets = dict([ (packet.name, num)
                         for num, packet in self.instr_cfg.instrument.tx_packets.iteritems() ])
     
     (text, ok) = QInputDialog.getItem(\
         self,
         self.trUtf8("Add operation command"),
         self.trUtf8("Select command to send:"),
         tx_packets.keys(),
         0, False)
     
     if ok and text:
         cmd_num = tx_packets[str(text)]
         command = self.instr_cfg.add_operation_command(cmd_num)
         item = QListWidgetItem(str(cmd_num))
         item.cmd = command
         self.operation_commands_list.addItem(item)
         self.operation_commands_list.setCurrentItem(item)
Example #56
0
 def make_css(self, html):
     ' make css '
     indnt = ' ' * int(
         QInputDialog.getInteger(None, __doc__, " CSS Indentation Spaces: ",
                                 4, 0, 8, 2)[0])
     plchs = QInputDialog.getItem(None, __doc__, "CSS Placeholder values?",
                                  ['Blank Empty CSS', 'Placeholders'], 0,
                                  False)[0]
     p = True if 'Placeholders' in plchs else False
     self.soup = self.get_soup(html)
     css, previously_styled = '@charset "utf-8";', []
     css += '/*{} by {}*/{}'.format(
         datetime.now().isoformat().split('.')[0], getuser(), linesep * 2)
     previously_styled.append(css_2_ignore)
     for part in self.get_tags():
         if part not in previously_styled:
             css += '{}{}{}{}{}{}{}'.format(
                 part, '{', linesep, indnt,
                 choice(placeholders) + linesep if p is True else linesep,
                 '}', linesep)
             previously_styled.append(part)
     css += '/*{}*/{}'.format('-' * 76, linesep)
     for part in self.get_ids():
         if part not in previously_styled:
             css += '/* {} */{}'.format('_'.join(part).lower(), linesep)
             css += css_template.format(
                 '', '#', part[1], '{', linesep, indnt,
                 choice(placeholders) + linesep if p is True else linesep,
                 '}', linesep)
             previously_styled.append(part)
     css += '/*{}*/{}'.format('-' * 76, linesep)
     for part in self.get_classes():
         if part not in previously_styled:
             css += '/* {} */{}'.format('_'.join(part).lower(), linesep)
             css += css_template.format(
                 '', '.', ',.'.join(part[1].split(' ')), '{', linesep,
                 indnt,
                 choice(placeholders) + linesep if p is True else linesep,
                 '}', linesep)
             previously_styled.append(part)
     return css.strip()
Example #57
0
    def addChoice(self):
        if len(self._possible_items) == 0:
            QMessageBox.information(self, "No items", "No items available for selection!")
        else:
            item, ok = QInputDialog.getItem(self,
                                            "Select a case",
                                            "Select a case to add to the case list:",
                                            self._possible_items)

            if ok:
                item = str(item).strip()
                text = str(self._list_edit_line.text()).rstrip()

                if len(text) == 0:
                    text = item + ", "
                elif text.endswith(","):
                    text += " " + item
                else:
                    text += ", " + item

                self._list_edit_line.setText(text)