code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
#logger.debug("_forceRefreshMinMax", stack_info=True) # Set the precision from by looking how many decimals are needed to show the difference # between the minimum and maximum, given the maximum. E.g. if min = 0.04 and max = 0.07, # we would only need zero decimals behind the point as we can write the range as # [4e-2, 7e-2]. However if min = 1.04 and max = 1.07, we need 2 decimals behind the point. # So, while the range is the same size we need more decimals because we are not zoomed in # around zero. rangeMin, rangeMax = self.getTargetRange() # [[xmin, xmax], [ymin, ymax]] maxOrder = np.log10(np.abs(max(rangeMax, rangeMin))) diffOrder = np.log10(np.abs(rangeMax - rangeMin)) extraDigits = 2 # add some extra digits to make each pan/zoom action show a new value. precisionF = np.clip(abs(maxOrder - diffOrder) + extraDigits, extraDigits + 1, 25) precision = int(precisionF) if np.isfinite(precisionF) else extraDigits + 1 #logger.debug("maxOrder: {}, diffOrder: {}, precision: {}" # .format(maxOrder, diffOrder, precision)) self.rangeMinCti.precision = precision self.rangeMaxCti.precision = precision self.rangeMinCti.data, self.rangeMaxCti.data = rangeMin, rangeMax # Update values in the tree self.model.emitDataChanged(self.rangeMinCti) self.model.emitDataChanged(self.rangeMaxCti)
def _forceRefreshMinMax(self)
Refreshes the min max config values from the axes' state.
5.231836
5.257641
0.995092
if self.getRefreshBlocked(): logger.debug("refreshMinMax blocked for {}".format(self.nodeName)) return self._forceRefreshMinMax()
def refreshMinMax(self)
Refreshes the min max config values from the axes' state. Does nothing when self.getRefreshBlocked() returns True.
13.048546
7.459276
1.749305
enabled = self.autoRangeCti and self.autoRangeCti.configValue self.rangeMinCti.enabled = not enabled self.rangeMaxCti.enabled = not enabled self.model.emitDataChanged(self)
def _forceRefreshAutoRange(self)
The min and max config items will be disabled if auto range is on.
8.337289
6.291447
1.325178
# TODO: catch exceptions. How? # /argos/hdf-eos/DeepBlue-SeaWiFS-1.0_L3_20100101_v002-20110527T191319Z.h5/aerosol_optical_thickness_stddev_ocean if self.getRefreshBlocked(): logger.debug("setAutoRangeOff blocked for {}".format(self.nodeName)) return if self.autoRangeCti: self.autoRangeCti.data = False self._forceRefreshAutoRange()
def setAutoRangeOff(self)
Turns off the auto range checkbox. Calls _refreshNodeFromTarget, not _updateTargetFromNode, because setting auto range off does not require a redraw of the target.
16.70579
17.368639
0.961836
if self.getRefreshBlocked(): logger.debug("Set autorange on blocked for {}".format(self.nodeName)) return if self.autoRangeCti: self.autoRangeCti.data = True self.model.sigItemChanged.emit(self)
def setAutoRangeOn(self)
Turns on the auto range checkbox for the equivalent axes Emits the sigItemChanged signal so that the inspector may be updated. Use the setXYAxesAutoRangeOn stand-alone function if you want to set the autorange on for both axes of a viewport.
11.465776
10.218413
1.12207
if not self.autoRangeCti or not self.autoRangeCti.configValue: return (self.rangeMinCti.data, self.rangeMaxCti.data) else: rangeFunction = self._rangeFunctions[self.autoRangeMethod] return rangeFunction()
def calculateRange(self)
Calculates the range depending on the config settings.
7.082876
6.044092
1.171868
if not self.autoRangeCti or not self.autoRangeCti.configValue: padding = 0 elif self.paddingCti.configValue == -1: # specialValueText # PyQtGraph dynamic padding: between 0.02 and 0.1 dep. on the size of the ViewBox padding = None else: padding = self.paddingCti.configValue / 100 targetRange = self.calculateRange() #logger.debug("axisRange: {}, padding={}".format(targetRange, padding)) if not np.all(np.isfinite(targetRange)): logger.warn("New target range is not finite. Plot range not updated") return self.setTargetRange(targetRange, padding=padding)
def _updateTargetFromNode(self)
Applies the configuration to the target axis.
7.560494
7.172047
1.054161
self.viewBox.sigRangeChangedManually.disconnect(self.setAutoRangeOff) self.viewBox.sigRangeChanged.disconnect(self.refreshMinMax)
def _closeResources(self)
Disconnects signals. Is called by self.finalize when the cti is deleted.
8.077653
7.340184
1.10047
# viewBox.setRange doesn't accept an axis number :-( if self.axisNumber == X_AXIS: xRange, yRange = targetRange, None else: xRange, yRange = None, targetRange # Do not set disableAutoRange to True in setRange; it triggers 'one last' auto range. # This is why the viewBox' autorange must be False at construction. self.viewBox.setRange(xRange = xRange, yRange=yRange, padding=padding, update=False, disableAutoRange=False)
def setTargetRange(self, targetRange, padding=None)
Sets the range of the target.
8.103156
8.209647
0.987029
self.histLutItem.sigLevelsChanged.disconnect(self.setAutoRangeOff) self.histLutItem.sigLevelsChanged.disconnect(self.refreshMinMax)
def _closeResources(self)
Disconnects signals. Is called by self.finalize when the cti is deleted.
11.376806
9.588131
1.186551
rangeMin, rangeMax = targetRange self.histLutItem.setLevels(rangeMin, rangeMax)
def setTargetRange(self, targetRange, padding=None)
Sets the (color) range of the HistogramLUTItem The padding variable is ignored.
11.507222
5.064683
2.272052
self.viewBox.setAspectLocked(lock=self.configValue, ratio=self.aspectRatioCti.configValue)
def _updateTargetFromNode(self)
Applies the configuration to its target axis
28.787567
21.650316
1.32966
if self.axisNumber == X_AXIS: self.viewBox.invertX(self.configValue) else: self.viewBox.invertY(self.configValue)
def _updateTargetFromNode(self)
Applies the configuration to its target axis
6.599984
4.985443
1.323851
rtiInfo = self.collector.rtiInfo self.plotItem.setLabel(self.axisPosition, self.configValue.format(**rtiInfo)) self.plotItem.showLabel(self.axisPosition, self.configValue != self.NO_LABEL)
def _updateTargetFromNode(self)
Applies the configuration to the target axis it monitors. The axis label will be set to the configValue. If the configValue equals PgAxisLabelCti.NO_LABEL, the label will be hidden.
11.95157
5.988169
1.995864
logger.debug("showAxis: {}, {}".format(self.axisPosition, self.configValue)) self.plotItem.showAxis(self.axisPosition, show=self.configValue)
def _updateTargetFromNode(self)
Applies the configuration to its target axis
9.691923
7.772549
1.246943
if self.axisNumber == X_AXIS: xMode, yMode = self.configValue, None else: xMode, yMode = None, self.configValue self.plotItem.setLogMode(x=xMode, y=yMode)
def _updateTargetFromNode(self)
Applies the configuration to its target axis
5.420528
4.49743
1.20525
self.plotItem.showGrid(x=self.xGridCti.configValue, y=self.yGridCti.configValue, alpha=self.alphaCti.configValue) self.plotItem.updateGrid()
def _updateTargetFromNode(self)
Applies the configuration to the grid of the plot item.
7.232065
4.536005
1.594369
antialias = self.antiAliasCti.configValue color = self.penColor if self.lineCti.configValue: pen = QtGui.QPen() pen.setCosmetic(True) pen.setColor(color) pen.setWidthF(self.lineWidthCti.configValue) pen.setStyle(self.lineStyleCti.configValue) shadowCti = self.lineCti.findByNodePath('shadow') shadowPen = shadowCti.createPen(altStyle=pen.style(), altWidth=2.0 * pen.widthF()) else: pen = None shadowPen = None drawSymbols = self.symbolCti.configValue symbolShape = self.symbolShapeCti.configValue if drawSymbols else None symbolSize = self.symbolSizeCti.configValue if drawSymbols else 0.0 symbolPen = None # otherwise the symbols will also have dotted/solid line. symbolBrush = QtGui.QBrush(color) if drawSymbols else None plotDataItem = pg.PlotDataItem(antialias=antialias, pen=pen, shadowPen=shadowPen, symbol=symbolShape, symbolSize=symbolSize, symbolPen=symbolPen, symbolBrush=symbolBrush) return plotDataItem
def createPlotDataItem(self)
Creates a PyQtGraph PlotDataItem from the config values
3.623291
3.489677
1.038288
table = self.table table.setUpdatesEnabled(False) try: table.clearContents() verticalHeader = table.verticalHeader() verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.Fixed) if currentRti is None: return # Each column in the repo tree corresponds to a row in this detail pane. repoModel = self._repoTreeView.model() propNames = RepoTreeModel.HEADERS table.setRowCount(len(propNames)) for row, propName in enumerate(propNames): nameItem = QtWidgets.QTableWidgetItem(propName) nameItem.setToolTip(propName) table.setItem(row, self.COL_PROP_NAME, nameItem) propValue = repoModel.itemData(currentRti, row) propItem = QtWidgets.QTableWidgetItem(propValue) propItem.setToolTip(propValue) table.setItem(row, self.COL_VALUE, propItem) table.resizeRowToContents(row) verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) finally: table.setUpdatesEnabled(True)
def _drawContents(self, currentRti=None)
Draws the attributes of the currentRTI
2.986799
3.062311
0.975342
if role == Qt.DisplayRole: if column == self.COL_NODE_NAME: return treeItem.nodeName elif column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_SHAPE: if treeItem.isSliceable: return " x ".join(str(elem) for elem in treeItem.arrayShape) else: return "" elif column == self.COL_IS_OPEN: # Only show for RTIs that actually open resources. # TODO: this must be clearer. Use CanFetchChildren? Set is Open to None by default? if treeItem.hasChildren(): return str(treeItem.isOpen) else: return "" elif column == self.COL_ELEM_TYPE: return treeItem.elementTypeName elif column == self.COL_FILE_NAME: return treeItem.fileName if hasattr(treeItem, 'fileName') else '' elif column == self.COL_UNIT: return treeItem.unit elif column == self.COL_MISSING_DATA: return to_string(treeItem.missingDataValue, noneFormat='') # empty str for Nones elif column == self.COL_RTI_TYPE: return type_name(treeItem) elif column == self.COL_EXCEPTION: return str(treeItem.exception) if treeItem.exception else '' else: raise ValueError("Invalid column: {}".format(column)) elif role == Qt.ToolTipRole: if treeItem.exception: return str(treeItem.exception) if column == self.COL_NODE_NAME: return treeItem.nodePath # Also path when hovering over the name elif column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_SHAPE: if treeItem.isSliceable: return " x ".join(str(elem) for elem in treeItem.arrayShape) else: return "" elif column == self.COL_UNIT: return treeItem.unit elif column == self.COL_MISSING_DATA: return to_string(treeItem.missingDataValue, noneFormat='') # empty str for Nones elif column == self.COL_RTI_TYPE: return type_name(treeItem) elif column == self.COL_ELEM_TYPE: return treeItem.elementTypeName elif column == self.COL_FILE_NAME: return treeItem.fileName if hasattr(treeItem, 'fileName') else '' else: return None else: return super(RepoTreeModel, self).itemData(treeItem, column, role=role)
def itemData(self, treeItem, column, role=Qt.DisplayRole)
Returns the data stored under the given role for the item. O
2.612191
2.62751
0.99417
parentItem = self.getItem(parentIndex) if not parentItem: return False return parentItem.canFetchChildren()
def canFetchMore(self, parentIndex)
Returns true if there is more data available for parent; otherwise returns false.
3.7757
3.779502
0.998994
return if not parentItem.canFetchChildren(): return # TODO: implement InsertItems to optimize? for childItem in parentItem.fetchChildren(): self.insertItem(childItem, parentIndex=parentIndex) # Check that Rti implementation correctly sets canFetchChildren assert not parentItem.canFetchChildren(), \ "not all children fetched: {}".format(parentItem)
def fetchMore(self, parentIndex): # TODO: Make LazyLoadRepoTreeModel? parentItem = self.getItem(parentIndex) if not parentItem
Fetches any available data for the items with the parent specified by the parent index.
9.215556
8.625617
1.068394
parentIndex = childIndex.parent() if not parentIndex.isValid(): return childIndex else: parentItem = self.getItem(parentIndex) childItem = self.getItem(childIndex) if parentItem.fileName == childItem.fileName: return self.findFileRtiIndex(parentIndex) else: return childIndex
def findFileRtiIndex(self, childIndex)
Traverses the tree upwards from the item at childIndex until the tree item is found that represents the file the item at childIndex
2.300169
2.395304
0.960283
fileRtiParentIndex = itemIndex.parent() fileRti = self.getItem(itemIndex) position = fileRti.childNumber() fileName = fileRti.fileName if rtiClass is None: rtiClass = type(fileRti) # Delete old RTI and Insert a new one instead. self.deleteItemAtIndex(itemIndex) # this will close the items resources. return self.loadFile(fileName, rtiClass, position=position, parentIndex=fileRtiParentIndex)
def reloadFileAtIndex(self, itemIndex, rtiClass=None)
Reloads the item at the index by removing the repo tree item and inserting a new one. The new item will have by of type rtiClass. If rtiClass is None (the default), the new rtiClass will be the same as the old one.
5.37426
5.54349
0.969472
logger.info("Loading data from: {!r}".format(fileName)) if rtiClass is None: repoTreeItem = createRtiFromFileName(fileName) else: repoTreeItem = rtiClass.createFromFileName(fileName) assert repoTreeItem.parentItem is None, "repoTreeItem {!r}".format(repoTreeItem) return self.insertItem(repoTreeItem, position=position, parentIndex=parentIndex)
def loadFile(self, fileName, rtiClass=None, position=None, parentIndex=QtCore.QModelIndex())
Loads a file in the repository as a repo tree item of class rtiClass. Autodetects the RTI type if rtiClass is None. If position is None the child will be appended as the last child of the parent. Returns the index of the newly inserted RTI
4.675847
4.240471
1.102672
self.model().sigItemChanged.disconnect(self.repoTreeItemChanged) selectionModel = self.selectionModel() # need to store reference to prevent crash in PySide selectionModel.currentChanged.disconnect(self.currentItemChanged)
def finalize(self)
Disconnects signals and frees resources
10.452912
9.369182
1.11567
menu = QtWidgets.QMenu(self) for action in self.actions(): menu.addAction(action) openAsMenu = self.createOpenAsMenu(parent=menu) menu.insertMenu(self.closeItemAction, openAsMenu) menu.exec_(event.globalPos())
def contextMenuEvent(self, event)
Creates and executes the context menu for the tree view
4.574269
4.931312
0.927597
openAsMenu = QtWidgets.QMenu(parent=parent) openAsMenu.setTitle("Open Item As") registry = globalRtiRegistry() for rtiRegItem in registry.items: #rtiRegItem.tryImportClass() def createTrigger(): _rtiRegItem = rtiRegItem # keep reference in closure return lambda: self.reloadFileOfCurrentItem(_rtiRegItem) action = QtWidgets.QAction("{}".format(rtiRegItem.name), self, enabled=bool(rtiRegItem.successfullyImported is not False), triggered=createTrigger()) openAsMenu.addAction(action) return openAsMenu
def createOpenAsMenu(self, parent=None)
Creates the submenu for the Open As choice
6.884657
6.969129
0.987879
logger.debug("openCurrentItem") _currentItem, currentIndex = self.getCurrentItem() if not currentIndex.isValid(): return # Expanding the node will call indirectly call RepoTreeModel.fetchMore which will call # BaseRti.fetchChildren, which will call BaseRti.open and thus open the current RTI. # BaseRti.open will emit the self.model.sigItemChanged signal, which is connected to # RepoTreeView.onItemChanged. self.expand(currentIndex)
def openCurrentItem(self)
Opens the current item in the repository.
12.628337
12.089689
1.044554
logger.debug("closeCurrentItem") currentItem, currentIndex = self.getCurrentItem() if not currentIndex.isValid(): return # First we remove all the children, this will close them as well. self.model().removeAllChildrenAtIndex(currentIndex) # Close the current item. BaseRti.close will emit the self.model.sigItemChanged signal, # which is connected to RepoTreeView.onItemChanged. currentItem.close() self.dataChanged(currentIndex, currentIndex) self.collapse(currentIndex)
def closeCurrentItem(self)
Closes the current item in the repository. All its children will be unfetched and closed.
9.638201
8.470621
1.137839
logger.debug("removeCurrentFile") currentIndex = self.getRowCurrentIndex() if not currentIndex.isValid(): return self.model().deleteItemAtIndex(currentIndex)
def removeCurrentItem(self)
Removes the current item from the repository tree.
12.072735
10.830285
1.11472
logger.debug("reloadFileOfCurrentItem, rtiClass={}".format(rtiRegItem)) currentIndex = self.getRowCurrentIndex() if not currentIndex.isValid(): return currentItem, _ = self.getCurrentItem() oldPath = currentItem.nodePath fileRtiIndex = self.model().findFileRtiIndex(currentIndex) isExpanded = self.isExpanded(fileRtiIndex) if rtiRegItem is None: rtiClass = None else: rtiRegItem.tryImportClass() rtiClass = rtiRegItem.cls newRtiIndex = self.model().reloadFileAtIndex(fileRtiIndex, rtiClass=rtiClass) try: # Expand and select the name with the old path _lastItem, lastIndex = self.expandPath(oldPath) self.setCurrentIndex(lastIndex) return lastIndex except Exception as ex: # The old path may not exist anymore. In that case select file RTI logger.warning("Unable to select {!r} beause of: {}".format(oldPath, ex)) self.setExpanded(newRtiIndex, isExpanded) self.setCurrentIndex(newRtiIndex) return newRtiIndex
def reloadFileOfCurrentItem(self, rtiRegItem=None)
Finds the repo tree item that holds the file of the current item and reloads it. Reloading is done by removing the repo tree item and inserting a new one. The new item will have by of type rtiRegItem.cls. If rtiRegItem is None (the default), the new rtiClass will be the same as the old one. The rtiRegItem.cls will be imported. If this fails the old class will be used, and a warning will be logged.
4.701405
4.313462
1.089938
logger.debug("onItemChanged: {}".format(rti)) currentItem, _currentIndex = self.getCurrentItem() if rti == currentItem: self.currentRepoTreeItemChanged() else: logger.debug("Ignoring changed item as is not the current item: {}".format(rti))
def repoTreeItemChanged(self, rti)
Called when repo tree item has changed (the item itself, not a new selection) If the item is the currently selected item, the the collector (inspector) and metadata widgets are updated.
5.806088
5.675493
1.02301
# When the model is empty the current index may be invalid and the currentItem may be None. currentItem, currentIndex = self.getCurrentItem() hasCurrent = currentIndex.isValid() assert hasCurrent == (currentItem is not None), \ "If current idex is valid, currentIndex may not be None" # sanity check # Set the item in the collector, will will subsequently update the inspector. if hasCurrent: logger.info("Adding rti to collector: {}".format(currentItem.nodePath)) self.collector.setRti(currentItem) #if rti.asArray is not None: # TODO: maybe later, first test how robust it is now # self.collector.setRti(rti) # Update context menus in the repo tree self.currentItemActionGroup.setEnabled(hasCurrent) isTopLevel = hasCurrent and self.model().isTopLevelIndex(currentIndex) self.topLevelItemActionGroup.setEnabled(isTopLevel) self.openItemAction.setEnabled(currentItem is not None and currentItem.hasChildren() and not currentItem.isOpen) self.closeItemAction.setEnabled(currentItem is not None and currentItem.hasChildren() and currentItem.isOpen) # Emit sigRepoItemChanged signal so that, for example, details panes can update. logger.debug("Emitting sigRepoItemChanged: {}".format(currentItem)) self.sigRepoItemChanged.emit(currentItem)
def currentRepoTreeItemChanged(self)
Called to update the GUI when a repo tree item has changed or a new one was selected.
6.741893
6.561834
1.02744
# PyQtGraph recommends raster graphics system for OS-X. if 'darwin' in sys.platform: graphicsSystem = "raster" # raster, native or opengl os.environ.setdefault('QT_GRAPHICSSYSTEM', graphicsSystem) logger.info("Setting QT_GRAPHICSSYSTEM to: {}".format(graphicsSystem)) app = QtWidgets.QApplication(sys.argv) initArgosApplicationSettings(app) return app
def initQApplication()
Initializes the QtWidgets.QApplication instance. Creates one if it doesn't exist. Sets Argos specific attributes, such as the OrganizationName, so that the application persistent settings are read/written to the correct settings file/winreg. It is therefore important to call this function at startup. The ArgosApplication constructor does this. Returns the application.
7.645875
7.767139
0.984388
def initArgosApplicationSettings(app): # TODO: this is Argos specific. Move somewhere else. assert app, \ "app undefined. Call QtWidgets.QApplication.instance() or QtCor.QApplication.instance() first." logger.debug("Setting Argos QApplication settings.") app.setApplicationName(info.REPO_NAME) app.setApplicationVersion(info.VERSION) app.setOrganizationName(info.ORGANIZATION_NAME) app.setOrganizationDomain(info.ORGANIZATION_DOMAIN)
Sets Argos specific attributes, such as the OrganizationName, so that the application persistent settings are read/written to the correct settings file/winreg. It is therefore important to call this function at startup. The ArgosApplication constructor does this.
null
null
null
logger.debug("Removing settings group: {}".format(groupName)) settings = QtCore.QSettings() if settings is None else settings settings.remove(groupName)
def removeSettingsGroup(groupName, settings=None)
Removes a group from the persistent settings
3.767993
4.15555
0.906738
def _containsPath(path, settings): "Aux function for containsSettingsGroup. Does the actual recursive search." if len(path) == 0: return True else: head = path[0] tail = path[1:] if head not in settings.childGroups(): return False else: settings.beginGroup(head) try: return _containsPath(tail, settings) finally: settings.endGroup() # Body starts here path = os.path.split(groupName) logger.debug("Looking for path: {}".format(path)) settings = QtCore.QSettings() if settings is None else settings return _containsPath(path, settings)
def containsSettingsGroup(groupName, settings=None)
Returns True if the settings contain a group with the name groupName. Works recursively when the groupName is a slash separated path.
3.804577
3.687496
1.031751
children=obj.children() if children==None: return for child in children: try: childName = child.objectName() except AttributeError: childName = "<no-name>" #print ("{}{:10s}: {}".format(indent, childName, child.__class__)) print ("{}{!r}: {}".format(indent, childName, child.__class__)) printChildren(child, indent + " ")
def printChildren(obj, indent="")
Recursively prints the children of a QObject. Useful for debugging.
3.87956
3.552171
1.092166
print ("Application's widgets {}".format(('of type: ' + str(ofType)) if ofType else '')) for widget in qApplication.allWidgets(): if ofType is None or isinstance(widget, ofType): print (" {!r}".format(widget))
def printAllWidgets(qApplication, ofType=None)
Prints list of all widgets to stdout (for debugging)
3.925585
3.800044
1.033037
opt = QtWidgets.QStyleOption() opt.initFrom(widget) style = widget.style() return style.subElementRect(QtWidgets.QStyle.SE_ViewItemCheckIndicator, opt, widget)
def widgetSubCheckBoxRect(widget, option)
Returns the rectangle of a check box drawn as a sub element of widget
3.301192
2.926826
1.127909
result = super(ResizeDetailsMessageBox, self).resizeEvent(event) details_box = self.findChild(QtWidgets.QTextEdit) if details_box is not None: #details_box.setFixedSize(details_box.sizeHint()) details_box.setFixedSize(QtCore.QSize(self.detailsBoxWidth, self.detailBoxHeight)) return result
def resizeEvent(self, event)
Resizes the details box if present (i.e. when 'Show Details' button was clicked)
3.586715
2.960188
1.211651
#logger.debug("_drawContents: {}".format(currentRti)) table = self.table table.setUpdatesEnabled(False) try: table.clearContents() verticalHeader = table.verticalHeader() verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.Fixed) attributes = currentRti.attributes if currentRti is not None else {} table.setRowCount(len(attributes)) for row, (attrName, attrValue) in enumerate(sorted(attributes.items())): attrStr = to_string(attrValue, decode_bytes='utf-8') try: type_str = type_name(attrValue) except Exception as ex: logger.exception(ex) type_str = "<???>" nameItem = QtWidgets.QTableWidgetItem(attrName) nameItem.setToolTip(attrName) table.setItem(row, self.COL_ATTR_NAME, nameItem) valItem = QtWidgets.QTableWidgetItem(attrStr) valItem.setToolTip(attrStr) table.setItem(row, self.COL_VALUE, valItem) table.setItem(row, self.COL_ELEM_TYPE, QtWidgets.QTableWidgetItem(type_str)) table.resizeRowToContents(row) verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) finally: table.setUpdatesEnabled(True)
def _drawContents(self, currentRti=None)
Draws the attributes of the currentRTI
2.555225
2.530791
1.009655
if reason not in cls.__VALID_REASONS: raise ValueError("reason must be one of {}, got {}".format(cls.__VALID_REASONS, reason))
def checkValid(cls, reason)
Raises ValueError if the reason is not one of the valid enumerations
3.386388
2.892835
1.170612
self.setCurrentIndex(self.CONTENTS_PAGE_IDX) wasBlocked = self.config.model.setRefreshBlocked(True) try: self._drawContents(reason=reason, initiator=initiator) logger.debug("_drawContents finished successfully") # Update the config tree from the (possibly) new state of the PgLinePlot1d inspector, # e.g. the axis range may have changed while drawing. # self.config.updateTarget() # TODO: enable this here (instead of doing it in the inspector._drawContents when needed)? finally: self.config.model.setRefreshBlocked(wasBlocked) # Call refreshFromTarget in case the newly applied configuration resulted in a change # of the state of the configuration's target's (i.e. the inspector state) logger.debug("_drawContents finished successfully, calling refreshFromTarget...") self.config.refreshFromTarget() logger.debug("refreshFromTarget finished successfully") except InvalidDataError as ex: logger.info("Unable to draw the inspector contents: {}".format(ex)) except Exception as ex: if DEBUGGING: # TODO: enable raise logger.error("Error while drawing the inspector: {} ----".format(ex)) logger.exception(ex) self._clearContents() self.setCurrentIndex(self.ERROR_PAGE_IDX) self._showError(msg=str(ex), title=type_name(ex)) else: logger.debug("---- updateContents finished successfully")
def updateContents(self, reason=None, initiator=None): # TODO: reason mandatory? UpdateReason.checkValid(reason) logger.debug("---- Inspector updateContents, reason: {}, initiator: {}" .format(reason, initiator)) logger.debug("Inspector: {}".format(self)) logger.debug("RTI: {}".format(self.collector.rti)) try
Tries to draw the widget contents with the updated RTI. Shows the error page in case an exception is raised while drawing the contents. Descendants should override _drawContents, not updateContents. During the call of _drawContents, the updating of the configuration tree is blocked to avoid circular effects. After that, a call to self.config.refreshFromTarget() is made to refresh the configuration tree with possible new values from the inspector (the inspector is the configuration's target, hence the name). The reason parameter is a string (one of the UpdateReason values) that indicates why the inspector contents whas updated. This can, for instance, be used to optimize drawing the inspector contents. Note that the reason may be undefined (None). The initiator may contain the object that initiated the updated. The type depends on the reason. At the moment the initiator is only implemented for the "config changed" reason. In this case the initiator will be the Config Tree Item (CTI that has changed).
7.284867
6.03424
1.207255
self.errorWidget.setError(msg=msg, title=title)
def _showError(self, msg="", title="Error")
Shows an error message.
8.531632
6.936368
1.229986
idx = int(data) if idx < 0: idx += len(self._displayValues) assert 0 <= idx < len(self._displayValues), \ "Index should be >= 0 and < {}. Got {}".format(len(self._displayValues), idx) return idx
def _enforceDataType(self, data)
Converts to int so that this CTI always stores that type. The data be set to a negative value, e.g. use -1 to select the last item by default. However, it will be converted to a positive by this method.
3.285787
3.242886
1.013229
dct = super(ChoiceCti, self)._nodeGetNonDefaultsDict() if self._configValues != self._defaultConfigValues: dct['choices'] = self._configValues return dct
def _nodeGetNonDefaultsDict(self)
Retrieves this nodes` values as a dictionary to be used for persistence. Non-recursive auxiliary function for getNonDefaultsDict
7.290939
8.232029
0.88568
if 'choices' in dct: self._configValues = list(dct['choices']) self._displayValues = list(dct['choices']) super(ChoiceCti, self)._nodeSetValuesFromDict(dct)
def _nodeSetValuesFromDict(self, dct)
Sets values from a dictionary in the current node. Non-recursive auxiliary function for setValuesFromDict
5.366364
5.949414
0.901999
return ChoiceCtiEditor(self, delegate, parent=parent)
def createEditor(self, delegate, parent, option)
Creates a ChoiceCtiEditor. For the parameters see the AbstractCti constructor documentation.
46.355587
5.351318
8.662462
self._configValues.insert(pos, configValue) self._displayValues.insert(pos, displayValue if displayValue is not None else configValue)
def insertValue(self, pos, configValue, displayValue=None)
Will insert the configValue in the configValues and the displayValue in the displayValues list. If displayValue is None, the configValue is set in the displayValues as well
2.483318
2.460132
1.009424
self._comboboxListView.removeEventFilter(self) self.comboBox.model().rowsInserted.disconnect(self.comboBoxRowsInserted) self.comboBox.activated.disconnect(self.comboBoxActivated) super(ChoiceCtiEditor, self).finalize()
def finalize(self)
Is called when the editor is closed. Disconnect signals.
8.002201
6.158474
1.299381
assert start == end, "Bug, please report: more than one row inserted" configValue = self.comboBox.itemText(start) logger.debug("Inserting {!r} at position {} in {}" .format(configValue, start, self.cti.nodePath)) self.cti.insertValue(start, configValue)
def comboBoxRowsInserted(self, _parent, start, end)
Called when the user has entered a new value in the combobox. Puts the combobox values back into the cti.
7.259785
5.835496
1.244073
if self.comboBox.isEditable() and event.type() == QtCore.QEvent.KeyPress: key = event.key() if key in (Qt.Key_Delete, Qt.Key_Backspace): if (watchedObject == self._comboboxListView or (watchedObject == self.comboBox and event.modifiers() == Qt.ControlModifier)): index = self._comboboxListView.currentIndex() if index.isValid(): row = index.row() logger.debug("Removing item {} from the combobox: {}" .format(row, self._comboboxListView.model().data(index))) self.cti.removeValueByIndex(row) self.comboBox.removeItem(row) return True # Calling parent event filter, which may filter out other events. return super(ChoiceCtiEditor, self).eventFilter(watchedObject, event)
def eventFilter(self, watchedObject, event)
Deletes an item from an editable combobox when the delete or backspace key is pressed in the list of items, or when ctrl-delete or ctrl-back space is pressed in the line-edit. When the combobox is not editable the filter does nothing.
3.578365
3.354504
1.066734
if topLeftIndex.isValid() and bottomRightIndex.isValid(): topRow = topLeftIndex.row() bottomRow = bottomRightIndex.row() for row in range(topRow, bottomRow + 1): index = topLeftIndex.sibling(row, 0) childItem = self.getItem(index) logger.debug("Data changed in: {}".format(childItem.nodePath))
def debug(self, topLeftIndex, bottomRightIndex)
Temporary debug to test the dataChanged signal. TODO: remove.
3.002276
2.61888
1.146397
if not index.isValid(): return 0 cti = self.getItem(index) result = Qt.ItemIsSelectable if cti.enabled: result |= Qt.ItemIsEnabled if index.column() == self.COL_VALUE: result |= cti.valueColumnItemFlags return result
def flags(self, index)
Returns the item flags for the given index.
5.580177
4.846071
1.151485
groupCti = GroupCti(groupName) return self._invisibleRootItem.insertChild(groupCti, position=position)
def insertTopLevelGroup(self, groupName, position=None)
Inserts a top level group tree item. Used to group all config nodes of (for instance) the current inspector, Returns the newly created CTI
13.041835
9.789854
1.332179
if role == Qt.DisplayRole: if column == self.COL_NODE_NAME: return treeItem.nodeName elif column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_VALUE: return treeItem.displayValue elif column == self.COL_DEF_VALUE: return treeItem.displayDefaultValue elif column == self.COL_CTI_TYPE: return type_name(treeItem) elif column == self.COL_DEBUG: return treeItem.debugInfo else: raise ValueError("Invalid column: {}".format(column)) elif role == Qt.EditRole: if column == self.COL_VALUE: return treeItem.data else: raise ValueError("Invalid column: {}".format(column)) elif role == Qt.ToolTipRole: if column == self.COL_NODE_NAME or column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_VALUE: # Give Access to exact values. In particular in scientific-notation spin boxes return repr(treeItem.configValue) elif column == self.COL_DEF_VALUE: return treeItem.displayDefaultValue elif column == self.COL_CTI_TYPE: return type_name(treeItem) elif column == self.COL_DEBUG: return treeItem.debugInfo else: return None elif role == Qt.CheckStateRole: if column != self.COL_VALUE: # The CheckStateRole is called for each cell so return None here. return None else: return treeItem.checkState else: return super(ConfigTreeModel, self).itemData(treeItem, column, role=role)
def itemData(self, treeItem, column, role=Qt.DisplayRole)
Returns the data stored under the given role for the item.
2.481845
2.477275
1.001845
if role == Qt.CheckStateRole: if column != self.COL_VALUE: return False else: logger.debug("Setting check state (col={}): {!r}".format(column, value)) treeItem.checkState = value return True elif role == Qt.EditRole: if column != self.COL_VALUE: return False else: logger.debug("Set Edit value (col={}): {!r}".format(column, value)) treeItem.data = value return True else: raise ValueError("Unexpected edit role: {}".format(role))
def setItemData(self, treeItem, column, value, role=Qt.EditRole)
Sets the role data for the item at index to value.
2.731139
2.739286
0.997026
if index.isValid(): item = self.getItem(index) item.expanded = expanded
def setExpanded(self, index, expanded)
Expands the model item specified by the index. Overridden from QTreeView to make it persistent (between inspector changes).
4.290967
4.07825
1.052159
return (QtCore.QModelIndex(), QtCore.QModelIndex()) if not treeItem.parentItem: # TODO: only necessary because of childNumber? return (QtCore.QModelIndex(), QtCore.QModelIndex()) # Is there a bug in Qt in QStandardItemModel::indexFromItem? # It passes the parent in createIndex. TODO: investigate row = treeItem.childNumber() return (self.createIndex(row, 0, treeItem), self.createIndex(row, self.columnCount() - 1, treeItem))
def indexTupleFromItem(self, treeItem): # TODO: move to BaseTreeItem? if not treeItem
Return (first column model index, last column model index) tuple for a configTreeItem
5.081475
4.894689
1.038161
def emitDataChanged(self, treeItem): # TODO: move to BaseTreeItem? indexLeft, indexRight = self.indexTupleFromItem(treeItem) checkItem = self.getItem(indexLeft) assert checkItem is treeItem, "{} != {}".format(checkItem, treeItem) # TODO: remove self.dataChanged.emit(indexLeft, indexRight)
Emits the data changed for the model indices (all columns) for this treeItem
null
null
null
wasBlocked = self._refreshBlocked logger.debug("Setting refreshBlocked from {} to {}".format(wasBlocked, blocked)) self._refreshBlocked = blocked return wasBlocked
def setRefreshBlocked(self, blocked)
Set to True to indicate that set the configuration should not be updated. This setting is part of the model so that is shared by all CTIs. Returns the old value.
3.870742
4.053964
0.954804
arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE) check_is_an_array(arr) self._array = arr
def _openResources(self)
Uses numpy.load to open the underlying file
9.487329
6.954118
1.364275
dct = np.load(self._fileName, allow_pickle=ALLOW_PICKLE) check_class(dct, NpzFile) self._dictionary = dct
def _openResources(self)
Uses numpy.load to open the underlying file
11.790665
8.218245
1.434694
# Descendants should convert the data to the desired type here self._data = self._enforceDataType(data) #logger.debug("BoolCti.setData: {} for {}".format(data, self)) enabled = self.enabled self.enableBranch(enabled and self.data != self.childrenDisabledValue) self.enabled = enabled
def data(self, data)
Sets the data of this item. Does type conversion to ensure data is always of the correct type.
17.608688
16.306463
1.079859
childItem = super(BoolCti, self).insertChild(childItem, position=None) enableChildren = self.enabled and self.data != self.childrenDisabledValue #logger.debug("BoolCti.insertChild: {} enableChildren={}".format(childItem, enableChildren)) childItem.enableBranch(enableChildren) childItem.enabled = enableChildren return childItem
def insertChild(self, childItem, position=None)
Inserts a child item to the current item. Overridden from BaseTreeItem.
6.48722
6.818891
0.95136
if self.data is True: return Qt.Checked elif self.data is False: return Qt.Unchecked else: raise ValueError("Unexpected data: {!r}".format(self.data))
def checkState(self)
Returns Qt.Checked or Qt.Unchecked.
3.980491
2.906197
1.369656
if checkState == Qt.Checked: logger.debug("BoolCti.checkState setting to True") self.data = True elif checkState == Qt.Unchecked: logger.debug("BoolCti.checkState setting to False") self.data = False else: raise ValueError("Unexpected check state: {!r}".format(checkState))
def checkState(self, checkState)
Sets the data to given a Qt.CheckState (Qt.Checked or Qt.Unchecked).
3.874463
3.213891
1.205536
self.enabled = enabled # Disabled children and further descendants enabled = enabled and self.data != self.childrenDisabledValue for child in self.childItems: child.enableBranch(enabled)
def enableBranch(self, enabled)
Sets the enabled member to True or False for a node and all it's children
10.77495
10.805628
0.997161
#commonData = self.childItems[0].data if self.childItems else Qt.PartiallyChecked commonData = None for child in self.childItems: if isinstance(child, BoolCti): if commonData is not None and child.data != commonData: return Qt.PartiallyChecked commonData = child.data if commonData is True: return Qt.Checked elif commonData is False: return Qt.Unchecked else: raise AssertionError("Please report this bug: commonData: {!r}".format(commonData))
def checkState(self)
Returns Qt.Checked or Qt.Unchecked if all children are checked or unchecked, else returns Qt.PartiallyChecked
4.483243
3.558867
1.259739
logger.debug("checkState setter: {}".format(checkState)) if checkState == Qt.Checked: commonData = True elif checkState == Qt.Unchecked: commonData = False elif checkState == Qt.PartiallyChecked: commonData = None # This never occurs, see remarks above in the classes' docstring assert False, "This never happens. Please report if it does." else: raise ValueError("Unexpected check state: {!r}".format(checkState)) for child in self.childItems: if isinstance(child, BoolCti): child.data = commonData
def checkState(self, checkState)
Sets the data to given a Qt.CheckState (Qt.Checked or Qt.Unchecked).
5.823482
5.115545
1.138389
# See https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods #logger.debug("Trying to create object of class: {!r}".format(cls)) basename = os.path.basename(os.path.realpath(fileName)) # strips trailing slashes return cls(nodeName=basename, fileName=fileName)
def createFromFileName(cls, fileName)
Creates a BaseRti (or descendant), given a file name.
7.025884
7.107703
0.988489
self.clearException() try: if self._isOpen: logger.warn("Resources already open. Closing them first before opening.") self._closeResources() self._isOpen = False assert not self._isOpen, "Sanity check failed: _isOpen should be false" logger.debug("Opening {}".format(self)) self._openResources() self._isOpen = True if self.model: self.model.sigItemChanged.emit(self) else: logger.warning("Model not set yet: {}".format(self)) except Exception as ex: if DEBUGGING: raise logger.exception("Error during tree item open: {}".format(ex)) self.setException(ex)
def open(self)
Opens underlying resources and sets isOpen flag. It calls _openResources. Descendants should usually override the latter function instead of this one.
5.1268
4.341455
1.180895
self.clearException() try: if self._isOpen: logger.debug("Closing {}".format(self)) self._closeResources() self._isOpen = False else: logger.debug("Resources already closed (ignored): {}".format(self)) if self.model: self.model.sigItemChanged.emit(self) else: logger.warning("Model not set yet: {}".format(self)) except Exception as ex: if DEBUGGING: raise logger.error("Error during tree item close: {}".format(ex)) self.setException(ex)
def close(self)
Closes underlying resources and un-sets the isOpen flag. Any exception that occurs is caught and put in the exception property. This method calls _closeResources, which does the actual resource cleanup. Descendants should typically override the latter instead of this one.
4.974644
3.966302
1.254227
if self._fileName and not os.path.exists(self._fileName): msg = "File not found: {}".format(self._fileName) logger.error(msg) self.setException(IOError(msg)) return False else: return True
def _checkFileExists(self)
Verifies that the underlying file exists and sets the _exception attribute if not Returns True if the file exists. If self._fileName is None, nothing is checked and True is returned.
3.03549
2.42612
1.25117
assert self._canFetchChildren, "canFetchChildren must be True" try: self.clearException() if not self.isOpen: self.open() # Will set self._exception in case of failure if not self.isOpen: logger.warn("Opening item failed during fetch (aborted)") return [] # no need to continue if opening failed. childItems = [] try: childItems = self._fetchAllChildren() assert is_a_sequence(childItems), "ChildItems must be a sequence" except Exception as ex: # This can happen, for example, when a NCDF/HDF5 file contains data types that # are not supported by the Python library that is used to read them. if DEBUGGING: raise logger.error("Unable fetch tree item children: {}".format(ex)) self.setException(ex) return childItems finally: self._canFetchChildren = False
def fetchChildren(self)
Creates child items and returns them. Opens the tree item first if it's not yet open.
6.999449
6.7392
1.038617
rtiIconFactory = RtiIconFactory.singleton() if self._exception: return rtiIconFactory.getIcon(rtiIconFactory.ERROR, isOpen=False, color=rtiIconFactory.COLOR_ERROR) else: return rtiIconFactory.getIcon(self.iconGlyph, isOpen=not self.canFetchChildren(), color=self.iconColor)
def decoration(self)
The displayed icon. Shows open icon when node was visited (children are fetched). This allows users for instance to collapse a directory node but still see that it was visited, which may be useful if there is a huge list of directories.
7.539044
6.690547
1.12682
table = self.table table.setUpdatesEnabled(False) sizeAlignment = Qt.AlignRight | Qt.AlignVCenter try: table.clearContents() verticalHeader = table.verticalHeader() verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.Fixed) if currentRti is None or not currentRti.isSliceable: return nDims = currentRti.nDims dimNames = currentRti.dimensionNames dimGroups = currentRti.dimensionGroupPaths dimSizes = currentRti.arrayShape # Sanity check assert len(dimNames) == nDims, "dimNames size {} != {}".format(len(dimNames), nDims) assert len(dimGroups) == nDims, "dimGroups size {} != {}".format(len(dimGroups), nDims) assert len(dimSizes) == nDims, "dimSizes size {} != {}".format(len(dimSizes), nDims) table.setRowCount(nDims) for row, (dimName, dimSize, dimGroup) in enumerate(zip(dimNames, dimSizes, dimGroups)): table.setItem(row, self.COL_NAME, QtWidgets.QTableWidgetItem(dimName)) table.setItem(row, self.COL_SIZE, QtWidgets.QTableWidgetItem(str(dimSize))) table.item(row, self.COL_SIZE).setTextAlignment(sizeAlignment) table.setItem(row, self.COL_GROUP, QtWidgets.QTableWidgetItem(str(dimGroup))) table.resizeRowToContents(row) verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) finally: table.setUpdatesEnabled(True)
def _drawContents(self, currentRti=None)
Draws the attributes of the currentRTI
2.178928
2.192544
0.99379
def format_float(value): # not used string = "{:g}".format(value).replace("e+", "e") string = re.sub("e(-?)0*(\d+)", r"e\1\2", string) return string
Modified form of the 'g' format specifier.
null
null
null
self._smallStepsPerLargeStep = smallStepsPerLargeStep self._smallStepFactor = np.power(self.largeStepFactor, 1.0 / smallStepsPerLargeStep)
def smallStepsPerLargeStep(self, smallStepsPerLargeStep)
Sets the number of small steps that go in a large one.
3.240075
3.053283
1.061177
oldValue = self.value() if oldValue == 0: newValue = steps elif steps == 1: newValue = self.value() * self.smallStepFactor elif steps == -1: newValue = self.value() / self.smallStepFactor elif steps == 10: newValue = self.value() * self.largeStepFactor elif steps == -10: newValue = self.value() / self.largeStepFactor else: raise ValueError("Invalid step size: {!r}, value={}".format(steps, oldValue)) newValue = float(newValue) if newValue < self.minimum(): newValue = self.minimum() if newValue > self.maximum(): newValue = self.maximum() #logger.debug("stepBy {}: {} -> {}".format(steps, oldValue, newValue)) try: self.setValue(newValue) except Exception: # TODO: does this ever happen? Better validation (e.g. catch underflows) logger.warn("Unable to set spinbox to: {!r}".format(newValue)) self.setValue(oldValue)
def stepBy(self, steps)
Function that is called whenever the user triggers a step. The steps parameter indicates how many steps were taken, e.g. Pressing Qt::Key_Down will trigger a call to stepBy(-1), whereas pressing Qt::Key_Prior will trigger a call to stepBy(10).
3.016174
3.029132
0.995722
self._name = name try: import importlib self._module = importlib.import_module(name) except ImportError: self._module = None self._version = '' self._packagePath = '' else: if self._versionAttribute: self._version = getattr(self._module, self._versionAttribute, '???') if self._pathAttribute: self._packagePath = getattr(self._module, self._pathAttribute, '???')
def tryImportModule(self, name)
Imports the module and sets version information If the module cannot be imported, the version is set to empty values.
2.696873
2.385731
1.130418
for key, value in kwargs.items(): logger.debug("Setting PyQtGraph config option: {} = {}".format(key, value)) pg.setConfigOptions(**kwargs)
def setPgConfigOptions(**kwargs)
Sets the PyQtGraph config options and emits a log message
3.991031
2.852697
1.399038
if self._model is None and self.parentItem is not None: self._model = self.parentItem.model return self._model
def model(self)
Returns the ConfigTreeModel this item belongs to. If the model is None (not set), it will use and cache the parent's model. Therefore make sure that an ancestor node has a reference to the model! Typically by setting the model property of the invisible root item in the model constructor.
4.678224
2.839988
1.647269
assert '/' not in nodeName, "nodeName may not contain slashes" self._nodeName = nodeName self._recursiveSetNodePath(self._constructNodePath())
def nodeName(self, nodeName)
The node name. Is used to construct the nodePath
8.396953
7.495754
1.120228
self._nodePath = nodePath for childItem in self.childItems: childItem._recursiveSetNodePath(nodePath + '/' + childItem.nodeName)
def _recursiveSetNodePath(self, nodePath)
Sets the nodePath property and updates it for all children.
3.398191
2.717542
1.250465
self._parentItem = value self._recursiveSetNodePath(self._constructNodePath())
def parentItem(self, value)
The parent item
13.826427
14.541897
0.950799
assert '/' not in nodeName, "nodeName can not contain slashes" for child in self.childItems: if child.nodeName == nodeName: return child raise IndexError("No child item found having nodeName: {}".format(nodeName))
def childByNodeName(self, nodeName)
Gets first (direct) child that has the nodeName.
5.271945
5.149663
1.023746
def _auxGetByPath(parts, item): "Aux function that does the actual recursive search" #logger.debug("_auxGetByPath item={}, parts={}".format(item, parts)) if len(parts) == 0: return item head, tail = parts[0], parts[1:] if head == '': # Two consecutive slashes. Just go one level deeper. return _auxGetByPath(tail, item) else: childItem = item.childByNodeName(head) return _auxGetByPath(tail, childItem) # The actual body of findByNodePath starts here check_is_a_string(nodePath) assert not nodePath.startswith('/'), "nodePath may not start with a slash" if not nodePath: raise IndexError("Item not found: {!r}".format(nodePath)) return _auxGetByPath(nodePath.split('/'), self)
def findByNodePath(self, nodePath)
Recursively searches for the child having the nodePath. Starts at self.
4.710486
4.492375
1.048551
if position is None: position = self.nChildren() assert childItem.parentItem is None, "childItem already has a parent: {}".format(childItem) assert childItem._model is None, "childItem already has a model: {}".format(childItem) childItem.parentItem = self childItem.model = self.model self.childItems.insert(position, childItem) return childItem
def insertChild(self, childItem, position=None)
Inserts a child item to the current item. The childItem must not yet have a parent (it will be set by this function). IMPORTANT: this does not let the model know that items have been added. Use BaseTreeModel.insertItem instead. param childItem: a BaseTreeItem that will be added param position: integer position before which the item will be added. If position is None (default) the item will be appended at the end. Returns childItem so that calls may be chained.
2.694335
2.6525
1.015772
assert 0 <= position <= len(self.childItems), \ "position should be 0 < {} <= {}".format(position, len(self.childItems)) self.childItems[position].finalize() self.childItems.pop(position)
def removeChild(self, position)
Removes the child at the position 'position' Calls the child item finalize to close its resources before removing it.
3.830004
3.135793
1.221383
if 0: print(indent * " " + str(self)) else: logger.log(level, indent * " " + str(self)) for childItems in self.childItems: childItems.logBranch(indent + 1, level=level)
def logBranch(self, indent=0, level=logging.DEBUG)
Logs the item and all descendants, one line per child
3.078273
2.958479
1.040492
assert self._canFetchChildren, "canFetchChildren must be True" try: childItems = self._fetchAllChildren() finally: self._canFetchChildren = False # Set to True, even if tried and failed. return childItems
def fetchChildren(self)
Fetches children. The actual work is done by _fetchAllChildren. Descendant classes should typically override that method instead of this one.
7.694605
6.451048
1.192768
cls = self.getClass(tryImport=tryImport) if not self.successfullyImported: raise ImportError("Class not successfully imported: {}".format(self.exception)) return cls(collector)
def create(self, collector, tryImport=True)
Creates an inspector of the registered and passes the collector to the constructor. Tries to import the class if tryImport is True. Raises ImportError if the class could not be imported.
7.559058
6.961026
1.085912
regInspector = InspectorRegItem(fullName, fullClassName, pythonPath=pythonPath) self.registerItem(regInspector)
def registerInspector(self, fullName, fullClassName, pythonPath='')
Registers an Inspector class.
4.870592
4.849789
1.004289
plugins = [ InspectorRegItem(DEFAULT_INSPECTOR, 'argos.inspector.qtplugins.table.TableInspector'), InspectorRegItem('Qt/Text', 'argos.inspector.qtplugins.text.TextInspector'), InspectorRegItem('PyQtGraph/1D Line Plot', 'argos.inspector.pgplugins.lineplot1d.PgLinePlot1d'), InspectorRegItem('PyQtGraph/2D Image Plot', 'argos.inspector.pgplugins.imageplot2d.PgImagePlot2d'), ] if DEBUGGING: plugins.append(InspectorRegItem('Debug Inspector', 'argos.inspector.debug.DebugInspector')) return plugins
def getDefaultItems(self)
Returns a list with the default plugins in the inspector registry.
4.341336
3.891615
1.115561
rootItem = MainGroupCti('debug inspector') if DEBUGGING: # Some test config items. import numpy as np from argos.config.untypedcti import UntypedCti from argos.config.stringcti import StringCti from argos.config.intcti import IntCti from argos.config.floatcti import FloatCti, SnFloatCti from argos.config.boolcti import BoolCti, BoolGroupCti from argos.config.choicecti import ChoiceCti from argos.config.qtctis import PenCti grpItem = GroupCti("group") rootItem.insertChild(grpItem) lcItem = UntypedCti('line color', 123) grpItem.insertChild(lcItem) disabledItem = rootItem.insertChild(StringCti('disabled', "Can't touch me")) disabledItem.enabled=False grpItem.insertChild(IntCti('line-1 color', 7, minValue = -5, stepSize=2, prefix="@", suffix="%", specialValueText="I'm special")) rootItem.insertChild(StringCti('letter', 'aa', maxLength = 1)) grpItem.insertChild(FloatCti('width', 2, minValue =5, stepSize=0.45, decimals=3, prefix="@", suffix="%", specialValueText="so very special")) grpItem.insertChild(SnFloatCti('scientific', defaultData=-np.inf)) gridItem = rootItem.insertChild(BoolGroupCti('grid', True)) gridItem.insertChild(BoolCti('X-Axis', True)) gridItem.insertChild(BoolCti('Y-Axis', False)) rootItem.insertChild(ChoiceCti('hobbit', 2, editable=True, configValues=['Frodo', 'Sam', 'Pippin', 'Merry'])) myPen = QtGui.QPen(QtGui.QColor('#1C8857')) myPen.setWidth(2) myPen.setStyle(Qt.DashDotDotLine) rootItem.insertChild(PenCti('line', False, resetTo=myPen)) return rootItem
def _createConfig(self)
Creates a config tree item (CTI) hierarchy containing default children.
5.295691
4.992911
1.060642
logger.debug("DebugInspector._drawContents: {}".format(self)) slicedArray = self.collector.getSlicedArray() if slicedArray is None: text = "<None>" else: text = ("data = {!r}, masked = {!r}, fill_value = {!r} (?= {}: {})" .format(slicedArray.data, slicedArray.mask, slicedArray.fill_value, slicedArray.data.item(), slicedArray.data.item() == slicedArray.fill_value)) logger.debug("_drawContents: {}".format(text)) logger.debug("_drawContents: {!r}".format(slicedArray)) if DEBUGGING: self.label.setText(text)
def _drawContents(self, reason=None, initiator=None)
Draws the table contents from the sliced array of the collected repo tree item. The reason and initiator parameters are ignored. See AbstractInspector.updateContents for their description.
5.016572
4.654706
1.077742
try: if index.isValid(): item = self.getItem(index, altItem=self.invisibleRootItem) return self.itemData(item, index.column(), role=role) else: return None except Exception as ex: # This Qt slot is called directly from the event loop so uncaught exception make the # application crash (exceptions can come from plugins here). Instead of crashing we # show the error message in the table/tree and hope the users report the error. if not DEBUGGING and role in (Qt.DisplayRole, Qt.EditRole, Qt.ToolTipRole, Qt.StatusTipRole, Qt.WhatsThisRole): return repr(ex) else: raise
def data(self, index, role=Qt.DisplayRole)
Returns the data stored under the given role for the item referred to by the index. Calls self.itemData for valid items. Descendants should typically override itemData instead of this function.
7.538796
6.86884
1.097535