_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q5800 | ViewBoxDebugCti._refreshNodeFromTarget | train | def _refreshNodeFromTarget(self):
""" Updates the config settings
"""
for key, value in self.viewBox.state.items():
if key != "limits":
childItem = self.childByNodeName(key)
childItem.data = value
else:
# limits contains a dictionary as well
for limitKey, | python | {
"resource": ""
} |
q5801 | AbstractRangeCti._forceRefreshMinMax | train | def _forceRefreshMinMax(self):
""" Refreshes the min max config values from the axes' state.
"""
#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 | python | {
"resource": ""
} |
q5802 | AbstractRangeCti._forceRefreshAutoRange | train | def _forceRefreshAutoRange(self):
""" The min and max config items will be disabled if auto range is on.
"""
| python | {
"resource": ""
} |
q5803 | AbstractRangeCti.setAutoRangeOff | train | 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.
"""
# TODO: catch exceptions. How? | python | {
"resource": ""
} |
q5804 | AbstractRangeCti.setAutoRangeOn | train | 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.
"""
| python | {
"resource": ""
} |
q5805 | AbstractRangeCti.calculateRange | train | def calculateRange(self):
""" Calculates the range depending on the config settings.
"""
if not self.autoRangeCti or not self.autoRangeCti.configValue:
return (self.rangeMinCti.data, self.rangeMaxCti.data)
| python | {
"resource": ""
} |
q5806 | AbstractRangeCti._updateTargetFromNode | train | def _updateTargetFromNode(self):
""" Applies the configuration to the target axis.
"""
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 | python | {
"resource": ""
} |
q5807 | PgAxisRangeCti.setTargetRange | train | def setTargetRange(self, targetRange, padding=None):
""" Sets the range of the target.
"""
# viewBox.setRange doesn't accept an axis number :-(
if self.axisNumber == X_AXIS:
xRange, yRange = targetRange, None
| python | {
"resource": ""
} |
q5808 | PgAxisLabelCti._updateTargetFromNode | train | 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.
"""
rtiInfo = self.collector.rtiInfo | python | {
"resource": ""
} |
q5809 | PgGridCti._updateTargetFromNode | train | def _updateTargetFromNode(self):
""" Applies the configuration to the grid of the plot item.
"""
self.plotItem.showGrid(x=self.xGridCti.configValue, y=self.yGridCti.configValue,
| python | {
"resource": ""
} |
q5810 | PgPlotDataItemCti.createPlotDataItem | train | def createPlotDataItem(self):
""" Creates a PyQtGraph PlotDataItem from the config values
"""
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
| python | {
"resource": ""
} |
q5811 | RepoTreeModel.itemData | train | def itemData(self, treeItem, column, role=Qt.DisplayRole):
""" Returns the data stored under the given role for the item. O
"""
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
| python | {
"resource": ""
} |
q5812 | RepoTreeModel.canFetchMore | train | def canFetchMore(self, parentIndex):
""" Returns true if there is more data available for parent; otherwise returns false. | python | {
"resource": ""
} |
q5813 | RepoTreeModel.fetchMore | train | def fetchMore(self, parentIndex): # TODO: Make LazyLoadRepoTreeModel?
""" Fetches any available data for the items with the parent specified by the parent index.
"""
parentItem = self.getItem(parentIndex)
if not parentItem:
return
if not parentItem.canFetchChildren():
return
# TODO: implement InsertItems to | python | {
"resource": ""
} |
q5814 | RepoTreeModel.findFileRtiIndex | train | 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
"""
parentIndex = childIndex.parent()
| python | {
"resource": ""
} |
q5815 | RepoTreeModel.reloadFileAtIndex | train | 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.
"""
| python | {
"resource": ""
} |
q5816 | RepoTreeModel.loadFile | train | 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
"""
logger.info("Loading data from: {!r}".format(fileName))
if rtiClass is None:
repoTreeItem = createRtiFromFileName(fileName)
| python | {
"resource": ""
} |
q5817 | RepoTreeView.finalize | train | def finalize(self):
""" Disconnects signals and frees resources
"""
self.model().sigItemChanged.disconnect(self.repoTreeItemChanged)
| python | {
"resource": ""
} |
q5818 | RepoTreeView.contextMenuEvent | train | def contextMenuEvent(self, event):
""" Creates and executes the context menu for the tree view
"""
menu = QtWidgets.QMenu(self)
for action in self.actions():
menu.addAction(action)
openAsMenu | python | {
"resource": ""
} |
q5819 | RepoTreeView.createOpenAsMenu | train | def createOpenAsMenu(self, parent=None):
""" Creates the submenu for the Open As choice
"""
openAsMenu = QtWidgets.QMenu(parent=parent)
openAsMenu.setTitle("Open Item As")
registry = globalRtiRegistry()
for rtiRegItem in registry.items:
#rtiRegItem.tryImportClass()
def createTrigger():
"""Function to create a closure with the regItem"""
_rtiRegItem = rtiRegItem # keep reference in closure
return | python | {
"resource": ""
} |
q5820 | RepoTreeView.openCurrentItem | train | def openCurrentItem(self):
""" Opens the current item in the repository.
"""
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 | python | {
"resource": ""
} |
q5821 | RepoTreeView.closeCurrentItem | train | def closeCurrentItem(self):
""" Closes the current item in the repository.
All its children will be unfetched and closed.
"""
logger.debug("closeCurrentItem")
currentItem, currentIndex = self.getCurrentItem()
if not currentIndex.isValid():
return
# First we remove all the children, this will close them as well.
| python | {
"resource": ""
} |
q5822 | RepoTreeView.removeCurrentItem | train | def removeCurrentItem(self):
""" Removes the current item from the repository tree.
"""
logger.debug("removeCurrentFile")
currentIndex = self.getRowCurrentIndex()
| python | {
"resource": ""
} |
q5823 | RepoTreeView.reloadFileOfCurrentItem | train | 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.
"""
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)
| python | {
"resource": ""
} |
q5824 | RepoTreeView.currentRepoTreeItemChanged | train | def currentRepoTreeItemChanged(self):
""" Called to update the GUI when a repo tree item has changed or a new one was selected.
"""
# 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)
| python | {
"resource": ""
} |
q5825 | initQApplication | train | 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.
"""
# PyQtGraph recommends raster graphics system for | python | {
"resource": ""
} |
q5826 | removeSettingsGroup | train | def removeSettingsGroup(groupName, settings=None):
""" Removes a group from the persistent settings
"""
logger.debug("Removing settings group: {}".format(groupName))
| python | {
"resource": ""
} |
q5827 | containsSettingsGroup | train | 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.
"""
def _containsPath(path, settings):
"Aux function for containsSettingsGroup. Does the actual recursive search."
if len(path) == 0:
return True
| python | {
"resource": ""
} |
q5828 | printChildren | train | def printChildren(obj, indent=""):
""" Recursively prints the children of a QObject. Useful for debugging.
"""
children=obj.children()
if children==None:
return
for child in children:
try:
childName = child.objectName()
except AttributeError:
| python | {
"resource": ""
} |
q5829 | widgetSubCheckBoxRect | train | def widgetSubCheckBoxRect(widget, option):
""" Returns the rectangle of a check box drawn as a sub element of widget
"""
opt = QtWidgets.QStyleOption()
opt.initFrom(widget)
| python | {
"resource": ""
} |
q5830 | UpdateReason.checkValid | train | def checkValid(cls, reason):
""" Raises ValueError if the reason is not one of the valid enumerations
| python | {
"resource": ""
} |
q5831 | AbstractInspector.updateContents | train | def updateContents(self, reason=None, initiator=None): # TODO: reason mandatory?
""" 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).
"""
UpdateReason.checkValid(reason)
logger.debug("---- Inspector updateContents, reason: {}, initiator: {}"
| python | {
"resource": ""
} |
q5832 | AbstractInspector._showError | train | def _showError(self, msg="", title="Error"):
""" Shows an error message.
"""
| python | {
"resource": ""
} |
q5833 | ChoiceCti._enforceDataType | train | 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.
"""
idx = int(data)
| python | {
"resource": ""
} |
q5834 | ChoiceCti.insertValue | train | 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
"""
| python | {
"resource": ""
} |
q5835 | ChoiceCtiEditor.comboBoxRowsInserted | train | 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.
"""
| python | {
"resource": ""
} |
q5836 | ChoiceCtiEditor.eventFilter | train | 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.
"""
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()
| python | {
"resource": ""
} |
q5837 | ConfigTreeModel.itemData | train | def itemData(self, treeItem, column, role=Qt.DisplayRole):
""" Returns the data stored under the given role for the item.
"""
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:
| python | {
"resource": ""
} |
q5838 | ConfigTreeModel.setItemData | train | def setItemData(self, treeItem, column, value, role=Qt.EditRole):
""" Sets the role data for the item at index to value.
"""
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:
| python | {
"resource": ""
} |
q5839 | ConfigTreeModel.setRefreshBlocked | train | 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.
"""
| python | {
"resource": ""
} |
q5840 | BoolCti.data | train | def data(self, data):
""" Sets the data of this item.
Does type conversion to ensure data is always of the correct type.
"""
# Descendants should convert the data to the desired type here
self._data = self._enforceDataType(data)
| python | {
"resource": ""
} |
q5841 | BoolCti.insertChild | train | def insertChild(self, childItem, position=None):
""" Inserts a child item to the current item.
Overridden from BaseTreeItem.
"""
childItem = super(BoolCti, self).insertChild(childItem, position=None)
enableChildren = self.enabled and self.data != self.childrenDisabledValue
| python | {
"resource": ""
} |
q5842 | BoolCti.checkState | train | def checkState(self):
""" Returns Qt.Checked or Qt.Unchecked.
"""
if self.data is True:
| python | {
"resource": ""
} |
q5843 | BoolGroupCti.checkState | train | def checkState(self):
""" Returns Qt.Checked or Qt.Unchecked if all children are checked or unchecked, else
returns Qt.PartiallyChecked
"""
#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
| python | {
"resource": ""
} |
q5844 | BaseRti.open | train | def open(self):
""" Opens underlying resources and sets isOpen flag.
It calls _openResources. Descendants should usually override the latter
function instead of this one.
"""
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()
| python | {
"resource": ""
} |
q5845 | BaseRti.close | train | 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.
"""
self.clearException()
try:
if self._isOpen:
logger.debug("Closing {}".format(self))
self._closeResources()
self._isOpen = False
else:
| python | {
"resource": ""
} |
q5846 | BaseRti._checkFileExists | train | 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.
"""
if self._fileName and not os.path.exists(self._fileName):
| python | {
"resource": ""
} |
q5847 | BaseRti.fetchChildren | train | def fetchChildren(self):
""" Creates child items and returns them.
Opens the tree item first if it's not yet open.
"""
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)")
| python | {
"resource": ""
} |
q5848 | BaseRti.decoration | train | 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.
"""
rtiIconFactory = RtiIconFactory.singleton()
if self._exception:
return rtiIconFactory.getIcon(rtiIconFactory.ERROR, isOpen=False,
| python | {
"resource": ""
} |
q5849 | format_float | train | def format_float(value): # not used
"""Modified form of the 'g' format specifier.
| python | {
"resource": ""
} |
q5850 | ScientificDoubleSpinBox.smallStepsPerLargeStep | train | def smallStepsPerLargeStep(self, smallStepsPerLargeStep):
""" Sets the number of small steps that go in a large one.
"""
| python | {
"resource": ""
} |
q5851 | ImportedModuleInfo.tryImportModule | train | def tryImportModule(self, name):
""" Imports the module and sets version information
If the module cannot be imported, the version is set to empty values.
"""
self._name = name
try:
import importlib
self._module = importlib.import_module(name)
except ImportError:
self._module = None
self._version = ''
self._packagePath = ''
else:
| python | {
"resource": ""
} |
q5852 | setPgConfigOptions | train | def setPgConfigOptions(**kwargs):
""" Sets the PyQtGraph config options and emits a log message
"""
for key, value in kwargs.items():
logger.debug("Setting | python | {
"resource": ""
} |
q5853 | BaseTreeItem.nodeName | train | def nodeName(self, nodeName):
""" The node name. Is used to construct the nodePath"""
assert '/' | python | {
"resource": ""
} |
q5854 | BaseTreeItem._recursiveSetNodePath | train | def _recursiveSetNodePath(self, nodePath):
""" Sets the nodePath property and updates it for all children.
| python | {
"resource": ""
} |
q5855 | BaseTreeItem.parentItem | train | def parentItem(self, value):
""" The parent item """
| python | {
"resource": ""
} |
q5856 | BaseTreeItem.findByNodePath | train | def findByNodePath(self, nodePath):
""" Recursively searches for the child having the nodePath. Starts at self.
"""
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)
| python | {
"resource": ""
} |
q5857 | BaseTreeItem.removeChild | train | def removeChild(self, position):
""" Removes the child at the position 'position'
Calls the child item finalize to close its resources before removing it.
"""
assert 0 <= position <= len(self.childItems), \
| python | {
"resource": ""
} |
q5858 | BaseTreeItem.logBranch | train | def logBranch(self, indent=0, level=logging.DEBUG):
""" Logs the item and all descendants, one line per child
"""
if 0:
print(indent * " " + str(self))
else:
| python | {
"resource": ""
} |
q5859 | AbstractLazyLoadTreeItem.fetchChildren | train | def fetchChildren(self):
""" Fetches children.
The actual work is done by _fetchAllChildren. Descendant classes should typically
override that method instead of this one.
"""
assert self._canFetchChildren, "canFetchChildren must be True"
try:
| python | {
"resource": ""
} |
q5860 | InspectorRegItem.create | train | 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.
"""
| python | {
"resource": ""
} |
q5861 | InspectorRegistry.registerInspector | train | def registerInspector(self, fullName, fullClassName, pythonPath=''):
""" Registers an Inspector class.
"""
| python | {
"resource": ""
} |
q5862 | InspectorRegistry.getDefaultItems | train | def getDefaultItems(self):
""" Returns a list with the default plugins in the inspector registry.
"""
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',
| python | {
"resource": ""
} |
q5863 | BaseTreeModel.itemData | train | def itemData(self, item, column, role=Qt.DisplayRole):
""" Returns the data stored under the given role for the item. O
The column parameter may be used to differentiate behavior per column.
The default implementation does nothing. Descendants should typically override this
function instead of data()
Note: If you do not have a value to return, return an invalid QVariant instead of
returning 0. (This means returning None in Python)
"""
if role == Qt.DecorationRole:
if column == self.COL_DECORATION:
| python | {
"resource": ""
} |
q5864 | BaseTreeModel.index | train | def index(self, row, column, parentIndex=QtCore.QModelIndex()):
""" Returns the index of the item in the model specified by the given row, column and parent
index.
Since each item contains information for an entire row of data, we create a model index
to uniquely identify it by calling createIndex() it with the row and column numbers and
a pointer to the item. (In the data() function, we will use the item pointer and column
number to access the data associated with the model index; in this model, the row number
is not needed to identify data.)
When reimplementing this function in a subclass, call createIndex() to generate
model indexes that other components can use to refer to items in your model.
"""
# logger.debug(" called index({}, {}, {}) {}"
# .format(parentIndex.row(), parentIndex.column(), parentIndex.isValid(),
# parentIndex.isValid() and parentIndex.column() != 0))
parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem)
#logger.debug(" Getting row {} from parentItem: {}".format(row, parentItem))
if not (0 <= row < parentItem.nChildren()):
| python | {
"resource": ""
} |
q5865 | BaseTreeModel.setData | train | def setData(self, index, value, role=Qt.EditRole):
""" Sets the role data for the item at index to value.
Returns true if successful; otherwise returns false.
The dataChanged and sigItemChanged signals will be emitted if the data was successfully
set.
Descendants should typically override setItemData function instead of setData()
"""
if role != Qt.CheckStateRole and role != Qt.EditRole:
return False
treeItem = self.getItem(index, altItem=self.invisibleRootItem)
try:
result = self.setItemData(treeItem, index.column(), value, role=role)
if result:
# Emit dataChanged to update the tree view
# TODO, update the entire tree?
# A check box can have a tristate checkbox as parent which state depends
# on the state of this child check box. Therefore we update the parentIndex
| python | {
"resource": ""
} |
q5866 | BaseTreeModel.getItem | train | def getItem(self, index, altItem=None):
""" Returns the TreeItem for the given index. Returns the altItem if the index is invalid.
"""
if index.isValid():
item = index.internalPointer()
if item: | python | {
"resource": ""
} |
q5867 | BaseTreeModel.insertItem | train | def insertItem(self, childItem, position=None, parentIndex=None):
""" Inserts a childItem before row 'position' under the parent index.
If position is None the child will be appended as the last child of the parent.
Returns the index of the new inserted child.
"""
if parentIndex is None:
parentIndex=QtCore.QModelIndex()
parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem)
nChildren = parentItem.nChildren()
if position is None:
position = nChildren
assert 0 <= position <= nChildren, \
"position should be 0 < | python | {
"resource": ""
} |
q5868 | BaseTreeModel.removeAllChildrenAtIndex | train | def removeAllChildrenAtIndex(self, parentIndex):
""" Removes all children of the item at the parentIndex.
The children's finalize method is called before removing them to give them a
chance to close their resources
"""
if not parentIndex.isValid():
logger.debug("No valid item selected for deletion (ignored).")
return
parentItem = self.getItem(parentIndex, None)
| python | {
"resource": ""
} |
q5869 | BaseTreeModel.deleteItemAtIndex | train | def deleteItemAtIndex(self, itemIndex):
""" Removes the item at the itemIndex.
The item's finalize method is called before removing so it can close its resources.
"""
if not itemIndex.isValid():
logger.debug("No valid item selected for deletion (ignored).")
return
item = self.getItem(itemIndex, "<no item>")
logger.debug("deleteItemAtIndex: removing {}".format(item))
parentIndex = | python | {
"resource": ""
} |
q5870 | BaseTreeModel.replaceItemAtIndex | train | def replaceItemAtIndex(self, newItem, oldItemIndex):
""" Removes the item at the itemIndex and insert a new item instead.
"""
oldItem = self.getItem(oldItemIndex)
childNumber = oldItem.childNumber()
| python | {
"resource": ""
} |
q5871 | ToggleColumnMixIn.addHeaderContextMenu | train | def addHeaderContextMenu(self, checked = None, checkable = None, enabled = None):
""" Adds the context menu from using header information
checked can be a header_name -> boolean dictionary. If given, headers
with the key name will get the checked value from the dictionary.
The corresponding column will be hidden if checked is False.
checkable can be a header_name -> boolean dictionary. If given, header actions
with the key name will get the checkable value from the dictionary. (Default True)
enabled can be a header_name -> boolean dictionary. If given, header actions
with the key name will get the enabled value from the dictionary. (Default True)
"""
checked = checked if checked is not None else {}
checkable = checkable if checkable is not None else {}
enabled = enabled if enabled is not None else {}
horizontal_header = self.horizontalHeader()
horizontal_header.setContextMenuPolicy(Qt.ActionsContextMenu)
self.toggle_column_actions_group = QtWidgets.QActionGroup(self)
self.toggle_column_actions_group.setExclusive(False)
self.__toggle_functions = [] # for keeping references
for col in range(horizontal_header.count()):
column_label = self.model().headerData(col, Qt.Horizontal, Qt.DisplayRole)
#logger.debug("Adding: col {}: {}".format(col, column_label))
action = QtWidgets.QAction(str(column_label),
| python | {
"resource": ""
} |
q5872 | ToggleColumnMixIn.__makeShowColumnFunction | train | def __makeShowColumnFunction(self, column_idx):
""" Creates a function that shows or | python | {
"resource": ""
} |
q5873 | ClassRegItem.descriptionHtml | train | def descriptionHtml(self):
""" HTML help describing the class. For use in the detail editor.
"""
if self.cls is None:
return | python | {
"resource": ""
} |
q5874 | ClassRegItem.tryImportClass | train | def tryImportClass(self):
""" Tries to import the registered class.
Will set the exception property if and error occurred.
"""
logger.info("Importing: {}".format(self.fullClassName))
self._triedImport = True
self._exception = None
self._cls = None
try:
for pyPath in self.pythonPath.split(':'):
if pyPath and pyPath not in sys.path:
logger.debug("Appending {!r} to the PythonPath.".format(pyPath))
sys.path.append(pyPath)
| python | {
"resource": ""
} |
q5875 | ClassRegistry.removeItem | train | def removeItem(self, regItem):
""" Removes a ClassRegItem object to the registry.
Will raise a KeyError if the regItem is not registered.
"""
check_class(regItem, ClassRegItem)
logger.info("Removing {!r} | python | {
"resource": ""
} |
q5876 | ClassRegistry.loadOrInitSettings | train | def loadOrInitSettings(self, groupName=None):
""" Reads the registry items from the persistent settings store, falls back on the
default plugins if there are no settings in the store for this registry.
"""
groupName = groupName if groupName else self.settingsGroupName
settings = QtCore.QSettings()
#for key in sorted(settings.allKeys()):
| python | {
"resource": ""
} |
q5877 | ClassRegistry.loadSettings | train | def loadSettings(self, groupName=None):
""" Reads the registry items from the persistent settings store.
"""
groupName = groupName if groupName else self.settingsGroupName
settings = QtCore.QSettings()
logger.info("Reading {!r} from: {}".format(groupName, settings.fileName()))
settings.beginGroup(groupName)
self.clear()
try:
for key in settings.childKeys():
if key.startswith('item'):
| python | {
"resource": ""
} |
q5878 | ClassRegistry.saveSettings | train | def saveSettings(self, groupName=None):
""" Writes the registry items into the persistent settings store.
"""
groupName = groupName if groupName else self.settingsGroupName
settings = QtCore.QSettings()
logger.info("Saving {} to: {}".format(groupName, settings.fileName()))
settings.remove(groupName) # start with a clean slate
settings.beginGroup(groupName)
try: | python | {
"resource": ""
} |
q5879 | ClassRegistry.deleteSettings | train | def deleteSettings(self, groupName=None):
""" Deletes registry items from the persistent store.
"""
groupName = groupName if groupName else self.settingsGroupName
settings = QtCore.QSettings()
| python | {
"resource": ""
} |
q5880 | DetailBasePane.repoItemChanged | train | def repoItemChanged(self, rti):
""" Updates the content when the current repo tree item changes.
The rti parameter can be None when no RTI is selected in the repository tree.
"""
check_class(rti, (BaseRti, int), allow_none=True)
| python | {
"resource": ""
} |
q5881 | addInspectorActionsToMenu | train | def addInspectorActionsToMenu(inspectorMenu, execInspectorDialogAction, inspectorActionGroup):
""" Adds menu items to the inpsectorMenu for the given set-inspector actions.
:param inspectorMenu: inspector menu that will be modified
:param execInspectorDialogAction: the "Browse Inspectors..." actions
:param inspectorActionGroup: action group with actions for selecting a new inspector
:return: the inspectorMenu, which has | python | {
"resource": ""
} |
q5882 | InspectorSelectionPane.updateFromInspectorRegItem | train | def updateFromInspectorRegItem(self, inspectorRegItem):
""" Updates the label from the full name of the InspectorRegItem
"""
library, name = inspectorRegItem.splitName()
| python | {
"resource": ""
} |
q5883 | StringCti.createEditor | train | def createEditor(self, delegate, parent, option):
""" Creates a StringCtiEditor.
For the parameters see the | python | {
"resource": ""
} |
q5884 | HistogramLUTItem.setHistogramRange | train | def setHistogramRange(self, mn, mx, padding=0.1):
"""Set the Y range on the histogram plot. This disables auto-scaling."""
| python | {
"resource": ""
} |
q5885 | HistogramLUTItem.setImageItem | train | def setImageItem(self, img):
"""Set an ImageItem to have its levels and LUT automatically controlled
by this HistogramLUTItem.
"""
self.imageItem = weakref.ref(img)
img.sigImageChanged.connect(self.imageChanged)
| python | {
"resource": ""
} |
q5886 | HistogramLUTItem.getLookupTable | train | def getLookupTable(self, img=None, n=None, alpha=None):
"""Return a lookup table from the color gradient defined by this
HistogramLUTItem.
"""
if n is None:
if img.dtype == np.uint8:
n = 256
else:
| python | {
"resource": ""
} |
q5887 | PgLinePlot1dCti.setAutoRangeOn | train | def setAutoRangeOn(self, axisNumber):
""" Sets the auto-range of the axis on.
:param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
| python | {
"resource": ""
} |
q5888 | PgLinePlot1d.finalize | train | def finalize(self):
""" Is called before destruction. Can be used to clean-up resources
"""
logger.debug("Finalizing: {}".format(self))
| python | {
"resource": ""
} |
q5889 | PgLinePlot1d._clearContents | train | def _clearContents(self):
""" Clears the the inspector widget when no valid input is available.
"""
self.titleLabel.setText('')
| python | {
"resource": ""
} |
q5890 | environment_var_to_bool | train | def environment_var_to_bool(env_var):
""" Converts an environment variable to a boolean
Returns False if the environment variable is False, 0 or a case-insenstive string "false"
or "0".
"""
# Try to see if env_var can be converted to an int
try:
env_var = int(env_var)
except ValueError:
pass
| python | {
"resource": ""
} |
q5891 | fill_values_to_nan | train | def fill_values_to_nan(masked_array):
""" Replaces the fill_values of the masked array by NaNs
If the array is None or it does not contain floating point values, it cannot contain NaNs.
In that case the original array is returned.
"""
if masked_array is not None and masked_array.dtype.kind == 'f':
check_class(masked_array, ma.masked_array)
| python | {
"resource": ""
} |
q5892 | setting_str_to_bool | train | def setting_str_to_bool(s):
""" Converts 'true' to True and 'false' to False if s is a string
"""
if isinstance(s, six.string_types):
s = s.lower()
if s == 'true':
return True
| python | {
"resource": ""
} |
q5893 | to_string | train | def to_string(var, masked=None, decode_bytes='utf-8', maskFormat='', strFormat='{}',
intFormat='{}', numFormat=DEFAULT_NUM_FORMAT, noneFormat='{!r}', otherFormat='{}'):
""" Converts var to a python string or unicode string so Qt widgets can display them.
If var consists of bytes, the decode_bytes is used to decode the bytes.
If var consists of a numpy.str_, the result will be converted to a regular Python string.
This is necessary to display the string in Qt widgets.
For the possible format string (replacement fields) see:
https://docs.python.org/3/library/string.html#format-string-syntax
:param masked: if True, the element is masked. The maskFormat is used.
:param decode_bytes': string containing the expected encoding when var is of type bytes
:param strFormat' : new style format string used to format strings
:param intFormat' : new style format string used to format integers
:param numFormat' : new style format string used to format all numbers except integers.
:param noneFormat': new style format string used to format Nones.
:param maskFormat': override with this | python | {
"resource": ""
} |
q5894 | check_is_a_string | train | def check_is_a_string(var, allow_none=False):
""" Calls is_a_string and raises a type error if the check fails.
"""
if not is_a_string(var, allow_none=allow_none):
| python | {
"resource": ""
} |
q5895 | is_text | train | def is_text(var, allow_none=False):
""" Returns True if var is a unicode text
Result py-2 py-3
----------------- ----- -----
b'bytes literal' False False
'string literal' False True
u'unicode literal' True True | python | {
"resource": ""
} |
q5896 | check_is_a_sequence | train | def check_is_a_sequence(var, allow_none=False):
""" Calls is_a_sequence and raises a type error if the check fails.
"""
if not is_a_sequence(var, allow_none=allow_none):
| python | {
"resource": ""
} |
q5897 | check_is_a_mapping | train | def check_is_a_mapping(var, allow_none=False):
""" Calls is_a_mapping and raises a type error if the check fails.
"""
if not is_a_mapping(var, allow_none=allow_none):
| python | {
"resource": ""
} |
q5898 | is_an_array | train | def is_an_array(var, allow_none=False):
""" Returns True if var is a numpy array.
""" | python | {
"resource": ""
} |
q5899 | check_is_an_array | train | def check_is_an_array(var, allow_none=False):
""" Calls is_an_array and raises a type error if the check fails.
"""
if not is_an_array(var, allow_none=allow_none):
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.