_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q5900
array_has_real_numbers
train
def array_has_real_numbers(array): """ Uses the dtype kind of the numpy array to determine if it represents real numbers. That is, the array kind should be one of: i u f Possible dtype.kind values. b boolean i signed integer u unsigned integer f ...
python
{ "resource": "" }
q5901
createPenStyleCti
train
def createPenStyleCti(nodeName, defaultData=0, includeNone=False): """ Creates a ChoiceCti with Qt PenStyles. If includeEmtpy is True, the first option will be None. """ displayValues=PEN_STYLE_DISPLAY_VALUES configValues=PEN_STYLE_CONFIG_VALUES if includeNone: displayValues = [''] +...
python
{ "resource": "" }
q5902
createPenWidthCti
train
def createPenWidthCti(nodeName, defaultData=1.0, zeroValueText=None): """ Creates a FloatCti with defaults for configuring a QPen width. If specialValueZero is set, this string will be displayed when 0.0 is selected. If specialValueZero is None, the minValue will be 0.1 """ # A pen line wid...
python
{ "resource": "" }
q5903
ColorCti._enforceDataType
train
def _enforceDataType(self, data): """ Converts to str so that this CTI always stores that type. """ qColor = QtGui.QColor(data) # TODO: store a RGB string? if not qColor.isValid(): raise ValueError("Invalid color specification: {!r}".format(data)) return qColor
python
{ "resource": "" }
q5904
ColorCti.createEditor
train
def createEditor(self, delegate, parent, option): """ Creates a ColorCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return ColorCtiEditor(self, delegate, parent=parent)
python
{ "resource": "" }
q5905
ColorCtiEditor.getData
train
def getData(self): """ Gets data from the editor widget. """ text = self.lineEditor.text() if not text.startswith('#'): text = '#' + text validator = self.lineEditor.validator() if validator is not None: state, text, _ = validator.validate(text, 0...
python
{ "resource": "" }
q5906
FontCti.data
train
def data(self, data): """ Sets the font data of this item. Does type conversion to ensure data is always of the correct type. Also updates the children (which is the reason for this property to be overloaded. """ self._data = self._enforceDataType(data) # Enforce self._d...
python
{ "resource": "" }
q5907
FontCti.defaultData
train
def defaultData(self, defaultData): """ Sets the data of this item. Does type conversion to ensure default data is always of the correct type. """ self._defaultData = self._enforceDataType(defaultData) # Enforce to be a QFont self.familyCti.defaultData = fontFamilyIndex(self....
python
{ "resource": "" }
q5908
FontCti._updateTargetFromNode
train
def _updateTargetFromNode(self): """ Applies the font config settings to the target widget's font. That is the targetWidget.setFont() is called with a font create from the config values. """ font = self.data if self.familyCti.configValue: font.setFamily(self.fami...
python
{ "resource": "" }
q5909
FontCti.createEditor
train
def createEditor(self, delegate, parent, option): """ Creates a FontCtiEditor. For the parameters see the AbstractCti documentation. """ return FontCtiEditor(self, delegate, parent=parent)
python
{ "resource": "" }
q5910
PenCti.configValue
train
def configValue(self): """ Creates a QPen made of the children's config values. """ if not self.data: return None else: pen = QtGui.QPen() pen.setCosmetic(True) pen.setColor(self.colorCti.configValue) style = self.styleCti.confi...
python
{ "resource": "" }
q5911
PenCti.createPen
train
def createPen(self, altStyle=None, altWidth=None): """ Creates a pen from the config values with the style overridden by altStyle if the None-option is selected in the combo box. """ pen = self.configValue if pen is not None: style = self.findByNodePath('style')....
python
{ "resource": "" }
q5912
maskedNanPercentile
train
def maskedNanPercentile(maskedArray, percentiles, *args, **kwargs): """ Calculates np.nanpercentile on the non-masked values """ #https://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html#accessing-the-data awm = ArrayWithMask.createFromMaskedArray(maskedArray) maskIdx = awm.maskIndex() ...
python
{ "resource": "" }
q5913
ArrayWithMask.mask
train
def mask(self, mask): """ The mask values. Must be an array or a boolean scalar.""" check_class(mask, (np.ndarray, bool, np.bool_)) if isinstance(mask, (bool, np.bool_)): self._mask = bool(mask) else: self._mask = mask
python
{ "resource": "" }
q5914
ArrayWithMask.checkIsConsistent
train
def checkIsConsistent(self): """ Raises a ConsistencyError if the mask has an incorrect shape. """ if is_an_array(self.mask) and self.mask.shape != self.data.shape: raise ConsistencyError("Shape mismatch mask={}, data={}" .format(self.mask.shape != ...
python
{ "resource": "" }
q5915
ArrayWithMask.createFromMaskedArray
train
def createFromMaskedArray(cls, masked_arr): """ Creates an ArrayWithMak :param masked_arr: a numpy MaskedArray or numpy array :return: ArrayWithMask """ if isinstance(masked_arr, ArrayWithMask): return masked_arr check_class(masked_arr, (np.ndarray, ...
python
{ "resource": "" }
q5916
ArrayWithMask.asMaskedArray
train
def asMaskedArray(self): """ Creates converts to a masked array """ return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)
python
{ "resource": "" }
q5917
ArrayWithMask.maskAt
train
def maskAt(self, index): """ Returns the mask at the index. It the mask is a boolean it is returned since this boolean representes the mask for all array elements. """ if isinstance(self.mask, bool): return self.mask else: return self.mask...
python
{ "resource": "" }
q5918
ArrayWithMask.maskIndex
train
def maskIndex(self): """ Returns a boolean index with True if the value is masked. Always has the same shape as the maksedArray.data, event if the mask is a single boolan. """ if isinstance(self.mask, bool): return np.full(self.data.shape, self.mask, dtype=np.bool) ...
python
{ "resource": "" }
q5919
ArrayWithMask.transpose
train
def transpose(self, *args, **kwargs): """ Transposes the array and mask separately :param awm: ArrayWithMask :return: copy/view with transposed """ tdata = np.transpose(self.data, *args, **kwargs) tmask = np.transpose(self.mask, *args, **kwargs) if is_an_array(se...
python
{ "resource": "" }
q5920
RegistryTab.importRegItem
train
def importRegItem(self, regItem): """ Imports the regItem Writes this in the statusLabel while the import is in progress. """ self.statusLabel.setText("Importing {}...".format(regItem.fullName)) QtWidgets.qApp.processEvents() regItem.tryImportClass() self.tabl...
python
{ "resource": "" }
q5921
RegistryTab.tryImportAllPlugins
train
def tryImportAllPlugins(self): """ Tries to import all underlying plugin classes """ for regItem in self.registeredItems: if not regItem.triedImport: self.importRegItem(regItem) logger.debug("Importing finished.")
python
{ "resource": "" }
q5922
RegistryTab.setCurrentRegItem
train
def setCurrentRegItem(self, regItem): """ Sets the current item to the regItem """ check_class(regItem, ClassRegItem, allow_none=True) self.tableView.setCurrentRegItem(regItem)
python
{ "resource": "" }
q5923
RegistryTab.currentItemChanged
train
def currentItemChanged(self, _currentIndex=None, _previousIndex=None): """ Updates the description text widget when the user clicks on a selector in the table. The _currentIndex and _previousIndex parameters are ignored. """ self.editor.clear() self.editor.setTextColor(QCOLOR...
python
{ "resource": "" }
q5924
PluginsDialog.tryImportAllPlugins
train
def tryImportAllPlugins(self): """ Refreshes the tables of all tables by importing the underlying classes """ logger.debug("Importing plugins: {}".format(self)) for tabNr in range(self.tabWidget.count()): tab = self.tabWidget.widget(tabNr) tab.tryImportAllPlugins(...
python
{ "resource": "" }
q5925
dimNamesFromDataset
train
def dimNamesFromDataset(h5Dataset): """ Constructs the dimension names given a h5py dataset. First looks in the dataset's dimension scales to see if it refers to another dataset. In that case the referred dataset's name is used. If not, the label of the dimension scale is used. Finally, if ...
python
{ "resource": "" }
q5926
dataSetElementType
train
def dataSetElementType(h5Dataset): """ Returns a string describing the element type of the dataset """ dtype = h5Dataset.dtype if dtype.names: return '<structured>' else: if dtype.metadata and 'vlen' in dtype.metadata: vlen_type = dtype.metadata['vlen'] try:...
python
{ "resource": "" }
q5927
dataSetUnit
train
def dataSetUnit(h5Dataset): """ Returns the unit of the h5Dataset by looking in the attributes. It searches in the attributes for one of the following keys: 'unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'. If these are not found, the empty string is returned. Always returns a str...
python
{ "resource": "" }
q5928
dataSetMissingValue
train
def dataSetMissingValue(h5Dataset): """ Returns the missingData given a HDF-5 dataset Looks for one of the following attributes: _FillValue, missing_value, MissingValue, missingValue. Returns None if these attributes are not found. HDF-EOS and NetCDF files seem to put the attributes in 1-e...
python
{ "resource": "" }
q5929
H5pyFieldRti._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. """ if self._h5Dataset.dtype.fields is None: return tuple() # regular field else: fieldName = self.nodeName ...
python
{ "resource": "" }
q5930
H5pyFieldRti.unit
train
def unit(self): """ Returns the unit of the RTI by calling dataSetUnit on the underlying dataset """ unit = dataSetUnit(self._h5Dataset) fieldNames = self._h5Dataset.dtype.names # If the missing value attribute is a list with the same length as the number of fields, # re...
python
{ "resource": "" }
q5931
H5pyDatasetRti.iconGlyph
train
def iconGlyph(self): """ Shows an Array icon for regular datasets but a dimension icon for dimension scales """ if self._h5Dataset.attrs.get('CLASS', None) == b'DIMENSION_SCALE': return RtiIconFactory.DIMENSION else: return RtiIconFactory.ARRAY
python
{ "resource": "" }
q5932
crossPlotAutoRangeMethods
train
def crossPlotAutoRangeMethods(pgImagePlot2d, crossPlot, intialItems=None): """ Creates an ordered dict with autorange methods for an PgImagePlot2d inspector. :param pgImagePlot2d: the range methods will work on (the sliced array) of this inspector. :param crossPlot: if None, the range will be calcu...
python
{ "resource": "" }
q5933
PgImagePlot2dCti.setImagePlotAutoRangeOn
train
def setImagePlotAutoRangeOn(self, axisNumber): """ Sets the image plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.yAxisRangeCti, axisNumber)
python
{ "resource": "" }
q5934
PgImagePlot2dCti.setHorCrossPlotAutoRangeOn
train
def setHorCrossPlotAutoRangeOn(self, axisNumber): """ Sets the horizontal cross-hair plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.horCrossPlotRange...
python
{ "resource": "" }
q5935
PgImagePlot2dCti.setVerCrossPlotAutoRangeOn
train
def setVerCrossPlotAutoRangeOn(self, axisNumber): """ Sets the vertical cross-hair plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ setXYAxesAutoRangeOn(self, self.verCrossPlotRangeCti, self.yAxisRangeCt...
python
{ "resource": "" }
q5936
PgImagePlot2d._clearContents
train
def _clearContents(self): """ Clears the contents when no valid data is available """ logger.debug("Clearing inspector contents") self.titleLabel.setText('') # Don't clear the imagePlotItem, the imageItem is only added in the constructor. self.imageItem.clear() s...
python
{ "resource": "" }
q5937
RtiRegItem.asDict
train
def asDict(self): """ Returns a dictionary for serialization. """ dct = super(RtiRegItem, self).asDict() dct['extensions'] = self.extensions return dct
python
{ "resource": "" }
q5938
RtiRegistry._registerExtension
train
def _registerExtension(self, extension, rtiRegItem): """ Links an file name extension to a repository tree item. """ check_is_a_string(extension) check_class(rtiRegItem, RtiRegItem) logger.debug(" Registering extension {!r} for {}".format(extension, rtiRegItem)) # TODO...
python
{ "resource": "" }
q5939
RtiRegistry.registerRti
train
def registerRti(self, fullName, fullClassName, extensions=None, pythonPath=''): """ Class that maintains the collection of registered inspector classes. Maintains a lit of file extensions that open the RTI by default. """ check_is_a_sequence(extensions) extensions = extension...
python
{ "resource": "" }
q5940
RtiRegistry.getDefaultItems
train
def getDefaultItems(self): """ Returns a list with the default plugins in the repo tree item registry. """ return [ RtiRegItem('HDF-5 file', 'argos.repo.rtiplugins.hdf5.H5pyFileRti', extensions=['hdf5', 'h5', 'h5e', 'he5', 'nc']), # hdf e...
python
{ "resource": "" }
q5941
AboutDialog.addDependencyInfo
train
def addDependencyInfo(self): """ Adds version info about the installed dependencies """ logger.debug("Adding dependency info to the AboutDialog") self.progressLabel.setText("Retrieving package info...") self.editor.clear() self._addModuleInfo(mi.PythonModuleInfo()) ...
python
{ "resource": "" }
q5942
FloatCti._enforceDataType
train
def _enforceDataType(self, data): """ Converts to float so that this CTI always stores that type. Replaces infinite with the maximum respresentable float. Raises a ValueError if data is a NaN. """ value = float(data) if math.isnan(value): raise ValueE...
python
{ "resource": "" }
q5943
detectRtiFromFileName
train
def detectRtiFromFileName(fileName): """ Determines the type of RepoTreeItem to use given a file name. Uses a DirectoryRti for directories and an UnknownFileRti if the file extension doesn't match one of the registered RTI extensions. Returns (cls, regItem) tuple. Both the cls ond the regIt...
python
{ "resource": "" }
q5944
createRtiFromFileName
train
def createRtiFromFileName(fileName): """ Determines the type of RepoTreeItem to use given a file name and creates it. Uses a DirectoryRti for directories and an UnknownFileRti if the file extension doesn't match one of the registered RTI extensions. """ cls, rtiRegItem = detectRtiFromFileNam...
python
{ "resource": "" }
q5945
DirectoryRti._fetchAllChildren
train
def _fetchAllChildren(self): """ Gets all sub directories and files within the current directory. Does not fetch hidden files. """ childItems = [] fileNames = os.listdir(self._fileName) absFileNames = [os.path.join(self._fileName, fn) for fn in fileNames] # A...
python
{ "resource": "" }
q5946
CollectorTree.resizeColumnsToContents
train
def resizeColumnsToContents(self, startCol=None, stopCol=None): """ Resizes all columns to the contents """ numCols = self.model().columnCount() startCol = 0 if startCol is None else max(startCol, 0) stopCol = numCols if stopCol is None else min(stopCol, numCols) row = ...
python
{ "resource": "" }
q5947
CollectorSpinBox.sizeHint
train
def sizeHint(self): """ Reimplemented from the C++ Qt source of QAbstractSpinBox.sizeHint, but without truncating to a maximum of 18 characters. """ # The cache is invalid after the prefix, postfix and other properties # have been set. I disabled it because sizeHint isn't cal...
python
{ "resource": "" }
q5948
ConfigItemDelegate.createEditor
train
def createEditor(self, parent, option, index): """ Returns the widget used to change data from the model and can be reimplemented to customize editing behavior. Reimplemented from QStyledItemDelegate. """ logger.debug("ConfigItemDelegate.createEditor, parent: {!r}".forma...
python
{ "resource": "" }
q5949
ConfigItemDelegate.setEditorData
train
def setEditorData(self, editor, index): """ Provides the widget with data to manipulate. Calls the setEditorValue of the config tree item at the index. :type editor: QWidget :type index: QModelIndex Reimplemented from QStyledItemDelegate. """ # W...
python
{ "resource": "" }
q5950
ConfigItemDelegate.setModelData
train
def setModelData(self, editor, model, index): """ Gets data from the editor widget and stores it in the specified model at the item index. Does this by calling getEditorValue of the config tree item at the index. :type editor: QWidget :type model: ConfigTreeModel ...
python
{ "resource": "" }
q5951
ConfigItemDelegate.updateEditorGeometry
train
def updateEditorGeometry(self, editor, option, index): """ Ensures that the editor is displayed correctly with respect to the item view. """ cti = index.model().getItem(index) if cti.checkState is None: displayRect = option.rect else: checkBoxRect = widget...
python
{ "resource": "" }
q5952
ConfigTreeView.closeEditor
train
def closeEditor(self, editor, hint): """ Finalizes, closes and releases the given editor. """ # It would be nicer if this method was part of ConfigItemDelegate since createEditor also # lives there. However, QAbstractItemView.closeEditor is sometimes called directly, # without th...
python
{ "resource": "" }
q5953
ncVarAttributes
train
def ncVarAttributes(ncVar): """ Returns the attributes of ncdf variable """ try: return ncVar.__dict__ except Exception as ex: # Due to some internal error netCDF4 may raise an AttributeError or KeyError, # depending on its version. logger.warn("Unable to read the attribu...
python
{ "resource": "" }
q5954
ncVarUnit
train
def ncVarUnit(ncVar): """ Returns the unit of the ncVar by looking in the attributes. It searches in the attributes for one of the following keys: 'unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'. If these are not found, the empty string is returned. """ attributes = ncVarAttribute...
python
{ "resource": "" }
q5955
variableMissingValue
train
def variableMissingValue(ncVar): """ Returns the missingData given a NetCDF variable Looks for one of the following attributes: _FillValue, missing_value, MissingValue, missingValue. Returns None if these attributes are not found. """ attributes = ncVarAttributes(ncVar) if not attribute...
python
{ "resource": "" }
q5956
NcdfFieldRti.unit
train
def unit(self): """ Returns the unit attribute of the underlying ncdf variable. If the units has a length (e.g is a list) and has precisely one element per field, the unit for this field is returned. """ unit = ncVarUnit(self._ncVar) fieldNames = self._ncVar.dtyp...
python
{ "resource": "" }
q5957
WavFileRti._openResources
train
def _openResources(self): """ Uses numpy.loadtxt to open the underlying file. """ try: rate, data = scipy.io.wavfile.read(self._fileName, mmap=True) except Exception as ex: logger.warning(ex) logger.warning("Unable to read wav with memmory mapping. Try...
python
{ "resource": "" }
q5958
WavFileRti._fetchAllChildren
train
def _fetchAllChildren(self): """ Adds an ArrayRti per column as children so that they can be inspected easily """ childItems = [] if self._array.ndim == 2: _nRows, nCols = self._array.shape if self._array is not None else (0, 0) for col in range(nCols): ...
python
{ "resource": "" }
q5959
middleMouseClickEvent
train
def middleMouseClickEvent(argosPgPlotItem, axisNumber, mouseClickEvent): """ Emits sigAxisReset when the middle mouse button is clicked on an axis of the the plot item. """ if mouseClickEvent.button() == QtCore.Qt.MiddleButton: mouseClickEvent.accept() argosPgPlotItem.emitResetAxisSignal(axi...
python
{ "resource": "" }
q5960
ArgosPgPlotItem.close
train
def close(self): """ Is called before destruction. Can be used to clean-up resources Could be called 'finalize' but PlotItem already has a close so we reuse that. """ logger.debug("Finalizing: {}".format(self)) super(ArgosPgPlotItem, self).close()
python
{ "resource": "" }
q5961
ArgosPgPlotItem.contextMenuEvent
train
def contextMenuEvent(self, event): """ Shows the context menu at the cursor position We need to take the event-based approach because ArgosPgPlotItem does derives from QGraphicsWidget, and not from QWidget, and therefore doesn't have the customContextMenuRequested signal. ...
python
{ "resource": "" }
q5962
ArgosPgPlotItem.emitResetAxisSignal
train
def emitResetAxisSignal(self, axisNumber): """ Emits the sigResetAxis with the axisNumber as parameter axisNumber should be 0 for X, 1 for Y, and 2 for both axes. """ assert axisNumber in (VALID_AXES_NUMBERS), \ "Axis Nr should be one of {}, got {}".format(VALID_AXES_NUMB...
python
{ "resource": "" }
q5963
notebook_merge
train
def notebook_merge(local, base, remote, check_modified=False): """Unify three notebooks into a single notebook with merge metadata. The result of this function is a valid notebook that can be loaded by the IPython Notebook front-end. This function adds additional cell metadata that the front-end Javasc...
python
{ "resource": "" }
q5964
NotebookParser.parse
train
def parse(self, json_data): """Parse a notebook .ipynb file. Parameters ---------- json_data : file A file handle for an .ipynb file. Returns ------- nb : An IPython Notebook data structure. """ data = current.read(json_data, 'ipynb')...
python
{ "resource": "" }
q5965
notebook_diff
train
def notebook_diff(nb1, nb2, check_modified=True): """Unify two notebooks into a single notebook with diff metadata. The result of this function is a valid notebook that can be loaded by the IPython Notebook front-end. This function adds additional cell metadata that the front-end Javascript uses to ren...
python
{ "resource": "" }
q5966
diff_result_to_cell
train
def diff_result_to_cell(item): '''diff.diff returns a dictionary with all the information we need, but we want to extract the cell and change its metadata.''' state = item['state'] if state == 'modified': new_cell = item['modifiedvalue'].data old_cell = item['originalvalue'].data ...
python
{ "resource": "" }
q5967
cells_diff
train
def cells_diff(before_cells, after_cells, check_modified=False): '''Diff two arrays of cells.''' before_comps = [ CellComparator(cell, check_modified=check_modified) for cell in before_cells ] after_comps = [ CellComparator(cell, check_modified=check_modified) for cell in...
python
{ "resource": "" }
q5968
words_diff
train
def words_diff(before_words, after_words): '''Diff the words in two strings. This is intended for use in diffing prose and other forms of text where line breaks have little semantic value. Parameters ---------- before_words : str A string to be used as the baseline version. after_w...
python
{ "resource": "" }
q5969
lines_diff
train
def lines_diff(before_lines, after_lines, check_modified=False): '''Diff the lines in two strings. Parameters ---------- before_lines : iterable Iterable containing lines used as the baseline version. after_lines : iterable Iterable containing lines to be compared against the baseli...
python
{ "resource": "" }
q5970
diff
train
def diff(before, after, check_modified=False): """Diff two sequences of comparable objects. The result of this function is a list of dictionaries containing values in ``before`` or ``after`` with a ``state`` of either 'unchanged', 'added', 'deleted', or 'modified'. >>> import pprint >>> result...
python
{ "resource": "" }
q5971
run_application
train
def run_application(component: Union[Component, Dict[str, Any]], *, event_loop_policy: str = None, max_threads: int = None, logging: Union[Dict[str, Any], int, None] = INFO, start_timeout: Union[int, float, None] = 10): """ Configure logging and start the given root compo...
python
{ "resource": "" }
q5972
executor
train
def executor(func_or_executor: Union[Executor, str, Callable[..., T_Retval]]) -> \ Union[WrappedCallable, Callable[..., WrappedCallable]]: """ Decorate a function to run in an executor. If no executor (or ``None``) is given, the current event loop's default executor is used. Otherwise, the argu...
python
{ "resource": "" }
q5973
merge_config
train
def merge_config(original: Optional[Dict[str, Any]], overrides: Optional[Dict[str, Any]]) -> Dict[str, Any]: """ Return a copy of the ``original`` configuration dictionary, with overrides from ``overrides`` applied. This similar to what :meth:`dict.update` does, but when a dictionary i...
python
{ "resource": "" }
q5974
PluginContainer.resolve
train
def resolve(self, obj): """ Resolve a reference to an entry point or a variable in a module. If ``obj`` is a ``module:varname`` reference to an object, :func:`resolve_reference` is used to resolve it. If it is a string of any other kind, the named entry point is loaded from this...
python
{ "resource": "" }
q5975
PluginContainer.create_object
train
def create_object(self, type: Union[type, str], **constructor_kwargs): """ Instantiate a plugin. The entry points in this namespace must point to subclasses of the ``base_class`` parameter passed to this container. :param type: an entry point identifier, a ``module:varname`` re...
python
{ "resource": "" }
q5976
ContainerComponent.add_component
train
def add_component(self, alias: str, type: Union[str, type] = None, **config): """ Add a child component. This will instantiate a component class, as specified by the ``type`` argument. If the second argument is omitted, the value of ``alias`` is used as its value. The locally ...
python
{ "resource": "" }
q5977
context_teardown
train
def context_teardown(func: Callable): """ Wrap an async generator function to execute the rest of the function at context teardown. This function returns an async function, which, when called, starts the wrapped async generator. The wrapped async function is run until the first ``yield`` statement ...
python
{ "resource": "" }
q5978
Context.context_chain
train
def context_chain(self) -> List['Context']: """Return a list of contexts starting from this one, its parent and so on.""" contexts = [] ctx = self # type: Optional[Context] while ctx is not None: contexts.append(ctx) ctx = ctx.parent return contexts
python
{ "resource": "" }
q5979
Context.add_teardown_callback
train
def add_teardown_callback(self, callback: Callable, pass_exception: bool = False) -> None: """ Add a callback to be called when this context closes. This is intended for cleanup of resources, and the list of callbacks is processed in the reverse order in which they were added, so the la...
python
{ "resource": "" }
q5980
Context.close
train
async def close(self, exception: BaseException = None) -> None: """ Close this context and call any necessary resource teardown callbacks. If a teardown callback returns an awaitable, the return value is awaited on before calling any further teardown callbacks. All callbacks wi...
python
{ "resource": "" }
q5981
Context.add_resource
train
def add_resource(self, value, name: str = 'default', context_attr: str = None, types: Union[type, Sequence[type]] = ()) -> None: """ Add a resource to this context. This will cause a ``resource_added`` event to be dispatched. :param value: the actual resource value...
python
{ "resource": "" }
q5982
Context.add_resource_factory
train
def add_resource_factory(self, factory_callback: factory_callback_type, types: Union[type, Sequence[Type]], name: str = 'default', context_attr: str = None) -> None: """ Add a resource factory to this context. This will cause a ``resourc...
python
{ "resource": "" }
q5983
Context.get_resources
train
def get_resources(self, type: Type[T_Resource]) -> Set[T_Resource]: """ Retrieve all the resources of the given type in this context and its parents. Any matching resource factories are also triggered if necessary. :param type: type of the resources to get :return: a set of all...
python
{ "resource": "" }
q5984
Context.require_resource
train
def require_resource(self, type: Type[T_Resource], name: str = 'default') -> T_Resource: """ Look up a resource in the chain of contexts and raise an exception if it is not found. This is like :meth:`get_resource` except that instead of returning ``None`` when a resource is not found, i...
python
{ "resource": "" }
q5985
Context.call_async
train
def call_async(self, func: Callable, *args, **kwargs): """ Call the given callable in the event loop thread. This method lets you call asynchronous code from a worker thread. Do not use it from within the event loop thread. If the callable returns an awaitable, it is resolved b...
python
{ "resource": "" }
q5986
Context.call_in_executor
train
def call_in_executor(self, func: Callable, *args, executor: Union[Executor, str] = None, **kwargs) -> Awaitable: """ Call the given callable in an executor. :param func: the callable to call :param args: positional arguments to call the callable with :pa...
python
{ "resource": "" }
q5987
stream_events
train
def stream_events(signals: Sequence[Signal], filter: Callable[[T_Event], bool] = None, *, max_queue_size: int = 0) -> AsyncIterator[T_Event]: """ Return an async generator that yields events from the given signals. Only events that pass the filter callable (if one has been given) are retu...
python
{ "resource": "" }
q5988
Signal.connect
train
def connect(self, callback: Callable[[T_Event], Any]) -> Callable[[T_Event], Any]: """ Connect a callback to this signal. Each callable can only be connected once. Duplicate registrations are ignored. If you need to pass extra arguments to the callback, you can use :func:`functools.par...
python
{ "resource": "" }
q5989
Signal.disconnect
train
def disconnect(self, callback: Callable) -> None: """ Disconnects the given callback. The callback will no longer receive events from this signal. No action is taken if the callback is not on the list of listener callbacks. :param callback: the callable to remove """ ...
python
{ "resource": "" }
q5990
Signal.dispatch_raw
train
def dispatch_raw(self, event: Event) -> Awaitable[bool]: """ Dispatch the given event object to all listeners. Creates a new task in which all listener callbacks are called with the given event as the only argument. Coroutine callbacks are converted to their own respective tasks and ...
python
{ "resource": "" }
q5991
Signal.dispatch
train
def dispatch(self, *args, **kwargs) -> Awaitable[bool]: """ Create and dispatch an event. This method constructs an event object and then passes it to :meth:`dispatch_event` for the actual dispatching. :param args: positional arguments to the constructor of the associated event...
python
{ "resource": "" }
q5992
stream._escape_sequence
train
def _escape_sequence(self, char): """ Handle characters seen when in an escape sequence. Most non-vt52 commands start with a left-bracket after the escape and then a stream of parameters and a command. """ num = ord(char) if char == "[": self.state =...
python
{ "resource": "" }
q5993
stream._end_escape_sequence
train
def _end_escape_sequence(self, char): """ Handle the end of an escape sequence. The final character in an escape sequence is the command to execute, which corresponds to the event that is dispatched here. """ num = ord(char) if num in self.sequence: s...
python
{ "resource": "" }
q5994
stream._stream
train
def _stream(self, char): """ Process a character when in the default 'stream' state. """ num = ord(char) if num in self.basic: self.dispatch(self.basic[num]) elif num == ctrl.ESC: self.state = "escape" elif num == 0x00: ...
python
{ "resource": "" }
q5995
stream.consume
train
def consume(self, char): """ Consume a single character and advance the state as necessary. """ if self.state == "stream": self._stream(char) elif self.state == "escape": self._escape_sequence(char) elif self.state == "escape-lb": self...
python
{ "resource": "" }
q5996
stream.process
train
def process(self, chars): """ Consume a string of and advance the state as necessary. """ while len(chars) > 0: self.consume(chars[0]) chars = chars[1:]
python
{ "resource": "" }
q5997
stream.dispatch
train
def dispatch(self, event, *args): """ Dispatch an event where `args` is a tuple of the arguments to send to any callbacks. If any callback throws an exception, the subsequent callbacks will be aborted. """ for callback in self.listeners.get(event, []): if l...
python
{ "resource": "" }
q5998
screen.attach
train
def attach(self, events): """ Attach this screen to a events that processes commands and dispatches events. Sets up the appropriate event handlers so that the screen will update itself automatically as the events processes data. """ if events is not None: ev...
python
{ "resource": "" }
q5999
screen.resize
train
def resize(self, shape): """ Resize the screen. If the requested screen size has more rows than the existing screen, rows will be added at the bottom. If the requested size has less rows than the existing screen rows will be clipped at the top of the screen. Similarly if...
python
{ "resource": "" }