_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q5700
|
cli
|
train
|
def cli(inargs=None):
"""
Commandline interface for receiving stem files
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--version', '-V',
action='version',
version='%%(prog)s %s' % __version__
)
parser.add_argument(
'filename',
metavar="filename",
help="Input STEM file"
)
parser.add_argument(
'--id',
metavar='id',
type=int,
nargs='+',
help="A list of stem_ids"
)
parser.add_argument(
'-s',
type=float,
nargs='?',
help="start offset in seconds"
)
parser.add_argument(
'-t',
type=float,
nargs='?',
help="read duration"
)
parser.add_argument(
'outdir',
metavar='outdir',
nargs='?',
help="Output folder"
)
args = parser.parse_args(inargs)
stem2wav(args.filename, args.outdir, args.id, args.s, args.t)
|
python
|
{
"resource": ""
}
|
q5701
|
check_available_aac_encoders
|
train
|
def check_available_aac_encoders():
"""Returns the available AAC encoders
Returns
----------
codecs : list(str)
List of available encoder codecs
"""
cmd = [
'ffmpeg',
'-v', 'error',
'-codecs'
]
output = sp.check_output(cmd)
aac_codecs = [
x for x in
output.splitlines() if "AAC (Advanced Audio Coding)" in str(x)
][0]
hay = aac_codecs.decode('ascii')
match = re.findall(r'\(encoders: ([^\)]*) \)', hay)
if match:
return match[0].split(" ")
else:
return None
|
python
|
{
"resource": ""
}
|
q5702
|
write_stems
|
train
|
def write_stems(
audio,
filename,
rate=44100,
bitrate=256000,
codec=None,
ffmpeg_params=None
):
"""Write stems from numpy Tensor
Parameters
----------
audio : array_like
The tensor of Matrix of stems. The data shape is formatted as
:code:`stems x channels x samples`.
filename : str
Output file_name of the stems file
rate : int
Output samplerate. Defaults to 44100 Hz.
bitrate : int
AAC Bitrate in Bits per second. Defaults to 256 Kbit/s
codec : str
AAC codec used. Defaults to `None` which automatically selects
either `libfdk_aac` or `aac` in that order, determined by availability.
ffmpeg_params : list(str)
List of additional ffmpeg parameters
Notes
-----
Output is written as 16bit/44.1 kHz
"""
if int(stempeg.ffmpeg_version()[0]) < 3:
warnings.warn(
"Writing STEMS with FFMPEG version < 3 is unsupported", UserWarning
)
if codec is None:
avail = check_available_aac_encoders()
if avail is not None:
if 'libfdk_aac' in avail:
codec = 'libfdk_aac'
else:
codec = 'aac'
warnings.warn("For better quality, please install libfdc_aac")
else:
codec = 'aac'
warnings.warn("For better quality, please install libfdc_aac")
tmps = [
tmp.NamedTemporaryFile(delete=False, suffix='.wav')
for t in range(audio.shape[0])
]
if audio.shape[1] % 1024 != 0:
warnings.warn(
"Number of samples does not divide by 1024, be aware that "
"the AAC encoder add silence to the input signal"
)
for k in range(audio.shape[0]):
sf.write(tmps[k].name, audio[k], rate)
cmd = (
[
'ffmpeg', '-y',
"-f", 's%dle' % (16),
"-acodec", 'pcm_s%dle' % (16),
'-ar', "%d" % rate,
'-ac', "%d" % 2
] +
list(chain.from_iterable(
[['-i', i.name] for i in tmps]
)) +
list(chain.from_iterable(
[['-map', str(k)] for k, _ in enumerate(tmps)]
)) +
[
'-vn',
'-acodec', codec,
'-ar', "%d" % rate,
'-strict', '-2',
'-loglevel', 'error'
] +
(['-ab', str(bitrate)] if (bitrate is not None) else []) +
(ffmpeg_params if ffmpeg_params else []) +
[filename]
)
sp.call(cmd)
|
python
|
{
"resource": ""
}
|
q5703
|
read_info
|
train
|
def read_info(
filename
):
"""Extracts FFMPEG info and returns info as JSON
Returns
-------
info : Dict
JSON info dict
"""
cmd = [
'ffprobe',
filename,
'-v', 'error',
'-print_format', 'json',
'-show_format', '-show_streams',
]
out = sp.check_output(cmd)
info = json.loads(out.decode('utf-8'))
return info
|
python
|
{
"resource": ""
}
|
q5704
|
read_stems
|
train
|
def read_stems(
filename,
out_type=np.float_,
stem_id=None,
start=0,
duration=None,
info=None
):
"""Read STEMS format into numpy Tensor
Parameters
----------
filename : str
Filename of STEMS format. Typically `filename.stem.mp4`.
out_type : type
Output type. Defaults to 32bit float aka `np.float32`.
stem_id : int
Stem ID (Stream ID) to read. Defaults to `None`, which reads all
available stems.
start : float
Start position (seek) in seconds, defaults to 0.
duration : float
Read `duration` seconds. End position then is `start + duration`.
Defaults to `None`: read till the end.
info : object
provide info object, useful if read_stems is called frequently on
file with same configuration (#streams, #channels, samplerate).
Returns
-------
stems : array_like
The tensor of Matrix of stems. The data shape is formatted as
:code:`stems x channels x samples`.
Notes
-----
Input is expected to be in 16bit/44.1 kHz
"""
if info is None:
FFinfo = Info(filename)
else:
FFinfo = info
if stem_id is not None:
substreams = stem_id
else:
substreams = FFinfo.audio_stream_idx()
if not isinstance(substreams, list):
substreams = [substreams]
stems = []
tmps = [
tmp.NamedTemporaryFile(delete=False, suffix='.wav')
for t in substreams
]
for tmp_id, stem in enumerate(substreams):
rate = FFinfo.rate(stem)
channels = FFinfo.channels(stem)
cmd = [
'ffmpeg',
'-y',
'-vn',
'-i', filename,
'-map', '0:' + str(stem),
'-acodec', 'pcm_s16le',
'-ar', str(rate),
'-ac', str(channels),
'-loglevel', 'error',
tmps[tmp_id].name
]
if start:
cmd.insert(3, '-ss')
cmd.insert(4, str(start))
if duration is not None:
cmd.insert(-1, '-t')
cmd.insert(-1, str(duration))
sp.call(cmd)
# read wav files
audio, rate = sf.read(tmps[tmp_id].name)
tmps[tmp_id].close()
os.remove(tmps[tmp_id].name)
stems.append(audio)
# check if all stems have the same duration
stem_durations = np.array([t.shape[0] for t in stems])
if not (stem_durations == stem_durations[0]).all():
warnings.warn("Warning.......Stems differ in length and were shortend")
min_length = np.min(stem_durations)
stems = [t[:min_length, :] for t in stems]
stems = np.array(stems)
stems = np.squeeze(stems).astype(out_type)
return stems, rate
|
python
|
{
"resource": ""
}
|
q5705
|
PandasIndexRti.nDims
|
train
|
def nDims(self):
""" The number of dimensions of the index. Will always be 1.
"""
result = self._index.ndim
assert result == 1, "Expected index to be 1D, got: {}D".format(result)
return result
|
python
|
{
"resource": ""
}
|
q5706
|
AbstractPandasNDFrameRti._createIndexRti
|
train
|
def _createIndexRti(self, index, nodeName):
""" Auxiliary method that creates a PandasIndexRti.
"""
return PandasIndexRti(index=index, nodeName=nodeName, fileName=self.fileName,
iconColor=self._iconColor)
|
python
|
{
"resource": ""
}
|
q5707
|
PandasSeriesRti._fetchAllChildren
|
train
|
def _fetchAllChildren(self):
""" Fetches the index if the showIndex member is True
Descendants can override this function to add the subdevicions.
"""
assert self.isSliceable, "No underlying pandas object: self._ndFrame is None"
childItems = []
if self._standAlone:
childItems.append(self._createIndexRti(self._ndFrame.index, 'index'))
return childItems
|
python
|
{
"resource": ""
}
|
q5708
|
OpenInspectorDialog.setCurrentInspectorRegItem
|
train
|
def setCurrentInspectorRegItem(self, regItem):
""" Sets the current inspector given an InspectorRegItem
"""
check_class(regItem, InspectorRegItem, allow_none=True)
self.inspectorTab.setCurrentRegItem(regItem)
|
python
|
{
"resource": ""
}
|
q5709
|
log_dictionary
|
train
|
def log_dictionary(dictionary, msg='', logger=None, level='debug', item_prefix=' '):
""" Writes a log message with key and value for each item in the dictionary.
:param dictionary: the dictionary to be logged
:type dictionary: dict
:param name: An optional message that is logged before the contents
:type name: string
:param logger: A logging.Logger object to log to. If not set, the 'main' logger is used.
:type logger: logging.Logger or a string
:param level: log level. String or int as described in the logging module documentation.
Default: 'debug'.
:type level: string or int
:param item_prefix: String that will be prefixed to each line. Default: two spaces.
:type item_prefix: string
"""
level_nr = logging.getLevelName(level.upper())
if logger is None:
logger = logging.getLogger('main')
if msg :
logger.log(level_nr, "Logging dictionary: {}".format(msg))
if not dictionary:
logger.log(level_nr,"{}<empty dictionary>".format(item_prefix))
return
max_key_len = max([len(k) for k in dictionary.keys()])
for key, value in sorted(dictionary.items()):
logger.log(level_nr, "{0}{1:<{2}s} = {3}".format(item_prefix, key, max_key_len, value))
|
python
|
{
"resource": ""
}
|
q5710
|
string_to_identifier
|
train
|
def string_to_identifier(s, white_space_becomes='_'):
""" Takes a string and makes it suitable for use as an identifier
Translates to lower case
Replaces white space by the white_space_becomes character (default=underscore).
Removes and punctuation.
"""
import re
s = s.lower()
s = re.sub(r"\s+", white_space_becomes, s) # replace whitespace with underscores
s = re.sub(r"-", "_", s) # replace hyphens with underscores
s = re.sub(r"[^A-Za-z0-9_]", "", s) # remove everything that's not a character, a digit or a _
return s
|
python
|
{
"resource": ""
}
|
q5711
|
RtiIconFactory.loadIcon
|
train
|
def loadIcon(self, fileName, color=None):
""" Reads SVG from a file name and creates an QIcon from it.
Optionally replaces the color. Caches the created icons.
:param fileName: absolute path to an icon file.
If False/empty/None, None returned, which yields no icon.
:param color: '#RRGGBB' string (e.g. '#FF0000' for red)
:return: QtGui.QIcon
"""
if not fileName:
return None
key = (fileName, color)
if key not in self._icons:
try:
with open(fileName, 'r') as input:
svg = input.read()
self._icons[key] = self.createIconFromSvg(svg, color=color)
except Exception as ex:
# It's preferable to show no icon in case of an error rather than letting
# the application fail. Icons are a (very) nice to have.
logger.warn("Unable to read icon: {}".format(ex))
if DEBUGGING:
raise
else:
return None
return self._icons[key]
|
python
|
{
"resource": ""
}
|
q5712
|
RtiIconFactory.createIconFromSvg
|
train
|
def createIconFromSvg(self, svg, color=None, colorsToBeReplaced=None):
""" Creates a QIcon given an SVG string.
Optionally replaces the colors in colorsToBeReplaced by color.
:param svg: string containing Scalable Vector Graphics XML
:param color: '#RRGGBB' string (e.g. '#FF0000' for red)
:param colorsToBeReplaced: optional list of colors to be replaced by color
If None, it will be set to the fill colors of the snip-icon libary
:return: QtGui.QIcon
"""
if colorsToBeReplaced is None:
colorsToBeReplaced = self.colorsToBeReplaced
if color:
for oldColor in colorsToBeReplaced:
svg = svg.replace(oldColor, color)
# From http://stackoverflow.com/questions/15123544/change-the-color-of-an-svg-in-qt
qByteArray = QtCore.QByteArray()
qByteArray.append(svg)
svgRenderer = QtSvg.QSvgRenderer(qByteArray)
icon = QtGui.QIcon()
for size in self.renderSizes:
pixMap = QtGui.QPixmap(QtCore.QSize(size, size))
pixMap.fill(Qt.transparent)
pixPainter = QtGui.QPainter(pixMap)
pixPainter.setRenderHint(QtGui.QPainter.TextAntialiasing, True)
pixPainter.setRenderHint(QtGui.QPainter.Antialiasing, True)
svgRenderer.render(pixPainter)
pixPainter.end()
icon.addPixmap(pixMap)
return icon
|
python
|
{
"resource": ""
}
|
q5713
|
RegistryTableProxyModel.lessThan
|
train
|
def lessThan(self, leftIndex, rightIndex):
""" Returns true if the value of the item referred to by the given index left is less than
the value of the item referred to by the given index right, otherwise returns false.
"""
leftData = self.sourceModel().data(leftIndex, RegistryTableModel.SORT_ROLE)
rightData = self.sourceModel().data(rightIndex, RegistryTableModel.SORT_ROLE)
return leftData < rightData
|
python
|
{
"resource": ""
}
|
q5714
|
RegistryTableProxyModel.itemFromIndex
|
train
|
def itemFromIndex(self, index):
""" Gets the item given the model index
"""
sourceIndex = self.mapToSource(index)
return self.sourceModel().itemFromIndex(sourceIndex)
|
python
|
{
"resource": ""
}
|
q5715
|
RegistryTableView.setCurrentRegItem
|
train
|
def setCurrentRegItem(self, regItem):
""" Sets the current registry item.
"""
rowIndex = self.model().indexFromItem(regItem)
if not rowIndex.isValid():
logger.warn("Can't select {!r} in table".format(regItem))
self.setCurrentIndex(rowIndex)
|
python
|
{
"resource": ""
}
|
q5716
|
persistentRegisterInspector
|
train
|
def persistentRegisterInspector(fullName, fullClassName, pythonPath=''):
""" Registers an inspector
Loads or inits the inspector registry, register the inspector and saves the settings.
Important: instantiate a Qt application first to use the correct settings file/winreg.
"""
registry = InspectorRegistry()
registry.loadOrInitSettings()
registry.registerInspector(fullName, fullClassName, pythonPath=pythonPath)
registry.saveSettings()
|
python
|
{
"resource": ""
}
|
q5717
|
printInspectors
|
train
|
def printInspectors():
""" Prints a list of inspectors
"""
# Imported here so this module can be imported without Qt being installed.
from argos.application import ArgosApplication
argosApp = ArgosApplication()
argosApp.loadOrInitRegistries()
for regItem in argosApp.inspectorRegistry.items:
print(regItem.fullName)
|
python
|
{
"resource": ""
}
|
q5718
|
ArgosTreeView.setModel
|
train
|
def setModel(self, model):
""" Sets the model.
Checks that the model is a
"""
check_class(model, BaseTreeModel)
super(ArgosTreeView, self).setModel(model)
|
python
|
{
"resource": ""
}
|
q5719
|
ArgosTreeView.expandBranch
|
train
|
def expandBranch(self, index=None, expanded=True):
""" Expands or collapses the node at the index and all it's descendants.
If expanded is True the nodes will be expanded, if False they will be collapsed.
If parentIndex is None, the invisible root will be used (i.e. the complete forest will
be expanded).
"""
treeModel = self.model()
if index is None:
index = QtCore.QModelIndex()
if index.isValid():
self.setExpanded(index, expanded)
for rowNr in range(treeModel.rowCount(index)):
childIndex = treeModel.index(rowNr, 0, parentIndex=index)
self.expandBranch(index=childIndex, expanded=expanded)
|
python
|
{
"resource": ""
}
|
q5720
|
Collector.blockChildrenSignals
|
train
|
def blockChildrenSignals(self, block):
""" If block equals True, the signals of the combo boxes and spin boxes are blocked
Returns the old blocking state.
"""
logger.debug("Blocking collector signals")
for spinBox in self._spinBoxes:
spinBox.blockSignals(block)
for comboBox in self._comboBoxes:
comboBox.blockSignals(block)
result = self._signalsBlocked
self._signalsBlocked = block
return result
|
python
|
{
"resource": ""
}
|
q5721
|
Collector._setColumnCountForContents
|
train
|
def _setColumnCountForContents(self):
""" Sets the column count given the current axes and selected RTI.
Returns the newly set column count.
"""
numRtiDims = self.rti.nDims if self.rti and self.rti.isSliceable else 0
colCount = self.COL_FIRST_COMBO + max(numRtiDims, len(self.axisNames))
self.tree.model().setColumnCount(colCount)
return colCount
|
python
|
{
"resource": ""
}
|
q5722
|
Collector.clear
|
train
|
def clear(self):
""" Removes all VisItems
"""
model = self.tree.model()
# Don't use model.clear(). it will delete the column sizes
model.removeRows(0, 1)
model.setRowCount(1)
self._setColumnCountForContents()
|
python
|
{
"resource": ""
}
|
q5723
|
Collector.clearAndSetComboBoxes
|
train
|
def clearAndSetComboBoxes(self, axesNames):
""" Removes all comboboxes.
"""
logger.debug("Collector clearAndSetComboBoxes: {}".format(axesNames))
check_is_a_sequence(axesNames)
row = 0
self._deleteComboBoxes(row)
self.clear()
self._setAxesNames(axesNames)
self._createComboBoxes(row)
self._updateWidgets()
|
python
|
{
"resource": ""
}
|
q5724
|
Collector._setAxesNames
|
train
|
def _setAxesNames(self, axisNames):
""" Sets the axesnames, combobox lables and updates the headers. Removes old values first.
The comboLables is the axes name + '-axis'
"""
for col, _ in enumerate(self._fullAxisNames, self.COL_FIRST_COMBO):
self._setHeaderLabel(col, '')
self._axisNames = tuple(axisNames)
self._fullAxisNames = tuple([axName + self.AXIS_POST_FIX for axName in axisNames])
for col, label in enumerate(self._fullAxisNames, self.COL_FIRST_COMBO):
self._setHeaderLabel(col, label)
|
python
|
{
"resource": ""
}
|
q5725
|
Collector._setHeaderLabel
|
train
|
def _setHeaderLabel(self, col, text):
""" Sets the header of column col to text.
Will increase the number of columns if col is larger than the current number.
"""
model = self.tree.model()
item = model.horizontalHeaderItem(col)
if item:
item.setText(text)
else:
model.setHorizontalHeaderItem(col, QtGui.QStandardItem(text))
|
python
|
{
"resource": ""
}
|
q5726
|
Collector.setRti
|
train
|
def setRti(self, rti):
""" Updates the current VisItem from the contents of the repo tree item.
Is a slot but the signal is usually connected to the Collector, which then calls
this function directly.
"""
check_class(rti, BaseRti)
#assert rti.isSliceable, "RTI must be sliceable" # TODO: maybe later
self._rti = rti
self._updateWidgets()
self._updateRtiInfo()
|
python
|
{
"resource": ""
}
|
q5727
|
Collector._updateWidgets
|
train
|
def _updateWidgets(self):
""" Updates the combo and spin boxes given the new rti or axes.
Emits the sigContentsChanged signal.
"""
row = 0
model = self.tree.model()
# Create path label
nodePath = '' if self.rti is None else self.rti.nodePath
pathItem = QtGui.QStandardItem(nodePath)
pathItem.setToolTip(nodePath)
pathItem.setEditable(False)
if self.rti is not None:
pathItem.setIcon(self.rti.decoration)
model.setItem(row, 0, pathItem)
self._deleteSpinBoxes(row)
self._populateComboBoxes(row)
self._createSpinBoxes(row)
self._updateRtiInfo()
self.tree.resizeColumnsToContents(startCol=self.COL_FIRST_COMBO)
logger.debug("{} sigContentsChanged signal (_updateWidgets)"
.format("Blocked" if self.signalsBlocked() else "Emitting"))
self.sigContentsChanged.emit(UpdateReason.RTI_CHANGED)
|
python
|
{
"resource": ""
}
|
q5728
|
Collector._createComboBoxes
|
train
|
def _createComboBoxes(self, row):
""" Creates a combo box for each of the fullAxisNames
"""
tree = self.tree
model = self.tree.model()
self._setColumnCountForContents()
for col, _ in enumerate(self._axisNames, self.COL_FIRST_COMBO):
logger.debug("Adding combobox at ({}, {})".format(row, col))
comboBox = QtWidgets.QComboBox()
comboBox.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
comboBox.activated.connect(self._comboBoxActivated)
self._comboBoxes.append(comboBox)
#editor = LabeledWidget(QtWidgets.QLabel(comboLabel), comboBox)
tree.setIndexWidget(model.index(row, col), comboBox)
|
python
|
{
"resource": ""
}
|
q5729
|
Collector._deleteComboBoxes
|
train
|
def _deleteComboBoxes(self, row):
""" Deletes all comboboxes of a row
"""
tree = self.tree
model = self.tree.model()
for col in range(self.COL_FIRST_COMBO, self.maxCombos):
logger.debug("Removing combobox at: ({}, {})".format(row, col))
tree.setIndexWidget(model.index(row, col), None)
self._comboBoxes = []
|
python
|
{
"resource": ""
}
|
q5730
|
Collector._populateComboBoxes
|
train
|
def _populateComboBoxes(self, row):
""" Populates the combo boxes with values of the repo tree item
"""
logger.debug("_populateComboBoxes")
for comboBox in self._comboBoxes:
comboBox.clear()
if not self.rtiIsSliceable:
# Add an empty item to the combo boxes so that resize to contents works.
for comboBoxNr, comboBox in enumerate(self._comboBoxes):
comboBox.addItem('', userData=None)
comboBox.setEnabled(False)
return
nDims = self._rti.nDims
nCombos = len(self._comboBoxes)
for comboBoxNr, comboBox in enumerate(self._comboBoxes):
# Add a fake dimension of length 1
comboBox.addItem(FAKE_DIM_NAME, userData = FAKE_DIM_OFFSET + comboBoxNr)
for dimNr in range(nDims):
comboBox.addItem(self._rti.dimensionNames[dimNr], userData=dimNr)
# Set combobox current index
if nDims >= nCombos:
# We set the nth combo-box index to the last item - n. This because the
# NetCDF-CF conventions have the preferred dimension order of T, Z, Y, X.
# The +1 below is from the fake dimension.
curIdx = nDims + 1 - nCombos + comboBoxNr
else:
# If there are less dimensions in the RTI than the inspector can show, we fill
# the comboboxes starting at the leftmost and set the remaining comboboxes to the
# fake dimension. This means that a table inspector fill have one column and many
# rows, which is the most convenient.
curIdx = comboBoxNr + 1 if comboBoxNr < nDims else 0
assert 0 <= curIdx <= nDims + 1, \
"curIdx should be <= {}, got {}".format(nDims + 1, curIdx)
comboBox.setCurrentIndex(curIdx)
comboBox.setEnabled(True)
|
python
|
{
"resource": ""
}
|
q5731
|
Collector._dimensionSelectedInComboBox
|
train
|
def _dimensionSelectedInComboBox(self, dimNr):
""" Returns True if the dimension is selected in one of the combo boxes.
"""
for combobox in self._comboBoxes:
if self._comboBoxDimensionIndex(combobox) == dimNr:
return True
return False
|
python
|
{
"resource": ""
}
|
q5732
|
Collector._createSpinBoxes
|
train
|
def _createSpinBoxes(self, row):
""" Creates a spinBox for each dimension that is not selected in a combo box.
"""
assert len(self._spinBoxes) == 0, "Spinbox list not empty. Call _deleteSpinBoxes first"
if not self.rtiIsSliceable:
return
logger.debug("_createSpinBoxes, array shape: {}".format(self._rti.arrayShape))
self._setColumnCountForContents()
tree = self.tree
model = self.tree.model()
col = self.COL_FIRST_COMBO + self.maxCombos
for dimNr, dimSize in enumerate(self._rti.arrayShape):
if self._dimensionSelectedInComboBox(dimNr):
continue
self._setHeaderLabel(col, '')
spinBox = CollectorSpinBox()
self._spinBoxes.append(spinBox)
spinBox.setKeyboardTracking(False)
spinBox.setCorrectionMode(QtWidgets.QAbstractSpinBox.CorrectToNearestValue)
spinBox.setMinimum(0)
spinBox.setMaximum(dimSize - 1)
spinBox.setSingleStep(1)
spinBox.setValue(dimSize // 2) # select the middle of the slice
spinBox.setPrefix("{}: ".format(self._rti.dimensionNames[dimNr]))
spinBox.setSuffix("/{}".format(spinBox.maximum()))
spinBox.setProperty("dim_nr", dimNr)
#spinBox.adjustSize() # necessary?
# This must be done after setValue to prevent emitting too many signals
spinBox.valueChanged[int].connect(self._spinboxValueChanged)
tree.setIndexWidget(model.index(row, col), spinBox)
col += 1
# Resize the spinbox columns to their new contents
self.tree.resizeColumnsToContents(startCol=self.COL_FIRST_COMBO + self.maxCombos)
|
python
|
{
"resource": ""
}
|
q5733
|
Collector._deleteSpinBoxes
|
train
|
def _deleteSpinBoxes(self, row):
""" Removes all spinboxes
"""
tree = self.tree
model = self.tree.model()
for col, spinBox in enumerate(self._spinBoxes, self.COL_FIRST_COMBO + self.maxCombos):
spinBox.valueChanged[int].disconnect(self._spinboxValueChanged)
tree.setIndexWidget(model.index(row, col), None)
self._spinBoxes = []
self._setColumnCountForContents()
|
python
|
{
"resource": ""
}
|
q5734
|
Collector._comboBoxActivated
|
train
|
def _comboBoxActivated(self, index, comboBox=None):
""" Is called when a combo box value was changed by the user.
Updates the spin boxes and sets other combo boxes having the same index to
the fake dimension of length 1.
"""
if comboBox is None:
comboBox = self.sender()
assert comboBox, "comboBox not defined and not the sender"
blocked = self.blockChildrenSignals(True)
# If one of the other combo boxes has the same value, set it to the fake dimension
curDimIdx = self._comboBoxDimensionIndex(comboBox)
if curDimIdx < FAKE_DIM_OFFSET:
otherComboBoxes = [cb for cb in self._comboBoxes if cb is not comboBox]
for otherComboBox in otherComboBoxes:
if otherComboBox.currentIndex() == comboBox.currentIndex():
#newIdx = otherComboBox.findData(FAKE_DIM_IDX)
#otherComboBox.setCurrentIndex(newIdx)
otherComboBox.setCurrentIndex(0) # Fake dimension is always the first
# Show only spin boxes that are not selected
row = 0
self._deleteSpinBoxes(row)
self._createSpinBoxes(row)
self._updateRtiInfo()
self.blockChildrenSignals(blocked)
logger.debug("{} sigContentsChanged signal (comboBox)"
.format("Blocked" if self.signalsBlocked() else "Emitting"))
self.sigContentsChanged.emit(UpdateReason.COLLECTOR_COMBO_BOX)
|
python
|
{
"resource": ""
}
|
q5735
|
Collector._spinboxValueChanged
|
train
|
def _spinboxValueChanged(self, index, spinBox=None):
""" Is called when a spin box value was changed.
Updates the spin boxes and sets other combo boxes having the same index to
the fake dimension of length 1.
"""
if spinBox is None:
spinBox = self.sender()
assert spinBox, "spinBox not defined and not the sender"
logger.debug("{} sigContentsChanged signal (spinBox)"
.format("Blocked" if self.signalsBlocked() else "Emitting"))
self.sigContentsChanged.emit(UpdateReason.COLLECTOR_SPIN_BOX)
|
python
|
{
"resource": ""
}
|
q5736
|
Collector.getSlicedArray
|
train
|
def getSlicedArray(self, copy=True):
""" Slice the rti using a tuple of slices made from the values of the combo and spin boxes.
:param copy: If True (the default), a copy is made so that inspectors cannot
accidentally modify the underlying of the RTIs. You can set copy=False as a
potential optimization, but only if you are absolutely sure that you don't modify
the the slicedArray in your inspector! Note that this function calls transpose,
which can still make a copy of the array for certain permutations.
:return: Numpy masked array with the same number of dimension as the number of
comboboxes (this can be zero!).
Returns None if no slice can be made (i.e. the RTI is not sliceable).
"""
#logger.debug("getSlicedArray() called")
if not self.rtiIsSliceable:
return None
# The dimensions that are selected in the combo boxes will be set to slice(None),
# the values from the spin boxes will be set as a single integer value
nDims = self.rti.nDims
sliceList = [slice(None)] * nDims
for spinBox in self._spinBoxes:
dimNr = spinBox.property("dim_nr")
sliceList[dimNr] = spinBox.value()
# Make the array slicer. It needs to be a tuple, a list of only integers will be
# interpreted as an index. With a tuple, array[(exp1, exp2, ..., expN)] is equivalent to
# array[exp1, exp2, ..., expN].
# See: http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
logger.debug("Array slice list: {}".format(str(sliceList)))
slicedArray = self.rti[tuple(sliceList)]
# Make a copy to prevent inspectors from modifying the underlying array.
if copy:
slicedArray = ma.copy(slicedArray)
# If there are no comboboxes the sliceList will contain no Slices objects, only ints. Then
# the resulting slicedArray will be a usually a scalar (only structured fields may yield an
# array). We convert this scalar to a zero-dimensional Numpy array so that inspectors
# always get an array (having the same number of dimensions as the dimensionality of the
# inspector, i.e. the number of comboboxes).
if self.maxCombos == 0:
slicedArray = ma.MaskedArray(slicedArray)
# Post-condition type check
check_is_an_array(slicedArray, np.ndarray)
# Enforce the return type to be a masked array.
if not isinstance(slicedArray, ma.MaskedArray):
slicedArray = ma.MaskedArray(slicedArray)
# Add fake dimensions of length 1 so that result.ndim will equal the number of combo boxes
for dimNr in range(slicedArray.ndim, self.maxCombos):
#logger.debug("Adding fake dimension: {}".format(dimNr))
slicedArray = ma.expand_dims(slicedArray, dimNr)
# Post-condition dimension check
assert slicedArray.ndim == self.maxCombos, \
"Bug: getSlicedArray should return a {:d}D array, got: {}D" \
.format(self.maxCombos, slicedArray.ndim)
# Convert to ArrayWithMask class for working around issues with the numpy maskedarray
awm = ArrayWithMask.createFromMaskedArray(slicedArray)
del slicedArray
# Shuffle the dimensions to be in the order as specified by the combo boxes
comboDims = [self._comboBoxDimensionIndex(cb) for cb in self._comboBoxes]
permutations = np.argsort(comboDims)
logger.debug("slicedArray.shape: {}".format(awm.data.shape))
logger.debug("Transposing dimensions: {}".format(permutations))
awm = awm.transpose(permutations)
awm.checkIsConsistent()
return awm
|
python
|
{
"resource": ""
}
|
q5737
|
Collector._updateRtiInfo
|
train
|
def _updateRtiInfo(self):
""" Updates the _rtiInfo property when a new RTI is set or the comboboxes value change.
"""
logger.debug("Updating self._rtiInfo")
# Info about the dependent dimension
rti = self.rti
if rti is None:
info = {'slices': '',
'name': '',
'path': '',
'file-name': '',
'dir-name': '',
'base-name': '',
'unit': '',
'raw-unit': ''}
else:
dirName, baseName = os.path.split(rti.fileName)
info = {'slices': self.getSlicesString(),
'name': rti.nodeName,
'path': rti.nodePath,
'file-name': rti.fileName,
'dir-name': dirName,
'base-name': baseName,
'unit': '({})'.format(rti.unit) if rti.unit else '',
'raw-unit': rti.unit}
# Add the info of the independent dimensions (appended with the axis name of that dim).
for axisName, comboBox in zip(self._axisNames, self._comboBoxes):
dimName = comboBox.currentText()
key = '{}-dim'.format(axisName.lower())
info[key] = dimName
self._rtiInfo = info
|
python
|
{
"resource": ""
}
|
q5738
|
FieldRti._subArrayShape
|
train
|
def _subArrayShape(self):
""" Returns the shape of the sub-array.
An empty tuple is returned for regular fields, which have no sub array.
"""
fieldName = self.nodeName
fieldDtype = self._array.dtype.fields[fieldName][0]
return fieldDtype.shape
|
python
|
{
"resource": ""
}
|
q5739
|
FieldRti.missingDataValue
|
train
|
def missingDataValue(self):
""" Returns the value to indicate missing data.
"""
value = getMissingDataValue(self._array)
fieldNames = self._array.dtype.names
# If the missing value attibute is a list with the same length as the number of fields,
# return the missing value for field that equals the self.nodeName.
if hasattr(value, '__len__') and len(value) == len(fieldNames):
idx = fieldNames.index(self.nodeName)
return value[idx]
else:
return value
|
python
|
{
"resource": ""
}
|
q5740
|
SyntheticArrayRti._openResources
|
train
|
def _openResources(self):
""" Evaluates the function to result an array
"""
arr = self._fun()
check_is_an_array(arr)
self._array = arr
|
python
|
{
"resource": ""
}
|
q5741
|
SequenceRti._fetchAllChildren
|
train
|
def _fetchAllChildren(self):
""" Adds a child item for each column
"""
childItems = []
for nr, elem in enumerate(self._sequence):
childItem = _createFromObject(elem, "elem-{}".format(nr), self.fileName)
childItem._iconColor = self.iconColor
childItems.append(childItem)
return childItems
|
python
|
{
"resource": ""
}
|
q5742
|
MappingRti._fetchAllChildren
|
train
|
def _fetchAllChildren(self):
""" Adds a child item for each item
"""
childItems = []
logger.debug("{!r} _fetchAllChildren {!r}".format(self, self.fileName))
if self.hasChildren():
for key, value in sorted(self._dictionary.items()):
# TODO: pass the attributes to the children? (probably not)
childItem = _createFromObject(value, str(key), self.fileName)
childItem._iconColor = self.iconColor
childItems.append(childItem)
return childItems
|
python
|
{
"resource": ""
}
|
q5743
|
IntCti.createEditor
|
train
|
def createEditor(self, delegate, parent, option):
""" Creates a IntCtiEditor.
For the parameters see the AbstractCti constructor documentation.
"""
return IntCtiEditor(self, delegate, parent=parent)
|
python
|
{
"resource": ""
}
|
q5744
|
MainWindow.__setupViews
|
train
|
def __setupViews(self):
""" Creates the UI widgets.
"""
self._collector = Collector(self.windowNumber)
self.configWidget = ConfigWidget(self._configTreeModel)
self.repoWidget = RepoWidget(self.argosApplication.repo, self.collector)
# self._configTreeModel.insertItem(self.repoWidget.repoTreeView.config) # No configurable items yet
# Define a central widget that will be the parent of the inspector widget.
# We don't set the inspector directly as the central widget to retain the size when the
# inspector is changed.
widget = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout(widget)
layout.setContentsMargins(CENTRAL_MARGIN, CENTRAL_MARGIN, CENTRAL_MARGIN, CENTRAL_MARGIN)
layout.setSpacing(CENTRAL_SPACING)
self.setCentralWidget(widget)
# Must be after setInspector since that already draws the inspector
self.collector.sigContentsChanged.connect(self.collectorContentsChanged)
self._configTreeModel.sigItemChanged.connect(self.configContentsChanged)
|
python
|
{
"resource": ""
}
|
q5745
|
MainWindow.__createInspectorActionGroup
|
train
|
def __createInspectorActionGroup(self, parent):
""" Creates an action group with 'set inspector' actions for all installed inspector.
"""
actionGroup = QtWidgets.QActionGroup(parent)
actionGroup.setExclusive(True)
sortedItems = sorted(self.argosApplication.inspectorRegistry.items,
key=lambda item: item.identifier)
shortCutNr = 1
for item in sortedItems:
logger.debug("item: {}".format(item.identifier))
setAndDrawFn = partial(self.setAndDrawInspectorById, item.identifier)
action = QtWidgets.QAction(item.name, self, triggered=setAndDrawFn, checkable=True)
action.setData(item.identifier)
if shortCutNr <= 9 and "debug" not in item.identifier: # TODO: make configurable by the user
action.setShortcut(QtGui.QKeySequence("Ctrl+{}".format(shortCutNr)))
shortCutNr += 1
actionGroup.addAction(action)
return actionGroup
|
python
|
{
"resource": ""
}
|
q5746
|
MainWindow.__setupDockWidgets
|
train
|
def __setupDockWidgets(self):
""" Sets up the dock widgets. Must be called after the menu is setup.
"""
#self.dockWidget(self.currentInspectorPane, "Current Inspector", Qt.LeftDockWidgetArea)
self.inspectorSelectionPane = InspectorSelectionPane(self.execInspectorDialogAction,
self.inspectorActionGroup)
self.sigInspectorChanged.connect(self.inspectorSelectionPane.updateFromInspectorRegItem)
self.dockWidget(self.inspectorSelectionPane, "Current Inspector",
area=Qt.LeftDockWidgetArea)
self.dockWidget(self.repoWidget, "Data Repository", Qt.LeftDockWidgetArea)
self.dockWidget(self.collector, "Data Collector", Qt.TopDockWidgetArea)
# TODO: if the title == "Settings" it won't be added to the view menu.
self.dockWidget(self.configWidget, "Application Settings", Qt.RightDockWidgetArea)
self.viewMenu.addSeparator()
propertiesPane = PropertiesPane(self.repoWidget.repoTreeView)
self.dockDetailPane(propertiesPane, area=Qt.LeftDockWidgetArea)
attributesPane = AttributesPane(self.repoWidget.repoTreeView)
self.dockDetailPane(attributesPane, area=Qt.LeftDockWidgetArea)
dimensionsPane = DimensionsPane(self.repoWidget.repoTreeView)
self.dockDetailPane(dimensionsPane, area=Qt.LeftDockWidgetArea)
# Add am extra separator on mac because OS-X adds an 'Enter Full Screen' item
if sys.platform.startswith('darwin'):
self.viewMenu.addSeparator()
|
python
|
{
"resource": ""
}
|
q5747
|
MainWindow.repopulateWinowMenu
|
train
|
def repopulateWinowMenu(self, actionGroup):
""" Clear the window menu and fills it with the actions of the actionGroup
"""
for action in self.windowMenu.actions():
self.windowMenu.removeAction(action)
for action in actionGroup.actions():
self.windowMenu.addAction(action)
|
python
|
{
"resource": ""
}
|
q5748
|
MainWindow.showContextMenu
|
train
|
def showContextMenu(self, pos):
""" Shows the context menu at position pos.
"""
contextMenu = QtWidgets.QMenu()
addInspectorActionsToMenu(contextMenu, self.execInspectorDialogAction,
self.inspectorActionGroup)
contextMenu.exec_(self.mapToGlobal(pos))
|
python
|
{
"resource": ""
}
|
q5749
|
MainWindow.dockWidget
|
train
|
def dockWidget(self, widget, title, area):
""" Adds a widget as a docked widget.
Returns the added dockWidget
"""
assert widget.parent() is None, "Widget already has a parent"
dockWidget = QtWidgets.QDockWidget(title, parent=self)
dockWidget.setObjectName("dock_" + string_to_identifier(title))
dockWidget.setWidget(widget)
# Prevent parent context menu (with e.g. 'set inspector" option) to be displayed.
dockWidget.setContextMenuPolicy(Qt.PreventContextMenu)
self.addDockWidget(area, dockWidget)
self.viewMenu.addAction(dockWidget.toggleViewAction())
return dockWidget
|
python
|
{
"resource": ""
}
|
q5750
|
MainWindow.dockDetailPane
|
train
|
def dockDetailPane(self, detailPane, title=None, area=None):
""" Creates a dockWidget and add the detailPane with a default title.
By default the detail widget is added to the Qt.LeftDockWidgetArea.
"""
title = detailPane.classLabel() if title is None else title
area = Qt.LeftDockWidgetArea if area is None else area
dockWidget = self.dockWidget(detailPane, title, area)
# TODO: undockDetailPane to disconnect
dockWidget.visibilityChanged.connect(detailPane.dockVisibilityChanged)
if len(self._detailDockWidgets) > 0:
self.tabifyDockWidget(self._detailDockWidgets[-1], dockWidget)
self._detailDockWidgets.append(dockWidget)
return dockWidget
|
python
|
{
"resource": ""
}
|
q5751
|
MainWindow.updateWindowTitle
|
train
|
def updateWindowTitle(self):
""" Updates the window title frm the window number, inspector, etc
Also updates the Window Menu
"""
self.setWindowTitle("{} #{} | {}-{}".format(self.inspectorName, self.windowNumber,
PROJECT_NAME, self.argosApplication.profile))
#self.activateWindowAction.setText("{} window".format(self.inspectorName, self.windowNumber))
self.activateWindowAction.setText("{} window".format(self.inspectorName))
|
python
|
{
"resource": ""
}
|
q5752
|
MainWindow.execInspectorDialog
|
train
|
def execInspectorDialog(self):
""" Opens the inspector dialog box to let the user change the current inspector.
"""
dialog = OpenInspectorDialog(self.argosApplication.inspectorRegistry, parent=self)
dialog.setCurrentInspectorRegItem(self.inspectorRegItem)
dialog.exec_()
if dialog.result():
inspectorRegItem = dialog.getCurrentInspectorRegItem()
if inspectorRegItem is not None:
self.getInspectorActionById(inspectorRegItem.identifier).trigger()
|
python
|
{
"resource": ""
}
|
q5753
|
MainWindow.getInspectorActionById
|
train
|
def getInspectorActionById(self, identifier):
""" Sets the inspector and draw the contents
Triggers the corresponding action so that it is checked in the menus.
"""
for action in self.inspectorActionGroup.actions():
if action.data() == identifier:
return action
raise KeyError("No action found with ID: {!r}".format(identifier))
|
python
|
{
"resource": ""
}
|
q5754
|
MainWindow.setAndDrawInspectorById
|
train
|
def setAndDrawInspectorById(self, identifier):
""" Sets the inspector and draw the contents.
Does NOT trigger any actions, so the check marks in the menus are not updated. To
achieve this, the user must update the actions by hand (or call
getInspectorActionById(identifier).trigger() instead).
"""
self.setInspectorById(identifier)
# Show dialog box if import was unsuccessful.
regItem = self.inspectorRegItem
if regItem and not regItem.successfullyImported:
msg = "Unable to import {} inspector.\n{}".format(regItem.identifier, regItem.exception)
QtWidgets.QMessageBox.warning(self, "Warning", msg)
logger.warn(msg)
self.drawInspectorContents(reason=UpdateReason.INSPECTOR_CHANGED)
|
python
|
{
"resource": ""
}
|
q5755
|
MainWindow.setInspectorById
|
train
|
def setInspectorById(self, identifier):
""" Sets the central inspector widget given a inspector ID.
If identifier is None, the inspector will be unset. Otherwise it will lookup the
inspector class in the registry. It will raise a KeyError if the ID is not found there.
It will do an import of the inspector code if it's loaded for the first time. If the
the inspector class cannot be imported a warning is logged and the inspector is unset.
NOTE: does not draw the new inspector, this is the responsibility of the caller.
Also, the corresponding action is not triggered.
Emits the sigInspectorChanged(self.inspectorRegItem)
"""
logger.info("Setting inspector: {}".format(identifier))
# Use the identifier to find a registered inspector and set self.inspectorRegItem.
# Then create an inspector object from it.
oldInspectorRegItem = self.inspectorRegItem
oldInspector = self.inspector
if not identifier:
inspector = None
self._inspectorRegItem = None
else:
inspectorRegistry = self.argosApplication.inspectorRegistry
inspectorRegItem = inspectorRegistry.getItemById(identifier)
self._inspectorRegItem = inspectorRegItem
if inspectorRegItem is None:
inspector = None
else:
try:
inspector = inspectorRegItem.create(self.collector, tryImport=True)
except ImportError as ex:
# Only log the error. No dialog box or user interaction here because this
# function may be called at startup.
logger.exception("Clearing inspector. Unable to create {!r} because {}"
.format(inspectorRegItem.identifier, ex))
inspector = None
self.getInspectorActionById(identifier).setEnabled(False)
if DEBUGGING:
raise
######################
# Set self.inspector #
######################
check_class(inspector, AbstractInspector, allow_none=True)
logger.debug("Disabling updates.")
self.setUpdatesEnabled(False)
try:
centralLayout = self.centralWidget().layout()
# Delete old inspector
if oldInspector is None: # can be None at start-up
oldConfigPosition = None # Last top level element in the config tree.
else:
self._updateNonDefaultsForInspector(oldInspectorRegItem, oldInspector)
# Remove old inspector configuration from tree
oldConfigPosition = oldInspector.config.childNumber()
configPath = oldInspector.config.nodePath
_, oldConfigIndex = self._configTreeModel.findItemAndIndexPath(configPath)[-1]
self._configTreeModel.deleteItemAtIndex(oldConfigIndex)
oldInspector.finalize() # TODO: before removing config
centralLayout.removeWidget(oldInspector)
oldInspector.deleteLater()
# Set new inspector
self._inspector = inspector
# Update collector widgets and the config tree
oldBlockState = self.collector.blockSignals(True)
try:
if self.inspector is None:
self.collector.clearAndSetComboBoxes([])
else:
# Add and apply config values to the inspector
key = self.inspectorRegItem.identifier
nonDefaults = self._inspectorsNonDefaults.get(key, {})
logger.debug("Setting non defaults: {}".format(nonDefaults))
self.inspector.config.setValuesFromDict(nonDefaults)
self._configTreeModel.insertItem(self.inspector.config, oldConfigPosition)
self.configWidget.configTreeView.expandBranch()
self.collector.clearAndSetComboBoxes(self.inspector.axesNames())
centralLayout.addWidget(self.inspector)
finally:
self.collector.blockSignals(oldBlockState)
finally:
logger.debug("Enabling updates.")
self.setUpdatesEnabled(True)
self.updateWindowTitle()
logger.debug("Emitting sigInspectorChanged({})".format(self.inspectorRegItem))
self.sigInspectorChanged.emit(self.inspectorRegItem)
|
python
|
{
"resource": ""
}
|
q5756
|
MainWindow.execPluginsDialog
|
train
|
def execPluginsDialog(self):
""" Shows the plugins dialog with the registered plugins
"""
pluginsDialog = PluginsDialog(parent=self,
inspectorRegistry=self.argosApplication.inspectorRegistry,
rtiRegistry=self.argosApplication.rtiRegistry)
pluginsDialog.exec_()
|
python
|
{
"resource": ""
}
|
q5757
|
MainWindow.configContentsChanged
|
train
|
def configContentsChanged(self, configTreeItem):
""" Slot is called when an item has been changed by setData of the ConfigTreeModel.
Will draw the window contents.
"""
logger.debug("configContentsChanged: {}".format(configTreeItem))
self.drawInspectorContents(reason=UpdateReason.CONFIG_CHANGED,
origin=configTreeItem)
|
python
|
{
"resource": ""
}
|
q5758
|
MainWindow.drawInspectorContents
|
train
|
def drawInspectorContents(self, reason, origin=None):
""" Draws all contents of this window's inspector.
The reason and origin parameters are passed on to the inspector's updateContents method.
:param reason: string describing the reason for the redraw.
Should preferably be one of the UpdateReason enumeration class, but new values may
be used (which are then ignored by existing inspectors).
:param origin: object with extra infor on the reason
"""
logger.debug("")
logger.debug("-------- Drawing inspector of window: {} --------".format(self.windowTitle()))
if self.inspector:
self.inspector.updateContents(reason=reason, initiator=origin)
else:
logger.debug("No inspector selected")
logger.debug("Finished draw inspector.\n")
|
python
|
{
"resource": ""
}
|
q5759
|
MainWindow.openFiles
|
train
|
def openFiles(self, fileNames=None, rtiRegItem=None, caption=None, fileMode=None):
""" Lets the user select on or more files and opens it.
:param fileNames: If None an open-file dialog allows the user to select files,
otherwise the files are opened directly.
:param rtiRegItem: Open the files as this type of registered RTI. None=autodetect.
:param caption: Optional caption for the file dialog.
:param fileMode: is passed to the file dialog.
:rtype fileMode: QtWidgets.QFileDialog.FileMode constant
"""
if fileNames is None:
dialog = QtWidgets.QFileDialog(self, caption=caption)
if rtiRegItem is None:
nameFilter = 'All files (*);;' # Default show all files.
nameFilter += self.argosApplication.rtiRegistry.getFileDialogFilter()
else:
nameFilter = rtiRegItem.getFileDialogFilter()
nameFilter += ';;All files (*)'
dialog.setNameFilter(nameFilter)
if fileMode:
dialog.setFileMode(fileMode)
if dialog.exec_() == QtWidgets.QFileDialog.Accepted:
fileNames = dialog.selectedFiles()
else:
fileNames = []
fileRootIndex = None
for fileName in fileNames:
rtiClass = rtiRegItem.getClass(tryImport=True) if rtiRegItem else None
fileRootIndex = self.argosApplication.repo.loadFile(fileName, rtiClass=rtiClass)
self.repoWidget.repoTreeView.setExpanded(fileRootIndex, True)
# Select last opened file
if fileRootIndex is not None:
self.repoWidget.repoTreeView.setCurrentIndex(fileRootIndex)
|
python
|
{
"resource": ""
}
|
q5760
|
MainWindow.trySelectRtiByPath
|
train
|
def trySelectRtiByPath(self, path):
""" Selects a repository tree item given a path, expanding nodes if along the way if needed.
Returns (item, index) if the path was selected successfully, else a warning is logged
and (None, None) is returned.
"""
try:
lastItem, lastIndex = self.repoWidget.repoTreeView.expandPath(path)
self.repoWidget.repoTreeView.setCurrentIndex(lastIndex)
return lastItem, lastIndex
except Exception as ex:
logger.warn("Unable to select {!r} because: {}".format(path, ex))
if DEBUGGING:
raise
return None, None
|
python
|
{
"resource": ""
}
|
q5761
|
MainWindow.saveProfile
|
train
|
def saveProfile(self, settings=None):
""" Writes the view settings to the persistent store
"""
self._updateNonDefaultsForInspector(self.inspectorRegItem, self.inspector)
if settings is None:
settings = QtCore.QSettings()
logger.debug("Writing settings to: {}".format(settings.group()))
settings.beginGroup('cfg_inspectors')
try:
for key, nonDefaults in self._inspectorsNonDefaults.items():
if nonDefaults:
settings.setValue(key, ctiDumps(nonDefaults))
logger.debug("Writing non defaults for {}: {}".format(key, nonDefaults))
finally:
settings.endGroup()
self.configWidget.configTreeView.saveProfile("config_tree/header_state", settings)
self.repoWidget.repoTreeView.saveProfile("repo_tree/header_state", settings)
settings.setValue("geometry", self.saveGeometry())
settings.setValue("state", self.saveState())
identifier = self.inspectorRegItem.identifier if self.inspectorRegItem else ''
settings.setValue("inspector", identifier)
|
python
|
{
"resource": ""
}
|
q5762
|
MainWindow.cloneWindow
|
train
|
def cloneWindow(self):
""" Opens a new window with the same inspector as the current window.
"""
# Save current window settings.
settings = QtCore.QSettings()
settings.beginGroup(self.argosApplication.windowGroupName(self.windowNumber))
try:
self.saveProfile(settings)
# Create new window with the freshly baked settings of the current window.
name = self.inspectorRegItem.fullName
newWindow = self.argosApplication.addNewMainWindow(settings=settings,
inspectorFullName=name)
finally:
settings.endGroup()
# Select the current item in the new window.
currentItem, _currentIndex = self.repoWidget.repoTreeView.getCurrentItem()
if currentItem:
newWindow.trySelectRtiByPath(currentItem.nodePath)
# Move the new window 24 pixels to the bottom right and raise it to the front.
newGeomRect = newWindow.geometry()
logger.debug("newGeomRect: x={}".format(newGeomRect.x()))
newGeomRect.moveTo(newGeomRect.x() + 24, newGeomRect.y() + 24)
newWindow.setGeometry(newGeomRect)
logger.debug("newGeomRect: x={}".format(newGeomRect.x()))
newWindow.raise_()
|
python
|
{
"resource": ""
}
|
q5763
|
MainWindow.activateAndRaise
|
train
|
def activateAndRaise(self):
""" Activates and raises the window.
"""
logger.debug("Activate and raising window: {}".format(self.windowNumber))
self.activateWindow()
self.raise_()
|
python
|
{
"resource": ""
}
|
q5764
|
MainWindow.event
|
train
|
def event(self, ev):
""" Detects the WindowActivate event. Pass all event through to the super class.
"""
if ev.type() == QtCore.QEvent.WindowActivate:
logger.debug("Window activated: {}".format(self.windowNumber))
self.activateWindowAction.setChecked(True)
return super(MainWindow, self).event(ev);
|
python
|
{
"resource": ""
}
|
q5765
|
MainWindow.closeEvent
|
train
|
def closeEvent(self, event):
""" Called when closing this window.
"""
logger.debug("closeEvent")
self.argosApplication.saveSettingsIfNeeded()
self.finalize()
self.argosApplication.removeMainWindow(self)
event.accept()
logger.debug("closeEvent accepted")
|
python
|
{
"resource": ""
}
|
q5766
|
MainWindow.about
|
train
|
def about(self):
""" Shows the about message window.
"""
aboutDialog = AboutDialog(parent=self)
aboutDialog.show()
aboutDialog.addDependencyInfo()
|
python
|
{
"resource": ""
}
|
q5767
|
ArgosApplication.profileGroupName
|
train
|
def profileGroupName(self, profile=None):
""" Returns the name of the QSetting group for the profile.
Converts to lower case and removes whitespace, interpunction, etc.
Prepends _debug_ if the debugging flag is set
:param profile: profile name. If None the current profile is used.
"""
profile = profile if profile else self.profile
profGroupName = '_debug_' if DEBUGGING else ''
profGroupName += string_to_identifier(profile)
return profGroupName
|
python
|
{
"resource": ""
}
|
q5768
|
ArgosApplication.windowGroupName
|
train
|
def windowGroupName(self, windowNumber, profile=None):
""" Returns the name of the QSetting group for this window in the this profile.
:param windowNumber: int
:param profile: profile name. If None the current profile is used.
"""
return "{}/window-{:02d}".format(self.profileGroupName(profile=profile), windowNumber)
|
python
|
{
"resource": ""
}
|
q5769
|
ArgosApplication.deleteProfile
|
train
|
def deleteProfile(self, profile):
""" Removes a profile from the persistent settings
"""
profGroupName = self.profileGroupName(profile)
logger.debug("Resetting profile settings: {}".format(profGroupName))
settings = QtCore.QSettings()
settings.remove(profGroupName)
|
python
|
{
"resource": ""
}
|
q5770
|
ArgosApplication.deleteAllProfiles
|
train
|
def deleteAllProfiles(self):
""" Returns a list of all profiles
"""
settings = QtCore.QSettings()
for profGroupName in QtCore.QSettings().childGroups():
settings.remove(profGroupName)
|
python
|
{
"resource": ""
}
|
q5771
|
ArgosApplication.loadProfile
|
train
|
def loadProfile(self, profile, inspectorFullName=None):
""" Reads the persistent program settings for the current profile.
If inspectorFullName is given, a window with this inspector will be created if it wasn't
already created in the profile. All windows with this inspector will be raised.
"""
settings = QtCore.QSettings()
logger.info("Reading profile {!r} from: {}".format(profile, settings.fileName()))
self._profile = profile
profGroupName = self.profileGroupName(profile)
# Instantiate windows from groups
settings.beginGroup(profGroupName)
try:
for windowGroupName in settings.childGroups():
if windowGroupName.startswith('window'):
settings.beginGroup(windowGroupName)
try:
self.addNewMainWindow(settings=settings)
finally:
settings.endGroup()
finally:
settings.endGroup()
if inspectorFullName is not None:
windows = [win for win in self._mainWindows
if win.inspectorFullName == inspectorFullName]
if len(windows) == 0:
logger.info("Creating window for inspector: {!r}".format(inspectorFullName))
try:
win = self.addNewMainWindow(inspectorFullName=inspectorFullName)
except KeyError:
logger.warn("No inspector found with ID: {}".format(inspectorFullName))
else:
for win in windows:
win.raise_()
if len(self.mainWindows) == 0:
logger.info("No open windows in profile (creating one).")
self.addNewMainWindow(inspectorFullName=DEFAULT_INSPECTOR)
|
python
|
{
"resource": ""
}
|
q5772
|
ArgosApplication.saveProfile
|
train
|
def saveProfile(self):
""" Writes the current profile settings to the persistent store
"""
if not self.profile:
logger.warning("No profile defined (no settings saved)")
return
settings = QtCore.QSettings()
logger.debug("Writing settings to: {}".format(settings.fileName()))
profGroupName = self.profileGroupName()
settings.remove(profGroupName) # start with a clean slate
assert self.mainWindows, "no main windows found"
for winNr, mainWindow in enumerate(self.mainWindows):
settings.beginGroup(self.windowGroupName(winNr))
try:
mainWindow.saveProfile(settings)
finally:
settings.endGroup()
|
python
|
{
"resource": ""
}
|
q5773
|
ArgosApplication.saveSettings
|
train
|
def saveSettings(self):
""" Saves the persistent settings. Only saves the profile.
"""
try:
self.saveProfile()
except Exception as ex:
# Continue, even if saving the settings fails.
logger.warn(ex)
if DEBUGGING:
raise
finally:
self._settingsSaved = True
|
python
|
{
"resource": ""
}
|
q5774
|
ArgosApplication.loadFiles
|
train
|
def loadFiles(self, fileNames, rtiClass=None):
""" Loads files into the repository as repo tree items of class rtiClass.
Auto-detects using the extensions when rtiClass is None
"""
for fileName in fileNames:
self.repo.loadFile(fileName, rtiClass=rtiClass)
|
python
|
{
"resource": ""
}
|
q5775
|
ArgosApplication.addNewMainWindow
|
train
|
def addNewMainWindow(self, settings=None, inspectorFullName=None):
""" Creates and shows a new MainWindow.
If inspectorFullName is set, it will set the identifier from that name.
If the inspector identifier is not found in the registry, a KeyError is raised.
"""
mainWindow = MainWindow(self)
self.mainWindows.append(mainWindow)
self.windowActionGroup.addAction(mainWindow.activateWindowAction)
self.repopulateAllWindowMenus()
if settings:
mainWindow.readViewSettings(settings)
if inspectorFullName:
inspectorId = nameToIdentifier(inspectorFullName)
mainWindow.setInspectorById(inspectorId)
if mainWindow.inspectorRegItem: # can be None at start
inspectorId = mainWindow.inspectorRegItem.identifier
mainWindow.getInspectorActionById(inspectorId).setChecked(True)
logger.info("Created new window with inspector: {}"
.format(mainWindow.inspectorRegItem.fullName))
else:
logger.info("Created new window without inspector")
mainWindow.drawInspectorContents(reason=UpdateReason.NEW_MAIN_WINDOW)
mainWindow.show()
if sys.platform.startswith('darwin'):
# Calling raise before the QApplication.exec_ only shows the last window
# that was added. Therefore we also call activeWindow. However, this may not
# always be desirable. TODO: make optional?
mainWindow.raise_()
pass
return mainWindow
|
python
|
{
"resource": ""
}
|
q5776
|
ArgosApplication.removeMainWindow
|
train
|
def removeMainWindow(self, mainWindow):
""" Removes the mainWindow from the list of windows. Saves the settings
"""
logger.debug("removeMainWindow called")
self.windowActionGroup.removeAction(mainWindow.activateWindowAction)
self.repopulateAllWindowMenus()
self.mainWindows.remove(mainWindow)
|
python
|
{
"resource": ""
}
|
q5777
|
ArgosApplication.raiseAllWindows
|
train
|
def raiseAllWindows(self):
""" Raises all application windows.
"""
logger.debug("raiseAllWindows called")
for mainWindow in self.mainWindows:
logger.debug("Raising {}".format(mainWindow._instanceNr))
mainWindow.raise_()
|
python
|
{
"resource": ""
}
|
q5778
|
ArgosApplication.execute
|
train
|
def execute(self):
""" Executes all main windows by starting the Qt main application
"""
logger.info("Starting Argos event loop...")
exitCode = self.qApplication.exec_()
logger.info("Argos event loop finished with exit code: {}".format(exitCode))
return exitCode
|
python
|
{
"resource": ""
}
|
q5779
|
PillowFileRti._openResources
|
train
|
def _openResources(self):
""" Uses open the underlying file
"""
with Image.open(self._fileName) as image:
self._array = np.asarray(image)
self._bands = image.getbands()
# Fill attributes. For now assume that the info item are not overridden by
# the Image items.
self._attributes = dict(image.info)
self._attributes['Format'] = image.format
self._attributes['Mode'] = image.mode
self._attributes['Size'] = image.size
self._attributes['Width'] = image.width
self._attributes['Height'] = image.height
|
python
|
{
"resource": ""
}
|
q5780
|
PillowFileRti._fetchAllChildren
|
train
|
def _fetchAllChildren(self):
""" Adds the bands as separate fields so they can be inspected easily.
"""
bands = self._bands
if len(bands) != self._array.shape[-1]:
logger.warn("No bands added, bands != last_dim_lenght ({} !: {})"
.format(len(bands), self._array.shape[-1]))
return []
childItems = []
for bandNr, band in enumerate(bands):
bandItem = PillowBandRti(self._array[..., bandNr],
nodeName=band, fileName=self.fileName,
iconColor=self.iconColor, attributes=self._attributes)
childItems.append(bandItem)
return childItems
|
python
|
{
"resource": ""
}
|
q5781
|
labelTextWidth
|
train
|
def labelTextWidth(label):
""" Returns the width of label text of the label in pixels.
IMPORTANT: does not work when the labels are styled using style sheets.
Unfortunately it is possible to retrieve the settings (e.g. padding) that were set by the
style sheet without parsing the style sheet as text.
"""
# The Qt source shows that fontMetrics().size calls fontMetrics().boundingRect with
# the TextLongestVariant included in the flags. TextLongestVariant is an internal flag
# which is used to force selecting the longest string in a multi-length string.
# See: http://stackoverflow.com/a/8638114/625350
fontMetrics = label.fontMetrics()
#contentsWidth = label.fontMetrics().boundingRect(label.text()).width()
contentsWidth = fontMetrics.size(label.alignment(), label.text()).width()
# If indent is negative, or if no indent has been set, the label computes the effective indent
# as follows: If frameWidth() is 0, the effective indent becomes 0. If frameWidth() is greater
# than 0, the effective indent becomes half the width of the "x" character of the widget's
# current font().
# See http://doc.qt.io/qt-4.8/qlabel.html#indent-prop
if label.indent() < 0 and label.frameWidth(): # no indent, but we do have a frame
indent = fontMetrics.width('x') / 2 - label.margin()
indent *= 2 # the indent seems to be added to the other side as well
else:
indent = label.indent()
result = contentsWidth + indent + 2 * label.frameWidth() + 2 * label.margin()
if 1:
#print ("contentsMargins: {}".format(label.getContentsMargins()))
#print ("contentsRect: {}".format(label.contentsRect()))
#print ("frameRect: {}".format(label.frameRect()))
print ("contentsWidth: {}".format(contentsWidth))
print ("lineWidth: {}".format(label.lineWidth()))
print ("midLineWidth: {}".format(label.midLineWidth()))
print ("frameWidth: {}".format(label.frameWidth()))
print ("margin: {}".format(label.margin()))
print ("indent: {}".format(label.indent()))
print ("actual indent: {}".format(indent))
print ("RESULT: {}".format(result))
print ()
return result
|
python
|
{
"resource": ""
}
|
q5782
|
AbstractCti.resetToDefault
|
train
|
def resetToDefault(self, resetChildren=True):
""" Resets the data to the default data. By default the children will be reset as well
"""
self.data = self.defaultData
if resetChildren:
for child in self.childItems:
child.resetToDefault(resetChildren=True)
|
python
|
{
"resource": ""
}
|
q5783
|
AbstractCti._nodeGetNonDefaultsDict
|
train
|
def _nodeGetNonDefaultsDict(self):
""" Retrieves this nodes` values as a dictionary to be used for persistence.
A dictionary with the data value will be returned if the data is not equal to the
defaultData, the node is enabled and the node is editable. Otherwise and empty
dictionary is returned.
Non-recursive auxiliary function for getNonDefaultsDict
"""
dct = {}
isEditable = bool(int(self.valueColumnItemFlags) and Qt.ItemIsEditable)
if (self.data != self.defaultData and self.enabled and isEditable):
dct['data'] = self.data
return dct
|
python
|
{
"resource": ""
}
|
q5784
|
AbstractCti.getNonDefaultsDict
|
train
|
def getNonDefaultsDict(self):
""" Recursively retrieves values as a dictionary to be used for persistence.
Does not save defaultData and other properties, only stores values if they differ from
the defaultData. If the CTI and none of its children differ from their default, a
completely empty dictionary is returned. This is to achieve a smaller json
representation.
Typically descendants should override _nodeGetNonDefaultsDict instead of this function.
"""
dct = self._nodeGetNonDefaultsDict()
childList = []
for childCti in self.childItems:
childDct = childCti.getNonDefaultsDict()
if childDct:
childList.append(childDct)
if childList:
dct['childItems'] = childList
if dct:
dct['nodeName'] = self.nodeName
return dct
|
python
|
{
"resource": ""
}
|
q5785
|
AbstractCti.setValuesFromDict
|
train
|
def setValuesFromDict(self, dct):
""" Recursively sets values from a dictionary created by getNonDefaultsDict.
Does not raise exceptions (logs warnings instead) so that we can remove/rename node
names in future Argos versions (or remove them) without breaking the application.
Typically descendants should override _nodeSetValuesFromDict instead of this function.
"""
if 'nodeName' not in dct:
return
nodeName = dct['nodeName']
if nodeName != self.nodeName:
msg = "nodeName mismatch: expected {!r}, got {!r}".format(self.nodeName, nodeName)
if DEBUGGING:
raise ValueError(msg)
else:
logger.warn(msg)
return
self._nodeSetValuesFromDict(dct)
for childDct in dct.get('childItems', []):
key = childDct['nodeName']
try:
childCti = self.childByNodeName(key)
except IndexError as _ex:
logger.warn("Unable to set values for: {}".format(key))
else:
childCti.setValuesFromDict(childDct)
|
python
|
{
"resource": ""
}
|
q5786
|
AbstractCtiEditor.removeSubEditor
|
train
|
def removeSubEditor(self, subEditor):
""" Removes the subEditor from the layout and removes the event filter.
"""
if subEditor is self.focusProxy():
self.setFocusProxy(None)
subEditor.removeEventFilter(self)
self._subEditors.remove(subEditor)
self.hBoxLayout.removeWidget(subEditor)
|
python
|
{
"resource": ""
}
|
q5787
|
AbstractCtiEditor.eventFilter
|
train
|
def eventFilter(self, watchedObject, event):
""" Calls commitAndClose when the tab and back-tab are pressed.
This is necessary because, normally the event filter of QStyledItemDelegate does this
for us. However, that event filter works on this object, not on the sub editor.
"""
if event.type() == QtCore.QEvent.KeyPress:
key = event.key()
if key in (Qt.Key_Tab, Qt.Key_Backtab):
self.commitAndClose()
return True
else:
return False
return super(AbstractCtiEditor, self).eventFilter(watchedObject, event)
|
python
|
{
"resource": ""
}
|
q5788
|
AbstractCtiEditor.commitAndClose
|
train
|
def commitAndClose(self):
""" Commits the data of the sub editor and instructs the delegate to close this ctiEditor.
The delegate will emit the closeEditor signal which is connected to the closeEditor
method of the ConfigTreeView class. This, in turn will, call the finalize method of
this object so that signals can be disconnected and resources can be freed. This is
complicated but I don't see a simpler solution.
"""
if self.delegate:
self.delegate.commitData.emit(self)
self.delegate.closeEditor.emit(self, QtWidgets.QAbstractItemDelegate.NoHint) # CLOSES SELF!
else:
# QAbstractItemView.closeEditor is sometimes called directly, without the
# QAbstractItemDelegate.closeEditor signal begin emitted, e.g when the currentItem
# changes. Therefore the commitAndClose method can be called twice, if we call it
# explicitly as well (e.g. in FontCtiEditor.execFontDialog(). We guard against this.
logger.debug("AbstractCtiEditor.commitAndClose: editor already closed (ignored).")
|
python
|
{
"resource": ""
}
|
q5789
|
AbstractCtiEditor.resetEditorValue
|
train
|
def resetEditorValue(self, checked=False):
""" Resets the editor to the default value. Also resets the children.
"""
# Block all signals to prevent duplicate inspector updates.
# No need to restore, the editors will be deleted after the reset.
for subEditor in self._subEditors:
subEditor.blockSignals(True)
self.cti.resetToDefault(resetChildren=True)
# This will commit the children as well.
self.setData(self.cti.defaultData)
self.commitAndClose()
|
python
|
{
"resource": ""
}
|
q5790
|
MessageDisplay.setError
|
train
|
def setError(self, msg=None, title=None):
""" Shows and error message
"""
if msg is not None:
self.messageLabel.setText(msg)
if title is not None:
self.titleLabel.setText(title)
|
python
|
{
"resource": ""
}
|
q5791
|
makeReplacementField
|
train
|
def makeReplacementField(formatSpec, altFormatSpec='', testValue=None):
""" Prepends a colon and wraps the formatSpec in curly braces to yield a replacement field.
The format specification is part of a replacement field, which can be used in new-style
string formatting. See:
https://docs.python.org/3/library/string.html#format-string-syntax
https://docs.python.org/3/library/string.html#format-specification-mini-language
If the formatSpec does not contain a a color or exclamation mark, a colon is prepended.
If the formatSpec starts and end in quotes (single or double) only the quotes are removed,
no curly braces or colon charactes are added. This allows users to define a format spec.
:param formatSpec: e.g. '5.2f' will return '{:5.2f}'
:param altFormatSpec: alternative that will be used if the formatSpec evaluates to False
:param testValue: if not None, result.format(testValue) will be evaluated as a test.
:return: string
"""
check_is_a_string(formatSpec)
check_is_a_string(altFormatSpec)
fmt = altFormatSpec if not formatSpec else formatSpec
if is_quoted(fmt):
fmt = fmt[1:-1] # remove quotes
else:
if fmt and ':' not in fmt and '!' not in fmt:
fmt = ':' + fmt
fmt = '{' + fmt + '}'
# Test resulting replacement field
if testValue is not None:
try:
_dummy = fmt.format(testValue)
except Exception:
msg = ("Format specifier failed: replacement-field={!r}, test-value={!r}"
.format(fmt, testValue))
logger.error(msg)
raise ValueError(msg)
logger.debug("Resulting replacement field: {!r}".format(fmt))
return fmt
|
python
|
{
"resource": ""
}
|
q5792
|
TableInspectorCti._refreshNodeFromTarget
|
train
|
def _refreshNodeFromTarget(self):
""" Refreshes the TableInspectorCti from the TableInspector target it monitors.
Disables auto-sizing of the header sizes for very large headers (> 10000 elements).
Otherwise the resizing may take to long and the program will hang.
"""
tableModel = self.tableInspector.model
# Disable row height and column with settings for large headers (too slow otherwise)
if tableModel.rowCount() >= RESET_HEADERS_AT_SIZE:
self.autoRowHeightCti.data = False
self.model.emitDataChanged(self.autoRowHeightCti)
self.autoRowHeightCti.enable = False
else:
self.autoRowHeightCti.enable = True
if tableModel.columnCount() >= RESET_HEADERS_AT_SIZE:
self.autoColWidthCti.data = False
self.model.emitDataChanged(self.autoColWidthCti)
self.autoColWidthCti.enable = False
else:
self.autoColWidthCti.enable = True
|
python
|
{
"resource": ""
}
|
q5793
|
TableInspectorModel.updateState
|
train
|
def updateState(self, slicedArray, rtiInfo, separateFields):
""" Sets the slicedArray and rtiInfo and other members. This will reset the model.
Will be called from the tableInspector._drawContents.
"""
self.beginResetModel()
try:
# The sliced array can be a masked array or a (regular) numpy array.
# The table works fine with masked arrays, no need to replace the masked values.
self._slicedArray = slicedArray
if slicedArray is None:
self._nRows = 0
self._nCols = 0
self._fieldNames = []
else:
self._nRows, self._nCols = self._slicedArray.shape
if self._slicedArray.data.dtype.names:
self._fieldNames = self._slicedArray.data.dtype.names
else:
self._fieldNames = []
self._rtiInfo = rtiInfo
self._separateFields = separateFields
# Don't put numbers in the header if the record is of structured type, fields are
# placed in separate cells and the fake dimension is selected (combo index 0)
if self._separateFields and self._fieldNames:
if self._rtiInfo['x-dim'] == FAKE_DIM_NAME:
self._separateFieldOrientation = Qt.Horizontal
self._numbersInHeader = False
elif self._rtiInfo['y-dim'] == FAKE_DIM_NAME:
self._separateFieldOrientation = Qt.Vertical
self._numbersInHeader = False
else:
self._separateFieldOrientation = Qt.Horizontal
self._numbersInHeader = True
else:
self._separateFieldOrientation = None
self._numbersInHeader = True
finally:
self.endResetModel()
|
python
|
{
"resource": ""
}
|
q5794
|
TableInspectorModel.data
|
train
|
def data(self, index, role = Qt.DisplayRole):
""" Returns the data at an index for a certain role
"""
try:
if role == Qt.DisplayRole:
return to_string(self._cellValue(index), masked=self._cellMask(index),
decode_bytes=self.encoding, maskFormat=self.maskFormat,
strFormat=self.strFormat, intFormat=self.intFormat,
numFormat=self.numFormat, otherFormat=self.otherFormat)
elif role == Qt.FontRole:
#assert self._font, "Font undefined"
return self._font
elif role == Qt.TextColorRole:
masked = self._cellMask(index)
if not is_an_array(masked) and masked:
return self.missingColor
else:
return self.dataColor
elif role == Qt.TextAlignmentRole:
if self.horAlignment == ALIGN_SMART:
cellContainsNumber = isinstance(self._cellValue(index), numbers.Number)
horAlign = Qt.AlignRight if cellContainsNumber else Qt.AlignLeft
return horAlign | self.verAlignment
else:
return self.horAlignment | self.verAlignment
else:
return None
except Exception as ex:
logger.error("Slot is not exception-safe.")
logger.exception(ex)
if DEBUGGING:
raise
|
python
|
{
"resource": ""
}
|
q5795
|
TableInspectorModel.rowCount
|
train
|
def rowCount(self, parent=None):
""" The number of rows of the sliced array.
The 'parent' parameter can be a QModelIndex. It is ignored since the number of
rows does not depend on the parent.
"""
if self._separateFieldOrientation == Qt.Vertical:
return self._nRows * len(self._fieldNames)
else:
return self._nRows
|
python
|
{
"resource": ""
}
|
q5796
|
TableInspectorModel.columnCount
|
train
|
def columnCount(self, parent=None):
""" The number of columns of the sliced array.
The 'parent' parameter can be a QModelIndex. It is ignored since the number of
columns does not depend on the parent.
"""
if self._separateFieldOrientation == Qt.Horizontal:
return self._nCols * len(self._fieldNames)
else:
return self._nCols
|
python
|
{
"resource": ""
}
|
q5797
|
viewBoxAxisRange
|
train
|
def viewBoxAxisRange(viewBox, axisNumber):
""" Calculates the range of an axis of a viewBox.
"""
rect = viewBox.childrenBoundingRect() # taken from viewBox.autoRange()
if rect is not None:
if axisNumber == X_AXIS:
return rect.left(), rect.right()
elif axisNumber == Y_AXIS:
return rect.bottom(), rect.top()
else:
raise ValueError("axisNumber should be 0 or 1, got: {}".format(axisNumber))
else:
# Does this happen? Probably when the plot is empty.
raise AssertionError("No children bbox. Plot range not updated.")
|
python
|
{
"resource": ""
}
|
q5798
|
defaultAutoRangeMethods
|
train
|
def defaultAutoRangeMethods(inspector, intialItems=None):
""" Creates an ordered dict with default autorange methods for an inspector.
:param inspector: the range methods will work on (the sliced array) of this inspector.
:param intialItems: will be passed on to the OrderedDict constructor.
"""
rangeFunctions = OrderedDict({} if intialItems is None else intialItems)
rangeFunctions['use all data'] = partial(inspectorDataRange, inspector, 0.0)
for percentage in [0.1, 0.2, 0.5, 1, 2, 5, 10, 20]:
label = "discard {}%".format(percentage)
rangeFunctions[label] = partial(inspectorDataRange, inspector, percentage)
return rangeFunctions
|
python
|
{
"resource": ""
}
|
q5799
|
setXYAxesAutoRangeOn
|
train
|
def setXYAxesAutoRangeOn(commonCti, xAxisRangeCti, yAxisRangeCti, axisNumber):
""" Turns on the auto range of an X and Y axis simultaneously.
It sets the autoRangeCti.data of the xAxisRangeCti and yAxisRangeCti to True.
After that, it emits the sigItemChanged signal of the commonCti.
Can be used with functools.partial to make a slot that atomically resets the X and Y axis.
That is, only one sigItemChanged will be emitted.
This function is necessary because, if one would call PgAxisRangeCti.sigItemChanged
separately on the X and Y axes the sigItemChanged signal would be emitted twice. This in
not only slower, but autoscaling one axis may slightly change the others range, so the
second call to sigItemChanged may unset the autorange of the first.
axisNumber must be one of: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
"""
assert axisNumber in VALID_AXIS_NUMBERS, \
"Axis number should be one of {}, got {}".format(VALID_AXIS_NUMBERS, axisNumber)
logger.debug("setXYAxesAutoRangeOn, axisNumber: {}".format(axisNumber))
if axisNumber == X_AXIS or axisNumber == BOTH_AXES:
xAxisRangeCti.autoRangeCti.data = True
if axisNumber == Y_AXIS or axisNumber == BOTH_AXES:
yAxisRangeCti.autoRangeCti.data = True
commonCti.model.sigItemChanged.emit(commonCti)
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.